cctop 0.25.2

An htop-like terminal monitor for AI coding agent sessions on Linux (Claude Code, Codex, Cursor, Devin, 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
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
//! The conversation itself, normalised out of a harness's transcript.
//!
//! Everything else cctop reads a transcript for is a number: tokens, costs,
//! how full the window is, which tool failed how often. None of that keeps the
//! words, and the words are what someone away from their desk actually wants —
//! what they asked for, what the agent said back, what it edited on the way.
//! [`crate::serve::report`] answers "where did the afternoon go"; this answers
//! "what is it *doing*".
//!
//! # Why this is not the extraction path
//!
//! [`SessionData`](crate::session::SessionData) is built for the table: it is
//! cached, it is loaded for every row on the machine, and it deliberately drops
//! message text — keeping it would multiply the cache by the size of every
//! conversation on disk to serve a panel that shows one. So this is a separate
//! read, on one session, on request, on the route that asked for it, and it
//! keeps nothing.
//!
//! # What bounds it
//!
//! A transcript is unbounded and a browser is not, so every axis is capped:
//! [`MAX_TURNS`] from the end, [`MAX_TEXT_CHARS`] per message,
//! [`MAX_RESULT_CHARS`] per tool result, [`MAX_DIFF_LINES`] per patch. The tail
//! rather than the head, because a conversation is read from where it got to.
//! Older turns are counted and reported as a number rather than sent, which is
//! how the page can say "312 earlier turns" instead of implying the session
//! began where the scroll does.
//!
//! # What each harness writes
//!
//! The JSONL harnesses say, per entry, who spoke and what they said, so one
//! reader walks the line stream and matches each result to the call before it.
//! Devin writes one ATIF document instead, and OpenCode writes two tables in a
//! database its own sessions share — where a message, its reasoning, its words
//! and its calls including their results are all part of the same row, so those
//! readers take a whole entry at a time and have nothing to pair up.
//!
//! # What a harness leaves out
//!
//! A transcript is not obliged to record everything, and the gaps are read as
//! gaps rather than filled in. Cursor dates nothing and pairs nothing, so its
//! turns carry no time and its calls carry an empty result — a call that
//! finished, about an outcome the file never kept, which is a different
//! statement from one still running. Gemini and Pi keep results keyed to the
//! call, so there an absent result really is a call in flight.
//!
//! Windsurf is the one harness with no reader. It packs a whole workspace's
//! conversations into one SQLite value rewritten wholesale on every write, and
//! nothing in that value is dated, so a conversation cannot even be placed in
//! time. Rather than half-read it into a view that looks authoritative and is
//! not, a Windsurf session comes back [`unsupported`](Conversation::supported)
//! with the reason attached, and the page keeps showing the tool log and the
//! diffs, which every provider does have.
//!
//! ponytail: subagent sidechains are skipped rather than nested. Claude writes
//! them interleaved into the same file, and threading them into the transcript
//! they branch from is a display problem this does not solve; the report's
//! subagent section already names them and what they cost.
//!
//! ponytail: Pi's transcript is a tree of `id`/`parentId` entries, so the
//! reader walks the file in order rather than resolving the tree to the leaf
//! the entries describe. An abandoned branch is therefore shown beside the one
//! that was kept. Resolving the tree first means holding every entry id in hand
//! before saying anything, which for a session file large enough to matter is
//! the whole cost of opening the page.

use crate::pricing::Provider;
use crate::session::{Delta, Session, devin, extract, gemini, opencode, pi};
use crate::util;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::borrow::Cow;
use std::collections::{HashMap, VecDeque};
use std::path::Path;

/// How many of the newest turns are sent.
///
/// A long session runs to thousands, and a page that renders all of them is a
/// page that locks the tab it was opened in. This is several screens of scroll
/// past what anyone reads in one sitting.
const MAX_TURNS: usize = 200;

/// The most text one message contributes.
///
/// Generous, because a pasted stack trace or a plan is exactly the message
/// someone opens this to re-read, and a message cut off at a tweet's length is
/// worse than useless — it looks like the agent said only that.
const MAX_TEXT_CHARS: usize = 6000;

/// The most of one tool result that is kept.
///
/// Shorter than a message on purpose: a result is shown to confirm what came
/// back, not to be read in full. The whole of it is in the transcript, and the
/// report's call log is where the argument that produced it lives.
const MAX_RESULT_CHARS: usize = 800;

/// The most tool calls attributed to one turn.
///
/// A turn issuing more than this is a fan-out, and the tail of it says nothing
/// the first sixty-four did not.
const MAX_TOOLS_PER_TURN: usize = 64;

/// The most diff lines carried for one edit.
const MAX_DIFF_LINES: usize = 200;

/// One session's conversation, as much of it as is sent.
///
/// `Deserialize` because the same document is the wire format between two
/// cctops: a remote row's conversation is this, read off an ssh pipe rather
/// than off a transcript — see [`crate::fleet`].
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Conversation {
    /// Whether this harness has a reader at all. False carries a `note` saying
    /// why, and is not an error: the rest of the report is still true.
    pub supported: bool,
    /// Turns oldest-first, which is the order they are read in.
    pub turns: Vec<Turn>,
    /// Turns the transcript holds that came before the ones sent.
    pub earlier: usize,
    /// Why this is empty or short, when there is a reason worth saying.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub note: Option<String>,
    /// What the transcript looked like when this was read — see [`stamp_of`].
    /// A page sends it back as `?since=` so that a poll of an unchanged
    /// session costs neither side a read.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub stamp: Option<String>,
    /// The page's `since` still holds: nothing was read and nothing is sent.
    #[serde(skip_serializing_if = "std::ops::Not::not", default)]
    pub unchanged: bool,
}

/// What a polling page already holds, so the answer can be only what it lacks.
///
/// A page following a running session asked for the whole tail every five
/// seconds, and the server re-read the whole transcript to answer — on a long
/// session hundreds of kilobytes a poll to a page that then rebuilt every turn
/// it showed, to learn that one tool result had landed. With this the page says
/// what it has: the stamp of its last read, and the newest turn it holds.
#[derive(Debug, Default, Clone)]
pub struct Since {
    pub stamp: Option<String>,
    /// Send turns from this sequence number on. Inclusive, because the newest
    /// turn a page holds is the one most likely to have grown since: a tool
    /// result lands on the call made in it.
    pub after: Option<usize>,
}

/// A transcript's size and modification time, as a token a page can hold.
///
/// Transcripts are appended to, so a file whose size and time are both
/// unchanged has nothing new in it. ponytail: OpenCode keeps every session in
/// one database, so its stamp moves when *any* OpenCode session writes — a
/// poll that reads for nothing, never one that misses a change.
pub fn stamp_of(path: &Path) -> Option<String> {
    let meta = std::fs::metadata(path).ok()?;
    let modified = meta
        .modified()
        .ok()?
        .duration_since(std::time::UNIX_EPOCH)
        .ok()?
        .as_nanos();
    Some(format!("{}-{modified}", meta.len()))
}

impl Conversation {
    /// The answer for a page holding `since`: nothing when its stamp still
    /// holds, and otherwise only the turns from `after` on.
    pub fn narrowed(mut self, since: &Since) -> Conversation {
        if since.stamp.is_some() && since.stamp == self.stamp {
            return Conversation {
                supported: self.supported,
                earlier: self.earlier,
                stamp: self.stamp,
                unchanged: true,
                ..Conversation::default()
            };
        }
        if let Some(after) = since.after {
            self.turns.retain(|t| t.seq >= after);
        }
        self
    }
}

/// One thing that was said, and what it caused.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Turn {
    /// The turn's place in the whole transcript, oldest counting from zero.
    ///
    /// Sent because the page needs a name for a turn that survives windowing:
    /// `?before=` paging and `#chat/turn-N` links both speak in sequence
    /// numbers, and a position in the returned window is neither — empty
    /// turns are filtered out of `turns`, so position and sequence part ways.
    pub seq: usize,
    /// `user`, `assistant`, or `system` for the harness speaking for itself.
    ///
    /// A `Cow` rather than `&'static str` because a turn read back over ssh is
    /// owned; every writer below still passes a literal, so nothing here
    /// allocates.
    pub role: Cow<'static, str>,
    /// `message` ordinarily; `reasoning` for a thinking summary, `compaction`
    /// for the summary a harness writes when it reclaims the window. The page
    /// styles them differently because they are read differently — a compaction
    /// is a seam in the conversation, not a thing anybody said.
    pub kind: Cow<'static, str>,
    pub ts: String,
    pub text: String,
    /// Whether `text` was cut to [`MAX_TEXT_CHARS`].
    #[serde(skip_serializing_if = "std::ops::Not::not", default)]
    pub clipped: bool,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub tools: Vec<ToolUse>,
}

impl Turn {
    fn new(role: &'static str, kind: &'static str, ts: &str) -> Turn {
        Turn {
            // Numbered by `push`, the only place that knows the count.
            seq: 0,
            role: Cow::Borrowed(role),
            kind: Cow::Borrowed(kind),
            ts: ts.to_string(),
            text: String::new(),
            clipped: false,
            tools: Vec::new(),
        }
    }

    fn set_text(&mut self, text: &str) {
        let trimmed = text.trim();
        self.clipped = trimmed.chars().count() > MAX_TEXT_CHARS;
        self.text = match self.clipped {
            true => trimmed.chars().take(MAX_TEXT_CHARS).collect(),
            false => trimmed.to_string(),
        };
    }

    /// Add more text to a turn that already has some.
    ///
    /// A cap that was reached stays reached: a run of entries must not be able
    /// to grow one turn past [`MAX_TEXT_CHARS`] a block at a time.
    fn append_text(&mut self, text: &str) {
        let trimmed = text.trim();
        if trimmed.is_empty() || self.clipped {
            return;
        }
        if self.text.is_empty() {
            return self.set_text(trimmed);
        }
        let joined = format!("{}\n\n{trimmed}", self.text);
        self.set_text(&joined);
    }

    fn is_empty(&self) -> bool {
        self.text.is_empty() && self.tools.is_empty()
    }
}

/// One tool call, with whatever came back from it.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct ToolUse {
    /// The name as the transcript spelled it, with an MCP server's prefix made
    /// readable — `mcp__linear__list_issues` is `linear: list issues` on screen
    /// and nowhere else.
    pub name: String,
    /// The one-line form: the path, the command, the pattern.
    pub detail: String,
    /// The argument in full, when it differs from `detail`.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub full: Option<String>,
    /// The head of what the tool returned, or `None` while it is still running —
    /// which is what makes the last call of a live session visibly pending.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub result: Option<String>,
    #[serde(skip_serializing_if = "std::ops::Not::not", default)]
    pub failed: bool,
    #[serde(skip_serializing_if = "is_zero", default)]
    pub added: u32,
    #[serde(skip_serializing_if = "is_zero", default)]
    pub removed: u32,
    /// Unified-diff lines, when the harness recorded the patch it applied.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub diff: Vec<String>,
}

fn is_zero(n: &u32) -> bool {
    *n == 0
}

/// Read `session`'s conversation, as far as its harness allows.
///
/// `before` pages backwards through the turns: when it is `Some(seq)`, the
/// conversation returned ends just before that turn's sequence number instead
/// of at the latest one — same [`MAX_TURNS`] window, reached from the other
/// side. The parse still reads the whole transcript either way, because a tool
/// result near the end of the file can belong to a call inside the window.
pub fn build(session: &Session, before: Option<usize>) -> Conversation {
    let Some(path) = session.data_file.as_ref() else {
        return unsupported("this session has no transcript file on this machine");
    };
    let mut sink = Sink {
        before,
        ..Sink::default()
    };
    let read = match session.provider {
        Provider::Claude => extract::for_each_jsonl(path, |item| sink.claude(item)),
        Provider::Codex => extract::for_each_jsonl(path, |item| sink.codex(item)),
        Provider::Devin => read_devin(path, &mut sink),
        Provider::OpenCode => read_opencode(path, &session.session_id, &mut sink),
        Provider::Cursor => extract::for_each_jsonl(path, |item| sink.cursor(item)),
        Provider::Gemini => gemini::for_each_record(path, |item| sink.gemini(item)),
        Provider::Pi => extract::for_each_jsonl(path, |item| sink.pi(item)),
        _ => {
            return unsupported(&format!(
                "cctop cannot read {} {} conversation yet — it keeps the whole \
                 workspace's conversations in one settings value, rewritten \
                 wholesale on every write, and the tool log and diffs below come \
                 from the same value and are complete",
                article(session.surface.label(session.provider)),
                session.surface.label(session.provider)
            ));
        }
    };
    if let Err(e) = read {
        return unsupported(&format!("could not read the transcript: {e}"));
    }
    Conversation {
        stamp: stamp_of(path),
        ..sink.finish()
    }
}

/// One OpenCode conversation, out of the database every one of its sessions
/// shares.
///
/// Nothing is asked for by file: the transcript is two tables in that
/// database, and a session is a `session_id` rather than a path. A message and
/// its parts come back together, which is what lets a tool call show as
/// finished the moment it is read — the call and its result are one row there,
/// rather than two entries a reader has to pair up.
fn read_opencode(path: &Path, session_id: &str, sink: &mut Sink) -> std::io::Result<()> {
    opencode::for_each_message(path, session_id, |message, created, parts| {
        sink.opencode(message, &opencode::message_time(message, created), parts);
    });
    Ok(())
}

/// Devin's transcript is one ATIF document rather than a line stream, so it
/// cannot go through [`extract::for_each_jsonl`]: read it whole and feed each
/// step through the same sink the other readers use.
fn read_devin(path: &Path, sink: &mut Sink) -> std::io::Result<()> {
    let content = std::fs::read_to_string(path)?;
    let doc: Value = serde_json::from_str(&content)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    // A call's outcome is not in the transcript — the step records the call,
    // the database records how it ended.
    let statuses = devin::tool_statuses(
        doc.get("session_id").and_then(Value::as_str),
        &devin::db_for(Some(path)),
    );
    if let Some(steps) = doc.get("steps").and_then(Value::as_array) {
        for step in steps {
            sink.devin(step, &statuses);
        }
    }
    Ok(())
}

/// `a` or `an`, whichever a harness label takes — "an OpenCode conversation",
/// not "a OpenCode conversation".
fn article(label: &str) -> &'static str {
    match label.chars().next() {
        Some('A' | 'E' | 'I' | 'O' | 'U') => "an",
        _ => "a",
    }
}

fn unsupported(why: &str) -> Conversation {
    Conversation {
        supported: false,
        note: Some(why.to_string()),
        ..Conversation::default()
    }
}

/// Turns as they are read, with the oldest dropped once there are too many.
///
/// A tool result arrives in a later entry than the call it belongs to, so the
/// call has to stay reachable by id. Keeping the window as a deque and the index
/// in *sequence* numbers rather than positions is what makes that survive the
/// dropping: an id whose turn has already fallen off the front resolves to
/// nothing and its result is discarded, instead of landing on whichever turn
/// happens to sit at that position now.
#[derive(Default)]
struct Sink {
    turns: VecDeque<Turn>,
    /// Sequence number of the turn at the front of `turns`.
    first: usize,
    /// Sequence number the next turn will get.
    next: usize,
    /// When set, the window stops at this sequence number: turns at or past it
    /// still count (`next` keeps moving, so a later window's `earlier` is
    /// unchanged) but are not kept. Their records are still read — a tool
    /// result can arrive entries after the boundary and still needs to land on
    /// a call inside the window.
    before: Option<usize>,
    /// `tool_use` id -> (turn sequence, index within that turn's tools).
    index: HashMap<String, (usize, usize)>,
    /// Codex repeats an entry when a turn is retried; the second copy of a
    /// `call_id` is the same call, not another one.
    seen_calls: std::collections::HashSet<String>,
    /// The assistant turn still being added to, if there is one.
    ///
    /// Both harnesses write one reply as several records — the text, then each
    /// call — so a turn per record makes one answer into four boxes, three of
    /// them holding nothing but a tool name. Merging every consecutive record
    /// instead collapses a whole session into two boxes with sixty calls each.
    /// A tool result is the seam: it means the model has been asked again, and
    /// what it says next is a new turn. This is the fallback rule, used where a
    /// harness gives nothing better.
    run: Option<usize>,
    /// The API request the open turn belongs to, where the transcript says.
    ///
    /// Claude stamps every record of one response with the same `requestId`,
    /// which is the exact answer the rule above approximates: an entry carrying
    /// a request id already seen is part of that reply, however many thinking
    /// blocks and parallel tool calls it was written as.
    run_request: Option<(String, usize)>,
}

impl Sink {
    fn push(&mut self, turn: Turn) -> usize {
        // Anything pushed directly ends the run: a user turn, a compaction, a
        // block of reasoning. Only `open_assistant` reopens one.
        self.run = None;
        let seq = self.next;
        self.next += 1;
        // Past the `before` boundary the turn is numbered but not kept: its
        // sequence has to exist so `first` still counts it, but the window a
        // paged-back request is answering ends before it.
        if self.before.is_none_or(|before| seq < before) {
            let mut turn = turn;
            turn.seq = seq;
            self.turns.push_back(turn);
            while self.turns.len() > MAX_TURNS {
                self.turns.pop_front();
                self.first += 1;
            }
        }
        seq
    }

    /// The assistant turn more of one reply belongs to, opening a new one when
    /// this record starts a different reply.
    ///
    /// `request` is the harness's own name for the response this record came
    /// from, where it has one. With it the grouping is exact; without it, the
    /// run rule in [`Sink::run`] stands in.
    fn open_assistant(&mut self, ts: &str, request: Option<&str>) -> usize {
        let roomy = |sink: &mut Sink, seq: usize| {
            sink.turn_mut(seq)
                .is_some_and(|turn| turn.tools.len() < MAX_TOOLS_PER_TURN)
        };
        if let Some(id) = request {
            if let Some((open, seq)) = self.run_request.clone()
                && open == id
                && roomy(self, seq)
            {
                self.run = Some(seq);
                return seq;
            }
        } else if let Some(seq) = self.run
            && roomy(self, seq)
        {
            return seq;
        }
        let seq = self.push(Turn::new("assistant", "message", ts));
        self.run = Some(seq);
        if let Some(id) = request {
            self.run_request = Some((id.to_string(), seq));
        }
        seq
    }

    fn turn_mut(&mut self, seq: usize) -> Option<&mut Turn> {
        let position = seq.checked_sub(self.first)?;
        self.turns.get_mut(position)
    }

    fn add_tool(&mut self, seq: usize, id: Option<&str>, tool: ToolUse) {
        let Some(turn) = self.turn_mut(seq) else {
            return;
        };
        if turn.tools.len() >= MAX_TOOLS_PER_TURN {
            return;
        }
        let at = turn.tools.len();
        turn.tools.push(tool);
        if let Some(id) = id {
            self.index.insert(id.to_string(), (seq, at));
        }
    }

    /// Attach a result to the call it came back from, if that call is still in
    /// the window.
    fn resolve(&mut self, id: &str, result: Option<String>, failed: bool, delta: Option<Delta>) {
        // Whatever the model says after this is a new reply, whether or not the
        // call it answers is still in the window.
        self.run = None;
        let Some((seq, at)) = self.index.remove(id) else {
            return;
        };
        let Some(tool) = self.turn_mut(seq).and_then(|t| t.tools.get_mut(at)) else {
            return;
        };
        // A result is recorded even when it is empty, because the presence of
        // one is what distinguishes a finished call from a running one.
        tool.result = Some(result.unwrap_or_default());
        tool.failed = failed;
        if let Some(delta) = delta {
            tool.added = delta.added;
            tool.removed = delta.removed;
            tool.diff = delta.hunks.into_iter().take(MAX_DIFF_LINES).collect();
        }
    }

    fn finish(self) -> Conversation {
        Conversation {
            supported: true,
            earlier: self.first,
            turns: self
                .turns
                .into_iter()
                .filter(|turn| !turn.is_empty())
                .collect(),
            note: None,
            stamp: None,
            unchanged: false,
        }
    }

    // --- Claude Code ---

    fn claude(&mut self, item: &Value) {
        // A subagent's turns are a different conversation that happens to share
        // a file. See the module docs.
        if item.get("isSidechain").and_then(Value::as_bool) == Some(true) {
            return;
        }
        let ts = item.get("timestamp").and_then(Value::as_str).unwrap_or("");
        match item.get("type").and_then(Value::as_str) {
            Some("user") => self.claude_user(item, ts),
            Some("assistant") => self.claude_assistant(item, ts),
            _ => {}
        }
    }

    fn claude_user(&mut self, item: &Value, ts: &str) {
        let content = item.get("message").and_then(|m| m.get("content"));
        // The patch an edit applied is recorded on the entry carrying its
        // result, not on the call, so it is read once here and handed to
        // whichever `tool_result` block claims it.
        let mut delta = claude_delta(item);
        let mut text = String::new();
        let mut had_result = false;

        match content {
            Some(Value::String(s)) => text.push_str(s),
            Some(Value::Array(blocks)) => {
                for block in blocks {
                    if let Value::String(s) = block {
                        push_text(&mut text, s);
                        continue;
                    }
                    match block.get("type").and_then(Value::as_str) {
                        Some("tool_result") => {
                            had_result = true;
                            let Some(id) = block.get("tool_use_id").and_then(Value::as_str) else {
                                continue;
                            };
                            let failed =
                                block.get("is_error").and_then(Value::as_bool) == Some(true);
                            let body = flatten_content(block.get("content"));
                            self.resolve(id, Some(body), failed, delta.take());
                        }
                        _ => {
                            if let Some(t) = block.get("text").and_then(Value::as_str) {
                                push_text(&mut text, t);
                            }
                        }
                    }
                }
            }
            _ => {}
        }

        if text.trim().is_empty() {
            return;
        }
        // A tool result and a typed message can share one entry when someone
        // types while a tool is running. The result has already been attached;
        // what is left is a person talking.
        let compaction = item.get("isCompactSummary").and_then(Value::as_bool) == Some(true);
        let (role, kind) = match compaction {
            true => ("system", "compaction"),
            // A `<command-name>` block or a hook's output is the harness
            // speaking through the user's turn, and reads wrong attributed to
            // the person.
            false if is_harness_text(&text) || (had_result && item_is_meta(item)) => {
                ("system", "message")
            }
            false => ("user", "message"),
        };
        // The harness writes for a parser, not for a reader. What it says is
        // worth keeping; the tags around it are not, and a turn that is only
        // tags says nothing at all.
        let text = match role {
            "system" if kind == "message" => tidy_harness_text(&text),
            _ => text,
        };
        if text.trim().is_empty() {
            return;
        }
        let mut turn = Turn::new(role, kind, ts);
        turn.set_text(&text);
        self.push(turn);
    }

    fn claude_assistant(&mut self, item: &Value, ts: &str) {
        let request = item.get("requestId").and_then(Value::as_str);
        let Some(blocks) = item
            .get("message")
            .and_then(|m| m.get("content"))
            .and_then(Value::as_array)
        else {
            return;
        };

        let mut text = String::new();
        let mut thinking = String::new();
        let mut calls: Vec<(Option<String>, ToolUse)> = Vec::new();
        for block in blocks {
            match block.get("type").and_then(Value::as_str) {
                Some("text") => {
                    if let Some(t) = block.get("text").and_then(Value::as_str) {
                        push_text(&mut text, t);
                    }
                }
                Some("thinking") => {
                    if let Some(t) = block.get("thinking").and_then(Value::as_str) {
                        push_text(&mut thinking, t);
                    }
                }
                Some("tool_use") => {
                    let name = block.get("name").and_then(Value::as_str).unwrap_or("tool");
                    let input = block.get("input").cloned().unwrap_or(Value::Null);
                    let (short, full) = extract::tool_detail(name, &input);
                    calls.push((
                        block.get("id").and_then(Value::as_str).map(str::to_string),
                        ToolUse {
                            name: util::pretty_mcp_name(name),
                            detail: short,
                            full,
                            ..ToolUse::default()
                        },
                    ));
                }
                _ => {}
            }
        }

        // Thinking is its own turn rather than a prefix of the reply: it is
        // shown differently, and folding it into the text would mean either
        // hiding what the agent said or leading with all of its reasoning.
        //
        // Pushing it does not end the reply it belongs to — `run_request` is
        // what reopens that — which matters because a harness with extended
        // thinking writes a thinking block into most records, and closing the
        // reply on each one puts every tool call in a box of its own.
        if !thinking.trim().is_empty() {
            let mut turn = Turn::new("assistant", "reasoning", ts);
            turn.set_text(&thinking);
            self.push(turn);
        }

        if text.trim().is_empty() && calls.is_empty() {
            return;
        }
        // One reply, however many entries it took. Claude writes a turn's text
        // and each of its tool calls as separate records, so a turn shown per
        // record is one answer split across four boxes with three of them
        // holding nothing but a tool name. Everything between two user turns is
        // one thing the agent said, which is how its own interface reads it.
        let seq = self.open_assistant(ts, request);
        if let Some(turn) = self.turn_mut(seq) {
            turn.append_text(&text);
        }
        for (id, tool) in calls {
            self.add_tool(seq, id.as_deref(), tool);
        }
    }

    // --- Codex ---

    fn codex(&mut self, item: &Value) {
        let ts = item.get("timestamp").and_then(Value::as_str).unwrap_or("");
        let kind = item.get("type").and_then(Value::as_str).unwrap_or("");
        let Some(payload) = item.get("payload") else {
            return;
        };
        // A rollout writes the same shapes either at the top level or wrapped
        // in a `response_item`, exactly as the extraction path finds them.
        let effective = match kind {
            "response_item" => payload
                .get("type")
                .and_then(Value::as_str)
                .unwrap_or_default(),
            other => other,
        };

        match effective {
            "message" => self.codex_message(payload, ts),
            "reasoning" => {
                let text = codex_summary(payload);
                if !text.trim().is_empty() {
                    let mut turn = Turn::new("assistant", "reasoning", ts);
                    turn.set_text(&text);
                    self.push(turn);
                }
            }
            "function_call" | "custom_tool_call" => self.codex_call(payload, ts),
            "function_call_output" | "custom_tool_call_output" => {
                let Some(id) = payload.get("call_id").and_then(Value::as_str) else {
                    return;
                };
                let output = payload.get("output");
                let failed = codex_output_failed(output);
                self.resolve(id, Some(flatten_content(output)), failed, None);
            }
            _ => {}
        }
    }

    fn codex_message(&mut self, payload: &Value, ts: &str) {
        let role = match payload.get("role").and_then(Value::as_str) {
            Some("user") => "user",
            Some("assistant") => "assistant",
            // `system` and `developer` are both the harness talking: the
            // instructions, the environment block, the wrapper around a slash
            // command.
            _ => "system",
        };
        let text = codex_text(payload);
        if text.trim().is_empty() {
            return;
        }
        let mut turn = Turn::new(role, "message", ts);
        turn.set_text(&text);
        let seq = self.push(turn);
        // The calls this reply makes are written as their own entries after it,
        // so the reply stays open for them until a result comes back.
        if role == "assistant" {
            self.run = Some(seq);
        }
    }

    fn codex_call(&mut self, payload: &Value, ts: &str) {
        if let Some(id) = payload.get("call_id").and_then(Value::as_str)
            && !self.seen_calls.insert(id.to_string())
        {
            return;
        }
        let name = payload
            .get("name")
            .and_then(Value::as_str)
            .unwrap_or("tool");
        // `arguments` is a JSON-encoded string on a `function_call` and `input`
        // on a `custom_tool_call`, and `apply_patch` sends a raw patch through
        // either — so the argument is parsed if it parses and shown verbatim if
        // it does not, which is what the extraction path does with the same
        // entries.
        let raw_field = payload.get("arguments").or_else(|| payload.get("input"));
        let raw = raw_field.and_then(Value::as_str);
        let args: Value = match raw_field {
            Some(Value::String(s)) => serde_json::from_str(s).unwrap_or(Value::Null),
            Some(other) => other.clone(),
            None => Value::Null,
        };

        let mut tool = ToolUse {
            name: util::pretty_mcp_name(name),
            ..ToolUse::default()
        };
        if let Some(patch) = raw.filter(|_| name == "apply_patch" || args.is_null()) {
            match name {
                "apply_patch" => {
                    let (summary, delta) = extract::parse_apply_patch(patch);
                    tool.detail = summary;
                    tool.full = Some(patch.to_string());
                    tool.added = delta.added;
                    tool.removed = delta.removed;
                    tool.diff = delta.hunks.into_iter().take(MAX_DIFF_LINES).collect();
                }
                _ => {
                    tool.detail = extract::flatten_public(patch, 300);
                    tool.full = Some(patch.to_string());
                }
            }
        } else {
            let (short, full) = extract::tool_detail(name, &args);
            tool.detail = short;
            tool.full = full;
        }

        let seq = self.open_assistant(ts, None);
        let id = payload.get("call_id").and_then(Value::as_str);
        self.add_tool(seq, id, tool);
    }

    // --- OpenCode ---

    /// One OpenCode message: what it said, and what it did while saying it.
    ///
    /// A message is already a whole reply. Its reasoning, its words and every
    /// call it made are parts of this one row, so there is no run to carry
    /// across entries as there is for the harnesses that write a reply in
    /// pieces, and no result waiting on a later one — which is also why two
    /// messages in a row are two replies rather than one spread over two.
    fn opencode(&mut self, message: &Value, ts: &str, parts: &[Value]) {
        let mut text = String::new();
        let mut thinking = String::new();
        let mut calls: Vec<ToolUse> = Vec::new();
        let mut compacted = false;

        for part in parts {
            match part.get("type").and_then(Value::as_str) {
                Some("text") => {
                    if opencode_is_played_back(part) {
                        continue;
                    }
                    if let Some(t) = part.get("text").and_then(Value::as_str) {
                        push_text(&mut text, t);
                    }
                }
                Some("reasoning") => {
                    if let Some(t) = part.get("text").and_then(Value::as_str) {
                        push_text(&mut thinking, t);
                    }
                }
                Some("tool") => calls.push(opencode_call(part)),
                Some("compaction") => compacted = true,
                // `step-start` and `step-finish` bracket a model call and carry
                // its cost; `patch` is the file state a call left behind, which
                // the call itself already reports; `file` is an attachment.
                _ => {}
            }
        }

        if compacted {
            // The messages before a compaction are deleted rather than scrolled
            // past, so the transcript jumps with nothing to mark it. This is the
            // only thing in it that says the conversation went on.
            let mut turn = Turn::new("system", "compaction", ts);
            turn.set_text(
                "the context was compacted here — every turn before it \
                           is no longer in this session's transcript",
            );
            self.push(turn);
        }
        if !thinking.trim().is_empty() {
            let mut turn = Turn::new("assistant", "reasoning", ts);
            turn.set_text(&thinking);
            self.push(turn);
        }
        if text.trim().is_empty() && calls.is_empty() {
            return;
        }
        let role = match message.get("role").and_then(Value::as_str) {
            Some("assistant") => "assistant",
            Some("user") => "user",
            _ => "system",
        };
        let mut turn = Turn::new(role, "message", ts);
        turn.set_text(&text);
        let seq = self.push(turn);
        // No call id: the result is on the same part as the call, so nothing
        // later can resolve it and an index entry would only be a leak.
        for call in calls {
            self.add_tool(seq, None, call);
        }
    }

    // --- Devin ---

    /// One ATIF step: the source says who is speaking, and an agent step is a
    /// whole model response — reasoning, reply text, tool calls, and the
    /// results they produced, which Devin records on the same step's
    /// `observation` rather than as the later entry Claude and Codex use.
    fn devin(&mut self, step: &Value, statuses: &HashMap<String, String>) {
        let ts = step.get("timestamp").and_then(Value::as_str).unwrap_or("");
        match step.get("source").and_then(Value::as_str) {
            Some("user") => {
                let Some(text) = step.get("message").and_then(Value::as_str) else {
                    return;
                };
                if text.trim().is_empty() {
                    return;
                }
                let mut turn = Turn::new("user", "message", ts);
                turn.set_text(text);
                self.push(turn);
            }
            Some("agent") => self.devin_agent(step, ts, statuses),
            Some("system") => {
                // Most `system` steps are the prompt being assembled — the
                // `sysprompt` and `rules` telemetry sources say so directly, and
                // the rest are context blocks re-injected at each turn:
                // `<available_skills>`, `<system_info>`, loose chunks of the
                // prompt. What is worth a turn is an *event* — a tagged block
                // reporting that something happened, like a backgrounded
                // subagent finishing or the user editing a file mid-run.
                match step
                    .pointer("/extra/telemetry/source")
                    .and_then(Value::as_str)
                {
                    Some("sysprompt") | Some("rules") => return,
                    _ => {}
                }
                let Some(text) = step.get("message").and_then(Value::as_str) else {
                    return;
                };
                match text
                    .trim_start()
                    .strip_prefix('<')
                    .and_then(|r| r.split(['>', ' ', '\n', '\t', '/']).next())
                {
                    Some(tag)
                        if !tag.is_empty()
                            && tag
                                .chars()
                                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
                            && !matches!(tag, "available_skills" | "system_info") => {}
                    _ => return,
                }
                let mut turn = Turn::new("system", "message", ts);
                turn.set_text(&tidy_devin_event(text));
                self.push(turn);
            }
            _ => {}
        }
    }

    fn devin_agent(&mut self, step: &Value, ts: &str, statuses: &HashMap<String, String>) {
        if let Some(thinking) = step.get("reasoning_content").and_then(Value::as_str)
            && !thinking.trim().is_empty()
        {
            let mut turn = Turn::new("assistant", "reasoning", ts);
            turn.set_text(thinking);
            self.push(turn);
        }

        let text = step.get("message").and_then(Value::as_str).unwrap_or("");
        let empty: Vec<Value> = Vec::new();
        let calls = step
            .get("tool_calls")
            .and_then(Value::as_array)
            .unwrap_or(&empty);
        if text.trim().is_empty() && calls.is_empty() {
            return;
        }
        // `step_id` names the response: every step gets a fresh id, so one
        // step is one turn and nothing is ever folded into the reply before.
        // It is a number in ATIF, not a string.
        let request = step.get("step_id").map(|id| match id {
            Value::String(s) => s.clone(),
            other => other.to_string(),
        });
        let seq = self.open_assistant(ts, request.as_deref());
        if let Some(turn) = self.turn_mut(seq) {
            turn.append_text(text);
        }
        for call in calls {
            let name = call
                .get("function_name")
                .and_then(Value::as_str)
                .unwrap_or("tool");
            let args = call.get("arguments").cloned().unwrap_or(Value::Null);
            let (short, full) = extract::tool_detail(name, &args);
            let mut tool = ToolUse {
                name: util::pretty_mcp_name(name),
                detail: short,
                full,
                ..ToolUse::default()
            };
            if matches!(name, "edit" | "write")
                && let Some(delta) = extract::edit_delta(&args)
            {
                tool.added = delta.added;
                tool.removed = delta.removed;
                tool.diff = delta.hunks.into_iter().take(MAX_DIFF_LINES).collect();
            }
            let id = call.get("tool_call_id").and_then(Value::as_str);
            self.add_tool(seq, id, tool);
        }
        for result in step
            .get("observation")
            .and_then(|o| o.get("results"))
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
        {
            let Some(id) = result.get("source_call_id").and_then(Value::as_str) else {
                continue;
            };
            let body = flatten_content(result.get("content"));
            let failed = statuses.get(id).is_some_and(|s| s != "completed");
            self.resolve(id, Some(body), failed, None);
        }
    }

    // --- Cursor ---

    /// One Cursor entry: the role says who is speaking, and the blocks beneath
    /// it are what they said and what they asked the agent to do.
    ///
    /// A Cursor transcript dates nothing and pairs nothing, so a turn here has
    /// no time and a call has nothing to resolve — which is why each call is
    /// given an empty result rather than none. A missing one would say the call
    /// is still running, and for a harness that keeps no outcomes at all that
    /// would be a claim the transcript cannot support.
    fn cursor(&mut self, item: &Value) {
        let Some(role) = item.get("role").and_then(Value::as_str) else {
            return;
        };
        let Some(blocks) = item
            .get("message")
            .and_then(|m| m.get("content"))
            .and_then(Value::as_array)
        else {
            return;
        };
        let mut text = String::new();
        let mut calls = Vec::new();
        for block in blocks {
            match block.get("type").and_then(Value::as_str) {
                Some("text") => {
                    if let Some(t) = block.get("text").and_then(Value::as_str) {
                        push_text(&mut text, t);
                    }
                }
                Some("tool_use") => {
                    let name = block.get("name").and_then(Value::as_str).unwrap_or("tool");
                    let args = block.get("input").cloned().unwrap_or(Value::Null);
                    calls.push(call_tool(name, &args, Outcome::NotRecorded));
                }
                _ => {}
            }
        }
        // Cursor wraps what a person typed in a `<user_query>` block, and hangs
        // attachments off the same message as their own tag.
        let tidy = tidy_harness_text(&text);
        if tidy.trim().is_empty() && calls.is_empty() {
            return;
        }
        let mut turn = Turn::new(
            match role {
                "assistant" => "assistant",
                "user" => "user",
                _ => "system",
            },
            "message",
            "",
        );
        turn.set_text(&tidy);
        let seq = self.push(turn);
        for call in calls {
            self.add_tool(seq, None, call);
        }
    }

    // --- Gemini ---

    /// One Gemini record: the header and the `$set` patches that revise it are
    /// not conversation, so a record without one of the three types a person
    /// reads as nothing.
    fn gemini(&mut self, item: &Value) {
        let ts = item
            .get("timestamp")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        match item.get("type").and_then(Value::as_str) {
            Some("user") => {
                let mut turn = Turn::new("user", "message", &ts);
                turn.set_text(&gemini_text(item.get("content")));
                self.push(turn);
            }
            Some("info") => {
                // "Switched to Plan Mode." and the like: the harness speaking
                // for itself, which is what a `system` turn is.
                let text = item.get("content").and_then(Value::as_str).unwrap_or("");
                if text.trim().is_empty() {
                    return;
                }
                let mut turn = Turn::new("system", "message", &ts);
                turn.set_text(&tidy_harness_text(text));
                self.push(turn);
            }
            Some("gemini") => self.gemini_reply(item, &ts),
            _ => {}
        }
    }

    /// One Gemini reply: what it thought, what it said, and every call it made
    /// in between.
    ///
    /// A `gemini` record is a whole response, and it carries each call's
    /// outcome on the call itself — the same one-record-one-reply shape
    /// OpenCode uses, and for the same reason there is no run to carry.
    fn gemini_reply(&mut self, item: &Value, ts: &str) {
        let mut thinking = String::new();
        for thought in item
            .get("thoughts")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
        {
            let body = thought
                .get("description")
                .and_then(Value::as_str)
                .or_else(|| thought.get("subject").and_then(Value::as_str))
                .unwrap_or("");
            push_text(&mut thinking, body);
        }
        if !thinking.trim().is_empty() {
            let mut turn = Turn::new("assistant", "reasoning", ts);
            turn.set_text(&thinking);
            self.push(turn);
        }

        let text = item.get("content").and_then(Value::as_str).unwrap_or("");
        let empty: Vec<Value> = Vec::new();
        let calls = item
            .get("toolCalls")
            .and_then(Value::as_array)
            .unwrap_or(&empty);
        if text.trim().is_empty() && calls.is_empty() {
            return;
        }
        let mut turn = Turn::new("assistant", "message", ts);
        turn.set_text(&tidy_harness_text(text));
        let seq = self.push(turn);
        for call in calls {
            let name = call.get("name").and_then(Value::as_str).unwrap_or("tool");
            let args = call.get("args").cloned().unwrap_or(Value::Null);
            // A Gemini call records what came back on the call itself, so a
            // missing result is a call still running rather than one whose
            // outcome the harness threw away.
            let outcome = match call.get("result") {
                Some(result) => Outcome::Recorded(
                    gemini_result(result),
                    call.get("status").and_then(Value::as_str) == Some("error"),
                ),
                None => Outcome::Running,
            };
            self.add_tool(seq, None, call_tool(name, &args, outcome));
        }
    }

    // --- Pi ---

    /// One Pi entry, of which only a `message` is conversation: the rest of the
    /// file is the harness narrating itself — labels, model changes, branch
    /// summaries, compactions.
    fn pi(&mut self, item: &Value) {
        if item.get("type").and_then(Value::as_str) != Some("message") {
            return;
        }
        let Some(message) = item.get("message") else {
            return;
        };
        let ts = pi::message_ts(item, message);
        match message.get("role").and_then(Value::as_str) {
            Some("toolResult") => {
                let Some(id) = message.get("toolCallId").and_then(Value::as_str) else {
                    return;
                };
                let body = flatten_content(message.get("content"));
                let failed = message.get("isError").and_then(Value::as_bool) == Some(true);
                self.resolve(id, Some(body), failed, None);
            }
            Some(role @ ("user" | "assistant")) => {
                let mut text = String::new();
                let mut thinking = String::new();
                let mut calls = Vec::new();
                match message.get("content") {
                    // A person's turn is the string; an agent's is blocks.
                    Some(Value::String(s)) => push_text(&mut text, s),
                    Some(Value::Array(blocks)) => {
                        for block in blocks {
                            match block.get("type").and_then(Value::as_str) {
                                Some("text") => {
                                    if let Some(t) = block.get("text").and_then(Value::as_str) {
                                        push_text(&mut text, t);
                                    }
                                }
                                Some("thinking") => {
                                    if let Some(t) = block.get("thinking").and_then(Value::as_str) {
                                        push_text(&mut thinking, t);
                                    }
                                }
                                Some("toolCall") => {
                                    let name =
                                        block.get("name").and_then(Value::as_str).unwrap_or("tool");
                                    let args =
                                        block.get("arguments").cloned().unwrap_or(Value::Null);
                                    // The result is a later entry keyed by
                                    // `toolCallId`, so the call starts in flight
                                    // and `resolve` is what fills it in.
                                    let call = call_tool(name, &args, Outcome::Running);
                                    calls.push((id_of(block), call));
                                }
                                // An image is what a person pasted; the page
                                // shows the words, not the bytes.
                                _ => {}
                            }
                        }
                    }
                    _ => {}
                }
                if !thinking.trim().is_empty() {
                    let mut turn = Turn::new("assistant", "reasoning", &ts);
                    turn.set_text(&thinking);
                    self.push(turn);
                }
                if text.trim().is_empty() && calls.is_empty() {
                    return;
                }
                let mut turn = Turn::new(
                    if role == "user" { "user" } else { "assistant" },
                    "message",
                    &ts,
                );
                turn.set_text(&tidy_harness_text(&text));
                let seq = self.push(turn);
                for (id, call) in calls {
                    self.add_tool(seq, id.as_deref(), call);
                }
            }
            _ => {}
        }
    }
}

/// The id a Pi tool call is answered by, if it gave one.
///
/// Pi pairs a result to its call by id, so an idless call is one no later entry
/// can resolve and indexing it would be a key nothing ever looks up.
fn id_of(block: &Value) -> Option<String> {
    block.get("id").and_then(Value::as_str).map(str::to_string)
}

/// What a transcript says about how a call ended.
enum Outcome {
    /// The outcome is here, and this is whether it was a failure.
    Recorded(String, bool),
    /// The call is in flight. This harness records results, and there is not
    /// one yet — which is a different statement from there being no kind.
    Running,
    /// This harness records no outcomes at all, so a call in the transcript
    /// has finished and whatever came back was never kept.
    NotRecorded,
}

/// One call as a transcript records it.
///
/// [`Outcome::NotRecorded`] is the case worth the type: a missing result on a
/// harness that keeps some is a call still running, and the page draws those
/// two differently. Reading one as the other is the difference between a live
/// conversation and a transcript claiming every call in it is in flight.
fn call_tool(name: &str, args: &Value, outcome: Outcome) -> ToolUse {
    let (detail, full) = extract::tool_detail(name, args);
    let (result, failed) = match outcome {
        Outcome::Recorded(result, failed) => (Some(result), failed),
        Outcome::Running => (None, false),
        Outcome::NotRecorded => (Some(String::new()), false),
    };
    let delta = edits_file(name)
        .then(|| extract::edit_delta(args))
        .flatten();
    ToolUse {
        name: util::pretty_mcp_name(name),
        detail,
        full,
        result,
        failed,
        added: delta.as_ref().map_or(0, |d| d.added),
        removed: delta.as_ref().map_or(0, |d| d.removed),
        diff: delta
            .map(|d| d.hunks.into_iter().take(MAX_DIFF_LINES).collect())
            .unwrap_or_default(),
    }
}

/// Whether a tool is one of the harnesses' own file editors, which are the
/// calls whose arguments are the patch.
///
/// The names differ by capitalisation and by synonym between harnesses, and
/// none of them is the same word, so this is the list rather than a rule about
/// the arguments — a call's `content` key can hold anything, and treating that
/// as a diff would invent one.
fn edits_file(name: &str) -> bool {
    matches!(
        name.to_ascii_lowercase().as_str(),
        "edit" | "write" | "replace" | "multiedit" | "str_replace" | "str_replace_editor"
    )
}

/// Whether a text part is something a person said rather than something
/// OpenCode or a plugin put in their mouth.
///
/// Two flags mark it, and both land on `user` messages: `ignored` is a plugin's
/// own progress output (a compression notice with a bar of block characters
/// under it), and `synthetic` is a replay of a tool call the reader has already
/// been shown. Neither is in the conversation, and a transcript showing either
/// is one nobody recognises.
fn opencode_is_played_back(part: &Value) -> bool {
    part.get("ignored").and_then(Value::as_bool) == Some(true)
        || part.get("synthetic").and_then(Value::as_bool) == Some(true)
}

/// One OpenCode tool call, with whatever came back from it.
///
/// The call and its outcome are one record, so there is nothing to wait for: a
/// `state` with no `output` yet is a call still running, and that absence is
/// what the page already draws for a live call from any other harness.
fn opencode_call(part: &Value) -> ToolUse {
    let state = part.get("state");
    let name = part.get("tool").and_then(Value::as_str).unwrap_or("tool");
    let input = state
        .and_then(|s| s.get("input"))
        .cloned()
        .unwrap_or(Value::Null);
    let (mut detail, full) = extract::tool_detail(name, &input);
    // OpenCode writes the one line it shows for the call, which is the only
    // thing that can describe a tool cctop has no rule for — a plugin's, or an
    // MCP server's, where `tool_detail` has nothing to go on.
    if detail.is_empty()
        && let Some(title) = state.and_then(|s| s.get("title")).and_then(Value::as_str)
    {
        detail = title.to_string();
    }
    let output = state.and_then(|s| s.get("output"));
    let why = state
        .and_then(|s| s.get("error"))
        .and_then(Value::as_str)
        .filter(|e| !e.trim().is_empty());
    let mut tool = ToolUse {
        name: util::pretty_mcp_name(name),
        detail,
        full,
        result: output
            .map(|out| flatten_content(Some(out)))
            .or_else(|| why.map(str::to_string)),
        failed: state.and_then(|s| s.get("status")).and_then(Value::as_str) == Some("error"),
        ..ToolUse::default()
    };
    if let Some(delta) = state.and_then(|s| opencode::tool_delta(name, s)) {
        tool.added = delta.added;
        tool.removed = delta.removed;
        tool.diff = delta.hunks.into_iter().take(MAX_DIFF_LINES).collect();
    }
    tool
}

/// The diff a Claude edit reported, from the entry carrying its result.
fn claude_delta(item: &Value) -> Option<Delta> {
    let hunks = item
        .get("toolUseResult")
        .and_then(|r| r.get("structuredPatch"))
        .and_then(Value::as_array)?;
    let mut delta = Delta::default();
    for hunk in hunks {
        let Some(lines) = hunk.get("lines").and_then(Value::as_array) else {
            continue;
        };
        for line in lines.iter().filter_map(Value::as_str) {
            if line.starts_with('+') {
                delta.added += 1;
            } else if line.starts_with('-') {
                delta.removed += 1;
            }
            if delta.hunks.len() < MAX_DIFF_LINES {
                delta.hunks.push(line.to_string());
            }
        }
    }
    (delta.added > 0 || delta.removed > 0).then_some(delta)
}

/// Text out of a Codex message payload's content blocks.
fn codex_text(payload: &Value) -> String {
    let mut out = String::new();
    match payload.get("content") {
        Some(Value::String(s)) => out.push_str(s),
        Some(Value::Array(blocks)) => {
            for block in blocks {
                match block {
                    Value::String(s) => push_text(&mut out, s),
                    _ => {
                        if let Some(t) = block.get("text").and_then(Value::as_str) {
                            push_text(&mut out, t);
                        }
                    }
                }
            }
        }
        _ => {}
    }
    out
}

/// The reasoning summary Codex records, which is a list of its own blocks.
fn codex_summary(payload: &Value) -> String {
    let mut out = String::new();
    for block in payload
        .get("summary")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        if let Some(t) = block.get("text").and_then(Value::as_str) {
            push_text(&mut out, t);
        }
    }
    out
}

/// Whether a Codex tool output says the call failed.
///
/// The field is not always there and not always a bool: a shell call reports an
/// exit status inside its output text instead, so both are checked and neither
/// is required.
fn codex_output_failed(output: Option<&Value>) -> bool {
    let Some(output) = output else {
        return false;
    };
    if output.get("success").and_then(Value::as_bool) == Some(false) {
        return true;
    }
    let text = match output {
        Value::String(s) => s.clone(),
        other => other
            .get("content")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string(),
    };
    let head: String = text.chars().take(400).collect();
    head.contains("exit code 1")
        || head.contains("Error:")
        || head.contains("command not found")
        || head.contains("No such file or directory")
}

/// A tool result's content, whatever shape it arrived in, cut to size.
fn flatten_content(content: Option<&Value>) -> String {
    let mut out = String::new();
    match content {
        Some(Value::String(s)) => out.push_str(s),
        Some(Value::Array(blocks)) => {
            for block in blocks {
                match block {
                    Value::String(s) => push_text(&mut out, s),
                    _ => {
                        if let Some(t) = block.get("text").and_then(Value::as_str) {
                            push_text(&mut out, t);
                        } else if block.get("type").and_then(Value::as_str) == Some("image") {
                            // The bytes are megabytes of base64 and the page has
                            // nothing to do with them, but a result that was an
                            // image should not read as an empty one.
                            push_text(&mut out, "[image]");
                        }
                    }
                }
            }
        }
        Some(Value::Object(map)) => {
            // Codex's `output` is an object with the text under one of a few
            // keys depending on the tool.
            for key in ["content", "output", "stdout", "text"] {
                if let Some(t) = map.get(key).and_then(Value::as_str) {
                    push_text(&mut out, t);
                }
            }
            if out.is_empty() {
                out = content.map(|c| c.to_string()).unwrap_or_default();
            }
        }
        Some(other) => out = other.to_string(),
        None => {}
    }
    let trimmed = out.trim();
    match trimmed.chars().count() > MAX_RESULT_CHARS {
        true => trimmed.chars().take(MAX_RESULT_CHARS).collect::<String>() + "…",
        false => trimmed.to_string(),
    }
}

/// Append with a blank line between blocks, so two text blocks do not run into
/// one word.
fn push_text(out: &mut String, text: &str) {
    if text.is_empty() {
        return;
    }
    if !out.is_empty() {
        out.push_str("\n\n");
    }
    out.push_str(text);
}

/// What a Gemini record said, whichever of its two shapes holds it.
///
/// A person's turn is a list of text blocks; an agent's is the string itself.
/// Both appear on the same field, so the string case is the one that has to be
/// told apart rather than assumed.
fn gemini_text(content: Option<&Value>) -> String {
    match content {
        Some(Value::String(s)) => s.clone(),
        Some(blocks) => {
            let mut out = String::new();
            for block in blocks.as_array().into_iter().flatten() {
                if let Some(t) = block.get("text").and_then(Value::as_str) {
                    push_text(&mut out, t);
                }
            }
            out
        }
        None => String::new(),
    }
}

/// What a Gemini call returned, out of the envelope it arrives in.
///
/// The outcome sits under `functionResponse.response`, whose shape is the
/// called tool's own, so the first response that carries any text is the one
/// shown and the whole envelope is the fallback — an empty box on a call that
/// demonstrably did something is worse than an ugly one.
fn gemini_result(result: &Value) -> String {
    for response in result
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|part| part.get("functionResponse"))
    {
        let body = response
            .get("response")
            .map(|inner| flatten_content(Some(inner)))
            .unwrap_or_default();
        if !body.trim().is_empty() {
            return body;
        }
    }
    flatten_content(Some(result))
}

/// Whether a user turn is really the harness talking.
///
/// Claude Code writes several of its own things into `user` entries — the
/// expansion of a slash command, a hook's output, the reminder blocks it
/// injects — and showing those as something a person typed is the difference
/// between a transcript someone recognises and one they do not.
///
/// The named prefixes stay because those blocks are also written on one line,
/// where the shape below cannot see them. The shape is what catches the rest:
/// the list of names was a list that had to be kept up to date and was not, and
/// `<task-notification>` reached a handoff brief quoted as the user's own words
/// because nothing had added it. A person opening a message with a bare tag and
/// nothing else on the line is the rarer mistake to make.
fn is_harness_text(text: &str) -> bool {
    let head = text.trim_start();
    head.starts_with("<command-name>")
        || head.starts_with("<local-command")
        || head.starts_with("<system-reminder>")
        || head.starts_with("<user-prompt-submit-hook>")
        || head.starts_with("Caveat:")
        || opens_with_bare_tag(head)
}

/// Whether the first line is `<name>` and nothing else — the shape every
/// injected block shares, and the shape prose does not.
fn opens_with_bare_tag(text: &str) -> bool {
    let Some(line) = text.lines().next().map(str::trim) else {
        return false;
    };
    let Some(name) = line.strip_prefix('<').and_then(|l| l.strip_suffix('>')) else {
        return false;
    };
    // No attributes and no closing tag on the same line: `<p>hi</p>` is
    // somebody pasting markup, and `<b>` alone on a line is not a sentence.
    !name.is_empty()
        && !name.starts_with('/')
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}

/// The text inside `<tag>…</tag>`, the first time it appears.
fn tagged<'a>(text: &'a str, tag: &str) -> Option<&'a str> {
    let open = format!("<{tag}>");
    let rest = &text[text.find(&open)? + open.len()..];
    Some(&rest[..rest.find(&format!("</{tag}>"))?])
}

/// A harness turn as something to read.
///
/// Claude Code records a slash command as the three tags it parsed it into —
/// `<command-name>`, `<command-message>`, `<command-args>` — and the output as
/// a fourth. Shown raw, a `/clear` fills four lines with markup and buries the
/// one token that matters. So it comes back out as the command someone typed,
/// with whatever it printed beneath it.
///
/// Anything else the harness writes keeps its text and loses its wrapper: a
/// reminder still reads as a reminder without the tag announcing it as one.
fn tidy_harness_text(text: &str) -> String {
    if text.trim_start().starts_with("<task-notification>") {
        return tidy_task_notification(text);
    }
    let out = tagged(text, "local-command-stdout").unwrap_or("").trim();
    if let Some(name) = tagged(text, "command-name") {
        let args = tagged(text, "command-args").unwrap_or("").trim();
        let said = format!("{} {args}", name.trim());
        return match out.is_empty() {
            true => said.trim().to_string(),
            false => format!("{}\n\n{out}", said.trim()),
        };
    }
    if text.trim_start().starts_with("<local-command") {
        return out.to_string();
    }
    // Every other block is a wrapper around prose. Dropping the tag lines is
    // enough — the text between them was written to be read.
    let stripped: Vec<&str> = text
        .lines()
        .map(str::trim_end)
        .filter(|line| !(line.trim_start().starts_with('<') && line.trim_end().ends_with('>')))
        .collect();
    let stripped = stripped.join("\n");
    let stripped = stripped.trim();
    match stripped.is_empty() {
        // A block written entirely on one line has no line to keep, so the
        // tags come off it directly rather than leaving the turn empty.
        true => strip_outer_tags(text.trim()).trim().to_string(),
        false => stripped.to_string(),
    }
}

/// `<tag>body</tag>` on a single line, reduced to `body`.
fn strip_outer_tags(text: &str) -> &str {
    let Some(open_end) = text.find('>') else {
        return text;
    };
    if !text.starts_with('<') || !text.ends_with('>') {
        return text;
    }
    let body = &text[open_end + 1..];
    match body.rfind("</") {
        Some(close) => &body[..close],
        None => body,
    }
}

/// A `<task-notification>` as news, not markup.
///
/// The notice that a background task or a monitor spoke arrives as a `user`
/// entry full of the fields a dispatcher needs — `task-id`, `tool-use-id`,
/// `output-file`, `usage`, `worktree` — around the ones a reader does:
/// `summary`, `event` when a monitor is reporting, and `result` when a
/// finished agent left a note. Every field sits on its own `<field>value
/// </field>` line, so the generic tidy strips them all, finds the body
/// empty, and strips only the outer tag — which is how the whole field list
/// reached the transcript as the turn's text. Read the fields that carry
/// the news; a notification holding none of them says nothing worth a turn.
fn tidy_task_notification(text: &str) -> String {
    let mut lines: Vec<String> = Vec::new();
    for field in ["summary", "event", "result"] {
        let Some(body) = tagged(text, field).map(str::trim) else {
            continue;
        };
        if body.is_empty() || lines.iter().any(|l| l == body) {
            continue;
        }
        lines.push(unescape_entities(body));
    }
    // Anything written after the closing tag is the entry's real text — the
    // notice is only the part inside it.
    if let Some(end) = text.find("</task-notification>") {
        let tail = text[end + "</task-notification>".len()..].trim();
        if !tail.is_empty() {
            lines.push(tail.to_string());
        }
    }
    lines.join("\n")
}

/// The entities the transcript writer escapes inside these fields. `&amp;`
/// goes last, or `&amp;gt;` decodes twice.
fn unescape_entities(text: &str) -> String {
    text.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#39;", "'")
        .replace("&apos;", "'")
        .replace("&amp;", "&")
}

/// A Devin system event, readable.
///
/// The block arrives dressed for the model, not for a reader: an
/// `additional_metadata` opens with instructions about when to mention it,
/// then a `user_actions` carrying one `[diff_block]` per file the user
/// touched — dozens of lines of pseudo-diff where the event was "you edited
/// these files". The block and its footnote go; the file names and any other
/// action prose stay. Anything else — a subagent's completion report — loses
/// only its envelope, same as every other harness block.
fn tidy_devin_event(text: &str) -> String {
    let Some(actions) = tagged(text, "user_actions") else {
        return tidy_harness_text(text);
    };
    let mut files = Vec::new();
    let mut prose = Vec::new();
    let mut in_diff = false;
    for line in actions.lines().map(str::trim) {
        match line {
            "[diff_block_start]" => in_diff = true,
            "[diff_block_end]" => in_diff = false,
            _ if in_diff || line.is_empty() => {}
            l if l.starts_with("Please note that") => {}
            l => match l.strip_prefix("The following changes were made by the USER to: ") {
                Some(file) => files.push(file.trim_end_matches('.').to_string()),
                None => prose.push(l.to_string()),
            },
        }
    }
    if !files.is_empty() {
        prose.insert(0, format!("the user edited {}", files.join(", ")));
    }
    match prose.is_empty() {
        true => tidy_harness_text(text),
        false => prose.join("\n"),
    }
}

fn item_is_meta(item: &Value) -> bool {
    item.get("isMeta").and_then(Value::as_bool) == Some(true)
}

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

    /// The named prefixes were a list that had to be kept up to date, and was
    /// not: a `<task-notification>` reached a handoff brief quoted as the
    /// user's own words. Every injected block shares a shape.
    #[test]
    fn a_block_the_harness_injected_is_not_something_a_person_said() {
        assert!(is_harness_text(
            "<system-reminder>\nbe careful\n</system-reminder>"
        ));
        assert!(is_harness_text(
            "<task-notification>\n<task-id>abc</task-id>"
        ));
        assert!(is_harness_text("<user-prompt-submit-hook>\nhook said this"));
        assert!(is_harness_text("<command-name>/clear</command-name>"));
        assert!(is_harness_text("Caveat: the messages below were generated"));
    }

    /// Matching on shape must not swallow a person who happens to write markup.
    #[test]
    fn a_person_who_pastes_markup_is_still_a_person() {
        assert!(!is_harness_text("<p>hello</p>"));
        assert!(!is_harness_text("why does <div> break here?"));
        assert!(!is_harness_text("<img src=\"x\">"));
        assert!(!is_harness_text("</closing>"));
        assert!(!is_harness_text("fix the parser"));
    }

    /// A page that already holds the conversation gets nothing for an
    /// unchanged transcript, and only its newest turn onward for a changed
    /// one — the newest included, because a tool result lands on it.
    #[test]
    fn a_poll_gets_only_what_the_page_lacks() {
        let turn = |seq| Turn {
            seq,
            ..sink_claude(&[r#"{"type":"user","message":{"content":"hi"}}"#]).turns[0].clone()
        };
        let whole = Conversation {
            supported: true,
            turns: (0..5).map(turn).collect(),
            earlier: 10,
            stamp: Some("100-1".into()),
            ..Default::default()
        };

        let same = whole.clone().narrowed(&Since {
            stamp: Some("100-1".into()),
            after: Some(4),
        });
        assert!(same.unchanged);
        assert!(same.turns.is_empty());
        assert_eq!(same.earlier, 10, "the count of earlier turns still holds");

        let moved = whole.clone().narrowed(&Since {
            stamp: Some("90-0".into()),
            after: Some(3),
        });
        assert!(!moved.unchanged);
        assert_eq!(
            moved.turns.iter().map(|t| t.seq).collect::<Vec<_>>(),
            [3, 4]
        );

        let first = whole.clone().narrowed(&Since::default());
        assert_eq!(first.turns.len(), 5, "a first read is the whole window");
    }

    fn sink_claude(lines: &[&str]) -> Conversation {
        let mut sink = Sink::default();
        for line in lines {
            sink.claude(&serde_json::from_str(line).unwrap());
        }
        sink.finish()
    }

    fn sink_codex(lines: &[&str]) -> Conversation {
        let mut sink = Sink::default();
        for line in lines {
            sink.codex(&serde_json::from_str(line).unwrap());
        }
        sink.finish()
    }

    fn sink_cursor(lines: &[&str]) -> Conversation {
        let mut sink = Sink::default();
        for line in lines {
            sink.cursor(&serde_json::from_str(line).unwrap());
        }
        sink.finish()
    }

    fn sink_gemini(lines: &[&str]) -> Conversation {
        let mut sink = Sink::default();
        for line in lines {
            sink.gemini(&serde_json::from_str(line).unwrap());
        }
        sink.finish()
    }

    fn sink_pi(lines: &[&str]) -> Conversation {
        let mut sink = Sink::default();
        for line in lines {
            sink.pi(&serde_json::from_str(line).unwrap());
        }
        sink.finish()
    }

    /// A database shaped the way OpenCode writes one, holding the rows of
    /// `ses_f1d129d6dffeGj3ft9REKBbzIY` verbatim.
    ///
    /// The envelope of each message and the JSON of each part are exactly what
    /// the real database held, so a reader that gets this right is right about
    /// the format rather than about a shape invented beside it.
    fn opencode_db(
        messages: &[(&str, i64, &str, &str, &[&str])],
    ) -> (tempfile::TempDir, std::path::PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("opencode.db");
        let db = rusqlite::Connection::open(&path).unwrap();
        db.execute_batch(
            "CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, \
             time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL); \
             CREATE TABLE part (id text PRIMARY KEY, message_id text NOT NULL, \
             session_id text NOT NULL, time_created integer NOT NULL, \
             time_updated integer NOT NULL, data text NOT NULL);",
        )
        .unwrap();
        for (index, (id, created, data, session, parts)) in messages.iter().enumerate() {
            db.execute(
                "INSERT INTO message (id, session_id, time_created, time_updated, data) \
                 VALUES (?1, ?4, ?2, ?2, ?3)",
                rusqlite::params![id, created, data, session],
            )
            .unwrap();
            for (part, data) in parts.iter().enumerate() {
                db.execute(
                    "INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) \
                     VALUES (?1, ?2, ?4, ?3, ?3, ?5)",
                    rusqlite::params![
                        format!("prt_{index}_{part:02}"),
                        id,
                        created,
                        session,
                        *data
                    ],
                )
                .unwrap();
            }
        }
        (dir, path)
    }

    /// What a person asked and what the agent did about it, read out of two
    /// tables rather than a line of JSON: the text is a part of a message, and
    /// so is the call the reply made.
    #[test]
    fn an_opencode_exchange_reads_the_same_way() {
        let (_dir, path) = opencode_db(&[
            (
                "msg_user",
                1_790_513_603_273,
                r#"{"role":"user","time":{"created":1790513603273},"agent":"build","model":{"providerID":"opencode-go","modelID":"deepseek-v4.1-flash"},"summary":{"diffs":[]}}"#,
                "ses_1",
                &[r#"{"type":"text","text":"fix that"}"#],
            ),
            (
                "msg_assistant",
                1_790_513_603_841,
                r#"{"parentID":"msg_user","role":"assistant","mode":"build","agent":"build","cost":0.005038026,"tokens":{"total":35130,"input":33267,"output":43,"reasoning":28,"cache":{"write":0,"read":1792}},"modelID":"deepseek-v4.1-flash","providerID":"opencode-go","time":{"created":1790513603841,"completed":1790513623910},"finish":"tool-calls"}"#,
                "ses_1",
                &[
                    r#"{"type":"step-start","snapshot":"b5c54e70bee180a4dfda72a57242f7cf0cf790c0"}"#,
                    r#"{"type":"reasoning","text":"the note reads wrong","time":{"start":1790513603841,"end":1790513604000}}"#,
                    r#"{"type":"tool","tool":"grep","callID":"call_00_2oelhco6qfl7o8wyhsmg9e2s","state":{"status":"completed","input":{"pattern":"cannot read a OpenCode conversation"},"output":"No files found","metadata":{"matches":0,"truncated":false},"title":"cannot read a OpenCode conversation","time":{"start":1790513604100,"end":1790513604110}}}"#,
                    r#"{"type":"step-finish","reason":"tool-calls","snapshot":"b5c54e70bee180a4dfda72a57242f7cf0cf790c0","cost":0.005038026}"#,
                ],
            ),
        ]);
        let mut session = Session::new(Provider::OpenCode, "ses_1".into());
        session.data_file = Some(path);
        let chat = build(&session, None);
        assert!(chat.supported, "{:?}", chat.note);
        // The thinking part and the two bookkeeping parts are not turns, but
        // the thinking is a turn of its own: it reads differently on purpose.
        assert_eq!(chat.turns.len(), 3);
        assert_eq!(
            (chat.turns[0].role.as_ref(), chat.turns[0].kind.as_ref()),
            ("user", "message")
        );
        assert_eq!(chat.turns[0].text, "fix that");
        assert_eq!(
            (chat.turns[1].role.as_ref(), chat.turns[1].kind.as_ref()),
            ("assistant", "reasoning")
        );
        assert_eq!(chat.turns[1].text, "the note reads wrong");
        // A message is already a whole reply, so the turn it becomes is its own
        // rather than an extension of the reasoning above it.
        assert_eq!(chat.turns[2].seq, 2);
        assert_eq!(chat.turns[2].role, "assistant");
        let call = &chat.turns[2].tools[0];
        assert_eq!(call.name, "grep");
        assert_eq!(call.detail, "cannot read a OpenCode conversation");
        assert_eq!(call.result.as_deref(), Some("No files found"));
        assert!(!call.failed);
        // The millisecond the envelope records is the turn's time, in the form
        // the page hands to its clock.
        assert_eq!(chat.turns[0].ts, util::ms_to_rfc3339(1_790_513_603_273));
    }

    /// A call that has not come back yet, and one that came back wrong, are
    /// both things the live view exists to show: the first has no result to
    /// show, the second has a message to show instead of output.
    #[test]
    fn an_opencode_call_says_whether_it_is_still_running() {
        let (_dir, path) = opencode_db(&[(
            "msg_assistant",
            1_790_513_603_841,
            r#"{"role":"assistant","time":{"created":1790513603841}}"#,
            "ses_1",
            &[
                r#"{"type":"tool","tool":"bash","state":{"status":"running","input":{"command":"cargo test"},"title":"cargo test"}}"#,
                r#"{"type":"tool","tool":"read","state":{"status":"error","input":{"filePath":"/tmp/backend_test.log"},"error":"Cannot read binary file: /tmp/backend_test.log","title":"/tmp/backend_test.log"}}"#,
            ],
        )]);
        let mut session = Session::new(Provider::OpenCode, "ses_1".into());
        session.data_file = Some(path);
        let chat = build(&session, None);
        let tools = &chat.turns[0].tools;
        assert_eq!(tools.len(), 2);
        assert!(tools[0].result.is_none(), "a running call has no result");
        assert!(!tools[0].failed);
        assert_eq!(
            tools[1].result.as_deref(),
            Some("Cannot read binary file: /tmp/backend_test.log")
        );
        assert!(tools[1].failed);
    }

    /// The lines an edit added and removed come out of the input OpenCode
    /// recorded, and the table already counts its `+` and `-` from there, so a
    /// call in the conversation view and its row in the table say one number.
    #[test]
    fn an_opencode_edit_carries_the_same_lines_the_table_counted() {
        let (_dir, path) = opencode_db(&[(
            "msg_assistant",
            1_790_513_603_841,
            r#"{"role":"assistant","time":{"created":1790513603841}}"#,
            "ses_1",
            &[
                r#"{"type":"tool","tool":"edit","state":{"status":"completed","input":{"filePath":"/a/b.rs","oldString":"let a = 1;\nlet b = 2;\n","newString":"let a = 1;\nlet b = 3;\nlet c = 4;\n"},"output":"ok","title":"/a/b.rs"}}"#,
            ],
        )]);
        let mut session = Session::new(Provider::OpenCode, "ses_1".into());
        session.data_file = Some(path);
        let chat = build(&session, None);
        let call = &chat.turns[0].tools[0];
        assert_eq!(call.name, "edit");
        assert_eq!((call.added, call.removed), (3, 2));
        assert!(call.diff.iter().any(|l| l.contains("let b = 3;")));
        assert!(call.diff.iter().any(|l| l.contains("let b = 2;")));
    }

    /// A plugin writing its progress and a tool call replayed into the prompt
    /// both land on a user message. Shown, they are a person being shown their
    /// own tool output a second time, as though they had asked for it.
    #[test]
    fn text_the_harness_played_back_is_not_something_a_person_said() {
        let (_dir, path) = opencode_db(&[(
            "msg_user",
            1_790_513_603_273,
            r#"{"role":"user","time":{"created":1790513603273},"summary":{"diffs":[]}}"#,
            "ses_1",
            &[
                r#"{"type":"text","text":"the real question"}"#,
                r#"{"type":"text","text":"▣ DCP | -31.1K removed, +4.7K summary","ignored":true}"#,
                r#"{"type":"text","text":"Called the Read tool with the following input: {\"filePath\":\"/a/b.rs\"}","synthetic":true}"#,
            ],
        )]);
        let mut session = Session::new(Provider::OpenCode, "ses_1".into());
        session.data_file = Some(path);
        let chat = build(&session, None);
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(chat.turns[0].text, "the real question");
    }

    /// OpenCode drops the messages before a compaction and records the seam. A
    /// transcript that opens mid-conversation says so, rather than implying the
    /// session began where the scroll does.
    #[test]
    fn an_opencode_compaction_is_a_seam_not_a_message() {
        let (_dir, path) = opencode_db(&[(
            "msg_compaction",
            1_790_513_603_273,
            r#"{"role":"user","model":{"providerID":"opencode-go"},"agent":"explore","time":{"created":1790513603273},"summary":{"diffs":[]}}"#,
            "ses_1",
            &[r#"{"type":"compaction","auto":true,"overflow":false,"tail_start_id":"msg_tail"}"#],
        )]);
        let mut session = Session::new(Provider::OpenCode, "ses_1".into());
        session.data_file = Some(path);
        let chat = build(&session, None);
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(
            (chat.turns[0].role.as_ref(), chat.turns[0].kind.as_ref()),
            ("system", "compaction")
        );
        assert!(chat.turns[0].text.contains("compacted"));
    }

    /// Four hundred and ninety of the seven hundred sessions here are a
    /// subagent, whose messages are their own. A parent that read its child's
    /// would show work twice, on two rows of the table at once.
    #[test]
    fn an_opencode_subagent_does_not_leak_into_its_parent() {
        let (_dir, path) = opencode_db(&[
            (
                "msg_parent",
                1_790_513_603_273,
                r#"{"role":"user","time":{"created":1790513603273}}"#,
                "ses_parent",
                &[r#"{"type":"text","text":"the parent's question"}"#],
            ),
            (
                "msg_child",
                1_790_513_603_274,
                r#"{"role":"user","time":{"created":1790513603274}}"#,
                "ses_child",
                &[r#"{"type":"text","text":"the subagent's brief"}"#],
            ),
        ]);
        let mut session = Session::new(Provider::OpenCode, "ses_parent".into());
        session.data_file = Some(path);
        let chat = build(&session, None);
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(chat.turns[0].text, "the parent's question");
    }

    /// A Cursor exchange reads the way every other does: the role says who is
    /// speaking, the blocks are the words and the calls, and what the harness
    /// does not keep is left as a gap rather than filled in.
    ///
    /// These are the shapes Cursor actually writes, taken from transcripts in
    /// `~/.cursor/projects`: no `type` on a message entry at all, `turn_ended`
    /// entries beside them, and user text wrapped in `<user_query>`.
    #[test]
    fn a_cursor_exchange_reads_the_same_way() {
        let chat = sink_cursor(&[
            r#"{"role":"user","message":{"content":[{"type":"text","text":"<user_query>\nextract doesn't extract the lorebook\n</user_query>"}]}}"#,
            r#"{"role":"assistant","message":{"content":[{"type":"text","text":"I'll trace how `extract` works."},{"type":"tool_use","name":"Grep","input":{"pattern":"lorebook","path":"/home/flo/JAR/jar_cli"}}]}}"#,
            r#"{"type":"turn_ended","status":"success"}"#,
            r#"{"type":"turn_ended","status":"error","error":"User aborted request"}"#,
        ]);
        assert_eq!(chat.turns.len(), 2);
        assert_eq!(chat.turns[0].role, "user");
        // The wrapper is Cursor's, not the person's.
        assert_eq!(chat.turns[0].text, "extract doesn't extract the lorebook");
        assert_eq!(chat.turns[1].role, "assistant");
        assert_eq!(chat.turns[1].text, "I'll trace how `extract` works.");
        assert_eq!(chat.turns[1].tools.len(), 1);
        assert_eq!(chat.turns[1].tools[0].name, "Grep");
        assert!(chat.turns[1].tools[0].detail.contains("lorebook"));
        // Cursor dates nothing, so there is no time to show.
        assert_eq!(chat.turns[1].ts, "");
    }

    /// A Cursor call carries no outcome, and saying so must not read as a call
    /// still running: the page shows a missing result as a live one.
    #[test]
    fn a_cursor_call_is_not_forever_running() {
        let chat = sink_cursor(&[
            r#"{"role":"assistant","message":{"content":[{"type":"tool_use","name":"Read","input":{"path":"src/main.rs"}}]}}"#,
        ]);
        let tool = &chat.turns[0].tools[0];
        assert_eq!(tool.result.as_deref(), Some(""));
        assert!(!tool.failed);
    }

    /// A Gemini reply is one record holding its thoughts, its words and every
    /// call it made, with each result on the call itself.
    #[test]
    fn a_gemini_reply_reads_the_same_way() {
        let chat = sink_gemini(&[
            r#"{"sessionId":"79709c93","startTime":"2026-05-14T17:34:01.387Z","kind":"main"}"#,
            r#"{"$set":{"summary":"Improving script latency"}}"#,
            r#"{"type":"user","timestamp":"2026-05-14T17:34:06.028Z","content":[{"text":"go"}]}"#,
            r#"{"type":"gemini","timestamp":"2026-05-14T17:34:13.475Z","content":"on it","thoughts":[{"subject":"Where it blocks","description":"the parser re-reads the file per record"}],"toolCalls":[{"id":"read_file_1","name":"read_file","args":{"file_path":"README.md"},"status":"success","result":[{"functionResponse":{"id":"read_file_1","name":"read_file","response":{"output":"the readme"}}}]}]}"#,
            r#"{"type":"info","timestamp":"2026-05-14T17:34:20.000Z","content":"Switched to Plan Mode."}"#,
        ]);
        // The header and the `$set` patch are not conversation.
        assert_eq!(chat.turns.len(), 4);
        assert_eq!(chat.turns[0].role, "user");
        assert_eq!(chat.turns[0].text, "go");
        assert_eq!(chat.turns[0].ts, "2026-05-14T17:34:06.028Z");
        assert_eq!(chat.turns[1].kind, "reasoning");
        assert_eq!(
            chat.turns[1].text,
            "the parser re-reads the file per record"
        );
        assert_eq!(chat.turns[2].text, "on it");
        let tool = &chat.turns[2].tools[0];
        assert_eq!(tool.name, "read_file");
        assert_eq!(tool.result.as_deref(), Some("the readme"));
        assert!(!tool.failed);
        // The harness speaking for itself.
        assert_eq!(chat.turns[3].role, "system");
        assert_eq!(chat.turns[3].text, "Switched to Plan Mode.");
    }

    /// A Gemini call that failed says so, and one with no result yet is a call
    /// in flight — this harness records outcomes, so the two are tellable apart.
    #[test]
    fn a_gemini_call_says_whether_it_still_is_running() {
        let chat = sink_gemini(&[
            r#"{"type":"gemini","timestamp":"t","content":"","toolCalls":[{"id":"a","name":"replace","args":{"file_path":"src/main.rs"},"status":"error","result":[{"functionResponse":{"response":{"output":"no such file"}}}]}]}"#,
            r#"{"type":"gemini","timestamp":"t2","content":"","toolCalls":[{"id":"b","name":"read_file","args":{}}]}"#,
        ]);
        assert!(chat.turns[0].tools[0].failed);
        assert_eq!(
            chat.turns[0].tools[0].result.as_deref(),
            Some("no such file")
        );
        // No result recorded: Gemini keeps them, so this one is still running.
        assert!(chat.turns[1].tools[0].result.is_none());
    }

    /// A Pi exchange: a person's turn is a bare string, an agent's is blocks,
    /// and a result is an entry of its own keyed to the call it answers.
    #[test]
    fn a_pi_exchange_reads_the_same_way() {
        let chat = sink_pi(&[
            r#"{"type":"session","version":3,"id":"pi-1","timestamp":"2024-12-03T14:00:00.000Z","cwd":"/work"}"#,
            r#"{"type":"label","label":"a name for this session"}"#,
            r#"{"type":"message","id":"a1","parentId":null,"timestamp":"2024-12-03T14:00:01.000Z","message":{"role":"user","content":"Hello"}}"#,
            r#"{"type":"message","id":"b2","parentId":"a1","timestamp":"2024-12-03T14:00:02.000Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"they said hello"},{"type":"text","text":"Hi!"},{"type":"toolCall","id":"call_123","name":"bash","arguments":{"command":"ls"}}]}}"#,
            r#"{"type":"message","id":"c3","parentId":"b2","timestamp":"2024-12-03T14:00:03.000Z","message":{"role":"toolResult","toolCallId":"call_123","toolName":"bash","content":[{"type":"text","text":"README.md"}],"isError":false}}"#,
        ]);
        // The session header and the label are the harness, not the conversation.
        assert_eq!(chat.turns.len(), 3);
        assert_eq!(chat.turns[0].role, "user");
        assert_eq!(chat.turns[0].text, "Hello");
        assert_eq!(chat.turns[1].kind, "reasoning");
        assert_eq!(chat.turns[1].text, "they said hello");
        assert_eq!(chat.turns[2].text, "Hi!");
        let tool = &chat.turns[2].tools[0];
        assert_eq!(tool.name, "bash");
        // The result arrived as a later entry and found its call.
        assert_eq!(tool.result.as_deref(), Some("README.md"));
        assert!(!tool.failed);
    }

    /// A Pi result that failed is marked as one, and a call with no result
    /// entry behind it is a call in flight.
    #[test]
    fn a_pi_call_says_whether_it_still_is_running() {
        let chat = sink_pi(&[
            r#"{"type":"message","timestamp":"t","message":{"role":"assistant","content":[{"type":"toolCall","id":"c1","name":"bash","arguments":{}}]}}"#,
            r#"{"type":"message","timestamp":"t2","message":{"role":"toolResult","toolCallId":"c1","toolName":"bash","content":[{"type":"text","text":"boom"}],"isError":true}}"#,
        ]);
        assert!(chat.turns[0].tools[0].failed);
        assert_eq!(chat.turns[0].tools[0].result.as_deref(), Some("boom"));
    }

    /// An editor's arguments are the patch, whichever harness spelled the tool
    /// its own way — this is what the report's per-file diffs read.
    #[test]
    fn an_edit_carries_the_patch_whatever_the_tool_is_called() {
        let chat = sink_cursor(&[
            r#"{"role":"assistant","message":{"content":[{"type":"tool_use","name":"Edit","input":{"path":"a.rs","oldString":"let x = 1;","newString":"let x = 2;"}}]}}"#,
        ]);
        let tool = &chat.turns[0].tools[0];
        assert_eq!((tool.added, tool.removed), (1, 1));
        assert_eq!(tool.diff, vec!["-let x = 1;", "+let x = 2;"]);
    }

    #[test]
    fn a_claude_exchange_becomes_a_user_turn_and_an_assistant_turn() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"role":"user","content":"fix the parser"}}"#,
            r#"{"type":"assistant","timestamp":"t2","message":{"role":"assistant","content":[{"type":"text","text":"on it"}]}}"#,
        ]);
        assert!(chat.supported);
        assert_eq!(chat.turns.len(), 2);
        assert_eq!(chat.turns[0].role, "user");
        assert_eq!(chat.turns[0].text, "fix the parser");
        assert_eq!(chat.turns[1].role, "assistant");
        assert_eq!(chat.turns[1].text, "on it");
    }

    /// The call and its result are two entries a long way apart in the file, and
    /// the whole point of the id index is that they come back as one thing.
    #[test]
    fn a_tool_result_lands_on_the_call_it_answers() {
        let chat = sink_claude(&[
            r#"{"type":"assistant","timestamp":"t1","message":{"content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{"file_path":"/a/b.rs"}}]}}"#,
            r#"{"type":"assistant","timestamp":"t2","message":{"content":[{"type":"text","text":"meanwhile"}]}}"#,
            r#"{"type":"user","timestamp":"t3","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"fn main() {}"}]}}"#,
        ]);
        let tool = &chat.turns[0].tools[0];
        assert_eq!(tool.name, "Read");
        assert_eq!(tool.detail, "/a/b.rs");
        assert_eq!(tool.result.as_deref(), Some("fn main() {}"));
        assert!(!tool.failed);
        // The result entry carried no text of its own, so it is not a turn —
        // and the two assistant entries are one reply, since nothing came back
        // in between.
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(chat.turns[0].text, "meanwhile");
    }

    /// Claude writes the text of a reply and each of its tool calls as separate
    /// records. Rendered one box per record, a single answer becomes four, three
    /// of them empty but for a tool name.
    #[test]
    fn a_run_of_assistant_entries_is_one_reply() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t0","message":{"content":"go"}}"#,
            r#"{"type":"assistant","timestamp":"t1","message":{"content":[{"type":"text","text":"first"}]}}"#,
            r#"{"type":"assistant","timestamp":"t2","message":{"content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{"file_path":"/a"}}]}}"#,
            r#"{"type":"assistant","timestamp":"t3","message":{"content":[{"type":"text","text":"second"}]}}"#,
            r#"{"type":"user","timestamp":"t4","message":{"content":"again"}}"#,
            r#"{"type":"assistant","timestamp":"t5","message":{"content":[{"type":"text","text":"a new reply"}]}}"#,
        ]);
        let roles: Vec<&str> = chat.turns.iter().map(|t| t.role.as_ref()).collect();
        assert_eq!(roles, vec!["user", "assistant", "user", "assistant"]);
        assert_eq!(chat.turns[1].text, "first\n\nsecond");
        assert_eq!(chat.turns[1].tools.len(), 1);
        // A user turn between them ends the run, so the next reply is its own.
        assert_eq!(chat.turns[3].text, "a new reply");
    }

    #[test]
    fn a_failed_result_is_marked_as_one() {
        let chat = sink_claude(&[
            r#"{"type":"assistant","timestamp":"t1","message":{"content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"cargo test"}}]}}"#,
            r#"{"type":"user","timestamp":"t2","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_1","is_error":true,"content":"no such command"}]}}"#,
        ]);
        assert!(chat.turns[0].tools[0].failed);
    }

    /// A call with no result yet is what a live session looks like, and the page
    /// shows it as running — so the absence has to survive to the JSON.
    #[test]
    fn a_call_still_running_has_no_result() {
        let chat = sink_claude(&[
            r#"{"type":"assistant","timestamp":"t1","message":{"content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"sleep 60"}}]}}"#,
        ]);
        assert!(chat.turns[0].tools[0].result.is_none());
    }

    #[test]
    fn an_edits_patch_is_carried_with_its_tool_call() {
        let chat = sink_claude(&[
            r#"{"type":"assistant","timestamp":"t1","message":{"content":[{"type":"tool_use","id":"toolu_1","name":"Edit","input":{"file_path":"/a/b.rs"}}]}}"#,
            r#"{"type":"user","timestamp":"t2","toolUseResult":{"structuredPatch":[{"lines":["-old","+new","+also"]}]},"message":{"content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"}]}}"#,
        ]);
        let tool = &chat.turns[0].tools[0];
        assert_eq!((tool.added, tool.removed), (2, 1));
        assert_eq!(tool.diff, vec!["-old", "+new", "+also"]);
    }

    /// A subagent writes into the same file, and its turns are another
    /// conversation. Including them interleaves two agents into one thread.
    #[test]
    fn sidechain_turns_are_left_out() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"content":"the real ask"}}"#,
            r#"{"type":"user","timestamp":"t2","isSidechain":true,"message":{"content":"a subagent's brief"}}"#,
        ]);
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(chat.turns[0].text, "the real ask");
    }

    #[test]
    fn a_compaction_summary_is_a_seam_not_a_message() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","isCompactSummary":true,"message":{"content":"everything so far"}}"#,
        ]);
        assert_eq!(chat.turns[0].kind, "compaction");
        assert_eq!(chat.turns[0].role, "system");
    }

    #[test]
    fn a_slash_command_expansion_is_attributed_to_the_harness() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"content":"<command-name>/clear</command-name>"}}"#,
        ]);
        assert_eq!(chat.turns[0].role, "system");
    }

    /// What the harness records for one `/loop 5m` is four tags. What it did
    /// is one line, and that is what the page has room for.
    #[test]
    fn a_slash_command_reads_as_the_command_that_was_typed() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"content":"<command-name>/loop</command-name>\n<command-message>loop</command-message>\n<command-args>5m</command-args>\n<local-command-stdout>started</local-command-stdout>"}}"#,
        ]);
        assert_eq!(chat.turns[0].text, "/loop 5m\n\nstarted");
    }

    /// `/clear` prints nothing, so its turn is the command alone rather than
    /// the command and an empty line where the output would have been.
    #[test]
    fn a_command_that_printed_nothing_is_just_the_command() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"content":"<command-name>/clear</command-name>\n<local-command-stdout></local-command-stdout>"}}"#,
        ]);
        assert_eq!(chat.turns[0].text, "/clear");
    }

    /// A reminder is prose in a wrapper. The prose survives; the wrapper does
    /// not, and neither does a turn that was nothing but wrapper.
    #[test]
    fn a_reminder_keeps_its_words_and_loses_its_tags() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"content":"<system-reminder>\nthe file changed on disk\n</system-reminder>"}}"#,
            r#"{"type":"user","timestamp":"t2","message":{"content":"<local-command-stdout></local-command-stdout>"}}"#,
        ]);
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(chat.turns[0].text, "the file changed on disk");
    }

    /// The same block written on one line has no line the filter can keep, and
    /// dropping it would lose the only thing it said.
    #[test]
    fn a_one_line_reminder_survives_the_same_way() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"content":"<system-reminder>read the file first</system-reminder>"}}"#,
        ]);
        assert_eq!(chat.turns[0].text, "read the file first");
    }

    /// A task notification is fields for a dispatcher around one line of
    /// news. The generic tidy used to strip every field line, find nothing
    /// left, and keep the whole list as the turn's text.
    #[test]
    fn a_task_notification_reads_as_its_summary() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"content":"<task-notification>\n<task-id>bgbdzpbxb</task-id>\n<tool-use-id>toolu_01EK11bfRvKo9QaZMQWsMBGf</tool-use-id>\n<output-file>/tmp/tasks/bgbdzpbxb.output</output-file>\n<status>completed</status>\n<summary>Background command &quot;cargo build 2&gt;&amp;1 | tail -3&quot; completed (exit code 0)</summary>\n</task-notification>"}}"#,
        ]);
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(chat.turns[0].role, "system");
        assert_eq!(
            chat.turns[0].text,
            "Background command \"cargo build 2>&1 | tail -3\" completed (exit code 0)"
        );
    }

    /// A monitor's report names its watch in `summary` and carries the news
    /// in `event`; both belong on the turn.
    #[test]
    fn a_monitor_event_keeps_the_event_it_reports() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"content":"<task-notification>\n<task-id>br7crykx8</task-id>\n<summary>Monitor event: &quot;rebuild chain&quot;</summary>\n<event>[Monitor expired after 30m with 11 events delivered.]</event>\n</task-notification>"}}"#,
        ]);
        assert_eq!(
            chat.turns[0].text,
            "Monitor event: \"rebuild chain\"\n[Monitor expired after 30m with 11 events delivered.]"
        );
    }

    /// A finished agent can leave a `result` note under its summary.
    #[test]
    fn a_task_notification_keeps_an_agents_parting_note() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"content":"<task-notification>\n<task-id>ad13e524</task-id>\n<status>completed</status>\n<summary>Agent &quot;bench linkage&quot; finished</summary>\n<result>the build query is running in the background</result>\n<usage><subagent_tokens>83901</subagent_tokens></usage>\n</task-notification>"}}"#,
        ]);
        assert_eq!(
            chat.turns[0].text,
            "Agent \"bench linkage\" finished\nthe build query is running in the background"
        );
    }

    /// A notification carrying none of the fields a reader needs is not a
    /// turn at all — the field list itself was the bug, not the content.
    #[test]
    fn a_notification_with_no_news_is_no_turn() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t1","message":{"content":"<task-notification>\n<task-id>x</task-id>\n<output-file>/tmp/x.output</output-file>\n<status>completed</status>\n</task-notification>"}}"#,
            r#"{"type":"user","timestamp":"t2","message":{"content":"a real message"}}"#,
        ]);
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(chat.turns[0].text, "a real message");
    }

    /// Everything after the cap is dropped from the *front*, because a
    /// conversation is read from where it got to — and the count of what was
    /// dropped is what stops the page implying the session started there.
    #[test]
    fn only_the_newest_turns_survive_and_the_rest_are_counted() {
        let lines: Vec<String> = (0..MAX_TURNS + 10)
            .map(|i| {
                format!(
                    r#"{{"type":"user","timestamp":"t","message":{{"content":"message {i}"}}}}"#
                )
            })
            .collect();
        let refs: Vec<&str> = lines.iter().map(String::as_str).collect();
        let chat = sink_claude(&refs);
        assert_eq!(chat.turns.len(), MAX_TURNS);
        assert_eq!(chat.earlier, 10);
        assert_eq!(chat.turns[0].text, "message 10");
    }

    /// A result whose call has already fallen off the front must not land on
    /// whichever turn now occupies that slot. This is the bug the sequence
    /// numbering exists to prevent.
    #[test]
    fn a_result_for_a_dropped_call_is_discarded() {
        let mut lines = vec![
            r#"{"type":"assistant","timestamp":"t0","message":{"content":[{"type":"tool_use","id":"toolu_old","name":"Read","input":{"file_path":"/gone.rs"}}]}}"#.to_string(),
        ];
        for i in 0..MAX_TURNS + 5 {
            lines.push(format!(
                r#"{{"type":"user","timestamp":"t","message":{{"content":"filler {i}"}}}}"#
            ));
        }
        lines.push(
            r#"{"type":"user","timestamp":"tz","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_old","content":"late"}]}}"#
                .to_string(),
        );
        let refs: Vec<&str> = lines.iter().map(String::as_str).collect();
        let chat = sink_claude(&refs);
        assert!(
            chat.turns
                .iter()
                .all(|t| t.tools.iter().all(|tool| tool.result.is_none())),
            "a result was attached to a turn that did not make the call"
        );
    }

    #[test]
    fn text_past_the_cap_is_cut_and_says_so() {
        let long = "x".repeat(MAX_TEXT_CHARS + 100);
        let chat = sink_claude(&[&format!(
            r#"{{"type":"user","timestamp":"t","message":{{"content":"{long}"}}}}"#
        )]);
        assert!(chat.turns[0].clipped);
        assert_eq!(chat.turns[0].text.chars().count(), MAX_TEXT_CHARS);
    }

    #[test]
    fn thinking_is_its_own_turn_ahead_of_the_reply() {
        let chat = sink_claude(&[
            r#"{"type":"assistant","timestamp":"t1","message":{"content":[{"type":"thinking","thinking":"weighing it up"},{"type":"text","text":"here goes"}]}}"#,
        ]);
        assert_eq!(chat.turns.len(), 2);
        assert_eq!(chat.turns[0].kind, "reasoning");
        assert_eq!(chat.turns[1].text, "here goes");
    }

    #[test]
    fn a_codex_exchange_reads_the_same_way() {
        let chat = sink_codex(&[
            r#"{"type":"response_item","timestamp":"t1","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"ship it"}]}}"#,
            r#"{"type":"response_item","timestamp":"t2","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"shipping"}]}}"#,
        ]);
        assert_eq!(chat.turns.len(), 2);
        assert_eq!(chat.turns[0].role, "user");
        assert_eq!(chat.turns[1].text, "shipping");
    }

    /// Codex writes a call as its own entry with nothing linking it to the
    /// message that issued it, so it has to attach to the turn in progress.
    #[test]
    fn a_codex_call_attaches_to_the_assistant_turn_in_progress() {
        let chat = sink_codex(&[
            r#"{"type":"response_item","timestamp":"t1","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"looking"}]}}"#,
            r#"{"type":"response_item","timestamp":"t2","payload":{"type":"function_call","call_id":"c1","name":"shell","arguments":"{\"command\":\"ls\"}"}}"#,
            r#"{"type":"response_item","timestamp":"t3","payload":{"type":"function_call_output","call_id":"c1","output":"a.rs\nb.rs"}}"#,
        ]);
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(chat.turns[0].tools.len(), 1);
        assert_eq!(chat.turns[0].tools[0].result.as_deref(), Some("a.rs\nb.rs"));
    }

    #[test]
    fn a_repeated_codex_call_id_is_one_call() {
        let entry = r#"{"type":"response_item","timestamp":"t","payload":{"type":"function_call","call_id":"c1","name":"shell","arguments":"{\"command\":\"ls\"}"}}"#;
        let chat = sink_codex(&[entry, entry]);
        assert_eq!(chat.turns[0].tools.len(), 1);
    }

    #[test]
    fn a_codex_apply_patch_carries_its_diff() {
        let chat = sink_codex(&[
            r#"{"type":"response_item","timestamp":"t","payload":{"type":"custom_tool_call","call_id":"c1","name":"apply_patch","input":"*** Begin Patch\n*** Update File: src/a.rs\n-old\n+new\n*** End Patch"}}"#,
        ]);
        let tool = &chat.turns[0].tools[0];
        assert!(tool.added >= 1 && tool.removed >= 1, "{tool:?}");
        assert!(!tool.diff.is_empty());
    }

    /// The other half of the merge: everything between two user turns is *not*
    /// one reply, because a tool result means the model was asked again. Without
    /// this bound an afternoon's session comes back as two boxes holding sixty
    /// tool calls each — which is what the first cut of this did.
    /// A reply with extended thinking writes a thinking block into every record
    /// of itself, and its parallel tool calls arrive as separate records too.
    /// The request id is what says they are all one answer.
    #[test]
    fn records_sharing_a_request_id_are_one_reply() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t0","message":{"content":"go"}}"#,
            r#"{"type":"assistant","timestamp":"t1","requestId":"req_1","message":{"content":[{"type":"thinking","thinking":"weighing"},{"type":"text","text":"two at once"}]}}"#,
            r#"{"type":"assistant","timestamp":"t2","requestId":"req_1","message":{"content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{"file_path":"/a"}}]}}"#,
            r#"{"type":"assistant","timestamp":"t3","requestId":"req_1","message":{"content":[{"type":"tool_use","id":"toolu_2","name":"Read","input":{"file_path":"/b"}}]}}"#,
        ]);
        let kinds: Vec<&str> = chat.turns.iter().map(|t| t.kind.as_ref()).collect();
        assert_eq!(kinds, vec!["message", "reasoning", "message"]);
        assert_eq!(chat.turns[2].text, "two at once");
        assert_eq!(chat.turns[2].tools.len(), 2, "{:?}", chat.turns[2]);
    }

    #[test]
    fn a_tool_result_ends_the_reply_it_came_back_to() {
        let chat = sink_claude(&[
            r#"{"type":"user","timestamp":"t0","message":{"content":"go"}}"#,
            r#"{"type":"assistant","timestamp":"t1","message":{"content":[{"type":"text","text":"looking"},{"type":"tool_use","id":"toolu_1","name":"Read","input":{"file_path":"/a"}}]}}"#,
            r#"{"type":"user","timestamp":"t2","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"contents"}]}}"#,
            r#"{"type":"assistant","timestamp":"t3","message":{"content":[{"type":"text","text":"now I know"}]}}"#,
        ]);
        let roles: Vec<&str> = chat.turns.iter().map(|t| t.role.as_ref()).collect();
        assert_eq!(roles, vec!["user", "assistant", "assistant"]);
        assert_eq!(chat.turns[1].text, "looking");
        assert_eq!(chat.turns[1].tools.len(), 1);
        assert_eq!(chat.turns[2].text, "now I know");
        assert!(chat.turns[2].tools.is_empty());
    }

    #[test]
    fn a_provider_with_no_reader_says_so_instead_of_looking_empty() {
        let mut session = Session::new(Provider::Windsurf, "s1".into());
        session.data_file = Some(std::path::PathBuf::from("/nonexistent"));
        let chat = build(&session, None);
        assert!(!chat.supported);
        assert!(chat.note.is_some_and(|n| n.contains("Windsurf")));
    }

    fn sink_devin(steps: &[&str], statuses: &HashMap<String, String>) -> Conversation {
        let mut sink = Sink::default();
        for step in steps {
            sink.devin(&serde_json::from_str(step).unwrap(), statuses);
        }
        sink.finish()
    }

    /// One ATIF step is one model response: the message is the reply text,
    /// `reasoning_content` is the thinking that preceded it.
    #[test]
    fn a_devin_exchange_reads_the_same_way() {
        let chat = sink_devin(
            &[
                r#"{"step_id":1,"source":"user","timestamp":"t1","message":"fix the parser"}"#,
                r#"{"step_id":2,"source":"agent","timestamp":"t2","reasoning_content":"weighing it up","message":"on it"}"#,
            ],
            &HashMap::new(),
        );
        assert!(chat.supported);
        let roles: Vec<(&str, &str)> = chat
            .turns
            .iter()
            .map(|t| (t.role.as_ref(), t.kind.as_ref()))
            .collect();
        assert_eq!(
            roles,
            vec![
                ("user", "message"),
                ("assistant", "reasoning"),
                ("assistant", "message")
            ]
        );
        assert_eq!(chat.turns[0].text, "fix the parser");
        assert_eq!(chat.turns[1].text, "weighing it up");
        assert_eq!(chat.turns[2].text, "on it");
    }

    /// Devin records a call's result on the same step that made it, under
    /// `observation.results` keyed by `source_call_id` — the call and its
    /// outcome still come back as one thing.
    #[test]
    fn a_devin_result_lands_on_the_call_it_made() {
        let chat = sink_devin(
            &[
                r#"{"step_id":3,"source":"agent","timestamp":"t","message":"reading","tool_calls":[{"tool_call_id":"read_1#abc","function_name":"read","arguments":{"file_path":"/a/b.rs"}}],"observation":{"results":[{"source_call_id":"read_1#abc","content":"fn main() {}"}]}}"#,
            ],
            &HashMap::new(),
        );
        assert_eq!(chat.turns.len(), 1);
        let tool = &chat.turns[0].tools[0];
        assert_eq!(tool.name, "read");
        assert_eq!(tool.detail, "/a/b.rs");
        assert_eq!(tool.result.as_deref(), Some("fn main() {}"));
        assert!(!tool.failed);
    }

    /// Two steps are two replies even when neither made a call — the step id
    /// is what stops them being folded into one.
    #[test]
    fn consecutive_devin_steps_stay_separate_replies() {
        let chat = sink_devin(
            &[
                r#"{"step_id":1,"source":"agent","timestamp":"t1","message":"first"}"#,
                r#"{"step_id":2,"source":"agent","timestamp":"t2","message":"second"}"#,
            ],
            &HashMap::new(),
        );
        assert_eq!(chat.turns.len(), 2);
        assert_eq!(chat.turns[0].text, "first");
        assert_eq!(chat.turns[1].text, "second");
    }

    /// The transcript does not say how a call ended; the database's status
    /// map does. A call whose last reported status is not `completed` failed.
    #[test]
    fn a_devin_call_the_database_marked_failed_is_marked() {
        let statuses = HashMap::from([("exec_1#abc".to_string(), "failed".to_string())]);
        let chat = sink_devin(
            &[
                r#"{"step_id":1,"source":"agent","timestamp":"t","tool_calls":[{"tool_call_id":"exec_1#abc","function_name":"exec","arguments":{"command":"cargo test"}}],"observation":{"results":[{"source_call_id":"exec_1#abc","content":"error: no such target"}]}}"#,
            ],
            &statuses,
        );
        let tool = &chat.turns[0].tools[0];
        assert!(tool.failed);
        assert_eq!(tool.result.as_deref(), Some("error: no such target"));
    }

    /// A call still running has an observation pending, so no result at all —
    /// which is what the page shows as in-flight.
    #[test]
    fn a_devin_call_with_no_observation_is_still_running() {
        let chat = sink_devin(
            &[
                r#"{"step_id":1,"source":"agent","timestamp":"t","tool_calls":[{"tool_call_id":"exec_1#abc","function_name":"exec","arguments":{"command":"sleep 60"}}]}"#,
            ],
            &HashMap::new(),
        );
        assert!(chat.turns[0].tools[0].result.is_none());
    }

    /// ATIF has no `structuredPatch`; the patch an `edit` applied is its own
    /// `old_string`/`new_string` arguments.
    #[test]
    fn a_devin_edit_carries_its_diff() {
        let chat = sink_devin(
            &[
                r#"{"step_id":1,"source":"agent","timestamp":"t","tool_calls":[{"tool_call_id":"edit_1#abc","function_name":"edit","arguments":{"file_path":"/a/b.rs","old_string":"old\nlines","new_string":"new\nalso"}}],"observation":{"results":[{"source_call_id":"edit_1#abc","content":"updated"}]}}"#,
            ],
            &HashMap::new(),
        );
        let tool = &chat.turns[0].tools[0];
        assert_eq!((tool.added, tool.removed), (2, 2));
        assert_eq!(tool.diff, vec!["-old", "-lines", "+new", "+also"]);
    }

    /// The system prompt, the rule files and the context blocks re-injected at
    /// every turn are all steps too, but they are the prompt being assembled,
    /// not the conversation. A step the harness injected mid-run — a
    /// backgrounded subagent finishing, the user editing a file — is one.
    #[test]
    fn devin_prompt_assembly_is_not_a_turn() {
        let chat = sink_devin(
            &[
                r#"{"step_id":1,"source":"system","timestamp":"t1","message":"You are Devin…","extra":{"telemetry":{"source":"sysprompt"}}}"#,
                r#"{"step_id":2,"source":"system","timestamp":"t2","message":"<rules>…</rules>","extra":{"telemetry":{"source":"rules"}}}"#,
                r#"{"step_id":3,"source":"system","timestamp":"t3","message":"<available_skills>…</available_skills>","extra":{"telemetry":{"source":"system"}}}"#,
                r#"{"step_id":4,"source":"system","timestamp":"t4","message":"You are powered by SWE-2 High.","extra":{"telemetry":{"source":"system"}}}"#,
                r#"{"step_id":5,"source":"system","timestamp":"t5","message":"<subagent_completion_notification>done</subagent_completion_notification>","extra":{"telemetry":{"source":"system"}}}"#,
            ],
            &HashMap::new(),
        );
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(chat.turns[0].role, "system");
        // The envelope comes off an event the same as any other harness block.
        assert_eq!(chat.turns[0].text, "done");
    }

    /// The user-edited-a-file block is aimed at the model: a preamble about
    /// when to mention it and a pseudo-diff per file. The turn is the event.
    #[test]
    fn a_devin_user_action_reads_as_the_files_touched() {
        let chat = sink_devin(
            &[
                r#"{"step_id":1,"source":"system","timestamp":"t1","message":"<additional_metadata>\nThe user took the following actions after the last message. ONLY talk about this if it is directly relevant to the user's next request.\n\n<user_actions>\nThe following changes were made by the USER to: /home/flo/src/a.rs.\n[diff_block_start]\n@@ -1 +1 @@\n-old\n+new\n[diff_block_end]\nPlease note that the above snippet only shows the MODIFIED lines.\nThe following changes were made by the USER to: /home/flo/src/b.rs.\n[diff_block_start]\n@@ -2 +2 @@\n-x\n+y\n[diff_block_end]\n</user_actions>\n</additional_metadata>","extra":{"telemetry":{"source":"system"}}}"#,
            ],
            &HashMap::new(),
        );
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(
            chat.turns[0].text,
            "the user edited /home/flo/src/a.rs, /home/flo/src/b.rs"
        );
    }

    /// A transcript that is not the document ATIF says it is reports as
    /// unreadable rather than panicking or looking empty.
    #[test]
    fn a_devin_transcript_that_is_not_json_is_unsupported() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s1.json");
        std::fs::write(&path, b"not json").unwrap();
        let mut session = Session::new(Provider::Devin, "s1".into());
        session.data_file = Some(path);
        let chat = build(&session, None);
        assert!(!chat.supported);
        assert!(chat.note.is_some_and(|n| n.contains("could not read")));
    }

    /// A harness name is the one place a label is read inside a sentence, and
    /// "a OpenCode conversation" would be the sentence that carried it.
    #[test]
    fn an_article_follows_the_first_letter_of_the_harness() {
        assert_eq!(article("OpenCode"), "an");
        assert_eq!(article("Claude Code"), "a");
        assert_eq!(article("Codex"), "a");
    }

    /// A provider with no reader says which one it is, rather than coming back
    /// empty and reading like a session that said nothing.
    #[test]
    fn a_provider_with_no_reader_names_itself() {
        let mut session = Session::new(Provider::Windsurf, "s1".into());
        session.data_file = Some(std::path::PathBuf::from("/nonexistent"));
        let chat = build(&session, None);
        assert!(!chat.supported);
        let note = chat.note.expect("a reason is attached");
        assert!(
            note.starts_with("cctop cannot read a Windsurf conversation yet"),
            "{note}"
        );
    }

    /// A turn's `seq` is its place in the whole transcript, not its position
    /// in the window — what `?before=` and the page's turn links count in.
    #[test]
    fn turns_kept_off_the_front_keep_their_sequence_numbers() {
        let mut sink = Sink::default();
        for i in 0..MAX_TURNS + 3 {
            let mut turn = Turn::new("user", "message", "t");
            turn.text = format!("turn {i}");
            sink.push(turn);
        }
        let chat = sink.finish();
        assert_eq!(chat.turns.len(), MAX_TURNS);
        assert_eq!(chat.earlier, 3);
        assert_eq!(chat.turns[0].seq, 3);
        assert_eq!(chat.turns[0].text, "turn 3");
    }

    /// `?before=` ends the window at the boundary rather than the newest
    /// turn, same size and same `earlier` count as the unwindowed one.
    #[test]
    fn a_before_window_ends_where_it_was_asked_to() {
        let mut sink = Sink {
            before: Some(MAX_TURNS + 2),
            ..Sink::default()
        };
        for i in 0..MAX_TURNS + 5 {
            let mut turn = Turn::new("user", "message", "t");
            turn.text = format!("turn {i}");
            sink.push(turn);
        }
        let chat = sink.finish();
        // The three turns past the boundary were numbered — `earlier` and the
        // next window's seqs depend on it — but never kept.
        assert_eq!(chat.turns.len(), MAX_TURNS);
        assert_eq!(chat.earlier, 2);
        assert_eq!(chat.turns[0].seq, 2);
        assert_eq!(chat.turns.last().unwrap().seq, MAX_TURNS + 1);
    }

    /// A result can be written entries after the window's boundary; the call
    /// it answers still has to show as finished.
    #[test]
    fn a_result_past_the_boundary_still_lands_on_its_call() {
        let mut sink = Sink {
            before: Some(1),
            ..Sink::default()
        };
        for line in [
            r#"{"type":"assistant","timestamp":"t1","message":{"content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{"file_path":"/a"}}]}}"#,
            // Turn 1 — past the boundary, numbered but not kept.
            r#"{"type":"user","timestamp":"t2","message":{"content":"next question"}}"#,
            // The call's result, recorded last of all.
            r#"{"type":"user","timestamp":"t3","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"done"}]}}"#,
        ] {
            sink.claude(&serde_json::from_str(line).unwrap());
        }
        let chat = sink.finish();
        assert_eq!(chat.turns.len(), 1);
        assert_eq!(chat.turns[0].seq, 0);
        assert_eq!(chat.turns[0].tools[0].result.as_deref(), Some("done"));
    }
}