All files / src settings.ts

100% Statements 1508/1508
100% Branches 451/451
100% Functions 330/330
100% Lines 1402/1402

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273              6x                                                                                                                               6x   6x 6x 6x 6x 6x 6x 6x 6x 6x         6x                       3x 3x                         6x     925x   925x     925x       925x 925x 925x 925x 925x 925x   925x 925x   925x 925x 925x 925x 925x 925x 925x   925x   925x 925x     925x 925x       280x 280x       335x 335x 335x 335x 335x 335x 335x   335x         335x 1x   335x   335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 335x 313x   335x 335x 335x       335x         335x 335x 335x       14x 14x 125x 125x 125x     14x 125x     14x         14x 20x 82x 20x 20x 1x           335x       335x         1x 1x 1x     335x   335x       335x 1x       335x 326x   9x                   364x 364x 364x 364x         365x 364x 364x   365x       368x 368x 367x 367x 367x 336x 336x 336x   87x 31x 31x 31x 31x 19x 19x 19x 19x       367x 367x 367x 1x             31x 31x 31x 93x 93x   31x         31x       31x 31x 56x   31x 31x 2x 2x 2x 2x 2x 2x           19x       19x 19x 1x 1x             19x       19x 1x         19x       19x 19x 19x 17x       17x 17x 1x               12x 12x 10x 10x   2x 12x 12x 1x         2x 2x 1x             19x         19x 19x 19x 19x         4x 4x 4x 4x 4x 4x 4x 1x 1x             652x       326x 13x 13x 13x     313x       313x 313x 313x   313x 326x 326x   326x       326x 309x 309x 1x 1x 1x       313x 4x 4x 1x 1x 1x       313x 4x 4x 2x 2x 2x   1x   2x         313x 313x 313x 313x 313x 313x 313x       313x       313x 3x           313x       313x 3x             1x 1x         604x 604x 2x 2x 2x         1x 1x               323x 323x         323x 323x 323x   323x 323x   323x         323x 166x 38x 38x   38x 38x 37x 37x 37x   38x 38x 38x 38x 38x     323x 323x 323x 323x 7x 7x       323x 323x 323x 323x 12x 9x 8x   20x           8x     8x 1x 1x         323x 323x 323x 14x         14x 14x   309x 309x       309x 309x   323x 323x 55x 145x 31x 31x 31x 31x           335x 38x   297x 297x 281x 281x   16x           313x       313x 3x 3x 3x             335x 335x 335x 335x 335x 335x 335x 335x 335x 335x                 313x 313x 313x   313x 313x 313x 313x   313x       313x 313x         4x 4x 3x 3x 3x 2x 2x 1x   1x 1x   2x             13x 1x       1x 1x 1x   1x   1x     12x   12x         12x 12x   12x 12x         12x 11x     10x     12x 12x 12x 12x 1x 1x       12x 12x 12x 12x 12x 6x 6x 5x       12x 12x 2x 2x 2x   10x 10x 9x 16x 9x 9x 9x 9x                 5x 5x 5x 5x 5x 5x 2x 2x     3x 2x 1x   1x 1x   2x 2x 2x           335x 335x 335x 335x     335x 335x 335x       335x 335x                   8x 8x 8x 8x 8x 8x 5x 5x 5x     3x 2x 1x     1x 1x   2x 2x 2x 2x         326x 326x       326x       5x 5x           313x 313x 6x 6x       6x 1x       6x 2x 1x 1x   1x 1x 1x             313x 313x 6x 6x 6x   6x 6x 6x 6x 6x       335x       335x 1x           9x       9x       1x 1x       9x   9x 9x 1x     9x   9x   9x       9x     1x 1x   9x   9x   9x       9x 1x 1x 1x 1x           335x 335x         335x 335x       335x 1x     335x 335x 1x       335x       335x   335x       335x 5x 4x 4x 3x   1x     335x   335x 335x   335x       335x 5x 4x 4x 3x   1x     335x   335x 335x       335x   335x       335x       1x 1x     335x   335x           335x                 338x           29x 1484x 1484x   38x 1484x 1484x 36x     29x 476x 476x   29x 56x 56x   29x 56x 56x 1x     29x 84x 84x 1x     29x 6x 6x 5x     29x 2x 2x 1x     29x 29x                 9x 9x 9x   9x               29x 1372x 27x               29x 25x 25x   4x 4x 3x   4x 3x 3x 3x         335x     36x       299x         23785x 23785x         274x 5x 5x 5x 3x 3x   2x                     2698x 2698x       30x 30x 30x 30x           335x 335x 335x 335x         335x       335x     1x 1x   335x   335x   335x       335x     1x 1x   335x   335x           335x       335x 335x 335x 335x 2x 2x   1x     335x 335x   335x 335x   335x                                                                                                                                   335x 3015x       3015x     56x 56x 17x 17x 16x   1x   17x   39x 56x 10x 10x 9x   1x     3015x   3015x 3015x 1340x 1340x           335x     335x 335x         335x             335x           335x       335x 5x 4x 4x 3x   1x     335x   335x         335x 335x   335x             335x           335x 335x 335x   335x 335x       335x 335x 335x 335x 335x 335x 2x 2x 1x   1x     335x   335x 335x 335x   335x 335x       335x 3x 2x 2x 1x   1x     335x   335x 335x 335x   335x             335x   335x             335x   335x             335x   335x 335x       335x     3x 3x 3x 2x   1x     335x   335x 335x 335x       335x     335x 335x               335x           335x           335x       2010x 335x 335x 2x 2x 1x   1x     335x   335x 335x     335x             335x 335x             335x 335x             335x 335x             335x             335x   335x             335x   335x             335x   335x             335x   335x             335x       339x 339x 339x     28x             28x                 311x 310x         56x       56x 56x 3x 3x 2x   1x     56x         335x     335x 335x         335x             335x   335x             335x   335x             335x   335x             335x           335x 335x             335x   335x           335x             335x   335x             335x   335x             335x   335x             335x             335x   335x       335x 7x 7x 5x 5x 4x   1x     335x   335x         335x           335x 335x   335x             335x         4020x       4020x 28x 26x 26x 24x   2x     4020x   4020x 4020x 4020x                     670x       670x 5x 4x 4x 2x   2x     670x   670x 670x 670x         335x       335x 3x   7x 7x       3x 3x 2x   1x     335x   335x                   8040x       8040x     108x   8040x   8040x 8040x 8040x                 108x 108x 86x 108x 23x 20x 7x 7x 7x 7x   18x 18x 15x 15x 2x 2x     3x         346x     337x 330x 330x           7x 7x 9x   7x       7x 7x   7x 1x   7x 4x 3x 3x 3x 3x 2x 2x 1x 1x   1x 1x 1x       7x 1x         9x         362x     2x     47x 47x 16x   47x     315x       314x                   47x 47x       47x 55x   47x     55x     47x 12x       47x 1x                 47x 47x 47x     47x 47x 47x 3x   47x               13x 13x 13x         6x 6x   7x 6x         8x 8x 3x 3x   5x       6x 6x 1x 1x   5x 5x 5x 5x 2x 2x       6x 6x 4x 2x 2x 1x 1x       2x 2x   3x       2x 2x 2x 1x         1x 1x 1x       2x 1x 1x 1x   1x 1x 1x       360x     2x     45x 45x 15x   45x     315x 314x                   45x 45x       45x 53x   45x     53x     45x 12x       45x 1x             45x 45x     45x 15x   45x 45x 3x   45x               13x 13x 13x         6x 6x   7x 6x         8x 8x 3x 3x   5x       6x 6x 1x 1x   5x 5x 5x 5x 2x 2x       6x 6x 4x 2x 2x 1x 1x       2x 2x   3x       2x 2x 2x 1x         1x 1x 1x       2x 1x 1x 1x   1x 1x 1x       343x       343x     4x 4x 3x 3x 3x 3x 2x 2x 1x 1x   1x 1x 1x   343x         335x                             335x                                                                                                                                                                                                     335x 3685x 335x       335x 6x 5x 5x 4x   1x     335x   335x 335x     3350x 3350x       3350x     52x 52x 13x 4x 4x 3x   1x   4x   39x 39x 8x 7x 6x 6x 5x   1x     3350x   3350x         335x 335x       335x 335x 335x 335x 2x 2x 1x   1x     335x   335x 335x 335x   335x       335x 2x   6x 6x 2x 2x 1x   1x     335x 335x   335x       335x 335x     335x   335x       335x 335x 2x 2x 2x 2x     335x   335x     335x 335x     335x               335x                 335x       335x           1x 1x     335x     335x       335x 335x 2x 2x 2x 1x 1x   1x       335x     335x       335x 335x 4x 4x 4x 3x       335x       335x           335x             335x   335x       335x 3x 3x     3x     2x   1x     335x   335x     335x       335x 335x 1x         335x       335x 335x 1x           337x       335x 335x 335x         335x       335x 335x 335x 2x 2x 2x 1x       335x 9x     335x   335x       335x           3x 3x 2x   1x     335x   335x   335x                                         335x 335x 335x 1005x       1005x 1005x 1005x 6x 6x 5x 5x 4x 4x   1x     1005x   1005x     335x       335x     3x 3x 3x 3x 2x   1x     335x               335x                           335x 670x       670x     4x 4x 3x 3x 2x   1x     670x   670x     335x       335x       4x 4x 4x 4x 3x   15x 3x 2x 2x 1x 1x   1x             17x 17x 17x 17x 17x 17x       340x 340x 340x 340x 340x 340x 340x 340x 340x       341x     1x     28x         28x 54x   28x                         55x 55x   55x       55x 55x 55x 58x   55x     58x     55x 22x 21x       55x 55x 55x 55x 55x 55x 55x 55x 106x               65x 61x 112x 61x 61x 61x         61x 3x   112x 61x 65x 1x 61x 3x 3x 4x     61x       42x 21x 18x           18x 18x 18x 17x 17x   3x 21x       3x 3x 1x 1x   2x 3x 3x       31x 31x 17x 17x 1x       16x   17x 17x       31x 31x 1x 1x   30x 30x 30x 30x 20x 13x 13x 13x 11x         7x 6x 6x 6x 6x       7x 3x 3x   4x 4x 4x   7x   17x 17x       129x 129x 129x 129x 129x         129x 129x 64x 64x 64x 64x 64x   65x 65x         6x 6x 1x 1x   5x 5x 5x 5x 1x     1x 1x 1x   4x 4x 4x 2x 2x 1x     4x 4x 4x 2x         335x 3x 3x     335x       335x     9x 9x 8x 8x 5x   335x         3x 3x 2x   1x           24x 24x 24x 24x    
import { App, ButtonComponent, DropdownComponent, Notice, PluginSettingTab, setIcon, Setting } from "obsidian";
import type LilbeePlugin from "./main";
import { LilbeeClient } from "./api";
import { isDownloadCanceled, listReleases, isDevBuild } from "./server-binary";
import type { ReleaseInfo } from "./server-binary";
 
/** Community IRC channel for dev-build feedback. */
const LIBERA_LILBEE_URL = "https://web.libera.chat/#lilbee";
import {
    AGENT_CLIENT,
    AGENT_MIN_CONTEXT_TOKENS,
    AGENT_SELECTION,
    CAPABILITY,
    CHAT_MODE,
    CONFIG_KEY,
    CRAWL_RENDER_MODE,
    DEFAULT_SETTINGS,
    ERROR_NAME,
    HOSTED_SOURCES,
    KV_CACHE_TYPE,
    LILBEE_REPO_URL,
    MEMORY_CONFIG_KEY,
    MODEL_TASK,
    SEARCH_CHUNK_TYPE,
    SERVER_MODE,
    SERVER_STATE,
    SSE_EVENT,
    TABLE_MODEL,
    TASK_TYPE,
    VERSION_ACTION,
} from "./types";
import type {
    AgentClient,
    AgentClientDetection,
    AgentSelection,
    CatalogEntry,
    ConfigResponse,
    InstalledModel,
    LilbeeSettings,
    SearchChunkType,
    ServerMode,
} from "./types";
import { exportDiagnostics } from "./diagnostics-export";
import { reportForVault } from "./storage-stats";
import { AGENT_LABELS, AGENT_LINKS, MESSAGES } from "./locales/en";
import { CLAUDIAN_OUTCOME, CLAUDIAN_PLUGIN_ID, isClaudianInstalled } from "./agent-integration";
import { PILL_CLS } from "./components/pill";
import { displayLabelForRef, extractHfRepo, matchModelOption } from "./utils/model-ref";
import { versionActionFor, versionButtonLabel, versionDescription } from "./utils/server-version";
import { CatalogModal } from "./views/catalog-modal";
import { hostedOptions, KEY_STATUS_PILL_CLASS } from "./views/catalog-helpers";
import { ModelPickerModal } from "./views/model-picker-modal";
import { ConfirmModal } from "./views/confirm-modal";
import { ConfirmPullModal } from "./views/confirm-pull-modal";
import { SetupWizard } from "./views/setup-wizard";
import { UninstallModal } from "./views/uninstall-modal";
import {
    debounce,
    DEBOUNCE_MS,
    percentFromSse,
    errorMessage,
    extractSseErrorMessage,
    formatDiskSize,
    noticeForResultError,
    getRelevantSystemMemoryGB,
    noticeServerUnreachableIfApplicable,
    openPluginSettingsById,
    renderExternalLink,
    setDeterminateProgress,
} from "./utils";
 
const CHECK_TIMEOUT_MS = 5000;
/** GitHub's unauthenticated releases API allows 60 requests/hour per IP, so renders share one fetch. */
const RELEASES_CACHE_TTL_MS = 10 * 60 * 1000;
const CLS_MODELS_CONTAINER = "lilbee-models-container";
const RERANKER_DISABLED_KEY = "";
const VISION_DISABLED_KEY = "";
const RERANK_CANDIDATES_MIN = 1;
const RERANK_CANDIDATES_MAX = 100;
const SEPARATOR_KEY = "__separator__";
const SEPARATOR_LABEL = "\u2500\u2500 Other... \u2500\u2500";
const ICON_RESET = "rotate-ccw";
 
// Credential-like fields that must never be clobbered by the global "Reset all" button,
// even if the server endpoint returns a default for them. Resetting a user's API key to the
// empty default would silently break external-provider access with no undo path.
const CREDENTIAL_FIELDS = new Set([
    "openai_api_key",
    "anthropic_api_key",
    "gemini_api_key",
    "hf_token",
    "manual_session_token",
]);
 
export { SEPARATOR_KEY, SEPARATOR_LABEL };
 
/** Paint the phase line, and grow the bar once a real percentage arrives. */
function showPhase(progress: UpdateProgressEls, message: string, percent?: number): void {
    progress.phase.setText(message);
    if (percent !== undefined) setDeterminateProgress(progress.fill, percent);
}
 
/** Elements of the managed-server update progress panel. */
interface UpdateProgressEls {
    panel: HTMLElement;
    phase: HTMLElement;
    size: HTMLElement;
    fill: HTMLElement;
    cancel: HTMLElement;
}
 
/** Marks the setting a navigation landed on; the theme colours the flash. */
const SETTING_FOCUS_CLASS = "lilbee-setting-focus";
 
export class LilbeeSettingTab extends PluginSettingTab {
    private versionSettingEl: HTMLElement | null = null;
    /** Set by the update ribbon icon and the reminder: keep the version row in view across re-renders. */
    private focusServerUpdate = false;
    plugin: LilbeePlugin;
    /** Total bytes of the shared install, set by the storage report each render. */
    private storageTotalBytes = 0;
    // Textareas live here too: the prompt fields are multi-line but are filled
    // from a plain string like every other input, and both element types carry
    // the value and placeholder this map is read for.
    private serverConfigInputs: Map<string, HTMLInputElement | HTMLTextAreaElement> = new Map();
    private serverConfigToggles: Map<string, { setValue: (v: boolean) => unknown }> = new Map();
    private memoryToggles: Map<string, { setValue: (v: boolean) => unknown }> = new Map();
    private serverConfigTextAreas: Map<string, HTMLTextAreaElement> = new Map();
    private serverConfigDropdowns: Map<string, { setValue: (v: string) => unknown }> = new Map();
    private serverConfigSliders: Map<string, { setValue: (v: number) => unknown }> = new Map();
    // Rows hidden until loadServerDefaults sees a defined value for the matching cfg key.
    private serverConfigHideableEls: Map<string, HTMLElement> = new Map();
    private configDefaults: Record<string, unknown> = {};
    // Guards programmatic toggle.setValue() and slider.setValue() calls from echoing back to the server.
    private suppressChangeEvents = false;
    private chatModeSettingEl: HTMLElement | null = null;
    private chatModeDropdown: { setValue: (v: string) => unknown } | null = null;
    private chatModeSelectEl: HTMLSelectElement | null = null;
    private apiKeysContainerEl: HTMLElement | null = null;
    private crawlingContainerEl: HTMLElement | null = null;
    private wikiContainerEl: HTMLElement | null = null;
    /** Last successful release-list fetch; failures are not cached, so a retry always refetches. */
    private releasesCache: { at: number; releases: ReleaseInfo[] } | null = null;
    /** Detected agent CLIs; null until the first probe lands or after it fails. */
    private agentDetections: AgentClientDetection[] | null = null;
    private agentBodyEl: HTMLElement | null = null;
 
    constructor(app: App, plugin: LilbeePlugin) {
        super(app, plugin);
        this.plugin = plugin;
    }
 
    display(): void {
        this.render();
        this.revealServerUpdate();
    }
 
    render(): void {
        const { containerEl } = this;
        containerEl.empty();
        this.serverConfigInputs.clear();
        this.serverConfigToggles.clear();
        this.serverConfigTextAreas.clear();
        this.serverConfigDropdowns.clear();
        this.serverConfigHideableEls.clear();
 
        const filterInput = containerEl.createEl("input", {
            cls: "lilbee-settings-filter",
            placeholder: MESSAGES.PLACEHOLDER_FILTER_SETTINGS,
            attr: { type: "text" },
        });
        filterInput.addEventListener("input", () => {
            this.filterSettings(containerEl, filterInput.value);
        });
        this.renderBugFeedback(containerEl);
 
        this.renderConnectionSettings(containerEl);
        this.renderModelsSection(containerEl);
        this.renderChatSettings(containerEl);
        this.renderSearchRetrievalSettings(containerEl);
        this.renderGenerationSettings(containerEl);
        this.renderMemorySection(containerEl);
        this.renderRetrievalAdvanced(containerEl);
        this.renderIngestSettings(containerEl);
        this.renderWorkerPoolSettings(containerEl);
        this.crawlingContainerEl = containerEl.createDiv();
        this.renderCrawlingSettings(this.crawlingContainerEl);
        this.wikiContainerEl = containerEl.createDiv();
        this.renderWikiSettings(this.wikiContainerEl);
        this.renderAgentIntegration(containerEl);
        this.renderDiagnostics(containerEl);
        this.renderAdvancedSettings(containerEl);
        this.renderFleetSettings(containerEl);
        if (this.plugin.settings.serverMode === SERVER_MODE.MANAGED && this.hasManagedServer()) {
            this.renderUninstallSection(containerEl, this.storageTotalBytes);
        }
        this.loadServerDefaults();
        this.loadConfigDefaults();
        void this.applyCapabilityGating();
    }
 
    private async applyCapabilityGating(): Promise<void> {
        const [apiKeys, crawling, wiki] = await Promise.all([
            this.plugin.api.getCapability(CAPABILITY.API_KEYS),
            this.plugin.api.getCapability(CAPABILITY.CRAWLING),
            this.plugin.api.getCapability(CAPABILITY.WIKI),
        ]);
        if (!apiKeys && this.apiKeysContainerEl) this.apiKeysContainerEl.hide();
        if (!crawling && this.crawlingContainerEl) this.crawlingContainerEl.hide();
        if (!wiki && this.wikiContainerEl) this.wikiContainerEl.hide();
    }
 
    private filterSettings(containerEl: HTMLElement, query: string): void {
        const term = query.trim().toLowerCase();
        const matches = (item: Element): boolean => {
            const name = item.querySelector(".setting-item-name")?.textContent?.toLowerCase() ?? "";
            const desc = item.querySelector(".setting-item-description")?.textContent?.toLowerCase() ?? "";
            return !term || name.includes(term) || desc.includes(term);
        };
 
        for (const item of Array.from(containerEl.querySelectorAll(".setting-item"))) {
            (item as HTMLElement).style.display = matches(item) ? "" : "none";
        }
 
        const wrappers = containerEl.querySelectorAll(
            ".lilbee-settings-section, .lilbee-models-container, .lilbee-chat-container, " +
                ".lilbee-embedding-container, .lilbee-vision-container, .lilbee-reranker-container, " +
                ".lilbee-model-section",
        );
        for (const wrapper of Array.from(wrappers)) {
            const items = Array.from(wrapper.querySelectorAll(".setting-item"));
            const anyVisible = items.some((i) => (i as HTMLElement).style.display !== "none");
            (wrapper as HTMLElement).style.display = anyVisible || !term ? "" : "none";
            if (term && anyVisible && wrapper.tagName === "DETAILS") {
                wrapper.setAttribute("open", "");
            }
        }
    }
 
    private renderConnectionSettings(containerEl: HTMLElement): void {
        const modeSetting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_SERVER_MODE)
            .setDesc(MESSAGES.DESC_SERVER_MODE)
            .addDropdown((dropdown) =>
                dropdown
                    .addOption(SERVER_MODE.MANAGED, MESSAGES.DESC_MANAGED_BUILTIN)
                    .addOption(SERVER_MODE.EXTERNAL, MESSAGES.DESC_EXTERNAL_MANUAL)
                    .setValue(this.plugin.settings.serverMode)
                    .onChange(async (value) => {
                        this.plugin.settings.serverMode = value as ServerMode;
                        await this.plugin.saveSettings();
                        this.render();
                    }),
            );
        this.appendLocalResetAffordance(modeSetting, "serverMode", MESSAGES.LABEL_SERVER_MODE);
 
        new Setting(containerEl)
            .setName(MESSAGES.LABEL_SETUP_WIZARD)
            .setDesc(MESSAGES.DESC_SETUP_WIZARD)
            .addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_RUN_SETUP_WIZARD).onClick(() => {
                    new SetupWizard(this.app, this.plugin).open();
                }),
            );
 
        if (this.plugin.settings.serverMode === SERVER_MODE.MANAGED) {
            this.renderManagedSettings(containerEl);
        } else {
            this.renderExternalSettings(containerEl);
        }
    }
 
    /**
     * A binary on disk that the plugin is still allowed to run. An uninstalled
     * server never starts, even if a binary was put back by hand, until an
     * explicit install clears the flag.
     */
    private renderAgentIntegration(containerEl: HTMLElement): void {
        const section = containerEl.createDiv({ cls: "lilbee-settings-section lilbee-agent-section" });
        new Setting(section).setName(MESSAGES.LABEL_AGENT_SECTION).setHeading().setDesc(MESSAGES.DESC_AGENT_SECTION);
        this.agentBodyEl = section.createDiv({ cls: "lilbee-agent-body" });
        void this.loadAgentDetections();
    }
 
    /** Probe for agent CLIs, reusing the last result unless the user asked to rescan. */
    private async loadAgentDetections(force = false): Promise<void> {
        if (this.agentDetections === null || force) {
            const index = await this.plugin.api.getAgentConfigIndex();
            this.agentDetections = index.isOk() ? index.value.clients : null;
        }
        this.renderAgentBody();
    }
 
    private renderAgentBody(): void {
        const body = this.agentBodyEl;
        if (!body) return;
        body.empty();
        const detections = this.agentDetections;
        if (detections === null) {
            body.createEl("p", { cls: "setting-item-description", text: MESSAGES.AGENT_DETECT_UNAVAILABLE });
            this.addRescanButton(body);
            return;
        }
        const installed = detections.filter((d) => d.cli_detected).map((d) => d.client);
        this.renderAgentChoice(body, installed);
        this.renderSupportedAgents(body);
        const selected = this.plugin.settings.agentIntegration.agent;
        if (selected === AGENT_SELECTION.NONE) return;
        this.renderAgentKeepFresh(body);
        this.renderAgentModelRow(body);
        if (selected === AGENT_CLIENT.OPENCODE) this.renderClaudianRow(body);
        this.renderAgentStatus(body, selected);
    }
 
    private addRescanButton(parent: HTMLElement, setting?: Setting): void {
        const target = setting ?? new Setting(parent).setName(MESSAGES.LABEL_AGENT_SUPPORTED);
        target.addButton((btn) =>
            btn.setButtonText(MESSAGES.BUTTON_AGENT_RESCAN).onClick(() => {
                void this.loadAgentDetections(true);
            }),
        );
    }
 
    /** A plain links row: the projects a user installs to get a coding agent. */
    private renderSupportedAgents(body: HTMLElement): void {
        const setting = new Setting(body).setName(MESSAGES.LABEL_AGENT_SUPPORTED);
        const links = setting.descEl.createSpan({ cls: "lilbee-agent-links" });
        AGENT_LINKS.forEach((link, i) => {
            if (i > 0) links.appendText(" · ");
            renderExternalLink(links, link.label, link.url);
        });
        this.addRescanButton(body, setting);
    }
 
    /** The dropdown lists only installed agents, so what shows is what you can pick. */
    private renderAgentChoice(body: HTMLElement, installed: AgentClient[]): void {
        new Setting(body)
            .setName(MESSAGES.LABEL_AGENT_CHOICE)
            .setDesc(MESSAGES.DESC_AGENT_CHOICE)
            .addDropdown((dropdown) => {
                dropdown.addOption(AGENT_SELECTION.NONE, MESSAGES.AGENT_OPTION_NONE);
                for (const client of installed) {
                    dropdown.addOption(client, AGENT_LABELS[client]);
                }
                dropdown.setValue(this.plugin.settings.agentIntegration.agent);
                dropdown.onChange(async (value) => {
                    const agent = value as AgentSelection;
                    this.plugin.settings.agentIntegration.agent = agent;
                    this.plugin.settings.agentIntegration.pickerShown = true;
                    await this.plugin.persistAgentIntegration();
                    if (agent !== AGENT_SELECTION.NONE) await this.plugin.applyAgentWiring(agent);
                    this.renderAgentBody();
                });
            });
    }
 
    private renderAgentKeepFresh(body: HTMLElement): void {
        new Setting(body)
            .setName(MESSAGES.LABEL_AGENT_KEEP_FRESH)
            .setDesc(MESSAGES.DESC_AGENT_KEEP_FRESH)
            .addToggle((toggle) => {
                toggle.setValue(this.plugin.settings.agentIntegration.keepConfigFresh);
                toggle.onChange(async (value) => {
                    this.plugin.settings.agentIntegration.keepConfigFresh = value;
                    await this.plugin.persistAgentIntegration();
                });
            });
    }
 
    /** The agent runs on lilbee's chat model, so this row drives the same selection. */
    private renderAgentModelRow(body: HTMLElement): void {
        const setting = new Setting(body)
            .setName(MESSAGES.LABEL_AGENT_MODEL)
            .setDesc(displayLabelForRef(this.plugin.activeModel) || MESSAGES.LABEL_NOT_SET)
            .addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_AGENT_CHANGE_MODEL).onClick(() => {
                    new ModelPickerModal(this.app, this.plugin, MODEL_TASK.CHAT).open();
                }),
            );
        // The context pill sits in the control slot, left of the button; the
        // low-context warning, if any, gets its own note row below.
        void this.renderAgentContext(setting, body);
    }
 
    private async renderAgentContext(setting: Setting, body: HTMLElement): Promise<void> {
        const health = await this.plugin.api.health();
        const ctx = health.isOk() ? health.value.chat_ctx : null;
        if (typeof ctx !== "number") return;
        const pill = createSpan({
            cls: `lilbee-key-status-pill ${PILL_CLS.CONTEXT}`,
            text: MESSAGES.AGENT_CONTEXT_BADGE(ctx),
        });
        setting.controlEl.prepend(pill);
        if (ctx < AGENT_MIN_CONTEXT_TOKENS) {
            body.createDiv({
                cls: "lilbee-agent-note setting-item-description is-warning",
                text: MESSAGES.AGENT_CONTEXT_WARNING,
            });
        }
    }
 
    private renderClaudianRow(body: HTMLElement): void {
        const setting = new Setting(body).setName(MESSAGES.LABEL_AGENT_CLAUDIAN);
        if (!isClaudianInstalled(this.app)) {
            setting.setDesc(MESSAGES.DESC_AGENT_CLAUDIAN_MISSING);
            return;
        }
        const skipped = this.plugin.lastAgentWrite?.claudian === CLAUDIAN_OUTCOME.SKIPPED;
        setting.setDesc(skipped ? MESSAGES.DESC_AGENT_CLAUDIAN_SKIPPED : MESSAGES.DESC_AGENT_CLAUDIAN_CONFIGURED);
        if (!skipped) {
            setting.controlEl.createSpan({
                cls: `lilbee-key-status-pill ${KEY_STATUS_PILL_CLASS.READY}`,
                text: MESSAGES.PILL_AGENT_CLAUDIAN_CONFIGURED,
            });
        }
        setting.addButton((btn) =>
            btn.setButtonText(MESSAGES.BUTTON_OPEN_CLAUDIAN).onClick(() => {
                openPluginSettingsById(this.app, CLAUDIAN_PLUGIN_ID);
            }),
        );
    }
 
    private renderAgentStatus(body: HTMLElement, agent: AgentClient): void {
        const text =
            agent === AGENT_CLIENT.HERMES
                ? MESSAGES.AGENT_STATUS_GLOBAL
                : this.plugin.lastAgentWrite === null
                  ? MESSAGES.AGENT_STATUS_PENDING
                  : MESSAGES.AGENT_STATUS_CONNECTED;
        const status = body.createDiv({ cls: "lilbee-agent-status setting-item-description" });
        status.createSpan({ cls: "lilbee-agent-status-dot" });
        status.createSpan({ text });
        if (agent === AGENT_CLIENT.HERMES) this.renderHermesConfigBlock(body);
    }
 
    /** hermes keeps one global config, so lilbee offers the block rather than writing it. */
    private renderHermesConfigBlock(body: HTMLElement): void {
        const setting = new Setting(body).setName(MESSAGES.LABEL_AGENT_COPY_CONFIG);
        const block = body.createEl("pre", { cls: "lilbee-agent-config-block" });
        void this.plugin.api.getAgentConfig(AGENT_CLIENT.HERMES).then((result) => {
            const content = result.isOk() ? (result.value.content ?? "") : "";
            block.setText(content);
            setting.addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_AGENT_COPY).onClick(() => {
                    void navigator.clipboard.writeText(content);
                    new Notice(MESSAGES.NOTICE_AGENT_COPIED);
                }),
            );
        });
    }
 
    private hasManagedServer(): boolean {
        return this.plugin.isServerInstalled() && !this.plugin.isServerUninstalled();
    }
 
    private renderManagedSettings(containerEl: HTMLElement): void {
        if (!this.hasManagedServer()) {
            this.renderInstallServer(containerEl);
            this.renderSharedRootSetting(containerEl);
            return;
        }
 
        const statusSetting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_SERVER_STATUS)
            .setDesc(MESSAGES.DESC_SERVER_STATUS_CURRENT);
 
        const statusEl = statusSetting.settingEl.createDiv({ cls: "lilbee-server-status" });
        const dot = statusEl.createDiv({ cls: "lilbee-server-dot" });
        const stateText = statusEl.createSpan();
 
        const serverState = this.plugin.serverManager?.state ?? SERVER_STATE.STOPPED;
        stateText.setText(serverState);
        dot.classList.add(`is-${serverState}`);
 
        const controlSetting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_SERVER_CONTROLS)
            .setDesc(MESSAGES.DESC_SERVER_CONTROLS_START_STOP);
 
        if (serverState === SERVER_STATE.STOPPED || serverState === SERVER_STATE.ERROR) {
            controlSetting.addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_START).onClick(async () => {
                    this.plugin.journal.lifecycle("start requested from the settings tab");
                    await this.plugin.startManagedServer();
                    this.render();
                }),
            );
        }
        if (serverState === SERVER_STATE.READY || serverState === SERVER_STATE.STARTING) {
            controlSetting.addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_STOP).onClick(async () => {
                    this.plugin.journal.lifecycle("stop requested from the settings tab");
                    await this.plugin.serverManager?.stop();
                    this.render();
                }),
            );
        }
        if (serverState === SERVER_STATE.READY) {
            controlSetting.addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_RESTART).onClick(async () => {
                    this.plugin.journal.lifecycle("restart requested from the settings tab");
                    try {
                        await this.plugin.serverManager?.restart();
                    } catch (err) {
                        new Notice(errorMessage(err, MESSAGES.ERROR_START_SERVER));
                    }
                    this.render();
                }),
            );
        }
 
        this.renderSharedRootSetting(containerEl);
        this.renderAdoptDataDir(containerEl);
        this.renderStorageReport(containerEl);
        this.renderVersionSetting(containerEl);
        this.renderAutoUpdateToggle(containerEl);
        this.renderUpdateReminderToggle(containerEl);
        this.renderDevBuildsToggle(containerEl);
    }
 
    private renderAutoUpdateToggle(containerEl: HTMLElement): void {
        new Setting(containerEl)
            .setName(MESSAGES.LABEL_SERVER_AUTO_UPDATE)
            .setDesc(MESSAGES.DESC_SERVER_AUTO_UPDATE)
            .addToggle((toggle) =>
                toggle.setValue(this.plugin.isServerAutoUpdateEnabled()).onChange((value) => {
                    this.plugin.setServerAutoUpdate(value);
                }),
            );
    }
 
    private renderUpdateReminderToggle(containerEl: HTMLElement): void {
        new Setting(containerEl)
            .setName(MESSAGES.LABEL_SERVER_UPDATE_REMINDER)
            .setDesc(MESSAGES.DESC_SERVER_UPDATE_REMINDER)
            .addToggle((toggle) =>
                toggle.setValue(this.plugin.isServerUpdateReminderEnabled()).onChange((value) => {
                    this.plugin.setServerUpdateReminder(value);
                }),
            );
    }
 
    /** Bring the server version row into view and mark it; the update ribbon icon and reminder land here. */
    scrollToServerUpdate(): void {
        this.focusServerUpdate = true;
        this.revealServerUpdate();
    }
 
    /** Runs after a render and after the release list lands, so the row is measured before it scrolls. */
    private revealServerUpdate(): void {
        const row = this.versionSettingEl;
        if (!this.focusServerUpdate || !row) return;
        window.setTimeout(() => {
            row.scrollIntoView({ block: "center" });
            row.addClass(SETTING_FOCUS_CLASS);
        }, 0);
    }
 
    hide(): void {
        this.focusServerUpdate = false;
        this.versionSettingEl?.removeClass(SETTING_FOCUS_CLASS);
    }
 
    /**
     * One control for upgrade, downgrade, and reinstall. The dropdown lists
     * recent releases newest-first; the button names what the selection does.
     */
    private renderVersionSetting(containerEl: HTMLElement): void {
        const installed = this.plugin.getSharedLilbeeVersion();
        const setting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_SERVER_VERSION)
            .setDesc(MESSAGES.DESC_SERVER_VERSION_LOADING);
        // aria-label only: Obsidian renders its styled tooltip from it, and a
        // title attribute would stack the native browser tooltip on top.
        setting.settingEl.setAttribute("aria-label", MESSAGES.TOOLTIP_SERVER_VERSION_SUPPORT);
        this.versionSettingEl = setting.settingEl;
        const progress = this.renderUpdateProgress(containerEl);
 
        let releases: ReleaseInfo[] = [];
        let selectedTag = installed;
        // A dev build newer than the newest stable, shown as a nudge when dev builds are off.
        let newerDevTag: string | null = null;
        // addDropdown / addButton run their callback synchronously, so both are set below.
        let dropdown!: DropdownComponent;
        let actionBtn!: ButtonComponent;
 
        const refresh = (): void => {
            const tags = releases.map((r) => r.tag);
            const action = versionActionFor(tags, installed, selectedTag);
            let desc = versionDescription(action, installed, selectedTag, tags[0] === installed);
            // Which build is installed answers why the download was the size it was.
            const installedBuild = this.plugin.getSharedLilbeeVariant();
            if (installed && installedBuild) {
                desc += MESSAGES.DESC_SERVER_BUILD(MESSAGES.LABEL_SERVER_BUILD(installedBuild));
                const detection = this.plugin.getSharedGpuDetection();
                if (detection) desc += ` ${MESSAGES.DESC_GPU_DETECTION(detection)}`;
            }
            if (newerDevTag) desc += ` ${MESSAGES.DESC_DEV_BUILD_AVAILABLE(newerDevTag)}`;
            setting.setDesc(desc);
            actionBtn.setButtonText(versionButtonLabel(action, selectedTag));
            actionBtn.buttonEl.toggleClass("mod-cta", action === VERSION_ACTION.UPDATE);
            actionBtn.buttonEl.toggleClass("mod-warning", action === VERSION_ACTION.DOWNGRADE);
        };
 
        setting.addDropdown((dd) => {
            dropdown = dd;
            dd.setDisabled(true);
            dd.onChange((value) => {
                selectedTag = value;
                refresh();
            });
        });
 
        setting.addButton((btn) => {
            actionBtn = btn;
            btn.setDisabled(true);
            btn.setButtonText(MESSAGES.BUTTON_REINSTALL).onClick(async () => {
                const release = releases.find((r) => r.tag === selectedTag);
                if (!release) return;
                const label = versionButtonLabel(
                    versionActionFor(
                        releases.map((r) => r.tag),
                        installed,
                        selectedTag,
                    ),
                    selectedTag,
                );
                const updated = await this.runServerUpdate(release, btn, progress, label);
                // An explicit non-latest install turns off automatic updates
                // so the chosen version is honored across plugin updates.
                if (updated && selectedTag !== releases[0].tag) {
                    this.plugin.setServerAutoUpdate(false);
                    this.render();
                }
            });
        });
 
        void this.loadReleases().then((loaded) => {
            this.revealServerUpdate();
            if (loaded.releases === null) {
                setting.setDesc(
                    installed
                        ? MESSAGES.DESC_SERVER_VERSION_OFFLINE(installed, loaded.error)
                        : MESSAGES.DESC_SERVER_VERSION_UNKNOWN,
                );
                setting.addButton((btn) => btn.setButtonText(MESSAGES.BUTTON_RETRY).onClick(() => this.render()));
                return;
            }
            const all = loaded.releases;
            const includeDev = this.plugin.settings.includeDevBuilds;
            // all holds every installable release (dev builds included); when dev builds are
            // off, hide them and nudge toward the newest one if it leads the stable line and the
            // user isn't already running it.
            const newest = all[0];
            newerDevTag =
                !includeDev && newest && isDevBuild(newest.tag) && newest.tag !== installed ? newest.tag : null;
            releases = includeDev ? all : all.filter((r) => !isDevBuild(r.tag));
            if (releases.length === 0) return;
            if (!releases.some((r) => r.tag === selectedTag)) selectedTag = releases[0].tag;
            for (const release of releases) dropdown.addOption(release.tag, release.tag);
            dropdown.setValue(selectedTag);
            dropdown.setDisabled(false);
            actionBtn.setDisabled(false);
            refresh();
        });
    }
 
    /** Recent installable releases, dev builds included, or why GitHub could not be read. */
    private async loadReleases(): Promise<{ releases: ReleaseInfo[] } | { releases: null; error: string }> {
        if (this.releasesCache && Date.now() - this.releasesCache.at < RELEASES_CACHE_TTL_MS) {
            return { releases: this.releasesCache.releases };
        }
        try {
            const releases = await listReleases(true);
            this.releasesCache = { at: Date.now(), releases };
            return { releases };
        } catch (err) {
            return { releases: null, error: errorMessage(err, String(err)) };
        }
    }
 
    /** Opt in to in-development builds. */
    private renderDevBuildsToggle(containerEl: HTMLElement): void {
        new Setting(containerEl)
            .setName(MESSAGES.LABEL_INCLUDE_DEV_BUILDS)
            .setDesc(MESSAGES.DESC_INCLUDE_DEV_BUILDS)
            .addToggle((toggle) =>
                toggle.setValue(this.plugin.settings.includeDevBuilds).onChange(async (value) => {
                    this.plugin.settings.includeDevBuilds = value;
                    await this.plugin.saveSettings();
                    this.render();
                }),
            );
    }
 
    /** Where bug reports go. Rendered at the top of the settings view in both server modes. */
    private renderBugFeedback(containerEl: HTMLElement): void {
        const feedback = containerEl.createDiv({ cls: "lilbee-bug-feedback" });
        feedback.createSpan({ text: MESSAGES.BUG_FEEDBACK_PREFIX });
        const gh = feedback.createEl("a", { text: MESSAGES.BUG_FEEDBACK_GITHUB });
        gh.setAttribute("href", `${LILBEE_REPO_URL}/issues`);
        gh.setAttribute("target", "_blank");
        feedback.createSpan({ text: " or " });
        const irc = feedback.createEl("a", { text: MESSAGES.BUG_FEEDBACK_IRC });
        irc.setAttribute("href", LIBERA_LILBEE_URL);
        irc.setAttribute("target", "_blank");
        feedback.createSpan({ text: MESSAGES.BUG_FEEDBACK_SUFFIX });
    }
 
    /**
     * Managed mode only: Obsidian never removes the server this plugin downloaded.
     * Sized from the storage report so the model cache is walked once per render;
     * the delete plan is built when the button is clicked.
     */
    private renderUninstallSection(containerEl: HTMLElement, totalBytes: number): void {
        const heading = new Setting(containerEl).setName(MESSAGES.LABEL_UNINSTALL).setHeading();
        heading.settingEl.addClass("lilbee-danger-heading");
        heading.settingEl.setAttribute("aria-label", MESSAGES.TOOLTIP_UNINSTALL_SECTION);
 
        const callout = containerEl.createDiv({ cls: "lilbee-uninstall-callout" });
        const mark = callout.createSpan({ cls: "lilbee-uninstall-callout-mark", text: "!" });
        mark.setAttribute("aria-hidden", "true");
        callout.createEl("p", { text: MESSAGES.CALLOUT_UNINSTALL_FIRST });
 
        new Setting(containerEl)
            .setName(MESSAGES.LABEL_UNINSTALL_SERVER)
            .setDesc(MESSAGES.DESC_UNINSTALL_SERVER(formatDiskSize(totalBytes)))
            .addButton((btn) => {
                btn.setButtonText(MESSAGES.BUTTON_UNINSTALL_SERVER).onClick(() => void this.confirmUninstall());
                btn.buttonEl.addClass("mod-warning");
            });
    }
 
    private async confirmUninstall(): Promise<void> {
        const plan = this.plugin.planServerUninstall();
        if (!plan) return;
        const modal = new UninstallModal(this.app, plan);
        modal.open();
        if (!(await modal.result)) return;
        try {
            const freed = await this.plugin.uninstallServer(plan);
            new Notice(MESSAGES.NOTICE_UNINSTALLED(formatDiskSize(freed)));
        } catch (err) {
            new Notice(errorMessage(err, MESSAGES.ERROR_UNINSTALL_FAILED));
            console.error("[lilbee] uninstall failed:", err);
        }
        this.render();
    }
 
    /** Recovery path after an uninstall: pick a release and pull the server back. */
    private renderInstallServer(containerEl: HTMLElement): void {
        // A download kicked off outside Settings (first run, consent modal) is still
        // in flight: offer to stop it rather than a dead Install button.
        if (this.plugin.isDownloadingServer()) {
            new Setting(containerEl)
                .setName(MESSAGES.LABEL_SERVER_STATUS)
                .setDesc(MESSAGES.DESC_SERVER_DOWNLOADING)
                .addButton((btn) => {
                    btn.setButtonText(MESSAGES.BUTTON_CANCEL_DOWNLOAD).onClick(() => {
                        this.plugin.cancelServerDownload();
                        this.render();
                    });
                    btn.buttonEl.addClass("mod-warning");
                });
            return;
        }
 
        new Setting(containerEl).setName(MESSAGES.LABEL_SERVER_STATUS).setDesc(MESSAGES.DESC_SERVER_NOT_INSTALLED);
 
        const setting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_INSTALL_SERVER)
            .setDesc(MESSAGES.DESC_SERVER_VERSION_LOADING);
        // aria-label only: Obsidian renders its styled tooltip from it, and a
        // title attribute would stack the native browser tooltip on top.
        setting.settingEl.setAttribute("aria-label", MESSAGES.TOOLTIP_SERVER_VERSION_SUPPORT);
        const progress = this.renderUpdateProgress(containerEl);
 
        let releases: ReleaseInfo[] = [];
        let selectedTag = "";
        // addDropdown / addButton run their callback synchronously, so both are set below.
        let dropdown!: DropdownComponent;
        let installBtn!: ButtonComponent;
 
        const describe = (): void => {
            const release = releases.find((r) => r.tag === selectedTag);
            /* v8 ignore next -- the dropdown only ever offers tags from `releases` */
            if (!release) return;
            setting.setDesc(MESSAGES.DESC_INSTALL_SERVER(formatDiskSize(release.size)));
        };
 
        setting.addDropdown((dd) => {
            dropdown = dd;
            dd.setDisabled(true);
            dd.onChange((value) => {
                selectedTag = value;
                describe();
            });
        });
 
        setting.addButton((btn) => {
            installBtn = btn;
            btn.setDisabled(true);
            btn.buttonEl.addClass("mod-cta");
            btn.setButtonText(MESSAGES.BUTTON_INSTALL_SERVER).onClick(async () => {
                const release = releases.find((r) => r.tag === selectedTag);
                if (!release) return;
                await this.runServerInstall(release, btn, progress);
            });
        });
 
        void this.loadReleases().then((loaded) => {
            if (loaded.releases === null) {
                setting.setDesc(MESSAGES.ERROR_RELEASE_LIST(loaded.error));
                setting.addButton((btn) => btn.setButtonText(MESSAGES.BUTTON_RETRY).onClick(() => this.render()));
                return;
            }
            releases = loaded.releases;
            if (releases.length === 0) return;
            selectedTag = releases[0].tag;
            for (const release of releases) dropdown.addOption(release.tag, release.tag);
            dropdown.setValue(selectedTag);
            dropdown.setDisabled(false);
            installBtn.setDisabled(false);
            describe();
        });
    }
 
    private async runServerInstall(
        release: ReleaseInfo,
        btn: ButtonComponent,
        progress: UpdateProgressEls,
    ): Promise<void> {
        btn.setDisabled(true);
        btn.setButtonText(MESSAGES.BUTTON_DOWNLOADING);
        progress.panel.show();
        progress.size.setText(MESSAGES.STATUS_UPDATE_SIZE(release.tag, formatDiskSize(release.size)));
        try {
            await this.plugin.installServer(release, (msg, percent) => showPhase(progress, msg, percent));
            new Notice(MESSAGES.NOTICE_INSTALLED(release.tag));
            this.render();
        } catch (err) {
            // Unloading aborted it, and this tab is gone with the plugin.
            if (this.plugin.isUnloaded()) return;
            if (isDownloadCanceled(err)) {
                new Notice(MESSAGES.NOTICE_DOWNLOAD_CANCELED);
            } else {
                new Notice(errorMessage(err, MESSAGES.ERROR_INSTALL_FAILED));
                console.error("[lilbee] install failed:", err);
            }
            progress.panel.hide();
            btn.setButtonText(MESSAGES.BUTTON_INSTALL_SERVER);
            btn.setDisabled(false);
        }
    }
 
    /** Indeterminate progress panel for the managed-server update; hidden until an update runs. */
    private renderUpdateProgress(containerEl: HTMLElement): UpdateProgressEls {
        const panel = containerEl.createDiv({ cls: "lilbee-update-progress" });
        panel.hide();
        const bar = panel.createDiv({ cls: "lilbee-progress-bar-container" });
        const fill = bar.createDiv({
            cls: "lilbee-progress-bar lilbee-wizard-progress-fill lilbee-progress-indeterminate",
        });
        const phase = panel.createDiv({ cls: "lilbee-update-progress-phase" });
        const size = panel.createDiv({ cls: "lilbee-update-progress-size" });
        const cancel = panel.createEl("button", {
            cls: "lilbee-update-progress-cancel",
            text: MESSAGES.BUTTON_CANCEL_DOWNLOAD,
        });
        cancel.addEventListener("click", () => this.plugin.cancelServerDownload());
        return { panel, phase, size, fill, cancel };
    }
 
    /** Download and install *release*, surfacing phase + total download size. Returns false on failure. */
    private async runServerUpdate(
        release: ReleaseInfo,
        actionBtn: ButtonComponent,
        progress: UpdateProgressEls,
        restoreLabel: string,
    ): Promise<boolean> {
        actionBtn.setDisabled(true);
        actionBtn.setButtonText(MESSAGES.BUTTON_DOWNLOADING);
        progress.panel.show();
        progress.size.setText(MESSAGES.STATUS_UPDATE_SIZE(release.tag, formatDiskSize(release.size)));
        try {
            await this.plugin.updateServer(release, (msg, percent) => showPhase(progress, msg, percent));
            new Notice(MESSAGES.NOTICE_UPDATED_TO(release.tag));
            this.render();
            return true;
        } catch (err) {
            // Unloading aborted it, and this tab is gone with the plugin.
            if (this.plugin.isUnloaded()) return false;
            if (isDownloadCanceled(err)) {
                new Notice(MESSAGES.NOTICE_DOWNLOAD_CANCELED);
            } else {
                // errorMessage carries the server's reason, e.g. insufficient disk space.
                new Notice(errorMessage(err, MESSAGES.ERROR_FAILED_UPDATE));
                console.error("[lilbee] update failed:", err);
            }
            progress.panel.hide();
            actionBtn.setButtonText(restoreLabel);
            actionBtn.setDisabled(false);
            return false;
        }
    }
 
    private renderSharedRootSetting(containerEl: HTMLElement): void {
        const resolved = this.plugin.vaultRegistry?.sharedRoot ?? "";
        new Setting(containerEl)
            .setName(MESSAGES.LABEL_SHARED_ROOT)
            .setDesc(MESSAGES.DESC_SHARED_ROOT(resolved))
            .addText((text) =>
                text
                    .setPlaceholder(resolved)
                    .setValue(this.plugin.settings.sharedRoot)
                    .onChange(async (value) => {
                        this.plugin.settings.sharedRoot = value.trim();
                        await this.plugin.saveSettings();
                    }),
            );
    }
 
    private renderAdoptDataDir(containerEl: HTMLElement): void {
        const registry = this.plugin.vaultRegistry;
        if (!registry) return;
        let staged = "";
        new Setting(containerEl)
            .setName(MESSAGES.LABEL_ADOPT_DATA_DIR)
            .setDesc(MESSAGES.DESC_ADOPT_DATA_DIR)
            .addText((text) =>
                text.setPlaceholder(MESSAGES.PLACEHOLDER_ADOPT_DATA_DIR).onChange((value) => {
                    staged = value.trim();
                }),
            )
            .addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_ADOPT_DATA_DIR).onClick(async () => {
                    if (!staged) {
                        new Notice(MESSAGES.NOTICE_ADOPT_DATA_DIR_BLANK);
                        return;
                    }
                    await this.plugin.adoptDataDir(staged);
                    new Notice(MESSAGES.NOTICE_ADOPT_DATA_DIR_DONE(staged));
                    this.render();
                }),
            );
    }
 
    /** Walks the shared install; the total is reused by the uninstall section. */
    private renderStorageReport(containerEl: HTMLElement): void {
        const registry = this.plugin.vaultRegistry;
        if (!registry) return;
        const report = reportForVault(registry.sharedRoot, registry.resolveDataDir(this.plugin.vaultId));
        this.storageTotalBytes = report.totalBytes;
        new Setting(containerEl).setName(MESSAGES.LABEL_STORAGE_REPORT).setDesc(MESSAGES.DESC_STORAGE_REPORT);
 
        const list = containerEl.createDiv({ cls: "lilbee-storage-report" });
        appendStorageRow(list, MESSAGES.LABEL_STORAGE_BIN, report.binBytes);
        appendStorageRow(list, MESSAGES.LABEL_STORAGE_MODELS, report.modelsBytes);
        appendStorageRow(list, MESSAGES.LABEL_STORAGE_VAULT, report.vaultBytes, report.vaultDataDir);
        appendStorageRow(list, MESSAGES.LABEL_STORAGE_TOTAL, report.totalBytes);
    }
 
    private renderDiagnostics(containerEl: HTMLElement): void {
        new Setting(containerEl)
            .setName(MESSAGES.LABEL_EXPORT_DIAGNOSTICS)
            .setDesc(MESSAGES.DESC_EXPORT_DIAGNOSTICS)
            .addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_EXPORT_DIAGNOSTICS).onClick(() => {
                    void exportDiagnostics(this.plugin.diagnosticsContext());
                }),
            );
    }
 
    private renderExternalSettings(containerEl: HTMLElement): void {
        const serverSetting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_SERVER_URL)
            .setDesc(MESSAGES.DESC_SERVER_URL_HELP)
            .addText((text) =>
                text
                    .setPlaceholder(MESSAGES.PLACEHOLDER_HTTP_LOCALHOST)
                    .setValue(this.plugin.settings.serverUrl)
                    .onChange(async (value) => {
                        this.plugin.settings.serverUrl = value;
                        await this.plugin.saveSettings();
                    }),
            );
 
        const serverStatusEl = serverSetting.settingEl.createSpan({ cls: "lilbee-health-status" });
 
        serverSetting.addButton((btn) =>
            btn.setButtonText(MESSAGES.BUTTON_TEST).onClick(async () => {
                await this.checkEndpoint(`${this.plugin.settings.serverUrl}/api/health`, serverStatusEl);
            }),
        );
        this.appendLocalResetAffordance(serverSetting, "serverUrl", MESSAGES.LABEL_SERVER_URL);
 
        void this.checkEndpoint(`${this.plugin.settings.serverUrl}/api/health`, serverStatusEl);
 
        const manualTokenSetting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_MANUAL_TOKEN)
            .setDesc(MESSAGES.DESC_MANUAL_TOKEN)
            .addText((text) => {
                text.setPlaceholder("")
                    .setValue(this.plugin.settings.manualToken)
                    .onChange(async (value) => {
                        this.plugin.settings.manualToken = value.trim();
                        await this.plugin.saveSettings();
                    });
                text.inputEl.type = "password";
            });
        this.appendLocalResetAffordance(manualTokenSetting, "manualToken", MESSAGES.LABEL_MANUAL_TOKEN);
 
        new Setting(containerEl)
            .setName(MESSAGES.LABEL_SWITCH_MANAGED)
            .setDesc(MESSAGES.DESC_SWITCH_MANAGED)
            .addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_RESET_MANAGED).onClick(async () => {
                    this.plugin.settings.serverMode = SERVER_MODE.MANAGED;
                    this.plugin.settings.serverUrl = DEFAULT_SETTINGS.serverUrl;
                    await this.plugin.saveSettings();
                    this.render();
                }),
            );
    }
 
    private renderModelsSection(containerEl: HTMLElement): void {
        new Setting(containerEl).setName(MESSAGES.LABEL_MODELS).setHeading();
        containerEl.createEl("p", {
            text: MESSAGES.DESC_MODELS_HELP,
            cls: "setting-item-description",
        });
 
        const modelsContainer = containerEl.createDiv(CLS_MODELS_CONTAINER);
        const modelSettings = new Setting(containerEl)
            .setName(MESSAGES.LABEL_REFRESH_MODELS)
            .setDesc(MESSAGES.DESC_REFRESH_MODELS)
            .addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_REFRESH).onClick(async () => {
                    await this.loadModels(modelsContainer);
                }),
            );
        modelSettings.addButton((btn) =>
            btn.setButtonText(MESSAGES.BUTTON_BROWSE_CATALOG).onClick(() => {
                new CatalogModal(this.app, this.plugin).open();
            }),
        );
 
        void this.loadModels(modelsContainer);
    }
 
    private renderChatSettings(containerEl: HTMLElement): void {
        new Setting(containerEl).setName(MESSAGES.LABEL_CHAT_SECTION).setHeading();
 
        const showReasoningSetting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_SHOW_REASONING)
            .setDesc(MESSAGES.DESC_SHOW_REASONING)
            .addToggle((toggle) => {
                toggle.onChange(async (value) => {
                    if (this.suppressChangeEvents) return;
                    try {
                        await this.plugin.api.updateConfig({ [CONFIG_KEY.SHOW_REASONING]: value });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_SHOW_REASONING));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_SHOW_REASONING));
                    }
                });
                this.serverConfigToggles.set(CONFIG_KEY.SHOW_REASONING, toggle);
            });
        showReasoningSetting.settingEl.hide();
        this.serverConfigHideableEls.set(CONFIG_KEY.SHOW_REASONING, showReasoningSetting.settingEl);
 
        const compactionSetting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_CHAT_COMPACTION)
            .setDesc(MESSAGES.DESC_CHAT_COMPACTION)
            .addToggle((toggle) => {
                toggle.onChange(async (value) => {
                    if (this.suppressChangeEvents) return;
                    try {
                        await this.plugin.api.updateConfig({ [CONFIG_KEY.CHAT_COMPACTION]: value });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_CHAT_COMPACTION));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_CHAT_COMPACTION));
                    }
                });
                this.serverConfigToggles.set(CONFIG_KEY.CHAT_COMPACTION, toggle);
            });
        compactionSetting.settingEl.hide();
        this.serverConfigHideableEls.set(CONFIG_KEY.CHAT_COMPACTION, compactionSetting.settingEl);
    }
 
    private renderSearchRetrievalSettings(containerEl: HTMLElement): void {
        new Setting(containerEl).setName(MESSAGES.LABEL_SEARCH_RETRIEVAL).setHeading();
 
        const topKSetting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_RESULTS_COUNT)
            .setDesc(MESSAGES.DESC_RESULTS_COUNT)
            .addSlider((slider) =>
                slider
                    .setLimits(1, 20, 1)
                    .setValue(this.plugin.settings.topK)
                    .onChange(async (value) => {
                        this.plugin.settings.topK = value;
                        await this.plugin.saveSettings();
                    }),
            );
        this.appendLocalResetAffordance(topKSetting, "topK", MESSAGES.LABEL_RESULTS_COUNT);
 
        this.renderConfigSlider(containerEl, "max_distance", MESSAGES.LABEL_MAX_DISTANCE, MESSAGES.DESC_MAX_DISTANCE, {
            min: 0.05,
            max: 1.0,
            step: 0.05,
        });
 
        this.renderConfigToggle(
            containerEl,
            "adaptive_threshold",
            MESSAGES.LABEL_ADAPTIVE_THRESHOLD,
            MESSAGES.DESC_ADAPTIVE_THRESHOLD,
        );
    }
 
    private loadServerDefaults(): void {
        this.plugin.api
            .config()
            .then((cfg: ConfigResponse) => {
                // Populate editable server-config inputs with the current server values
                // and surface them as placeholders so users see what's effective when
                // they clear an override.
                for (const [key, inputEl] of this.serverConfigInputs) {
                    const v = cfg[key];
                    if (v === undefined) continue;
                    const formatted =
                        typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : "";
                    inputEl.value = formatted;
                    if (formatted !== "") {
                        inputEl.placeholder = formatted;
                    }
                }
                for (const [key, toggle] of this.serverConfigToggles) {
                    const v = cfg[key];
                    if (typeof v === "boolean") this.setValueSilently(() => toggle.setValue(v));
                }
                for (const [key, slider] of this.serverConfigSliders) {
                    const v = cfg[key];
                    if (typeof v === "number") this.setValueSilently(() => slider.setValue(v));
                }
                for (const [key, textArea] of this.serverConfigTextAreas) {
                    const v = cfg[key];
                    if (Array.isArray(v)) {
                        textArea.value = v.join("\n");
                    }
                }
                for (const [key, dropdown] of this.serverConfigDropdowns) {
                    const v = cfg[key];
                    if (typeof v === "string") {
                        dropdown.setValue(v);
                    }
                }
                if (typeof cfg.rag_system_prompt === "string") {
                    const ragInput = this.serverConfigInputs.get("rag_system_prompt");
                    if (ragInput) {
                        ragInput.placeholder = cfg.rag_system_prompt;
                    }
                }
                if (typeof cfg.general_system_prompt === "string") {
                    const generalInput = this.serverConfigInputs.get("general_system_prompt");
                    if (generalInput) {
                        generalInput.placeholder = cfg.general_system_prompt;
                    }
                }
                this.applyChatModeFromConfig(cfg);
                this.applyHideableConfigFields(cfg);
            })
            .catch(() => {
                // Connection status is shown via the Test button — no duplicate warning needed
            });
    }
 
    /** Runs a programmatic setValue with the control's onChange muted, so nothing echoes to the server. */
    private setValueSilently(apply: () => unknown): void {
        this.suppressChangeEvents = true;
        try {
            apply();
        } finally {
            this.suppressChangeEvents = false;
        }
    }
 
    private applyHideableConfigFields(cfg: ConfigResponse): void {
        // The initial render leaves each row's settingEl with display = "none". When the server
        // reports a value for a key, reveal the row. Older servers omit unknown keys entirely,
        // in which case the row stays hidden via its initial style.
        for (const [key, settingEl] of this.serverConfigHideableEls) {
            if (cfg[key] !== undefined) {
                settingEl.show();
            }
        }
    }
 
    private applyChatModeFromConfig(cfg: ConfigResponse): void {
        /* v8 ignore next 2 */
        if (!this.chatModeSettingEl) return;
        if (cfg.chat_mode === undefined) {
            this.chatModeSettingEl.hide();
            return;
        }
        this.chatModeSettingEl.show();
        if (this.chatModeDropdown) {
            this.chatModeDropdown.setValue(cfg.chat_mode);
        }
        if (this.chatModeSelectEl) {
            const noEmbedding = !cfg.embedding_model || cfg.embedding_model === "";
            this.chatModeSelectEl.disabled = noEmbedding;
            this.chatModeSelectEl.title = noEmbedding ? MESSAGES.TOOLTIP_CHAT_MODE_NEEDS_EMBEDDING : "";
        }
    }
 
    private loadConfigDefaults(): void {
        this.plugin.api
            .configDefaults()
            .then((defaults: Record<string, unknown>) => {
                this.configDefaults = defaults;
            })
            .catch(() => {
                // Older servers without /api/config/defaults — reset affordances simply hide.
                this.configDefaults = {};
            });
    }
 
    private appendResetAffordance(setting: Setting, key: string, label: string): Setting {
        return setting.addExtraButton((btn) =>
            btn
                .setIcon(ICON_RESET)
                .setTooltip(MESSAGES.LABEL_RESET_TO_DEFAULT)
                .onClick(async () => {
                    // Silent no-op until defaults have loaded (old servers or racing first click).
                    if (!(key in this.configDefaults)) return;
                    const def = this.configDefaults[key];
                    try {
                        await this.plugin.api.updateConfig({ [key]: def });
                        new Notice(MESSAGES.NOTICE_FIELD_RESET(label));
                        this.render();
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_RESET(label));
                    }
                }),
        );
    }
 
    private appendLocalResetAffordance<K extends keyof LilbeeSettings>(
        setting: Setting,
        key: K,
        label: string,
    ): Setting {
        return setting.addExtraButton((btn) =>
            btn
                .setIcon(ICON_RESET)
                .setTooltip(MESSAGES.LABEL_RESET_TO_DEFAULT)
                .onClick(async () => {
                    this.plugin.settings[key] = DEFAULT_SETTINGS[key];
                    await this.plugin.saveSettings();
                    new Notice(MESSAGES.NOTICE_FIELD_RESET(label));
                    this.render();
                }),
        );
    }
 
    private renderGenerationSettings(containerEl: HTMLElement): void {
        const details = containerEl.createEl("details", { cls: "lilbee-generation-details lilbee-settings-section" });
        const modelLabel = displayLabelForRef(this.plugin.activeModel) || MESSAGES.LABEL_NO_MODEL_SELECTED;
        details.createEl("summary", { text: `${MESSAGES.LABEL_GENERATION} (${modelLabel})` });
        details.createEl("p", {
            text: MESSAGES.LABEL_GENERATION_HELP,
            cls: "setting-item-description",
        });
 
        const ragPromptSetting = new Setting(details)
            .setName(MESSAGES.LABEL_RAG_SYSTEM_PROMPT)
            .setDesc(MESSAGES.DESC_RAG_SYSTEM_PROMPT)
            .addTextArea((text) => {
                text.setPlaceholder(MESSAGES.PLACEHOLDER_DEFAULT)
                    .setValue(this.plugin.settings.ragSystemPrompt)
                    .onChange(async (value) => {
                        this.plugin.settings.ragSystemPrompt = value;
                        await this.plugin.saveSettings();
                    });
                this.serverConfigInputs.set("rag_system_prompt", text.inputEl);
            });
        this.appendLocalResetAffordance(ragPromptSetting, "ragSystemPrompt", MESSAGES.LABEL_RAG_SYSTEM_PROMPT);
 
        const generalPromptSetting = new Setting(details)
            .setName(MESSAGES.LABEL_GENERAL_SYSTEM_PROMPT)
            .setDesc(MESSAGES.DESC_GENERAL_SYSTEM_PROMPT)
            .addTextArea((text) => {
                text.setPlaceholder(MESSAGES.PLACEHOLDER_DEFAULT)
                    .setValue(this.plugin.settings.generalSystemPrompt)
                    .onChange(async (value) => {
                        this.plugin.settings.generalSystemPrompt = value;
                        await this.plugin.saveSettings();
                    });
                this.serverConfigInputs.set("general_system_prompt", text.inputEl);
            });
        this.appendLocalResetAffordance(
            generalPromptSetting,
            "generalSystemPrompt",
            MESSAGES.LABEL_GENERAL_SYSTEM_PROMPT,
        );
 
        const chatModeSetting = new Setting(details)
            .setName(MESSAGES.LABEL_CHAT_MODE)
            .setDesc(MESSAGES.DESC_CHAT_MODE)
            .addDropdown((dd) => {
                dd.addOption(CHAT_MODE.SEARCH, MESSAGES.LABEL_CHAT_MODE_SEARCH);
                dd.addOption(CHAT_MODE.CHAT, MESSAGES.LABEL_CHAT_MODE_CHAT);
                dd.setValue(CHAT_MODE.SEARCH);
                dd.onChange(async (value) => {
                    try {
                        await this.plugin.api.updateConfig({ [CONFIG_KEY.CHAT_MODE]: value });
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_CHAT_MODE));
                    }
                });
                this.chatModeDropdown = dd;
                this.chatModeSelectEl = dd.selectEl;
            });
        this.chatModeSettingEl = chatModeSetting.settingEl;
        this.chatModeSettingEl.hide();
 
        const fields: { key: string; name: string; desc: string; integer: boolean; hideable?: boolean }[] = [
            {
                key: "temperature",
                name: MESSAGES.LABEL_GEN_TEMPERATURE,
                desc: MESSAGES.DESC_GEN_TEMPERATURE,
                integer: false,
            },
            {
                key: "top_p",
                name: MESSAGES.LABEL_GEN_TOP_P,
                desc: MESSAGES.DESC_GEN_TOP_P,
                integer: false,
            },
            {
                key: "top_k_sampling",
                name: MESSAGES.LABEL_GEN_TOP_K,
                desc: MESSAGES.DESC_GEN_TOP_K,
                integer: true,
            },
            {
                key: "repeat_penalty",
                name: MESSAGES.LABEL_GEN_REPEAT_PENALTY,
                desc: MESSAGES.DESC_GEN_REPEAT_PENALTY,
                integer: false,
            },
            // num_ctx is intentionally not surfaced — it's a model-side
            // property. The server picks a context window appropriate to the
            // active model; exposing it as a user knob invites mismatches
            // (asking for more than the model supports, or over-allocating
            // RAM for no benefit).
            {
                key: "seed",
                name: MESSAGES.LABEL_GEN_SEED,
                desc: MESSAGES.DESC_GEN_SEED,
                integer: true,
            },
            {
                key: "max_tokens",
                name: MESSAGES.LABEL_GEN_MAX_TOKENS,
                desc: MESSAGES.DESC_GEN_MAX_TOKENS,
                integer: true,
                hideable: true,
            },
            {
                key: "max_reasoning_chars",
                name: MESSAGES.LABEL_GEN_MAX_REASONING_CHARS,
                desc: MESSAGES.DESC_GEN_MAX_REASONING_CHARS,
                integer: true,
                hideable: true,
            },
            {
                key: "model_keep_alive",
                name: MESSAGES.LABEL_GEN_MODEL_KEEP_ALIVE,
                desc: MESSAGES.DESC_GEN_MODEL_KEEP_ALIVE,
                integer: true,
                hideable: true,
            },
            {
                key: "gpu_memory_fraction",
                name: MESSAGES.LABEL_GEN_GPU_MEMORY_FRACTION,
                desc: MESSAGES.DESC_GEN_GPU_MEMORY_FRACTION,
                integer: false,
                hideable: true,
            },
        ];
 
        for (const field of fields) {
            const genSetting = new Setting(details)
                .setName(field.name)
                .setDesc(field.desc)
                .addText((text) => {
                    text.setPlaceholder(MESSAGES.PLACEHOLDER_NOT_SET)
                        .setValue("")
                        .onChange(async (value) => {
                            const trimmed = value.trim();
                            if (trimmed === "") {
                                try {
                                    await this.plugin.api.updateConfig({ [field.key]: null });
                                    new Notice(MESSAGES.NOTICE_FIELD_UPDATED(field.name));
                                } catch {
                                    new Notice(MESSAGES.NOTICE_FAILED_UPDATE(field.name));
                                }
                                return;
                            }
                            const num = field.integer ? parseInt(trimmed, 10) : parseFloat(trimmed);
                            if (isNaN(num)) return;
                            try {
                                await this.plugin.api.updateConfig({ [field.key]: num });
                                new Notice(MESSAGES.NOTICE_FIELD_UPDATED(field.name));
                            } catch {
                                new Notice(MESSAGES.NOTICE_FAILED_UPDATE(field.name));
                            }
                        });
                    this.serverConfigInputs.set(field.key, text.inputEl);
                });
            this.appendResetAffordance(genSetting, field.key, field.name);
            if (field.hideable) {
                genSetting.settingEl.hide();
                this.serverConfigHideableEls.set(field.key, genSetting.settingEl);
            }
        }
    }
 
    private renderWorkerPoolSettings(containerEl: HTMLElement): void {
        const details = containerEl.createEl("details", {
            cls: "lilbee-worker-pool-details lilbee-settings-section",
        });
        details.createEl("summary", { text: MESSAGES.LABEL_WORKER_POOL });
        details.createEl("p", {
            text: MESSAGES.LABEL_WORKER_POOL_HELP,
            cls: "setting-item-description",
        });
 
        const callTimeoutSetting = this.renderHideableNumberField(
            details,
            "worker_pool_call_timeout_s",
            MESSAGES.LABEL_WORKER_POOL_CALL_TIMEOUT,
            MESSAGES.DESC_WORKER_POOL_CALL_TIMEOUT,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(
            callTimeoutSetting,
            "worker_pool_call_timeout_s",
            MESSAGES.LABEL_WORKER_POOL_CALL_TIMEOUT,
        );
 
        const eagerStartSetting = new Setting(details)
            .setName(MESSAGES.LABEL_WORKER_POOL_EAGER_START)
            .setDesc(MESSAGES.DESC_WORKER_POOL_EAGER_START)
            .addToggle((toggle) => {
                toggle.onChange(async (value) => {
                    if (this.suppressChangeEvents) return;
                    try {
                        await this.plugin.api.updateConfig({ worker_pool_eager_start: value });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_WORKER_POOL_EAGER_START));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_WORKER_POOL_EAGER_START));
                    }
                });
                this.serverConfigToggles.set("worker_pool_eager_start", toggle);
            });
        this.appendResetAffordance(
            eagerStartSetting,
            "worker_pool_eager_start",
            MESSAGES.LABEL_WORKER_POOL_EAGER_START,
        );
        eagerStartSetting.settingEl.hide();
        this.serverConfigHideableEls.set("worker_pool_eager_start", eagerStartSetting.settingEl);
 
        const maxIdleSetting = this.renderHideableNumberField(
            details,
            "worker_pool_max_idle_s",
            MESSAGES.LABEL_WORKER_POOL_MAX_IDLE,
            MESSAGES.DESC_WORKER_POOL_MAX_IDLE,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(maxIdleSetting, "worker_pool_max_idle_s", MESSAGES.LABEL_WORKER_POOL_MAX_IDLE);
    }
 
    /** GPU / fleet tuning knobs not surfaced in the placement view. Each row stays
     * hidden until the connected server reports the key, so older servers show none. */
    private renderFleetSettings(containerEl: HTMLElement): void {
        const details = containerEl.createEl("details", { cls: "lilbee-fleet-details lilbee-settings-section" });
        details.createEl("summary", { text: MESSAGES.LABEL_FLEET });
        details.createEl("p", { text: MESSAGES.LABEL_FLEET_HELP, cls: "setting-item-description" });
 
        const kvContainer = details.createDiv();
        const kvSetting = new Setting(kvContainer)
            .setName(MESSAGES.LABEL_KV_CACHE_TYPE)
            .setDesc(MESSAGES.DESC_KV_CACHE_TYPE)
            .addDropdown((dropdown) => {
                dropdown.addOption(KV_CACHE_TYPE.F16, KV_CACHE_TYPE.F16);
                dropdown.addOption(KV_CACHE_TYPE.Q8_0, KV_CACHE_TYPE.Q8_0);
                dropdown.addOption(KV_CACHE_TYPE.Q4_0, KV_CACHE_TYPE.Q4_0);
                dropdown.addOption(KV_CACHE_TYPE.F32, KV_CACHE_TYPE.F32);
                dropdown.setValue(KV_CACHE_TYPE.Q8_0);
                dropdown.onChange(async (value) => {
                    try {
                        await this.plugin.api.updateConfig({ kv_cache_type: value });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_KV_CACHE_TYPE));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_KV_CACHE_TYPE));
                    }
                });
                this.serverConfigDropdowns.set("kv_cache_type", dropdown);
            });
        this.appendResetAffordance(kvSetting, "kv_cache_type", MESSAGES.LABEL_KV_CACHE_TYPE);
        kvContainer.hide();
        this.serverConfigHideableEls.set("kv_cache_type", kvContainer);
 
        const flashContainer = details.createDiv();
        const flashSetting = new Setting(flashContainer)
            .setName(MESSAGES.LABEL_FLASH_ATTENTION)
            .setDesc(MESSAGES.DESC_FLASH_ATTENTION)
            .addToggle((toggle) => {
                toggle.onChange(async (value) => {
                    if (this.suppressChangeEvents) return;
                    try {
                        await this.plugin.api.updateConfig({ flash_attention: value });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_FLASH_ATTENTION));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_FLASH_ATTENTION));
                    }
                });
                this.serverConfigToggles.set("flash_attention", toggle);
            });
        this.appendResetAffordance(flashSetting, "flash_attention", MESSAGES.LABEL_FLASH_ATTENTION);
        flashContainer.hide();
        this.serverConfigHideableEls.set("flash_attention", flashContainer);
 
        const layers = this.renderHideableNumberField(
            details,
            "n_gpu_layers",
            MESSAGES.LABEL_N_GPU_LAYERS,
            MESSAGES.DESC_N_GPU_LAYERS,
            { integer: true, min: 0 },
        );
        this.appendResetAffordance(layers, "n_gpu_layers", MESSAGES.LABEL_N_GPU_LAYERS);
 
        const embedReplicas = this.renderHideableNumberField(
            details,
            "embed_replicas",
            MESSAGES.LABEL_EMBED_REPLICAS,
            MESSAGES.DESC_EMBED_REPLICAS,
            { integer: true, min: 0 },
        );
        this.appendResetAffordance(embedReplicas, "embed_replicas", MESSAGES.LABEL_EMBED_REPLICAS);
 
        const visionReplicas = this.renderHideableNumberField(
            details,
            "vision_replicas",
            MESSAGES.LABEL_VISION_REPLICAS,
            MESSAGES.DESC_VISION_REPLICAS,
            { integer: true, min: 0 },
        );
        this.appendResetAffordance(visionReplicas, "vision_replicas", MESSAGES.LABEL_VISION_REPLICAS);
 
        const devContainer = details.createDiv();
        const devSetting = new Setting(devContainer)
            .setName(MESSAGES.LABEL_GPU_DEVICES)
            .setDesc(MESSAGES.DESC_GPU_DEVICES)
            .addText((text) => {
                text.setPlaceholder(MESSAGES.PLACEHOLDER_GPU_DEVICES)
                    .setValue("")
                    .onChange(async (value) => {
                        const trimmed = value.trim();
                        try {
                            await this.plugin.api.updateConfig({ gpu_devices: trimmed === "" ? null : trimmed });
                            new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_GPU_DEVICES));
                        } catch {
                            new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_GPU_DEVICES));
                        }
                    });
                this.serverConfigInputs.set("gpu_devices", text.inputEl);
            });
        this.appendResetAffordance(devSetting, "gpu_devices", MESSAGES.LABEL_GPU_DEVICES);
        devContainer.hide();
        this.serverConfigHideableEls.set("gpu_devices", devContainer);
    }
 
    private renderIngestSettings(containerEl: HTMLElement): void {
        const details = containerEl.createEl("details", {
            cls: "lilbee-ingest-details lilbee-settings-section",
        });
        details.createEl("summary", { text: MESSAGES.LABEL_INGEST });
        details.createEl("p", {
            text: MESSAGES.LABEL_INGEST_HELP,
            cls: "setting-item-description",
        });
 
        // Extraction quality. layout_detection is off by default server-side
        // because of what it costs, so the description says so rather than
        // leaving someone to discover it on a slow ingest.
        this.renderConfigToggle(
            details,
            "layout_detection",
            MESSAGES.LABEL_LAYOUT_DETECTION,
            MESSAGES.DESC_LAYOUT_DETECTION,
        );
        this.renderConfigToggle(
            details,
            "table_extraction",
            MESSAGES.LABEL_TABLE_EXTRACTION,
            MESSAGES.DESC_TABLE_EXTRACTION,
        );
        const tableModelSetting = new Setting(details)
            .setName(MESSAGES.LABEL_TABLE_MODEL)
            .setDesc(MESSAGES.DESC_TABLE_MODEL)
            .addDropdown((dropdown) => {
                for (const model of Object.values(TABLE_MODEL)) dropdown.addOption(model, model);
                dropdown.setValue(TABLE_MODEL.SLANET_AUTO);
                dropdown.onChange(async (value) => {
                    try {
                        await this.plugin.api.updateConfig({ table_model: value });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_TABLE_MODEL));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_TABLE_MODEL));
                    }
                });
                this.serverConfigDropdowns.set("table_model", dropdown);
            });
        this.appendResetAffordance(tableModelSetting, "table_model", MESSAGES.LABEL_TABLE_MODEL);
        this.renderConfigList(details, "ocr_language", MESSAGES.LABEL_OCR_LANGUAGE, MESSAGES.DESC_OCR_LANGUAGE);
 
        // How much of the machine ingest and the engine may take.
        const ingestProcesses = this.renderHideableNumberField(
            details,
            "ingest_processes",
            MESSAGES.LABEL_INGEST_PROCESSES,
            MESSAGES.DESC_INGEST_PROCESSES,
            { integer: true, min: 0 },
        );
        this.appendResetAffordance(ingestProcesses, "ingest_processes", MESSAGES.LABEL_INGEST_PROCESSES);
        const memReserve = this.renderHideableNumberField(
            details,
            "system_memory_reserve_gb",
            MESSAGES.LABEL_SYSTEM_MEMORY_RESERVE_GB,
            MESSAGES.DESC_SYSTEM_MEMORY_RESERVE_GB,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(memReserve, "system_memory_reserve_gb", MESSAGES.LABEL_SYSTEM_MEMORY_RESERVE_GB);
        const vramFraction = this.renderHideableNumberField(
            details,
            "usable_vram_fraction",
            MESSAGES.LABEL_USABLE_VRAM_FRACTION,
            MESSAGES.DESC_USABLE_VRAM_FRACTION,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(vramFraction, "usable_vram_fraction", MESSAGES.LABEL_USABLE_VRAM_FRACTION);
        this.renderConfigToggle(
            details,
            "fast_model_downloads",
            MESSAGES.LABEL_FAST_MODEL_DOWNLOADS,
            MESSAGES.DESC_FAST_MODEL_DOWNLOADS,
        );
 
        const chunkSizeSetting = this.renderHideableNumberField(
            details,
            "chunk_size",
            MESSAGES.LABEL_CHUNK_SIZE,
            MESSAGES.DESC_CHUNK_SIZE,
            { integer: true, min: 1, reindex: true },
        );
        this.appendResetAffordance(chunkSizeSetting, "chunk_size", MESSAGES.LABEL_CHUNK_SIZE);
 
        const chunkOverlapSetting = this.renderHideableNumberField(
            details,
            "chunk_overlap",
            MESSAGES.LABEL_CHUNK_OVERLAP,
            MESSAGES.DESC_CHUNK_OVERLAP,
            { integer: true, min: 0, reindex: true },
        );
        this.appendResetAffordance(chunkOverlapSetting, "chunk_overlap", MESSAGES.LABEL_CHUNK_OVERLAP);
 
        const maxChunksSetting = this.renderHideableNumberField(
            details,
            "max_chunks_per_file",
            MESSAGES.LABEL_MAX_CHUNKS_PER_FILE,
            MESSAGES.DESC_MAX_CHUNKS_PER_FILE,
            { integer: true, min: 0 },
        );
        this.appendResetAffordance(maxChunksSetting, "max_chunks_per_file", MESSAGES.LABEL_MAX_CHUNKS_PER_FILE);
 
        const tesseractSetting = this.renderHideableNumberField(
            details,
            "tesseract_timeout",
            MESSAGES.LABEL_TESSERACT_TIMEOUT,
            MESSAGES.DESC_TESSERACT_TIMEOUT,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(tesseractSetting, "tesseract_timeout", MESSAGES.LABEL_TESSERACT_TIMEOUT);
 
        const visionBudgetSetting = this.renderHideableNumberField(
            details,
            "vision_load_budget_s",
            MESSAGES.LABEL_VISION_LOAD_BUDGET,
            MESSAGES.DESC_VISION_LOAD_BUDGET,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(visionBudgetSetting, "vision_load_budget_s", MESSAGES.LABEL_VISION_LOAD_BUDGET);
    }
 
    private renderMemorySection(containerEl: HTMLElement): void {
        const section = containerEl.createDiv({ cls: "lilbee-settings-section" });
        new Setting(section).setName(MESSAGES.LABEL_MEMORY_SECTION).setHeading();
        this.plugin.api
            .config()
            .then((cfg) => {
                this.renderMemoryToggle(
                    section,
                    MEMORY_CONFIG_KEY.ENABLED,
                    cfg[MEMORY_CONFIG_KEY.ENABLED] === true,
                    MESSAGES.LABEL_MEMORY_ENABLED,
                    MESSAGES.DESC_MEMORY_ENABLED,
                );
                this.renderMemoryToggle(
                    section,
                    MEMORY_CONFIG_KEY.AUTO_EXTRACT,
                    cfg[MEMORY_CONFIG_KEY.AUTO_EXTRACT] === true,
                    MESSAGES.LABEL_MEMORY_AUTO_EXTRACT,
                    MESSAGES.DESC_MEMORY_AUTO_EXTRACT,
                );
            })
            .catch((err) => {
                if (noticeServerUnreachableIfApplicable(err)) return;
                this.plugin.journal.record(MESSAGES.NOTICE_MEMORY_CONFIG_FAILED, errorMessage(err, ""));
            });
    }
 
    private renderMemoryToggle(section: HTMLElement, key: string, initial: boolean, name: string, desc: string): void {
        new Setting(section)
            .setName(name)
            .setDesc(desc)
            .addToggle((toggle) => {
                toggle.setValue(initial);
                toggle.onChange(async (value) => {
                    try {
                        await this.plugin.api.updateConfig({ [key]: value });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(name));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(name));
                    }
                });
                this.memoryToggles.set(key, toggle);
            });
    }
 
    private renderRetrievalAdvanced(containerEl: HTMLElement): void {
        const details = containerEl.createEl("details", {
            cls: "lilbee-retrieval-advanced-details lilbee-settings-section",
        });
        details.createEl("summary", { text: MESSAGES.LABEL_RETRIEVAL_ADVANCED });
        details.createEl("p", {
            text: MESSAGES.LABEL_RETRIEVAL_ADVANCED_HELP,
            cls: "setting-item-description",
        });
 
        const candidateSetting = this.renderHideableNumberField(
            details,
            "candidate_multiplier",
            MESSAGES.LABEL_CANDIDATE_MULTIPLIER,
            MESSAGES.DESC_CANDIDATE_MULTIPLIER,
            { integer: true, min: 1 },
        );
        this.appendResetAffordance(candidateSetting, "candidate_multiplier", MESSAGES.LABEL_CANDIDATE_MULTIPLIER);
 
        const minRelevanceSetting = this.renderHideableNumberField(
            details,
            "min_relevance_score",
            MESSAGES.LABEL_MIN_RELEVANCE_SCORE,
            MESSAGES.DESC_MIN_RELEVANCE_SCORE,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(minRelevanceSetting, "min_relevance_score", MESSAGES.LABEL_MIN_RELEVANCE_SCORE);
 
        const maxSourcesSetting = this.renderHideableNumberField(
            details,
            "max_context_sources",
            MESSAGES.LABEL_MAX_CONTEXT_SOURCES,
            MESSAGES.DESC_MAX_CONTEXT_SOURCES,
            { integer: true, min: 1 },
        );
        this.appendResetAffordance(maxSourcesSetting, "max_context_sources", MESSAGES.LABEL_MAX_CONTEXT_SOURCES);
 
        const diversitySetting = this.renderHideableNumberField(
            details,
            "diversity_max_per_source",
            MESSAGES.LABEL_DIVERSITY_MAX_PER_SOURCE,
            MESSAGES.DESC_DIVERSITY_MAX_PER_SOURCE,
            { integer: true, min: 1 },
        );
        this.appendResetAffordance(
            diversitySetting,
            "diversity_max_per_source",
            MESSAGES.LABEL_DIVERSITY_MAX_PER_SOURCE,
        );
 
        this.renderConfigToggle(details, "title_search", MESSAGES.LABEL_TITLE_SEARCH, MESSAGES.DESC_TITLE_SEARCH);
        const titleWeight = this.renderHideableNumberField(
            details,
            "title_search_weight",
            MESSAGES.LABEL_TITLE_SEARCH_WEIGHT,
            MESSAGES.DESC_TITLE_SEARCH_WEIGHT,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(titleWeight, "title_search_weight", MESSAGES.LABEL_TITLE_SEARCH_WEIGHT);
 
        this.renderConfigToggle(
            details,
            "adaptive_fusion",
            MESSAGES.LABEL_ADAPTIVE_FUSION,
            MESSAGES.DESC_ADAPTIVE_FUSION,
        );
        const fusionMargin = this.renderHideableNumberField(
            details,
            "adaptive_fusion_margin",
            MESSAGES.LABEL_ADAPTIVE_FUSION_MARGIN,
            MESSAGES.DESC_ADAPTIVE_FUSION_MARGIN,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(fusionMargin, "adaptive_fusion_margin", MESSAGES.LABEL_ADAPTIVE_FUSION_MARGIN);
 
        const lexicalWeight = this.renderHideableNumberField(
            details,
            "lexical_fusion_weight",
            MESSAGES.LABEL_LEXICAL_FUSION_WEIGHT,
            MESSAGES.DESC_LEXICAL_FUSION_WEIGHT,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(lexicalWeight, "lexical_fusion_weight", MESSAGES.LABEL_LEXICAL_FUSION_WEIGHT);
 
        const neighbors = this.renderHideableNumberField(
            details,
            "neighbor_expansion",
            MESSAGES.LABEL_NEIGHBOR_EXPANSION,
            MESSAGES.DESC_NEIGHBOR_EXPANSION,
            { integer: true, min: 0 },
        );
        this.appendResetAffordance(neighbors, "neighbor_expansion", MESSAGES.LABEL_NEIGHBOR_EXPANSION);
 
        this.renderConfigToggle(
            details,
            "filter_structural_chunks",
            MESSAGES.LABEL_FILTER_STRUCTURAL_CHUNKS,
            MESSAGES.DESC_FILTER_STRUCTURAL_CHUNKS,
        );
 
        const rerankMin = this.renderHideableNumberField(
            details,
            "rerank_min_score",
            MESSAGES.LABEL_RERANK_MIN_SCORE,
            MESSAGES.DESC_RERANK_MIN_SCORE,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(rerankMin, "rerank_min_score", MESSAGES.LABEL_RERANK_MIN_SCORE);
 
        const ftsLanguage = new Setting(details)
            .setName(MESSAGES.LABEL_FTS_LANGUAGE)
            .setDesc(MESSAGES.DESC_FTS_LANGUAGE)
            .addText((text) => {
                text.onChange(async (value) => {
                    const trimmed = value.trim();
                    if (trimmed === "") return;
                    try {
                        await this.plugin.api.updateConfig({ fts_language: trimmed });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_FTS_LANGUAGE));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_FTS_LANGUAGE));
                    }
                });
                this.serverConfigInputs.set("fts_language", text.inputEl);
            });
        this.appendResetAffordance(ftsLanguage, "fts_language", MESSAGES.LABEL_FTS_LANGUAGE);
 
        // Indexing-side quality: these only take effect on documents ingested
        // after the change, which is why they sit with retrieval rather than
        // with the ingest controls.
        this.renderConfigToggle(
            details,
            "contextual_enrichment",
            MESSAGES.LABEL_CONTEXTUAL_ENRICHMENT,
            MESSAGES.DESC_CONTEXTUAL_ENRICHMENT,
        );
        this.renderConfigToggle(details, "embed_titles", MESSAGES.LABEL_EMBED_TITLES, MESSAGES.DESC_EMBED_TITLES);
        this.renderConfigToggle(details, "token_sizing", MESSAGES.LABEL_TOKEN_SIZING, MESSAGES.DESC_TOKEN_SIZING);
 
        const mmrSetting = this.renderHideableNumberField(
            details,
            "mmr_lambda",
            MESSAGES.LABEL_MMR_LAMBDA,
            MESSAGES.DESC_MMR_LAMBDA,
            { integer: false, min: 0 },
        );
        this.appendResetAffordance(mmrSetting, "mmr_lambda", MESSAGES.LABEL_MMR_LAMBDA);
    }
 
    /** A server-config boolean on a toggle, hidden until loadServerDefaults sees the key. */
    private renderConfigToggle(container: HTMLElement, key: string, name: string, desc: string): void {
        const setting = new Setting(container)
            .setName(name)
            .setDesc(desc)
            .addToggle((toggle) => {
                toggle.onChange(async (value) => {
                    if (this.suppressChangeEvents) return;
                    try {
                        await this.plugin.api.updateConfig({ [key]: value });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(name));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(name));
                    }
                });
                this.serverConfigToggles.set(key, toggle);
            });
        setting.settingEl.hide();
        this.serverConfigHideableEls.set(key, setting.settingEl);
        this.appendResetAffordance(setting, key, name);
    }
 
    /** A server-config number on a slider, hidden until loadServerDefaults sees the key. */
    private renderConfigSlider(
        container: HTMLElement,
        key: string,
        name: string,
        desc: string,
        opts: { min: number; max: number; step: number },
    ): void {
        const setting = new Setting(container)
            .setName(name)
            .setDesc(desc)
            .addSlider((slider) => {
                slider.setLimits(opts.min, opts.max, opts.step).onChange(async (value) => {
                    if (this.suppressChangeEvents) return;
                    try {
                        await this.plugin.api.updateConfig({ [key]: value });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(name));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(name));
                    }
                });
                this.serverConfigSliders.set(key, slider);
            });
        setting.settingEl.hide();
        this.serverConfigHideableEls.set(key, setting.settingEl);
        this.appendResetAffordance(setting, key, name);
    }
 
    /** A server-config list of short strings, one per line (e.g. OCR languages). */
    private renderConfigList(container: HTMLElement, key: string, name: string, desc: string): void {
        const setting = new Setting(container)
            .setName(name)
            .setDesc(desc)
            .addTextArea((area) => {
                area.onChange(async (value) => {
                    const items = value
                        .split("\n")
                        .map((line) => line.trim())
                        .filter((line) => line !== "");
                    // An empty box means "use the server default", not "no
                    // languages" — sending [] would leave OCR unable to read
                    // anything at all.
                    try {
                        await this.plugin.api.updateConfig({ [key]: items.length > 0 ? items : null });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(name));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(name));
                    }
                });
                this.serverConfigTextAreas.set(key, area.inputEl);
            });
        this.appendResetAffordance(setting, key, name);
    }
 
    private renderHideableNumberField(
        container: HTMLElement,
        key: string,
        name: string,
        desc: string,
        opts: { integer: boolean; min?: number; reindex?: boolean },
    ): Setting {
        const setting = new Setting(container)
            .setName(name)
            .setDesc(desc)
            .addText((text) => {
                text.setPlaceholder(MESSAGES.PLACEHOLDER_NOT_SET)
                    .setValue("")
                    .onChange(async (value) => {
                        await this.handleHideableNumberChange(value, key, name, opts);
                    });
                this.serverConfigInputs.set(key, text.inputEl);
            });
        setting.settingEl.hide();
        this.serverConfigHideableEls.set(key, setting.settingEl);
        return setting;
    }
 
    private async handleHideableNumberChange(
        value: string,
        key: string,
        name: string,
        opts: { integer: boolean; min?: number; reindex?: boolean },
    ): Promise<void> {
        const trimmed = value.trim();
        if (trimmed === "") return;
        const num = opts.integer ? parseInt(trimmed, 10) : parseFloat(trimmed);
        if (isNaN(num)) return;
        if (opts.min !== undefined && num < opts.min) return;
        if (opts.reindex) {
            const confirmModal = new ConfirmModal(this.app, MESSAGES.DESC_REINDEX_WARNING.replace("{field}", name));
            confirmModal.open();
            const confirmed = await confirmModal.result;
            if (!confirmed) return;
        }
        try {
            const result = await this.plugin.api.updateConfig({ [key]: num });
            new Notice(MESSAGES.NOTICE_FIELD_UPDATED(name));
            if (opts.reindex && result.reindex_required) {
                new Notice(MESSAGES.NOTICE_REINDEX_REQUIRED);
                void this.plugin.triggerSync();
            }
        } catch {
            new Notice(MESSAGES.NOTICE_FAILED_UPDATE(name));
        }
    }
 
    private loadEmbeddingDropdown(container: HTMLElement): void {
        this.plugin.api
            .catalog({ task: MODEL_TASK.EMBEDDING })
            .then((result) => {
                if (result.isErr()) {
                    this.renderEmbeddingFallback(container);
                    return;
                }
                // Settings dropdown lists installed local embedding models plus
                // always-on hosted ones (e.g. an Ollama embedding model), matching
                // the chat/vision/reranker pickers. Discovery and downloads happen
                // via Browse catalog, which the button on the right of this row opens.
                const catalogEntries = result.value.models;
                const localInstalled = catalogEntries.filter(
                    (m) => m.task === MODEL_TASK.EMBEDDING && m.installed && !HOSTED_SOURCES.has(m.source),
                );
                new Setting(container)
                    .setName(MESSAGES.LABEL_EMBEDDING_MODEL)
                    .setDesc(MESSAGES.DESC_EMBEDDING_MODEL)
                    .addDropdown((dropdown) => {
                        for (const model of localInstalled) {
                            dropdown.addOption(model.hf_repo, model.display_name);
                        }
                        for (const [ref, label] of hostedOptions(catalogEntries)) {
                            dropdown.addOption(ref, label);
                        }
                        dropdown.onChange(async (value) => {
                            if (!value) return;
                            const confirmModal = new ConfirmModal(this.app, MESSAGES.DESC_EMBEDDING_REINDEX_WARNING);
                            confirmModal.open();
                            const confirmed = await confirmModal.result;
                            if (!confirmed) return;
                            const result = await this.plugin.api.setEmbeddingModel(value);
                            if (result.isErr()) {
                                new Notice(noticeForResultError(result.error, MESSAGES.NOTICE_FAILED_EMBEDDING));
                                return;
                            }
                            new Notice(MESSAGES.NOTICE_EMBEDDING_UPDATED);
                            new Notice(MESSAGES.NOTICE_REINDEX_REQUIRED);
                            void this.plugin.triggerSync();
                        });
                    })
                    .addButton((btn) =>
                        btn.setButtonText(MESSAGES.BUTTON_BROWSE_MORE).onClick(() => {
                            new CatalogModal(this.app, this.plugin, MODEL_TASK.EMBEDDING).open();
                        }),
                    );
            })
            .catch(() => {
                this.renderEmbeddingFallback(container);
            });
    }
 
    private renderRerankerSection(container: HTMLElement): void {
        Promise.all([
            this.plugin.api.config(),
            this.plugin.api.catalog({ task: MODEL_TASK.RERANK }),
            this.plugin.api.installedModels({ task: MODEL_TASK.RERANK }).catch(() => ({ models: [] })),
        ])
            .then(([cfg, catalogResult, installedResp]) => {
                const active = typeof cfg.reranker_model === "string" ? cfg.reranker_model : RERANKER_DISABLED_KEY;
                const catalogEntries = catalogResult.isOk()
                    ? catalogResult.value.models.filter((m) => m.task === MODEL_TASK.RERANK)
                    : [];
                this.renderRerankerDropdown(container, active, catalogEntries, installedResp.models);
            })
            .catch((err) => {
                if (noticeServerUnreachableIfApplicable(err)) return;
                // Journal, not a notice: this fires while a section renders
                // (often mid-startup) and an optional dropdown failing to
                // populate is not something the user can act on.
                this.plugin.journal.record(MESSAGES.NOTICE_RERANKER_LOAD_FAILED, errorMessage(err, ""));
            });
    }
 
    private renderRerankerDropdown(
        container: HTMLElement,
        active: string,
        catalogEntries: CatalogEntry[],
        installed: InstalledModel[],
    ): void {
        const options = this.buildRerankerOptions(catalogEntries, installed);
        new Setting(container)
            .setName(MESSAGES.LABEL_RERANKER_TITLE)
            .setDesc(MESSAGES.DESC_RERANKER_MODEL)
            .addDropdown((dropdown) => {
                for (const [value, label] of options) {
                    dropdown.addOption(value, label);
                }
                dropdown.setValue(
                    matchModelOption(
                        active || RERANKER_DISABLED_KEY,
                        options.map(([value]) => value),
                    ),
                );
                dropdown.onChange(async (value) => {
                    await this.handleRerankerChange(value, catalogEntries, installed);
                });
            })
            .addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_BROWSE_MORE).onClick(() => {
                    new CatalogModal(this.app, this.plugin, MODEL_TASK.RERANK).open();
                }),
            );
    }
 
    private buildRerankerOptions(catalogEntries: CatalogEntry[], installed: InstalledModel[]): Array<[string, string]> {
        // `installed[].name` is the server's canonical ref (full HF path, or `provider/name`).
        // For HF refs we strip the trailing `/<filename>.gguf` so it matches `entry.hf_repo`;
        // provider refs pass through unchanged so hosted rerankers aren't mislabelled.
        const installedRepos = new Set(installed.map((m) => extractHfRepo(m.name)));
        const isInstalled = (e: CatalogEntry): boolean => installedRepos.has(e.hf_repo);
        const opts: Array<[string, string]> = [[RERANKER_DISABLED_KEY, MESSAGES.LABEL_RERANKER_DISABLED]];
        // Settings dropdown lists installed local rerankers + always-on hosted rerankers.
        // Discovery and downloads happen via the Browse catalog button.
        const localInstalled = catalogEntries.filter((e) => !HOSTED_SOURCES.has(e.source) && isInstalled(e));
        for (const e of localInstalled) opts.push([e.hf_repo, e.display_name]);
        for (const [ref, label] of hostedOptions(catalogEntries)) {
            opts.push([ref, `${label} — ${MESSAGES.LABEL_RERANKER_HOSTED_GROUP}`]);
        }
        return opts;
    }
 
    private async handleRerankerChange(
        value: string,
        catalogEntries: CatalogEntry[],
        installed: InstalledModel[],
    ): Promise<void> {
        const installedRepos = new Set(installed.map((m) => extractHfRepo(m.name)));
        const catalogEntry = catalogEntries.find((e) => e.hf_repo === value);
        if (
            value === RERANKER_DISABLED_KEY ||
            installedRepos.has(value) ||
            (catalogEntry !== undefined && HOSTED_SOURCES.has(catalogEntry.source))
        ) {
            await this.applyRerankerSelection(value);
            return;
        }
        if (catalogEntry) {
            await this.pullAndSetReranker(catalogEntry);
        }
    }
 
    private async applyRerankerSelection(value: string): Promise<void> {
        const result = await this.plugin.api.setRerankerModel(value);
        if (result.isErr()) {
            new Notice(noticeForResultError(result.error, MESSAGES.NOTICE_FAILED_RERANKER));
            return;
        }
        new Notice(MESSAGES.NOTICE_RERANKER_UPDATED);
    }
 
    private async pullAndSetReranker(entry: CatalogEntry): Promise<void> {
        const taskId = this.plugin.enqueuePull(`Pull ${entry.display_name}`);
        if (taskId === null) {
            new Notice(MESSAGES.NOTICE_QUEUE_FULL);
            return;
        }
        const controller = new AbortController();
        this.plugin.taskQueue.registerAbort(taskId, controller);
        const ok = await this.streamRerankerPull(taskId, entry, controller.signal);
        if (!ok) return;
        this.plugin.taskQueue.complete(taskId);
        await this.applyRerankerSelection(entry.hf_repo);
    }
 
    private async streamRerankerPull(taskId: string, entry: CatalogEntry, signal: AbortSignal): Promise<boolean> {
        try {
            for await (const event of this.plugin.api.pullModel(entry.hf_repo, "native", signal)) {
                if (event.event === SSE_EVENT.PROGRESS) {
                    this.handleRerankerPullProgress(taskId, entry, event.data);
                } else if (event.event === SSE_EVENT.ERROR) {
                    this.handleRerankerPullSseError(taskId, entry, event.data);
                    return false;
                }
            }
        } catch (err) {
            this.handleRerankerPullException(taskId, entry, err);
            return false;
        }
        return true;
    }
 
    private handleRerankerPullProgress(taskId: string, entry: CatalogEntry, data: unknown): void {
        const d = data as { percent?: number; current?: number; total?: number };
        const pct = percentFromSse(d);
        if (pct !== undefined) {
            this.plugin.taskQueue.update(taskId, pct, entry.display_name, { current: d.current, total: d.total });
        }
    }
 
    private handleRerankerPullSseError(taskId: string, entry: CatalogEntry, data: unknown): void {
        const msg = extractSseErrorMessage(data, MESSAGES.ERROR_UNKNOWN);
        new Notice(`${MESSAGES.ERROR_PULL_MODEL.replace("{model}", entry.display_name)}: ${msg}`);
        this.plugin.taskQueue.fail(taskId, msg);
    }
 
    private handleRerankerPullException(taskId: string, entry: CatalogEntry, err: unknown): void {
        if (err instanceof Error && err.name === ERROR_NAME.ABORT_ERROR) {
            new Notice(MESSAGES.NOTICE_PULL_CANCELLED);
            this.plugin.taskQueue.cancel(taskId);
            return;
        }
        const reason = errorMessage(err, MESSAGES.ERROR_UNKNOWN);
        new Notice(`${MESSAGES.ERROR_PULL_MODEL.replace("{model}", entry.display_name)}: ${reason}`);
        this.plugin.taskQueue.fail(taskId, reason);
    }
 
    private renderVisionSection(container: HTMLElement): void {
        Promise.all([
            this.plugin.api.config(),
            this.plugin.api.catalog({ task: MODEL_TASK.VISION }),
            this.plugin.api.installedModels({ task: MODEL_TASK.VISION }).catch(() => ({ models: [] })),
        ])
            .then(([cfg, catalogResult, installedResp]) => {
                const active = typeof cfg.vision_model === "string" ? cfg.vision_model : VISION_DISABLED_KEY;
                const catalogEntries = catalogResult.isOk()
                    ? catalogResult.value.models.filter((m) => m.task === MODEL_TASK.VISION)
                    : [];
                this.renderVisionDropdown(container, active, catalogEntries, installedResp.models);
            })
            .catch((err) => {
                if (noticeServerUnreachableIfApplicable(err)) return;
                this.plugin.journal.record(MESSAGES.NOTICE_VISION_LOAD_FAILED, errorMessage(err, ""));
            });
    }
 
    private renderVisionDropdown(
        container: HTMLElement,
        active: string,
        catalogEntries: CatalogEntry[],
        installed: InstalledModel[],
    ): void {
        const options = this.buildVisionOptions(catalogEntries, installed);
        new Setting(container)
            .setName(MESSAGES.LABEL_VISION_TITLE)
            .setDesc(MESSAGES.DESC_VISION_MODEL)
            .addDropdown((dropdown) => {
                for (const [value, label] of options) {
                    dropdown.addOption(value, label);
                }
                dropdown.setValue(
                    matchModelOption(
                        active || VISION_DISABLED_KEY,
                        options.map(([value]) => value),
                    ),
                );
                dropdown.onChange(async (value) => {
                    await this.handleVisionChange(value, catalogEntries, installed);
                });
            })
            .addButton((btn) =>
                btn.setButtonText(MESSAGES.BUTTON_BROWSE_MORE).onClick(() => {
                    new CatalogModal(this.app, this.plugin, MODEL_TASK.VISION).open();
                }),
            );
    }
 
    private buildVisionOptions(catalogEntries: CatalogEntry[], installed: InstalledModel[]): Array<[string, string]> {
        // Strip the trailing `/<filename>.gguf` from installed refs so they match the catalog's bare `hf_repo`.
        const installedRepos = new Set(installed.map((m) => extractHfRepo(m.name)));
        const opts: Array<[string, string]> = [[VISION_DISABLED_KEY, MESSAGES.LABEL_VISION_DISABLED]];
        // Settings dropdown lists installed local vision models + hosted ones.
        // Discovery and downloads happen via the Browse catalog button.
        const localInstalled = catalogEntries.filter(
            (e) => !HOSTED_SOURCES.has(e.source) && installedRepos.has(e.hf_repo),
        );
        for (const e of localInstalled) opts.push([e.hf_repo, e.display_name]);
        for (const [ref, label] of hostedOptions(catalogEntries)) {
            opts.push([ref, `${label} — ${MESSAGES.LABEL_VISION_HOSTED_GROUP}`]);
        }
        return opts;
    }
 
    private async handleVisionChange(
        value: string,
        catalogEntries: CatalogEntry[],
        installed: InstalledModel[],
    ): Promise<void> {
        const installedRepos = new Set(installed.map((m) => extractHfRepo(m.name)));
        const catalogEntry = catalogEntries.find((e) => e.hf_repo === value);
        if (
            value === VISION_DISABLED_KEY ||
            installedRepos.has(value) ||
            (catalogEntry !== undefined && HOSTED_SOURCES.has(catalogEntry.source))
        ) {
            await this.applyVisionSelection(value);
            return;
        }
        if (catalogEntry) {
            await this.pullAndSetVision(catalogEntry);
        }
    }
 
    private async applyVisionSelection(value: string): Promise<void> {
        const result = await this.plugin.api.setVisionModel(value);
        if (result.isErr()) {
            new Notice(noticeForResultError(result.error, MESSAGES.NOTICE_FAILED_VISION));
            return;
        }
        new Notice(MESSAGES.NOTICE_VISION_UPDATED);
    }
 
    private async pullAndSetVision(entry: CatalogEntry): Promise<void> {
        const taskId = this.plugin.enqueuePull(`Pull ${entry.display_name}`);
        if (taskId === null) {
            new Notice(MESSAGES.NOTICE_QUEUE_FULL);
            return;
        }
        const controller = new AbortController();
        this.plugin.taskQueue.registerAbort(taskId, controller);
        const ok = await this.streamVisionPull(taskId, entry, controller.signal);
        if (!ok) return;
        this.plugin.taskQueue.complete(taskId);
        await this.applyVisionSelection(entry.hf_repo);
    }
 
    private async streamVisionPull(taskId: string, entry: CatalogEntry, signal: AbortSignal): Promise<boolean> {
        try {
            for await (const event of this.plugin.api.pullModel(entry.hf_repo, "native", signal)) {
                if (event.event === SSE_EVENT.PROGRESS) {
                    this.handleVisionPullProgress(taskId, entry, event.data);
                } else if (event.event === SSE_EVENT.ERROR) {
                    this.handleVisionPullSseError(taskId, entry, event.data);
                    return false;
                }
            }
        } catch (err) {
            this.handleVisionPullException(taskId, entry, err);
            return false;
        }
        return true;
    }
 
    private handleVisionPullProgress(taskId: string, entry: CatalogEntry, data: unknown): void {
        const d = data as { percent?: number; current?: number; total?: number };
        const pct = percentFromSse(d);
        if (pct !== undefined) {
            this.plugin.taskQueue.update(taskId, pct, entry.display_name, { current: d.current, total: d.total });
        }
    }
 
    private handleVisionPullSseError(taskId: string, entry: CatalogEntry, data: unknown): void {
        const msg = extractSseErrorMessage(data, MESSAGES.ERROR_UNKNOWN);
        new Notice(`${MESSAGES.ERROR_PULL_MODEL.replace("{model}", entry.display_name)}: ${msg}`);
        this.plugin.taskQueue.fail(taskId, msg);
    }
 
    private handleVisionPullException(taskId: string, entry: CatalogEntry, err: unknown): void {
        if (err instanceof Error && err.name === ERROR_NAME.ABORT_ERROR) {
            new Notice(MESSAGES.NOTICE_PULL_CANCELLED);
            this.plugin.taskQueue.cancel(taskId);
            return;
        }
        const reason = errorMessage(err, MESSAGES.ERROR_UNKNOWN);
        new Notice(`${MESSAGES.ERROR_PULL_MODEL.replace("{model}", entry.display_name)}: ${reason}`);
        this.plugin.taskQueue.fail(taskId, reason);
    }
 
    private renderEmbeddingFallback(container: HTMLElement): void {
        new Setting(container)
            .setName(MESSAGES.LABEL_EMBEDDING_MODEL)
            .setDesc(MESSAGES.DESC_EMBEDDING_MODEL)
            .addText((text) => {
                text.setPlaceholder(MESSAGES.PLACEHOLDER_DEFAULT)
                    .setValue("")
                    .onChange(async (value) => {
                        const trimmed = value.trim();
                        if (trimmed === "") return;
                        const confirmModal = new ConfirmModal(this.app, MESSAGES.DESC_EMBEDDING_REINDEX_WARNING);
                        confirmModal.open();
                        const confirmed = await confirmModal.result;
                        if (!confirmed) return;
                        const result = await this.plugin.api.setEmbeddingModel(trimmed);
                        if (result.isErr()) {
                            new Notice(noticeForResultError(result.error, MESSAGES.NOTICE_FAILED_EMBEDDING));
                            return;
                        }
                        new Notice(MESSAGES.NOTICE_EMBEDDING_UPDATED);
                        new Notice(MESSAGES.NOTICE_REINDEX_REQUIRED);
                        void this.plugin.triggerSync();
                    });
                this.serverConfigInputs.set("embedding_model", text.inputEl);
            });
    }
 
    private renderCrawlingSettings(containerEl: HTMLElement): void {
        new Setting(containerEl).setName(MESSAGES.LABEL_CRAWLING).setHeading();
 
        type NumericKind = "int" | "float";
        type NumericField = {
            key: string;
            name: string;
            desc: string;
            placeholder: string;
            kind: NumericKind;
            nullable: boolean;
            min?: number;
        };
        type BoolField = { key: string; name: string; desc: string; kind: "bool" };
        type Field = NumericField | BoolField;
 
        const fields: Field[] = [
            {
                key: "crawl_max_depth",
                name: MESSAGES.LABEL_CRAWL_MAX_DEPTH,
                desc: MESSAGES.DESC_CRAWL_MAX_DEPTH,
                placeholder: MESSAGES.HINT_CRAWL_BLANK_NO_LIMIT,
                kind: "int",
                nullable: true,
                min: 0,
            },
            {
                key: "crawl_max_pages",
                name: MESSAGES.LABEL_CRAWL_MAX_PAGES,
                desc: MESSAGES.DESC_CRAWL_MAX_PAGES,
                placeholder: MESSAGES.HINT_CRAWL_BLANK_NO_LIMIT,
                kind: "int",
                nullable: true,
                min: 1,
            },
            {
                key: "crawl_timeout",
                name: MESSAGES.LABEL_CRAWL_TIMEOUT,
                desc: MESSAGES.DESC_CRAWL_TIMEOUT,
                placeholder: MESSAGES.PLACEHOLDER_30,
                kind: "int",
                nullable: false,
                min: 1,
            },
            {
                key: "crawl_mean_delay",
                name: MESSAGES.LABEL_CRAWL_MEAN_DELAY,
                desc: MESSAGES.DESC_CRAWL_MEAN_DELAY,
                placeholder: "0.5",
                kind: "float",
                nullable: false,
                min: 0,
            },
            {
                key: "crawl_max_delay_range",
                name: MESSAGES.LABEL_CRAWL_MAX_DELAY_RANGE,
                desc: MESSAGES.DESC_CRAWL_MAX_DELAY_RANGE,
                placeholder: "0.5",
                kind: "float",
                nullable: false,
                min: 0,
            },
            {
                key: "crawl_concurrent_requests",
                name: MESSAGES.LABEL_CRAWL_CONCURRENT_REQUESTS,
                desc: MESSAGES.DESC_CRAWL_CONCURRENT_REQUESTS,
                placeholder: "3",
                kind: "int",
                nullable: false,
                min: 1,
            },
            {
                key: "crawl_retry_on_rate_limit",
                name: MESSAGES.LABEL_CRAWL_RETRY_ON_RATE_LIMIT,
                desc: MESSAGES.DESC_CRAWL_RETRY_ON_RATE_LIMIT,
                kind: "bool",
            },
            {
                key: "crawl_retry_base_delay_min",
                name: MESSAGES.LABEL_CRAWL_RETRY_BASE_DELAY_MIN,
                desc: MESSAGES.DESC_CRAWL_RETRY_BASE_DELAY_MIN,
                placeholder: "1.0",
                kind: "float",
                nullable: false,
                min: 0,
            },
            {
                key: "crawl_retry_base_delay_max",
                name: MESSAGES.LABEL_CRAWL_RETRY_BASE_DELAY_MAX,
                desc: MESSAGES.DESC_CRAWL_RETRY_BASE_DELAY_MAX,
                placeholder: "3.0",
                kind: "float",
                nullable: false,
                min: 0,
            },
            {
                key: "crawl_retry_max_backoff",
                name: MESSAGES.LABEL_CRAWL_RETRY_MAX_BACKOFF,
                desc: MESSAGES.DESC_CRAWL_RETRY_MAX_BACKOFF,
                placeholder: "30.0",
                kind: "float",
                nullable: false,
                min: 0,
            },
            {
                key: "crawl_retry_max_attempts",
                name: MESSAGES.LABEL_CRAWL_RETRY_MAX_ATTEMPTS,
                desc: MESSAGES.DESC_CRAWL_RETRY_MAX_ATTEMPTS,
                placeholder: "3",
                kind: "int",
                nullable: false,
                min: 0,
            },
        ];
 
        for (const field of fields) {
            if (field.kind === "bool") {
                const boolSetting = new Setting(containerEl)
                    .setName(field.name)
                    .setDesc(field.desc)
                    .addToggle((toggle) => {
                        toggle.onChange(async (value) => {
                            if (this.suppressChangeEvents) return;
                            try {
                                await this.plugin.api.updateConfig({ [field.key]: value });
                                new Notice(MESSAGES.NOTICE_FIELD_UPDATED(field.name));
                            } catch {
                                new Notice(MESSAGES.NOTICE_FAILED_UPDATE(field.name));
                            }
                        });
                        this.serverConfigToggles.set(field.key, toggle);
                    });
                this.appendResetAffordance(boolSetting, field.key, field.name);
                continue;
            }
 
            const numField = field;
            const numSetting = new Setting(containerEl)
                .setName(numField.name)
                .setDesc(numField.desc)
                .addText((text) => {
                    text.setPlaceholder(numField.placeholder)
                        .setValue("")
                        .onChange(async (value) => {
                            const trimmed = value.trim();
                            if (trimmed === "") {
                                if (!numField.nullable) return;
                                try {
                                    await this.plugin.api.updateConfig({ [numField.key]: null });
                                    new Notice(MESSAGES.NOTICE_FIELD_UPDATED(numField.name));
                                } catch {
                                    new Notice(MESSAGES.NOTICE_FAILED_UPDATE(numField.name));
                                }
                                return;
                            }
                            const num = Number(trimmed);
                            if (!Number.isFinite(num)) return;
                            if (numField.kind === "int" && !Number.isInteger(num)) return;
                            if (numField.min !== undefined && num < numField.min) return;
                            try {
                                await this.plugin.api.updateConfig({ [numField.key]: num });
                                new Notice(MESSAGES.NOTICE_FIELD_UPDATED(numField.name));
                            } catch {
                                new Notice(MESSAGES.NOTICE_FAILED_UPDATE(numField.name));
                            }
                        });
                    this.serverConfigInputs.set(numField.key, text.inputEl);
                });
            this.appendResetAffordance(numSetting, numField.key, numField.name);
        }
 
        // Wrap the render-mode row in its own child div so the hide-until-supported
        // toggle targets just this row, not the capability-gated crawling container.
        const renderModeContainer = containerEl.createDiv();
        const renderModeSetting = new Setting(renderModeContainer)
            .setName(MESSAGES.LABEL_CRAWL_RENDER_MODE)
            .setDesc(MESSAGES.DESC_CRAWL_RENDER_MODE)
            .addDropdown((dropdown) => {
                dropdown.addOption(CRAWL_RENDER_MODE.HTTP, MESSAGES.LABEL_CRAWL_RENDER_MODE_HTTP);
                dropdown.addOption(CRAWL_RENDER_MODE.BROWSER, MESSAGES.LABEL_CRAWL_RENDER_MODE_BROWSER);
                dropdown.setValue(CRAWL_RENDER_MODE.HTTP);
                dropdown.onChange(async (value) => {
                    try {
                        await this.plugin.api.updateConfig({ [CONFIG_KEY.CRAWL_RENDER_MODE]: value });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_CRAWL_RENDER_MODE));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_CRAWL_RENDER_MODE));
                    }
                });
                this.serverConfigDropdowns.set(CONFIG_KEY.CRAWL_RENDER_MODE, dropdown);
            });
        this.appendResetAffordance(renderModeSetting, CONFIG_KEY.CRAWL_RENDER_MODE, MESSAGES.LABEL_CRAWL_RENDER_MODE);
        renderModeContainer.hide();
        this.serverConfigHideableEls.set(CONFIG_KEY.CRAWL_RENDER_MODE, renderModeContainer);
 
        const patternsSetting = new Setting(containerEl)
            .setName(MESSAGES.LABEL_CRAWL_EXCLUDE_PATTERNS)
            .setDesc(MESSAGES.DESC_CRAWL_EXCLUDE_PATTERNS)
            .addTextArea((text) => {
                text.setValue("").onChange(async (value) => {
                    const patterns = value
                        .split("\n")
                        .map((p) => p.trim())
                        .filter((p) => p.length > 0);
                    try {
                        await this.plugin.api.updateConfig({ crawl_exclude_patterns: patterns });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_CRAWL_EXCLUDE_PATTERNS));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_CRAWL_EXCLUDE_PATTERNS));
                    }
                });
                text.inputEl.addClass("lilbee-crawl-exclude-patterns");
                this.serverConfigTextAreas.set("crawl_exclude_patterns", text.inputEl);
            });
        this.appendResetAffordance(patternsSetting, "crawl_exclude_patterns", MESSAGES.LABEL_CRAWL_EXCLUDE_PATTERNS);
    }
 
    private renderWikiSettings(containerEl: HTMLElement): void {
        const details = containerEl.createEl("details", { cls: "lilbee-advanced-details lilbee-settings-section" });
        details.createEl("summary", { text: MESSAGES.LABEL_WIKI_SECTION });
 
        // Enable wiki toggle (user preference — independent of server)
        const subSettingsContainer = details.createDiv({ cls: "lilbee-wiki-sub-settings" });
 
        const enableSetting = new Setting(details)
            .setName(MESSAGES.LABEL_WIKI_ENABLE_TOGGLE)
            .setDesc(MESSAGES.DESC_WIKI_ENABLE_TOGGLE)
            .addToggle((toggle) => {
                toggle.setValue(this.plugin.settings.wikiEnabled);
                toggle.onChange(async (value) => {
                    this.plugin.settings.wikiEnabled = value;
                    this.plugin.wikiEnabled = value;
                    await this.plugin.saveSettings();
                    this.setSubSettingsVisible(subSettingsContainer, value);
                });
            });
        this.appendLocalResetAffordance(enableSetting, "wikiEnabled", MESSAGES.LABEL_WIKI_ENABLE_TOGGLE);
 
        this.setSubSettingsVisible(subSettingsContainer, this.plugin.settings.wikiEnabled);
 
        // Wiki status (display only)
        const statusDesc = `Enabled — ${this.plugin.wikiPageCount} pages, ${this.plugin.wikiDraftCount} drafts`;
        new Setting(subSettingsContainer).setName(MESSAGES.LABEL_WIKI_STATUS).setDesc(statusDesc).setDisabled(true);
 
        // Prune raw chunks
        this.renderConfigToggle(
            subSettingsContainer,
            "wiki_prune_raw",
            MESSAGES.LABEL_WIKI_PRUNE_RAW,
            MESSAGES.DESC_WIKI_PRUNE_RAW,
        );
 
        // Faithfulness threshold
        this.renderConfigSlider(
            subSettingsContainer,
            "wiki_embedding_faithfulness_threshold",
            MESSAGES.LABEL_WIKI_FAITHFULNESS,
            MESSAGES.DESC_WIKI_FAITHFULNESS,
            { min: 0, max: 1, step: 0.05 },
        );
 
        // Default search mode
        const searchModeSetting = new Setting(subSettingsContainer)
            .setName(MESSAGES.LABEL_WIKI_SEARCH_MODE)
            .setDesc(MESSAGES.DESC_WIKI_SEARCH_MODE)
            .addDropdown((dropdown) => {
                dropdown
                    .addOption(SEARCH_CHUNK_TYPE.ALL, MESSAGES.LABEL_SEARCH_ALL)
                    .addOption(SEARCH_CHUNK_TYPE.WIKI, MESSAGES.LABEL_SEARCH_WIKI)
                    .addOption(SEARCH_CHUNK_TYPE.RAW, MESSAGES.LABEL_SEARCH_RAW)
                    .setValue(this.plugin.settings.searchChunkType)
                    .onChange(async (value) => {
                        this.plugin.settings.searchChunkType = value as SearchChunkType;
                        await this.plugin.saveSettings();
                    });
            });
        this.appendLocalResetAffordance(searchModeSetting, "searchChunkType", MESSAGES.LABEL_WIKI_SEARCH_MODE);
 
        // Sync wiki to vault
        const syncSetting = new Setting(subSettingsContainer)
            .setName(MESSAGES.LABEL_WIKI_SYNC_TO_VAULT)
            .setDesc(MESSAGES.DESC_WIKI_SYNC_TO_VAULT)
            .addToggle((toggle) => {
                toggle.setValue(this.plugin.settings.wikiSyncToVault);
                toggle.onChange(async (value) => {
                    this.plugin.settings.wikiSyncToVault = value;
                    await this.plugin.saveSettings();
                    if (value && this.plugin.wikiEnabled) {
                        this.plugin.initWikiSync();
                        void this.plugin.reconcileWiki();
                    } else {
                        this.plugin.wikiSync = null;
                    }
                });
            });
        this.appendLocalResetAffordance(syncSetting, "wikiSyncToVault", MESSAGES.LABEL_WIKI_SYNC_TO_VAULT);
 
        // Wiki vault folder
        const folderSetting = new Setting(subSettingsContainer)
            .setName(MESSAGES.LABEL_WIKI_VAULT_FOLDER)
            .setDesc(MESSAGES.DESC_WIKI_VAULT_FOLDER)
            .addText((text) => {
                text.setValue(this.plugin.settings.wikiVaultFolder);
                text.onChange(async (value) => {
                    this.plugin.settings.wikiVaultFolder = value || "lilbee-wiki";
                    await this.plugin.saveSettings();
                    if (this.plugin.settings.wikiSyncToVault && this.plugin.wikiEnabled) {
                        this.plugin.initWikiSync();
                    }
                });
            });
        this.appendLocalResetAffordance(folderSetting, "wikiVaultFolder", MESSAGES.LABEL_WIKI_VAULT_FOLDER);
 
        // Server-side wiki behaviour. These live under the same disclosure as
        // the vault options so everything about the wiki is in one place.
        this.renderConfigToggle(
            subSettingsContainer,
            "wiki_auto_update",
            MESSAGES.LABEL_WIKI_AUTO_UPDATE,
            MESSAGES.DESC_WIKI_AUTO_UPDATE,
        );
        const stubRefs = this.renderHideableNumberField(
            subSettingsContainer,
            "wiki_stub_max_chunk_refs",
            MESSAGES.LABEL_WIKI_STUB_MAX_CHUNK_REFS,
            MESSAGES.DESC_WIKI_STUB_MAX_CHUNK_REFS,
            { integer: true, min: 1 },
        );
        this.appendResetAffordance(stubRefs, "wiki_stub_max_chunk_refs", MESSAGES.LABEL_WIKI_STUB_MAX_CHUNK_REFS);
 
        const entityPrompt = new Setting(subSettingsContainer)
            .setName(MESSAGES.LABEL_WIKI_ENTITY_PAGE_PROMPT)
            .setDesc(MESSAGES.DESC_WIKI_ENTITY_PAGE_PROMPT)
            .addTextArea((area) => {
                area.onChange(async (value) => {
                    const trimmed = value.trim();
                    try {
                        // Empty means "use the built-in prompt", which is null
                        // rather than an empty prompt the model would be given.
                        await this.plugin.api.updateConfig({
                            wiki_entity_page_prompt: trimmed === "" ? null : trimmed,
                        });
                        new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_WIKI_ENTITY_PAGE_PROMPT));
                    } catch {
                        new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_WIKI_ENTITY_PAGE_PROMPT));
                    }
                });
                this.serverConfigInputs.set("wiki_entity_page_prompt", area.inputEl);
            });
        this.appendResetAffordance(entityPrompt, "wiki_entity_page_prompt", MESSAGES.LABEL_WIKI_ENTITY_PAGE_PROMPT);
 
        // Run lint button
        new Setting(subSettingsContainer)
            .setName(MESSAGES.LABEL_WIKI_RUN_LINT)
            .setDesc(MESSAGES.DESC_WIKI_RUN_LINT)
            .addButton((btn) => {
                btn.setButtonText(MESSAGES.LABEL_WIKI_RUN_LINT);
                btn.onClick(() => {
                    void this.plugin.runWikiLint();
                });
            });
 
        // Run prune button
        new Setting(subSettingsContainer)
            .setName(MESSAGES.LABEL_WIKI_RUN_PRUNE)
            .setDesc(MESSAGES.DESC_WIKI_RUN_PRUNE)
            .addButton((btn) => {
                btn.setButtonText(MESSAGES.LABEL_WIKI_RUN_PRUNE);
                btn.onClick(() => {
                    void this.plugin.runWikiPrune();
                });
            });
    }
 
    private setSubSettingsVisible(container: HTMLElement, visible: boolean): void {
        container.style.display = visible ? "" : "none";
    }
 
    private renderAdvancedSettings(containerEl: HTMLElement): void {
        const details = containerEl.createEl("details", { cls: "lilbee-advanced-details lilbee-settings-section" });
        details.createEl("summary", { text: MESSAGES.LABEL_ADVANCED });
        details.createEl("p", {
            text: MESSAGES.LABEL_ADVANCED_HELP,
            cls: "setting-item-description",
        });
 
        const storeSetting = new Setting(details)
            .setName(MESSAGES.LABEL_STORE_CONTENT_IN_VAULT)
            .setDesc(MESSAGES.DESC_STORE_CONTENT_IN_VAULT)
            .addToggle((toggle) => {
                toggle.setValue(this.plugin.settings.storeContentInVault);
                toggle.setDisabled(this.plugin.settings.serverMode !== SERVER_MODE.MANAGED);
                toggle.onChange(async (value) => {
                    this.plugin.settings.storeContentInVault = value;
                    await this.plugin.saveSettings();
                    if (value) {
                        void this.plugin.configureManagedStorage();
                    }
                });
            });
        if (this.plugin.settings.serverMode !== SERVER_MODE.MANAGED) {
            storeSetting.settingEl.addClass("lilbee-setting-disabled");
        }
 
        this.renderRerankCandidatesField(details);
 
        const llmSetting = new Setting(details)
            .setName(MESSAGES.LABEL_LLM_PROVIDER)
            .setDesc(MESSAGES.DESC_LLM_PROVIDER)
            .addDropdown((dropdown) => {
                dropdown
                    .addOption("auto", MESSAGES.DESC_LLM_PROVIDER_AUTO)
                    .addOption("llama-cpp", MESSAGES.DESC_LLM_PROVIDER_LOCAL)
                    .addOption("litellm", MESSAGES.DESC_LLM_PROVIDER_EXTERNAL)
                    .setValue("auto")
                    .onChange(async (value) => {
                        try {
                            await this.plugin.api.updateConfig({ llm_provider: value });
                            new Notice(MESSAGES.NOTICE_LLM_UPDATED);
                        } catch {
                            new Notice(MESSAGES.NOTICE_FAILED_LLM);
                        }
                    });
                this.serverConfigInputs.set("llm_provider", dropdown.selectEl as unknown as HTMLInputElement);
            });
        this.appendResetAffordance(llmSetting, "llm_provider", MESSAGES.LABEL_LLM_PROVIDER);
 
        const apiKeyFields: { label: string; desc: string; configKey: string; provider: string }[] = [
            {
                label: MESSAGES.LABEL_OPENAI_API_KEY,
                desc: MESSAGES.DESC_OPENAI_API_KEY,
                configKey: "openai_api_key",
                provider: "openai",
            },
            {
                label: MESSAGES.LABEL_ANTHROPIC_API_KEY,
                desc: MESSAGES.DESC_ANTHROPIC_API_KEY,
                configKey: "anthropic_api_key",
                provider: "anthropic",
            },
            {
                label: MESSAGES.LABEL_GEMINI_API_KEY,
                desc: MESSAGES.DESC_GEMINI_API_KEY,
                configKey: "gemini_api_key",
                provider: "gemini",
            },
        ];
 
        const apiKeysContainer = details.createDiv({ cls: "lilbee-api-keys-section" });
        this.apiKeysContainerEl = apiKeysContainer;
        for (const apiField of apiKeyFields) {
            const setting = new Setting(apiKeysContainer)
                .setName(apiField.label)
                .setDesc(apiField.desc)
                .addText((text) => {
                    text.setPlaceholder(MESSAGES.PLACEHOLDER_SK).setValue("");
                    text.inputEl.type = "password";
                    const saveKey = async (): Promise<void> => {
                        const trimmed = text.inputEl.value.trim();
                        if (trimmed === "") return;
                        try {
                            await this.plugin.api.updateConfig({ [apiField.configKey]: trimmed });
                            this.plugin.api.invalidateCapability(CAPABILITY.API_KEYS);
                            new Notice(MESSAGES.NOTICE_API_KEY_SAVED);
                        } catch {
                            new Notice(MESSAGES.NOTICE_FAILED_SAVE_KEY);
                        }
                    };
                    text.inputEl.addEventListener("blur", () => void saveKey());
                });
            setting.settingEl.setAttribute("data-lilbee-api-key", apiField.provider);
        }
 
        new Setting(details)
            .setName(MESSAGES.LABEL_HF_TOKEN)
            .setDesc(MESSAGES.DESC_HF_TOKEN)
            .addText((text) => {
                text.setPlaceholder(MESSAGES.PLACEHOLDER_HF_TOKEN)
                    .setValue(this.plugin.getSharedHfToken())
                    .onChange(async (value) => {
                        const trimmed = value.trim();
                        this.plugin.setSharedHfToken(trimmed);
                        try {
                            await this.plugin.api.updateConfig({ hf_token: trimmed });
                            new Notice(MESSAGES.NOTICE_HF_TOKEN_SAVED);
                        } catch {
                            new Notice(MESSAGES.NOTICE_FAILED_HF_TOKEN);
                        }
                    });
                text.inputEl.type = "password";
            });
 
        const localServerFields: {
            label: string;
            desc: string;
            configKey: string;
            placeholder: string;
        }[] = [
            {
                label: MESSAGES.LABEL_OLLAMA_BASE_URL,
                desc: MESSAGES.DESC_OLLAMA_BASE_URL,
                configKey: "ollama_base_url",
                placeholder: "http://localhost:11434",
            },
            {
                label: MESSAGES.LABEL_LM_STUDIO_BASE_URL,
                desc: MESSAGES.DESC_LM_STUDIO_BASE_URL,
                configKey: "lm_studio_base_url",
                placeholder: "http://localhost:1234/v1",
            },
        ];
        for (const field of localServerFields) {
            const setting = new Setting(details)
                .setName(field.label)
                .setDesc(field.desc)
                .addText((text) => {
                    text.setPlaceholder(field.placeholder)
                        .setValue("")
                        .onChange(async (value) => {
                            const trimmed = value.trim();
                            if (trimmed === "") return;
                            try {
                                await this.plugin.api.updateConfig({ [field.configKey]: trimmed });
                                new Notice(MESSAGES.NOTICE_LOCAL_SERVER_URL_UPDATED);
                            } catch {
                                new Notice(MESSAGES.NOTICE_FAILED_LOCAL_SERVER_URL);
                            }
                        });
                    this.serverConfigInputs.set(field.configKey, text.inputEl);
                });
            this.appendResetAffordance(setting, field.configKey, field.label);
        }
 
        new Setting(details)
            .setName(MESSAGES.LABEL_RESET_ALL_SETTINGS)
            .setDesc(MESSAGES.DESC_RESET_ALL_SETTINGS)
            .addButton((btn) =>
                btn
                    .setButtonText(MESSAGES.BUTTON_RESET_ALL)
                    .setClass("mod-warning")
                    .onClick(async () => {
                        const confirm = new ConfirmModal(this.app, MESSAGES.CONFIRM_RESET_ALL_SETTINGS);
                        confirm.open();
                        const confirmed = await confirm.result;
                        if (!confirmed) return;
                        const payload = { ...this.configDefaults };
                        // Never wipe credential fields — resetting them would surprise the user.
                        for (const k of CREDENTIAL_FIELDS) delete payload[k];
                        if (Object.keys(payload).length === 0) return;
                        try {
                            await this.plugin.api.updateConfig(payload);
                            new Notice(MESSAGES.NOTICE_SETTINGS_RESET);
                            this.render();
                        } catch {
                            new Notice(MESSAGES.NOTICE_FAILED_RESET_ALL);
                        }
                    }),
            );
    }
 
    async checkEndpoint(url: string, statusEl: HTMLSpanElement): Promise<void> {
        statusEl.empty();
        statusEl.classList.remove("lilbee-health-ok", "lilbee-health-error");
        const dot = statusEl.createDiv({ cls: "lilbee-health-dot" });
        const ok = await LilbeeClient.probe(url, CHECK_TIMEOUT_MS, this.plugin.readCurrentToken());
        dot.classList.add(ok ? "is-ok" : "is-error");
        statusEl.classList.add(ok ? "lilbee-health-ok" : "lilbee-health-error");
    }
 
    private async loadModels(container: HTMLElement): Promise<void> {
        container.empty();
        const chatContainer = container.createDiv({ cls: "lilbee-chat-container" });
        this.renderChatSection(chatContainer);
        const embeddingContainer = container.createDiv({ cls: "lilbee-embedding-container" });
        this.loadEmbeddingDropdown(embeddingContainer);
        const visionContainer = container.createDiv({ cls: "lilbee-vision-container" });
        this.renderVisionSection(visionContainer);
        const rerankerContainer = container.createDiv({ cls: "lilbee-reranker-container" });
        this.renderRerankerSection(rerankerContainer);
    }
 
    private renderChatSection(container: HTMLElement): void {
        Promise.all([
            this.plugin.api.config(),
            this.plugin.api.catalog({ task: MODEL_TASK.CHAT }),
            this.plugin.api.installedModels({ task: MODEL_TASK.CHAT }).catch(() => ({ models: [] })),
        ])
            .then(([cfg, catalogResult, installedResp]) => {
                const active = typeof cfg.chat_model === "string" ? cfg.chat_model : "";
                // Defensive client-side task filter: older server builds and
                // some frontier providers return rows tagged with a different
                // task than requested, which would surface embedding/vision
                // models in the chat dropdown.
                const catalogEntries = catalogResult.isOk()
                    ? catalogResult.value.models.filter((m) => m.task === MODEL_TASK.CHAT)
                    : [];
                this.renderChatPicker(container, active, catalogEntries, installedResp.models);
            })
            .catch(() => {
                // Connection status is shown via the Test button — no duplicate warning needed.
            });
    }
 
    private renderChatPicker(
        container: HTMLElement,
        active: string,
        catalogEntries: CatalogEntry[],
        installed: InstalledModel[],
    ): void {
        const section = container.createDiv("lilbee-model-section");
        new Setting(section).setName(MESSAGES.LABEL_CHAT_MODEL).setHeading();
 
        const activeSetting = new Setting(section)
            .setName(`${MESSAGES.LABEL_ACTIVE} chat model`)
            .setDesc(displayLabelForRef(active) || MESSAGES.LABEL_NOT_SET);
 
        const options = this.buildChatOptions(catalogEntries, installed);
        activeSetting.addDropdown((dropdown) => {
            for (const [value, label] of options) {
                dropdown.addOption(value, label);
            }
            dropdown.setValue(
                matchModelOption(
                    active,
                    options.map(([value]) => value),
                ),
            );
            dropdown.onChange(async (value) => {
                if (value === SEPARATOR_KEY) return;
                await this.handleChatChange(value, catalogEntries);
            });
        });
 
        const catalogEl = section.createDiv("lilbee-model-catalog");
        const table = catalogEl.createEl("table");
        const header = table.createEl("tr");
        header.createEl("th", { text: MESSAGES.LABEL_MODEL });
        header.createEl("th", { text: MESSAGES.LABEL_SIZE });
        header.createEl("th", { text: MESSAGES.LABEL_DESCRIPTION });
        header.createEl("th", { text: "" });
        for (const entry of catalogEntries) {
            this.renderChatCatalogRow(table, entry, active);
        }
    }
 
    private buildChatOptions(catalogEntries: CatalogEntry[], installed: InstalledModel[]): Array<[string, string]> {
        // Settings is a quick-pick of what's already on disk; downloads happen
        // in Browse Catalog. Showing 30 "(not installed)" entries here is
        // noise that pushes installed models off-screen.
        const installedRepos = new Set(installed.map((m) => extractHfRepo(m.name)));
        const opts: Array<[string, string]> = [];
        const featuredInstalled = catalogEntries.filter((e) => installedRepos.has(e.hf_repo));
        for (const entry of featuredInstalled) {
            const sourceTag = HOSTED_SOURCES.has(entry.source) ? ` [${entry.provider ?? entry.source}]` : "";
            opts.push([entry.hf_repo, `${entry.display_name}${sourceTag}`]);
        }
        // Hosted rows are selectable even when absent from the installed
        // registry — ollama always, frontier with a ready key. Skip any already
        // emitted above as an installed featured row.
        for (const [ref, label] of hostedOptions(catalogEntries)) {
            if (!installedRepos.has(ref)) opts.push([ref, label]);
        }
        const featuredRepos = new Set(catalogEntries.map((e) => e.hf_repo));
        const otherInstalled = installed
            .filter((m) => !featuredRepos.has(extractHfRepo(m.name)))
            .sort((a, b) => a.name.localeCompare(b.name));
        if (otherInstalled.length > 0) {
            opts.push([SEPARATOR_KEY, SEPARATOR_LABEL]);
            for (const m of otherInstalled) {
                opts.push([m.name, displayLabelForRef(m.name)]);
            }
        }
        return opts;
    }
 
    private async handleChatChange(value: string, catalogEntries: CatalogEntry[]): Promise<void> {
        const featuredEntry = catalogEntries.find((e) => e.hf_repo === value);
        if (featuredEntry && !featuredEntry.installed) {
            const modal = new ConfirmPullModal(this.app, {
                displayName: featuredEntry.display_name,
                sizeGb: featuredEntry.size_gb,
                minRamGb: featuredEntry.min_ram_gb,
                systemMemGb: getRelevantSystemMemoryGB(this.plugin.settings.serverMode),
            });
            modal.open();
            const confirmed = await modal.result;
            if (!confirmed) return;
            await this.pullAndSetChat(featuredEntry);
            return;
        }
        const label = featuredEntry?.display_name ?? displayLabelForRef(value);
        await this.applyChatSelection(value, label);
    }
 
    private async applyChatSelection(ref: string, label: string): Promise<void> {
        const result = await this.plugin.api.setChatModel(ref);
        if (result.isErr()) {
            new Notice(noticeForResultError(result.error, MESSAGES.NOTICE_FAILED_SET_MODEL(MODEL_TASK.CHAT)));
            return;
        }
        new Notice(MESSAGES.NOTICE_SET_MODEL(MESSAGES.LABEL_CHAT_MODEL, label || MESSAGES.LABEL_NOT_SET.toLowerCase()));
        void this.plugin.fetchActiveModel();
        this.render();
    }
 
    private async pullAndSetChat(entry: CatalogEntry): Promise<void> {
        const ok = await this.streamChatPull(entry);
        if (!ok) return;
        const setResult = await this.plugin.api.setChatModel(entry.hf_repo);
        if (setResult.isErr()) {
            new Notice(
                noticeForResultError(setResult.error, MESSAGES.ERROR_SET_MODEL.replace("{model}", entry.display_name)),
            );
        } else {
            new Notice(MESSAGES.NOTICE_MODEL_ACTIVATED_FULL(entry.display_name));
        }
        void this.plugin.fetchActiveModel();
        this.render();
    }
 
    private async streamChatPull(entry: CatalogEntry): Promise<boolean> {
        const taskId = this.plugin.enqueuePull(`Pull ${entry.display_name}`);
        if (taskId === null) {
            new Notice(MESSAGES.NOTICE_QUEUE_FULL);
            return false;
        }
        const controller = new AbortController();
        this.plugin.taskQueue.registerAbort(taskId, controller);
        try {
            for await (const event of this.plugin.api.pullModel(entry.hf_repo, "native", controller.signal)) {
                if (event.event === SSE_EVENT.PROGRESS) {
                    const d = event.data as { percent?: number; current?: number; total?: number };
                    const pct = percentFromSse(d);
                    if (pct !== undefined) {
                        this.plugin.taskQueue.update(taskId, pct, entry.display_name, {
                            current: d.current,
                            total: d.total,
                        });
                    }
                } else if (event.event === SSE_EVENT.ERROR) {
                    const msg = extractSseErrorMessage(event.data, MESSAGES.ERROR_UNKNOWN);
                    new Notice(`${MESSAGES.ERROR_PULL_MODEL.replace("{model}", entry.display_name)}: ${msg}`);
                    this.plugin.taskQueue.fail(taskId, msg);
                    return false;
                }
            }
        } catch (err) {
            if (err instanceof Error && err.name === ERROR_NAME.ABORT_ERROR) {
                new Notice(MESSAGES.NOTICE_PULL_CANCELLED);
                this.plugin.taskQueue.cancel(taskId);
            } else {
                const reason = errorMessage(err, MESSAGES.ERROR_UNKNOWN);
                new Notice(`${MESSAGES.ERROR_PULL_MODEL.replace("{model}", entry.display_name)}: ${reason}`);
                this.plugin.taskQueue.fail(taskId, reason);
            }
            return false;
        }
        this.plugin.taskQueue.complete(taskId);
        return true;
    }
 
    private renderChatCatalogRow(table: HTMLTableElement, entry: CatalogEntry, active: string): void {
        const row = table.createEl("tr");
        row.createEl("td", { text: entry.display_name });
        row.createEl("td", { text: `${entry.size_gb} GB` });
        row.createEl("td", { text: entry.description });
        const actionCell = row.createEl("td");
        // Wrap the action contents in an inner div so the cell stays a
        // proper table cell — display:flex on a <td> drops it out of
        // the table layout and any wrapped text in adjacent cells then
        // misaligns the row.
        const actions = actionCell.createDiv({ cls: "lilbee-model-actions" });
        if (entry.installed) {
            actions.createSpan({ text: MESSAGES.LABEL_INSTALLED, cls: "lilbee-installed" });
            const deleteBtn = actions.createEl("button", { cls: "lilbee-model-delete" });
            setIcon(deleteBtn, "trash-2");
            deleteBtn.setAttribute("aria-label", MESSAGES.LABEL_DELETE_MODEL);
            deleteBtn.addEventListener("click", () => void this.deleteChatEntry(deleteBtn, entry, active));
        } else {
            const btn = actions.createEl("button", { text: MESSAGES.BUTTON_PULL });
            btn.addEventListener("click", () => void this.pullAndSetChat(entry));
        }
    }
 
    private async deleteChatEntry(btn: HTMLButtonElement, entry: CatalogEntry, active: string): Promise<void> {
        const taskId = this.plugin.taskQueue.enqueue(`Remove ${entry.display_name}`, TASK_TYPE.DELETE);
        if (taskId === null) {
            new Notice(MESSAGES.NOTICE_QUEUE_FULL);
            return;
        }
        btn.disabled = true;
        this.plugin.taskQueue.update(taskId, -1, entry.display_name);
        const result = await this.plugin.api.deleteModel(entry.hf_repo, entry.source);
        if (result.isErr()) {
            new Notice(
                noticeForResultError(result.error, MESSAGES.ERROR_DELETE_MODEL.replace("{model}", entry.display_name)),
            );
            this.plugin.taskQueue.fail(taskId, errorMessage(result.error, result.error.message));
            btn.disabled = false;
            return;
        }
        this.plugin.taskQueue.complete(taskId);
        new Notice(MESSAGES.NOTICE_REMOVED(entry.display_name));
        if (extractHfRepo(active) === entry.hf_repo) {
            const clearResult = await this.plugin.api.setChatModel("");
            if (clearResult.isOk()) {
                this.plugin.activeModel = "";
            }
        }
        void this.plugin.fetchActiveModel();
        const modelsContainer = this.containerEl.querySelector(`.${CLS_MODELS_CONTAINER}`);
        if (modelsContainer) {
            await this.loadModels(modelsContainer as HTMLElement);
        }
    }
 
    private renderRerankCandidatesField(container: HTMLElement): void {
        const patch = debounce((...args: unknown[]) => {
            const num = args[0] as number;
            void this.patchRerankCandidates(num);
        }, DEBOUNCE_MS);
 
        new Setting(container)
            .setName(MESSAGES.LABEL_RERANKER_CANDIDATES)
            .setDesc(MESSAGES.DESC_RERANKER_CANDIDATES)
            .addText((text) => {
                text.setPlaceholder(MESSAGES.PLACEHOLDER_RERANK_CANDIDATES)
                    .setValue("")
                    .onChange((value) => {
                        const trimmed = value.trim();
                        if (trimmed === "") return;
                        const num = parseInt(trimmed, 10);
                        if (isNaN(num) || num < RERANK_CANDIDATES_MIN || num > RERANK_CANDIDATES_MAX) return;
                        patch.run(num);
                    });
                this.serverConfigInputs.set("rerank_candidates", text.inputEl);
            });
    }
 
    private async patchRerankCandidates(num: number): Promise<void> {
        try {
            await this.plugin.api.updateConfig({ rerank_candidates: num });
            new Notice(MESSAGES.NOTICE_FIELD_UPDATED(MESSAGES.LABEL_RERANKER_CANDIDATES));
        } catch {
            new Notice(MESSAGES.NOTICE_FAILED_UPDATE(MESSAGES.LABEL_RERANKER_CANDIDATES));
        }
    }
}
 
function appendStorageRow(parent: HTMLElement, label: string, bytes: number, detail?: string): void {
    const row = parent.createDiv({ cls: "lilbee-storage-row" });
    row.createSpan({ text: label, cls: "lilbee-storage-row-label" });
    row.createSpan({ text: formatDiskSize(bytes), cls: "lilbee-storage-row-bytes" });
    if (detail) row.createSpan({ text: detail, cls: "lilbee-storage-row-detail" });
}