Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 | 2x 2x 2x 2x 2x 2x 153x 17x 17x 6x 11x 11x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 21x 21x 21x 63x 3x 3x 21x 30x 30x 3x 3x 102x 36x 34x 33x 151x 151x 170x 109x 109x 109x 109x 14x 14x 14x 14x 2x 2x 2x 2x 4x 3x 6x 5x 21x 21x 21x 21x 265x 2x 57x 53x 53x 53x 57x 57x 57x 53x 44x 45x 147x 147x 147x 45x 49x 49x 49x 49x 729x 729x 8x 8x 8x 729x 729x 49x 49x 9x 7x 7x 7x 5x 12x 11x 11x 9x 27x 25x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 2x 751x 751x 751x 751x 654x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 751x 622x 622x 622x 622x 622x 622x 622x 622x 622x 622x 622x 622x 622x 622x 1x 622x 622x 3106x 3106x 6x 622x 622x 622x 622x 622x 622x 622x 662x 662x 662x 622x 622x 1x 1x 1x 622x 612x 1x 611x 190x 190x 190x 421x 421x 421x 421x 621x 10x 621x 621x 621x 621x 621x 622x 622x 622x 622x 4x 3x 4x 623x 3115x 3115x 623x 216x 211x 211x 210x 1x 1x 209x 209x 209x 209x 209x 209x 209x 1x 1x 1x 208x 208x 208x 199x 199x 198x 198x 198x 198x 198x 216x 191x 191x 191x 191x 191x 191x 191x 8x 1x 1x 1x 1x 7x 7x 209x 9x 9x 9x 7x 7x 9x 1x 1x 1x 8x 8x 4x 4x 4x 4x 4x 4x 9x 1x 1x 1x 1x 3x 3x 3x 192x 192x 3x 3x 3x 2x 2x 209x 209x 208x 208x 208x 2x 208x 34x 34x 34x 9x 9x 9x 30x 30x 9x 9x 21x 9x 21x 21x 20x 20x 3x 3x 2x 2x 2x 2x 197x 197x 196x 196x 196x 178x 178x 178x 18x 18x 9x 9x 9x 9x 9x 9x 9x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 202x 2x 16x 5x 4x 4x 5x 5x 5x 2x 2x 1x 1x 1x 1x 3x 3x 3x 751x 237x 237x 237x 237x 237x 248x 6x 12x 218x 218x 29x 29x 29x 29x 29x 218x 217x 12x 12x 1x 218x 218x 218x 185x 185x 185x 12x 12x 10x 10x 1x 1x 9x 10x 12x 29x 29x 1x 1x 28x 28x 28x 2x 199x 7x 7x 1x 24x 24x 24x 2x 195x 195x 195x 193x 193x 193x 751x 9x 207x 207x 207x 5x 4x 202x 1x 9x 8x 1x 1x 7x 7x 6x 7x 1x 7x 1x 1x 7x 7x 7x 2x 2x 202x 201x 2x 2x 199x 197x 196x 196x 6x 5x 5x 5x 3x 3x 3x 2x 2x 2x 2x 2x 1x 1x 5x 5x 19x 19x 7x 7x 211x 199x 199x 198x 2x 2x 196x 18x 199x 199x 199x 199x 198x 198x 198x 196x 196x 1x 1x 193x 196x 196x 18x 18x 18x 6x 6x 6x 6x 12x 12x 12x 12x 12x 12x 1x 1x 12x 12x 12x 12x 12x 3x 3x 2x 12x 12x 11x 10x 10x 9x 9x 9x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 5x 5x 11x 11x 160x 158x 158x 158x 158x 158x 158x 6x 6x 195x 195x 194x 193x 193x 16x 16x 16x 177x 159x 159x 145x 14x 14x 9x 9x 9x 195x 195x 195x 6x 3x 2x 1x 9x 183x 183x 184x 184x 183x 183x 180x 17x 14x 14x 5x 5x 9x 6x 6x 6x 6x 1x 442x 442x 442x 442x 423x 442x 427x 427x 427x 425x 424x 2x 751x 48x 48x 48x 48x 26x 26x 6x 6x 3x 2x 20x 20x 20x 19x 20x 20x 5x 5x 5x 19x 20x 20x 4x 1x 19x 17x 17x 17x 17x 8x 8x 17x 622x 4x 4x 622x 4x 4x 3x 4x 12x 12x 8x 8x 8x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 18x 17x 9x 8x 9x 9x 9x 9x 9x 9x 2x 2x 2x 4x 3x 3x 3x 2x 2x 2x 1876x 1876x 684x 193x 491x 3x 488x 488x 640x 640x 640x 640x 13x 6x 6x 7x 1x 1x 1x 6x 1x 1x 5x 4x 3x 3x 62x 47x 15x 621x 3x 2x 2x 621x 3x 2x 2x 621x 3x 2x 2x 621x 6x 5x 5x 621x 4x 3x 3x 2x 2x 621x 7x 5x 5x 3x 3x 3x 2x 1x 1x 2x 621x 3x 3x 2x 1x 1x 2x 621x 3x 2x 2x 621x 5x 4x 4x 3x 3x 621x 5x 4x 4x 5x 2x 2x 621x 3x 2x 2x 621x 3x 2x 2x 621x 4x 3x 2x 2x 2x 2x 3x 621x 3x 2x 2x 621x 3x 2x 2x 621x 6x 4x 4x 621x 3x 2x 2x 621x 3x 2x 2x 621x 11x 10x 10x 621x 3x 2x 2x 621x 3x 2x 2x 621x 3x 2x 2x 621x 1x 621x 1x 621x 1x 621x 3x 2x 2x 621x 3x 2x 2x 621x 3x 2x 2x 621x 3x 2x 2x 621x 1x 621x 1x 621x 4x 3x 2x 2x 5x 5x 4x 4x 4x 5x 5x 1x 1x 4x 3x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 11x 11x 3x 3x 929x 929x 719x 719x 719x 719x 719x 719x 719x 719x 719x 719x 719x 719x 719x 504x 1x 1x 215x 751x 6x 17x 17x 17x 16x 933x 26x 26x 25x 924x 29x 27x 27x 26x 2x 4x 4x 3x 3x 2x 2x 2x 5x 5x 3x 3x 2x 2x 16x 16x 3x 13x 12x 12x 12x 8x 8x 16x 7x 1x 1x 12x 12x 6x 6x 6x 6x 29x 29x 3x 3x 4x 3x 3x 2x 197x 197x 197x 716x 662x 16x 16x 16x 16x 16x 4x 2x 2x 12x 3x 3x 3x 12x 12x 8x 12x 12x 1508x 1469x 1508x 1508x 1508x 1305x 1305x 1469x 1676x 1637x 1637x 444x 444x 5x 5x 5x 173x 172x 169x 168x 1x 1x 167x 4x 4x 4x 163x 173x 173x 623x 622x 622x 622x 58x 48x 47x 46x 45x 45x 45x 45x 18x 18x 18x 17x 18x 2x 2x 18x 18x 18x 18x 4x 4x 14x 14x 27x 27x 27x 15x 14x 13x 9x 9x 9x 9x 43x 43x 43x 43x 43x 2x 2x 43x 21x 21x 21x 12x 12x 12x 9x 3x 3x 3x 6x 22x 9x 9x 9x 13x 12x 12x 12x 13x 13x 5x 4x 3x 11x 4x 3x 3x 1x 3x 751x 9x 8x 7x 7x 9x 665x 665x 665x 665x 278x 278x 161x 161x 117x 117x 387x 1x 1x 1x 386x 386x 665x 665x 665x 366x 366x 20x 20x 386x 161x 99x 99x 99x 99x 99x 62x 52x 52x 52x 52x 52x 52x 10x 10x 10x 1x 1x 9x 10x 10x 1x 1x 8x 8x 8x 10x 1x 1x 7x 7x 7x 1x 1x 6x 1x 1x 5x 641x 641x 19x 19x 13x 11x 19x 639x 639x 638x 4x 4x 639x 15x 15x 19x 15x 15x 1x 15x 15x 17x 20x 19x 19x 5x 1x 76x 2x 2x 85x 4x 4x 81x 3x 3x 78x 6x 8x 3x 2x 2x 5x 22x 63x 63x 63x 63x 9x 9x 9x 54x 36x 34x 33x 32x 36x 36x 31x 31x 29x 29x 4x 4x 1x 1x 1x 3x 25x 8x 8x 8x 16x 7x 11x 11x 9x 7x 9x 6x 31x 31x 31x 31x 1x 1x 1x 30x 30x 36x 2x 2x 34x 36x 36x 36x 36x 3x 31x 30x 4x 4x 30x 45x 34x 34x 3x 3x 34x 1001x 1001x 1x 46x 45x 44x 43x 43x 46x 46x 46x 41x 41x 38x 38x 1x 1x 1x 37x 3x 40x 41x 5x 5x 8x 4x 5x 44x 44x 44x 2x 2x 42x 137x 41x 45x 45x 41x 24x 4x 4x 4x 4x 9x 15x 9x 9x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 6x 2x 2x 4x 2x 2x 2x 9x 4x 2x 2x 68x 68x 1x 1x 71x 67x 67x 67x 67x 67x 67x 67x 68x 42x 3x 3x 3x 39x 1x 1x 1x 38x 1x 1x 1x 37x 1x 1x 1x 36x 25x 25x 11x 3x 3x 3x 3x 3x 8x 7x 7x 7x 7x 7x 7x 44x 21x 21x 20x 20x 3x 44x 13x 4x 4x 4x 9x 2x 2x 2x 7x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 67x 20x 2x 2x 2x 3x 3x 1x 1x 2x 2x 1x 1x 7x 2x 3x 1x 1x 4x 2x 2x 2x 2x 2x 4x 4x 1x 1x 3x 2x 2x 2x 2x 1x 1x 2x 2x 1x 1x 1x 1x 5x 23x 23x 23x 1x 3x 2x 2x 1x 2x 2x 4x 4x 1x 1x 3x 3x 2x 2x 6x 6x 6x 6x 2x 2x 4x 3x 3x 3x 3x 2x 2x 3x 9x 8x 8x 8x 8x 9x 40x 9x 9x 21x 21x 13x 13x 10x 18x 8x 21x 21x 19x 8x 621x 6x 5x 2x 621x 621x 621x 621x 621x 695x 427x 695x 225x 225x 224x 854x 609x 245x 854x 244x 14x 13x 244x 244x 244x 244x 244x 245x 244x 9x 1x 236x 10x 855x 854x 854x 853x 853x 3x 3x 850x 4x 4x 1x 1x 3x 3x 1x 1x 1x 2x 2x 9x 9x 1x 1x 8x 8x 8x 8x 8x 11x 2x 2x 2x 9x 2x 2x 7x 4x 3x 2x 2x 4x 4x 4x 4x 1x 4x 7x 7x 7x 7x 6x 6x 1x 1x 5x 5x 3x 3x 3x 3x 1x 2x 2x 7x 7x 1x 1x 6x 6x 6x 6x 5x 3x 3x 3x 2x 2x 2x 2x 1x 1x 1x 1x 6x 6x 6x 11x 5x 5x 5x 2x 2x 4x 4x 4x 5x 29x 29x 1x 1x 28x 28x 28x 28x 28x 28x 28x 28x 28x 57x 10x 10x 10x 8x 8x 6x 10x 6x 4x 4x 8x 8x 8x 5x 5x 3x 3x 3x 3x 3x 5x 4x 7x 7x 7x 2x 2x 16x 16x 16x 16x 16x 3x 3x 3x 3x 1x 5x 1x 5x 2x 2x 2x 3x 3x 3x 42x 41x 5x 3x 5x 36x 36x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 19x 2x 2x 2x 17x 1x 1x 1x 16x 1x 1x 1x 15x 1x 1x 1x 14x 10x 10x 4x 3x 3x 3x 3x 3x 23x 7x 7x 23x 6x 2x 2x 4x 2x 2x 2x 1x 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 2x 2x | import {
type ItemView,
type Menu,
type MenuItem,
Notice,
Plugin,
type TAbstractFile,
TFile,
TFolder,
type WorkspaceLeaf,
} from "obsidian";
import {
AgentWiring,
CLAUDIAN_OUTCOME,
isClaudianInstalled,
isClaudianLoaded,
reloadClaudian,
type AgentWireOutcome,
} from "./agent-integration";
import { LilbeeClient, SessionTokenError, hasStatusLine, isClientError } from "./api";
import type { Result } from "./result";
import { node } from "./node";
import { exportDatasetToDisk, importDatasetFromDisk } from "./dataset-io";
import { electronDialog } from "./utils/file-dialog";
import { CHAT_EXPORT_EXTENSION } from "./utils/session";
import { exportDiagnostics } from "./diagnostics-export";
import { hasNvidiaDevice, readEngineBackend, readFleetDevices } from "./engine-backend";
import { ErrorJournal } from "./error-journal";
import {
ServerBinary,
ServerUpdateBusyError,
getLatestRelease,
checkForUpdate,
isDownloadCanceled,
migrateFlatBinary,
} from "./server-binary";
import type { DownloadProgress, EnsureResult, ReleaseInfo } from "./server-binary";
import { ScopeHeldError, ServerManager, askServerToExit, readScopeOwner, serverIsLive } from "./server-manager";
import { executeUninstall, planUninstall } from "./server-uninstall";
import { readSessionToken, resolveExternalDataRoot } from "./session-token";
import { LilbeeSettingTab } from "./settings";
import { VaultRegistry, computeVaultId, resolveSharedRoot, sharedBinDir, sharedModelsDir } from "./vault-registry";
import { AGENT_PICKER_RESULT, AgentPickerModal } from "./views/agent-picker-modal";
import {
AGENT_SELECTION,
CONFIG_KEY,
DEFAULT_AGENT_INTEGRATION,
DEFAULT_SETTINGS,
DOT_STATE,
ENSURE_SOURCE,
CAPABILITY,
ERROR_NAME,
LOGS_DIR,
LOG_FILE,
MANAGED_CONSENT_RESULT,
MANAGED_PHASE,
MODEL_INFO_SOURCE,
MODEL_TASK,
REQUEST_OUTCOME,
SERVER_MODE,
SERVER_STATE,
SERVER_VARIANT,
SETUP_OUTCOME,
SSE_EVENT,
cudaVersionUnknown,
SYNC_TRIGGER,
TASK_STATUS,
TASK_TYPE,
type AgentClient,
type BatchProgressPayload,
type CrawlRenderMode,
type DiagnosticsContext,
type DotState,
type EngineBackend,
type GpuDetection,
type GpuInfo,
CHAT_STATUS,
type ChatStatus,
type HealthResponse,
type LibraryUpgrade,
UPGRADE_PHASE,
type HealthWarning,
type LilbeeSettings,
type ManagedServerProgressHandler,
type ModelShowResponse,
type RequestOutcome,
type ServerMode,
type SetupOutcome,
type ServerState,
type ServerVariant,
type StorageMoveTarget,
type SetupDonePayload,
type SetupProgressPayload,
type SetupStartPayload,
INDETERMINATE_PROGRESS,
type AddDone,
type IndexMismatch,
type SyncDone,
type SSEEvent,
type WarmProgress,
type SyncOptions,
type SyncTrigger,
type TaskEntry,
type WikiBuildResult,
type WikiPagePayload,
type WikiPhasePayload,
type UninstallPlan,
type VaultAdapter,
type SkippedSource,
MANAGED_DOCS_PREFIX,
UPLOAD_REFUSED_EXTENSIONS,
} from "./types";
import { AGENT_LABELS, MESSAGES } from "./locales/en";
import { displayLabelForRef, extractHfRepo } from "./utils/model-ref";
import { applyConfig } from "./utils/reindex";
import { isVersionOlder } from "./min-server-version";
import {
errorMessage,
extractServerErrorDetail,
extractSseErrorMessage,
formatDiskSize,
HEALTH_FAILURE_STREAK_THRESHOLD,
HEALTH_PROBE_INTERVAL_MS,
NOTICE_DURATION_MS,
NOTICE_ERROR_DURATION_MS,
NOTICE_PERMANENT,
openPluginSettingsById,
percentOfBytes,
sessionTokenInvalidMessage,
supportsPlacement,
supportsSessionExport,
supportsSessionFork,
supportsSessions,
isUpgradeRunning,
sameWarnings,
warmStatusText,
STREAM_IDLE_TIMEOUT_MS,
} from "./utils";
import { StreamIdleError, withIdleTimeout } from "./utils/idle";
import { CatalogModal } from "./views/catalog-modal";
import { ManagedConsentModal } from "./views/managed-consent-modal";
import { ModelInfoModal } from "./views/model-info-modal";
import { ModelPickerModal } from "./views/model-picker-modal";
import { ChatView, VIEW_TYPE_CHAT } from "./views/chat-view";
import { CrawlModal } from "./views/crawl-modal";
import { DocumentsModal } from "./views/documents-modal";
import { SearchModal } from "./views/search-modal";
import { SetupWizard } from "./views/setup-wizard";
import { TaskCenterView, VIEW_TYPE_TASKS } from "./views/task-center";
import { WikiView, VIEW_TYPE_WIKI } from "./views/wiki-view";
import { MemoriesView, openMemoriesView, VIEW_TYPE_MEMORIES } from "./views/memories-view";
import { PlacementView, VIEW_TYPE_PLACEMENT, revealPlacementBeside } from "./views/placement-view";
import { RememberModal } from "./views/remember-modal";
import { LintModal } from "./views/lint-modal";
import { DraftModal } from "./views/draft-modal";
import { ConfirmModal } from "./views/confirm-modal";
import { UpdateAvailableModal } from "./views/update-available-modal";
import { StatusModal } from "./views/status-modal";
import { GatekeeperModal } from "./views/gatekeeper-modal";
import { TaskQueue, FLASH_WINDOW_MS as TASK_FLASH_WINDOW_MS } from "./task-queue";
import { WikiSync } from "./wiki-sync";
const BYTES_PER_MB = 1_000_000;
const PENDING_SYNC_HINT_DEBOUNCE_MS = 1000;
/** How long a taken-over server gets to exit after agreeing to stop. */
const TAKE_OVER_SHUTDOWN_TIMEOUT_MS = 10_000;
// How long terminateOwningProcess waits for the previous owner to exit.
const SUPPORTED_SYNC_EXTENSIONS = new Set(["md", "pdf", "txt", "html"]);
// A single /api/add/upload request is bounded server-side by file count and
// body size, so large folders upload in sequential batches that stay under both.
const UPLOAD_BATCH_MAX_FILES = 90;
const UPLOAD_BATCH_MAX_BYTES = 8 * BYTES_PER_MB;
const basename = (p: string): string => p.slice(p.lastIndexOf("/") + 1);
function formatSetupDetail(downloaded: number, total: number | null): string {
const dlMB = (downloaded / BYTES_PER_MB).toFixed(1);
if (total === null) {
return MESSAGES.STATUS_TASK_SETUP_PROGRESS_INDETERMINATE.replace("{downloaded}", dlMB);
}
const totalMB = (total / BYTES_PER_MB).toFixed(1);
return MESSAGES.STATUS_TASK_SETUP_PROGRESS.replace("{downloaded}", dlMB).replace("{total}", totalMB);
}
function summarizeSyncResult(done: AddDone): string {
const parts: string[] = [];
if (done.added.length > 0) parts.push(`${done.added.length} added`);
if (done.updated.length > 0) parts.push(`${done.updated.length} updated`);
if (done.removed.length > 0) parts.push(`${done.removed.length} removed`);
if (done.failed.length > 0) parts.push(`${done.failed.length} failed`);
if (done.skipped.length > 0) parts.push(`${done.skipped.length} skipped`);
if (done.held_out.length > 0) parts.push(`${done.held_out.length} held out`);
if (done.tracked.length > 0) parts.push(`${done.tracked.length} already tracked`);
if (done.absorbed.length > 0) parts.push(MESSAGES.SYNC_PART_FOLDERS_TAKEN_IN(done.absorbed.length));
return parts.join(", ");
}
/** One notice for each kind of refusal; true when the add refused anything. */
function noticeAddRefusals(done: AddDone): boolean {
const kinds: [string[], (names: string) => string][] = [
[done.name_taken, MESSAGES.NOTICE_ADD_NAME_TAKEN],
[done.overlapping, MESSAGES.NOTICE_ADD_OVERLAPPING],
[done.errors, MESSAGES.NOTICE_ADD_REFUSED],
];
let refused = false;
for (const [names, message] of kinds) {
if (names.length === 0) continue;
new Notice(message(names.join(", ")), NOTICE_ERROR_DURATION_MS);
refused = true;
}
return refused;
}
/** Warn about a lost held-out list and about an index the server can no longer search; true when the index warning showed. */
function noticeSyncProblems(done: AddDone): boolean {
if (done.skip_records_error) new Notice(done.skip_records_error, NOTICE_ERROR_DURATION_MS);
if (!done.index_mismatch) return false;
new Notice(done.index_mismatch.message, NOTICE_ERROR_DURATION_MS);
return true;
}
/** Forward-slash form of a path with no trailing separator. */
function posixPath(p: string): string {
return p.replace(/\\/g, "/").replace(/\/+$/, "");
}
/** Task-center label for a sync, distinguishing the recovery variants. */
function syncTaskLabel(options?: SyncOptions): string {
if (options?.forceRebuild) return MESSAGES.COMMAND_SYNC_REBUILD;
if (options?.retrySkipped) return MESSAGES.COMMAND_SYNC_RETRY_SKIPPED;
return MESSAGES.COMMAND_SYNC;
}
function countRecentByStatus(completed: readonly TaskEntry[], status: TaskEntry["status"]): number {
const now = Date.now();
return completed.filter(
(t) => t.status === status && t.completedAt !== null && now - t.completedAt < TASK_FLASH_WINDOW_MS,
).length;
}
/**
* Tracks combined file-level + intra-file progress for sync/add streams.
*
* Server emits FILE_START per file with `current_file/total_files`, plus
* EXTRACT (pages within a file) and EMBED (chunks within a file). We split
* each file's work budget 50/50 between extract and embed so the bar advances
* smoothly instead of snapping to file boundaries.
*/
export class FileProgressTracker {
private totalFiles = 1;
private currentFile = 0;
private extractFraction = 0;
private embedFraction = 0;
startFile(current: number, total: number): void {
this.currentFile = current;
this.totalFiles = Math.max(1, total);
this.extractFraction = 0;
this.embedFraction = 0;
}
completeFile(current: number, total: number): void {
this.currentFile = current + 1;
this.totalFiles = Math.max(1, total);
this.extractFraction = 0;
this.embedFraction = 0;
}
setExtractFraction(page: number, totalPages: number): void {
if (totalPages <= 0) return;
this.extractFraction = Math.max(0, Math.min(1, page / totalPages));
}
setEmbedFraction(chunk: number, totalChunks: number): void {
if (totalChunks <= 0) return;
this.embedFraction = Math.max(0, Math.min(1, chunk / totalChunks));
}
percent(): number {
const intra = this.extractFraction * 0.5 + this.embedFraction * 0.5;
const filesDone = Math.max(0, this.currentFile - 1);
const pct = ((filesDone + intra) / this.totalFiles) * 100;
return Math.max(0, Math.min(100, Math.round(pct)));
}
}
const stringList = (value: unknown): string[] => (Array.isArray(value) ? (value as string[]) : []);
const EMPTY_SYNC: SyncDone = {
added: [],
updated: [],
removed: [],
unchanged: 0,
failed: [],
skipped: [],
held_out: [],
index_mismatch: null,
skip_records_error: null,
};
export function parseAddDoneEvent(data: unknown): AddDone | null {
if (!data || typeof data !== "object") return null;
const obj = data as Record<string, unknown>;
// The add outcomes sit on the envelope beside `sync`, never inside it.
const outcomes = {
tracked: stringList(obj.tracked),
name_taken: stringList(obj.name_taken),
overlapping: stringList(obj.overlapping),
errors: stringList(obj.errors),
absorbed: stringList(obj.absorbed),
};
const sync = obj.sync && typeof obj.sync === "object" ? (obj.sync as Record<string, unknown>) : obj;
// The server sends no `sync` when nothing reached the corpus.
const refused = outcomes.name_taken.length + outcomes.overlapping.length + outcomes.errors.length > 0;
const done = coerceSyncDone(sync) ?? (refused ? EMPTY_SYNC : null);
return done === null ? null : { ...done, ...outcomes };
}
function coerceSyncDone(obj: Record<string, unknown>): SyncDone | null {
if (!Array.isArray(obj.added) || !Array.isArray(obj.updated)) return null;
return {
added: obj.added as string[],
updated: obj.updated as string[],
removed: Array.isArray(obj.removed) ? (obj.removed as string[]) : [],
unchanged: typeof obj.unchanged === "number" ? obj.unchanged : 0,
failed: Array.isArray(obj.failed) ? (obj.failed as string[]) : [],
skipped: Array.isArray(obj.skipped) ? (obj.skipped as string[]) : [],
held_out: Array.isArray(obj.held_out) ? (obj.held_out as SkippedSource[]) : [],
index_mismatch: (obj.index_mismatch as IndexMismatch | null | undefined) ?? null,
skip_records_error:
typeof obj.skip_records_error === "string" && obj.skip_records_error ? obj.skip_records_error : null,
};
}
type UploadPayload = { name: string; data: ArrayBuffer };
/** Drop audio and video files before an upload: no server reads them. */
export function dropRefusedUploads(files: UploadPayload[]): { kept: UploadPayload[]; leftOut: number } {
const kept = files.filter((f) => {
const name = basename(f.name);
const dot = name.lastIndexOf(".");
return dot <= 0 || !UPLOAD_REFUSED_EXTENSIONS.includes(name.slice(dot).toLowerCase());
});
return { kept, leftOut: files.length - kept.length };
}
/** Split uploads into batches that stay under the server's per-request file
* count and body-size limits. A lone file over the byte budget still gets its
* own batch (the server rejects only if it also exceeds its hard cap). */
export function batchUploads(files: UploadPayload[]): UploadPayload[][] {
const batches: UploadPayload[][] = [];
let current: UploadPayload[] = [];
let bytes = 0;
for (const file of files) {
const size = file.data.byteLength;
if (current.length > 0 && (current.length >= UPLOAD_BATCH_MAX_FILES || bytes + size > UPLOAD_BATCH_MAX_BYTES)) {
batches.push(current);
current = [];
bytes = 0;
}
current.push(file);
bytes += size;
}
if (current.length > 0) batches.push(current);
return batches;
}
/** Progress for a settings-driven install/update: a phase line plus a percent when known. */
export type ServerDownloadProgressHandler = (msg: string, percent?: number) => void;
/** "Downloading... 45% (128 MB of 283 MB)", or bytes-only when the server sends no length. */
function downloadMessage(progress: DownloadProgress): string {
if (progress.done === 0) return MESSAGES.STATUS_DOWNLOAD_STARTING;
const received = formatDiskSize(progress.done);
const percent = downloadPercent(progress);
if (percent === undefined || progress.total === null) return MESSAGES.STATUS_DOWNLOAD_RECEIVED(received);
return MESSAGES.STATUS_DOWNLOAD_PROGRESS(percent, received, formatDiskSize(progress.total));
}
/** The status bar is narrow: percent only, with the byte detail left to Settings. */
function downloadStatusBar(progress: DownloadProgress): string {
if (progress.done === 0) return `lilbee: ${MESSAGES.STATUS_DOWNLOAD_STARTING}`;
const percent = downloadPercent(progress);
if (percent === undefined) return MESSAGES.STATUS_DOWNLOADING;
return MESSAGES.STATUS_DOWNLOADING_PERCENT(percent);
}
/** Percent for a progress bar; undefined until bytes arrive, so the bar stays indeterminate while the transfer opens. */
function downloadPercent(progress: DownloadProgress): number | undefined {
if (progress.done === 0) return undefined;
return percentOfBytes(progress.done, progress.total);
}
export default class LilbeePlugin extends Plugin {
settings: LilbeeSettings = { ...DEFAULT_SETTINGS };
private settingTab: LilbeeSettingTab | null = null;
private updateRibbonIconEl: HTMLElement | null = null;
api: LilbeeClient = new LilbeeClient("");
activeModel = "";
statusBarEl: HTMLElement | null = null;
syncPillEl: HTMLElement | null = null;
chatRibbonIconEl: HTMLElement | null = null;
serverManager: ServerManager | null = null;
journal = new ErrorJournal();
vaultRegistry: VaultRegistry | null = null;
vaultId = "";
syncController: AbortController | null = null;
/** An automatic sync requested while another ran; the running one carries it. */
private deferredSync: { options?: SyncOptions } | null = null;
private pendingSyncCount = 0;
private pendingHintTimeout: number | null = null;
private previousServerMode: ServerMode = SERVER_MODE.MANAGED;
/** Compared in `saveSettings()` so an unrelated save doesn't re-request the
* server's health. Kept in sync with `previousServerMode` by `recordServerBaseline()`. */
private previousServerUrl: string | null = null;
private startingServer = false;
private serverStartFailed = false;
private unloaded = false;
/** True once onunload ran; UI that outlives the instance must stop reporting. */
isUnloaded(): boolean {
return this.unloaded;
}
// Guards chat-leaf creation against re-entrant duplicate tabs while setViewState is in flight (issue #169).
private openingChatLeaf = false;
// Same re-entrancy guard for the placement view's main-area tab and beside-chat split.
private openingPlacementLeaf = false;
taskQueue: TaskQueue = new TaskQueue();
/** Paths whose most-recent add failed — retry skips the reindex confirm. */
private failedAddPaths = new Set<string>();
get wikiEnabled(): boolean {
return this.settings.wikiEnabled;
}
/** True while the setup wizard owns the screen; nothing else may take the foreground. */
setupWizardOpen = false;
/** Set when agent pairing wanted the screen and the wizard had it. */
private agentPickerDeferred = false;
wikiPageCount = 0;
wikiDraftCount = 0;
wikiSync: WikiSync | null = null;
private healthProbeHandle: number | null = null;
private serverUnreachable = false;
// True when the server is up but the chat role is still cold-loading (from /api/health).
private chatStatus: ChatStatus = CHAT_STATUS.READY;
private chatError: string | null = null;
/** The library upgrade the last health probe saw running; null once it ends. */
private libraryUpgrade: LibraryUpgrade | null = null;
/** Degradations from the last health probe; surfaces read this. */
healthWarnings: HealthWarning[] = [];
private warmController: AbortController | null = null;
// While > 0, probeServerHealth() bails: llama.cpp serializes requests,
// so /api/health stalls behind the active stream and would falsely flip
// the status bar to error.
private chatInFlight = 0;
// Counts consecutive failed probes against HEALTH_FAILURE_STREAK_THRESHOLD.
private healthFailureStreak = 0;
// True once a health probe has validated status "ok". External readiness
// belongs to the probe, never to a model-list response.
private healthValidated = false;
// External-mode server version, refreshed by refreshExternalServerVersion()
// and the health probe; managed mode reads the recorded install version
// instead.
private externalServerVersion = "";
// Bumped by every request that can write externalServerVersion (a launch/
// switch refresh or a probe tick), so a response that resolves out of
// order can tell it was superseded and skip the write. Same shape as
// ServerManager's startGeneration.
private externalVersionGeneration = 0;
// The managed server has reached READY at least once this session. Until
// it has, a failing health probe means "still coming up", not "error" —
// so a fresh install / first-run wizard doesn't flash a red error pill
// while the binary downloads and the server boots.
private serverEverReady = false;
async onload(): Promise<void> {
this.registerErrorCapture();
await this.loadSettings();
// Dead instances skip unload and leave their pills behind; a reload
// then stacks another set beside them. Sweep our markers first.
this.sweepStaleChrome();
this.statusBarEl = this.addStatusBarItem();
this.statusBarEl.addClass("lilbee-status-pill", "lilbee-clickable");
this.statusBarEl.setAttribute("aria-label", MESSAGES.LABEL_STATUSBAR_OPEN_SETTINGS);
this.statusBarEl.addEventListener("click", () => this.openPluginSettings());
// A separate, visually distinct sync pill (refresh glyph + count) that
// only appears when the vault has documents the server hasn't ingested.
// Keeping it off the main status pill lets the green "running" state
// stay clean and prominent; this pill is a sync affordance, not a
// second status icon. Clicking it triggers a sync.
this.syncPillEl = this.addStatusBarItem();
this.syncPillEl.addClass("lilbee-sync-pill");
this.syncPillEl.addClass("lilbee-clickable");
this.syncPillEl.hide();
this.syncPillEl.setAttribute("aria-label", MESSAGES.TOOLTIP_PENDING_SYNC_HINT);
this.syncPillEl.addEventListener("click", () => void this.triggerSync());
this.chatRibbonIconEl = this.addRibbonIcon("messages-square", MESSAGES.LABEL_RIBBON_OPEN_CHAT, () =>
this.activateChatView(),
);
this.chatRibbonIconEl.addClass("lilbee-ribbon-icon", "lilbee-ribbon-chat");
// Guard against Obsidian holding stale view registrations from a
// previous plugin instance that didn't unload cleanly (e.g. an
// onload that threw before registerView ran, or a disable that
// skipped its unregister callback). registerView throws on
// duplicate registration; wrap so the new instance still loads.
const safeRegisterView = (type: string, factory: (leaf: WorkspaceLeaf) => ItemView): void => {
try {
this.registerView(type, factory);
} catch (err) {
if (!(err instanceof Error) || !/existing view type/.test(err.message)) throw err;
}
};
safeRegisterView(VIEW_TYPE_CHAT, (leaf) => new ChatView(leaf, this));
safeRegisterView(VIEW_TYPE_TASKS, (leaf) => new TaskCenterView(leaf, this));
safeRegisterView(VIEW_TYPE_WIKI, (leaf) => new WikiView(leaf, this));
safeRegisterView(VIEW_TYPE_MEMORIES, (leaf) => new MemoriesView(leaf, this));
safeRegisterView(VIEW_TYPE_PLACEMENT, (leaf) => new PlacementView(leaf, this));
this.settingTab = new LilbeeSettingTab(this.app, this);
this.addSettingTab(this.settingTab);
this.taskQueue.onChange(() => this.updateStatusBarFromQueue());
this.taskQueue.onChange(() => this.schedulePersistHistory());
// Add/sync/crawl tasks completing is when the server's set of known
// documents changes, so re-count pending sync then. Vault file events
// alone miss it: adding a file fires a create event (pill appears),
// but nothing fires when the ingest finishes (pill would never clear).
this.taskQueue.onChange(() => this.schedulePendingSyncHint());
this.registerCommands();
this.registerEvent(
this.app.workspace.on("file-menu", (menu: Menu, file: TAbstractFile) => {
menu.addItem((item: MenuItem) => {
item.setTitle(MESSAGES.COMMAND_ADD_TO_LILBEE)
.setIcon("plus-circle")
.onClick(() => this.addToLilbee(file));
});
}),
);
// On first-ever load (setupCompleted === false), defer server start
// to the wizard's Server step. Otherwise users see the binary download
// fire before they've even picked managed vs. external, and the
// wizard arrives at the Model step against a server that isn't
// actually ready yet (empty catalog, failed reads).
if (this.settings.setupCompleted) {
if (this.settings.serverMode === SERVER_MODE.MANAGED && this.serverUninstalled) {
// The user removed the server on purpose. Wait to be asked.
this.showNotInstalledStatus();
} else if (this.settings.serverMode === SERVER_MODE.MANAGED) {
void this.ensureManagedConsentThenStart().then((outcome) => {
// If the user opts into external mode from the consent modal,
// drop them on the plugin's external-server settings.
if (outcome.kind === SETUP_OUTCOME.SWITCHED_TO_EXTERNAL) this.openPluginSettings();
if (outcome.kind === SETUP_OUTCOME.STARTED) void this.afterManagedStart();
});
} else {
this.configureApi(this.settings.serverUrl);
this.setStatusConnecting();
void this.fetchActiveModel();
void this.warnExternalServerOutdated();
}
}
// A run left part-way records a server but not a finished wizard, so the remaining steps still run.
if (!this.settings.wizardCompleted) {
new SetupWizard(this.app, this).open();
}
this.registerPendingSyncHintWatchers();
void this.updatePendingSyncHint();
this.startHealthProbe();
// No view is force-opened here: Obsidian restores whatever leaves the
// user left open. New users get the chat panel once, from the wizard.
// Defend against duplicate sidebar leaves persisted in workspace.json
// from prior sessions. activateChatView() is idempotent for one leaf,
// but Obsidian restores whatever was saved, so a workspace that ended
// up with two chat panes restores both.
this.app.workspace.onLayoutReady(() => {
this.dedupeLilbeeLeaves();
});
}
/** Remove lilbee pills + ribbon icons a dead instance left behind, across every reachable document. */
private sweepStaleChrome(): void {
const docs = new Set<Document>();
if (typeof activeDocument !== "undefined") docs.add(activeDocument);
if (typeof document !== "undefined") docs.add(document);
for (const doc of docs) {
// The first selector catches pills from before the marker class;
// the second catches everything carrying one.
doc.querySelectorAll(".status-bar-item.plugin-lilbee").forEach((el) => el.remove());
doc.querySelectorAll(".lilbee-status-pill, .lilbee-sync-pill, .lilbee-ribbon-icon").forEach((el) =>
el.remove(),
);
}
}
/** Collapse multiple lilbee-chat / -tasks / -wiki leaves to one of each. */
private dedupeLilbeeLeaves(): void {
for (const type of [VIEW_TYPE_CHAT, VIEW_TYPE_TASKS, VIEW_TYPE_WIKI, VIEW_TYPE_MEMORIES, VIEW_TYPE_PLACEMENT]) {
const leaves = this.app.workspace.getLeavesOfType(type);
for (let i = 1; i < leaves.length; i++) leaves[i].detach();
}
this.app.workspace.requestSaveLayout?.();
}
async startManagedServer(
onProgress?: ManagedServerProgressHandler,
allowTakeOver = true,
signal?: AbortSignal,
): Promise<void> {
if (this.startingServer) return;
const registry = this.vaultRegistry;
if (!registry) return;
if (this.serverUninstalled) {
this.showNotInstalledStatus();
return;
}
this.startingServer = true;
this.serverStartFailed = false;
try {
const sharedRoot = registry.sharedRoot;
// Wired before the binary ensure so download failures and early
// lifecycle lines persist to logs/plugin.log, not just memory.
this.journal.setLogDir(node.join(registry.resolveDataDir(this.vaultId), LOGS_DIR));
// A server predating the OS locks cannot refuse our spawn, so scan
// for a live server another vault started and offer the same
// take-over the refusal path does — instead of spawning next to it.
const foreignDataDir = await this.findLiveForeignServer(registry);
if (foreignDataDir !== null) {
// Negotiate outside this call's startingServer window.
window.setTimeout(() => {
void this.negotiateTakeOver(registry, onProgress, allowTakeOver, foreignDataDir, signal);
}, 0);
return;
}
const binary = new ServerBinary(sharedBinDir(sharedRoot));
const installed = await this.ensureBinaryWithUi(binary, onProgress, signal);
if (installed === null) return;
this.recordDownloadedBinary(installed);
// A spawn after unload would leak a server no plugin instance tracks.
if (this.unloaded) return;
try {
this.serverManager = this.buildServerManager(installed.path, registry, sharedRoot);
this.updateStatusBar(MESSAGES.STATUS_STARTING, DOT_STATE.PRIMARY);
this.setStatusClass("lilbee-status-starting");
onProgress?.({ phase: MANAGED_PHASE.STARTING, message: MESSAGES.STATUS_STARTING_SERVER });
await this.serverManager.start();
this.reconcileRecordedVersion();
this.configureApi(this.serverManager.serverUrl);
void this.fetchActiveModel();
void this.configureManagedStorage();
void this.runAgentBoot();
this.recordReadyState();
onProgress?.({ phase: MANAGED_PHASE.READY, message: "" });
} catch (err) {
if (err instanceof ScopeHeldError) {
this.serverManager = null;
// Recurse outside this call's startingServer window.
window.setTimeout(() => {
void this.negotiateTakeOver(registry, onProgress, allowTakeOver, null, signal);
}, 0);
return;
}
this.showError("failed to start server", err);
onProgress?.({ phase: MANAGED_PHASE.ERROR, message: errorMessage(err, String(err)) });
}
} finally {
this.startingServer = false;
}
}
/**
* Another vault's server holds the shared root — found by a refused spawn
* (*knownOwnerDataDir* null, owner read from the scope sidecar) or by the
* pre-spawn scan for servers predating the locks. Ask the user, ask that
* server to exit over its API, then start again — the server-side lock
* grace rides out the handoff. One round only: a second refusal lands in
* the quiet "serving another vault" state instead of a loop.
*/
private async negotiateTakeOver(
registry: VaultRegistry,
onProgress?: ManagedServerProgressHandler,
allowTakeOver = true,
knownOwnerDataDir: string | null = null,
signal?: AbortSignal,
): Promise<void> {
const owner: { dataDir: string; pid: number | null } | null = knownOwnerDataDir
? { dataDir: knownOwnerDataDir, pid: null }
: readScopeOwner(registry.sharedRoot);
const ownerName = owner ? await this.resolveOwnerName(owner.dataDir) : MESSAGES.LABEL_UNKNOWN_VAULT;
if (owner) {
this.updateStatusBar(MESSAGES.STATUS_LOCKED_BY_OTHER(ownerName), DOT_STATE.MUTED);
this.setStatusClass("lilbee-status-muted");
}
if (!allowTakeOver) {
this.updateStatusBar(MESSAGES.STATUS_LOCKED_BY_OTHER(ownerName), DOT_STATE.MUTED);
onProgress?.({
phase: MANAGED_PHASE.ERROR,
message: MESSAGES.NOTICE_TAKE_OVER_DECLINED(ownerName),
});
return;
}
const takeOver = await this.confirmTakeOver(ownerName);
if (!takeOver) {
this.journal.lifecycle(`take-over of the shared root declined (owner: ${ownerName})`);
new Notice(MESSAGES.NOTICE_TAKE_OVER_DECLINED(ownerName));
this.updateStatusBar(MESSAGES.STATUS_LOCKED_BY_OTHER(ownerName), DOT_STATE.MUTED);
onProgress?.({
phase: MANAGED_PHASE.ERROR,
message: MESSAGES.NOTICE_TAKE_OVER_DECLINED(ownerName),
});
return;
}
this.journal.lifecycle(
`take-over accepted: asking the server of ${ownerName}${owner?.pid != null ? ` (pid ${owner.pid})` : ""} to exit`,
);
if (owner && !(await askServerToExit(owner.dataDir, TAKE_OVER_SHUTDOWN_TIMEOUT_MS))) {
this.journal.lifecycle(`take-over failed: the server of ${ownerName} did not stop when asked`);
new Notice(MESSAGES.NOTICE_TAKE_OVER_TIMEOUT);
this.updateStatusBar(MESSAGES.STATUS_LOCKED_BY_OTHER(ownerName), DOT_STATE.MUTED);
return;
}
this.journal.lifecycle(`take-over complete: the server of ${ownerName} is gone; starting ours`);
new Notice(MESSAGES.NOTICE_TAKE_OVER_SUCCESS(ownerName));
await this.startManagedServer(onProgress, false, signal);
}
/**
* After a spawn, make the recorded version match what the binary reported.
* A wrong record would otherwise make adoption replace our own healthy
* server on every plugin reload. Never reconciled from an adopted server:
* its version may be the stale one a later start is meant to replace.
*/
private reconcileRecordedVersion(): void {
const sm = this.serverManager;
if (!sm || sm.isAdopted || !sm.spawnedVersion) return;
const reported = sm.spawnedVersion.replace(/^v/, "");
const recorded = this.getSharedLilbeeVersion();
if (recorded.replace(/^v/, "") === reported) return;
this.setSharedLilbeeVersion(`v${reported}`);
this.journal.lifecycle(
`recorded server version corrected to v${reported}${recorded ? ` (was ${recorded})` : ""}`,
);
}
/** Data dir of a live server another vault started, or null. Our own live server is the adopt path, not a foreigner. */
private async findLiveForeignServer(registry: VaultRegistry): Promise<string | null> {
const ourDataDir = registry.resolveDataDir(this.vaultId);
if (await serverIsLive(ourDataDir)) return null;
const others = registry.list().map((e) => registry.resolveDataDir(e.id));
const foreign = others.filter((dataDir) => dataDir !== ourDataDir);
const live = await Promise.all(
foreign.map(async (dataDir) => ((await serverIsLive(dataDir)) ? dataDir : null)),
);
return live.find((dataDir) => dataDir !== null) ?? null;
}
/** Display name of the registered vault whose server serves *dataDir*. */
private lookupVaultNameByDataDir(dataDir: string): string {
const registry = this.vaultRegistry;
const entry = registry?.list().find((e) => registry.resolveDataDir(e.id) === dataDir);
return entry?.displayName ?? MESSAGES.LABEL_UNKNOWN_VAULT;
}
/** Poll the registry for the owner vault's display name for up to two seconds. */
private resolveOwnerName(dataDir: string): Promise<string> {
const deadline = Date.now() + 2000;
return new Promise((resolve) => {
const poll = () => {
const name = this.lookupVaultNameByDataDir(dataDir);
if (name !== MESSAGES.LABEL_UNKNOWN_VAULT || Date.now() >= deadline) {
resolve(name);
return;
}
window.setTimeout(poll, 100);
};
poll();
});
}
/** If another vault owns the shared root, show "serving <vault>" and return true. */
private refreshLockedByOtherStatus(): boolean {
const registry = this.vaultRegistry;
if (!registry) return false;
const owner = readScopeOwner(registry.sharedRoot);
if (owner === null) return false;
const ourDataDir = registry.resolveDataDir(this.vaultId);
if (owner.dataDir === ourDataDir) return false;
const ownerName = this.lookupVaultNameByDataDir(owner.dataDir);
this.updateStatusBar(MESSAGES.STATUS_LOCKED_BY_OTHER(ownerName), DOT_STATE.MUTED);
this.setStatusClass("lilbee-status-muted");
return true;
}
/**
* Gate run before a first-time managed binary download. When the binary is
* already present we start straight away; otherwise we ask for consent and
* route on the user's choice (download / switch-to-external / cancel).
*/
async ensureManagedConsentThenStart(
onProgress?: ManagedServerProgressHandler,
signal?: AbortSignal,
): Promise<SetupOutcome> {
const registry = this.vaultRegistry;
if (!registry) return { kind: SETUP_OUTCOME.CANCELED };
const binDir = sharedBinDir(registry.sharedRoot);
const binaryPresent = new ServerBinary(binDir).installed() !== null;
if (binaryPresent && !this.serverUninstalled) {
// True up the baseline before starting, the way the branches below do.
this.recordServerBaseline();
await this.startManagedServer(onProgress, true, signal);
return { kind: SETUP_OUTCOME.STARTED, mode: SERVER_MODE.MANAGED };
}
// The gate owns the server lifecycle for each outcome, so it persists
// directly via persistAll() rather than saveSettings() — the latter
// would fire its own startManagedServer on a mode switch and race ours.
const result = await new ManagedConsentModal(this.app, this.settings.includeDevBuilds, binDir).openConsent();
if (result.kind === MANAGED_CONSENT_RESULT.DOWNLOAD) {
this.settings.serverMode = SERVER_MODE.MANAGED;
this.recordServerBaseline();
await this.persistAll();
this.setServerUninstalled(false);
await this.startManagedServer(onProgress, true, signal);
return { kind: SETUP_OUTCOME.STARTED, mode: SERVER_MODE.MANAGED };
}
if (result.kind === MANAGED_CONSENT_RESULT.EXTERNAL) {
this.settings.serverMode = SERVER_MODE.EXTERNAL;
this.recordServerBaseline();
await this.persistAll();
this.configureApi(this.settings.serverUrl);
void this.refreshExternalServerVersion();
this.setStatusReady();
new Notice(MESSAGES.NOTICE_SWITCHED_TO_EXTERNAL);
// Navigation to the external server settings is the caller's job:
// onload opens the plugin Settings tab; the wizard reveals its own
// inline URL/token fields. The gate itself never leaves the app.
return { kind: SETUP_OUTCOME.SWITCHED_TO_EXTERNAL };
}
new Notice(MESSAGES.NOTICE_SERVER_DOWNLOAD_CANCELED);
return { kind: SETUP_OUTCOME.CANCELED };
}
private buildServerManager(binaryPath: string, registry: VaultRegistry, sharedRoot: string): ServerManager {
return new ServerManager({
binaryPath,
dataDir: registry.resolveDataDir(this.vaultId),
sharedRoot,
modelsDir: sharedModelsDir(sharedRoot),
systemPrompts: () => ({
rag: this.settings.ragSystemPrompt,
general: this.settings.generalSystemPrompt,
}),
installedVersion: this.getSharedLilbeeVersion(),
onStateChange: (state) => this.handleServerStateChange(state),
onRestartsExhausted: (output: string) => {
if (this.serverStartFailed) return;
console.error(`[lilbee] server crashed; output:\n${output}`);
this.journal.record("server-crash", MESSAGES.ERROR_SERVER_CRASHED, output || undefined);
const detail = output ? `\n${output.split("\n").slice(-5).join("\n")}` : "";
const notice = new Notice(`${MESSAGES.ERROR_SERVER_CRASHED}${detail}`, NOTICE_PERMANENT);
this.attachExportLink(notice);
},
onScopeHeld: () => {
// Another vault took the root while this server was down. The
// restart path has no take-over of its own, so route it into the
// same negotiation a first start uses instead of dying silently.
const registry = this.vaultRegistry;
if (!registry) return;
this.serverManager = null;
void this.negotiateTakeOver(registry);
},
onShutdownFailure: (err: Error) => {
new Notice(`${MESSAGES.ERROR_SERVER_SHUTDOWN_FAILED}: ${err.message}`);
},
onJournal: (message: string) => this.journal.lifecycle(message),
});
}
private async confirmTakeOver(ownerName: string): Promise<boolean> {
const modal = new ConfirmModal(this.app, MESSAGES.CONFIRM_TAKE_OVER(ownerName));
modal.open();
return modal.result;
}
/** Aborts the in-flight server download, if any. Set while a download runs. */
private downloadController: AbortController | null = null;
/** The controller for one download. A caller's signal aborts it too, so the caller owns the download it asked for. */
private startDownloadController(signal?: AbortSignal): AbortController {
const controller = new AbortController();
// A listener never fires for a signal that aborted before this point, so read it as well.
signal?.addEventListener("abort", () => controller.abort(), { once: true });
if (signal?.aborted) controller.abort();
this.downloadController = controller;
return controller;
}
private finishDownload(): void {
this.downloadController = null;
}
/** True while a server binary is downloading, so the UI can offer to stop it. */
isDownloadingServer(): boolean {
return this.downloadController !== null;
}
/** Stop an in-flight server download. The partial file is discarded; any installed binary stays. */
cancelServerDownload(): void {
this.downloadController?.abort();
}
private async ensureBinaryWithUi(
binary: ServerBinary,
onProgress?: ManagedServerProgressHandler,
signal?: AbortSignal,
): Promise<EnsureResult | null> {
const missing = binary.installed() === null;
if (missing) {
this.updateStatusBar(MESSAGES.STATUS_DOWNLOADING, DOT_STATE.PRIMARY);
this.setStatusClass("lilbee-status-downloading");
onProgress?.({ phase: MANAGED_PHASE.DOWNLOADING, message: MESSAGES.STATUS_DOWNLOADING });
this.updateStatusBar(`lilbee: ${MESSAGES.STATUS_FETCHING_RELEASE}`, DOT_STATE.PRIMARY);
onProgress?.({ phase: MANAGED_PHASE.DOWNLOADING, message: MESSAGES.STATUS_FETCHING_RELEASE });
}
const ensure = (release: string | undefined, controller: AbortController): Promise<EnsureResult> =>
binary.ensure({
includeDev: this.settings.includeDevBuilds,
release,
onProgress: (progress) => {
this.updateStatusBar(downloadStatusBar(progress), DOT_STATE.PRIMARY);
onProgress?.({
phase: MANAGED_PHASE.DOWNLOADING,
message: downloadMessage(progress),
percent: downloadPercent(progress),
});
},
onQuarantineFailed: () => this.showGatekeeperHelp(),
signal: controller.signal,
});
try {
const downloaded = missing ? await this.downloadNewestBinary(ensure, signal) : null;
const installed = downloaded ?? (await ensure(undefined, this.startDownloadController(signal)));
this.finishDownload();
this.setStatusClass(null);
return installed;
} catch (err) {
this.finishDownload();
// Unloading aborted it, and the UI it would report to is gone.
if (this.unloaded) return null;
this.setStatusClass(null);
// Cancelling is a choice, not a failure: say so plainly and skip the error journal.
if (isDownloadCanceled(err)) {
new Notice(MESSAGES.NOTICE_DOWNLOAD_CANCELED);
this.updateStatusBar(MESSAGES.STATUS_NOT_INSTALLED, DOT_STATE.MUTED, false);
} else {
this.showError("failed to download server", err);
}
onProgress?.({ phase: MANAGED_PHASE.ERROR, message: errorMessage(err, String(err)) });
return null;
}
}
/** First run: download the newest release as the one binary install in flight. While another
* install runs, wait for it instead and return null. */
private async downloadNewestBinary(
ensure: (release: string, controller: AbortController) => Promise<EnsureResult>,
signal?: AbortSignal,
): Promise<EnsureResult | null> {
const running = this.binaryInstall;
if (running) {
await running.done;
return null;
}
const controller = this.startDownloadController(signal);
const tag = getLatestRelease(this.settings.includeDevBuilds).then((release) => release.tag);
return this.claimBinaryInstall(tag, async () => ensure(await tag, controller));
}
/** Tell the user how to allow the unsigned server when macOS Gatekeeper blocks it. */
private showGatekeeperHelp(): void {
new GatekeeperModal(this.app).open();
}
/** Remember which release and build a download installed; best-effort, the server runs either way. */
private recordDownloadedBinary(installed: EnsureResult): void {
if (installed.source !== ENSURE_SOURCE.DOWNLOAD) return;
try {
this.recordInstalledBinary(installed);
} catch (err) {
this.journal.lifecycle(`could not record the downloaded server version: ${errorMessage(err, String(err))}`);
}
}
/** Record the release, the build, and the probe that chose it in the shared config. */
private recordInstalledBinary(installed: EnsureResult): void {
this.setSharedLilbeeVersion(installed.release);
this.setSharedLilbeeVariant(installed.variant, installed.detection);
if (installed.detection)
this.journalGpuDetection("gpu detection at install", installed.variant, installed.detection);
}
/** Persist the registry entry once the server is up. */
private recordReadyState(): void {
const sm = this.serverManager;
const registry = this.vaultRegistry;
if (!sm || !registry) return;
const now = Date.now();
const existing = registry.get(this.vaultId);
registry.upsert({
id: this.vaultId,
displayName: existing?.displayName ?? this.getVaultDisplayName(),
dataDir: sm.dataDir,
obsidianVaultPath: this.getVaultBasePath(),
addedAt: existing?.addedAt ?? now,
lastActiveAt: now,
});
}
/** Wiring state for the settings status line; the token it wrote dies with the server. */
lastAgentWrite: AgentWireOutcome | null = null;
private agentWiring(): AgentWiring {
return new AgentWiring(this.app, this.api);
}
/**
* Rewrite the paired agent's config, then offer the picker if nothing is
* paired yet. Started with `void` during boot, so it absorbs its own
* failures rather than surfacing as an unhandled rejection.
*/
private async runAgentBoot(): Promise<void> {
try {
const { agent, keepConfigFresh } = this.settings.agentIntegration;
if (agent !== AGENT_SELECTION.NONE) {
if (keepConfigFresh) await this.applyAgentWiring(agent, { silent: true });
return;
}
await this.maybeShowAgentPicker();
} catch (err) {
this.journal.lifecycle(`agent integration failed: ${errorMessage(err, String(err))}`);
}
}
/**
* Fetch *client*'s config and write it into the vault. A boot refresh passes
* `silent` so a healthy rewrite says nothing; failures always surface.
*/
async applyAgentWiring(client: AgentClient, opts?: { silent?: boolean }): Promise<void> {
const result = await this.agentWiring().apply(client);
if (result.isErr()) {
new Notice(MESSAGES.NOTICE_AGENT_CONFIG_FAILED(errorMessage(result.error, String(result.error))));
return;
}
this.lastAgentWrite = result.value;
if (!opts?.silent) {
const label = AGENT_LABELS[client];
new Notice(
result.value.path === null
? MESSAGES.NOTICE_AGENT_CONNECTED_GLOBAL(label)
: MESSAGES.NOTICE_AGENT_CONNECTED(label),
);
}
if (result.value.claudian === CLAUDIAN_OUTCOME.WRITTEN && isClaudianLoaded(this.app)) {
this.offerClaudianReload();
}
this.refreshSettingsTab();
}
/** Claudian caches its data file at load, so a change only lands after a reload. */
private offerClaudianReload(): void {
this.offerAction(
MESSAGES.NOTICE_CLAUDIAN_UPDATED,
MESSAGES.BUTTON_RELOAD_CLAUDIAN,
() => void reloadClaudian(this.app),
);
}
/** A notice that stays up until the user takes its action or dismisses it. */
private offerAction(message: string, label: string, act: () => void): void {
const notice = new Notice(message, NOTICE_PERMANENT);
const link = notice.messageEl.createEl("a", { text: label });
link.addEventListener("click", () => {
notice.hide();
act();
});
}
/** Offer the picker the first time lilbee sees an agent CLI on this machine. */
private async maybeShowAgentPicker(): Promise<void> {
if (this.settings.agentIntegration.pickerShown) return;
// Deferred, not dropped: the wizard re-offers pairing on close.
if (this.setupWizardOpen) {
this.agentPickerDeferred = true;
return;
}
const index = await this.api.getAgentConfigIndex();
if (index.isErr()) return;
const detections = index.value.clients;
if (!detections.some((d) => d.cli_detected)) return;
if (this.unloaded) return;
const modal = new AgentPickerModal(this.app, detections, isClaudianInstalled(this.app));
const choice = await modal.openPicker();
if (choice.kind === AGENT_PICKER_RESULT.DISMISS) {
this.settings.agentIntegration.pickerShown = true;
await this.persistAgentIntegration();
return;
}
// Connecting answers the question; `remember` decides only whether the selection is kept.
this.settings.agentIntegration.pickerShown = true;
if (choice.remember) this.settings.agentIntegration.agent = choice.client;
await this.persistAgentIntegration();
await this.applyAgentWiring(choice.client);
}
/** Offer the agent pairing the setup wizard pushed aside, now that it has the screen back. */
async resumeDeferredAgentPicker(): Promise<void> {
if (!this.agentPickerDeferred) return;
this.agentPickerDeferred = false;
await this.runAgentBoot();
}
/** Agent settings never change the server mode, so they skip saveSettings' restart logic. */
async persistAgentIntegration(): Promise<void> {
await this.persistAll();
this.refreshSettingsTab();
}
/** This vault's server data directory, or null before the registry loads. */
private ownDataDir(): string | null {
const registry = this.vaultRegistry;
return registry ? registry.resolveDataDir(this.vaultId) : null;
}
/** Where the managed server keeps content when it is not stored in the vault. */
private serverOwnedDocumentsDir(): string | null {
const dataDir = this.ownDataDir();
return dataDir === null ? null : node.join(dataDir, "documents");
}
/** Tell the managed server where to keep content: under the vault, or in its own data dir. */
async configureManagedStorage(): Promise<void> {
if (this.settings.serverMode !== SERVER_MODE.MANAGED) return;
const target = this.wantedStorageLayout();
if (target === null) return;
if (this.alreadyRefusedStorage(target)) {
this.journal.lifecycle("storage move skipped: the server already refused this layout");
return;
}
if (await this.serverStorageMatches(target)) return;
await this.sendStorageMove(target);
}
/** The layout the plugin wants, or null while the data dir is unknown. */
private wantedStorageLayout(): StorageMoveTarget | null {
// Opting out names the data dir explicitly; the server has no reset for documents_dir.
const storeInVault = this.settings.storeContentInVault;
const vaultBase = this.getVaultBasePath();
const documentsDir = storeInVault ? `${vaultBase}/lilbee` : this.serverOwnedDocumentsDir();
if (documentsDir === null) return null;
return { documentsDir, vaultBase: storeInVault ? vaultBase : null };
}
/** True when the server already refused this exact layout. */
private alreadyRefusedStorage(target: StorageMoveTarget): boolean {
const refused = this.settings.rejectedStorageMove;
return (
refused !== null && refused.documentsDir === target.documentsDir && refused.vaultBase === target.vaultBase
);
}
/** True when the server already has this layout. An unreadable config counts as a match. */
private async serverStorageMatches(target: StorageMoveTarget): Promise<boolean> {
let current: Record<string, unknown>;
try {
current = await this.api.config();
} catch {
new Notice(MESSAGES.ERROR_STORAGE_CHECK_FAILED, NOTICE_ERROR_DURATION_MS);
return true;
}
const currentDocs = typeof current.documents_dir === "string" ? current.documents_dir : "";
const currentVault = typeof current.vault_base === "string" ? current.vault_base : null;
return currentDocs === target.documentsDir && currentVault === target.vaultBase;
}
/** Move the server's storage, clearing any remembered refusal once it lands. */
private async sendStorageMove(target: StorageMoveTarget): Promise<void> {
const notice = new Notice(MESSAGES.NOTICE_STORAGE_REORGANIZING, NOTICE_PERMANENT);
try {
await applyConfig(this, {
documents_dir: target.documentsDir,
vault_base: target.vaultBase,
});
notice.hide();
this.settings.rejectedStorageMove = null;
await this.persistAll();
new Notice(MESSAGES.NOTICE_STORAGE_REORGANIZED);
} catch (err) {
notice.hide();
await this.reportStorageMoveFailure(target, err);
}
}
/** Say why a move failed, and remember a layout the server itself refused. */
private async reportStorageMoveFailure(target: StorageMoveTarget, err: unknown): Promise<void> {
// Only a 4xx is a refusal; a 5xx or an unanswered request is retried next start.
const message = errorMessage(err, String(err));
const answered = hasStatusLine(err);
const refused = isClientError(err);
if (refused) {
this.settings.rejectedStorageMove = target;
await this.persistAll();
}
// A status line is not a reason: show the server's detail when it answered.
const reason = answered ? extractServerErrorDetail(message) : message;
const dataDir = this.ownDataDir();
const logPath = dataDir === null ? null : node.join(dataDir, LOGS_DIR, LOG_FILE.SERVER);
new Notice(MESSAGES.NOTICE_STORAGE_REORGANIZE_FAILED(reason, logPath, !refused), NOTICE_ERROR_DURATION_MS);
console.error("[lilbee] storage reorganisation failed", err);
}
/** True when the shared bin dir holds a server binary this vault can run. */
isServerInstalled(): boolean {
const registry = this.vaultRegistry;
if (!registry) return false;
return new ServerBinary(sharedBinDir(registry.sharedRoot)).installed() !== null;
}
/** Size what an uninstall would delete, so the confirmation can list it. */
planServerUninstall(): UninstallPlan | null {
const registry = this.vaultRegistry;
if (!registry) return null;
return planUninstall(registry.sharedRoot, registry.resolveDataDir(this.vaultId));
}
/**
* Delete the server binary, the shared models, and this vault's index, then
* remember the choice so no later launch downloads the server again.
* Returns the bytes freed. Vault documents are never touched.
*/
async uninstallServer(plan: UninstallPlan): Promise<number> {
const registry = this.vaultRegistry;
if (!registry) return 0;
// The binary and the models are shared. Deleting them under another
// vault's running server would break it mid-query.
const owner = readScopeOwner(registry.sharedRoot);
const ownDataDir = registry.resolveDataDir(this.vaultId);
if (owner !== null && owner.dataDir !== ownDataDir) {
throw new Error(MESSAGES.ERROR_UNINSTALL_SERVER_IN_USE(this.lookupVaultNameByDataDir(owner.dataDir)));
}
await this.serverManager?.stop();
this.serverManager = null;
// A server orphaned by a crashed Obsidian still writes to the data dir;
// ask it to exit before deleting the tree out from under it.
if (owner !== null) await askServerToExit(owner.dataDir, TAKE_OVER_SHUTDOWN_TIMEOUT_MS);
await executeUninstall(plan, registry.sharedRoot, ownDataDir);
registry.saveConfig({
...registry.loadConfig(),
lilbeeVersion: "",
lilbeeVariant: "",
lilbeeDetection: null,
serverAutoUpdate: true,
serverUninstalled: true,
});
this.serverUninstalled = true;
this.serverEverReady = false;
this.serverUnreachable = false;
this.showNotInstalledStatus();
return plan.totalBytes;
}
/** Download *release* and start it, clearing an earlier uninstall. */
async installServer(release: ReleaseInfo, onProgress?: ServerDownloadProgressHandler): Promise<void> {
this.setServerUninstalled(false);
await this.updateServer(release, onProgress);
}
private showNotInstalledStatus(): void {
this.updateStatusBar(MESSAGES.STATUS_NOT_INSTALLED, DOT_STATE.MUTED, false);
this.setStatusClass(null);
}
/** Journal which build the GPU probe chose and why. */
private journalGpuDetection(context: string, variant: ServerVariant, detection: GpuDetection): void {
this.journal.lifecycle(
`${context}: ${MESSAGES.LABEL_SERVER_BUILD(variant)} build. ` + MESSAGES.DESC_GPU_DETECTION(detection),
);
}
async checkForUpdate(): Promise<{ available: boolean; release?: ReleaseInfo }> {
const release = await getLatestRelease(this.settings.includeDevBuilds);
this.journalGpuDetection("gpu detection at update check", release.variant, release.detection);
const versionChanged = checkForUpdate(this.getSharedLilbeeVersion(), release.tag);
// A known installed variant that differs from the detected one means the
// hardware-appropriate build changed (e.g. an NVIDIA driver was added).
const installedVariant = this.getSharedLilbeeVariant();
const variantChanged = installedVariant !== "" && installedVariant !== release.variant;
if (versionChanged || variantChanged) {
return { available: true, release };
}
return { available: false };
}
/** Once per plugin version, fetch the latest server release and install it if newer. */
private async autoUpdateServerBinary(): Promise<void> {
const registry = this.vaultRegistry;
if (!registry) return;
if (this.serverUninstalled) return;
const config = registry.loadConfig();
if (!config.serverAutoUpdate) {
this.journal.lifecycle("automatic server update skipped: turned off in settings");
await this.remindServerUpdate(config.serverUpdateReminder);
return;
}
if (config.lastUpdateCheckPluginVersion === this.manifest.version) return;
let result: { available: boolean; release?: ReleaseInfo };
try {
result = await this.checkForUpdate();
} catch {
// offline or rate-limited; the next load retries
return;
}
registry.saveConfig({ ...config, lastUpdateCheckPluginVersion: this.manifest.version });
if (!result.available || !result.release) return;
const release = result.release;
// A build switch keeps the version it already has, so naming the version would
// report an update to the version the user is on. Name the build instead.
const installedVariant = this.getSharedLilbeeVariant();
const build =
installedVariant !== "" && installedVariant !== release.variant
? MESSAGES.LABEL_SERVER_BUILD(release.variant)
: null;
const notice = new Notice(
build ? MESSAGES.NOTICE_SERVER_SWITCHING_BUILD(build) : MESSAGES.NOTICE_SERVER_AUTO_UPDATING(release.tag),
NOTICE_PERMANENT,
);
try {
await this.updateServer(release);
new Notice(
build ? MESSAGES.NOTICE_SERVER_SWITCHED_BUILD(build) : MESSAGES.NOTICE_SERVER_AUTO_UPDATED(release.tag),
);
} catch (err) {
if (this.unloaded) return;
if (err instanceof ServerUpdateBusyError) new Notice(err.message);
else new Notice(MESSAGES.NOTICE_SERVER_AUTO_UPDATE_FAILED, NOTICE_ERROR_DURATION_MS);
} finally {
notice.hide();
}
}
/** Work that needs a running server, in order: the update check, then the build cross-check. */
private async afterManagedStart(): Promise<void> {
await this.autoUpdateServerBinary();
await this.offerCudaBuild();
}
/** The installed build against the devices the running server reports. A default
* build chosen without the driver's CUDA version, on a host reporting an NVIDIA
* card, gets the CUDA build offered once. */
private async offerCudaBuild(): Promise<void> {
const registry = this.vaultRegistry;
if (!registry) return;
const config = registry.loadConfig();
if (config.cudaBuildOffered) return;
if (this.getSharedLilbeeVariant() !== SERVER_VARIANT.DEFAULT) return;
if (!cudaVersionUnknown(this.getSharedGpuDetection())) return;
let devices: readonly GpuInfo[] | null;
try {
devices = await readFleetDevices(this.api);
} catch (err) {
this.journal.record("cuda-cross-check", errorMessage(err, String(err)));
return;
}
if (devices === null || !hasNvidiaDevice(devices)) return;
registry.saveConfig({ ...config, cudaBuildOffered: true });
const build = MESSAGES.LABEL_SERVER_BUILD(SERVER_VARIANT.DEFAULT);
this.journal.lifecycle(`cuda cross-check: the server reports an NVIDIA device on the ${build} build`);
this.offerAction(MESSAGES.NOTICE_CUDA_BUILD_AVAILABLE(build), MESSAGES.BUTTON_OPEN_UPDATE_SETTINGS, () =>
this.openServerUpdateSettings(),
);
}
/** The single place `externalServerVersion` gets (re)read outside the probe
* tick: clears the cached value, then fills it from a fresh health check,
* staying "" (which fails open) when the server doesn't answer. Call
* whenever the plugin starts pointing at a (re)configured external server,
* including a mode or URL switch, not only at launch. Shares a generation
* counter with the probe tick, so a response that resolves out of order
* (an earlier switch's check answering after a later one) is discarded
* instead of overwriting the newer answer. */
private async refreshExternalServerVersion(): Promise<Result<HealthResponse, Error> | null> {
const generation = ++this.externalVersionGeneration;
this.externalServerVersion = "";
const health = await this.api.health().catch(() => null);
if (generation === this.externalVersionGeneration && health?.isOk()) {
this.externalServerVersion = health.value.version;
}
return health;
}
/** External mode: on launch, tell the user when the running server is not the
* latest release. Best-effort — silent when offline or the server is unreachable. */
private async warnExternalServerOutdated(): Promise<void> {
try {
const health = await this.refreshExternalServerVersion();
if (!health || health.isErr()) return;
const latest = (await getLatestRelease(this.settings.includeDevBuilds)).tag.replace(/^v/, "");
if (!latest || !isVersionOlder(health.value.version, latest)) return;
// NOTICE_PERMANENT keeps it up until the user clicks it away.
new Notice(MESSAGES.NOTICE_EXTERNAL_SERVER_OUTDATED(health.value.version, latest), NOTICE_PERMANENT);
} catch {
// offline, unreachable, or rate-limited — stay quiet
}
}
/** The server binary install in flight (an update, a Settings install, or the first-run
* download) and the release it fetches; cleared when it settles. */
private binaryInstall: { tag: Promise<string>; done: Promise<unknown> } | null = null;
private claimBinaryInstall<T>(tag: Promise<string>, install: () => Promise<T>): Promise<T> {
const done = install().finally(() => {
this.binaryInstall = null;
});
this.binaryInstall = { tag, done };
return done;
}
/** Install *release* and restart. One binary install runs at a time: a request for the
* release it fetches joins it, and a request for another release is refused. */
async updateServer(release: ReleaseInfo, onProgress?: ServerDownloadProgressHandler): Promise<void> {
const running = this.binaryInstall;
if (running) {
const runningTag = await running.tag;
if (runningTag !== release.tag) throw new ServerUpdateBusyError(runningTag);
await running.done;
return;
}
await this.claimBinaryInstall(Promise.resolve(release.tag), () => this.installRelease(release, onProgress));
}
private async installRelease(release: ReleaseInfo, onProgress?: ServerDownloadProgressHandler): Promise<void> {
const registry = this.vaultRegistry;
if (!registry) return;
this.journal.lifecycle(
`updating server binary: ${this.getSharedLilbeeVersion() || "(unknown)"} -> ${release.tag}`,
);
const binary = new ServerBinary(sharedBinDir(registry.sharedRoot));
// Stop the running server first
if (this.serverManager) {
onProgress?.("Stopping server...");
await this.serverManager.stop();
this.serverManager = null;
}
// Download the new binary (replaces the old one once its checksum clears)
onProgress?.(MESSAGES.STATUS_DOWNLOAD_STARTING);
let installed: EnsureResult;
try {
installed = await binary.ensure({
includeDev: this.settings.includeDevBuilds,
release: release.tag,
force: true,
onProgress: (progress) => onProgress?.(downloadMessage(progress), downloadPercent(progress)),
onQuarantineFailed: () => this.showGatekeeperHelp(),
signal: this.startDownloadController().signal,
});
} finally {
this.finishDownload();
}
this.recordInstalledBinary(installed);
this.journal.lifecycle(`server binary updated to ${installed.release}`);
this.clearUpdateIndicator();
// Restart if in managed mode
if (this.settings.serverMode === SERVER_MODE.MANAGED) {
onProgress?.("Starting server...");
await this.startManagedServer();
}
onProgress?.("Update complete.");
}
/** Journal lilbee-originated window errors and unhandled rejections. */
private registerErrorCapture(): void {
this.registerDomEvent(window, "error", (e: ErrorEvent) => {
const stack: string = e.error instanceof Error ? (e.error.stack ?? "") : "";
if (stack.includes("lilbee")) this.journal.record("window", e.message, stack);
});
this.registerDomEvent(window, "unhandledrejection", (e: PromiseRejectionEvent) => {
const reason: unknown = e.reason;
if (!(reason instanceof Error)) return;
const stack = reason.stack ?? "";
if (stack.includes("lilbee")) this.journal.record("unhandledrejection", reason.message, stack);
});
}
private attachExportLink(notice: Notice): void {
const link = notice.messageEl.createEl("a", { text: MESSAGES.BUTTON_EXPORT_DIAGNOSTICS });
link.addEventListener("click", () => void this.diagnosticsContext().then(exportDiagnostics));
}
/** Snapshot of plugin + server state for the diagnostics collector. The engine
* backend is only the server's to answer, so the snapshot asks for it. */
async diagnosticsContext(): Promise<DiagnosticsContext> {
return {
dataDir: this.serverManager?.dataDir ?? null,
sharedRoot: this.vaultRegistry?.sharedRoot ?? null,
settings: this.settings,
journalEntries: this.journal.entries,
pluginVersion: this.manifest.version,
serverVersion: this.getSharedLilbeeVersion(),
serverVariant: this.getSharedLilbeeVariant(),
gpuDetection: this.getSharedGpuDetection(),
engineBackend: await this.readEngineBackend(),
serverState: this.serverManager?.state ?? SERVER_STATE.STOPPED,
serverUrl: this.serverManager?.serverUrl ?? this.settings.serverUrl,
serverBinaryPath: this.serverManager?.binaryPath ?? null,
lastOutput: this.serverManager?.lastOutput ?? "",
};
}
/** The backend the server reports, or null with the reason journalled. */
private async readEngineBackend(): Promise<EngineBackend | null> {
try {
return await readEngineBackend(this.api);
} catch (err) {
this.journal.record("engine-backend", errorMessage(err, String(err)));
return null;
}
}
private showError(label: string, err: unknown): void {
const detail = errorMessage(err, String(err));
this.journal.record(label, detail, err instanceof Error ? err.stack : undefined);
console.error(`[lilbee] ${label}:`, err);
const output = this.serverManager?.lastOutput;
if (output) console.error(`[lilbee] server output:\n${output}`);
const outputTail = output ? `\n${output.split("\n").slice(-5).join("\n")}` : "";
const notice = new Notice(`lilbee: ${label}: ${detail}${outputTail}`, NOTICE_ERROR_DURATION_MS);
if (this.serverManager !== null) this.attachExportLink(notice);
this.updateStatusBar(MESSAGES.STATUS_ERROR, DOT_STATE.ERROR);
this.setStatusClass(null);
this.serverStartFailed = true;
}
private handleServerStateChange(state: ServerState): void {
// The managed child fires state transitions even after the user has
// switched to External mode (e.g. STOPPED on the way out). Painting
// "stopped" / "starting" / "error" from a now-irrelevant managed
// process would lie about the user's actually-reachable external
// server, so external mode owns its own status — set optimistically
// by saveSettings on the mode switch and corrected by the health
// probe thereafter.
if (this.settings.serverMode === SERVER_MODE.EXTERNAL) return;
switch (state) {
case SERVER_STATE.READY:
if (this.serverManager) {
this.configureApi(this.serverManager.serverUrl);
}
this.serverUnreachable = false;
this.serverEverReady = true;
this.setStatusReady();
this.refreshSettingsTab();
new Notice(MESSAGES.STATUS_READY, NOTICE_DURATION_MS);
break;
case SERVER_STATE.STARTING:
this.updateStatusBar(MESSAGES.STATUS_STARTING, DOT_STATE.PRIMARY);
this.setStatusClass("lilbee-status-starting");
break;
case SERVER_STATE.ERROR:
// A clean exit while another vault holds the shared root is a
// take-over, not a crash. Show "serving <vault>" instead of
// "error" so the loser knows who won without a restart loop.
if (this.refreshLockedByOtherStatus()) return;
this.updateStatusBar(MESSAGES.STATUS_ERROR, DOT_STATE.ERROR);
this.setStatusClass("lilbee-status-error");
break;
case SERVER_STATE.STOPPED:
this.updateStatusBar(MESSAGES.STATUS_STOPPED, DOT_STATE.MUTED);
this.setStatusClass(null);
break;
}
}
private getVaultBasePath(): string {
const adapter = this.app.vault.adapter as unknown as VaultAdapter;
return adapter.getBasePath();
}
/**
* Read the lilbee session token.
*
* Managed mode: server-manager's dataDir owns the token. `manualToken`
* is only consulted in external mode -- sending an external-mode paste
* to the managed server produces a misleading "paste a new token" error.
*
* External mode: auto-discovers the user's data root the same way lilbee
* itself does (LILBEE_DATA env > .lilbee walk-up > platform default).
*/
readCurrentToken(): string | null {
if (this.settings.serverMode === SERVER_MODE.MANAGED) {
return this.serverManager ? readSessionToken(this.serverManager.dataDir) : null;
}
if (this.settings.manualToken) {
return this.settings.manualToken;
}
const dataRoot = resolveExternalDataRoot(this.getVaultBasePath());
return readSessionToken(dataRoot);
}
/** Point the API client at *baseUrl* and re-bind the hooks. Updates the
* existing client instance in place so any caller already mid-await on
* fetchWithRetry (waiting for the server to come up) sees the new URL
* land instead of being orphaned on a replaced reference. */
private configureApi(baseUrl: string): void {
this.api.setBaseUrl(baseUrl);
this.api.setTokenProvider(() => this.readCurrentToken());
this.api.setToken(this.readCurrentToken());
this.api.setOutcomeCallback((outcome) => this.handleRequestOutcome(outcome));
}
/** Update the status bar to reflect the latest API outcome. */
private handleRequestOutcome(outcome: RequestOutcome): void {
if (outcome === REQUEST_OUTCOME.OK) {
this.setStatusReady();
return;
}
if (outcome === REQUEST_OUTCOME.AUTH_ERROR) {
this.updateStatusBar(MESSAGES.STATUS_AUTH_ERROR, DOT_STATE.ERROR);
this.setStatusClass("lilbee-status-error");
return;
}
if (outcome === REQUEST_OUTCOME.UPGRADING) {
this.paintLibraryUpgrade(this.libraryUpgrade);
return;
}
if (outcome === REQUEST_OUTCOME.SERVER_ERROR || outcome === REQUEST_OUTCOME.UNREACHABLE) {
// Before the managed server has ever reached READY, a failed
// request means it's still coming up — don't flash a red error.
if (this.settings.serverMode === SERVER_MODE.MANAGED && !this.serverEverReady) return;
this.updateStatusBar(MESSAGES.STATUS_ERROR, DOT_STATE.ERROR);
this.setStatusClass("lilbee-status-error");
}
// "starting" is a no-op — the existing startup UI already says so.
}
/**
* Whether lilbee can actually serve requests right now. Managed mode
* needs a live server-manager that isn't flagged unreachable; external
* mode trusts the user's server until a probe says otherwise.
*
* Server-dependent commands gate their checkCallback on this so the
* command palette doesn't offer (and silently fail) catalog / chat /
* crawl / sync while the managed server is stopped — when it's down,
* the only lilbee command offered is the one that starts it.
*/
private isLilbeeReady(): boolean {
if (this.settings.serverMode === SERVER_MODE.EXTERNAL) {
return !this.serverUnreachable;
}
return this.serverManager !== null && !this.serverUnreachable;
}
private registerCommands(): void {
this.addCommand({
id: "search",
name: MESSAGES.COMMAND_SEARCH,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) new SearchModal(this.app, this).open();
return true;
},
});
this.addCommand({
id: "chat",
name: MESSAGES.COMMAND_CHAT,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) void this.activateChatView();
return true;
},
});
this.addCommand({
id: "open-memories",
name: MESSAGES.COMMAND_MEMORIES,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) void this.activateMemoriesView();
return true;
},
});
this.addCommand({
id: "open-placement",
name: MESSAGES.COMMAND_PLACEMENT,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) void this.openPlacementGated(() => this.activatePlacementView());
return true;
},
});
this.addCommand({
id: "open-placement-beside-chat",
name: MESSAGES.COMMAND_PLACEMENT_BESIDE_CHAT,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
const chatLeaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0];
if (!chatLeaf) return false;
if (!checking) void this.openPlacementGated(() => this.openPlacementBesideChat(chatLeaf));
return true;
},
});
this.addCommand({
id: "fork-current-chat",
name: MESSAGES.COMMAND_FORK_CHAT,
checkCallback: (checking) => {
if (!this.isLilbeeReady() || !this.serverSupportsSessionFork()) return false;
const chatLeaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0];
if (!chatLeaf || !(chatLeaf.view instanceof ChatView)) return false;
const view = chatLeaf.view;
const sessionId = view.currentSessionId();
if (!sessionId) return false;
if (!checking) {
this.revealChatLeaf(chatLeaf);
void view.forkSession(sessionId);
}
return true;
},
});
this.addCommand({
id: "export-chat-to-file",
name: MESSAGES.COMMAND_EXPORT_CHAT,
checkCallback: (checking) => {
const chatLeaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0];
if (!chatLeaf || !(chatLeaf.view instanceof ChatView)) return false;
if (!checking) {
this.revealChatLeaf(chatLeaf);
void chatLeaf.view.exportToFile();
}
return true;
},
});
this.addCommand({
id: "remember",
name: MESSAGES.COMMAND_REMEMBER,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) new RememberModal(this.app, this).open();
return true;
},
});
this.addCommand({
id: "add-file",
name: MESSAGES.COMMAND_ADD_FILE,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
const file = this.app.workspace.getActiveFile();
if (!file) return false;
if (!checking) void this.addToLilbee(file);
return true;
},
});
this.addCommand({
id: "add-folder",
name: MESSAGES.COMMAND_ADD_FOLDER,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
const file = this.app.workspace.getActiveFile();
const folder = file?.parent;
if (!folder) return false;
if (!checking) void this.addToLilbee(folder);
return true;
},
});
this.addCommand({
id: "sync",
name: MESSAGES.COMMAND_SYNC,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) void this.triggerSync();
return true;
},
});
this.addCommand({
id: "sync-retry-skipped",
name: MESSAGES.COMMAND_SYNC_RETRY_SKIPPED,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) void this.triggerSync({ retrySkipped: true });
return true;
},
});
this.addCommand({
id: "sync-rebuild",
name: MESSAGES.COMMAND_SYNC_REBUILD,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) {
void (async () => {
const confirmModal = new ConfirmModal(this.app, MESSAGES.CONFIRM_SYNC_REBUILD);
confirmModal.open();
if (await confirmModal.result) void this.triggerSync({ forceRebuild: true });
})();
}
return true;
},
});
this.addCommand({
id: "export-dataset",
name: MESSAGES.COMMAND_EXPORT_DATASET,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) void exportDatasetToDisk(this.api);
return true;
},
});
this.addCommand({
id: "import-dataset",
name: MESSAGES.COMMAND_IMPORT_DATASET,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) void importDatasetFromDisk(this.app, this.api, this.taskQueue);
return true;
},
});
this.addCommand({
id: "catalog",
name: MESSAGES.COMMAND_CATALOG,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) new CatalogModal(this.app, this).open();
return true;
},
});
this.addCommand({
id: "model-picker-chat",
name: MESSAGES.COMMAND_MODEL_PICKER_CHAT,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) new ModelPickerModal(this.app, this, MODEL_TASK.CHAT).open();
return true;
},
});
this.addCommand({
id: "model-picker-embedding",
name: MESSAGES.COMMAND_MODEL_PICKER_EMBED,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) new ModelPickerModal(this.app, this, MODEL_TASK.EMBEDDING).open();
return true;
},
});
this.addCommand({
id: "model-info-active-chat",
name: MESSAGES.COMMAND_MODEL_INFO_CHAT,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) void this.openModelInfoForActiveTask(MODEL_TASK.CHAT);
return true;
},
});
this.addCommand({
id: "model-info-active-embedding",
name: MESSAGES.COMMAND_MODEL_INFO_EMBED,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) void this.openModelInfoForActiveTask(MODEL_TASK.EMBEDDING);
return true;
},
});
this.addCommand({
id: "crawl",
name: MESSAGES.COMMAND_CRAWL,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) new CrawlModal(this.app, this).open();
return true;
},
});
this.addCommand({
id: "documents",
name: MESSAGES.COMMAND_DOCUMENTS,
checkCallback: (checking) => {
if (!this.isLilbeeReady()) return false;
if (!checking) new DocumentsModal(this.app, this).open();
return true;
},
});
this.addCommand({
id: "setup",
name: MESSAGES.COMMAND_SETUP,
callback: () => new SetupWizard(this.app, this).open(),
});
this.addCommand({
id: "tasks",
name: MESSAGES.COMMAND_TASKS,
callback: () => this.activateTaskView(),
});
this.addCommand({
id: "arrange-views",
name: "Arrange views",
callback: () => this.arrangeViews(),
});
this.addCommand({
id: "wiki",
name: MESSAGES.COMMAND_WIKI,
checkCallback: (checking) => {
if (!this.wikiEnabled) return false;
if (!checking) void this.activateWikiView();
return true;
},
});
this.addCommand({
id: "wiki-lint",
name: MESSAGES.COMMAND_WIKI_LINT,
checkCallback: (checking) => {
if (!this.wikiEnabled) return false;
if (!checking) void this.runWikiLint();
return true;
},
});
this.addCommand({
id: "wiki-drafts",
name: MESSAGES.COMMAND_REVIEW_DRAFTS,
checkCallback: (checking) => {
if (!this.wikiEnabled) return false;
if (!checking) new DraftModal(this.app, this).open();
return true;
},
});
this.addCommand({
id: "wiki-update",
name: MESSAGES.COMMAND_WIKI_UPDATE,
checkCallback: (checking) => {
if (!this.wikiEnabled) return false;
if (!checking) void this.runWikiUpdate();
return true;
},
});
this.addCommand({
id: "status",
name: MESSAGES.COMMAND_STATUS,
callback: () => new StatusModal(this.app, this).open(),
});
// Plain callback: exporting diagnostics must work while the server is down.
this.addCommand({
id: "export-diagnostics",
name: MESSAGES.BUTTON_EXPORT_DIAGNOSTICS,
callback: () => void this.diagnosticsContext().then(exportDiagnostics),
});
this.addCommand({
id: "take-over",
name: MESSAGES.COMMAND_TAKE_OVER,
checkCallback: (checking) => {
if (this.settings.serverMode !== SERVER_MODE.MANAGED) return false;
if (this.serverManager !== null) return false;
if (!checking) void this.startManagedServer();
return true;
},
});
}
/**
* Re-point this vault at a different lilbee data-dir. Used by Settings →
* "Use existing lilbee data directory" so a user can adopt an existing
* `lilbee serve` data-dir or one they moved manually from the old layout.
*/
async adoptDataDir(dataDir: string): Promise<void> {
const registry = this.vaultRegistry;
if (!registry) return;
const existing = registry.get(this.vaultId);
const now = Date.now();
registry.upsert({
id: this.vaultId,
displayName: existing?.displayName ?? this.getVaultDisplayName(),
dataDir,
obsidianVaultPath: this.getVaultBasePath(),
addedAt: existing?.addedAt ?? now,
lastActiveAt: now,
});
this.journal.lifecycle(`re-pointing this vault at data dir ${dataDir}`);
if (this.serverManager) {
await this.serverManager.stop();
this.serverManager = null;
}
if (this.settings.serverMode === SERVER_MODE.MANAGED) {
await this.startManagedServer();
}
}
onunload(): void {
this.unloaded = true;
// Detach our chrome first: nothing below may throw past this point
// and leave pills behind for the next instance to sit next to.
this.statusBarEl?.remove();
this.statusBarEl = null;
this.syncPillEl?.remove();
this.syncPillEl = null;
this.chatRibbonIconEl?.remove();
this.chatRibbonIconEl = null;
this.clearUpdateIndicator();
// A download must not outlive the instance: a re-enabled plugin would race it for the same bin dir.
this.cancelServerDownload();
this.finishDownload();
if (this.pendingHintTimeout) {
window.clearTimeout(this.pendingHintTimeout);
this.pendingHintTimeout = null;
}
this.taskQueue.dispose();
if (this.serverManager) {
this.journal.lifecycle("plugin unloading; killing the managed server before unload");
this.serverManager.killChildSync();
}
}
/** Mirrors the mode and URL into the `previous*` pair. Call after writing
* `settings.serverMode` anywhere outside `saveSettings()` itself. */
recordServerBaseline(): void {
this.previousServerMode = this.settings.serverMode;
this.previousServerUrl = this.settings.serverUrl;
}
async loadSettings(): Promise<void> {
const raw = (await this.loadData()) as (LilbeeSettings & { taskHistory?: { history?: unknown[] } }) | null;
this.settings = Object.assign({}, DEFAULT_SETTINGS, raw ?? {});
// Object.assign only merges one level, so a stored agentIntegration would
// shadow the defaults of any key added to it later.
this.settings.agentIntegration = { ...DEFAULT_AGENT_INTEGRATION, ...(raw?.agentIntegration ?? {}) };
// A vault saved before this flag existed recorded a finished wizard in setupCompleted.
this.settings.wizardCompleted = raw?.wizardCompleted ?? this.settings.setupCompleted;
this.recordServerBaseline();
this.taskQueue.loadFromJSON(raw?.taskHistory as { history?: import("./types").TaskEntry[] } | undefined);
this.vaultId = computeVaultId(this.getVaultBasePath());
this.vaultRegistry = new VaultRegistry(resolveSharedRoot(this.settings.sharedRoot));
this.serverUninstalled = this.vaultRegistry.loadConfig().serverUninstalled;
await this.migrateFlatInstall(this.vaultRegistry.sharedRoot);
}
/** Move a flat pre-launcher install into the release layout; a probed identity fills an empty record. */
private async migrateFlatInstall(sharedRoot: string): Promise<void> {
const recorded = this.getSharedLilbeeVersion();
try {
const moved = await migrateFlatBinary(sharedBinDir(sharedRoot), recorded, this.getSharedLilbeeVariant());
if (moved === null || recorded) return;
this.setSharedLilbeeVersion(moved.release);
this.setSharedLilbeeVariant(moved.variant, null);
} catch (err) {
this.journal.lifecycle(
`could not move the installed server into the release layout: ${errorMessage(err, String(err))}`,
);
}
}
/** Mirrors `SharedConfig.serverUninstalled`; read on every status paint and health probe. */
private serverUninstalled = false;
isServerUninstalled(): boolean {
return this.serverUninstalled;
}
setServerUninstalled(uninstalled: boolean): void {
this.serverUninstalled = uninstalled;
const reg = this.vaultRegistry;
if (!reg) return;
reg.saveConfig({ ...reg.loadConfig(), serverUninstalled: uninstalled });
}
getSharedLilbeeVersion(): string {
return this.vaultRegistry?.loadConfig().lilbeeVersion ?? "";
}
setSharedLilbeeVersion(version: string): void {
const reg = this.vaultRegistry;
if (!reg) return;
reg.saveConfig({ ...reg.loadConfig(), lilbeeVersion: version });
}
getSharedLilbeeVariant(): ServerVariant | "" {
return this.vaultRegistry?.loadConfig().lilbeeVariant ?? "";
}
/** The GPU probe that chose the installed build, or null when none is recorded. */
getSharedGpuDetection(): GpuDetection | null {
return this.vaultRegistry?.loadConfig().lilbeeDetection ?? null;
}
setSharedLilbeeVariant(variant: ServerVariant, detection: GpuDetection | null): void {
const reg = this.vaultRegistry;
if (!reg) return;
reg.saveConfig({
...reg.loadConfig(),
lilbeeVariant: variant,
lilbeeDetection: detection,
cudaBuildOffered: false,
});
}
isServerAutoUpdateEnabled(): boolean {
return this.vaultRegistry?.loadConfig().serverAutoUpdate ?? true;
}
setServerAutoUpdate(enabled: boolean): void {
const reg = this.vaultRegistry;
if (!reg) return;
const config = reg.loadConfig();
if (config.serverAutoUpdate === enabled) return;
reg.saveConfig({ ...config, serverAutoUpdate: enabled });
this.journal.lifecycle(enabled ? "automatic server updates turned on" : "automatic server updates turned off");
}
isServerUpdateReminderEnabled(): boolean {
return this.vaultRegistry?.loadConfig().serverUpdateReminder ?? true;
}
setServerUpdateReminder(enabled: boolean): void {
const reg = this.vaultRegistry;
if (!reg) return;
const config = reg.loadConfig();
if (config.serverUpdateReminder === enabled) return;
reg.saveConfig({ ...config, serverUpdateReminder: enabled });
this.journal.lifecycle(enabled ? "server update reminder turned on" : "server update reminder turned off");
}
/** With automatic updates off, point at a newer release instead of installing it. */
private async remindServerUpdate(showModal: boolean): Promise<void> {
let result: { available: boolean; release?: ReleaseInfo };
try {
result = await this.checkForUpdate();
} catch {
return;
}
if (!result.available || !result.release) return;
const release = result.release;
this.showUpdateIndicator(release);
if (!showModal) return;
const installedVariant = this.getSharedLilbeeVariant();
const build =
installedVariant !== "" && installedVariant !== release.variant
? MESSAGES.LABEL_SERVER_BUILD(release.variant)
: null;
// A modal opened before the layout exists is closed with the startup screen.
this.app.workspace.onLayoutReady(() => {
new UpdateAvailableModal(this.app, release, build, {
openSettings: () => this.openServerUpdateSettings(),
stopReminding: () => this.setServerUpdateReminder(false),
}).open();
});
}
private showUpdateIndicator(release: ReleaseInfo): void {
const label = MESSAGES.LABEL_RIBBON_UPDATE_AVAILABLE(release.tag);
if (this.updateRibbonIconEl) {
this.updateRibbonIconEl.setAttribute("aria-label", label);
return;
}
this.updateRibbonIconEl = this.addRibbonIcon("arrow-up-circle", label, () => this.openServerUpdateSettings());
this.updateRibbonIconEl.addClass("lilbee-ribbon-icon", "lilbee-ribbon-update");
}
private clearUpdateIndicator(): void {
this.updateRibbonIconEl?.remove();
this.updateRibbonIconEl = null;
}
openServerUpdateSettings(): void {
this.openPluginSettings();
this.settingTab?.scrollToServerUpdate();
}
getSharedHfToken(): string {
return this.vaultRegistry?.loadConfig().hfToken ?? "";
}
setSharedHfToken(token: string): void {
const reg = this.vaultRegistry;
if (!reg) return;
reg.saveConfig({ ...reg.loadConfig(), hfToken: token });
}
private getVaultDisplayName(): string {
const path = this.getVaultBasePath();
const base = path.split("/").filter(Boolean).pop();
return base ?? "vault";
}
private async persistAll(): Promise<void> {
await this.saveData({ ...this.settings, taskHistory: this.taskQueue.toJSON() });
}
private schedulePersistHistory(): void {
void this.persistAll();
}
async saveSettings(): Promise<void> {
const previousMode = this.previousServerMode;
const previousUrl = this.previousServerUrl;
this.recordServerBaseline();
await this.persistAll();
if (this.settings.serverMode === SERVER_MODE.MANAGED) {
if (previousMode !== SERVER_MODE.MANAGED) {
this.journal.lifecycle("server mode switched to managed; starting the managed server");
void this.startManagedServer();
}
} else {
if (previousMode === SERVER_MODE.MANAGED) {
this.journal.lifecycle("server mode switched to external; stopping the managed server");
void this.serverManager?.stop();
this.serverManager = null;
}
this.configureApi(this.settings.serverUrl);
// Only a genuine switch needs a fresh read: an unrelated save (a
// toggle, a token edit) would otherwise re-request the server's
// health on every save for no reason.
if (previousMode === SERVER_MODE.MANAGED || previousUrl !== this.settings.serverUrl) {
void this.refreshExternalServerVersion();
}
// The first successful health probe promotes this to "ready"; until
// then the user sees "connecting..." so a non-lilbee server never
// briefly claims ready on the strength of a mode switch alone.
this.setStatusConnecting();
void this.fetchActiveModel();
}
}
private updateStatusBar(text: string, dotState: DotState | null = null, withModel = true): void {
if (!this.statusBarEl) return;
const label = withModel ? displayLabelForRef(this.activeModel) : "";
const model = label ? ` (${label})` : "";
this.statusBarEl.empty();
if (dotState) {
const dot = this.statusBarEl.createSpan({ cls: `lilbee-statusbar-dot is-${dotState}` });
dot.setAttribute("aria-hidden", "true");
}
this.statusBarEl.createSpan({ text: `${text}${model}` });
}
private setStatusClass(cls: string | null): void {
if (!this.statusBarEl) return;
this.statusBarEl.classList.remove(
"lilbee-status-downloading",
"lilbee-status-starting",
"lilbee-status-ready",
"lilbee-status-adding",
"lilbee-status-error",
"lilbee-status-muted",
);
if (cls) this.statusBarEl.classList.add(cls);
}
private setStatusConnecting(): void {
this.updateStatusBar(MESSAGES.STATUS_CONNECTING, DOT_STATE.PRIMARY);
this.setStatusClass("lilbee-status-starting");
}
private paintLibraryUpgrade(upgrade: LibraryUpgrade | null): void {
const text =
upgrade?.phase === UPGRADE_PHASE.TABLE && upgrade.tables_total > 0
? MESSAGES.STATUS_UPGRADING_PROGRESS(upgrade.tables_done, upgrade.tables_total)
: MESSAGES.STATUS_UPGRADING;
this.updateStatusBar(text, DOT_STATE.PRIMARY);
this.setStatusClass("lilbee-status-starting");
}
private setStatusReady(): void {
// Running work owns the pill. Every successful response lands here, so
// without this a sync's progress text is repainted as "ready" between
// queue ticks and the status bar visibly flickers between the two.
// The queue republishes on every change, so there is nothing to restore.
if (this.taskQueue.activeAll.length > 0 || this.taskQueue.queued.length > 0) return;
// A served response says the server answered, not that the chat engine
// is up. Without this the health probe's own OK outcome repaints "ready"
// over the pill reflectChatStatus just painted.
if (this.chatStatus === CHAT_STATUS.LOADING || this.chatStatus === CHAT_STATUS.ERROR) return;
if (this.libraryUpgrade) return;
if (this.settings.serverMode === SERVER_MODE.MANAGED && this.serverUninstalled) {
this.showNotInstalledStatus();
return;
}
// Managed mode without a running serverManager is the "released"
// state (after switch-to-another-vault or onunload). Stay stuck
// on STOPPED instead of cheerfully claiming "ready" against a
// server that isn't running.
if (this.settings.serverMode === SERVER_MODE.MANAGED && this.serverManager === null) {
this.updateStatusBar(MESSAGES.STATUS_STOPPED, DOT_STATE.MUTED, false);
this.setStatusClass(null);
return;
}
// The main pill always shows running status, plainly and prominently.
// Pending-sync work lives on the separate sync pill, never here.
const text =
this.settings.serverMode === SERVER_MODE.EXTERNAL ? MESSAGES.STATUS_READY_EXTERNAL : MESSAGES.STATUS_READY;
this.updateStatusBar(text);
this.setStatusClass("lilbee-status-ready");
}
private startHealthProbe(): void {
if (this.healthProbeHandle !== null) return;
const handle = window.setInterval(() => void this.probeServerHealth(), HEALTH_PROBE_INTERVAL_MS);
this.registerInterval(handle);
this.healthProbeHandle = handle;
}
private async probeServerHealth(): Promise<void> {
if (this.taskQueue.activeAll.length > 0) return;
if (this.startingServer) return;
if (this.chatInFlight > 0) return;
// Nothing to probe, and "error" would misread a deliberate uninstall.
if (this.serverUninstalled) return;
// Re-read the token before probing — the server writes a fresh one on
// every restart, and this is the cheapest way to stay in sync.
this.api.setToken(this.readCurrentToken());
const generation = ++this.externalVersionGeneration;
const health = await this.api.health().catch(() => null);
// A 200 with a non-lilbee JSON body (e.g. {}) parses fine but is not a
// healthy lilbee server. Only a body carrying status: "ok" counts, so a
// foreign HTTP server on the configured URL reads as unreachable.
if (health?.isOk() && health.value.status === "ok") {
this.healthFailureStreak = 0;
this.healthValidated = true;
if (this.settings.serverMode === SERVER_MODE.EXTERNAL && generation === this.externalVersionGeneration) {
this.externalServerVersion = health.value.version;
}
// Only a reconnect refetches the model: a restarted server may be on a different one.
if (this.serverUnreachable) {
this.serverUnreachable = false;
void this.fetchActiveModel();
}
const upgrade = health.value.upgrade;
this.libraryUpgrade = upgrade && isUpgradeRunning(upgrade) ? upgrade : null;
this.reflectChatStatus(health.value);
if (this.libraryUpgrade) {
this.paintLibraryUpgrade(this.libraryUpgrade);
return;
}
// reflectChatStatus early-returns when the chat status is unchanged,
// so a "connecting..." from a mode switch would never clear. Promote
// to ready explicitly after a successful probe.
this.setStatusReady();
return;
}
this.healthFailureStreak += 1;
this.libraryUpgrade = null;
if (this.healthFailureStreak < HEALTH_FAILURE_STREAK_THRESHOLD) return;
// Managed mode, pre-first-ready (fresh install, wizard still
// downloading/booting): a failing probe is "starting", not "error".
// Don't paint a red pill. External mode reports errors normally —
// it points at a server the user already runs.
if (this.settings.serverMode === SERVER_MODE.MANAGED && !this.serverEverReady) return;
// Another vault holds the shared root: the server was asked to exit,
// not down. Show who won and skip the "missing token" notice.
if (this.refreshLockedByOtherStatus()) return;
if (this.serverUnreachable) return;
this.serverUnreachable = true;
this.updateStatusBar(MESSAGES.STATUS_ERROR, DOT_STATE.ERROR);
this.setStatusClass("lilbee-status-error");
this.maybeWarnMissingToken();
}
/** The engine state a health snapshot reports. Servers without `chat_status`
* only distinguish ready from not-ready, so `chat_ready` stands in. */
private static chatStatusOf(health: HealthResponse): ChatStatus {
return health.chat_status ?? (health.chat_ready === false ? CHAT_STATUS.LOADING : CHAT_STATUS.READY);
}
/** Reflect the chat engine's state from a health snapshot. `not_started` is
* not a fault and not a wait: nothing is loading because nothing asked it to,
* and the next request warms it. */
private reflectChatStatus(health: HealthResponse): void {
const status = LilbeePlugin.chatStatusOf(health);
this.chatError = health.chat_error ?? null;
const warnings = health.warnings ?? [];
if (!sameWarnings(this.healthWarnings, warnings)) {
this.healthWarnings = warnings;
this.refreshOpenChatWarnings();
}
if (status === this.chatStatus) return;
this.chatStatus = status;
this.syncWarmStream();
if (status === CHAT_STATUS.LOADING) {
this.updateStatusBar(MESSAGES.STATUS_WARMING, DOT_STATE.PRIMARY);
this.setStatusClass("lilbee-status-starting");
return;
}
if (status === CHAT_STATUS.ERROR) {
this.updateStatusBar(MESSAGES.STATUS_CHAT_FAILED, DOT_STATE.ERROR);
this.setStatusClass("lilbee-status-error");
return;
}
this.setStatusReady();
}
/** Follow the cold-load stream while the engine is loading, and drop it as
* soon as it is not. Only `loading` has progress to report. */
private syncWarmStream(): void {
if (this.chatStatus !== CHAT_STATUS.LOADING) {
this.warmController?.abort();
this.warmController = null;
return;
}
if (this.warmController) return;
const controller = new AbortController();
this.warmController = controller;
void this.consumeWarmStream(controller);
}
private async consumeWarmStream(controller: AbortController): Promise<void> {
try {
for await (const event of this.api.warmStream(controller.signal)) {
if (event.event !== SSE_EVENT.WARM) continue;
if (this.warmController !== controller) return;
this.paintWarmProgress(event.data as WarmProgress);
}
} catch {
// Stream refused or dropped: the health probe still drives the pill.
} finally {
if (this.warmController === controller) this.warmController = null;
}
}
/** Paint one warm snapshot onto the status pill. */
private paintWarmProgress(snapshot: WarmProgress): void {
if (this.chatStatus !== CHAT_STATUS.LOADING) return;
this.updateStatusBar(warmStatusText(snapshot), DOT_STATE.PRIMARY);
this.setStatusClass("lilbee-status-starting");
}
notifyChatStart(): void {
this.chatInFlight += 1;
}
notifyChatEnd(): void {
if (this.chatInFlight > 0) this.chatInFlight -= 1;
}
private missingTokenNoticeFired = false;
private maybeWarnMissingToken(): void {
if (this.missingTokenNoticeFired) return;
if (this.readCurrentToken() !== null) return;
this.missingTokenNoticeFired = true;
const msg =
this.settings.serverMode === SERVER_MODE.MANAGED
? MESSAGES.NOTICE_NO_TOKEN_MANAGED
: MESSAGES.NOTICE_NO_TOKEN_EXTERNAL;
new Notice(msg, NOTICE_DURATION_MS);
}
private updateStatusBarFromQueue(): void {
const allActive = this.taskQueue.activeAll;
const queued = this.taskQueue.queued;
const completed = this.taskQueue.completed;
if (allActive.length === 0 && queued.length === 0) {
const recent = completed[0];
if (recent && recent.completedAt !== null && Date.now() - recent.completedAt < TASK_FLASH_WINDOW_MS) {
this.renderStatusFlash(recent, completed);
return;
}
this.setStatusReady();
return;
}
if (allActive.length === 0 && queued.length > 0) {
this.updateStatusBar(
`lilbee: ${MESSAGES.STATUS_TASKS_QUEUED_ONLY.replace("{count}", String(queued.length))}`,
DOT_STATE.PRIMARY,
);
this.setStatusClass("lilbee-status-adding");
return;
}
const first = allActive[0];
const pct = first.progress > 0 ? first.progress : 0;
const suffix = queued.length > 0 ? ` +${queued.length}` : "";
// Writing a wiki page reports no phases, so it runs indeterminate. It
// was still being rendered here as "0%", which is the one number that
// is certainly wrong for a job that is actively running.
const indeterminate = first.progress <= INDETERMINATE_PROGRESS;
if (allActive.length === 1) {
const text = indeterminate
? MESSAGES.STATUS_TASK_RUNNING_SINGLE_INDETERMINATE.replace("{name}", first.name)
: MESSAGES.STATUS_TASK_RUNNING_SINGLE.replace("{name}", first.name).replace("{pct}", String(pct));
this.updateStatusBar(`lilbee: ${text}${suffix}`, DOT_STATE.PRIMARY);
} else {
const text = indeterminate
? MESSAGES.STATUS_TASKS_RUNNING_PLURAL_INDETERMINATE.replace(
"{count}",
String(allActive.length),
).replace("{name}", first.name)
: MESSAGES.STATUS_TASKS_RUNNING_PLURAL.replace("{count}", String(allActive.length))
.replace("{name}", first.name)
.replace("{pct}", String(pct));
this.updateStatusBar(`lilbee: ${text}${suffix}`, DOT_STATE.PRIMARY);
}
this.setStatusClass("lilbee-status-adding");
}
private renderStatusFlash(recent: TaskEntry, completed: readonly TaskEntry[]): void {
if (recent.status === TASK_STATUS.DONE) {
const recentDone = countRecentByStatus(completed, TASK_STATUS.DONE);
const text =
recentDone > 1
? MESSAGES.STATUS_TASKS_DONE_FLASH.replace("{count}", String(recentDone)).replace(
"{name}",
recent.name,
)
: MESSAGES.STATUS_TASK_DONE_FLASH.replace("{name}", recent.name);
this.updateStatusBar(`lilbee: ${text}`, DOT_STATE.SUCCESS);
this.setStatusClass("lilbee-status-ready");
return;
}
if (recent.status === TASK_STATUS.FAILED) {
const recentFailed = countRecentByStatus(completed, TASK_STATUS.FAILED);
const template = recentFailed > 1 ? MESSAGES.STATUS_TASKS_FAILED_FLASH : MESSAGES.STATUS_TASK_FAILED_FLASH;
const text = template.replace("{count}", String(recentFailed)).replace("{name}", recent.name);
this.updateStatusBar(`lilbee: ${text}`, DOT_STATE.ERROR);
this.setStatusClass("lilbee-status-error");
return;
}
this.setStatusReady();
}
async openModelInfoForActiveTask(task: typeof MODEL_TASK.CHAT | typeof MODEL_TASK.EMBEDDING): Promise<void> {
let cfg: Record<string, unknown>;
try {
cfg = await this.api.config();
} catch {
new Notice(MESSAGES.NOTICE_NO_ACTIVE_MODEL(task));
return;
}
const key = task === MODEL_TASK.CHAT ? "chat_model" : "embedding_model";
const ref = typeof cfg[key] === "string" ? cfg[key] : "";
if (!ref) {
new Notice(MESSAGES.NOTICE_NO_ACTIVE_MODEL(task));
return;
}
const repo = extractHfRepo(ref);
const result = await this.api.catalog({ task, search: repo });
const entry = result.isOk() ? result.value.models.find((e) => e.hf_repo === repo) : undefined;
if (entry) {
new ModelInfoModal(this.app, this, { kind: MODEL_INFO_SOURCE.CATALOG, entry }).open();
return;
}
await this.openModelInfoFromServer(ref, task);
}
/** The catalog carries no row for the active model, so ask the server what it is serving. */
private async openModelInfoFromServer(
ref: string,
task: typeof MODEL_TASK.CHAT | typeof MODEL_TASK.EMBEDDING,
): Promise<void> {
let details: ModelShowResponse;
try {
details = await this.api.showModel(ref);
} catch {
new Notice(MESSAGES.NOTICE_MODEL_INFO_UNAVAILABLE(ref));
return;
}
// The server answers with an empty object for a model it cannot describe. A populated
// answer opens the modal even when none of its fields earns a row.
if (Object.keys(details).length === 0) {
new Notice(MESSAGES.NOTICE_MODEL_INFO_UNAVAILABLE(ref));
return;
}
new ModelInfoModal(this.app, this, { kind: MODEL_INFO_SOURCE.SERVER, ref, task, details }).open();
}
async fetchActiveModel(): Promise<void> {
try {
const models = await this.api.listModels();
this.activeModel = models.chat.active;
// Repaint the pill so a new model name shows without claiming
// ready: only a validated probe promotes to ready.
if (this.settings.serverMode === SERVER_MODE.EXTERNAL) {
if (this.healthValidated) this.setStatusReady();
else this.setStatusConnecting();
}
await this.applyReasoningDefaultOnce();
} catch {
// Silently fail - will retry on next action
}
// Check wiki feature status
try {
const wiki = await this.api.wikiStatus();
if (wiki.isOk()) {
this.wikiPageCount = wiki.value.pages;
this.wikiDraftCount = wiki.value.drafts;
}
} catch {
// wiki detection is best-effort
}
if (this.wikiEnabled && this.settings.wikiSyncToVault) {
this.initWikiSync();
void this.reconcileWiki();
}
}
/** Turn reasoning display on once, the first time we reach a ready server. */
private async applyReasoningDefaultOnce(): Promise<void> {
if (this.settings.reasoningDefaulted) return;
// Patch only when the server reports it explicitly off; older servers omit the key.
const cfg = await this.api.config();
if (cfg.show_reasoning === false) {
await applyConfig(this, { [CONFIG_KEY.SHOW_REASONING]: true });
}
this.settings.reasoningDefaulted = true;
await this.persistAll();
}
initWikiSync(): void {
this.wikiSync = new WikiSync(this.api, this.app.vault.adapter, this.settings.wikiVaultFolder);
}
async reconcileWiki(): Promise<void> {
if (!this.wikiSync) return;
try {
const result = await this.wikiSync.reconcile();
if (result.written > 0 || result.removed > 0) {
new Notice(MESSAGES.NOTICE_WIKI_SYNC(result.written, result.removed), NOTICE_DURATION_MS);
}
} catch {
// reconcile is best-effort
}
}
private assertActiveModel(): boolean {
if (this.activeModel) return true;
new Notice(MESSAGES.NOTICE_NO_CHAT_MODEL);
return false;
}
/** Block chat and ingest only while a request cannot be served. Public so the
* chat view gates on it too.
*
* `not_started` passes: the server warms the engine on the next request, so
* blocking here would withhold the one call that loads the model. */
assertFleetReady(): boolean {
if (this.chatStatus === CHAT_STATUS.LOADING) {
new Notice(MESSAGES.NOTICE_FLEET_WARMING);
return false;
}
if (this.chatStatus === CHAT_STATUS.ERROR) {
new Notice(MESSAGES.NOTICE_FLEET_ERROR(this.chatError), NOTICE_DURATION_MS);
return false;
}
return true;
}
/** Saved conversations need the /api/sessions routes, which pre-0.6.90 servers don't have. */
serverSupportsSessions(): boolean {
return supportsSessions(this.runningServerVersion());
}
/** Forking a saved conversation needs the fork route, newer than the other session routes. */
serverSupportsSessionFork(): boolean {
return supportsSessionFork(this.runningServerVersion());
}
/** Exporting a saved conversation as markdown needs the export route, newer than the other session routes. */
serverSupportsSessionExport(): boolean {
return supportsSessionExport(this.runningServerVersion());
}
/** Ask the user where to export a chat; null when they cancel. End-to-end runs replace it to skip the native dialog. */
async chooseChatExportPath(defaultName: string): Promise<string | null> {
const result = await electronDialog.showSaveDialog({
defaultPath: defaultName,
filters: [{ name: MESSAGES.LABEL_MARKDOWN_FILTER, extensions: [CHAT_EXPORT_EXTENSION] }],
});
return result.canceled || !result.filePath ? null : result.filePath;
}
/** GPU placement needs the /api/placement routes, which pre-0.6.90 servers don't have. */
serverSupportsPlacement(): boolean {
return supportsPlacement(this.runningServerVersion());
}
/** Managed mode knows the install version up front; external mode caches it from
* a health check run at launch, on every mode/URL switch, and on every
* health-probe tick, so it always describes the server the plugin currently
* points at. Reports "" (which fails open) only until the next such check answers. */
private runningServerVersion(): string {
return this.settings.serverMode === SERVER_MODE.MANAGED
? this.getSharedLilbeeVersion()
: this.externalServerVersion;
}
private async confirmReindexIfNeeded(name: string): Promise<boolean> {
try {
const searchName = name.replace(/\.md$/, "");
const listing = await this.api.listDocuments(searchName, 1);
if (listing.documents.length > 0) {
const modal = new ConfirmModal(this.app, MESSAGES.CONFIRM_REINDEX(searchName));
modal.open();
return await modal.result;
}
} catch {
// graceful fallback: proceed with add if check fails
}
return true;
}
async addExternalFiles(paths: string[]): Promise<void> {
if (!this.statusBarEl || paths.length === 0) return;
if (!this.assertActiveModel()) return;
if (!this.assertFleetReady()) return;
const label = paths.length === 1 ? paths[0].split("/").pop() || paths[0] : `${paths.length} files`;
const isRetry = paths.length === 1 && this.failedAddPaths.has(paths[0]);
if (paths.length === 1 && !isRetry && !(await this.confirmReindexIfNeeded(label))) return;
// Copy disk-picked files into the vault before indexing so the
// resulting source lives where the user expects — visible in the
// file tree, reachable as a native Obsidian file, and eligible for
// the vault_path deep-link on chat source chips. Skips files whose
// paths are already inside the vault (right-click "Add to lilbee"
// routes through here too for single-path external paths).
const copiedPaths = this.copyExternalFilesToVault(paths);
if (copiedPaths.length === 0) return;
new Notice(MESSAGES.STATUS_ADDING.replace("{label}", label));
if (this.settings.serverMode === SERVER_MODE.EXTERNAL) {
// A remote server can't read the just-copied local paths, so send
// the bytes — same upload route as the right-click "Add to lilbee".
let uploads: UploadPayload[];
try {
uploads = this.readUploadsFromDisk(copiedPaths);
} catch (err) {
console.error("[lilbee] add failed:", err);
new Notice(MESSAGES.ERROR_ADD_FAILED_DETAIL(errorMessage(err, MESSAGES.ERROR_CANNOT_CONNECT)));
return;
}
await this.runUpload(uploads, paths, () => this.addExternalFiles(paths));
} else {
await this.runAdd(copiedPaths, paths, () => this.addExternalFiles(paths));
}
}
/** Upload payloads for every file under each path, keyed by vault-relative path like collectVaultUploads. */
private readUploadsFromDisk(paths: string[]): UploadPayload[] {
const vaultBase = this.getVaultBasePath();
const out: UploadPayload[] = [];
const walk = (p: string, relative: string): void => {
if (node.statSync(p).isDirectory()) {
for (const child of node.readdirSync(p)) walk(node.join(p, child), `${relative}/${child}`);
} else {
const buf = node.readFileSync(p);
out.push({
name: relative,
data: buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
});
}
};
for (const p of paths) walk(p, this.uploadRootName(p, vaultBase));
return out;
}
/** Vault-relative path of a picked entry; its own name when the entry sits outside the vault. */
private uploadRootName(p: string, vaultBase: string): string {
if (!this.isUnderVault(p, vaultBase)) return node.basename(p);
return posixPath(p).slice(posixPath(vaultBase).length + 1);
}
/** Absolute vault paths for each entry: copied into ``<vault>/lilbee/imports/`` unless already under the vault. */
private copyExternalFilesToVault(paths: string[]): string[] {
const vaultBase = this.getVaultBasePath();
const importsDir = node.join(vaultBase, "lilbee", "imports");
try {
node.mkdirSync(importsDir, { recursive: true });
} catch (err) {
console.error("[lilbee] import dir create failed:", importsDir, err);
new Notice(MESSAGES.ERROR_FILE_PICKER);
return [];
}
const results: string[] = [];
for (const source of paths) {
if (this.isUnderVault(source, vaultBase)) {
results.push(source);
continue;
}
const name = node.basename(source) || "imported";
const dest = this.uniqueImportPath(importsDir, name);
try {
const isDirectory = node.statSync(source).isDirectory();
if (isDirectory) {
node.cpSync(source, dest, { recursive: true });
} else {
node.copyFileSync(source, dest);
}
results.push(dest);
} catch (err) {
console.error("[lilbee] import copy failed:", source, err);
new Notice(MESSAGES.ERROR_FILE_PICKER);
}
}
return results;
}
/** True if ``source`` sits under ``vaultBase``, whichever separator either side uses. */
private isUnderVault(source: string, vaultBase: string): boolean {
return posixPath(source).startsWith(`${posixPath(vaultBase)}/`);
}
/** Append a ``-N`` suffix until ``<dir>/<name>`` doesn't exist on disk. */
private uniqueImportPath(dir: string, name: string): string {
const candidate = node.join(dir, name);
if (!node.existsSync(candidate)) return candidate;
const dot = name.lastIndexOf(".");
const [stem, ext] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""];
for (let n = 1; n < 1000; n++) {
const next = node.join(dir, `${stem}-${n}${ext}`);
if (!node.existsSync(next)) return next;
}
return node.join(dir, `${stem}-${Date.now()}${ext}`);
}
async addToLilbee(file: TAbstractFile): Promise<void> {
if (!this.statusBarEl) return;
if (!this.assertActiveModel()) return;
if (!this.assertFleetReady()) return;
const absolutePath = `${this.getVaultBasePath()}/${file.path}`;
// The vault root's name is the empty string and its path is "/", so
// `?? file.path` doesn't fall back; both have to be checked.
const name = file.name || file.path || MESSAGES.LABEL_VAULT_ROOT;
const isRetry = this.failedAddPaths.has(absolutePath);
// A note is keyed by its vault path, so the check searches for that, not the basename.
const indexKey = file instanceof TFile && file.path ? file.path : name;
if (!isRetry && !(await this.confirmReindexIfNeeded(indexKey))) return;
new Notice(MESSAGES.STATUS_ADDING.replace("{label}", name));
if (this.settings.serverMode === SERVER_MODE.EXTERNAL) {
// A remote server can't read this machine's paths, so send the file
// bytes straight from the vault instead of a server-side path. The
// read runs before runAdd's guard, so surface a failure here too.
let uploads: UploadPayload[];
try {
uploads = await this.collectVaultUploads(file);
} catch (err) {
console.error("[lilbee] add failed:", err);
new Notice(MESSAGES.ERROR_ADD_FAILED_DETAIL(errorMessage(err, MESSAGES.ERROR_CANNOT_CONNECT)));
return;
}
await this.runUpload(uploads, [absolutePath], () => this.addToLilbee(file));
} else {
await this.runAdd([absolutePath], [absolutePath], () => this.addToLilbee(file));
}
}
/** Upload payloads for every file under *file*, keyed by vault-relative path. */
private async collectVaultUploads(file: TAbstractFile): Promise<UploadPayload[]> {
const tfiles = file instanceof TFolder ? this.filesInFolder(file) : file instanceof TFile ? [file] : [];
return Promise.all(tfiles.map(async (f) => ({ name: f.path, data: await this.app.vault.readBinary(f) })));
}
private filesInFolder(folder: TFolder): TFile[] {
const out: TFile[] = [];
for (const child of folder.children) {
if (child instanceof TFile) out.push(child);
else if (child instanceof TFolder) out.push(...this.filesInFolder(child));
}
return out;
}
/** Ingest by uploading file content (external mode); reuses runAdd's stream loop. */
private async runUpload(
files: UploadPayload[],
retryKeys: string[],
retry?: () => void | Promise<void>,
): Promise<void> {
const { kept, leftOut } = dropRefusedUploads(files);
if (leftOut > 0) new Notice(MESSAGES.NOTICE_UPLOAD_LEFT_OUT(leftOut));
if (kept.length === 0) {
if (leftOut === 0) new Notice(MESSAGES.STATUS_NOTHING_NEW);
return;
}
await this.runAdd(
kept.map((f) => f.name),
retryKeys,
retry,
(signal) => this.uploadInBatches(kept, signal),
"Uploading files",
);
}
/** Upload files in server-safe batches while presenting one continuous
* stream: progress counters are renumbered across the whole set, and a
* single merged done event is emitted after the last batch. */
private async *uploadInBatches(files: UploadPayload[], signal: AbortSignal): AsyncGenerator<SSEEvent, void> {
const batches = batchUploads(files);
// One request: the server's counters already span the whole set — stream through untouched.
if (batches.length <= 1) {
yield* this.api.uploadFiles(files, signal);
return;
}
const total = files.length;
const merged: AddDone = {
added: [],
updated: [],
removed: [],
unchanged: 0,
failed: [],
skipped: [],
held_out: [],
tracked: [],
name_taken: [],
overlapping: [],
errors: [],
absorbed: [],
index_mismatch: null,
skip_records_error: null,
};
let done = 0;
for (const batch of batches) {
for await (const event of this.api.uploadFiles(batch, signal)) {
if (event.event === SSE_EVENT.DONE) {
const parsed = parseAddDoneEvent(event.data);
if (parsed) {
merged.added.push(...parsed.added);
merged.updated.push(...parsed.updated);
merged.removed.push(...parsed.removed);
merged.failed.push(...parsed.failed);
merged.skipped.push(...parsed.skipped);
merged.held_out.push(...parsed.held_out);
merged.tracked.push(...parsed.tracked);
merged.name_taken.push(...parsed.name_taken);
merged.overlapping.push(...parsed.overlapping);
merged.errors.push(...parsed.errors);
merged.absorbed.push(...parsed.absorbed);
merged.unchanged += parsed.unchanged;
// The last batch's verdict is the state the index ends in.
merged.index_mismatch = parsed.index_mismatch;
// The first failure stands: a later batch that saves cleanly does not undo it.
merged.skip_records_error ??= parsed.skip_records_error;
}
} else if (event.event === SSE_EVENT.FILE_START) {
const d = event.data as { current_file: number; total_files: number };
yield {
event: SSE_EVENT.FILE_START,
data: { current_file: done + d.current_file, total_files: total },
};
} else if (event.event === SSE_EVENT.BATCH_PROGRESS) {
const d = event.data as BatchProgressPayload;
yield { event: SSE_EVENT.BATCH_PROGRESS, data: { ...d, current: done + d.current, total } };
} else {
yield event;
}
}
done += batch.length;
}
yield { event: SSE_EVENT.DONE, data: merged };
}
cancelSync(): void {
this.syncController?.abort();
this.syncController = null;
}
private async runAdd(
paths: string[],
retryKeys: string[] = paths,
retry?: () => void | Promise<void>,
makeStream?: (signal: AbortSignal) => AsyncGenerator<SSEEvent, void>,
label = "Adding files",
): Promise<void> {
const taskId = this.taskQueue.enqueue(label, TASK_TYPE.ADD, retry);
if (taskId === null) {
new Notice(MESSAGES.NOTICE_QUEUE_FULL);
return;
}
for (const p of retryKeys) this.failedAddPaths.delete(p);
this.syncController = new AbortController();
this.taskQueue.registerAbort(taskId, this.syncController);
try {
const progress = new FileProgressTracker();
let syncResult: AddDone | null = null;
const controller = this.syncController;
const rawStream = makeStream
? makeStream(controller.signal)
: this.api.addFiles(paths, true, controller.signal);
for await (const event of withIdleTimeout(rawStream, STREAM_IDLE_TIMEOUT_MS, () => controller.abort())) {
if (event.event === SSE_EVENT.FILE_START) {
const d = event.data as { current_file: number; total_files: number };
progress.startFile(d.current_file, d.total_files);
this.taskQueue.update(
taskId,
progress.percent(),
MESSAGES.STATUS_TASK_FILE.replace("{current}", String(d.current_file)).replace(
"{total}",
String(d.total_files),
),
);
} else if (event.event === SSE_EVENT.EXTRACT) {
const d = event.data as { page: number; total_pages: number; file: string };
progress.setExtractFraction(d.page, d.total_pages);
this.taskQueue.update(
taskId,
progress.percent(),
MESSAGES.STATUS_TASK_EXTRACTING.replace("{file}", d.file)
.replace("{page}", String(d.page))
.replace("{total}", String(d.total_pages)),
);
} else if (event.event === SSE_EVENT.EMBED) {
const d = event.data as { chunk: number; total_chunks: number };
progress.setEmbedFraction(d.chunk, d.total_chunks);
this.taskQueue.update(
taskId,
progress.percent(),
MESSAGES.STATUS_TASK_EMBEDDING.replace("{chunk}", String(d.chunk)).replace(
"{total}",
String(d.total_chunks),
),
);
} else if (event.event === SSE_EVENT.BATCH_PROGRESS) {
const d = event.data as BatchProgressPayload;
progress.completeFile(d.current, d.total);
this.taskQueue.update(
taskId,
progress.percent(),
MESSAGES.STATUS_TASK_BATCH(d.current, d.total, d.file, d.status),
);
} else if (event.event === SSE_EVENT.DONE) {
const parsed = parseAddDoneEvent(event.data);
if (parsed) syncResult = parsed;
} else if (event.event === SSE_EVENT.ALREADY_INGESTING) {
const d = (event.data ?? {}) as { source?: string };
const source = typeof d.source === "string" && d.source ? d.source : paths[0];
new Notice(MESSAGES.NOTICE_ALREADY_INGESTING(source));
this.taskQueue.markWaiting(taskId, MESSAGES.STATUS_WAITING_ON_SERVER);
return;
} else if (event.event === SSE_EVENT.ERROR) {
const d = event.data as { message?: string } | string;
const msg = extractSseErrorMessage(d, MESSAGES.ERROR_UNKNOWN);
new Notice(MESSAGES.ERROR_ADD_FAILED_DETAIL(msg));
this.taskQueue.fail(taskId, msg);
this.markAddFailed(retryKeys);
return;
}
}
if (syncResult) {
const refused = noticeAddRefusals(syncResult);
if (!noticeSyncProblems(syncResult)) {
const summary = summarizeSyncResult(syncResult);
if (summary) new Notice(MESSAGES.NOTICE_SYNC_SUMMARY(summary));
else if (!refused) new Notice(MESSAGES.STATUS_NOTHING_NEW);
}
}
this.taskQueue.complete(taskId);
} catch (err) {
if (err instanceof StreamIdleError) {
new Notice(MESSAGES.ERROR_STREAM_IDLE);
this.taskQueue.fail(taskId, MESSAGES.ERROR_STREAM_IDLE);
this.markAddFailed(retryKeys);
} else if (err instanceof Error && err.name === ERROR_NAME.ABORT_ERROR) {
new Notice(MESSAGES.STATUS_ADD_CANCELLED);
this.taskQueue.cancel(taskId);
this.markAddFailed(retryKeys);
} else if (err instanceof SessionTokenError) {
const msg = sessionTokenInvalidMessage(this.settings.serverMode);
new Notice(msg);
this.taskQueue.fail(taskId, msg);
this.markAddFailed(retryKeys);
} else {
console.error("[lilbee] add failed:", err);
const raw = errorMessage(err, MESSAGES.ERROR_CANNOT_CONNECT);
const msg = extractServerErrorDetail(raw) ?? raw;
new Notice(MESSAGES.ERROR_ADD_FAILED_DETAIL(msg));
this.taskQueue.fail(taskId, msg);
this.markAddFailed(retryKeys);
}
} finally {
this.syncController = null;
}
}
private markAddFailed(paths: string[]): void {
for (const p of paths) this.failedAddPaths.add(p);
}
/** Enqueue a model pull and open the Task Center so the download is visible. */
enqueuePull(name: string): string | null {
const taskId = this.taskQueue.enqueue(name, TASK_TYPE.PULL);
if (taskId !== null) void this.activateTaskView();
return taskId;
}
async activateTaskView(): Promise<void> {
const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_TASKS);
if (existing.length > 0) {
void this.app.workspace.revealLeaf(existing[0]);
return;
}
const leaf = this.app.workspace.getRightLeaf(false);
if (leaf) {
await leaf.setViewState({ type: VIEW_TYPE_TASKS, active: true });
void this.app.workspace.revealLeaf(leaf);
}
}
refreshOpenWikiViews(): void {
for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_WIKI)) {
void (leaf.view as WikiView).refresh();
}
}
async activateMemoriesView(): Promise<void> {
await openMemoriesView(this.app);
}
refreshMemoryViews(): void {
for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_MEMORIES)) {
void (leaf.view as MemoriesView).reload();
}
}
/** When the running server predates the /api/placement routes, explain and
* offer to jump straight to Settings, where the version picker lives. */
private async openPlacementGated(open: () => Promise<void>): Promise<void> {
if (this.serverSupportsPlacement()) {
await open();
return;
}
const modal = new ConfirmModal(this.app, MESSAGES.PLACEMENT_UPDATE_SERVER_PROMPT);
modal.open();
if (await modal.result) this.openPluginSettings();
}
/** Open the placement view in a main-area tab (it is wider than the sidebar views). */
async activatePlacementView(): Promise<void> {
const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_PLACEMENT);
if (existing.length > 0) {
void this.app.workspace.revealLeaf(existing[0]);
return;
}
if (this.openingPlacementLeaf) return;
this.openingPlacementLeaf = true;
try {
// "tab" is the explicit form; the boolean getLeaf(true) is deprecated.
const leaf = this.app.workspace.getLeaf("tab");
if (leaf) {
await leaf.setViewState({ type: VIEW_TYPE_PLACEMENT, active: true });
void this.app.workspace.revealLeaf(leaf);
}
} finally {
this.openingPlacementLeaf = false;
}
}
private async openPlacementBesideChat(chatLeaf: WorkspaceLeaf): Promise<void> {
if (this.openingPlacementLeaf) return;
this.openingPlacementLeaf = true;
try {
await revealPlacementBeside(this.app, chatLeaf);
} finally {
this.openingPlacementLeaf = false;
}
}
openPluginSettings(): void {
openPluginSettingsById(this.app, this.manifest.id);
}
/**
* Re-render the Settings tab if (and only if) the open tab is ours.
* Called whenever server-owned state — active models, persisted config,
* server reachability — changes from somewhere other than the Settings
* UI itself, so the rendered controls don't lie about the live state.
*/
refreshSettingsTab(): void {
const setting = (this.app as unknown as { setting?: { activeTab?: unknown } }).setting;
const activeTab = setting?.activeTab;
if (activeTab instanceof LilbeeSettingTab) {
activeTab.refresh();
}
}
// Re-sync the model rail in every open chat view after a model is switched
// elsewhere (e.g. the catalog), so the pills don't show a stale selection.
/** Repaint the degradation banner in every open chat view. The health probe
* owns the data and runs on its own cadence, so the view cannot pull it. */
refreshOpenChatWarnings(): void {
for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)) {
const view = leaf.view;
if (view instanceof ChatView) view.refreshHealthWarnings();
}
}
refreshOpenChatRails(): void {
for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)) {
const view = leaf.view;
if (view instanceof ChatView) view.refreshRail();
}
}
async activateWikiView(): Promise<void> {
const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_WIKI);
if (existing.length > 0) {
void this.app.workspace.revealLeaf(existing[0]);
return;
}
const leaf = this.app.workspace.getRightLeaf(false);
if (leaf) {
await leaf.setViewState({ type: VIEW_TYPE_WIKI, active: true });
void this.app.workspace.revealLeaf(leaf);
}
}
/** Reveal an already-open chat leaf; its rail can predate a model change. */
private revealChatLeaf(leaf: WorkspaceLeaf): void {
void this.app.workspace.revealLeaf(leaf);
if (leaf.view instanceof ChatView) leaf.view.refreshRail();
}
async activateChatView(): Promise<void> {
const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT);
if (existing.length > 0) {
this.revealChatLeaf(existing[0]);
return;
}
if (this.openingChatLeaf) return;
this.openingChatLeaf = true;
try {
const leaf = this.app.workspace.getRightLeaf(false);
if (leaf) {
await leaf.setViewState({ type: VIEW_TYPE_CHAT, active: true });
void this.app.workspace.revealLeaf(leaf);
}
} finally {
this.openingChatLeaf = false;
}
}
/**
* Tile the plugin's views as side-by-side columns in the main area: chat and
* the Task Center always, plus wiki, memories, and placement when they are
* already open. Reuses open leaves (chat keeps its conversation) and splits
* any it has to create beside the previous one. Bind a hotkey in Settings → Hotkeys.
*/
async arrangeViews(): Promise<void> {
if (this.openingChatLeaf) return;
this.openingChatLeaf = true;
try {
const workspace = this.app.workspace;
const openChat = workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0] ?? null;
const included = [
VIEW_TYPE_CHAT,
VIEW_TYPE_TASKS,
VIEW_TYPE_WIKI,
VIEW_TYPE_MEMORIES,
VIEW_TYPE_PLACEMENT,
].filter(
(type) =>
type === VIEW_TYPE_CHAT || type === VIEW_TYPE_TASKS || workspace.getLeavesOfType(type).length > 0,
);
let anchor: WorkspaceLeaf | null = null;
for (const type of included) {
let leaf = workspace.getLeavesOfType(type)[0] ?? null;
if (!leaf) {
// Tile as side-by-side columns in the main area: a fresh tab
// for the first view, then vertical splits beside it.
leaf = anchor ? workspace.createLeafBySplit(anchor, "vertical") : workspace.getLeaf("tab");
if (!leaf) continue;
await leaf.setViewState({ type, active: true });
}
anchor = leaf;
}
for (const type of included) {
const leaf = workspace.getLeavesOfType(type)[0];
if (leaf === openChat) this.revealChatLeaf(leaf);
else if (leaf) void workspace.revealLeaf(leaf);
}
} finally {
this.openingChatLeaf = false;
}
}
private registerPendingSyncHintWatchers(): void {
const handler = (file: TAbstractFile) => {
if (this.wikiSync?.isWikiPath(file.path)) return;
// Skip paths the server itself writes into the vault — they're
// already known sources, not work to sync.
if (file.path.startsWith(MANAGED_DOCS_PREFIX)) return;
this.schedulePendingSyncHint();
};
const vault = this.app.vault;
this.registerEvent(vault.on("create", handler));
this.registerEvent(vault.on("modify", handler));
this.registerEvent(vault.on("delete", handler));
this.registerEvent(vault.on("rename", handler));
}
private schedulePendingSyncHint(): void {
if (this.pendingHintTimeout) {
window.clearTimeout(this.pendingHintTimeout);
}
this.pendingHintTimeout = window.setTimeout(() => {
this.pendingHintTimeout = null;
// Bail if the plugin was unloaded between scheduling and firing.
// The statusBarEl guard inside updatePendingSyncHint covers this,
// but the explicit check here keeps the contract local.
if (!this.statusBarEl) return;
void this.updatePendingSyncHint();
}, PENDING_SYNC_HINT_DEBOUNCE_MS);
}
private async countPendingSync(): Promise<number> {
// Only managed mode with vault storage points the server's documents_dir at
// <vault>/lilbee; elsewhere Sync can't reconcile these files, so don't count them.
if (this.settings.serverMode !== SERVER_MODE.MANAGED || !this.settings.storeContentInVault) {
return 0;
}
// The vault adapter can be gone if the timer fires after the host
// environment teared down (vitest end-of-file cleanup while a real
// setTimeout was still pending). Bail cleanly instead of crashing.
const files = this.app?.vault?.getFiles?.();
if (!Array.isArray(files)) return 0;
// Only count files inside lilbee's managed document folder
// (<vault>/lilbee/). That's the scope `Sync vault` actually
// reconciles. Loose vault notes live outside it and are indexed
// only via the explicit Add action (which copies them in), so
// counting them here would show a count that sync can never clear.
const docFiles = files
.filter((f) => SUPPORTED_SYNC_EXTENSIONS.has(f.extension.toLowerCase()))
.filter((f) => f.path.startsWith(MANAGED_DOCS_PREFIX) && !this.wikiSync?.isWikiPath(f.path));
const known = new Set<string>();
try {
// Sources are relative paths; the basename is the key shared with vault files.
let offset = 0;
const limit = 100;
while (true) {
const page = await this.api.listDocuments(undefined, limit, offset);
for (const d of page.documents) known.add(basename(d.filename));
if (!page.has_more || page.documents.length === 0) break;
offset += page.documents.length;
}
} catch {
// Server offline — leave the hint hidden rather than guessing.
return 0;
}
return docFiles.filter((f) => !known.has(f.name)).length;
}
async updatePendingSyncHint(): Promise<void> {
if (!this.syncPillEl) return;
const count = await this.countPendingSync();
if (!this.syncPillEl) return;
// countPendingSync returns 0 when the server is unreachable, so the
// pill naturally hides when lilbee isn't up — the main status pill
// owns the running/stopped state, this one only the sync count.
this.pendingSyncCount = count;
if (count > 0) {
this.syncPillEl.setText(MESSAGES.STATUS_SYNC_PILL(count));
this.syncPillEl.show();
} else {
this.syncPillEl.hide();
}
}
async runWikiLint(): Promise<void> {
const taskId = this.taskQueue.enqueue("Wiki lint", TASK_TYPE.WIKI);
if (taskId === null) {
new Notice(MESSAGES.NOTICE_QUEUE_FULL);
return;
}
try {
const result = await this.api.wikiLint();
this.taskQueue.complete(taskId);
new Notice(MESSAGES.NOTICE_WIKI_LINT_DONE(result.issues.length), NOTICE_DURATION_MS);
new LintModal(this.app, result.issues).open();
} catch (err) {
const msg = errorMessage(err, MESSAGES.ERROR_UNKNOWN);
this.taskQueue.fail(taskId, msg);
}
}
/**
* Refresh the wiki across every ingested source.
*
* The run issues per-source LLM calls and can take minutes, so the server
* streams its progress and closes with a `done` event carrying the summary.
* Aborting stops it at the next source boundary and releases the server's
* build mutex, so a cancelled run does not block the other wiki commands.
*/
async runWikiUpdate(): Promise<void> {
const taskId = this.taskQueue.enqueue(MESSAGES.TASK_WIKI_UPDATE, TASK_TYPE.WIKI);
if (taskId === null) {
new Notice(MESSAGES.NOTICE_QUEUE_FULL);
return;
}
const controller = new AbortController();
this.taskQueue.registerAbort(taskId, controller);
try {
let count = 0;
for await (const event of this.api.wikiUpdate(controller.signal)) {
if (event.event === SSE_EVENT.WIKI_PAGE) {
const d = event.data as WikiPagePayload;
// A phase with no unit count reports total 0; -1 keeps the
// bar indeterminate rather than dividing by zero.
const pct = d.total > 0 ? Math.round((d.current / d.total) * 100) : -1;
this.taskQueue.update(taskId, pct, MESSAGES.TASK_WIKI_PAGE(d.label, d.current, d.total));
} else if (event.event === SSE_EVENT.WIKI_PHASE) {
const d = event.data as WikiPhasePayload;
this.taskQueue.update(taskId, -1, MESSAGES.TASK_WIKI_PHASE(d.phase));
} else if (event.event === SSE_EVENT.DONE) {
count = (event.data as WikiBuildResult).count;
} else if (event.event === SSE_EVENT.ERROR) {
const d = event.data as { message?: string } | string;
throw new Error(extractSseErrorMessage(d, MESSAGES.ERROR_UNKNOWN));
}
}
this.taskQueue.complete(taskId);
new Notice(MESSAGES.NOTICE_WIKI_UPDATE_DONE(count), NOTICE_DURATION_MS);
this.refreshOpenWikiViews();
if (this.wikiSync) {
void this.reconcileWiki();
}
} catch (err) {
this.taskQueue.fail(taskId, errorMessage(err, MESSAGES.ERROR_UNKNOWN));
}
}
async runWikiPrune(): Promise<void> {
const modal = new ConfirmModal(this.app, MESSAGES.NOTICE_WIKI_PRUNE_CONFIRM);
modal.open();
const confirmed = await modal.result;
if (!confirmed) return;
const taskId = this.taskQueue.enqueue("Wiki prune", TASK_TYPE.WIKI);
if (taskId === null) {
new Notice(MESSAGES.NOTICE_QUEUE_FULL);
return;
}
try {
const result = await this.api.wikiPrune();
this.taskQueue.complete(taskId);
new Notice(MESSAGES.NOTICE_WIKI_PRUNE_DONE(result.archived), NOTICE_DURATION_MS);
this.refreshOpenWikiViews();
// Reconcile vault after pruning
if (this.wikiSync) {
void this.reconcileWiki();
}
} catch (err) {
const msg = errorMessage(err, MESSAGES.ERROR_UNKNOWN);
this.taskQueue.fail(taskId, msg);
}
}
/** Download Chromium so the crawler can render with a browser. True once it is installed. */
async installCrawlerBrowser(): Promise<boolean> {
const taskId = this.taskQueue.enqueue(MESSAGES.TASK_CRAWLER_BROWSER_SETUP, TASK_TYPE.SETUP);
if (taskId === null) {
new Notice(MESSAGES.NOTICE_QUEUE_FULL);
return false;
}
const controller = new AbortController();
this.taskQueue.registerAbort(taskId, controller);
try {
const error = await this.drainCrawlerSetup(taskId, controller.signal);
if (error !== null) {
this.taskQueue.fail(taskId, error);
new Notice(MESSAGES.ERROR_CRAWLER_SETUP_FAILED.replace("{error}", error));
return false;
}
this.taskQueue.complete(taskId);
this.api.invalidateCapability(CAPABILITY.CRAWLING_BROWSER);
new Notice(MESSAGES.NOTICE_CRAWLER_BROWSER_READY, NOTICE_DURATION_MS);
return true;
} catch (err) {
const msg = errorMessage(err, MESSAGES.ERROR_UNKNOWN);
this.taskQueue.fail(taskId, msg);
new Notice(MESSAGES.ERROR_CRAWLER_SETUP_FAILED.replace("{error}", msg));
return false;
}
}
/** A download with no announced total stays indeterminate rather than dividing by zero. */
private renderSetupProgress(taskId: string, d: SetupProgressPayload): void {
const pct = d.total_bytes ? (d.downloaded_bytes / d.total_bytes) * 100 : -1;
this.taskQueue.update(taskId, pct, formatSetupDetail(d.downloaded_bytes, d.total_bytes));
}
/** Renders the setup stream onto `taskId`. Returns null on success, else the error text. */
private async drainCrawlerSetup(taskId: string, signal: AbortSignal): Promise<string | null> {
let outcome: string | null = MESSAGES.ERROR_CRAWLER_SETUP_INCOMPLETE;
for await (const event of this.api.setupCrawler(signal)) {
switch (event.event) {
case SSE_EVENT.SETUP_START: {
const d = event.data as SetupStartPayload;
this.taskQueue.update(taskId, 0, formatSetupDetail(0, d.size_estimate_bytes));
break;
}
case SSE_EVENT.SETUP_PROGRESS:
this.renderSetupProgress(taskId, event.data as SetupProgressPayload);
break;
case SSE_EVENT.SETUP_DONE: {
const d = event.data as SetupDonePayload;
outcome = d.success ? null : (d.error ?? MESSAGES.ERROR_UNKNOWN);
break;
}
}
}
return outcome;
}
async runCrawl(
url: string,
depth: number | null,
maxPages: number | null,
renderMode?: CrawlRenderMode,
includeSubdomains?: boolean,
): Promise<void> {
const taskId = this.taskQueue.enqueue(`Crawl ${url}`, TASK_TYPE.CRAWL);
if (taskId === null) {
new Notice(MESSAGES.NOTICE_QUEUE_FULL);
return;
}
const controller = new AbortController();
this.taskQueue.registerAbort(taskId, controller);
let setupTaskId: string | null = null;
let setupResolved = false;
try {
let pageCount = 0;
let failedCount = 0;
const rawStream = this.api.crawl(url, depth, maxPages, controller.signal, renderMode, includeSubdomains);
for await (const event of withIdleTimeout(rawStream, STREAM_IDLE_TIMEOUT_MS, () => controller.abort())) {
switch (event.event) {
case SSE_EVENT.SETUP_START: {
// Always surface the preparing-crawler stage on the crawl task —
// covers both the Chromium download and the first-run browser warmup.
this.taskQueue.update(taskId, -1, MESSAGES.STATUS_TASK_CRAWLER_PREPARING);
// Only track a separate download sub-task for a real install (one
// with a size estimate). The browser warmup has none and would
// otherwise show a misleading "0 MB" download.
const d = event.data as SetupStartPayload;
if (d.size_estimate_bytes && setupTaskId === null) {
setupTaskId = this.taskQueue.enqueue("Chromium setup", TASK_TYPE.SETUP);
if (setupTaskId !== null) {
this.taskQueue.update(setupTaskId, 0, formatSetupDetail(0, d.size_estimate_bytes));
}
}
break;
}
case SSE_EVENT.SETUP_PROGRESS: {
if (setupTaskId === null) break;
this.renderSetupProgress(setupTaskId, event.data as SetupProgressPayload);
break;
}
case SSE_EVENT.SETUP_DONE: {
const d = event.data as SetupDonePayload;
setupResolved = true;
if (d.success) {
if (setupTaskId !== null) this.taskQueue.complete(setupTaskId);
this.taskQueue.update(taskId, -1, "");
} else {
const err = d.error ?? MESSAGES.ERROR_UNKNOWN;
if (setupTaskId !== null) this.taskQueue.fail(setupTaskId, err);
this.taskQueue.fail(taskId, MESSAGES.ERROR_CRAWLER_SETUP_FAILED_SHORT);
new Notice(MESSAGES.ERROR_CRAWLER_SETUP_FAILED.replace("{error}", err));
return;
}
break;
}
case SSE_EVENT.CRAWL_START:
break;
case SSE_EVENT.CRAWL_PAGE: {
pageCount++;
this.taskQueue.update(taskId, -1, `${pageCount} pages`);
break;
}
case SSE_EVENT.CRAWL_PAGE_FAILED: {
failedCount++;
break;
}
case SSE_EVENT.CRAWL_DONE: {
const d = event.data as { pages_crawled?: number };
this.taskQueue.complete(taskId);
new Notice(MESSAGES.NOTICE_CRAWL_DONE(d.pages_crawled ?? pageCount, failedCount));
void this.triggerSync(undefined, SYNC_TRIGGER.AUTOMATIC);
return;
}
case SSE_EVENT.CRAWL_ERROR:
case SSE_EVENT.ERROR: {
const d = event.data as { message?: string };
this.taskQueue.fail(taskId, d.message ?? "unknown");
new Notice(MESSAGES.ERROR_CRAWL_ERROR.replace("{msg}", d.message ?? "unknown"));
return;
}
}
}
this.taskQueue.complete(taskId);
} catch (err) {
if (setupTaskId !== null && !setupResolved) {
this.taskQueue.fail(setupTaskId, MESSAGES.ERROR_CRAWLER_SETUP_FAILED_SHORT);
}
if (err instanceof StreamIdleError) {
new Notice(MESSAGES.ERROR_STREAM_IDLE);
this.taskQueue.fail(taskId, MESSAGES.ERROR_STREAM_IDLE);
return;
}
const msg = errorMessage(err, MESSAGES.ERROR_UNKNOWN);
this.taskQueue.fail(taskId, msg);
new Notice(MESSAGES.ERROR_CRAWL_FAILED.replace("{msg}", msg));
}
}
async triggerSync(options?: SyncOptions, trigger: SyncTrigger = SYNC_TRIGGER.USER): Promise<void> {
if (!this.statusBarEl) return;
// One sync at a time: a user trigger reports the running one, an automatic one defers.
if (this.taskQueue.hasPending(TASK_TYPE.SYNC)) {
if (trigger === SYNC_TRIGGER.USER) new Notice(MESSAGES.NOTICE_SYNC_IN_PROGRESS);
else this.deferredSync = { options };
return;
}
const taskId = this.taskQueue.enqueue(syncTaskLabel(options), TASK_TYPE.SYNC);
if (taskId === null) {
new Notice(MESSAGES.NOTICE_QUEUE_FULL);
return;
}
this.syncController = new AbortController();
this.taskQueue.registerAbort(taskId, this.syncController);
try {
const progress = new FileProgressTracker();
let syncResult: AddDone | null = null;
const controller = this.syncController;
const rawStream = this.api.syncStream(controller.signal, options);
for await (const event of withIdleTimeout(rawStream, STREAM_IDLE_TIMEOUT_MS, () => controller.abort())) {
if (event.event === SSE_EVENT.FILE_START) {
const d = event.data as { current_file: number; total_files: number };
progress.startFile(d.current_file, d.total_files);
this.taskQueue.update(
taskId,
progress.percent(),
MESSAGES.STATUS_TASK_SYNCING_FILE.replace("{current}", String(d.current_file)).replace(
"{total}",
String(d.total_files),
),
);
} else if (event.event === SSE_EVENT.EXTRACT) {
const d = event.data as { page: number; total_pages: number; file: string };
progress.setExtractFraction(d.page, d.total_pages);
this.taskQueue.update(
taskId,
progress.percent(),
MESSAGES.STATUS_TASK_EXTRACTING.replace("{file}", d.file)
.replace("{page}", String(d.page))
.replace("{total}", String(d.total_pages)),
);
} else if (event.event === SSE_EVENT.EMBED) {
const d = event.data as { chunk: number; total_chunks: number };
progress.setEmbedFraction(d.chunk, d.total_chunks);
this.taskQueue.update(
taskId,
progress.percent(),
MESSAGES.STATUS_TASK_EMBEDDING.replace("{chunk}", String(d.chunk)).replace(
"{total}",
String(d.total_chunks),
),
);
} else if (event.event === SSE_EVENT.BATCH_PROGRESS) {
const d = event.data as BatchProgressPayload;
progress.completeFile(d.current, d.total);
this.taskQueue.update(
taskId,
progress.percent(),
MESSAGES.STATUS_TASK_BATCH(d.current, d.total, d.file, d.status),
);
} else if (event.event === SSE_EVENT.DONE) {
const parsed = parseAddDoneEvent(event.data);
if (parsed) syncResult = parsed;
} else if (event.event === SSE_EVENT.ERROR) {
const d = event.data as { message?: string } | string;
const msg = extractSseErrorMessage(d, MESSAGES.ERROR_UNKNOWN);
new Notice(MESSAGES.STATUS_SYNC_FAILED);
this.taskQueue.fail(taskId, msg);
return;
}
}
if (syncResult && !noticeSyncProblems(syncResult)) {
const summary = summarizeSyncResult(syncResult);
if (summary) new Notice(MESSAGES.STATUS_SYNCED.replace("{summary}", summary));
}
this.taskQueue.complete(taskId);
} catch (err) {
if (err instanceof StreamIdleError) {
new Notice(MESSAGES.ERROR_STREAM_IDLE);
this.taskQueue.fail(taskId, MESSAGES.ERROR_STREAM_IDLE);
} else if (err instanceof Error && err.name === ERROR_NAME.ABORT_ERROR) {
new Notice(MESSAGES.STATUS_SYNC_CANCELLED);
this.taskQueue.cancel(taskId);
} else if (err instanceof SessionTokenError) {
const msg = sessionTokenInvalidMessage(this.settings.serverMode);
new Notice(msg);
this.taskQueue.fail(taskId, msg);
} else {
console.error("[lilbee] sync failed:", err);
new Notice(MESSAGES.STATUS_SYNC_FAILED);
this.taskQueue.fail(taskId, MESSAGES.ERROR_CANNOT_CONNECT);
}
} finally {
this.syncController = null;
this.schedulePendingSyncHint();
this.runDeferredSync();
}
}
/** Runs the sync deferred during this one; the sync task is terminal before this fires. */
private runDeferredSync(): void {
const deferred = this.deferredSync;
if (!deferred) return;
this.deferredSync = null;
void this.triggerSync(deferred.options, SYNC_TRIGGER.AUTOMATIC);
}
}
|