winx-code-agent 0.2.329

High-performance Rust implementation of WCGW for LLM code agents
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
//! Implementation of the `BashCommand` tool with WCGW parity.
//!
//! This module provides the implementation for the `BashCommand` tool, which is used
//! to execute shell commands, check command status, and interact with the shell.
//! Matches the behavior of wcgw Python implementation 1:1.

use anyhow::Context as AnyhowContext;
use rand::RngExt;
use regex::Regex;
use std::collections::HashMap;
use std::fmt::Write as FmtWrite;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex as StdMutex};
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use tokio::time::sleep;
use tracing::{debug, error, info, warn};

use crate::errors::{Result, WinxError};
use crate::state::bash_state::BashState;
use crate::state::live_terminal::ScreenUpdate;
use crate::state::pty::PtyShell;
use crate::state::terminal::{render_terminal_output, strip_ansi_codes};
use crate::types::{normalize_thread_id, BashCommand, BashCommandAction, SpecialKey};

type SharedPtyShell = Arc<Mutex<Option<PtyShell>>>;

// ==================== WCGW-Style Constants ====================

/// Default timeout for command execution (seconds) - matches WCGW Python Config.timeout
const DEFAULT_TIMEOUT: f64 = 5.0;

/// Extended timeout while output is still being produced - matches WCGW Python `Config.timeout_while_output`
const TIMEOUT_WHILE_OUTPUT: f64 = 20.0;

/// Number of iterations to wait without new output before giving up - matches WCGW Python `Config.output_wait_patience`
const OUTPUT_WAIT_PATIENCE: i32 = 3;

/// Async poll interval for adaptive output reads. We drain whatever the reader
/// thread has queued (non-blocking), release the shell lock, then `await` this
/// long — yielding the executor instead of pinning it on a blocking sleep.
const POLL_INTERVAL_MS: u64 = 20;

/// Grace period after the prompt is seen, to capture bytes that land just after
/// it (mirrors the old `read_output` post-prompt drain) — awaited, not blocked.
const POST_PROMPT_DRAIN_MS: u64 = 100;

/// Chunk size for sending commands (characters) - matches WCGW Python (64 chars)
const COMMAND_CHUNK_SIZE: usize = 64;

/// Chunk size for sending text input (characters) - matches WCGW Python (128 chars)
const TEXT_CHUNK_SIZE: usize = 128;

/// Cheap byte-level safety net. We never even consider token counting if the
/// raw payload is smaller than this — tokenizing is fast but not free, and
/// the vast majority of responses are tiny status updates.
const MAX_OUTPUT_LENGTH: usize = 100_000;

/// Token budget reserved for a single PTY response when token-aware truncation
/// kicks in. Picked to leave plenty of room for the surrounding context — most
/// frontier models have 128k+ windows, so 25k for one shell payload is generous
/// without monopolizing the conversation.
const MAX_OUTPUT_TOKENS: usize = 25_000;

/// Delay between typing text and the submitting Enter. Ink-based TUIs (Claude
/// Code) collapse a burst of bytes into a single render tick and drop a CR that
/// arrives glued to the text — the input box updates but never submits. Sending
/// the Enter as a separate write after this short pause lets the TUI commit the
/// typed text first, so `submit: true` reliably submits. ~40ms is imperceptible
/// yet enough for the event loop to flush; harmless for plain shells.
const SUBMIT_NUDGE_DELAY: Duration = Duration::from_millis(40);

/// `screen` diff mode emits a per-line delta only when at most this many lines
/// changed; beyond that the full frame is cheaper to read than a giant diff.
const SCREEN_DIFF_THRESHOLD: usize = 10;

/// Tail of `text` at most `max_len` bytes long, snapped up to a char boundary so
/// we never slice through a multibyte UTF-8 sequence (which would panic).
fn char_safe_tail(text: &str, max_len: usize) -> &str {
    if text.len() <= max_len {
        return text;
    }
    let mut start = text.len() - max_len;
    while start < text.len() && !text.is_char_boundary(start) {
        start += 1;
    }
    &text[start..]
}

/// Truncate `text` so its Claude token count stays under `max_tokens`.
///
/// We tokenize the tail of the string only when the raw byte length already
/// exceeds the byte cap; otherwise we trust the byte budget and return as-is.
/// When the tail still overshoots, we keep the last `max_tokens - reserve`
/// tokens and prepend a "(...truncated)" marker — exactly what wcgw does in
/// `_incremental_text`.
fn truncate_to_token_budget(text: &str, max_tokens: usize) -> std::borrow::Cow<'_, str> {
    if text.len() <= MAX_OUTPUT_LENGTH {
        return std::borrow::Cow::Borrowed(text);
    }

    let Some(tokens) = crate::utils::encoder::encode_ids(text) else {
        // Fallback to the byte-based truncation we used before the tokenizer.
        return std::borrow::Cow::Owned(format!(
            "(...truncated)\n{}",
            char_safe_tail(text, MAX_OUTPUT_LENGTH)
        ));
    };

    if tokens.len() <= max_tokens {
        return std::borrow::Cow::Borrowed(text);
    }

    // Reserve one token slot for the marker overhead.
    let keep = max_tokens.saturating_sub(1);
    let tail = &tokens[tokens.len() - keep..];
    let decoded = crate::utils::encoder::decode_ids(tail).unwrap_or_else(|| {
        // Tokenizer present but decode failed: fall back to a byte tail.
        char_safe_tail(text, MAX_OUTPUT_LENGTH).to_string()
    });
    std::borrow::Cow::Owned(format!("(...truncated)\n{decoded}"))
}

/// Message when a command is already running - matches WCGW Python `WAITING_INPUT_MESSAGE`
const WAITING_INPUT_MESSAGE: &str = "A command is already running. NOTE: You can't run multiple shell commands in main shell, likely a previous program hasn't exited.
1. Get its output using status check.
2. Use `send_ascii` or `send_specials` to give inputs to the running program OR
3. kill the previous program by sending ctrl+c first using `send_ascii` or `send_specials`
4. Interrupt and run the process in background
";

// ==================== Background Shell Manager ====================

/// Snapshot of a background shell that has exited but whose final output has not
/// yet been consumed by the caller. We keep it around so the next call (typically
/// a `status_check`) can return the trailing output before the entry is gone.
#[derive(Debug, Clone)]
pub struct ExitedShellInfo {
    pub last_command: String,
    pub final_output: String,
    pub exited_at: Instant,
}

/// Manages background shell sessions - matches WCGW Python's `background_shells` dict
#[derive(Debug, Default)]
pub struct BackgroundShellManager {
    shells: HashMap<String, SharedPtyShell>,
    /// Recently exited shells that still owe their final output to the caller.
    /// Entries are consumed the first time the caller queries the id, then dropped.
    tombstones: HashMap<String, ExitedShellInfo>,
}

impl BackgroundShellManager {
    /// Tombstones older than this are garbage-collected on the next prune pass.
    const TOMBSTONE_TTL: Duration = Duration::from_secs(300);

    /// Create a new background shell manager
    pub fn new() -> Self {
        Self { shells: HashMap::new(), tombstones: HashMap::new() }
    }

    /// Start a new background shell and return its command ID
    /// Register an already-built shell and return its id.
    ///
    /// The caller builds the `PtyShell` BEFORE taking the manager lock —
    /// `PtyShell::new` forks+execs and does a ~300ms blocking prompt init, which
    /// must not run under the global `std::Mutex` (it would serialize every other
    /// background-shell op behind one slow spawn).
    pub fn register_shell(&mut self, shell: PtyShell) -> String {
        let cid = format!("{:010x}", rand::rng().random::<u32>());
        self.shells.insert(cid.clone(), Arc::new(Mutex::new(Some(shell))));
        info!("Started background shell with id: {}", cid);
        cid
    }

    /// Get a background shell by its command ID
    pub fn get_shell(&self, bg_command_id: &str) -> Option<SharedPtyShell> {
        self.shells.get(bg_command_id).cloned()
    }

    /// Remove and cleanup a background shell
    pub fn remove_shell(&mut self, bg_command_id: &str) -> bool {
        if let Some(shell_arc) = self.shells.remove(bg_command_id) {
            if let Ok(mut guard) = shell_arc.try_lock() {
                *guard = None;
            }
            info!("Removed background shell: {}", bg_command_id);
            true
        } else {
            false
        }
    }

    fn prune_finished_shells(&mut self) {
        // GC old tombstones first.
        let now = Instant::now();
        self.tombstones.retain(|_, info| now.duration_since(info.exited_at) < Self::TOMBSTONE_TTL);

        let mut finished: Vec<(String, Option<ExitedShellInfo>)> = Vec::new();

        for (id, shell_arc) in &self.shells {
            let Ok(mut guard) = shell_arc.try_lock() else {
                continue;
            };

            let Some(shell) = guard.as_mut() else {
                finished.push((id.clone(), None));
                continue;
            };

            if !shell.is_alive() {
                let tombstone = ExitedShellInfo {
                    last_command: shell.last_command.clone(),
                    final_output: std::mem::take(&mut shell.output_buffer),
                    exited_at: now,
                };
                finished.push((id.clone(), Some(tombstone)));
                continue;
            }

            // Never prune shells that haven't received a command yet.
            // The global BG_SHELL_MANAGER is shared across parallel tests; a freshly
            // spawned shell would otherwise be evicted between start_new_shell and
            // the first send_command, leading to "Failed to get background shell".
            if shell.last_command.is_empty() {
                continue;
            }

            if shell.command_running {
                // Non-blocking: draining here must NOT hold the global manager
                // lock across a 100ms blocking read (that serializes every other
                // background-shell op behind a single slow PTY).
                shell.poll_output_nonblocking();
            }

            if !shell.command_running {
                let tombstone = ExitedShellInfo {
                    last_command: shell.last_command.clone(),
                    final_output: std::mem::take(&mut shell.output_buffer),
                    exited_at: now,
                };
                finished.push((id.clone(), Some(tombstone)));
            }
        }

        for (id, tombstone) in finished {
            self.remove_shell(&id);
            if let Some(info) = tombstone {
                self.tombstones.insert(id, info);
            }
        }
    }

    /// Look up the tombstone for a recently-exited shell, if any.
    ///
    /// The entry stays in the map until the TTL expires (see
    /// `prune_finished_shells`), so repeated `status_check` calls on the same
    /// `bg_command_id` keep returning the cached final output instead of
    /// flipping to "shell not found" after the first read.
    pub fn peek_tombstone(&self, bg_command_id: &str) -> Option<ExitedShellInfo> {
        self.tombstones.get(bg_command_id).cloned()
    }

    /// Get info about all running background shells - matches WCGW Python `get_bg_running_commandsinfo`
    pub fn get_running_info(&mut self) -> String {
        self.prune_finished_shells();

        if self.shells.is_empty() {
            return "No command running in background.\n".to_string();
        }

        let mut running = Vec::new();
        for (id, shell_arc) in &self.shells {
            if let Ok(guard) = shell_arc.try_lock() {
                if let Some(bash) = guard.as_ref() {
                    if bash.command_running {
                        running
                            .push(format!("Command: {}, bg_command_id: {}", bash.last_command, id));
                    }
                }
            } else {
                running.push(format!("Command: <busy>, bg_command_id: {id}"));
            }
        }

        if running.is_empty() {
            "No command running in background.\n".to_string()
        } else {
            format!("Following background commands are attached:\n{}\n", running.join("\n"))
        }
    }
}

// Global background shell manager (thread-safe) - matches WCGW Python's BashState.background_shells
lazy_static::lazy_static! {
    static ref BG_SHELL_MANAGER: StdMutex<BackgroundShellManager> = StdMutex::new(BackgroundShellManager::new());
}

/// Lock the global background-shell manager, recovering from poisoning.
///
/// A panic while holding this lock (e.g. in the rendering path during a prune)
/// must NOT permanently brick all background-shell functionality for the rest of
/// the server's lifetime. The manager's data stays consistent across a panic, so
/// recovering the inner guard is safe.
fn lock_bg_manager() -> std::sync::MutexGuard<'static, BackgroundShellManager> {
    BG_SHELL_MANAGER.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}

// ==================== WCGW-Style Helper Functions ====================

/// Get WCGW-style status string - matches WCGW Python's `get_status()`
fn get_status(
    bash_state: &BashState,
    is_bg: bool,
    bg_id: Option<&str>,
    is_running: bool,
    running_for: Option<&str>,
    exit_code: Option<i32>,
) -> String {
    let mut status = "\n\n---\n\n".to_string();

    if is_bg {
        if let Some(id) = bg_id {
            let _ = writeln!(status, "bg_command_id = {id}");
        }
    }

    if is_running {
        status.push_str("status = still running\n");
        if let Some(duration) = running_for {
            let _ = writeln!(status, "running for = {duration}");
        }
    } else {
        status.push_str("status = process exited\n");
        // Exit code of the just-finished command, parsed from the prompt marker
        // (`──➤<nonce>:<code>`). Lets the agent see failure without grepping stderr.
        if let Some(code) = exit_code {
            let _ = writeln!(status, "exit code = {code}");
        }
    }

    let _ = writeln!(status, "cwd = {}", bash_state.cwd.display());

    if !is_bg {
        // Add background shell info for main shell - matches WCGW Python
        {
            let mut manager = lock_bg_manager();
            status.push_str("This is the main shell. ");
            status.push_str(&manager.get_running_info());
        }
    }

    status.trim_end().to_string()
}

/// Process output with WCGW-style incremental text handling - matches WCGW Python _`incremental_text`
fn wcgw_incremental_text(text: &str, last_pending_output: &str) -> String {
    let truncated = truncate_to_token_budget(text, MAX_OUTPUT_TOKENS);
    let text = truncated.as_ref();

    if last_pending_output.is_empty() {
        let rendered = render_terminal_output(text);
        return rstrip_lines(&rendered).trim_start().to_string();
    }

    let last_rendered = render_terminal_output(last_pending_output);
    if last_rendered.is_empty() {
        return rstrip_lines(&render_terminal_output(text));
    }

    // Get text after last pending output. Snap the offset down to a char
    // boundary: `last_pending_output.len()` is a byte count and may land inside
    // a multibyte code point of `text`, which would panic on the slice.
    let text_after_last = if text.len() > last_pending_output.len() {
        let cut = crate::utils::floor_char_boundary(text, last_pending_output.len());
        &text[cut..]
    } else {
        text
    };

    let combined = format!("{}\n{}", last_rendered.join("\n"), text_after_last);
    let new_rendered = render_terminal_output(&combined);

    // Get incremental part - matches WCGW Python get_incremental_output
    let incremental = get_incremental_output(&last_rendered, &new_rendered);
    rstrip_lines(&incremental)
}

fn extract_prompt_cwd(output: &str) -> Option<PathBuf> {
    static PROMPT_RE: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
    // `.expect`, not `.ok()`: a compile-time-literal regex that fails to build is a
    // dev bug, not a runtime condition. The old `OnceLock<Option<Regex>>` froze
    // `None` forever on the first failure, silently disabling all CWD tracking for
    // the rest of the process. Fail loud instead.
    #[allow(clippy::expect_used)]
    let prompt_regex = PROMPT_RE
        .get_or_init(|| Regex::new(r"◉ (?P<cwd>[^\r\n]*?)──➤").expect("prompt regex must compile"));
    let stripped = strip_ansi_codes(output);

    prompt_regex
        .captures_iter(&stripped)
        .filter_map(|captures| captures.name("cwd").map(|cwd| cwd.as_str().trim()))
        .filter(|cwd| !cwd.is_empty())
        .last()
        .map(PathBuf::from)
}

/// Right-strip each line and join - matches WCGW Python rstrip
fn rstrip_lines(lines: &[String]) -> String {
    lines.iter().map(|line| line.trim_end()).collect::<Vec<_>>().join("\n")
}

/// Get incremental output between old and new - matches WCGW Python `get_incremental_output`
fn get_incremental_output(old_output: &[String], new_output: &[String]) -> Vec<String> {
    if old_output.is_empty() {
        return new_output.to_vec();
    }

    let nold = old_output.len();
    let nnew = new_output.len();

    // Find where old output ends in new output
    for i in (0..nnew).rev() {
        if new_output[i] != old_output[nold - 1] {
            continue;
        }

        let mut matched = true;
        for j in (0..i).rev() {
            let old_idx = (nold as i64 - 1 + j as i64 - i as i64) as isize;
            if old_idx < 0 {
                break;
            }
            if new_output[j] != old_output[old_idx as usize] {
                matched = false;
                break;
            }
        }

        if matched {
            return new_output[i + 1..].to_vec();
        }
    }

    new_output.to_vec()
}

fn send_utf8_in_byte_chunks(shell: &mut PtyShell, text: &str, chunk_size: usize) -> Result<()> {
    let mut start = 0;

    while start < text.len() {
        let mut end = (start + chunk_size).min(text.len());
        while !text.is_char_boundary(end) {
            end -= 1;
        }
        if end == start {
            end = text[start..].char_indices().nth(1).map_or(text.len(), |(idx, _)| start + idx);
        }

        shell.send_text(&text[start..end]).map_err(|e| {
            WinxError::CommandExecutionError(format!("Failed to write PTY input: {e}"))
        })?;
        start = end;
    }

    Ok(())
}

/// Send the submitting Enter as a separate, slightly-delayed write so an
/// Ink-based TUI doesn't swallow a CR glued to the preceding input. Briefly
/// drops the shell lock during the pause so the reader thread keeps draining.
/// See [`SUBMIT_NUDGE_DELAY`].
async fn submit_enter(shell_arc: &SharedPtyShell) -> Result<()> {
    tokio::time::sleep(SUBMIT_NUDGE_DELAY).await;
    let mut guard = shell_arc.lock().await;
    let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
    bash.send_special_key("Enter")
        .map_err(|e| WinxError::CommandExecutionError(format!("Failed to submit: {e}")))?;
    Ok(())
}

// ==================== Main Tool Handler ====================

/// Handles the `BashCommand` tool call with WCGW parity
///
/// This function processes the `BashCommand` tool call following WCGW Python's
/// `execute_bash()` function behavior exactly.
#[tracing::instrument(level = "info", skip(bash_state_arc, bash_command))]
pub async fn handle_tool_call(
    bash_state_arc: &Arc<Mutex<Option<BashState>>>,
    bash_command: BashCommand,
) -> Result<String> {
    info!("BashCommand tool called with: {:?}", bash_command);

    let thread_id = normalize_thread_id(&bash_command.thread_id);

    // Check if thread_id is empty
    if thread_id.is_empty() {
        error!("Empty thread_id provided in BashCommand");
        return Err(WinxError::ThreadIdMismatch(
            "Error: No saved bash state found for thread ID \"\". Please initialize first with this ID.".to_string()
        ));
    }

    // Extract bash_state data
    let mut bash_state: BashState;
    {
        let bash_state_guard = bash_state_arc.lock().await;

        let Some(state) = &*bash_state_guard else {
            error!("BashState not initialized");
            return Err(WinxError::BashStateNotInitialized);
        };

        bash_state = state.clone();
    }

    // Verify thread ID matches - matches WCGW Python thread_id check
    if thread_id != bash_state.current_thread_id {
        // Try to load state from thread_id - matches WCGW Python load_state_from_thread_id
        // Distinguish "no state for this id" (Ok(false)) from a real load failure
        // (Err: permission denied, corrupt JSON). The old `.unwrap_or(false)`
        // collapsed both into the misleading "initialize first" message.
        let loaded = bash_state.load_state_from_disk(&thread_id).map_err(|e| {
            WinxError::CommandExecutionError(format!(
                "Failed to load saved bash state for thread_id `{thread_id}`: {e}"
            ))
        })?;
        if !loaded {
            return Err(WinxError::ThreadIdMismatch(format!(
                "Error: No saved bash state found for thread_id `{thread_id}`. Please initialize first with this ID."
            )));
        }
        // Promote the loaded state back to the shared slot. The old code only wrote
        // `cwd` back at the end, so switching thread_id silently dropped the loaded
        // whitelist/mode/thread_id — the next command re-cloned the stale state.
        // load_state_from_disk doesn't touch pty_shell (shells aren't serialized),
        // so the live shell Arc is preserved through the clone.
        if let Some(state) = bash_state_arc.lock().await.as_mut() {
            *state = bash_state.clone();
        }
    }

    // Calculate effective timeout - matches WCGW Python
    // SECURITY: Ensure timeout is not negative to prevent unexpected behavior
    let timeout_s = bash_command
        .wait_for_seconds
        .map_or(DEFAULT_TIMEOUT, |t| f64::from(t).max(0.0))
        .min(TIMEOUT_WHILE_OUTPUT);

    // Execute the action based on type - matches WCGW Python's _execute_bash()
    let result = execute_bash_action(&mut bash_state, &bash_command.action_json, timeout_s).await;

    {
        let mut bash_state_guard = bash_state_arc.lock().await;
        if let Some(state) = bash_state_guard.as_mut() {
            state.cwd.clone_from(&bash_state.cwd);
        }
    }

    // Remove echo if it's a command - matches WCGW Python
    match result {
        Ok(mut output) => {
            if let BashCommandAction::Command { ref command, .. } = bash_command.action_json {
                let cmd_trimmed = command.trim();
                if output.starts_with(cmd_trimmed) {
                    output = output[cmd_trimmed.len()..].to_string();
                }
            }
            Ok(output)
        }
        Err(e) => Err(e),
    }
}

/// Execute a bash action - matches WCGW Python's _`execute_bash()` function
#[allow(clippy::too_many_lines)]
async fn execute_bash_action(
    bash_state: &mut BashState,
    action: &BashCommandAction,
    timeout_s: f64,
) -> Result<String> {
    let mut is_bg = false;
    let mut bg_id: Option<String> = None;

    // Handle bg_command_id routing - matches WCGW Python
    let bg_shell: Option<SharedPtyShell> = match action {
        BashCommandAction::Command { .. } => None, // Commands don't use bg_command_id for routing
        BashCommandAction::StatusCheck { bg_command_id, .. }
        | BashCommandAction::SendText { bg_command_id, .. }
        | BashCommandAction::SendSpecials { bg_command_id, .. }
        | BashCommandAction::SendAscii { bg_command_id, .. }
        | BashCommandAction::Screen { bg_command_id, .. }
        | BashCommandAction::WaitForTurn { bg_command_id, .. } => {
            if let Some(id) = bg_command_id {
                // Use the recovery helper (poison -> into_inner) like every other
                // call site, rather than hard-failing this one path on poison.
                let mut manager = lock_bg_manager();
                manager.prune_finished_shells();

                if let Some(shell) = manager.get_shell(id) {
                    is_bg = true;
                    bg_id = Some(id.clone());
                    Some(shell)
                } else if let Some(tombstone) = manager.peek_tombstone(id) {
                    // Shell already exited. For a status check we can hand back the
                    // final cached output exactly once. For anything else (send_text,
                    // send_specials, send_ascii) tell the caller the shell is gone
                    // and include the captured output so they can recover state.
                    drop(manager);
                    return finalize_tombstone(&bash_state.cwd, id, tombstone, action);
                } else {
                    // Error message matches WCGW Python
                    let error = format!(
                        "No shell found running with command id {}.\n{}",
                        id,
                        manager.get_running_info()
                    );
                    return Err(WinxError::CommandExecutionError(error));
                }
            } else {
                None
            }
        }
    };

    // Process based on action type - matches WCGW Python _execute_bash dispatch
    match action {
        BashCommandAction::Command { command, is_background, allow_multi } => {
            execute_command(bash_state, command, *is_background, *allow_multi, timeout_s).await
        }
        BashCommandAction::StatusCheck { scrollback_lines, verbose, .. } => {
            execute_status_check(
                bash_state,
                bg_shell,
                is_bg,
                bg_id.as_deref(),
                timeout_s,
                *scrollback_lines,
                *verbose,
            )
            .await
        }
        BashCommandAction::SendText { send_text, submit, .. } => {
            execute_send_text(
                bash_state,
                send_text,
                *submit,
                bg_shell,
                is_bg,
                bg_id.as_deref(),
                timeout_s,
            )
            .await
        }
        BashCommandAction::SendSpecials { send_specials, submit, .. } => {
            execute_send_specials(
                bash_state,
                send_specials,
                *submit,
                bg_shell,
                is_bg,
                bg_id.as_deref(),
                timeout_s,
            )
            .await
        }
        BashCommandAction::SendAscii { send_ascii, submit, .. } => {
            execute_send_ascii(
                bash_state,
                send_ascii,
                *submit,
                bg_shell,
                is_bg,
                bg_id.as_deref(),
                timeout_s,
            )
            .await
        }
        BashCommandAction::Screen { lines, diff, .. } => {
            execute_screen(bash_state, bg_shell, is_bg, bg_id.as_deref(), *lines, *diff).await
        }
        BashCommandAction::WaitForTurn {
            recognizer,
            quiet_ms,
            timeout_seconds,
            lines,
            wait_through_busy,
            ..
        } => {
            execute_wait_for_turn(
                bash_state,
                bg_shell,
                is_bg,
                bg_id.as_deref(),
                recognizer.as_deref(),
                *quiet_ms,
                *timeout_seconds,
                *lines,
                *wait_through_busy,
            )
            .await
        }
    }
}

/// Strip a trailing `| tail ...` from a command (wcgw parity, `strip_tail_pipe`).
///
/// LLMs habitually pipe output through `tail`, but we already truncate output
/// server-side — stripping the pipe avoids hiding the earlier output the model
/// usually wants. Only a `tail` at the very end of the command is removed.
///
/// This matches wcgw by default. Set `WINX_KEEP_TAIL_PIPE=1` to preserve the
/// pipe instead (winx's original behavior), e.g. when you deliberately want only
/// the tail of a huge log rather than the server-side truncation.
fn strip_tail_pipe(command: &str) -> String {
    strip_tail_pipe_impl(command, keep_tail_pipe())
}

/// Pure core of [`strip_tail_pipe`], split out so both modes are unit-testable
/// without touching process-wide env vars (tests run concurrently).
fn strip_tail_pipe_impl(command: &str, keep: bool) -> String {
    static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
    if keep {
        return command.to_string();
    }
    // `.expect`, not `.ok()`: a compile-time-literal regex that fails to build is
    // a dev bug. The old `OnceLock<Option<Regex>>` + `.ok()` would freeze `None`
    // and silently stop stripping `| tail` for the whole process.
    #[allow(clippy::expect_used)]
    let re = RE.get_or_init(|| {
        regex::Regex::new(r"\|\s*tail(?:\s+(?:-n\s*|-)?(\d+))?\s*$")
            .expect("tail-pipe regex must compile")
    });
    match re.find(command) {
        Some(matched) => command[..matched.start()].trim_end().to_string(),
        None => command.to_string(),
    }
}

/// Whether the user opted out of `| tail` stripping via `WINX_KEEP_TAIL_PIPE`.
fn keep_tail_pipe() -> bool {
    std::env::var("WINX_KEEP_TAIL_PIPE").is_ok_and(|value| {
        let value = value.trim();
        !value.is_empty() && value != "0" && !value.eq_ignore_ascii_case("false")
    })
}

/// Execute a command - matches WCGW Python's Command handling in _`execute_bash`
async fn execute_command(
    bash_state: &mut BashState,
    command: &str,
    is_background: bool,
    allow_multi: bool,
    timeout_s: f64,
) -> Result<String> {
    // wcgw strips a trailing `| tail` before anything else (model_validator).
    let stripped_command = strip_tail_pipe(command);
    let command = stripped_command.as_str();
    debug!("Processing Command action: {command:?} (allow_multi={allow_multi})");

    // Check mode permissions - matches WCGW Python bash_command_mode check
    if !bash_state.is_command_allowed(command) {
        error!("Command '{}' not allowed in current mode", command);
        return Err(WinxError::CommandNotAllowed(
            "Error: BashCommand not allowed in current mode".to_string(),
        ));
    }

    // Single-statement guard (wcgw parity). Callers can opt out via
    // `allow_multi: true` when they knowingly want to chain commands
    // without wrapping in `bash -lc '...'`.
    let command = command.trim();
    if !allow_multi {
        // The `bash -n -c` fallback inside the parser spawns a shell; only allow
        // that probe in trusted (wcgw) mode. In restricted modes tree-sitter is
        // the sole arbiter so we never shell out to vet a command.
        let allow_shell_probe = matches!(bash_state.mode, crate::types::Modes::Wcgw);
        crate::utils::bash_parser::assert_single_statement(command, allow_shell_probe)?;
    }

    // If background execution requested, start new shell - matches WCGW Python is_background handling
    if is_background {
        return execute_in_background(bash_state, command, timeout_s).await;
    }

    // Check if a command is already running - matches WCGW Python state check
    {
        let bash_guard = bash_state.pty_shell.lock().await;

        if let Some(ref bash) = *bash_guard {
            if bash.command_running {
                return Err(WinxError::CommandExecutionError(WAITING_INPUT_MESSAGE.to_string()));
            }
        }
    }

    // Initialize bash if needed
    if bash_state.pty_shell.lock().await.is_none() {
        bash_state
            .init_pty_shell()
            .await
            .map_err(|e| WinxError::CommandExecutionError(format!("Failed to init bash: {e}")))?;
    }

    // Clear prompt before sending - matches WCGW Python clear_to_run.
    // Drain any leftover output and, if the shell still looks busy, send
    // Ctrl-C so the new command lands on a fresh prompt instead of being
    // appended to whatever was hanging on stdin.
    {
        let needs_reset = {
            // Only when a shell exists. clear_to_run_async drains/interrupts WITHOUT
            // holding the lock across a blocking sleep (was bash.clear_to_run, which
            // slept up to DEFAULT_TIMEOUT seconds inside the tokio mutex).
            if bash_state.pty_shell.lock().await.is_some() {
                if clear_to_run_async(&bash_state.pty_shell, DEFAULT_TIMEOUT).await {
                    false
                } else {
                    warn!("clear_to_run: shell still busy after Ctrl-C, resetting it");
                    true
                }
            } else {
                false
            }
        };
        // wcgw parity: a shell that won't return to a prompt even after Ctrl-C is
        // recreated, so the new command lands on a fresh prompt instead of being
        // appended to a hung shell. init_pty_shell rebuilds at the same cwd/mode.
        if needs_reset {
            if let Err(e) = bash_state.init_pty_shell().await {
                warn!("Failed to reset shell after clear_to_run: {e}");
            }
        }
    }

    // Send command in chunks of 64 characters - matches WCGW Python exactly
    let scratch_root = bash_state.workspace_root.clone();
    {
        let mut bash_guard = bash_state.pty_shell.lock().await;

        let bash = bash_guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;

        bash.output_buffer.clear();
        bash.output_truncated = false;
        // Offload an over-long output's dropped head to a scratch file under the
        // current workspace so the agent can recover it via ReadFiles.
        bash.reset_scratch();
        bash.set_scratch_root(&scratch_root);
        // Mirror send_command's full reset. This foreground path hand-rolls the
        // field mutation (it chunks the send for WCGW parity) and used to drop
        // these two: a stale exit code or dedup hash would then leak into the
        // next status_check — wrong `exit code`, or a false "no new output".
        bash.last_exit_code = None;
        bash.last_returned_hash = None;
        // Send in chunks - matches WCGW Python: for i in range(0, len(command), 64)
        send_utf8_in_byte_chunks(bash, command, COMMAND_CHUNK_SIZE)?;

        // Send linesep to execute - matches WCGW Python bash_state.send(bash_state.linesep, ...)
        bash.send_special_key("Enter").map_err(|e| {
            WinxError::CommandExecutionError(format!("Failed to send newline: {e}"))
        })?;

        bash.last_command = command.to_string();
        bash.command_running = true;
    }

    // Wait for output with WCGW-style patience handling
    let shell_arc = bash_state.pty_shell.clone();
    wait_for_output(bash_state, &shell_arc, timeout_s, false, None, false).await
}

/// Wait for command output with WCGW-style patience handling - matches WCGW Python expect/wait logic.
///
/// Non-blocking drain of queued shell output under the lock; returns whether the
/// command has completed. The lock is released before returning so the caller can
/// `await` a poll interval without pinning the executor — unlike the old
/// `read_output`, which slept (blocking) inside this lock.
async fn poll_shell(shell_arc: &SharedPtyShell) -> bool {
    let mut guard = shell_arc.lock().await;
    match guard.as_mut() {
        Some(bash) => bash.poll_output_nonblocking(),
        None => true,
    }
}

/// Snapshot the shell's accumulated output buffer in one lock acquisition.
async fn snapshot_shell(shell_arc: &SharedPtyShell) -> String {
    let mut guard = shell_arc.lock().await;
    guard.as_mut().map_or_else(String::new, |bash| bash.output_snapshot())
}

/// Poll-drain the shell until its prompt returns or `budget_secs` elapses; returns
/// whether the prompt was seen (i.e. the shell is idle). The lock is released
/// between polls and the wait is awaited, so the executor is never blocked.
async fn drain_until_prompt(shell_arc: &SharedPtyShell, budget_secs: f64) -> bool {
    let start = Instant::now();
    loop {
        if poll_shell(shell_arc).await {
            return true;
        }
        if start.elapsed().as_secs_f64() >= budget_secs {
            return false;
        }
        sleep(Duration::from_millis(POLL_INTERVAL_MS)).await;
    }
}

/// Async replacement for `PtyShell::clear_to_run`: drain leftover output, and if
/// the shell still looks busy, send Ctrl-C and re-drain — returning whether the
/// shell reached an idle prompt. The old sync method ran `read_output` (a blocking
/// `thread::sleep` loop, up to `DEFAULT_TIMEOUT` seconds) WHILE the caller held the
/// tokio mutex, pinning the worker on every foreground command. This holds the
/// lock only for the instantaneous poll/interrupt, never across a wait.
async fn clear_to_run_async(shell_arc: &SharedPtyShell, max_wait_secs: f64) -> bool {
    // Phase 1: a quick drain — return the moment the prompt is already back.
    if drain_until_prompt(shell_arc, max_wait_secs.min(0.5)).await {
        return true;
    }
    // Still busy: interrupt (lock held only for the send), then re-drain.
    {
        let mut guard = shell_arc.lock().await;
        if let Some(bash) = guard.as_mut() {
            if let Err(e) = bash.send_interrupt() {
                warn!("clear_to_run: failed to send Ctrl-C: {e}");
            }
        }
    }
    drain_until_prompt(shell_arc, max_wait_secs).await
}

/// `shell_arc` selects which shell to read from (main shell or a bg shell handle).
async fn wait_for_output(
    bash_state: &mut BashState,
    shell_arc: &SharedPtyShell,
    timeout_s: f64,
    is_bg: bool,
    bg_id: Option<&str>,
    is_status_check: bool,
) -> Result<String> {
    let start = Instant::now();
    let wait = timeout_s.min(TIMEOUT_WHILE_OUTPUT);
    let mut last_pending_output = String::new();
    let mut complete = false;

    // Adaptive polling instead of a blind sleep. wcgw sleeps the full `wait`
    // budget before reading even once, so a `pwd` that finishes in 10ms still
    // costs ~5s. Instead we read in short slices and return the moment the
    // prompt comes back (`read_output` already exits early on prompt + drain),
    // dropping fast-command latency from seconds to ~100ms. Long-running
    // commands still consume the whole budget, since we loop until `complete`
    // or `wait` elapses — identical upper-bound behavior, far snappier floor.
    // Drain non-blocking, release the lock, then `await` the poll interval. The
    // old `read_output(slice)` slept up to ~0.5s of blocking `thread::sleep` WHILE
    // holding this tokio mutex — pinning the worker thread (starving every other
    // task on it) and the shell lock the whole time. poll + `await` frees both.
    let mut output = String::new();
    loop {
        if start.elapsed().as_secs_f64() >= wait {
            break;
        }
        complete = poll_shell(shell_arc).await;
        if complete {
            break;
        }
        sleep(Duration::from_millis(POLL_INTERVAL_MS)).await;
    }
    // Post-prompt grace drain (awaited, no lock held), then one buffer snapshot —
    // the old read_output cloned the whole buffer on every slice (performance-2).
    if complete {
        sleep(Duration::from_millis(POST_PROMPT_DRAIN_MS)).await;
        poll_shell(shell_arc).await;
    }
    output = snapshot_shell(shell_arc).await;

    // If not complete and this is a status check, use WCGW-style patience waiting.
    //
    // Treat `timeout_s` (== caller's `wait_for_seconds`, capped at
    // `TIMEOUT_WHILE_OUTPUT`) as the hard upper bound on the TOTAL wall-clock
    // spent inside this call. wcgw computes `remaining = TIMEOUT_WHILE_OUTPUT
    // - wait`, which makes a 2-second `wait_for_seconds` block for almost 20s
    // on a TUI that keeps emitting spinner frames. We diverge from wcgw here
    // because driving agents expect their wait budget to be respected.
    if !complete && is_status_check {
        let budget_secs = timeout_s.min(TIMEOUT_WHILE_OUTPUT);
        let iter_wait_secs = 0.5_f64;
        let mut patience = OUTPUT_WAIT_PATIENCE;

        let incremental = wcgw_incremental_text(&output, &last_pending_output);
        if incremental.is_empty() {
            patience -= 1;
        }

        let mut last_incremental = incremental;

        while start.elapsed().as_secs_f64() < budget_secs && patience > 0 {
            let remaining = (budget_secs - start.elapsed().as_secs_f64()).max(0.0);
            if remaining < 0.1 {
                break;
            }
            sleep(Duration::from_secs_f64(iter_wait_secs.min(remaining))).await;

            // The patience `sleep(iter_wait_secs)` above already elapsed, so the
            // last half-second of output is queued — drain it non-blocking (was
            // read_output(0.5) holding the lock across its own internal sleep).
            let done = poll_shell(shell_arc).await;
            let new_output = snapshot_shell(shell_arc).await;

            if done {
                complete = true;
                output = new_output;
                break;
            }

            // Check if output changed - matches WCGW Python patience logic
            let new_incremental = wcgw_incremental_text(&new_output, &last_pending_output);
            if new_incremental == last_incremental {
                patience -= 1;
            } else {
                patience = OUTPUT_WAIT_PATIENCE; // Reset patience on new output
            }
            last_incremental = new_incremental;

            output = new_output;
        }

        if !complete {
            // Update pending output - matches WCGW Python bash_state.set_pending(text)
            last_pending_output = output.clone();
        }
    }

    if complete {
        if let Some(cwd) = extract_prompt_cwd(&output) {
            bash_state.cwd = cwd;
        }
    }

    // Process output through terminal emulation - matches WCGW Python _incremental_text
    let rendered = wcgw_incremental_text(&output, &last_pending_output);

    // Conscious compression: collapse mechanical repetition (identical line runs,
    // blank-line blocks) before truncating, to save tokens without dropping any
    // unique context. Falls back to the raw text when nothing is safe to collapse.
    let rendered = {
        let before_lines = rendered.lines().count();
        match crate::utils::output_compress::compress_output(&rendered) {
            Some(compressed) => {
                debug!(
                    from_lines = before_lines,
                    to_lines = compressed.lines().count(),
                    "winx collapsed mechanical repetition in shell output"
                );
                compressed
            }
            None => rendered,
        }
    };

    // Truncate if needed - matches WCGW Python token truncation
    let rendered = truncate_to_token_budget(&rendered, MAX_OUTPUT_TOKENS).into_owned();

    // Calculate running duration for status
    let running_for =
        if complete { None } else { Some(format!("{} seconds", start.elapsed().as_secs())) };

    // Surface the just-finished command's exit code (parsed from the prompt
    // marker) so the agent sees failure without grepping stderr.
    // Exit code (parsed from the prompt) plus a pointer to any offloaded output
    // scratch file, read in one lock acquisition.
    let (exit_code, scratch_pointer) = read_completion_extras(shell_arc, complete).await;

    // Add status - matches WCGW Python get_status
    let status = get_status(bash_state, is_bg, bg_id, !complete, running_for.as_deref(), exit_code);
    Ok(format!("{rendered}{status}{scratch_pointer}"))
}

/// Pull the just-finished command's exit code and, if its output overflowed and
/// the dropped head was offloaded, a pointer message to the scratch file - in a
/// single lock acquisition so callers don't lock the shell twice.
async fn read_completion_extras(
    shell_arc: &SharedPtyShell,
    complete: bool,
) -> (Option<i32>, String) {
    let guard = shell_arc.lock().await;
    let Some(shell) = guard.as_ref() else {
        return (None, String::new());
    };
    let exit_code = if complete { shell.last_exit_code } else { None };
    let pointer = match (shell.output_truncated, shell.scratch_path()) {
        (true, Some(path)) => format!(
            "\n\n---\n[Output was truncated to fit context. The earlier (dropped) output was \
             saved to:\n{}\nRead it with ReadFiles or grep it via BashCommand.]\n---",
            path.display()
        ),
        _ => String::new(),
    };
    (exit_code, pointer)
}

/// Render the final cached output of an exited background shell.
///
/// `status_check` is allowed to "consume" the tombstone and return the trailing
/// output exactly once. Send-style actions (`send_text`, `send_specials`,
/// `send_ascii`) cannot interact with a dead shell, so we return an explicit
/// error that still includes the captured output so the agent can recover state.
fn finalize_tombstone(
    cwd: &Path,
    id: &str,
    tombstone: ExitedShellInfo,
    action: &BashCommandAction,
) -> Result<String> {
    let ExitedShellInfo { last_command, final_output, .. } = tombstone;
    match action {
        // A dead shell's turn is over: Screen/WaitForTurn hand back the final
        // captured output as the snapshot, exactly like a status check.
        BashCommandAction::StatusCheck { .. }
        | BashCommandAction::Screen { .. }
        | BashCommandAction::WaitForTurn { .. } => {
            let rendered = wcgw_incremental_text(&final_output, "");
            let rendered = truncate_to_token_budget(&rendered, MAX_OUTPUT_TOKENS).into_owned();
            // Build a compact status block matching `get_status` for a finished bg shell.
            let mut status = "\n\n---\n\n".to_string();
            let _ = writeln!(status, "bg_command_id = {id}");
            status.push_str("status = process exited\n");
            let _ = writeln!(status, "cwd = {}", cwd.display());
            Ok(format!("{rendered}{}", status.trim_end()))
        }
        BashCommandAction::SendText { .. }
        | BashCommandAction::SendSpecials { .. }
        | BashCommandAction::SendAscii { .. } => Err(WinxError::CommandExecutionError(format!(
            "Background shell {id} already exited (last command: {last_command}).\nFinal captured output:\n{final_output}"
        ))),
        BashCommandAction::Command { .. } => {
            // We only enter `finalize_tombstone` from the bg routing path, which
            // never matches Command. Treat this as a programmer error.
            unreachable!("finalize_tombstone called for non-bg action")
        }
    }
}

/// Execute a status check - matches WCGW Python's `StatusCheck` handling.
///
/// New behavior (v0.2.308):
/// - Deduplicates against the last response by fingerprint; when nothing
///   changed and `verbose=false`, returns a compact "no new output" payload
///   instead of resending the same screen.
/// - Optional `scrollback_lines` pulls bounded history from the `PtyShell`
///   ringbuffer so agents can reorient after a long pause.
async fn execute_status_check(
    bash_state: &mut BashState,
    bg_shell: Option<SharedPtyShell>,
    is_bg: bool,
    bg_id: Option<&str>,
    timeout_s: f64,
    scrollback_lines: Option<usize>,
    verbose: bool,
) -> Result<String> {
    debug!("Processing StatusCheck action (verbose={verbose}, scrollback={scrollback_lines:?})");

    // Pick the shell we're going to inspect: bg shell when bg_command_id was provided,
    // otherwise fall back to the main interactive shell.
    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());

    // Check if there's a running command - matches WCGW Python state check
    let is_running = {
        let guard = shell_arc.lock().await;
        if let Some(ref bash) = *guard {
            bash.command_running
        } else {
            false
        }
    };

    // If no command running and not background, return error - matches WCGW Python
    if !is_running && !is_bg {
        let mut manager = lock_bg_manager();
        let error = format!(
            "No command is currently running, so there's nothing to check. The previous \
             command already finished and its output was returned when it completed. Start a \
             new command, or pass a bg_command_id if you launched one in the background.\n{}",
            manager.get_running_info()
        );
        return Err(WinxError::CommandExecutionError(error));
    }

    // Read output with patience handling - this IS a status check
    let response = wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, true).await?;

    // Inter-call dedup: hash only the response *body* (the chunk before the
    // `\n\n---\n` status footer). The footer contains a live "running for"
    // counter that would otherwise defeat the comparison.
    let body = response.split("\n\n---\n").next().unwrap_or(&response);
    if !verbose && scrollback_lines.is_none() {
        let mut guard = shell_arc.lock().await;
        if let Some(bash) = guard.as_mut() {
            let fingerprint = PtyShell::fingerprint(body);
            if Some(fingerprint) == bash.last_returned_hash {
                let status = get_status(bash_state, is_bg, bg_id, is_running, None, None);
                return Ok(format!("no new output since last check{status}"));
            }
            bash.last_returned_hash = Some(fingerprint);
        }
    } else if !verbose {
        // Still record the hash so subsequent non-scrollback calls can dedup.
        let mut guard = shell_arc.lock().await;
        if let Some(bash) = guard.as_mut() {
            bash.last_returned_hash = Some(PtyShell::fingerprint(body));
        }
    }

    // Optional scrollback prefix — only ever pulled when the caller asks for it.
    if let Some(lines) = scrollback_lines {
        if lines > 0 {
            let scrollback = {
                let guard = shell_arc.lock().await;
                guard.as_ref().map(|s| s.collect_scrollback(lines)).unwrap_or_default()
            };
            if !scrollback.is_empty() {
                let count = scrollback.lines().count();
                return Ok(format!(
                    "--- scrollback ({count} lines) ---\n{scrollback}\n--- latest ---\n{response}"
                ));
            }
        }
    }

    Ok(response)
}

/// Execute `Screen` — a stable, point-in-time snapshot of a shell's live
/// terminal screen (consolidated grid, ANSI stripped). No waiting, no dedup;
/// the foundation for reading an interactive TUI's current frame.
async fn execute_screen(
    bash_state: &BashState,
    bg_shell: Option<SharedPtyShell>,
    is_bg: bool,
    bg_id: Option<&str>,
    lines: Option<usize>,
    diff: bool,
) -> Result<String> {
    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
    let max_lines = lines.unwrap_or(0);

    if diff {
        let (update, is_running, in_alt, cursor) = {
            let guard = shell_arc.lock().await;
            match guard.as_ref() {
                Some(bash) => (
                    bash.live_snapshot_diff(max_lines, SCREEN_DIFF_THRESHOLD),
                    bash.command_running,
                    bash.live_in_alt_screen(),
                    bash.live_cursor_position(),
                ),
                None => (ScreenUpdate::Full(Vec::new()), false, false, (0, 0)),
            }
        };
        let (crow, ccol) = cursor;
        let alt = if in_alt { " [alt-screen]" } else { "" };
        let status = get_status(bash_state, is_bg, bg_id, is_running, None, None);
        let body = match update {
            ScreenUpdate::Unchanged => "(no change since last screen)".to_string(),
            ScreenUpdate::Diff(changed) => {
                let mut out = String::from("(changed lines only)\n");
                for (row, content) in changed {
                    let _ = writeln!(out, "{row:>4}: {content}");
                }
                out
            }
            ScreenUpdate::Full(snap) => {
                let joined = snap.join("\n");
                if joined.trim().is_empty() {
                    "(screen is empty)".to_string()
                } else {
                    truncate_to_token_budget(&joined, MAX_OUTPUT_TOKENS).into_owned()
                }
            }
        };
        return Ok(format!(
            "--- live screen{alt} [cursor row={crow} col={ccol}] (diff) ---\n{body}{status}"
        ));
    }

    let (snapshot, is_running, in_alt, cursor) = {
        let guard = shell_arc.lock().await;
        match guard.as_ref() {
            Some(bash) => (
                bash.live_snapshot(max_lines),
                bash.command_running,
                bash.live_in_alt_screen(),
                bash.live_cursor_position(),
            ),
            None => (Vec::new(), false, false, (0, 0)),
        }
    };

    let joined = snapshot.join("\n");
    let body = if joined.trim().is_empty() {
        "(screen is empty)".to_string()
    } else {
        truncate_to_token_budget(&joined, MAX_OUTPUT_TOKENS).into_owned()
    };
    let alt = if in_alt { " [alt-screen]" } else { "" };
    let (crow, ccol) = cursor;
    let status = get_status(bash_state, is_bg, bg_id, is_running, None, None);
    Ok(format!("--- live screen{alt} [cursor row={crow} col={ccol}] ---\n{body}{status}"))
}

/// Why [`execute_wait_for_turn`] should stop polling, or `None` to keep waiting.
///
/// Extracted as a pure function so the (subtle) exit logic is unit-testable
/// without driving a real PTY. `busy_for` is how long we've read `Busy`
/// *continuously*: a TUI that is actively working never holds a stable screen
/// (its spinner repaints every frame), so we confirm `Busy` by elapsed duration,
/// not by `stable_for` — that was exactly why a busy child used to pin the caller
/// for the whole `hard_cap` (up to 600s).
#[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
fn wait_turn_outcome(
    state: crate::state::turn::TurnState,
    alive: bool,
    activity: bool,
    seen_busy: bool,
    stable_for: Duration,
    busy_for: Duration,
    settle: Duration,
    quiet: Duration,
    timed_out: bool,
    wait_through_busy: bool,
) -> Option<&'static str> {
    use crate::state::turn::TurnState;
    if !alive {
        return Some("exited");
    }
    let ready = match state {
        TurnState::Busy => false,
        // A short settle is enough once we saw it go Busy; otherwise wait the
        // full quiet window so a slow first token isn't read as "done".
        TurnState::AwaitingInput | TurnState::AwaitingApproval => {
            activity && stable_for >= if seen_busy { settle } else { quiet }
        }
        TurnState::Unknown => activity && stable_for >= quiet,
    };
    if ready {
        return Some("ready");
    }
    // Early-out on a confirmed-busy turn instead of blocking until the hard cap.
    // A settled `busy` reading is a valid answer on its own (the tool documents
    // `busy` as a return state); the caller can poll again to keep watching. This
    // is the fix for a parent that "waits forever" on a long-running child.
    if !wait_through_busy && state == TurnState::Busy && busy_for >= settle {
        return Some("busy");
    }
    if timed_out {
        return Some("timeout");
    }
    None
}

/// Execute `WaitForTurn` — wait for an interactive TUI's turn.
///
/// Polls the live screen, combining a per-app recognizer (claude/codex/auto)
/// with a generic quiescence window: the turn is "ready" when the recognizer
/// reports awaiting-input/approval (after a short settle) or, for an unknown
/// TUI, when the screen simply stops changing for `quiet`. By default it also
/// returns as soon as `Busy` is confirmed (see [`wait_turn_outcome`]); pass
/// `wait_through_busy` to block through busy until ready. Returns the stable
/// snapshot plus the detected state.
#[allow(clippy::too_many_arguments)]
async fn execute_wait_for_turn(
    bash_state: &BashState,
    bg_shell: Option<SharedPtyShell>,
    is_bg: bool,
    bg_id: Option<&str>,
    recognizer_hint: Option<&str>,
    quiet_ms: Option<u64>,
    timeout_seconds: Option<f32>,
    lines: Option<usize>,
    wait_through_busy: bool,
) -> Result<String> {
    use crate::state::turn::{recognizer_for, TurnState};

    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
    let recognizer = recognizer_for(recognizer_hint.unwrap_or("auto"));
    let quiet = Duration::from_millis(quiet_ms.unwrap_or(600).clamp(50, 10_000));
    let settle = quiet.min(Duration::from_millis(300));
    let hard_cap =
        Duration::from_secs_f64(f64::from(timeout_seconds.unwrap_or(30.0)).clamp(0.5, 600.0));
    let max_lines = lines.unwrap_or(0);
    let poll = Duration::from_millis(120);
    // Grace period so a freshly-prompted app has time to react before we'd
    // otherwise mistake the *pre-input* idle screen for a finished turn.
    let warmup = Duration::from_millis(2500);

    let start = Instant::now();
    let mut last_hash: Option<u64> = None;
    let mut initial_hash: Option<u64> = None;
    let mut stable_since = Instant::now();
    let mut seen_busy = false;
    let mut busy_since: Option<Instant> = None;

    loop {
        let (snapshot, in_alt, alive, running) = {
            let mut guard = shell_arc.lock().await;
            match guard.as_mut() {
                Some(bash) => (
                    bash.live_snapshot(max_lines),
                    bash.live_in_alt_screen(),
                    bash.is_alive(),
                    bash.command_running,
                ),
                None => (Vec::new(), false, false, false),
            }
        };

        let hash = PtyShell::fingerprint(&snapshot.join("\n"));
        if initial_hash.is_none() {
            initial_hash = Some(hash);
        }
        if Some(hash) != last_hash {
            last_hash = Some(hash);
            stable_since = Instant::now();
        }

        let state = recognizer.detect(&snapshot);
        if state == TurnState::Busy {
            seen_busy = true;
            if busy_since.is_none() {
                busy_since = Some(Instant::now());
            }
        } else {
            busy_since = None;
        }
        let busy_for = busy_since.map_or(Duration::ZERO, |since| since.elapsed());
        let stable_for = stable_since.elapsed();
        // Don't call it "done" until something actually happened since we began
        // waiting: the app went Busy, the screen changed from the first frame we
        // saw, or the warmup elapsed (instant reply / nothing to do).
        let activity = seen_busy || Some(hash) != initial_hash || start.elapsed() >= warmup;
        let timed_out = start.elapsed() >= hard_cap;
        if let Some(reason) = wait_turn_outcome(
            state,
            alive,
            activity,
            seen_busy,
            stable_for,
            busy_for,
            settle,
            quiet,
            timed_out,
            wait_through_busy,
        ) {
            let joined = snapshot.join("\n");
            let body = if joined.trim().is_empty() {
                "(screen is empty)".to_string()
            } else {
                truncate_to_token_budget(&joined, MAX_OUTPUT_TOKENS).into_owned()
            };
            let alt = if in_alt { " [alt-screen]" } else { "" };
            let header = format!(
                "--- turn: {} ({}, recognizer={}, waited {:.1}s){} ---",
                state.as_str(),
                reason,
                recognizer.name(),
                start.elapsed().as_secs_f64(),
                alt
            );
            let status = get_status(bash_state, is_bg, bg_id, running, None, None);
            return Ok(format!("{header}\n{body}{status}"));
        }

        tokio::time::sleep(poll).await;
    }
}

/// Execute `send_text` - matches WCGW Python's `SendText` handling
async fn execute_send_text(
    bash_state: &mut BashState,
    text: &str,
    submit: bool,
    bg_shell: Option<SharedPtyShell>,
    is_bg: bool,
    bg_id: Option<&str>,
    timeout_s: f64,
) -> Result<String> {
    debug!("Processing SendText action: {text:?} (submit={submit})");

    // Validate - matches WCGW Python
    if text.is_empty() {
        return Err(WinxError::CommandExecutionError(
            "Failure: send_text cannot be empty".to_string(),
        ));
    }

    // Get the target shell
    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());

    // Send text in chunks of 128 characters - matches WCGW Python exactly
    {
        let mut guard = shell_arc.lock().await;

        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;

        // Send in chunks - matches WCGW Python: for i in range(0, len(command_data.send_text), 128)
        send_utf8_in_byte_chunks(bash, text, TEXT_CHUNK_SIZE)?;
    }

    // Only submit when explicitly asked. The Enter goes as a separate, delayed
    // write so Ink TUIs (Claude Code) don't swallow a CR glued to the text — a
    // bare CR there is otherwise treated as a soft newline and never submits.
    if submit {
        submit_enter(&shell_arc).await?;
    }

    // Wait for output
    wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await
}

/// Execute `send_specials` - matches WCGW Python's `SendSpecials` handling exactly
async fn execute_send_specials(
    bash_state: &mut BashState,
    keys: &[SpecialKey],
    submit: bool,
    bg_shell: Option<SharedPtyShell>,
    is_bg: bool,
    bg_id: Option<&str>,
    timeout_s: f64,
) -> Result<String> {
    debug!("Processing SendSpecials action: {keys:?} (submit={submit})");

    // Validate - matches WCGW Python
    if keys.is_empty() {
        return Err(WinxError::CommandExecutionError(
            "Failure: send_specials cannot be empty".to_string(),
        ));
    }

    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
    let mut is_interrupt = false;

    {
        let mut guard = shell_arc.lock().await;

        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;

        // Send each special key - matches WCGW Python exactly
        for key in keys {
            match key {
                SpecialKey::KeyUp => {
                    // matches WCGW Python: bash_state.send("\033[A", ...)
                    bash.send_special_key("KeyUp").map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send KeyUp: {e}"))
                    })?;
                }
                SpecialKey::KeyDown => {
                    // matches WCGW Python: bash_state.send("\033[B", ...)
                    bash.send_special_key("KeyDown").map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send KeyDown: {e}"))
                    })?;
                }
                SpecialKey::KeyLeft => {
                    // matches WCGW Python: bash_state.send("\033[D", ...)
                    bash.send_special_key("KeyLeft").map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send KeyLeft: {e}"))
                    })?;
                }
                SpecialKey::KeyRight => {
                    // matches WCGW Python: bash_state.send("\033[C", ...)
                    bash.send_special_key("KeyRight").map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send KeyRight: {e}"))
                    })?;
                }
                SpecialKey::Enter => {
                    // matches WCGW Python: bash_state.send("\x0d", ...) - carriage return
                    bash.send_special_key("Enter").map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send Enter: {e}"))
                    })?;
                }
                SpecialKey::CtrlC => {
                    // matches WCGW Python: bash_state.sendintr()
                    bash.send_interrupt().map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send interrupt: {e}"))
                    })?;
                    is_interrupt = true;
                }
                SpecialKey::CtrlD => {
                    // matches WCGW Python: bash_state.sendintr() - same as Ctrl+C in WCGW
                    bash.send_eof().map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send Ctrl+D: {e}"))
                    })?;
                    is_interrupt = true;
                }
                SpecialKey::CtrlZ => {
                    // Ctrl+Z = SIGTSTP (suspend) - ASCII 0x1a
                    bash.send_suspend().map_err(|e| {
                        WinxError::CommandExecutionError(format!("Failed to send Ctrl+Z: {e}"))
                    })?;
                }
            }
        }
    }

    // Submit as a separate, slightly-delayed write (see `submit_enter`) so an
    // Ink TUI doesn't drop the CR.
    if submit {
        submit_enter(&shell_arc).await?;
    }

    // NOTE: wcgw treats a bare Enter as a status check and applies its
    // patience loop. We deliberately diverge: for a driving agent (e.g.,
    // pushing Enter to submit text in a TUI) the patience loop swallows the
    // immediate response. Callers that want patience semantics should use the
    // explicit `status_check` action instead.

    // Wait for output
    let mut output =
        wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await?;

    // Add interrupt failure message if still running - matches WCGW Python exactly
    if is_interrupt && output.contains("status = still running") {
        output.push_str("\n---\n----\nFailure interrupting.\nYou may want to try Ctrl-c again or program specific exit interactive commands.\n");
    }

    Ok(output)
}

/// Execute `send_ascii` - matches WCGW Python's `SendAscii` handling
async fn execute_send_ascii(
    bash_state: &mut BashState,
    ascii_codes: &[u8],
    submit: bool,
    bg_shell: Option<SharedPtyShell>,
    is_bg: bool,
    bg_id: Option<&str>,
    timeout_s: f64,
) -> Result<String> {
    debug!("Processing SendAscii action: {ascii_codes:?} (submit={submit})");

    // Validate - matches WCGW Python
    if ascii_codes.is_empty() {
        return Err(WinxError::CommandExecutionError(
            "Failure: send_ascii cannot be empty".to_string(),
        ));
    }

    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
    let mut is_interrupt = false;

    {
        let mut guard = shell_arc.lock().await;

        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;

        // Send each ASCII code - matches WCGW Python
        for &code in ascii_codes {
            // matches WCGW Python: bash_state.send(chr(ascii_char), ...)
            bash.send_bytes(&[code]).map_err(|e| {
                WinxError::CommandExecutionError(format!("Failed to write ASCII code: {e}"))
            })?;

            // Check for interrupt - matches WCGW Python: if ascii_char == 3: is_interrupt = True
            if code == 3 {
                is_interrupt = true;
            }
        }
    }

    // Submit as a separate, slightly-delayed write (see `submit_enter`) so an
    // Ink TUI doesn't drop the CR.
    if submit {
        submit_enter(&shell_arc).await?;
    }

    // Same divergence from wcgw as in `execute_send_specials`: send_ascii [10]
    // or [13] is treated as a direct write, not a status check. Callers that
    // need patience-aware reads should use `status_check`.

    // Wait for output
    let mut output =
        wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await?;

    // Add interrupt failure message if still running - matches WCGW Python
    if is_interrupt && output.contains("status = still running") {
        output.push_str("\n---\n----\nFailure interrupting.\nYou may want to try Ctrl-c again or program specific exit interactive commands.\n");
    }

    Ok(output)
}

/// Execute command in background - matches WCGW Python's `is_background` handling
async fn execute_in_background(
    bash_state: &mut BashState,
    command: &str,
    timeout_s: f64,
) -> Result<String> {
    debug!("Executing command in background: {}", command);

    // Start a new background shell - matches WCGW Python bash_state.start_new_bg_shell
    let restricted_mode =
        matches!(bash_state.bash_command_mode.bash_mode, crate::types::BashMode::RestrictedMode);

    // Build the shell OFF the tokio worker AND outside the manager lock:
    // PtyShell::new forks+execs and blocks ~300ms on prompt init. The old
    // start_new_shell did all of that under the std::Mutex on the executor thread.
    let bg_id = {
        let cwd = bash_state.cwd.clone();
        let shell = tokio::task::spawn_blocking(move || PtyShell::new(&cwd, restricted_mode))
            .await
            .map_err(|e| {
                WinxError::CommandExecutionError(format!("bg shell init task failed: {e}"))
            })?
            .map_err(|e| {
                WinxError::CommandExecutionError(format!("Failed to start background shell: {e}"))
            })?;
        lock_bg_manager().register_shell(shell)
    };

    // Get the shell
    let shell_arc = {
        let manager = lock_bg_manager();
        manager.get_shell(&bg_id).ok_or_else(|| {
            WinxError::CommandExecutionError("Failed to get background shell".to_string())
        })?
    };

    // Send command via the same PTY path used by foreground execute_command.
    let scratch_root = bash_state.workspace_root.clone();
    {
        let mut guard = shell_arc.lock().await;
        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
        // Offload an over-long bg output's dropped head too (send_command resets
        // the per-command scratch state; this points it at the workspace).
        bash.set_scratch_root(&scratch_root);
        bash.send_command(command).map_err(|e| {
            WinxError::CommandExecutionError(format!("Failed to send bg command: {e}"))
        })?;
    }
    debug!("bg[{}]: send_command returned, replying with bg_command_id", bg_id);

    let _ = timeout_s;
    let _ = shell_arc;
    Ok(get_status(bash_state, true, Some(&bg_id), true, None, None))
}

#[cfg(test)]
mod wait_turn_tests {
    use super::wait_turn_outcome;
    use crate::state::turn::TurnState;
    use std::time::Duration;

    const SETTLE: Duration = Duration::from_millis(300);
    const QUIET: Duration = Duration::from_millis(600);

    fn call(
        state: TurnState,
        busy_for: Duration,
        stable_for: Duration,
        seen_busy: bool,
        timed_out: bool,
        wait_through_busy: bool,
    ) -> Option<&'static str> {
        // `activity` is true in these cases (something happened) unless noted.
        wait_turn_outcome(
            state,
            true,
            true,
            seen_busy,
            stable_for,
            busy_for,
            SETTLE,
            QUIET,
            timed_out,
            wait_through_busy,
        )
    }

    #[test]
    fn confirmed_busy_returns_early_instead_of_blocking_to_timeout() {
        // The bug: a busy child used to pin the caller until hard_cap. Now a
        // busy reading held for >= settle returns "busy" with NO timeout.
        let out = call(TurnState::Busy, SETTLE, Duration::ZERO, true, false, false);
        assert_eq!(out, Some("busy"));
    }

    #[test]
    fn busy_not_yet_confirmed_keeps_waiting() {
        // Seen busy for less than settle (one-frame flicker): keep polling.
        let out =
            call(TurnState::Busy, Duration::from_millis(100), Duration::ZERO, true, false, false);
        assert_eq!(out, None);
    }

    #[test]
    fn wait_through_busy_blocks_through_busy_until_timeout() {
        // Opt-out preserves the old contract: busy never returns early...
        let out = call(TurnState::Busy, SETTLE * 10, Duration::ZERO, true, false, true);
        assert_eq!(out, None);
        // ...only the hard cap ends it.
        let out = call(TurnState::Busy, SETTLE * 10, Duration::ZERO, true, true, true);
        assert_eq!(out, Some("timeout"));
    }

    #[test]
    fn awaiting_input_after_busy_is_ready_on_short_settle() {
        let out = call(TurnState::AwaitingInput, Duration::ZERO, SETTLE, true, false, false);
        assert_eq!(out, Some("ready"));
    }

    #[test]
    fn awaiting_input_without_prior_busy_needs_full_quiet() {
        // No prior busy: a short settle is not enough, must wait the quiet window.
        let short = call(TurnState::AwaitingInput, Duration::ZERO, SETTLE, false, false, false);
        assert_eq!(short, None);
        let full = call(TurnState::AwaitingInput, Duration::ZERO, QUIET, false, false, false);
        assert_eq!(full, Some("ready"));
    }

    #[test]
    fn dead_shell_reports_exited_even_if_busy() {
        let out = wait_turn_outcome(
            TurnState::Busy,
            false,
            true,
            true,
            Duration::ZERO,
            SETTLE,
            SETTLE,
            QUIET,
            false,
            false,
        );
        assert_eq!(out, Some("exited"));
    }

    #[test]
    fn nothing_happening_keeps_waiting() {
        let out = call(TurnState::Unknown, Duration::ZERO, Duration::ZERO, false, false, false);
        assert_eq!(out, None);
    }
}

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

    #[test]
    fn strips_trailing_tail_by_default() {
        assert_eq!(strip_tail_pipe_impl("seq 1 5 | tail -2", false), "seq 1 5");
        assert_eq!(strip_tail_pipe_impl("cat log | tail -n 20", false), "cat log");
        assert_eq!(strip_tail_pipe_impl("cat log | tail", false), "cat log");
        assert_eq!(strip_tail_pipe_impl("ls -la|tail -5", false), "ls -la");
    }

    #[test]
    fn keeps_command_without_trailing_tail() {
        // tail not at the end, or piped further, must be left alone.
        assert_eq!(strip_tail_pipe_impl("tail -f log | grep err", false), "tail -f log | grep err");
        assert_eq!(strip_tail_pipe_impl("echo hi", false), "echo hi");
        assert_eq!(
            strip_tail_pipe_impl("cat a | tail -5 | wc -l", false),
            "cat a | tail -5 | wc -l"
        );
    }

    #[test]
    fn keep_mode_preserves_tail_pipe() {
        // WINX_KEEP_TAIL_PIPE behavior: command passes through untouched.
        assert_eq!(strip_tail_pipe_impl("seq 1 5 | tail -2", true), "seq 1 5 | tail -2");
        assert_eq!(strip_tail_pipe_impl("cat log | tail -n 20", true), "cat log | tail -n 20");
    }
}