All files / src main.ts

100% Statements 1359/1359
100% Branches 746/746
100% Functions 186/186
100% Lines 1177/1177

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                                                                                                                                                                                                            2x   2x   2x       2x   4x     10x 10x 1x   9x 9x       13x 13x 13x 13x 13x 13x 13x         23x 22x 21x       121x 121x 134x                         83x 83x 83x 83x     14x 14x 14x 14x       2x 2x 2x 2x       4x 3x       6x 5x       21x 21x 21x 21x         25x 21x 21x 2x   19x       21x 17x                             7x 7x 7x 5x         5x 5x 4x       478x 478x 478x 478x 478x 478x 478x 478x 478x 478x 478x 478x 478x 478x 478x 478x 478x 478x   478x 478x   478x 478x 478x 478x 478x 478x 478x       478x   478x         478x     408x 408x 408x               408x 2x 2x     408x 408x 408x 408x             408x 408x 408x 408x 408x 408x   408x 1x   408x           408x 1629x 1629x   5x     408x 408x 408x 408x 408x 530x 530x         530x 408x   408x   1x 1x   1x                   408x 400x   1x 399x 80x     80x 80x     319x 319x 319x       407x 7x     407x 407x   407x                 407x 407x           409x 1636x 1636x   409x       97x 93x 93x 92x 1x 1x   91x 91x   91x 91x   90x 90x 90x 90x 84x   84x   83x 83x 83x 83x 83x 83x 97x 77x 77x 77x 77x 77x   6x 6x     91x                   83x 83x   82x 82x 70x 70x           12x 12x 8x 8x 8x 8x 8x 8x   4x 3x 3x 3x 3x 3x 3x       3x   1x 1x       86x           15x   5x 4x 4x 5x 5x 5x     1x                   98x 98x 6x 6x 6x 6x 4x 4x 4x 4x   2x 1x 1x   1x   93x       1x 1x 1x       6x       5x   4x 4x 4x       4x 53x 53x   3x   50x   50x       478x     106x 106x       106x         3x         1x       99x 99x 98x 98x 18x 18x 18x   98x 98x     9x 9x 9x 9x   1x     89x 89x 89x   9x 9x   9x 1x 1x   8x   9x 9x           2x       84x 55x 55x 55x 55x               82x 82x 82x 80x 82x 82x             82x 82x                                       84x 78x   76x 76x     76x 76x   1x 1x     75x 84x 84x 72x     3x 3x 3x       2x 2x   1x 1x 1x 1x           2x 2x 1x         11x 11x 10x                 9x 9x       8x 8x 1x     7x 7x 7x   7x 7x   7x   7x           7x 7x 7x 7x 7x         1x 1x       10x 10x       75x 75x     75x 75x 75x 4x   29x         78x 78x 77x 76x 76x   75x 75x     43x   32x 32x 4x 4x 4x 4x 3x   1x   4x         9x 9x 8x 2x       8x 4x 4x 4x       8x 9x 9x         3x 1x 1x   2x         1x       8x       8x 8x     8x 6x 6x     8x         408x 4x 4x   408x 4x 4x 3x 4x         11x 11x         4x                           18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x                     17x 16x   9x 8x   9x 9x 9x 9x 9x 9x   2x 2x 2x   3x 3x 3x   2x 2x 2x         1115x 1115x                           429x 83x   346x 3x   343x 343x               412x 412x 412x 412x         8x 2x 2x   6x 1x 1x 1x   5x     4x 3x 3x                               58x 43x   15x       407x       3x 2x 2x       407x       3x 2x 2x       407x       3x 2x 2x       407x       3x 2x 2x       407x       5x 4x 4x 3x 3x       407x       5x 4x 4x 5x 2x 2x       407x       3x 2x 2x       407x       3x 2x 2x       407x       4x 3x 2x 2x 2x 2x     3x       407x       3x 2x 2x       407x       3x 2x 2x       407x       6x 4x 4x       407x       3x 2x 2x       407x       3x 2x 2x       407x       7x 6x 6x       407x       3x 2x 2x       407x       3x 2x 2x       407x       3x 2x 2x       407x     1x     407x     1x     407x     1x     407x       3x 2x 2x       407x       3x 2x 2x       407x       3x 2x 2x       407x       4x 3x 3x 2x 2x       407x     1x       407x     1x     407x       4x 3x 2x 2x                     5x 5x 4x 4x 4x               5x 1x 1x   4x 3x         5x 5x 1x 1x           5x 5x 5x 5x 5x 5x 5x       476x 476x 476x 476x 476x 476x 476x       478x     6x       12x 12x 12x 11x       150x       19x 19x 18x       33x       17x 17x 16x       4x       3x 3x 2x       84x 84x 84x       559x       530x       7x 7x 7x   7x 3x 2x     4x 3x 3x 3x   4x           4x 4x         1044x 1022x 1044x 1044x 1044x 571x 571x   1022x       1128x 1105x             1105x       453x 1x 1x           452x 2x 2x 2x         450x 453x 453x       409x 408x 408x 408x       36x 23x 22x   21x     20x 20x 36x 3x 3x 1x 1x   3x   17x 17x         9x 8x 7x 7x 7x 7x       1x       3x     478x     7x 6x 5x   5x     7x       532x 532x 532x   532x 223x 223x 131x 131x   92x 92x     309x 1x       1x 1x     308x 308x 532x   532x 291x       291x   17x     17x   308x       131x 72x   72x           72x 72x 72x   59x 49x 49x 49x 49x 49x 49x   10x         6x 6x   1x 1x   5x 6x 6x 1x 1x     4x 4x 4x 1x 1x   3x 6x 1x 1x   2x       413x 413x 13x 13x 13x           413x 413x 412x 6x 6x 6x           413x 2x 2x           13x   11x 11x 1x   11x 11x       5x       7x 6x 6x 5x 1x               61x 2x 2x       50x 50x 50x 50x 9x 9x 9x         41x       31x 29x 28x   31x 31x               27x 27x   25x 25x                                       27x 27x 27x 27x   1x 1x 1x   26x 26x 32x 2x 2x   30x 32x 32x 32x 32x 3x   27x   26x   4x 4x     26x                 64x 32x 32x         30x 30x 3x 3x 30x 1001x 1001x   1x       33x 32x 31x     31x   33x 33x   29x 29x       2x 2x               55x 55x 1x 1x   59x 54x 54x   54x 54x 54x 54x 54x 54x 30x 3x 3x 3x               27x 1x 1x 1x             26x 1x 1x 1x               25x 1x 1x 1x         24x 15x 15x 9x 3x 3x 3x 3x 3x 6x 5x 5x 5x 5x 5x 5x       34x 11x 11x   34x   12x 4x 4x 4x 8x 2x 2x 2x 6x 1x 1x 1x 1x   5x 5x 5x 5x 5x     54x         17x       3x 3x 1x 1x   2x 2x 1x 1x         8x 2x         3x 3x 1x 1x   2x 2x 1x 1x         1x 1x             3x   3x 2x 2x                   11x 11x 11x 1x             1x 2x 2x         4x 4x 1x 1x   3x 3x 2x 2x         5x 5x 1x 1x   4x 3x 3x 3x 3x 2x 2x     3x                     6x 5x 5x 5x 5x   20x   5x 5x 14x 14x     8x 8x 5x   11x   5x 14x 14x     5x         407x 6x     5x 2x   407x 407x 407x 407x 407x       552x 335x   552x 110x       110x 109x             525x 432x         93x 525x           92x 14x 13x 92x 92x         92x 92x 92x 93x 92x 7x 1x       86x   10x       526x 525x 525x       524x 524x 3x 3x   521x         4x 4x 1x 1x   3x 3x 1x 1x 1x   2x 2x         11x 11x 1x 1x   10x 10x 10x 10x 10x 4x 6x 2x 2x 4x 3x 3x     4x 4x 4x   4x 2x     6x 6x         11x 11x 11x 11x   10x 10x 1x 1x   9x 9x 9x 9x 9x 8x 4x 4x 4x 3x 3x     4x 4x 4x   4x 1x     5x 5x                   24x 24x 1x 1x   23x 23x 23x 23x 23x 23x 23x 23x 46x       10x       10x 10x 8x 8x 6x     10x     6x 4x 4x 6x 6x     8x 8x 8x 5x 5x   3x 3x 3x 3x 3x   5x     4x   3x 3x 3x     11x 11x 11x 11x 11x       3x 3x 3x 3x       1x   5x 1x   5x 2x 2x 2x   3x 3x 3x         25x         24x 23x 23x 1x 1x   22x 22x   22x 22x 22x 22x 22x 22x 12x 2x 2x 2x               10x 1x 1x 1x             9x 1x 1x 1x               8x 1x 1x 1x         7x 3x 3x 4x 3x 3x 3x 3x 3x       12x 2x 2x   12x   6x 2x 2x 4x 2x 2x 2x 1x 1x 1x   1x 1x 1x     21x 21x        
import {
    type ItemView,
    type Menu,
    type MenuItem,
    Notice,
    Plugin,
    type TAbstractFile,
    type WorkspaceLeaf,
} from "obsidian";
import { LilbeeClient, SessionTokenError } from "./api";
import type { RequestOutcome } from "./api";
import { BinaryManager, getLatestRelease, checkForUpdate, node } from "./binary-manager";
import { exportDatasetToDisk, importDatasetFromDisk } from "./dataset-io";
import { exportDiagnostics } from "./diagnostics-export";
import { ErrorJournal } from "./error-journal";
import { DownloadCanceledError } from "./binary-manager";
import type { DownloadProgress, ReleaseInfo } from "./binary-manager";
import { ServerManager, killServerTree } 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 {
    CONFIG_KEY,
    DEFAULT_SETTINGS,
    DOT_STATE,
    ERROR_NAME,
    LOCK_STATE,
    LOGS_DIR,
    MANAGED_CONSENT_RESULT,
    MANAGED_PHASE,
    SERVER_MODE,
    SERVER_STATE,
    SETUP_OUTCOME,
    SSE_EVENT,
    TASK_STATUS,
    TASK_TYPE,
    type ActiveLock,
    type BatchProgressPayload,
    type CrawlRenderMode,
    type DiagnosticsContext,
    type DotState,
    type LilbeeSettings,
    type ManagedServerProgressHandler,
    type ServerMode,
    type SetupOutcome,
    type ServerState,
    type ServerVariant,
    type SetupDonePayload,
    type SetupProgressPayload,
    type SetupStartPayload,
    type SyncDone,
    type SyncOptions,
    type TaskEntry,
    type UninstallPlan,
    type VaultAdapter,
} from "./types";
import { MESSAGES } from "./locales/en";
import { displayLabelForRef, extractHfRepo } from "./utils/model-ref";
import {
    errorMessage,
    extractSseErrorMessage,
    HEALTH_FAILURE_STREAK_THRESHOLD,
    HEALTH_PROBE_INTERVAL_MS,
    NOTICE_DURATION_MS,
    NOTICE_ERROR_DURATION_MS,
    NOTICE_PERMANENT,
    percentOfBytes,
    sessionTokenInvalidMessage,
    STREAM_IDLE_TIMEOUT_MS,
    StreamIdleError,
    withIdleTimeout,
} from "./utils";
import { formatBytes } from "./storage-stats";
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, VIEW_TYPE_MEMORIES } from "./views/memories-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 { 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";
 
interface GenerateErrorData {
    message?: string;
}
interface PruneData {
    archived?: number;
}
 
const BYTES_PER_MB = 1_000_000;
 
const PENDING_SYNC_HINT_DEBOUNCE_MS = 1000;
 
const SUPPORTED_SYNC_EXTENSIONS = new Set(["md", "pdf", "txt", "html"]);
 
// Vault-relative folder where managed mode stores lilbee's documents
// (see configureManagedStorage). It is the only scope `Sync vault` reconciles.
const MANAGED_DOCS_PREFIX = "lilbee/";
 
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: SyncDone): 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`);
    return parts.join(", ");
}
 
/** 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)));
    }
}
 
export function parseAddDoneEvent(data: unknown): SyncDone | null {
    if (!data || typeof data !== "object") return null;
    const obj = data as Record<string, unknown>;
    if (obj.sync && typeof obj.sync === "object") {
        return coerceSyncDone(obj.sync as Record<string, unknown>);
    }
    return coerceSyncDone(obj);
}
 
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[]) : [],
    };
}
 
/** 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 {
    const received = formatBytes(progress.receivedBytes);
    const percent = percentOfBytes(progress.receivedBytes, progress.totalBytes);
    if (percent === undefined || progress.totalBytes === null) return MESSAGES.STATUS_DOWNLOAD_RECEIVED(received);
    return MESSAGES.STATUS_DOWNLOAD_PROGRESS(percent, received, formatBytes(progress.totalBytes));
}
 
/** The status bar is narrow: percent only, with the byte detail left to Settings. */
function downloadStatusBar(progress: DownloadProgress): string {
    const percent = percentOfBytes(progress.receivedBytes, progress.totalBytes);
    if (percent === undefined) return MESSAGES.STATUS_DOWNLOADING;
    return MESSAGES.STATUS_DOWNLOADING_PERCENT(percent);
}
 
export default class LilbeePlugin extends Plugin {
    settings: LilbeeSettings = { ...DEFAULT_SETTINGS };
    api: LilbeeClient = new LilbeeClient("");
    activeModel = "";
    statusBarEl: HTMLElement | null = null;
    syncPillEl: HTMLElement | null = null;
    chatRibbonIconEl: HTMLElement | null = null;
    binaryManager: BinaryManager | null = null;
    serverManager: ServerManager | null = null;
    journal = new ErrorJournal();
    vaultRegistry: VaultRegistry | null = null;
    vaultId = "";
    syncController: AbortController | null = null;
    private pendingSyncCount = 0;
    private pendingHintTimeout: number | null = null;
    private previousServerMode: ServerMode = SERVER_MODE.MANAGED;
    private startingServer = false;
    private serverStartFailed = false;
    private unloaded = false;
    // Guards chat-leaf creation against re-entrant duplicate tabs while setViewState is in flight (issue #169).
    private openingChatLeaf = false;
    taskQueue: TaskQueue = new TaskQueue();
    /** Paths whose most-recent add failed — retry skips the reindex confirm. */
    private failedAddPaths = new Set<string>();
    wikiEnabled = false;
    wikiPageCount = 0;
    wikiDraftCount = 0;
    wikiSync: WikiSync | null = null;
    private healthProbeHandle: number | null = null;
    private serverUnreachable = false;
    // 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;
    // 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();
        this.wikiEnabled = this.settings.wikiEnabled;
 
        // Sweep up status-bar items + ribbon icons that prior dead lilbee
        // instances left behind. Each crashed/incompletely-unloaded reload
        // accumulates more, so the corner ends up with multiple "lilbee:
        // ready" / "lilbee: error" pills side by side until Obsidian
        // restarts. Take a clean slate before adding our own. Guarded for
        // node-environment tests where document is undefined.
        if (typeof activeDocument !== "undefined") {
            activeDocument.querySelectorAll(".status-bar-item.plugin-lilbee").forEach((el) => el.remove());
            activeDocument.querySelectorAll(".lilbee-ribbon-icon").forEach((el) => el.remove());
        }
 
        this.statusBarEl = this.addStatusBarItem();
        this.statusBarEl.addClass("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));
        this.addSettingTab(new LilbeeSettingTab(this.app, this));
        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.autoUpdateServerBinary();
                });
            } else {
                this.configureApi(this.settings.serverUrl);
                this.setStatusReady();
                void this.fetchActiveModel();
            }
        }
 
        if (!this.settings.setupCompleted) {
            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();
        });
    }
 
    /** 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]) {
            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): 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 {
            if (!(await this.acquireLockOrBail(registry, onProgress))) return;
 
            const sharedRoot = registry.sharedRoot;
            this.binaryManager = new BinaryManager(sharedBinDir(sharedRoot));
            const binaryPath = await this.ensureBinaryWithUi(onProgress);
            if (binaryPath === null) return;
            await this.recordLilbeeVersionAfterDownload();
            // A spawn after unload would leak a server no plugin instance tracks.
            if (this.unloaded) return;
 
            try {
                this.serverManager = this.buildServerManager(binaryPath, registry, sharedRoot);
                this.journal.setLogDir(node.join(this.serverManager.dataDir, LOGS_DIR));
                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.configureApi(this.serverManager.serverUrl);
                void this.fetchActiveModel();
                void this.configureManagedStorage();
                this.recordReadyState();
                onProgress?.({ phase: MANAGED_PHASE.READY, message: "" });
            } catch (err) {
                this.showError("failed to start server", err);
                onProgress?.({ phase: MANAGED_PHASE.ERROR, message: errorMessage(err, String(err)) });
            }
        } finally {
            this.startingServer = false;
        }
    }
 
    /**
     * 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): Promise<SetupOutcome> {
        const registry = this.vaultRegistry;
        if (!registry) return { kind: SETUP_OUTCOME.CANCELED };
 
        const binaryPresent = new BinaryManager(sharedBinDir(registry.sharedRoot)).binaryExists();
        if (binaryPresent && !this.serverUninstalled) {
            await this.startManagedServer(onProgress);
            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).openConsent();
        if (result.kind === MANAGED_CONSENT_RESULT.DOWNLOAD) {
            this.settings.serverMode = SERVER_MODE.MANAGED;
            this.previousServerMode = SERVER_MODE.MANAGED;
            await this.persistAll();
            this.setServerUninstalled(false);
            await this.startManagedServer(onProgress);
            return { kind: SETUP_OUTCOME.STARTED, mode: SERVER_MODE.MANAGED };
        }
        if (result.kind === MANAGED_CONSENT_RESULT.EXTERNAL) {
            this.settings.serverMode = SERVER_MODE.EXTERNAL;
            this.previousServerMode = SERVER_MODE.EXTERNAL;
            await this.persistAll();
            this.configureApi(this.settings.serverUrl);
            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),
            modelsDir: sharedModelsDir(sharedRoot),
            ragSystemPrompt: this.settings.ragSystemPrompt,
            generalSystemPrompt: this.settings.generalSystemPrompt,
            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);
            },
            onShutdownFailure: (err: Error) => {
                new Notice(`${MESSAGES.ERROR_SERVER_SHUTDOWN_FAILED}: ${err.message}`);
            },
        });
    }
 
    /** Decide who owns the shared root and (if not us) ask the user. */
    private async acquireLockOrBail(
        registry: VaultRegistry,
        onProgress?: ManagedServerProgressHandler,
    ): Promise<boolean> {
        const state = registry.lockState(this.vaultId);
        if (state === LOCK_STATE.LIVE_OTHER) {
            const owner = registry.readLock();
            const ownerName = owner ? this.lookupVaultName(owner.vaultId) : "another vault";
            const takeOver = await this.confirmTakeOver(ownerName);
            if (!takeOver) {
                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 false;
            }
            if (!(await this.terminateOwningProcess(owner))) {
                new Notice(MESSAGES.NOTICE_TAKE_OVER_TIMEOUT);
                return false;
            }
            new Notice(MESSAGES.NOTICE_TAKE_OVER_SUCCESS(ownerName));
        }
        return true;
    }
 
    private async confirmTakeOver(ownerName: string): Promise<boolean> {
        const modal = new ConfirmModal(this.app, MESSAGES.CONFIRM_TAKE_OVER(ownerName));
        modal.open();
        return modal.result;
    }
 
    private lookupVaultName(vaultId: string): string {
        return this.vaultRegistry?.get(vaultId)?.displayName ?? "another vault";
    }
 
    private async terminateOwningProcess(owner: ActiveLock | null): Promise<boolean> {
        if (!owner) return true;
        // Stop the other vault's server too, or it orphans when its Obsidian goes.
        if (owner.serverPid) await killServerTree(owner.serverPid);
        try {
            node.processKill(owner.pid);
        } catch {
            // already gone — fine
        }
        for (let i = 0; i < 50; i++) {
            try {
                node.processKill(owner.pid, 0);
            } catch {
                return true;
            }
            await new Promise((r) => window.setTimeout(r, 100));
        }
        return false;
    }
 
    /** Aborts the in-flight server download, if any. Set while a download runs. */
    private downloadController: AbortController | null = null;
 
    private startDownloadController(): AbortController {
        this.downloadController = new AbortController();
        return this.downloadController;
    }
 
    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(onProgress?: ManagedServerProgressHandler): Promise<string | null> {
        const bm = this.binaryManager;
        if (!bm) return null;
        const needsDownload = !bm.binaryExists();
        if (needsDownload) {
            this.updateStatusBar(MESSAGES.STATUS_DOWNLOADING, DOT_STATE.PRIMARY);
            this.setStatusClass("lilbee-status-downloading");
            onProgress?.({ phase: MANAGED_PHASE.DOWNLOADING, message: MESSAGES.STATUS_DOWNLOADING });
        }
        try {
            const path = await bm.ensureBinary(
                this.settings.includeDevBuilds,
                (rawMsg, url, progress) => {
                    const percent = progress ? percentOfBytes(progress.receivedBytes, progress.totalBytes) : undefined;
                    const msg = progress ? downloadMessage(progress) : rawMsg;
                    this.updateStatusBar(progress ? downloadStatusBar(progress) : `lilbee: ${msg}`, DOT_STATE.PRIMARY);
                    onProgress?.({ phase: MANAGED_PHASE.DOWNLOADING, message: msg, url, percent });
                },
                () => this.showGatekeeperHelp(),
                this.startDownloadController().signal,
            );
            this.finishDownload();
            this.setStatusClass(null);
            return path;
        } catch (err) {
            this.finishDownload();
            this.setStatusClass(null);
            // Cancelling is a choice, not a failure: say so plainly and skip the error journal.
            if (err instanceof DownloadCanceledError) {
                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;
        }
    }
 
    /** Tell the user how to allow the unsigned server when macOS Gatekeeper blocks it. */
    private showGatekeeperHelp(): void {
        new GatekeeperModal(this.app).open();
    }
 
    private async recordLilbeeVersionAfterDownload(): Promise<void> {
        if (this.getSharedLilbeeVersion()) return;
        try {
            const release = await getLatestRelease(this.settings.includeDevBuilds);
            this.setSharedLilbeeVersion(release.tag);
            this.setSharedLilbeeVariant(release.variant);
        } catch {
            /* version tracking is best-effort */
        }
    }
 
    /** Persist lock + registry entry once the server is up. */
    private recordReadyState(): void {
        const sm = this.serverManager;
        const registry = this.vaultRegistry;
        if (!sm || !registry) return;
        const port = parseInt(sm.serverUrl.split(":").pop() || "0", 10);
        const now = Date.now();
        registry.writeLock({
            vaultId: this.vaultId,
            pid: process.pid,
            serverPid: sm.serverPid ?? undefined,
            port,
            startedAt: 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,
        });
    }
 
    /**
     * Tell the managed server to store content under the vault.
     *
     * PATCHes ``documents_dir`` to ``<vault>/lilbee`` and ``vault_base`` to the
     * vault root. Server performs a locked relocation if paths changed, then
     * stamps ``vault_path`` on every Source response so chat-chip clicks can
     * deep-link into the local editor. No-op when the toggle is off, the
     * server is external, or the current values already match.
     */
    async configureManagedStorage(): Promise<void> {
        if (this.settings.serverMode !== SERVER_MODE.MANAGED) return;
        if (!this.settings.storeContentInVault) return;
 
        const vaultBase = this.getVaultBasePath();
        const desiredDocsDir = `${vaultBase}/lilbee`;
 
        let current: Record<string, unknown>;
        try {
            current = await this.api.config();
        } catch (err) {
            console.error("[lilbee] could not read server config for vault setup", err);
            return;
        }
 
        const currentDocs = typeof current.documents_dir === "string" ? current.documents_dir : "";
        const currentVault = typeof current.vault_base === "string" ? current.vault_base : null;
        if (currentDocs === desiredDocsDir && currentVault === vaultBase) {
            return;
        }
 
        const notice = new Notice(MESSAGES.NOTICE_STORAGE_REORGANIZING, NOTICE_PERMANENT);
        try {
            await this.api.updateConfig({
                documents_dir: desiredDocsDir,
                vault_base: vaultBase,
            });
            notice.hide();
            new Notice(MESSAGES.NOTICE_STORAGE_REORGANIZED);
        } catch (err) {
            notice.hide();
            const detail = errorMessage(err, String(err));
            new Notice(`${MESSAGES.NOTICE_STORAGE_REORGANIZE_FAILED}${detail}`, 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 BinaryManager(sharedBinDir(registry.sharedRoot)).binaryExists();
    }
 
    /** 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 = registry.readLock();
        if (owner !== null && registry.lockState(this.vaultId) === LOCK_STATE.LIVE_OTHER) {
            throw new Error(MESSAGES.ERROR_UNINSTALL_SERVER_IN_USE(this.lookupVaultName(owner.vaultId)));
        }
 
        await this.serverManager?.stop();
        this.serverManager = null;
        this.binaryManager = null;
        // A server orphaned by a crashed Obsidian still writes to the data dir.
        if (owner?.serverPid) await killServerTree(owner.serverPid);
        registry.releaseLock(this.vaultId);
 
        executeUninstall(plan);
 
        registry.saveConfig({
            ...registry.loadConfig(),
            lilbeeVersion: "",
            lilbeeVariant: "",
            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);
    }
 
    async checkForUpdate(): Promise<{ available: boolean; release?: ReleaseInfo }> {
        const release = await getLatestRelease(this.settings.includeDevBuilds);
        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.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;
        const notice = new Notice(MESSAGES.NOTICE_SERVER_AUTO_UPDATING(release.tag), NOTICE_PERMANENT);
        try {
            await this.updateServer(release);
            new Notice(MESSAGES.NOTICE_SERVER_AUTO_UPDATED(release.tag));
        } catch {
            new Notice(MESSAGES.NOTICE_SERVER_AUTO_UPDATE_FAILED, NOTICE_ERROR_DURATION_MS);
        } finally {
            notice.hide();
        }
    }
 
    async updateServer(release: ReleaseInfo, onProgress?: ServerDownloadProgressHandler): Promise<void> {
        const registry = this.vaultRegistry;
        if (!registry) return;
        if (!this.binaryManager) {
            this.binaryManager = new BinaryManager(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?.("Downloading...");
        try {
            await this.binaryManager.download(
                release.assetUrl,
                release.sizeBytes,
                release.digest,
                (msg, _url, progress) => {
                    if (!progress) {
                        onProgress?.(msg);
                        return;
                    }
                    onProgress?.(
                        downloadMessage(progress),
                        percentOfBytes(progress.receivedBytes, progress.totalBytes),
                    );
                },
                () => this.showGatekeeperHelp(),
                this.startDownloadController().signal,
            );
        } finally {
            this.finishDownload();
        }
 
        // Save the new version and the build variant we just installed
        this.setSharedLilbeeVersion(release.tag);
        this.setSharedLilbeeVariant(release.variant);
 
        // 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 exportDiagnostics(this.diagnosticsContext()));
    }
 
    /** Snapshot of plugin + server state for the diagnostics collector. */
    diagnosticsContext(): 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(),
            serverState: this.serverManager?.state ?? SERVER_STATE.STOPPED,
            serverUrl: this.serverManager?.serverUrl ?? this.settings.serverUrl,
            lastOutput: this.serverManager?.lastOutput ?? "",
        };
    }
 
    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:
                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).
     */
    private 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 === "ok") {
            this.setStatusReady();
            return;
        }
        if (outcome === "auth_error") {
            this.updateStatusBar(MESSAGES.STATUS_AUTH_ERROR, DOT_STATE.ERROR);
            this.setStatusClass("lilbee-status-error");
            return;
        }
        if (outcome === "server_error" || 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: "Search knowledge base",
            checkCallback: (checking) => {
                if (!this.isLilbeeReady()) return false;
                if (!checking) new SearchModal(this.app, this).open();
                return true;
            },
        });
 
        this.addCommand({
            id: "chat",
            name: "Open chat",
            checkCallback: (checking) => {
                if (!this.isLilbeeReady()) return false;
                if (!checking) void this.activateChatView();
                return true;
            },
        });
 
        this.addCommand({
            id: "open-memories",
            name: "Open memories",
            checkCallback: (checking) => {
                if (!this.isLilbeeReady()) return false;
                if (!checking) void this.activateMemoriesView();
                return true;
            },
        });
 
        this.addCommand({
            id: "remember",
            name: "Remember…",
            checkCallback: (checking) => {
                if (!this.isLilbeeReady()) return false;
                if (!checking) new RememberModal(this.app, this).open();
                return true;
            },
        });
 
        this.addCommand({
            id: "add-file",
            name: "Add current 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: "Add current 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: "Browse model 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, "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, "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("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("embedding");
                return true;
            },
        });
 
        this.addCommand({
            id: "crawl",
            name: "Crawl web page",
            checkCallback: (checking) => {
                if (!this.isLilbeeReady()) return false;
                if (!checking) new CrawlModal(this.app, this).open();
                return true;
            },
        });
 
        this.addCommand({
            id: "documents",
            name: "Browse documents",
            checkCallback: (checking) => {
                if (!this.isLilbeeReady()) return false;
                if (!checking) new DocumentsModal(this.app, this).open();
                return true;
            },
        });
 
        this.addCommand({
            id: "setup",
            name: "Run setup wizard",
            callback: () => new SetupWizard(this.app, this).open(),
        });
 
        this.addCommand({
            id: "tasks",
            name: "Show task center",
            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-generate",
            name: MESSAGES.COMMAND_WIKI_GENERATE,
            checkCallback: (checking) => {
                if (!this.wikiEnabled) return false;
                const file = this.app.workspace.getActiveFile();
                if (!file) return false;
                if (!checking) void this.runWikiGenerate(file.path);
                return true;
            },
        });
 
        this.addCommand({
            id: "status",
            name: "Show 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 exportDiagnostics(this.diagnosticsContext()),
        });
 
        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,
        });
        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;
        if (this.pendingHintTimeout) {
            window.clearTimeout(this.pendingHintTimeout);
            this.pendingHintTimeout = null;
        }
        // Tear down the status-bar items we own. addStatusBarItem returns
        // DOM nodes that survive plugin unload if the plugin doesn't detach
        // them explicitly, so a disable/enable cycle leaves stale duplicates
        // in the bar that the new plugin instance then sits next to.
        this.statusBarEl?.remove();
        this.statusBarEl = null;
        this.syncPillEl?.remove();
        this.syncPillEl = null;
        this.taskQueue.dispose();
        void this.serverManager?.stop();
        this.vaultRegistry?.releaseLock(this.vaultId);
    }
 
    async loadSettings(): Promise<void> {
        const raw = (await this.loadData()) as (LilbeeSettings & { taskHistory?: { history?: unknown[] } }) | null;
        this.settings = Object.assign({}, DEFAULT_SETTINGS, raw ?? {});
        this.previousServerMode = this.settings.serverMode;
        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;
    }
 
    /** 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 ?? "";
    }
 
    setSharedLilbeeVariant(variant: ServerVariant): void {
        const reg = this.vaultRegistry;
        if (!reg) return;
        reg.saveConfig({ ...reg.loadConfig(), lilbeeVariant: variant });
    }
 
    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;
        this.previousServerMode = this.settings.serverMode;
        await this.persistAll();
 
        if (this.settings.serverMode === SERVER_MODE.MANAGED) {
            if (previousMode !== SERVER_MODE.MANAGED) {
                void this.startManagedServer();
            }
        } else {
            if (previousMode === SERVER_MODE.MANAGED) {
                void this.serverManager?.stop();
                this.serverManager = null;
                this.binaryManager = null;
            }
            this.configureApi(this.settings.serverUrl);
            // External mode owns its own status via the health probe; paint
            // "ready [external]" optimistically so the user doesn't see a
            // stale "stopped" label between the mode switch and the next
            // probe tick. If the external server is in fact unreachable,
            // the probe will flip to error on its next run.
            this.setStatusReady();
            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",
        );
        if (cls) this.statusBarEl.classList.add(cls);
    }
 
    private setStatusReady(): void {
        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 ok = (await this.api.health().catch(() => null))?.isOk() ?? false;
        if (ok) {
            this.healthFailureStreak = 0;
            if (this.serverUnreachable) {
                this.serverUnreachable = false;
                void this.fetchActiveModel();
            }
            return;
        }
        this.healthFailureStreak += 1;
        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;
        if (this.serverUnreachable) return;
        this.serverUnreachable = true;
        this.updateStatusBar(MESSAGES.STATUS_ERROR, DOT_STATE.ERROR);
        this.setStatusClass("lilbee-status-error");
        this.maybeWarnMissingToken();
    }
 
    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}` : "";
 
        if (allActive.length === 1) {
            const text = MESSAGES.STATUS_TASK_RUNNING_SINGLE.replace("{name}", first.name).replace(
                "{pct}",
                String(pct),
            );
            this.updateStatusBar(`lilbee: ${text}${suffix}`, DOT_STATE.PRIMARY);
        } else {
            const text = 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: "chat" | "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 === "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 });
        if (result.isErr()) {
            new Notice(MESSAGES.NOTICE_NO_ACTIVE_MODEL(task));
            return;
        }
        const entry = result.value.models.find((e) => e.hf_repo === repo) ?? result.value.models[0];
        if (!entry) {
            new Notice(MESSAGES.NOTICE_NO_ACTIVE_MODEL(task));
            return;
        }
        new ModelInfoModal(this.app, this, entry).open();
    }
 
    async fetchActiveModel(): Promise<void> {
        try {
            const models = await this.api.listModels();
            this.activeModel = models.chat.active;
            this.setStatusReady();
            await this.applyReasoningDefaultOnce();
        } catch {
            // Silently fail - will retry on next action
        }
 
        // Check wiki feature status
        try {
            const status = await this.api.status();
            if (status.isOk()) {
                this.wikiEnabled = this.settings.wikiEnabled;
                this.wikiPageCount = status.value.wiki?.page_count ?? 0;
                this.wikiDraftCount = status.value.wiki?.draft_count ?? 0;
            }
        } 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 this.api.updateConfig({ [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;
    }
 
    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;
        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));
        await this.runAdd(copiedPaths, paths, () => this.addExternalFiles(paths));
    }
 
    /**
     * Copy each external path into ``<vault>/lilbee/imports/`` and return the
     * new absolute paths for indexing. Paths already under the vault root
     * are returned unchanged. On copy failure the offending file is dropped
     * with a user-visible Notice so the rest of the batch still proceeds.
     *
     * Directory sources are copied recursively with ``node.cpSync`` — the
     * native file picker's "openDirectory" mode returns folder paths, and
     * ``copyFileSync`` on a directory throws EISDIR. Without the stat-first
     * branch every picked folder would fall into the catch and get silently
     * dropped, regressing folder ingestion.
     *
     * All path joins go through ``node.path`` so Windows ``\\`` separators
     * round-trip correctly — a naïve string ``startsWith(vaultBase + "/")``
     * check would miss every file on Windows and mis-copy them into imports.
     */
    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``. Normalises separators so
     * ``C:\\vault\\foo.pdf`` correctly matches a vault base of ``C:\\vault``
     * regardless of which slash flavour either side uses.
     */
    private isUnderVault(source: string, vaultBase: string): boolean {
        const norm = (p: string) => p.replace(/\\/g, "/");
        const prefix = norm(vaultBase).replace(/\/+$/, "");
        return norm(source).startsWith(`${prefix}/`);
    }
 
    /** 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;
        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);
        if (!isRetry && !(await this.confirmReindexIfNeeded(name))) return;
 
        new Notice(MESSAGES.STATUS_ADDING.replace("{label}", name));
        await this.runAdd([absolutePath], [absolutePath], () => this.addToLilbee(file));
    }
 
    cancelSync(): void {
        this.syncController?.abort();
        this.syncController = null;
    }
 
    private async runAdd(
        paths: string[],
        retryKeys: string[] = paths,
        retry?: () => void | Promise<void>,
    ): Promise<void> {
        const taskId = this.taskQueue.enqueue("Adding files", 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: SyncDone | null = null;
            const controller = this.syncController;
            const rawStream = 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 summary = summarizeSyncResult(syncResult);
                new Notice(summary ? MESSAGES.NOTICE_SYNC_SUMMARY(summary) : 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 msg = errorMessage(err, MESSAGES.ERROR_CANNOT_CONNECT);
                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);
    }
 
    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> {
        const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_MEMORIES);
        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_MEMORIES, active: true });
            void this.app.workspace.revealLeaf(leaf);
        }
    }
 
    refreshMemoryViews(): void {
        for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_MEMORIES)) {
            void (leaf.view as MemoriesView).reload();
        }
    }
 
    openPluginSettings(): void {
        // `app.setting` is an undocumented-but-stable Obsidian API used
        // widely by community plugins to jump straight to their own tab.
        const setting = (this.app as unknown as { setting?: { open: () => void; openTabById: (id: string) => void } })
            .setting;
        if (!setting) return;
        setting.open();
        setting.openTabById(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.render();
        }
    }
 
    // 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.
    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);
        }
    }
 
    async activateChatView(): Promise<void> {
        const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT);
        if (existing.length > 0) {
            void this.app.workspace.revealLeaf(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 and memories 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 included = [VIEW_TYPE_CHAT, VIEW_TYPE_TASKS, VIEW_TYPE_WIKI, VIEW_TYPE_MEMORIES].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) 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("lilbee/")) 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 {
            // Page through the documents endpoint so we count every known
            // source, not just the first page. Match on basename: crawled
            // sources keep a relative path (_web/.../index.md) while added
            // files use a basename, so the basename is the common key.
            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);
        }
    }
 
    async runWikiGenerate(source: string): Promise<void> {
        const taskId = this.taskQueue.enqueue(`Generate wiki: ${source}`, TASK_TYPE.WIKI);
        if (taskId === null) {
            new Notice(MESSAGES.NOTICE_QUEUE_FULL);
            return;
        }
        const controller = new AbortController();
        this.taskQueue.registerAbort(taskId, controller);
        try {
            for await (const event of this.api.wikiGenerate(source, controller.signal)) {
                if (event.event === SSE_EVENT.WIKI_GENERATE_DONE) {
                    break;
                } else if (event.event === SSE_EVENT.WIKI_GENERATE_ERROR) {
                    const d = event.data as GenerateErrorData;
                    throw new Error(d.message ?? "generation failed");
                } 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_GENERATE_DONE(source), NOTICE_DURATION_MS);
            this.refreshOpenWikiViews();
            // Sync generated page to vault
            if (this.wikiSync) {
                void this.reconcileWiki();
            }
        } catch (err) {
            const msg = errorMessage(err, MESSAGES.ERROR_UNKNOWN);
            this.taskQueue.fail(taskId, msg);
        }
    }
 
    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;
        }
        const controller = new AbortController();
        this.taskQueue.registerAbort(taskId, controller);
        try {
            let archived = 0;
            for await (const event of this.api.wikiPrune(controller.signal)) {
                if (event.event === SSE_EVENT.WIKI_PRUNE_DONE) {
                    const d = event.data as PruneData;
                    archived = d.archived ?? 0;
                } 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_PRUNE_DONE(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);
        }
    }
 
    async runCrawl(
        url: string,
        depth: number | null,
        maxPages: number | null,
        renderMode?: CrawlRenderMode,
    ): 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;
            const rawStream = this.api.crawl(url, depth, maxPages, controller.signal, renderMode);
            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;
                        const d = event.data as SetupProgressPayload;
                        const pct = d.total_bytes ? (d.downloaded_bytes / d.total_bytes) * 100 : -1;
                        this.taskQueue.update(setupTaskId, pct, formatSetupDetail(d.downloaded_bytes, d.total_bytes));
                        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_DONE: {
                        const d = event.data as { pages_crawled?: number };
                        this.taskQueue.complete(taskId);
                        new Notice(MESSAGES.NOTICE_CRAWL_DONE(d.pages_crawled ?? pageCount));
                        void this.triggerSync();
                        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): Promise<void> {
        if (!this.statusBarEl) return;
        // Re-entry guard: if a sync is already active or queued, this trigger
        // is a no-op. Without it, repeated clicks (sync hint, command palette,
        // crawler-finished auto-trigger) stack up — and cancelling the active
        // task just promotes the next queued sync, making cancel feel broken.
        if (this.taskQueue.hasPending(TASK_TYPE.SYNC)) 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: SyncDone | 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) {
                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();
        }
    }
}