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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
/**
 * Unit tests for SessionService and Sessions API
 */

import { describe, it, expect, beforeEach, afterEach } from 'bun:test'
import * as fs from 'node:fs/promises'
import { execFileSync } from 'node:child_process'
import * as path from 'node:path'
import * as os from 'node:os'
import { SessionService, sessionService } from '../services/sessionService.js'
import {
  getRepositoryContext,
  prepareSessionWorkspace,
} from '../services/repositoryLaunchService.js'
import { conversationService } from '../services/conversationService.js'
import { clearCommandsCache } from '../../commands.js'
import { parseJSONL } from '../../utils/json.js'
import { createSessionBranch } from '../../utils/sessionBranching.js'
import { sanitizePath } from '../../utils/sessionStoragePortable.js'
import { clearInstalledPluginsCache } from '../../utils/plugins/installedPluginsManager.js'
import { clearPluginCache } from '../../utils/plugins/pluginLoader.js'
import { resetSettingsCache } from '../../utils/settings/settingsCache.js'
import { updateSessionSlashCommands } from '../ws/handler.js'

// ============================================================================
// Test helpers
// ============================================================================

let tmpDir: string
let service: SessionService

/** Create a temporary config dir and configure the service to use it. */
async function setupTmpConfigDir(): Promise<string> {
  tmpDir = path.join(os.tmpdir(), `claude-test-${Date.now()}-${Math.random().toString(36).slice(2)}`)
  await fs.mkdir(path.join(tmpDir, 'projects'), { recursive: true })
  process.env.CLAUDE_CONFIG_DIR = tmpDir
  return tmpDir
}

async function cleanupTmpDir(): Promise<void> {
  if (tmpDir) {
    await fs.rm(tmpDir, { recursive: true, force: true })
  }
  delete process.env.CLAUDE_CONFIG_DIR
}

function git(cwd: string, ...args: string[]): string {
  return execFileSync('git', args, {
    cwd,
    encoding: 'utf8',
  })
}

async function createCleanGitRepo(baseDir: string): Promise<string> {
  const workDir = path.join(
    baseDir,
    `repo-${Date.now()}-${Math.random().toString(36).slice(2)}`,
  )

  await fs.mkdir(workDir, { recursive: true })
  git(workDir, 'init')
  git(workDir, 'config', 'user.email', 'sessions-api@example.com')
  git(workDir, 'config', 'user.name', 'Sessions API')
  git(workDir, 'checkout', '-b', 'main')
  await fs.writeFile(path.join(workDir, 'README.md'), 'main\n')
  git(workDir, 'add', 'README.md')
  git(workDir, 'commit', '-m', 'initial')
  git(workDir, 'checkout', '-b', 'feature/rail')
  await fs.writeFile(path.join(workDir, 'feature.txt'), 'feature\n')
  git(workDir, 'add', 'feature.txt')
  git(workDir, 'commit', '-m', 'feature')
  git(workDir, 'checkout', 'main')

  return workDir
}

/** Write a JSONL session file with given entries. */
async function writeSessionFile(
  projectDir: string,
  sessionId: string,
  entries: Record<string, unknown>[]
): Promise<string> {
  const dir = path.join(tmpDir, 'projects', projectDir)
  await fs.mkdir(dir, { recursive: true })
  const filePath = path.join(dir, `${sessionId}.jsonl`)
  const content = entries.map((e) => JSON.stringify(e)).join('\n') + '\n'
  await fs.writeFile(filePath, content, 'utf-8')
  return filePath
}

async function writeSubagentTranscriptFile(
  projectDir: string,
  sessionId: string,
  agentId: string,
  entries: Record<string, unknown>[],
): Promise<string> {
  const dir = path.join(tmpDir, 'projects', projectDir, sessionId, 'subagents')
  await fs.mkdir(dir, { recursive: true })
  const normalizedAgentId = agentId.startsWith('agent-') ? agentId : `agent-${agentId}`
  const filePath = path.join(dir, `${normalizedAgentId}.jsonl`)
  const content = entries.map((e) => JSON.stringify(e)).join('\n') + '\n'
  await fs.writeFile(filePath, content, 'utf-8')
  return filePath
}

async function writeSkill(
  rootDir: string,
  skillName: string,
  description: string,
): Promise<void> {
  const skillDir = path.join(rootDir, skillName)
  await fs.mkdir(skillDir, { recursive: true })
  await fs.writeFile(
    path.join(skillDir, 'SKILL.md'),
    ['---', `description: ${description}`, '---', '', `# ${skillName}`].join('\n'),
    'utf-8',
  )
}

async function writeLegacySlashCommand(
  commandsDir: string,
  commandName: string,
  description: string,
): Promise<void> {
  await fs.mkdir(commandsDir, { recursive: true })
  await fs.writeFile(
    path.join(commandsDir, `${commandName}.md`),
    ['---', `description: ${description}`, 'argument-hint: <topic>', '---', '', `Run ${commandName}.`].join('\n'),
    'utf-8',
  )
}

function git(cwd: string, ...args: string[]): string {
  return execFileSync('git', args, {
    cwd,
    encoding: 'utf8',
  })
}

async function createWorkspaceApiGitRepo(baseDir: string): Promise<string> {
  const workDir = path.join(
    baseDir,
    `workspace-api-${Date.now()}-${Math.random().toString(36).slice(2)}`,
  )

  await fs.mkdir(path.join(workDir, 'src'), { recursive: true })
  git(workDir, 'init')
  git(workDir, 'config', 'user.email', 'sessions-api@example.com')
  git(workDir, 'config', 'user.name', 'Sessions API')

  await fs.writeFile(path.join(workDir, 'tracked.txt'), 'before\n')
  await fs.writeFile(path.join(workDir, 'src', 'app.ts'), 'export const answer = 42\n')
  git(workDir, 'add', 'tracked.txt', 'src/app.ts')
  git(workDir, 'commit', '-m', 'initial')

  await fs.writeFile(path.join(workDir, 'tracked.txt'), 'before\nafter\n')

  return workDir
}

async function createCleanGitRepo(baseDir: string): Promise<string> {
  const workDir = path.join(
    baseDir,
    `repo-${Date.now()}-${Math.random().toString(36).slice(2)}`,
  )

  await fs.mkdir(workDir, { recursive: true })
  git(workDir, 'init')
  git(workDir, 'config', 'user.email', 'sessions-api@example.com')
  git(workDir, 'config', 'user.name', 'Sessions API')
  git(workDir, 'checkout', '-b', 'main')
  await fs.writeFile(path.join(workDir, 'README.md'), 'main\n')
  git(workDir, 'add', 'README.md')
  git(workDir, 'commit', '-m', 'initial')
  git(workDir, 'checkout', '-b', 'feature/rail')
  await fs.writeFile(path.join(workDir, 'feature.txt'), 'feature\n')
  git(workDir, 'add', 'feature.txt')
  git(workDir, 'commit', '-m', 'feature')
  git(workDir, 'checkout', 'main')

  return workDir
}

// Sample entries matching real CLI format
function makeSnapshotEntry(): Record<string, unknown> {
  return {
    type: 'file-history-snapshot',
    messageId: crypto.randomUUID(),
    snapshot: {
      messageId: crypto.randomUUID(),
      trackedFileBackups: {},
      timestamp: '2026-01-01T00:00:00.000Z',
    },
    isSnapshotUpdate: false,
  }
}

function makeFileHistorySnapshotEntry(
  snapshotMessageId: string,
  trackedFileBackups: Record<string, unknown>,
): Record<string, unknown> {
  return {
    type: 'file-history-snapshot',
    messageId: crypto.randomUUID(),
    snapshot: {
      messageId: snapshotMessageId,
      trackedFileBackups,
      timestamp: '2026-01-01T00:00:00.000Z',
    },
    isSnapshotUpdate: false,
  }
}

function makeUserEntry(content: string, uuid?: string): Record<string, unknown> {
  return {
    parentUuid: null,
    isSidechain: false,
    type: 'user',
    message: { role: 'user', content },
    uuid: uuid || crypto.randomUUID(),
    timestamp: '2026-01-01T00:01:00.000Z',
    userType: 'external',
    cwd: '/tmp/test',
    sessionId: 'test-session',
  }
}

function makeAssistantEntry(content: string, parentUuid?: string): Record<string, unknown> {
  return {
    parentUuid: parentUuid || null,
    isSidechain: false,
    type: 'assistant',
    message: {
      model: 'claude-opus-4-7',
      id: `msg_${crypto.randomUUID().slice(0, 20)}`,
      type: 'message',
      role: 'assistant',
      content: [{ type: 'text', text: content }],
    },
    uuid: crypto.randomUUID(),
    timestamp: '2026-01-01T00:02:00.000Z',
  }
}

function makeAssistantToolUseEntry(
  toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }>,
  parentUuid?: string,
): Record<string, unknown> {
  return {
    parentUuid: parentUuid || null,
    isSidechain: false,
    type: 'assistant',
    message: {
      model: 'claude-opus-4-7',
      id: `msg_${crypto.randomUUID().slice(0, 20)}`,
      type: 'message',
      role: 'assistant',
      content: toolUses.map((toolUse) => ({
        type: 'tool_use',
        id: toolUse.id,
        name: toolUse.name,
        input: toolUse.input,
      })),
    },
    uuid: crypto.randomUUID(),
    timestamp: '2026-01-01T00:02:00.000Z',
  }
}

function makeToolResultUserEntry(
  toolUseId: string,
  content: string,
  uuid?: string,
  parentUuid?: string,
  sessionId = 'test-session',
): Record<string, unknown> {
  return {
    parentUuid: parentUuid || null,
    isSidechain: false,
    type: 'user',
    message: {
      role: 'user',
      content: [{
        type: 'tool_result',
        tool_use_id: toolUseId,
        content,
      }],
    },
    uuid: uuid || crypto.randomUUID(),
    timestamp: '2026-01-01T00:02:30.000Z',
    userType: 'external',
    cwd: '/tmp/test',
    sessionId,
  }
}

function makeMetaUserEntry(): Record<string, unknown> {
  return {
    parentUuid: null,
    isSidechain: false,
    type: 'user',
    message: { role: 'user', content: '<local-command-caveat>internal</local-command-caveat>' },
    isMeta: true,
    uuid: crypto.randomUUID(),
    timestamp: '2026-01-01T00:00:30.000Z',
  }
}

function makeSessionMetaEntry(workDir: string): Record<string, unknown> {
  return {
    type: 'session-meta',
    isMeta: true,
    workDir,
    timestamp: '2026-01-01T00:00:00.000Z',
  }
}

function makeWorktreeStateEntry(
  sessionId: string,
  worktreePath: string,
  overrides: Record<string, unknown> = {},
): Record<string, unknown> {
  return {
    type: 'worktree-state',
    sessionId,
    worktreeSession: {
      originalCwd: '/tmp/source',
      worktreePath,
      worktreeName: 'desktop-main-12345678',
      worktreeBranch: 'worktree-desktop-main-12345678',
      originalBranch: 'main',
      sessionId,
      ...overrides,
    },
  }
}

function makeContentReplacementEntry(
  sessionId: string,
  replacements: Array<{ kind: 'tool-result'; toolUseId: string; replacement: string }>,
): Record<string, unknown> {
  return {
    type: 'content-replacement',
    sessionId,
    replacements,
  }
}

async function writeFileHistoryBackup(
  sessionId: string,
  backupFileName: string,
  content: string,
): Promise<void> {
  const dir = path.join(tmpDir, 'file-history', sessionId)
  await fs.mkdir(dir, { recursive: true })
  await fs.writeFile(path.join(dir, backupFileName), content, 'utf-8')
}

type ThreeTurnCheckpointFixture = {
  sessionId: string
  workDir: string
  stepFile: string
  createdFile: string
  firstUserId: string
  secondUserId: string
  thirdUserId: string
}

async function createThreeTurnCheckpointFixture(
  sessionId: string,
): Promise<ThreeTurnCheckpointFixture> {
  const workDir = path.join(tmpDir, `turn-checkpoints-${sessionId}`)
  const stepFile = path.join(workDir, 'src', 'step.js')
  const createdFile = path.join(workDir, 'notes', 'generated.txt')
  const firstUserId = crypto.randomUUID()
  const secondUserId = crypto.randomUUID()
  const thirdUserId = crypto.randomUUID()
  const backupBase = `${sessionId}-step@v1`
  const backupV1 = `${sessionId}-step@v2`
  const backupV2 = `${sessionId}-step@v3`

  await fs.mkdir(path.dirname(stepFile), { recursive: true })
  await fs.mkdir(path.dirname(createdFile), { recursive: true })
  await fs.writeFile(stepFile, "export const STEP = 'v3'\n", 'utf-8')
  await fs.writeFile(createdFile, 'generated third turn\n', 'utf-8')
  await writeFileHistoryBackup(sessionId, backupBase, "export const STEP = 'base'\n")
  await writeFileHistoryBackup(sessionId, backupV1, "export const STEP = 'v1'\n")
  await writeFileHistoryBackup(sessionId, backupV2, "export const STEP = 'v2'\n")

  await writeSessionFile('-tmp-api-turn-checkpoints', sessionId, [
    makeSessionMetaEntry(workDir),
    makeFileHistorySnapshotEntry(firstUserId, {
      'src/step.js': {
        backupFileName: backupBase,
        version: 1,
        backupTime: '2026-01-01T00:00:00.000Z',
      },
    }),
    {
      ...makeUserEntry('make v1', firstUserId),
      cwd: workDir,
      sessionId,
    },
    makeAssistantEntry('DONE v1', firstUserId),
    makeFileHistorySnapshotEntry(secondUserId, {
      'src/step.js': {
        backupFileName: backupV1,
        version: 2,
        backupTime: '2026-01-01T00:00:00.000Z',
      },
    }),
    {
      ...makeUserEntry('make v2', secondUserId),
      cwd: workDir,
      sessionId,
    },
    makeAssistantEntry('DONE v2', secondUserId),
    makeFileHistorySnapshotEntry(thirdUserId, {
      'src/step.js': {
        backupFileName: backupV2,
        version: 3,
        backupTime: '2026-01-01T00:00:00.000Z',
      },
      'notes/generated.txt': {
        backupFileName: null,
        version: 3,
        backupTime: '2026-01-01T00:00:00.000Z',
      },
    }),
    {
      ...makeUserEntry('make v3 and create file', thirdUserId),
      cwd: workDir,
      sessionId,
    },
    makeAssistantEntry('DONE v3', thirdUserId),
  ])

  return {
    sessionId,
    workDir,
    stepFile,
    createdFile,
    firstUserId,
    secondUserId,
    thirdUserId,
  }
}

// ============================================================================
// SessionService tests
// ============================================================================

describe('SessionService', () => {
  beforeEach(async () => {
    await setupTmpConfigDir()
    service = new SessionService()
    clearInstalledPluginsCache()
    clearPluginCache('sessions-api-test-setup')
    resetSettingsCache()
  })

  afterEach(async () => {
    clearCommandsCache()
    clearInstalledPluginsCache()
    clearPluginCache('session-service-test-teardown')
    resetSettingsCache()
    await cleanupTmpDir()
  })

  // --------------------------------------------------------------------------
  // listSessions
  // --------------------------------------------------------------------------

  it('should return empty list when no sessions exist', async () => {
    const result = await service.listSessions()
    expect(result.sessions).toEqual([])
    expect(result.total).toBe(0)
  })

  it('should list sessions from JSONL files', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-testproject', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('Hello Claude'),
      makeAssistantEntry('Hi there!'),
    ])

    const result = await service.listSessions()
    expect(result.total).toBe(1)
    expect(result.sessions).toHaveLength(1)

    const session = result.sessions[0]!
    expect(session.id).toBe(sessionId)
    expect(session.title).toBe('Hello Claude')
    expect(session.messageCount).toBe(2) // 1 user + 1 assistant
    expect(session.projectPath).toBe('-tmp-testproject')
    expect(session.projectRoot).toBe('/tmp/test')
  })

  it('should expose the source project root for persisted worktree sessions', async () => {
    const sourceWorkDir = path.join(tmpDir, 'source-repo')
    const worktreePath = path.join(sourceWorkDir, '.claude', 'worktrees', 'desktop-main-12345678')
    await fs.mkdir(worktreePath, { recursive: true })
    const sessionId = 'bbbbbbbb-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile(sanitizePath(worktreePath), sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry(worktreePath),
      makeWorktreeStateEntry(sessionId, worktreePath, {
        originalCwd: sourceWorkDir,
      }),
      makeUserEntry('Hello from worktree'),
    ])

    const result = await service.listSessions()

    expect(result.sessions).toHaveLength(1)
    expect(result.sessions[0]).toMatchObject({
      id: sessionId,
      projectPath: sanitizePath(worktreePath),
      projectRoot: await fs.realpath(sourceWorkDir),
      workDir: worktreePath,
    })
  })

  it('should paginate results with limit and offset', async () => {
    // Create 3 sessions
    for (let i = 0; i < 3; i++) {
      const id = `0000000${i}-bbbb-cccc-dddd-eeeeeeeeeeee`
      await writeSessionFile('-tmp-test', id, [
        makeSnapshotEntry(),
        makeUserEntry(`Message ${i}`),
      ])
    }

    const page1 = await service.listSessions({ limit: 2, offset: 0 })
    expect(page1.total).toBe(3)
    expect(page1.sessions).toHaveLength(2)

    const page2 = await service.listSessions({ limit: 2, offset: 2 })
    expect(page2.total).toBe(3)
    expect(page2.sessions).toHaveLength(1)
  })

  it('should only parse the requested page when listing many sessions', async () => {
    for (let i = 0; i < 12; i++) {
      const id = `1000000${i.toString(16)}-bbbb-cccc-dddd-eeeeeeeeeeee`
      const filePath = await writeSessionFile('-tmp-many-sessions', id, [
        makeSnapshotEntry(),
        makeUserEntry(`Message ${i}`),
      ])
      const mtime = new Date(Date.now() - i * 1000)
      await fs.utimes(filePath, mtime, mtime)
    }

    const serviceWithSpy = service as unknown as {
      readJsonlFile: (...args: unknown[]) => Promise<unknown>
    }
    const originalReadJsonlFile = serviceWithSpy.readJsonlFile.bind(service)
    let readCount = 0
    serviceWithSpy.readJsonlFile = async (...args) => {
      readCount += 1
      return originalReadJsonlFile(...args)
    }

    const result = await service.listSessions({ limit: 3, offset: 0 })

    expect(result.total).toBe(12)
    expect(result.sessions).toHaveLength(3)
    expect(readCount).toBe(3)
  })

  it('should filter sessions by project', async () => {
    const id1 = 'aaaaaaaa-1111-cccc-dddd-eeeeeeeeeeee'
    const id2 = 'aaaaaaaa-2222-cccc-dddd-eeeeeeeeeeee'

    await writeSessionFile('-project-a', id1, [makeSnapshotEntry(), makeUserEntry('In A')])
    await writeSessionFile('-project-b', id2, [makeSnapshotEntry(), makeUserEntry('In B')])

    const resultA = await service.listSessions({ project: '/project/a' })
    expect(resultA.total).toBe(1)
    expect(resultA.sessions[0]!.id).toBe(id1)
  })

  // --------------------------------------------------------------------------
  // getSession
  // --------------------------------------------------------------------------

  it('should return null for non-existent session', async () => {
    const result = await service.getSession('00000000-0000-0000-0000-000000000000')
    expect(result).toBeNull()
  })

  it('should return session detail with messages', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const userUuid = crypto.randomUUID()
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('Tell me a joke', userUuid),
      makeAssistantEntry('Why did the chicken cross the road?', userUuid),
    ])

    const detail = await service.getSession(sessionId)
    expect(detail).not.toBeNull()
    expect(detail!.id).toBe(sessionId)
    expect(detail!.title).toBe('Tell me a joke')
    expect(detail!.messages).toHaveLength(2)
    expect(detail!.messages[0]!.type).toBe('user')
    expect(detail!.messages[1]!.type).toBe('assistant')
  })

  it('should skip meta entries in messages', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeMetaUserEntry(),
      makeUserEntry('Real message'),
    ])

    const detail = await service.getSession(sessionId)
    expect(detail!.messages).toHaveLength(1)
    expect(detail!.messages[0]!.content).toBe('Real message')
  })

  // --------------------------------------------------------------------------
  // getSessionMessages
  // --------------------------------------------------------------------------

  it('should throw for non-existent session messages', async () => {
    expect(
      service.getSessionMessages('00000000-0000-0000-0000-000000000000')
    ).rejects.toThrow('Session not found')
  })

  it('should return messages only', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('Hello'),
      makeAssistantEntry('World'),
    ])

    const messages = await service.getSessionMessages(sessionId)
    expect(messages).toHaveLength(2)
  })

  it('should append subagent tool calls under their parent agent tool result', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const projectDir = '-tmp-project'
    const agentId = 'abc123'

    await writeSessionFile(projectDir, sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('Dispatch an agent'),
      {
        type: 'assistant',
        message: {
          role: 'assistant',
          content: [
            {
              type: 'tool_use',
              id: 'Agent:0',
              name: 'Agent',
              input: { description: 'Inspect alpha' },
            },
          ],
        },
        uuid: crypto.randomUUID(),
        timestamp: '2026-01-01T00:00:02.000Z',
      },
      {
        type: 'user',
        message: {
          role: 'user',
          content: [
            {
              type: 'tool_result',
              tool_use_id: 'Agent:0',
              content: [
                {
                  type: 'text',
                  text: `alpha summary\nagentId: ${agentId} (use SendMessage with to: '${agentId}' to continue this agent)\n<usage>total_tokens: 10\ntool_uses: 2\nduration_ms: 30</usage>`,
                },
              ],
            },
          ],
        },
        uuid: crypto.randomUUID(),
        timestamp: '2026-01-01T00:00:03.000Z',
      },
    ])
    await writeSubagentTranscriptFile(projectDir, sessionId, agentId, [
      {
        type: 'assistant',
        message: {
          role: 'assistant',
          content: [
            {
              type: 'tool_use',
              id: 'Read:0',
              name: 'Read',
              input: { file_path: '/tmp/alpha.txt' },
            },
          ],
        },
        uuid: crypto.randomUUID(),
        timestamp: '2026-01-01T00:00:04.000Z',
      },
      {
        type: 'user',
        message: {
          role: 'user',
          content: [
            {
              type: 'tool_result',
              tool_use_id: 'Read:0',
              content: 'alpha body',
            },
          ],
        },
        uuid: crypto.randomUUID(),
        timestamp: '2026-01-01T00:00:05.000Z',
      },
    ])

    const messages = await service.getSessionMessages(sessionId)
    const childToolUse = messages.find(
      (message) => message.type === 'tool_use' && message.parentToolUseId === 'Agent:0',
    )
    const childToolResult = messages.find(
      (message) => message.type === 'tool_result' && message.parentToolUseId === 'Agent:0',
    )

    expect(childToolUse?.content).toEqual([
      {
        type: 'tool_use',
        id: 'Agent:0/abc123/Read:0',
        name: 'Read',
        input: { file_path: '/tmp/alpha.txt' },
      },
    ])
    expect(childToolResult?.content).toEqual([
      {
        type: 'tool_result',
        tool_use_id: 'Agent:0/abc123/Read:0',
        content: 'alpha body',
      },
    ])
  })

  it('should hide synthetic interruption, no-response, and command breadcrumb transcript entries', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('正常用户消息', crypto.randomUUID()),
      {
        type: 'user',
        message: {
          role: 'user',
          content: [{ type: 'text', text: '[Request interrupted by user]' }],
        },
        uuid: crypto.randomUUID(),
        timestamp: '2026-01-01T00:00:02.000Z',
      },
      {
        type: 'assistant',
        message: {
          role: 'assistant',
          content: [{ type: 'text', text: 'No response requested.' }],
          model: '<synthetic>',
        },
        uuid: crypto.randomUUID(),
        timestamp: '2026-01-01T00:00:03.000Z',
      },
      {
        type: 'user',
        message: {
          role: 'user',
          content: '<command-name>/exit</command-name>\n<command-message>exit</command-message>\n<command-args></command-args>',
        },
        uuid: crypto.randomUUID(),
        timestamp: '2026-01-01T00:00:04.000Z',
      },
      makeAssistantEntry('正常助手消息', crypto.randomUUID()),
    ])

    const messages = await service.getSessionMessages(sessionId)

    expect(messages).toHaveLength(2)
    expect(messages[0]).toMatchObject({ type: 'user', content: '正常用户消息' })
    expect(messages[1]).toMatchObject({
      type: 'assistant',
      content: [{ type: 'text', text: '正常助手消息' }],
    })
  })

  it('should keep /goal local command transcript entries for desktop history restore', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      {
        parentUuid: null,
        isSidechain: false,
        type: 'system',
        subtype: 'local_command',
        content: '<command-name>/goal</command-name>\n<command-message>goal</command-message>\n<command-args>ship persisted goal</command-args>',
        level: 'info',
        timestamp: '2026-01-01T00:00:01.000Z',
        uuid: 'goal-command',
      },
      {
        parentUuid: 'goal-command',
        isSidechain: false,
        type: 'system',
        subtype: 'local_command',
        content: '<local-command-stdout>Goal set: ship persisted goal</local-command-stdout>',
        level: 'info',
        timestamp: '2026-01-01T00:00:02.000Z',
        uuid: 'goal-output',
      },
      makeAssistantEntry('正常助手消息', crypto.randomUUID()),
    ])

    const messages = await service.getSessionMessages(sessionId)

    expect(messages).toMatchObject([
      {
        id: 'goal-command',
        type: 'system',
        content: expect.stringContaining('<command-name>/goal</command-name>'),
      },
      {
        id: 'goal-output',
        type: 'system',
        content: expect.stringContaining('Goal set: ship persisted goal'),
      },
      {
        type: 'assistant',
      },
    ])
  })

  it('should hide task-notification turns and their automatic responses from history', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const firstUserId = crypto.randomUUID()
    const firstAssistantId = crypto.randomUUID()
    const taskNotificationId = crypto.randomUUID()
    const taskAssistantId = crypto.randomUUID()
    const taskToolUseMessageId = crypto.randomUUID()
    const taskToolResultId = crypto.randomUUID()
    const taskAfterToolId = crypto.randomUUID()
    const realFollowUpId = crypto.randomUUID()
    const realAssistantId = crypto.randomUUID()

    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      {
        ...makeUserEntry('创建一个项目', firstUserId),
        parentUuid: null,
      },
      {
        ...makeAssistantEntry('项目已经创建', firstUserId),
        uuid: firstAssistantId,
      },
      {
        ...makeUserEntry(
          '<task-notification>\n<task-id>bg-1</task-id>\n<tool-use-id>toolu_bg</tool-use-id>\n<status>completed</status>\n<summary>Background command completed</summary>\n</task-notification>',
          taskNotificationId,
        ),
        parentUuid: firstAssistantId,
      },
      {
        ...makeAssistantEntry('旧后台任务通知,无需处理', taskNotificationId),
        uuid: taskAssistantId,
      },
      {
        ...makeAssistantToolUseEntry([{
          id: 'toolu_restart',
          name: 'Bash',
          input: { command: 'npm run dev' },
        }], taskAssistantId),
        uuid: taskToolUseMessageId,
      },
      {
        type: 'user',
        message: {
          role: 'user',
          content: [{
            type: 'tool_result',
            tool_use_id: 'toolu_restart',
            content: 'server restarted',
          }],
        },
        uuid: taskToolResultId,
        parentUuid: taskToolUseMessageId,
        timestamp: '2026-01-01T00:03:00.000Z',
      },
      {
        ...makeAssistantEntry('后台任务触发的工具调用完成', taskToolResultId),
        uuid: taskAfterToolId,
      },
      {
        ...makeUserEntry('继续真实问题', realFollowUpId),
        parentUuid: taskAfterToolId,
      },
      {
        ...makeAssistantEntry('真实回答', realFollowUpId),
        uuid: realAssistantId,
      },
    ])

    const messages = await service.getSessionMessages(sessionId)
    const taskNotifications = await service.getSessionTaskNotifications(sessionId)

    expect(messages.map((message) => message.id)).toEqual([
      firstUserId,
      firstAssistantId,
      realFollowUpId,
      realAssistantId,
    ])
    expect(JSON.stringify(messages)).not.toContain('<task-notification>')
    expect(JSON.stringify(messages)).not.toContain('旧后台任务通知')
    expect(JSON.stringify(messages)).not.toContain('server restarted')
    expect(JSON.stringify(messages)).not.toContain('后台任务触发的工具调用完成')
    expect(taskNotifications).toEqual([
      {
        taskId: 'bg-1',
        toolUseId: 'toolu_bg',
        status: 'completed',
        summary: 'Background command completed',
        timestamp: '2026-01-01T00:01:00.000Z',
      },
    ])
  })

  it('should reconstruct parent agent tool linkage from parentUuid chains', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const userUuid = crypto.randomUUID()
    const agentAssistantUuid = crypto.randomUUID()
    const childAssistantUuid = crypto.randomUUID()

    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('Inspect the codebase', userUuid),
      {
        parentUuid: userUuid,
        isSidechain: false,
        type: 'assistant',
        message: {
          model: 'claude-opus-4-7',
          id: `msg_${crypto.randomUUID().slice(0, 20)}`,
          type: 'message',
          role: 'assistant',
          content: [
            {
              type: 'tool_use',
              name: 'Agent',
              id: 'agent-tool-1',
              input: { description: 'Inspect src/components' },
            },
          ],
        },
        uuid: agentAssistantUuid,
        timestamp: '2026-01-01T00:02:00.000Z',
      },
      {
        parentUuid: agentAssistantUuid,
        isSidechain: true,
        type: 'assistant',
        message: {
          model: 'claude-opus-4-7',
          id: `msg_${crypto.randomUUID().slice(0, 20)}`,
          type: 'message',
          role: 'assistant',
          content: [
            {
              type: 'tool_use',
              name: 'Read',
              id: 'read-tool-1',
              input: { file_path: 'src/components/App.tsx' },
            },
          ],
        },
        uuid: childAssistantUuid,
        timestamp: '2026-01-01T00:02:30.000Z',
      },
      {
        parentUuid: childAssistantUuid,
        isSidechain: true,
        type: 'user',
        message: {
          role: 'user',
          content: [
            {
              type: 'tool_result',
              tool_use_id: 'read-tool-1',
              content: 'ok',
              is_error: false,
            },
          ],
        },
        uuid: crypto.randomUUID(),
        timestamp: '2026-01-01T00:03:00.000Z',
        userType: 'external',
        cwd: '/tmp/test',
        sessionId: 'test-session',
      },
    ])

    const messages = await service.getSessionMessages(sessionId)

    expect(messages[1]).toMatchObject({
      type: 'tool_use',
      parentToolUseId: undefined,
    })
    expect(messages[2]).toMatchObject({
      type: 'tool_use',
      parentToolUseId: 'agent-tool-1',
    })
    expect(messages[3]).toMatchObject({
      type: 'tool_result',
      parentToolUseId: 'agent-tool-1',
    })
  })

  it('should recover workDir from session-meta entries', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry('/tmp/from-meta'),
      makeUserEntry('Hello'),
    ])

    const workDir = await service.getSessionWorkDir(sessionId)
    expect(workDir).toBe('/tmp/from-meta')
  })

  it('should recover workDir from the latest session-meta entry', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry('/tmp/old-worktree'),
      makeUserEntry('Hello'),
      makeSessionMetaEntry('/tmp/latest-worktree'),
    ])

    const workDir = await service.getSessionWorkDir(sessionId)
    expect(workDir).toBe('/tmp/latest-worktree')
  })

  it('should prefer the newest duplicate session file when worktree metadata moves', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const sourceFile = await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry('/tmp/project'),
    ])
    const worktreeFile = await writeSessionFile('-tmp-project--claude-worktrees-desktop-main-12345678', sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry('/tmp/project/.claude/worktrees/desktop-main-12345678'),
    ])

    const oldTime = new Date('2026-01-01T00:00:00.000Z')
    const newTime = new Date('2026-01-01T00:00:01.000Z')
    await fs.utimes(sourceFile, oldTime, oldTime)
    await fs.utimes(worktreeFile, newTime, newTime)

    const workDir = await service.getSessionWorkDir(sessionId)
    expect(workDir).toBe('/tmp/project/.claude/worktrees/desktop-main-12345678')
  })

  it('should recover CLI worktree state from transcript metadata', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project--claude-worktrees-desktop-main-12345678', sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry('/tmp/project/.claude/worktrees/desktop-main-12345678'),
      makeWorktreeStateEntry(sessionId, '/tmp/project/.claude/worktrees/desktop-main-12345678', {
        originalCwd: '/tmp/project',
      }),
      makeUserEntry('Hello from CLI worktree'),
    ])

    const launchInfo = await service.getSessionLaunchInfo(sessionId)
    expect(launchInfo?.worktreeSession).toMatchObject({
      originalCwd: '/tmp/project',
      worktreePath: '/tmp/project/.claude/worktrees/desktop-main-12345678',
      worktreeName: 'desktop-main-12345678',
      worktreeBranch: 'worktree-desktop-main-12345678',
      originalBranch: 'main',
    })
  })

  it('should preserve repository metadata when replacing placeholder transcripts', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const { sessionId, workDir: sessionWorkDir } = await service.createSession(
      workDir,
      { branch: 'feature/rail', worktree: true },
    )

    await service.clearSessionTranscript(sessionId, sessionWorkDir)
    const launchInfo = await service.getSessionLaunchInfo(sessionId)

    expect(launchInfo?.workDir).toBe(sessionWorkDir)
    expect(launchInfo?.repository).toMatchObject({
      requestedWorkDir: await fs.realpath(workDir),
      worktree: true,
      worktreePath: expect.stringContaining(path.join('.claude', 'worktrees', 'desktop-feature-rail-')),
    })
  })

  it('should remove stale placeholder files after native CLI worktree startup', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const sourceFile = await writeSessionFile('-tmp-source', sessionId, [
      makeSnapshotEntry(),
      { type: 'session-meta', isMeta: true, workDir: '/tmp/source', timestamp: '2026-01-01T00:00:00.000Z' },
      { type: 'session-meta', isMeta: true, workDir: '/tmp/source/.claude/worktrees/desktop-agent', timestamp: '2026-01-01T00:00:02.000Z' },
    ])
    const worktreeFile = await writeSessionFile('-tmp-source--claude-worktrees-desktop-agent', sessionId, [
      makeSnapshotEntry(),
      { type: 'session-meta', isMeta: true, workDir: '/tmp/source/.claude/worktrees/desktop-agent', timestamp: '2026-01-01T00:00:01.000Z' },
      makeUserEntry('Hello from worktree'),
    ])

    const removed = await service.deletePlaceholderSessionFiles(
      sessionId,
      '/tmp/source/.claude/worktrees/desktop-agent',
    )

    expect(removed).toBe(1)
    await expect(fs.access(sourceFile)).rejects.toThrow()
    await expect(fs.access(worktreeFile)).resolves.toBeNull()
  })

  it('should move repository metadata to the CLI worktree transcript before deleting placeholders', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const { sessionId } = await service.createSession(
      workDir,
      { branch: 'main', worktree: true },
    )
    const initialLaunchInfo = await service.getSessionLaunchInfo(sessionId)
    const worktreePath = initialLaunchInfo?.repository?.worktreePath
    expect(worktreePath).toBeTruthy()

    const worktreeFile = await writeSessionFile(sanitizePath(worktreePath!), sessionId, [
      makeSnapshotEntry(),
      {
        type: 'system',
        subtype: 'init',
        cwd: worktreePath,
        timestamp: '2026-01-01T00:00:01.000Z',
      },
      makeUserEntry('Hello from worktree'),
    ])

    await service.appendSessionMetadata(sessionId, {
      workDir: worktreePath!,
    })
    const removed = await service.deletePlaceholderSessionFiles(sessionId, worktreePath!)
    const launchInfo = await service.getSessionLaunchInfo(sessionId)

    expect(removed).toBe(1)
    await expect(fs.access(worktreeFile)).resolves.toBeNull()
    expect(launchInfo?.workDir).toBe(worktreePath)
    expect(launchInfo?.repository).toMatchObject({
      requestedWorkDir: await fs.realpath(workDir),
      branch: 'main',
      worktree: true,
      worktreePath,
      worktreeSlug: initialLaunchInfo?.repository?.worktreeSlug,
    })
  })

  it('should recover workDir from transcript cwd when session-meta is missing', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      {
        ...makeUserEntry('Hello'),
        cwd: '/tmp/from-cwd',
      },
    ])

    const workDir = await service.getSessionWorkDir(sessionId)
    expect(workDir).toBe('/tmp/from-cwd')
  })

  // --------------------------------------------------------------------------
  // createSession
  // --------------------------------------------------------------------------

  it('should create a new session file', async () => {
    const workDir = path.join(tmpDir, 'workspace', 'my-project')
    await fs.mkdir(workDir, { recursive: true })
    const { sessionId } = await service.createSession(workDir)
    expect(sessionId).toMatch(
      /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
    )

    // Verify the file was created
    const canonicalWorkDir = await fs.realpath(workDir)
    const sanitized = sanitizePath(canonicalWorkDir)
    const filePath = path.join(tmpDir, 'projects', sanitized, `${sessionId}.jsonl`)
    const stat = await fs.stat(filePath)
    expect(stat.isFile()).toBe(true)

    // Verify the file starts with the initial snapshot entry
    const content = await fs.readFile(filePath, 'utf-8')
    const entry = JSON.parse(content.trim().split('\n')[0]!)
    expect(entry.type).toBe('file-history-snapshot')
  })

  it('should defer isolated worktree creation until CLI startup', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const { sessionId, workDir: sessionWorkDir } = await service.createSession(
      workDir,
      { branch: 'feature/rail', worktree: true },
    )

    expect(sessionWorkDir).toBe(await fs.realpath(workDir))
    expect(git(workDir, 'branch', '--show-current')).toBe('main\n')
    expect(git(workDir, 'status', '--porcelain')).toBe('')

    const sanitized = sanitizePath(await fs.realpath(workDir))
    const filePath = path.join(tmpDir, 'projects', sanitized, `${sessionId}.jsonl`)
    const lines = (await fs.readFile(filePath, 'utf-8')).trim().split('\n')
    const metadata = JSON.parse(lines[1]!)
    const plannedWorktreePath = metadata.repository.worktreePath as string
    expect(metadata.workDir).toBe(await fs.realpath(workDir))
    expect(metadata.repository).toMatchObject({
      requestedWorkDir: await fs.realpath(workDir),
      branch: 'feature/rail',
      worktree: true,
      baseRef: 'feature/rail',
      worktreePath: expect.stringContaining(path.join('.claude', 'worktrees', 'desktop-feature-rail-')),
      worktreeBranch: expect.stringContaining('worktree-desktop-feature-rail-'),
      worktreeSlug: expect.stringContaining('desktop-feature-rail-'),
    })
    await expect(fs.access(plannedWorktreePath)).rejects.toThrow()

    const context = await getRepositoryContext(workDir)
    expect(context.state).toBe('ok')
    expect(context.branches.map((branch) => branch.name)).not.toContain(
      path.basename(plannedWorktreePath).replace(/^desktop-/, 'worktree-desktop-'),
    )
    expect(context.branches.some((branch) => branch.name.startsWith('worktree-desktop-'))).toBe(false)
  })

  it('should defer direct branch switching until CLI startup when worktree isolation is disabled', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const { sessionId, workDir: sessionWorkDir } = await service.createSession(
      workDir,
      { branch: 'feature/rail', worktree: false },
    )

    expect(sessionWorkDir).toBe(await fs.realpath(workDir))
    expect(git(workDir, 'branch', '--show-current')).toBe('main\n')

    const sanitized = sanitizePath(await fs.realpath(workDir))
    const filePath = path.join(tmpDir, 'projects', sanitized, `${sessionId}.jsonl`)
    const lines = (await fs.readFile(filePath, 'utf-8')).trim().split('\n')
    const metadata = JSON.parse(lines[1]!)
    expect(metadata.workDir).toBe(await fs.realpath(workDir))
    expect(metadata.repository).toMatchObject({
      requestedWorkDir: await fs.realpath(workDir),
      branch: 'feature/rail',
      worktree: false,
      baseRef: 'feature/rail',
    })
  })

  it('should not list hidden desktop worktree branches', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const existingWorktree = path.join(tmpDir, `desktop-hidden-${Date.now()}`)
    git(workDir, 'worktree', 'add', '-b', 'worktree-desktop-hidden', existingWorktree, 'feature/rail')

    expect(git(existingWorktree, 'branch', '--show-current')).toBe('worktree-desktop-hidden\n')

    const context = await getRepositoryContext(existingWorktree)
    expect(context.state).toBe('ok')
    expect(context.currentBranch).toBe('worktree-desktop-hidden')
    expect(context.branches.some((branch) => branch.name === context.currentBranch)).toBe(false)
    expect(context.branches.some((branch) => branch.name.startsWith('worktree-desktop-'))).toBe(false)
  })

  it('should keep stale worktree records when their paths cannot be resolved', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const staleWorktreeName = `stale-worktree-${Date.now()}`
    const staleWorktree = path.join(tmpDir, staleWorktreeName)
    git(workDir, 'worktree', 'add', '-b', 'stale-worktree', staleWorktree, 'feature/rail')
    await fs.rm(staleWorktree, { recursive: true, force: true })

    const context = await getRepositoryContext(workDir)
    const expectedPath = path.join(await fs.realpath(tmpDir), staleWorktreeName).normalize('NFC')
    expect(context.state).toBe('ok')
    expect(context.worktrees.some((worktree) => (
      worktree.path === expectedPath && worktree.branch === 'stale-worktree' && !worktree.current
    ))).toBe(true)
  })

  it('should let git carry compatible dirty changes during direct branch launch', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    await fs.writeFile(path.join(workDir, 'README.md'), 'main\nlocal-pricing-edit\n')

    const { sessionId } = await service.createSession(
      workDir,
      { branch: 'feature/rail', worktree: false },
    )

    expect(git(workDir, 'branch', '--show-current')).toBe('main\n')
    expect(await fs.readFile(path.join(workDir, 'README.md'), 'utf-8'))
      .toContain('local-pricing-edit')
    const prepared = await prepareSessionWorkspace(
      workDir,
      { branch: 'feature/rail', worktree: false },
      sessionId,
    )

    expect(prepared.workDir).toBe(await fs.realpath(workDir))
    expect(git(workDir, 'branch', '--show-current')).toBe('feature/rail\n')
    expect(await fs.readFile(path.join(workDir, 'README.md'), 'utf-8'))
      .toContain('local-pricing-edit')
  })

  it('should plan isolated worktrees from dirty source checkouts without switching branches', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    await fs.writeFile(path.join(workDir, 'README.md'), 'main\nlocal-pricing-edit\n')

    const { sessionId } = await service.createSession(
      workDir,
      { branch: 'feature/rail', worktree: true },
    )
    const launchInfo = await service.getSessionLaunchInfo(sessionId)

    expect(launchInfo?.repository).toMatchObject({
      branch: 'feature/rail',
      worktree: true,
      baseRef: 'feature/rail',
    })
    expect(git(workDir, 'branch', '--show-current')).toBe('main\n')
    expect(await fs.readFile(path.join(workDir, 'README.md'), 'utf-8'))
      .toContain('local-pricing-edit')
  })

  it('should defer checked-out direct branch launch validation until CLI startup', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const existingWorktree = path.join(tmpDir, `existing-feature-rail-${Date.now()}`)
    git(workDir, 'worktree', 'add', existingWorktree, 'feature/rail')

    const { sessionId } = await service.createSession(
      workDir,
      { branch: 'feature/rail', worktree: false },
    )

    expect(git(workDir, 'branch', '--show-current')).toBe('main\n')
    await expect(prepareSessionWorkspace(
      workDir,
      { branch: 'feature/rail', worktree: false },
      sessionId,
    )).rejects.toMatchObject({ code: 'REPOSITORY_BRANCH_CHECKED_OUT' })
  })

  it('should reject branch launch outside Git repositories with a stable error code', async () => {
    const workDir = path.join(tmpDir, `not-git-${Date.now()}`)
    await fs.mkdir(workDir, { recursive: true })

    await expect(service.createSession(
      workDir,
      { branch: 'main', worktree: false },
    )).rejects.toMatchObject({ code: 'REPOSITORY_NOT_GIT' })
  })

  it('should reject missing selected branches with a stable error code', async () => {
    const workDir = await createCleanGitRepo(tmpDir)

    await expect(service.createSession(
      workDir,
      { branch: 'missing/branch', worktree: true },
    )).rejects.toMatchObject({ code: 'REPOSITORY_BRANCH_NOT_FOUND' })
  })

  it('should create a Windows-safe project directory name', async () => {
    if (process.platform !== 'win32') return

    const workDir = process.cwd()
    const { sessionId } = await service.createSession(workDir)
    const sanitized = sanitizePath(workDir)
    const projectDir = path.join(tmpDir, 'projects', sanitized)

    expect(sanitized.includes(':')).toBe(false)
    const stat = await fs.stat(path.join(projectDir, `${sessionId}.jsonl`))
    expect(stat.isFile()).toBe(true)
  })

  it('should default to the user home directory when workDir is missing', async () => {
    const { sessionId } = await service.createSession('')
    const filePath = path.join(
      tmpDir,
      'projects',
      sanitizePath(os.homedir()),
      `${sessionId}.jsonl`,
    )

    const stat = await fs.stat(filePath)
    expect(stat.isFile()).toBe(true)
  })

  it('should throw when workDir does not exist', async () => {
    expect(service.createSession('/tmp/definitely-missing-claude-code-haha')).rejects.toThrow(
      'Working directory does not exist'
    )
  })

  // --------------------------------------------------------------------------
  // deleteSession
  // --------------------------------------------------------------------------

  it('should delete an existing session', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const filePath = await writeSessionFile('-tmp-project', sessionId, [makeSnapshotEntry()])

    await service.deleteSession(sessionId)

    // File should no longer exist
    expect(fs.access(filePath)).rejects.toThrow()
  })

  it('should throw when deleting non-existent session', async () => {
    expect(
      service.deleteSession('00000000-0000-0000-0000-000000000000')
    ).rejects.toThrow('Session not found')
  })

  // --------------------------------------------------------------------------
  // renameSession
  // --------------------------------------------------------------------------

  it('should rename a session by appending custom-title entry', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const filePath = await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('Original message'),
    ])

    await service.renameSession(sessionId, 'My Custom Title')

    // Read the file and check the last entry
    const content = await fs.readFile(filePath, 'utf-8')
    const lines = content.trim().split('\n')
    const lastEntry = JSON.parse(lines[lines.length - 1]!)
    expect(lastEntry.type).toBe('custom-title')
    expect(lastEntry.customTitle).toBe('My Custom Title')

    // Verify the title is now returned in list
    const detail = await service.getSession(sessionId)
    expect(detail!.title).toBe('My Custom Title')
  })

  it('should throw when renaming non-existent session', async () => {
    expect(
      service.renameSession('00000000-0000-0000-0000-000000000000', 'Title')
    ).rejects.toThrow('Session not found')
  })

  // --------------------------------------------------------------------------
  // Title extraction
  // --------------------------------------------------------------------------

  it('should use first user message as title when no custom title', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeMetaUserEntry(),
      makeUserEntry('This is my first real question'),
    ])

    const detail = await service.getSession(sessionId)
    expect(detail!.title).toBe('This is my first real question')
  })

  it('should derive a clean title from slash command breadcrumb metadata', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry([
        '<command-message>frontend-design</command-message>',
        '<command-name>/frontend-design</command-name>',
        '<command-args>@website 重新设计首页</command-args>',
      ].join('\n')),
    ])

    const detail = await service.getSession(sessionId)
    expect(detail!.title).toBe('/frontend-design @website 重新设计首页')
  })

  it('should keep a goal creation title instead of later goal status titles', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      {
        parentUuid: null,
        isSidechain: false,
        type: 'system',
        subtype: 'local_command',
        content: '<command-name>/goal</command-name>\n<command-message>goal</command-message>\n<command-args>ship the actual objective</command-args>',
        level: 'info',
        timestamp: '2026-01-01T00:00:01.000Z',
        uuid: 'goal-command',
      },
      {
        type: 'ai-title',
        aiTitle: '/goal status',
        timestamp: '2026-01-01T00:02:00.000Z',
      },
    ])

    const detail = await service.getSession(sessionId)
    expect(detail!.title).toBe('/goal ship the actual objective')
  })

  it('should display stored AI titles without internal XML tags', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('fallback message'),
      {
        type: 'ai-title',
        aiTitle: [
          '<command-message>frontend-design</command-message>',
          '<command-name>/frontend-design</command-name>',
          '<command-args>@website</command-args>',
        ].join(' '),
        timestamp: '2026-01-01T00:02:00.000Z',
      },
    ])

    const detail = await service.getSession(sessionId)
    expect(detail!.title).toBe('/frontend-design @website')
  })

  it('should truncate long titles to 80 chars', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const longMessage = 'A'.repeat(120)
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry(longMessage),
    ])

    const detail = await service.getSession(sessionId)
    expect(detail!.title.length).toBe(83) // 80 + '...'
    expect(detail!.title.endsWith('...')).toBe(true)
  })

  it('should fall back to "Untitled Session" when no user message', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-project', sessionId, [makeSnapshotEntry()])

    const detail = await service.getSession(sessionId)
    expect(detail!.title).toBe('Untitled Session')
  })

  it('should detect placeholder launch info for desktop-created sessions', async () => {
    const workDir = await fs.realpath(os.tmpdir())
    const { sessionId } = await service.createSession(workDir)

    const launchInfo = await service.getSessionLaunchInfo(sessionId)
    expect(launchInfo).not.toBeNull()
    expect(launchInfo!.workDir).toBe(workDir)
    expect(launchInfo!.transcriptMessageCount).toBe(0)
    expect(launchInfo!.customTitle).toBeNull()
  })

  it('should detect resumable launch info for transcript sessions', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const userUuid = crypto.randomUUID()
    await writeSessionFile('-tmp-project', sessionId, [
      makeSnapshotEntry(),
      { type: 'session-meta', isMeta: true, workDir: '/tmp/project', timestamp: '2026-01-01T00:00:00.000Z' },
      makeUserEntry('Hello again', userUuid),
      makeAssistantEntry('Welcome back', userUuid),
      { type: 'custom-title', customTitle: 'Saved chat', timestamp: '2026-01-01T00:03:00.000Z' },
    ])

    const launchInfo = await service.getSessionLaunchInfo(sessionId)
    expect(launchInfo).not.toBeNull()
    expect(launchInfo!.workDir).toBe('/tmp/project')
    expect(launchInfo!.transcriptMessageCount).toBe(2)
    expect(launchInfo!.customTitle).toBe('Saved chat')
  })

  it('should recover Windows drive paths from sanitized project dirs for old transcripts without metadata', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-ffffffffffff'
    const userUuid = crypto.randomUUID()
    const userEntry = makeUserEntry('Resume this Windows session', userUuid)
    delete userEntry.cwd
    await writeSessionFile('g--AI-NTos-NT-deepseek-nano-core', sessionId, [
      makeSnapshotEntry(),
      userEntry,
      makeAssistantEntry('Welcome back', userUuid),
    ])

    const expectedWorkDir = 'g:\\AI\\NTos\\NT\\deepseek\\nano\\core'
    expect(await service.getSessionWorkDir(sessionId)).toBe(expectedWorkDir)

    const launchInfo = await service.getSessionLaunchInfo(sessionId)
    expect(launchInfo).not.toBeNull()
    expect(launchInfo!.workDir).toBe(expectedWorkDir)
    expect(launchInfo!.transcriptMessageCount).toBe(2)
  })

  it('createSessionBranch should preserve branch metadata, copied snapshots, and filtered replacements', async () => {
    const sessionId = 'branch-source-session'
    const workDir = path.join(tmpDir, 'branch-source')
    const worktreePath = path.join(workDir, '.claude', 'worktrees', 'desktop-main-12345678')
    const firstUserId = crypto.randomUUID()
    const firstAssistantId = crypto.randomUUID()
    const firstToolResultId = crypto.randomUUID()
    const laterUserId = crypto.randomUUID()
    const laterAssistantId = crypto.randomUUID()
    const repository = {
      branch: 'feature/rail',
      worktree: true,
      baseRef: 'feature/rail',
      repoRoot: workDir,
    }
    const sourceProjectDir = sanitizePath(workDir)
    const sourcePath = await writeSessionFile(sourceProjectDir, sessionId, [
      makeSessionMetaEntry(workDir),
      {
        type: 'session-meta',
        isMeta: true,
        workDir,
        repository,
        timestamp: '2026-01-01T00:00:00.000Z',
      },
      makeWorktreeStateEntry(sessionId, worktreePath, {
        originalCwd: workDir,
      }),
      makeFileHistorySnapshotEntry(firstUserId, {
        'src/step.js': {
          backupFileName: 'branch-source-step@v1',
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('branch this conversation', firstUserId),
        cwd: workDir,
        sessionId,
      },
      {
        ...makeAssistantToolUseEntry([
          { id: 'tool-1', name: 'Read', input: { path: 'src/step.js' } },
        ], firstUserId),
        uuid: firstAssistantId,
        cwd: workDir,
        sessionId,
      },
      {
        ...makeToolResultUserEntry('tool-1', 'first tool result', firstToolResultId, firstAssistantId, sessionId),
        cwd: workDir,
      },
      makeContentReplacementEntry(sessionId, [
        { kind: 'tool-result', toolUseId: 'tool-1', replacement: 'preview-1' },
        { kind: 'tool-result', toolUseId: 'tool-2', replacement: 'preview-2' },
      ]),
      makeFileHistorySnapshotEntry(laterUserId, {
        'src/step.js': {
          backupFileName: 'branch-source-step@v2',
          version: 2,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('later prompt', laterUserId),
        parentUuid: firstToolResultId,
        cwd: workDir,
        sessionId,
      },
      {
        ...makeAssistantEntry('later reply', laterUserId),
        uuid: laterAssistantId,
        cwd: workDir,
        sessionId,
      },
    ])

    const sourceBefore = await fs.readFile(sourcePath, 'utf-8')

    const branch = await createSessionBranch({
      sourceSessionId: sessionId,
      sourceTranscriptPath: sourcePath,
      targetMessageId: firstToolResultId,
      title: 'Desktop branch',
      sourceWorkDir: workDir,
      sourceRepository: repository,
      sourceWorktreeSession: {
        originalCwd: workDir,
        worktreePath,
        worktreeName: 'desktop-main-12345678',
        worktreeBranch: 'worktree-desktop-main-12345678',
        originalBranch: 'main',
        sessionId,
      },
    })

    const branchMessages = await service.getSessionMessages(branch.sessionId)
    expect(branchMessages.map((message) => message.id)).toEqual([
      firstUserId,
      firstAssistantId,
      firstToolResultId,
    ])
    expect(branch.title).toBe('Desktop branch (Branch)')

    const launchInfo = await service.getSessionLaunchInfo(branch.sessionId)
    expect(launchInfo).toMatchObject({
      workDir,
      repository,
      worktreeSession: {
        originalCwd: workDir,
        worktreePath,
      },
    })

    const branchEntries = parseJSONL<Record<string, unknown>>(await fs.readFile(branch.forkPath))
    expect(branchEntries.some((entry) => (
      entry.type === 'content-replacement' &&
      entry.sessionId === branch.sessionId &&
      Array.isArray(entry.replacements) &&
      entry.replacements.length === 1 &&
      (entry.replacements[0] as { toolUseId?: string }).toolUseId === 'tool-1'
    ))).toBe(true)
    expect(branchEntries.some((entry) => (
      entry.type === 'file-history-snapshot' &&
      typeof (entry.snapshot as { messageId?: string } | undefined)?.messageId === 'string' &&
      (entry.snapshot as { messageId?: string }).messageId === firstUserId
    ))).toBe(true)
    expect(branchEntries.some((entry) => (
      entry.type === 'file-history-snapshot' &&
      typeof (entry.snapshot as { messageId?: string } | undefined)?.messageId === 'string' &&
      (entry.snapshot as { messageId?: string }).messageId === laterUserId
    ))).toBe(false)
    expect(branchEntries.some((entry) => (
      entry.type === 'custom-title' &&
      entry.customTitle === 'Desktop branch (Branch)'
    ))).toBe(true)
    expect(branchEntries.filter((entry) => (
      entry.type === 'user' ||
      entry.type === 'assistant'
    )).every((entry) => (
      entry.sessionId === branch.sessionId &&
      typeof (entry.forkedFrom as { sessionId?: string } | undefined)?.sessionId === 'string'
    ))).toBe(true)

    const sourceAfter = await fs.readFile(sourcePath, 'utf-8')
    expect(sourceAfter).toBe(sourceBefore)
  })
})

// ============================================================================
// Sessions API integration tests
// ============================================================================

describe('Sessions API', () => {
  let baseUrl: string
  let server: ReturnType<typeof Bun.serve> | null = null

  beforeEach(async () => {
    await setupTmpConfigDir()
    service = new SessionService()

    // Import and start a minimal test server
    const { handleSessionsApi } = await import('../api/sessions.js')
    const { handleConversationsApi } = await import('../api/conversations.js')

    server = Bun.serve({
      port: 0,
      hostname: '127.0.0.1',

      async fetch(req) {
        const url = new URL(req.url)
        const segments = url.pathname.split('/').filter(Boolean)

        if (segments[0] === 'api' && segments[1] === 'sessions') {
          // Route chat sub-resource to conversations handler
          if (segments[3] === 'chat') {
            return handleConversationsApi(req, url, segments)
          }
          return handleSessionsApi(req, url, segments)
        }

        return new Response('Not Found', { status: 404 })
      },
    })
    baseUrl = `http://127.0.0.1:${server.port}`
  })

  afterEach(async () => {
    if (server) {
      server.stop(true)
      server = null
    }
    clearInstalledPluginsCache()
    clearPluginCache('sessions-api-test-teardown')
    resetSettingsCache()
    await cleanupTmpDir()
  })

  it('GET /api/sessions should return empty list', async () => {
    const res = await fetch(`${baseUrl}/api/sessions`)
    expect(res.status).toBe(200)

    const body = (await res.json()) as { sessions: unknown[]; total: number }
    expect(body.sessions).toEqual([])
    expect(body.total).toBe(0)
  })

  it('POST /api/sessions should create a session', async () => {
    const workDir = await fs.mkdtemp(path.join(tmpDir, 'api-session-'))
    const res = await fetch(`${baseUrl}/api/sessions`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ workDir }),
    })
    expect(res.status).toBe(201)

    const body = (await res.json()) as { sessionId: string }
    expect(body.sessionId).toMatch(
      /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
    )
  })

  it('POST /api/sessions should create a session when workDir is omitted', async () => {
    const res = await fetch(`${baseUrl}/api/sessions`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({}),
    })
    expect(res.status).toBe(201)

    const body = (await res.json()) as { sessionId: string }
    expect(body.sessionId).toMatch(
      /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
    )
  })

  it('GET /api/sessions/repository-context should return branch launch metadata', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const res = await fetch(
      `${baseUrl}/api/sessions/repository-context?workDir=${encodeURIComponent(workDir)}`,
    )
    expect(res.status).toBe(200)

    const body = (await res.json()) as {
      state: string
      repoName: string
      currentBranch: string
      branches: Array<{ name: string; current: boolean; local: boolean }>
      worktrees: Array<{ path: string; branch: string | null; current: boolean }>
    }
    expect(body.state).toBe('ok')
    expect(body.repoName).toBe(path.basename(workDir))
    expect(body.currentBranch).toBe('main')
    expect(body.branches.some((branch) => branch.name === 'main' && branch.current)).toBe(true)
    expect(body.branches.some((branch) => branch.name === 'feature/rail' && branch.local)).toBe(true)
    const realWorkDir = await fs.realpath(workDir)
    expect(body.worktrees.some((worktree) => worktree.path === realWorkDir && worktree.current)).toBe(true)
  })

  it('GET /api/sessions/recent-projects should keep pending repository launches on the source project', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const createRes = await fetch(`${baseUrl}/api/sessions`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        workDir,
        repository: { branch: 'feature/rail', worktree: true },
      }),
    })
    expect(createRes.status).toBe(201)

    const created = (await createRes.json()) as { workDir: string }
    const recentRes = await fetch(`${baseUrl}/api/sessions/recent-projects?limit=20`)
    expect(recentRes.status).toBe(200)

    const body = (await recentRes.json()) as {
      projects: Array<{ realPath: string; projectName: string; branch: string | null }>
    }
    const project = body.projects.find((candidate) => candidate.realPath === created.workDir)
    expect(project).toBeDefined()
    expect(project?.projectName).toBe(path.basename(workDir))
    expect(project?.branch).toBe('main')
    expect(project?.realPath).toBe(await fs.realpath(workDir))
  })

  it('GET /api/sessions/:id should return session detail', async () => {
    // Create a session file
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-api-test', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('API test message'),
      makeAssistantEntry('API test response'),
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}`)
    expect(res.status).toBe(200)

    const body = (await res.json()) as { id: string; title: string; messages: unknown[] }
    expect(body.id).toBe(sessionId)
    expect(body.title).toBe('API test message')
    expect(body.messages).toHaveLength(2)
  })

  it('GET /api/sessions/:id should 404 for unknown session', async () => {
    const res = await fetch(`${baseUrl}/api/sessions/00000000-0000-0000-0000-000000000000`)
    expect(res.status).toBe(404)
  })

  it('GET /api/sessions/:id/messages should return messages', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-api-test', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('Hello'),
      makeAssistantEntry('World'),
      makeUserEntry(
        '<task-notification>\n<task-id>bg-1</task-id>\n<tool-use-id>toolu_bg</tool-use-id>\n<status>failed</status>\n<summary>Background command failed &amp; stopped</summary>\n<result>Stack trace &amp; failed assertion</result>\n<output-file>C:\\Temp\\bg.output</output-file>\n</task-notification>',
        crypto.randomUUID(),
      ),
      makeAssistantEntry('internal task response'),
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/messages`)
    expect(res.status).toBe(200)

    const body = (await res.json()) as {
      messages: unknown[]
      taskNotifications: unknown[]
    }
    expect(body.messages).toHaveLength(2)
    expect(JSON.stringify(body.messages)).not.toContain('<task-notification>')
    expect(body.taskNotifications).toEqual([
      {
        taskId: 'bg-1',
        toolUseId: 'toolu_bg',
        status: 'failed',
        summary: 'Background command failed & stopped',
        result: 'Stack trace & failed assertion',
        outputFile: 'C:\\Temp\\bg.output',
        timestamp: expect.any(String),
      },
    ])
  })

  it('GET /api/sessions/:id/git-info should prefer the active CLI workDir', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const activeWorktree = path.join(tmpDir, `active-feature-rail-${Date.now()}`)
    git(workDir, 'worktree', 'add', activeWorktree, 'feature/rail')
    const { sessionId } = await sessionService.createSession(workDir)
    const sessionsMap = (conversationService as any).sessions as Map<string, { workDir: string }>

    sessionsMap.set(sessionId, { workDir: activeWorktree })
    try {
      const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/git-info`)
      expect(res.status).toBe(200)

      const body = (await res.json()) as { branch: string | null; workDir: string }
      expect(body.workDir).toBe(activeWorktree)
      expect(body.branch).toBe('feature/rail')
    } finally {
      sessionsMap.delete(sessionId)
    }
  })

  it('GET /api/sessions/:id/git-info should keep the session launch branch stable', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const { sessionId } = await sessionService.createSession(
      workDir,
      { branch: 'feature/rail', worktree: false },
    )
    const sessionsMap = (conversationService as any).sessions as Map<string, { workDir: string }>

    sessionsMap.set(sessionId, { workDir })
    git(workDir, 'switch', 'main')
    try {
      const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/git-info`)
      expect(res.status).toBe(200)

      const body = (await res.json()) as { branch: string | null; workDir: string }
      expect(body.workDir).toBe(workDir)
      expect(body.branch).toBe('feature/rail')
    } finally {
      sessionsMap.delete(sessionId)
    }
  })

  it('GET /api/sessions/:id/git-info should include isolated worktree identity', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const { sessionId } = await sessionService.createSession(
      workDir,
      { branch: 'main', worktree: true },
    )
    const launchInfo = await sessionService.getSessionLaunchInfo(sessionId)
    const repository = launchInfo?.repository
    expect(repository?.worktreePath).toBeTruthy()
    expect(repository?.worktreeBranch).toBeTruthy()

    const activeWorktree = repository!.worktreePath!
    git(workDir, 'worktree', 'add', '-b', repository!.worktreeBranch!, activeWorktree, 'main')
    const sessionsMap = (conversationService as any).sessions as Map<string, { workDir: string }>

    sessionsMap.set(sessionId, { workDir: activeWorktree })
    try {
      const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/git-info`)
      expect(res.status).toBe(200)

      const body = (await res.json()) as {
        branch: string | null
        workDir: string
        worktree: {
          enabled: boolean
          path: string | null
          plannedPath: string | null
          sourceWorkDir: string | null
          slug: string | null
          branch: string | null
        } | null
      }
      expect(body.branch).toBe(repository!.worktreeBranch)
      expect(body.workDir).toBe(activeWorktree)
      expect(body.worktree).toEqual({
        enabled: true,
        path: activeWorktree,
        plannedPath: activeWorktree,
        sourceWorkDir: repository!.requestedWorkDir,
        slug: repository!.worktreeSlug,
        branch: repository!.worktreeBranch,
      })
    } finally {
      sessionsMap.delete(sessionId)
    }
  })

  it('GET /api/sessions/:id/git-info should use CLI worktree-state after reload', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const activeWorktree = path.join(workDir, '.claude', 'worktrees', 'desktop-main-12345678')
    git(workDir, 'worktree', 'add', '-b', 'worktree-desktop-main-12345678', activeWorktree, 'main')
    await writeSessionFile(sanitizePath(activeWorktree), sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry(activeWorktree),
      makeWorktreeStateEntry(sessionId, activeWorktree, {
        originalCwd: await fs.realpath(workDir),
      }),
      makeUserEntry('Hello from persisted worktree state'),
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/git-info`)
    expect(res.status).toBe(200)

    const body = (await res.json()) as {
      branch: string | null
      repoName: string | null
      workDir: string
      worktree: {
        enabled: boolean
        path: string | null
        plannedPath: string | null
        sourceWorkDir: string | null
        slug: string | null
        branch: string | null
      } | null
    }
    expect(body.branch).toBe('worktree-desktop-main-12345678')
    expect(body.workDir).toBe(activeWorktree)
    expect(body.worktree).toEqual({
      enabled: true,
      path: activeWorktree,
      plannedPath: activeWorktree,
      sourceWorkDir: await fs.realpath(workDir),
      slug: 'desktop-main-12345678',
      branch: 'worktree-desktop-main-12345678',
    })
  })

  it('GET /api/sessions/:id/git-info should prefer CLI worktree-state identity over desktop metadata', async () => {
    const workDir = await createCleanGitRepo(tmpDir)
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const activeWorktree = path.join(workDir, '.claude', 'worktrees', 'desktop-main-12345678')
    git(workDir, 'worktree', 'add', '-b', 'worktree-desktop-main-12345678', activeWorktree, 'main')
    await writeSessionFile(sanitizePath(activeWorktree), sessionId, [
      makeSnapshotEntry(),
      {
        type: 'session-meta',
        isMeta: true,
        workDir: activeWorktree,
        repository: {
          requestedWorkDir: '/stale/source',
          repoRoot: '/stale/source',
          branch: 'main',
          worktree: true,
          baseRef: 'main',
          worktreePath: '/stale/source/.claude/worktrees/stale',
          worktreeBranch: 'worktree-stale',
          worktreeSlug: 'stale',
        },
        timestamp: '2026-01-01T00:00:00.000Z',
      },
      makeWorktreeStateEntry(sessionId, activeWorktree, {
        originalCwd: await fs.realpath(workDir),
      }),
      makeUserEntry('Hello from persisted worktree state'),
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/git-info`)
    expect(res.status).toBe(200)

    const body = (await res.json()) as {
      branch: string | null
      worktree: {
        path: string | null
        plannedPath: string | null
        sourceWorkDir: string | null
        slug: string | null
        branch: string | null
      } | null
    }
    expect(body.branch).toBe('worktree-desktop-main-12345678')
    expect(body.worktree).toMatchObject({
      path: activeWorktree,
      plannedPath: activeWorktree,
      sourceWorkDir: await fs.realpath(workDir),
      slug: 'desktop-main-12345678',
      branch: 'worktree-desktop-main-12345678',
    })
  })

  it('DELETE /api/sessions/:id should delete the session', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-api-test', sessionId, [makeSnapshotEntry()])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}`, { method: 'DELETE' })
    expect(res.status).toBe(200)

    // Verify it's gone
    const res2 = await fetch(`${baseUrl}/api/sessions/${sessionId}`)
    expect(res2.status).toBe(404)
  })

  it('DELETE /api/sessions/:id should remove matching IM adapter session mappings', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const otherSessionId = 'ffffffff-1111-2222-3333-ffffffffffff'
    await writeSessionFile('-tmp-api-test', sessionId, [makeSnapshotEntry()])
    await fs.writeFile(
      path.join(tmpDir, 'adapter-sessions.json'),
      JSON.stringify({
        'wechat-chat': {
          sessionId,
          workDir: '/tmp/project-a',
          updatedAt: 1,
        },
        'wechat-chat-2': {
          sessionId,
          workDir: '/tmp/project-b',
          updatedAt: 2,
        },
        'other-chat': {
          sessionId: otherSessionId,
          workDir: '/tmp/project-c',
          updatedAt: 3,
        },
      }, null, 2),
      'utf-8',
    )

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}`, { method: 'DELETE' })
    expect(res.status).toBe(200)

    const persisted = JSON.parse(
      await fs.readFile(path.join(tmpDir, 'adapter-sessions.json'), 'utf-8'),
    )
    expect(persisted['wechat-chat']).toBeUndefined()
    expect(persisted['wechat-chat-2']).toBeUndefined()
    expect(persisted['other-chat'].sessionId).toBe(otherSessionId)
  })

  it('DELETE /api/sessions/:id should roll back the deleted marker when file deletion fails', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-api-test', sessionId, [makeSnapshotEntry()])

    const originalDeleteSession = sessionService.deleteSession.bind(sessionService)
    sessionService.deleteSession = (async (targetSessionId: string) => {
      if (targetSessionId === sessionId) {
        throw new Error('simulated unlink failure')
      }
      return originalDeleteSession(targetSessionId)
    }) as typeof sessionService.deleteSession

    try {
      const res = await fetch(`${baseUrl}/api/sessions/${sessionId}`, { method: 'DELETE' })
      expect(res.status).toBe(500)
      expect((conversationService as any).deletedSessions.has(sessionId)).toBe(false)

      const detailRes = await fetch(`${baseUrl}/api/sessions/${sessionId}`)
      expect(detailRes.status).toBe(200)
    } finally {
      sessionService.deleteSession = originalDeleteSession as typeof sessionService.deleteSession
      conversationService.unmarkSessionDeleted(sessionId)
    }
  })

  it('POST /api/sessions/batch-delete should delete sessions and clean adapter mappings', async () => {
    const sessionIdA = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const sessionIdB = 'ffffffff-1111-2222-3333-ffffffffffff'
    const otherSessionId = '99999999-1111-2222-3333-999999999999'
    await writeSessionFile('-tmp-api-test', sessionIdA, [makeSnapshotEntry()])
    await writeSessionFile('-tmp-api-test', sessionIdB, [makeSnapshotEntry()])
    await fs.writeFile(
      path.join(tmpDir, 'adapter-sessions.json'),
      JSON.stringify({
        'wechat-chat-a': {
          sessionId: sessionIdA,
          workDir: '/tmp/project-a',
          updatedAt: 1,
        },
        'wechat-chat-b': {
          sessionId: sessionIdB,
          workDir: '/tmp/project-b',
          updatedAt: 2,
        },
        'other-chat': {
          sessionId: otherSessionId,
          workDir: '/tmp/project-c',
          updatedAt: 3,
        },
      }, null, 2),
      'utf-8',
    )

    const res = await fetch(`${baseUrl}/api/sessions/batch-delete`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ sessionIds: [sessionIdA, sessionIdB] }),
    })

    expect(res.status).toBe(200)
    expect(await res.json()).toEqual({
      ok: true,
      successes: [sessionIdA, sessionIdB],
      failures: [],
    })

    expect((await fetch(`${baseUrl}/api/sessions/${sessionIdA}`)).status).toBe(404)
    expect((await fetch(`${baseUrl}/api/sessions/${sessionIdB}`)).status).toBe(404)
    const persisted = JSON.parse(
      await fs.readFile(path.join(tmpDir, 'adapter-sessions.json'), 'utf-8'),
    )
    expect(persisted['wechat-chat-a']).toBeUndefined()
    expect(persisted['wechat-chat-b']).toBeUndefined()
    expect(persisted['other-chat'].sessionId).toBe(otherSessionId)
  })

  it('POST /api/sessions/batch-delete should report partial failures and roll back failed delete markers', async () => {
    const successSessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const failedSessionId = 'ffffffff-1111-2222-3333-ffffffffffff'
    await writeSessionFile('-tmp-api-test', successSessionId, [makeSnapshotEntry()])
    await writeSessionFile('-tmp-api-test', failedSessionId, [makeSnapshotEntry()])

    const originalDeleteSession = sessionService.deleteSession.bind(sessionService)
    sessionService.deleteSession = (async (targetSessionId: string) => {
      if (targetSessionId === failedSessionId) {
        throw new Error('simulated batch unlink failure')
      }
      return originalDeleteSession(targetSessionId)
    }) as typeof sessionService.deleteSession

    try {
      const res = await fetch(`${baseUrl}/api/sessions/batch-delete`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sessionIds: [successSessionId, failedSessionId] }),
      })

      expect(res.status).toBe(200)
      expect(await res.json()).toEqual({
        ok: false,
        successes: [successSessionId],
        failures: [{
          sessionId: failedSessionId,
          message: 'simulated batch unlink failure',
        }],
      })
      expect((conversationService as any).deletedSessions.has(failedSessionId)).toBe(false)
      expect((await fetch(`${baseUrl}/api/sessions/${successSessionId}`)).status).toBe(404)
      expect((await fetch(`${baseUrl}/api/sessions/${failedSessionId}`)).status).toBe(200)
    } finally {
      sessionService.deleteSession = originalDeleteSession as typeof sessionService.deleteSession
      conversationService.unmarkSessionDeleted(successSessionId)
      conversationService.unmarkSessionDeleted(failedSessionId)
    }
  })

  it('PATCH /api/sessions/:id should rename the session', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-api-test', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('Old title message'),
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title: 'New Custom Title' }),
    })
    expect(res.status).toBe(200)

    // Verify new title
    const detailRes = await fetch(`${baseUrl}/api/sessions/${sessionId}`)
    const detail = (await detailRes.json()) as { title: string }
    expect(detail.title).toBe('New Custom Title')
  })

  it('GET /api/sessions/:id/slash-commands should include user and project skills before CLI init', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const workDir = path.join(tmpDir, 'workspace', 'app')

    await fs.mkdir(path.join(workDir, '.claude', 'skills'), { recursive: true })
    await fs.mkdir(path.join(tmpDir, 'skills'), { recursive: true })
    await writeSkill(path.join(tmpDir, 'skills'), 'user-skill', 'User skill description')
    await writeSkill(path.join(workDir, '.claude', 'skills'), 'project-skill', 'Project skill description')

    await writeSessionFile('-tmp-api-test', sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry(workDir),
    ])

    clearCommandsCache()

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/slash-commands`)
    expect(res.status).toBe(200)

    const body = (await res.json()) as {
      commands: Array<{ name: string; description: string }>
    }

    expect(body.commands).toContainEqual(
      expect.objectContaining({ name: 'user-skill', description: 'User skill description' }),
    )
    expect(body.commands).toContainEqual(
      expect.objectContaining({ name: 'project-skill', description: 'Project skill description' }),
    )
  })

  it('GET /api/sessions/:id/slash-commands should include legacy custom commands before CLI init', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeef'
    const workDir = path.join(tmpDir, 'workspace', 'app')

    await writeLegacySlashCommand(
      path.join(tmpDir, 'commands'),
      'user-probe',
      'User custom slash command',
    )
    await writeLegacySlashCommand(
      path.join(workDir, '.claude', 'commands'),
      'project-probe',
      'Project custom slash command',
    )

    await writeSessionFile('-tmp-api-test', sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry(workDir),
    ])

    clearCommandsCache()

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/slash-commands`)
    expect(res.status).toBe(200)

    const body = (await res.json()) as {
      commands: Array<{ name: string; description: string; argumentHint?: string }>
    }

    expect(body.commands).toContainEqual(
      expect.objectContaining({
        name: 'user-probe',
        description: 'User custom slash command',
        argumentHint: '<topic>',
      }),
    )
    expect(body.commands).toContainEqual(
      expect.objectContaining({
        name: 'project-probe',
        description: 'Project custom slash command',
        argumentHint: '<topic>',
      }),
    )
  })

  it('GET /api/sessions/:id/slash-commands should preserve cached command argument hints when merging custom commands', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeef001'
    const workDir = path.join(tmpDir, 'workspace', 'app')

    await writeLegacySlashCommand(
      path.join(workDir, '.claude', 'commands'),
      'project-probe',
      'Project custom slash command',
    )

    await writeSessionFile('-tmp-api-test', sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry(workDir),
    ])

    updateSessionSlashCommands(
      sessionId,
      [{ name: 'builtin-probe', description: 'Cached CLI command', argumentHint: '<value>' }],
      { notifyClient: false },
    )
    clearCommandsCache()

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/slash-commands`)
    expect(res.status).toBe(200)

    const body = (await res.json()) as {
      commands: Array<{ name: string; description: string; argumentHint?: string }>
    }

    expect(body.commands).toContainEqual({
      name: 'builtin-probe',
      description: 'Cached CLI command',
      argumentHint: '<value>',
    })
    expect(body.commands).toContainEqual(
      expect.objectContaining({
        name: 'project-probe',
        description: 'Project custom slash command',
      }),
    )
  })

  it('GET /api/sessions/:id/slash-commands should include enabled plugin skills before CLI init', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-ffffffffffff'
    const workDir = path.join(tmpDir, 'workspace', 'app')
    const marketplaceRoot = path.join(tmpDir, 'marketplace-root')
    const pluginRoot = path.join(marketplaceRoot, 'plugins', 'superpowers')
    const pluginsDir = path.join(tmpDir, 'plugins')
    const marketplaceFile = path.join(
      marketplaceRoot,
      '.claude-plugin',
      'marketplace.json',
    )

    await fs.mkdir(path.join(pluginRoot, '.claude-plugin'), { recursive: true })
    await fs.mkdir(path.dirname(marketplaceFile), { recursive: true })
    await fs.mkdir(pluginsDir, { recursive: true })
    await fs.mkdir(workDir, { recursive: true })
    await writeSkill(
      path.join(pluginRoot, 'skills'),
      'brainstorming',
      'Superpowers brainstorming skill',
    )
    await fs.writeFile(
      path.join(pluginRoot, '.claude-plugin', 'plugin.json'),
      JSON.stringify({
        name: 'superpowers',
        version: '5.0.7',
        description: 'Core skills library',
      }),
      'utf-8',
    )
    await fs.writeFile(
      marketplaceFile,
      JSON.stringify({
        name: 'claude-plugins-official',
        owner: { name: 'Test' },
        plugins: [
          {
            name: 'superpowers',
            source: './plugins/superpowers',
            version: '5.0.7',
          },
        ],
      }),
      'utf-8',
    )
    await fs.writeFile(
      path.join(pluginsDir, 'known_marketplaces.json'),
      JSON.stringify({
        'claude-plugins-official': {
          source: { source: 'directory', path: marketplaceRoot },
          installLocation: marketplaceRoot,
          lastUpdated: new Date(0).toISOString(),
        },
      }),
      'utf-8',
    )
    await fs.writeFile(
      path.join(tmpDir, 'settings.json'),
      JSON.stringify({
        enabledPlugins: {
          'superpowers@claude-plugins-official': true,
        },
      }),
      'utf-8',
    )

    resetSettingsCache()
    clearPluginCache('sessions-api-plugin-skills')
    clearCommandsCache()
    await writeSessionFile('-tmp-api-test', sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry(workDir),
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/slash-commands`)
    expect(res.status).toBe(200)

    const body = (await res.json()) as {
      commands: Array<{ name: string; description: string }>
    }

    expect(body.commands).toContainEqual(
      expect.objectContaining({
        name: 'superpowers:brainstorming',
        description: 'Superpowers brainstorming skill',
      }),
    )
  })

  it('GET /api/sessions/:id/workspace/status|tree|file|diff should return workspace data', async () => {
    const workDir = await createWorkspaceApiGitRepo(tmpDir)
    const { sessionId } = await service.createSession(workDir)

    const statusRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/workspace/status`)
    expect(statusRes.status).toBe(200)
    const statusBody = await statusRes.json() as {
      state: string
      workDir: string
      changedFiles: Array<{ path: string; status: string }>
      isGitRepo: boolean
    }
    expect(statusBody.state).toBe('ok')
    expect(statusBody.workDir).toBe(await fs.realpath(workDir))
    expect(statusBody.isGitRepo).toBe(true)
    expect(statusBody.changedFiles).toEqual(
      expect.arrayContaining([
        expect.objectContaining({ path: 'tracked.txt', status: 'modified' }),
      ]),
    )

    const treeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/workspace/tree`)
    expect(treeRes.status).toBe(200)
    const treeBody = await treeRes.json() as {
      state: string
      path: string
      entries: Array<{ name: string; path: string; isDirectory: boolean }>
    }
    expect(treeBody).toMatchObject({
      state: 'ok',
      path: '',
    })
    expect(treeBody.entries).toEqual([
      { name: 'src', path: 'src', isDirectory: true },
      { name: 'tracked.txt', path: 'tracked.txt', isDirectory: false },
    ])

    const fileRes = await fetch(
      `${baseUrl}/api/sessions/${sessionId}/workspace/file?path=${encodeURIComponent('src/app.ts')}`,
    )
    expect(fileRes.status).toBe(200)
    const fileBody = await fileRes.json() as {
      state: string
      path: string
      content?: string
      language: string
      size: number
    }
    expect(fileBody).toMatchObject({
      state: 'ok',
      path: 'src/app.ts',
      language: 'typescript',
      size: 25,
      content: 'export const answer = 42\n',
    })

    const diffRes = await fetch(
      `${baseUrl}/api/sessions/${sessionId}/workspace/diff?path=${encodeURIComponent('tracked.txt')}`,
    )
    expect(diffRes.status).toBe(200)
    const diffBody = await diffRes.json() as {
      state: string
      path: string
      diff?: string
    }
    expect(diffBody.state).toBe('ok')
    expect(diffBody.path).toBe('tracked.txt')
    expect(diffBody.diff).toContain('tracked.txt')
  })

  it('GET /api/sessions/:id/workspace/* should surface transcript changes for a non-git tmp session', async () => {
    const sessionId = 'bbbbbbbb-cccc-dddd-eeee-ffffffffffff'
    const workDir = await fs.mkdtemp(path.join(tmpDir, 'workspace-api-non-git-'))
    const srcDir = path.join(workDir, 'src')
    const notesDir = path.join(workDir, 'notes')
    const assetsDir = path.join(workDir, 'assets')

    await fs.mkdir(srcDir, { recursive: true })
    await fs.mkdir(notesDir, { recursive: true })
    await fs.mkdir(assetsDir, { recursive: true })
    await fs.writeFile(path.join(workDir, 'README.md'), '# Temporary project\n')
    await fs.writeFile(path.join(srcDir, 'app.ts'), 'export const answer = 2\n')
    await fs.writeFile(path.join(notesDir, 'todo.md'), '- ship workspace panel\n')
    await fs.writeFile(
      path.join(assetsDir, 'pixel.png'),
      Buffer.from(
        'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
        'base64',
      ),
    )

    await writeSessionFile(sanitizePath(workDir), sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry(workDir),
      makeUserEntry('Update this temporary project'),
      makeAssistantToolUseEntry([
        {
          id: 'toolu-edit-app',
          name: 'Edit',
          input: {
            file_path: path.join(workDir, 'src', 'app.ts'),
            old_string: 'export const answer = 1\n',
            new_string: 'export const answer = 2\n',
          },
        },
        {
          id: 'toolu-write-todo',
          name: 'Write',
          input: {
            file_path: path.join(workDir, 'notes', 'todo.md'),
            content: '- ship workspace panel\n',
          },
        },
      ]),
    ])

    const statusRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/workspace/status`)
    expect(statusRes.status).toBe(200)
    const statusBody = await statusRes.json() as {
      state: string
      workDir: string
      repoName: string | null
      branch: string | null
      isGitRepo: boolean
      changedFiles: Array<{
        path: string
        status: string
        additions: number
        deletions: number
      }>
    }
    expect(statusBody).toMatchObject({
      state: 'ok',
      workDir,
      repoName: path.basename(workDir),
      branch: null,
      isGitRepo: false,
    })
    expect(statusBody.changedFiles).toEqual([
      expect.objectContaining({
        path: 'notes/todo.md',
        status: 'added',
        additions: 1,
        deletions: 0,
      }),
      expect.objectContaining({
        path: 'src/app.ts',
        status: 'modified',
        additions: 1,
        deletions: 1,
      }),
    ])

    const treeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/workspace/tree`)
    expect(treeRes.status).toBe(200)
    const treeBody = await treeRes.json() as {
      state: string
      path: string
      entries: Array<{ name: string; path: string; isDirectory: boolean }>
    }
    expect(treeBody).toMatchObject({ state: 'ok', path: '' })
    expect(treeBody.entries).toEqual([
      { name: 'assets', path: 'assets', isDirectory: true },
      { name: 'notes', path: 'notes', isDirectory: true },
      { name: 'src', path: 'src', isDirectory: true },
      { name: 'README.md', path: 'README.md', isDirectory: false },
    ])

    const srcTreeRes = await fetch(
      `${baseUrl}/api/sessions/${sessionId}/workspace/tree?path=${encodeURIComponent('src')}`,
    )
    expect(srcTreeRes.status).toBe(200)
    expect(await srcTreeRes.json()).toMatchObject({
      state: 'ok',
      path: 'src',
      entries: [{ name: 'app.ts', path: 'src/app.ts', isDirectory: false }],
    })

    const fileRes = await fetch(
      `${baseUrl}/api/sessions/${sessionId}/workspace/file?path=${encodeURIComponent('src/app.ts')}`,
    )
    expect(fileRes.status).toBe(200)
    expect(await fileRes.json()).toMatchObject({
      state: 'ok',
      path: 'src/app.ts',
      previewType: 'text',
      language: 'typescript',
      content: 'export const answer = 2\n',
    })

    const imageRes = await fetch(
      `${baseUrl}/api/sessions/${sessionId}/workspace/file?path=${encodeURIComponent('assets/pixel.png')}`,
    )
    expect(imageRes.status).toBe(200)
    const imageBody = await imageRes.json() as {
      state: string
      path: string
      previewType: string
      mimeType: string
      dataUrl: string
    }
    expect(imageBody).toMatchObject({
      state: 'ok',
      path: 'assets/pixel.png',
      previewType: 'image',
      mimeType: 'image/png',
    })
    expect(imageBody.dataUrl).toStartWith('data:image/png;base64,')

    const appDiffRes = await fetch(
      `${baseUrl}/api/sessions/${sessionId}/workspace/diff?path=${encodeURIComponent('src/app.ts')}`,
    )
    expect(appDiffRes.status).toBe(200)
    const appDiffBody = await appDiffRes.json() as { state: string; path: string; diff?: string }
    expect(appDiffBody).toMatchObject({ state: 'ok', path: 'src/app.ts' })
    expect(appDiffBody.diff).toContain('diff --session a/src/app.ts b/src/app.ts')
    expect(appDiffBody.diff).toContain('-export const answer = 1')
    expect(appDiffBody.diff).toContain('+export const answer = 2')

    const todoDiffRes = await fetch(
      `${baseUrl}/api/sessions/${sessionId}/workspace/diff?path=${encodeURIComponent('notes/todo.md')}`,
    )
    expect(todoDiffRes.status).toBe(200)
    const todoDiffBody = await todoDiffRes.json() as { state: string; path: string; diff?: string }
    expect(todoDiffBody).toMatchObject({ state: 'ok', path: 'notes/todo.md' })
    expect(todoDiffBody.diff).toContain('--- /dev/null')
    expect(todoDiffBody.diff).toContain('+++ b/notes/todo.md')
    expect(todoDiffBody.diff).toContain('+- ship workspace panel')
  })

  it('GET /api/sessions/:id/workspace/* should surface file-history changes for a non-git generated subdirectory', async () => {
    const sessionId = crypto.randomUUID()
    const workDir = path.join(tmpDir, 'workspace-file-history-generated')
    const generatedFile = path.join(workDir, 'aacc', 'src', 'App.tsx')
    const userId = crypto.randomUUID()

    await fs.mkdir(path.dirname(generatedFile), { recursive: true })
    await fs.writeFile(
      generatedFile,
      'export default function App() { return <main>Tetris</main> }\n',
      'utf-8',
    )

    await writeSessionFile(sanitizePath(workDir), sessionId, [
      makeSessionMetaEntry(workDir),
      makeFileHistorySnapshotEntry(userId, {
        'aacc/src/App.tsx': {
          backupFileName: null,
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('create aacc project', userId),
        cwd: workDir,
        sessionId,
      },
      makeAssistantEntry('DONE', userId),
      makeUserEntry(
        '<task-notification>\n<task-id>bg-1</task-id>\n<tool-use-id>toolu_bg</tool-use-id>\n<status>completed</status>\n<summary>Background command completed</summary>\n</task-notification>',
        crypto.randomUUID(),
      ),
      makeAssistantEntry('Background task completed again, no action needed'),
    ])

    const statusRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/workspace/status`)
    expect(statusRes.status).toBe(200)
    const statusBody = await statusRes.json() as {
      state: string
      workDir: string
      isGitRepo: boolean
      changedFiles: Array<{
        path: string
        status: string
        additions: number
        deletions: number
      }>
    }
    expect(statusBody).toMatchObject({
      state: 'ok',
      workDir,
      isGitRepo: false,
    })
    expect(statusBody.changedFiles).toEqual([
      expect.objectContaining({
        path: 'aacc/src/App.tsx',
        status: 'added',
        additions: 1,
        deletions: 0,
      }),
    ])

    const diffRes = await fetch(
      `${baseUrl}/api/sessions/${sessionId}/workspace/diff?path=${encodeURIComponent('aacc/src/App.tsx')}`,
    )
    expect(diffRes.status).toBe(200)
    const diffBody = await diffRes.json() as {
      state: string
      path: string
      diff: string
    }
    expect(diffBody).toMatchObject({
      state: 'ok',
      path: 'aacc/src/App.tsx',
    })
    expect(diffBody.diff).toContain('diff --session /dev/null b/aacc/src/App.tsx')
    expect(diffBody.diff).toContain('+export default function App() { return <main>Tetris</main> }')

    const checkpointsRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/turn-checkpoints`)
    expect(checkpointsRes.status).toBe(200)
    const checkpointsBody = await checkpointsRes.json() as {
      checkpoints: Array<{
        target: {
          targetUserMessageId: string
          userMessageIndex: number
          userMessageCount: number
        }
        code: {
          filesChanged: string[]
        }
      }>
    }
    expect(checkpointsBody.checkpoints).toHaveLength(1)
    expect(checkpointsBody.checkpoints[0]?.target).toMatchObject({
      targetUserMessageId: userId,
      userMessageIndex: 0,
      userMessageCount: 1,
    })
    expect(checkpointsBody.checkpoints[0]?.code.filesChanged).toEqual([generatedFile])
  })

  it('GET /api/sessions/:id/workspace/file and diff should require a path query', async () => {
    const workDir = await createWorkspaceApiGitRepo(tmpDir)
    const { sessionId } = await service.createSession(workDir)

    for (const route of ['file', 'diff']) {
      const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/workspace/${route}`)
      expect(res.status).toBe(400)
      expect(await res.json()).toMatchObject({
        error: 'BAD_REQUEST',
      })
    }
  })

  it('GET /api/sessions/:id/workspace/file and tree should reject traversal with 403', async () => {
    const workDir = await createWorkspaceApiGitRepo(tmpDir)
    const { sessionId } = await service.createSession(workDir)

    for (const route of ['file', 'tree']) {
      const res = await fetch(
        `${baseUrl}/api/sessions/${sessionId}/workspace/${route}?path=${encodeURIComponent('../outside.txt')}`,
      )
      expect(res.status).toBe(403)
      expect(await res.json()).toMatchObject({
        error: 'FORBIDDEN',
      })
    }
  })

  it('GET /api/sessions/:id/workspace/diff should reject traversal with 403', async () => {
    const workDir = await createWorkspaceApiGitRepo(tmpDir)
    const { sessionId } = await service.createSession(workDir)

    const res = await fetch(
      `${baseUrl}/api/sessions/${sessionId}/workspace/diff?path=${encodeURIComponent('../outside.txt')}`,
    )
    expect(res.status).toBe(403)
    expect(await res.json()).toMatchObject({
      error: 'FORBIDDEN',
    })
  })

  it('GET /api/sessions/:id/workspace/status should 404 for unknown sessions', async () => {
    const res = await fetch(
      `${baseUrl}/api/sessions/00000000-0000-0000-0000-000000000000/workspace/status`,
    )
    expect(res.status).toBe(404)
    expect(await res.json()).toMatchObject({
      error: 'NOT_FOUND',
    })
  })

  it('non-GET workspace routes should return 405', async () => {
    const workDir = await createWorkspaceApiGitRepo(tmpDir)
    const { sessionId } = await service.createSession(workDir)

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/workspace/status`, {
      method: 'POST',
    })

    expect(res.status).toBe(405)
    expect(await res.json()).toMatchObject({
      error: 'METHOD_NOT_ALLOWED',
    })
  })

  it('POST /api/sessions/:id/branch should create a branched session up to the target message', async () => {
    const sessionId = '11111111-1111-4111-8111-111111111111'
    const workDir = path.join(tmpDir, 'branch-api-workdir')
    const firstUserId = crypto.randomUUID()
    const firstAssistantId = crypto.randomUUID()
    const secondUserId = crypto.randomUUID()
    const secondAssistantId = crypto.randomUUID()

    await writeSessionFile(sanitizePath(workDir), sessionId, [
      {
        type: 'session-meta',
        isMeta: true,
        workDir,
        timestamp: '2026-01-01T00:00:00.000Z',
      },
      {
        ...makeUserEntry('first prompt', firstUserId),
        cwd: workDir,
        sessionId,
      },
      {
        ...makeAssistantEntry('first reply', firstUserId),
        uuid: firstAssistantId,
        cwd: workDir,
        sessionId,
      },
      {
        ...makeUserEntry('second prompt', secondUserId),
        parentUuid: firstAssistantId,
        cwd: workDir,
        sessionId,
      },
      {
        ...makeAssistantEntry('second reply', secondUserId),
        uuid: secondAssistantId,
        cwd: workDir,
        sessionId,
      },
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/branch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        targetMessageId: firstAssistantId,
        title: 'API branch',
      }),
    })
    expect(res.status).toBe(201)

    const body = await res.json() as {
      sessionId: string
      title: string
      workDir: string
      sourceSessionId: string
      targetMessageId: string
    }
    expect(body).toMatchObject({
      title: 'API branch (Branch)',
      workDir,
      sourceSessionId: sessionId,
      targetMessageId: firstAssistantId,
    })

    const branchMessages = await service.getSessionMessages(body.sessionId)
    expect(branchMessages.map((message) => message.id)).toEqual([
      firstUserId,
      firstAssistantId,
    ])
  })

  it('POST /api/sessions/:id/branch should reject sidechain targets', async () => {
    const sessionId = '22222222-2222-4222-8222-222222222222'
    const rootUserId = crypto.randomUUID()
    const rootAssistantId = crypto.randomUUID()
    const sidechainId = crypto.randomUUID()

    await writeSessionFile('-tmp-api-branch-sidechain', sessionId, [
      makeSnapshotEntry(),
      {
        ...makeUserEntry('root prompt', rootUserId),
        sessionId,
      },
      {
        ...makeAssistantEntry('root reply', rootUserId),
        uuid: rootAssistantId,
        sessionId,
      },
      {
        ...makeUserEntry('side question', sidechainId),
        parentUuid: rootAssistantId,
        isSidechain: true,
        sessionId,
      },
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/branch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ targetMessageId: sidechainId }),
    })

    expect(res.status).toBe(400)
    expect(await res.json()).toMatchObject({
      error: 'BAD_REQUEST',
    })
  })

  it('POST /api/sessions/:id/branch should validate request bodies and missing sessions', async () => {
    const methodNotAllowedRes = await fetch(`${baseUrl}/api/sessions/33333333-3333-4333-8333-333333333333/branch`)
    expect(methodNotAllowedRes.status).toBe(405)

    const missingTargetRes = await fetch(`${baseUrl}/api/sessions/branch-missing-target/branch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({}),
    })
    expect(missingTargetRes.status).toBe(400)

    const invalidJsonRes = await fetch(`${baseUrl}/api/sessions/branch-invalid-json/branch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: '{',
    })
    expect(invalidJsonRes.status).toBe(400)

    const invalidTitleRes = await fetch(`${baseUrl}/api/sessions/44444444-4444-4444-8444-444444444444/branch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ targetMessageId: 'message-1', title: 123 }),
    })
    expect(invalidTitleRes.status).toBe(400)

    const missingSessionRes = await fetch(`${baseUrl}/api/sessions/00000000-0000-0000-0000-000000000000/branch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ targetMessageId: 'missing-target' }),
    })
    expect(missingSessionRes.status).toBe(404)
  })

  it('POST /api/sessions/:id/rewind should preview and trim the active conversation chain', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const firstUserId = crypto.randomUUID()
    const firstAssistantId = crypto.randomUUID()
    const secondUserId = crypto.randomUUID()
    const secondAssistantId = crypto.randomUUID()

    await writeSessionFile('-tmp-api-test', sessionId, [
      makeSnapshotEntry(),
      {
        parentUuid: null,
        isSidechain: false,
        type: 'user',
        message: { role: 'user', content: 'first prompt' },
        uuid: firstUserId,
        timestamp: '2026-01-01T00:01:00.000Z',
        userType: 'external',
        cwd: '/tmp/test',
        sessionId,
      },
      {
        parentUuid: firstUserId,
        isSidechain: false,
        type: 'assistant',
        message: {
          model: 'claude-opus-4-7',
          id: `msg_${crypto.randomUUID().slice(0, 20)}`,
          type: 'message',
          role: 'assistant',
          content: [{ type: 'text', text: 'first reply' }],
        },
        uuid: firstAssistantId,
        timestamp: '2026-01-01T00:02:00.000Z',
      },
      {
        parentUuid: firstAssistantId,
        isSidechain: false,
        type: 'user',
        message: { role: 'user', content: 'second prompt' },
        uuid: secondUserId,
        timestamp: '2026-01-01T00:03:00.000Z',
        userType: 'external',
        cwd: '/tmp/test',
        sessionId,
      },
      {
        parentUuid: secondUserId,
        isSidechain: false,
        type: 'assistant',
        message: {
          model: 'claude-opus-4-7',
          id: `msg_${crypto.randomUUID().slice(0, 20)}`,
          type: 'message',
          role: 'assistant',
          content: [{ type: 'text', text: 'second reply' }],
        },
        uuid: secondAssistantId,
        timestamp: '2026-01-01T00:04:00.000Z',
      },
    ])

    const previewRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 1, dryRun: true }),
    })
    expect(previewRes.status).toBe(200)

    const previewBody = await previewRes.json() as {
      conversation: { messagesRemoved: number }
      code: { available: boolean }
    }
    expect(previewBody.conversation.messagesRemoved).toBe(2)
    expect(previewBody.code.available).toBe(false)

    const executeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 1 }),
    })
    expect(executeRes.status).toBe(200)

    const executeBody = await executeRes.json() as {
      conversation: { messagesRemoved: number; removedMessageIds: string[] }
    }
    expect(executeBody.conversation.messagesRemoved).toBe(2)
    expect(executeBody.conversation.removedMessageIds).toEqual([
      secondUserId,
      secondAssistantId,
    ])

    const remainingMessages = await service.getSessionMessages(sessionId)
    expect(remainingMessages.map((message) => message.id)).toEqual([
      firstUserId,
      firstAssistantId,
    ])
  })

  it('trimSessionMessagesFrom should remove orphan transcript entries beyond the rewind point', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const firstUserId = crypto.randomUUID()
    const firstAssistantId = crypto.randomUUID()
    const secondUserId = crypto.randomUUID()
    const secondAssistantId = crypto.randomUUID()

    const filePath = await writeSessionFile('-tmp-api-rewind-orphans', sessionId, [
      makeSnapshotEntry(),
      makeSessionMetaEntry('/tmp/project-with-hyphen'),
      {
        ...makeUserEntry('first prompt', firstUserId),
        sessionId,
      },
      {
        ...makeAssistantEntry('first reply', firstUserId),
        uuid: firstAssistantId,
      },
      {
        ...makeUserEntry('second prompt', secondUserId),
        parentUuid: firstAssistantId,
        sessionId,
      },
      {
        ...makeAssistantEntry('second reply', secondUserId),
        uuid: secondAssistantId,
      },
      {
        ...makeAssistantEntry('late stale reply', secondUserId),
        uuid: crypto.randomUUID(),
      },
    ])

    const result = await service.trimSessionMessagesFrom(sessionId, firstUserId)
    expect(result.removedMessageIds).toContain(firstUserId)
    expect(result.removedMessageIds).toContain(secondUserId)

    const raw = await fs.readFile(filePath, 'utf-8')
    expect(raw).toContain('"type":"session-meta"')
    expect(raw).not.toContain('late stale reply')
    expect(await service.getSessionMessages(sessionId)).toEqual([])

    const launchInfo = await service.getSessionLaunchInfo(sessionId)
    expect(launchInfo).not.toBeNull()
    expect(launchInfo!.workDir).toBe('/tmp/project-with-hyphen')
    expect(launchInfo!.transcriptMessageCount).toBe(0)
  })

  it('POST /api/sessions/:id/rewind should target the selected message id instead of a shifted visible index', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-ffffffffffff'
    const firstUserId = crypto.randomUUID()
    const firstAssistantId = crypto.randomUUID()
    const hiddenUserId = crypto.randomUUID()
    const targetUserId = crypto.randomUUID()
    const targetAssistantId = crypto.randomUUID()

    await writeSessionFile('-tmp-api-rewind-id-target', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('first prompt', firstUserId),
      {
        ...makeAssistantEntry('first reply', firstUserId),
        uuid: firstAssistantId,
      },
      makeUserEntry(
        '<teammate-message teammate_id="reviewer">internal status that the main chat hides</teammate-message>',
        hiddenUserId,
      ),
      makeUserEntry('second visible prompt', targetUserId),
      {
        ...makeAssistantEntry('second reply', targetUserId),
        uuid: targetAssistantId,
      },
    ])

    const executeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        userMessageIndex: 1,
        targetUserMessageId: targetUserId,
        expectedContent: 'second visible prompt',
      }),
    })
    expect(executeRes.status).toBe(200)

    const executeBody = await executeRes.json() as {
      target: { targetUserMessageId: string; userMessageIndex: number }
      conversation: { messagesRemoved: number; removedMessageIds: string[] }
    }
    expect(executeBody.target.targetUserMessageId).toBe(targetUserId)
    expect(executeBody.target.userMessageIndex).toBe(2)
    expect(executeBody.conversation.messagesRemoved).toBe(2)
    expect(executeBody.conversation.removedMessageIds).toEqual([
      targetUserId,
      targetAssistantId,
    ])

    const remainingMessages = await service.getSessionMessages(sessionId)
    expect(remainingMessages.map((message) => message.id)).toEqual([
      firstUserId,
      firstAssistantId,
      hiddenUserId,
    ])
  })

  it('POST /api/sessions/:id/rewind should reject an index fallback when the selected prompt no longer matches', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-000000000000'
    const firstUserId = crypto.randomUUID()
    const hiddenUserId = crypto.randomUUID()
    const targetUserId = crypto.randomUUID()

    await writeSessionFile('-tmp-api-rewind-index-guard', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('first prompt', firstUserId),
      makeUserEntry(
        '<teammate-message teammate_id="reviewer">internal status that the main chat hides</teammate-message>',
        hiddenUserId,
      ),
      makeUserEntry('second visible prompt', targetUserId),
    ])

    const executeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        userMessageIndex: 1,
        expectedContent: 'second visible prompt',
      }),
    })
    expect(executeRes.status).toBe(400)

    const body = await executeRes.json() as { message: string }
    expect(body.message).toContain('does not match the selected prompt')

    const remainingMessages = await service.getSessionMessages(sessionId)
    expect(remainingMessages.map((message) => message.id)).toEqual([
      firstUserId,
      hiddenUserId,
      targetUserId,
    ])
  })

  it('POST /api/sessions/:id/rewind should restore a single edited file', async () => {
    const sessionId = 'bbbbbbbb-bbbb-cccc-dddd-eeeeeeeeeeee'
    const workDir = path.join(tmpDir, 'single-file-fixture')
    const targetFile = path.join(workDir, 'src', 'app.js')
    const userId = crypto.randomUUID()
    const assistantId = crypto.randomUUID()
    const backupName = 'single-file@v1'

    await fs.mkdir(path.dirname(targetFile), { recursive: true })
    await fs.writeFile(
      targetFile,
      "export const ORIGINAL_VALUE = 'after-rewind'\n",
      'utf-8',
    )
    await writeFileHistoryBackup(
      sessionId,
      backupName,
      "export const ORIGINAL_VALUE = 'before-rewind'\n",
    )

    await writeSessionFile('-tmp-api-single-file', sessionId, [
      makeSessionMetaEntry(workDir),
      makeFileHistorySnapshotEntry(userId, {
        'src/app.js': {
          backupFileName: backupName,
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('edit app.js', userId),
        cwd: workDir,
        sessionId,
      },
      {
        ...makeAssistantEntry('DONE', userId),
        uuid: assistantId,
      },
    ])

    const previewRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 0, dryRun: true }),
    })
    expect(previewRes.status).toBe(200)
    const preview = await previewRes.json() as {
      code: { available: boolean; filesChanged: string[] }
    }
    expect(preview.code.available).toBe(true)
    expect(preview.code.filesChanged).toEqual([targetFile])

    const executeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 0 }),
    })
    expect(executeRes.status).toBe(200)
    expect(await fs.readFile(targetFile, 'utf-8')).toBe(
      "export const ORIGINAL_VALUE = 'before-rewind'\n",
    )

    const remainingMessages = await service.getSessionMessages(sessionId)
    expect(remainingMessages).toHaveLength(0)
  })

  it('POST /api/sessions/:id/rewind should resolve checkpoint paths from the target prompt cwd', async () => {
    const sessionId = 'bbbbbbbb-bbbb-cccc-dddd-ffffffffffff'
    const parentDir = path.join(tmpDir, 'nested-cwd-parent')
    const workDir = path.join(parentDir, 'testbb')
    const targetFile = path.join(workDir, 'vite.config.js')
    const userId = crypto.randomUUID()
    const assistantId = crypto.randomUUID()
    const laterUserId = crypto.randomUUID()
    const backupName = 'nested-cwd@v1'

    await fs.mkdir(workDir, { recursive: true })
    await fs.writeFile(targetFile, "export default 'after'\n", 'utf-8')
    await writeFileHistoryBackup(sessionId, backupName, "export default 'before'\n")

    await writeSessionFile(sanitizePath(parentDir), sessionId, [
      makeFileHistorySnapshotEntry(userId, {
        'testbb/vite.config.js': {
          backupFileName: backupName,
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('create a nested project', userId),
        cwd: parentDir,
        sessionId,
      },
      {
        ...makeAssistantEntry('DONE', userId),
        uuid: assistantId,
      },
      {
        ...makeUserEntry('latest tool result after cd', laterUserId),
        cwd: workDir,
        sessionId,
      },
    ])

    const previewRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 0, dryRun: true }),
    })
    expect(previewRes.status).toBe(200)
    const preview = await previewRes.json() as {
      code: { available: boolean; filesChanged: string[] }
    }
    expect(preview.code.available).toBe(true)
    expect(preview.code.filesChanged).toEqual([targetFile])

    const executeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 0 }),
    })
    expect(executeRes.status).toBe(200)
    expect(await fs.readFile(targetFile, 'utf-8')).toBe("export default 'before'\n")
  })

  it('POST /api/sessions/:id/rewind should restore multiple files and remove created files', async () => {
    const sessionId = 'cccccccc-bbbb-cccc-dddd-eeeeeeeeeeee'
    const workDir = path.join(tmpDir, 'multi-file-fixture')
    const appFile = path.join(workDir, 'src', 'app.js')
    const readmeFile = path.join(workDir, 'README.md')
    const createdFile = path.join(workDir, 'notes', 'generated.txt')
    const userId = crypto.randomUUID()
    const backupApp = 'multi-app@v1'
    const backupReadme = 'multi-readme@v1'

    await fs.mkdir(path.dirname(appFile), { recursive: true })
    await fs.mkdir(path.dirname(createdFile), { recursive: true })
    await fs.writeFile(appFile, "export const VALUE = 'edited'\n", 'utf-8')
    await fs.writeFile(readmeFile, '# changed\n', 'utf-8')
    await fs.writeFile(createdFile, 'new file\n', 'utf-8')
    await writeFileHistoryBackup(sessionId, backupApp, "export const VALUE = 'original'\n")
    await writeFileHistoryBackup(sessionId, backupReadme, '# original\n')

    await writeSessionFile('-tmp-api-multi-file', sessionId, [
      makeSessionMetaEntry(workDir),
      makeFileHistorySnapshotEntry(userId, {
        'src/app.js': {
          backupFileName: backupApp,
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
        'README.md': {
          backupFileName: backupReadme,
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
        'notes/generated.txt': {
          backupFileName: null,
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('edit multiple files', userId),
        cwd: workDir,
        sessionId,
      },
      makeAssistantEntry('DONE', userId),
    ])

    const previewRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 0, dryRun: true }),
    })
    expect(previewRes.status).toBe(200)
    const preview = await previewRes.json() as {
      code: { available: boolean; filesChanged: string[] }
    }
    expect(preview.code.available).toBe(true)
    expect(preview.code.filesChanged.sort()).toEqual([
      appFile,
      createdFile,
      readmeFile,
    ].sort())

    const executeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 0 }),
    })
    expect(executeRes.status).toBe(200)

    expect(await fs.readFile(appFile, 'utf-8')).toBe("export const VALUE = 'original'\n")
    expect(await fs.readFile(readmeFile, 'utf-8')).toBe('# original\n')
    await expect(fs.stat(createdFile)).rejects.toMatchObject({ code: 'ENOENT' })
  })

  it('POST /api/sessions/:id/rewind should restore the previous version when rewinding the second edit of the same file', async () => {
    const sessionId = 'dddddddd-bbbb-cccc-dddd-eeeeeeeeeeee'
    const workDir = path.join(tmpDir, 'same-file-two-turns')
    const targetFile = path.join(workDir, 'src', 'app.js')
    const firstUserId = crypto.randomUUID()
    const secondUserId = crypto.randomUUID()
    const backupV1 = 'same-file@v1'
    const backupV2 = 'same-file@v2'

    await fs.mkdir(path.dirname(targetFile), { recursive: true })
    await fs.writeFile(targetFile, "export const STEP = 'v2'\n", 'utf-8')
    await writeFileHistoryBackup(sessionId, backupV1, "export const STEP = 'base'\n")
    await writeFileHistoryBackup(sessionId, backupV2, "export const STEP = 'v1'\n")

    await writeSessionFile('-tmp-api-two-turns', sessionId, [
      makeSessionMetaEntry(workDir),
      makeFileHistorySnapshotEntry(firstUserId, {
        'src/app.js': {
          backupFileName: backupV1,
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('make v1', firstUserId),
        cwd: workDir,
        sessionId,
      },
      makeAssistantEntry('DONE', firstUserId),
      makeFileHistorySnapshotEntry(secondUserId, {
        'src/app.js': {
          backupFileName: backupV2,
          version: 2,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('make v2', secondUserId),
        cwd: workDir,
        sessionId,
      },
      makeAssistantEntry('DONE', secondUserId),
    ])

    const executeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 1 }),
    })
    expect(executeRes.status).toBe(200)
    expect(await fs.readFile(targetFile, 'utf-8')).toBe("export const STEP = 'v1'\n")

    const remainingMessages = await service.getSessionMessages(sessionId)
    expect(remainingMessages.map((message) => message.id)).toHaveLength(2)
    expect(remainingMessages[0]?.id).toBe(firstUserId)
  })

  it('POST /api/sessions/:id/rewind should keep first-turn file state when undoing only the latest turn', async () => {
    const sessionId = 'dddddddd-bbbb-cccc-dddd-ffffffffffff'
    const workDir = path.join(tmpDir, 'two-turns-separate-files')
    const firstTurnFile = path.join(workDir, 'src', 'first.js')
    const secondTurnFile = path.join(workDir, 'src', 'second.js')
    const firstUserId = crypto.randomUUID()
    const secondUserId = crypto.randomUUID()
    const firstBaseBackup = 'separate-first@v1'
    const firstAfterTurnBackup = 'separate-first@v2'
    const secondBaseBackup = 'separate-second@v1'

    await fs.mkdir(path.dirname(firstTurnFile), { recursive: true })
    await fs.writeFile(firstTurnFile, "export const FIRST = 'v1'\n", 'utf-8')
    await fs.writeFile(secondTurnFile, "export const SECOND = 'v2'\n", 'utf-8')
    await writeFileHistoryBackup(sessionId, firstBaseBackup, "export const FIRST = 'base'\n")
    await writeFileHistoryBackup(sessionId, firstAfterTurnBackup, "export const FIRST = 'v1'\n")
    await writeFileHistoryBackup(sessionId, secondBaseBackup, "export const SECOND = 'base'\n")

    await writeSessionFile('-tmp-api-two-turns-separate-files', sessionId, [
      makeSessionMetaEntry(workDir),
      makeFileHistorySnapshotEntry(firstUserId, {
        'src/first.js': {
          backupFileName: firstBaseBackup,
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('make first file v1', firstUserId),
        cwd: workDir,
        sessionId,
      },
      makeAssistantEntry('DONE first', firstUserId),
      makeFileHistorySnapshotEntry(secondUserId, {
        'src/first.js': {
          backupFileName: firstAfterTurnBackup,
          version: 2,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
        'src/second.js': {
          backupFileName: secondBaseBackup,
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('make second file v2', secondUserId),
        cwd: workDir,
        sessionId,
      },
      makeAssistantEntry('DONE second', secondUserId),
    ])

    const previewRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 1, dryRun: true }),
    })
    expect(previewRes.status).toBe(200)
    const preview = await previewRes.json() as {
      code: { available: boolean; filesChanged: string[] }
    }
    expect(preview.code.available).toBe(true)
    expect(preview.code.filesChanged).toEqual([secondTurnFile])

    const executeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 1 }),
    })
    expect(executeRes.status).toBe(200)

    expect(await fs.readFile(firstTurnFile, 'utf-8')).toBe("export const FIRST = 'v1'\n")
    expect(await fs.readFile(secondTurnFile, 'utf-8')).toBe("export const SECOND = 'base'\n")

    const remainingMessages = await service.getSessionMessages(sessionId)
    expect(remainingMessages).toHaveLength(2)
    expect(remainingMessages[0]?.id).toBe(firstUserId)
  })

  it('POST /api/sessions/:id/rewind should include files created after the first turn', async () => {
    const sessionId = 'eeeeeeee-bbbb-cccc-dddd-eeeeeeeeeeee'
    const workDir = path.join(tmpDir, 'created-on-second-turn')
    const firstFile = path.join(workDir, 'src', 'step.js')
    const createdFile = path.join(workDir, 'notes', 'generated.txt')
    const firstUserId = crypto.randomUUID()
    const secondUserId = crypto.randomUUID()
    const backupV1 = 'second-created-step@v1'
    const backupV2 = 'second-created-step@v2'

    await fs.mkdir(path.dirname(firstFile), { recursive: true })
    await fs.mkdir(path.dirname(createdFile), { recursive: true })
    await fs.writeFile(firstFile, "export const STEP = 'v2'\n", 'utf-8')
    await fs.writeFile(createdFile, 'generated\n', 'utf-8')
    await writeFileHistoryBackup(sessionId, backupV1, "export const STEP = 'base'\n")
    await writeFileHistoryBackup(sessionId, backupV2, "export const STEP = 'v1'\n")

    await writeSessionFile('-tmp-api-second-turn-created', sessionId, [
      makeSessionMetaEntry(workDir),
      makeFileHistorySnapshotEntry(firstUserId, {
        'src/step.js': {
          backupFileName: backupV1,
          version: 1,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('make v1', firstUserId),
        cwd: workDir,
        sessionId,
      },
      makeAssistantEntry('DONE', firstUserId),
      makeFileHistorySnapshotEntry(secondUserId, {
        'src/step.js': {
          backupFileName: backupV2,
          version: 2,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
        'notes/generated.txt': {
          backupFileName: null,
          version: 2,
          backupTime: '2026-01-01T00:00:00.000Z',
        },
      }),
      {
        ...makeUserEntry('make v2 and create file', secondUserId),
        cwd: workDir,
        sessionId,
      },
      makeAssistantEntry('DONE', secondUserId),
    ])

    const previewRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 1, dryRun: true }),
    })
    expect(previewRes.status).toBe(200)
    const preview = await previewRes.json() as {
      code: { available: boolean; filesChanged: string[]; insertions: number }
    }
    expect(preview.code.filesChanged.sort()).toEqual([
      createdFile,
      firstFile,
    ].sort())
    expect(preview.code.insertions).toBe(2)

    const executeRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 1 }),
    })
    expect(executeRes.status).toBe(200)
    expect(await fs.readFile(firstFile, 'utf-8')).toBe("export const STEP = 'v1'\n")
    await expect(fs.stat(createdFile)).rejects.toMatchObject({ code: 'ENOENT' })
  })

  it('GET /api/sessions/:id/turn-checkpoints should list completed turn previews with turn-bound diff stats', async () => {
    const fixture = await createThreeTurnCheckpointFixture(
      '99999999-bbbb-cccc-dddd-eeeeeeeeeeee',
    )

    const res = await fetch(`${baseUrl}/api/sessions/${fixture.sessionId}/turn-checkpoints`)
    expect(res.status).toBe(200)

    const body = await res.json() as {
      checkpoints: Array<{
        target: {
          targetUserMessageId: string
          userMessageIndex: number
          userMessageCount: number
        }
        conversation: { messagesRemoved: number }
        code: {
          available: boolean
          filesChanged: string[]
          insertions: number
          deletions: number
        }
        workDir: string
      }>
    }

    expect(body.checkpoints).toHaveLength(3)
    expect(body.checkpoints).toEqual([
      {
        target: {
          targetUserMessageId: fixture.firstUserId,
          userMessageIndex: 0,
          userMessageCount: 3,
        },
        conversation: { messagesRemoved: 6 },
        code: {
          available: true,
          filesChanged: [fixture.stepFile],
          insertions: 1,
          deletions: 1,
        },
        workDir: fixture.workDir,
      },
      {
        target: {
          targetUserMessageId: fixture.secondUserId,
          userMessageIndex: 1,
          userMessageCount: 3,
        },
        conversation: { messagesRemoved: 4 },
        code: {
          available: true,
          filesChanged: [fixture.stepFile],
          insertions: 1,
          deletions: 1,
        },
        workDir: fixture.workDir,
      },
      {
        target: {
          targetUserMessageId: fixture.thirdUserId,
          userMessageIndex: 2,
          userMessageCount: 3,
        },
        conversation: { messagesRemoved: 2 },
        code: {
          available: true,
          filesChanged: [fixture.stepFile, fixture.createdFile],
          insertions: 2,
          deletions: 1,
        },
        workDir: fixture.workDir,
      },
    ])
  })

  it('GET /api/sessions/:id/turn-checkpoints/diff should return target-bound checkpoint diffs', async () => {
    const fixture = await createThreeTurnCheckpointFixture(
      '99999999-bbbb-cccc-dddd-ffffffffffff',
    )

    const secondTurnRes = await fetch(
      `${baseUrl}/api/sessions/${fixture.sessionId}/turn-checkpoints/diff?targetUserMessageId=${fixture.secondUserId}&path=src/step.js`,
    )
    expect(secondTurnRes.status).toBe(200)
    const secondTurnBody = await secondTurnRes.json() as {
      state: string
      path: string
      diff?: string
      target: { targetUserMessageId: string }
    }
    expect(secondTurnBody.target.targetUserMessageId).toBe(fixture.secondUserId)
    expect(secondTurnBody.state).toBe('ok')
    expect(secondTurnBody.path).toBe('src/step.js')
    expect(secondTurnBody.diff).toContain("export const STEP = 'v2'")
    expect(secondTurnBody.diff).toContain("export const STEP = 'v1'")
    expect(secondTurnBody.diff).not.toContain("export const STEP = 'v3'")

    const thirdTurnRes = await fetch(
      `${baseUrl}/api/sessions/${fixture.sessionId}/turn-checkpoints/diff?targetUserMessageId=${fixture.thirdUserId}&path=src/step.js`,
    )
    expect(thirdTurnRes.status).toBe(200)
    const thirdTurnBody = await thirdTurnRes.json() as {
      state: string
      diff?: string
      target: { targetUserMessageId: string }
    }
    expect(thirdTurnBody.target.targetUserMessageId).toBe(fixture.thirdUserId)
    expect(thirdTurnBody.state).toBe('ok')
    expect(thirdTurnBody.diff).toContain("export const STEP = 'v3'")
    expect(thirdTurnBody.diff).toContain("export const STEP = 'v2'")
    expect(thirdTurnBody.diff).not.toContain("export const STEP = 'v1'")

    const createdFileRes = await fetch(
      `${baseUrl}/api/sessions/${fixture.sessionId}/turn-checkpoints/diff?targetUserMessageId=${fixture.thirdUserId}&path=notes/generated.txt`,
    )
    expect(createdFileRes.status).toBe(200)
    const createdFileBody = await createdFileRes.json() as {
      state: string
      diff?: string
    }
    expect(createdFileBody.state).toBe('ok')
    expect(createdFileBody.diff).toContain('generated third turn')
    expect(createdFileBody.diff).toContain('/dev/null')
  })

  it('GET /api/sessions/:id/turn-checkpoints should fall back to transcript tool changes when file snapshots are missing', async () => {
    const sessionId = '99999999-bbbb-cccc-dddd-000000000001'
    const workDir = path.join(tmpDir, 'transcript-only-session')
    const userId = crypto.randomUUID()
    await fs.mkdir(path.join(workDir, 'todo-app', 'src'), { recursive: true })

    await writeSessionFile('-tmp-transcript-only-session', sessionId, [
      makeSessionMetaEntry(workDir),
      {
        ...makeUserEntry('build a todo app', userId),
        cwd: workDir,
        sessionId,
      },
      makeAssistantToolUseEntry([
        {
          id: 'Write:1',
          name: 'Write',
          input: {
            file_path: path.join(workDir, 'todo-app', 'src', 'App.tsx'),
            content: 'export function App() {\n  return <main>Todo</main>\n}\n',
          },
        },
        {
          id: 'Write:2',
          name: 'Write',
          input: {
            file_path: 'todo-app/vite.config.ts',
            content: 'import { defineConfig } from "vite"\nexport default defineConfig({})\n',
          },
        },
      ], userId),
      makeAssistantEntry('Todo app created', userId),
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/turn-checkpoints`)
    expect(res.status).toBe(200)
    const body = await res.json() as {
      checkpoints: Array<{
        target: { targetUserMessageId: string }
        code: {
          available: boolean
          filesChanged: string[]
          insertions: number
          deletions: number
        }
        workDir: string
      }>
    }

    expect(body.checkpoints).toHaveLength(1)
    expect(body.checkpoints[0]!.target.targetUserMessageId).toBe(userId)
    expect(body.checkpoints[0]!.workDir).toBe(workDir)
    expect(body.checkpoints[0]!.code.available).toBe(true)
    expect(body.checkpoints[0]!.code.filesChanged.sort()).toEqual([
      path.join(workDir, 'todo-app', 'src', 'App.tsx'),
      path.join(workDir, 'todo-app', 'vite.config.ts'),
    ].sort())
    expect(body.checkpoints[0]!.code.insertions).toBe(5)
    expect(body.checkpoints[0]!.code.deletions).toBe(0)
  })

  it('GET /api/sessions/:id/turn-checkpoints/diff should return transcript tool diffs when file snapshots are missing', async () => {
    const sessionId = '99999999-bbbb-cccc-dddd-000000000002'
    const workDir = path.join(tmpDir, 'transcript-only-diff-session')
    const userId = crypto.randomUUID()

    await writeSessionFile('-tmp-transcript-only-diff-session', sessionId, [
      makeSessionMetaEntry(workDir),
      {
        ...makeUserEntry('edit config', userId),
        cwd: workDir,
        sessionId,
      },
      makeAssistantToolUseEntry([
        {
          id: 'Edit:1',
          name: 'Edit',
          input: {
            file_path: path.join(workDir, 'todo-app', 'vite.config.ts'),
            old_string: 'plugins: [react()]',
            new_string: 'plugins: [react(), tailwindcss()]',
          },
        },
      ], userId),
      makeAssistantEntry('Config updated', userId),
    ])

    const res = await fetch(
      `${baseUrl}/api/sessions/${sessionId}/turn-checkpoints/diff?targetUserMessageId=${userId}&path=${encodeURIComponent('todo-app/vite.config.ts')}`,
    )
    expect(res.status).toBe(200)
    const body = await res.json() as {
      state: string
      path: string
      diff?: string
      target: { targetUserMessageId: string }
    }

    expect(body.target.targetUserMessageId).toBe(userId)
    expect(body.state).toBe('ok')
    expect(body.path).toBe('todo-app/vite.config.ts')
    expect(body.diff).toContain('diff --session a/todo-app/vite.config.ts b/todo-app/vite.config.ts')
    expect(body.diff).toContain('-plugins: [react()]')
    expect(body.diff).toContain('+plugins: [react(), tailwindcss()]')
  })

  it('GET /api/sessions/:id/turn-checkpoints should include subagent transcript file changes for the parent turn', async () => {
    const sessionId = '99999999-bbbb-cccc-dddd-000000000003'
    const workDir = path.join(tmpDir, 'transcript-subagent-session')
    const firstUserId = crypto.randomUUID()
    const secondUserId = crypto.randomUUID()
    const agentMessageId = crypto.randomUUID()
    await fs.mkdir(path.join(workDir, 'todo-app', 'src'), { recursive: true })

    await writeSessionFile('-tmp-transcript-subagent-session', sessionId, [
      makeSessionMetaEntry(workDir),
      {
        ...makeUserEntry('build a todo app', firstUserId),
        cwd: workDir,
        sessionId,
      },
      {
        parentUuid: firstUserId,
        isSidechain: false,
        type: 'assistant',
        message: {
          model: 'claude-opus-4-7',
          id: `msg_${crypto.randomUUID().slice(0, 20)}`,
          type: 'message',
          role: 'assistant',
          content: [{
            type: 'tool_use',
            id: 'Agent:todo',
            name: 'Agent',
            input: { description: 'Create todo app files' },
          }],
        },
        uuid: agentMessageId,
        timestamp: '2026-01-01T00:02:00.000Z',
      },
      {
        ...makeUserEntry('now explain it', secondUserId),
        parentUuid: agentMessageId,
        cwd: workDir,
        sessionId,
      },
      {
        parentUuid: agentMessageId,
        isSidechain: true,
        type: 'assistant',
        message: {
          model: 'claude-opus-4-7',
          id: `msg_${crypto.randomUUID().slice(0, 20)}`,
          type: 'message',
          role: 'assistant',
          content: [{
            type: 'tool_use',
            id: 'Write:child',
            name: 'Write',
            input: {
              file_path: path.join(workDir, 'todo-app', 'src', 'Board.tsx'),
              content: 'export function Board() {\n  return null\n}\n',
            },
          }],
        },
        uuid: crypto.randomUUID(),
        timestamp: '2026-01-01T00:03:00.000Z',
      },
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/turn-checkpoints`)
    expect(res.status).toBe(200)
    const body = await res.json() as {
      checkpoints: Array<{
        target: { targetUserMessageId: string }
        code: { filesChanged: string[]; insertions: number; deletions: number }
      }>
    }

    expect(body.checkpoints).toHaveLength(1)
    expect(body.checkpoints[0]!.target.targetUserMessageId).toBe(firstUserId)
    expect(body.checkpoints[0]!.code.filesChanged).toEqual([
      path.join(workDir, 'todo-app', 'src', 'Board.tsx'),
    ])
    expect(body.checkpoints[0]!.code.insertions).toBe(3)
    expect(body.checkpoints[0]!.code.deletions).toBe(0)
  })

  it('POST /api/sessions/:id/rewind should restore the base state when rewinding the first turn of a three-turn file history', async () => {
    const fixture = await createThreeTurnCheckpointFixture(
      'aaaaaaaa-1111-2222-3333-444444444444',
    )

    const executeRes = await fetch(`${baseUrl}/api/sessions/${fixture.sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 0 }),
    })
    expect(executeRes.status).toBe(200)

    expect(await fs.readFile(fixture.stepFile, 'utf-8')).toBe("export const STEP = 'base'\n")
    await expect(fs.stat(fixture.createdFile)).rejects.toMatchObject({ code: 'ENOENT' })

    const remainingMessages = await service.getSessionMessages(fixture.sessionId)
    expect(remainingMessages).toHaveLength(0)
  })

  it('POST /api/sessions/:id/rewind should keep the first turn and remove later file changes when rewinding the second turn of a three-turn history', async () => {
    const fixture = await createThreeTurnCheckpointFixture(
      'aaaaaaaa-5555-6666-7777-888888888888',
    )

    const executeRes = await fetch(`${baseUrl}/api/sessions/${fixture.sessionId}/rewind`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userMessageIndex: 1 }),
    })
    expect(executeRes.status).toBe(200)

    expect(await fs.readFile(fixture.stepFile, 'utf-8')).toBe("export const STEP = 'v1'\n")
    await expect(fs.stat(fixture.createdFile)).rejects.toMatchObject({ code: 'ENOENT' })

    const remainingMessages = await service.getSessionMessages(fixture.sessionId)
    expect(remainingMessages).toHaveLength(2)
    expect(remainingMessages[0]?.id).toBe(fixture.firstUserId)
    expect(remainingMessages[1]?.type).toBe('assistant')
  })

  // --------------------------------------------------------------------------
  // Conversations API via /api/sessions/:id/chat
  // --------------------------------------------------------------------------

  it('GET /api/sessions/:id/chat/status should return idle by default', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/chat/status`)
    expect(res.status).toBe(200)

    const body = (await res.json()) as { state: string }
    expect(body.state).toBe('idle')
  })

  it('POST /api/sessions/:id/chat should queue a message', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    await writeSessionFile('-tmp-api-test', sessionId, [
      makeSnapshotEntry(),
      makeUserEntry('Previous'),
    ])

    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ content: 'New question' }),
    })
    expect(res.status).toBe(202)

    const body = (await res.json()) as { messageId: string; status: string }
    expect(body.status).toBe('queued')
    expect(body.messageId).toBeTruthy()
  })

  it('POST /api/sessions/:id/chat/stop should reset state to idle', async () => {
    const sessionId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
    const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/chat/stop`, {
      method: 'POST',
    })
    expect(res.status).toBe(200)

    // Verify state is idle
    const statusRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/chat/status`)
    const status = (await statusRes.json()) as { state: string }
    expect(status.state).toBe('idle')
  })
})