boxmux 0.240.3373

YAML-driven terminal UI framework for rich, interactive CLI applications and dashboards with PTY support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
use serde::Deserializer;
use serde_json::Value;
use std::{collections::HashMap, error::Error, hash::Hash};

use crate::{
    color_utils::{get_bg_color, get_fg_color},
    model::choice::Choice,
    screen_bounds, screen_height, screen_width,
    utils::input_bounds_to_bounds,
    AppContext, AppGraph, Layout, Message, MuxBox,
};
use serde::{Deserialize, Serialize};
use std::time::Duration;

// F0220: ExecutionMode Enum Definition - Replace thread+pty boolean flags with single enum
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq, Default)]
pub enum ExecutionMode {
    /// Synchronous execution on UI thread but still flowing through stream architecture
    #[default]
    Immediate,
    /// Background execution in thread pool with stream updates when complete
    Thread,
    /// Real-time PTY execution with continuous stream updates
    Pty,
}

impl ExecutionMode {
    /// Get descriptive string for execution mode
    pub fn description(&self) -> &'static str {
        match self {
            ExecutionMode::Immediate => "Synchronous execution on UI thread",
            ExecutionMode::Thread => "Background execution in thread pool",
            ExecutionMode::Pty => "Real-time PTY execution with continuous output",
        }
    }

    /// Check if execution mode should create streams
    pub fn creates_streams(&self) -> bool {
        true // All execution modes create streams - no bypassing stream architecture
    }

    /// Check if execution mode is real-time
    pub fn is_realtime(&self) -> bool {
        match self {
            ExecutionMode::Immediate => false,
            ExecutionMode::Thread => false,
            ExecutionMode::Pty => true,
        }
    }

    /// Check if execution mode runs in background
    pub fn is_background(&self) -> bool {
        match self {
            ExecutionMode::Immediate => false,
            ExecutionMode::Thread => true,
            ExecutionMode::Pty => true,
        }
    }

    /// F0224: Get stream suffix for execution mode identification
    pub fn as_stream_suffix(&self) -> &'static str {
        match self {
            ExecutionMode::Immediate => "immediate",
            ExecutionMode::Thread => "thread",
            ExecutionMode::Pty => "pty",
        }
    }

    /// Check if execution mode is PTY-based
    pub fn is_pty(&self) -> bool {
        matches!(self, ExecutionMode::Pty)
    }

    /// Convert legacy thread+pty boolean flags to ExecutionMode enum
    /// PTY takes precedence when both flags are true
    pub fn from_legacy(thread: bool, pty: bool) -> Self {
        match (thread, pty) {
            (_, true) => ExecutionMode::Pty, // PTY takes precedence
            (true, false) => ExecutionMode::Thread,
            (false, false) => ExecutionMode::Immediate,
        }
    }
}

// UNIFIED EXECUTION ARCHITECTURE - T0300-T0305: New message types for unified execution system

/// T0300: ExecuteScript message struct - Universal entry point for all script execution
#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct ExecuteScript {
    pub script: Vec<String>,             // Script commands to execute
    pub source: ExecutionSource,         // Source information and reference
    pub execution_mode: ExecutionMode,   // How to execute (Batch/Thread/PTY)
    pub target_box_id: String,           // Where to create the stream
    pub libs: Vec<String>,               // Library dependencies
    pub redirect_output: Option<String>, // Optional output redirection
    pub append_output: bool,             // Append vs replace mode
    pub stream_id: String,               // Stream ID from source registry
    pub target_bounds: Option<Bounds>,   // Target muxbox bounds for PTY sizing
}

/// T0301: ExecutionSource and SourceType enums - Track what triggered the execution
#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct ExecutionSource {
    pub source_type: SourceType,           // What kind of source this is
    pub source_id: String,                 // Unique identifier for this execution
    pub source_reference: SourceReference, // Actual source data/object
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub enum SourceType {
    Choice(String),   // Choice ID that triggered execution
    StaticScript,     // Box-level YAML script (one-time execution)
    PeriodicRefresh,  // Periodic refresh script execution
    SocketUpdate,     // Dynamic socket-based script
    RedirectedScript, // Script with output redirection
    HotkeyScript,     // Hotkey-triggered script
    ScheduledScript,  // Timer/scheduled execution
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub enum SourceReference {
    Choice(Choice),         // Full choice object
    StaticConfig(String),   // YAML configuration reference (one-time)
    PeriodicConfig(String), // YAML configuration for periodic refresh
    SocketCommand(String),  // Socket command that triggered this
    HotkeyBinding(String),  // Hotkey that triggered this
    Schedule(String),       // Schedule configuration
}

/// T0302: StreamUpdate message struct - Universal content updates from any execution mode
#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct StreamUpdate {
    pub stream_id: String,             // Target stream to update
    pub target_box_id: String,         // Target box to create/update stream in
    pub content_update: String,        // New content to append
    pub source_state: SourceState,     // Current state of execution source
    pub execution_mode: ExecutionMode, // Mode that generated this update
}

/// T0303: SourceState enums - Track execution status for each mode
#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub enum SourceState {
    Batch(BatchSourceState),
    Thread(ThreadSourceState),
    Pty(PtySourceState),
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct BatchSourceState {
    pub task_id: String,           // Task queue identifier
    pub queue_wait_time: Duration, // Time spent waiting in queue
    pub execution_time: Duration,  // Actual execution duration
    pub exit_code: Option<i32>,    // Process exit code
    pub status: BatchStatus,       // Current status
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct ThreadSourceState {
    pub thread_id: String,             // Thread identifier
    pub execution_time: Duration,      // How long execution took
    pub exit_code: Option<i32>,        // Process exit code
    pub status: ExecutionThreadStatus, // Current status
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct PtySourceState {
    pub process_id: u32,            // PTY process ID
    pub runtime: Duration,          // How long process has been running
    pub exit_code: Option<i32>,     // Exit code if completed
    pub status: ExecutionPtyStatus, // Current process status
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub enum BatchStatus {
    Queued,         // Waiting in task queue
    Executing,      // Currently being executed
    Completed,      // Finished successfully - no more updates
    Failed(String), // Failed with error message - no more updates
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub enum ExecutionThreadStatus {
    Running,        // Thread is executing
    Completed,      // Finished successfully - no more updates
    Failed(String), // Failed with error message - no more updates
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub enum ExecutionPtyStatus {
    Starting,       // PTY process starting up
    Running,        // Process is running normally - more updates expected
    Completed,      // Process completed successfully - no more updates
    Failed(String), // Process failed with error - no more updates
    Terminated,     // Process was killed/terminated - no more updates
}

/// T0304: SourceAction message struct - Lifecycle management for executing sources
#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct SourceAction {
    pub action: ActionType,            // What action to perform
    pub source_id: String,             // Source identifier to act on
    pub execution_mode: ExecutionMode, // Mode of the target source
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub enum ActionType {
    Kill,   // Terminate execution
    Query,  // Get status information
    Pause,  // Pause execution (if supported)
    Resume, // Resume paused execution
}

impl SourceState {
    /// Determine if this source expects more updates based on status (NO is_final flag needed)
    pub fn expects_more_updates(&self) -> bool {
        match self {
            SourceState::Batch(state) => {
                matches!(state.status, BatchStatus::Queued | BatchStatus::Executing)
            }
            SourceState::Thread(state) => matches!(state.status, ExecutionThreadStatus::Running),
            SourceState::Pty(state) => matches!(
                state.status,
                ExecutionPtyStatus::Starting | ExecutionPtyStatus::Running
            ),
        }
    }
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub enum EntityType {
    AppContext,
    App,
    Layout,
    MuxBox,
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub enum StreamType {
    Content,
    Choices,
    RedirectedOutput(String), // Named redirect output
    PTY,
    Plugin(String),
    // F0210: Complete StreamType Enum - Add missing variants for source tracking
    ChoiceExecution(String), // Track choice executions as streams
    RedirectSource(String),  // Track redirect output sources
    ExternalSocket,          // External socket connections
    PtySession(String),      // PTY session with command info
    OwnScript,               // Box's own script execution stream
}

/// Unified source object that tracks all execution sources with their stream IDs
#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct UnifiedExecutionSource {
    pub source_id: String,     // Unique source identifier
    pub stream_id: String,     // Stream ID for this source
    pub target_box_id: String, // Which box receives updates
    pub source_type: ExecutionSourceType,
    pub created_at: std::time::SystemTime,
    pub status: ExecutionSourceStatus,
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub enum ExecutionSourceType {
    StaticContent(String),  // Box's static content
    PeriodicScript(String), // Box's periodic refresh script
    ChoiceExecution {
        // Choice script execution
        choice_id: String,
        script: Vec<String>,
        redirect_output: Option<String>,
    },
    PtyProcess {
        // PTY process
        process_id: Option<u32>,
        command: Vec<String>,
    },
    SocketUpdate {
        // Socket-based updates
        command_type: String,
    },
    HotkeyScript {
        // Hotkey-triggered script
        hotkey: String,
        script: Vec<String>,
    },
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub enum ExecutionSourceStatus {
    Pending,        // Waiting to start
    Running,        // Currently executing
    Completed,      // Finished successfully
    Failed(String), // Failed with error
    Terminated,     // Killed/stopped
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct Stream {
    pub id: String,
    pub stream_type: StreamType,
    pub label: String,
    pub content: Vec<String>,
    pub choices: Option<Vec<Choice>>, // For choices stream
    // F0212: Stream Source Tracking - enable stream termination when tabs closed
    pub source: Option<StreamSource>,
    // F0216: Stream Change Detection - track content changes for efficient updates
    #[serde(skip, default = "default_content_hash")]
    pub content_hash: u64,
    #[serde(skip, default = "default_system_time")]
    pub last_updated: std::time::SystemTime,
    #[serde(skip, default = "default_system_time")]
    pub created_at: std::time::SystemTime,
}

// Helper functions for default values
fn default_content_hash() -> u64 {
    0
}
fn default_system_time() -> std::time::SystemTime {
    std::time::SystemTime::now()
}

// F0217: Stream rendering behavior traits - exclusive content OR choices
pub trait ContentStreamTrait {
    fn get_content_lines(&self) -> &Vec<String>;
    fn set_content_lines(&mut self, content: Vec<String>);
}

pub trait ChoicesStreamTrait {
    fn get_choices(&self) -> &Vec<Choice>;
    fn get_choices_mut(&mut self) -> &mut Vec<Choice>;
    fn set_choices(&mut self, choices: Vec<Choice>);
}

// F0212: Base trait for all stream sources with lifecycle management
pub trait StreamSourceTrait {
    fn source_type(&self) -> &'static str;
    fn source_id(&self) -> String;
    fn can_terminate(&self) -> bool;
    fn cleanup(&self) -> Result<(), String>;
    fn get_metadata(&self) -> std::collections::HashMap<String, String>;
}

// F0227: ExecutionMode Stream Source Traits - Execution-mode-specific source traits
// These traits provide specialized lifecycle management for different execution modes

/// Trait for immediate execution sources - synchronous UI thread execution
pub trait ImmediateSource: StreamSourceTrait {
    /// Get the execution result if available
    fn get_execution_result(&self) -> Option<Result<String, String>>;
    /// Check if execution is complete
    fn is_complete(&self) -> bool;
    /// Get execution duration
    fn get_execution_duration(&self) -> Option<std::time::Duration>;
}

/// Trait for thread pool execution sources - background thread execution
pub trait ThreadPoolSource: StreamSourceTrait {
    /// Get thread handle for cancellation
    fn get_thread_id(&self) -> Option<String>;
    /// Check if thread is still running
    fn is_thread_running(&self) -> bool;
    /// Cancel the background thread
    fn cancel_thread(&self) -> Result<(), String>;
    /// Get thread execution status
    fn get_thread_status(&self) -> ThreadStatus;
    /// Set timeout for thread execution
    fn set_timeout(&mut self, timeout_seconds: u32);
}

/// Thread execution status for ThreadPoolSource
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Hash)]
pub enum ThreadStatus {
    NotStarted,
    Running,
    Completed,
    Failed,
    Cancelled,
    TimedOut,
}

/// Trait for PTY session sources - real-time process execution
pub trait PtySessionSource: StreamSourceTrait {
    /// Get PTY process ID
    fn get_process_id(&self) -> Option<u32>;
    /// Check if PTY process is still running
    fn is_process_running(&self) -> bool;
    /// Send input to PTY process
    fn send_input(&self, input: &str) -> Result<(), String>;
    /// Kill the PTY process
    fn kill_process(&self) -> Result<(), String>;
    /// Resize the PTY terminal
    fn resize_terminal(&self, rows: u16, cols: u16) -> Result<(), String>;
    /// Get terminal size
    fn get_terminal_size(&self) -> (u16, u16);
    /// Get command being executed
    fn get_command(&self) -> String;
    /// Get working directory
    fn get_working_directory(&self) -> Option<String>;
}

// F0212: Static content sources (no lifecycle management needed)
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct StaticContentSource {
    pub content_type: String, // "default", "choices", "manual"
    pub created_at: std::time::SystemTime,
}

impl StreamSourceTrait for StaticContentSource {
    fn source_type(&self) -> &'static str {
        "static_content"
    }
    fn source_id(&self) -> String {
        format!("static_{}", self.content_type)
    }
    fn can_terminate(&self) -> bool {
        false
    }
    fn cleanup(&self) -> Result<(), String> {
        Ok(())
    }
    fn get_metadata(&self) -> std::collections::HashMap<String, String> {
        let mut meta = std::collections::HashMap::new();
        meta.insert("content_type".to_string(), self.content_type.clone());
        meta.insert("created_at".to_string(), format!("{:?}", self.created_at));
        meta
    }
}

// F0212: Choice execution sources with thread management
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct ChoiceExecutionSource {
    pub choice_id: String,
    pub muxbox_id: String,
    pub thread_id: Option<String>, // For thread tracking
    pub process_id: Option<u32>,   // For process-based choices
    pub execution_type: String,    // "threaded", "process", "pty"
    pub started_at: std::time::SystemTime,
    pub timeout_seconds: Option<u32>,
}

/// Periodic refresh execution source - manages periodic script execution with persistent stream
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct PeriodicRefreshSource {
    pub source_id: String,                             // Unique source identifier
    pub box_id: String,                                // Target box for updates
    pub script: Vec<String>,                           // Script to execute periodically
    pub stream_id: String,                             // EMBEDDED: Stream ID for consistent updates
    pub execution_mode: ExecutionMode,                 // How to execute the script
    pub refresh_interval: u64,                         // Milliseconds between executions
    pub last_execution: Option<std::time::SystemTime>, // Last execution time
    pub created_at: std::time::SystemTime,             // When source was created
    pub execution_count: u64,                          // Number of times executed
}

impl StreamSourceTrait for ChoiceExecutionSource {
    fn source_type(&self) -> &'static str {
        "choice_execution"
    }
    fn source_id(&self) -> String {
        self.choice_id.clone()
    }
    fn can_terminate(&self) -> bool {
        true
    }
    fn cleanup(&self) -> Result<(), String> {
        match self.execution_type.as_str() {
            "process" => {
                if let Some(pid) = self.process_id {
                    // Terminate the process
                    let _ = std::process::Command::new("kill")
                        .arg("-9")
                        .arg(pid.to_string())
                        .output();
                }
                Ok(())
            }
            "threaded" => {
                // Thread cleanup would be handled by ThreadManager
                Ok(())
            }
            _ => Ok(()),
        }
    }
    fn get_metadata(&self) -> std::collections::HashMap<String, String> {
        let mut meta = std::collections::HashMap::new();
        meta.insert("choice_id".to_string(), self.choice_id.clone());
        meta.insert("muxbox_id".to_string(), self.muxbox_id.clone());
        meta.insert("execution_type".to_string(), self.execution_type.clone());
        if let Some(pid) = self.process_id {
            meta.insert("process_id".to_string(), pid.to_string());
        }
        if let Some(thread_id) = &self.thread_id {
            meta.insert("thread_id".to_string(), thread_id.clone());
        }
        meta
    }
}

impl StreamSourceTrait for PeriodicRefreshSource {
    fn source_type(&self) -> &'static str {
        "periodic_refresh"
    }
    fn source_id(&self) -> String {
        self.source_id.clone()
    }
    fn can_terminate(&self) -> bool {
        true // Periodic refresh can always be terminated
    }
    fn cleanup(&self) -> Result<(), String> {
        log::info!("Cleaning up periodic refresh source: {}", self.source_id);
        Ok(())
    }
    fn get_metadata(&self) -> std::collections::HashMap<String, String> {
        let mut metadata = std::collections::HashMap::new();
        metadata.insert("source_id".to_string(), self.source_id.clone());
        metadata.insert("box_id".to_string(), self.box_id.clone());
        metadata.insert("stream_id".to_string(), self.stream_id.clone());
        metadata.insert(
            "execution_mode".to_string(),
            format!("{:?}", self.execution_mode),
        );
        metadata.insert(
            "refresh_interval".to_string(),
            self.refresh_interval.to_string(),
        );
        metadata.insert(
            "execution_count".to_string(),
            self.execution_count.to_string(),
        );
        metadata
    }
}

// F0227: ExecutionMode-specific source implementations
// These provide specialized lifecycle management for each execution mode

/// Immediate execution source - for synchronous UI thread execution
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct ImmediateExecutionSource {
    pub choice_id: String,
    pub muxbox_id: String,
    pub script: Vec<String>,
    pub started_at: std::time::SystemTime,
    pub completed_at: Option<std::time::SystemTime>,
    pub execution_result: Option<Result<String, String>>,
    pub execution_duration: Option<std::time::Duration>,
}

impl StreamSourceTrait for ImmediateExecutionSource {
    fn source_type(&self) -> &'static str {
        "immediate_execution"
    }
    fn source_id(&self) -> String {
        format!("immediate_{}", self.choice_id)
    }
    fn can_terminate(&self) -> bool {
        false // Immediate execution cannot be cancelled once started
    }
    fn cleanup(&self) -> Result<(), String> {
        Ok(()) // No cleanup needed for immediate execution
    }
    fn get_metadata(&self) -> std::collections::HashMap<String, String> {
        let mut meta = std::collections::HashMap::new();
        meta.insert("choice_id".to_string(), self.choice_id.clone());
        meta.insert("muxbox_id".to_string(), self.muxbox_id.clone());
        meta.insert("script_lines".to_string(), self.script.len().to_string());
        meta.insert("started_at".to_string(), format!("{:?}", self.started_at));
        if let Some(completed_at) = self.completed_at {
            meta.insert("completed_at".to_string(), format!("{:?}", completed_at));
        }
        if let Some(duration) = self.execution_duration {
            meta.insert("duration_ms".to_string(), duration.as_millis().to_string());
        }
        meta.insert("is_complete".to_string(), self.is_complete().to_string());
        meta
    }
}

impl ImmediateSource for ImmediateExecutionSource {
    fn get_execution_result(&self) -> Option<Result<String, String>> {
        self.execution_result.clone()
    }

    fn is_complete(&self) -> bool {
        self.execution_result.is_some()
    }

    fn get_execution_duration(&self) -> Option<std::time::Duration> {
        self.execution_duration
    }
}

/// Thread pool execution source - for background thread execution
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct ThreadPoolExecutionSource {
    pub choice_id: String,
    pub muxbox_id: String,
    pub script: Vec<String>,
    pub thread_id: Option<String>,
    pub started_at: std::time::SystemTime,
    pub timeout_seconds: Option<u32>,
    pub thread_status: ThreadStatus,
    pub completion_result: Option<Result<String, String>>,
    pub execution_duration: Option<std::time::Duration>,
}

impl StreamSourceTrait for ThreadPoolExecutionSource {
    fn source_type(&self) -> &'static str {
        "thread_pool_execution"
    }
    fn source_id(&self) -> String {
        format!("thread_{}", self.choice_id)
    }
    fn can_terminate(&self) -> bool {
        matches!(
            self.thread_status,
            ThreadStatus::Running | ThreadStatus::NotStarted
        )
    }
    fn cleanup(&self) -> Result<(), String> {
        if let Some(thread_id) = &self.thread_id {
            // Note: Actual thread cancellation would be handled by ThreadManager
            log::info!("Cleanup requested for thread pool execution: {}", thread_id);
            Ok(())
        } else {
            Ok(())
        }
    }
    fn get_metadata(&self) -> std::collections::HashMap<String, String> {
        let mut meta = std::collections::HashMap::new();
        meta.insert("choice_id".to_string(), self.choice_id.clone());
        meta.insert("muxbox_id".to_string(), self.muxbox_id.clone());
        meta.insert("script_lines".to_string(), self.script.len().to_string());
        meta.insert(
            "thread_status".to_string(),
            format!("{:?}", self.thread_status),
        );
        meta.insert("started_at".to_string(), format!("{:?}", self.started_at));
        if let Some(thread_id) = &self.thread_id {
            meta.insert("thread_id".to_string(), thread_id.clone());
        }
        if let Some(timeout) = self.timeout_seconds {
            meta.insert("timeout_seconds".to_string(), timeout.to_string());
        }
        if let Some(duration) = self.execution_duration {
            meta.insert("duration_ms".to_string(), duration.as_millis().to_string());
        }
        meta
    }
}

impl ThreadPoolSource for ThreadPoolExecutionSource {
    fn get_thread_id(&self) -> Option<String> {
        self.thread_id.clone()
    }

    fn is_thread_running(&self) -> bool {
        matches!(self.thread_status, ThreadStatus::Running)
    }

    fn cancel_thread(&self) -> Result<(), String> {
        if matches!(
            self.thread_status,
            ThreadStatus::Running | ThreadStatus::NotStarted
        ) {
            // Note: Actual cancellation would be implemented by ThreadManager
            log::warn!(
                "Thread cancellation requested for choice: {}",
                self.choice_id
            );
            Ok(())
        } else {
            Err(format!(
                "Cannot cancel thread in status: {:?}",
                self.thread_status
            ))
        }
    }

    fn get_thread_status(&self) -> ThreadStatus {
        self.thread_status.clone()
    }

    fn set_timeout(&mut self, timeout_seconds: u32) {
        self.timeout_seconds = Some(timeout_seconds);
    }
}

/// PTY session execution source - for real-time process execution
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct PtySessionExecutionSource {
    pub choice_id: String,
    pub muxbox_id: String,
    pub command: String,
    pub args: Vec<String>,
    pub working_dir: Option<String>,
    pub process_id: Option<u32>,
    pub terminal_size: (u16, u16),
    pub started_at: std::time::SystemTime,
    pub reader_thread_id: Option<String>,
    pub is_process_running: bool,
}

impl StreamSourceTrait for PtySessionExecutionSource {
    fn source_type(&self) -> &'static str {
        "pty_session_execution"
    }
    fn source_id(&self) -> String {
        format!("pty_{}", self.choice_id)
    }
    fn can_terminate(&self) -> bool {
        self.process_id.is_some() && self.is_process_running
    }
    fn cleanup(&self) -> Result<(), String> {
        if let Some(pid) = self.process_id {
            if self.is_process_running {
                let result = std::process::Command::new("kill")
                    .arg("-9")
                    .arg(pid.to_string())
                    .output();
                match result {
                    Ok(_) => Ok(()),
                    Err(e) => Err(format!("Failed to terminate PTY process {}: {}", pid, e)),
                }
            } else {
                Ok(()) // Already terminated
            }
        } else {
            Ok(()) // No process to clean up
        }
    }
    fn get_metadata(&self) -> std::collections::HashMap<String, String> {
        let mut meta = std::collections::HashMap::new();
        meta.insert("choice_id".to_string(), self.choice_id.clone());
        meta.insert("muxbox_id".to_string(), self.muxbox_id.clone());
        meta.insert("command".to_string(), self.command.clone());
        meta.insert("args".to_string(), self.args.join(" "));
        meta.insert(
            "is_running".to_string(),
            self.is_process_running.to_string(),
        );
        meta.insert("started_at".to_string(), format!("{:?}", self.started_at));
        meta.insert(
            "terminal_size".to_string(),
            format!("{}x{}", self.terminal_size.0, self.terminal_size.1),
        );
        if let Some(pid) = self.process_id {
            meta.insert("process_id".to_string(), pid.to_string());
        }
        if let Some(thread_id) = &self.reader_thread_id {
            meta.insert("reader_thread_id".to_string(), thread_id.clone());
        }
        if let Some(wd) = &self.working_dir {
            meta.insert("working_dir".to_string(), wd.clone());
        }
        meta
    }
}

impl PtySessionSource for PtySessionExecutionSource {
    fn get_process_id(&self) -> Option<u32> {
        self.process_id
    }

    fn is_process_running(&self) -> bool {
        self.is_process_running
    }

    fn send_input(&self, input: &str) -> Result<(), String> {
        if self.process_id.is_some() && self.is_process_running {
            // Note: Actual input sending would be implemented by PTY manager
            log::info!(
                "PTY input requested for choice {}: {}",
                self.choice_id,
                input
            );
            Ok(())
        } else {
            Err("PTY process is not running".to_string())
        }
    }

    fn kill_process(&self) -> Result<(), String> {
        if let Some(pid) = self.process_id {
            if self.is_process_running {
                let result = std::process::Command::new("kill")
                    .arg("-TERM")
                    .arg(pid.to_string())
                    .output();
                match result {
                    Ok(_) => Ok(()),
                    Err(e) => Err(format!("Failed to kill PTY process {}: {}", pid, e)),
                }
            } else {
                Err("Process is not running".to_string())
            }
        } else {
            Err("No process ID available".to_string())
        }
    }

    fn resize_terminal(&self, rows: u16, cols: u16) -> Result<(), String> {
        if self.process_id.is_some() && self.is_process_running {
            // Note: Actual terminal resizing would be implemented by PTY manager
            log::info!(
                "PTY resize requested for choice {}: {}x{}",
                self.choice_id,
                rows,
                cols
            );
            Ok(())
        } else {
            Err("PTY process is not running".to_string())
        }
    }

    fn get_terminal_size(&self) -> (u16, u16) {
        self.terminal_size
    }

    fn get_command(&self) -> String {
        if self.args.is_empty() {
            self.command.clone()
        } else {
            format!("{} {}", self.command, self.args.join(" "))
        }
    }

    fn get_working_directory(&self) -> Option<String> {
        self.working_dir.clone()
    }
}

// F0212: PTY sources with process and terminal management
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct PTYSource {
    pub pty_id: String,
    pub process_id: u32,
    pub command: String,
    pub args: Vec<String>,
    pub working_dir: Option<String>,
    pub reader_thread_id: Option<String>,
    pub started_at: std::time::SystemTime,
    pub terminal_size: (u16, u16), // (rows, cols)
}

impl StreamSourceTrait for PTYSource {
    fn source_type(&self) -> &'static str {
        "pty"
    }
    fn source_id(&self) -> String {
        self.pty_id.clone()
    }
    fn can_terminate(&self) -> bool {
        true
    }
    fn cleanup(&self) -> Result<(), String> {
        // Terminate PTY process
        let result = std::process::Command::new("kill")
            .arg("-9")
            .arg(self.process_id.to_string())
            .output();
        match result {
            Ok(_) => Ok(()),
            Err(e) => Err(format!(
                "Failed to terminate PTY process {}: {}",
                self.process_id, e
            )),
        }
    }
    fn get_metadata(&self) -> std::collections::HashMap<String, String> {
        let mut meta = std::collections::HashMap::new();
        meta.insert("pty_id".to_string(), self.pty_id.clone());
        meta.insert("process_id".to_string(), self.process_id.to_string());
        meta.insert("command".to_string(), self.command.clone());
        meta.insert("args".to_string(), self.args.join(" "));
        meta.insert(
            "terminal_size".to_string(),
            format!("{}x{}", self.terminal_size.0, self.terminal_size.1),
        );
        if let Some(ref thread_id) = self.reader_thread_id {
            meta.insert("reader_thread_id".to_string(), thread_id.clone());
        }
        meta
    }
}

// F0212: Redirect sources with source tracking
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct RedirectSource {
    pub source_muxbox_id: String,
    pub source_choice_id: Option<String>,
    pub redirect_name: String,
    pub redirect_type: String, // "choice", "script", "pty", "external"
    pub created_at: std::time::SystemTime,
    pub source_process_id: Option<u32>, // For process-based redirects
}

impl StreamSourceTrait for RedirectSource {
    fn source_type(&self) -> &'static str {
        "redirect"
    }
    fn source_id(&self) -> String {
        format!("{}_{}", self.source_muxbox_id, self.redirect_name)
    }
    fn can_terminate(&self) -> bool {
        self.source_process_id.is_some()
    }
    fn cleanup(&self) -> Result<(), String> {
        if let Some(pid) = self.source_process_id {
            let result = std::process::Command::new("kill")
                .arg("-9")
                .arg(pid.to_string())
                .output();
            match result {
                Ok(_) => Ok(()),
                Err(e) => Err(format!(
                    "Failed to terminate redirect source process {}: {}",
                    pid, e
                )),
            }
        } else {
            Ok(())
        }
    }
    fn get_metadata(&self) -> std::collections::HashMap<String, String> {
        let mut meta = std::collections::HashMap::new();
        meta.insert(
            "source_muxbox_id".to_string(),
            self.source_muxbox_id.clone(),
        );
        meta.insert("redirect_name".to_string(), self.redirect_name.clone());
        meta.insert("redirect_type".to_string(), self.redirect_type.clone());
        if let Some(ref choice_id) = self.source_choice_id {
            meta.insert("source_choice_id".to_string(), choice_id.clone());
        }
        if let Some(pid) = self.source_process_id {
            meta.insert("source_process_id".to_string(), pid.to_string());
        }
        meta
    }
}

// F0212: Socket sources with connection management
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct SocketSource {
    pub connection_id: String,
    pub socket_path: Option<String>,
    pub client_info: String,
    pub protocol_version: String,
    pub connected_at: std::time::SystemTime,
    pub last_activity: std::time::SystemTime,
}

impl StreamSourceTrait for SocketSource {
    fn source_type(&self) -> &'static str {
        "socket"
    }
    fn source_id(&self) -> String {
        self.connection_id.clone()
    }
    fn can_terminate(&self) -> bool {
        true
    }
    fn cleanup(&self) -> Result<(), String> {
        // Socket cleanup would be handled by socket manager
        Ok(())
    }
    fn get_metadata(&self) -> std::collections::HashMap<String, String> {
        let mut meta = std::collections::HashMap::new();
        meta.insert("connection_id".to_string(), self.connection_id.clone());
        meta.insert("client_info".to_string(), self.client_info.clone());
        meta.insert(
            "protocol_version".to_string(),
            self.protocol_version.clone(),
        );
        if let Some(ref socket_path) = self.socket_path {
            meta.insert("socket_path".to_string(), socket_path.clone());
        }
        meta
    }
}

// F0212: Unified stream source enum containing all source types
// F0227: Updated to include execution-mode-specific sources
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub enum StreamSource {
    StaticContent(StaticContentSource),
    ChoiceExecution(ChoiceExecutionSource), // Legacy - kept for compatibility
    PeriodicRefresh(PeriodicRefreshSource), // Periodic refresh execution source
    PTY(PTYSource),
    Redirect(RedirectSource),
    Socket(SocketSource),
    // F0227: ExecutionMode-specific sources for enhanced lifecycle management
    ImmediateExecution(ImmediateExecutionSource),
    ThreadPoolExecution(ThreadPoolExecutionSource),
    PtySessionExecution(PtySessionExecutionSource),
}

// F0212: Implementation of StreamSourceTrait for the unified enum
// F0227: Updated to handle execution-mode-specific sources
impl StreamSourceTrait for StreamSource {
    fn source_type(&self) -> &'static str {
        match self {
            StreamSource::StaticContent(s) => s.source_type(),
            StreamSource::ChoiceExecution(s) => s.source_type(),
            StreamSource::PeriodicRefresh(s) => s.source_type(),
            StreamSource::PTY(s) => s.source_type(),
            StreamSource::Redirect(s) => s.source_type(),
            StreamSource::Socket(s) => s.source_type(),
            // F0227: ExecutionMode-specific sources
            StreamSource::ImmediateExecution(s) => s.source_type(),
            StreamSource::ThreadPoolExecution(s) => s.source_type(),
            StreamSource::PtySessionExecution(s) => s.source_type(),
        }
    }

    fn source_id(&self) -> String {
        match self {
            StreamSource::StaticContent(s) => s.source_id(),
            StreamSource::ChoiceExecution(s) => s.source_id(),
            StreamSource::PeriodicRefresh(s) => s.source_id(),
            StreamSource::PTY(s) => s.source_id(),
            StreamSource::Redirect(s) => s.source_id(),
            StreamSource::Socket(s) => s.source_id(),
            // F0227: ExecutionMode-specific sources
            StreamSource::ImmediateExecution(s) => s.source_id(),
            StreamSource::ThreadPoolExecution(s) => s.source_id(),
            StreamSource::PtySessionExecution(s) => s.source_id(),
        }
    }

    fn can_terminate(&self) -> bool {
        match self {
            StreamSource::StaticContent(s) => s.can_terminate(),
            StreamSource::ChoiceExecution(s) => s.can_terminate(),
            StreamSource::PeriodicRefresh(s) => s.can_terminate(),
            StreamSource::PTY(s) => s.can_terminate(),
            StreamSource::Redirect(s) => s.can_terminate(),
            StreamSource::Socket(s) => s.can_terminate(),
            // F0227: ExecutionMode-specific sources
            StreamSource::ImmediateExecution(s) => s.can_terminate(),
            StreamSource::ThreadPoolExecution(s) => s.can_terminate(),
            StreamSource::PtySessionExecution(s) => s.can_terminate(),
        }
    }

    fn cleanup(&self) -> Result<(), String> {
        match self {
            StreamSource::StaticContent(s) => s.cleanup(),
            StreamSource::ChoiceExecution(s) => s.cleanup(),
            StreamSource::PeriodicRefresh(s) => s.cleanup(),
            StreamSource::PTY(s) => s.cleanup(),
            StreamSource::Redirect(s) => s.cleanup(),
            StreamSource::Socket(s) => s.cleanup(),
            // F0227: ExecutionMode-specific sources
            StreamSource::ImmediateExecution(s) => s.cleanup(),
            StreamSource::ThreadPoolExecution(s) => s.cleanup(),
            StreamSource::PtySessionExecution(s) => s.cleanup(),
        }
    }

    fn get_metadata(&self) -> std::collections::HashMap<String, String> {
        match self {
            StreamSource::StaticContent(s) => s.get_metadata(),
            StreamSource::ChoiceExecution(s) => s.get_metadata(),
            StreamSource::PeriodicRefresh(s) => s.get_metadata(),
            StreamSource::PTY(s) => s.get_metadata(),
            StreamSource::Redirect(s) => s.get_metadata(),
            StreamSource::Socket(s) => s.get_metadata(),
            // F0227: ExecutionMode-specific sources
            StreamSource::ImmediateExecution(s) => s.get_metadata(),
            StreamSource::ThreadPoolExecution(s) => s.get_metadata(),
            StreamSource::PtySessionExecution(s) => s.get_metadata(),
        }
    }
}

// F0227: ExecutionMode Stream Source Factory Functions
// These functions create execution-mode-specific sources for stream integration

impl StreamSource {
    /// Create an immediate execution source for synchronous UI thread execution
    pub fn create_immediate_execution_source(
        choice_id: String,
        muxbox_id: String,
        script: Vec<String>,
    ) -> Self {
        StreamSource::ImmediateExecution(ImmediateExecutionSource {
            choice_id,
            muxbox_id,
            script,
            started_at: std::time::SystemTime::now(),
            completed_at: None,
            execution_result: None,
            execution_duration: None,
        })
    }

    /// Create a thread pool execution source for background thread execution
    pub fn create_thread_pool_execution_source(
        choice_id: String,
        muxbox_id: String,
        script: Vec<String>,
        thread_id: Option<String>,
        timeout_seconds: Option<u32>,
    ) -> Self {
        StreamSource::ThreadPoolExecution(ThreadPoolExecutionSource {
            choice_id,
            muxbox_id,
            script,
            thread_id,
            started_at: std::time::SystemTime::now(),
            timeout_seconds,
            thread_status: ThreadStatus::NotStarted,
            completion_result: None,
            execution_duration: None,
        })
    }

    /// Create a PTY session execution source for real-time process execution
    pub fn create_pty_session_execution_source(
        choice_id: String,
        muxbox_id: String,
        command: String,
        args: Vec<String>,
        working_dir: Option<String>,
        terminal_size: (u16, u16),
    ) -> Self {
        StreamSource::PtySessionExecution(PtySessionExecutionSource {
            choice_id,
            muxbox_id,
            command,
            args,
            working_dir,
            process_id: None,
            terminal_size,
            started_at: std::time::SystemTime::now(),
            reader_thread_id: None,
            is_process_running: false,
        })
    }

    /// Convert ExecutionMode to the appropriate source type
    pub fn from_execution_mode(
        execution_mode: &ExecutionMode,
        choice_id: String,
        muxbox_id: String,
        script: Vec<String>,
        additional_params: Option<std::collections::HashMap<String, String>>,
    ) -> Self {
        match execution_mode {
            ExecutionMode::Immediate => {
                Self::create_immediate_execution_source(choice_id, muxbox_id, script)
            }
            ExecutionMode::Thread => {
                let thread_id = additional_params
                    .as_ref()
                    .and_then(|p| p.get("thread_id"))
                    .cloned();
                let timeout_seconds = additional_params
                    .as_ref()
                    .and_then(|p| p.get("timeout_seconds"))
                    .and_then(|s| s.parse().ok());
                Self::create_thread_pool_execution_source(
                    choice_id,
                    muxbox_id,
                    script,
                    thread_id,
                    timeout_seconds,
                )
            }
            ExecutionMode::Pty => {
                let command = if script.is_empty() {
                    "sh".to_string()
                } else {
                    script[0].clone()
                };
                let args = if script.len() > 1 {
                    script[1..].to_vec()
                } else {
                    vec![]
                };
                let working_dir = additional_params
                    .as_ref()
                    .and_then(|p| p.get("working_dir"))
                    .cloned();
                let terminal_size = additional_params
                    .as_ref()
                    .and_then(|p| {
                        let rows = p.get("terminal_rows")?.parse().ok()?;
                        let cols = p.get("terminal_cols")?.parse().ok()?;
                        Some((rows, cols))
                    })
                    .unwrap_or((24, 80));
                Self::create_pty_session_execution_source(
                    choice_id,
                    muxbox_id,
                    command,
                    args,
                    working_dir,
                    terminal_size,
                )
            }
        }
    }

    /// Check if this source supports a specific execution mode trait
    pub fn supports_immediate_source(&self) -> bool {
        matches!(self, StreamSource::ImmediateExecution(_))
    }

    pub fn supports_thread_pool_source(&self) -> bool {
        matches!(self, StreamSource::ThreadPoolExecution(_))
    }

    pub fn supports_pty_session_source(&self) -> bool {
        matches!(self, StreamSource::PtySessionExecution(_))
    }

    /// Get execution mode-specific source as trait object
    pub fn as_immediate_source(&self) -> Option<&dyn ImmediateSource> {
        match self {
            StreamSource::ImmediateExecution(source) => Some(source),
            _ => None,
        }
    }

    pub fn as_thread_pool_source(&self) -> Option<&dyn ThreadPoolSource> {
        match self {
            StreamSource::ThreadPoolExecution(source) => Some(source),
            _ => None,
        }
    }

    pub fn as_pty_session_source(&self) -> Option<&dyn PtySessionSource> {
        match self {
            StreamSource::PtySessionExecution(source) => Some(source),
            _ => None,
        }
    }
}

// F0216: Stream Change Detection Implementation
impl Stream {
    /// Create a new stream with proper change detection initialization
    pub fn new(
        id: String,
        stream_type: StreamType,
        label: String,
        content: Vec<String>,
        choices: Option<Vec<Choice>>,
        source: Option<StreamSource>,
    ) -> Self {
        let now = std::time::SystemTime::now();
        let mut stream = Self {
            id,
            stream_type,
            label,
            content,
            choices,
            source,
            content_hash: 0,
            last_updated: now,
            created_at: now,
        };
        stream.update_content_hash();
        stream
    }

    /// Update the content hash for change detection
    pub fn update_content_hash(&mut self) {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        self.content.hash(&mut hasher);
        if let Some(ref choices) = self.choices {
            choices.hash(&mut hasher);
        }
        self.content_hash = hasher.finish();
        self.last_updated = std::time::SystemTime::now();
    }

    /// Check if content has changed since last hash update
    pub fn has_content_changed(&self) -> bool {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        self.content.hash(&mut hasher);
        if let Some(ref choices) = self.choices {
            choices.hash(&mut hasher);
        }
        let current_hash = hasher.finish();
        current_hash != self.content_hash
    }

    /// Update content and automatically refresh change detection
    pub fn update_content(&mut self, new_content: Vec<String>) {
        self.content = new_content;
        self.update_content_hash();
    }

    /// Update choices and automatically refresh change detection  
    pub fn update_choices(&mut self, new_choices: Option<Vec<Choice>>) {
        self.choices = new_choices;
        self.update_content_hash();
    }

    /// Get time since last update for staleness detection
    pub fn time_since_last_update(
        &self,
    ) -> Result<std::time::Duration, std::time::SystemTimeError> {
        std::time::SystemTime::now().duration_since(self.last_updated)
    }

    /// F0219: Check if stream can be closed (has close button)
    pub fn is_closeable(&self) -> bool {
        matches!(
            &self.stream_type,
            StreamType::RedirectedOutput(_)
                | StreamType::ChoiceExecution(_)
                | StreamType::PtySession(_)
                | StreamType::ExternalSocket
        )
    }
}

// F0217: Implement ContentStreamTrait for content-type streams
impl ContentStreamTrait for Stream {
    fn get_content_lines(&self) -> &Vec<String> {
        match self.stream_type {
            StreamType::Content
            | StreamType::RedirectedOutput(_)
            | StreamType::PTY
            | StreamType::Plugin(_)
            | StreamType::ChoiceExecution(_)
            | StreamType::PtySession(_)
            | StreamType::OwnScript => &self.content,
            _ => panic!(
                "ContentStreamTrait called on non-content stream: {:?}",
                self.stream_type
            ),
        }
    }

    fn set_content_lines(&mut self, content: Vec<String>) {
        match self.stream_type {
            StreamType::Content
            | StreamType::RedirectedOutput(_)
            | StreamType::PTY
            | StreamType::Plugin(_)
            | StreamType::ChoiceExecution(_)
            | StreamType::PtySession(_)
            | StreamType::OwnScript => {
                self.content = content;
                self.update_content_hash();
            }
            _ => panic!(
                "ContentStreamTrait called on non-content stream: {:?}",
                self.stream_type
            ),
        }
    }
}

// F0217: Implement ChoicesStreamTrait for choices-type streams
impl ChoicesStreamTrait for Stream {
    fn get_choices(&self) -> &Vec<Choice> {
        match self.stream_type {
            StreamType::Choices => self
                .choices
                .as_ref()
                .expect("Choices stream must have choices"),
            _ => panic!(
                "ChoicesStreamTrait called on non-choices stream: {:?}",
                self.stream_type
            ),
        }
    }

    fn get_choices_mut(&mut self) -> &mut Vec<Choice> {
        match self.stream_type {
            StreamType::Choices => self
                .choices
                .as_mut()
                .expect("Choices stream must have choices"),
            _ => panic!(
                "ChoicesStreamTrait called on non-choices stream: {:?}",
                self.stream_type
            ),
        }
    }

    fn set_choices(&mut self, choices: Vec<Choice>) {
        match self.stream_type {
            StreamType::Choices => {
                self.choices = Some(choices);
                self.update_content_hash();
            }
            _ => panic!(
                "ChoicesStreamTrait called on non-choices stream: {:?}",
                self.stream_type
            ),
        }
    }
}

// Represents a granular field update
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct FieldUpdate {
    pub entity_type: EntityType,   // The type of entity being updated
    pub entity_id: Option<String>, // The ID of the entity (App, Layout, or MuxBox)
    pub field_name: String,        // The field name to be updated
    pub new_value: Value,          // The new value for the field
}

// The Updatable trait
pub trait Updatable {
    // Generate a diff of changes from another instance
    fn generate_diff(&self, other: &Self) -> Vec<FieldUpdate>;

    // Apply a list of updates to the current instance
    fn apply_updates(&mut self, updates: Vec<FieldUpdate>);
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct Config {
    pub frame_delay: u64,
    pub locked: bool, // Disable muxbox resizing and moving when true
    #[serde(default)]
    pub calibrate: bool,
}

impl Hash for Config {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.frame_delay.hash(state);
        self.locked.hash(state);
        self.calibrate.hash(state);
    }
}

impl Default for Config {
    fn default() -> Self {
        Config {
            frame_delay: 30,
            locked: false, // Default to unlocked (resizable/movable)
            calibrate: false,
        }
    }
}

impl Config {
    pub fn new(frame_delay: u64) -> Self {
        let result = Config {
            frame_delay,
            locked: false, // Default to unlocked
            calibrate: false,
        };
        result.validate();
        result
    }

    pub fn new_with_lock(frame_delay: u64, locked: bool) -> Self {
        let result = Config {
            frame_delay,
            locked,
            calibrate: false,
        };
        result.validate();
        result
    }

    pub fn new_with_lock_and_calibration(frame_delay: u64, locked: bool, calibrate: bool) -> Self {
        let result = Config {
            frame_delay,
            locked,
            calibrate,
        };
        result.validate();
        result
    }
    pub fn validate(&self) {
        if self.frame_delay == 0 {
            panic!("Validation error: frame_delay cannot be 0");
        }
    }
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub enum SocketFunction {
    ReplaceBoxContent {
        box_id: String,
        success: bool,
        content: String,
    },
    ReplaceBoxScript {
        box_id: String,
        script: Vec<String>,
    },
    StopBoxRefresh {
        box_id: String,
    },
    StartBoxRefresh {
        box_id: String,
    },
    ReplaceBox {
        box_id: String,
        new_box: MuxBox,
    },
    SwitchActiveLayout {
        layout_id: String,
    },
    AddBox {
        layout_id: String,
        muxbox: MuxBox,
    },
    RemoveBox {
        box_id: String,
    },
    // F0137: Socket PTY Control - Kill and restart PTY processes
    KillPtyProcess {
        box_id: String,
    },
    RestartPtyProcess {
        box_id: String,
    },
    // F0138: Socket PTY Query - Get PTY status and info
    QueryPtyStatus {
        box_id: String,
    },
    // F0136: Socket PTY Spawn - Spawn PTY processes via socket commands
    SpawnPtyProcess {
        box_id: String,
        script: Vec<String>,
        libs: Option<Vec<String>>,
        redirect_output: Option<String>,
    },
    // F0139: Socket PTY Input - Send input to PTY processes remotely
    SendPtyInput {
        box_id: String,
        input: String,
    },
}

pub fn run_socket_function(
    socket_function: SocketFunction,
    app_context: &AppContext,
) -> Result<(AppContext, Vec<Message>), Box<dyn Error>> {
    let mut app_context = app_context.clone();
    let mut messages = Vec::new();
    match socket_function {
        SocketFunction::ReplaceBoxContent {
            box_id,
            success,
            content,
        } => {
            // T0328: Replace MuxBoxOutputUpdate with StreamUpdateMessage
            messages.push(Message::StreamUpdateMessage(
                crate::model::common::StreamUpdate {
                    stream_id: format!("socket-{}", box_id),
                    target_box_id: box_id.clone(),
                    content_update: content,
                    source_state: crate::model::common::SourceState::Batch(
                        crate::model::common::BatchSourceState {
                            task_id: format!("socket-{}", box_id),
                            queue_wait_time: std::time::Duration::from_millis(0),
                            execution_time: std::time::Duration::from_millis(0),
                            exit_code: if success { Some(0) } else { Some(1) },
                            status: if success {
                                crate::model::common::BatchStatus::Completed
                            } else {
                                crate::model::common::BatchStatus::Failed(
                                    "Unknown error".to_string(),
                                )
                            },
                        },
                    ),
                    execution_mode: crate::model::common::ExecutionMode::Immediate,
                },
            ));
        }
        SocketFunction::ReplaceBoxScript { box_id, script } => {
            messages.push(Message::MuxBoxScriptUpdate(box_id, script));
        }
        SocketFunction::StopBoxRefresh { box_id } => {
            messages.push(Message::StopBoxRefresh(box_id));
        }
        SocketFunction::StartBoxRefresh { box_id } => {
            messages.push(Message::StartBoxRefresh(box_id));
        }
        SocketFunction::ReplaceBox { box_id, new_box } => {
            messages.push(Message::ReplaceMuxBox(box_id, new_box));
        }
        SocketFunction::SwitchActiveLayout { layout_id } => {
            messages.push(Message::SwitchActiveLayout(layout_id));
        }
        SocketFunction::AddBox { layout_id, muxbox } => {
            messages.push(Message::AddBox(layout_id, muxbox));
        }
        SocketFunction::RemoveBox { box_id } => {
            messages.push(Message::RemoveBox(box_id));
        }
        // F0137: Socket PTY Control - Kill and restart PTY processes
        SocketFunction::KillPtyProcess { box_id } => {
            if let Some(pty_manager) = &app_context.pty_manager {
                // Get the stream ID from the PTY process source object
                let stream_id = pty_manager
                    .get_stream_id(&box_id)
                    .unwrap_or_else(|| format!("error-no-pty-{}", box_id));

                match pty_manager.kill_pty_process(&box_id) {
                    Ok(_) => {
                        messages.push(Message::StreamUpdateMessage(
                            crate::model::common::StreamUpdate {
                                target_box_id: box_id.clone(),
                                stream_id,
                                content_update: format!("PTY process killed for box {}", box_id),
                                source_state: crate::model::common::SourceState::Pty(
                                    crate::model::common::PtySourceState {
                                        process_id: 0,
                                        runtime: std::time::Duration::from_millis(0),
                                        exit_code: Some(0),
                                        status: crate::model::common::ExecutionPtyStatus::Completed,
                                    },
                                ),
                                execution_mode: crate::model::common::ExecutionMode::Pty,
                            },
                        ));
                    }
                    Err(err) => {
                        messages.push(Message::StreamUpdateMessage(
                            crate::model::common::StreamUpdate {
                                target_box_id: box_id.clone(),
                                stream_id,
                                content_update: format!("Failed to kill PTY process: {}", err),
                                source_state: crate::model::common::SourceState::Pty(
                                    crate::model::common::PtySourceState {
                                        process_id: 0,
                                        runtime: std::time::Duration::from_millis(0),
                                        exit_code: Some(1),
                                        status: crate::model::common::ExecutionPtyStatus::Failed(
                                            "Error".to_string(),
                                        ),
                                    },
                                ),
                                execution_mode: crate::model::common::ExecutionMode::Pty,
                            },
                        ));
                    }
                }
            } else {
                messages.push(Message::StreamUpdateMessage(
                    crate::model::common::StreamUpdate {
                        target_box_id: box_id.clone(),
                        stream_id: format!("error-no-pty-{}", box_id),
                        content_update: "PTY manager not available".to_string(),
                        source_state: crate::model::common::SourceState::Pty(
                            crate::model::common::PtySourceState {
                                process_id: 0,
                                runtime: std::time::Duration::from_millis(0),
                                exit_code: Some(1),
                                status: crate::model::common::ExecutionPtyStatus::Failed(
                                    "PTY manager not available".to_string(),
                                ),
                            },
                        ),
                        execution_mode: crate::model::common::ExecutionMode::Pty,
                    },
                ));
            }
        }
        SocketFunction::RestartPtyProcess { box_id } => {
            if let Some(pty_manager) = &app_context.pty_manager {
                match pty_manager.restart_pty_process(&box_id) {
                    Ok(_) => {
                        messages.push(Message::StreamUpdateMessage(
                            crate::model::common::StreamUpdate {
                                target_box_id: box_id.clone(),
                                stream_id: pty_manager
                                    .get_stream_id(&box_id)
                                    .unwrap_or_else(|| format!("error-no-pty-{}", box_id)),
                                content_update: format!("PTY process restarted for box {}", box_id),
                                source_state: crate::model::common::SourceState::Pty(
                                    crate::model::common::PtySourceState {
                                        process_id: 0,
                                        runtime: std::time::Duration::from_millis(0),
                                        exit_code: Some(0),
                                        status: crate::model::common::ExecutionPtyStatus::Completed,
                                    },
                                ),
                                execution_mode: crate::model::common::ExecutionMode::Pty,
                            },
                        ));
                    }
                    Err(err) => {
                        messages.push(Message::StreamUpdateMessage(
                            crate::model::common::StreamUpdate {
                                target_box_id: box_id.clone(),
                                stream_id: pty_manager
                                    .get_stream_id(&box_id)
                                    .unwrap_or_else(|| format!("error-no-pty-{}", box_id)),
                                content_update: format!("Failed to restart PTY process: {}", err),
                                source_state: crate::model::common::SourceState::Pty(
                                    crate::model::common::PtySourceState {
                                        process_id: 0,
                                        runtime: std::time::Duration::from_millis(0),
                                        exit_code: Some(1),
                                        status: crate::model::common::ExecutionPtyStatus::Failed(
                                            "Error".to_string(),
                                        ),
                                    },
                                ),
                                execution_mode: crate::model::common::ExecutionMode::Pty,
                            },
                        ));
                    }
                }
            } else {
                messages.push(Message::StreamUpdateMessage(
                    crate::model::common::StreamUpdate {
                        target_box_id: box_id.clone(),
                        stream_id: format!("error-no-pty-{}", box_id),
                        content_update: "PTY manager not available".to_string(),
                        source_state: crate::model::common::SourceState::Pty(
                            crate::model::common::PtySourceState {
                                process_id: 0,
                                runtime: std::time::Duration::from_millis(0),
                                exit_code: Some(1),
                                status: crate::model::common::ExecutionPtyStatus::Failed(
                                    "PTY manager not available".to_string(),
                                ),
                            },
                        ),
                        execution_mode: crate::model::common::ExecutionMode::Pty,
                    },
                ));
            }
        }
        // F0138: Socket PTY Query - Get PTY status and info
        SocketFunction::QueryPtyStatus { box_id } => {
            if let Some(pty_manager) = &app_context.pty_manager {
                if let Some(info) = pty_manager.get_detailed_process_info(&box_id) {
                    let status_info = format!(
                        "PTY Status - Box: {}, PID: {:?}, Status: {:?}, Running: {}, Buffer Lines: {}",
                        info.muxbox_id, info.process_id, info.status, info.is_running, info.buffer_lines
                    );
                    messages.push(Message::StreamUpdateMessage(
                        crate::model::common::StreamUpdate {
                            target_box_id: box_id.clone(),
                            stream_id: format!("error-no-manager-{}", box_id),
                            content_update: status_info,
                            source_state: crate::model::common::SourceState::Pty(
                                crate::model::common::PtySourceState {
                                    process_id: 0,
                                    runtime: std::time::Duration::from_millis(0),
                                    exit_code: Some(0),
                                    status: crate::model::common::ExecutionPtyStatus::Completed,
                                },
                            ),
                            execution_mode: crate::model::common::ExecutionMode::Pty,
                        },
                    ));
                } else {
                    messages.push(Message::StreamUpdateMessage(
                        crate::model::common::StreamUpdate {
                            target_box_id: box_id.clone(),
                            stream_id: format!("error-no-manager-{}", box_id),
                            content_update: format!("No PTY process found for box {}", box_id),
                            source_state: crate::model::common::SourceState::Pty(
                                crate::model::common::PtySourceState {
                                    process_id: 0,
                                    runtime: std::time::Duration::from_millis(0),
                                    exit_code: Some(1),
                                    status: crate::model::common::ExecutionPtyStatus::Failed(
                                        "Error".to_string(),
                                    ),
                                },
                            ),
                            execution_mode: crate::model::common::ExecutionMode::Pty,
                        },
                    ));
                }
            } else {
                messages.push(Message::StreamUpdateMessage(
                    crate::model::common::StreamUpdate {
                        target_box_id: box_id.clone(),
                        stream_id: format!("error-no-pty-{}", box_id),
                        content_update: "PTY manager not available".to_string(),
                        source_state: crate::model::common::SourceState::Pty(
                            crate::model::common::PtySourceState {
                                process_id: 0,
                                runtime: std::time::Duration::from_millis(0),
                                exit_code: Some(1),
                                status: crate::model::common::ExecutionPtyStatus::Failed(
                                    "PTY manager not available".to_string(),
                                ),
                            },
                        ),
                        execution_mode: crate::model::common::ExecutionMode::Pty,
                    },
                ));
            }
        }
        // F0136: Socket PTY Spawn - Spawn PTY processes via socket commands
        SocketFunction::SpawnPtyProcess {
            box_id,
            script,
            libs,
            redirect_output,
        } => {
            // First register execution source to get stream_id
            let stream_id = app_context.app.register_execution_source(
                ExecutionSourceType::SocketUpdate {
                    command_type: "spawn_pty_process".to_string(),
                },
                box_id.clone(),
            );

            // Route through unified execution architecture with registered stream_id
            let execute_script_msg =
                crate::thread_manager::Message::ExecuteScriptMessage(ExecuteScript {
                    script,
                    source: ExecutionSource {
                        source_type: SourceType::SocketUpdate,
                        source_id: box_id.clone(),
                        source_reference: SourceReference::SocketCommand(
                            "spawn_pty_process".to_string(),
                        ),
                    },
                    execution_mode: ExecutionMode::Pty,
                    target_box_id: box_id.clone(),
                    libs: libs.unwrap_or_default(),
                    redirect_output,
                    append_output: false,
                    stream_id,
                    target_bounds: None, // Socket commands don't have direct access to bounds - will use defaults
                });

            // Add ExecuteScript message to be sent via ThreadManager
            messages.push(execute_script_msg);
            log::info!(
                "PTY process spawn queued for execution via unified architecture: {}",
                box_id
            );
        }
        // F0139: Socket PTY Input - Send input to PTY processes remotely
        SocketFunction::SendPtyInput { box_id, input } => {
            if let Some(pty_manager) = &app_context.pty_manager {
                // Get the stream ID from the PTY process source object
                let stream_id = pty_manager
                    .get_stream_id(&box_id)
                    .unwrap_or_else(|| format!("error-no-pty-{}", box_id));

                match pty_manager.send_input(&box_id, &input) {
                    Ok(_) => {
                        messages.push(Message::StreamUpdateMessage(
                            crate::model::common::StreamUpdate {
                                target_box_id: box_id.clone(),
                                stream_id,
                                content_update: format!(
                                    "Input sent successfully to PTY process for box {}",
                                    box_id
                                ),
                                source_state: crate::model::common::SourceState::Pty(
                                    crate::model::common::PtySourceState {
                                        process_id: 0,
                                        runtime: std::time::Duration::from_millis(0),
                                        exit_code: Some(0),
                                        status: crate::model::common::ExecutionPtyStatus::Completed,
                                    },
                                ),
                                execution_mode: crate::model::common::ExecutionMode::Pty,
                            },
                        ));
                    }
                    Err(err) => {
                        messages.push(Message::StreamUpdateMessage(
                            crate::model::common::StreamUpdate {
                                target_box_id: box_id.clone(),
                                stream_id,
                                content_update: format!(
                                    "Failed to send input to PTY process: {}",
                                    err
                                ),
                                source_state: crate::model::common::SourceState::Pty(
                                    crate::model::common::PtySourceState {
                                        process_id: 0,
                                        runtime: std::time::Duration::from_millis(0),
                                        exit_code: Some(1),
                                        status: crate::model::common::ExecutionPtyStatus::Failed(
                                            "Error".to_string(),
                                        ),
                                    },
                                ),
                                execution_mode: crate::model::common::ExecutionMode::Pty,
                            },
                        ));
                    }
                }
            } else {
                messages.push(Message::StreamUpdateMessage(
                    crate::model::common::StreamUpdate {
                        target_box_id: box_id.clone(),
                        stream_id: format!("error-no-pty-{}", box_id),
                        content_update: "PTY manager not available".to_string(),
                        source_state: crate::model::common::SourceState::Pty(
                            crate::model::common::PtySourceState {
                                process_id: 0,
                                runtime: std::time::Duration::from_millis(0),
                                exit_code: Some(1),
                                status: crate::model::common::ExecutionPtyStatus::Failed(
                                    "PTY manager not available".to_string(),
                                ),
                            },
                        ),
                        execution_mode: crate::model::common::ExecutionMode::Pty,
                    },
                ));
            }
        }
    }
    Ok((app_context, messages))
}

#[derive(Clone, PartialEq, Debug)]
pub struct Cell {
    pub fg_color: String,
    pub bg_color: String,
    pub ch: char,
}

#[derive(Debug, Clone)]
pub struct ScreenBuffer {
    pub width: usize,
    pub height: usize,
    pub buffer: Vec<Vec<Cell>>,
}

impl Default for ScreenBuffer {
    fn default() -> Self {
        Self::new()
    }
}

impl ScreenBuffer {
    pub fn new() -> Self {
        // Theme-aware default so any cell never touched by a draw (the root area
        // behind/around panels) shows the THEME background — white in light, black
        // in dark — instead of a hardcoded black that darkened the whole app in
        // light mode.
        let default_cell = Cell {
            fg_color: get_fg_color(crate::color_utils::default_fg_color(false)),
            bg_color: get_bg_color(crate::color_utils::default_bg_color(false)),
            ch: ' ',
        };
        let width = screen_width();
        let height = screen_height();
        let buffer = vec![vec![default_cell; width]; height];
        ScreenBuffer {
            width,
            height,
            buffer,
        }
    }

    pub fn new_custom(width: usize, height: usize) -> Self {
        // Theme-aware default so any cell never touched by a draw (the root area
        // behind/around panels) shows the THEME background — white in light, black
        // in dark — instead of a hardcoded black that darkened the whole app in
        // light mode.
        let default_cell = Cell {
            fg_color: get_fg_color(crate::color_utils::default_fg_color(false)),
            bg_color: get_bg_color(crate::color_utils::default_bg_color(false)),
            ch: ' ',
        };
        let buffer = vec![vec![default_cell; width]; height];
        ScreenBuffer {
            width,
            height,
            buffer,
        }
    }

    pub fn clear(&mut self) {
        // Theme-aware default so any cell never touched by a draw (the root area
        // behind/around panels) shows the THEME background — white in light, black
        // in dark — instead of a hardcoded black that darkened the whole app in
        // light mode.
        let default_cell = Cell {
            fg_color: get_fg_color(crate::color_utils::default_fg_color(false)),
            bg_color: get_bg_color(crate::color_utils::default_bg_color(false)),
            ch: ' ',
        };
        self.buffer = vec![vec![default_cell; self.width]; self.height];
    }

    pub fn update(&mut self, x: usize, y: usize, cell: Cell) {
        if x < self.width && y < self.height {
            self.buffer[y][x] = cell;
        }
    }

    pub fn get(&self, x: usize, y: usize) -> Option<&Cell> {
        if x < self.width && y < self.height {
            Some(&self.buffer[y][x])
        } else {
            None
        }
    }

    pub fn resize(&mut self, width: usize, height: usize) {
        // First handle shrinking the buffer if necessary
        if height < self.height {
            self.buffer.truncate(height);
        }
        if width < self.width {
            for row in &mut self.buffer {
                row.truncate(width);
            }
        }

        // Now handle expanding the buffer if necessary
        if height > self.height {
            let default_row = vec![
                Cell {
                    fg_color: get_fg_color("white"),
                    bg_color: get_bg_color("black"),
                    ch: ' ',
                };
                width
            ];

            self.buffer.resize_with(height, || default_row.clone());
        }
        if width > self.width {
            for row in &mut self.buffer {
                row.resize_with(width, || Cell {
                    fg_color: get_fg_color("white"),
                    bg_color: get_bg_color("black"),
                    ch: ' ',
                });
            }
        }

        // Update the dimensions
        self.width = width;
        self.height = height;
    }
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq)]
pub struct InputBounds {
    pub x1: String,
    pub y1: String,
    pub x2: String,
    pub y2: String,
}

impl InputBounds {
    pub fn to_bounds(&self, parent_bounds: &Bounds) -> Bounds {
        input_bounds_to_bounds(self, parent_bounds)
    }
}

#[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Bounds {
    pub x1: usize,
    pub y1: usize,
    pub x2: usize,
    pub y2: usize,
}

// PartialEq and Eq now derived automatically

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Hash, Eq, Default)]
pub enum Anchor {
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
    #[default]
    Center,
    CenterTop,
    CenterBottom,
    CenterLeft,
    CenterRight,
}

impl Bounds {
    pub fn new(x1: usize, y1: usize, x2: usize, y2: usize) -> Self {
        Bounds { x1, y1, x2, y2 }
    }

    pub fn validate(&self) {
        if self.x1 > self.x2 {
            panic!(
                "Validation error: x1 ({}) is greater than x2 ({})",
                self.x1, self.x2
            );
        }
        if self.y1 > self.y2 {
            panic!(
                "Validation error: y1 ({}) is greater than y2 ({})",
                self.y1, self.y2
            );
        }
    }

    pub fn width(&self) -> usize {
        // For inclusive coordinate bounds, width is x2 - x1 + 1
        self.x2.saturating_sub(self.x1).saturating_add(1)
    }

    pub fn height(&self) -> usize {
        // For inclusive coordinate bounds, height is y2 - y1 + 1
        self.y2.saturating_sub(self.y1).saturating_add(1)
    }

    pub fn extend(&mut self, horizontal_amount: usize, vertical_amount: usize, anchor: Anchor) {
        match anchor {
            Anchor::TopLeft => {
                self.x1 = self.x1.saturating_sub(horizontal_amount);
                self.y1 = self.y1.saturating_sub(vertical_amount);
            }
            Anchor::TopRight => {
                self.x2 += horizontal_amount;
                self.y1 = self.y1.saturating_sub(vertical_amount);
            }
            Anchor::BottomLeft => {
                self.x1 = self.x1.saturating_sub(horizontal_amount);
                self.y2 += vertical_amount;
            }
            Anchor::BottomRight => {
                self.x2 += horizontal_amount;
                self.y2 += vertical_amount;
            }
            Anchor::Center => {
                let half_horizontal = horizontal_amount / 2;
                let half_vertical = vertical_amount / 2;
                self.x1 = self.x1.saturating_sub(half_horizontal);
                self.y1 = self.y1.saturating_sub(half_vertical);
                self.x2 += half_horizontal;
                self.y2 += half_vertical;
            }
            Anchor::CenterTop => {
                let half_horizontal = horizontal_amount / 2;
                self.x1 = self.x1.saturating_sub(half_horizontal);
                self.x2 += half_horizontal;
                self.y1 = self.y1.saturating_sub(vertical_amount);
            }
            Anchor::CenterBottom => {
                let half_horizontal = horizontal_amount / 2;
                self.x1 = self.x1.saturating_sub(half_horizontal);
                self.x2 += half_horizontal;
                self.y2 += vertical_amount;
            }
            Anchor::CenterLeft => {
                let half_vertical = vertical_amount / 2;
                self.x1 = self.x1.saturating_sub(horizontal_amount);
                self.y1 = self.y1.saturating_sub(half_vertical);
                self.y2 += half_vertical;
            }
            Anchor::CenterRight => {
                let half_vertical = vertical_amount / 2;
                self.x2 += horizontal_amount;
                self.y1 = self.y1.saturating_sub(half_vertical);
                self.y2 += half_vertical;
            }
        }
        self.validate();
    }

    pub fn contract(&mut self, horizontal_amount: usize, vertical_amount: usize, anchor: Anchor) {
        match anchor {
            Anchor::TopLeft => {
                self.x1 += horizontal_amount;
                self.y1 += vertical_amount;
            }
            Anchor::TopRight => {
                self.x2 = self.x2.saturating_sub(horizontal_amount);
                self.y1 += vertical_amount;
            }
            Anchor::BottomLeft => {
                self.x1 += horizontal_amount;
                self.y2 = self.y2.saturating_sub(vertical_amount);
            }
            Anchor::BottomRight => {
                self.x2 = self.x2.saturating_sub(horizontal_amount);
                self.y2 = self.y2.saturating_sub(vertical_amount);
            }
            Anchor::Center => {
                let half_horizontal = horizontal_amount / 2;
                let half_vertical = vertical_amount / 2;
                self.x1 += half_horizontal;
                self.y1 += half_vertical;
                self.x2 = self.x2.saturating_sub(half_horizontal);
                self.y2 = self.y2.saturating_sub(half_vertical);
            }
            Anchor::CenterTop => {
                let half_horizontal = horizontal_amount / 2;
                self.x1 += half_horizontal;
                self.x2 = self.x2.saturating_sub(half_horizontal);
                self.y1 += vertical_amount;
            }
            Anchor::CenterBottom => {
                let half_horizontal = horizontal_amount / 2;
                self.x1 += half_horizontal;
                self.x2 = self.x2.saturating_sub(half_horizontal);
                self.y2 = self.y2.saturating_sub(vertical_amount);
            }
            Anchor::CenterLeft => {
                let half_vertical = vertical_amount / 2;
                self.x1 += horizontal_amount;
                self.y1 += half_vertical;
                self.y2 = self.y2.saturating_sub(half_vertical);
            }
            Anchor::CenterRight => {
                let half_vertical = vertical_amount / 2;
                self.x2 = self.x2.saturating_sub(horizontal_amount);
                self.y1 += half_vertical;
                self.y2 = self.y2.saturating_sub(half_vertical);
            }
        }
        self.validate();
    }

    pub fn move_to(&mut self, x: usize, y: usize, anchor: Anchor) {
        match anchor {
            Anchor::TopLeft => {
                let width = self.width();
                let height = self.height();
                self.x1 = x;
                self.y1 = y;
                self.x2 = x + width - 1; // Inclusive bounds
                self.y2 = y + height - 1; // Inclusive bounds
            }
            Anchor::TopRight => {
                let width = self.width();
                let height = self.height();
                self.x2 = x;
                self.y1 = y;
                self.x1 = x - width + 1; // Inclusive bounds
                self.y2 = y + height - 1; // Inclusive bounds
            }
            Anchor::BottomLeft => {
                let width = self.width();
                let height = self.height();
                self.x1 = x;
                self.y2 = y;
                self.x2 = x + width - 1; // Inclusive bounds
                self.y1 = y - height + 1; // Inclusive bounds
            }
            Anchor::BottomRight => {
                let width = self.width();
                let height = self.height();
                self.x2 = x;
                self.y2 = y;
                self.x1 = x - width + 1; // Inclusive bounds
                self.y1 = y - height + 1; // Inclusive bounds
            }
            Anchor::Center => {
                let width = self.width();
                let height = self.height();
                let half_width = width / 2;
                let half_height = height / 2;
                self.x1 = x - half_width;
                self.y1 = y - half_height;
                self.x2 = x + width - half_width - 1; // Inclusive bounds
                self.y2 = y + height - half_height - 1; // Inclusive bounds
            }
            Anchor::CenterTop => {
                let width = self.width();
                let height = self.height();
                let half_width = width / 2;
                self.x1 = x - half_width;
                self.x2 = x + width - half_width - 1; // Inclusive bounds
                self.y1 = y;
                self.y2 = y + height - 1; // Inclusive bounds
            }
            Anchor::CenterBottom => {
                let width = self.width();
                let height = self.height();
                let half_width = width / 2;
                self.x1 = x - half_width;
                self.x2 = x + width - half_width - 1; // Inclusive bounds
                self.y2 = y;
                self.y1 = y - height + 1; // Inclusive bounds
            }
            Anchor::CenterLeft => {
                let width = self.width();
                let height = self.height();
                let half_height = height / 2;
                self.x1 = x;
                self.x2 = x + width - 1; // Inclusive bounds
                self.y1 = y - half_height;
                self.y2 = y + height - half_height - 1; // Inclusive bounds
            }
            Anchor::CenterRight => {
                let width = self.width();
                let height = self.height();
                let half_height = height / 2;
                self.x2 = x;
                self.x1 = x - width + 1; // Inclusive bounds
                self.y1 = y - half_height;
                self.y2 = y + height - half_height - 1; // Inclusive bounds
            }
        }
        self.validate();
    }

    pub fn move_by(&mut self, dx: isize, dy: isize) {
        self.x1 = (self.x1 as isize + dx) as usize;
        self.y1 = (self.y1 as isize + dy) as usize;
        self.x2 = (self.x2 as isize + dx) as usize;
        self.y2 = (self.y2 as isize + dy) as usize;
        self.validate();
    }

    pub fn contains(&self, x: usize, y: usize) -> bool {
        x >= self.x1 && x < self.x2 && y >= self.y1 && y < self.y2
    }

    pub fn contains_bounds(&self, other: &Bounds) -> bool {
        self.contains(other.x1, other.y1) && self.contains(other.x2, other.y2)
    }

    pub fn intersects(&self, other: &Bounds) -> bool {
        self.contains(other.x1, other.y1)
            || self.contains(other.x2, other.y2)
            || self.contains(other.x1, other.y2)
            || self.contains(other.x2, other.y1)
    }

    pub fn intersection(&self, other: &Bounds) -> Option<Bounds> {
        if self.intersects(other) {
            Some(Bounds {
                x1: self.x1.max(other.x1),
                y1: self.y1.max(other.y1),
                x2: self.x2.min(other.x2),
                y2: self.y2.min(other.y2),
            })
        } else {
            None
        }
    }

    pub fn union(&self, other: &Bounds) -> Bounds {
        Bounds {
            x1: self.x1.min(other.x1),
            y1: self.y1.min(other.y1),
            x2: self.x2.max(other.x2),
            y2: self.y2.max(other.y2),
        }
    }

    pub fn translate(&self, dx: isize, dy: isize) -> Bounds {
        Bounds {
            x1: (self.x1 as isize + dx) as usize,
            y1: (self.y1 as isize + dy) as usize,
            x2: (self.x2 as isize + dx) as usize,
            y2: (self.y2 as isize + dy) as usize,
        }
    }

    pub fn center(&self) -> (usize, usize) {
        ((self.x1 + self.x2) / 2, (self.y1 + self.y2) / 2)
    }

    pub fn center_x(&self) -> usize {
        (self.x1 + self.x2) / 2
    }

    pub fn center_y(&self) -> usize {
        (self.y1 + self.y2) / 2
    }

    pub fn top_left(&self) -> (usize, usize) {
        (self.x1, self.y1)
    }

    pub fn top_right(&self) -> (usize, usize) {
        (self.x2, self.y1)
    }

    pub fn bottom_left(&self) -> (usize, usize) {
        (self.x1, self.y2)
    }

    pub fn bottom_right(&self) -> (usize, usize) {
        (self.x2, self.y2)
    }

    pub fn top(&self) -> usize {
        self.y1
    }

    pub fn bottom(&self) -> usize {
        self.y2
    }

    pub fn left(&self) -> usize {
        self.x1
    }

    pub fn right(&self) -> usize {
        self.x2
    }

    pub fn center_top(&self) -> (usize, usize) {
        ((self.x1 + self.x2) / 2, self.y1)
    }

    pub fn center_bottom(&self) -> (usize, usize) {
        ((self.x1 + self.x2) / 2, self.y2)
    }

    pub fn center_left(&self) -> (usize, usize) {
        (self.x1, (self.y1 + self.y2) / 2)
    }

    pub fn center_right(&self) -> (usize, usize) {
        (self.x2, (self.y1 + self.y2) / 2)
    }

    /// Check if a point (x, y) is contained within these bounds (inclusive)
    pub fn contains_point(&self, x: usize, y: usize) -> bool {
        x >= self.x1 && x <= self.x2 && y >= self.y1 && y <= self.y2
    }
}

impl std::fmt::Display for Bounds {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}, {}), ({}, {})", self.x1, self.y1, self.x2, self.y2)
    }
}

pub fn calculate_initial_bounds(app_graph: &AppGraph, layout: &Layout) -> HashMap<String, Bounds> {
    let mut bounds_map = HashMap::new();

    fn dfs(
        _app_graph: &AppGraph,
        _layout_id: &str,
        muxbox: &MuxBox,
        parent_bounds: Bounds,
        bounds_map: &mut HashMap<String, Bounds>,
    ) {
        let bounds = muxbox.absolute_bounds(Some(&parent_bounds));
        bounds_map.insert(muxbox.id.clone(), bounds.clone());

        if let Some(children) = &muxbox.children {
            for child in children {
                dfs(_app_graph, _layout_id, child, bounds.clone(), bounds_map);
            }
        }
    }

    let root_bounds = screen_bounds();
    if let Some(children) = &layout.children {
        for muxbox in children {
            dfs(
                app_graph,
                &layout.id,
                muxbox,
                root_bounds.clone(),
                &mut bounds_map,
            );
        }
    }

    bounds_map
}

pub fn adjust_bounds_with_constraints(
    layout: &Layout,
    mut bounds_map: HashMap<String, Bounds>,
) -> HashMap<String, Bounds> {
    fn apply_constraints(muxbox: &MuxBox, bounds: &mut Bounds) {
        if let Some(min_width) = muxbox.min_width {
            if bounds.width() < min_width {
                bounds.extend(min_width - bounds.width(), 0, muxbox.anchor.clone());
            }
        }
        if let Some(min_height) = muxbox.min_height {
            if bounds.height() < min_height {
                bounds.extend(0, min_height - bounds.height(), muxbox.anchor.clone());
            }
        }
        if let Some(max_width) = muxbox.max_width {
            if bounds.width() > max_width {
                bounds.contract(bounds.width() - max_width, 0, muxbox.anchor.clone());
            }
        }
        if let Some(max_height) = muxbox.max_height {
            if bounds.height() > max_height {
                bounds.contract(0, bounds.height() - max_height, muxbox.anchor.clone());
            }
        }
    }

    fn dfs(muxbox: &MuxBox, bounds_map: &mut HashMap<String, Bounds>) -> Bounds {
        let mut bounds = bounds_map.remove(&muxbox.id).unwrap();
        apply_constraints(muxbox, &mut bounds);
        bounds_map.insert(muxbox.id.clone(), bounds.clone());

        if let Some(children) = &muxbox.children {
            for child in children {
                let child_bounds = dfs(child, bounds_map);
                bounds.x2 = bounds.x2.max(child_bounds.x2);
                bounds.y2 = bounds.y2.max(child_bounds.y2);
            }
        }

        bounds
    }

    fn revalidate_children(
        muxbox: &MuxBox,
        bounds_map: &mut HashMap<String, Bounds>,
        parent_bounds: &Bounds,
    ) {
        if let Some(children) = &muxbox.children {
            for child in children {
                if let Some(child_bounds) = bounds_map.get_mut(&child.id) {
                    // Ensure child bounds are within parent bounds
                    if child_bounds.x2 > parent_bounds.x2 {
                        child_bounds.x2 = parent_bounds.x2;
                    }
                    if child_bounds.y2 > parent_bounds.y2 {
                        child_bounds.y2 = parent_bounds.y2;
                    }
                    if child_bounds.x1 < parent_bounds.x1 {
                        child_bounds.x1 = parent_bounds.x1;
                    }
                    if child_bounds.y1 < parent_bounds.y1 {
                        child_bounds.y1 = parent_bounds.y1;
                    }
                }
                revalidate_children(child, bounds_map, parent_bounds);
            }
        }
    }

    if let Some(children) = &layout.children {
        for muxbox in children {
            let parent_bounds = dfs(muxbox, &mut bounds_map);
            revalidate_children(muxbox, &mut bounds_map, &parent_bounds);
        }
    }

    bounds_map
}

pub fn calculate_bounds_map(app_graph: &AppGraph, layout: &Layout) -> HashMap<String, Bounds> {
    let bounds_map = calculate_initial_bounds(app_graph, layout);
    adjust_bounds_with_constraints(layout, bounds_map)
}

/// Flexible deserializer for script fields that handles:
/// - Single string (split on newlines)
/// - Array of strings
/// - Mixed array with YAML literal blocks
pub fn deserialize_script<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum ScriptFormat {
        Single(String),
        Multiple(Vec<String>),
        Mixed(Vec<serde_yaml::Value>),
    }

    let script_format = Option::<ScriptFormat>::deserialize(deserializer)?;

    match script_format {
        None => Ok(None),
        Some(ScriptFormat::Single(single)) => {
            // Split single string on newlines, filter empty lines
            let commands: Vec<String> = single
                .lines()
                .map(|line| line.trim().to_string())
                .filter(|line| !line.is_empty())
                .collect();
            Ok(Some(commands))
        }
        Some(ScriptFormat::Multiple(multiple)) => Ok(Some(multiple)),
        Some(ScriptFormat::Mixed(mixed)) => {
            // Handle mixed array with literal blocks and simple strings
            let mut commands = Vec::new();
            for value in mixed {
                match value {
                    serde_yaml::Value::String(s) => commands.push(s),
                    serde_yaml::Value::Mapping(_) | serde_yaml::Value::Sequence(_) => {
                        // Convert complex YAML structures to string representation
                        if let Ok(yaml_str) = serde_yaml::to_string(&value) {
                            // For literal blocks, extract the actual content
                            let clean_str = yaml_str.trim_start_matches("---\n").trim().to_string();
                            if !clean_str.is_empty() {
                                commands.push(clean_str);
                            }
                        }
                    }
                    _ => {
                        // For other types, convert to string
                        commands.push(format!("{:?}", value));
                    }
                }
            }
            Ok(Some(commands))
        }
    }
}

use std::io::{Read, Write};
use std::os::unix::net::UnixStream;

pub fn send_json_to_socket(socket_path: &str, json: &str) -> Result<String, Box<dyn Error>> {
    let mut stream = UnixStream::connect(socket_path)?;
    stream.write_all(json.as_bytes())?;
    let mut response = String::new();
    stream.read_to_string(&mut response)?;
    Ok(response)
}

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

    // === Config Tests ===

    /// Tests that Config::new() creates a valid configuration with the specified frame delay.
    /// This test demonstrates how to create a Config with proper validation.
    #[test]
    fn test_config_new_valid_frame_delay() {
        let config = Config::new(60);
        assert_eq!(config.frame_delay, 60);
    }

    /// Tests that Config::new() panics when frame_delay is zero.
    /// This test demonstrates Config validation for invalid frame delays.
    #[test]
    #[should_panic(expected = "Validation error: frame_delay cannot be 0")]
    fn test_config_new_zero_frame_delay_panics() {
        Config::new(0);
    }

    /// Tests that Config::default() creates a configuration with default values.
    /// This test demonstrates the default configuration settings.
    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert_eq!(config.frame_delay, 30);
    }

    /// Tests that Config::validate() correctly identifies invalid configurations.
    /// This test demonstrates Config validation behavior.
    #[test]
    #[should_panic(expected = "Validation error: frame_delay cannot be 0")]
    fn test_config_validate_zero_frame_delay() {
        let config = Config {
            frame_delay: 0,
            locked: false,
            calibrate: false,
        };
        config.validate();
    }

    /// Tests that Config::validate() passes for valid configurations.
    /// This test demonstrates successful Config validation.
    #[test]
    fn test_config_validate_valid() {
        let config = Config {
            frame_delay: 16,
            locked: false,
            calibrate: false,
        };
        config.validate(); // Should not panic
    }

    /// Tests that Config implements Hash consistently.
    /// This test demonstrates that Configs with the same values hash to the same value.
    #[test]
    fn test_config_hash_consistency() {
        let config1 = Config::new(30);
        let config2 = Config::new(30);
        let config3 = Config::new(60);

        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher1 = DefaultHasher::new();
        let mut hasher2 = DefaultHasher::new();
        let mut hasher3 = DefaultHasher::new();

        config1.hash(&mut hasher1);
        config2.hash(&mut hasher2);
        config3.hash(&mut hasher3);

        assert_eq!(hasher1.finish(), hasher2.finish());
        assert_ne!(hasher1.finish(), hasher3.finish());
    }

    // === Bounds Tests ===

    /// Tests that Bounds::new() creates bounds with correct coordinates.
    /// This test demonstrates basic Bounds construction.
    #[test]
    fn test_bounds_new() {
        let bounds = Bounds::new(10, 20, 100, 200);
        assert_eq!(bounds.x1, 10);
        assert_eq!(bounds.y1, 20);
        assert_eq!(bounds.x2, 100);
        assert_eq!(bounds.y2, 200);
    }

    /// Tests that Bounds::validate() panics for invalid x coordinates.
    /// This test demonstrates Bounds validation for x-coordinate ordering.
    #[test]
    #[should_panic(expected = "Validation error: x1 (100) is greater than x2 (50)")]
    fn test_bounds_validate_invalid_x_coordinates() {
        let bounds = Bounds::new(100, 20, 50, 200);
        bounds.validate();
    }

    /// Tests that Bounds::validate() panics for invalid y coordinates.
    /// This test demonstrates Bounds validation for y-coordinate ordering.
    #[test]
    #[should_panic(expected = "Validation error: y1 (200) is greater than y2 (100)")]
    fn test_bounds_validate_invalid_y_coordinates() {
        let bounds = Bounds::new(10, 200, 100, 100);
        bounds.validate();
    }

    /// Tests that Bounds::validate() passes for valid bounds.
    /// This test demonstrates successful Bounds validation.
    #[test]
    fn test_bounds_validate_valid() {
        let bounds = Bounds::new(10, 20, 100, 200);
        bounds.validate(); // Should not panic
    }

    /// Tests that Bounds::width() calculates width correctly.
    /// This test demonstrates the width calculation feature.
    #[test]
    fn test_bounds_width() {
        let bounds = Bounds::new(10, 20, 100, 200);
        assert_eq!(bounds.width(), 91); // Inclusive bounds: 100-10+1 = 91
    }

    /// Tests that Bounds::height() calculates height correctly.
    /// This test demonstrates the height calculation feature.
    #[test]
    fn test_bounds_height() {
        let bounds = Bounds::new(10, 20, 100, 200);
        assert_eq!(bounds.height(), 181); // Inclusive bounds: 200-20+1 = 181
    }

    /// Tests that Bounds::width() handles edge case where x1 equals x2.
    /// This test demonstrates edge case handling in width calculation.
    #[test]
    fn test_bounds_width_zero() {
        let bounds = Bounds::new(50, 20, 50, 200);
        assert_eq!(bounds.width(), 1); // Inclusive bounds: 50-50+1 = 1
    }

    /// Tests that Bounds::height() handles edge case where y1 equals y2.
    /// This test demonstrates edge case handling in height calculation.
    #[test]
    fn test_bounds_height_zero() {
        let bounds = Bounds::new(10, 50, 100, 50);
        assert_eq!(bounds.height(), 1); // Inclusive bounds: 50-50+1 = 1
    }

    /// Tests that Bounds::contains() correctly identifies points within bounds.
    /// This test demonstrates the point containment feature.
    #[test]
    fn test_bounds_contains() {
        let bounds = Bounds::new(10, 20, 100, 200);
        assert!(bounds.contains(50, 100));
        assert!(bounds.contains(10, 20)); // Edge case: top-left corner
        assert!(!bounds.contains(100, 200)); // Edge case: bottom-right corner (exclusive)
        assert!(!bounds.contains(5, 100)); // Outside left
        assert!(!bounds.contains(150, 100)); // Outside right
        assert!(!bounds.contains(50, 10)); // Outside top
        assert!(!bounds.contains(50, 250)); // Outside bottom
    }

    /// Tests that Bounds::contains_bounds() correctly identifies bounds containment.
    /// This test demonstrates the bounds containment feature.
    #[test]
    fn test_bounds_contains_bounds() {
        let outer = Bounds::new(10, 20, 100, 200);
        let inner = Bounds::new(30, 40, 80, 180);
        let overlapping = Bounds::new(5, 15, 50, 100);

        assert!(outer.contains_bounds(&inner));
        assert!(!outer.contains_bounds(&overlapping));
    }

    /// Tests that Bounds::intersects() correctly identifies intersecting bounds.
    /// This test demonstrates the bounds intersection detection feature.
    #[test]
    fn test_bounds_intersects() {
        let bounds1 = Bounds::new(10, 20, 100, 200);
        let bounds2 = Bounds::new(50, 100, 150, 250); // Overlapping
        let bounds3 = Bounds::new(200, 300, 250, 350); // Non-overlapping

        assert!(bounds1.intersects(&bounds2));
        assert!(!bounds1.intersects(&bounds3));
    }

    /// Tests that Bounds::intersection() returns correct intersection bounds.
    /// This test demonstrates the bounds intersection calculation feature.
    #[test]
    fn test_bounds_intersection() {
        let bounds1 = Bounds::new(10, 20, 100, 200);
        let bounds2 = Bounds::new(50, 100, 150, 250);
        let bounds3 = Bounds::new(200, 300, 250, 350);

        let intersection = bounds1.intersection(&bounds2);
        assert!(intersection.is_some());
        let intersection = intersection.unwrap();
        assert_eq!(intersection.x1, 50);
        assert_eq!(intersection.y1, 100);
        assert_eq!(intersection.x2, 100);
        assert_eq!(intersection.y2, 200);

        assert!(bounds1.intersection(&bounds3).is_none());
    }

    /// Tests that Bounds::union() returns correct union bounds.
    /// This test demonstrates the bounds union calculation feature.
    #[test]
    fn test_bounds_union() {
        let bounds1 = Bounds::new(10, 20, 100, 200);
        let bounds2 = Bounds::new(50, 100, 150, 250);

        let union = bounds1.union(&bounds2);
        assert_eq!(union.x1, 10);
        assert_eq!(union.y1, 20);
        assert_eq!(union.x2, 150);
        assert_eq!(union.y2, 250);
    }

    /// Tests that Bounds::translate() correctly translates bounds.
    /// This test demonstrates the bounds translation feature.
    #[test]
    fn test_bounds_translate() {
        let bounds = Bounds::new(10, 20, 100, 200);
        let translated = bounds.translate(5, -10);
        assert_eq!(translated.x1, 15);
        assert_eq!(translated.y1, 10);
        assert_eq!(translated.x2, 105);
        assert_eq!(translated.y2, 190);
    }

    /// Tests that Bounds::center() returns correct center point.
    /// This test demonstrates the center calculation feature.
    #[test]
    fn test_bounds_center() {
        let bounds = Bounds::new(10, 20, 100, 200);
        let center = bounds.center();
        assert_eq!(center, (55, 110));
    }

    /// Tests that Bounds::center_x() returns correct x center.
    /// This test demonstrates the x-center calculation feature.
    #[test]
    fn test_bounds_center_x() {
        let bounds = Bounds::new(10, 20, 100, 200);
        assert_eq!(bounds.center_x(), 55);
    }

    /// Tests that Bounds::center_y() returns correct y center.
    /// This test demonstrates the y-center calculation feature.
    #[test]
    fn test_bounds_center_y() {
        let bounds = Bounds::new(10, 20, 100, 200);
        assert_eq!(bounds.center_y(), 110);
    }

    /// Tests that Bounds::extend() correctly extends bounds in all directions.
    /// This test demonstrates the bounds extension feature with Center anchor.
    #[test]
    fn test_bounds_extend_center() {
        let mut bounds = Bounds::new(50, 50, 100, 100);
        bounds.extend(20, 10, Anchor::Center);
        assert_eq!(bounds.x1, 40);
        assert_eq!(bounds.y1, 45);
        assert_eq!(bounds.x2, 110);
        assert_eq!(bounds.y2, 105);
    }

    /// Tests that Bounds::extend() correctly extends bounds with TopLeft anchor.
    /// This test demonstrates the bounds extension feature with TopLeft anchor.
    #[test]
    fn test_bounds_extend_top_left() {
        let mut bounds = Bounds::new(50, 50, 100, 100);
        bounds.extend(20, 10, Anchor::TopLeft);
        assert_eq!(bounds.x1, 30);
        assert_eq!(bounds.y1, 40);
        assert_eq!(bounds.x2, 100);
        assert_eq!(bounds.y2, 100);
    }

    /// Tests that Bounds::contract() correctly contracts bounds.
    /// This test demonstrates the bounds contraction feature.
    #[test]
    fn test_bounds_contract_center() {
        let mut bounds = Bounds::new(50, 50, 100, 100);
        bounds.contract(10, 20, Anchor::Center);
        assert_eq!(bounds.x1, 55);
        assert_eq!(bounds.y1, 60);
        assert_eq!(bounds.x2, 95);
        assert_eq!(bounds.y2, 90);
    }

    /// Tests that Bounds::move_to() correctly moves bounds to new position.
    /// This test demonstrates the bounds movement feature.
    #[test]
    fn test_bounds_move_to() {
        let mut bounds = Bounds::new(10, 20, 60, 70);
        bounds.move_to(100, 150, Anchor::TopLeft);
        assert_eq!(bounds.x1, 100);
        assert_eq!(bounds.y1, 150);
        assert_eq!(bounds.x2, 150);
        assert_eq!(bounds.y2, 200);
    }

    /// Tests that Bounds::move_by() correctly moves bounds by offset.
    /// This test demonstrates the bounds offset movement feature.
    #[test]
    fn test_bounds_move_by() {
        let mut bounds = Bounds::new(10, 20, 60, 70);
        bounds.move_by(5, -10);
        assert_eq!(bounds.x1, 15);
        assert_eq!(bounds.y1, 10);
        assert_eq!(bounds.x2, 65);
        assert_eq!(bounds.y2, 60);
    }

    /// Tests various anchor point getters.
    /// This test demonstrates the anchor point calculation features.
    #[test]
    fn test_bounds_anchor_points() {
        let bounds = Bounds::new(10, 20, 100, 200);

        assert_eq!(bounds.top_left(), (10, 20));
        assert_eq!(bounds.top_right(), (100, 20));
        assert_eq!(bounds.bottom_left(), (10, 200));
        assert_eq!(bounds.bottom_right(), (100, 200));
        assert_eq!(bounds.center_top(), (55, 20));
        assert_eq!(bounds.center_bottom(), (55, 200));
        assert_eq!(bounds.center_left(), (10, 110));
        assert_eq!(bounds.center_right(), (100, 110));
        assert_eq!(bounds.top(), 20);
        assert_eq!(bounds.bottom(), 200);
        assert_eq!(bounds.left(), 10);
        assert_eq!(bounds.right(), 100);
    }

    /// Tests that Bounds::to_string() formats bounds correctly.
    /// This test demonstrates the bounds string formatting feature.
    #[test]
    fn test_bounds_to_string() {
        let bounds = Bounds::new(10, 20, 100, 200);
        assert_eq!(bounds.to_string(), "(10, 20), (100, 200)");
    }

    // === InputBounds Tests ===

    /// Tests that InputBounds::to_bounds() converts percentage strings to absolute bounds.
    /// This test demonstrates the InputBounds to Bounds conversion feature.
    #[test]
    fn test_input_bounds_to_bounds() {
        let input_bounds = InputBounds {
            x1: "25%".to_string(),
            y1: "50%".to_string(),
            x2: "75%".to_string(),
            y2: "100%".to_string(),
        };
        let parent_bounds = Bounds::new(0, 0, 100, 200);
        let bounds = input_bounds.to_bounds(&parent_bounds);

        assert_eq!(bounds.x1, 25);
        assert_eq!(bounds.y1, 100);
        assert_eq!(bounds.x2, 75); // 75% of (101-1) range = 75
        assert_eq!(bounds.y2, 200); // 100% of (201-1) range = 200
    }

    // === Anchor Tests ===

    /// Tests that Anchor::default() returns Center.
    /// This test demonstrates the default anchor behavior.
    #[test]
    fn test_anchor_default() {
        let anchor = Anchor::default();
        assert_eq!(anchor, Anchor::Center);
    }

    // === ScreenBuffer Tests ===

    /// Tests that ScreenBuffer::new_custom() creates a buffer with specified dimensions.
    /// This test demonstrates how to create a custom-sized screen buffer.
    #[test]
    fn test_screenbuffer_new() {
        let screen_buffer = ScreenBuffer::new_custom(5, 5);
        assert_eq!(screen_buffer.width, 5);
        assert_eq!(screen_buffer.height, 5);
        assert_eq!(screen_buffer.buffer.len(), 5);
        assert_eq!(screen_buffer.buffer[0].len(), 5);
    }

    /// Tests that ScreenBuffer::clear() resets all cells to default values.
    /// This test demonstrates the screen buffer clearing feature.
    #[test]
    fn test_screenbuffer_clear() {
        let mut screen_buffer = ScreenBuffer::new_custom(5, 5);
        let test_cell = Cell {
            fg_color: String::from("red"),
            bg_color: String::from("blue"),
            ch: 'X',
        };
        screen_buffer.update(2, 2, test_cell.clone());
        screen_buffer.clear();
        for row in screen_buffer.buffer.iter() {
            for cell in row.iter() {
                assert_eq!(cell.fg_color, get_fg_color("white"));
                assert_eq!(cell.bg_color, get_bg_color("black"));
                assert_eq!(cell.ch, ' ');
            }
        }
    }

    /// Tests that ScreenBuffer::update() correctly updates a cell.
    /// This test demonstrates the screen buffer cell update feature.
    #[test]
    fn test_screenbuffer_update() {
        let mut screen_buffer = ScreenBuffer::new_custom(5, 5);
        let test_cell = Cell {
            fg_color: String::from("red"),
            bg_color: String::from("blue"),
            ch: 'X',
        };
        screen_buffer.update(2, 2, test_cell.clone());
        assert_eq!(screen_buffer.get(2, 2).unwrap(), &test_cell);
    }

    /// Tests that ScreenBuffer::get() returns correct cell references.
    /// This test demonstrates the screen buffer cell retrieval feature.
    #[test]
    fn test_screenbuffer_get() {
        let screen_buffer = ScreenBuffer::new_custom(5, 5);
        assert!(screen_buffer.get(6, 6).is_none());
        assert!(screen_buffer.get(3, 3).is_some());
    }

    /// Tests that ScreenBuffer::update() ignores out-of-bounds coordinates.
    /// This test demonstrates bounds checking in screen buffer updates.
    #[test]
    fn test_screenbuffer_update_out_of_bounds() {
        let mut screen_buffer = ScreenBuffer::new_custom(5, 5);
        let test_cell = Cell {
            fg_color: String::from("red"),
            bg_color: String::from("blue"),
            ch: 'X',
        };
        screen_buffer.update(10, 10, test_cell); // Should not panic
        assert!(screen_buffer.get(10, 10).is_none());
    }

    /// Tests that ScreenBuffer::resize() correctly resizes the buffer.
    /// This test demonstrates the screen buffer resizing feature.
    #[test]
    fn test_screenbuffer_resize() {
        let mut screen_buffer = ScreenBuffer::new_custom(5, 5);
        screen_buffer.resize(10, 8);
        assert_eq!(screen_buffer.width, 10);
        assert_eq!(screen_buffer.height, 8);
        assert_eq!(screen_buffer.buffer.len(), 8);
        assert_eq!(screen_buffer.buffer[0].len(), 10);
    }

    /// Tests that ScreenBuffer::resize() handles shrinking correctly.
    /// This test demonstrates the screen buffer shrinking feature.
    #[test]
    fn test_screenbuffer_resize_shrink() {
        let mut screen_buffer = ScreenBuffer::new_custom(10, 10);
        screen_buffer.resize(5, 5);
        assert_eq!(screen_buffer.width, 5);
        assert_eq!(screen_buffer.height, 5);
        assert_eq!(screen_buffer.buffer.len(), 5);
        assert_eq!(screen_buffer.buffer[0].len(), 5);
    }

    // === Helper Functions ===

    /// Creates a test app context with a valid layout for testing.
    /// This helper ensures tests have a valid app context with layouts.
    fn create_test_app_context() -> AppContext {
        let current_dir = std::env::current_dir().expect("Failed to get current directory");
        let dashboard_path = current_dir.join("layouts/tests.yaml");
        let app = crate::load_app_from_yaml(dashboard_path.to_str().unwrap())
            .expect("Failed to load app");
        AppContext::new(app, Config::default())
    }

    // === SocketFunction Tests ===

    /// Tests that run_socket_function() correctly handles ReplaceBoxContent.
    /// This test demonstrates socket function message processing.
    #[test]
    fn test_run_socket_function_replace_muxbox_content() {
        let app_context = create_test_app_context();
        let socket_function = SocketFunction::ReplaceBoxContent {
            box_id: "test_muxbox".to_string(),
            success: true,
            content: "Test content".to_string(),
        };

        let result = run_socket_function(socket_function, &app_context);
        assert!(result.is_ok());

        let (_, messages) = result.unwrap();
        assert_eq!(messages.len(), 1);
        match &messages[0] {
            crate::Message::StreamUpdateMessage(stream_update) => {
                assert_eq!(stream_update.stream_id, "socket-test_muxbox");
                assert_eq!(stream_update.content_update, "Test content");
                match &stream_update.source_state {
                    crate::model::common::SourceState::Batch(state) => {
                        assert!(matches!(
                            state.status,
                            crate::model::common::BatchStatus::Completed
                        ));
                    }
                    _ => panic!("Expected Batch source state"),
                }
            }
            _ => panic!("Expected StreamUpdateMessage"),
        }
    }

    /// Tests that run_socket_function() correctly handles SwitchActiveLayout.
    /// This test demonstrates socket function layout switching.
    #[test]
    fn test_run_socket_function_switch_active_layout() {
        let app_context = create_test_app_context();
        let socket_function = SocketFunction::SwitchActiveLayout {
            layout_id: "new_layout".to_string(),
        };

        let result = run_socket_function(socket_function, &app_context);
        assert!(result.is_ok());

        let (_, messages) = result.unwrap();
        assert_eq!(messages.len(), 1);
        match &messages[0] {
            crate::Message::SwitchActiveLayout(layout_id) => {
                assert_eq!(layout_id, "new_layout");
            }
            _ => panic!("Expected SwitchActiveLayout message"),
        }
    }

    // === Cell Tests ===

    /// Tests that Cell implements Clone and PartialEq correctly.
    /// This test demonstrates Cell trait implementations.
    #[test]
    fn test_cell_clone_and_eq() {
        let cell1 = Cell {
            fg_color: "red".to_string(),
            bg_color: "blue".to_string(),
            ch: 'X',
        };
        let cell2 = cell1.clone();
        assert_eq!(cell1, cell2);

        let cell3 = Cell {
            fg_color: "green".to_string(),
            bg_color: "blue".to_string(),
            ch: 'X',
        };
        assert_ne!(cell1, cell3);
    }

    /// Test send_json_to_socket function
    #[test]
    fn test_send_json_to_socket_function() {
        use std::os::unix::net::UnixListener;
        use std::thread;
        use std::time::Duration;

        let socket_path = "/tmp/test_send_json.sock";
        let _ = std::fs::remove_file(socket_path);

        // Start a simple test server
        let server_socket_path = socket_path.to_string();
        let server_handle = thread::spawn(move || {
            match UnixListener::bind(&server_socket_path) {
                Ok(listener) => {
                    // Set a timeout to prevent hanging
                    if let Some(Ok(mut stream)) = listener.incoming().next() {
                        let mut buffer = Vec::new();
                        let mut temp_buffer = [0; 1024];

                        // Read data in chunks to avoid hanging on read_to_string
                        match stream.read(&mut temp_buffer) {
                            Ok(n) => {
                                buffer.extend_from_slice(&temp_buffer[..n]);
                                let _ = stream.write_all(b"Test Response");
                                String::from_utf8_lossy(&buffer).to_string()
                            }
                            Err(_) => String::new(),
                        }
                    } else {
                        String::new()
                    }
                }
                Err(_) => String::new(),
            }
        });

        // Give server time to start
        thread::sleep(Duration::from_millis(100));

        // Test send_json_to_socket
        let test_json = r#"{"test": "message"}"#;
        let result = send_json_to_socket(socket_path, test_json);

        // The test is successful if either:
        // 1. The connection succeeds and we get the expected response
        // 2. The connection fails (which can happen in CI environments)
        match result {
            Ok(response) => {
                assert_eq!(response, "Test Response");

                // Verify server received the correct message
                let received_message = server_handle.join().unwrap();
                assert_eq!(received_message, test_json);
            }
            Err(_) => {
                // Connection failed - this can happen in CI environments
                // The important thing is that the function doesn't panic
                let _ = server_handle.join();
            }
        }

        // Clean up
        let _ = std::fs::remove_file(socket_path);
    }
}

// F0203: Multi-Stream Input Tabs - Tab system data structures (uses StreamType defined above)

// Duplicate StreamSource removed - using new trait-based system above