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
// Multi-binary crate (psmux, pmux, tmux) sharing all modules —
// suppress dead_code warnings for functions only used by a subset of binaries.
#![allow(dead_code)]

mod types;
mod platform;
mod cli;
mod session;
mod tree;
mod style;
mod rendering;
mod config;
mod commands;
mod pane;
mod warm_pane_sync;
mod popup;
mod clipboard;
mod copy_mode;
mod input;
mod layout;
mod window_ops;
mod util;
mod format;
mod help;
mod server;
mod preview;
mod client;
mod ssh_input;
mod debug_log;
mod control;
mod proxy_pane;
mod cross_session;
mod cross_session_server;

use std::io::{self, Write, Read as _, BufRead as _, IsTerminal};
use std::time::Duration;
use std::env;

use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;
use crossterm::terminal::{enable_raw_mode, disable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen};
use crossterm::{execute};
use crossterm::cursor::{EnableBlinking, DisableBlinking};
use crossterm::event::{EnableMouseCapture, DisableMouseCapture, EnableBracketedPaste, DisableBracketedPaste};

use crate::platform::enable_virtual_terminal_processing;
use crate::cli::{print_help, print_version, print_commands};
use crate::session::{cleanup_stale_port_files, read_session_key, send_control,
    send_control_with_response, resolve_default_session_name,
    kill_remaining_server_processes};
use crate::rendering::apply_cursor_style;
use crate::server::run_server;
use crate::client::run_remote;
use crate::ssh_input::{send_mouse_enable, InputSource};

/// Convert a ratatui Color to an ANSI SGR escape sequence.
fn color_to_ansi(c: ratatui::style::Color, fg: bool) -> String {
    use ratatui::style::Color;
    let base = if fg { 30 } else { 40 };
    let bright = if fg { 90 } else { 100 };
    match c {
        Color::Reset => format!("\x1b[{}m", if fg { 39 } else { 49 }),
        Color::Black => format!("\x1b[{}m", base + 0),
        Color::Red => format!("\x1b[{}m", base + 1),
        Color::Green => format!("\x1b[{}m", base + 2),
        Color::Yellow => format!("\x1b[{}m", base + 3),
        Color::Blue => format!("\x1b[{}m", base + 4),
        Color::Magenta => format!("\x1b[{}m", base + 5),
        Color::Cyan => format!("\x1b[{}m", base + 6),
        Color::Gray => format!("\x1b[{}m", base + 7),
        Color::DarkGray => format!("\x1b[{}m", bright + 0),
        Color::LightRed => format!("\x1b[{}m", bright + 1),
        Color::LightGreen => format!("\x1b[{}m", bright + 2),
        Color::LightYellow => format!("\x1b[{}m", bright + 3),
        Color::LightBlue => format!("\x1b[{}m", bright + 4),
        Color::LightMagenta => format!("\x1b[{}m", bright + 5),
        Color::LightCyan => format!("\x1b[{}m", bright + 6),
        Color::White => format!("\x1b[{}m", bright + 7),
        Color::Rgb(r, g, b) => format!("\x1b[{};2;{};{};{}m", if fg { 38 } else { 48 }, r, g, b),
        Color::Indexed(i) => format!("\x1b[{};5;{}m", if fg { 38 } else { 48 }, i),
    }
}

/// Returns Some(true) if the window spec (index or name) exists in the target
/// server, Some(false) if it definitively does not, or None if the server could
/// not be queried (in which case the caller should NOT block the command).
/// Routing uses the already-set PSMUX_TARGET_SESSION (from the global -t parse).
fn cli_window_exists(window_spec: &str) -> Option<bool> {
    // Clear PSMUX_TARGET_FULL for the query: it holds the (possibly bad) target
    // window we are validating, which would otherwise scope list-windows to that
    // nonexistent window and return nothing. We want ALL windows of the session.
    let saved_full = std::env::var("PSMUX_TARGET_FULL").ok();
    std::env::remove_var("PSMUX_TARGET_FULL");
    let resp = crate::session::send_control_with_response(
        "list-windows -F #{window_index}|#{window_name}\n".to_string(),
    );
    if let Some(v) = saved_full { std::env::set_var("PSMUX_TARGET_FULL", v); }
    let resp = resp.ok()?;
    let mut any = false;
    for line in resp.lines() {
        let line = line.trim();
        if line.is_empty() || line == "OK" { continue; }
        let mut parts = line.splitn(2, '|');
        let idx = parts.next().unwrap_or("").trim();
        let name = parts.next().unwrap_or("").trim();
        // Only count lines that actually look like "<index>|<name>".
        if idx.parse::<usize>().is_ok() {
            any = true;
            if idx == window_spec || name == window_spec { return Some(true); }
        }
    }
    if any { Some(false) } else { None }
}

/// Returns Some(true)/Some(false) for whether a "%<id>" pane id exists anywhere in
/// the target server, or None if it could not be queried. Uses `list-panes -a`
/// because pane ids are globally unique across windows (a pane index is not, so we
/// only validate the unambiguous %id form to avoid false negatives).
fn cli_pane_id_exists(pane_id: &str) -> Option<bool> {
    let saved_full = std::env::var("PSMUX_TARGET_FULL").ok();
    std::env::remove_var("PSMUX_TARGET_FULL");
    let resp = crate::session::send_control_with_response(
        "list-panes -a -F #{pane_id}\n".to_string(),
    );
    if let Some(v) = saved_full { std::env::set_var("PSMUX_TARGET_FULL", v); }
    let resp = resp.ok()?;
    let mut any = false;
    for line in resp.lines() {
        let line = line.trim();
        if !line.starts_with('%') { continue; }
        any = true;
        if line == pane_id { return Some(true); }
    }
    if any { Some(false) } else { None }
}

/// Returns Some(true)/Some(false) for whether a pane index exists in the ACTIVE
/// window of the target session, or None if it could not be queried. Used for the
/// "<session>.<index>" target form (no explicit window), which refers to the active
/// window. PSMUX_TARGET_FULL is cleared so the query is not scoped to the (possibly
/// nonexistent) target pane.
fn cli_pane_index_exists(idx_spec: &str) -> Option<bool> {
    let saved_full = std::env::var("PSMUX_TARGET_FULL").ok();
    std::env::remove_var("PSMUX_TARGET_FULL");
    let resp = crate::session::send_control_with_response(
        "list-panes -F #{pane_index}\n".to_string(),
    );
    if let Some(v) = saved_full { std::env::set_var("PSMUX_TARGET_FULL", v); }
    let resp = resp.ok()?;
    let mut any = false;
    for line in resp.lines() {
        let line = line.trim();
        if line.parse::<usize>().is_err() { continue; }
        any = true;
        if line == idx_spec { return Some(true); }
    }
    if any { Some(false) } else { None }
}

fn main() {
    if let Err(e) = run_main() {
        // Print a user-friendly error message instead of Rust's Debug format
        // which shows "Error: Custom { kind: Other, error: \"...\" }"  (fixes #47)
        let msg = e.to_string();
        eprintln!("psmux: {}", msg);
        std::process::exit(1);
    }
}

fn run_main() -> io::Result<()> {
    let args: Vec<String> = crate::cli::normalize_flag_equals(env::args().collect());
    
    // Set console code page to UTF-8 early so ALL output paths (CLI commands
    // like capture-pane, list-sessions, display-message, etc.) correctly
    // render multi-byte Unicode characters instead of mojibake.
    enable_virtual_terminal_processing();

    // Clean up any stale port files at startup
    cleanup_stale_port_files();
    
    // Parse -L flag early (tmux-compatible: names the server socket for namespace isolation)
    // In psmux, -L <name> creates a namespace prefix for session port/key files.
    // Sessions under -L "foo" are stored as "foo__sessionname.port".
    // IMPORTANT: Only recognize -L as a global flag when it appears BEFORE the subcommand.
    // This avoids conflict with subcommand flags (e.g. select-pane -L, resize-pane -L).
    let mut l_socket_name: Option<String> = None;
    let mut f_config_file: Option<String> = None;
    let mut control_mode: u8 = 0; // 0=off, 1=-C (echo), 2=-CC (no echo)
    {
        let mut i = 1; // skip binary name
        while i < args.len() {
            let arg = &args[i];
            if arg == "-CC" {
                control_mode = 2;
                i += 1;
            } else if arg == "-C" {
                control_mode = 1;
                i += 1;
            } else if arg == "-L" && i + 1 < args.len() {
                l_socket_name = Some(args[i + 1].clone());
                i += 2;
            } else if arg == "-f" && i + 1 < args.len() {
                f_config_file = Some(args[i + 1].clone());
                i += 2;
            } else if (arg == "-S" || arg == "-t") && i + 1 < args.len() {
                i += 2; // skip other global flag-value pairs
            } else if arg.starts_with('-') {
                i += 1; // skip single global flags (e.g. -v, -V)
            } else {
                break; // hit the subcommand name — stop scanning for global flags
            }
        }
    }

    // Set PSMUX_CONFIG_FILE if -f was provided, so load_config() picks it up.
    if let Some(ref cf) = f_config_file {
        env::set_var("PSMUX_CONFIG_FILE", cf);
    }

    // Parse -t flag early to set target session for all commands
    // Supports session:window.pane format (e.g., "dev:0.1")
    // PSMUX_TARGET_SESSION stores the port file base name (for port file lookup)
    // PSMUX_TARGET_FULL stores the full target (session:window.pane) for the server
    if let Some(pos) = args.iter().position(|a| a == "-t") {
        if let Some(target) = args.get(pos + 1) {
            // Extract just the session name for port file lookup
            let parsed_target = crate::cli::parse_target(target);
            let has_explicit_session = parsed_target.session.is_some();
            let session = parsed_target.session.unwrap_or_else(|| "default".to_string());
            // Store the full target for the server to parse, with $N resolved
            // to the actual session name so the server can look up port files.
            let resolved_full = if target.starts_with('$') {
                if let Some(colon_pos) = target.find(':') {
                    format!("{}{}", session, &target[colon_pos..])
                } else {
                    session.clone()
                }
            } else {
                target.to_string()
            };
            env::set_var("PSMUX_TARGET_FULL", &resolved_full);
            // Apply -L namespace prefix for port file lookup
            let port_file_base = if let Some(ref l) = l_socket_name {
                format!("{}__{}", l, session)
            } else {
                session.clone()
            };
            // If the -t target includes an explicit session name, use it
            // directly. Otherwise (e.g. -t %2, -t :1.0) fall through to
            // the TMUX env var resolution below so we connect to the right
            // server when invoked from inside a psmux pane.
            //
            // Exception: for switch-client, -t is the DESTINATION session,
            // not the server to route the command to. Skip setting
            // PSMUX_TARGET_SESSION so the TMUX-based fallback below resolves
            // the current (source) session for routing. PSMUX_TARGET_FULL
            // still carries the destination for the server handler.
            let is_switch_client = args.iter().any(|a| a == "switch-client" || a == "switchc");
            if has_explicit_session && !is_switch_client {
                env::set_var("PSMUX_TARGET_SESSION", &port_file_base);
            }
        }
    }
    if env::var("PSMUX_TARGET_SESSION").is_err() {
        // No explicit session from -t: try to resolve from TMUX env var (set inside psmux panes)
        // TMUX format: /tmp/psmux-<pid>/<socket_name>,<port>,<session_idx>
        if let Ok(tmux_val) = env::var("TMUX") {
            // Extract the port from the TMUX value
            let parts: Vec<&str> = tmux_val.split(',').collect();
            if parts.len() >= 2 {
                if let Ok(port) = parts[1].trim().parse::<u16>() {
                    // Look up which session owns this port (port file base
                    // already includes -L namespace prefix if applicable)
                    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                    let psmux_dir = format!("{}\\.psmux", home);
                    if let Ok(entries) = std::fs::read_dir(&psmux_dir) {
                        for entry in entries.flatten() {
                            let path = entry.path();
                            if path.extension().map(|e| e == "port").unwrap_or(false) {
                                if let Ok(port_str) = std::fs::read_to_string(&path) {
                                    if let Ok(file_port) = port_str.trim().parse::<u16>() {
                                        if file_port == port {
                                            if let Some(port_file_base) = path.file_stem().and_then(|s| s.to_str()) {
                                                // Skip warm (standby) sessions — they are internal-only
                                                if !crate::session::is_warm_session(port_file_base) {
                                                    env::set_var("PSMUX_TARGET_SESSION", port_file_base);
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // Fallback: if no -t flag and session still not resolved (e.g. TMUX pointed
    // to a warm session, or no TMUX at all), pick the most recent real session.
    // When -L namespace is active, only resolve within that namespace.
    if env::var("PSMUX_TARGET_SESSION").is_err() {
        if let Some(name) = crate::session::resolve_last_session_name_ns(l_socket_name.as_deref()) {
            env::set_var("PSMUX_TARGET_SESSION", &name);
        }
    }
    
    // Find the actual command by skipping global -t/-L and their arguments.
    // -t is stripped everywhere (the global handler already set PSMUX_TARGET_SESSION).
    // -L is only stripped BEFORE the subcommand (global socket namespace flag);
    // after the subcommand, -L is kept (e.g. select-pane -L, resize-pane -L).
    let cmd_args: Vec<&String> = {
        let mut result = Vec::new();
        let mut i = 1; // skip binary name
        let mut found_subcommand = false;
        while i < args.len() {
            if !found_subcommand {
                // Before subcommand: skip global flags with values
                if (args[i] == "-t" || args[i] == "-L" || args[i] == "-f" || args[i] == "-S") && i + 1 < args.len() {
                    i += 2; // skip flag and its value
                    continue;
                } else if args[i] == "-h" || args[i] == "--help"
                       || args[i] == "-V" || args[i] == "-v" || args[i] == "--version" {
                    // Treat help/version flags as the subcommand itself
                    found_subcommand = true;
                    // fall through to push
                } else if args[i].starts_with('-') {
                    i += 1; // skip single global flags (e.g. -v)
                    continue;
                } else {
                    found_subcommand = true;
                    // fall through to push the subcommand name
                }
            } else {
                // After subcommand: strip only -t (and its value)
                if args[i] == "-t" && i + 1 < args.len() {
                    i += 2;
                    continue;
                }
            }
            result.push(&args[i]);
            i += 1;
        }
        result
    };
    
    let cmd = cmd_args.first().map(|s| s.as_str()).unwrap_or("");
    
    // Handle help and version flags first
    match cmd {
        "-h" | "--help" | "help" => {
            print_help();
            return Ok(());
        }
        "-V" | "-v" | "--version" | "version" => {
            print_version();
            return Ok(());
        }
        "list-commands" | "lscm" => {
            print_commands();
            return Ok(());
        }
        // Hidden internal command for empirical preview rendering tests.
        // Usage: psmux _render-preview <session> <win_id> <width> <height>
        // Fetches the window-dump and renders it via the SAME render_layout_json
        // the choose-tree/choose-session preview uses, then prints the resulting
        // buffer as ANSI text to stdout. Lets us compare REAL vs PREVIEW.
        "_render-preview" => {
            if cmd_args.len() < 5 {
                eprintln!("usage: psmux _render-preview <session> <win_id> <width> <height>");
                std::process::exit(2);
            }
            let sess = cmd_args[1].clone();
            let win_id: usize = cmd_args[2].parse().expect("win_id must be a number");
            let w: u16 = cmd_args[3].parse().expect("width must be a number");
            let h: u16 = cmd_args[4].parse().expect("height must be a number");
            let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
            let layout = match crate::preview::fetch_window_dump(&home, &sess, win_id) {
                Some(l) => l,
                None => { eprintln!("failed to fetch window-dump for {}:@{}", sess, win_id); std::process::exit(3); }
            };
            use ratatui::Terminal;
            use ratatui::backend::TestBackend;
            use ratatui::layout::Rect;
            use ratatui::style::Color;
            let backend = TestBackend::new(w, h);
            let mut term = Terminal::new(backend).unwrap();
            term.draw(|f| {
                let area = Rect::new(0, 0, w, h);
                let active_rect = crate::client::compute_active_rect_json(&layout, area);
                let total_panes = layout.count_leaves();
                crate::client::render_layout_json(
                    f, &layout, area,
                    false,
                    Color::DarkGray, Color::Green,
                    false, Color::Reset,
                    active_rect,
                    "", false, "off", "",
                    total_panes,
                );
                crate::rendering::fix_border_intersections(f.buffer_mut());
            }).unwrap();
            // Dump the buffer as ANSI escape sequences so colors are visible.
            let buf = term.backend().buffer().clone();
            let area = buf.area;
            use std::io::Write;
            let stdout = std::io::stdout();
            let mut out = stdout.lock();
            for y in 0..area.height {
                let mut last_fg: Option<Color> = None;
                let mut last_bg: Option<Color> = None;
                for x in 0..area.width {
                    let cell = &buf.content[(y as usize) * (area.width as usize) + (x as usize)];
                    let fg = cell.style().fg;
                    let bg = cell.style().bg;
                    if fg != last_fg || bg != last_bg {
                        let _ = write!(out, "\x1b[0m");
                        if let Some(c) = fg { let _ = write!(out, "{}", color_to_ansi(c, true)); }
                        if let Some(c) = bg { let _ = write!(out, "{}", color_to_ansi(c, false)); }
                        last_fg = fg;
                        last_bg = bg;
                    }
                    let _ = write!(out, "{}", cell.symbol());
                }
                let _ = writeln!(out, "\x1b[0m");
            }
            return Ok(());
        }
        _ => {}
    }

    match cmd {
        // kill-server MUST be handled early before any potential fall-through
        "kill-server" => {
            let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
            let psmux_dir = format!("{}\\.psmux", home);
            // Compute namespace prefix for -L filtering (matches list-sessions behavior)
            let ns_prefix = l_socket_name.as_ref().map(|l| format!("{l}__"));
            let mut targets: Vec<(std::path::PathBuf, u16, String)> = Vec::new();
            let mut stale_ports: Vec<std::path::PathBuf> = Vec::new();
            if let Ok(entries) = std::fs::read_dir(&psmux_dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.extension().map(|e| e == "port").unwrap_or(false) {
                        if let Some(session_name) = path.file_stem().and_then(|s| s.to_str()) {
                            // Apply -L namespace filtering:
                            // With -L: only kill sessions under that namespace
                            // Without -L: kill ALL sessions (tmux behavior)
                            if let Some(ref pfx) = ns_prefix {
                                if !session_name.starts_with(pfx.as_str()) { continue; }
                            }
                            if let Ok(port_str) = std::fs::read_to_string(&path) {
                                if let Ok(port) = port_str.trim().parse::<u16>() {
                                    let sess_key = read_session_key(session_name).unwrap_or_default();
                                    targets.push((path.clone(), port, sess_key));
                                }
                            } else {
                                stale_ports.push(path.clone());
                            }
                        }
                    }
                }
            }
            // Send kill-server to all sessions in parallel via threads
            let handles: Vec<std::thread::JoinHandle<()>> = targets.into_iter().map(|(path, port, sess_key)| {
                std::thread::spawn(move || {
                    let addr = format!("127.0.0.1:{}", port);
                    if let Ok(mut stream) = std::net::TcpStream::connect_timeout(
                        &addr.parse().unwrap(),
                        Duration::from_millis(500),
                    ) {
                        let _ = stream.set_nodelay(true);
                        let _ = write!(stream, "AUTH {}\n", sess_key);
                        let _ = stream.flush();
                        let _ = std::io::Write::write_all(&mut stream, b"kill-server\n");
                        let _ = stream.flush();
                        let _ = stream.shutdown(std::net::Shutdown::Write);
                        // Wait for server to exit (EOF = done)
                        let _ = stream.set_read_timeout(Some(Duration::from_millis(2000)));
                        let mut buf = [0u8; 64];
                        loop {
                            match std::io::Read::read(&mut stream, &mut buf) {
                                Ok(0) => break,
                                Err(_) => break,
                                Ok(_) => continue,
                            }
                        }
                    }
                    // Remove port/key files regardless
                    let _ = std::fs::remove_file(&path);
                    let key_path = path.with_extension("key");
                    let _ = std::fs::remove_file(&key_path);
                })
            }).collect();
            // Wait for all threads to complete
            for h in handles { let _ = h.join(); }
            // Clean up stale port/key files
            for path in &stale_ports {
                let _ = std::fs::remove_file(path);
                let key_path = path.with_extension("key");
                let _ = std::fs::remove_file(&key_path);
            }
            // Brief wait then verify no processes remain; if any do, force-kill them.
            // Only do the nuclear fallback when not using -L namespace filtering.
            std::thread::sleep(Duration::from_millis(50));
            if ns_prefix.is_none() {
                kill_remaining_server_processes();
            }
            return Ok(());
        }
        "ls" | "list-sessions" => {
                // Parse -F (format) and -f (filter) flags
                let mut format_str: Option<String> = None;
                let mut filter_str: Option<String> = None;
                {
                    let mut i = 1;
                    while i < cmd_args.len() {
                        match cmd_args[i].as_str() {
                            "-F" => {
                                if let Some(f) = cmd_args.get(i + 1) {
                                    format_str = Some(f.to_string());
                                    i += 1;
                                }
                            }
                            s if s.starts_with("-F") && s.len() > 2 => {
                                format_str = Some(s[2..].to_string());
                            }
                            "-f" => {
                                if let Some(f) = cmd_args.get(i + 1) {
                                    filter_str = Some(f.to_string());
                                    i += 1;
                                }
                            }
                            s if s.starts_with('-') => {
                                // Unknown flag: error like tmux rather than ignoring it,
                                // so scripts (libtmux/tmuxp) see a nonzero exit.
                                eprintln!("psmux: list-sessions: unknown option '{}'", s);
                                std::process::exit(1);
                            }
                            _ => {}
                        }
                        i += 1;
                    }
                }
                let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                let dir = format!("{}\\.psmux", home);
                // Compute namespace prefix for -L filtering
                let ns_prefix = l_socket_name.as_ref().map(|l| format!("{l}__"));
                if let Ok(entries) = std::fs::read_dir(&dir) {
                    for e in entries.flatten() {
                        if let Some(name) = e.file_name().to_str() {
                            if let Some((base, ext)) = name.rsplit_once('.') {
                                if ext == "port" {
                                    // Skip warm (standby) sessions — internal-only
                                    if crate::session::is_warm_session(base) { continue; }
                                    // Filter by -L namespace: when -L is given, only show
                                    // sessions with that prefix; when no -L, only show
                                    // sessions without any namespace prefix
                                    if let Some(ref pfx) = ns_prefix {
                                        if !base.starts_with(pfx.as_str()) { continue; }
                                    } else {
                                        if base.contains("__") { continue; }
                                    }
                                    if let Ok(port_str) = std::fs::read_to_string(e.path()) {
                                        if let Ok(_p) = port_str.trim().parse::<u16>() {
                                            let addr = format!("127.0.0.1:{}", port_str.trim());
                                            if let Ok(mut s) = std::net::TcpStream::connect_timeout(
                                                &addr.parse().unwrap(),
                                                Duration::from_millis(200)
                                            ) {
                                                // Format expansion for variables like
                                                // pane_current_command/pane_current_path can
                                                // take 40+ ms each (OS process queries), so
                                                // 50 ms was too tight for multi-variable
                                                // format strings (e.g. libtmux's 123-field
                                                // format). 500 ms allows complex formats
                                                // while still detecting dead sessions quickly.
                                                let _ = s.set_read_timeout(Some(Duration::from_millis(500)));
                                                // Read session key and authenticate
                                                let key_path = format!("{}\\.psmux\\{}.key", home, base);
                                                if let Ok(key) = std::fs::read_to_string(&key_path) {
                                                    let _ = std::io::Write::write_all(&mut s, format!("AUTH {}\n", key.trim()).as_bytes());
                                                }
                                                // Use -F format if provided, otherwise session-info
                                                let query = if let Some(ref fmt) = format_str {
                                                    format!("list-sessions -F \"{}\"\n", fmt.replace('"', "\\\""))
                                                } else {
                                                    "session-info\n".to_string()
                                                };
                                                let _ = std::io::Write::write_all(&mut s, query.as_bytes());
                                                let mut br = std::io::BufReader::new(s);
                                                let mut line = String::new();
                                                // Skip "OK" response from AUTH
                                                let _ = br.read_line(&mut line);
                                                if line.trim() == "OK" {
                                                    line.clear();
                                                    let _ = br.read_line(&mut line);
                                                }
                                                if line.trim() == "ERROR: Authentication required" {
                                                    // Auth failed, skip this session
                                                    continue;
                                                }
                                                // When -F format is provided, the server already
                                                // expanded it; use the result even if empty (tmux
                                                // prints an empty line for unknown format vars).
                                                // Only fall back to display_name when no -F was given.
                                                if format_str.is_some() || !line.trim().is_empty() {
                                                    let output = line.trim_end().to_string();
                                                    // Apply -f filter if provided.
                                                    // tmux -f accepts format expressions; support
                                                    // the common #{==:#{session_name},NAME} pattern
                                                    // as well as a plain substring fallback.
                                                    if let Some(ref flt) = filter_str {
                                                        let passes = if let Some(target) = flt
                                                            .strip_prefix("#{==:#{session_name},")
                                                            .and_then(|s| s.strip_suffix('}'))
                                                        {
                                                            // Compare port-file display name against literal
                                                            let display_name = if let Some(ref pfx) = ns_prefix {
                                                                base.strip_prefix(pfx.as_str()).unwrap_or(base)
                                                            } else {
                                                                base
                                                            };
                                                            display_name == target
                                                        } else {
                                                            // Fallback: plain substring match
                                                            output.contains(flt.as_str())
                                                        };
                                                        if !passes { continue; }
                                                    }
                                                    println!("{}", output);
                                                } else {
                                                    // Strip namespace prefix for display (e.g. "foo__dev" -> "dev")
                                                    let display_name = if let Some(ref pfx) = ns_prefix {
                                                        base.strip_prefix(pfx.as_str()).unwrap_or(base)
                                                    } else {
                                                        base
                                                    };
                                                    if let Some(ref flt) = filter_str {
                                                        let passes = if let Some(target) = flt
                                                            .strip_prefix("#{==:#{session_name},")
                                                            .and_then(|s| s.strip_suffix('}'))
                                                        {
                                                            display_name == target
                                                        } else {
                                                            display_name.contains(flt.as_str())
                                                        };
                                                        if !passes { continue; }
                                                    }
                                                    println!("{}", display_name); 
                                                }
                                            } else {
                                                // stale port file - remove it along with matching key
                                                let _ = std::fs::remove_file(e.path());
                                                let key_path = e.path().with_extension("key");
                                                let _ = std::fs::remove_file(&key_path);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return Ok(());
            }
            "a" | "at" | "attach" | "attach-session" => {
                // Search cmd_args (skips binary name + global flags). Skip
                // cmd_args[0] which is the subcommand itself ("a"/"attach"/etc),
                // otherwise argv[0] (the exe path or subcommand name) gets
                // picked up as the target session name.
                let sub_args: Vec<&String> = cmd_args.iter().skip(1).copied().collect();
                let name = sub_args
                    .iter()
                    .position(|a| *a == "-t")
                    .and_then(|i| sub_args.get(i + 1))
                    .map(|s| {
                        if let Some(ref l) = l_socket_name {
                            format!("{}__{}", l, s)
                        } else {
                            (*s).clone()
                        }
                    })
                    .or_else(|| {
                        // Accept positional argument as target session name
                        // (e.g. "psmux attach work" without -t flag)
                        let t_val_idx = sub_args.iter().position(|a| *a == "-t").map(|i| i + 1);
                        sub_args.iter().enumerate().find_map(|(i, a)| {
                            if !a.starts_with('-') && Some(i) != t_val_idx {
                                Some(if let Some(ref l) = l_socket_name {
                                    format!("{}__{}", l, a)
                                } else {
                                    (*a).clone()
                                })
                            } else {
                                None
                            }
                        })
                    })
                    .or_else(resolve_default_session_name)
                    .or_else(|| crate::session::resolve_last_session_name_ns(l_socket_name.as_deref()))
                    .unwrap_or_else(|| {
                        if let Some(ref l) = l_socket_name {
                            format!("{}__0", l)
                        } else {
                            "0".to_string()
                        }
                    });
                // #362: tmux runs `new-session` from the config at server start,
                // so `attach-session` works even with no server running. psmux has
                // no persistent server, so when no session exists yet and the
                // config requests a new-session, bootstrap it: delegate to our own
                // `new-session` (which loads the config — the `new-session` line is
                // a no-op during config load, so there is no recursion — then
                // creates the session and attaches in this same console). Honour
                // the config's new-session args (e.g. -s NAME) but drop -d/-D so we
                // attach rather than leave it detached.
                if crate::session::list_session_names_ns(l_socket_name.as_deref()).is_empty() {
                    if let Some(ns_args) = crate::config::config_new_session_args() {
                        let exe = env::current_exe()?;
                        let mut child = std::process::Command::new(exe);
                        if let Some(ref l) = l_socket_name { child.arg("-L").arg(l); }
                        child.arg("new-session");
                        for a in ns_args.iter().filter(|a| a.as_str() != "-d" && a.as_str() != "-D") {
                            child.arg(a);
                        }
                        let _ = child.status()?;
                        return Ok(());
                    }
                }
                env::set_var("PSMUX_SESSION_NAME", name);
                env::set_var("PSMUX_REMOTE_ATTACH", "1");
            }
            "server" => {
                // Internal command - run headless server (used when spawning background server)
                let name = args.iter().position(|a| a == "-s").and_then(|i| args.get(i+1)).map(|s| s.clone()).unwrap_or_else(|| "default".to_string());
                // Parse -L socket name for namespace isolation
                let server_socket_name = args.iter().position(|a| a == "-L").and_then(|i| args.get(i+1)).map(|s| s.clone());
                // Check for initial command via -c flag (shell-wrapped)
                let initial_cmd = args.iter().position(|a| a == "-c").and_then(|i| args.get(i+1)).map(|s| s.clone());
                // Parse start directory via -d flag
                let srv_start_dir = args.iter().position(|a| a == "-d").and_then(|i| args.get(i+1)).map(|s| s.clone());
                // Parse window name via -n flag
                let srv_window_name = args.iter().position(|a| a == "-n").and_then(|i| args.get(i+1)).map(|s| s.clone());
                // Parse initial dimensions via -x / -y flags
                let srv_init_width = args.iter().position(|a| a == "-x").and_then(|i| args.get(i+1)).and_then(|s| s.parse::<u16>().ok());
                let srv_init_height = args.iter().position(|a| a == "-y").and_then(|i| args.get(i+1)).and_then(|s| s.parse::<u16>().ok());
                let srv_init_size = match (srv_init_width, srv_init_height) {
                    (Some(w), Some(h)) => Some((w, h)),
                    (Some(w), None) => Some((w, 24)),
                    (None, Some(h)) => Some((80, h)),
                    _ => None,
                };
                // Parse session group target via -g flag
                let srv_group_target = args.iter().position(|a| a == "-g").and_then(|i| args.get(i+1)).map(|s| s.clone());
                // Parse -e environment variables (may appear multiple times)
                let srv_env_vars = crate::util::collect_server_session_env_args(&args).map_err(|e| {
                    io::Error::new(io::ErrorKind::InvalidInput, e)
                })?;
                // Check for raw command after -- (direct execution)
                let raw_cmd: Option<Vec<String>> = args.iter().position(|a| a == "--").map(|pos| {
                    args.iter().skip(pos + 1).cloned().collect()
                }).filter(|v: &Vec<String>| !v.is_empty());
                return run_server(name, server_socket_name, initial_cmd, raw_cmd, srv_start_dir, srv_window_name, srv_init_size, srv_group_target, srv_env_vars);
            }
            "new-session" | "new" => {
                // Prevent nesting: block new-session inside an existing psmux session
                if env::var("PSMUX_ALLOW_NESTING").ok().as_deref() != Some("1") {
                    if env::var("PSMUX_ACTIVE").ok().as_deref() == Some("1")
                        || env::var("PSMUX_SESSION").ok().filter(|v| !v.is_empty()).is_some()
                    {
                        eprintln!("psmux: sessions should be nested with care, unset PSMUX_SESSION to force");
                        return Ok(());
                    }
                }
                // Strict getopt-style parsing for new-session flags.
                // tmux template: "Ac:dDe:EF:f:n:Ps:t:x:Xy:"
                // Flags that take a value (letter followed by ':'):
                //   -s (session name), -n (window name), -F (format),
                //   -c (start dir), -x (width), -y (height), -e (env),
                //   -f (client flags), -t (target session)
                // Boolean flags: -A, -d, -D, -E, -P, -X
                let mut session_name: Option<String> = None;
                let mut detached = false;
                let mut print_info = false;
                let mut format_str: Option<String> = None;
                let mut window_name: Option<String> = None;
                let mut start_dir: Option<String> = None;
                let mut attach_if_exists = false;
                let mut init_width: Option<u16> = None;
                let mut init_height: Option<u16> = None;
                let mut group_target: Option<String> = None;
                let mut env_vars: Vec<(String, String)> = Vec::new();
                let mut positional_args: Vec<String> = Vec::new();
                let mut raw_cmd_after_dd: Option<Vec<String>> = None;

                {
                    let mut i = 1; // skip command name (cmd_args[0])
                    while i < cmd_args.len() {
                        let a = cmd_args[i].as_str();
                        if a == "--" {
                            // Everything after -- is raw command
                            raw_cmd_after_dd = Some(cmd_args[i+1..].iter().map(|s| s.to_string()).collect());
                            break;
                        }
                        // tmux uses getopt, which allows combined short flags
                        // like `-As main` (= `-A -s main`) or `-dP` (= `-d -P`).
                        // We expand combined flags inline.
                        if !a.starts_with('-') {
                            // Positional argument — collect it and everything after
                            positional_args.extend(cmd_args[i..].iter().map(|s| s.to_string()));
                            break;
                        }

                        let chars: Vec<char> = if a.len() > 2 && !a.starts_with("--") {
                            a[1..].chars().collect()
                        } else if a.len() == 2 {
                            vec![a.chars().nth(1).unwrap()]
                        } else {
                            // Unknown long flag, skip
                            i += 1; continue;
                        };

                        let mut k = 0;
                        while k < chars.len() {
                            let c = chars[k];
                            // Value-consuming flags: when in a combined group,
                            // remaining chars after the flag letter are the value (getopt style).
                            // If no remaining chars, the value is the next cmd_args element.
                            macro_rules! consume_value {
                                () => {{
                                    if k + 1 < chars.len() {
                                        // Rest of this arg is the value (e.g., -F#{fmt})
                                        let val: String = chars[k+1..].iter().collect();
                                        (val, true)
                                    } else {
                                        // Value is the next arg
                                        i += 1;
                                        let val = if i < cmd_args.len() { cmd_args[i].to_string() } else { String::new() };
                                        (val, true)
                                    }
                                }};
                            }
                            match c {
                            's' => { let (v, _) = consume_value!(); session_name = Some(v); break; }
                            'n' => { let (v, _) = consume_value!(); window_name = Some(v); break; }
                            'F' => { let (v, _) = consume_value!(); format_str = Some(v.trim_matches('"').to_string()); break; }
                            'c' => { let (v, _) = consume_value!(); start_dir = Some(v.trim_matches('"').to_string()); break; }
                            'x' => { let (v, _) = consume_value!(); init_width = v.parse::<u16>().ok(); break; }
                            'y' => { let (v, _) = consume_value!(); init_height = v.parse::<u16>().ok(); break; }
                            'e' => {
                                let (v, _) = consume_value!();
                                match crate::util::parse_new_session_e_value_token(
                                    Some(v.as_str()),
                                ) {
                                    Ok(pair) => env_vars.push(pair),
                                    Err(msg) => {
                                        return Err(io::Error::new(io::ErrorKind::InvalidInput, msg));
                                    }
                                }
                                break;
                            }
                            'f' => { let _ = consume_value!(); break; /* skip value */ }
                            't' => { let (v, _) = consume_value!(); group_target = Some(v); break; }
                            // Boolean flags
                            'd' => { detached = true; }
                            'P' => { print_info = true; }
                            'A' => { attach_if_exists = true; }
                            'D' | 'E' | 'X' => { /* ignored for compatibility */ }
                            _ => { /* unknown flag, skip */ }
                            }
                            k += 1;
                        }
                        i += 1;
                    }
                }

                let name = session_name.unwrap_or_else(|| {
                    // tmux-compatible: auto-generate numeric name (0, 1, 2, ...)
                    crate::session::next_session_name(l_socket_name.as_deref())
                });
                // Compute port file base name: with -L namespace prefix if specified
                let port_file_base = if let Some(ref l) = l_socket_name {
                    format!("{}__{}", l, name)
                } else {
                    name.clone()
                };
                // Check for -- separator: everything after it is a raw command (direct execution)
                let raw_cmd_args: Option<Vec<String>> = raw_cmd_after_dd.filter(|v| !v.is_empty());
                // Parse initial command from positional args (legacy mode, no --)
                let initial_cmd: Option<String> = if raw_cmd_args.is_some() || positional_args.is_empty() {
                    None
                } else {
                    Some(positional_args.join(" "))
                };
                
                // Check if session already exists AND is actually running
                let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                let port_path = format!("{}\\.psmux\\{}.port", home, port_file_base);
                // PID of the server we spawn on the cold path (None when we adopt
                // a warm server or attach to a remote one). The readiness gate
                // below uses it to fail fast if the freshly spawned server dies.
                let mut server_pid: Option<u32> = None;
                if std::path::Path::new(&port_path).exists() {
                    // Verify server is actually running
                    let server_alive = if let Ok(port_str) = std::fs::read_to_string(&port_path) {
                        if let Ok(port) = port_str.trim().parse::<u16>() {
                            let addr = format!("127.0.0.1:{}", port);
                            std::net::TcpStream::connect_timeout(
                                &addr.parse().unwrap(),
                                Duration::from_millis(100)
                            ).is_ok()
                        } else { false }
                    } else { false };
                    
                    if server_alive {
                        if attach_if_exists {
                            // -A flag: attach to existing session instead of erroring
                            env::set_var("PSMUX_SESSION_NAME", &port_file_base);
                            env::set_var("PSMUX_REMOTE_ATTACH", "1");
                            // Skip server creation, jump straight to attach
                            // (handled at the bottom of this match block)
                        } else {
                            eprintln!("duplicate session: {}", name);
                            std::process::exit(1);
                        }
                    } else {
                        // Stale port file - remove it and continue
                        let _ = std::fs::remove_file(&port_path);
                    }
                }
                
                // If -A attached to an existing session, skip server creation
                if env::var("PSMUX_REMOTE_ATTACH").ok().as_deref() == Some("1") {
                    // Already set up for attach — skip server spawn
                } else {
                // Fast path: try to claim a pre-spawned warm server.
                // The warm server has config loaded and shell already running,
                // so claiming it avoids the full cold-start latency.
                // Only eligible when no custom command/dir is requested.
                // Skipped when PSMUX_NO_WARM=1 is set or config has 'set -g warm off'.
                // Also skipped when a custom config file is specified (-f or PSMUX_CONFIG_FILE)
                // because the warm server loaded the default config, not the custom one.
                let warm_disabled = std::env::var("PSMUX_NO_WARM").map(|v| v == "1" || v == "true").unwrap_or(false)
                    || crate::config::is_warm_disabled_by_config();
                let has_custom_config = f_config_file.is_some() || std::env::var("PSMUX_CONFIG_FILE").is_ok();
                let claimed_warm = if !warm_disabled && !has_custom_config && initial_cmd.is_none() && raw_cmd_args.is_none() && start_dir.is_none() && env_vars.is_empty() {
                    let warm_base = if let Some(ref l) = l_socket_name {
                        format!("{}____warm__", l)
                    } else {
                        "__warm__".to_string()
                    };
                    let warm_port_path = format!("{}\\.psmux\\{}.port", home, warm_base);
                    // Atomically CLAIM the warm server before connecting. The
                    // __warm__.port file is a shared handoff: under rapid
                    // new-session, several clients could read the SAME file (and
                    // OS ephemeral-port reuse can make a stale entry point at an
                    // already-claimed server), which intermittently dropped a
                    // session. Renaming the port file is atomic on the same dir,
                    // so exactly one client wins the claim; losers cold-spawn.
                    let warm_port_opt = std::fs::read_to_string(&warm_port_path)
                        .ok()
                        .and_then(|s| s.trim().parse::<u16>().ok());
                    let claim_path = format!("{}\\.psmux\\{}.claiming.{}", home, warm_base, std::process::id());
                    if let Some(warm_port) = warm_port_opt {
                        if std::fs::rename(&warm_port_path, &claim_path).is_ok() {
                            let warm_addr = format!("127.0.0.1:{}", warm_port);
                            let result = if std::net::TcpStream::connect_timeout(
                                &warm_addr.parse().unwrap(),
                                Duration::from_millis(100),
                            ).is_ok() {
                                let warm_key = crate::session::read_session_key(&warm_base).unwrap_or_default();
                                if !warm_key.is_empty() {
                                    let client_cwd = std::env::current_dir()
                                        .ok()
                                        .and_then(|p| p.to_str().map(|s| s.to_string()));
                                    let claim_cmd = if let Some(ref cwd) = client_cwd {
                                        format!("claim-session {} {}\n", crate::util::quote_arg(&name), crate::util::quote_arg(cwd))
                                    } else {
                                        format!("claim-session {}\n", crate::util::quote_arg(&name))
                                    };
                                    match crate::session::send_auth_cmd_response(
                                        &warm_addr, &warm_key,
                                        claim_cmd.as_bytes(),
                                    ) {
                                        Ok(resp) if resp.contains("OK") => {
                                            if let Some(ref wn) = window_name {
                                                let new_key = crate::session::read_session_key(&port_file_base).unwrap_or_default();
                                                let _ = crate::session::send_auth_cmd(
                                                    &warm_addr, &new_key,
                                                    format!("rename-window {}\n", crate::util::quote_arg(wn)).as_bytes(),
                                                );
                                            }
                                            // Apply -e environment variables to the claimed warm session
                                            if !env_vars.is_empty() {
                                                let new_key = crate::session::read_session_key(&port_file_base).unwrap_or_default();
                                                for (k, v) in &env_vars {
                                                    let _ = crate::session::send_auth_cmd(
                                                        &warm_addr, &new_key,
                                                        format!("set-environment {} {}\n", crate::util::quote_arg(k), crate::util::quote_arg(v)).as_bytes(),
                                                    );
                                                }
                                            }
                                            true
                                        }
                                        // Explicit rejection: the server answered
                                        // but it is NOT a warm server (e.g. a stale
                                        // __warm__.port left pointing at an already-
                                        // claimed session, or OS ephemeral-port reuse
                                        // routing us to a live non-warm server). This
                                        // claim will NEVER produce our session, so do
                                        // NOT commit — fall through to a clean cold
                                        // spawn. The stale handoff file was already
                                        // consumed (renamed to .claiming then removed
                                        // below), so the bad warm pointer self-heals
                                        // and the next open is fast again. Without
                                        // this, we would wait the full port-file
                                        // timeout (~5s) for a session that never
                                        // appears and then fail the open entirely.
                                        Ok(resp) if resp.contains("ERR") => false,
                                        // We have ALREADY atomically claimed this
                                        // warm (won the .port rename) and sent
                                        // claim-session to a live server, so it WILL
                                        // become our session. A slow/missing response
                                        // here must NOT trigger a cold spawn: doing so
                                        // would create a SECOND server with the same
                                        // name (duplicate -> desynced .port/.key ->
                                        // the session appears lost). Commit to the
                                        // claim; the post-claim port-wait below
                                        // verifies completion (and errors cleanly if
                                        // the warm somehow died mid-claim).
                                        _ => true,
                                    }
                                } else { false }
                            } else {
                                // Connect failed: the warm is dead and will NOT become
                                // our session, so a cold spawn is correct (no duplicate
                                // is possible because nothing claimed this name).
                                false
                            };
                            // The server writes <session>.port on a successful
                            // claim; our renamed handoff file is now orphaned
                            // either way, so remove it. On failure this also
                            // ensures the dead/stale warm entry does not linger.
                            let _ = std::fs::remove_file(&claim_path);
                            result
                        } else {
                            // Lost the claim race (another client renamed it
                            // first) or the file vanished — fall back to cold spawn.
                            false
                        }
                    } else { false }
                } else { false };

                if !claimed_warm {
                // Cold path: spawn a background server from scratch
                let exe = std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("psmux"));
                let mut server_args: Vec<String> = vec!["server".into(), "-s".into(), name.clone()];
                // Pass -L socket name to server for namespace isolation
                if let Some(ref l) = l_socket_name {
                    server_args.push("-L".into());
                    server_args.push(l.clone());
                }
                // Pass initial command if provided
                if let Some(ref init_cmd) = initial_cmd {
                    server_args.push("-c".into());
                    server_args.push(init_cmd.clone());
                }
                // Pass start directory to server
                if let Some(ref dir) = start_dir {
                    server_args.push("-d".into());
                    server_args.push(dir.clone());
                }
                // Pass window name to server
                if let Some(ref wn) = window_name {
                    server_args.push("-n".into());
                    server_args.push(wn.clone());
                }
                // Pass initial dimensions to server
                if let Some(w) = init_width {
                    server_args.push("-x".into());
                    server_args.push(w.to_string());
                }
                if let Some(h) = init_height {
                    server_args.push("-y".into());
                    server_args.push(h.to_string());
                }
                // Pass session group target to server
                if let Some(ref gt) = group_target {
                    server_args.push("-g".into());
                    server_args.push(gt.clone());
                }
                // Pass -e environment variables to server
                for (k, v) in &env_vars {
                    server_args.push("-e".into());
                    server_args.push(format!("{}={}", k, v));
                }
                // Pass raw command args (direct execution) if -- was used
                if let Some(ref raw_args) = raw_cmd_args {
                    server_args.push("--".into());
                    for a in raw_args {
                        server_args.push(a.clone());
                    }
                }
                // On Windows, mark parent's stdout/stderr as non-inheritable before
                // spawning the server. This prevents the server from inheriting
                // PowerShell's redirect pipes (which would cause the parent to hang
                // waiting for the pipe to close). The server creates its own ConPTY
                // handles so it doesn't need the parent's stdio.
                #[cfg(windows)]
                {
                    #[link(name = "kernel32")]
                    extern "system" {
                        fn GetStdHandle(nStdHandle: u32) -> *mut std::ffi::c_void;
                        fn SetHandleInformation(hObject: *mut std::ffi::c_void, dwMask: u32, dwFlags: u32) -> i32;
                    }
                    const STD_OUTPUT_HANDLE: u32 = 0xFFFFFFF5u32; // -11i32 as u32
                    const STD_ERROR_HANDLE: u32 = 0xFFFFFFF4u32;  // -12i32 as u32
                    const HANDLE_FLAG_INHERIT: u32 = 0x00000001;
                    unsafe {
                        let stdout = GetStdHandle(STD_OUTPUT_HANDLE);
                        let stderr = GetStdHandle(STD_ERROR_HANDLE);
                        SetHandleInformation(stdout, HANDLE_FLAG_INHERIT, 0);
                        SetHandleInformation(stderr, HANDLE_FLAG_INHERIT, 0);
                    }
                }
                // Spawn server with a hidden console window via CreateProcessW.
                // This gives ConPTY a real console while keeping the window invisible.
                #[cfg(windows)]
                { server_pid = Some(crate::platform::spawn_server_hidden(&exe, &server_args)?); }
                #[cfg(not(windows))]
                {
                    let mut cmd = std::process::Command::new(&exe);
                    for a in &server_args { cmd.arg(a); }
                    cmd.stdin(std::process::Stdio::null());
                    cmd.stdout(std::process::Stdio::null());
                    cmd.stderr(std::process::Stdio::null());
                    let _child = cmd.spawn().map_err(|e| io::Error::new(io::ErrorKind::Other, format!("failed to spawn server: {e}")))?;
                }
                } // end if !claimed_warm (cold path)
                } // end else (not PSMUX_REMOTE_ATTACH)
                
                // Wait for server to create port file (up to 5 seconds)
                // Poll fast (10ms) — the server writes the port file early,
                // before spawning ConPTY/pwsh, so it should appear quickly.
                //
                // Wait for the server to become READY before returning, gating on
                // ACTUAL readiness rather than mere socket reachability. The server
                // writes its .port file and binds/accepts BEFORE it creates the
                // initial window and BEFORE its main request loop runs; under load
                // any of those steps can take seconds. The old tight check (5s port
                // poll + one 100ms connect) wrongly declared a slow-but-healthy
                // server dead — and even deleted its .port file, orphaning a live
                // session. Instead, loop until one of these terminal conditions:
                //
                //   READY (rc=0):
                //     - .port present + readable + a TCP connect succeeds, AND
                //     - for detached sessions, list-windows is non-empty (the
                //       initial window exists). list-windows is answered only by
                //       the main loop, which runs only after create_window, so a
                //       non-empty reply IS the "command finished server-side"
                //       signal — matching how tmux gates on command completion.
                //
                //   FAST-FAIL (rc=1), so we NEVER block on a doomed server:
                //     - .port vanished after we first saw it: the server hit a
                //       create_window failure / panic (its panic hook removes the
                //       .port) and exited. The client never deletes the .port
                //       itself — the server owns it.
                //     - the server PROCESS we spawned has died: covers a hard kill
                //       / abrupt exit / any path that skips the panic-hook cleanup
                //       and would otherwise leave a stale .port. We only consult
                //       this AFTER the readiness check fails for the iteration, so
                //       a healthy reachable server is never declared dead.
                //
                //   DEADLINE (rc=1): a hard 15s upper bound. The fast-fail signals
                //     above catch every real failure within ~20ms, so in practice
                //     this only ever fires for the pathological "process alive but
                //     create_window genuinely hangs forever" case — bounded, never
                //     an infinite hang. 15s comfortably exceeds the measured worst
                //     case window-creation latency under heavy concurrent load
                //     (~9s), so it does not reintroduce false failures.
                env::set_var("PSMUX_TARGET_SESSION", &port_file_base);
                // Wall-clock second this attempt began — used to tell a fresh
                // server-startup.log (this failure) from a stale one (issue #370).
                let attempt_start_epoch = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                let ready_deadline = std::time::Instant::now() + Duration::from_secs(15);
                let mut port_seen = false;
                let mut ready = false;
                loop {
                    if std::path::Path::new(&port_path).exists() {
                        port_seen = true;
                        let connectable = std::fs::read_to_string(&port_path).ok()
                            .and_then(|s| s.trim().parse::<u16>().ok())
                            .map(|port| {
                                let addr = format!("127.0.0.1:{}", port);
                                std::net::TcpStream::connect_timeout(
                                    &addr.parse().unwrap(),
                                    Duration::from_millis(200),
                                ).is_ok()
                            })
                            .unwrap_or(false);
                        if connectable {
                            if !detached {
                                // Attached: connectivity is enough — we attach below.
                                ready = true;
                                break;
                            }
                            // Detached: also require the initial window to exist.
                            if let Ok(resp) = send_control_with_response("list-windows\n".to_string()) {
                                if !resp.trim().is_empty() { ready = true; break; }
                            }
                        }
                    } else if port_seen {
                        // .port vanished after appearing → server cleaned up and exited.
                        break;
                    }
                    // Readiness not met this iteration → consult the process-death
                    // fast-fail signal (cold path only; None when we adopted a warm
                    // or remote server). A dead PID here means the server exited
                    // without leaving a usable session.
                    if let Some(pid) = server_pid {
                        if !crate::platform::process_is_alive(pid) { break; }
                    }
                    if std::time::Instant::now() >= ready_deadline { break; }
                    std::thread::sleep(Duration::from_millis(20));
                }
                if !ready {
                    eprintln!("psmux: failed to create session '{}'", name);
                    // Issue #370: surface the real reason instead of leaving it
                    // buried in ~/.psmux/server-startup.log. The detached server
                    // records the concrete spawn failure (e.g. a bad
                    // default-shell path) there before exiting; echo it so the
                    // user isn't left guessing why their config "silently" failed.
                    if let Some((reason, log_path)) =
                        crate::server::read_fresh_startup_error(attempt_start_epoch)
                    {
                        eprintln!("psmux: {}", reason);
                        eprintln!("psmux: full startup diagnostics in {}", log_path);
                    }
                    std::process::exit(1);
                }

                // Session came up. Surface any non-fatal config parse warnings
                // (unknown command/option, malformed value) the server recorded
                // during config load, so a typo'd ~/.psmux.conf is not silently
                // ignored (issue #370 follow-up). Printed before attaching so it
                // is visible in the terminal / scrollback.
                let cfg_warnings = crate::server::read_fresh_config_warnings(attempt_start_epoch);
                if !cfg_warnings.is_empty() {
                    eprintln!("psmux: {} config warning(s):", cfg_warnings.len());
                    for w in &cfg_warnings {
                        eprintln!("psmux:   {}", w);
                    }
                }

                if detached {
                    // The readiness wait above already confirmed the initial
                    // window exists. If -P, print the pane info before returning.
                    if print_info {
                        // Query the server for pane info using display-message
                        let fmt = if let Some(ref f) = format_str {
                            f.clone()
                        } else {
                            // tmux default: new-session -P prints "session_name:"
                            "#{session_name}:".to_string()
                        };
                        match send_control_with_response(format!("display-message -p {}\n", fmt)) {
                            Ok(resp) => { let trimmed = resp.trim(); if !trimmed.is_empty() { println!("{}", trimmed); } }
                            Err(_) => {}
                        }
                    }
                    return Ok(());
                } else {
                    // User wants attached session - set env vars to attach
                    env::set_var("PSMUX_SESSION_NAME", &port_file_base);
                    env::set_var("PSMUX_REMOTE_ATTACH", "1");
                    // Continue to attach below...
                }
            }
            "new-window" | "neww" => {
                // Strict getopt-style parsing for new-window flags.
                // tmux template: "ac:dDe:F:kn:Pt:S:"
                let mut name_arg: Option<String> = None;
                let mut detached = false;
                let mut print_info = false;
                let mut format_str: Option<String> = None;
                let mut start_dir: Option<String> = None;
                let mut nw_positional: Vec<String> = Vec::new();
                {
                    let mut i = 1;
                    while i < cmd_args.len() {
                        let a = cmd_args[i].as_str();
                        if a == "--" { nw_positional.extend(cmd_args[i+1..].iter().map(|s| s.to_string())); break; }
                        match a {
                            "-n" => { i += 1; if i < cmd_args.len() { name_arg = Some(cmd_args[i].trim_matches('"').to_string()); } }
                            "-F" => { i += 1; if i < cmd_args.len() { format_str = Some(cmd_args[i].trim_matches('"').to_string()); } }
                            s if s.starts_with("-F") && s.len() > 2 => { format_str = Some(s[2..].trim_matches('"').to_string()); }
                            "-c" => { i += 1; if i < cmd_args.len() { start_dir = Some(cmd_args[i].trim_matches('"').to_string()); } }
                            "-t" | "-e" | "-S" => { i += 1; /* skip value */ }
                            "-d" => { detached = true; }
                            "-P" => { print_info = true; }
                            "-a" | "-D" | "-k" => { /* ignored for compatibility */ }
                            _ if a.starts_with('-') => { /* unknown flag, skip */ }
                            _ => { nw_positional.extend(cmd_args[i..].iter().map(|s| s.to_string())); break; }
                        }
                        i += 1;
                    }
                }
                // cwd parity: a command-line new-window with no -c must open in
                // the CALLER's cwd, not the server's (session) cwd. tmux picks a
                // new window's cwd from three cases — an explicit -c, an attached
                // client (session start dir), or a detached client (the caller's
                // dir); the three cases are spelled out in tmux's own source. Each
                // psmux CLI call is a one-shot detached client, so default -c to
                // our current dir when the user gave none. Tradeoff: this defeats
                // the warm-pane fast path for command-line new-window (the warm
                // pane lives in the server's cwd) — interactive prefix-c, which
                // never routes through here, keeps it.
                if start_dir.is_none() {
                    if let Ok(cwd) = std::env::current_dir() {
                        start_dir = Some(cwd.to_string_lossy().into_owned());
                    }
                }
                let cmd_arg = nw_positional.join(" ");
                let cmd_arg = cmd_arg.as_str();
                let mut cmd_line = "new-window".to_string();
                if detached { cmd_line.push_str(" -d"); }
                if print_info { cmd_line.push_str(" -P"); }
                if let Some(ref fmt) = format_str {
                    cmd_line.push_str(&format!(" -F \"{}\"", fmt.replace("\"", "\\\"")));
                }
                if let Some(name) = &name_arg {
                    cmd_line.push_str(&format!(" -n \"{}\"", name.replace("\"", "\\\"")));
                }
                if let Some(dir) = &start_dir {
                    cmd_line.push_str(&format!(" -c \"{}\"", dir.replace("\"", "\\\"")));
                }
                if !cmd_arg.is_empty() {
                    cmd_line.push_str(&format!(" \"{}\"", cmd_arg.replace("\"", "\\\"")));
                }
                cmd_line.push('\n');
                if print_info {
                    let resp = send_control_with_response(cmd_line)?;
                    print!("{}", resp);
                } else {
                    send_control(cmd_line)?;
                }
                return Ok(());
            }
            "split-window" | "splitw" => {
                // Strict getopt-style parsing for split-window flags.
                // tmux template: "bc:de:F:fhIl:p:Pt:vZ"
                let mut flag = "-v";
                let mut detached = false;
                let mut print_info = false;
                let mut format_str: Option<String> = None;
                let mut start_dir: Option<String> = None;
                let mut size_pct: Option<String> = None;
                let mut size_cells: Option<String> = None;
                let mut sw_positional: Vec<String> = Vec::new();
                {
                    let mut i = 1;
                    while i < cmd_args.len() {
                        let a = cmd_args[i].as_str();
                        if a == "--" { sw_positional.extend(cmd_args[i+1..].iter().map(|s| s.to_string())); break; }
                        match a {
                            "-F" => { i += 1; if i < cmd_args.len() { format_str = Some(cmd_args[i].trim_matches('"').to_string()); } }
                            s if s.starts_with("-F") && s.len() > 2 => { format_str = Some(s[2..].trim_matches('"').to_string()); }
                            "-c" => { i += 1; if i < cmd_args.len() { start_dir = Some(cmd_args[i].trim_matches('"').to_string()); } }
                            "-p" => { i += 1; if i < cmd_args.len() { size_pct = Some(cmd_args[i].to_string()); size_cells = None; } }
                            "-l" => { i += 1; if i < cmd_args.len() { let v = cmd_args[i].to_string(); if v.ends_with('%') { size_pct = Some(v); size_cells = None; } else { size_cells = Some(v); size_pct = None; } } }
                            "-t" | "-e" => { i += 1; /* skip value */ }
                            "-h" => { flag = "-h"; }
                            "-v" => { flag = "-v"; }
                            "-d" => { detached = true; }
                            "-P" => { print_info = true; }
                            "-b" | "-f" | "-I" | "-Z" => { /* ignored for compatibility */ }
                            _ if a.starts_with('-') => { /* unknown flag, skip */ }
                            _ => { sw_positional.extend(cmd_args[i..].iter().map(|s| s.to_string())); break; }
                        }
                        i += 1;
                    }
                }
                // cwd parity (same as new-window): a command-line split with no
                // -c must open in the CALLER's cwd, not the server's (session)
                // cwd. Each psmux CLI call is a one-shot detached client, so
                // default -c to our current dir when none given.
                if start_dir.is_none() {
                    if let Ok(cwd) = std::env::current_dir() {
                        start_dir = Some(cwd.to_string_lossy().into_owned());
                    }
                }
                let cmd_arg = sw_positional.join(" ");
                let cmd_arg = cmd_arg.as_str();
                let mut cmd_line = format!("split-window {}", flag);
                if detached { cmd_line.push_str(" -d"); }
                if print_info { cmd_line.push_str(" -P"); }
                if let Some(ref fmt) = format_str {
                    cmd_line.push_str(&format!(" -F \"{}\"", fmt.replace("\"", "\\\"")));
                }
                if let Some(dir) = &start_dir {
                    cmd_line.push_str(&format!(" -c \"{}\"", dir.replace("\"", "\\\"")));
                }
                if let Some(pct) = &size_pct {
                    cmd_line.push_str(&format!(" -p {}", pct));
                } else if let Some(cells) = &size_cells {
                    cmd_line.push_str(&format!(" -l {}", cells));
                }
                if !cmd_arg.is_empty() {
                    cmd_line.push_str(&format!(" \"{}\"", cmd_arg.replace("\"", "\\\"")));
                }
                cmd_line.push('\n');
                if print_info {
                    let resp = send_control_with_response(cmd_line)?;
                    print!("{}", resp);
                } else {
                    let resp = send_control_with_response(cmd_line)?;
                    if !resp.is_empty() {
                        eprint!("{}", resp);
                        std::process::exit(1);
                    }
                }
                return Ok(());
            }
            "kill-pane" | "killp" => { send_control("kill-pane\n".to_string())?; return Ok(()); }
            "capture-pane" | "capturep" => {
                // Parse optional flags - cmd_args[0] is command, start from 1
                let mut cmd = "capture-pane".to_string();
                let mut print_stdout = false;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-t" => {
                            if let Some(target) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", target));
                                i += 1;
                            }
                        }
                        "-S" => {
                            if let Some(start) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -S {}", start));
                                i += 1;
                            }
                        }
                        "-E" => {
                            if let Some(end) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -E {}", end));
                                i += 1;
                            }
                        }
                        "-p" => { cmd.push_str(" -p"); print_stdout = true; }
                        "-e" => { cmd.push_str(" -e"); }
                        "-J" => { cmd.push_str(" -J"); }
                        "-b" => {
                            if let Some(buf) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -b {}", buf));
                                i += 1;
                            }
                        }
                        a if a.len() > 2
                            && a.starts_with('-')
                            && !a.starts_with("--")
                            && a.chars().skip(1).all(|c| matches!(c, 'p' | 'e' | 'J')) =>
                        {
                            // POSIX cluster of capture-pane booleans (-ep, -pe, -pJ, -eJ,
                            // -epJ, ...). -t/-S/-E/-b take a value, so they are NOT
                            // eligible for clustering.
                            if a.contains('p') { cmd.push_str(" -p"); print_stdout = true; }
                            if a.contains('e') { cmd.push_str(" -e"); }
                            if a.contains('J') { cmd.push_str(" -J"); }
                        }
                        // Cluster ending in a value-taking flag: -pt <target>,
                        // -pet <target>, -pS <start>, etc.
                        a if a.len() > 2
                            && a.starts_with('-')
                            && !a.starts_with("--")
                            && {
                                let last = a.chars().last().unwrap_or(' ');
                                matches!(last, 't' | 'S' | 'E' | 'b')
                                    && a[1..a.len()-1].chars().all(|c| matches!(c, 'p' | 'e' | 'J'))
                            } =>
                        {
                            let last = a.chars().last().unwrap();
                            // Expand boolean flags in the cluster
                            if a.contains('p') { cmd.push_str(" -p"); print_stdout = true; }
                            if a.contains('e') { cmd.push_str(" -e"); }
                            if a.contains('J') { cmd.push_str(" -J"); }
                            // Consume the next arg as the value for the trailing flag
                            if let Some(val) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -{} {}", last, val));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                if print_stdout {
                    let resp = send_control_with_response(cmd)?;
                    print!("{}", resp);
                } else {
                    send_control(cmd)?;
                }
                return Ok(());
            }
            // send-keys - Send keys to a pane (critical for scripting)
            "send-keys" | "send" | "send-key" => {
                let mut literal = false;
                let mut has_x = false;
                let mut keys: Vec<String> = Vec::new();
                // Getopt-style parsing: -t consumes next arg, -l/-R/-X are flags
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-l" => { literal = true; }
                        "-R" => { keys.push("__RESET__".to_string()); }
                        "-X" => { has_x = true; }
                        "-t" => { i += 1; } // consume target value (already handled globally)
                        "-N" => { i += 1; } // repeat count, consume value
                        _ => { keys.push(cmd_args[i].to_string()); }
                    }
                    i += 1;
                }
                let mut cmd = "send-keys".to_string();
                if literal { cmd.push_str(" -l"); }
                if has_x { cmd.push_str(" -X"); }
                // Quote arguments that contain spaces to preserve them
                for k in keys { 
                    if k.contains(' ') || k.contains('\t') || k.contains('"') {
                        // Escape embedded double-quotes and wrap in quotes.
                        // Do NOT escape backslashes: the server parser treats
                        // them as literal (Windows path separator).
                        let escaped = k.replace('"', "\\\"");
                        cmd.push_str(&format!(" \"{}\"", escaped));
                    } else {
                        cmd.push_str(&format!(" {}", k)); 
                    }
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // send-paste - Paste base64-encoded text to a pane
            "send-paste" => {
                let mut payload = String::new();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-t" => { i += 1; } // consume target (handled globally)
                        _ => { payload = cmd_args[i].to_string(); }
                    }
                    i += 1;
                }
                if !payload.is_empty() {
                    send_control(format!("send-paste {}\n", payload))?;
                }
                return Ok(());
            }
            // select-pane - Select the active pane
            "select-pane" | "selectp" => {
                let mut cmd = "select-pane".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        "-T" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -T \"{}\"", t));
                                i += 1;
                            }
                        }
                        "-P" => {
                            if let Some(s) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -P \"{}\"", s));
                                i += 1;
                            }
                        }
                        "-D" => { cmd.push_str(" -D"); }
                        "-U" => { cmd.push_str(" -U"); }
                        "-L" => { cmd.push_str(" -L"); }
                        "-R" => { cmd.push_str(" -R"); }
                        "-l" => { cmd.push_str(" -l"); }
                        "-Z" => { cmd.push_str(" -Z"); }
                        "-m" => { cmd.push_str(" -m"); }
                        "-M" => { cmd.push_str(" -M"); }
                        "-e" => { cmd.push_str(" -e"); }
                        "-d" => { cmd.push_str(" -d"); }
                        _ => {}
                    }
                    i += 1;
                }
                // tmux parity: error when a pane target does not exist. The global
                // -t parse stores the target in PSMUX_TARGET_FULL.
                if let Ok(full) = std::env::var("PSMUX_TARGET_FULL") {
                    if full.starts_with('%') {
                        // "%<id>" pane id: globally unique, validate across all panes.
                        if cli_pane_id_exists(&full) == Some(false) {
                            eprintln!("psmux: can't find pane: {}", full);
                            std::process::exit(1);
                        }
                    } else if !full.contains(':') {
                        // "<session>.<index>" form (no window): the pane index refers
                        // to the active window. Validate only a purely-numeric index
                        // so session names that merely contain a dot are not blocked.
                        if let Some(dot) = full.rfind('.') {
                            let pane_part = &full[dot + 1..];
                            if !pane_part.is_empty()
                                && pane_part.chars().all(|c| c.is_ascii_digit())
                                && cli_pane_index_exists(pane_part) == Some(false)
                            {
                                eprintln!("psmux: can't find pane: {}", full);
                                std::process::exit(1);
                            }
                        }
                    }
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // select-window - Select a window
            "select-window" | "selectw" => {
                let mut cmd = "select-window".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        "-l" => { cmd.push_str(" -l"); }
                        "-n" => { cmd.push_str(" -n"); }
                        "-p" => { cmd.push_str(" -p"); }
                        _ => {}
                    }
                    i += 1;
                }
                // tmux parity: error (nonzero exit) when an explicit window target
                // does not exist, instead of silently doing nothing. Only validated
                // when the target contains ':' (an unambiguous window specifier), so
                // valid `select-window -t <session>` calls are never blocked.
                // The global -t parse moves the target into PSMUX_TARGET_FULL (and
                // strips it from cmd_args), so read the window specifier from there.
                if let Ok(full) = std::env::var("PSMUX_TARGET_FULL") {
                    if let Some(ci) = full.find(':') {
                        let win_part = &full[ci + 1..];
                        let window_spec = win_part.split('.').next().unwrap_or(win_part);
                        if !window_spec.is_empty() && cli_window_exists(window_spec) == Some(false) {
                            eprintln!("psmux: can't find window: {}", window_spec);
                            std::process::exit(1);
                        }
                    }
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // list-panes - List all panes
            "list-panes" | "lsp" => {
                let mut all_sessions = false;
                let mut session_scope = false;
                let mut format_str: Option<String> = None;
                let mut target_session: Option<String> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-a" => { all_sessions = true; }
                        "-s" => { session_scope = true; }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                target_session = Some(t.to_string());
                                i += 1;
                            }
                        }
                        "-F" => {
                            if let Some(f) = cmd_args.get(i + 1) {
                                format_str = Some(f.to_string());
                                i += 1;
                            }
                        }
                        s if s.starts_with("-F") && s.len() > 2 => {
                            format_str = Some(s[2..].to_string());
                        }
                        _ => {}
                    }
                    i += 1;
                }

                if all_sessions {
                    // Iterate over all session port files (like list-sessions does)
                    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                    let dir = format!("{}\\.psmux", home);
                    let ns_prefix = l_socket_name.as_ref().map(|l| format!("{l}__"));
                    if let Ok(entries) = std::fs::read_dir(&dir) {
                        for e in entries.flatten() {
                            if let Some(name) = e.file_name().to_str() {
                                if let Some((base, ext)) = name.rsplit_once('.') {
                                    if ext != "port" { continue; }
                                    if crate::session::is_warm_session(base) { continue; }
                                    if let Some(ref pfx) = ns_prefix {
                                        if !base.starts_with(pfx.as_str()) { continue; }
                                    } else if base.contains("__") { continue; }
                                    if let Ok(port_str) = std::fs::read_to_string(e.path()) {
                                        if let Ok(_p) = port_str.trim().parse::<u16>() {
                                            let addr = format!("127.0.0.1:{}", port_str.trim());
                                            if let Ok(mut s) = std::net::TcpStream::connect_timeout(
                                                &addr.parse().unwrap(),
                                                Duration::from_millis(500),
                                            ) {
                                                let _ = s.set_read_timeout(Some(Duration::from_millis(500)));
                                                let key_path = format!("{}\\.psmux\\{}.key", home, base);
                                                if let Ok(key) = std::fs::read_to_string(&key_path) {
                                                    let _ = std::io::Write::write_all(&mut s, format!("AUTH {}\n", key.trim()).as_bytes());
                                                }
                                                // Send list-panes -s (all panes in this session) to each server
                                                let query = if let Some(ref fmt) = format_str {
                                                    format!("list-panes -s -F \"{}\"\n", fmt.replace('"', "\\\""))
                                                } else {
                                                    "list-panes -s\n".to_string()
                                                };
                                                let _ = std::io::Write::write_all(&mut s, query.as_bytes());
                                                let _ = s.flush();
                                                let mut br = std::io::BufReader::new(s);
                                                let mut line = String::new();
                                                let _ = std::io::BufRead::read_line(&mut br, &mut line);
                                                if line.trim() == "OK" {
                                                    line.clear();
                                                    let _ = std::io::BufRead::read_line(&mut br, &mut line);
                                                }
                                                if line.trim() == "ERROR: Authentication required" { continue; }
                                                // Print all lines from this session
                                                if !line.trim().is_empty() {
                                                    print!("{}", line);
                                                }
                                                loop {
                                                    let mut next = String::new();
                                                    match std::io::BufRead::read_line(&mut br, &mut next) {
                                                        Ok(0) => break,
                                                        Ok(_) => {
                                                            if !next.trim().is_empty() {
                                                                print!("{}", next);
                                                            }
                                                        }
                                                        Err(_) => break,
                                                    }
                                                }
                                            } else {
                                                let _ = std::fs::remove_file(e.path());
                                                let key_path = e.path().with_extension("key");
                                                let _ = std::fs::remove_file(&key_path);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    // Single session: build command and send to target session
                    let mut cmd = "list-panes".to_string();
                    if session_scope { cmd.push_str(" -s"); }
                    if let Some(ref t) = target_session {
                        cmd.push_str(&format!(" -t {}", t));
                    }
                    if let Some(ref f) = format_str {
                        cmd.push_str(&format!(" -F \"{}\"", f.trim_matches('"').replace("\"", "\\\"")));
                    }
                    cmd.push('\n');
                    let resp = send_control_with_response(cmd)?;
                    print!("{}", resp);
                }
                return Ok(());
            }
            // list-windows - List all windows
            "list-windows" | "lsw" => {
                let mut all_sessions = false;
                let mut json_mode = false;
                let mut format_str: Option<String> = None;
                let mut target_session: Option<String> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-a" => { all_sessions = true; }
                        "-J" => { json_mode = true; }
                        "-F" => {
                            if let Some(f) = cmd_args.get(i + 1) {
                                format_str = Some(f.to_string());
                                i += 1;
                            }
                        }
                        s if s.starts_with("-F") && s.len() > 2 => {
                            format_str = Some(s[2..].to_string());
                        }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                target_session = Some(t.to_string());
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }

                if all_sessions {
                    // Iterate over all session port files (like list-sessions does)
                    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                    let dir = format!("{}\\.psmux", home);
                    let ns_prefix = l_socket_name.as_ref().map(|l| format!("{l}__"));
                    if let Ok(entries) = std::fs::read_dir(&dir) {
                        for e in entries.flatten() {
                            if let Some(name) = e.file_name().to_str() {
                                if let Some((base, ext)) = name.rsplit_once('.') {
                                    if ext != "port" { continue; }
                                    if crate::session::is_warm_session(base) { continue; }
                                    if let Some(ref pfx) = ns_prefix {
                                        if !base.starts_with(pfx.as_str()) { continue; }
                                    } else if base.contains("__") { continue; }
                                    if let Ok(port_str) = std::fs::read_to_string(e.path()) {
                                        if let Ok(_p) = port_str.trim().parse::<u16>() {
                                            let addr = format!("127.0.0.1:{}", port_str.trim());
                                            if let Ok(mut s) = std::net::TcpStream::connect_timeout(
                                                &addr.parse().unwrap(),
                                                Duration::from_millis(500),
                                            ) {
                                                let _ = s.set_read_timeout(Some(Duration::from_millis(500)));
                                                let key_path = format!("{}\\.psmux\\{}.key", home, base);
                                                if let Ok(key) = std::fs::read_to_string(&key_path) {
                                                    let _ = std::io::Write::write_all(&mut s, format!("AUTH {}\n", key.trim()).as_bytes());
                                                }
                                                // Send list-windows to each server (without -a to avoid recursion)
                                                let query = if let Some(ref fmt) = format_str {
                                                    format!("list-windows -F \"{}\"\n", fmt.replace('"', "\\\""))
                                                } else if json_mode {
                                                    "list-windows -J\n".to_string()
                                                } else {
                                                    "list-windows\n".to_string()
                                                };
                                                let _ = std::io::Write::write_all(&mut s, query.as_bytes());
                                                let _ = s.flush();
                                                let mut br = std::io::BufReader::new(s);
                                                let mut line = String::new();
                                                let _ = std::io::BufRead::read_line(&mut br, &mut line);
                                                if line.trim() == "OK" {
                                                    line.clear();
                                                    let _ = std::io::BufRead::read_line(&mut br, &mut line);
                                                }
                                                if line.trim() == "ERROR: Authentication required" { continue; }
                                                if !line.trim().is_empty() {
                                                    print!("{}", line);
                                                }
                                                loop {
                                                    let mut next = String::new();
                                                    match std::io::BufRead::read_line(&mut br, &mut next) {
                                                        Ok(0) => break,
                                                        Ok(_) => {
                                                            if !next.trim().is_empty() {
                                                                print!("{}", next);
                                                            }
                                                        }
                                                        Err(_) => break,
                                                    }
                                                }
                                            } else {
                                                let _ = std::fs::remove_file(e.path());
                                                let key_path = e.path().with_extension("key");
                                                let _ = std::fs::remove_file(&key_path);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    // Single session: build command and send to target session
                    let mut cmd = "list-windows".to_string();
                    if json_mode { cmd.push_str(" -J"); }
                    if let Some(ref f) = format_str {
                        cmd.push_str(&format!(" -F \"{}\"", f.trim_matches('"').replace("\"", "\\\"")));
                    }
                    if let Some(ref t) = target_session {
                        cmd.push_str(&format!(" -t {}", t));
                    }
                    cmd.push('\n');
                    let resp = send_control_with_response(cmd)?;
                    print!("{}", resp);
                }
                return Ok(());
            }
            // kill-window - Kill a window
            "kill-window" | "killw" => {
                let mut cmd = "kill-window".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        "-a" => { cmd.push_str(" -a"); }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // detach-client - Gracefully detach attached client(s) (issue #275)
            "detach-client" | "detach" => {
                let mut t_target: Option<String> = None;
                let mut s_target: Option<String> = None;
                let mut detach_all = false;
                let mut kill_parent = false;
                let mut shell_cmd: Option<String> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-a" => { detach_all = true; }
                        "-P" => { kill_parent = true; }
                        "-t" => {
                            if let Some(v) = cmd_args.get(i + 1) {
                                t_target = Some(v.to_string());
                                i += 1;
                            }
                        }
                        "-s" => {
                            if let Some(v) = cmd_args.get(i + 1) {
                                s_target = Some(v.to_string());
                                i += 1;
                            }
                        }
                        "-E" => {
                            if let Some(v) = cmd_args.get(i + 1) {
                                shell_cmd = Some(v.to_string());
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                // Apply -L namespace prefix to -s session lookup so users can
                // target a namespaced session by its short name.
                let session_for_routing = if let Some(s) = &s_target {
                    if let Some(ref l) = l_socket_name {
                        format!("{}__{}", l, s)
                    } else {
                        s.clone()
                    }
                } else {
                    env::var("PSMUX_TARGET_SESSION").unwrap_or_else(|_| {
                        if let Some(ref l) = l_socket_name {
                            format!("{}__{}", l, "default")
                        } else {
                            "default".to_string()
                        }
                    })
                };
                env::set_var("PSMUX_TARGET_SESSION", &session_for_routing);

                // Build the command to forward.  -s is consumed by routing; we
                // don't re-send it because the server is already this session.
                let mut server_cmd = String::from("detach-client");
                // CLI invocations have no "current attached client" to detach,
                // so we silently promote a flag-less `psmux detach-client` to
                // `-a` (detach all). With `-t` specified we leave it alone so
                // the server force-detaches just that target.
                let effective_all = detach_all || (t_target.is_none() && shell_cmd.is_none());
                if effective_all { server_cmd.push_str(" -a"); }
                if kill_parent { server_cmd.push_str(" -P"); }
                if let Some(t) = &t_target {
                    // Quote the value so tty paths with slashes survive arg parsing.
                    server_cmd.push_str(&format!(" -t {}", crate::util::quote_arg(t)));
                }
                if let Some(c) = &shell_cmd {
                    // -E is documented but currently a no-op (we do not exec
                    // arbitrary shell commands on the server's behalf).
                    server_cmd.push_str(&format!(" -E {}", crate::util::quote_arg(c)));
                }
                server_cmd.push('\n');

                // If the target session has no port file, fall through with a
                // friendly message (matches kill-session behavior).
                if send_control(server_cmd).is_err() {
                    eprintln!("psmux: no session '{}'", session_for_routing);
                    std::process::exit(1);
                }
                return Ok(());
            }
            // kill-session - Kill a session
            "kill-session" | "kill-ses" => {
                let mut target: Option<String> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                // Resolve $N session IDs via parse_target
                                let resolved = crate::cli::parse_target(t)
                                    .session
                                    .unwrap_or_else(|| t.to_string());
                                // Apply -L namespace prefix for port file lookup
                                let namespaced = if let Some(ref l) = l_socket_name {
                                    format!("{}__{}", l, resolved)
                                } else {
                                    resolved
                                };
                                target = Some(namespaced);
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                let session_name = target.clone().unwrap_or_else(|| {
                    env::var("PSMUX_TARGET_SESSION").unwrap_or_else(|_| {
                        // Apply -L namespace prefix to default
                        if let Some(ref l) = l_socket_name {
                            format!("{}__{}", l, "default")
                        } else {
                            "default".to_string()
                        }
                    })
                });
                if let Some(ref t) = target {
                    env::set_var("PSMUX_TARGET_SESSION", t);
                }
                // Try to send kill command to server
                if send_control("kill-session\n".to_string()).is_err() {
                    // Server not responding - clean up stale port file
                    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                    let port_path = format!("{}\\.psmux\\{}.port", home, session_name);
                    let _ = std::fs::remove_file(&port_path);
                }
                return Ok(());
            }
            // has-session - Check if session exists (for scripting)
            "has-session" | "has" => {
                // Get target from env (set from -t flag) or from remaining args
                let target = env::var("PSMUX_TARGET_SESSION").unwrap_or_else(|_| {
                    // Try to get session name from cmd_args
                    let mut t = "default".to_string();
                    let mut i = 1;
                    while i < cmd_args.len() {
                        if cmd_args[i].as_str() == "-t" {
                            if let Some(v) = cmd_args.get(i + 1) {
                                // Strip leading '=' prefix (tmux exact-match semantics)
                                t = v.strip_prefix('=').unwrap_or(v).to_string();
                            }
                            i += 1;
                        } else if !cmd_args[i].starts_with('-') {
                            let raw = &cmd_args[i];
                            t = raw.strip_prefix('=').unwrap_or(raw).to_string();
                            break;
                        }
                        i += 1;
                    }
                    // Apply -L namespace prefix for port file lookup
                    if let Some(ref l) = l_socket_name {
                        format!("{}__{}", l, t)
                    } else {
                        t
                    }
                });
                // Warm (standby) sessions are internal-only — treat as non-existent
                if crate::session::is_warm_session(&target) {
                    std::process::exit(1);
                }
                let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                let path = format!("{}\\.psmux\\{}.port", home, target);
                if let Ok(port_str) = std::fs::read_to_string(&path) {
                    if let Ok(port) = port_str.trim().parse::<u16>() {
                        let addr = format!("127.0.0.1:{}", port);
                        // Actually authenticate and query the server to ensure it's healthy
                        let session_key = read_session_key(&target).unwrap_or_default();
                        if let Ok(mut s) = std::net::TcpStream::connect_timeout(
                            &addr.parse().unwrap(),
                            Duration::from_millis(500)
                        ) {
                            let _ = s.set_read_timeout(Some(Duration::from_millis(500)));
                            let _ = write!(s, "AUTH {}\n", session_key);
                            let _ = write!(s, "session-info\n");
                            let _ = s.flush();
                            let mut buf = [0u8; 256];
                            if let Ok(n) = std::io::Read::read(&mut s, &mut buf) {
                                if n > 0 {
                                    let resp = String::from_utf8_lossy(&buf[..n]);
                                    if resp.contains("OK") {
                                        std::process::exit(0);
                                    }
                                }
                            }
                            // Fallback: connection succeeded so session likely exists
                            std::process::exit(0);
                        } else {
                            // Stale port file - clean it up
                            let _ = std::fs::remove_file(&path);
                        }
                    }
                }
                std::process::exit(1);
            }
            // rename-session - Rename a session
            "rename-session" | "rename" => {
                let mut new_name: Option<String> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    if !cmd_args[i].starts_with('-') {
                        new_name = Some(cmd_args[i].to_string());
                        break;
                    }
                    i += 1;
                }
                if let Some(name) = new_name {
                    send_control(format!("rename-session {}\n", crate::util::quote_arg(&name)))?;
                }
                return Ok(());
            }
            // swap-pane - Swap panes
            "swap-pane" | "swapp" => {
                let mut cmd = "swap-pane".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-D" => { cmd.push_str(" -D"); }
                        "-U" => { cmd.push_str(" -U"); }
                        "-d" => { cmd.push_str(" -d"); }
                        "-s" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -s {}", t));
                                i += 1;
                            }
                        }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // resize-pane - Resize a pane
            "resize-pane" | "resizep" => {
                let mut cmd = "resize-pane".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-D" => { cmd.push_str(" -D"); }
                        "-U" => { cmd.push_str(" -U"); }
                        "-L" => { cmd.push_str(" -L"); }
                        "-R" => { cmd.push_str(" -R"); }
                        "-Z" => { cmd.push_str(" -Z"); }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        "-x" => {
                            if let Some(v) = cmd_args.get(i + 1) {
                                if v.trim_end_matches('%').parse::<i32>().is_err() {
                                    eprintln!("psmux: resize-pane: -x value must be a number, got '{}'", v);
                                    std::process::exit(1);
                                }
                                cmd.push_str(&format!(" -x {}", v));
                                i += 1;
                            }
                        }
                        "-y" => {
                            if let Some(v) = cmd_args.get(i + 1) {
                                if v.trim_end_matches('%').parse::<i32>().is_err() {
                                    eprintln!("psmux: resize-pane: -y value must be a number, got '{}'", v);
                                    std::process::exit(1);
                                }
                                cmd.push_str(&format!(" -y {}", v));
                                i += 1;
                            }
                        }
                        s if s.parse::<i32>().is_ok() => {
                            cmd.push_str(&format!(" {}", s));
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // paste-buffer - Paste buffer into pane
            "paste-buffer" | "pasteb" => {
                let mut cmd = "paste-buffer".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        "-b" => {
                            if let Some(b) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -b {}", b));
                                i += 1;
                            }
                        }
                        "-d" => { cmd.push_str(" -d"); }
                        "-p" => { cmd.push_str(" -p"); }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // set-buffer - Set buffer contents
            "set-buffer" | "setb" => {
                let mut buffer_name: Option<String> = None;
                let mut data: Option<String> = None;
                let mut propagate_to_clipboard = false;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-b" => {
                            if let Some(b) = cmd_args.get(i + 1) {
                                buffer_name = Some(b.to_string());
                                i += 1;
                            }
                        }
                        "-w" => { propagate_to_clipboard = true; }
                        s if !s.starts_with('-') => {
                            data = Some(s.to_string());
                        }
                        _ => {}
                    }
                    i += 1;
                }
                if propagate_to_clipboard {
                    if let Some(ref d) = data {
                        crate::clipboard::copy_to_system_clipboard(d);
                    }
                }
                let mut cmd = "set-buffer".to_string();
                if let Some(b) = buffer_name { cmd.push_str(&format!(" -b {}", b)); }
                if let Some(d) = data { cmd.push_str(&format!(" {}", d)); }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // list-buffers - List paste buffers
            "list-buffers" | "lsb" => {
                let mut format_str: Option<String> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-F" => {
                            if let Some(f) = cmd_args.get(i + 1) {
                                format_str = Some(f.to_string());
                                i += 1;
                            }
                        }
                        s if s.starts_with("-F") && s.len() > 2 => {
                            format_str = Some(s[2..].to_string());
                        }
                        "-t" => { i += 1; } // skip target
                        _ => {}
                    }
                    i += 1;
                }
                let cmd = if let Some(fmt) = format_str {
                    format!("list-buffers -F {}\n", fmt)
                } else {
                    "list-buffers\n".to_string()
                };
                let resp = send_control_with_response(cmd)?;
                print!("{}", resp);
                return Ok(());
            }
            // show-buffer - Show buffer contents
            "show-buffer" | "showb" => {
                let mut buffer_name: Option<String> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-b" => {
                            if let Some(b) = cmd_args.get(i + 1) {
                                buffer_name = Some(b.to_string());
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                let mut cmd = "show-buffer".to_string();
                if let Some(b) = buffer_name { cmd.push_str(&format!(" -b {}", b)); }
                cmd.push('\n');
                let resp = send_control_with_response(cmd)?;
                print!("{}", resp);
                return Ok(());
            }
            // delete-buffer - Delete a paste buffer
            "delete-buffer" | "deleteb" => {
                let mut buffer_name: Option<String> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-b" => {
                            if let Some(b) = cmd_args.get(i + 1) {
                                buffer_name = Some(b.to_string());
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                let mut cmd = "delete-buffer".to_string();
                if let Some(b) = buffer_name { cmd.push_str(&format!(" -b {}", b)); }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // display-message - Display a message
            "display-message" | "display" => {
                // A target containing "::" is always malformed (a valid target is
                // session:window.pane with single colons), so reject it with a
                // nonzero exit rather than silently resolving to the active session.
                if let Ok(full) = std::env::var("PSMUX_TARGET_FULL") {
                    if full.contains("::") {
                        eprintln!("psmux: bad target: {}", full);
                        std::process::exit(1);
                    }
                }
                let mut message: Vec<String> = Vec::new();
                let mut target: Option<String> = None;
                let mut print_to_stdout = false;
                let mut duration_ms: Option<u64> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                target = Some(t.to_string());
                                i += 1;
                            }
                        }
                        "-p" => { print_to_stdout = true; }
                        "-d" => {
                            if let Some(val) = cmd_args.get(i + 1) {
                                duration_ms = val.parse::<u64>().ok();
                            }
                            i += 1;
                        }
                        "-I" => { i += 1; } // consume -I <input>, skip value
                        // POSIX cluster ending in value-taking flag: -pt <target>
                        a if a.len() > 2
                            && a.starts_with('-')
                            && !a.starts_with("--")
                            && {
                                let last = a.chars().last().unwrap_or(' ');
                                matches!(last, 't' | 'd' | 'I')
                                    && a[1..a.len()-1].chars().all(|c| matches!(c, 'p'))
                            } =>
                        {
                            let last = a.chars().last().unwrap();
                            if a.contains('p') { print_to_stdout = true; }
                            if let Some(val) = cmd_args.get(i + 1) {
                                match last {
                                    't' => { target = Some(val.to_string()); }
                                    'd' => { duration_ms = val.parse::<u64>().ok(); }
                                    _ => {}
                                }
                                i += 1;
                            }
                        }
                        s => { message.push(s.to_string()); }
                    }
                    i += 1;
                }
                let msg = message.join(" ");
                let mut cmd = "display-message".to_string();
                if let Some(t) = target { cmd.push_str(&format!(" -t {}", t)); }
                if print_to_stdout { cmd.push_str(" -p"); }
                if let Some(d) = duration_ms { cmd.push_str(&format!(" -d {}", d)); }
                // Quote the message to preserve literal whitespace (tabs etc)
                // that would otherwise be split by the server's command parser.
                cmd.push_str(&format!(" \"{}\"", msg.replace('"', "\\\"")));
                cmd.push('\n');
                if print_to_stdout {
                    let resp = send_control_with_response(cmd)?;
                    print!("{}", resp);
                } else {
                    send_control(cmd)?;
                }
                return Ok(());
            }
            // run-shell - Run a shell command
            "run-shell" | "run" => {
                let mut cmd_to_run: Vec<String> = Vec::new();
                let mut background = false;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-b" => { background = true; }
                        s => { cmd_to_run.push(s.to_string()); }
                    }
                    i += 1;
                }
                let shell_cmd_str = cmd_to_run.join(" ");
                if shell_cmd_str.trim().is_empty() {
                    eprintln!("usage: run-shell [-b] shell-command");
                    std::process::exit(1);
                }
                let shell_cmd = crate::util::expand_run_shell_path(&shell_cmd_str);
                // Run the command using the resolved shell
                if background {
                    let mut c = crate::commands::build_run_shell_command(&shell_cmd);
                    let _ = c.spawn();
                } else {
                    let mut c = crate::commands::build_run_shell_command(&shell_cmd);
                    let output = c.output()?;
                    io::stdout().write_all(&output.stdout)?;
                    io::stderr().write_all(&output.stderr)?;
                    std::process::exit(output.status.code().unwrap_or(0));
                }
                return Ok(());
            }
            // respawn-pane - Restart the pane's process
            "respawn-pane" | "respawnp" | "resp" => {
                let mut cmd = "respawn-pane".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-k" => { cmd.push_str(" -k"); }
                        "-c" => {
                            if let Some(d) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -c {}", d));
                                i += 1;
                            }
                        }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => { cmd.push_str(&format!(" {}", cmd_args[i])); }
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // last-window - Select last used window
            "last-window" | "last" => {
                send_control("last-window\n".to_string())?;
                return Ok(());
            }
            // last-pane - Select last used pane
            "last-pane" | "lastp" => {
                send_control("last-pane\n".to_string())?;
                return Ok(());
            }
            // next-window - Move to next window
            "next-window" | "next" => {
                send_control("next-window\n".to_string())?;
                return Ok(());
            }
            // previous-window - Move to previous window
            "previous-window" | "prev" => {
                send_control("previous-window\n".to_string())?;
                return Ok(());
            }
            // rotate-window - Rotate panes in window
            "rotate-window" | "rotatew" => {
                let mut cmd = "rotate-window".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-D" => { cmd.push_str(" -D"); }
                        "-U" => { cmd.push_str(" -U"); }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // display-panes - Show pane numbers
            "display-panes" | "displayp" => {
                send_control("display-panes\n".to_string())?;
                return Ok(());
            }
            // break-pane - Break pane out to a new window
            "break-pane" | "breakp" => {
                let mut cmd = "break-pane".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-d" => { cmd.push_str(" -d"); }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // join-pane - Join a pane to another window (or across sessions)
            "join-pane" | "joinp" | "move-pane" | "movep" => {
                // Parse args to detect cross-session scenario
                // Note: -t is stripped from cmd_args by the global handler above,
                // but preserved in PSMUX_TARGET_FULL env var.
                let mut source_spec = String::new();
                let mut horizontal = false;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-h" => horizontal = true,
                        "-v" => {} // vertical is default
                        "-d" => {} // detach (ignored at CLI level)
                        "-s" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                source_spec = t.to_string();
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                // Get -t from the saved env var (global handler stripped it from cmd_args)
                let target_spec = std::env::var("PSMUX_TARGET_FULL").unwrap_or_default();
                // Check if source and target reference different sessions
                let src_session = if source_spec.contains(':') {
                    source_spec.split(':').next().unwrap_or("").to_string()
                } else {
                    String::new()
                };
                let tgt_session = if target_spec.contains(':') {
                    target_spec.split(':').next().unwrap_or("").to_string()
                } else {
                    String::new()
                };
                let current_session = std::env::var("PSMUX_TARGET_SESSION")
                    .or_else(|_| std::env::var("PSMUX_SESSION"))
                    .unwrap_or_default();
                let effective_src = if src_session.is_empty() { current_session.clone() } else { src_session.clone() };
                let effective_tgt = if tgt_session.is_empty() { current_session.clone() } else { tgt_session.clone() };
                // tmux parity: require at least one of -s or -t. Reject empty invocation.
                if source_spec.is_empty() && target_spec.is_empty() {
                    eprintln!("psmux: usage: join-pane [-bdhv] [-l size | -p percentage] [-s src-pane] [-t dst-pane]");
                    std::process::exit(1);
                }
                // tmux parity: src and target panes must be in different windows.
                // Detect same-session same-window case and reject (matches tmux's
                // "source and target panes must be different" error).
                let src_after_colon_check = if source_spec.contains(':') {
                    source_spec.split(':').nth(1).unwrap_or("")
                } else { source_spec.as_str() };
                let tgt_after_colon_check = if target_spec.contains(':') {
                    target_spec.split(':').nth(1).unwrap_or("")
                } else { target_spec.as_str() };
                let same_session = effective_src == effective_tgt && !effective_src.is_empty();
                if same_session && !src_after_colon_check.is_empty() && !tgt_after_colon_check.is_empty() {
                    // Prefix with ':' so parse_target reads "0.2" as window=0,pane=2
                    // (a bare "0.2" is otherwise read as session="0", pane=2).
                    let sp_chk = crate::cli::parse_target(&format!(":{}", src_after_colon_check));
                    let tp_chk = crate::cli::parse_target(&format!(":{}", tgt_after_colon_check));
                    if let (Some(sw), Some(tw)) = (sp_chk.window, tp_chk.window) {
                        if sw == tw {
                            eprintln!("psmux: can't join a pane to its own window");
                            std::process::exit(1);
                        }
                    }
                }
                if !effective_src.is_empty() && !effective_tgt.is_empty() && effective_src != effective_tgt {
                    // Cross-session join-pane: orchestrate via TCP
                    let src_after_colon = if source_spec.contains(':') {
                        source_spec.split(':').nth(1).unwrap_or("0.0")
                    } else if !source_spec.is_empty() {
                        &source_spec
                    } else {
                        "0.0"
                    };
                    let tgt_after_colon = if target_spec.contains(':') {
                        target_spec.split(':').nth(1).unwrap_or("")
                    } else if !target_spec.is_empty() {
                        &target_spec
                    } else {
                        ""
                    };
                    let sp = crate::cli::parse_target(src_after_colon);
                    let tp = crate::cli::parse_target(tgt_after_colon);
                    match crate::cross_session::orchestrate_cross_session_join(
                        &effective_src,
                        sp.window.unwrap_or(0),
                        sp.pane.unwrap_or(0),
                        &effective_tgt,
                        tp.window,
                        tp.pane,
                        horizontal,
                    ) {
                        Ok(()) => {}
                        Err(e) => {
                            eprintln!("psmux: cross-session join-pane failed: {}", e);
                            std::process::exit(1);
                        }
                    }
                } else {
                    // Same-session join-pane: forward to server as before
                    let mut cmd = "join-pane".to_string();
                    if horizontal { cmd.push_str(" -h"); }
                    if !source_spec.is_empty() { cmd.push_str(&format!(" -s {}", source_spec)); }
                    if !target_spec.is_empty() { cmd.push_str(&format!(" -t {}", target_spec)); }
                    cmd.push('\n');
                    send_control(cmd)?;
                }
                return Ok(());
            }
            // rename-window - Rename current window
            "rename-window" | "renamew" => {
                // cmd_args[0] is the command, cmd_args[1] should be the new name
                if let Some(name) = cmd_args.get(1) {
                    if !name.starts_with('-') {
                        send_control(format!("rename-window {}\n", crate::util::quote_arg(name)))?;
                    }
                }
                return Ok(());
            }
            // zoom-pane - Toggle pane zoom
            "zoom-pane" | "resizep -Z" => {
                send_control("zoom-pane\n".to_string())?;
                return Ok(());
            }
            // source-file - Load a configuration file
            "source-file" | "source" => {
                let mut quiet = false;
                let mut file_path: Option<String> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-q" => { quiet = true; }
                        "-n" => { /* parse only, don't execute */ }
                        "-v" => { /* verbose */ }
                        s if !s.starts_with('-') => { file_path = Some(s.to_string()); }
                        _ => {}
                    }
                    i += 1;
                }
                if let Some(path) = file_path {
                    // Expand ~ to home directory
                    let expanded = if path.starts_with('~') {
                        let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                        path.replacen('~', &home, 1)
                    } else {
                        path
                    };
                    if let Err(e) = std::fs::read_to_string(&expanded) {
                        if !quiet {
                            eprintln!("psmux: {}: {}", expanded, e);
                            std::process::exit(1);
                        }
                    } else {
                        // Send source-file command to server if attached
                        send_control(format!("source-file {}\n", crate::util::quote_arg(&expanded)))?;
                    }
                }
                return Ok(());
            }
            // list-keys - List all key bindings
            "list-keys" | "lsk" => {
                let mut table_filter: Option<String> = None;
                let mut key_filter: Option<String> = None;
                let mut cmd = "list-keys".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-T" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                table_filter = Some(t.to_string());
                                cmd.push_str(&format!(" -T {}", t));
                                i += 1;
                            }
                        }
                        "-t" => { i += 1; } // target handled globally
                        arg if !arg.starts_with('-') => {
                            // Positional: key name to filter
                            if key_filter.is_none() {
                                key_filter = Some(arg.to_string());
                            }
                            cmd.push_str(&format!(" {}", arg));
                        }
                        _ => { cmd.push_str(&format!(" {}", cmd_args[i])); }
                    }
                    i += 1;
                }
                cmd.push('\n');
                match send_control_with_response(cmd) {
                    Ok(resp) => { print!("{}", resp); }
                    Err(_) => {
                        // No running server — emit built-in defaults filtered by -T and key.
                        // Real tmux supports this without a server for the prefix table.
                        let table = table_filter.as_deref().unwrap_or("prefix");
                        if table == "prefix" || table_filter.is_none() {
                            for (key, action) in crate::help::PREFIX_DEFAULTS {
                                if let Some(ref kf) = key_filter {
                                    if *key != kf.as_str() { continue; }
                                }
                                println!("bind-key -T prefix {} {}", key, action);
                            }
                        }
                        if table == "root" || table_filter.is_none() {
                            for (key, action) in crate::help::ROOT_DEFAULTS {
                                if let Some(ref kf) = key_filter {
                                    if *key != kf.as_str() { continue; }
                                }
                                println!("bind-key -T root {} {}", key, action);
                            }
                        }
                    }
                }
                return Ok(());
            }
            // bind-key - Bind a key to a command
            "bind-key" | "bind" => {
                let cmd_str: String = cmd_args.iter().map(|s| s.as_str()).collect::<Vec<&str>>().join(" ");
                match send_control(format!("{}\n", cmd_str)) {
                    Ok(()) => {},
                    Err(e) if e.to_string().contains("no session") => {
                        eprintln!("warning: no active session; bind-key will take effect when set inside a session or via config file");
                    },
                    Err(e) => return Err(e),
                }
                return Ok(());
            }
            // unbind-key - Unbind a key
            "unbind-key" | "unbind" => {
                let cmd_str: String = cmd_args.iter().map(|s| s.as_str()).collect::<Vec<&str>>().join(" ");
                match send_control(format!("{}\n", cmd_str)) {
                    Ok(()) => {},
                    Err(e) if e.to_string().contains("no session") => {
                        eprintln!("warning: no active session; unbind-key will take effect when set inside a session or via config file");
                    },
                    Err(e) => return Err(e),
                }
                return Ok(());
            }
            // set-option / set / set-window-option / setw - Set an option
            "set-option" | "set" | "set-window-option" | "setw" => {
                // Validate that known integer-valued options receive a numeric value,
                // erroring (nonzero exit) like tmux instead of silently accepting junk.
                {
                    const INT_OPTS: &[&str] = &[
                        "history-limit", "escape-time", "display-time", "display-panes-time",
                        "repeat-time", "message-limit", "status-interval", "base-index",
                        "pane-base-index", "status-left-length", "status-right-length",
                        "lock-after-time", "history-file-limit",
                    ];
                    // Collect positional (non-flag) args, skipping -t's value.
                    let mut positionals: Vec<&str> = Vec::new();
                    let mut j = 1;
                    while j < cmd_args.len() {
                        let a = cmd_args[j].as_str();
                        if a == "-t" { j += 2; continue; }
                        if a.starts_with('-') { j += 1; continue; }
                        positionals.push(a);
                        j += 1;
                    }
                    if let (Some(name), Some(val)) = (positionals.first(), positionals.get(1)) {
                        if INT_OPTS.contains(name) && val.parse::<i64>().is_err() {
                            eprintln!("psmux: set-option: value for '{}' must be a number, got '{}'", name, val);
                            std::process::exit(1);
                        }
                    }
                }
                let cmd_str: String = cmd_args.iter().map(|s| {
                    let s = s.as_str();
                    if s.contains(' ') {
                        format!("\"{}\"", s.replace('"', "\\\""))
                    } else {
                        s.to_string()
                    }
                }).collect::<Vec<String>>().join(" ");
                match send_control(format!("{}\n", cmd_str)) {
                    Ok(()) => {},
                    Err(e) if e.to_string().contains("no session") => {
                        eprintln!("warning: no active session; option will take effect when set inside a session or via config file");
                    },
                    Err(e) => return Err(e),
                }
                return Ok(());
            }
            // show-options / show / show-window-options / showw - Show options
            "show-options" | "show" | "show-window-options" | "showw" => {
                let cmd_str: String = cmd_args.iter().map(|s| s.as_str()).collect::<Vec<&str>>().join(" ");
                let resp = send_control_with_response(format!("{}\n", cmd_str))?;
                print!("{}", resp);
                return Ok(());
            }
            // if-shell - Conditional execution
            "if-shell" | "if" => {
                let mut background = false;
                let mut condition: Option<String> = None;
                let mut cmd_true: Option<String> = None;
                let mut cmd_false: Option<String> = None;
                let mut format_mode = false;
                let mut i = 1;
                
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-b" => { background = true; }
                        "-F" => { format_mode = true; }
                        "-t" => { i += 1; } // Skip target
                        s if !s.starts_with('-') => {
                            if condition.is_none() {
                                condition = Some(s.to_string());
                            } else if cmd_true.is_none() {
                                cmd_true = Some(s.to_string());
                            } else if cmd_false.is_none() {
                                cmd_false = Some(s.to_string());
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                
                if let (Some(cond), Some(true_cmd)) = (condition, cmd_true) {
                    if background && !format_mode {
                        // -b flag: run the condition check in a background thread
                        // and dispatch the result command asynchronously (like tmux)
                        let cmd_false_bg = cmd_false.clone();
                        std::thread::spawn(move || {
                            let success = {
                                let (shell_prog, shell_args) = crate::commands::resolve_run_shell();
                                let mut c = std::process::Command::new(&shell_prog);
                                for a in &shell_args { c.arg(a); }
                                c.arg(&cond);
                                c.stdout(std::process::Stdio::null());
                                c.stderr(std::process::Stdio::null());
                                { use crate::platform::HideWindowCommandExt; c.hide_window(); }
                                c.status().map(|s| s.success()).unwrap_or(false)
                            };
                            let cmd_to_run = if success { Some(true_cmd) } else { cmd_false_bg };
                            if let Some(cmd) = cmd_to_run {
                                let tcp_cmd = format!("{}\n", cmd);
                                let _ = send_control_with_response(tcp_cmd);
                            }
                        });
                        // Return immediately — condition runs in background
                        return Ok(());
                    }

                    let success = if format_mode {
                        // Expand format string via server before evaluating
                        let fmt_cmd = format!("display-message -p {}\n", crate::util::quote_arg(&cond));
                        let expanded = send_control_with_response(fmt_cmd).unwrap_or_default();
                        let expanded = expanded.trim_end_matches('\n');
                        !expanded.is_empty() && expanded != "0"
                    } else if cond == "true" || cond == "1" {
                        true
                    } else if cond == "false" || cond == "0" {
                        false
                    } else {
                        // Run shell command - suppress stdout/stderr so it doesn't leak to terminal
                        {
                            let (shell_prog, shell_args) = crate::commands::resolve_run_shell();
                            let mut c = std::process::Command::new(&shell_prog);
                            for a in &shell_args { c.arg(a); }
                            c.arg(&cond);
                            c.stdout(std::process::Stdio::null());
                            c.stderr(std::process::Stdio::null());
                            { use crate::platform::HideWindowCommandExt; c.hide_window(); }
                            c.status().map(|s| s.success()).unwrap_or(false)
                        }
                    };
                    
                    let cmd_to_run = if success { Some(true_cmd) } else { cmd_false };
                    
                    if let Some(cmd) = cmd_to_run {
                        // Re-quote multi-word arguments for TCP transport
                        let needs_quoting = cmd.contains(' ');
                        let tcp_cmd = if needs_quoting {
                            // The command string may contain spaces (e.g. "display-message -p hello")
                            // Send it as-is since it's already a full command line
                            format!("{}\n", cmd)
                        } else {
                            format!("{}\n", cmd)
                        };
                        // Use send_control_with_response to capture any output from the chosen command
                        let resp = send_control_with_response(tcp_cmd)?;
                        if !resp.is_empty() {
                            print!("{}", resp);
                        }
                    }
                }
                return Ok(());
            }
            // wait-for - Wait for a signal
            "wait-for" | "wait" => {
                let mut lock = false;
                let mut signal = false;
                let mut unlock = false;
                let mut channel: Option<String> = None;
                let mut i = 1;
                
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-L" => { lock = true; }
                        "-S" => { signal = true; }
                        "-U" => { unlock = true; }
                        s if !s.starts_with('-') => { channel = Some(s.to_string()); }
                        _ => {}
                    }
                    i += 1;
                }
                
                if let Some(ch) = channel {
                    if signal {
                        send_control(format!("wait-for -S {}\n", ch))?;
                    } else if lock {
                        send_control(format!("wait-for -L {}\n", ch))?;
                    } else if unlock {
                        send_control(format!("wait-for -U {}\n", ch))?;
                    } else {
                        // Wait for channel - this blocks
                        let resp = send_control_with_response(format!("wait-for {}\n", ch))?;
                        if !resp.is_empty() {
                            print!("{}", resp);
                        }
                    }
                }
                return Ok(());
            }
            // select-layout - Select a layout for the window
            "select-layout" | "selectl" => {
                let mut layout: Option<String> = None;
                let mut next = false;
                let mut prev = false;
                let mut i = 1;
                
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-n" => { next = true; }
                        "-p" => { prev = true; }
                        "-o" => { /* last layout */ }
                        "-E" => { /* spread evenly */ }
                        "-t" => { i += 1; } // Skip target
                        s if !s.starts_with('-') => { layout = Some(s.to_string()); }
                        _ => {}
                    }
                    i += 1;
                }
                
                if next {
                    send_control("next-layout\n".to_string())?;
                } else if prev {
                    send_control("previous-layout\n".to_string())?;
                } else if let Some(l) = layout {
                    send_control(format!("select-layout {}\n", l))?;
                } else {
                    send_control("select-layout\n".to_string())?;
                }
                return Ok(());
            }
            // move-window - Move a window
            "move-window" | "movew" => {
                let mut cmd = "move-window".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-a" => { cmd.push_str(" -a"); }
                        "-b" => { cmd.push_str(" -b"); }
                        "-r" => { cmd.push_str(" -r"); }
                        "-d" => { cmd.push_str(" -d"); }
                        "-k" => { cmd.push_str(" -k"); }
                        "-s" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -s {}", t));
                                i += 1;
                            }
                        }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // swap-window - Swap windows
            "swap-window" | "swapw" => {
                let mut cmd = "swap-window".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-d" => { cmd.push_str(" -d"); }
                        "-s" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -s {}", t));
                                i += 1;
                            }
                        }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // list-clients - List all clients
            "list-clients" | "lsc" => {
                let resp = send_control_with_response("list-clients\n".to_string())?;
                print!("{}", resp);
                return Ok(());
            }
            // switch-client - Switch the current client to another session
            "switch-client" | "switchc" => {
                let mut cmd = "switch-client".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-l" => { cmd.push_str(" -l"); }
                        "-n" => { cmd.push_str(" -n"); }
                        "-p" => { cmd.push_str(" -p"); }
                        "-r" => { cmd.push_str(" -r"); }
                        "-c" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -c {}", t));
                                i += 1;
                            }
                        }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // copy-mode - Enter copy mode
            "copy-mode" => {
                let mut cmd = "copy-mode".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-u" => { cmd.push_str(" -u"); }
                        "-d" => { cmd.push_str(" -d"); }
                        "-e" => { cmd.push_str(" -e"); }
                        "-H" => { cmd.push_str(" -H"); }
                        "-q" => { cmd.push_str(" -q"); }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // clock-mode - Display a clock
            "clock-mode" => {
                send_control("clock-mode\n".to_string())?;
                return Ok(());
            }
            // choose-buffer - List paste buffers interactively
            "choose-buffer" | "chooseb" => {
                let resp = send_control_with_response("choose-buffer\n".to_string())?;
                print!("{}", resp);
                return Ok(());
            }
            // set-environment / setenv - Set environment variable
            "set-environment" | "setenv" => {
                let mut cmd = "set-environment".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-g" => { cmd.push_str(" -g"); }
                        "-r" => { cmd.push_str(" -r"); }
                        "-u" => { cmd.push_str(" -u"); }
                        "-h" => { cmd.push_str(" -h"); }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        s => { cmd.push_str(&format!(" {}", s)); }
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // show-environment / showenv - Show environment variables
            "show-environment" | "showenv" => {
                let mut cmd = "show-environment".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-g" => { cmd.push_str(" -g"); }
                        "-s" => { cmd.push_str(" -s"); }
                        "-h" => { cmd.push_str(" -h"); }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        s if !s.starts_with('-') => { cmd.push_str(&format!(" {}", s)); }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                let resp = send_control_with_response(cmd)?;
                print!("{}", resp);
                return Ok(());
            }
            // load-buffer - Load a paste buffer from a file
            "load-buffer" | "loadb" => {
                let mut buffer_name: Option<String> = None;
                let mut file_path: Option<String> = None;
                let mut propagate_to_clipboard = false;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-b" => {
                            if let Some(b) = cmd_args.get(i + 1) {
                                buffer_name = Some(b.to_string());
                                i += 1;
                            }
                        }
                        // tmux 3.2+: forward the loaded buffer to the outer
                        // terminal's system clipboard. Real tmux does this
                        // via OSC 52 to the host terminal; on Windows we
                        // have direct access to the Win32 clipboard, so
                        // just write to it. Failures are non-fatal
                        // (matches tmux's permissive behavior).
                        "-w" => { propagate_to_clipboard = true; }
                        "-" => { file_path = Some("-".to_string()); }
                        s if !s.starts_with('-') => { file_path = Some(s.to_string()); }
                        _ => {}
                    }
                    i += 1;
                }
                if let Some(path) = file_path {
                    let content = if path == "-" {
                        let mut input = String::new();
                        io::stdin().read_to_string(&mut input)?;
                        input
                    } else {
                        std::fs::read_to_string(&path)?
                    };
                    if propagate_to_clipboard {
                        crate::clipboard::copy_to_system_clipboard(&content);
                    }
                    let mut cmd = "set-buffer".to_string();
                    if let Some(b) = buffer_name {
                        cmd.push_str(&format!(" -b {}", b));
                    }
                    // Escape the content for transmission
                    let escaped = content.replace('\n', "\\n").replace('\r', "\\r");
                    cmd.push_str(&format!(" {}", escaped));
                    cmd.push('\n');
                    send_control(cmd)?;
                }
                return Ok(());
            }
            // save-buffer - Save a paste buffer to a file
            "save-buffer" | "saveb" => {
                let mut buffer_name: Option<String> = None;
                let mut file_path: Option<String> = None;
                let mut append = false;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-a" => { append = true; }
                        "-b" => {
                            if let Some(b) = cmd_args.get(i + 1) {
                                buffer_name = Some(b.to_string());
                                i += 1;
                            }
                        }
                        "-" => { file_path = Some("-".to_string()); }
                        s if !s.starts_with('-') => { file_path = Some(s.to_string()); }
                        _ => {}
                    }
                    i += 1;
                }
                if let Some(path) = file_path {
                    let mut cmd = "show-buffer".to_string();
                    if let Some(b) = buffer_name {
                        cmd.push_str(&format!(" -b {}", b));
                    }
                    cmd.push('\n');
                    let content = send_control_with_response(cmd)?;
                    if path == "-" {
                        print!("{}", content);
                    } else if append {
                        use std::fs::OpenOptions;
                        let mut file = OpenOptions::new().append(true).create(true).open(&path)?;
                        file.write_all(content.as_bytes())?;
                    } else {
                        std::fs::write(&path, &content)?;
                    }
                }
                return Ok(());
            }
            // clear-history - Clear pane history
            "clear-history" | "clearhist" => {
                let mut cmd = "clear-history".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-H" => { cmd.push_str(" -H"); }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // pipe-pane - Pipe pane output to a command
            "pipe-pane" | "pipep" => {
                let mut cmd = "pipe-pane".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-I" => { cmd.push_str(" -I"); }
                        "-O" => { cmd.push_str(" -O"); }
                        "-o" => { cmd.push_str(" -o"); }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        s => { cmd.push_str(&format!(" {}", s)); }
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // find-window - Search for a window
            "find-window" | "findw" => {
                let mut pattern: Option<String> = None;
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-C" | "-N" | "-T" | "-i" | "-r" | "-Z" => {}
                        "-t" => { i += 1; }
                        s if !s.starts_with('-') => { pattern = Some(s.to_string()); }
                        _ => {}
                    }
                    i += 1;
                }
                if let Some(p) = pattern {
                    let resp = send_control_with_response(format!("find-window {}\n", p))?;
                    print!("{}", resp);
                }
                return Ok(());
            }
            // list-commands - List all commands (duplicate handled above but kept for match completeness)
            "list-commands" | "lscm" => {
                print_commands();
                return Ok(());
            }
            // set-hook - Set a hook
            "set-hook" => {
                let cmd_str: String = cmd_args.iter().map(|s| s.as_str()).collect::<Vec<&str>>().join(" ");
                send_control(format!("{}\n", cmd_str))?;
                return Ok(());
            }
            // show-hooks - Show hooks
            "show-hooks" => {
                let cmd_str: String = cmd_args.iter().map(|s| s.as_str()).collect::<Vec<&str>>().join(" ");
                let resp = send_control_with_response(format!("{}\n", cmd_str))?;
                print!("{}", resp);
                return Ok(());
            }
            // next-layout - Cycle to next layout
            "next-layout" => {
                send_control("next-layout\n".to_string())?;
                return Ok(());
            }
            // previous-layout - Cycle to previous layout
            "previous-layout" => {
                send_control("previous-layout\n".to_string())?;
                return Ok(());
            }
            // choose-tree / choose-window / choose-session — interactive TUI choosers.
            // From the CLI just forward to the server so the attached client
            // (if any) can display the chooser.  Return exit 0.
            "choose-tree" | "choose-window" | "choose-session" => {
                send_control(format!("{}\n", cmd))?;
                return Ok(());
            }
            // command-prompt - Open interactive command prompt
            "command-prompt" => {
                let mut cmd = "command-prompt".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-I" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -I {}", t));
                                i += 1;
                            }
                        }
                        "-p" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -p {}", t));
                                i += 1;
                            }
                        }
                        "-1" => { cmd.push_str(" -1"); }
                        "-N" => { cmd.push_str(" -N"); }
                        "-W" => { cmd.push_str(" -W"); }
                        "-T" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -T {}", t));
                                i += 1;
                            }
                        }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // display-menu - Display a menu
            "display-menu" | "menu" => {
                let parts: Vec<String> = cmd_args.iter().map(|s| {
                    if s.contains(' ') || s.contains('"') { format!("\"{}\"" , s.replace('"', "\\\"")) } else { s.to_string() }
                }).collect();
                send_control(format!("{}\n", parts.join(" ")))?;
                return Ok(());
            }
            // display-popup - Display a popup window
            "display-popup" | "popup" => {
                let parts: Vec<String> = cmd_args.iter().map(|s| {
                    if s.contains(' ') || s.contains('"') { format!("\"{}\"" , s.replace('"', "\\\"")) } else { s.to_string() }
                }).collect();
                send_control(format!("{}\n", parts.join(" ")))?;
                return Ok(());
            }
            // server-info - Show server information
            "server-info" | "info" => {
                let resp = send_control_with_response("server-info\n".to_string())?;
                print!("{}", resp);
                return Ok(());
            }
            // start-server / warmup - Pre-spawn a warm server
            "start-server" | "start" | "warmup" => {
                // Pre-spawn a warm __warm__ server so the next new-session is
                // instant.  Also triggers Windows Defender's scan cache on the
                // binary, eliminating the ~200-400ms first-run penalty.
                let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
                let warm_base = if let Some(ref l) = l_socket_name {
                    format!("{}____warm__", l)
                } else {
                    "__warm__".to_string()
                };
                let warm_port_path = format!("{}\\.psmux\\{}.port", home, warm_base);
                // Check if warm server is already running
                let already_running = if std::path::Path::new(&warm_port_path).exists() {
                    if let Ok(port_str) = std::fs::read_to_string(&warm_port_path) {
                        if let Ok(port) = port_str.trim().parse::<u16>() {
                            std::net::TcpStream::connect_timeout(
                                &format!("127.0.0.1:{}", port).parse().unwrap(),
                                Duration::from_millis(100),
                            ).is_ok()
                        } else { false }
                    } else { false }
                } else { false };
                if already_running {
                    return Ok(());
                }
                // Clean up stale port file if any
                let _ = std::fs::remove_file(&warm_port_path);
                // Spawn the warm server
                let exe = std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("psmux"));
                let mut server_args: Vec<String> = vec!["server".into(), "-s".into(), "__warm__".into()];
                if let Some(ref l) = l_socket_name {
                    server_args.push("-L".into());
                    server_args.push(l.clone());
                }
                // Detect terminal size for the warm server
                if let Ok((tw, th)) = crossterm::terminal::size() {
                    let h = th.saturating_sub(1);
                    if tw > 0 && h > 0 {
                        server_args.push("-x".into());
                        server_args.push(tw.to_string());
                        server_args.push("-y".into());
                        server_args.push(h.to_string());
                    }
                }
                #[cfg(windows)]
                crate::platform::spawn_server_hidden(&exe, &server_args)?;
                #[cfg(not(windows))]
                {
                    let mut cmd = std::process::Command::new(&exe);
                    for a in &server_args { cmd.arg(a); }
                    cmd.stdin(std::process::Stdio::null());
                    cmd.stdout(std::process::Stdio::null());
                    cmd.stderr(std::process::Stdio::null());
                    let _child = cmd.spawn().map_err(|e| io::Error::new(io::ErrorKind::Other, format!("failed to spawn warm server: {e}")))?;
                }
                return Ok(());
            }
            // confirm-before - Ask for confirmation before running a command
            "confirm-before" | "confirm" => {
                let parts: Vec<String> = cmd_args.iter().map(|s| {
                    if s.contains(' ') || s.contains('"') { format!("\"{}\"", s.replace('"', "\\\"")) } else { s.to_string() }
                }).collect();
                send_control(format!("{}\n", parts.join(" ")))?;
                return Ok(());
            }
            // refresh-client - Refresh the client display
            "refresh-client" | "refresh" => {
                let mut cmd = "refresh-client".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-S" => { cmd.push_str(" -S"); }
                        "-l" => { cmd.push_str(" -l"); }
                        "-C" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -C {}", t));
                                i += 1;
                            }
                        }
                        "-t" => {
                            if let Some(t) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" -t {}", t));
                                i += 1;
                            }
                        }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // send-prefix - Send the prefix key to the active pane
            "send-prefix" => {
                send_control("send-prefix\n".to_string())?;
                return Ok(());
            }
            // show-messages - Show message log
            "show-messages" | "showmsgs" => {
                let resp = send_control_with_response("show-messages\n".to_string())?;
                if !resp.trim().is_empty() {
                    print!("{}", resp);
                }
                return Ok(());
            }
            // suspend-client - Suspend client (no-op on Windows)
            "suspend-client" | "suspendc" => {
                // No-op on Windows — no SIGTSTP concept
                return Ok(());
            }
            // lock-client / lock-server / lock-session (no-op on Windows)
            "lock-client" | "lockc" | "lock-server" | "lock" | "lock-session" | "locks" => {
                // No-op on Windows — no terminal locking concept
                return Ok(());
            }
            // resize-window - Resize window
            "resize-window" | "resizew" => {
                let mut cmd = "resize-window".to_string();
                let mut i = 1;
                while i < cmd_args.len() {
                    match cmd_args[i].as_str() {
                        "-x" | "-y" => {
                            if let Some(v) = cmd_args.get(i + 1) {
                                cmd.push_str(&format!(" {} {}", cmd_args[i], v));
                                i += 1;
                            }
                        }
                        "-t" => { i += 1; } // target handled globally
                        "-A" | "-D" | "-U" => { cmd.push_str(&format!(" {}", cmd_args[i])); }
                        _ => {}
                    }
                    i += 1;
                }
                cmd.push('\n');
                send_control(cmd)?;
                return Ok(());
            }
            // customize-mode - tmux 3.2+ customize mode
            "customize-mode" => {
                send_control("customize-mode\n".to_string())?;
                return Ok(());
            }
            // choose-client - List clients interactively
            "choose-client" => {
                // Single-client model — returns current client info
                let resp = send_control_with_response("list-clients\n".to_string())?;
                print!("{}", resp);
                return Ok(());
            }
            // respawn-window - Respawn active pane in window
            "respawn-window" | "respawnw" => {
                send_control("respawn-window\n".to_string())?;
                return Ok(());
            }
            // link-window - Link a window
            "link-window" | "linkw" => {
                let full = cmd_args.iter().map(|s| s.as_str()).collect::<Vec<&str>>().join(" ");
                send_control(format!("{}\n", full))?;
                return Ok(());
            }
            // unlink-window - Unlink a window
            "unlink-window" | "unlinkw" => {
                send_control("unlink-window\n".to_string())?;
                return Ok(());
            }
            _ => {
                // Unknown command - print error and exit
                if !cmd.is_empty() {
                    eprintln!("psmux: unknown command: {}", cmd);
                    eprintln!("Run 'psmux --help' for usage information.");
                    return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unknown command: {}", cmd)));
                }
            }
        }
    
    // Default behavior (bare `psmux` with no command):
    // tmux-compatible: always create a new session with the next available
    // numeric name (0, 1, 2, ...) and attach to it.
    //
    // For both control mode (-C/-CC) and TUI mode, ensure a session server
    // is running before we try to connect.  Real tmux's bare `tmux -CC`
    // starts the server and creates a session automatically; we do the same.

    if env::var("PSMUX_REMOTE_ATTACH").ok().as_deref() != Some("1") {
        let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
        let session_name = env::var("PSMUX_SESSION_NAME").unwrap_or_else(|_| {
            crate::session::next_session_name(l_socket_name.as_deref())
        });
        let port_file_base = if let Some(ref l) = l_socket_name {
            format!("{}__{}", l, session_name)
        } else {
            session_name.clone()
        };
        let port_path = format!("{}\\.psmux\\{}.port", home, port_file_base);

        // Try warm server claim first (fast path)
        // Skipped when PSMUX_NO_WARM=1 is set or config has 'set -g warm off'.
        let warm_disabled = std::env::var("PSMUX_NO_WARM").map(|v| v == "1" || v == "true").unwrap_or(false)
            || crate::config::is_warm_disabled_by_config();
        let warm_base = if let Some(ref l) = l_socket_name {
            format!("{}____warm__", l)
        } else {
            "__warm__".to_string()
        };
        let warm_port_path = format!("{}\\.psmux\\{}.port", home, warm_base);
        let mut warm_claimed = false;
        // Atomically CLAIM the warm server before connecting (see the detached
        // path above for the full rationale): renaming the shared __warm__.port
        // file is atomic, so exactly one concurrent new-session wins a given warm
        // server and the rest cold-spawn. Prevents the rapid-creation race where
        // two clients claim the same warm and one session is lost.
        let warm_port_opt = if warm_disabled { None } else {
            std::fs::read_to_string(&warm_port_path).ok().and_then(|s| s.trim().parse::<u16>().ok())
        };
        let warm_claim_path = format!("{}\\.psmux\\{}.claiming.{}", home, warm_base, std::process::id());
        if let Some(port) = warm_port_opt {
            if std::fs::rename(&warm_port_path, &warm_claim_path).is_ok() {
            let warm_key = crate::session::read_session_key(&warm_base).unwrap_or_default();
            {
                {
                    let addr = format!("127.0.0.1:{}", port);
                    if let Ok(mut stream) = std::net::TcpStream::connect_timeout(
                        &addr.parse().unwrap(),
                        Duration::from_millis(500),
                    ) {
                        let _ = stream.set_nodelay(true);
                        let _ = stream.set_read_timeout(Some(Duration::from_millis(3000)));
                        let _ = write!(stream, "AUTH {}\n", warm_key);
                        let client_cwd = std::env::current_dir()
                            .ok()
                            .and_then(|p| p.to_str().map(|s| s.to_string()));
                        if let Some(ref cwd) = client_cwd {
                            let _ = write!(stream, "claim-session {} {}\n", crate::util::quote_arg(&session_name), crate::util::quote_arg(cwd));
                        } else {
                            let _ = write!(stream, "claim-session {}\n", crate::util::quote_arg(&session_name));
                        }
                        let _ = stream.flush();
                        // Committed: we atomically own this warm (won the .port
                        // rename) and have sent claim-session, so it WILL become our
                        // session. Set warm_claimed NOW so a slow/missing response
                        // does not trigger a duplicate cold spawn (the duplicate was
                        // the residual cause of rapid-creation session loss). The OK
                        // read below still waits for the rename to finish (issue
                        // #136), and the port-file wait after this block covers a
                        // slow response.
                        warm_claimed = true;
                        // Use send_auth_cmd_response pattern: read AUTH
                        // "OK" line first, then read the claim-session
                        // response.  Previously a single raw read() would
                        // pick up only the AUTH "OK" and proceed before
                        // the server finished renaming port/key files,
                        // causing "auth failed" on the subsequent attach
                        // (issue #136).
                        if let Ok(reader_stream) = stream.try_clone() {
                            let mut br = std::io::BufReader::new(reader_stream);
                            let mut auth_line = String::new();
                            if std::io::BufRead::read_line(&mut br, &mut auth_line).unwrap_or(0) > 0
                                && auth_line.trim().starts_with("OK")
                            {
                                // Auth succeeded — now wait for the claim
                                // response so files are renamed before we
                                // try to attach.
                                let mut claim_line = String::new();
                                let got = std::io::BufRead::read_line(&mut br, &mut claim_line).unwrap_or(0) > 0;
                                if got && claim_line.contains("OK") {
                                    warm_claimed = true;
                                } else if got && claim_line.contains("ERR") {
                                    // Explicit rejection: this server is NOT a warm
                                    // server (stale __warm__.port -> already-claimed
                                    // session, or OS port reuse). Do NOT commit; the
                                    // handoff file was already consumed above, so the
                                    // bad warm pointer self-heals. Cold-spawn instead
                                    // of waiting ~5s for a session that never appears.
                                    warm_claimed = false;
                                }
                                // No/garbled response: leave warm_claimed = true
                                // (set above) to preserve the rapid-creation race
                                // fix — we own a live warm that will complete.
                            }
                        }
                    }
                }
            }
            }
            // Orphaned handoff file: server wrote <session>.port on success.
            let _ = std::fs::remove_file(&warm_claim_path);
        }


        if !warm_claimed {
            // Cold path: spawn a new background server
            let exe = std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("psmux"));
            let server_args: Vec<String> = vec!["server".into(), "-s".into(), session_name.clone()];
            #[cfg(windows)]
            crate::platform::spawn_server_hidden(&exe, &server_args)?;
            #[cfg(not(windows))]
            {
                let mut cmd = std::process::Command::new(&exe);
                for a in &server_args { cmd.arg(a); }
                cmd.stdin(std::process::Stdio::null());
                cmd.stdout(std::process::Stdio::null());
                cmd.stderr(std::process::Stdio::null());
                let _child = cmd.spawn().map_err(|e| io::Error::new(io::ErrorKind::Other, format!("failed to spawn server: {e}")))?;
            }
        }

        // Wait for the session's port file before attaching. This covers BOTH the
        // cold spawn (server writes it on startup) AND a committed warm claim whose
        // rename of __warm__.port -> <session>.port may still be completing — so the
        // attach never races ahead of the rename (issue #136).
        for _ in 0..500 {
            if std::path::Path::new(&port_path).exists() {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }

        // Now attach to the session
        env::set_var("PSMUX_SESSION_NAME", &port_file_base);
        env::set_var("PSMUX_REMOTE_ATTACH", "1");
    }

    // Control mode: connect to server with CONTROL/CONTROL_NOECHO protocol
    // instead of launching the TUI client. Must be checked before the
    // is_terminal() gate since control mode reads from piped stdin.
    if control_mode > 0 {
        return run_control_mode(control_mode);
    }

    // If stdin is not a terminal (headless/non-interactive environment, e.g.
    // winget validation pipeline), print version and exit cleanly — starting
    // a TUI session would fail without an interactive console.
    if !std::io::stdin().is_terminal() {
        print_version();
        return Ok(());
    }

    // Prevent nesting: similar to tmux checking $TMUX.
    // PSMUX_ACTIVE is set on the client process itself.
    // PSMUX_SESSION is set on child panes spawned by the server.
    // Both indicate we are already inside psmux.
    // Override with PSMUX_ALLOW_NESTING=1 if nesting is intentional.
    if env::var("PSMUX_ALLOW_NESTING").ok().as_deref() != Some("1") {
        if env::var("PSMUX_ACTIVE").ok().as_deref() == Some("1")
            || env::var("PSMUX_SESSION").ok().filter(|v| !v.is_empty()).is_some()
        {
            eprintln!("psmux: sessions should be nested with care, unset PSMUX_SESSION to force");
            return Ok(());
        }
    }
    env::set_var("PSMUX_ACTIVE", "1");

    let mut stdout = crate::platform::create_writer();
    enable_virtual_terminal_processing();
    enable_raw_mode()?;

    // Detect terminal type for input handling.
    // Use VT input parsing for SSH sessions and terminals that send VT mouse
    // sequences through ConPTY (e.g. JetBrains JediTerm).
    let use_vt_input = crate::ssh_input::needs_vt_input();

    // For standard terminals (not SSH), clear VTI flag from stdin if
    // crossterm or another layer set it. Keeps normal ReadConsoleInputW
    // behavior via proper INPUT_RECORDs.
    if !use_vt_input {
        crate::platform::disable_vti_on_stdin();
    }

    execute!(stdout, EnterAlternateScreen, EnableBlinking, EnableMouseCapture, EnableBracketedPaste)?;
    apply_cursor_style(&mut stdout)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let input = InputSource::new(use_vt_input)?;

    // For VT input mode (SSH / JetBrains), explicitly (re-)send mouse-enable
    // escape sequences.  ConPTY may have consumed crossterm's
    // EnableMouseCapture output without forwarding it.
    if use_vt_input {
        send_mouse_enable();
    }

    // Loop to handle session switching without spawning new processes
    let result = loop {
        let result = run_remote(&mut terminal, &input);
        
        // Check if we should switch to another session
        if let Ok(switch_to) = env::var("PSMUX_SWITCH_TO") {
            env::remove_var("PSMUX_SWITCH_TO");
            env::set_var("PSMUX_SESSION_NAME", &switch_to);
            // Update last_session file
            let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
            let last_path = format!("{}\\.psmux\\last_session", home);
            let _ = std::fs::write(&last_path, &switch_to);
            // Continue loop to attach to new session
            continue;
        }
        
        break result;
    };

    // Terminal cleanup — always runs, even on error, to prevent leaked
    // SGR attributes (invisible text), stuck raw mode, or stale cursor style.
    let _ = disable_raw_mode();
    let out = terminal.backend_mut();
    // Reset all SGR attributes (fg/bg color, bold, hidden, etc.) BEFORE
    // leaving the alternate screen.  SGR state is global and NOT restored
    // by the alternate-screen save/restore mechanism (\x1b[?1049l).
    // Without this, the last ratatui frame's foreground color can persist
    // into the main screen, making typed text invisible.
    let _ = execute!(out, crossterm::style::Print("\x1b[0m"));
    // Reset cursor style to terminal default (\x1b[0 q)
    let _ = execute!(out, crossterm::style::Print("\x1b[0 q"));
    let _ = execute!(out, DisableBlinking, DisableMouseCapture, DisableBracketedPaste, LeaveAlternateScreen);
    let _ = terminal.show_cursor();
    result
}

/// Run as a control mode client (psmux -C or psmux -CC).
/// Connects to the server via TCP, sends CONTROL/CONTROL_NOECHO,
/// reads commands from stdin and prints responses/notifications to stdout.
///
/// When running over SSH with a ConPTY console, Windows ConPTY silently
/// consumes DCS escape sequences (including the `\x1bP1000p` that iTerm2
/// uses to detect tmux control mode) and also interleaves its own cursor
/// positioning sequences into the output, corrupting the line-based
/// protocol.  To bypass ConPTY, the SSH client must disable PTY allocation
/// so that stdin/stdout are raw pipes: `ssh -T user@host tmux -CC`.
fn run_control_mode(mode: u8) -> io::Result<()> {
    use std::net::TcpStream;

    // Create diagnostic log FIRST, before anything else, so we can see failures.
    let home = env::var("USERPROFILE").or_else(|_| env::var("HOME")).unwrap_or_default();
    let psmux_dir = format!("{}\\.psmux", home);
    let _ = std::fs::create_dir_all(&psmux_dir);
    let cc_log_path = format!("{}\\cc_debug.log", psmux_dir);
    let mut log_file = std::fs::File::create(&cc_log_path).ok();
    macro_rules! cclog {
        ($($arg:tt)*) => {
            if let Some(ref mut f) = log_file {
                let _ = writeln!(f, $($arg)*);
                let _ = f.flush();
            }
        }
    }
    cclog!("=== psmux control mode log ===");
    cclog!("time: {:?}", std::time::SystemTime::now());
    cclog!("mode: {}", if mode == 1 { "CONTROL" } else { "CONTROL_NOECHO" });
    cclog!("USERPROFILE: {:?}", env::var("USERPROFILE"));
    cclog!("HOME: {:?}", env::var("HOME"));
    cclog!("log_path: {}", cc_log_path);
    cclog!("SSH_CLIENT: {:?}", env::var("SSH_CLIENT"));
    cclog!("SSH_CONNECTION: {:?}", env::var("SSH_CONNECTION"));
    cclog!("PSMUX_SESSION_NAME: {:?}", env::var("PSMUX_SESSION_NAME"));
    cclog!("PSMUX_REMOTE_ATTACH: {:?}", env::var("PSMUX_REMOTE_ATTACH"));

    // Win32 handle diagnostics
    #[cfg(windows)]
    {
        #[link(name = "kernel32")]
        extern "system" {
            fn GetStdHandle(nStdHandle: u32) -> *mut std::ffi::c_void;
            fn GetFileType(hFile: *mut std::ffi::c_void) -> u32;
            fn PeekNamedPipe(
                hNamedPipe: *mut std::ffi::c_void,
                lpBuffer: *mut u8,
                nBufferSize: u32,
                lpBytesRead: *mut u32,
                lpTotalBytesAvail: *mut u32,
                lpBytesLeftThisMessage: *mut u32,
            ) -> i32;
            fn GetLastError() -> u32;
        }
        const STD_INPUT_HANDLE: u32 = (-10i32) as u32;
        const STD_OUTPUT_HANDLE: u32 = (-11i32) as u32;
        unsafe {
            let h_in = GetStdHandle(STD_INPUT_HANDLE);
            let h_out = GetStdHandle(STD_OUTPUT_HANDLE);
            let ft_in = GetFileType(h_in);
            let ft_out = GetFileType(h_out);
            // FILE_TYPE_UNKNOWN=0, FILE_TYPE_DISK=1, FILE_TYPE_CHAR=2, FILE_TYPE_PIPE=3
            cclog!("stdin_handle: 0x{:x} (file_type={})", h_in as u64, ft_in);
            cclog!("stdout_handle: 0x{:x} (file_type={})", h_out as u64, ft_out);
            // Try to peek stdin to see if pipe is alive
            let mut avail: u32 = 0;
            let peek_ok = PeekNamedPipe(h_in, std::ptr::null_mut(), 0, std::ptr::null_mut(), &mut avail, std::ptr::null_mut());
            let last_err = GetLastError();
            cclog!("stdin PeekNamedPipe: ok={} avail={} last_error={}", peek_ok, avail, last_err);
        }
        cclog!("stdin_is_terminal: {}", std::io::stdin().is_terminal());
        cclog!("stdout_is_terminal: {}", std::io::stdout().is_terminal());
    }

    // Detect ConPTY + SSH: control mode over SSH requires raw pipe I/O.
    // ConPTY injects cursor-positioning escape sequences between protocol
    // lines, corrupting the tmux control protocol for iTerm2.
    //
    // Detection: if stdout IS a console handle directly, we know ConPTY is
    // active. However, when DefaultShell is pwsh, stdout is a pipe from pwsh
    // and we cannot reliably distinguish ConPTY-backed pipes from raw pipes.
    // We only block the definite case (direct console handle).
    // ConPTY raw passthrough: when stdin/stdout are consoles (e.g. ssh -t
    // allocated a PTY), put them into raw mode so ConPTY doesn't cook bytes
    // (line buffering, ECHO, NL<->CRLF) or interpret VT sequences. This
    // lets the tmux DCS protocol flow intact regardless of `ssh -T` vs
    // `ssh -t`. Some clients (e.g. iTerm2's tmux integration) close stdin
    // on the SSH session shortly after seeing the DCS opener when no PTY
    // is allocated, so supporting `ssh -t` is required for them.
    #[cfg(windows)]
    {
        #[link(name = "kernel32")]
        extern "system" {
            fn GetStdHandle(n: u32) -> *mut std::ffi::c_void;
            fn GetConsoleMode(h: *mut std::ffi::c_void, m: *mut u32) -> i32;
            fn SetConsoleMode(h: *mut std::ffi::c_void, m: u32) -> i32;
        }
        const STD_INPUT_HANDLE: u32 = (-10i32) as u32;
        const STD_OUTPUT_HANDLE: u32 = (-11i32) as u32;
        const ENABLE_PROCESSED_INPUT: u32 = 0x0001;
        const ENABLE_LINE_INPUT: u32 = 0x0002;
        const ENABLE_ECHO_INPUT: u32 = 0x0004;
        const ENABLE_VIRTUAL_TERMINAL_INPUT: u32 = 0x0200;
        const ENABLE_VIRTUAL_TERMINAL_PROCESSING_OUT: u32 = 0x0004;
        const DISABLE_NEWLINE_AUTO_RETURN: u32 = 0x0008;
        unsafe {
            let h_in = GetStdHandle(STD_INPUT_HANDLE);
            let h_out = GetStdHandle(STD_OUTPUT_HANDLE);
            let mut mode_in: u32 = 0;
            let mut mode_out: u32 = 0;
            if GetConsoleMode(h_in, &mut mode_in) != 0 {
                let new_in = (mode_in & !(ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))
                    | ENABLE_VIRTUAL_TERMINAL_INPUT;
                let r = SetConsoleMode(h_in, new_in);
                cclog!("ConPTY stdin: mode 0x{:x} -> 0x{:x} (set ok={})", mode_in, new_in, r);
            }
            if GetConsoleMode(h_out, &mut mode_out) != 0 {
                let new_out = mode_out | ENABLE_VIRTUAL_TERMINAL_PROCESSING_OUT | DISABLE_NEWLINE_AUTO_RETURN;
                let r = SetConsoleMode(h_out, new_out);
                cclog!("ConPTY stdout: mode 0x{:x} -> 0x{:x} (set ok={})", mode_out, new_out, r);
            }
        }
    }

    let session_name = env::var("PSMUX_SESSION_NAME")
        .unwrap_or_else(|_| "default".to_string());
    cclog!("session: {}", session_name);

    // Read port and key
    let port_path = format!("{}\\{}.port", psmux_dir, session_name);
    let key_path = format!("{}\\{}.key", psmux_dir, session_name);
    cclog!("port_path: {}", port_path);
    cclog!("key_path: {}", key_path);
    cclog!("port_path exists: {}", std::path::Path::new(&port_path).exists());
    cclog!("key_path exists: {}", std::path::Path::new(&key_path).exists());

    let port_str = match std::fs::read_to_string(&port_path) {
        Ok(s) => { cclog!("port_str: {:?}", s.trim()); s }
        Err(e) => { cclog!("FATAL: cannot read port file: {}", e); return Err(io::Error::new(io::ErrorKind::NotFound, format!("session '{}' not found (no port file)", session_name))); }
    };
    let port: u16 = match port_str.trim().parse() {
        Ok(p) => { cclog!("port: {}", p); p }
        Err(e) => { cclog!("FATAL: corrupted port file: {}", e); return Err(io::Error::new(io::ErrorKind::InvalidData, "corrupted port file")); }
    };
    let key = match std::fs::read_to_string(&key_path) {
        Ok(k) => { cclog!("key: (read {} bytes)", k.trim().len()); k.trim().to_string() }
        Err(e) => { cclog!("FATAL: cannot read key file: {}", e); return Err(io::Error::new(io::ErrorKind::NotFound, "session key file not found")); }
    };

    // Connect
    cclog!("connecting to 127.0.0.1:{}", port);
    let mut stream = match TcpStream::connect(format!("127.0.0.1:{}", port)) {
        Ok(s) => { cclog!("connected OK"); s }
        Err(e) => { cclog!("FATAL: connect failed: {}", e); return Err(io::Error::new(io::ErrorKind::ConnectionRefused, format!("cannot connect to session: {}", e))); }
    };
    let _ = stream.set_nodelay(true);

    // Auth
    write!(stream, "AUTH {}\n", key)?;
    stream.flush()?;
    cclog!("AUTH sent");

    // Read OK response
    let mut reader = io::BufReader::new(stream.try_clone()?);
    let mut ok_line = String::new();
    reader.read_line(&mut ok_line)?;
    cclog!("auth response: {:?}", ok_line.trim());
    if !ok_line.trim().starts_with("OK") {
        cclog!("FATAL: auth failed");
        return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("auth failed: {}", ok_line.trim())));
    }

    // Send CONTROL or CONTROL_NOECHO
    let mode_str = if mode == 1 { "CONTROL" } else { "CONTROL_NOECHO" };
    let mut write_stream = reader.get_ref().try_clone()?;
    write!(write_stream, "{}\n", mode_str)?;
    write_stream.flush()?;
    cclog!("{} sent, starting I/O threads", mode_str);

    // Spawn a thread to read server responses/notifications and print to stdout
    let reader_stream = reader.get_ref().try_clone()?;
    let cc_log_path = Some(cc_log_path);
    let cc_log_out = cc_log_path.clone();
    let reader_thread = std::thread::spawn(move || {
        let mut br = io::BufReader::new(reader_stream);
        let mut line = String::new();
        let stdout = io::stdout();
        let start = std::time::Instant::now();
        let mut log_file = cc_log_out.as_ref().and_then(|p| {
            std::fs::OpenOptions::new().append(true).open(p).ok()
        });
        loop {
            line.clear();
            match br.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => {
                    if let Some(ref mut f) = log_file {
                        let _ = writeln!(f, "[{:>8.3}s] OUT ({} bytes): {:?}",
                            start.elapsed().as_secs_f64(), line.len(),
                            &line[..line.len().min(200)]);
                    }
                    let mut out = stdout.lock();
                    let _ = out.write_all(line.as_bytes());
                    let _ = out.flush();
                }
            }
        }
    });

    // Read commands from stdin and send to server.
    // iTerm2's tmux integration sends \r as the command terminator by default
    // (TmuxGateway.newline = @"\r"). On Linux/macOS the PTY's ICRNL flag
    // translates \r → \n, but Windows ConPTY may not always do this.
    // Read raw bytes and translate bare \r to \n to avoid blocking the
    // server's read_line (which splits on \n only).
    let mut stdin_buf = [0u8; 4096];
    let stdin_start = std::time::Instant::now();
    let mut stdin_log_file = cc_log_path.as_ref().and_then(|p| {
        std::fs::OpenOptions::new().append(true).open(p).ok()
    });
    if let Some(ref mut f) = stdin_log_file {
        let _ = writeln!(f, "[{:>8.3}s] stdin reader started",
            stdin_start.elapsed().as_secs_f64());
        let _ = f.flush();
    }

    // Use raw Win32 ReadFile for stdin to handle SSH pipe edge cases.
    // Windows sshd may close the stdin pipe before the SSH channel is
    // fully established (race condition). We use PeekNamedPipe to
    // distinguish a genuinely broken pipe from a temporary condition.
    #[cfg(windows)]
    let stdin_handle = {
        #[link(name = "kernel32")]
        extern "system" {
            fn GetStdHandle(nStdHandle: u32) -> *mut std::ffi::c_void;
        }
        unsafe { GetStdHandle((-10i32) as u32) }
    };
    #[cfg(not(windows))]
    let stdin_handle = ();

    let mut total_bytes_read: u64 = 0;
    let mut eof_retries: u32 = 0;
    const MAX_EOF_RETRIES: u32 = 20; // 20 * 50ms = 1 second of retries

    loop {
        // On Windows, use ReadFile directly for better diagnostics
        #[cfg(windows)]
        let read_result = {
            #[link(name = "kernel32")]
            extern "system" {
                fn ReadFile(
                    hFile: *mut std::ffi::c_void,
                    lpBuffer: *mut u8,
                    nNumberOfBytesToRead: u32,
                    lpNumberOfBytesRead: *mut u32,
                    lpOverlapped: *mut std::ffi::c_void,
                ) -> i32;
                fn GetLastError() -> u32;
                fn PeekNamedPipe(
                    hNamedPipe: *mut std::ffi::c_void, lpBuffer: *mut u8, nBufferSize: u32,
                    lpBytesRead: *mut u32, lpTotalBytesAvail: *mut u32,
                    lpBytesLeftThisMessage: *mut u32,
                ) -> i32;
            }
            let mut bytes_read: u32 = 0;
            let ok = unsafe {
                ReadFile(
                    stdin_handle,
                    stdin_buf.as_mut_ptr(),
                    stdin_buf.len() as u32,
                    &mut bytes_read,
                    std::ptr::null_mut(),
                )
            };
            if ok == 0 {
                let err = unsafe { GetLastError() };
                // ERROR_BROKEN_PIPE = 109, ERROR_NO_DATA = 232
                if err == 109 || err == 232 {
                    // Pipe is broken. Check if we should retry.
                    if total_bytes_read == 0 && eof_retries < MAX_EOF_RETRIES {
                        eof_retries += 1;
                        if let Some(ref mut f) = stdin_log_file {
                            if eof_retries <= 5 || eof_retries % 20 == 0 {
                                let _ = writeln!(f, "[{:>8.3}s] stdin pipe broken (err={}), retry {}/{}",
                                    stdin_start.elapsed().as_secs_f64(), err, eof_retries, MAX_EOF_RETRIES);
                                let _ = f.flush();
                            }
                        }
                        std::thread::sleep(Duration::from_millis(50));
                        // Re-check pipe state
                        let mut avail: u32 = 0;
                        let peek_ok = unsafe {
                            PeekNamedPipe(stdin_handle, std::ptr::null_mut(), 0,
                                std::ptr::null_mut(), &mut avail, std::ptr::null_mut())
                        };
                        if peek_ok != 0 {
                            // Pipe is alive again!
                            if let Some(ref mut f) = stdin_log_file {
                                let _ = writeln!(f, "[{:>8.3}s] stdin pipe recovered! avail={}",
                                    stdin_start.elapsed().as_secs_f64(), avail);
                                let _ = f.flush();
                            }
                        }
                        continue;
                    }
                    if let Some(ref mut f) = stdin_log_file {
                        let _ = writeln!(f, "[{:>8.3}s] stdin pipe broken (err={}), giving up after {} retries",
                            stdin_start.elapsed().as_secs_f64(), err, eof_retries);
                        let _ = writeln!(f, "HINT: check DefaultShell and SSH client settings");
                        let _ = f.flush();
                    }
                    // Do NOT print to stderr: it travels through the SSH
                    // session and corrupts iTerm2's tmux control protocol.
                    // Diagnostics are in ~/.psmux/cc_debug.log.
                    Err(io::Error::from_raw_os_error(err as i32))
                } else {
                    if let Some(ref mut f) = stdin_log_file {
                        let _ = writeln!(f, "[{:>8.3}s] stdin ReadFile error: {}",
                            stdin_start.elapsed().as_secs_f64(), err);
                        let _ = f.flush();
                    }
                    Err(io::Error::from_raw_os_error(err as i32))
                }
            } else if bytes_read == 0 {
                // ReadFile succeeded but 0 bytes = EOF
                if total_bytes_read == 0 && eof_retries < MAX_EOF_RETRIES {
                    eof_retries += 1;
                    if let Some(ref mut f) = stdin_log_file {
                        if eof_retries <= 5 || eof_retries % 20 == 0 {
                            let _ = writeln!(f, "[{:>8.3}s] stdin EOF (0 bytes), retry {}/{}",
                                stdin_start.elapsed().as_secs_f64(), eof_retries, MAX_EOF_RETRIES);
                            let _ = f.flush();
                        }
                    }
                    std::thread::sleep(Duration::from_millis(50));
                    continue;
                }
                if let Some(ref mut f) = stdin_log_file {
                    let _ = writeln!(f, "[{:>8.3}s] stdin EOF, giving up after {} retries",
                        stdin_start.elapsed().as_secs_f64(), eof_retries);
                    let _ = f.flush();
                }
                Ok(0usize)
            } else {
                eof_retries = 0;
                Ok(bytes_read as usize)
            }
        };

        #[cfg(not(windows))]
        let read_result = {
            use std::io::Read;
            let stdin = io::stdin();
            stdin.lock().read(&mut stdin_buf)
        };

        let n = match read_result {
            Ok(0) => break,
            Err(_) => break,
            Ok(n) => {
                total_bytes_read += n as u64;
                if let Some(ref mut f) = stdin_log_file {
                    // Log a printable ASCII dump of all bytes (replace control bytes with .)
                    // plus the byte count. Avoids 80-byte truncation in the hex dump.
                    let asc: String = stdin_buf[..n].iter()
                        .map(|&b| {
                            if b == b'\r' { "\\r".to_string() }
                            else if b == b'\n' { "\\n".to_string() }
                            else if b == b'\t' { "\\t".to_string() }
                            else if (0x20..0x7f).contains(&b) { (b as char).to_string() }
                            else { format!("\\x{:02x}", b) }
                        }).collect::<String>();
                    let _ = writeln!(f, "[{:>8.3}s] IN  ({} bytes): {}",
                        stdin_start.elapsed().as_secs_f64(), n, asc);
                    let _ = f.flush();
                }
                n
            }
        };
        // Translate bare \r to \n (iTerm2 compat), skip if already \r\n
        let mut out = Vec::with_capacity(n);
        let chunk = &stdin_buf[..n];
        for i in 0..n {
            if chunk[i] == b'\r' {
                if i + 1 < n && chunk[i + 1] == b'\n' {
                    // \r\n pair: keep as-is (the \n will be written next iteration)
                    out.push(b'\r');
                } else {
                    // Bare \r: translate to \n
                    out.push(b'\n');
                }
            } else {
                out.push(chunk[i]);
            }
        }
        if write_stream.write_all(&out).is_err() { break; }
        if write_stream.flush().is_err() { break; }
    }

    // After stdin EOF, shut down the TCP write side so the server sees
    // EOF and can clean up.  Then emit %exit + ST to stdout like real
    // tmux's client does (tmux/client.c).
    let _ = write_stream.shutdown(std::net::Shutdown::Write);
    if let Some(ref mut f) = stdin_log_file {
        let _ = writeln!(f, "[{:>8.3}s] stdin closed (total_bytes_read={}), TCP write shut down",
            stdin_start.elapsed().as_secs_f64(), total_bytes_read);
        let _ = f.flush();
    }

    // Wait briefly for the reader thread to drain remaining responses,
    // then forcibly close.  The server may take up to 5s (its read timeout)
    // to notice the client is gone.
    let handle = reader_thread;
    let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let done2 = done.clone();
    std::thread::spawn(move || {
        let _ = handle.join();
        done2.store(true, std::sync::atomic::Ordering::Release);
    });
    // Drain for up to 2 seconds, then exit
    for _ in 0..40 {
        if done.load(std::sync::atomic::Ordering::Acquire) { break; }
        std::thread::sleep(Duration::from_millis(50));
    }

    // Emit %exit and ST to stdout like real tmux's client does
    // (tmux/client.c). iTerm2 watches for %exit to leave tmux
    // integration mode cleanly.  ST (\x1b\\) terminates the DCS.
    {
        let stdout = io::stdout();
        let mut out = stdout.lock();
        let _ = out.write_all(b"%exit\n");
        if mode == 2 {
            let _ = out.write_all(b"\x1b\\");
        }
        let _ = out.flush();
    }

    Ok(())
}

/// Returns `true` when stdout is a Windows console handle (ConPTY).
/// When stdout is a pipe (e.g. `ssh -T`), returns `false`.
#[cfg(windows)]
fn stdout_is_console() -> bool {
    #[link(name = "kernel32")]
    extern "system" {
        fn GetStdHandle(n: u32) -> *mut std::ffi::c_void;
        fn GetConsoleMode(h: *mut std::ffi::c_void, m: *mut u32) -> i32;
    }
    const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
    unsafe {
        let handle = GetStdHandle(STD_OUTPUT_HANDLE);
        if handle.is_null() || handle == (-1isize as *mut std::ffi::c_void) {
            return false;
        }
        let mut mode: u32 = 0;
        // GetConsoleMode succeeds only for console handles (not pipes/files)
        GetConsoleMode(handle, &mut mode) != 0
    }
}

/// Returns `true` when the process appears to be running inside an SSH session.
#[cfg(windows)]
fn is_ssh_session() -> bool {
    env::var("SSH_CLIENT").is_ok()
        || env::var("SSH_CONNECTION").is_ok()
        || env::var("SSH_TTY").is_ok()
}