codewhale-tui 0.8.64

Terminal UI for open-source and open-weight coding models
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
use super::{
    ASSISTANT_GLYPH, ExecCell, ExecSource, GenericToolCell, HistoryCell, PlanUpdateCell,
    REASONING_CURSOR, REASONING_OPENER, REASONING_RAIL, TOOL_RUNNING_SYMBOLS,
    TOOL_STATUS_SYMBOL_MS, ToolCell, ToolStatus, TranscriptRenderOptions, USER_GLYPH,
    assistant_label_style_for, extract_reasoning_summary, render_thinking,
    running_status_label_with_elapsed,
};
use crate::deepseek_theme::Theme;
use crate::models::{ContentBlock, Message};
use crate::palette;
use crate::tools::plan::{PlanSnapshot, StepStatus};
use ratatui::style::Modifier;
use std::time::{Duration, Instant};

// ---- elapsed-seconds badge for long-running tools ----
//
// Below 3s the label stays "running" — quick reads/greps shouldn't
// visually churn. From 3s onward the badge appears and ticks each
// second so the user can tell the call hasn't hung.
// ---- #423 spillover-path UI annotation ----
//
// When a tool result carries a `spillover_path` (set by the
// tool-routing layer when the tool's `metadata.spillover_path` is
// populated), the live render appends a one-line muted hint
// pointing at the file. Transcript-mode replay leaves the hint
// off because the full output is already inline.

#[test]
fn render_spillover_annotation_shows_path() {
    use std::path::PathBuf;
    let cell = GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Success,
        input_summary: Some("cmd: cargo build --release".to_string()),
        output: Some("very large output...".to_string()),
        prompts: None,
        spillover_path: Some(PathBuf::from(
            "/Users/dev/.deepseek/tool_outputs/call-abc12.txt",
        )),
        output_summary: None,
        is_diff: false,
    };
    let lines = cell.lines_with_mode(120, true, super::RenderMode::Live);
    let joined: String = lines
        .iter()
        .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
        .collect();
    assert!(
        joined.contains("read done · cmd: cargo build --release"),
        "expected compact live summary: {joined:?}"
    );
    assert!(
        !joined.contains("full output:"),
        "spillover paths stay out of compact live rows: {joined:?}"
    );
}

#[test]
fn render_spillover_annotation_omitted_in_transcript_mode() {
    use std::path::PathBuf;
    // Transcript mode is for replay; the full output is already
    // inline so the annotation would just be redundant.
    let cell = GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Success,
        input_summary: None,
        output: Some("output".to_string()),
        prompts: None,
        spillover_path: Some(PathBuf::from("/tmp/spill.txt")),
        output_summary: None,
        is_diff: false,
    };
    let lines = cell.lines_with_mode(120, true, super::RenderMode::Transcript);
    let joined: String = lines
        .iter()
        .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
        .collect();
    assert!(
        !joined.contains("full output:"),
        "annotation should be omitted in transcript mode: {joined:?}"
    );
}

#[test]
fn render_spillover_annotation_omitted_when_no_path_set() {
    // The common case: most tool results don't trigger spillover.
    let cell = GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Success,
        input_summary: None,
        output: Some("contents".to_string()),
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    };
    let lines = cell.lines_with_mode(80, true, super::RenderMode::Live);
    let joined: String = lines
        .iter()
        .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
        .collect();
    assert!(!joined.contains("full output:"), "{joined:?}");
}

#[test]
fn render_spillover_annotation_truncates_to_width() {
    use std::path::PathBuf;
    let long_path = "/Users/dev/.deepseek/tool_outputs/this-is-a-very-long-tool-call-id-that-will-not-fit-in-narrow-widths.txt";
    let cell = GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Success,
        input_summary: None,
        output: Some("output".to_string()),
        prompts: None,
        spillover_path: Some(PathBuf::from(long_path)),
        output_summary: None,
        is_diff: false,
    };
    let lines = cell.lines_with_mode(40, true, super::RenderMode::Live);
    let rendered: String = lines
        .iter()
        .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref()))
        .collect();
    assert!(
        !rendered.contains("full output:"),
        "compact live rows should omit spillover annotations: {rendered:?}"
    );
}

#[test]
fn activity_group_renders_as_single_metadata_line() {
    let cell = GenericToolCell {
        name: "activity_group".to_string(),
        status: ToolStatus::Success,
        input_summary: Some("Explored 2 files, 1 search".to_string()),
        output: None,
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    };

    let lines = cell.lines_with_mode(120, true, super::RenderMode::Live);
    let joined: String = lines
        .iter()
        .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref()))
        .collect();

    assert_eq!(lines.len(), 1);
    assert_eq!(joined, "Explored 2 files, 1 search");
    assert!(!joined.contains("activity_group"));
}

// ---- Compact agent rendering ----
//
// The DelegateCard owns live state for spawned sub-agents; the
// generic tool block previously duplicated that signal at 3-4 lines
// per spawn. In live mode we now render a single compact line that
// points at the spawned agent id; transcript-mode replay keeps the
// full block so debug history is intact.

#[test]
fn extract_agent_id_pulls_id_from_json_output() {
    let output =
        r#"{"agent_id": "agent-abc12", "nickname": "Beluga", "model": "deepseek-v4-flash"}"#;
    assert_eq!(super::extract_agent_id(output), Some("agent-abc12"));
}

#[test]
fn extract_agent_id_handles_extra_whitespace() {
    let output = r#"{
        "agent_id"   :    "agent-xyz",
        "model": "x"
    }"#;
    assert_eq!(super::extract_agent_id(output), Some("agent-xyz"));
}

#[test]
fn extract_agent_id_returns_none_when_missing() {
    let output = r#"{"nickname": "Orca", "model": "x"}"#;
    assert!(super::extract_agent_id(output).is_none());
    assert!(super::extract_agent_id("(not json)").is_none());
    assert!(super::extract_agent_id("").is_none());
}

#[test]
fn extract_agent_id_returns_none_for_empty_id() {
    let output = r#"{"agent_id": "", "model": "x"}"#;
    assert!(super::extract_agent_id(output).is_none());
}

#[test]
fn agent_renders_single_compact_line_in_live_mode() {
    let cell = GenericToolCell {
        name: "agent".to_string(),
        status: ToolStatus::Running,
        input_summary: Some("prompt: do thing".to_string()),
        output: Some(
            r#"{"agent_id": "agent-abc12", "nickname": "Beluga", "model": "deepseek-v4-flash"}"#
                .to_string(),
        ),
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    };
    let lines = cell.lines_with_mode(80, true, super::RenderMode::Live);
    // One header line, no details/args/output expansion.
    assert_eq!(lines.len(), 1, "expected exactly 1 line, got {lines:?}");
    let rendered: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
    // Header carries the agent id and the running status.
    assert!(
        rendered.contains("agent-abc12"),
        "expected agent id in header: {rendered:?}"
    );
    assert!(
        rendered.contains("running"),
        "expected status in header: {rendered:?}"
    );
    // No verbose `args:` / `name:` rows.
    assert!(
        !rendered.contains("args"),
        "args should be hidden: {rendered:?}"
    );
}

#[test]
fn agent_pending_render_uses_placeholder_id() {
    // No output yet → use the … placeholder so the user still sees a
    // header line during the brief gap between tool-call-started and
    // the spawn returning the agent_id.
    let cell = GenericToolCell {
        name: "agent".to_string(),
        status: ToolStatus::Running,
        input_summary: Some("prompt: do thing".to_string()),
        output: None,
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    };
    let lines = cell.lines_with_mode(80, true, super::RenderMode::Live);
    assert_eq!(lines.len(), 1);
    let rendered: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
    assert!(rendered.contains('\u{2026}'), "{rendered:?}"); //}

#[test]
fn agent_transcript_mode_keeps_full_block() {
    // Transcript mode is for replay/debug — preserve the full block
    // so session export still carries the args/output verbatim.
    let cell = GenericToolCell {
        name: "agent".to_string(),
        status: ToolStatus::Success,
        input_summary: Some("prompt: do thing".to_string()),
        output: Some(r#"{"agent_id": "agent-abc12", "model": "deepseek-v4-flash"}"#.to_string()),
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    };
    let lines = cell.lines_with_mode(80, true, super::RenderMode::Transcript);
    // Transcript mode emits header + name kv + (no args, output present)
    // + output rows. At minimum more than the live one-liner.
    assert!(lines.len() > 1, "expected verbose transcript render");
}

#[test]
fn other_tools_are_unaffected_by_agent_compact_path() {
    // Live-mode tool rows are compact by default; raw detail remains
    // available through the detail pager.
    let cell = GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Success,
        input_summary: Some("path: foo.rs".to_string()),
        output: Some("first line\nsecond line\nthird line".to_string()),
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    };
    let lines = cell.lines_with_mode(80, true, super::RenderMode::Live);
    assert_eq!(lines.len(), 1, "live tools should use compact rows");
}

// ---- #403 concise todo / checklist update rendering ----
//
// The tool emits an "Updated todo #N to STATUS" leading line plus a
// JSON snapshot. The renderer should detect the prefix and produce
// a compact one-line state-change card instead of dumping the full
// item list every time.

#[test]
fn parse_update_prefix_recognises_todo_form() {
    let parsed = super::parse_update_prefix("Updated todo #3 to in_progress\n{ \"items\": [...] }");
    assert_eq!(
        parsed,
        Some(super::ChecklistChange {
            id: 3,
            status: "in_progress".to_string(),
        }),
    );
}

#[test]
fn parse_update_prefix_recognises_checklist_form() {
    let parsed = super::parse_update_prefix("Updated checklist #7 to completed\n{ \"items\": [] }");
    assert_eq!(
        parsed,
        Some(super::ChecklistChange {
            id: 7,
            status: "completed".to_string(),
        }),
    );
}

#[test]
fn parse_update_prefix_returns_none_for_writes() {
    // `todo_write` / `checklist_write` outputs don't start with
    // "Updated …" — they should fall through to the full-card path.
    assert!(super::parse_update_prefix("{ \"items\": [] }").is_none());
    assert!(super::parse_update_prefix("Wrote 5 todos\n{}").is_none());
}

#[test]
fn parse_update_prefix_returns_none_for_malformed() {
    // Missing arrow/status → fall through.
    assert!(super::parse_update_prefix("Updated todo #3\n").is_none());
    // Non-numeric id → fall through.
    assert!(super::parse_update_prefix("Updated todo #foo to done\n").is_none());
}

#[test]
fn render_checklist_change_card_shows_only_changed_item() {
    // Build a snapshot with three items; render the change for #2.
    let snapshot = super::ChecklistSnapshot {
        items: vec![
            super::ChecklistItemSnapshot {
                content: "Read the spec".to_string(),
                status: "completed".to_string(),
            },
            super::ChecklistItemSnapshot {
                content: "Write the test".to_string(),
                status: "in_progress".to_string(),
            },
            super::ChecklistItemSnapshot {
                content: "Land the PR".to_string(),
                status: "pending".to_string(),
            },
        ],
        completion_pct: 33,
        completed: 1,
        total: 3,
    };
    let change = super::ChecklistChange {
        id: 2,
        status: "in_progress".to_string(),
    };
    let lines = super::render_checklist_change_card(
        "todo_update",
        ToolStatus::Success,
        &snapshot,
        &change,
        80,
        true,
    );
    // Header + change line + summary affordance = 3 lines.
    assert!(lines.len() >= 3, "expected ≥3 lines, got {}", lines.len());

    // The change line should mention the title and the new status,
    // and should NOT include the other two item titles (that's the
    // whole point — concise rendering).
    let change_line: String = lines[1].spans.iter().map(|s| s.content.as_ref()).collect();
    assert!(change_line.contains("#2"), "missing id: {change_line:?}");
    assert!(
        change_line.contains("Write the test"),
        "missing title: {change_line:?}"
    );
    assert!(
        change_line.contains("in_progress"),
        "missing status: {change_line:?}"
    );
    assert!(
        !change_line.contains("Land the PR"),
        "should not show other items: {change_line:?}"
    );
    assert!(
        !change_line.contains("Read the spec"),
        "should not show other items: {change_line:?}"
    );

    // The summary line carries the count + Alt+V hint.
    let summary_line: String = lines
        .last()
        .unwrap()
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect();
    assert!(summary_line.contains("3 items"), "{summary_line:?}");
    assert!(summary_line.contains("Alt+V"), "{summary_line:?}");
}

#[test]
fn render_checklist_change_card_handles_missing_title_gracefully() {
    // If the change targets an out-of-range id, the title falls
    // back to a placeholder rather than crashing.
    let snapshot = super::ChecklistSnapshot {
        items: vec![super::ChecklistItemSnapshot {
            content: "only item".to_string(),
            status: "pending".to_string(),
        }],
        completion_pct: 0,
        completed: 0,
        total: 1,
    };
    let change = super::ChecklistChange {
        id: 99,
        status: "completed".to_string(),
    };
    let lines = super::render_checklist_change_card(
        "todo_update",
        ToolStatus::Success,
        &snapshot,
        &change,
        80,
        true,
    );
    let change_line: String = lines[1].spans.iter().map(|s| s.content.as_ref()).collect();
    assert!(change_line.contains("#99"));
    assert!(change_line.contains("(missing title)"));
}

#[test]
fn running_status_label_omits_elapsed_below_threshold() {
    assert_eq!(running_status_label_with_elapsed(0), "running");
    assert_eq!(running_status_label_with_elapsed(1), "running");
    assert_eq!(running_status_label_with_elapsed(2), "running");
}

#[test]
fn running_status_label_appends_elapsed_at_three_seconds() {
    assert_eq!(running_status_label_with_elapsed(3), "running (3s)");
    assert_eq!(running_status_label_with_elapsed(7), "running (7s)");
    assert_eq!(running_status_label_with_elapsed(120), "running (120s)");
}

#[test]
fn extract_reasoning_summary_prefers_summary_block() {
    let text = "Thinking...\nSummary: First line\nSecond line\n\nTail";
    let summary = extract_reasoning_summary(text).expect("summary should exist");
    assert_eq!(summary, "First line\nSecond line");
}

#[test]
fn extract_reasoning_summary_falls_back_to_full_text() {
    let text = "Line one\nLine two";
    let summary = extract_reasoning_summary(text).expect("summary should exist");
    assert_eq!(summary, "Line one\nLine two");
}

#[test]
fn archived_context_metadata_preserves_spaces_in_attributes() {
    let msg = Message {
        role: "assistant".to_string(),
        content: vec![ContentBlock::Text {
            text: "<archived_context level=\"1\" range=\"msg 0-128\" tokens=\"2499\" density=\"~2,500 tokens\" model=\"deepseek-v4-flash\" timestamp=\"2026-04-28T00:00:00Z\">\nSummary body\n</archived_context>".to_string(),
            cache_control: None,
        }],
    };

    let cells = super::history_cells_from_message(&msg);
    assert_eq!(cells.len(), 1);
    let HistoryCell::ArchivedContext {
        level,
        range,
        tokens,
        density,
        model,
        timestamp,
        summary,
    } = &cells[0]
    else {
        panic!("expected archived context cell");
    };

    assert_eq!(*level, 1);
    assert_eq!(range, "msg 0-128");
    assert_eq!(tokens, "2499");
    assert_eq!(density, "~2,500 tokens");
    assert_eq!(model, "deepseek-v4-flash");
    assert_eq!(timestamp, "2026-04-28T00:00:00Z");
    assert_eq!(summary, "Summary body");
}

#[test]
fn history_replays_update_plan_tool_use_as_plan_card() {
    let msg = Message {
        role: "assistant".to_string(),
        content: vec![ContentBlock::ToolUse {
            id: "plan-1".to_string(),
            name: "update_plan".to_string(),
            input: serde_json::json!({
                "objective": "Make Plan mode reviewable",
                "sources_used": ["gh issue view 2691"],
                "critical_files": ["crates/tui/src/tools/plan.rs"],
                "plan": [
                    { "step": "render replay card", "status": "completed" }
                ]
            }),
            caller: None,
        }],
    };

    let cells = super::history_cells_from_message(&msg);
    assert_eq!(cells.len(), 1);
    let HistoryCell::Tool(ToolCell::PlanUpdate(cell)) = &cells[0] else {
        panic!("expected update_plan replay cell");
    };

    assert_eq!(cell.status, ToolStatus::Success);
    assert_eq!(
        cell.snapshot.objective.as_deref(),
        Some("Make Plan mode reviewable")
    );
    assert_eq!(cell.snapshot.sources_used, vec!["gh issue view 2691"]);
    assert_eq!(cell.snapshot.items[0].status, StepStatus::Completed);
}

#[test]
fn render_thinking_collapsed_shows_details_affordance() {
    let lines = render_thinking(
        "Summary: First line\nSecond line\nThird line\nFourth line\nFifth line",
        80,
        false,
        Some(2.0),
        true,
        false,
    );
    let text = lines
        .iter()
        .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref()))
        .collect::<String>();
    assert!(text.contains("Full reasoning in Ctrl+O"));
    // Pin the actual header shape ("… reasoning done") — a bare
    // `contains("reasoning")` is already satisfied by the Ctrl+O
    // affordance line above and would never fail on its own.
    let header = lines
        .first()
        .map(|line| {
            line.spans
                .iter()
                .map(|span| span.content.as_ref())
                .collect::<String>()
        })
        .unwrap_or_default();
    assert!(
        header.starts_with(REASONING_OPENER),
        "header opens with the dotted opener: {header:?}"
    );
    assert!(
        header.contains("reasoning done"),
        "header carries the reasoning title and done status: {header:?}"
    );
}

#[test]
fn render_thinking_streaming_collapsed_shows_live_content() {
    // #861 RC4 / #1324: during a live thinking block in collapsed view,
    // the body must NOT be blanked out. Users want to watch the model
    // think; the previous behaviour stalled on a "thinking..." spinner
    // until ThinkingComplete fired.
    let lines = render_thinking(
        "Step 1: read the code\nStep 2: trace the call\nStep 3: form a hypothesis",
        80,
        true, // streaming
        None, // no duration yet
        true, // collapsed
        true, // low_motion (no cursor noise to grep)
    );
    let text = lines
        .iter()
        .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref()))
        .collect::<String>();
    assert!(
        text.contains("Step 3: form a hypothesis"),
        "the most recent thinking line must be visible during streaming, got: {text}"
    );
    // "thinking..." placeholder must not be the only thing rendered.
    assert!(
        !text.contains("thinking..."),
        "raw content present means the placeholder line should not be drawn, got: {text}"
    );
}

#[test]
fn render_hidden_streaming_thinking_shows_activity_without_content() {
    let cell = HistoryCell::Thinking {
        content: "private chain of thought that must not be shown".to_string(),
        streaming: true,
        duration_secs: None,
    };

    let lines = cell.lines_with_options(
        80,
        TranscriptRenderOptions {
            show_thinking: false,
            low_motion: true,
            ..TranscriptRenderOptions::default()
        },
    );
    let text = lines_text(&lines);

    assert!(
        text.contains("reasoning hidden"),
        "hidden live thinking should still show progress: {text}"
    );
    assert!(
        !text.contains("private chain of thought"),
        "hidden live thinking must not reveal content: {text}"
    );
}

#[test]
fn render_hidden_completed_thinking_stays_hidden() {
    let cell = HistoryCell::Thinking {
        content: "completed hidden reasoning".to_string(),
        streaming: false,
        duration_secs: Some(1.0),
    };

    let lines = cell.lines_with_options(
        80,
        TranscriptRenderOptions {
            show_thinking: false,
            ..TranscriptRenderOptions::default()
        },
    );

    assert!(
        lines.is_empty(),
        "completed hidden thinking should stay out of the transcript"
    );
}

#[test]
fn render_thinking_streaming_truncated_shows_continues_affordance() {
    // #861 RC4: when a streaming thinking block exceeds the line cap,
    // surface a live affordance pointing at Ctrl+O. The earlier code
    // suppressed the affordance unless `!streaming`.
    let long = (1..=12)
        .map(|i| format!("Reasoning line {i}"))
        .collect::<Vec<_>>()
        .join("\n");
    let lines = render_thinking(&long, 80, true, None, true, true);
    let text = lines
        .iter()
        .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref()))
        .collect::<String>();
    assert!(
        text.contains("More reasoning in Ctrl+O"),
        "streaming-truncation affordance missing, got: {text}"
    );
    // The most recent line must be the visible tail (head dropped).
    assert!(
        text.contains("Reasoning line 12"),
        "tail line missing, got: {text}"
    );
    assert!(
        !text.contains("Reasoning line 1\n"),
        "head should be clipped, got: {text}"
    );
}

#[test]
fn tool_lines_with_options_respects_low_motion_in_default_path() {
    // Use a 2× cycle offset so the animated frame lands on index 2,
    // which is maximally far from index 0. This avoids flaky failures on
    // platforms with coarse timer resolution (Windows ≈ 15.6 ms) and
    // gives several frame intervals of headroom before the index could
    // wrap back to 0.
    let started_at = Some(Instant::now() - Duration::from_millis(TOOL_STATUS_SYMBOL_MS * 2));
    let cell = HistoryCell::Tool(ToolCell::Exec(ExecCell {
        command: "echo hi".to_string(),
        status: ToolStatus::Running,
        output: None,
        live_output: None,
        shell_task_id: None,
        owner_agent_id: None,
        owner_agent_name: None,
        started_at,
        duration_ms: None,
        source: ExecSource::Assistant,
        interaction: None,
        output_summary: None,
    }));

    let animated = cell.lines_with_options(80, TranscriptRenderOptions::default());
    let low_motion = cell.lines_with_options(
        80,
        TranscriptRenderOptions {
            low_motion: true,
            ..TranscriptRenderOptions::default()
        },
    );

    // Index 0 is card-rail glyph (╭); the animated symbol is at index 1.
    let animated_symbol = animated[0].spans[1].content.trim();
    let low_motion_symbol = low_motion[0].spans[1].content.trim();

    // low_motion always pins to the first (static) frame.
    assert_eq!(low_motion_symbol, TOOL_RUNNING_SYMBOLS[0]);
    // The animated path should be on a different frame (index 2).
    assert_ne!(animated_symbol, TOOL_RUNNING_SYMBOLS[0]);
}

// === Speaker glyph tests (v0.6.6 UI redesign) ===
//
// The literal "Assistant" / "You" labels are replaced by the calmer
// bullet/bar glyphs (`●` / `▎`). Only the assistant glyph pulses, and
// only while the cell is streaming — finished turns sit at the source
// sky color so the transcript reads as solid history.

#[test]
fn user_cell_renders_with_bar_glyph_not_literal_label() {
    let cell = HistoryCell::User {
        content: "hello".to_string(),
    };
    let lines = cell.lines(80);
    let head = &lines[0];
    assert_eq!(head.spans[0].content.as_ref(), USER_GLYPH);
    assert_eq!(head.spans[0].style.fg, Some(palette::USER_BODY));
    assert_eq!(head.style.bg, Some(palette::SURFACE_ELEVATED));
    assert_eq!(head.width(), 80);
    assert!(
        head.spans.iter().any(|span| span.style.bg.is_none()),
        "content spans should keep their own styles and inherit the line background"
    );
    // No "You" literal anywhere in the rendered head line.
    let visible: String = head
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect::<String>();
    assert!(!visible.contains("You"), "user label dropped: {visible:?}");
    assert!(visible.contains("hello"));
}

#[test]
fn user_cell_wraps_fill_transcript_rows() {
    let cell = HistoryCell::User {
        content: "hello world this prompt wraps onto multiple transcript lines".to_string(),
    };
    let lines = cell.lines(18);

    assert!(lines.len() > 1, "expected wrapped user message");
    assert!(
        lines
            .iter()
            .all(|line| line.style.bg == Some(palette::SURFACE_ELEVATED)),
        "wrapped user message lines should keep the highlighted block background"
    );
    assert!(
        lines.iter().all(|line| line.width() == 18),
        "wrapped user message lines should fill the rendered row width"
    );
}

#[test]
fn user_transcript_lines_do_not_append_visual_padding() {
    let cell = HistoryCell::User {
        content: "hello".to_string(),
    };
    let lines = cell.transcript_lines(80);
    let head = &lines[0];
    let visible: String = head.spans.iter().map(|s| s.content.as_ref()).collect();

    assert_eq!(visible, format!("{USER_GLYPH} hello"));
    assert!(head.width() < 80);
    assert_eq!(head.style.bg, None);
}

#[test]
fn user_cell_renders_plain_text_without_markdown_interpretation() {
    let cell = HistoryCell::User {
        content: "  # heading\n- item\n   \nhello    world".to_string(),
    };
    let visible: Vec<String> = cell.lines(80).iter().map(line_text).collect();

    assert_eq!(visible[0].trim_end(), format!("{USER_GLYPH}   # heading"));
    assert!(
        visible[1].trim_end().ends_with("- item"),
        "dash-prefixed text must remain literal: {visible:?}"
    );
    assert!(
        visible[2].ends_with("   "),
        "whitespace-only lines must survive: {visible:?}"
    );
    assert!(
        visible[3].trim_end().ends_with("hello    world"),
        "internal spacing must remain literal: {visible:?}"
    );
    assert!(
        !visible.iter().any(|line| line.contains('\u{2500}')),
        "plain user heading must not add markdown heading rule: {visible:?}"
    );
}

#[test]
fn assistant_cell_renders_with_bullet_glyph_not_literal_label() {
    let cell = HistoryCell::Assistant {
        content: "ready".to_string(),
        streaming: false,
    };
    let lines = cell.lines(80);
    let head = &lines[0];
    assert_eq!(head.spans[0].content.as_ref(), ASSISTANT_GLYPH);
    let visible: String = head
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect::<String>();
    assert!(
        !visible.contains("Assistant"),
        "assistant label dropped: {visible:?}"
    );
    assert!(visible.contains("ready"));
    assert_ne!(head.style.bg, Some(palette::SURFACE_ELEVATED));
}

#[test]
fn whitespace_only_assistant_cell_renders_nothing() {
    // Regression: a stray newline/space streamed between reasoning and a
    // tool call produced a whitespace-only Assistant cell that rendered as
    // a bare, orphaned role glyph — the "blue dot with nothing after it"
    // artifact. It must collapse to zero lines instead.
    for content in ["", "   ", "\n", "\n\n", " \t \n"] {
        for streaming in [false, true] {
            let cell = HistoryCell::Assistant {
                content: content.to_string(),
                streaming,
            };
            assert!(
                cell.lines(80).is_empty(),
                "whitespace-only assistant content {content:?} (streaming={streaming}) \
                 must render no lines",
            );
        }
    }

    // Sanity: real prose still renders the role glyph as its first span.
    let cell = HistoryCell::Assistant {
        content: "hi".to_string(),
        streaming: false,
    };
    assert_eq!(
        cell.lines(80)[0].spans[0].content.as_ref(),
        ASSISTANT_GLYPH,
        "non-empty assistant content must still render the role glyph",
    );
}

#[test]
fn assistant_cell_still_renders_markdown() {
    let cell = HistoryCell::Assistant {
        content: "# Heading\n\n- item".to_string(),
        streaming: false,
    };
    let visible: Vec<String> = cell.lines(80).iter().map(line_text).collect();

    assert!(
        visible[0].contains("Heading"),
        "assistant heading text should render: {visible:?}"
    );
    assert!(
        !visible[0].contains("# Heading"),
        "assistant heading should still be parsed as markdown: {visible:?}"
    );
    assert!(
        visible.iter().any(|line| line.contains('\u{2500}')),
        "assistant h1 markdown should still add a heading rule: {visible:?}"
    );
}

#[test]
fn assistant_code_block_lines_do_not_get_transcript_rail() {
    let cell = HistoryCell::Assistant {
        content: "SQL:\n```sql\nSELECT\nFROM customers\n```".to_string(),
        streaming: false,
    };
    let visible: Vec<String> = cell
        .lines(80)
        .iter()
        .map(|line| {
            line.spans
                .iter()
                .map(|span| span.content.as_ref())
                .collect::<String>()
        })
        .collect();

    assert_eq!(visible[0], format!("{ASSISTANT_GLYPH} SQL:"));
    for line in visible
        .iter()
        .filter(|line| line.contains("SELECT") || line.contains("FROM customers"))
    {
        assert!(
            !line.contains('\u{258F}'),
            "code block line should not inherit the transcript rail: {line:?}"
        );
    }
}

/// Issue #1212 repro: a multi-line SQL fence rendered after a short
/// intro paragraph. Every code-block line — not just the first or last —
/// must avoid the `▏` rail.
#[test]
fn assistant_long_code_block_keeps_every_line_rail_free() {
    let cell = HistoryCell::Assistant {
        content: "Here's the query:\n```sql\nSELECT\n  c.customer_id,\n  c.name,\n  COUNT(o.order_id) AS order_count\nFROM customers c\nJOIN orders o ON c.customer_id = o.customer_id;\n```".to_string(),
        streaming: false,
    };
    let visible: Vec<String> = cell
        .lines(80)
        .iter()
        .map(|line| {
            line.spans
                .iter()
                .map(|span| span.content.as_ref())
                .collect::<String>()
        })
        .collect();

    let code_markers = ["SELECT", "customer_id", "name,", "COUNT", "FROM", "JOIN"];
    for marker in code_markers {
        let line = visible
            .iter()
            .find(|line| line.contains(marker))
            .unwrap_or_else(|| panic!("expected code line containing {marker:?}"));
        assert!(
            !line.contains('\u{258F}'),
            "code block line containing {marker:?} must not have the transcript rail: {line:?}"
        );
    }
}

/// Edge case: a blank line inside a fence is still a code line; it must
/// not regress to the rail because the empty body falls through a
/// different wrap branch.
#[test]
fn assistant_code_block_blank_line_keeps_no_rail() {
    let cell = HistoryCell::Assistant {
        content: "```\nfn one() {}\n\nfn two() {}\n```".to_string(),
        streaming: false,
    };
    for line in cell.lines(80).iter().skip(1) {
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(
            !text.contains('\u{258F}'),
            "fence body line must stay rail-free: {text:?}"
        );
    }
}

/// Wrapped code lines (a single source line longer than the viewport)
/// emit multiple rendered lines from one `Block::Code`. None of them
/// should leak the rail.
#[test]
fn assistant_wrapped_code_lines_keep_no_rail() {
    let long = "let x = ".to_string() + &"abcdef ".repeat(40);
    let content = format!("```\n{long}\n```");
    let cell = HistoryCell::Assistant {
        content,
        streaming: false,
    };
    for line in cell.lines(40).iter().skip(1) {
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(
            !text.contains('\u{258F}'),
            "wrapped code line must stay rail-free: {text:?}"
        );
    }
}

#[test]
fn assistant_glyph_holds_full_brightness_when_idle() {
    // Idle (streaming=false) and low_motion both pin the colour to the
    // source sky — pulse only fires when actively streaming.
    let idle = assistant_label_style_for(false, false);
    let low_motion = assistant_label_style_for(true, true);
    assert_eq!(idle.fg, Some(palette::DEEPSEEK_SKY));
    assert_eq!(low_motion.fg, Some(palette::DEEPSEEK_SKY));
}

#[test]
fn assistant_glyph_pulses_when_streaming_and_motion_allowed() {
    // The streaming path runs through `pulse_brightness`, which yields
    // an RGB colour scaled within 30%..100% of the source. Sample twice
    // — at least one of the samples must fall below 100% brightness, or
    // the test wouldn't be exercising the pulse at all. (We can't pin
    // the value because the function reads SystemTime::now().)
    use ratatui::style::Color;
    let mut saw_dimmed = false;
    for _ in 0..50 {
        if let Some(Color::Rgb(_, _, b)) = assistant_label_style_for(true, false).fg {
            let Color::Rgb(_, _, src_b) = palette::DEEPSEEK_SKY else {
                panic!("DEEPSEEK_SKY must be RGB");
            };
            if b < src_b {
                saw_dimmed = true;
                break;
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        saw_dimmed,
        "expected the streaming pulse to dip below source brightness at least once",
    );
}

// === Tool-card verb-glyph tests (v0.6.6 UI redesign) ===

#[test]
fn exec_cell_header_uses_run_verb_glyph_and_label() {
    let cell = ExecCell {
        command: "ls".to_string(),
        status: ToolStatus::Success,
        output: Some("a\nb\n".to_string()),
        live_output: None,
        shell_task_id: None,
        owner_agent_id: None,
        owner_agent_name: None,
        started_at: None,
        duration_ms: Some(10),
        source: ExecSource::Assistant,
        interaction: None,
        output_summary: None,
    };
    let header = &cell.lines_with_motion(80, true)[0];
    let visible: String = header
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect::<String>();
    assert!(
        visible.contains('\u{25B6}'),
        "Run glyph `▶` present: {visible:?}"
    );
    assert!(visible.contains(" run "), "verb label `run`: {visible:?}");
    // Old literal title must be gone.
    assert!(
        !visible.contains("Shell"),
        "old `Shell` literal is gone: {visible:?}"
    );
}

#[test]
fn exec_cell_header_includes_compact_command_summary() {
    let cell = ExecCell {
        command: "cargo test --workspace --all-features".to_string(),
        status: ToolStatus::Running,
        output: None,
        live_output: None,
        shell_task_id: None,
        owner_agent_id: None,
        owner_agent_name: None,
        started_at: None,
        duration_ms: None,
        source: ExecSource::Assistant,
        interaction: None,
        output_summary: None,
    };

    let header = &cell.lines_with_motion(80, true)[0];
    let visible: String = header
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect::<String>();
    assert!(visible.contains("run running"));
    assert!(
        visible.contains("cargo test --workspace --all-features"),
        "header should expose command target: {visible:?}"
    );
}

#[test]
fn generic_tool_cell_picks_family_from_tool_name() {
    let cell = GenericToolCell {
        name: "agent".to_string(),
        status: ToolStatus::Running,
        input_summary: Some("foo".to_string()),
        output: None,
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    };
    let lines = cell.lines_with_mode(80, true, super::RenderMode::Live);
    let header_visible: String = lines[0]
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect::<String>();
    // agent → Delegate family (◐ delegate).
    assert!(
        header_visible.contains('\u{25D0}'),
        "Delegate glyph `◐`: {header_visible:?}"
    );
    assert!(
        header_visible.contains(" delegate "),
        "verb label `delegate`: {header_visible:?}"
    );
}

#[test]
fn generic_tool_cell_renders_rlm_with_rlm_label_not_swarm() {
    let cell = GenericToolCell {
        name: "rlm".to_string(),
        status: ToolStatus::Running,
        input_summary: Some("task: compare source trees".to_string()),
        output: None,
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    };
    let lines = cell.lines_with_mode(80, true, super::RenderMode::Live);
    let header_visible: String = lines[0]
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect::<String>();

    assert!(
        header_visible.contains(" rlm "),
        "RLM card should identify RLM work: {header_visible:?}"
    );
    assert!(
        !header_visible.contains("swarm"),
        "RLM card must not use removed swarm wording: {header_visible:?}"
    );
}

// === Reasoning treatment tests (v0.6.6 UI redesign) ===

#[test]
fn render_thinking_uses_dotted_opener_in_header() {
    let lines = render_thinking("Step one\nStep two", 80, false, Some(2.0), false, true);
    let header = &lines[0];
    // First span carries `…` followed by a space.
    assert!(
        header.spans[0].content.starts_with(REASONING_OPENER),
        "header opener: {:?}",
        header.spans[0].content
    );
}

#[test]
fn render_thinking_body_lines_use_dashed_rail_and_italic() {
    let lines = render_thinking(
        "concrete reasoning content",
        80,
        /*streaming*/ false,
        Some(1.0),
        /*collapsed*/ false,
        /*low_motion*/ true,
    );
    // Header is index 0; first body line is index 1.
    assert!(lines.len() >= 2, "expected at least one body line");
    let body = &lines[1];
    assert_eq!(
        body.spans[0].content.as_ref(),
        REASONING_RAIL,
        "body rail must be the dashed `╎ ` glyph"
    );
    // The body span should carry italic.
    let italic_seen = body
        .spans
        .iter()
        .skip(1)
        .any(|span| span.style.add_modifier.contains(Modifier::ITALIC));
    assert!(italic_seen, "body content should carry italic modifier");
}

#[test]
fn render_thinking_streaming_appends_cursor_when_motion_allowed() {
    let lines = render_thinking(
        "ongoing reasoning...",
        80,
        /*streaming*/ true,
        None,
        /*collapsed*/ false,
        /*low_motion*/ false,
    );
    // Last line is the most recent body line — cursor lives there.
    let last = lines.last().expect("body line present");
    let last_span = last.spans.last().expect("trailing span present");
    assert!(
        last_span.content.contains(REASONING_CURSOR),
        "expected trailing cursor `▎` on last streaming body line, got {:?}",
        last_span.content
    );
}

#[test]
fn render_thinking_streaming_omits_cursor_when_low_motion() {
    let lines = render_thinking(
        "ongoing reasoning...",
        80,
        /*streaming*/ true,
        None,
        /*collapsed*/ false,
        /*low_motion*/ true,
    );
    let last = lines.last().expect("body line present");
    let visible: String = last
        .spans
        .iter()
        .map(|s| s.content.as_ref())
        .collect::<String>();
    assert!(
        !visible.contains(REASONING_CURSOR),
        "low_motion must suppress the streaming cursor: {visible:?}"
    );
}

// === Theme parity tests ===
//
// These lock the visible color/style choices for one plan cell and one
// tool cell against `deepseek_theme::Theme::dark()`. The render path is
// unchanged in shape; the assertions just guarantee a future skin swap
// (or accidental drift) is caught here instead of at runtime.

#[test]
fn plan_update_cell_renders_with_dark_theme_tokens() {
    let theme = Theme::dark();
    let cell = PlanUpdateCell {
        snapshot: PlanSnapshot {
            items: vec![
                crate::tools::plan::PlanItemArg {
                    step: "scan repo".to_string(),
                    status: StepStatus::Completed,
                },
                crate::tools::plan::PlanItemArg {
                    step: "extract theme".to_string(),
                    status: StepStatus::InProgress,
                },
                crate::tools::plan::PlanItemArg {
                    step: "land tests".to_string(),
                    status: StepStatus::Pending,
                },
            ],
            ..PlanSnapshot::default()
        },
        status: ToolStatus::Running,
    };

    let lines = cell.lines_with_motion(80, true);

    // Header: "<spinner> <family-glyph> <verb> <state>" (v0.6.6 layout).
    // PlanUpdate has no canonical family yet, so it falls into the
    // Generic bullet glyph + "tool" verb. The shape and colour wiring
    // is what matters for the theme parity; the verb text moves with
    // the redesign.
    // PlanUpdate does NOT use card-rail wrapping (separate render path).
    let header = &lines[0];
    let symbol_span = &header.spans[0];
    let glyph_span = &header.spans[1];
    let title_span = &header.spans[2];
    let state_span = &header.spans[4];

    assert_eq!(
        symbol_span.style.fg,
        Some(theme.tool_running_accent),
        "running header symbol should use the dark theme running accent"
    );
    assert_eq!(
        glyph_span.style.fg,
        Some(theme.tool_running_accent),
        "family glyph rides the same status colour as the spinner"
    );
    assert_eq!(
        title_span.content.as_ref(),
        "tool",
        "PlanUpdate routes to Generic family → 'tool' verb",
    );
    assert_eq!(title_span.style.fg, Some(theme.tool_title_color));
    assert!(
        title_span.style.add_modifier.contains(Modifier::BOLD),
        "tool title should be bold"
    );
    assert_eq!(
        state_span.content.as_ref(),
        "running",
        "running PlanUpdate should label state as 'running'"
    );
    assert_eq!(state_span.style.fg, Some(theme.tool_running_accent));

    // Each step row: ["▏ ", "<marker>:", " ", "<step>"]
    let step_line = &lines[1];
    let label_span = &step_line.spans[1];
    let value_span = &step_line.spans[3];
    assert_eq!(
        label_span.style.fg,
        Some(theme.tool_label_color),
        "step label should use theme.tool_label_color"
    );
    assert_eq!(
        value_span.style.fg,
        Some(theme.tool_value_color),
        "step value should use theme.tool_value_color"
    );

    // Plain content stays identical so visible output does not move.
    let visible = lines
        .iter()
        .map(|l| {
            l.spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>()
        })
        .collect::<Vec<_>>();
    assert_eq!(visible[1].trim_end(), "▏ done: scan repo");
    assert_eq!(visible[2].trim_end(), "▏ live: extract theme");
    assert_eq!(visible[3].trim_end(), "▏ next: land tests");
}

#[test]
fn plan_update_cell_renders_rich_artifact_metadata() {
    let cell = PlanUpdateCell {
        snapshot: PlanSnapshot {
            objective: Some("Make Plan mode reviewable".to_string()),
            context_summary: Some("Grounded in issue #2691".to_string()),
            sources_used: vec!["gh issue view 2691".to_string()],
            critical_files: vec!["crates/tui/src/tools/plan.rs".to_string()],
            constraints: vec!["Keep checklist primary".to_string()],
            recommended_approach: Some(
                "Enrich update_plan without breaking legacy calls".to_string(),
            ),
            verification_plan: Some("Run focused renderer tests".to_string()),
            risks_and_unknowns: Some("Metadata-only plans can disappear".to_string()),
            handoff_packet: Some("Next agent should inspect relay output".to_string()),
            items: vec![crate::tools::plan::PlanItemArg {
                step: "Render artifact sections".to_string(),
                status: StepStatus::InProgress,
            }],
            ..PlanSnapshot::default()
        },
        status: ToolStatus::Success,
    };

    let visible = cell
        .lines_with_motion(120, true)
        .into_iter()
        .map(|line| {
            line.spans
                .into_iter()
                .map(|span| span.content.into_owned())
                .collect::<String>()
        })
        .collect::<Vec<_>>()
        .join("\n");

    assert!(visible.contains("objective:"));
    assert!(visible.contains("Make Plan mode reviewable"));
    assert!(visible.contains("source:"));
    assert!(visible.contains("gh issue view 2691"));
    assert!(visible.contains("file:"));
    assert!(visible.contains("verify:"));
    assert!(visible.contains("handoff:"));
    assert!(visible.contains("Render artifact sections"));
}

#[test]
fn exec_cell_failed_status_renders_with_dark_theme_tokens() {
    let theme = Theme::dark();
    let cell = ExecCell {
        command: "false".to_string(),
        status: ToolStatus::Failed,
        output: Some("boom".to_string()),
        live_output: None,
        shell_task_id: None,
        owner_agent_id: None,
        owner_agent_name: None,
        started_at: None,
        duration_ms: Some(42),
        source: ExecSource::Assistant,
        interaction: None,
        output_summary: None,
    };

    let lines = cell.lines_with_motion(80, true);

    let header = &lines[0];
    let symbol_span = &header.spans[1];
    let glyph_span = &header.spans[2];
    let title_span = &header.spans[3];
    let state_span = &header.spans[5];

    assert_eq!(
        symbol_span.style.fg,
        Some(theme.tool_failed_accent),
        "failed exec header symbol should use the dark theme failed accent"
    );
    // ExecCell is family Run → glyph `▶ ` and verb `run`.
    assert!(
        glyph_span.content.starts_with('\u{25B6}'),
        "Run family glyph: {:?}",
        glyph_span.content
    );
    assert_eq!(
        title_span.content.as_ref(),
        "run",
        "ExecCell routes to Run family → 'run' verb",
    );
    assert_eq!(title_span.style.fg, Some(theme.tool_title_color));
    assert!(title_span.style.add_modifier.contains(Modifier::BOLD));
    assert_eq!(state_span.content.as_ref(), "issue");
    assert_eq!(state_span.style.fg, Some(theme.tool_failed_accent));
}

// === display_lines (lines_with_options) vs transcript_lines parity ===
//
// These lock the contract for CX#8: live view keeps reasoning compact
// and caps tool output, transcript view shows the full body. Completed
// reasoning without an explicit Summary stays out of the main flow so it
// cannot masquerade as user text.

fn line_text(line: &ratatui::text::Line<'static>) -> String {
    line.spans
        .iter()
        .map(|span| span.content.as_ref())
        .collect()
}

fn lines_text(lines: &[ratatui::text::Line<'static>]) -> String {
    lines.iter().map(line_text).collect::<Vec<_>>().join("\n")
}

#[test]
fn exec_cell_renders_live_shell_output_before_final_output() {
    let cell = ExecCell {
        command: "cargo test".to_string(),
        status: ToolStatus::Running,
        output: None,
        live_output: Some("running line 1\nrunning line 2".to_string()),
        shell_task_id: Some("shell_live".to_string()),
        owner_agent_id: None,
        owner_agent_name: None,
        started_at: None,
        duration_ms: None,
        source: ExecSource::Assistant,
        interaction: None,
        output_summary: None,
    };

    let text = lines_text(&cell.lines_with_motion(80, true));

    assert!(text.contains("running line 1"));
    assert!(text.contains("running line 2"));
    assert!(!text.contains("Ctrl+B backgrounds this command"));
}

#[test]
fn exec_cell_prefers_final_output_over_live_shell_tail() {
    let cell = ExecCell {
        command: "cargo test".to_string(),
        status: ToolStatus::Success,
        output: Some("final output".to_string()),
        live_output: Some("stale live tail".to_string()),
        shell_task_id: Some("shell_live".to_string()),
        owner_agent_id: None,
        owner_agent_name: None,
        started_at: None,
        duration_ms: None,
        source: ExecSource::Assistant,
        interaction: None,
        output_summary: None,
    };

    let text = lines_text(&cell.lines_with_motion(80, true));

    assert!(text.contains("cargo test"));
    assert!(!text.contains("stale live tail"));
}

#[test]
fn long_thinking_display_is_shorter_than_transcript() {
    // Build a multi-paragraph thinking body so the live view has
    // something to compress. Without an explicit Summary block, the live
    // surface should show a bounded preview plus affordance; Ctrl+O
    // remains the path to the full body.
    let body = "First paragraph lede.\n\
                Second sentence of the first paragraph.\n\n\
                Second paragraph: deeper analysis follows.\n\
                More detail in paragraph two.\n\n\
                Third paragraph: even more reasoning.\n\
                With another line.\n\n\
                Fourth paragraph: the conclusion.\n\
                And one more line for good measure.";
    let cell = HistoryCell::Thinking {
        content: body.to_string(),
        streaming: false,
        duration_secs: Some(3.2),
    };

    let live = cell.lines_with_options(
        80,
        TranscriptRenderOptions {
            low_motion: true,
            ..TranscriptRenderOptions::default()
        },
    );
    let transcript = cell.transcript_lines(80);

    assert!(
        live.len() < transcript.len(),
        "live thinking should compress (live = {} lines, transcript = {} lines)",
        live.len(),
        transcript.len()
    );

    let live_text = lines_text(&live);
    let transcript_text = lines_text(&transcript);

    assert!(
        transcript_text.contains("First paragraph lede"),
        "transcript thinking must keep the lede"
    );
    assert!(
        live_text.contains("First paragraph lede"),
        "live thinking should preview completed reasoning: {live_text}"
    );
    assert!(
        transcript_text.contains("Fourth paragraph"),
        "transcript thinking must keep the full body"
    );
    assert!(
        !live_text.contains("Fourth paragraph"),
        "live thinking must drop the tail when collapsed"
    );
    assert!(
        live_text.contains("Full reasoning in Ctrl+O"),
        "live thinking must offer the pager affordance"
    );
    assert!(
        !transcript_text.contains("Full reasoning in Ctrl+O"),
        "transcript thinking must not include the live affordance"
    );
}

#[test]
fn completed_short_thinking_without_summary_stays_visible_in_live_view() {
    // Short completed reasoning should not become a dead "Full reasoning
    // in Ctrl+O" card. The reasoning rail and tint already distinguish it
    // from the user's prompt, so show the useful body inline.
    let cell = HistoryCell::Thinking {
        content: "One brief reasoning step.".to_string(),
        streaming: false,
        duration_secs: Some(0.4),
    };

    let live = cell.lines_with_options(
        80,
        TranscriptRenderOptions {
            low_motion: true,
            ..TranscriptRenderOptions::default()
        },
    );
    let transcript = cell.transcript_lines(80);

    let live_text = lines_text(&live);
    let transcript_text = lines_text(&transcript);

    assert!(
        live_text.contains("One brief reasoning step."),
        "live thinking must preview short completed reasoning: {live_text}"
    );
    assert!(
        transcript_text.contains("One brief reasoning step."),
        "transcript thinking must keep the full reasoning body"
    );
    assert!(
        !live_text.contains("Full reasoning in Ctrl+O"),
        "complete short reasoning should not need the detail affordance: {live_text}"
    );
}

#[test]
fn tool_exec_live_caps_failed_output_transcript_does_not() {
    // A *failed* exec keeps its output in live mode, capped to head+tail
    // with a "lines omitted" marker. Transcript mode emits it uncapped.
    let total_output_lines = 30usize;
    let output = (0..total_output_lines)
        .map(|i| format!("output line {i:02}"))
        .collect::<Vec<_>>()
        .join("\n");

    let cell = HistoryCell::Tool(ToolCell::Exec(ExecCell {
        command: "noisy_script.sh".to_string(),
        status: ToolStatus::Failed,
        output: Some(output),
        live_output: None,
        shell_task_id: None,
        owner_agent_id: None,
        owner_agent_name: None,
        started_at: None,
        duration_ms: Some(120),
        source: ExecSource::Assistant,
        interaction: None,
        output_summary: None,
    }));

    let live = cell.lines_with_options(
        80,
        TranscriptRenderOptions {
            low_motion: true,
            ..TranscriptRenderOptions::default()
        },
    );
    let transcript = cell.transcript_lines(80);

    let live_text = lines_text(&live);
    let transcript_text = lines_text(&transcript);

    assert!(
        live.len() < transcript.len(),
        "live exec output must be shorter than transcript exec output (live={}, transcript={})",
        live.len(),
        transcript.len()
    );
    assert!(
        live_text.contains("lines omitted"),
        "live failed-exec output must surface the omission marker: {live_text}"
    );
    assert!(
        !transcript_text.contains("lines omitted"),
        "transcript exec output must not include the omission marker"
    );
    assert!(transcript_text.contains("output line 00"));
    // The middle should only appear in the transcript, since the live
    // view truncates the head/tail around the cap.
    assert!(
        transcript_text.contains("output line 15"),
        "transcript must include the middle of the exec output"
    );
    // Last line should appear in both because the live view shows
    // head + tail around an omission marker.
    let last = format!("output line {:02}", total_output_lines - 1);
    assert!(transcript_text.contains(&last));
}

#[test]
fn tool_exec_live_collapses_successful_command() {
    // A *successful* exec is rarely interesting — live mode collapses it to
    // the single header line (no command body, no output). Transcript mode
    // still records everything for the pager/clipboard.
    let output = (0..30usize)
        .map(|i| format!("output line {i:02}"))
        .collect::<Vec<_>>()
        .join("\n");
    let cell = HistoryCell::Tool(ToolCell::Exec(ExecCell {
        command: "noisy_script.sh".to_string(),
        status: ToolStatus::Success,
        output: Some(output),
        live_output: None,
        shell_task_id: None,
        owner_agent_id: None,
        owner_agent_name: None,
        started_at: None,
        duration_ms: Some(120),
        source: ExecSource::Assistant,
        interaction: None,
        output_summary: None,
    }));

    let live_text = lines_text(&cell.lines_with_options(
        80,
        TranscriptRenderOptions {
            low_motion: true,
            ..TranscriptRenderOptions::default()
        },
    ));
    let transcript_text = lines_text(&cell.transcript_lines(80));

    // Live: header only — no output body, no omission marker.
    assert!(
        !live_text.contains("output line 00"),
        "successful exec must not render its output body in live mode: {live_text}"
    );
    assert!(
        !live_text.contains("lines omitted"),
        "collapsed exec must not show an omission marker: {live_text}"
    );
    // Transcript still has the full output.
    assert!(transcript_text.contains("output line 00"));
    assert!(transcript_text.contains("output line 29"));
}

#[test]
fn generic_tool_cell_renders_prompts_as_indexed_rows() {
    // When prompts are populated by a fan-out tool, each child shows on
    // its own row instead of the inline `args:` summary so the user can
    // read what each child was asked.
    let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Running,
        input_summary: Some("prompts: <3 items>".to_string()),
        output: None,
        prompts: Some(vec![
            "Summarize the README".to_string(),
            "List the public types in client.rs".to_string(),
            "Diff this commit against main".to_string(),
        ]),
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }));
    let text = lines_text(&cell.lines(80));

    assert!(text.contains("[0] Summarize the README"));
    assert!(text.contains("[1] List the public types in client.rs"));
    assert!(text.contains("[2] Diff this commit against main"));
    // The inline args summary must not also be emitted — we replaced it
    // with the per-child rows.
    assert!(
        !text.contains("args: prompts:"),
        "inline `args:` summary must be suppressed when per-prompt rows render"
    );
}

#[test]
fn generic_tool_cell_falls_back_to_args_when_prompts_none() {
    // Non-fan-out tools keep the existing `args:` summary so behavior
    // doesn't drift for everything else.
    let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: "file_search".to_string(),
        status: ToolStatus::Running,
        input_summary: Some("query: foo".to_string()),
        output: None,
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }));
    let text = lines_text(&cell.lines(80));
    assert!(text.contains("query: foo"));
}

#[test]
fn known_generic_tool_hides_raw_name_in_live_mode() {
    let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: "run_verifiers".to_string(),
        status: ToolStatus::Running,
        input_summary: Some("profile: auto, level: quick".to_string()),
        output: None,
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }));

    let text = lines_text(&cell.lines(80));
    assert!(text.contains("verify running"), "{text}");
    assert!(
        !text.contains("name: run_verifiers"),
        "live card should not spend a row on internal tool id: {text}"
    );
    assert!(
        !text.contains("run_verifiers"),
        "known tool id should not leak into compact live card: {text}"
    );
}

#[test]
fn known_generic_tool_keeps_raw_name_in_transcript_mode() {
    let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: "run_verifiers".to_string(),
        status: ToolStatus::Running,
        input_summary: Some("profile: auto, level: quick".to_string()),
        output: None,
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }));

    let text = lines_text(&cell.transcript_lines(80));
    assert!(text.contains("verify running"), "{text}");
    assert!(
        text.contains("name: run_verifiers"),
        "transcript replay should preserve exact tool id: {text}"
    );
}

#[test]
fn unknown_generic_tool_keeps_raw_name_in_live_mode() {
    let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: "future_private_tool".to_string(),
        status: ToolStatus::Running,
        input_summary: Some("query: foo".to_string()),
        output: None,
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }));

    let text = lines_text(&cell.lines(80));
    // Unknown/Generic tools collapse to a single header line in live mode.
    assert!(
        !text.is_empty(),
        "collapsed header must still render: {text}"
    );
}

#[test]
fn generic_tool_cell_preserves_multi_line_output_in_transcript() {
    // Repro for #80: a `git diff --stat`-shaped tool result should keep
    // its newlines on the transcript surface — one file per row, not
    // squashed into a single line.
    let diff_stat = "Cargo.lock                |  1 +\n\
                     crates/cli/Cargo.toml     |  1 +\n\
                     crates/cli/src/main.rs    | 47 ++++++\n\
                     crates/config/src/lib.rs  | 27 ++++\n\
                     crates/tui/src/mcp.rs     | 384 +++++";

    let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Success,
        input_summary: Some("command: git diff --stat".to_string()),
        output: Some(diff_stat.to_string()),
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }));

    let transcript_text = lines_text(&cell.transcript_lines(80));

    // Each file path must appear on its own row in the transcript.
    for needle in [
        "Cargo.lock",
        "crates/cli/Cargo.toml",
        "crates/cli/src/main.rs",
        "crates/config/src/lib.rs",
        "crates/tui/src/mcp.rs",
    ] {
        assert!(
            transcript_text.contains(needle),
            "transcript missing '{needle}': {transcript_text}"
        );
    }
    // The pre-fix bug: result line containing
    // "Cargo.lock | 1 + crates/cli/Cargo.toml" — joined into one row.
    // With the fix, the diff-stat pipes are still present per-line, but
    // adjacent file paths are on separate rendered rows. Assert that the
    // first file's line ends before the second begins.
    let lines: Vec<&str> = transcript_text.lines().collect();
    let cargo_lock_line = lines
        .iter()
        .find(|l| l.contains("Cargo.lock"))
        .expect("Cargo.lock row must exist");
    assert!(
        !cargo_lock_line.contains("crates/cli/Cargo.toml"),
        "Cargo.lock row must not also contain the second file: {cargo_lock_line}"
    );
}

#[test]
fn generic_tool_cell_caps_failed_multi_line_output_in_live_with_affordance() {
    // Failed tools keep error output visible in live mode, capped at
    // TOOL_OUTPUT_LINE_LIMIT (=6) with an omission marker.
    let total = 30usize;
    let output = (0..total)
        .map(|i| format!("row {i:02}: payload"))
        .collect::<Vec<_>>()
        .join("\n");

    let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Failed,
        input_summary: Some("command: ls".to_string()),
        output: Some(output),
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }));

    let live = cell.lines_with_options(80, TranscriptRenderOptions::default());
    let transcript = cell.transcript_lines(80);

    assert!(
        live.len() < transcript.len(),
        "live generic-tool output must be shorter than transcript (live={}, transcript={})",
        live.len(),
        transcript.len(),
    );
    let live_text = lines_text(&live);
    assert!(
        live_text.contains("lines omitted"),
        "live view must show the omission marker: {live_text}"
    );
    let transcript_text = lines_text(&transcript);
    assert!(transcript_text.contains("row 29"));
}

#[test]
fn generic_tool_failed_output_live_renders_card_rail() {
    let output = (0..24usize)
        .map(|i| format!("line {i:02}"))
        .collect::<Vec<_>>()
        .join("\n");
    let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Failed,
        input_summary: Some("command: noisy".to_string()),
        output: Some(output),
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }));

    let live_text = lines_text(&cell.lines_with_options(80, TranscriptRenderOptions::default()));

    // Card-rail wrapping: first line starts with ╭, last with ╰.
    assert!(
        live_text.starts_with('\u{256D}'),
        "live view must start with card-rail top glyph ╭: {live_text}"
    );
    assert!(live_text.contains("lines omitted"));
    assert!(live_text.contains("line 00"));
    assert!(live_text.contains("line 23"));
}

#[test]
fn generic_tool_success_live_collapses_output_transcript_keeps_it() {
    let output = (0..24usize)
        .map(|i| format!("row {i:02}: payload"))
        .collect::<Vec<_>>()
        .join("\n");
    let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Success,
        input_summary: Some("path: crates/tui/src/main.rs".to_string()),
        output: Some(output),
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }));

    let live_text = lines_text(&cell.lines_with_options(80, TranscriptRenderOptions::default()));
    let transcript_text = lines_text(&cell.transcript_lines(80));

    assert!(
        !live_text.contains("row 00"),
        "successful generic tool output should be hidden live: {live_text}"
    );
    assert!(
        !live_text.contains("lines omitted"),
        "collapsed success should not spend a row on an omission marker: {live_text}"
    );
    assert!(transcript_text.contains("row 00"));
    assert!(transcript_text.contains("row 23"));
}

#[test]
fn tool_output_live_preserves_error_card_rail() {
    let output = [
        "start",
        "still starting",
        "middle noise 1",
        "fatal: failed to read /tmp/deepseek/config.toml",
        "middle noise 2",
        "see https://example.test/build/log for details",
        "middle noise 3",
        "almost done",
        "final line",
    ]
    .join("\n");
    let cell = HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: "read_file".to_string(),
        status: ToolStatus::Failed,
        input_summary: Some("command: tool".to_string()),
        output: Some(output),
        prompts: None,
        spillover_path: None,
        output_summary: Some("Error: failed to read config".to_string()),
        is_diff: false,
    }));

    let live_text = lines_text(&cell.lines_with_options(80, TranscriptRenderOptions::default()));

    // Live mode: one-line summary + omission marker.
    assert!(
        live_text.contains("lines omitted"),
        "live view must show the omission marker: {live_text}"
    );
    // The pre-computed summary captures the first meaningful content.
    assert!(
        live_text.contains("Error:") || live_text.contains("fatal:"),
        "live summary should capture error text: {live_text}"
    );
}

// === ErrorEnvelope severity → cell color tests (#66) ===

/// Snapshot: an `Error`-severity cell uses the red status palette token
/// for both the leading "Error" label glyph and the body. This is the
/// load-bearing visual signal that distinguishes an error cell from a
/// neutral system note.
#[test]
fn error_severity_cell_renders_in_red() {
    let cell = HistoryCell::Error {
        message: "Authentication failed: invalid API key".to_string(),
        severity: crate::error_taxonomy::ErrorSeverity::Error,
    };
    let lines = cell.lines(80);
    assert!(
        !lines.is_empty(),
        "error cell must render at least one line"
    );

    let head = &lines[0];
    let label_span = &head.spans[0];
    assert_eq!(label_span.content.as_ref(), "Error");
    assert_eq!(label_span.style.fg, Some(palette::STATUS_ERROR));
    assert!(label_span.style.add_modifier.contains(Modifier::BOLD));

    // The body carries the error message and is rendered in the same red.
    let body_text = lines
        .iter()
        .flat_map(|line| line.spans.iter().map(|span| span.content.as_ref()))
        .collect::<String>();
    assert!(body_text.contains("Authentication failed"));
    // Find a span whose text contains "Authentication" and verify its color.
    let body_span = lines
        .iter()
        .flat_map(|line| line.spans.iter())
        .find(|span| span.content.contains("Authentication"))
        .expect("error body span must exist");
    assert_eq!(body_span.style.fg, Some(palette::STATUS_ERROR));
}

/// `Warning`-severity uses amber, not red — distinguishes a transient
/// retry hiccup from a hard failure.
#[test]
fn warning_severity_cell_renders_in_amber() {
    let cell = HistoryCell::Error {
        message: "Stream stalled: no data received for 60s, closing stream".to_string(),
        severity: crate::error_taxonomy::ErrorSeverity::Warning,
    };
    let lines = cell.lines(80);
    let label_span = &lines[0].spans[0];
    assert_eq!(label_span.content.as_ref(), "Warn");
    assert_eq!(label_span.style.fg, Some(palette::STATUS_WARNING));
}

/// `Critical` severity collapses to the same red as `Error` — both flip
/// offline mode and both should read as the loudest signal in the
/// transcript.
#[test]
fn critical_severity_cell_renders_in_red() {
    let cell = HistoryCell::Error {
        message: "API key expired".to_string(),
        severity: crate::error_taxonomy::ErrorSeverity::Critical,
    };
    let lines = cell.lines(80);
    let label_span = &lines[0].spans[0];
    assert_eq!(label_span.content.as_ref(), "Error");
    assert_eq!(label_span.style.fg, Some(palette::STATUS_ERROR));
}

/// `Info` severity stays neutral / dim so it doesn't draw the eye away
/// from real failures sitting alongside it in the transcript.
#[test]
fn info_severity_cell_renders_in_dim() {
    let cell = HistoryCell::Error {
        message: "Reconnected".to_string(),
        severity: crate::error_taxonomy::ErrorSeverity::Info,
    };
    let lines = cell.lines(80);
    let label_span = &lines[0].spans[0];
    assert_eq!(label_span.content.as_ref(), "Info");
    assert_eq!(label_span.style.fg, Some(palette::TEXT_DIM));
}

fn success_generic_tool(name: &str) -> HistoryCell {
    HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: name.to_string(),
        status: ToolStatus::Success,
        input_summary: Some(format!("args for {name}")),
        output: Some(format!("output for {name}")),
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }))
}

fn failed_generic_tool(name: &str) -> HistoryCell {
    HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: name.to_string(),
        status: ToolStatus::Failed,
        input_summary: None,
        output: Some("failed".to_string()),
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }))
}

fn running_generic_tool(name: &str) -> HistoryCell {
    HistoryCell::Tool(ToolCell::Generic(GenericToolCell {
        name: name.to_string(),
        status: ToolStatus::Running,
        input_summary: None,
        output: None,
        prompts: None,
        spillover_path: None,
        output_summary: None,
        is_diff: false,
    }))
}

fn shell_tool(command: &str) -> HistoryCell {
    HistoryCell::Tool(ToolCell::Exec(ExecCell {
        command: command.to_string(),
        status: ToolStatus::Success,
        output: Some("ok".to_string()),
        live_output: None,
        shell_task_id: None,
        owner_agent_id: None,
        owner_agent_name: None,
        started_at: None,
        duration_ms: None,
        source: ExecSource::Assistant,
        interaction: None,
        output_summary: None,
    }))
}

#[test]
fn detect_tool_runs_finds_contiguous_successful_safe_tools() {
    let history = vec![
        HistoryCell::User {
            content: "go".to_string(),
        },
        success_generic_tool("read_file"),
        success_generic_tool("list_dir"),
        success_generic_tool("web_search"),
        HistoryCell::Assistant {
            content: "done".to_string(),
            streaming: false,
        },
    ];

    let runs = super::detect_tool_runs(&history, 3);

    assert_eq!(runs.len(), 1);
    assert_eq!(runs[0].start, 1);
    assert_eq!(runs[0].count, 3);
    assert_eq!(
        runs[0].tool_families,
        vec!["read_file", "list_dir", "web_search"]
    );
    assert_eq!(runs[0].activity.files, 2);
    assert_eq!(runs[0].activity.searches, 1);
}

#[test]
fn detect_tool_runs_honors_threshold_and_boundaries() {
    let short = vec![
        success_generic_tool("read_file"),
        success_generic_tool("list_dir"),
    ];
    assert!(super::detect_tool_runs(&short, 3).is_empty());

    let with_assistant_boundary = vec![
        success_generic_tool("read_file"),
        HistoryCell::Assistant {
            content: "pause".to_string(),
            streaming: false,
        },
        success_generic_tool("list_dir"),
        success_generic_tool("web_search"),
    ];
    assert!(super::detect_tool_runs(&with_assistant_boundary, 3).is_empty());
}

#[test]
fn detect_tool_runs_keeps_failed_running_and_shell_cells_visible() {
    let history = vec![
        success_generic_tool("read_file"),
        success_generic_tool("list_dir"),
        failed_generic_tool("web_search"),
        success_generic_tool("read_file"),
        success_generic_tool("list_dir"),
        running_generic_tool("web_search"),
        success_generic_tool("read_file"),
        success_generic_tool("list_dir"),
        shell_tool("rm -rf target"),
        success_generic_tool("read_file"),
        success_generic_tool("list_dir"),
        success_generic_tool("web_search"),
    ];

    let runs = super::detect_tool_runs(&history, 3);

    assert_eq!(runs.len(), 1);
    assert_eq!(runs[0].start, 9);
    assert_eq!(runs[0].count, 3);
}

#[test]
fn detect_tool_runs_summarizes_safe_command_tools() {
    let history = vec![
        success_generic_tool("run_tests"),
        success_generic_tool("run_verifiers"),
        success_generic_tool("validate_data"),
    ];

    let runs = super::detect_tool_runs(&history, 3);

    assert_eq!(runs.len(), 1);
    assert_eq!(runs[0].start, 0);
    assert_eq!(runs[0].count, 3);
    assert_eq!(runs[0].activity.commands, 3);
    assert_eq!(
        runs[0].tool_families,
        vec!["run_tests", "run_verifiers", "validate_data"]
    );
    assert_eq!(
        super::tool_run_summary(&runs[0]),
        "Ran 3 commands: run_tests, run_verifiers, validate_data"
    );
}

#[test]
fn tool_run_summary_reports_compact_success_group() {
    let run = super::ToolRun {
        start: 4,
        count: 5,
        tool_families: vec!["read_file".to_string(), "list_dir".to_string()],
        activity: super::ToolRunActivitySummary {
            files: 4,
            searches: 1,
            ..Default::default()
        },
    };

    let summary = super::tool_run_summary(&run);

    assert_eq!(summary, "Explored 4 files, 1 search");
}

#[test]
fn tool_run_summary_lists_only_command_families_for_command_clause() {
    let run = super::ToolRun {
        start: 4,
        count: 4,
        tool_families: vec![
            "read_file".to_string(),
            "run_tests".to_string(),
            "validate_data".to_string(),
        ],
        activity: super::ToolRunActivitySummary {
            files: 2,
            commands: 2,
            ..Default::default()
        },
    };

    assert_eq!(
        super::tool_run_summary(&run),
        "Explored 2 files, ran 2 commands: run_tests, validate_data"
    );
}

#[test]
fn tool_run_summary_uses_metadata_fallback_for_unknown_groups() {
    let run = super::ToolRun {
        start: 4,
        count: 2,
        tool_families: vec!["session_sync".to_string()],
        activity: super::ToolRunActivitySummary {
            other: 2,
            ..Default::default()
        },
    };

    assert_eq!(super::tool_run_summary(&run), "Updated metadata");
}