File size: 101,834 Bytes
1f21206 | 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 | /**
* Tests for ConversationService and WebSocket chat integration
*
* ConversationService 管理 CLI 子进程的生命周期。
* WebSocket 集成测试验证消息从客户端经过服务端到达 CLI 的完整流转。
*/
import { describe, it, expect, beforeAll, afterAll } from 'bun:test'
import * as fs from 'fs/promises'
import * as path from 'path'
import * as os from 'os'
import { execFileSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { ConversationService, ConversationStartupError, conversationService } from '../services/conversationService.js'
import { SessionService, sessionService } from '../services/sessionService.js'
import { ProviderService } from '../services/providerService.js'
async function rmWithRetry(targetPath: string): Promise<void> {
const attempts = process.platform === 'win32' ? 5 : 1
for (let attempt = 0; attempt < attempts; attempt++) {
try {
await fs.rm(targetPath, { recursive: true, force: true })
return
} catch (error) {
if (
attempt === attempts - 1 ||
!['EBUSY', 'EPERM', 'ENOTEMPTY'].includes((error as NodeJS.ErrnoException).code || '')
) {
throw error
}
await new Promise((resolve) => setTimeout(resolve, 100 * (attempt + 1)))
}
}
}
// ============================================================================
// ConversationService unit tests
// ============================================================================
describe('ConversationService', () => {
it('should report no session for unknown ID', () => {
const svc = new ConversationService()
const sid = crypto.randomUUID()
expect(svc.hasSession(sid)).toBe(false)
})
it('should track active sessions as empty initially', () => {
const svc = new ConversationService()
expect(svc.getActiveSessions()).toEqual([])
})
it('should block startup after a session is deleted during prewarm', async () => {
const svc = new ConversationService()
const sid = crypto.randomUUID()
svc.markSessionDeleted(sid)
try {
await svc.startSession(sid, process.cwd(), 'ws://127.0.0.1:1/sdk/test')
throw new Error('expected startSession to reject')
} catch (error) {
expect(error).toBeInstanceOf(ConversationStartupError)
expect((error as ConversationStartupError).code).toBe('SESSION_DELETED')
}
})
it('should return false when sending message to non-existent session', async () => {
const svc = new ConversationService()
const result = await svc.sendMessage('no-such-session', 'hello')
expect(result).toBe(false)
})
it('should return false when responding to permission for non-existent session', () => {
const svc = new ConversationService()
const result = svc.respondToPermission('no-such-session', 'req-1', true)
expect(result).toBe(false)
})
it('should not queue control requests before the SDK socket connects', async () => {
const svc = new ConversationService()
const sid = crypto.randomUUID()
const sent: unknown[] = []
const session: any = {
proc: { kill() {}, exited: Promise.resolve(0) },
outputCallbacks: [],
workDir: process.cwd(),
permissionMode: 'default',
sdkToken: 'token',
sdkSocket: null,
pendingOutbound: [],
startupPending: false,
startupExitCode: null,
stdoutLines: [],
stderrLines: [],
outputDrain: Promise.resolve(),
sdkMessages: [],
initMessage: null,
pendingPermissionRequests: new Map(),
}
;(svc as any).sessions.set(sid, session)
const request = svc.requestControl(sid, { subtype: 'get_context_usage' }, 1_000)
await new Promise((resolve) => setTimeout(resolve, 75))
expect(session.pendingOutbound).toHaveLength(0)
expect(sent).toHaveLength(0)
session.sdkSocket = {
send(data: string) {
sent.push(JSON.parse(data))
},
}
await new Promise((resolve) => setTimeout(resolve, 75))
expect(session.pendingOutbound).toHaveLength(0)
expect(sent).toHaveLength(1)
const requestId = (sent[0] as any).request_id
for (const callback of [...session.outputCallbacks]) {
callback({
type: 'control_response',
response: {
subtype: 'success',
request_id: requestId,
response: { ok: true },
},
})
}
await expect(request).resolves.toEqual({ ok: true })
})
it('should forward suggested permission updates for allow-for-session decisions', () => {
const svc = new ConversationService()
const sent: unknown[] = []
;(svc as any).sessions.set('session-1', {
proc: null,
outputCallbacks: [],
workDir: process.cwd(),
sdkToken: 'token',
sdkSocket: {
send(data: string) {
sent.push(JSON.parse(data))
},
},
pendingOutbound: [],
stderrLines: [],
sdkMessages: [],
pendingPermissionRequests: new Map([
['req-1', {
toolName: 'Bash',
input: { command: 'ls src' },
permissionSuggestions: [
{
type: 'addRules',
rules: [{ toolName: 'Bash', ruleContent: 'ls src' }],
behavior: 'allow',
destination: 'localSettings',
},
],
}],
]),
})
const result = svc.respondToPermission('session-1', 'req-1', true, 'always')
expect(result).toBe(true)
expect(sent).toHaveLength(1)
expect(sent[0]).toMatchObject({
type: 'control_response',
response: {
response: {
behavior: 'allow',
updatedPermissions: [
{
type: 'addRules',
rules: [{ toolName: 'Bash', ruleContent: 'ls src' }],
behavior: 'allow',
destination: 'session',
},
],
},
},
})
})
it('should send set_permission_mode requests to active sessions', () => {
const svc = new ConversationService()
const sent: unknown[] = []
;(svc as any).sessions.set('session-2', {
proc: null,
outputCallbacks: [],
workDir: process.cwd(),
sdkToken: 'token',
sdkSocket: {
send(data: string) {
sent.push(JSON.parse(data))
},
},
pendingOutbound: [],
stderrLines: [],
sdkMessages: [],
pendingPermissionRequests: new Map(),
})
const result = svc.setPermissionMode('session-2', 'acceptEdits')
expect(result).toBe(true)
expect(sent).toHaveLength(1)
expect(sent[0]).toMatchObject({
type: 'control_request',
request: {
subtype: 'set_permission_mode',
mode: 'acceptEdits',
},
})
})
it('should not inject a desktop-specific ask override in default permission mode', () => {
const svc = new ConversationService()
expect((svc as any).getPermissionArgs('default', false)).toEqual([
'--permission-mode',
'default',
])
})
it('should pass disabled thinking to the CLI runtime args', () => {
const svc = new ConversationService()
expect((svc as any).getRuntimeArgs({
model: 'deepseek-v4-pro',
effort: 'medium',
thinking: 'disabled',
})).toEqual([
'--model',
'deepseek-v4-pro',
'--effort',
'medium',
'--thinking',
'disabled',
])
})
it('should send thinking token controls to active CLI sessions', () => {
const svc = new ConversationService() as any
const sent: string[] = []
svc.sessions.set('session-thinking-control', {
sdkSocket: { send: (data: string) => sent.push(data) },
pendingOutbound: [],
})
expect(svc.setMaxThinkingTokens('session-thinking-control', 0)).toBe(true)
expect(svc.setMaxThinkingTokens('session-thinking-control', null)).toBe(true)
expect(svc.setMaxThinkingTokensForActiveSessions(0)).toBe(1)
expect(sent.map((line) => JSON.parse(line).request)).toEqual([
{
subtype: 'set_max_thinking_tokens',
max_thinking_tokens: 0,
},
{
subtype: 'set_max_thinking_tokens',
max_thinking_tokens: null,
},
{
subtype: 'set_max_thinking_tokens',
max_thinking_tokens: 0,
},
])
})
it('should return false when sending interrupt to non-existent session', () => {
const svc = new ConversationService()
const result = svc.sendInterrupt('no-such-session')
expect(result).toBe(false)
})
it('should not throw when stopping non-existent session', () => {
const svc = new ConversationService()
expect(() => svc.stopSession('no-such-session')).not.toThrow()
})
it('should not throw when registering callback for non-existent session', () => {
const svc = new ConversationService()
expect(() => svc.onOutput('no-such-session', () => {})).not.toThrow()
})
it('should ignore stale process exits after a session restarts', async () => {
const svc = new ConversationService()
const oldProc = { pid: 1 } as any
const newProc = { pid: 2 } as any
;(svc as any).sessions.set('session-restart', {
proc: newProc,
outputCallbacks: [],
workDir: process.cwd(),
permissionMode: 'bypassPermissions',
sdkToken: 'token',
sdkSocket: null,
pendingOutbound: [],
stderrLines: [],
sdkMessages: [],
pendingPermissionRequests: new Map(),
})
await (svc as any).handleProcessExit('session-restart', oldProc, 143)
expect(svc.hasSession('session-restart')).toBe(true)
await (svc as any).handleProcessExit('session-restart', newProc, 0)
expect(svc.hasSession('session-restart')).toBe(false)
})
it('should retain SDK init metadata after recent message trimming', () => {
const svc = new ConversationService()
;(svc as any).sessions.set('session-init-retention', {
proc: { pid: 1 },
outputCallbacks: [],
workDir: process.cwd(),
permissionMode: 'default',
sdkToken: 'token',
sdkSocket: null,
pendingOutbound: [],
stderrLines: [],
sdkMessages: [],
initMessage: null,
pendingPermissionRequests: new Map(),
})
;(svc as any).handleSdkPayload('session-init-retention', JSON.stringify({
type: 'system',
subtype: 'init',
model: 'mock-opus',
claude_code_version: 'test-version',
slash_commands: ['help', 'context'],
}))
for (let i = 0; i < 45; i++) {
;(svc as any).handleSdkPayload('session-init-retention', JSON.stringify({
type: 'stream_event',
event: { type: 'message_delta', index: i },
}))
}
expect(svc.getRecentSdkMessages('session-init-retention').some((message) => message.subtype === 'init')).toBe(false)
expect(svc.getSessionInitMessage('session-init-retention')).toMatchObject({
model: 'mock-opus',
claude_code_version: 'test-version',
slash_commands: ['help', 'context'],
})
})
it('should reconstruct usage and metadata from a persisted transcript', async () => {
const previousConfigDir = process.env.CLAUDE_CONFIG_DIR
const previousAnthropicApiKey = process.env.ANTHROPIC_API_KEY
const tmpConfigDir = await fs.mkdtemp(path.join(os.tmpdir(), 'claude-transcript-'))
const workDir = await fs.mkdtemp(path.join(os.tmpdir(), 'claude-workdir-'))
process.env.CLAUDE_CONFIG_DIR = tmpConfigDir
process.env.ANTHROPIC_API_KEY = 'test-key'
try {
const svc = new SessionService()
const { sessionId } = await svc.createSession(workDir)
const found = await svc.findSessionFile(sessionId)
expect(found).not.toBeNull()
await fs.appendFile(found!.filePath, JSON.stringify({
type: 'assistant',
uuid: crypto.randomUUID(),
timestamp: '2026-04-27T12:00:00.000Z',
cwd: workDir,
version: '999.0.0-test',
message: {
role: 'assistant',
model: 'mock-model',
content: [{ type: 'text', text: 'hello' }],
usage: {
input_tokens: 1234,
output_tokens: 56,
cache_read_input_tokens: 7,
cache_creation_input_tokens: 8,
server_tool_use: { web_search_requests: 1 },
},
},
}) + '\n')
const metadata = await svc.getTranscriptMetadata(sessionId)
const usage = await svc.getTranscriptUsage(sessionId)
expect(metadata).toMatchObject({
cwd: workDir,
version: '999.0.0-test',
model: 'mock-model',
})
expect(usage).toMatchObject({
source: 'transcript',
totalInputTokens: 1234,
totalOutputTokens: 56,
totalCacheReadInputTokens: 7,
totalCacheCreationInputTokens: 8,
totalWebSearchRequests: 1,
})
expect(usage?.models[0]?.model).toBe('mock-model')
} finally {
if (previousConfigDir === undefined) {
delete process.env.CLAUDE_CONFIG_DIR
} else {
process.env.CLAUDE_CONFIG_DIR = previousConfigDir
}
if (previousAnthropicApiKey === undefined) {
delete process.env.ANTHROPIC_API_KEY
} else {
process.env.ANTHROPIC_API_KEY = previousAnthropicApiKey
}
await fs.rm(tmpConfigDir, { recursive: true, force: true })
await fs.rm(workDir, { recursive: true, force: true })
}
})
it('should reconstruct Sonnet 4.6 transcript usage before CLI config is initialized', async () => {
const previousConfigDir = process.env.CLAUDE_CONFIG_DIR
const previousNodeEnv = process.env.NODE_ENV
const tmpConfigDir = await fs.mkdtemp(path.join(os.tmpdir(), 'claude-transcript-sonnet-'))
const workDir = await fs.mkdtemp(path.join(os.tmpdir(), 'claude-workdir-sonnet-'))
process.env.CLAUDE_CONFIG_DIR = tmpConfigDir
process.env.NODE_ENV = 'development'
try {
const svc = new SessionService()
const { sessionId } = await svc.createSession(workDir)
const found = await svc.findSessionFile(sessionId)
expect(found).not.toBeNull()
await fs.appendFile(found!.filePath, JSON.stringify({
type: 'assistant',
uuid: crypto.randomUUID(),
timestamp: '2026-04-27T12:00:00.000Z',
cwd: workDir,
version: '999.0.0-test',
message: {
role: 'assistant',
model: 'claude-sonnet-4-6',
content: [{ type: 'text', text: 'hello' }],
usage: {
input_tokens: 100,
output_tokens: 20,
},
},
}) + '\n')
const usage = await svc.getTranscriptUsage(sessionId)
const contextEstimate = await svc.getTranscriptContextEstimate(sessionId)
expect(usage?.models[0]?.model).toBe('claude-sonnet-4-6')
expect(usage?.models[0]?.contextWindow).toBe(200_000)
expect(contextEstimate?.model).toBe('claude-sonnet-4-6')
expect(contextEstimate?.totalTokens).toBe(120)
expect(contextEstimate?.rawMaxTokens).toBe(200_000)
expect(contextEstimate?.categories.some((category) => category.name === 'Output tokens' && category.tokens === 20)).toBe(true)
} finally {
if (previousConfigDir === undefined) {
delete process.env.CLAUDE_CONFIG_DIR
} else {
process.env.CLAUDE_CONFIG_DIR = previousConfigDir
}
if (previousNodeEnv === undefined) {
delete process.env.NODE_ENV
} else {
process.env.NODE_ENV = previousNodeEnv
}
await fs.rm(tmpConfigDir, { recursive: true, force: true })
await fs.rm(workDir, { recursive: true, force: true })
}
})
})
// ============================================================================
// WebSocket integration tests (with mock CLI using the SDK websocket protocol)
// ============================================================================
describe('WebSocket Chat Integration', () => {
let server: ReturnType<typeof Bun.serve>
let baseUrl: string
let wsUrl: string
let tmpDir: string
function git(cwd: string, ...args: string[]): string {
return execFileSync('git', args, {
cwd,
encoding: 'utf8',
})
}
async function createCleanGitRepo(): Promise<string> {
const workDir = path.join(
tmpDir,
`repo-${Date.now()}-${Math.random().toString(36).slice(2)}`,
)
await fs.mkdir(workDir, { recursive: true })
git(workDir, 'init')
git(workDir, 'config', 'user.email', 'conversations@example.com')
git(workDir, 'config', 'user.name', 'Conversations Test')
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
}
async function withMockInitMode<T>(
mode: string | undefined,
callback: () => Promise<T>,
): Promise<T> {
const previousMode = process.env.MOCK_SDK_INIT_MODE
if (mode) {
process.env.MOCK_SDK_INIT_MODE = mode
} else {
delete process.env.MOCK_SDK_INIT_MODE
}
try {
return await callback()
} finally {
if (previousMode === undefined) {
delete process.env.MOCK_SDK_INIT_MODE
} else {
process.env.MOCK_SDK_INIT_MODE = previousMode
}
}
}
async function withMockInitDelay<T>(
delayMs: number | undefined,
callback: () => Promise<T>,
): Promise<T> {
const previousDelay = process.env.MOCK_SDK_INIT_DELAY_MS
if (delayMs && delayMs > 0) {
process.env.MOCK_SDK_INIT_DELAY_MS = String(delayMs)
} else {
delete process.env.MOCK_SDK_INIT_DELAY_MS
}
try {
return await callback()
} finally {
if (previousDelay === undefined) {
delete process.env.MOCK_SDK_INIT_DELAY_MS
} else {
process.env.MOCK_SDK_INIT_DELAY_MS = previousDelay
}
}
}
async function withMockStreamDelay<T>(
delayMs: number | undefined,
callback: () => Promise<T>,
): Promise<T> {
const previousDelay = process.env.MOCK_SDK_STREAM_DELAY_MS
if (delayMs && delayMs > 0) {
process.env.MOCK_SDK_STREAM_DELAY_MS = String(delayMs)
} else {
delete process.env.MOCK_SDK_STREAM_DELAY_MS
}
try {
return await callback()
} finally {
if (previousDelay === undefined) {
delete process.env.MOCK_SDK_STREAM_DELAY_MS
} else {
process.env.MOCK_SDK_STREAM_DELAY_MS = previousDelay
}
}
}
async function withMockMcpStatusDelay<T>(
delayMs: number | undefined,
callback: () => Promise<T>,
): Promise<T> {
const previousDelay = process.env.MOCK_SDK_MCP_STATUS_DELAY_MS
if (delayMs && delayMs > 0) {
process.env.MOCK_SDK_MCP_STATUS_DELAY_MS = String(delayMs)
} else {
delete process.env.MOCK_SDK_MCP_STATUS_DELAY_MS
}
try {
return await callback()
} finally {
if (previousDelay === undefined) {
delete process.env.MOCK_SDK_MCP_STATUS_DELAY_MS
} else {
process.env.MOCK_SDK_MCP_STATUS_DELAY_MS = previousDelay
}
}
}
async function withMockExitAfterFirstUser<T>(
delayMs: number | undefined,
callback: () => Promise<T>,
): Promise<T> {
const previousDelay = process.env.MOCK_SDK_EXIT_AFTER_FIRST_USER_MS
if (delayMs && delayMs > 0) {
process.env.MOCK_SDK_EXIT_AFTER_FIRST_USER_MS = String(delayMs)
} else {
delete process.env.MOCK_SDK_EXIT_AFTER_FIRST_USER_MS
}
try {
return await callback()
} finally {
if (previousDelay === undefined) {
delete process.env.MOCK_SDK_EXIT_AFTER_FIRST_USER_MS
} else {
process.env.MOCK_SDK_EXIT_AFTER_FIRST_USER_MS = previousDelay
}
}
}
async function withMockStartupStdoutExit<T>(
stdout: string,
exitDelayMs: number,
callback: () => Promise<T>,
): Promise<T> {
const previousStdout = process.env.MOCK_SDK_STARTUP_STDOUT
const previousExitDelay = process.env.MOCK_SDK_EXIT_BEFORE_SDK_MS
process.env.MOCK_SDK_STARTUP_STDOUT = stdout
process.env.MOCK_SDK_EXIT_BEFORE_SDK_MS = String(exitDelayMs)
try {
return await callback()
} finally {
if (previousStdout === undefined) {
delete process.env.MOCK_SDK_STARTUP_STDOUT
} else {
process.env.MOCK_SDK_STARTUP_STDOUT = previousStdout
}
if (previousExitDelay === undefined) {
delete process.env.MOCK_SDK_EXIT_BEFORE_SDK_MS
} else {
process.env.MOCK_SDK_EXIT_BEFORE_SDK_MS = previousExitDelay
}
}
}
async function runTurn(sessionId: string, content: string, allowError = false): Promise<any[]> {
const messages: any[] = []
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
ws.close()
reject(new Error(`Timed out waiting for completion for session ${sessionId}`))
}, 30000)
ws.onmessage = (e) => {
const msg = JSON.parse(e.data as string)
messages.push(msg)
if (msg.type === 'connected') {
ws.send(JSON.stringify({ type: 'user_message', content }))
}
if (msg.type === 'error') {
clearTimeout(timeout)
ws.close()
if (allowError) {
resolve()
} else {
reject(new Error(msg.message))
}
}
if (msg.type === 'message_complete') {
clearTimeout(timeout)
ws.close()
resolve()
}
}
ws.onerror = () => {
clearTimeout(timeout)
ws.close()
reject(new Error(`WebSocket error for session ${sessionId}`))
}
})
return messages
}
async function runTurnUntilComplete(sessionId: string, content: string): Promise<any[]> {
const messages: any[] = []
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
ws.close()
reject(new Error(`Timed out waiting for terminal event for session ${sessionId}`))
}, 10000)
ws.onmessage = (e) => {
const msg = JSON.parse(e.data as string)
messages.push(msg)
if (msg.type === 'connected') {
ws.send(JSON.stringify({ type: 'user_message', content }))
}
if (msg.type === 'message_complete') {
clearTimeout(timeout)
ws.close()
resolve()
}
}
ws.onerror = () => {
clearTimeout(timeout)
ws.close()
reject(new Error(`WebSocket error for session ${sessionId}`))
}
})
return messages
}
async function waitUntil(
predicate: () => boolean | Promise<boolean>,
label: string,
timeoutMs = 8000,
): Promise<void> {
const startedAt = Date.now()
while (Date.now() - startedAt < timeoutMs) {
if (await predicate()) return
await new Promise((resolve) => setTimeout(resolve, 50))
}
throw new Error(`Timed out waiting for ${label}`)
}
const originalCliPath = process.env.CLAUDE_CLI_PATH
beforeAll(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'claude-conv-'))
process.env.CLAUDE_CONFIG_DIR = tmpDir
process.env.CLAUDE_CLI_PATH = fileURLToPath(
new URL('./fixtures/mock-sdk-cli.ts', import.meta.url)
)
await fs.mkdir(path.join(tmpDir, 'projects'), { recursive: true })
const port = 15000 + Math.floor(Math.random() * 1000)
const { startServer } = await import('../index.js')
server = startServer(port, '127.0.0.1')
baseUrl = `http://127.0.0.1:${port}`
wsUrl = `ws://127.0.0.1:${port}`
})
afterAll(async () => {
server?.stop(true)
if (tmpDir) {
await rmWithRetry(tmpDir)
}
if (originalCliPath) {
process.env.CLAUDE_CLI_PATH = originalCliPath
} else {
delete process.env.CLAUDE_CLI_PATH
}
delete process.env.CLAUDE_CONFIG_DIR
})
it('should connect and receive connected event', async () => {
const messages: any[] = []
const ws = new WebSocket(`${wsUrl}/ws/chat-test-1`)
await new Promise<void>((resolve) => {
ws.onmessage = (e) => {
messages.push(JSON.parse(e.data as string))
if (messages.length >= 1) {
ws.close()
resolve()
}
}
ws.onerror = () => {
ws.close()
resolve()
}
setTimeout(() => {
ws.close()
resolve()
}, 3000)
})
expect(messages[0].type).toBe('connected')
expect(messages[0].sessionId).toBe('chat-test-1')
})
it('should handle stop_generation and return idle status', async () => {
const messages: any[] = []
const ws = new WebSocket(`${wsUrl}/ws/chat-test-2`)
await new Promise<void>((resolve) => {
ws.onmessage = (e) => {
const msg = JSON.parse(e.data as string)
messages.push(msg)
if (msg.type === 'connected') {
ws.send(JSON.stringify({ type: 'stop_generation' }))
}
if (msg.type === 'status' && msg.state === 'idle') {
ws.close()
resolve()
}
}
ws.onerror = () => {
ws.close()
resolve()
}
setTimeout(() => {
ws.close()
resolve()
}, 3000)
})
expect(messages.some((m) => m.type === 'status' && m.state === 'idle')).toBe(true)
})
it('should send user_message and receive streamed SDK response', async () => {
const messages: any[] = []
const ws = new WebSocket(`${wsUrl}/ws/chat-test-3`)
await new Promise<void>((resolve) => {
ws.onmessage = (e) => {
const msg = JSON.parse(e.data as string)
messages.push(msg)
if (msg.type === 'connected') {
ws.send(
JSON.stringify({ type: 'user_message', content: 'Hello from test' })
)
}
// Wait until we receive completion after the streamed response
if (
msg.type === 'message_complete' &&
messages.some((entry) => entry.type === 'thinking')
) {
ws.close()
resolve()
}
}
ws.onerror = () => {
ws.close()
resolve()
}
setTimeout(() => {
ws.close()
resolve()
}, 5000)
})
const types = messages.map((m) => m.type)
expect(types).toContain('connected')
expect(types).toContain('status')
// Mock SDK flow produces text streaming, thinking, and completion events.
expect(types).toContain('content_start')
expect(types).toContain('content_delta')
expect(types).toContain('thinking')
expect(types).toContain('message_complete')
// Verify thinking was first status
const statusMsgs = messages.filter((m) => m.type === 'status')
expect(statusMsgs[0].state).toBe('thinking')
})
it('emits a worktree startup status before launching a repository session', async () => {
const repoDir = await createCleanGitRepo()
const { sessionId } = await sessionService.createSession(repoDir, {
branch: 'feature/rail',
worktree: true,
})
const messages = await runTurn(sessionId, 'Hello from repository launch test')
const statusVerbs = messages
.filter((msg) => msg.type === 'status')
.map((msg) => msg.verb)
expect(statusVerbs).toContain('Creating worktree')
})
it('does not emit worktree startup status for an already materialized worktree session', async () => {
const repoDir = await createCleanGitRepo()
const { sessionId } = await sessionService.createSession(repoDir, {
branch: 'feature/rail',
worktree: true,
})
const launchInfo = await sessionService.getSessionLaunchInfo(sessionId)
const worktreePath = launchInfo?.repository?.worktreePath
expect(worktreePath).toBeTruthy()
await fs.mkdir(worktreePath!, { recursive: true })
await sessionService.appendSessionMetadata(sessionId, {
workDir: worktreePath!,
repository: launchInfo!.repository,
})
await sessionService.deletePlaceholderSessionFiles(sessionId, worktreePath!)
const messages = await runTurn(sessionId, 'Continue in the existing worktree')
const statusVerbs = messages
.filter((msg) => msg.type === 'status')
.map((msg) => msg.verb)
expect(statusVerbs).toContain('Thinking')
expect(statusVerbs).not.toContain('Creating worktree')
})
it('keeps the default startup status for current-worktree repository sessions', async () => {
const repoDir = await createCleanGitRepo()
const { sessionId } = await sessionService.createSession(repoDir, {
branch: 'main',
worktree: false,
})
const messages = await runTurn(sessionId, 'Hello from current worktree launch test')
const statusVerbs = messages
.filter((msg) => msg.type === 'status')
.map((msg) => msg.verb)
expect(statusVerbs).toContain('Thinking')
expect(statusVerbs).not.toContain('Creating worktree')
})
it('emits the derived session title before the first response completes', async () => {
const sessionId = `title-fast-${crypto.randomUUID()}`
const messages: any[] = []
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
ws.close()
reject(new Error('Timed out waiting for derived session title'))
}, 5000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
messages.push(msg)
if (msg.type === 'connected') {
ws.send(JSON.stringify({
type: 'user_message',
content: '开始优化UI',
}))
return
}
if (msg.type === 'message_complete') {
clearTimeout(timeout)
ws.close()
resolve()
}
}
ws.onerror = () => {
clearTimeout(timeout)
reject(new Error(`WebSocket error for title session ${sessionId}`))
}
})
const titleIndex = messages.findIndex((msg) => msg.type === 'session_title_updated')
const completionIndex = messages.findIndex((msg) => msg.type === 'message_complete')
expect(titleIndex).toBeGreaterThan(-1)
expect(completionIndex).toBeGreaterThan(-1)
expect(messages[titleIndex].title).toBe('开始优化UI')
expect(titleIndex).toBeLessThan(completionIndex)
})
it('uses the /goal objective for the derived session title', async () => {
const sessionId = `title-goal-${crypto.randomUUID()}`
const messages: any[] = []
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
ws.close()
reject(new Error('Timed out waiting for goal title'))
}, 5000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
messages.push(msg)
if (msg.type === 'connected') {
ws.send(JSON.stringify({
type: 'user_message',
content: '/goal ship the desktop goal card',
}))
return
}
if (msg.type === 'session_title_updated') {
clearTimeout(timeout)
ws.close()
resolve()
}
}
ws.onerror = () => {
clearTimeout(timeout)
reject(new Error(`WebSocket error for goal title session ${sessionId}`))
}
})
const title = messages.find((msg) => msg.type === 'session_title_updated')?.title
expect(title).toBe('ship the desktop goal card')
})
it('should start desktop sessions with disabled thinking when configured', async () => {
const sessionId = `chat-thinking-disabled-${crypto.randomUUID()}`
const originalStartSession = conversationService.startSession.bind(conversationService)
const startOptions: Array<{ thinking?: string; model?: string }> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
if (sid === sessionId) {
startOptions.push({ thinking: options?.thinking, model: options?.model })
}
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
try {
await fs.writeFile(
path.join(tmpDir, 'settings.json'),
JSON.stringify({ alwaysThinkingEnabled: false }, null, 2),
'utf-8',
)
const messages = await runTurn(sessionId, 'Hello without thinking')
expect(messages.some((m) => m.type === 'message_complete')).toBe(true)
expect(startOptions).toEqual([{ thinking: 'disabled', model: undefined }])
} finally {
conversationService.startSession = originalStartSession as typeof conversationService.startSession
conversationService.stopSession(sessionId)
await fs.writeFile(path.join(tmpDir, 'settings.json'), '{}\n', 'utf-8')
}
})
it('should let the global Thinking setting control DeepSeek desktop sessions', async () => {
const providerService = new ProviderService()
const provider = await providerService.addProvider({
presetId: 'deepseek',
name: 'DeepSeek Thinking Toggle',
apiKey: 'key-deepseek-toggle',
baseUrl: 'https://api.deepseek.com/anthropic',
apiFormat: 'anthropic',
models: {
main: 'deepseek-v4-pro',
haiku: 'deepseek-v4-flash',
sonnet: 'deepseek-v4-pro',
opus: 'deepseek-v4-pro',
},
})
await providerService.activateProvider(provider.id)
const originalStartSession = conversationService.startSession.bind(conversationService)
const startOptions: Array<{
sessionId: string
thinking?: string
providerId?: string | null
}> = []
const sessionIds: string[] = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
if (sessionIds.includes(sid)) {
startOptions.push({
sessionId: sid,
thinking: options?.thinking,
providerId: options?.providerId,
})
}
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
try {
const disabledSessionId = `ds-think-off-${crypto.randomUUID()}`
sessionIds.push(disabledSessionId)
await fs.writeFile(
path.join(tmpDir, 'settings.json'),
JSON.stringify({ alwaysThinkingEnabled: false }, null, 2),
'utf-8',
)
const disabledMessages = await runTurn(disabledSessionId, 'DeepSeek with global thinking off')
expect(disabledMessages.some((m) => m.type === 'message_complete')).toBe(true)
const enabledSessionId = `ds-think-on-${crypto.randomUUID()}`
sessionIds.push(enabledSessionId)
await fs.writeFile(
path.join(tmpDir, 'settings.json'),
JSON.stringify({ alwaysThinkingEnabled: true }, null, 2),
'utf-8',
)
const enabledMessages = await runTurn(enabledSessionId, 'DeepSeek with global thinking on')
expect(enabledMessages.some((m) => m.type === 'message_complete')).toBe(true)
expect(startOptions).toEqual([
{
sessionId: disabledSessionId,
thinking: 'disabled',
providerId: provider.id,
},
{
sessionId: enabledSessionId,
thinking: undefined,
providerId: provider.id,
},
])
} finally {
conversationService.startSession = originalStartSession as typeof conversationService.startSession
for (const sessionId of sessionIds) {
conversationService.stopSession(sessionId)
}
await providerService.activateOfficial()
await fs.writeFile(path.join(tmpDir, 'settings.json'), '{}\n', 'utf-8')
}
}, 20_000)
it('should continue chat when SDK init arrives only after the first user turn', async () => {
const messages = await withMockInitMode('on_first_user', () =>
runTurn('chat-test-lazy-init', 'Hello after lazy init'),
)
expect(messages.some((m) => m.type === 'message_complete')).toBe(true)
expect(messages.some((m) => m.type === 'error')).toBe(false)
expect(
messages.some(
(m) => m.type === 'system_notification' && m.subtype === 'init',
),
).toBe(true)
})
it('should display CLI /cost local command output', async () => {
const messages = await runTurn(`chat-cost-${crypto.randomUUID()}`, '/cost')
expect(messages.some((m) => m.type === 'error')).toBe(false)
expect(
messages.some(
(m) =>
m.type === 'content_delta' &&
typeof m.text === 'string' &&
m.text.includes('Total cost: $0.0000'),
),
).toBe(true)
expect(messages.some((m) => m.type === 'message_complete')).toBe(true)
})
it('should display CLI /context local command output', async () => {
const messages = await runTurn(`chat-context-${crypto.randomUUID()}`, '/context')
expect(messages.some((m) => m.type === 'error')).toBe(false)
expect(
messages.some(
(m) =>
m.type === 'content_delta' &&
typeof m.text === 'string' &&
m.text.includes('## Context Usage'),
),
).toBe(true)
expect(messages.some((m) => m.type === 'message_complete')).toBe(true)
})
it('should expose structured session inspection data from the active CLI', async () => {
const sessionId = `chat-inspection-${crypto.randomUUID()}`
await runTurn(sessionId, 'hello before inspection')
const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/inspection`)
expect(res.status).toBe(200)
const body = await res.json() as any
expect(body.active).toBe(true)
expect(body.status.model).toBe('mock-opus')
expect(body.status.slashCommandCount).toBe(1)
expect(body.usage.costDisplay).toBe('$0.1234')
expect(body.usage.source).toBe('current_process')
expect(body.context.model).toBe('mock-opus')
expect(body.context.estimateOnly).toBe(true)
expect(body.status.mcpServers).toEqual([{ name: 'mock', status: 'connected' }])
const basicRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/inspection?includeContext=0`)
expect(basicRes.status).toBe(200)
const basicBody = await basicRes.json() as any
expect(basicBody.usage.source).toBe('current_process')
expect(basicBody.context).toBeUndefined()
})
it('should expose context-only inspection without waiting on mcp status', async () => {
await withMockMcpStatusDelay(2_000, async () => {
const sessionId = `chat-context-only-${crypto.randomUUID()}`
await runTurn(sessionId, 'hello before context-only inspection')
const startedAt = performance.now()
const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/inspection?includeContext=1&contextOnly=1`)
const elapsedMs = performance.now() - startedAt
expect(res.status).toBe(200)
const body = await res.json() as any
expect(body.context.model).toBe('mock-opus')
expect(body.context.estimateOnly).toBe(true)
expect(body.usage).toBeUndefined()
expect(elapsedMs).toBeLessThan(1_500)
})
})
it('should return initial context for a prewarmed empty session on the first inspection request', async () => {
await withMockInitDelay(500, async () => {
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
ws.close()
reject(new Error(`Timed out waiting for prewarm connection for ${sessionId}`))
}, 5_000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
if (msg.type === 'connected') {
clearTimeout(timeout)
ws.send(JSON.stringify({ type: 'prewarm_session' }))
resolve()
}
}
ws.onerror = () => {
clearTimeout(timeout)
ws.close()
reject(new Error(`WebSocket error for prewarm context session ${sessionId}`))
}
})
await waitUntil(
() => conversationService.hasSession(sessionId),
`prewarmed CLI process for ${sessionId}`,
)
const startedAt = performance.now()
const res = await fetch(`${baseUrl}/api/sessions/${sessionId}/inspection?includeContext=1&contextOnly=1`)
const elapsedMs = performance.now() - startedAt
expect(res.status).toBe(200)
const body = await res.json() as any
expect(body.context.model).toBe('mock-opus')
expect(body.context.totalTokens).toBeGreaterThan(0)
expect(body.context.percentage).toBe(13)
expect(body.context.categories.some((category: any) => category.name === 'System prompt')).toBe(true)
expect(body.errors).toEqual({})
expect(elapsedMs).toBeLessThan(2_000)
} finally {
ws.close()
conversationService.stopSession(sessionId)
}
})
}, 10_000)
it('should complete the client turn when the CLI exits after startup', async () => {
const messages = await withMockExitAfterFirstUser(50, () =>
runTurnUntilComplete(`chat-late-exit-${crypto.randomUUID()}`, 'trigger late exit'),
)
expect(
messages.some(
(m) =>
m.type === 'error' &&
m.code === 'CLI_ERROR' &&
typeof m.message === 'string' &&
m.message.includes('CLI process exited unexpectedly'),
),
).toBe(true)
expect(messages.some((m) => m.type === 'message_complete')).toBe(true)
expect(messages.at(-1)?.type).toBe('message_complete')
}, 15_000)
it('should not duplicate SDK API errors with the final error result', async () => {
const messages = await runTurnUntilComplete(
`chat-api-error-${crypto.randomUUID()}`,
'trigger api error',
)
const errors = messages.filter((m) => m.type === 'error')
expect(errors).toHaveLength(1)
expect(errors[0]).toMatchObject({
code: 'invalid_request',
message: 'Prompt is too long',
})
expect(messages.some((m) => m.type === 'message_complete')).toBe(true)
expect(messages.at(-1)?.type).toBe('message_complete')
}, 15_000)
it('should not add a CLI exit error after a reported SDK API error', async () => {
const messages = await runTurnUntilComplete(
`chat-api-error-exit-${crypto.randomUUID()}`,
'trigger api error then exit',
)
const errors = messages.filter((m) => m.type === 'error')
expect(errors).toHaveLength(1)
expect(errors[0]).toMatchObject({
code: 'invalid_request',
message: 'Prompt is too long',
})
expect(messages.some((m) => m.type === 'message_complete')).toBe(true)
expect(messages.at(-1)?.type).toBe('message_complete')
}, 15_000)
it('should handle permission_response without error', async () => {
const messages: any[] = []
const ws = new WebSocket(`${wsUrl}/ws/chat-test-4`)
await new Promise<void>((resolve) => {
ws.onmessage = (e) => {
const msg = JSON.parse(e.data as string)
messages.push(msg)
if (msg.type === 'connected') {
// Send a permission response (no active session, should not crash)
ws.send(
JSON.stringify({
type: 'permission_response',
requestId: 'test-req-1',
allowed: true,
})
)
// Give a moment then close
setTimeout(() => {
ws.close()
resolve()
}, 500)
}
}
ws.onerror = () => {
ws.close()
resolve()
}
setTimeout(() => {
ws.close()
resolve()
}, 3000)
})
// Should have received connected and no error
expect(messages[0].type).toBe('connected')
expect(messages.some((m) => m.type === 'error')).toBe(false)
})
it('should handle ping/pong', async () => {
const messages: any[] = []
const ws = new WebSocket(`${wsUrl}/ws/chat-test-5`)
await new Promise<void>((resolve) => {
ws.onmessage = (e) => {
const msg = JSON.parse(e.data as string)
messages.push(msg)
if (msg.type === 'connected') {
ws.send(JSON.stringify({ type: 'ping' }))
}
if (msg.type === 'pong') {
ws.close()
resolve()
}
}
ws.onerror = () => {
ws.close()
resolve()
}
setTimeout(() => {
ws.close()
resolve()
}, 3000)
})
expect(messages.some((m) => m.type === 'pong')).toBe(true)
})
it('should start a placeholder REST session and continue it on a later reconnect', async () => {
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const firstTurn = await runTurn(sessionId, 'reply with first')
expect(firstTurn.some((m) => m.type === 'message_complete')).toBe(true)
expect(firstTurn.some((m) => m.type === 'error')).toBe(false)
await new Promise((resolve) => setTimeout(resolve, 1000))
const secondTurn = await runTurn(sessionId, 'reply with second')
expect(secondTurn.some((m) => m.type === 'message_complete')).toBe(true)
expect(secondTurn.some((m) => m.type === 'error')).toBe(false)
})
it('should keep a long desktop session alive in a /tmp project across engineering turns', async () => {
const projectDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cc-haha-issue247-project-'))
let sessionId: string | undefined
try {
await fs.writeFile(
path.join(projectDir, 'package.json'),
JSON.stringify({ name: 'issue-247-repro', type: 'module' }, null, 2),
)
await fs.mkdir(path.join(projectDir, 'src'), { recursive: true })
await fs.writeFile(
path.join(projectDir, 'src', 'index.ts'),
'export function greet(name: string) { return `hello ${name}` }\n',
)
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: projectDir }),
})
expect(createRes.status).toBe(201)
;({ sessionId } = await createRes.json() as { sessionId: string })
const prompts = [
'Inspect this TypeScript project and summarize what you see.',
'Plan a small change to add a farewell helper.',
'Implement the helper in src/index.ts.',
'Review whether the exported functions are easy to test.',
'Suggest the next regression test for this project.',
]
for (const prompt of prompts) {
const messages = await runTurn(sessionId, prompt)
expect(messages.some((m) => m.type === 'error')).toBe(false)
expect(messages.some((m) => m.type === 'message_complete')).toBe(true)
}
} finally {
if (sessionId) {
await conversationService.stopSession(sessionId)
}
await rmWithRetry(projectDir)
}
}, 20_000)
it('should clear a desktop session without sending /clear to the CLI turn loop', async () => {
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const firstTurn = await runTurn(sessionId, 'message before clear')
expect(firstTurn.some((m) => m.type === 'message_complete')).toBe(true)
const clearTurn = await runTurn(sessionId, '/clear')
expect(
clearTurn.some(
(m) => m.type === 'system_notification' && m.subtype === 'session_cleared',
),
).toBe(true)
expect(clearTurn.some((m) => m.type === 'content_delta')).toBe(false)
const messagesRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/messages`)
expect(messagesRes.status).toBe(200)
const body = await messagesRes.json() as { messages: unknown[] }
expect(body.messages).toEqual([])
})
it('should reject /clear arguments without clearing the desktop session', async () => {
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
await runTurn(sessionId, 'message before invalid clear')
const clearTurn = await runTurn(sessionId, '/clear please keep this', true)
expect(
clearTurn.some(
(m) => m.type === 'error' && m.code === 'INVALID_SLASH_COMMAND_ARGS',
),
).toBe(true)
expect(
clearTurn.some(
(m) => m.type === 'system_notification' && m.subtype === 'session_cleared',
),
).toBe(false)
const nextTurn = await runTurn(sessionId, 'message after invalid clear')
expect(nextTurn.some((m) => m.type === 'message_complete')).toBe(true)
})
it('should include desktop service diagnostics when CLI startup fails', async () => {
const workDir = await fs.mkdtemp(path.join(os.tmpdir(), 'claude-startup-missing-workdir-'))
const canonicalWorkDir = await fs.realpath(workDir)
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
await fs.rm(workDir, { recursive: true, force: true })
const messages = await runTurn(sessionId, 'trigger startup diagnostics', true)
const error = messages.find((msg) => msg.type === 'error')
expect(error).toMatchObject({
code: 'WORKDIR_INVALID',
})
expect(error?.message).toContain('Desktop service diagnostics:')
expect(error?.message).toContain(`sessionId: ${sessionId}`)
expect(error?.message).toContain(`workDir: ${canonicalWorkDir}`)
expect(error?.message).toContain('runtimeOverride: (none)')
expect(error?.message).toContain('activeProviderId:')
expect(error?.message).toContain('configuredProviders:')
})
it('should include CLI stdout diagnostics when startup exits before SDK messages', async () => {
const sessionId = `chat-startup-stdout-${crypto.randomUUID()}`
const messages = await withMockStartupStdoutExit(
'provider rejected request: invalid model id',
25,
() => runTurn(sessionId, 'trigger startup stdout diagnostics', true),
)
const error = messages.find((msg) => msg.type === 'error')
expect(error).toMatchObject({
code: 'CLI_START_FAILED',
})
expect(error?.message).toContain(
'CLI exited during startup (code 1): provider rejected request: invalid model id',
)
expect(error?.message).toContain('Desktop service diagnostics:')
}, 10_000)
it('should prewarm the CLI before the first user turn and reuse that process', async () => {
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const originalStartSession = conversationService.startSession.bind(conversationService)
const startCalls: Array<{ sessionId: string }> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid })
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
const messages: any[] = []
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
let connected = false
let awaitingCompletion = false
let preUserMessageCount = 0
let resolveCompletion: (() => void) | null = null
let rejectCompletion: ((err: Error) => void) | null = null
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(`Timed out waiting for prewarm connection for session ${sessionId}`))
}, 5000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
messages.push(msg)
if (msg.type === 'connected' && !connected) {
connected = true
clearTimeout(timeout)
ws.send(JSON.stringify({ type: 'prewarm_session' }))
resolve()
return
}
if (msg.type === 'error') {
const err = new Error(msg.message)
clearTimeout(timeout)
rejectCompletion?.(err)
reject(err)
return
}
if (awaitingCompletion && msg.type === 'message_complete') {
resolveCompletion?.()
}
}
ws.onerror = () => {
const err = new Error(`WebSocket error for prewarm session ${sessionId}`)
clearTimeout(timeout)
rejectCompletion?.(err)
reject(err)
}
})
await waitUntil(
() => startCalls.length === 1 && conversationService.hasSession(sessionId),
`prewarmed CLI process for ${sessionId}`,
)
await waitUntil(async () => {
const commandsRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/slash-commands`)
if (!commandsRes.ok) return false
const { commands } = await commandsRes.json() as { commands?: Array<{ name: string }> }
if (!Array.isArray(commands)) return false
return commands.some((command) => command.name === 'help')
}, `prewarmed slash commands for ${sessionId}`)
preUserMessageCount = messages.length
expect(
messages
.slice(0, preUserMessageCount)
.some((msg) => ['content_start', 'content_delta', 'thinking', 'message_complete'].includes(msg.type)),
).toBe(false)
awaitingCompletion = true
const completion = new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(`Timed out waiting for completion after prewarm for session ${sessionId}`))
}, 10_000)
resolveCompletion = () => {
clearTimeout(timeout)
resolve()
}
rejectCompletion = (err) => {
clearTimeout(timeout)
reject(err)
}
})
ws.send(JSON.stringify({ type: 'user_message', content: 'first turn after prewarm' }))
await completion
expect(startCalls).toHaveLength(1)
expect(messages.some((msg) => msg.type === 'content_delta')).toBe(true)
expect(messages.some((msg) => msg.type === 'message_complete')).toBe(true)
expect(messages.some((msg) => msg.type === 'error')).toBe(false)
} finally {
ws.close()
conversationService.startSession = originalStartSession
conversationService.stopSession(sessionId)
}
}, 20_000)
it('should pass the active provider id into default desktop sessions', async () => {
const providerService = new ProviderService()
const provider = await providerService.addProvider({
presetId: 'jiekouai',
name: 'Active Default Provider',
apiKey: 'key-active-default',
baseUrl: 'https://api.jiekou.ai/anthropic',
apiFormat: 'anthropic',
models: {
main: 'active-main',
haiku: 'active-haiku',
sonnet: 'active-sonnet',
opus: 'active-opus',
},
})
await providerService.activateProvider(provider.id)
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const originalStartSession = conversationService.startSession.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
try {
const messages = await runTurn(sessionId, 'first turn with active provider')
expect(messages.some((msg) => msg.type === 'message_complete')).toBe(true)
expect(startCalls).toHaveLength(1)
expect(startCalls[0]).toMatchObject({
sessionId,
options: {
providerId: provider.id,
},
})
} finally {
conversationService.startSession = originalStartSession
conversationService.stopSession(sessionId)
await providerService.activateOfficial()
}
}, 20_000)
it('should isolate provider runtime overrides across parallel sessions', async () => {
const providerService = new ProviderService()
const providerA = await providerService.addProvider({
presetId: 'custom',
name: 'Parallel Provider A',
apiKey: 'key-parallel-a',
baseUrl: 'http://127.0.0.1:1/anthropic',
apiFormat: 'anthropic',
models: {
main: 'parallel-a-main',
haiku: 'parallel-a-haiku',
sonnet: 'parallel-a-sonnet',
opus: 'parallel-a-opus',
},
})
const providerB = await providerService.addProvider({
presetId: 'custom',
name: 'Parallel Provider B',
apiKey: 'key-parallel-b',
baseUrl: 'http://127.0.0.1:1/anthropic',
apiFormat: 'anthropic',
models: {
main: 'parallel-b-main',
haiku: 'parallel-b-haiku',
sonnet: 'parallel-b-sonnet',
opus: 'parallel-b-opus',
},
})
const createSession = async () => {
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
return sessionId
}
const [sessionA, sessionB] = await Promise.all([createSession(), createSession()])
const originalStartSession = conversationService.startSession.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
const runRuntimeTurn = (
sessionId: string,
providerId: string,
modelId: string,
content: string,
) => new Promise<void>((resolve, reject) => {
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
const timeout = setTimeout(() => {
ws.close()
reject(new Error(`Timed out waiting for parallel runtime turn for ${sessionId}`))
}, 10_000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
if (msg.type === 'connected') {
ws.send(JSON.stringify({
type: 'set_runtime_config',
providerId,
modelId,
}))
ws.send(JSON.stringify({ type: 'user_message', content }))
return
}
if (msg.type === 'error') {
clearTimeout(timeout)
ws.close()
reject(new Error(msg.message))
return
}
if (msg.type === 'message_complete') {
clearTimeout(timeout)
ws.close()
resolve()
}
}
ws.onerror = () => {
clearTimeout(timeout)
reject(new Error(`WebSocket error for parallel runtime session ${sessionId}`))
}
})
try {
await Promise.all([
runRuntimeTurn(sessionA, providerA.id, 'parallel-a-sonnet', 'turn on provider a'),
runRuntimeTurn(sessionB, providerB.id, 'parallel-b-opus', 'turn on provider b'),
])
expect(startCalls).toHaveLength(2)
expect(startCalls.find((call) => call.sessionId === sessionA)).toMatchObject({
options: {
providerId: providerA.id,
model: 'parallel-a-sonnet',
},
})
expect(startCalls.find((call) => call.sessionId === sessionB)).toMatchObject({
options: {
providerId: providerB.id,
model: 'parallel-b-opus',
},
})
} finally {
conversationService.startSession = originalStartSession
conversationService.stopSession(sessionA)
conversationService.stopSession(sessionB)
}
}, 20_000)
it('should restart a prewarm that began before runtime config arrived', async () => {
const providerService = new ProviderService()
const provider = await providerService.addProvider({
presetId: 'custom',
name: 'Provider Late Runtime',
apiKey: 'key-late-runtime',
baseUrl: 'http://127.0.0.1:1/anthropic',
apiFormat: 'anthropic',
models: {
main: 'late-main',
haiku: 'late-haiku',
sonnet: 'late-sonnet',
opus: 'late-opus',
},
})
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const originalStartSession = conversationService.startSession.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
let releaseFirstStart!: () => void
const firstStartGate = new Promise<void>((resolve) => {
releaseFirstStart = resolve
})
let markFirstStart!: () => void
const firstStartEntered = new Promise<void>((resolve) => {
markFirstStart = resolve
})
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
if (startCalls.length === 1) {
markFirstStart()
await firstStartGate
}
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
const messages: any[] = []
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(`Timed out waiting for late runtime prewarm connection for session ${sessionId}`))
}, 5000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
messages.push(msg)
if (msg.type === 'connected') {
clearTimeout(timeout)
resolve()
}
if (msg.type === 'error') {
clearTimeout(timeout)
reject(new Error(msg.message))
}
}
ws.onerror = () => {
clearTimeout(timeout)
reject(new Error(`WebSocket error for late runtime prewarm session ${sessionId}`))
}
})
ws.send(JSON.stringify({ type: 'prewarm_session' }))
await firstStartEntered
ws.send(JSON.stringify({
type: 'set_runtime_config',
providerId: provider.id,
modelId: 'late-sonnet',
}))
releaseFirstStart()
await waitUntil(async () => startCalls.length >= 2, `runtime restart for ${sessionId}`)
await waitUntil(
async () => messages.some((msg) => msg.type === 'status' && msg.state === 'idle'),
`runtime restart idle status for ${sessionId}`,
)
expect(startCalls[0]).toMatchObject({ sessionId })
expect(startCalls[0]?.options?.providerId).toBeNull()
expect(startCalls[1]).toMatchObject({
sessionId,
options: {
providerId: provider.id,
model: 'late-sonnet',
},
})
} finally {
ws.close()
conversationService.startSession = originalStartSession
conversationService.stopSession(sessionId)
}
}, 20_000)
it('should wait for a runtime restart queued during first-turn startup before sending that turn', async () => {
const providerService = new ProviderService()
const provider = await providerService.addProvider({
presetId: 'custom',
name: 'Provider First Turn Runtime',
apiKey: 'key-first-turn-runtime',
baseUrl: 'http://127.0.0.1:1/anthropic',
apiFormat: 'anthropic',
models: {
main: 'first-turn-main',
haiku: 'first-turn-haiku',
sonnet: 'first-turn-sonnet',
opus: 'first-turn-opus',
},
})
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const originalStartSession = conversationService.startSession.bind(conversationService)
const originalSendMessage = conversationService.sendMessage.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
const sendCalls: Array<{ content: string; startCallCount: number }> = []
let releaseFirstStart!: () => void
const firstStartGate = new Promise<void>((resolve) => {
releaseFirstStart = resolve
})
let markFirstStart!: () => void
const firstStartEntered = new Promise<void>((resolve) => {
markFirstStart = resolve
})
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
if (startCalls.length === 1) {
markFirstStart()
await firstStartGate
}
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
conversationService.sendMessage = (function patchedSendMessage(
sid: string,
content: string,
attachments?: any,
) {
sendCalls.push({ content, startCallCount: startCalls.length })
return originalSendMessage(sid, content, attachments)
}) as typeof conversationService.sendMessage
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
const messages: any[] = []
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(`Timed out waiting for first-turn runtime synchronization for session ${sessionId}`))
}, 15_000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
messages.push(msg)
if (msg.type === 'connected') {
ws.send(JSON.stringify({ type: 'prewarm_session' }))
void firstStartEntered.then(() => {
ws.send(JSON.stringify({ type: 'user_message', content: 'first turn while runtime changes' }))
ws.send(JSON.stringify({
type: 'set_runtime_config',
providerId: provider.id,
modelId: 'first-turn-sonnet',
}))
releaseFirstStart()
})
return
}
if (msg.type === 'error') {
clearTimeout(timeout)
reject(new Error(msg.message))
return
}
if (msg.type === 'message_complete') {
clearTimeout(timeout)
resolve()
}
}
ws.onerror = () => {
clearTimeout(timeout)
reject(new Error(`WebSocket error for first-turn runtime synchronization session ${sessionId}`))
}
})
expect(startCalls).toHaveLength(2)
expect(startCalls[0]).toMatchObject({ sessionId })
expect(startCalls[0]?.options?.providerId).toBeNull()
expect(startCalls[1]).toMatchObject({
sessionId,
options: {
providerId: provider.id,
model: 'first-turn-sonnet',
},
})
expect(sendCalls).toEqual([{
content: 'first turn while runtime changes',
startCallCount: 2,
}])
expect(messages.some((msg) => msg.type === 'content_delta')).toBe(true)
} finally {
ws.close()
conversationService.startSession = originalStartSession
conversationService.sendMessage = originalSendMessage
conversationService.stopSession(sessionId)
}
}, 20_000)
it('should keep the session idle in the UI while applying a runtime-only model switch', async () => {
const providerService = new ProviderService()
const provider = await providerService.addProvider({
presetId: 'custom',
name: 'Provider Idle Runtime',
apiKey: 'key-idle-runtime',
baseUrl: 'http://127.0.0.1:1/anthropic',
apiFormat: 'anthropic',
models: {
main: 'idle-main',
haiku: 'idle-haiku',
sonnet: 'idle-sonnet',
opus: 'idle-opus',
},
})
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const originalStartSession = conversationService.startSession.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
const messages: any[] = []
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(`Timed out waiting for idle runtime switch connection for session ${sessionId}`))
}, 5000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
messages.push(msg)
if (msg.type === 'connected') {
clearTimeout(timeout)
ws.send(JSON.stringify({ type: 'prewarm_session' }))
resolve()
}
if (msg.type === 'error') {
clearTimeout(timeout)
reject(new Error(msg.message))
}
}
ws.onerror = () => {
clearTimeout(timeout)
reject(new Error(`WebSocket error for idle runtime switch session ${sessionId}`))
}
})
await waitUntil(
() => startCalls.length === 1 && conversationService.hasSession(sessionId),
`prewarmed CLI process for idle runtime switch ${sessionId}`,
)
await waitUntil(async () => {
const commandsRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/slash-commands`)
if (!commandsRes.ok) return false
const { commands } = await commandsRes.json() as { commands?: Array<{ name: string }> }
return Array.isArray(commands) && commands.some((command) => command.name === 'help')
}, `prewarmed slash commands for idle runtime switch ${sessionId}`)
const switchStartIndex = messages.length
ws.send(JSON.stringify({
type: 'set_runtime_config',
providerId: provider.id,
modelId: 'idle-sonnet',
}))
await waitUntil(
async () => messages.slice(switchStartIndex).some((msg) => msg.type === 'status' && msg.state === 'idle'),
`idle runtime switch completion for ${sessionId}`,
)
expect(startCalls).toHaveLength(2)
expect(startCalls[1]).toMatchObject({
sessionId,
options: {
providerId: provider.id,
model: 'idle-sonnet',
},
})
expect(
messages
.slice(switchStartIndex)
.filter((msg) => msg.type === 'status')
.map((msg) => msg.state),
).toEqual(['idle'])
expect(messages.slice(switchStartIndex).some((msg) => msg.type === 'error')).toBe(false)
} finally {
ws.close()
conversationService.startSession = originalStartSession
conversationService.stopSession(sessionId)
}
}, 20_000)
it('should keep the session idle in the UI while restarting for a bypass permission switch', async () => {
await fetch(`${baseUrl}/api/permissions/mode`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode: 'default' }),
})
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const originalStartSession = conversationService.startSession.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
const messages: any[] = []
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(`Timed out waiting for idle permission switch connection for session ${sessionId}`))
}, 5000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
messages.push(msg)
if (msg.type === 'connected') {
clearTimeout(timeout)
ws.send(JSON.stringify({ type: 'prewarm_session' }))
resolve()
}
if (msg.type === 'error') {
clearTimeout(timeout)
reject(new Error(msg.message))
}
}
ws.onerror = () => {
clearTimeout(timeout)
reject(new Error(`WebSocket error for idle permission switch session ${sessionId}`))
}
})
await waitUntil(
() => startCalls.length === 1 && conversationService.hasSession(sessionId),
`prewarmed CLI process for idle permission switch ${sessionId}`,
)
await waitUntil(async () => {
const commandsRes = await fetch(`${baseUrl}/api/sessions/${sessionId}/slash-commands`)
if (!commandsRes.ok) return false
const { commands } = await commandsRes.json() as { commands?: Array<{ name: string }> }
return Array.isArray(commands) && commands.some((command) => command.name === 'help')
}, `prewarmed slash commands for idle permission switch ${sessionId}`)
const switchStartIndex = messages.length
ws.send(JSON.stringify({
type: 'set_permission_mode',
mode: 'bypassPermissions',
}))
await waitUntil(
async () => messages.slice(switchStartIndex).some((msg) => msg.type === 'status' && msg.state === 'idle'),
`idle permission switch completion for ${sessionId}`,
)
expect(startCalls).toHaveLength(2)
expect(startCalls[1]).toMatchObject({
sessionId,
options: {
permissionMode: 'bypassPermissions',
},
})
expect(
messages
.slice(switchStartIndex)
.filter((msg) => msg.type === 'status')
.map((msg) => msg.state),
).toEqual(['idle'])
expect(messages.slice(switchStartIndex).some((msg) => msg.type === 'error')).toBe(false)
} finally {
ws.close()
conversationService.startSession = originalStartSession
conversationService.stopSession(sessionId)
await fetch(`${baseUrl}/api/permissions/mode`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode: 'default' }),
})
}
}, 20_000)
it('should ignore stale persisted runtime provider ids when resuming old sessions', async () => {
const providerService = new ProviderService()
const activeProvider = await providerService.addProvider({
presetId: 'custom',
name: 'Current Valid Provider',
apiKey: 'key-current-valid',
baseUrl: 'http://127.0.0.1:1/anthropic',
apiFormat: 'anthropic',
models: {
main: 'current-main',
haiku: 'current-haiku',
sonnet: 'current-sonnet',
opus: 'current-opus',
},
})
await providerService.activateProvider(activeProvider.id)
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const staleProviderId = crypto.randomUUID()
const originalStartSession = conversationService.startSession.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
const messages: any[] = []
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
ws.close()
reject(new Error(`Timed out waiting for stale runtime resume for session ${sessionId}`))
}, 10_000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
messages.push(msg)
if (msg.type === 'connected') {
ws.send(JSON.stringify({
type: 'set_runtime_config',
providerId: staleProviderId,
modelId: 'stale-model',
}))
ws.send(JSON.stringify({ type: 'user_message', content: 'resume old session' }))
return
}
if (msg.type === 'error') {
clearTimeout(timeout)
ws.close()
reject(new Error(msg.message))
return
}
if (msg.type === 'message_complete') {
clearTimeout(timeout)
ws.close()
resolve()
}
}
ws.onerror = () => {
clearTimeout(timeout)
reject(new Error(`WebSocket error for stale runtime resume session ${sessionId}`))
}
})
expect(startCalls).toHaveLength(1)
expect(startCalls[0]).toMatchObject({
sessionId,
options: {
providerId: activeProvider.id,
},
})
expect(startCalls[0]?.options?.model).not.toBe('stale-model')
expect(messages.some((msg) => msg.type === 'message_complete')).toBe(true)
} finally {
ws.close()
conversationService.startSession = originalStartSession
conversationService.stopSession(sessionId)
await providerService.activateOfficial()
}
}, 20_000)
it('should preserve ChatGPT Official as the active default runtime after restart', async () => {
const providerService = new ProviderService()
await providerService.activateProvider('openai-official')
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const originalStartSession = conversationService.startSession.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
try {
const messages = await runTurn(sessionId, 'default ChatGPT Official runtime')
expect(startCalls).toHaveLength(1)
expect(startCalls[0]).toMatchObject({
sessionId,
options: {
providerId: 'openai-official',
},
})
expect(messages.some((msg) => msg.type === 'message_complete')).toBe(true)
await expect(providerService.listProviders()).resolves.toMatchObject({
activeId: 'openai-official',
})
} finally {
conversationService.startSession = originalStartSession
conversationService.stopSession(sessionId)
await providerService.activateOfficial()
}
}, 20_000)
it('should resume streaming to a reconnected client during an active turn', async () => {
await withMockStreamDelay(150, async () => {
const sessionId = `chat-reconnect-${crypto.randomUUID()}`
const firstMessages: any[] = []
const secondMessages: any[] = []
await new Promise<void>((resolve, reject) => {
let reconnected = false
let ws2: WebSocket | null = null
const timeout = setTimeout(() => {
ws2?.close()
reject(new Error(`Timed out waiting for reconnect completion for session ${sessionId}`))
}, 10_000)
const cleanup = () => {
clearTimeout(timeout)
ws2?.close()
resolve()
}
const handleFailure = (message: string) => {
clearTimeout(timeout)
ws2?.close()
reject(new Error(message))
}
const ws1 = new WebSocket(`${wsUrl}/ws/${sessionId}`)
ws1.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
firstMessages.push(msg)
if (msg.type === 'connected') {
ws1.send(JSON.stringify({ type: 'user_message', content: 'resume after reconnect' }))
return
}
if (msg.type === 'thinking' && !reconnected) {
reconnected = true
ws1.close()
setTimeout(() => {
ws2 = new WebSocket(`${wsUrl}/ws/${sessionId}`)
ws2.onmessage = (reconnectEvent) => {
const reconnectMsg = JSON.parse(reconnectEvent.data as string)
secondMessages.push(reconnectMsg)
if (reconnectMsg.type === 'error') {
handleFailure(reconnectMsg.message)
return
}
if (reconnectMsg.type === 'message_complete') {
cleanup()
}
}
ws2.onerror = () => handleFailure(`WebSocket reconnect error for session ${sessionId}`)
}, 50)
}
}
ws1.onerror = () => handleFailure(`Initial WebSocket error for session ${sessionId}`)
})
expect(firstMessages.some((msg) => msg.type === 'thinking')).toBe(true)
expect(secondMessages.some((msg) => msg.type === 'connected')).toBe(true)
expect(secondMessages.some((msg) => msg.type === 'content_delta')).toBe(true)
expect(secondMessages.some((msg) => msg.type === 'message_complete')).toBe(true)
})
})
it('should keep using the selected runtime config across the whole session until changed', async () => {
const providerService = new ProviderService()
const providerA = await providerService.addProvider({
presetId: 'custom',
name: 'Provider A',
apiKey: 'key-a',
baseUrl: 'http://127.0.0.1:1/anthropic',
apiFormat: 'anthropic',
models: {
main: 'model-a-main',
haiku: 'model-a-haiku',
sonnet: 'model-a-sonnet',
opus: 'model-a-opus',
},
})
const providerB = await providerService.addProvider({
presetId: 'custom',
name: 'Provider B',
apiKey: 'key-b',
baseUrl: 'http://127.0.0.1:1/anthropic',
apiFormat: 'anthropic',
models: {
main: 'model-b-main',
haiku: 'model-b-haiku',
sonnet: 'model-b-sonnet',
opus: 'model-b-opus',
},
})
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const originalStartSession = conversationService.startSession.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
try {
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
let phase: 'boot' | 'turn1' | 'switching' | 'turn2' | 'turn3' | 'done' = 'boot'
let switchingTriggered = false
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
ws.close()
reject(new Error(`Timed out waiting for runtime persistence flow for session ${sessionId}`))
}, 15_000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
if (msg.type === 'connected' && phase === 'boot') {
ws.send(JSON.stringify({
type: 'set_runtime_config',
providerId: providerA.id,
modelId: 'model-a-sonnet',
}))
ws.send(JSON.stringify({ type: 'user_message', content: 'first turn' }))
phase = 'turn1'
return
}
if (msg.type === 'error') {
clearTimeout(timeout)
ws.close()
reject(new Error(msg.message))
return
}
if (msg.type === 'message_complete' && phase === 'turn1' && !switchingTriggered) {
switchingTriggered = true
phase = 'switching'
ws.send(JSON.stringify({
type: 'set_runtime_config',
providerId: providerB.id,
modelId: 'model-b-opus',
}))
return
}
if (
msg.type === 'status' &&
msg.state === 'idle' &&
phase === 'switching'
) {
ws.send(JSON.stringify({ type: 'user_message', content: 'second turn' }))
phase = 'turn2'
return
}
if (msg.type === 'message_complete' && phase === 'turn2') {
ws.send(JSON.stringify({ type: 'user_message', content: 'third turn' }))
phase = 'turn3'
return
}
if (msg.type === 'message_complete' && phase === 'turn3') {
clearTimeout(timeout)
phase = 'done'
ws.close()
resolve()
}
}
ws.onerror = () => {
reject(new Error(`WebSocket error for runtime persistence session ${sessionId}`))
}
})
expect(startCalls).toHaveLength(2)
expect(startCalls[0]).toMatchObject({
sessionId,
options: {
providerId: providerA.id,
model: 'model-a-sonnet',
},
})
expect(startCalls[1]).toMatchObject({
sessionId,
options: {
providerId: providerB.id,
model: 'model-b-opus',
},
})
} finally {
conversationService.startSession = originalStartSession
conversationService.stopSession(sessionId)
}
}, 20_000)
it('should wait for an in-flight runtime restart before sending the next user turn', async () => {
const providerService = new ProviderService()
const providerA = await providerService.addProvider({
presetId: 'custom',
name: 'Provider Restart A',
apiKey: 'key-a',
baseUrl: 'http://127.0.0.1:1/anthropic',
apiFormat: 'anthropic',
models: {
main: 'restart-a-main',
haiku: 'restart-a-haiku',
sonnet: 'restart-a-sonnet',
opus: 'restart-a-opus',
},
})
const providerB = await providerService.addProvider({
presetId: 'custom',
name: 'Provider Restart B',
apiKey: 'key-b',
baseUrl: 'http://127.0.0.1:1/anthropic',
apiFormat: 'anthropic',
models: {
main: 'restart-b-main',
haiku: 'restart-b-haiku',
sonnet: 'restart-b-sonnet',
opus: 'restart-b-opus',
},
})
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const originalStartSession = conversationService.startSession.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
try {
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
let phase: 'boot' | 'turn1' | 'turn2' | 'turn3' | 'done' = 'boot'
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
ws.close()
reject(new Error(`Timed out waiting for runtime restart synchronization flow for session ${sessionId}`))
}, 15_000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
if (msg.type === 'connected' && phase === 'boot') {
ws.send(JSON.stringify({
type: 'set_runtime_config',
providerId: providerA.id,
modelId: 'restart-a-sonnet',
}))
ws.send(JSON.stringify({ type: 'user_message', content: 'first turn' }))
phase = 'turn1'
return
}
if (msg.type === 'error') {
clearTimeout(timeout)
ws.close()
reject(new Error(msg.message))
return
}
if (msg.type === 'message_complete' && phase === 'turn1') {
ws.send(JSON.stringify({
type: 'set_runtime_config',
providerId: providerB.id,
modelId: 'restart-b-opus',
}))
ws.send(JSON.stringify({ type: 'user_message', content: 'second turn immediately after switch' }))
phase = 'turn2'
return
}
if (msg.type === 'message_complete' && phase === 'turn2') {
ws.send(JSON.stringify({ type: 'user_message', content: 'third turn should reuse restarted runtime' }))
phase = 'turn3'
return
}
if (msg.type === 'message_complete' && phase === 'turn3') {
clearTimeout(timeout)
phase = 'done'
ws.close()
resolve()
}
}
ws.onerror = () => {
reject(new Error(`WebSocket error for runtime restart synchronization session ${sessionId}`))
}
})
expect(startCalls).toHaveLength(2)
expect(startCalls[0]).toMatchObject({
sessionId,
options: {
providerId: providerA.id,
model: 'restart-a-sonnet',
},
})
expect(startCalls[1]).toMatchObject({
sessionId,
options: {
providerId: providerB.id,
model: 'restart-b-opus',
},
})
} finally {
conversationService.startSession = originalStartSession
conversationService.stopSession(sessionId)
}
}, 20_000)
it('should wait for an in-flight permission restart before sending the next user turn', async () => {
await fetch(`${baseUrl}/api/permissions/mode`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode: 'default' }),
})
const createRes = await fetch(`${baseUrl}/api/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workDir: process.cwd() }),
})
expect(createRes.status).toBe(201)
const { sessionId } = await createRes.json() as { sessionId: string }
const originalStartSession = conversationService.startSession.bind(conversationService)
const originalSendMessage = conversationService.sendMessage.bind(conversationService)
const startCalls: Array<{
sessionId: string
options: { permissionMode?: string; model?: string; effort?: string; providerId?: string | null } | undefined
}> = []
const sendCalls: Array<{
content: string
startCallCount: number
permissionMode: string
}> = []
conversationService.startSession = (async function patchedStartSession(
sid: string,
workDir: string,
sdkUrl: string,
options?: { permissionMode?: string; model?: string; effort?: string; thinking?: 'enabled' | 'adaptive' | 'disabled'; providerId?: string | null },
) {
startCalls.push({ sessionId: sid, options })
return originalStartSession(sid, workDir, sdkUrl, options)
}) as typeof conversationService.startSession
conversationService.sendMessage = (function patchedSendMessage(
sid: string,
content: string,
attachments?: any,
) {
sendCalls.push({
content,
startCallCount: startCalls.length,
permissionMode: conversationService.getSessionPermissionMode(sid),
})
return originalSendMessage(sid, content, attachments)
}) as typeof conversationService.sendMessage
try {
const ws = new WebSocket(`${wsUrl}/ws/${sessionId}`)
let phase: 'boot' | 'turn1' | 'turn2' | 'done' = 'boot'
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
ws.close()
reject(new Error(`Timed out waiting for permission restart synchronization flow for session ${sessionId}`))
}, 15_000)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string)
if (msg.type === 'connected' && phase === 'boot') {
ws.send(JSON.stringify({ type: 'user_message', content: 'first turn before permission switch' }))
phase = 'turn1'
return
}
if (msg.type === 'error') {
clearTimeout(timeout)
ws.close()
reject(new Error(msg.message))
return
}
if (msg.type === 'message_complete' && phase === 'turn1') {
ws.send(JSON.stringify({
type: 'set_permission_mode',
mode: 'bypassPermissions',
}))
ws.send(JSON.stringify({ type: 'user_message', content: 'second turn immediately after permission switch' }))
phase = 'turn2'
return
}
if (msg.type === 'message_complete' && phase === 'turn2') {
clearTimeout(timeout)
phase = 'done'
ws.close()
resolve()
}
}
ws.onerror = () => {
reject(new Error(`WebSocket error for permission restart synchronization session ${sessionId}`))
}
})
expect(startCalls).toHaveLength(2)
expect(startCalls[0]).toMatchObject({
sessionId,
options: {
permissionMode: 'default',
},
})
expect(startCalls[1]).toMatchObject({
sessionId,
options: {
permissionMode: 'bypassPermissions',
},
})
expect(sendCalls).toMatchObject([
{
content: 'first turn before permission switch',
startCallCount: 1,
permissionMode: 'default',
},
{
content: 'second turn immediately after permission switch',
startCallCount: 2,
permissionMode: 'bypassPermissions',
},
])
} finally {
conversationService.startSession = originalStartSession
conversationService.sendMessage = originalSendMessage
conversationService.stopSession(sessionId)
await fetch(`${baseUrl}/api/permissions/mode`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode: 'default' }),
})
}
}, 20_000)
})
|