All files / src main.ts

100% Statements 1548/1548
100% Branches 691/691
100% Functions 117/117
100% Lines 1548/1548

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 19441x                                                                                                                                                   1x   1x   1x   10x 10x 10x 3x 3x 7x 7x 7x   12x 12x 12x 12x 12x 12x 12x 12x 12x     22x 22x 22x 20x 20x   114x 114x 114x 114x 114x 114x                                               1x 79x 79x 79x 79x   79x 14x 14x 14x 14x 14x   79x 2x 2x 2x 2x 2x   79x 4x 3x 4x   79x 6x 5x 6x   79x 21x 21x 21x 21x 21x 79x   1x 23x 19x 23x 2x 2x 17x 17x   19x 19x 16x 16x 16x 19x 19x 19x 19x 19x 19x   378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x 378x   378x 378x 378x 378x 378x 378x 378x       378x   378x   378x 329x 329x   329x 329x 329x 329x   329x 329x 329x 329x 329x 329x 1x 329x 329x 329x 1x 329x 329x 329x 329x 329x 329x 329x 329x 329x 329x   329x 329x 1x 1x 1x 1x 1x 329x 329x             329x 323x 53x 323x 270x 270x 270x 270x 323x   329x 6x 6x   329x 329x   329x           329x 1x 1x 1x 1x           329x 329x 329x 329x     378x 331x 993x 993x 993x 331x 331x   378x 64x 62x 62x 61x 61x   61x 61x   60x 60x 60x 60x 54x   54x 54x 54x 54x 61x 64x 48x 48x 48x 48x 61x 64x 6x 6x 6x 64x 61x 61x 64x   378x 54x 54x 54x 54x 54x 54x 54x 54x 3x 3x 3x 3x 54x 1x 1x 54x 54x     378x 68x 68x 68x 68x 68x 6x 6x 6x 6x 4x 4x 4x 4x 4x 6x 1x 1x 1x 1x 1x 63x 68x   378x 1x 1x 1x 1x   378x 5x 5x   378x 4x 3x 3x 4x   1x 4x 52x 52x 52x 2x 2x 50x 50x 50x 4x   378x 65x 65x 64x 65x 11x 11x 11x 11x 64x 64x 64x 9x 9x 9x 6x 6x 9x 2x 2x 2x 64x 65x 65x 65x 65x 8x 8x 8x 8x 8x 8x 65x   378x 54x 51x 51x 51x 54x   34x 54x     378x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x                     378x 55x 51x   49x 49x   49x 49x 49x 55x 1x 1x 1x   55x 55x 55x 45x 45x   3x 3x 3x 3x 3x 3x 2x 2x 55x 1x 1x 1x 1x 1x 55x   378x 2x 2x 1x 1x 1x 2x   378x 4x 4x 3x 2x 2x     3x 1x 1x 1x 1x     3x 4x     3x     3x 1x 1x 1x   3x 4x   378x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   378x               15x 14x 15x 7x 7x 7x 7x 7x 7x 7x 7x 15x 2x 2x 2x 15x 3x 3x 3x 15x 2x 2x 2x 15x 15x   378x 872x 872x 872x                       378x 346x 54x 54x 346x 3x 3x 289x 289x 346x     378x 329x 329x 329x 329x 329x     378x 5x 1x 1x 1x 5x 1x 1x 1x 1x 5x 2x 2x 2x   5x   378x 329x 329x 329x 329x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 3x 3x 3x 2x 3x 329x   329x 329x 329x 329x 3x 3x 3x 1x 1x 3x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 2x 2x 2x 2x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 3x 3x 2x 3x 329x   329x 329x 329x 329x 3x 3x 2x 3x 329x   329x 329x 329x 329x 3x 3x 2x 3x 329x   329x 329x 329x 329x 4x 3x 4x 4x 2x 4x 329x   329x 329x 329x 329x 329x   329x 329x 329x 329x 4x 4x 4x 2x 4x 329x   329x 329x 329x 329x 4x 4x 4x 2x 4x 329x 329x   378x 3x 3x 2x 2x 3x             378x 5x 5x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 5x 3x 3x 5x   378x 2x 1x 1x 1x 2x 2x 2x 2x 2x   378x 4x 1x 1x 1x 4x 4x 4x 4x 4x   378x 377x 377x 377x 377x 377x 377x 377x   378x 54x 54x   378x 20x 20x 19x 20x   378x 4x 4x   378x 3x 3x 2x 3x   378x 54x 54x 54x 54x   378x 509x 509x   378x 504x 504x   378x 5x 5x 5x   5x 1x 1x 1x 5x 4x 3x 3x 3x 3x 4x           4x 4x 4x 5x   378x 909x 909x 909x 909x 909x 500x 500x 500x 896x 909x   378x 959x 948x 948x 948x 948x 948x 948x 948x 949x 959x   378x         396x 1x 1x 1x 1x 395x 396x 396x 396x 396x   378x 330x 329x 329x 329x 330x   378x 22x 21x 20x     19x 22x 22x 3x 3x 1x 1x 1x 3x 3x 16x 16x 8x 7x 7x 7x 7x 22x   378x 1x 1x   378x 3x 3x   378x   378x 7x 6x 5x 5x 5x 1x 4x 7x 7x   378x 506x 506x 506x   506x 220x 220x 124x 124x 124x 96x 96x 96x   506x 1x 1x 1x 1x 1x 1x 1x   285x 506x 506x   506x 262x 262x 262x 262x 262x 506x 23x 23x 23x 23x 23x 285x 506x   378x 508x 507x 507x 507x 507x 507x 508x 285x 285x 285x 222x 508x 219x 508x 55x 508x   378x 124x 69x 69x 69x 5x 5x 5x 5x 64x 69x 69x 69x 69x 124x 45x 45x 45x 45x 45x 45x 45x 10x 124x   378x 6x 6x 6x 6x 1x 1x 1x 6x 6x 6x 1x 1x 1x   4x 4x 6x 1x 1x 1x 6x 6x 1x 1x 1x 2x 6x   378x 331x 331x 8x 8x 331x   323x     331x 331x 331x 5x 5x 5x 5x 331x   325x   331x 2x 2x 2x 331x   378x 5x 5x   378x 7x 6x 6x 7x 1x 1x 7x   1x 7x   378x 58x 2x 2x 58x   378x 47x 47x 47x 47x 9x 9x 9x 9x 47x   38x 38x 47x   378x 31x 29x 31x   31x 31x               27x 27x   25x 25x 31x                                   378x 27x 27x 27x 27x 27x 1x 1x 1x 1x 26x 27x 32x 2x 2x 2x 32x 32x 32x 32x 32x 3x 32x 27x 27x 26x 32x 4x 4x 4x 32x 26x 27x             378x 32x 32x 32x 32x     378x 30x 30x 3x 30x 30x 1001x 1001x 1001x 1x 30x   378x 30x 29x 28x     30x   30x 30x   26x 26x 30x   378x 2x 2x 2x   378x 52x 52x 52x 52x 52x 52x 1x 1x 1x 52x 51x 51x   51x 51x 51x 51x 51x 52x 26x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 26x 1x 1x 1x 1x 1x 1x 1x 1x 1x 23x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 22x 1x 1x 1x 1x 1x 1x 1x 21x 14x 14x 20x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 26x   52x 10x 10x 10x 34x 52x 11x 3x 3x 3x 11x 2x 2x 2x 8x 1x 1x 1x 1x 6x 5x 5x 5x 5x 5x 5x 52x 51x 51x 52x   378x 14x 14x   378x 3x 3x 1x 1x 1x 2x 3x 1x 1x 1x 3x   378x 6x 2x 2x 6x   378x     2x 2x 2x 1x 1x 2x               378x 9x 9x 9x 1x 1x 9x   378x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x   378x 3x 3x 1x 1x 1x 2x 3x 1x 1x 1x 3x               378x 5x 5x 5x   5x 5x 4x 4x 2x 2x 2x             5x 5x 2x 2x 1x 1x 1x 2x   3x 5x 5x   378x 329x 6x     5x 2x 6x 329x 329x 329x 329x 329x 329x   378x 24x 1x 1x 24x 22x       22x 21x 24x 24x   378x       355x 355x 354x 354x 354x 354x 354x     354x 354x 355x 355x 355x 355x 1x 1x 355x   350x 350x 4x 355x   378x 356x 355x 355x 356x 2x 2x 356x 348x 348x 356x   378x 4x 4x 1x 1x 1x 3x 3x 1x 1x 1x 4x 2x 2x 2x 4x   378x 10x 10x 1x 1x 1x 9x 9x 9x 10x 8x 3x 8x 2x 2x 5x 3x 3x 3x 8x 3x 3x 3x   10x 2x 2x 10x 6x 6x 6x 10x   378x 10x 10x 10x 10x   9x 10x 1x 1x 1x 8x 8x 8x 8x 10x 6x 3x 3x 3x 3x 3x 3x 6x 3x 3x 3x   10x 1x 1x 10x 5x 5x 5x 10x   378x 19x 19x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 19x 36x 36x 7x 6x 6x 6x 6x 6x 6x 6x 6x 36x 5x 4x 5x 5x 5x 5x 36x 5x 5x 5x 3x 3x 5x 2x 2x 2x 2x 2x 2x 3x 3x 36x 4x 36x 3x 3x 3x 3x 36x 8x 8x 8x 8x 8x 8x 36x 36x 3x 3x 3x 3x 3x 36x 36x 1x 19x 4x 1x 1x 4x 1x 1x 1x 1x 3x 3x 3x 3x 19x   378x 24x         23x 22x 24x 1x 1x 1x 21x 21x 21x   21x 21x 21x 21x 21x 24x 11x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 1x 1x 1x 1x 1x 1x 1x 7x 2x 2x 6x 3x 3x 3x 3x 3x 3x 11x   24x 2x 2x 2x 12x 24x 5x 1x 1x 5x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 24x 20x 20x 20x 20x 24x   378x 43x 43x 21x 21x 21x 43x 20x 20x 43x 378x  
import { type Menu, type MenuItem, Notice, Plugin, type TAbstractFile } from "obsidian";
import { LilbeeClient, SessionTokenError } from "./api";
import type { RequestOutcome } from "./api";
import { BinaryManager, getLatestRelease, checkForUpdate, node } from "./binary-manager";
import type { ReleaseInfo } from "./binary-manager";
import { ServerManager } from "./server-manager";
import { readSessionToken, resolveExternalDataRoot } from "./session-token";
import { LilbeeSettingTab } from "./settings";
import { VaultRegistry, computeVaultId, resolveSharedRoot, sharedBinDir, sharedModelsDir } from "./vault-registry";
import {
    DEFAULT_SETTINGS,
    DOT_STATE,
    ERROR_NAME,
    LOCK_STATE,
    SERVER_MODE,
    SERVER_STATE,
    SSE_EVENT,
    TASK_STATUS,
    TASK_TYPE,
    type ActiveLock,
    type BatchProgressPayload,
    type DotState,
    type LilbeeSettings,
    type ServerMode,
    type ServerState,
    type SetupDonePayload,
    type SetupProgressPayload,
    type SetupStartPayload,
    type SyncDone,
    type SyncOptions,
    type TaskEntry,
    type VaultAdapter,
    type VaultRegistryEntry,
} 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,
    sessionTokenInvalidMessage,
    STREAM_IDLE_TIMEOUT_MS,
    StreamIdleError,
    withIdleTimeout,
} from "./utils";
import { CatalogModal } from "./views/catalog-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 { LintModal } from "./views/lint-modal";
import { DraftModal } from "./views/draft-modal";
import { ConfirmModal } from "./views/confirm-modal";
import { StatusModal } from "./views/status-modal";
import { VaultPickerModal } from "./views/vault-picker-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"]);
 
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;
}
 
/**
 * Progress phases emitted by {@link LilbeePlugin.startManagedServer} to any
 * observer that passes an ``onProgress`` handler — currently the setup wizard,
 * which wants to show binary-download and server-startup state inline while
 * the user waits on the Server step.
 */
export type ManagedServerProgressPhase = "downloading" | "starting" | "ready" | "error";
export type ManagedServerProgress = {
    phase: ManagedServerProgressPhase;
    message: string;
    url?: string;
};
export type ManagedServerProgressHandler = (event: ManagedServerProgress) => void;
 
/**
 * 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[]) : [],
    };
}
 
export default class LilbeePlugin extends Plugin {
    settings: LilbeeSettings = { ...DEFAULT_SETTINGS };
    api: LilbeeClient = new LilbeeClient("");
    activeModel = "";
    statusBarEl: HTMLElement | null = null;
    syncHintEl: HTMLElement | null = null;
    ribbonIconEl: HTMLElement | null = null;
    chatRibbonIconEl: HTMLElement | null = null;
    binaryManager: BinaryManager | null = null;
    serverManager: ServerManager | null = null;
    vaultRegistry: VaultRegistry | null = null;
    vaultId = "";
    syncController: AbortController | null = null;
    private pendingHintTimeout: ReturnType<typeof setTimeout> | null = null;
    private previousServerMode: ServerMode = SERVER_MODE.MANAGED;
    private startingServer = false;
    private serverStartFailed = 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;
 
    async onload(): Promise<void> {
        await this.loadSettings();
        this.wikiEnabled = this.settings.wikiEnabled;
 
        this.statusBarEl = this.addStatusBarItem();
        this.statusBarEl.style.cursor = "pointer";
        this.statusBarEl.setAttribute("aria-label", MESSAGES.LABEL_STATUSBAR_OPEN_SETTINGS);
        this.statusBarEl.addEventListener("click", () => this.openPluginSettings());
 
        this.syncHintEl = this.addStatusBarItem();
        this.syncHintEl.addClass("lilbee-sync-hint");
        this.syncHintEl.style.display = "none";
        this.syncHintEl.setAttribute("aria-label", MESSAGES.TOOLTIP_PENDING_SYNC_HINT);
        this.syncHintEl.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");
        this.ribbonIconEl = this.addRibbonIcon("list-checks", MESSAGES.LABEL_RIBBON_OPEN_TASK_CENTER, () =>
            this.activateTaskView(),
        );
        this.ribbonIconEl.addClass("lilbee-ribbon-icon");
        this.registerView(VIEW_TYPE_CHAT, (leaf) => new ChatView(leaf, this));
        this.registerView(VIEW_TYPE_TASKS, (leaf) => new TaskCenterView(leaf, this));
        this.registerView(VIEW_TYPE_WIKI, (leaf) => new WikiView(leaf, this));
        this.addSettingTab(new LilbeeSettingTab(this.app, this));
        this.taskQueue.onChange(() => this.updateStatusBarFromQueue());
        this.taskQueue.onChange(() => this.updateRibbonFromQueue());
        this.taskQueue.onChange(() => this.schedulePersistHistory());
        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) {
                void this.startManagedServer();
            } else {
                this.configureApi(this.settings.serverUrl);
                this.setStatusReady();
                this.fetchActiveModel();
            }
        }
 
        if (!this.settings.setupCompleted) {
            new SetupWizard(this.app, this).open();
        }
 
        this.registerPendingSyncHintWatchers();
        void this.updatePendingSyncHint();
 
        this.startHealthProbe();
 
        // Auto-open chat + task center for returning users so the workspace
        // is immediately usable. Defer until the workspace layout is up so
        // sidebar splits land in the right place. New users go through the
        // wizard, which calls openCockpit on completion.
        if (this.settings.setupCompleted && this.settings.autoOpenCockpit) {
            this.app.workspace.onLayoutReady(() => {
                void this.openCockpit();
            });
        }
 
        // Defend against duplicate sidebar leaves persisted in workspace.json
        // from prior sessions. activateChatView() / openCockpit() are
        // 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]) {
            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;
        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();
 
            try {
                this.serverManager = this.buildServerManager(binaryPath, registry, sharedRoot);
                this.updateStatusBar(MESSAGES.STATUS_STARTING, DOT_STATE.PRIMARY);
                this.setStatusClass("lilbee-status-starting");
                onProgress?.({ phase: "starting", message: MESSAGES.STATUS_STARTING_SERVER });
                await this.serverManager.start();
                this.configureApi(this.serverManager.serverUrl);
                this.fetchActiveModel();
                void this.configureManagedStorage();
                this.recordReadyState();
                onProgress?.({ phase: "ready", message: "" });
            } catch (err) {
                this.showError("failed to start server", err);
                onProgress?.({ phase: "error", message: errorMessage(err, String(err)) });
            }
        } finally {
            this.startingServer = false;
        }
    }
 
    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: (stderr: string) => {
                if (this.serverStartFailed) return;
                const detail = stderr ? `\n${stderr.split("\n").slice(-5).join("\n")}` : "";
                new Notice(`${MESSAGES.ERROR_SERVER_CRASHED}${detail}`, NOTICE_PERMANENT);
            },
            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: "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;
        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) => setTimeout(r, 100));
        }
        return false;
    }
 
    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: "downloading", message: MESSAGES.STATUS_DOWNLOADING });
        }
        let downloadNotice: Notice | undefined;
        try {
            const path = await bm.ensureBinary((msg, url) => {
                this.updateStatusBar(`lilbee: ${msg}`, DOT_STATE.PRIMARY);
                onProgress?.({ phase: "downloading", message: msg, url });
                if (!downloadNotice && needsDownload) {
                    const text = url ? `lilbee: ${msg}\n${url}` : `lilbee: ${msg}`;
                    downloadNotice = new Notice(text, NOTICE_PERMANENT);
                } else if (downloadNotice) {
                    const text = url ? `lilbee: ${msg}\n${url}` : `lilbee: ${msg}`;
                    downloadNotice.setMessage(text);
                }
            });
            downloadNotice?.hide();
            this.setStatusClass(null);
            return path;
        } catch (err) {
            downloadNotice?.hide();
            this.setStatusClass(null);
            this.showError("failed to download server", err);
            onProgress?.({ phase: "error", message: errorMessage(err, String(err)) });
            return null;
        }
    }
 
    private async recordLilbeeVersionAfterDownload(): Promise<void> {
        if (this.getSharedLilbeeVersion()) return;
        try {
            const release = await getLatestRelease();
            this.setSharedLilbeeVersion(release.tag);
        } 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, 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);
        }
    }
 
    async checkForUpdate(): Promise<{ available: boolean; release?: ReleaseInfo }> {
        const release = await getLatestRelease();
        if (checkForUpdate(this.getSharedLilbeeVersion(), release.tag)) {
            return { available: true, release };
        }
        return { available: false };
    }
 
    async updateServer(release: ReleaseInfo, onProgress?: (msg: string) => void): 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 (overwrites the old one)
        onProgress?.("Downloading...");
        await this.binaryManager.download(release.assetUrl, onProgress);
 
        // Save the new version
        this.setSharedLilbeeVersion(release.tag);
 
        // Restart if in managed mode
        if (this.settings.serverMode === SERVER_MODE.MANAGED) {
            onProgress?.("Starting server...");
            await this.startManagedServer();
        }
 
        onProgress?.("Update complete.");
    }
 
    private showError(label: string, err: unknown): void {
        console.error(`[lilbee] ${label}:`, err);
        const stderr = this.serverManager?.lastStderr;
        if (stderr) console.error(`[lilbee] server stderr:\n${stderr}`);
        const detail = errorMessage(err, String(err));
        const stderrTail = stderr ? `\n${stderr.split("\n").slice(-5).join("\n")}` : "";
        new Notice(`lilbee: ${label} — ${detail}${stderrTail}`, NOTICE_ERROR_DURATION_MS);
        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.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);
    }
 
    /** Build a fresh API client for *baseUrl* and re-register all hooks. */
    private configureApi(baseUrl: string): void {
        this.api = new LilbeeClient(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") {
            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.
    }
 
    private registerCommands(): void {
        this.addCommand({
            id: "lilbee:search",
            name: "Search knowledge base",
            callback: () => new SearchModal(this.app, this).open(),
        });
 
        this.addCommand({
            id: "lilbee:chat",
            name: "Open chat",
            callback: () => this.activateChatView(),
        });
 
        this.addCommand({
            id: "lilbee:add-file",
            name: "Add current file to lilbee",
            checkCallback: (checking) => {
                const file = this.app.workspace.getActiveFile();
                if (!file) return false;
                if (!checking) void this.addToLilbee(file);
                return true;
            },
        });
 
        this.addCommand({
            id: "lilbee:add-folder",
            name: "Add current folder to lilbee",
            checkCallback: (checking) => {
                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: "lilbee:sync",
            name: MESSAGES.COMMAND_SYNC,
            callback: () => this.triggerSync(),
        });
 
        this.addCommand({
            id: "lilbee:sync-retry-skipped",
            name: MESSAGES.COMMAND_SYNC_RETRY_SKIPPED,
            callback: () => this.triggerSync({ retrySkipped: true }),
        });
 
        this.addCommand({
            id: "lilbee:sync-rebuild",
            name: MESSAGES.COMMAND_SYNC_REBUILD,
            callback: async () => {
                const confirmModal = new ConfirmModal(this.app, MESSAGES.CONFIRM_SYNC_REBUILD);
                confirmModal.open();
                if (await confirmModal.result) void this.triggerSync({ forceRebuild: true });
            },
        });
 
        this.addCommand({
            id: "lilbee:catalog",
            name: "Browse model catalog",
            callback: () => new CatalogModal(this.app, this).open(),
        });
 
        this.addCommand({
            id: "lilbee:model-picker-chat",
            name: MESSAGES.COMMAND_MODEL_PICKER_CHAT,
            callback: () => new ModelPickerModal(this.app, this, "chat").open(),
        });
 
        this.addCommand({
            id: "lilbee:model-picker-embedding",
            name: MESSAGES.COMMAND_MODEL_PICKER_EMBED,
            callback: () => new ModelPickerModal(this.app, this, "embedding").open(),
        });
 
        this.addCommand({
            id: "lilbee:model-info-active-chat",
            name: MESSAGES.COMMAND_MODEL_INFO_CHAT,
            callback: () => this.openModelInfoForActiveTask("chat"),
        });
 
        this.addCommand({
            id: "lilbee:model-info-active-embedding",
            name: MESSAGES.COMMAND_MODEL_INFO_EMBED,
            callback: () => this.openModelInfoForActiveTask("embedding"),
        });
 
        this.addCommand({
            id: "lilbee:crawl",
            name: "Crawl web page",
            callback: () => new CrawlModal(this.app, this).open(),
        });
 
        this.addCommand({
            id: "lilbee:documents",
            name: "Browse documents",
            callback: () => new DocumentsModal(this.app, this).open(),
        });
 
        this.addCommand({
            id: "lilbee:setup",
            name: "Run setup wizard",
            callback: () => new SetupWizard(this.app, this).open(),
        });
 
        this.addCommand({
            id: "lilbee:tasks",
            name: "Show task center",
            callback: () => this.activateTaskView(),
        });
 
        this.addCommand({
            id: "lilbee:wiki",
            name: MESSAGES.COMMAND_WIKI,
            checkCallback: (checking) => {
                if (!this.wikiEnabled) return false;
                if (!checking) void this.activateWikiView();
                return true;
            },
        });
 
        this.addCommand({
            id: "lilbee:wiki-lint",
            name: MESSAGES.COMMAND_WIKI_LINT,
            checkCallback: (checking) => {
                if (!this.wikiEnabled) return false;
                if (!checking) void this.runWikiLint();
                return true;
            },
        });
 
        this.addCommand({
            id: "lilbee: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: "lilbee: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: "lilbee:status",
            name: "Show status",
            callback: () => new StatusModal(this.app, this).open(),
        });
 
        this.addCommand({
            id: "lilbee: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;
            },
        });
 
        this.addCommand({
            id: "lilbee:switch-vault",
            name: MESSAGES.COMMAND_SWITCH_VAULT,
            checkCallback: (checking) => {
                if (this.settings.serverMode !== SERVER_MODE.MANAGED) return false;
                if (!this.vaultRegistry) return false;
                if (!checking) void this.openVaultPicker();
                return true;
            },
        });
    }
 
    private async openVaultPicker(): Promise<void> {
        const registry = this.vaultRegistry;
        if (!registry) return;
        const others = registry.list().filter((e) => e.id !== this.vaultId);
        new VaultPickerModal(this.app, others, (picked) => void this.releaseFor(picked)).open();
    }
 
    /**
     * 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();
        }
    }
 
    private async releaseFor(picked: VaultRegistryEntry): Promise<void> {
        if (this.serverManager) {
            await this.serverManager.stop();
            this.serverManager = null;
        }
        this.vaultRegistry?.releaseLock(this.vaultId);
        new Notice(MESSAGES.NOTICE_RELEASED_FOR_VAULT(picked.displayName));
        this.updateStatusBar(MESSAGES.STATUS_STOPPED, DOT_STATE.MUTED, false);
        this.setStatusClass(null);
    }
 
    onunload(): void {
        if (this.pendingHintTimeout) {
            clearTimeout(this.pendingHintTimeout);
            this.pendingHintTimeout = null;
        }
        this.syncHintEl = 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));
    }
 
    getSharedLilbeeVersion(): string {
        return this.vaultRegistry?.loadConfig().lilbeeVersion ?? "";
    }
 
    setSharedLilbeeVersion(version: string): void {
        const reg = this.vaultRegistry;
        if (!reg) return;
        reg.saveConfig({ ...reg.loadConfig(), lilbeeVersion: version });
    }
 
    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 {
        // 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;
        }
        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 = setInterval(() => void this.probeServerHealth(), HEALTH_PROBE_INTERVAL_MS) as unknown as number;
        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;
        // 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;
        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 updateRibbonFromQueue(): void {
        if (!this.ribbonIconEl) return;
        const el = this.ribbonIconEl;
        el.removeClass("lilbee-ribbon-active", "lilbee-ribbon-success", "lilbee-ribbon-error");
        const allActive = this.taskQueue.activeAll;
        const queued = this.taskQueue.queued;
        const completed = this.taskQueue.completed;
        if (allActive.length > 0 || queued.length > 0) {
            el.addClass("lilbee-ribbon-active");
            return;
        }
        const recent = completed[0];
        if (!recent || recent.completedAt === null) return;
        if (Date.now() - recent.completedAt >= TASK_FLASH_WINDOW_MS) return;
        if (recent.status === TASK_STATUS.DONE) el.addClass("lilbee-ribbon-success");
        else if (recent.status === TASK_STATUS.FAILED) el.addClass("lilbee-ribbon-error");
    }
 
    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] as string) : "";
        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();
        } 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();
        }
    }
 
    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, this.settings.enableOcr, 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) {
            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 });
            this.app.workspace.revealLeaf(leaf);
        }
    }
 
    refreshOpenWikiViews(): void {
        for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_WIKI)) {
            (leaf.view as WikiView).refresh();
        }
    }
 
    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.display();
        }
    }
 
    async activateWikiView(): Promise<void> {
        const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_WIKI);
        if (existing.length > 0) {
            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 });
            this.app.workspace.revealLeaf(leaf);
        }
    }
 
    async activateChatView(): Promise<void> {
        const existing = this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT);
        if (existing.length > 0) {
            this.app.workspace.revealLeaf(existing[0]);
            return;
        }
        const leaf = this.app.workspace.getRightLeaf(false);
        if (leaf) {
            await leaf.setViewState({ type: VIEW_TYPE_CHAT, active: true });
            this.app.workspace.revealLeaf(leaf);
        }
    }
 
    /**
     * Open the chat view and the task center as adjacent leaves in the right
     * sidebar so a fresh-install user lands on a usable workspace without
     * having to discover the ribbon icon and the slash command. Idempotent —
     * if either view is already open, just reveal it; no duplicates.
     */
    async openCockpit(): Promise<void> {
        const workspace = this.app.workspace;
        const existingChat = workspace.getLeavesOfType(VIEW_TYPE_CHAT);
        const existingTasks = workspace.getLeavesOfType(VIEW_TYPE_TASKS);
 
        let chatLeaf = existingChat[0] ?? null;
        if (!chatLeaf) {
            const leaf = workspace.getRightLeaf(false);
            if (!leaf) return;
            chatLeaf = leaf;
            await chatLeaf.setViewState({ type: VIEW_TYPE_CHAT, active: true });
        }
 
        // Task center lives as a bottom panel under the editor — not a right
        // sidebar tab, because the right sidebar collapses sibling leaves into
        // tabs and only one would be visible at a time. getLeaf("split",
        // "horizontal") splits the active root leaf in the main editor area
        // along the horizontal axis (editor on top, task center beneath).
        let tasksLeaf = existingTasks[0] ?? null;
        if (!tasksLeaf) {
            const split = workspace.getLeaf("split", "horizontal");
            if (split) {
                tasksLeaf = split;
                await tasksLeaf.setViewState({ type: VIEW_TYPE_TASKS, active: true });
            }
        }
 
        workspace.revealLeaf(chatLeaf);
        if (tasksLeaf) workspace.revealLeaf(tasksLeaf);
    }
 
    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) {
            clearTimeout(this.pendingHintTimeout);
        }
        this.pendingHintTimeout = setTimeout(() => {
            this.pendingHintTimeout = null;
            // Bail if the plugin was unloaded between scheduling and firing.
            // The syncHintEl guard inside updatePendingSyncHint covers this,
            // but the explicit check here keeps the contract local.
            if (!this.syncHintEl) return;
            void this.updatePendingSyncHint();
        }, PENDING_SYNC_HINT_DEBOUNCE_MS);
    }
 
    private async countPendingSync(): Promise<number> {
        // 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;
        const vaultFiles = files
            .filter((f) => SUPPORTED_SYNC_EXTENSIONS.has(f.extension.toLowerCase()))
            .filter((f) => !this.wikiSync?.isWikiPath(f.path) && !f.path.startsWith("lilbee/"));
        const known = new Set<string>();
        try {
            // Page through the documents endpoint so we count every known
            // source, not just the first page.
            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(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 vaultFiles.filter((f) => !known.has(f.name)).length;
    }
 
    async updatePendingSyncHint(): Promise<void> {
        if (!this.syncHintEl) return;
        const count = await this.countPendingSync();
        if (!this.syncHintEl) return;
        if (count > 0) {
            this.syncHintEl.setText(MESSAGES.STATUS_DOCS_PENDING_SYNC(count));
            this.syncHintEl.style.display = "";
        } else {
            this.syncHintEl.style.display = "none";
        }
    }
 
    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): 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);
            for await (const event of withIdleTimeout(rawStream, STREAM_IDLE_TIMEOUT_MS, () => controller.abort())) {
                switch (event.event) {
                    case SSE_EVENT.SETUP_START: {
                        if (setupTaskId !== null) break;
                        setupTaskId = this.taskQueue.enqueue("Chromium setup", TASK_TYPE.SETUP);
                        this.taskQueue.update(taskId, -1, MESSAGES.STATUS_TASK_CRAWLER_PREPARING);
                        if (setupTaskId !== null) {
                            const d = event.data as SetupStartPayload;
                            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);
        this.markSyncHintRunning(true);
 
        try {
            const progress = new FileProgressTracker();
            let syncResult: SyncDone | null = null;
            const controller = this.syncController;
            const rawStream = this.api.syncStream(this.settings.enableOcr, 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.markSyncHintRunning(false);
            this.schedulePendingSyncHint();
        }
    }
 
    private markSyncHintRunning(running: boolean): void {
        if (!this.syncHintEl) return;
        if (running) {
            this.syncHintEl.setAttribute("data-running", "true");
            this.syncHintEl.setText(MESSAGES.STATUS_SYNC_IN_PROGRESS);
            this.syncHintEl.style.display = "";
        } else {
            this.syncHintEl.removeAttribute("data-running");
        }
    }
}