cargo-e 0.3.2

e is for Example. A command-line tool for running and exploring source, examples, and binaries from Rust projects. It will run the first example, if no options are given.
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
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::env;
use std::io::Read;
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, Sender};
use std::time::SystemTime;
use which::which;

use crate::e_cargocommand_ext::CargoProcessResult;
use crate::e_cargocommand_ext::{CargoCommandExt, CargoDiagnostic, CargoProcessHandle};
use crate::e_eventdispatcher::{
    CallbackResponse, CallbackType, CargoDiagnosticLevel, EventDispatcher, ThreadLocalContext,
};
use crate::e_runner::GLOBAL_CHILDREN;
use crate::e_target::{CargoTarget, TargetKind, TargetOrigin};
use std::sync::{Arc, Mutex};

#[derive(Debug, Clone, PartialEq, Copy)]
pub enum TerminalError {
    NotConnected,
    NoTerminal,
    NoError,
}

impl Default for TerminalError {
    fn default() -> Self {
        TerminalError::NoError
    }
}

/// A builder that constructs a Cargo command for a given target.
#[derive(Clone, Debug)]
pub struct CargoCommandBuilder {
    pub target_name: String,
    pub manifest_path: PathBuf,
    pub args: Vec<String>,
    pub subcommand: String,
    pub pid: Option<u32>,
    pub alternate_cmd: Option<String>,
    pub execution_dir: Option<PathBuf>,
    pub suppressed_flags: HashSet<String>,
    pub stdout_dispatcher: Option<Arc<EventDispatcher>>,
    pub stderr_dispatcher: Option<Arc<EventDispatcher>>,
    pub progress_dispatcher: Option<Arc<EventDispatcher>>,
    pub stage_dispatcher: Option<Arc<EventDispatcher>>,
    pub terminal_error_flag: Arc<Mutex<bool>>,
    pub sender: Option<Arc<Mutex<Sender<TerminalError>>>>,
    pub diagnostics: Arc<Mutex<Vec<CargoDiagnostic>>>,
    pub is_filter: bool,
    pub use_cache: bool,
    pub default_binary_is_runner: bool,
    pub be_silent: bool,
    pub detached: bool,
    pub time_limit: Option<u32>,
    pub detached_hold: Option<u32>,
    pub detached_delay: Option<u32>,
    pub cwd_wsr: bool,
}

impl std::fmt::Display for CargoCommandBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "CargoCommandBuilder {{\n  target_name: {:?},\n  manifest_path: {:?},\n  args: {:?},\n  subcommand: {:?},\n  pid: {:?},\n  alternate_cmd: {:?},\n  execution_dir: {:?},\n  suppressed_flags: {:?},\n  is_filter: {:?}\n,\n  use_cache: {:?}\n}}",
            self.target_name,
            self.manifest_path,
            self.args,
            self.subcommand,
            self.pid,
            self.alternate_cmd,
            self.execution_dir,
            self.suppressed_flags,
            self.is_filter,
            self.use_cache,
        )
    }
}
impl Default for CargoCommandBuilder {
    fn default() -> Self {
        Self::new(
            &String::new(),
            &PathBuf::from("Cargo.toml"),
            "run".into(),
            false,
            false,
            false,
            false,
            false,
            false,
        )
    }
}
impl CargoCommandBuilder {
    /// Creates a new, empty builder.
    pub fn new(
        target_name: &str,
        manifest: &PathBuf,
        subcommand: &str,
        is_filter: bool,
        use_cache: bool,
        default_binary_is_runner: bool,
        be_silent: bool,
        detached: bool,
        cwd_wsr: bool,
    ) -> Self {
        ThreadLocalContext::set_context(target_name, manifest.to_str().unwrap_or_default());
        let (sender, _receiver) = channel::<TerminalError>();
        let sender = Arc::new(Mutex::new(sender));
        let mut builder = CargoCommandBuilder {
            target_name: target_name.to_owned(),
            manifest_path: manifest.clone(),
            args: Vec::new(),
            subcommand: subcommand.to_string(),
            pid: None,
            alternate_cmd: None,
            execution_dir: None,
            suppressed_flags: HashSet::new(),
            stdout_dispatcher: None,
            stderr_dispatcher: None,
            progress_dispatcher: None,
            stage_dispatcher: None,
            terminal_error_flag: Arc::new(Mutex::new(false)),
            sender: Some(sender),
            diagnostics: Arc::new(Mutex::new(Vec::<CargoDiagnostic>::new())),
            is_filter,
            use_cache,
            default_binary_is_runner,
            be_silent,
            detached,
            time_limit: None,
            detached_hold: None,
            detached_delay: None,
            cwd_wsr,
        };
        builder.set_default_dispatchers();
        builder
    }

    // Switch to passthrough mode when the terminal error is detected
    fn switch_to_passthrough_mode<F>(self: Arc<Self>, on_spawn: F) -> anyhow::Result<u32>
    where
        F: FnOnce(u32, Arc<Mutex<CargoProcessHandle>>),
    {
        let mut command = self.build_command();

        // Now, spawn the cargo process in passthrough mode
        let cargo_process_handle = command.spawn_cargo_passthrough(Arc::clone(&self));
        let pid = cargo_process_handle.pid;
        // Notify observer
        let cargo_process_handle = Arc::new(Mutex::new(cargo_process_handle));
        on_spawn(pid, cargo_process_handle);

        Ok(pid)
    }

    // Set up the default dispatchers, which includes error detection
    fn set_default_dispatchers(&mut self) {
        if !self.is_filter {
            // If this is a filter, we don't need to set up dispatchers
            return;
        }
        let sender = self.sender.clone().unwrap();

        let mut stdout_dispatcher = EventDispatcher::new();
        stdout_dispatcher.add_callback(
            r"listening on",
            Box::new(
                |line: &str,
                 _captures: Option<regex::Captures>,
                 _state: std::sync::Arc<std::sync::atomic::AtomicBool>,
                 stats: std::sync::Arc<std::sync::Mutex<crate::e_cargocommand_ext::CargoStats>>,
                 _prior_response: Option<crate::e_eventdispatcher::CallbackResponse>|
                 -> Option<crate::e_eventdispatcher::CallbackResponse> {
                    println!("(STDOUT) Dispatcher caught: {}", line);
                    // Use a regex to capture a URL from the line.
                    // Move the regex construction outside the closure to avoid lifetime issues.
                    static URL_REGEX: once_cell::sync::Lazy<Regex> =
                        once_cell::sync::Lazy::new(|| Regex::new(r"(http://[^\s]+)").unwrap());
                    if let Some(url_caps) = URL_REGEX.captures(line) {
                        if let Some(url_match) = url_caps.get(1) {
                            let url = url_match.as_str();
                            // Call open::that on the captured URL.
                            if let Err(e) = open::that_detached(url) {
                                eprintln!("Failed to open URL: {}. Error: {}", url, e);
                            } else {
                                println!("Opened URL: {}", url);
                            }
                        }
                    }
                    let mut stats = stats.lock().unwrap();
                    // Add debug statements to trace stats changes
                    println!("[DEBUG] Locked stats: {:?}", *stats);
                    if stats.build_finished_time.is_none() {
                        let now = SystemTime::now();
                        stats.build_finished_time = Some(now);
                        // Add debug statements to trace stats changes
                        println!(
                            "[DEBUG] Updated stats.build_finished_time: {:?}",
                            stats.build_finished_time
                        );
                    }
                    None
                },
            )
                as Box<
                    dyn Fn(
                            &str,
                            Option<regex::Captures>,
                            std::sync::Arc<std::sync::atomic::AtomicBool>,
                            std::sync::Arc<std::sync::Mutex<crate::e_cargocommand_ext::CargoStats>>,
                            Option<crate::e_eventdispatcher::CallbackResponse>,
                        )
                            -> Option<crate::e_eventdispatcher::CallbackResponse>
                        + Send
                        + Sync
                        + 'static,
                >,
        );

        stdout_dispatcher.add_callback(
            r"BuildFinished",
            Box::new(move |line, _captures, _state, stats, _prior_response| {
                println!("******* {}", line);
                let mut stats = stats.lock().unwrap();
                // Add debug statements to trace stats changes
                println!("[DEBUG] Locked stats: {:?}", *stats);
                if stats.build_finished_time.is_none() {
                    let now = SystemTime::now();
                    stats.build_finished_time = Some(now);
                    // Add debug statements to trace stats changes
                    println!(
                        "[DEBUG] Updated stats.build_finished_time: {:?}",
                        stats.build_finished_time
                    );
                }
                None
            }),
        );
        stdout_dispatcher.add_callback(
            r"server listening at:",
            Box::new(move |line, _captures, state, stats, _prior_response| {
                // If we're not already in multiline mode, this is the initial match.
                if !state.load(Ordering::Relaxed) {
                    println!("Matched 'server listening at:' in: {}", line);
                    state.store(true, Ordering::Relaxed);
                    Some(CallbackResponse {
                        callback_type: CallbackType::Note, // Choose as appropriate
                        message: Some(format!("Started multiline mode after: {}", line)),
                        file: None,
                        line: None,
                        column: None,
                        suggestion: None,
                        terminal_status: None,
                    })
                } else {
                    // We are in multiline mode; process subsequent lines.
                    println!("Multiline callback received: {}", line);
                    // Use a regex to capture a URL from the line.
                    let url_regex = match Regex::new(r"(http://[^\s]+)") {
                        Ok(regex) => regex,
                        Err(e) => {
                            eprintln!("Failed to create URL regex: {}", e);
                            return None;
                        }
                    };
                    if let Some(url_caps) = url_regex.captures(line) {
                        let url = url_caps.get(1).unwrap().as_str();
                        // Call open::that on the captured URL.
                        match open::that_detached(url) {
                            Ok(_) => println!("Opened URL: {}", url),
                            Err(e) => eprintln!("Failed to open URL: {}. Error: {}", url, e),
                        }
                        let mut stats = stats.lock().unwrap();
                        if stats.build_finished_time.is_none() {
                            let now = SystemTime::now();
                            stats.build_finished_time = Some(now);
                        }
                        // End multiline mode.
                        state.store(false, Ordering::Relaxed);
                        Some(CallbackResponse {
                            callback_type: CallbackType::Note, // Choose as appropriate
                            message: Some(format!("Captured and opened URL: {}", url)),
                            file: None,
                            line: None,
                            column: None,
                            suggestion: None,
                            terminal_status: None,
                        })
                    } else {
                        None
                    }
                }
            }),
        );

        let mut stderr_dispatcher = EventDispatcher::new();

        let suggestion_mode = Arc::new(AtomicBool::new(false));
        let suggestion_regex = Regex::new(r"^\s*(\d+)\s*\|\s*(.*)$").unwrap();
        let warning_location: Arc<Mutex<Option<CallbackResponse>>> = Arc::new(Mutex::new(None));
        let pending_diag: Arc<Mutex<Option<CargoDiagnostic>>> = Arc::new(Mutex::new(None));
        let diagnostic_counts: Arc<Mutex<HashMap<CargoDiagnosticLevel, usize>>> =
            Arc::new(Mutex::new(HashMap::new()));

        let pending_d = Arc::clone(&pending_diag);
        let counts = Arc::clone(&diagnostic_counts);

        let diagnostics_arc = Arc::clone(&self.diagnostics);
        // Callback for Rust panic messages (e.g., "thread 'main' panicked at ...")
        // To avoid lifetime issues, capture only the data needed by value (clone).
        let pid_for_panic = self.pid;
        stderr_dispatcher.add_callback(
            r"^thread '([^']+)' panicked at (.+):(\d+):(\d+):$",
            Box::new(
                move |line, captures, multiline_flag, stats, prior_response| {
                    multiline_flag.store(false, Ordering::Relaxed);

                    if let Some(caps) = captures {
                        multiline_flag.store(true, Ordering::Relaxed); // the next line is the panic message
                        let thread = caps.get(1).map(|m| m.as_str()).unwrap_or("unknown");
                        let message = caps.get(2).map(|m| m.as_str()).unwrap_or("unknown panic");
                        let file = caps.get(3).map(|m| m.as_str()).unwrap_or("unknown file");
                        let line_num = caps
                            .get(4)
                            .map(|m| m.as_str())
                            .unwrap_or("0")
                            .parse()
                            .unwrap_or(0);
                        let col_num = caps
                            .get(5)
                            .map(|m| m.as_str())
                            .unwrap_or("0")
                            .parse()
                            .unwrap_or(0);
                        println!("\n\n\n");
                        println!("{}", line);
                        // Use a global TTS instance via OnceCell for program lifetime

                        #[cfg(feature = "uses_tts")]
                        {
                            let mut say_something = true;
                            if let Some(cli) = crate::GLOBAL_CLI.get() {
                                if cli.no_tts {
                                    say_something = false;
                                }
                            }
                            if say_something {
                                let tts_mutex = crate::GLOBAL_TTS.get_or_init(|| {
                                    std::sync::Mutex::new(
                                        tts::Tts::default().expect("TTS engine failure"),
                                    )
                                });
                                // Extract the filename without extension
                                let filename = Path::new(message)
                                    .file_stem()
                                    .and_then(|s| s.to_str())
                                    .unwrap_or("unknown file");
                                let speech = format!(
                                    "thread {} panic, {} line {}",
                                    thread, filename, line_num
                                );
                                println!("TTS: {}", speech);
                                crate::e_runner::wait_for_tts_to_finish(15000);
                                let mut tts = tts_mutex.lock().expect("Failed to lock TTS mutex");
                                let _ = tts.speak(&speech, false);
                                drop(tts);
                            }
                        }

                        println!(
                            "Panic detected: thread='{}', message='{}', file='{}:{}:{}'",
                            thread, message, file, line_num, col_num
                        );
                        println!("\n\n\n");
                        Some(CallbackResponse {
                            callback_type: CallbackType::Error,
                            message: Some(format!(
                                "thread '{}' panicked at {} ({}:{}:{})",
                                thread, message, file, line_num, col_num
                            )),
                            file: Some(message.to_string()),
                            line: Some(file.parse::<usize>().unwrap_or(0)),
                            column: Some(line_num),
                            suggestion: None,
                            terminal_status: None,
                        })
                    } else {
                        let context = ThreadLocalContext::get_context();
                        let mut show_window = true;
                        let mut say_something = true;
                        if let Some(cli) = crate::GLOBAL_CLI.get() {
                            if cli.no_window {
                                show_window = false;
                            }
                            if cli.no_tts {
                                say_something = false;
                            }
                        }
                        if show_window {
                            show_graphical_panic(
                                line.to_string(),
                                prior_response,
                                PathBuf::from(&context.manifest_path),
                                pid_for_panic.unwrap_or_default(),
                                stats.clone(),
                            );
                            println!("[DEBUG] dispatch stats: {:?}", stats);
                        }
                        #[cfg(feature = "uses_tts")]
                        {
                            if say_something {
                                let tts_mutex = crate::GLOBAL_TTS.get_or_init(|| {
                                    std::sync::Mutex::new(
                                        tts::Tts::default().expect("TTS engine failure"),
                                    )
                                });

                                let speech = format!("panic says {}", line);
                                println!("TTS: {}", speech);
                                crate::e_runner::wait_for_tts_to_finish(15000);
                                let mut tts = tts_mutex.lock().expect("Failed to lock TTS mutex");
                                let _ = tts.speak(&speech, true);
                            }
                        }

                        None
                    }
                },
            ),
        );

        // Add a callback to detect "could not compile" errors
        stderr_dispatcher.add_callback(
            r"error: could not compile `(?P<crate_name>.+)` \((?P<due_to>.+)\) due to (?P<error_count>\d+) previous errors; (?P<warning_count>\d+) warnings emitted",
            Box::new(|line, captures, _state, stats, _prior_response| {
                println!("{}", line);
            if let Some(caps) = captures {
                // Extract dynamic fields from the error message
                let crate_name = caps.name("crate_name").map(|m| m.as_str()).unwrap_or("unknown");
                let due_to = caps.name("due_to").map(|m| m.as_str()).unwrap_or("unknown");
                let error_count: usize = caps
                .name("error_count")
                .map(|m| m.as_str().parse().unwrap_or(0))
                .unwrap_or(0);
                let warning_count: usize = caps
                .name("warning_count")
                .map(|m| m.as_str().parse().unwrap_or(0))
                .unwrap_or(0);

                // Log the captured information (optional)
                println!(
                "Detected compilation failure: crate=`{}`, due_to=`{}`, errors={}, warnings={}",
                crate_name, due_to, error_count, warning_count
                );

                // Set `is_could_not_compile` to true in the stats
                let mut stats = stats.lock().unwrap();
                stats.is_could_not_compile = true;
            }
            None // No callback response needed
            }),
        );

        // Clone diagnostics_arc for this closure to avoid move
        let diagnostics_arc_for_diag = Arc::clone(&diagnostics_arc);
        stderr_dispatcher.add_callback(
            r"^(?P<level>\w+)(\[(?P<error_code>E\d+)\])?:\s+(?P<msg>.+)$", // Regex for diagnostic line
            Box::new(
                move |_line, caps, _multiline_flag, _stats, _prior_response| {
                    if let Some(caps) = caps {
                        let mut counts = counts.lock().unwrap();
                        // Create a PendingDiag and save the message
                        let mut pending_diag = pending_d.lock().unwrap();
                        let mut last_lineref = String::new();
                        if let Some(existing_diag) = pending_diag.take() {
                            let mut diags = diagnostics_arc_for_diag.lock().unwrap();
                            last_lineref = existing_diag.lineref.clone();
                            diags.push(existing_diag.clone());
                        }
                        log::trace!("Diagnostic line: {}", _line);
                        let level = caps["level"].to_string(); // e.g., "warning", "error"
                        let message = caps["msg"].to_string();
                        // If the message contains "generated" followed by one or more digits,
                        // then ignore this diagnostic by returning None.
                        let re_generated = regex::Regex::new(r"generated\s+\d+").unwrap();
                        if re_generated.is_match(&message) {
                            log::trace!("Skipping generated diagnostic: {}", _line);
                            return None;
                        }

                        let error_code = caps.name("error_code").map(|m| m.as_str().to_string());
                        let diag_level = match level.as_str() {
                            "error" => CargoDiagnosticLevel::Error,
                            "warning" => CargoDiagnosticLevel::Warning,
                            "help" => CargoDiagnosticLevel::Help,
                            "note" => CargoDiagnosticLevel::Note,
                            _ => {
                                println!("Unknown diagnostic level: {}", level);
                                return None; // Ignore unknown levels
                            }
                        };
                        // Increment the count for this level
                        *counts.entry(diag_level).or_insert(0) += 1;

                        let current_count = counts.get(&diag_level).unwrap_or(&0);
                        let diag = CargoDiagnostic {
                            error_code: error_code.clone(),
                            lineref: last_lineref.clone(),
                            level: level.clone(),
                            message,
                            suggestion: None,
                            help: None,
                            note: None,
                            uses_color: true,
                            diag_num_padding: Some(2),
                            diag_number: Some(*current_count),
                        };

                        // Save the new diagnostic
                        *pending_diag = Some(diag);

                        // Track the count of diagnostics for each level
                        return Some(CallbackResponse {
                            callback_type: CallbackType::LevelMessage, // Treat subsequent lines as warnings
                            message: None,
                            file: None,
                            line: None,
                            column: None,
                            suggestion: None, // This is the suggestion part
                            terminal_status: None,
                        });
                    } else {
                        println!("No captures found in line: {}", _line);
                        None
                    }
                },
            ),
        );
        // Look-behind buffer for last 6 lines before backtrace
        let look_behind = Arc::new(Mutex::new(Vec::<String>::new()));
        {
            let look_behind = Arc::clone(&look_behind);
            // This callback runs for every stderr line to update the look-behind buffer
            stderr_dispatcher.add_callback(
                r"^(?P<msg>.*)$",
                Box::new(move |line, _captures, _state, _stats, _prior_response| {
                    let mut buf = look_behind.lock().unwrap();
                    if line.trim().is_empty() {
                        return None;
                    }
                    buf.push(line.to_string());
                    if buf.len() > 6 {
                        buf.remove(0);
                    }
                    None
                }),
            );
        }

        // --- Patch: Use look_behind before backtrace_lines in the note ---
        {
            let pending_diag = Arc::clone(&pending_diag);
            let diagnostics_arc = Arc::clone(&diagnostics_arc);
            let backtrace_mode = Arc::new(AtomicBool::new(false));
            let backtrace_lines = Arc::new(Mutex::new(Vec::<String>::new()));
            let look_behind = Arc::clone(&look_behind);
            let stored_lines_behind = Arc::new(Mutex::new(Vec::<String>::new()));

            // Enable backtrace mode when we see "stack backtrace:"
            {
                let backtrace_mode = Arc::clone(&backtrace_mode);
                let backtrace_lines = Arc::clone(&backtrace_lines);
                let stored_lines_behind = Arc::clone(&stored_lines_behind);
                let look_behind = Arc::clone(&look_behind);
                stderr_dispatcher.add_callback(
                    r"stack backtrace:",
                    Box::new(move |_line, _captures, _state, _stats, _prior_response| {
                        backtrace_mode.store(true, Ordering::Relaxed);
                        backtrace_lines.lock().unwrap().clear();
                        // Save the current look_behind buffer into a shared stored_lines_behind for later use
                        {
                            let look_behind_buf = look_behind.lock().unwrap();
                            let mut stored = stored_lines_behind.lock().unwrap();
                            *stored = look_behind_buf.clone();
                        }
                        None
                    }),
                );
            }

            // Process backtrace lines, filter and summarize
            {
                let backtrace_mode = Arc::clone(&backtrace_mode);
                let backtrace_lines = Arc::clone(&backtrace_lines);
                let pending_diag = Arc::clone(&pending_diag);
                let diagnostics_arc = Arc::clone(&diagnostics_arc);

                // Regex for numbered backtrace line: "  0: type::path"
                let re_number_type = Regex::new(r"^\s*(\d+):\s+(.*)$").unwrap();
                // Regex for "at path:line"
                let re_at_path = Regex::new(r"^\s*at\s+([^\s:]+):(\d+)").unwrap();

                stderr_dispatcher.add_callback(
                    r"^(?P<msg>.*)$",
                    Box::new(
                        move |mut line, _captures, _state, _stats, _prior_response| {
                            if backtrace_mode.load(Ordering::Relaxed) {
                                line = line.trim();
                                // End of backtrace if empty line or new diagnostic/note
                                if line.trim().is_empty()
                                    || line.starts_with("note:")
                                    || line.starts_with("error:")
                                {
                                    let mut bt_lines = Vec::new();
                                    let mut skip_next = false;
                                    let mut last_number_type: Option<(String, String)> = None;
                                    for l in backtrace_lines.lock().unwrap().iter() {
                                        if let Some(caps) = re_number_type.captures(l) {
                                            // Save the (number, type) line, but don't push yet
                                            last_number_type =
                                                Some((caps[1].to_string(), caps[2].to_string()));
                                            skip_next = true;
                                        } else if skip_next && re_at_path.is_match(l) {
                                            let path_caps = re_at_path.captures(l).unwrap();
                                            let path = path_caps.get(1).unwrap().as_str();
                                            let line_num = path_caps.get(2).unwrap().as_str();
                                            if path.starts_with("/rustc")
                                                || path.contains(".cargo")
                                                || path.contains(".rustup")
                                            {
                                                // Skip both the number: type and the at line
                                                // (do not push either)
                                            } else {
                                                // Push both the number: type and the at line, on the same line
                                                if let Some((num, typ)) = last_number_type.take() {
                                                    // Canonicalize the path if possible for better readability
                                                    let path = match std::fs::canonicalize(path) {
                                                        Ok(canon) => canon.display().to_string(),
                                                        Err(_) => path.to_string(),
                                                    };

                                                    bt_lines.push(format!(
                                                        "{}: {} @ {}:{}",
                                                        num, typ, path, line_num
                                                    ));
                                                }
                                            }
                                            skip_next = false;
                                        } else if let Some((num, typ)) = last_number_type.take() {
                                            // If the previous number: type was not followed by an at line, push it
                                            bt_lines.push(format!("{}: {}", num, typ));
                                            if !l.trim().is_empty() {
                                                bt_lines.push(l.clone());
                                            }
                                            skip_next = false;
                                        } else if !l.trim().is_empty() {
                                            bt_lines.push(l.clone());
                                            skip_next = false;
                                        }
                                    }
                                    if !bt_lines.is_empty() {
                                        let mut pending_diag = pending_diag.lock().unwrap();
                                        if let Some(ref mut diag) = *pending_diag {
                                            // --- Insert stored_lines_behind lines before backtrace_lines ---
                                            let stored_lines = {
                                                let buf = stored_lines_behind.lock().unwrap();
                                                buf.clone()
                                            };
                                            let note = diag.note.get_or_insert_with(String::new);
                                            if !stored_lines.is_empty() {
                                                note.push_str(&stored_lines.join("\n"));
                                                note.push('\n');
                                            }
                                            note.push_str(&bt_lines.join("\n"));
                                            let mut diags = diagnostics_arc.lock().unwrap();
                                            diags.push(diag.clone());
                                        }
                                    }
                                    backtrace_mode.store(false, Ordering::Relaxed);
                                    backtrace_lines.lock().unwrap().clear();
                                    return None;
                                }

                                // Only keep lines that are part of the backtrace
                                if re_number_type.is_match(line) || re_at_path.is_match(line) {
                                    backtrace_lines.lock().unwrap().push(line.to_string());
                                }
                                // Ignore further lines
                                return None;
                            }
                            None
                        },
                    ),
                );
            }
        }

        // suggestion callback
        {
            let location_lock_clone = Arc::clone(&warning_location);
            let suggestion_m = Arc::clone(&suggestion_mode);

            // Suggestion callback that adds subsequent lines as suggestions
            stderr_dispatcher.add_callback(
                r"^(?P<msg>.*)$", // Capture all lines following the location
                Box::new(
                    move |line, _captures, _multiline_flag, _stats, _prior_response| {
                        if suggestion_m.load(Ordering::Relaxed) {
                            // Only process lines that match the suggestion format
                            if let Some(caps) = suggestion_regex.captures(line.trim()) {
                                // Capture the line number and code from the suggestion line
                                // let line_num = caps[1].parse::<usize>().unwrap_or(0);
                                let code = caps[2].to_string();

                                // Lock the pending_diag to add the suggestion
                                if let Ok(mut lock) = location_lock_clone.lock() {
                                    if let Some(mut loc) = lock.take() {
                                        // let file = loc.file.clone().unwrap_or_default();
                                        // let col = loc.column.unwrap_or(0);

                                        // Concatenate the suggestion line to the message
                                        let mut msg = loc.message.unwrap_or_default();
                                        msg.push_str(&format!("\n{}", code));

                                        // Print the concatenated suggestion for debugging
                                        // println!("daveSuggestion for {}:{}:{} - {}", file, line_num, col, msg);

                                        // Update the location with the new concatenated message
                                        loc.message = Some(msg.clone());
                                        // println!("Updating location lock with new suggestion: {}", msg);
                                        // Save the updated location back to shared state
                                        // if let Ok(mut lock) = location_lock_clone.lock() {
                                        // println!("Updating location lock with new suggestion: {}", msg);
                                        lock.replace(loc);
                                        // } else {
                                        //     eprintln!("Failed to acquire lock for location_lock_clone");
                                        // }
                                    }
                                    // return Some(CallbackResponse {
                                    //     callback_type: CallbackType::Warning, // Treat subsequent lines as warnings
                                    //     message: Some(msg.clone()),
                                    //     file: Some(file),
                                    //     line: Some(line_num),
                                    //     column: Some(col),
                                    //     suggestion: Some(msg),  // This is the suggestion part
                                    //     terminal_status: None,
                                    // });
                                }
                            }
                        } else {
                            // println!("Suggestion mode is not active. Ignoring line: {}", line);
                        }

                        None
                    },
                ),
            );
        }
        {
            let suggestion_m = Arc::clone(&suggestion_mode);
            let pending_diag_clone = Arc::clone(&pending_diag);
            let diagnostics_arc = Arc::clone(&self.diagnostics);
            // Callback for handling when an empty line or new diagnostic is received
            stderr_dispatcher.add_callback(
                r"^\s*$", // Regex to capture empty line
                Box::new(
                    move |_line, _captures, _multiline_flag, _stats, _prior_response| {
                        // println!("Empty line detected: {}", line);
                        suggestion_m.store(false, Ordering::Relaxed);
                        // End of current diagnostic: take and process it.
                        if let Some(pending_diag) = pending_diag_clone.lock().unwrap().take() {
                            //println!("{:?}", pending_diag);
                            // Use diagnostics_arc instead of self.diagnostices
                            let mut diags = diagnostics_arc.lock().unwrap();
                            diags.push(pending_diag.clone());
                        } else {
                            // println!("No pending diagnostic to process.");
                        }
                        // Handle empty line scenario to end the current diagnostic processing
                        // if let Some(pending_diag) = pending_diag_clone.lock().unwrap().take() {
                        //     println!("{:?}", pending_diag);
                        //     let mut diags = self.diagnostics.lock().unwrap();
                        //     diags.push(pending_diag.clone());
                        //                             // let diag = crate::e_eventdispatcher::convert_message_to_diagnostic(msg, &msg_str);
                        //                             // diags.push(diag.clone());
                        //                             // if let Some(ref sd) = stage_disp_clone {
                        //                             //     sd.dispatch(&format!("Stage: Diagnostic occurred at {:?}", now));
                        //                             // }
                        //     // Handle the saved PendingDiag and its CallbackResponse
                        //     // if let Some(callback_response) = pending_diag.callback_response {
                        //     //     println!("End of Diagnostic: {:?}", callback_response);
                        //     // }
                        // } else {
                        //     println!("No pending diagnostic to process.");
                        // }

                        None
                    },
                ),
            );
        }

        // {
        //     let pending_diag = Arc::clone(&pending_diag);
        //     let location_lock = Arc::clone(&warning_location);
        //     let suggestion_m = Arc::clone(&suggestion_mode);

        // let suggestion_regex = Regex::new(r"^\s*(\d+)\s*\|\s*(.*)$").unwrap();

        //     stderr_dispatcher.add_callback(
        //     r"^\s*(\d+)\s*\|\s*(.*)$",  // Match suggestion line format
        //     Box::new(move |line, _captures, _multiline_flag| {
        //         if suggestion_m.load(Ordering::Relaxed) {
        //             // Only process lines that match the suggestion format
        //             if let Some(caps) = suggestion_regex.captures(line.trim()) {
        //                 // Capture the line number and code from the suggestion line
        //                 let line_num = caps[1].parse::<usize>().unwrap_or(0);
        //                 let code = caps[2].to_string();

        //                 // Lock the pending_diag to add the suggestion
        //                 if let Some(mut loc) = location_lock.lock().unwrap().take() {
        //                     println!("Suggestion line: {}", line);
        //                     let file = loc.file.clone().unwrap_or_default();
        //                     let col = loc.column.unwrap_or(0);

        //                     // Concatenate the suggestion line to the message
        //                     let mut msg = loc.message.unwrap_or_default();
        //                     msg.push_str(&format!("\n{} | {}", line_num, code));  // Append the suggestion properly

        //                     // Print the concatenated suggestion for debugging
        //                     println!("Suggestion for {}:{}:{} - {}", file, line_num, col, msg);

        //                     // Update the location with the new concatenated message
        //                     loc.message = Some(msg.clone());

        //                     // Save the updated location back to shared state
        //                     location_lock.lock().unwrap().replace(loc);

        //                     // return Some(CallbackResponse {
        //                     //     callback_type: CallbackType::Warning, // Treat subsequent lines as warnings
        //                     //     message: Some(msg.clone()),
        //                     //     file: Some(file),
        //                     //     line: Some(line_num),
        //                     //     column: Some(col),
        //                     //     suggestion: Some(msg),  // This is the suggestion part
        //                     //     terminal_status: None,
        //                     // });
        //                 } else {
        //                     println!("No location information available for suggestion line: {}", line);
        //                 }
        //             } else {
        //                 println!("Suggestion line does not match expected format: {}", line);
        //             }
        //         } else {
        //             println!("Suggestion mode is not active. Ignoring line: {}", line);
        //         }

        //         None
        //     }),
        // );

        // }

        {
            let location_lock = Arc::clone(&warning_location);
            let pending_diag = Arc::clone(&pending_diag);
            let suggestion_mode = Arc::clone(&suggestion_mode);
            stderr_dispatcher.add_callback(
                r"^(?P<msg>.*)$", // Capture all lines following the location
                Box::new(
                    move |line, _captures, _multiline_flag, _stats, _prior_response| {
                        // Lock the location to fetch the original diagnostic info
                        if let Ok(location_guard) = location_lock.lock() {
                            if let Some(loc) = location_guard.as_ref() {
                                let file = loc.file.clone().unwrap_or_default();
                                let line_num = loc.line.unwrap_or(0);
                                let col = loc.column.unwrap_or(0);
                                // println!("SUGGESTION: Suggestion for {}:{}:{} {}", file, line_num, col, line);

                                // Only treat lines starting with | or numbers as suggestion lines
                                if line.trim().starts_with('|')
                                    || line.trim().starts_with(char::is_numeric)
                                {
                                    // Get the existing suggestion and append the new line
                                    let suggestion = line.trim();

                                    // Print the suggestion for debugging
                                    // println!("Suggestion for {}:{}:{} - {}", file, line_num, col, suggestion);

                                    // Lock the pending_diag and update its callback_response field
                                    let mut pending_diag = match pending_diag.lock() {
                                        Ok(lock) => lock,
                                        Err(e) => {
                                            eprintln!("Failed to acquire lock: {}", e);
                                            return None; // Handle the error appropriately
                                        }
                                    };
                                    if let Some(diag) = pending_diag.take() {
                                        // If a PendingDiag already exists, update the existing callback response with the new suggestion
                                        let mut diag = diag;

                                        // Append the new suggestion to the existing one
                                        if let Some(ref mut existing) = diag.suggestion {
                                            diag.suggestion =
                                                Some(format!("{}\n{}", existing, suggestion));
                                        } else {
                                            diag.suggestion = Some(suggestion.to_string());
                                        }

                                        // Update the shared state with the new PendingDiag
                                        *pending_diag = Some(diag.clone());
                                        return Some(CallbackResponse {
                                            callback_type: CallbackType::Suggestion, // Treat subsequent lines as warnings
                                            message: Some(
                                                diag.clone().suggestion.clone().unwrap().clone(),
                                            ),
                                            file: Some(file),
                                            line: Some(line_num),
                                            column: Some(col),
                                            suggestion: diag.clone().suggestion.clone(), // This is the suggestion part
                                            terminal_status: None,
                                        });
                                    } else {
                                        // println!("No pending diagnostic to process for suggestion line: {}", line);
                                    }
                                } else {
                                    // If the line doesn't match the suggestion format, just return it as is
                                    if line.trim().is_empty() {
                                        // Ignore empty lines
                                        suggestion_mode.store(false, Ordering::Relaxed);
                                        return None;
                                    }
                                }
                            } else {
                                // println!("No location information available for suggestion line: {}", line);
                            }
                        }
                        None
                    },
                ),
            );
        }

        // 2) Location callback stores its response into that shared state
        {
            let pending_diag = Arc::clone(&pending_diag);
            let warning_location = Arc::clone(&warning_location);
            let location_lock = Arc::clone(&warning_location);
            let suggestion_mode = Arc::clone(&suggestion_mode);
            let manifest_path = self.manifest_path.clone();
            stderr_dispatcher.add_callback(
                // r"^\s*-->\s+(?P<file>[^:]+):(?P<line>\d+):(?P<col>\d+)$",
                r"^\s*-->\s+(?P<file>.+?)(?::(?P<line>\d+))?(?::(?P<col>\d+))?\s*$",
                Box::new(
                    move |_line, caps, _multiline_flag, _stats, _prior_response| {
                        log::trace!("Location line: {}", _line);
                        // if multiline_flag.load(Ordering::Relaxed) {
                        if let Some(caps) = caps {
                            let file = caps["file"].to_string();
                            let resolved_path = resolve_file_path(&manifest_path, &file);
                            let file = resolved_path.to_str().unwrap_or_default().to_string();
                            let line = caps["line"].parse::<usize>().unwrap_or(0);
                            let column = caps["col"].parse::<usize>().unwrap_or(0);
                            let resp = CallbackResponse {
                                callback_type: CallbackType::Location,
                                message: format!("{}:{}:{}", file, line, column).into(),
                                file: Some(file.clone()),
                                line: Some(line),
                                column: Some(column),
                                suggestion: None,
                                terminal_status: None,
                            };
                            // Lock the pending_diag and update its callback_response field
                            let mut pending_diag = pending_diag.lock().unwrap();
                            if let Some(diag) = pending_diag.take() {
                                // If a PendingDiag already exists, save the new callback response in the existing PendingDiag
                                let mut diag = diag;
                                diag.lineref = format!("{}:{}:{}", file, line, column); // Update the lineref
                                                                                        // diag.save_callback_response(resp.clone()); // Save the callback response
                                                                                        // Update the shared state with the new PendingDiag
                                *pending_diag = Some(diag);
                            }
                            // Save it for the generic callback to see
                            *warning_location.lock().unwrap() = Some(resp.clone());
                            *location_lock.lock().unwrap() = Some(resp.clone());
                            // Set suggestion mode to true as we've encountered a location line
                            suggestion_mode.store(true, Ordering::Relaxed);
                            return Some(resp.clone());
                        } else {
                            println!("No captures found in line: {}", _line);
                        }
                        // }
                        None
                    },
                ),
            );
        }

        // // 3) Note callback — attach note to pending_diag
        {
            let pending_diag = Arc::clone(&pending_diag);
            stderr_dispatcher.add_callback(
                r"^\s*=\s*note:\s*(?P<msg>.+)$",
                Box::new(move |_line, caps, _state, _stats, _prior_response| {
                    if let Some(caps) = caps {
                        let mut pending_diag = pending_diag.lock().unwrap();
                        if let Some(ref mut resp) = *pending_diag {
                            // Prepare the new note with the blue prefix
                            let new_note = format!("note: {}", caps["msg"].to_string());

                            // Append or set the note
                            if let Some(existing_note) = &resp.note {
                                // If there's already a note, append with newline and the new note
                                resp.note = Some(format!("{}\n{}", existing_note, new_note));
                            } else {
                                // If no existing note, just set the new note
                                resp.note = Some(new_note);
                            }
                        }
                    }
                    None
                }),
            );
        }

        // 4) Help callback — attach help to pending_diag
        {
            let pending_diag = Arc::clone(&pending_diag);
            stderr_dispatcher.add_callback(
                r"^\s*(?:\=|\|)\s*help:\s*(?P<msg>.+)$", // Regex to match both '=' and '|' before help:
                Box::new(move |_line, caps, _state, _stats, _prior_response| {
                    if let Some(caps) = caps {
                        let mut pending_diag = pending_diag.lock().unwrap();
                        if let Some(ref mut resp) = *pending_diag {
                            // Create the new help message with the orange "h:" prefix
                            let new_help =
                                format!("\x1b[38;5;214mhelp: {}\x1b[0m", caps["msg"].to_string());

                            // Append or set the help message
                            if let Some(existing_help) = &resp.help {
                                // If there's already a help message, append with newline
                                resp.help = Some(format!("{}\n{}", existing_help, new_help));
                            } else {
                                // If no existing help message, just set the new one
                                resp.help = Some(new_help);
                            }
                        }
                    }
                    None
                }),
            );
        }

        stderr_dispatcher.add_callback(
    r"(?:\x1b\[[0-9;]*[A-Za-z])*\s*Serving(?:\x1b\[[0-9;]*[A-Za-z])*\s+at\s+(http://[^\s]+)",
    Box::new(|line, captures, _state, stats , _prior_response| {
        if let Some(caps) = captures {
            let url = caps.get(1).unwrap().as_str();
            let url = url.replace("0.0.0.0", "127.0.0.1");
            println!("(STDERR) Captured URL: {}", url);
            match open::that_detached(&url) {
                Ok(_) => println!("(STDERR) Opened URL: {}",&url),
                Err(e) => eprintln!("(STDERR) Failed to open URL: {}. Error: {:?}", url, e),
            }
             let mut stats = stats.lock().unwrap();
             if stats.build_finished_time.is_none() {
              let now = SystemTime::now();
             stats.build_finished_time = Some(now);
             }
            Some(CallbackResponse {
                callback_type: CallbackType::OpenedUrl, // Choose as appropriate
                message: Some(format!("Captured and opened URL: {}", url)),
                file: None,
                line: None,
                column: None,
                suggestion: None,
                terminal_status: None,
            })
        } else {
            println!("(STDERR) No URL captured in line: {}", line);
            None
        }
    }),
);

        let finished_flag = Arc::new(AtomicBool::new(false));

        // 0) Finished‐profile summary callback
        {
            let finished_flag = Arc::clone(&finished_flag);
            stderr_dispatcher.add_callback(
        r"^Finished\s+`(?P<profile>[^`]+)`\s+profile\s+\[(?P<opts>[^\]]+)\]\s+target\(s\)\s+in\s+(?P<dur>[0-9.]+s)$",
        Box::new(move |_line, caps, _multiline_flag, stats, _prior_response | {
            if let Some(caps) = caps {
                finished_flag.store(true, Ordering::Relaxed);
                let profile = &caps["profile"];
                let opts    = &caps["opts"];
                let dur     = &caps["dur"];
                             let mut stats = stats.lock().unwrap();
             if stats.build_finished_time.is_none() {
              let now = SystemTime::now();
             stats.build_finished_time = Some(now);
             }
                Some(CallbackResponse {
                    callback_type: CallbackType::Note,
                    message: Some(format!("Finished `{}` [{}] in {}", profile, opts, dur)),
                    file: None, line: None, column: None, suggestion: None, terminal_status: None,
                })
            } else {
                None
            }
        }),
    );
        }

        let summary_flag = Arc::new(AtomicBool::new(false));
        {
            let summary_flag = Arc::clone(&summary_flag);
            stderr_dispatcher.add_callback(
    r"^(?P<level>warning|error):\s+`(?P<name>[^`]+)`\s+\((?P<otype>lib|bin)\)\s+generated\s+(?P<count>\d+)\s+(?P<kind>warnings|errors).*run\s+`(?P<cmd>[^`]+)`\s+to apply\s+(?P<fixes>\d+)\s+suggestions",
    Box::new(move |_line, caps, multiline_flag, _stats, _prior_response | {
        let summary_flag = Arc::clone(&summary_flag);
        if let Some(caps) = caps {
            summary_flag.store(true, Ordering::Relaxed);
            // Always start fresh
            multiline_flag.store(false, Ordering::Relaxed);

            let level    = &caps["level"];
            let name     = &caps["name"];
            let otype    = &caps["otype"];
            let count: usize = caps["count"].parse().unwrap_or(0);
            let kind     = &caps["kind"];   // "warnings" or "errors"
            let cmd      = caps["cmd"].to_string();
            let fixes: usize = caps["fixes"].parse().unwrap_or(0);

            println!("SUMMARIZATION CALLBACK {}",
                    &format!("{}: `{}` ({}) generated {} {}; run `{}` to apply {} fixes",
                    level, name, otype, count, kind, cmd, fixes));
            Some(CallbackResponse {
                callback_type: CallbackType::Note,  // treat as informational
                message: Some(format!(
                    "{}: `{}` ({}) generated {} {}; run `{}` to apply {} fixes",
                    level, name, otype, count, kind, cmd, fixes
                )),
                file: None,
                line: None,
                column: None,
                suggestion: Some(cmd),
                terminal_status: None,
            })
        } else {
            None
        }
    }),
    );
        }

        // {
        //     let summary_flag = Arc::clone(&summary_flag);
        //     let finished_flag = Arc::clone(&finished_flag);
        //     let warning_location = Arc::clone(&warning_location);
        //     // Warning callback for stdout.
        //     stderr_dispatcher.add_callback(
        //         r"^warning:\s+(?P<msg>.+)$",
        //         Box::new(
        //             move |line: &str, captures: Option<regex::Captures>, multiline_flag: Arc<AtomicBool>| {
        //                             // If summary or finished just matched, skip
        //             if summary_flag.swap(false, Ordering::Relaxed)
        //                 || finished_flag.swap(false, Ordering::Relaxed)
        //             {
        //                 return None;
        //             }

        //         // 2) If this line *matches* the warning regex, handle as a new warning
        //         if let Some(caps) = captures {
        //             let msg = caps.name("msg").unwrap().as_str().to_string();
        //                    // 1) If a location was saved, print file:line:col – msg
        //             // println!("*WARNING detected: {:?}", msg);
        //                 multiline_flag.store(true, Ordering::Relaxed);
        //         if let Some(loc) = warning_location.lock().unwrap().take() {
        //                 let file = loc.file.unwrap_or_default();
        //                 let line_num = loc.line.unwrap_or(0);
        //                 let col  = loc.column.unwrap_or(0);
        //                 println!("{}:{}:{} - {}", file, line_num, col, msg);
        //                 return Some(CallbackResponse {
        //                     callback_type: CallbackType::Warning,
        //                     message: Some(msg.to_string()),
        //                     file: None, line: None, column: None, suggestion: None, terminal_status: None,
        //                 });
        //         }
        //             return Some(CallbackResponse {
        //                 callback_type: CallbackType::Warning,
        //                 message: Some(msg),
        //                 file: None,
        //                 line: None,
        //                 column: None,
        //                 suggestion: None,
        //                 terminal_status: None,
        //             });
        //         }

        //                 // 3) Otherwise, if we’re in multiline mode, treat as continuation
        //         if multiline_flag.load(Ordering::Relaxed) {
        //             let text = line.trim();
        //             if text.is_empty() {
        //                 multiline_flag.store(false, Ordering::Relaxed);
        //                 return None;
        //             }
        //             // println!("   - {:?}", text);
        //             return Some(CallbackResponse {
        //                 callback_type: CallbackType::Warning,
        //                 message: Some(text.to_string()),
        //                 file: None,
        //                 line: None,
        //                 column: None,
        //                 suggestion: None,
        //                 terminal_status: None,
        //             });
        //         }
        //                     None
        //             },
        //         ),
        //     );
        // }

        stderr_dispatcher.add_callback(
            r"IO\(Custom \{ kind: NotConnected",
            Box::new(move |line, _captures, _state, _stats, _prior_response| {
                println!("(STDERR) Terminal error detected: {:?}", &line);
                let result = if line.contains("NotConnected") {
                    TerminalError::NoTerminal
                } else {
                    TerminalError::NoError
                };
                let sender = sender.lock().unwrap();
                sender.send(result).ok();
                Some(CallbackResponse {
                    callback_type: CallbackType::Warning, // Choose as appropriate
                    message: Some(format!("Terminal Error: {}", line)),
                    file: None,
                    line: None,
                    column: None,
                    suggestion: None,
                    terminal_status: None,
                })
            }),
        );
        stderr_dispatcher.add_callback(
            r".*",
            Box::new(|line, _captures, _state, _stats, _prior_response| {
                log::trace!("stdraw[{:?}]", line);
                None // We're just printing, so no callback response is needed.
            }),
        );
        // need to implement autosense/filtering for tool installers; TBD
        // stderr_dispatcher.add_callback(
        //     r"Command 'perl' not found\. Is perl installed\?",
        //     Box::new(|line, _captures, _state, stats| {
        //     println!("cargo e sees a perl issue; maybe a prompt in the future or auto-resolution.");
        //     crate::e_autosense::auto_sense_perl();
        //     None
        //     }),
        // );
        // need to implement autosense/filtering for tool installers; TBD
        // stderr_dispatcher.add_callback(
        //     r"Error configuring OpenSSL build:\s+Command 'perl' not found\. Is perl installed\?",
        //     Box::new(|line, _captures, _state, stats| {
        //     println!("Detected OpenSSL build error due to missing 'perl'. Attempting auto-resolution.");
        //     crate::e_autosense::auto_sense_perl();
        //     None
        //     }),
        // );
        self.stderr_dispatcher = Some(Arc::new(stderr_dispatcher));

        // let mut progress_dispatcher = EventDispatcher::new();
        // progress_dispatcher.add_callback(r"Progress", Box::new(|line, _captures,_state| {
        //     println!("(Progress) {}", line);
        //     None
        // }));
        // self.progress_dispatcher = Some(Arc::new(progress_dispatcher));

        // let mut stage_dispatcher = EventDispatcher::new();
        // stage_dispatcher.add_callback(r"Stage:", Box::new(|line, _captures, _state| {
        //     println!("(Stage) {}", line);
        //     None
        // }));
        // self.stage_dispatcher = Some(Arc::new(stage_dispatcher));
    }

    pub fn run<F>(self: Arc<Self>, on_spawn: F) -> anyhow::Result<u32>
    where
        F: FnOnce(u32, Arc<Mutex<CargoProcessHandle>>),
    {
        if !self.is_filter {
            return self.switch_to_passthrough_mode(on_spawn);
        }

        let mut command = self.build_command();
        let mut cargo_process_handle = command.spawn_cargo_capture(
            self.clone(),
            self.stdout_dispatcher.clone(),
            self.stderr_dispatcher.clone(),
            self.progress_dispatcher.clone(),
            self.stage_dispatcher.clone(),
            None,
        );
        cargo_process_handle.diagnostics = Arc::clone(&self.diagnostics);
        let pid = cargo_process_handle.pid;

        // Wrap the handle in Arc<Mutex<>> for thread-safe sharing
        let cargo_process_handle = Arc::new(Mutex::new(cargo_process_handle));

        // Notify observer
        on_spawn(pid, cargo_process_handle.clone());

        if self.detached {
            let timeout = std::time::Duration::from_secs(self.time_limit.unwrap_or(0) as u64);
            let (tx, rx) = std::sync::mpsc::channel();
            let cargo_process_handle_clone = Arc::clone(&cargo_process_handle);
            let handle = std::thread::spawn(move || {
                let result = cargo_process_handle_clone.lock().unwrap().child.wait();
                let _ = tx.send(result);
            });
            // Wait for the thread to finish to ensure proper cleanup
            let _ = handle.join();

            match rx.recv_timeout(timeout) {
                Ok(result) => {
                    result?;
                }
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                    eprintln!("Timeout reached for process with PID: {}", pid);
                    let _ = cargo_process_handle.lock().unwrap().kill();
                    return Err(anyhow::anyhow!(
                        "Timeout reached for process with PID: {}",
                        pid
                    ));
                }
                Err(e) => {
                    return Err(anyhow::anyhow!("Thread join error: {}", e));
                }
            }
        }

        Ok(pid)
    }

    // pub fn run(self: Arc<Self>) -> anyhow::Result<u32> {
    //     // Build the command using the builder's configuration
    //     let mut command = self.build_command();

    //     // Spawn the cargo process handle
    //     let cargo_process_handle = command.spawn_cargo_capture(
    //         self.stdout_dispatcher.clone(),
    //         self.stderr_dispatcher.clone(),
    //         self.progress_dispatcher.clone(),
    //         self.stage_dispatcher.clone(),
    //         None,
    //     );
    // let pid = cargo_process_handle.pid;
    // let mut global = GLOBAL_CHILDREN.lock().unwrap();
    // global.insert(pid, Arc::new(Mutex::new(cargo_process_handle)));
    //     Ok(pid)
    // }

    pub fn wait(self: Arc<Self>, pid: Option<u32>) -> anyhow::Result<CargoProcessResult> {
        let mut global = GLOBAL_CHILDREN.lock().unwrap();
        if let Some(pid) = pid {
            // Lock the global list of processes and attempt to find the cargo process handle directly by pid
            if let Some(cargo_process_handle) = global.get_mut(&pid) {
                let mut cargo_process_handle = cargo_process_handle.lock().unwrap();

                // Wait for the process to finish and retrieve the result
                // println!("Waiting for process with PID: {}", pid);
                // let result = cargo_process_handle.wait();
                // println!("Process with PID {} finished", pid);
                loop {
                    println!("Waiting for process with PID: {}", pid);

                    // Attempt to wait for the process, but don't block indefinitely
                    let status = cargo_process_handle.child.try_wait()?;

                    // If the status is `Some(status)`, the process has finished
                    if let Some(status) = status {
                        if status.code() == Some(101) {
                            println!("Process with PID {} finished with cargo error", pid);
                        }

                        // Check the terminal error flag and update the result if there is an error
                        if *cargo_process_handle.terminal_error_flag.lock().unwrap()
                            != TerminalError::NoError
                        {
                            let terminal_error =
                                *cargo_process_handle.terminal_error_flag.lock().unwrap();
                            cargo_process_handle.result.terminal_error = Some(terminal_error);
                        }

                        let final_diagnostics = {
                            let diag_lock = self.diagnostics.lock().unwrap();
                            diag_lock.clone()
                        };
                        cargo_process_handle.result.diagnostics = final_diagnostics.clone();
                        cargo_process_handle.result.exit_status = Some(status);
                        cargo_process_handle.result.end_time = Some(SystemTime::now());
                        let stats_clone = {
                            let stats = cargo_process_handle.stats.lock().unwrap();
                            stats.clone()
                        };
                        cargo_process_handle.result.stats = stats_clone;
                        cargo_process_handle.result.elapsed_time = Some(
                            cargo_process_handle
                                .result
                                .end_time
                                .unwrap()
                                .duration_since(cargo_process_handle.result.start_time.unwrap())
                                .unwrap(),
                        );
                        println!(
                            "Process with PID {} finished {:?} {}",
                            pid,
                            status,
                            final_diagnostics.len()
                        );
                        return Ok(cargo_process_handle.result.clone());
                        // return Ok(CargoProcessResult { exit_status: status, ..Default::default() });
                    }

                    // Sleep briefly to yield control back to the system and avoid blocking
                    std::thread::sleep(std::time::Duration::from_secs(1));
                }

                // Return the result
                // match result {
                //     Ok(res) => Ok(res),
                //     Err(e) => Err(anyhow::anyhow!("Failed to wait for cargo process: {}", e).into()),
                // }
            } else {
                Err(anyhow::anyhow!(
                    "Process handle with PID {} not found in GLOBAL_CHILDREN",
                    pid
                )
                .into())
            }
        } else {
            Err(anyhow::anyhow!("No PID provided for waiting on cargo process").into())
        }
    }

    // pub fn run_wait(self: Arc<Self>) -> anyhow::Result<CargoProcessResult> {
    //     // Run the cargo command and get the process handle (non-blocking)
    //     let pid = self.clone().run()?; // adds to global list of processes
    //     let result = self.wait(Some(pid)); // Wait for the process to finish
    //     // Remove the completed process from GLOBAL_CHILDREN
    //     let mut global = GLOBAL_CHILDREN.lock().unwrap();
    //     global.remove(&pid);

    //     result
    // }

    // Runs the cargo command using the builder's configuration.
    // pub fn run(&self) -> anyhow::Result<CargoProcessResult> {
    //     // Build the command using the builder's configuration
    //     let mut command = self.build_command();

    //     // Now use the `spawn_cargo_capture` extension to run the command
    //     let mut cargo_process_handle = command.spawn_cargo_capture(
    //         self.stdout_dispatcher.clone(),
    //         self.stderr_dispatcher.clone(),
    //         self.progress_dispatcher.clone(),
    //         self.stage_dispatcher.clone(),
    //         None,
    //     );

    //     // Wait for the process to finish and retrieve the results
    //     cargo_process_handle.wait().context("Failed to execute cargo process")
    // }

    /// Configure the command based on the target kind.
    pub fn with_target(mut self, target: &CargoTarget) -> Self {
        if !self.be_silent {
            if let Some(origin) = target.origin.clone() {
                println!("\nTarget origin: {:?}", origin);
            } else {
                println!("\nTarget origin is not set");
            }
        }
        match target.kind {
            TargetKind::Unknown | TargetKind::Plugin => {
                return self;
            }
            TargetKind::Bench => {
                // // To run benchmarks, use the "bench" command.
                //  let exe_path = match which("bench") {
                //     Ok(path) => path,
                //     Err(err) => {
                //         eprintln!("Error: 'trunk' not found in PATH: {}", err);
                //         return self;
                //     }
                // };
                // self.alternate_cmd = Some("bench".to_string())
                self.args.push("bench".into());
                self.args.push(target.name.clone());
            }
            TargetKind::Test => {
                self.args.push("test".into());
                // Pass the target's name as a filter to run specific tests.
                self.args.push(target.name.clone());
            }
            TargetKind::UnknownExample
            | TargetKind::UnknownExtendedExample
            | TargetKind::Example
            | TargetKind::ExtendedExample => {
                self.args.push(self.subcommand.clone());
                // Set execution_dir to the parent of the manifest path
                if self.cwd_wsr {
                    self.execution_dir = target.manifest_path.parent().map(|p| p.to_path_buf());
                }
                //self.args.push("--message-format=json".into());
                self.args.push("--example".into());
                self.args.push(target.name.clone());
                // self.args.push("--manifest-path".into());
                // self.args.push(
                //     target
                //         .manifest_path
                //         .clone()
                //         .to_str()
                //         .unwrap_or_default()
                //         .to_owned(),
                // );
                self = self.with_required_features(&target.manifest_path, target);
            }
            TargetKind::UnknownBinary
            | TargetKind::UnknownExtendedBinary
            | TargetKind::Binary
            | TargetKind::ExtendedBinary => {
                // Set execution_dir to the parent of the manifest path
                if self.cwd_wsr {
                    self.execution_dir = target.manifest_path.parent().map(|p| p.to_path_buf());
                }
                self.args.push(self.subcommand.clone());
                self.args.push("--bin".into());
                self.args.push(target.name.clone());
                // self.args.push("--manifest-path".into());
                // self.args.push(
                //     target
                //         .manifest_path
                //         .clone()
                //         .to_str()
                //         .unwrap_or_default()
                //         .to_owned(),
                // );
                self = self.with_required_features(&target.manifest_path, target);
            }
            TargetKind::Manifest => {
                self.suppressed_flags.insert("quiet".to_string());
                self.args.push(self.subcommand.clone());
                self.args.push("--manifest-path".into());
                self.args.push(
                    target
                        .manifest_path
                        .clone()
                        .to_str()
                        .unwrap_or_default()
                        .to_owned(),
                );
            }
            TargetKind::ManifestTauriExample => {
                self.suppressed_flags.insert("quiet".to_string());
                self.args.push(self.subcommand.clone());
                self.args.push("--example".into());
                self.args.push(target.name.clone());
                self.args.push("--manifest-path".into());
                self.args.push(
                    target
                        .manifest_path
                        .clone()
                        .to_str()
                        .unwrap_or_default()
                        .to_owned(),
                );
                self = self.with_required_features(&target.manifest_path, target);
            }
            TargetKind::ScriptScriptisto => {
                let exe_path = match which("scriptisto") {
                    Ok(path) => path,
                    Err(err) => {
                        eprintln!("Error: 'scriptisto' not found in PATH: {}", err);
                        return self;
                    }
                };
                self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
                let candidate_opt = match &target.origin {
                    Some(TargetOrigin::SingleFile(path))
                    | Some(TargetOrigin::DefaultBinary(path)) => Some(path),
                    _ => None,
                };
                if let Some(candidate) = candidate_opt {
                    self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
                    self.args.push(candidate.to_string_lossy().to_string());
                } else {
                    println!("No scriptisto origin found for: {:?}", target);
                }
            }
            TargetKind::ScriptRustScript => {
                let exe_path = match crate::e_installer::ensure_rust_script() {
                    Ok(p) => p,
                    Err(e) => {
                        eprintln!("{}", e);
                        return self;
                    }
                };
                let candidate_opt = match &target.origin {
                    Some(TargetOrigin::SingleFile(path))
                    | Some(TargetOrigin::DefaultBinary(path)) => Some(path),
                    _ => None,
                };
                if let Some(candidate) = candidate_opt {
                    self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
                    if self.is_filter {
                        self.args.push("-c".into()); // ask for cargo output
                    }
                    self.args.push(candidate.to_string_lossy().to_string());
                } else {
                    println!("No rust-script origin found for: {:?}", target);
                }
            }
            TargetKind::ManifestTauri => {
                // Only locate the Cargo.toml if self.manifest_path is empty
                let manifest_path = if self.manifest_path.as_os_str().is_empty() {
                    crate::locate_manifest(true).unwrap_or_else(|_| {
                        eprintln!("Error: Unable to locate Cargo.toml file.");
                        std::process::exit(1);
                    })
                } else {
                    self.manifest_path.clone().display().to_string()
                };

                // Now, get the workspace parent from the manifest directory
                let manifest_dir = Path::new(&manifest_path)
                    .parent()
                    .unwrap_or(Path::new(".."));

                // Ensure npm dependencies are handled at the workspace parent level
                let pnpm = crate::e_installer::check_pnpm_and_install(manifest_dir, self.be_silent)
                    .unwrap_or_else(|_| {
                        eprintln!("Error: Unable to check pnpm dependencies.");
                        PathBuf::new()
                    });
                if pnpm == PathBuf::new() {
                    crate::e_installer::check_npm_and_install(manifest_dir, self.be_silent)
                        .unwrap_or_else(|_| {
                            eprintln!("Error: Unable to check npm dependencies.");
                        });
                }

                self.suppressed_flags.insert("quiet".to_string());
                // Helper closure to check for tauri.conf.json in a directory.
                let has_tauri_conf = |dir: &Path| -> bool { dir.join("tauri.conf.json").exists() };

                // Helper closure to check for tauri.conf.json and package.json in a directory.
                let has_file = |dir: &Path, filename: &str| -> bool { dir.join(filename).exists() };
                // Try candidate's parent (if origin is SingleFile or DefaultBinary).
                let candidate_dir_opt = match &target.origin {
                    Some(TargetOrigin::SingleFile(path))
                    | Some(TargetOrigin::DefaultBinary(path)) => path.parent(),
                    _ => None,
                };

                if let Some(candidate_dir) = candidate_dir_opt {
                    if has_tauri_conf(candidate_dir) {
                        if !self.be_silent {
                            println!("Using candidate directory: {}", candidate_dir.display());
                        }
                        self.execution_dir = Some(candidate_dir.to_path_buf());
                    } else if let Some(manifest_parent) = target.manifest_path.parent() {
                        if has_tauri_conf(manifest_parent) {
                            if !self.be_silent {
                                println!("Using manifest parent: {}", manifest_parent.display());
                            }
                            self.execution_dir = Some(manifest_parent.to_path_buf());
                        } else if let Some(grandparent) = manifest_parent.parent() {
                            if has_tauri_conf(grandparent) {
                                if !self.be_silent {
                                    println!(
                                        "Using manifest grandparent: {}",
                                        grandparent.display()
                                    );
                                }
                                self.execution_dir = Some(grandparent.to_path_buf());
                            } else {
                                if !self.be_silent {
                                    println!("No tauri.conf.json found in candidate, manifest parent, or grandparent; defaulting to manifest parent: {}", manifest_parent.display());
                                }
                                self.execution_dir = Some(manifest_parent.to_path_buf());
                            }
                        } else {
                            if !self.be_silent {
                                println!("No grandparent for manifest; defaulting to candidate directory: {}", candidate_dir.display());
                            }
                            self.execution_dir = Some(candidate_dir.to_path_buf());
                        }
                    } else {
                        if !self.be_silent {
                            println!(
                                "No manifest parent found for: {}",
                                target.manifest_path.display()
                            );
                        }
                    }
                    // Check for package.json and run npm ls if found.
                    if !self.be_silent {
                        println!("Checking for package.json in: {}", candidate_dir.display());
                    }
                    if has_file(candidate_dir, "package.json") {
                        crate::e_installer::check_npm_and_install(candidate_dir, self.be_silent)
                            .ok();
                    }
                } else if let Some(manifest_parent) = target.manifest_path.parent() {
                    if has_tauri_conf(manifest_parent) {
                        if !self.be_silent {
                            println!("Using manifest parent: {}", manifest_parent.display());
                        }
                        self.execution_dir = Some(manifest_parent.to_path_buf());
                    } else if let Some(grandparent) = manifest_parent.parent() {
                        if has_tauri_conf(grandparent) {
                            if !self.be_silent {
                                println!("Using manifest grandparent: {}", grandparent.display());
                            }
                            self.execution_dir = Some(grandparent.to_path_buf());
                        } else {
                            if !self.be_silent {
                                println!(
                                    "No tauri.conf.json found; defaulting to manifest parent: {}",
                                    manifest_parent.display()
                                );
                            }
                            self.execution_dir = Some(manifest_parent.to_path_buf());
                        }
                    }
                    // Check for package.json and run npm ls if found.
                    if !self.be_silent {
                        println!(
                            "Checking for package.json in: {}",
                            manifest_parent.display()
                        );
                    }
                    if has_file(manifest_parent, "package.json") {
                        crate::e_installer::check_npm_and_install(manifest_parent, self.be_silent)
                            .ok();
                    }
                    if has_file(Path::new("."), "package.json") {
                        crate::e_installer::check_npm_and_install(manifest_parent, self.be_silent)
                            .ok();
                    }
                } else {
                    if !self.be_silent {
                        println!(
                            "No manifest parent found for: {}",
                            target.manifest_path.display()
                        );
                    }
                }
                self.args.push("tauri".into());
                self.args.push("dev".into());
            }
            TargetKind::ManifestLeptos => {
                let readme_path = target
                    .manifest_path
                    .parent()
                    .map(|p| p.join("README.md"))
                    .filter(|p| p.exists())
                    .or_else(|| {
                        target
                            .manifest_path
                            .parent()
                            .map(|p| p.join("readme.md"))
                            .filter(|p| p.exists())
                    });

                if let Some(readme) = readme_path {
                    if let Ok(mut file) = std::fs::File::open(&readme) {
                        let mut contents = String::new();
                        if file.read_to_string(&mut contents).is_ok()
                            && contents.contains("cargo leptos watch")
                        {
                            // Use cargo leptos watch
                            if !self.be_silent {
                                println!("Detected 'cargo leptos watch' in {}", readme.display());
                            }
                            crate::e_installer::ensure_leptos().unwrap_or_else(|_| {
                                eprintln!("Error: Unable to ensure leptos installation.");
                                PathBuf::new() // Return an empty PathBuf as a fallback
                            });
                            self.execution_dir =
                                target.manifest_path.parent().map(|p| p.to_path_buf());

                            self.alternate_cmd = Some("cargo".to_string());
                            self.args.push("leptos".into());
                            self.args.push("watch".into());
                            self = self.with_required_features(&target.manifest_path, target);
                            if let Some(exec_dir) = &self.execution_dir {
                                if exec_dir.join("package.json").exists() {
                                    if !self.be_silent {
                                        println!(
                                            "Found package.json in execution directory: {}",
                                            exec_dir.display()
                                        );
                                    }
                                    crate::e_installer::check_npm_and_install(
                                        exec_dir,
                                        self.be_silent,
                                    )
                                    .ok();
                                }
                            }
                            return self;
                        }
                    }
                }

                // fallback to trunk
                let exe_path = match crate::e_installer::ensure_trunk() {
                    Ok(p) => p,
                    Err(e) => {
                        eprintln!("{}", e);
                        return self;
                    }
                };

                if !self.be_silent {
                    if let Some(manifest_parent) = target.manifest_path.parent() {
                        println!("Manifest path: {}", target.manifest_path.display());
                        println!(
                            "Execution directory (same as manifest folder): {}",
                            manifest_parent.display()
                        );
                        self.execution_dir = Some(manifest_parent.to_path_buf());
                    } else {
                        println!(
                            "No manifest parent found for: {}",
                            target.manifest_path.display()
                        );
                    }
                }
                if let Some(exec_dir) = &self.execution_dir {
                    if exec_dir.join("package.json").exists() {
                        if !self.be_silent {
                            println!(
                                "Found package.json in execution directory: {}",
                                exec_dir.display()
                            );
                        }
                        crate::e_installer::check_npm_and_install(exec_dir, self.be_silent).ok();
                    }
                }
                self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
                self.args.push("serve".into());
                self.args.push("--open".into());
                self.args.push("--color".into());
                self.args.push("always".into());
                self = self.with_required_features(&target.manifest_path, target);
            }
            TargetKind::ManifestDioxus => {
                // For Dioxus targets, print the manifest path and set the execution directory
                let exe_path = match crate::e_installer::ensure_dx() {
                    Ok(path) => path,
                    Err(e) => {
                        eprintln!("Error locating `dx`: {}", e);
                        return self;
                    }
                };
                // to be the same directory as the manifest.
                if !self.be_silent {
                    if let Some(manifest_parent) = target.manifest_path.parent() {
                        println!("Manifest path: {}", target.manifest_path.display());
                        println!(
                            "Execution directory (same as manifest folder): {}",
                            manifest_parent.display()
                        );
                        self.execution_dir = Some(manifest_parent.to_path_buf());
                    } else {
                        println!(
                            "No manifest parent found for: {}",
                            target.manifest_path.display()
                        );
                    }
                }
                self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
                self.args.push("serve".into());
                self = self.with_required_features(&target.manifest_path, target);
            }
            TargetKind::ManifestDioxusExample => {
                let exe_path = match crate::e_installer::ensure_dx() {
                    Ok(path) => path,
                    Err(e) => {
                        eprintln!("Error locating `dx`: {}", e);
                        return self;
                    }
                };
                // For Dioxus targets, print the manifest path and set the execution directory
                // to be the same directory as the manifest.
                if !self.be_silent {
                    if let Some(manifest_parent) = target.manifest_path.parent() {
                        println!("Manifest path: {}", target.manifest_path.display());
                        println!(
                            "Execution directory (same as manifest folder): {}",
                            manifest_parent.display()
                        );
                        self.execution_dir = Some(manifest_parent.to_path_buf());
                    } else {
                        println!(
                            "No manifest parent found for: {}",
                            target.manifest_path.display()
                        );
                    }
                }
                self.alternate_cmd = Some(exe_path.as_os_str().to_string_lossy().to_string());
                self.args.push("serve".into());
                self.args.push("--example".into());
                self.args.push(target.name.clone());
                self = self.with_required_features(&target.manifest_path, target);
            }
        }
        self
    }

    /// Configure the command using CLI options.
    pub fn with_cli(mut self, cli: &crate::Cli) -> Self {
        if cli.quiet && !self.suppressed_flags.contains("quiet") {
            // Insert --quiet right after "run" if present.
            if let Some(pos) = self.args.iter().position(|arg| arg == &self.subcommand) {
                self.args.insert(pos + 1, "--quiet".into());
            } else {
                self.args.push("--quiet".into());
            }
        }
        if cli.release {
            // Insert --release right after the initial "run" command if applicable.
            // For example, if the command already contains "run", insert "--release" after it.
            if let Some(pos) = self.args.iter().position(|arg| arg == &self.subcommand) {
                self.args.insert(pos + 1, "--release".into());
            } else {
                // If not running a "run" command (like in the Tauri case), simply push it.
                self.args.push("--release".into());
            }
        }
        if cli.detached_hold.is_some() {
            self.detached_hold = cli.detached_hold;
        }
        if cli.detached_delay.is_some() {
            self.detached_delay = cli.detached_delay;
        }
        if cli.detached {
            self.detached = true;
        }
        // Append extra arguments (if any) after a "--" separator.
        if !cli.extra.is_empty() {
            self.args.push("--".into());
            self.args.extend(cli.extra.iter().cloned());
        }
        self
    }
    /// Append required features based on the manifest, target kind, and name.
    /// This method queries your manifest helper function and, if features are found,
    /// appends "--features" and the feature list.
    pub fn with_required_features(mut self, manifest: &PathBuf, target: &CargoTarget) -> Self {
        if !self.args.contains(&"--features".to_string()) {
            if let Some(features) = crate::e_manifest::get_required_features_from_manifest(
                manifest,
                &target.kind,
                &target.name,
            ) {
                self.args.push("--features".to_string());
                self.args.push(features);
            }
        }
        self
    }

    /// Appends extra arguments to the command.
    pub fn with_extra_args(mut self, extra: &[String]) -> Self {
        if !extra.is_empty() {
            // Use "--" to separate Cargo arguments from target-specific arguments.
            self.args.push("--".into());
            self.args.extend(extra.iter().cloned());
        }
        self
    }

    /// Builds the final vector of command-line arguments.
    pub fn build(self) -> Vec<String> {
        self.args
    }

    pub fn is_compiler_target(&self) -> bool {
        let supported_subcommands = ["run", "build", "check", "leptos", "tauri"];
        if let Some(alternate) = &self.alternate_cmd {
            if alternate == "trunk" {
                return true;
            }
            if alternate != "cargo" {
                return false;
            }
        }
        if let Some(_) = self
            .args
            .iter()
            .position(|arg| supported_subcommands.contains(&arg.as_str()))
        {
            return true;
        }
        false
    }

    pub fn injected_args(&self) -> (String, Vec<String>) {
        let mut new_args = self.args.clone();
        let supported_subcommands = [
            "run", "build", "test", "bench", "clean", "doc", "publish", "update",
        ];

        if self.is_filter {
            if let Some(pos) = new_args
                .iter()
                .position(|arg| supported_subcommands.contains(&arg.as_str()))
            {
                // If the command is a supported subcommand like "cargo run", insert the JSON output format and color options.
                new_args.insert(pos + 1, "--message-format=json".into());
                new_args.insert(pos + 2, "--color".into());
                new_args.insert(pos + 3, "always".into());
            }
        }

        let mut program = self.alternate_cmd.as_deref().unwrap_or("cargo").to_string();

        if self.use_cache {
            #[cfg(target_os = "windows")]
            {
                // On Windows, we use the `cargo-e` executable.
                program = format!("{}.exe", self.target_name.clone());
            }
            #[cfg(not(target_os = "windows"))]
            {
                program = self.target_name.clone();
            }
            let debug_path = Path::new("target").join("debug").join(program.clone());
            let release_path = Path::new("target").join("release").join(program.clone());
            let release_examples_path = Path::new("target")
                .join("release")
                .join("examples")
                .join(program.clone());
            let debug_examples_path = Path::new("target")
                .join("debug")
                .join("examples")
                .join(program.clone());
            if release_path.exists() {
                program = release_path.to_string_lossy().to_string();
            } else if release_examples_path.exists() {
                program = release_examples_path.to_string_lossy().to_string();
            } else if debug_path.exists() {
                program = debug_path.to_string_lossy().to_string();
            } else if debug_examples_path.exists() {
                program = debug_examples_path.to_string_lossy().to_string();
            } else if Path::new(&program).exists() {
                // If the program exists in the current directory, use it.
                program = Path::new(&program).to_string_lossy().to_string();
            } else {
                program = self.alternate_cmd.as_deref().unwrap_or("cargo").to_string();
            }
            // new_args = vec![]
        }

        if self.default_binary_is_runner {
            program = "cargo".to_string();
            new_args = vec![
                "run".to_string(),
                "--".to_string(),
                self.target_name.clone(),
            ];
        }

        (program, new_args)
    }

    pub fn print_command(&self) {
        let (program, new_args) = self.injected_args();
        println!("{} {}", program, new_args.join(" "));
    }

    /// builds a std::process::Command.
    pub fn build_command(&self) -> Command {
        let (program, new_args) = self.injected_args();

        let mut cmd = if self.detached {
            #[cfg(target_os = "windows")]
            {
                let mut detached_cmd = Command::new("cmd");
                // On Windows, to ensure the timeout is applied after the command runs, you should use the `timeout` command after the actual command and its arguments.
                // However, the Windows `cmd /c start` command does not natively support running a command and then a timeout in sequence directly.
                // Instead, you can chain commands using `&&` so that the timeout runs after the main command completes.

                // Try to find "startt" using which::which
                let startt_path = which("startt").ok();
                if let Some(hold_time) = self.detached_hold {
                    println!(
                        "Running detached command with hold time: {} seconds",
                        hold_time
                    );
                    let cmdline = format!("{} {}", program, new_args.join(" "));
                    if let Some(startt) = startt_path {
                        // Use startt directly if found
                        detached_cmd = Command::new(startt);
                        //detached_cmd.creation_flags(0x00000008); // CREATE_NEW_CONSOLE
                        detached_cmd.args(&["/wait"]);
                        if let Some(_hold_time) = self.detached_hold {
                            detached_cmd.args(&["--detached-hold", &hold_time.to_string()]);
                        }
                        if let Some(delay_time) = self.detached_delay {
                            detached_cmd.args(&["--detached-delay", &delay_time.to_string()]);
                            // &delay_time.to_string()]);
                        }
                        detached_cmd.args(&[&program]);
                        detached_cmd.args(&new_args);
                        println!("Using startt: {:?}", detached_cmd);
                        return detached_cmd;
                    } else {
                        // Fallback to cmd /c start /wait
                        // To enforce a timeout regardless of how cmdline exits, use PowerShell's Start-Process with -Wait and a timeout loop.
                        // This launches the process and then waits up to hold_time seconds, killing it if it exceeds the timeout.
                        // Note: This requires PowerShell to be available.
                        if let Some(hold_time) = self.detached_hold {
                            let ps_script = format!(
                                "Start-Process -NoNewWindow -Wait -FilePath cmd -ArgumentList '/c', '{}' ; $p = Get-Process -Name '{}' -ErrorAction SilentlyContinue; $t = 0; while ($p -and $t -lt {}) {{ Start-Sleep -Seconds 1; $t++; $p = Get-Process -Name '{}' -ErrorAction SilentlyContinue }}; if ($p) {{ $p | Stop-Process }}",
                                cmdline,
                                program,
                                hold_time,
                                program
                            );
                            detached_cmd = Command::new("powershell");
                            detached_cmd.args(&["-NoProfile", "-Command", &ps_script]);
                        } else {
                            detached_cmd.args(&["/c", "start", "/wait", "cmd", "/c", &cmdline]);
                        }
                        return detached_cmd;
                    }
                } else {
                    let cmdline = format!("{} {}", program, new_args.join(" "));
                    if let Some(startt) = startt_path {
                        // Use startt directly if found
                        detached_cmd = Command::new(startt);
                        detached_cmd.args(&[&program]);
                        detached_cmd.args(&new_args);
                        return detached_cmd;
                    } else {
                        // Fallback to cmd /c start /wait
                        detached_cmd.args(&["/c", "start", "/wait", "cmd", "/c", &cmdline]);
                    }
                }
                detached_cmd
            }
            #[cfg(target_os = "linux")]
            {
                let mut detached_cmd = Command::new("xterm");
                detached_cmd.args(&["-e", &program]);
                detached_cmd.args(&new_args);
                detached_cmd
            }
            #[cfg(target_os = "macos")]
            {
                let mut detached_cmd = Command::new("osascript");
                detached_cmd.args(&[
                    "-e",
                    &format!(
                        "tell application \"Terminal\" to do script \"{} {}; sleep {}; exit\"",
                        program,
                        new_args.join(" "),
                        self.detached_hold.unwrap_or(0)
                    ),
                ]);
                detached_cmd
            }
        } else {
            let mut cmd = Command::new(program);
            cmd.args(&new_args);
            cmd
        };

        if let Some(dir) = &self.execution_dir {
            cmd.current_dir(dir);
        }

        cmd
    }
    /// Runs the command and returns everything it printed (stdout + stderr),
    /// regardless of exit status.
    pub fn capture_output(&self) -> anyhow::Result<String> {
        // Build and run
        let mut cmd = self.build_command();
        let output = cmd
            .output()
            .map_err(|e| anyhow::anyhow!("Failed to spawn cargo process: {}", e))?;

        // Decode both stdout and stderr lossily
        let mut all = String::new();
        all.push_str(&String::from_utf8_lossy(&output.stdout));
        all.push_str(&String::from_utf8_lossy(&output.stderr));

        // Return the combined string, even if exit was !success
        Ok(all)
    }
}

fn show_graphical_panic(
    line: String,
    prior_response: Option<CallbackResponse>,
    manifest_path: PathBuf,
    _window_for_pid: u32,
    _stats: std::sync::Arc<std::sync::Mutex<crate::e_cargocommand_ext::CargoStats>>,
) {
    if let Ok(e_window_path) = which("e_window") {
        // Compose a nice message for e_window's stdin
        // let stats = stats.lock().unwrap();
        // Compose a table with cargo-e and its version, plus panic info
        let cargo_e_version = env!("CARGO_PKG_VERSION");

        let anchor: String = {
            // If there's no prior response, return an empty string.
            if prior_response.is_none() {
                String::new()
            } else {
                // Try to parse the line as "file:line:col"
                let prior = prior_response.as_ref().unwrap();
                let file = prior.file.as_deref().unwrap_or("");
                //let line_num = prior.line.map(|n| n.to_string()).unwrap_or_default();
                //let col_num = prior.column.map(|n| n.to_string()).unwrap_or_default();

                let full_path = std::fs::canonicalize(file).unwrap_or_else(|_| {
                    // Remove the top folder from the file path if possible
                    let stripped_file = Path::new(file).components().skip(1).collect::<PathBuf>();
                    let fallback_path = stripped_file.clone();
                    std::fs::canonicalize(&fallback_path).unwrap_or_else(|_| {
                        let manifest_dir = manifest_path.parent().unwrap_or_else(|| {
                            eprintln!(
                                "Failed to determine parent directory for manifest: {:?}",
                                manifest_path
                            );
                            Path::new(".")
                        });
                        let parent_fallback_path = manifest_dir.join(file);
                        std::fs::canonicalize(&parent_fallback_path).unwrap_or_else(|_| {
                            eprintln!("Failed to resolve full path for: {} using ../", file);
                            let parent_fallback_path = manifest_dir.join(&stripped_file);
                            if parent_fallback_path.exists() {
                                parent_fallback_path
                            } else {
                                PathBuf::from(file)
                            }
                        })
                    })
                });
                let stripped_file = full_path.to_string_lossy().replace("\\\\?\\", "");
                let code_path = which("code").unwrap_or_else(|_| "code".to_string().into());
                String::from(format!(
                    "\nanchor: code {} {} {}|\"{}\" --goto \"{}:{}:{}\"\n",
                    stripped_file,
                    prior.line.unwrap_or(0),
                    prior.column.unwrap_or(0),
                    code_path.display(),
                    stripped_file,
                    prior.line.unwrap_or(0),
                    prior.column.unwrap_or(0)
                ))
            }
        };
        let context = ThreadLocalContext::get_context();
        let mut card = format!(
            "--title \"panic: {target}\" --width 400 --height 300\n\
                        target | {target} | string\n\
                        cargo-e | {version} | string\n\
                        \n\
                        panic: {target}\n{line}",
            target = context.target_name,
            version = cargo_e_version,
            line = line
        );
        if let Some(prior) = prior_response {
            if let Some(msg) = &prior.message {
                card = format!("{}\n{}", card, msg);
            }
        }
        if !anchor.is_empty() {
            card = format!("{}{}", card, anchor);
        }
        #[cfg(target_os = "windows")]
        let child = std::process::Command::new(e_window_path)
            .stdin(std::process::Stdio::piped())
            .creation_flags(0x00000008) // CREATE_NEW_CONSOLE
            .spawn();
        #[cfg(not(target_os = "windows"))]
        let child = std::process::Command::new(e_window_path)
            .stdin(std::process::Stdio::piped())
            .spawn();
        if let Ok(mut child) = child {
            if let Some(stdin) = child.stdin.as_mut() {
                use std::io::Write;
                let _ = stdin.write_all(card.as_bytes());
                let pid = child.id();
                // Add to global e_window pid list if available

                if let Some(global) = crate::GLOBAL_EWINDOW_PIDS.get() {
                    global.insert(pid, pid);
                    log::trace!("Added pid {} to GLOBAL_EWINDOW_PIDS", pid);
                } else {
                    log::trace!("GLOBAL_EWINDOW_PIDS is not initialized");
                }
                std::mem::drop(child)
            }
        }
    }
}

/// Resolves a file path by:
///   1. If the path is relative, try to resolve it relative to the current working directory.
///   2. If that file does not exist, try to resolve it relative to the parent directory of the manifest path.
///   3. Otherwise, return the original relative path.
pub(crate) fn resolve_file_path(manifest_path: &PathBuf, file_str: &str) -> PathBuf {
    let file_path = Path::new(file_str);
    if file_path.is_relative() {
        // 1. Try resolving relative to the current working directory.
        if let Ok(cwd) = env::current_dir() {
            let cwd_path = cwd.join(file_path);
            if cwd_path.exists() {
                return cwd_path;
            }
        }
        // 2. Try resolving relative to the parent of the manifest path.
        if let Some(manifest_parent) = manifest_path.parent() {
            let parent_path = manifest_parent.join(file_path);
            if parent_path.exists() {
                return parent_path;
            }
        }
        // 3. Neither existed; return the relative path as-is.
        return file_path.to_path_buf();
    }
    file_path.to_path_buf()
}

// --- Example usage ---
#[cfg(test)]
mod tests {
    use crate::e_target::TargetOrigin;

    use super::*;

    #[test]
    fn test_command_builder_example() {
        let target_name = "my_example".to_string();
        let target = CargoTarget {
            name: "my_example".to_string(),
            display_name: "My Example".to_string(),
            manifest_path: "Cargo.toml".into(),
            kind: TargetKind::Example,
            extended: true,
            toml_specified: false,
            origin: Some(TargetOrigin::SingleFile(PathBuf::from(
                "examples/my_example.rs",
            ))),
        };

        let extra_args = vec!["--flag".to_string(), "value".to_string()];

        let manifest_path = PathBuf::from("Cargo.toml");
        let args = CargoCommandBuilder::new(
            &target_name,
            &manifest_path,
            "run",
            false,
            false,
            false,
            false,
            false,
            false,
        )
        .with_target(&target)
        .with_extra_args(&extra_args)
        .build();

        // For an example target, we expect something like:
        // cargo run --example my_example --manifest-path Cargo.toml -- --flag value
        assert!(args.contains(&"--example".to_string()));
        assert!(args.contains(&"my_example".to_string()));
        assert!(args.contains(&"--".to_string()));
        assert!(args.contains(&"--flag".to_string()));
        assert!(args.contains(&"value".to_string()));
    }
}