cctop 0.2.0

An htop-like terminal monitor for AI coding agent sessions (Claude Code, Codex, Cursor, Gemini CLI, OpenCode, Pi, Windsurf)
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
//! Content builders for the bottom tab panels.
//!
//! Each returns `Vec<Line>` so the caller can scroll and clip uniformly; only
//! the Performance tab draws itself, since it renders charts rather than text.

use super::theme;
use crate::pricing::{Plan, Provider};
use crate::session::{Session, SessionData, Subagent, SubagentStatus, Surface};
use crate::util;
use chrono::{DateTime, Utc};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use std::path::Path;

pub const TABS: [&str; 8] = [
    "Info",
    "Performance",
    "Processes",
    "Tool Activity",
    "Subagents",
    "Cost",
    "Config",
    "Context",
];

fn label(text: &str) -> Span<'static> {
    Span::styled(text.to_string(), theme::label())
}

fn value(text: impl Into<String>) -> Span<'static> {
    Span::styled(text.into(), theme::value())
}

fn dim(text: impl Into<String>) -> Span<'static> {
    Span::styled(text.into(), theme::dim())
}

fn note(text: &str) -> Vec<Line<'static>> {
    vec![Line::from(dim(text.to_string()))]
}

fn is_free_model(model: &crate::session::ModelBreakdown) -> bool {
    model.total == 0.0
        && model.tokens.all_input() + model.tokens.output + model.tokens.reasoning_output > 0
}

fn displayed_cost(amount: f64, free: bool) -> String {
    if free {
        "FREE".into()
    } else {
        util::adaptive_usd(amount)
    }
}

fn cost_style(amount: f64, free: bool) -> Style {
    Style::default().fg(if free {
        theme::DIMMER
    } else {
        theme::cost_color(amount)
    })
}

/// `LABEL   value`, with labels padded to a shared column.
fn field(name: &str, val: impl Into<String>) -> Line<'static> {
    Line::from(vec![
        label(&format!("{name:<9}")),
        Span::raw(" "),
        value(val),
    ])
}

/// Wall time advances while a local agent is live, including pauses between
/// transcript events. Once it exits, preserve the final activity span.
fn wall_duration_ms(session: &Session, now: DateTime<Utc>) -> Option<i64> {
    let started = util::parse_ts(&session.started_at)?;
    let ended = if session.is_running() {
        now
    } else {
        util::parse_ts(&session.last_active)?
    };
    Some((ended.timestamp_millis() - started.timestamp_millis()).max(0))
}

// ---------------------------------------------------------------------------
// Info
// ---------------------------------------------------------------------------

pub fn info(session: &Session, data: Option<&SessionData>, plan: Plan) -> Vec<Line<'static>> {
    let Some(data) = data else {
        return note("Loading…");
    };
    if let Some(err) = &data.error {
        return vec![
            Line::from(Span::styled(
                "Could not read this session:".to_string(),
                Style::default().fg(theme::COST_HIGH),
            )),
            Line::from(dim(err.clone())),
        ];
    }

    let mut lines = Vec::new();
    let provider_color = match session.surface {
        Surface::DesktopCowork => theme::DESKTOP_COWORK,
        Surface::DesktopCode => theme::DESKTOP_CODE,
        Surface::Editor => theme::CURSOR,
        Surface::Cli => match session.provider {
            Provider::Claude => theme::CLAUDE,
            Provider::Codex => theme::OPENAI,
            Provider::Cursor => theme::CURSOR,
            Provider::Gemini => theme::GEMINI,
            Provider::OpenCode => theme::OPENCODE,
            Provider::Pi => theme::PI,
            Provider::Windsurf => theme::WINDSURF,
        },
    };
    let model = if data.last_model.is_empty() {
        session.model.clone()
    } else {
        data.last_model.clone()
    };

    lines.push(Line::from(vec![
        label(&format!("{:<9}", "Type")),
        Span::raw(" "),
        Span::styled(
            session.surface.label(session.provider).to_string(),
            Style::default()
                .fg(provider_color)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw("    "),
        label("Model"),
        Span::raw("   "),
        Span::styled(
            model.clone(),
            Style::default()
                .fg(theme::model_color(&model))
                .add_modifier(Modifier::BOLD),
        ),
    ]));

    lines.push(field("ID", session.session_id.clone()));
    if !session.harness.is_empty() {
        lines.push(field("Harness", session.harness.clone()));
    }
    if let Some(t) = &session.title {
        lines.push(field("Title", t.clone()));
    }
    lines.push(field(
        "Dir",
        util::tildify(if session.label_source.is_empty() {
            "unknown"
        } else {
            &session.label_source
        }),
    ));
    let cmd = match session.provider {
        Provider::Claude => format!("claude --resume {}", session.session_id),
        Provider::Codex => format!("codex resume {}", session.session_id),
        Provider::Cursor => "Open from Cursor history".to_string(),
        Provider::Gemini => "gemini, then /chat resume".to_string(),
        Provider::OpenCode => format!("opencode --session {}", session.session_id),
        Provider::Pi => format!("pi --session {}", session.session_id),
        Provider::Windsurf => "Open from Windsurf history".to_string(),
    };
    lines.push(field("Cmd", cmd));
    lines.push(field("Plan", plan.as_str()));
    if let Some(effort) = &data.reasoning_effort {
        lines.push(field("Effort", effort.clone()));
    }
    if data.tokens.reasoning_output > 0 {
        lines.push(field(
            "Reasoning",
            format!("{} tokens", util::with_commas(data.tokens.reasoning_output)),
        ));
    }

    let account = match session.provider {
        Provider::Claude => crate::quota::claude_account(),
        Provider::Codex => crate::quota::codex_account(),
        Provider::Cursor
        | Provider::Gemini
        | Provider::OpenCode
        | Provider::Pi
        | Provider::Windsurf => None,
    };
    if let Some(a) = account {
        if let Some(email) = a.email {
            lines.push(field("Account", email));
        }
        if let Some(org) = a.organization {
            lines.push(field("Org", org));
        }
    }

    if let Some(started) = util::parse_ts(&session.started_at) {
        lines.push(field(
            "Started",
            started
                .with_timezone(&chrono::Local)
                .format("%Y-%m-%d %H:%M:%S")
                .to_string(),
        ));
    }
    // API time is what the model actually spent working; wall time includes
    // every pause while the user was reading or typing.
    if data.metrics.api_duration_ms > 0 {
        lines.push(field(
            "API",
            util::long_duration(data.metrics.api_duration_ms as i64),
        ));
    }
    if let Some(wall_ms) = wall_duration_ms(session, Utc::now()) {
        lines.push(field("Wall", util::long_duration(wall_ms)));
    }

    let m = &data.metrics;
    if m.lines_added > 0 || m.lines_removed > 0 {
        lines.push(Line::from(vec![
            label(&format!("{:<9}", "Lines")),
            Span::raw(" "),
            Span::styled(
                format!("+{}", util::with_commas(m.lines_added)),
                Style::default().fg(theme::COST_LOW),
            ),
            Span::raw("  "),
            Span::styled(
                format!("-{}", util::with_commas(m.lines_removed)),
                Style::default().fg(theme::COST_HIGH),
            ),
        ]));
    }

    if let Some(ctx) = &session.context {
        lines.push(Line::default());
        if session.is_compacting() {
            lines.push(Line::from(vec![
                label("Compaction"),
                Span::raw(" "),
                Span::styled(
                    "compacting…".to_string(),
                    Style::default()
                        .fg(theme::COST_HIGH)
                        .add_modifier(Modifier::BOLD),
                ),
            ]));
        } else if ctx.compacted {
            // The percentage below would be of a window this session compacted
            // away, and nothing has measured what replaced it.
            lines.push(Line::from(vec![
                label("Compaction"),
                Span::raw(" "),
                dim("compacted; no request since"),
            ]));
        } else {
            let compact_at = (ctx.max as f64 * *crate::config::COMPACT_THRESHOLD).round() as u64;
            let pct = ctx.percent_to_compact();
            let color = theme::context_color(pct);
            lines.push(Line::from(vec![
                label("Compaction"),
                Span::raw(" "),
                Span::styled(
                    format!("{:>3}%", pct.round() as i64),
                    Style::default().fg(color).add_modifier(Modifier::BOLD),
                ),
                Span::raw("  "),
                label("used"),
                Span::raw(" "),
                value(util::compact_tokens(ctx.used)),
                Span::raw(" "),
                label("of"),
                Span::raw(" "),
                value(util::compact_tokens(compact_at)),
                Span::raw(" "),
                label("tokens"),
            ]));
            lines.push(Line::from(vec![
                Span::raw("           "),
                bar(pct / 100.0, 40, color),
            ]));
        }
    }

    lines
}

/// A horizontal meter: filled portion in `color`, remainder dimmed.
fn bar(ratio: f64, width: usize, color: ratatui::style::Color) -> Span<'static> {
    let filled = ((ratio.clamp(0.0, 1.0)) * width as f64).round() as usize;
    Span::styled(
        format!("{}{}", "".repeat(filled), "".repeat(width - filled)),
        Style::default().fg(color),
    )
}

// ---------------------------------------------------------------------------
// Processes
// ---------------------------------------------------------------------------

pub fn processes(session: &Session, width: usize) -> Vec<Line<'static>> {
    if session.surface == Surface::DesktopCowork {
        return note("Cowork sessions run in a cloud VM — no local process tree.");
    }
    if session.surface == Surface::Editor && session.provider == Provider::Cursor {
        return note("Cursor uses a shared editor process — no per-session process tree.");
    }
    let Some(pm) = &session.process else {
        return note("Process data is only available for running sessions.");
    };
    if pm.process_list.is_empty() {
        return note("No process data available.");
    }

    let mut procs = pm.process_list.clone();
    procs.sort_by(|a, b| {
        b.cpu
            .partial_cmp(&a.cpu)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    let cmd_w = width.saturating_sub(7 + 2 + 6 + 2 + 8 + 2).max(10);
    let mut lines = Vec::new();
    if !pm.command.is_empty() {
        lines.push(Line::from(vec![
            label("Root"),
            Span::raw(" "),
            dim(util::truncate(
                &util::tildify(&pm.command),
                width.saturating_sub(6),
            )),
        ]));
    }
    lines.push(Line::from(Span::styled(
        format!("{:>7}  {:>6}  {:>8}  {}", "PID", "CPU%", "MEM", "COMMAND"),
        Style::default()
            .fg(ratatui::style::Color::White)
            .bg(theme::HEADER_BG)
            .add_modifier(Modifier::BOLD),
    )));

    for p in procs {
        // A recently-exited child is shown greyed rather than vanishing, so a
        // burst of short-lived tool subprocesses doesn't make the list flicker.
        let base = if p.ghost {
            Style::default().fg(theme::DIM)
        } else if p.is_root {
            theme::value()
        } else {
            Style::default().fg(ratatui::style::Color::Indexed(250))
        };
        let cpu_style = if p.ghost {
            base
        } else {
            Style::default().fg(theme::cpu_color(p.cpu))
        };

        let argv0 = p.args.split(' ').next().unwrap_or("");
        let name = argv0.rsplit('/').next().unwrap_or(argv0);
        let rest = p.args[argv0.len()..].trim_start();
        let cmd = if rest.is_empty() {
            name.to_string()
        } else {
            format!("{name} {rest}")
        };

        lines.push(Line::from(vec![
            Span::styled(format!("{:>7}", p.pid), base),
            Span::raw("  "),
            Span::styled(format!("{:>5.1}%", p.cpu), cpu_style),
            Span::raw("  "),
            Span::styled(format!("{:>8}", util::compact_bytes(p.memory)), base),
            Span::raw("  "),
            Span::styled(util::truncate(&cmd, cmd_w), base),
        ]));
    }
    lines
}

// ---------------------------------------------------------------------------
// Tool activity
// ---------------------------------------------------------------------------

/// Tool names for the sidebar, most-used first, with an "All" entry at index 0.
pub fn tool_tabs(data: &SessionData) -> Vec<(String, u64)> {
    let mut tools: Vec<(String, u64)> = data
        .metrics
        .tools
        .iter()
        .map(|(k, v)| (k.clone(), *v))
        .collect();
    tools.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    let mut out = vec![("All".to_string(), data.metrics.tool_count)];
    out.extend(tools);
    out
}

/// Invocation rows for the selected tool tab, oldest first.
/// Stable identity for one invocation, so an expanded row survives the log
/// growing beneath it. Row indices shift as new entries arrive; ids don't.
pub fn detail_key(d: &crate::session::ToolDetail) -> String {
    d.id.clone().unwrap_or_else(|| format!("{}|{}", d.ts, d.d))
}

/// Wrap text to `width`, breaking on the last space that fits.
fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut out = Vec::new();
    for raw in text.lines() {
        let mut line = raw;
        if line.is_empty() {
            out.push(String::new());
            continue;
        }
        while line.chars().count() > width {
            // Prefer the last space that still fits; fall back to a hard cut
            // when a single token is longer than the whole line.
            let mut cut = None;
            for (i, c) in line.char_indices().take(width + 1) {
                if c == ' ' {
                    cut = Some(i);
                }
            }
            let cut = cut.unwrap_or_else(|| {
                line.char_indices()
                    .nth(width)
                    .map(|(i, _)| i)
                    .unwrap_or(line.len())
            });
            let cut = if cut == 0 { line.len().min(width) } else { cut };
            out.push(line[..cut].to_string());
            line = line[cut..].trim_start();
        }
        out.push(line.to_string());
    }
    out
}

/// Rendered rows plus, for each rendered line, the invocation it belongs to.
///
/// The caller needs that mapping to turn a mouse click on a screen row back into
/// the entry under it, since wrapped and diff lines make the relationship
/// non-uniform.
pub fn tool_activity(
    data: &SessionData,
    tab: usize,
    live_since: Option<&str>,
    show_diff: bool,
    expanded: Option<&str>,
    width: usize,
) -> (Vec<Line<'static>>, Vec<Option<String>>) {
    let tabs = tool_tabs(data);
    let bare = |lines: Vec<Line<'static>>| {
        let owners = vec![None; lines.len()];
        (lines, owners)
    };
    if data.metrics.tool_count == 0 {
        return bare(note("No tool invocations."));
    }
    let Some((name, _)) = tabs.get(tab) else {
        return bare(note("No tool selected."));
    };
    let all = tab == 0;

    let mut rows: Vec<(String, &crate::session::ToolDetail)> = Vec::new();
    for (tool, details) in &data.metrics.tool_details {
        if !all && tool != name {
            continue;
        }
        rows.extend(details.iter().map(|d| (tool.clone(), d)));
    }
    if let Some(since) = live_since {
        rows.retain(|(_, d)| d.ts.as_str() >= since);
    }
    rows.sort_by(|a, b| a.1.ts.cmp(&b.1.ts));

    if rows.is_empty() {
        return bare(note(if live_since.is_some() {
            "No invocations since cctop started."
        } else {
            "No invocations recorded."
        }));
    }

    let mut out = Vec::with_capacity(rows.len());
    let mut owners: Vec<Option<String>> = Vec::with_capacity(rows.len());
    for (tool, d) in rows {
        let key = detail_key(d);
        let is_open = expanded == Some(key.as_str());
        let ts = util::parse_ts(&d.ts)
            .map(|t| t.with_timezone(&chrono::Local).format("%H:%M").to_string())
            .unwrap_or_else(|| "     ".into());
        // The gap after the timestamp doubles as a failure marker, so a failed
        // call is legible without relying on the background colour alone — and
        // the row's width is unchanged either way.
        let mut spans = vec![
            dim(ts),
            if d.failed {
                Span::styled("", Style::default().fg(theme::COST_HIGH))
            } else {
                Span::raw(" ")
            },
        ];
        let mut used = 6;

        // Who made the call: the main session, or one of its subagents. Subagent
        // activity is interleaved into the same log, so without a marker there
        // is no way to tell an agent's edits from the parent's.
        let origin_tag = match &d.origin {
            None => "main".to_string(),
            Some(agent) => {
                let short = agent.strip_prefix("agent-").unwrap_or(agent);
                format!("{}", &short[..short.len().min(6)])
            }
        };
        let origin_style = if d.origin.is_some() {
            Style::default().fg(theme::DESKTOP_CODE)
        } else {
            Style::default().fg(theme::DIMMER)
        };
        used += 8;
        spans.push(Span::styled(format!("{origin_tag:<7} "), origin_style));

        if all {
            let pretty = util::pretty_mcp_name(&tool);
            used += pretty.chars().count() + 1;
            spans.push(Span::styled(
                format!("{pretty} "),
                Style::default().fg(tool_color(&tool)),
            ));
        }

        // Right-hand metrics are built first so the detail column can claim
        // exactly the width they leave behind.
        let mut trailing: Vec<Span<'static>> = Vec::new();
        if let Some(delta) = &d.delta {
            trailing.push(Span::styled(
                format!(" +{}", delta.added),
                Style::default().fg(theme::COST_LOW),
            ));
            trailing.push(Span::styled(
                format!(" -{}", delta.removed),
                Style::default().fg(theme::COST_HIGH),
            ));
        }
        if let Some(ms) = d.dur_ms {
            trailing.push(Span::styled(
                format!(" {:>7}", fmt_millis(ms)),
                theme::dim(),
            ));
        }
        if d.tokens_in > 0 || d.tokens_out > 0 {
            // `shared` marks a turn that issued several calls: the counts below
            // belong to the whole turn, not to this call alone.
            let mark = if d.shared > 1 { "*" } else { " " };
            trailing.push(Span::styled(
                format!(
                    "{mark}{:>6}{:>5}",
                    util::compact_tokens(d.tokens_in),
                    util::compact_tokens(d.tokens_out)
                ),
                Style::default().fg(theme::DIM),
            ));
        }
        let trailing_w: usize = trailing.iter().map(|sp| sp.content.chars().count()).sum();

        let text = util::tildify(&d.d);
        let detail_w = width.saturating_sub(used + trailing_w).max(8);
        spans.push(value(format!(
            "{:<detail_w$}",
            util::truncate(&text, detail_w)
        )));
        spans.extend(trailing);
        let row_style = if d.failed {
            Style::default().bg(theme::FAILED_BG)
        } else {
            Style::default()
        };
        out.push(Line::from(spans).style(row_style));
        owners.push(Some(key.clone()));

        // Expanded: show the untruncated argument, wrapped.
        if is_open {
            let full = d.full.as_deref().unwrap_or(&d.d);
            for line in wrap(full, width.saturating_sub(10)) {
                out.push(
                    Line::from(vec![
                        Span::raw("        "),
                        Span::styled(
                            line,
                            Style::default().fg(ratatui::style::Color::Indexed(252)),
                        ),
                    ])
                    .style(row_style),
                );
                owners.push(Some(key.clone()));
            }
        }

        if show_diff && let Some(delta) = &d.delta {
            for hunk in &delta.hunks {
                let style = match hunk.chars().next() {
                    Some('+') => Style::default().fg(theme::COST_LOW),
                    Some('-') => Style::default().fg(theme::COST_HIGH),
                    _ => Style::default().fg(theme::DIMMER),
                };
                out.push(Line::from(vec![
                    Span::raw("        "),
                    Span::styled(util::truncate(hunk, width.saturating_sub(9)), style),
                ]));
                owners.push(Some(key.clone()));
            }
        }
    }
    (out, owners)
}

/// Sub-second durations read better in milliseconds than as `0s`.
fn fmt_millis(ms: i64) -> String {
    if ms < 1000 {
        format!("{ms}ms")
    } else if ms < 60_000 {
        format!("{:.1}s", ms as f64 / 1000.0)
    } else {
        util::compact_duration(ms)
    }
}

/// Stable per-tool colour so the same tool keeps its hue between refreshes.
fn tool_color(name: &str) -> ratatui::style::Color {
    const PALETTE: [u8; 10] = [75, 114, 173, 180, 139, 109, 146, 215, 152, 167];
    let hash = name
        .bytes()
        .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32));
    ratatui::style::Color::Indexed(PALETTE[(hash as usize) % PALETTE.len()])
}

// ---------------------------------------------------------------------------
// Subagents
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubagentSort {
    Last,
    Type,
    Model,
    Description,
    Cost,
    Tools,
    Context,
    Duration,
}

impl SubagentSort {
    pub fn key(&self) -> &'static str {
        match self {
            SubagentSort::Last => "last",
            SubagentSort::Type => "type",
            SubagentSort::Model => "model",
            SubagentSort::Description => "desc",
            SubagentSort::Cost => "cost",
            SubagentSort::Tools => "tools",
            SubagentSort::Context => "ctx",
            SubagentSort::Duration => "dur",
        }
    }

    pub fn parse(s: &str) -> Self {
        match s {
            "type" => SubagentSort::Type,
            "model" => SubagentSort::Model,
            "desc" => SubagentSort::Description,
            "cost" => SubagentSort::Cost,
            "tools" => SubagentSort::Tools,
            "ctx" => SubagentSort::Context,
            "dur" => SubagentSort::Duration,
            _ => SubagentSort::Last,
        }
    }
}

pub fn sort_subagents(list: &mut [Subagent], sort: SubagentSort, asc: bool) {
    list.sort_by(|a, b| {
        let ord = match sort {
            SubagentSort::Last => a
                .last_active
                .as_deref()
                .unwrap_or_default()
                .cmp(b.last_active.as_deref().unwrap_or_default()),
            SubagentSort::Type => a.agent_type.cmp(&b.agent_type),
            SubagentSort::Model => a.model.cmp(&b.model),
            SubagentSort::Description => a.description.cmp(&b.description),
            SubagentSort::Cost => a
                .cost
                .partial_cmp(&b.cost)
                .unwrap_or(std::cmp::Ordering::Equal),
            SubagentSort::Tools => a.tool_count.cmp(&b.tool_count),
            SubagentSort::Context => {
                let r = |s: &Subagent| s.context.map(|c| c.percent_to_compact()).unwrap_or(-1.0);
                r(a).partial_cmp(&r(b)).unwrap_or(std::cmp::Ordering::Equal)
            }
            SubagentSort::Duration => a.duration_ms.cmp(&b.duration_ms),
        }
        .then_with(|| a.agent_id.cmp(&b.agent_id));
        if asc { ord } else { ord.reverse() }
    });
}

pub fn subagents(
    data: Option<&SessionData>,
    sort: SubagentSort,
    asc: bool,
    width: usize,
) -> Vec<Line<'static>> {
    let Some(data) = data else {
        return note("Loading…");
    };
    if data.subagents.is_empty() {
        return note("No subagents.");
    }
    let mut list = data.subagents.clone();
    sort_subagents(&mut list, sort, asc);

    let fixed = 6 + 2 + 2 + 12 + 1 + 12 + 1 + 8 + 1 + 6 + 1 + 5 + 1 + 7;
    let desc_w = width.saturating_sub(fixed).max(10);

    let mut lines = vec![Line::from(Span::styled(
        format!(
            "{:<6}   {:<12} {:<12} {:<desc_w$} {:>8} {:>6} {:>5} {:>7}",
            "LAST", "TYPE", "MODEL", "DESC", "COST", "TOOLS", "CTX", "TIME"
        ),
        Style::default()
            .fg(ratatui::style::Color::White)
            .bg(theme::HEADER_BG)
            .add_modifier(Modifier::BOLD),
    ))];

    let now = chrono::Utc::now();
    for sa in list {
        let running = sa.status == SubagentStatus::Running;
        // A ghost's transcript was purged, so its per-agent metrics are gone;
        // showing zeros would read as "did nothing" rather than "unknown".
        let (icon, icon_color) = if sa.ghost {
            ("", theme::DIM)
        } else if running {
            ("", theme::COST_LOW)
        } else {
            ("", theme::DIM)
        };
        let row_style = if sa.ghost {
            Style::default().fg(theme::DIM)
        } else if running {
            theme::value()
        } else {
            Style::default().fg(ratatui::style::Color::Indexed(250))
        };

        let last = sa
            .last_active
            .as_deref()
            .or(sa.started_at.as_deref())
            .map(|t| util::relative_age(t, &now))
            .unwrap_or_else(|| "".into());
        let unknown = |s: String| if sa.ghost { "".to_string() } else { s };
        let cost = unknown(util::compact_usd(sa.cost));
        let tools = unknown(sa.tool_count.to_string());
        let time = unknown(util::compact_duration(sa.duration_ms));
        let ctx = match (sa.ghost, sa.context) {
            (false, Some(c)) => format!("{}%", c.percent_to_compact().round() as i64),
            _ => "".into(),
        };

        lines.push(Line::from(vec![
            Span::styled(format!("{last:<6}"), row_style),
            Span::raw(" "),
            Span::styled(icon.to_string(), Style::default().fg(icon_color)),
            Span::raw(" "),
            Span::styled(
                format!("{:<12}", util::truncate(&sa.agent_type, 12)),
                row_style,
            ),
            Span::raw(" "),
            Span::styled(
                format!("{:<12}", util::truncate(&util::short_model(&sa.model), 12)),
                if sa.ghost {
                    row_style
                } else {
                    Style::default().fg(theme::model_color(&sa.model))
                },
            ),
            Span::raw(" "),
            Span::styled(
                format!("{:<desc_w$}", util::truncate(&sa.description, desc_w)),
                row_style,
            ),
            Span::raw(" "),
            Span::styled(
                format!("{cost:>8}"),
                if sa.ghost {
                    row_style
                } else {
                    Style::default().fg(theme::cost_color(sa.cost))
                },
            ),
            Span::raw(" "),
            Span::styled(format!("{tools:>6}"), row_style),
            Span::raw(" "),
            Span::styled(format!("{ctx:>5}"), row_style),
            Span::raw(" "),
            Span::styled(format!("{time:>7}"), row_style),
        ]));
    }
    lines
}

// ---------------------------------------------------------------------------
// Cost
// ---------------------------------------------------------------------------

pub fn cost(session: &Session, data: Option<&SessionData>, plan: Plan) -> Vec<Line<'static>> {
    let Some(data) = data else {
        return note("Loading…");
    };
    let included = plan.includes(session.provider);
    let mut lines = Vec::new();

    if !session.cost_available {
        return note("Cost and token usage are not present in Cursor transcripts.");
    }

    if included && !session.cost_is_free {
        lines.push(Line::from(vec![
            label("Total cost"),
            Span::raw("  "),
            dim("included in plan"),
        ]));
        lines.push(Line::default());
        lines.push(Line::from(dim(format!(
            "Retail-equivalent: {}",
            util::compact_usd(data.costs.total)
        ))));
        return lines;
    }

    lines.push(Line::from(vec![
        label("Total cost"),
        Span::raw("  "),
        Span::styled(
            displayed_cost(data.costs.total, session.cost_is_free),
            cost_style(data.costs.total, session.cost_is_free).add_modifier(Modifier::BOLD),
        ),
    ]));
    lines.push(Line::from(dim(
        "estimate: tokens × published per-token rates",
    )));
    lines.push(Line::default());

    // Calendar-bucket spend windows.
    let now = chrono::Utc::now();
    let midnight = util::local_midnight_today();
    let today = util::local_date_key(&midnight);
    let week = util::local_date_key(&(midnight - chrono::Duration::days(6)));
    let month = util::local_date_key(&(midnight - chrono::Duration::days(29)));
    let hour = util::local_hour_key(&now);

    let sum_day = |from: &str| -> f64 {
        data.costs_by_day
            .iter()
            .filter(|(d, _)| d.as_str() >= from)
            .map(|(_, m)| m.values().sum::<f64>())
            .sum()
    };
    let hour_cost: f64 = data
        .costs_by_hour
        .get(&hour)
        .map(|m| m.values().sum())
        .unwrap_or(0.0);

    for (name, amount) in [
        ("this hour", hour_cost),
        ("today", sum_day(&today)),
        ("7 days", sum_day(&week)),
        ("30 days", sum_day(&month)),
    ] {
        lines.push(Line::from(vec![
            label(&format!("  {name:<10}")),
            Span::styled(
                format!("{:>10}", displayed_cost(amount, session.cost_is_free)),
                cost_style(amount, session.cost_is_free),
            ),
        ]));
    }

    // Per-model breakdown.
    for mb in &data.model_breakdown {
        let free_model = is_free_model(mb);
        lines.push(Line::default());
        lines.push(Line::from(vec![
            value(mb.model.clone()),
            Span::raw("  "),
            Span::styled(
                displayed_cost(mb.total, free_model),
                cost_style(mb.total, free_model),
            ),
        ]));
        let rows: [(&str, u64, f64); 5] = [
            ("in", mb.tokens.input, mb.costs.input),
            ("out", mb.tokens.output, mb.costs.output),
            (
                "cache↓",
                mb.tokens.cache_read + mb.tokens.cached_input,
                mb.costs.cache_read + mb.costs.cached_input,
            ),
            (
                "cache↑",
                mb.tokens.cache_write_5m + mb.tokens.cache_write_1h,
                mb.costs.cache_write_5m + mb.costs.cache_write_1h,
            ),
            ("reasoning", mb.tokens.reasoning_output, 0.0),
        ];
        for (name, tokens, amount) in rows {
            if tokens == 0 {
                continue;
            }
            lines.push(Line::from(vec![
                label(&format!("  {name:<9}")),
                value(format!("{:>8}", util::compact_tokens(tokens))),
                Span::raw("  "),
                Span::styled(
                    format!("{:>10}", displayed_cost(amount, free_model)),
                    cost_style(amount, free_model),
                ),
            ]));
        }
    }

    if let Some(r) = &data.rates {
        lines.push(Line::default());
        lines.push(Line::from(dim(format!(
            "rates per 1M tokens — in ${:.2}  cached ${:.3}  out ${:.2}",
            r.input, r.cached_input, r.output
        ))));
    }

    lines
}

// ---------------------------------------------------------------------------
// Context breakdown
// ---------------------------------------------------------------------------

/// One category of what the window holds.
struct Slice {
    name: &'static str,
    tokens: u64,
    color: ratatui::style::Color,
    /// What the bar and the legend swatch are drawn with. Solid for everything
    /// the window holds; the free remainder is shaded so that "nothing is here
    /// yet" does not read as one more category.
    fill: char,
}

impl Slice {
    fn held(name: &'static str, tokens: u64, color: ratatui::style::Color) -> Self {
        Slice {
            name,
            tokens,
            color,
            fill: '',
        }
    }
}

/// What the context window is filled with, largest share first.
///
/// The panel's job is to be believed, so it never pretends the parts add up.
/// `Startup` is measured and the other categories are estimated from transcript
/// characters, and whatever the two together fail to reach gets its own share
/// instead of being spread over the categories that happen to be measurable.
///
/// The shares are drawn as one stacked bar rather than as a bar apiece: the
/// question the panel answers is what proportion of a *single* window each
/// category holds, and separate bars make that a comparison between rows instead
/// of something the eye reads off at once. It also leaves room for the window's
/// unused remainder, which is the part a bar-per-row cannot show at all.
pub fn context(session: &Session, data: Option<&SessionData>, width: usize) -> Vec<Line<'static>> {
    let Some(data) = data else {
        return note("Loading…");
    };
    let Some(b) = data.context_breakdown else {
        return note("This transcript reports no per-request usage — nothing to break down.");
    };

    use ratatui::style::Color::Indexed;
    let mut slices = vec![
        // Named for what it holds rather than "system prompt", because after a
        // compaction the summary is folded into the same number.
        Slice::held("Startup", b.startup, theme::PANEL_TITLE),
        Slice::held("Tool output", b.tool_output, Indexed(75)),
        Slice::held("Tool input", b.tool_input, Indexed(109)),
        Slice::held("Attachments", b.attachments, Indexed(180)),
        Slice::held("Your messages", b.user_text, theme::COST_LOW),
        Slice::held("Assistant text", b.assistant_text, Indexed(139)),
    ];
    slices.retain(|s| s.tokens > 0);
    slices.sort_by_key(|s| std::cmp::Reverse(s.tokens));
    // Pinned last wherever it lands by size: it is the leftover, and it belongs
    // against the free remainder rather than in the middle of the measured
    // categories.
    let unaccounted = b.unaccounted();
    if unaccounted > 0 {
        slices.push(Slice::held("Unaccounted", unaccounted as u64, theme::DIM));
    }
    // What is still free, so the bar is the whole window rather than only the
    // part already spent — which is what makes the used portion's length mean
    // something at a glance.
    let free = session
        .context
        .map(|ctx| ctx.max.saturating_sub(b.total))
        .unwrap_or(0);
    if free > 0 {
        slices.push(Slice {
            name: "Free",
            tokens: free,
            color: theme::DIMMER,
            fill: '',
        });
    }

    let compaction = compaction_cell(session, &slices, b.superseded, width);
    let mut lines = vec![context_header(session, &b)];
    lines.push(Line::default());
    lines.push(stacked_bar(&slices, compaction, width));
    lines.push(Line::default());
    lines.extend(legend(&slices, width));
    lines.push(Line::default());
    lines.extend(context_footnotes(
        &b,
        unaccounted,
        compaction.is_some(),
        width,
    ));
    lines.extend(context_timeline(session, data, width));
    lines
}

/// The window across every request the session made, under the bar that shows
/// what it currently holds.
///
/// The bar answers "what is in there"; this answers "how did it get that full",
/// which is the question that changes what anyone does next. A window that
/// climbed evenly is a conversation that grew and will keep growing. One that
/// stepped is a handful of large tool results, and the same call will do it
/// again. A sawtooth is a session living on compactions, paying to rebuild its
/// context over and over.
fn context_timeline(session: &Session, data: &SessionData, width: usize) -> Vec<Line<'static>> {
    // Two points is a line between two measurements, which says nothing a
    // reader could not get from the header. Below that there is no shape.
    if data.context_series.len() < 3 || width < 24 {
        return Vec::new();
    }
    let values: Vec<f64> = data
        .context_series
        .iter()
        .map(|p| p.window as f64)
        .collect();
    // Scaled to the window rather than to the tallest point, so the chart's
    // height means the same thing as the bar above it: how full, not how much
    // taller than the rest of this session.
    let max = session
        .context
        .map(|c| c.max as f64)
        .filter(|m| *m > 0.0)
        .unwrap_or_else(|| values.iter().cloned().fold(1.0, f64::max));

    let compactions = data
        .context_series
        .iter()
        .filter(|p| p.after_compaction)
        .count();
    let peak = values.iter().cloned().fold(0.0, f64::max);

    let mut lines = vec![
        Line::default(),
        Line::from(vec![
            label("How it filled  "),
            dim(format!("{} requests", data.context_series.len())),
            dim("   peak "),
            value(crate::util::compact_tokens(peak as u64)),
            match compactions {
                0 => dim(String::new()),
                // Named on the chart because they are the only drops in it: a
                // fall with no compaction behind it would be a measurement
                // error, and telling the two apart matters.
                n => dim(format!(
                    "   {n} compaction{}",
                    if n == 1 { "" } else { "s" }
                )),
            },
        ]),
    ];
    lines.extend(crate::ui::spark::line_chart(
        &values,
        width,
        5,
        max,
        theme::Gradient::Accent,
        None,
    ));
    lines
}

/// Which bar cell the auto-compact threshold falls on, when it is still ahead.
///
/// Marking it turns the free remainder into two readable parts: the room that is
/// genuinely usable, and the tail past the threshold that the harness will
/// reclaim before it is ever reached. `None` once the threshold is behind — the
/// header already says so in red, and a marker there would erase a category.
fn compaction_cell(
    session: &Session,
    slices: &[Slice],
    superseded: bool,
    width: usize,
) -> Option<usize> {
    let ctx = session.context?;
    let scale = slices.iter().map(|s| s.tokens).sum::<u64>();
    // Nothing to point at once the compaction has happened: the bar is a window
    // that has already been reclaimed, and a threshold ahead of it is a claim
    // about a window nobody has measured.
    if scale == 0 || superseded {
        return None;
    }
    let compact_at = ctx.max as f64 * *crate::config::COMPACT_THRESHOLD;
    let cell = (compact_at / scale as f64 * width as f64).round() as usize;
    // Only inside the free tail: elsewhere it would overwrite something held.
    let held: u64 = slices
        .iter()
        .filter(|s| s.name != "Free")
        .map(|s| s.tokens)
        .sum();
    let free_starts = (held as f64 / scale as f64 * width as f64).round() as usize;
    (cell > free_starts && cell < width).then_some(cell)
}

/// Window size, how full it is, and how much is left before auto-compaction.
///
/// Headroom in tokens rather than only a percentage: "how much can I still say"
/// is the decision this panel is consulted for, and a share of a window whose
/// size varies by model does not answer it. The gauge rides on the same line
/// because fullness is the one thing here worth seeing without reading.
fn context_header(session: &Session, b: &crate::session::ContextBreakdown) -> Line<'static> {
    let mut spans = vec![
        label("Window"),
        Span::raw("  "),
        value(util::compact_tokens(b.total)),
    ];
    let Some(ctx) = session.context else {
        spans.push(Span::raw(" "));
        spans.push(dim("in the live conversation"));
        return Line::from(spans);
    };

    spans.push(dim(format!(" of {}", util::compact_tokens(ctx.max))));
    // Headroom is the one thing that cannot be stated across a compaction: the
    // window below is the one that was compacted away, so how much is "left" in
    // the one replacing it is not known until its first request lands.
    if b.superseded {
        spans.push(Span::raw("   "));
        spans.push(if session.is_compacting() {
            Span::styled(
                "compacting…",
                Style::default()
                    .fg(theme::COST_HIGH)
                    .add_modifier(Modifier::BOLD),
            )
        } else {
            dim("as it stood before the last compaction")
        });
        return Line::from(spans);
    }

    let pct = ctx.percent_to_compact();
    let color = theme::context_color(pct);
    let compact_at = (ctx.max as f64 * *crate::config::COMPACT_THRESHOLD).round() as u64;
    // No gauge here: the bar below already shows how full the window is, and a
    // second meter measuring a *different* denominator — share of the threshold
    // rather than of the window — is two answers to one question.
    spans.push(Span::raw("   "));
    spans.push(Span::styled(
        format!("{}%", pct.round() as i64),
        Style::default().fg(color).add_modifier(Modifier::BOLD),
    ));
    spans.push(dim(" to compaction"));
    spans.push(Span::raw("   "));
    spans.push(value(util::compact_tokens(
        compact_at.saturating_sub(b.total),
    )));
    spans.push(dim(" left"));
    Line::from(spans)
}

/// Every category in one bar, in the legend's order, spanning the panel.
fn stacked_bar(slices: &[Slice], compaction: Option<usize>, width: usize) -> Line<'static> {
    let cells = width.max(1);
    let weights: Vec<u64> = slices.iter().map(|s| s.tokens).collect();

    // Laid out cell by cell so the threshold marker can replace one of them: a
    // marker appended as its own span would push the bar a cell past the panel.
    let mut cell_styles: Vec<(char, ratatui::style::Color)> = slices
        .iter()
        .zip(apportion(&weights, cells))
        .flat_map(|(slice, w)| std::iter::repeat_n((slice.fill, slice.color), w))
        .collect();
    if let Some(at) = compaction
        && let Some(cell) = cell_styles.get_mut(at)
    {
        *cell = ('', theme::DIM);
    }

    // Runs of one style become one span; a span per cell would allocate a String
    // per column of the panel, on every frame.
    let mut spans: Vec<Span<'static>> = Vec::new();
    for (glyph, color) in cell_styles {
        match spans.last_mut() {
            Some(last) if last.style.fg == Some(color) => last.content.to_mut().push(glyph),
            _ => spans.push(Span::styled(glyph.to_string(), Style::default().fg(color))),
        }
    }
    Line::from(spans)
}

/// Split `cells` across `weights` in proportion, summing to exactly `cells`.
///
/// Largest remainder rather than a rounded share apiece: independent rounding
/// leaves the bar a cell or two short of the panel width, and in a stacked bar
/// that error lands on the boundary between two colours, which is exactly where
/// the eye is already looking.
fn apportion(weights: &[u64], cells: usize) -> Vec<usize> {
    let scale: u64 = weights.iter().sum::<u64>().max(1);
    let exact: Vec<f64> = weights
        .iter()
        .map(|w| *w as f64 / scale as f64 * cells as f64)
        .collect();
    let mut out: Vec<usize> = exact.iter().map(|e| e.floor() as usize).collect();

    let mut spare = cells.saturating_sub(out.iter().sum::<usize>());
    let mut order: Vec<usize> = (0..weights.len()).collect();
    order.sort_by(|a, b| {
        let frac = |i: usize| exact[i] - exact[i].floor();
        frac(*b).total_cmp(&frac(*a))
    });
    for i in order {
        if spare == 0 {
            break;
        }
        out[i] += 1;
        spare -= 1;
    }
    out
}

/// Swatch, name, tokens and share per category, two to a line where it fits.
///
/// Shares are of the whole window, free space included, so a legend entry and
/// its segment in the bar above are always the same length of the same thing.
fn legend(slices: &[Slice], width: usize) -> Vec<Line<'static>> {
    let scale = slices.iter().map(|s| s.tokens).sum::<u64>().max(1);
    // Two columns halve the panel's height for free, but need the room; below
    // that the entries stack rather than truncate.
    let columns = if width >= 64 { 2 } else { 1 };

    let mut lines = Vec::new();
    for row in slices.chunks(columns) {
        let mut spans = Vec::new();
        for (i, slice) in row.iter().enumerate() {
            if i > 0 {
                spans.push(Span::raw("   "));
            }
            let share = slice.tokens as f64 / scale as f64 * 100.0;
            spans.push(Span::styled(
                format!("{} ", slice.fill),
                Style::default().fg(slice.color),
            ));
            spans.push(value(format!("{:<14}", slice.name)));
            spans.push(Span::styled(
                format!("{:>7}", util::compact_tokens(slice.tokens)),
                Style::default().fg(slice.color),
            ));
            spans.push(dim(format!(" {:>3}%", share.round() as i64)));
        }
        lines.push(Line::from(spans));
    }
    lines
}

/// Which numbers were measured and which were guessed.
///
/// The distinction is the point of the panel, so it stays on screen — but as two
/// dim lines under the bar rather than as the three paragraphs it takes to say
/// the same thing in prose.
fn context_footnotes(
    b: &crate::session::ContextBreakdown,
    unaccounted: i64,
    marked: bool,
    width: usize,
) -> Vec<Line<'static>> {
    let marker = if marked {
        " ┊ on the bar is where auto-compaction triggers."
    } else {
        ""
    };
    let startup = if b.after_compaction {
        "Measured: Window, and Startup — this segment's first request (system prompt, tool schemas, CLAUDE.md, skills index, compaction summary), which the transcript cannot split further."
    } else {
        "Measured: Window, and Startup — the first request (system prompt, tool schemas, CLAUDE.md, skills index), which the transcript cannot split further."
    };
    let rest = if unaccounted >= 0 {
        "Estimated from transcript characters: everything else — read as proportions. Unaccounted is thinking (stored stripped), the harness's per-turn reminders, and estimation error."
    } else {
        "Estimated from transcript characters: everything else — read as proportions. Here they overshoot the window, which means the harness has dropped context the transcript still holds."
    };
    // Said outright rather than left to the header: every number in the panel
    // describes a window that no longer exists, and that is not something to
    // infer from a missing threshold marker.
    let superseded = if b.superseded {
        " A compaction has since replaced this window; nothing has measured what took its place."
    } else {
        ""
    };
    [startup.to_string(), format!("{rest}{marker}{superseded}")]
        .iter()
        .flat_map(|note| wrap(note, width.max(20)))
        .map(|l| Line::from(dim(l)))
        .collect()
}

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------

/// Read a file's first `max_lines` lines, prefixed by a header.
fn file_section(path: &Path, display: &str, max_lines: usize) -> Option<Vec<Line<'static>>> {
    let content = util::read_head(path, 32 * 1024)?;
    let mut out = vec![Line::from(Span::styled(
        display.to_string(),
        Style::default()
            .fg(theme::BORDER_HI)
            .add_modifier(Modifier::BOLD),
    ))];
    let src: Vec<&str> = content.lines().collect();
    for line in src.iter().take(max_lines) {
        out.push(Line::from(Span::raw(format!(
            "  {}",
            line.replace('\t', "    ")
        ))));
    }
    if src.len() > max_lines {
        out.push(Line::from(dim("  … (truncated)")));
    }
    out.push(Line::default());
    Some(out)
}

fn missing(text: String) -> Line<'static> {
    Line::from(Span::styled(text, Style::default().fg(theme::DIMMER)))
}

/// Instructions, memory, skills, and MCP servers backing this session.
pub fn config(session: &Session) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    let cwd = Path::new(&session.label_source);

    match session.provider {
        Provider::Claude => {
            let root = match (session.surface.is_desktop(), &session.mac_meta) {
                (true, Some(m)) => m.session_dir.join(".claude"),
                _ => crate::config::CLAUDE_CONFIG_DIR.clone(),
            };

            lines.push(Line::from(Span::styled(
                "── Instructions ──".to_string(),
                theme::title(),
            )));
            let global = root.join("CLAUDE.md");
            match file_section(&global, &util::tildify(&global.to_string_lossy()), 30) {
                Some(block) => lines.extend(block),
                None => lines.push(missing(format!("{} not found", global.display()))),
            }
            if !session.label_source.is_empty() {
                match file_section(&cwd.join("CLAUDE.md"), "./CLAUDE.md", 40) {
                    Some(block) => lines.extend(block),
                    None => lines.push(missing("./CLAUDE.md not found".into())),
                }
            }

            lines.push(Line::from(Span::styled(
                "── Skills ──".to_string(),
                theme::title(),
            )));
            lines.extend(skill_list(&root.join("skills")));

            lines.push(Line::from(Span::styled(
                "── MCP ──".to_string(),
                theme::title(),
            )));
            lines.extend(mcp_from_json(&root.join("settings.json"), "global"));
            if !session.label_source.is_empty() {
                lines.extend(mcp_from_json(&cwd.join(".mcp.json"), "project"));
            }
        }
        Provider::Codex => {
            lines.push(Line::from(Span::styled(
                "── Instructions ──".to_string(),
                theme::title(),
            )));
            let global = crate::config::CODEX_HOME.join("AGENTS.md");
            match file_section(&global, "~/.codex/AGENTS.md", 30) {
                Some(block) => lines.extend(block),
                None => lines.push(missing("~/.codex/AGENTS.md not found".into())),
            }
            if !session.label_source.is_empty() {
                match file_section(&cwd.join("AGENTS.md"), "./AGENTS.md", 40) {
                    Some(block) => lines.extend(block),
                    None => lines.push(missing("./AGENTS.md not found".into())),
                }
            }

            lines.push(Line::from(Span::styled(
                "── Config ──".to_string(),
                theme::title(),
            )));
            let toml = crate::config::CODEX_HOME.join("config.toml");
            match file_section(&toml, "~/.codex/config.toml", 30) {
                Some(block) => lines.extend(block),
                None => lines.push(missing("~/.codex/config.toml not found".into())),
            }

            lines.push(Line::from(Span::styled(
                "── Skills ──".to_string(),
                theme::title(),
            )));
            lines.extend(skill_list(&crate::config::CODEX_HOME.join("skills")));

            lines.push(Line::from(Span::styled(
                "── MCP ──".to_string(),
                theme::title(),
            )));
            lines.extend(mcp_from_toml(&toml));
        }
        Provider::Cursor => {
            lines.push(Line::from(Span::styled(
                "── Cursor ──".to_string(),
                theme::title(),
            )));
            lines.push(Line::from(dim(
                "Native agent transcripts do not expose model, token, context, or cost data.",
            )));
            lines.push(Line::from(dim(format!(
                "Transcript: {}",
                session
                    .data_file
                    .as_ref()
                    .map(|p| util::tildify(&p.to_string_lossy()))
                    .unwrap_or_else(|| "unknown".into())
            ))));
        }
        Provider::OpenCode => {
            lines.push(Line::from(Span::styled(
                "── Instructions ──".to_string(),
                theme::title(),
            )));
            if !session.label_source.is_empty() {
                match file_section(&cwd.join("AGENTS.md"), "./AGENTS.md", 40) {
                    Some(block) => lines.extend(block),
                    None => lines.push(missing("./AGENTS.md not found".into())),
                }
            }
            lines.push(Line::from(Span::styled(
                "── Config ──".to_string(),
                theme::title(),
            )));
            let config = dirs::config_dir()
                .unwrap_or_else(|| crate::config::HOME.join(".config"))
                .join("opencode")
                .join("opencode.json");
            match file_section(&config, &util::tildify(&config.to_string_lossy()), 30) {
                Some(block) => lines.extend(block),
                None => lines.push(missing(format!("{} not found", config.display()))),
            }
        }
        Provider::Pi => {
            lines.push(Line::from(Span::styled(
                "── Instructions ──".to_string(),
                theme::title(),
            )));
            let global = crate::config::PI_AGENT_DIR.join("AGENTS.md");
            match file_section(&global, &util::tildify(&global.to_string_lossy()), 30) {
                Some(block) => lines.extend(block),
                None => lines.push(missing(format!("{} not found", global.display()))),
            }
            if !session.label_source.is_empty() {
                match file_section(&cwd.join("AGENTS.md"), "./AGENTS.md", 40) {
                    Some(block) => lines.extend(block),
                    None => lines.push(missing("./AGENTS.md not found".into())),
                }
            }
            lines.push(Line::from(Span::styled(
                "── Config ──".to_string(),
                theme::title(),
            )));
            let settings = crate::config::PI_AGENT_DIR.join("settings.json");
            match file_section(&settings, &util::tildify(&settings.to_string_lossy()), 30) {
                Some(block) => lines.extend(block),
                None => lines.push(missing(format!("{} not found", settings.display()))),
            }
            lines.push(Line::from(Span::styled(
                "── Skills ──".to_string(),
                theme::title(),
            )));
            lines.extend(skill_list(&crate::config::PI_AGENT_DIR.join("skills")));
        }
        Provider::Gemini => {
            lines.push(Line::from(Span::styled(
                "── Instructions ──".to_string(),
                theme::title(),
            )));
            let global = crate::config::GEMINI_HOME.join("GEMINI.md");
            match file_section(&global, &util::tildify(&global.to_string_lossy()), 30) {
                Some(block) => lines.extend(block),
                None => lines.push(missing(format!("{} not found", global.display()))),
            }
            if !session.label_source.is_empty() {
                match file_section(&cwd.join("GEMINI.md"), "./GEMINI.md", 40) {
                    Some(block) => lines.extend(block),
                    None => lines.push(missing("./GEMINI.md not found".into())),
                }
            }
            lines.push(Line::from(Span::styled(
                "── Config ──".to_string(),
                theme::title(),
            )));
            let settings = crate::config::GEMINI_HOME.join("settings.json");
            match file_section(&settings, &util::tildify(&settings.to_string_lossy()), 30) {
                Some(block) => lines.extend(block),
                None => lines.push(missing(format!("{} not found", settings.display()))),
            }
            lines.push(Line::from(Span::styled(
                "── Skills ──".to_string(),
                theme::title(),
            )));
            lines.extend(skill_list(&crate::config::GEMINI_HOME.join("skills")));
        }
        Provider::Windsurf => {
            // Windsurf's global rules live in the editor's own settings UI, not
            // in a file cctop can point at; only the workspace rules are on disk.
            lines.push(Line::from(Span::styled(
                "── Instructions ──".to_string(),
                theme::title(),
            )));
            match file_section(&cwd.join(".windsurfrules"), "./.windsurfrules", 40) {
                Some(block) => lines.extend(block),
                None => lines.push(missing("./.windsurfrules not found".into())),
            }
        }
    }
    lines
}

/// Skill names and descriptions read from each `SKILL.md` front matter.
fn skill_list(dir: &Path) -> Vec<Line<'static>> {
    if !dir.is_dir() {
        return vec![missing(format!("No skills installed ({})", dir.display()))];
    }
    let mut out = Vec::new();
    for entry in crate::config::list_dir(dir) {
        let skill_md = dir.join(&entry).join("SKILL.md");
        let (mut name, mut desc) = (entry.clone(), String::new());
        if let Some(text) = util::read_head(&skill_md, 4096) {
            for line in text.lines().take(20) {
                if let Some(v) = line.strip_prefix("name:") {
                    name = v.trim().to_string();
                } else if let Some(v) = line.strip_prefix("description:") {
                    desc = v.trim().to_string();
                }
            }
        }
        let mut spans = vec![Span::styled(name, Style::default().fg(theme::COST_LOW))];
        if !desc.is_empty() {
            spans.push(Span::raw("  "));
            spans.push(dim(util::truncate(&desc, 80)));
        }
        out.push(Line::from(spans));
    }
    if out.is_empty() {
        out.push(missing("No skills installed".into()));
    }
    out
}

fn mcp_from_json(path: &Path, scope: &str) -> Vec<Line<'static>> {
    let Some(text) = util::read_head(path, 64 * 1024) else {
        return Vec::new();
    };
    let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) else {
        return Vec::new();
    };
    // Project `.mcp.json` may hold the servers at the top level.
    let servers = v.get("mcpServers").unwrap_or(&v);
    let Some(map) = servers.as_object() else {
        return Vec::new();
    };
    map.iter()
        .filter(|(_, cfg)| cfg.is_object())
        .map(|(name, cfg)| {
            let mut spans = vec![
                Span::styled(
                    name.clone(),
                    Style::default().fg(ratatui::style::Color::Indexed(180)),
                ),
                Span::raw("  "),
                dim(format!("({scope})")),
            ];
            if let Some(cmd) = cfg.get("command").and_then(|c| c.as_str()) {
                spans.push(Span::raw("  "));
                spans.push(dim(cmd.to_string()));
            }
            Line::from(spans)
        })
        .collect()
}

fn mcp_from_toml(path: &Path) -> Vec<Line<'static>> {
    let Some(text) = util::read_head(path, 64 * 1024) else {
        return vec![missing("No MCP servers configured".into())];
    };
    let out: Vec<Line<'static>> = text
        .lines()
        .filter_map(|l| {
            l.trim()
                .strip_prefix("[mcp_servers.")
                .and_then(|r| r.strip_suffix(']'))
                .map(|name| {
                    Line::from(Span::styled(
                        name.to_string(),
                        Style::default().fg(ratatui::style::Color::Indexed(180)),
                    ))
                })
        })
        .collect();
    if out.is_empty() {
        vec![missing("No MCP servers in config.toml".into())]
    } else {
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::{ContextUsage, SubagentStatus};

    fn series(windows: &[u64]) -> SessionData {
        SessionData {
            context_series: windows
                .iter()
                .enumerate()
                .map(|(i, w)| crate::session::CtxPoint {
                    ts: format!("2026-08-05T10:{i:02}:00+00:00"),
                    window: *w,
                    after_compaction: false,
                })
                .collect(),
            ..SessionData::default()
        }
    }

    /// The chart says how the window filled, which needs a shape to show. Two
    /// points are a straight line between two numbers the header already
    /// prints, so the section stays off rather than drawing a truism.
    #[test]
    fn the_context_chart_needs_more_than_a_pair_of_points() {
        let session = Session::new(crate::pricing::Provider::Claude, "x".into());
        assert!(context_timeline(&session, &series(&[10, 20]), 80).is_empty());
        assert!(!context_timeline(&session, &series(&[10, 20, 30]), 80).is_empty());
    }

    /// A narrow panel has no room for a chart, and drawing one anyway would push
    /// the bar and legend — which do fit — off the top.
    #[test]
    fn the_context_chart_stays_off_a_narrow_panel() {
        let session = Session::new(crate::pricing::Provider::Claude, "x".into());
        assert!(context_timeline(&session, &series(&[10, 20, 30, 40]), 12).is_empty());
    }

    /// Compactions are the only drops in the chart, so the header counts them:
    /// a fall with nothing behind it would otherwise read as a measurement bug.
    #[test]
    fn the_context_chart_counts_the_compactions_it_drew() {
        let session = Session::new(crate::pricing::Provider::Claude, "x".into());
        let mut data = series(&[10, 90, 20, 40]);
        data.context_series[2].after_compaction = true;
        let text: String = context_timeline(&session, &data, 80)
            .iter()
            .flat_map(|line| line.spans.iter().map(|s| s.content.to_string()))
            .collect();
        assert!(text.contains("1 compaction"), "got {text:?}");
        assert!(text.contains("4 requests"), "got {text:?}");
    }

    /// A failed call is marked two ways on purpose: the red wash, and a glyph in
    /// the gap after the timestamp so the row still reads on a terminal that
    /// drops background colour.
    #[test]
    fn failed_tool_calls_are_marked_in_the_activity_rows() {
        let mut data = SessionData::default();
        for (command, failed) in [("true", false), ("exit 1", true)] {
            data.metrics
                .tool_details
                .entry("Bash".to_string())
                .or_default()
                .push(crate::session::ToolDetail {
                    d: command.to_string(),
                    ts: "2026-08-05T10:00:00+00:00".to_string(),
                    failed,
                    ..Default::default()
                });
        }
        data.metrics.tool_count = 2;

        let (lines, _) = tool_activity(&data, 0, None, false, None, 120);
        let row_of = |needle: &str| {
            lines
                .iter()
                .find(|l| l.spans.iter().any(|s| s.content.contains(needle)))
                .unwrap_or_else(|| panic!("no row for {needle}"))
        };

        let ok = row_of("true");
        assert_eq!(ok.style.bg, None, "a successful call keeps the normal row");
        assert!(!ok.spans.iter().any(|s| s.content.contains('')));

        let bad = row_of("exit 1");
        assert_eq!(bad.style.bg, Some(theme::FAILED_BG));
        assert!(
            bad.spans.iter().any(|s| s.content.contains('')),
            "the failure must not be conveyed by colour alone"
        );
    }

    fn subagent(id: &str, cost: f64, ghost: bool) -> Subagent {
        Subagent {
            agent_id: id.into(),
            agent_type: "Explore".into(),
            description: "look around".into(),
            model: "claude-haiku-4-5-20251001".into(),
            started_at: Some("2026-01-01T00:00:00Z".into()),
            last_active: Some("2026-01-01T00:01:00Z".into()),
            duration_ms: 60_000,
            status: SubagentStatus::Done,
            cost,
            tool_count: 3,
            tool_use_id: None,
            context: Some(ContextUsage {
                used: 1000,
                max: 200_000,
                compacted: false,
            }),
            ghost,
        }
    }

    #[test]
    fn subagent_sort_respects_direction() {
        let mut list = vec![subagent("a", 1.0, false), subagent("b", 5.0, false)];
        sort_subagents(&mut list, SubagentSort::Cost, true);
        assert_eq!(list[0].agent_id, "a");
        sort_subagents(&mut list, SubagentSort::Cost, false);
        assert_eq!(list[0].agent_id, "b");
    }

    #[test]
    fn ghost_subagents_show_unknown_not_zero() {
        let data = SessionData {
            subagents: vec![subagent("g", 0.0, true)],
            ..Default::default()
        };
        let lines = subagents(Some(&data), SubagentSort::Last, false, 120);
        let row: String = lines[1].spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(row.contains(''), "ghost needs its own marker: {row}");
        assert!(
            !row.contains("$0.00"),
            "purged transcript must not report $0.00 as if measured: {row}"
        );
        assert!(row.contains(''));
    }

    #[test]
    fn tool_tabs_are_ordered_by_use_with_all_first() {
        let mut data = SessionData::default();
        data.metrics.tools.insert("Read".into(), 3);
        data.metrics.tools.insert("Bash".into(), 9);
        data.metrics.tool_count = 12;
        let tabs = tool_tabs(&data);
        assert_eq!(tabs[0].0, "All");
        assert_eq!(tabs[0].1, 12);
        assert_eq!(tabs[1].0, "Bash");
        assert_eq!(tabs[2].0, "Read");
    }

    #[test]
    fn tool_activity_live_filter_excludes_older_entries() {
        let mut data = SessionData::default();
        data.metrics.tool_count = 2;
        data.metrics.tools.insert("Bash".into(), 2);
        data.metrics.tool_details.insert(
            "Bash".into(),
            vec![
                crate::session::ToolDetail {
                    d: "old".into(),
                    ts: "2026-01-01T00:00:00Z".into(),
                    ..Default::default()
                },
                crate::session::ToolDetail {
                    d: "new".into(),
                    ts: "2026-06-01T00:00:00Z".into(),
                    ..Default::default()
                },
            ],
        );
        let (lines, _) = tool_activity(&data, 0, Some("2026-03-01T00:00:00Z"), false, None, 80);
        let text: String = lines
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.to_string()))
            .collect();
        assert!(text.contains("new"));
        assert!(!text.contains("old"));
    }

    #[test]
    fn info_reports_extraction_errors_instead_of_blank() {
        let s = Session::new(Provider::Claude, "x".into());
        let data = SessionData {
            error: Some("boom".into()),
            ..Default::default()
        };
        let lines = info(&s, Some(&data), Plan::Retail);
        let text: String = lines
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.to_string()))
            .collect();
        assert!(text.contains("boom"));
    }

    #[test]
    fn wall_time_advances_for_live_sessions_and_freezes_when_stopped() {
        let now = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:02:00Z")
            .unwrap()
            .with_timezone(&Utc);
        let mut session = Session::new(Provider::Claude, "x".into());
        session.started_at = "2026-01-01T00:00:00Z".into();
        session.last_active = "2026-01-01T00:00:49Z".into();

        assert_eq!(wall_duration_ms(&session, now), Some(49_000));

        session.process = Some(crate::proc::ProcInfo::default());
        assert_eq!(wall_duration_ms(&session, now), Some(120_000));
    }

    #[test]
    fn bundled_plan_cost_panel_still_shows_retail_equivalent() {
        let s = Session::new(Provider::Claude, "x".into());
        let data = SessionData {
            costs: crate::session::Costs {
                total: 4.25,
                ..Default::default()
            },
            ..Default::default()
        };
        let lines = cost(&s, Some(&data), Plan::Max);
        let text: String = lines
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.to_string()))
            .collect();
        assert!(text.contains("included in plan"));
        assert!(text.contains("$4.25"));
    }

    #[test]
    fn cost_panel_labels_free_model_usage() {
        let mut s = Session::new(Provider::OpenCode, "x".into());
        s.cost_is_free = true;
        let data = SessionData {
            model_breakdown: vec![crate::session::ModelBreakdown {
                model: "deepseek-v4-flash-free".into(),
                tokens: crate::session::Tokens {
                    input: 100,
                    output: 20,
                    cache_read: 50,
                    reasoning_output: 10,
                    total: 180,
                    ..Default::default()
                },
                costs: crate::session::Costs::default(),
                total: 0.0,
            }],
            ..Default::default()
        };
        let lines = cost(&s, Some(&data), Plan::Retail);
        let text: String = lines
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.to_string()))
            .collect();
        assert!(text.contains("deepseek-v4-flash-free  FREE"));
        assert!(!text.contains("$0.00"));
        assert!(text.matches("FREE").count() >= 8, "{text}");
    }

    /// The panel exists to say what is in the window, so the part it cannot
    /// explain has to be as visible as the parts it can. Folding the shortfall
    /// into the measurable categories would make every bar a lie.
    #[test]
    fn context_panel_shows_the_gap_rather_than_hiding_it() {
        let s = Session::new(Provider::Claude, "x".into());
        let data = SessionData {
            context_breakdown: Some(crate::session::ContextBreakdown {
                total: 100_000,
                startup: 20_000,
                tool_output: 30_000,
                tool_input: 5_000,
                ..Default::default()
            }),
            ..Default::default()
        };
        let lines = rendered(&s, &data, 100);
        let text = lines.join("\n");
        let entries = legend_entries(&lines);

        // 100k window, 55k attributed: the gap is 45%, the biggest single share.
        // It still reads last, because it is the leftover and belongs at the tail
        // of the bar rather than in the middle of the measured categories.
        let gap = entries.last().expect("the legend must have entries");
        assert!(gap.starts_with("Unaccounted"), "{entries:?}");
        assert!(gap.contains("45%"), "{gap}");
        // Shares are of what the window holds, so they account for all of it.
        let shares: i64 = entries.iter().filter_map(|e| share_of(e)).sum();
        assert!((99..=101).contains(&shares), "shares summed to {shares}");
        assert!(
            text.contains("Estimated"),
            "the estimate must say so: {text}"
        );
    }

    /// When the estimate overshoots, saying so beats drawing bars that run off
    /// the panel — the overshoot means the harness dropped context the
    /// transcript still holds, which is worth knowing.
    #[test]
    fn context_panel_admits_when_the_estimate_exceeds_the_window() {
        let s = Session::new(Provider::Claude, "x".into());
        let data = SessionData {
            context_breakdown: Some(crate::session::ContextBreakdown {
                total: 50_000,
                startup: 20_000,
                tool_output: 60_000,
                ..Default::default()
            }),
            ..Default::default()
        };
        let text = rendered(&s, &data, 100).join("\n");
        assert!(!text.contains("Unaccounted"), "there is no gap to report");
        assert!(text.contains("overshoot"), "{text}");
        // Shares are measured against the larger of the two, so the bar cannot
        // run past the panel.
        assert!(text.contains("75%"), "60k of 80k: {text}");
    }

    /// Once a compaction has replaced the window, headroom in it is not a thing
    /// anyone has measured. Quoting a figure anyway — in the header or as the
    /// threshold marker on the bar — would invite the reader to plan the next
    /// turn around a window that no longer exists.
    #[test]
    fn a_superseded_window_is_shown_as_past_rather_than_as_headroom() {
        let mut s = Session::new(Provider::Claude, "x".into());
        s.context = Some(ContextUsage {
            used: 100_000,
            max: 200_000,
            compacted: true,
        });
        let data = SessionData {
            context_breakdown: Some(crate::session::ContextBreakdown {
                total: 100_000,
                startup: 20_000,
                tool_output: 30_000,
                superseded: true,
                ..Default::default()
            }),
            ..Default::default()
        };
        let text = rendered(&s, &data, 100).join("\n");
        assert!(text.contains("before the last compaction"), "{text}");
        assert!(!text.contains("left"), "no headroom claim: {text}");
        assert!(!text.contains(''), "no threshold marker: {text}");

        // Still running, so the same transcript reads as a compaction in flight —
        // which is what the CTX% column says for it too.
        s.inferred_running = true;
        let text = rendered(&s, &data, 100).join("\n");
        assert!(text.contains("compacting…"), "{text}");
    }

    #[test]
    fn processes_panel_explains_cowork_absence() {
        let mut s = Session::new(Provider::Claude, "x".into());
        s.surface = Surface::DesktopCowork;
        let text: String = processes(&s, 80)[0]
            .spans
            .iter()
            .map(|sp| sp.content.to_string())
            .collect();
        assert!(text.contains("cloud VM"));
    }

    /// A stacked bar has to land exactly on the panel width whatever the shares
    /// round to, or its right edge wanders against everything drawn beside it.
    #[test]
    fn apportioning_a_bar_always_spends_every_cell() {
        for weights in [
            vec![1u64, 1, 1],        // thirds, which never divide evenly
            vec![999_999, 1],        // a share too small for one cell
            vec![7, 11, 13, 17, 19], // primes, so no share is exact
            vec![0, 0, 5],           // categories that contributed nothing
        ] {
            for cells in [10usize, 37, 96] {
                let parts = apportion(&weights, cells);
                assert_eq!(
                    parts.iter().sum::<usize>(),
                    cells,
                    "{weights:?} over {cells} cells"
                );
            }
        }
    }

    fn breakdown() -> crate::session::ContextBreakdown {
        crate::session::ContextBreakdown {
            total: 118_200,
            startup: 45_200,
            tool_output: 32_100,
            tool_input: 18_000,
            attachments: 2_100,
            user_text: 8_100,
            assistant_text: 6_900,
            after_compaction: false,
            superseded: false,
        }
    }

    fn rendered(session: &Session, data: &SessionData, width: usize) -> Vec<String> {
        context(session, Some(data), width)
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.to_string()).collect())
            .collect()
    }

    /// The legend's entries in reading order, however many share a line.
    ///
    /// A legend line is a swatch followed by a space, which is what tells it
    /// apart from the solid bar above it.
    fn legend_entries(lines: &[String]) -> Vec<String> {
        lines
            .iter()
            .filter(|l| l.starts_with("") || l.starts_with(""))
            .flat_map(|l| l.split(['', '']))
            .map(|e| e.trim().to_string())
            .filter(|e| e.ends_with('%'))
            .collect()
    }

    /// The trailing `NN%` of a legend entry.
    fn share_of(entry: &str) -> Option<i64> {
        entry.trim_end_matches('%').rsplit(' ').next()?.parse().ok()
    }

    /// The header carries the two numbers a running session is consulted for —
    /// how full the window is and how much room is left — and the bar underneath
    /// spans the panel exactly.
    #[test]
    fn the_context_panel_leads_with_headroom_and_a_full_width_bar() {
        let mut s = Session::new(Provider::Claude, "x".into());
        s.context = Some(ContextUsage {
            used: 118_200,
            max: 200_000,
            compacted: false,
        });
        let data = SessionData {
            context_breakdown: Some(breakdown()),
            ..Default::default()
        };

        let lines = rendered(&s, &data, 100);
        assert!(lines[0].contains("118.2K of 200.0K"), "{}", lines[0]);
        assert!(lines[0].contains("to compaction"), "{}", lines[0]);
        assert!(lines[0].contains("left"), "{}", lines[0]);
        assert_eq!(
            lines[2].chars().count(),
            100,
            "the stacked bar must fill the panel: {}",
            lines[2]
        );
        // 118.2K of a 200K window: held cells and free cells in that proportion.
        assert_eq!(lines[2].chars().filter(|c| *c == '').count(), 59);
        assert!(
            lines[2].ends_with(''),
            "free space must trail the bar: {}",
            lines[2]
        );
        // The marker lands on the auto-compaction threshold, wherever the
        // harness (or its env override) puts it.
        let expected = (*crate::config::COMPACT_THRESHOLD * 100.0).round() as usize;
        assert_eq!(
            lines[2].find('').map(|i| lines[2][..i].chars().count()),
            Some(expected),
            "{}",
            lines[2]
        );

        let entries = legend_entries(&lines);
        let free = entries.last().expect("the legend must have entries");
        assert!(free.starts_with("Free"), "{entries:?}");
        assert!(free.contains("81.8K"), "{free}");
    }
}