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 | 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 1x 168x 168x 168x 168x 1x 1x 1x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 2x 2x 169x 169x 169x 169x 12x 12x 12x 11x 11x 10x 10x 8x 8x 9x 9x 8x 4x 3x 167x 167x 1002x 1002x 1002x 1002x 1002x 1002x 8x 7x 7x 6x 36x 36x 36x 7x 7x 7x 7x 7x 7x 7x 175x 174x 174x 174x 174x 167x 167x 167x 167x 167x 167x 167x 167x 167x 174x 174x 15x 14x 14x 28x 28x 28x 14x 279x 279x 32x 32x 247x 247x 40x 40x 40x 40x 40x 40x 40x 40x 1x 1x 40x 40x 7x 7x 3x 3x 2x 14x 14x 4x 4x 2x 2x 2x 167x 167x 2x 2x 167x 3x 3x 167x 167x 9x 9x 167x 167x 167x 334x 334x 1503x 1503x 334x 22x 22x 22x 23x 22x 221x 221x 221x 212x 212x 212x 212x 212x 360x 278x 92x 75x 84x 74x 12x 285x 285x 285x 285x 285x 285x 278x 278x 278x 628x 278x 278x 278x 278x 278x 288x 285x 285x 9x 9x 9x 285x 285x 285x 285x 285x 285x 285x 285x 284x 4x 280x 2x 278x 284x 284x 284x 282x 280x 278x 84x 17x 17x 339x 337x 337x 337x 18x 18x 126x 337x 15x 15x 322x 50x 50x 272x 12x 12x 260x 260x 260x 98x 98x 162x 134x 28x 15x 15x 45x 45x 45x 45x 45x 45x 45x 28x 28x 17x 56x 50x 50x 28x 28x 22x 21x 1x 12x 12x 12x 1x 1x 11x 15x 15x 15x 59x 59x 59x 59x 59x 59x 59x 55x 59x 3x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 157x 619x 619x 619x 156x 2x 156x 156x 96x 156x 156x 156x 554x 554x 458x 96x 156x 160x 159x 159x 159x 159x 619x 675x 675x 17x 15x 6x 1x 718x 157x 156x 156x 156x 156x 30x 29x 29x 29x 29x 43x 29x 29x 29x 174x 174x 116x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 1x 1x 43x 43x 43x 3x 40x 6x 6x 6x 6x 34x 1x 33x 33x 5x 1x 4x 4x 5x 29x 6x 6x 29x 6x 6x 6x 4x 29x 12x 4x 2x 2x 2x 2x 7x 7x 7x 7x 6x 6x 6x 1x 1x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 3x 3x 3x 3x 16x 16x 16x 16x 4x 4x 4x 4x 12x 12x 12x 12x 12x 20x 26x 26x 3x 23x 2x 21x 4x 4x 4x 17x 17x 17x 19x 1x 1x 18x 18x 18x 18x 17x 17x 17x 1x 1x 16x 16x 16x 16x 16x 8x 4x 4x 4x 3x 4x 3x 3x 3x 3x 3x 5x 2x 2x 3x 3x 3x 5x 8x 8x 8x 1x 1x 1x 1x 7x 7x 7x 7x 7x 12x 12x 12x 1x 1x 6x 6x 5x 5x | import { App, Modal, Notice, setIcon } from "obsidian";
import type LilbeePlugin from "../main";
import type { CatalogEntry, CatalogResponse, CatalogTab, CatalogViewMode, KeyStatus, ModelTask } from "../types";
import {
CATALOG_SOURCE,
CATALOG_TAB,
KEY_STATUS,
MODEL_COMPAT,
MODEL_INFO_SOURCE,
MODEL_TASK,
SSE_EVENT,
TASK_TYPE,
CATALOG_VIEW_MODE,
ERROR_NAME,
} from "../types";
import { MESSAGES, FILTERS, CATALOG_FILTERS } from "../locales/en";
import { extractHfRepo, nativeModelRef } from "../utils/model-ref";
import { ConfirmModal } from "./confirm-modal";
import { ConfirmPullModal } from "./confirm-pull-modal";
import {
bindEscapeToClose,
debounce,
DEBOUNCE_MS,
formatAbbreviatedCount,
percentFromSse,
errorMessage,
extractSseErrorMessage,
noticeForResultError,
getRelevantSystemMemoryGB,
} from "../utils";
import { applyEmbeddingModel } from "../utils/reindex";
import { noticeModelWarnings } from "../utils/model-warnings";
import { renderModelCard, renderCompatTag } from "../components/model-card";
import { renderModelDetail } from "../components/model-detail";
import { ModelInfoModal } from "./model-info-modal";
import {
deepLinkToApiKeySettings,
forYouRail,
freshRail,
groupByProvider,
hasReadyHostedRow,
hostedRowsOnly,
localRowsOnly,
renderKeyStatusPill,
renderProviderPill,
tabIdToTask,
taskToTabId,
yourCollectionRail,
} from "./catalog-helpers";
const PAGE_SIZE = 20;
// Page size for search; matches are spread across the hub.
const SEARCH_PAGE_SIZE = 50;
const SCROLL_BOTTOM_THRESHOLD_PX = 200;
// Follow-up fetches per fill: five pages cover 45 hosted rows (three pages, as measured) and two native pages.
const MAX_FILL_FOLLOW_UPS = 4;
const DRAWER_BREAKPOINT_PX = 800;
const DRAWER_FOCUS_DEBOUNCE_MS = 30;
type TaskFilter = (typeof FILTERS.TASK)[keyof typeof FILTERS.TASK];
type SizeFilter = "" | typeof FILTERS.SIZE.SMALL | typeof FILTERS.SIZE.MEDIUM | typeof FILTERS.SIZE.LARGE;
type SortFilter = (typeof FILTERS.SORT)[keyof typeof FILTERS.SORT];
/**
* The catalog modal's task tabs carry a local/hosted sub-toggle. View-only
* state distinct from the wire `CatalogSource`: "hosted" spans frontier + ollama.
*/
type SubTab = "local" | "hosted";
const SUB_TAB = {
LOCAL: "local",
HOSTED: "hosted",
} as const satisfies Record<string, SubTab>;
/** What started a fill: opening or filtering the view, or a Load more click. */
type FillTrigger = "auto" | "load-more";
const FILL_TRIGGER = {
AUTO: "auto",
LOAD_MORE: "load-more",
} as const satisfies Record<string, FillTrigger>;
const TASK_SECTION_LABEL: Record<ModelTask, string> = {
[MODEL_TASK.CHAT]: MESSAGES.LABEL_SECTION_CHAT,
[MODEL_TASK.VISION]: MESSAGES.LABEL_SECTION_VISION,
[MODEL_TASK.EMBEDDING]: MESSAGES.LABEL_SECTION_EMBEDDING,
[MODEL_TASK.RERANK]: MESSAGES.LABEL_SECTION_RERANK,
};
interface TabSpec {
id: CatalogTab;
label: string;
}
const TAB_SPECS: readonly TabSpec[] = [
{ id: CATALOG_TAB.DISCOVER, label: MESSAGES.TAB_DISCOVER },
{ id: CATALOG_TAB.CHAT, label: MESSAGES.TAB_CHAT_MODELS },
{ id: CATALOG_TAB.EMBED, label: MESSAGES.TAB_EMBED_MODELS },
{ id: CATALOG_TAB.VISION, label: MESSAGES.TAB_VISION_MODELS },
{ id: CATALOG_TAB.RERANK, label: MESSAGES.TAB_RERANK_MODELS },
{ id: CATALOG_TAB.LIBRARY, label: MESSAGES.TAB_LIBRARY },
];
interface RailSpec {
heading: string;
help: string;
rows: CatalogEntry[];
}
export class CatalogModal extends Modal {
private plugin: LilbeePlugin;
private filterTask: TaskFilter = "";
private filterSize: SizeFilter = "";
private filterSort: SortFilter = FILTERS.SORT.FEATURED;
private filterSearch = "";
private offset = 0;
// The query the offset was fetched under.
private fetchedQuery = "";
private hasMore = false;
// Hosted rows lead the listing; true when the last page had room for rows after them.
private pastHostedRows = false;
// The fill stopped while the server still had rows; the results offer Load more.
private canLoadMore = false;
private isFetching = false;
private fetchGeneration = 0;
private catalogController: AbortController | null = null;
private modalClosed = true;
private entries: CatalogEntry[] = [];
private resultsEl: HTMLElement | null = null;
private viewMode: CatalogViewMode = CATALOG_VIEW_MODE.GRID;
private sortColumn = "";
private sortAscending = true;
private viewToggleBtn: HTMLElement | null = null;
private debouncedSearch: () => void;
private cancelDebouncedSearch: () => void;
private currentTab: SubTab = SUB_TAB.LOCAL;
private subTabBarEl: HTMLElement | null = null;
private hostedTabBtn: HTMLElement | null = null;
private activeTab: CatalogTab;
private mainTabBarEl: HTMLElement | null = null;
private bodyEl: HTMLElement | null = null;
private drawerEl: HTMLElement | null = null;
private drawerContentEl: HTMLElement | null = null;
private drawerToggleBtn: HTMLElement | null = null;
// Drawer starts collapsed: the cards are too cramped at the default modal
// width when the 320px drawer eats half the row. Users discover details via
// the per-card 'i' info button (Model Info modal); the drawer toggle in
// the modal header lets them switch to the passive-panel layout.
private drawerCollapsedByUser = true;
private focusedRepo: string | null = null;
private focusDebounceTimeout: number | null = null;
/** Set only by openCatalog; resolves the caller waiting behind this modal. */
private dismissed: (() => void) | null = null;
/**
* @param initialTaskFilter Pre-select a task tab when opening (e.g.
* from the wizard's Vision step so users land on vision-only results).
* Defaults to "" which shows all tasks.
* @param initialTab Pre-select one of the top-level catalog tabs. When
* omitted, the modal restores the user's last-used tab from settings.
*/
constructor(app: App, plugin: LilbeePlugin, initialTaskFilter: TaskFilter = "", initialTab?: CatalogTab) {
super(app);
this.plugin = plugin;
this.filterTask = initialTaskFilter;
this.activeTab = initialTab ?? plugin.settings.lastCatalogTab ?? CATALOG_TAB.DISCOVER;
if (initialTab === undefined && initialTaskFilter !== "") {
this.activeTab = taskToTabId(initialTaskFilter);
}
const searchDebounced = debounce(() => this.resetAndFetch(), DEBOUNCE_MS);
this.debouncedSearch = searchDebounced.run;
this.cancelDebouncedSearch = searchDebounced.cancel;
bindEscapeToClose(this);
}
/** Opens the catalog over whatever is already on screen and resolves when it closes. */
openCatalog(): Promise<void> {
return new Promise((resolve) => {
this.dismissed = resolve;
this.open();
});
}
onOpen(): void {
this.modalClosed = false;
const { contentEl } = this;
contentEl.empty();
contentEl.addClass("lilbee-catalog-modal");
contentEl.createEl("h2", { text: MESSAGES.TITLE_MODEL_CATALOG });
this.renderMainTabBar(contentEl);
this.renderSubTabBar(contentEl);
this.renderFilterBar(contentEl);
this.bodyEl = contentEl.createDiv({ cls: "lilbee-catalog-body lilbee-catalog-body-with-drawer" });
this.resultsEl = this.bodyEl.createDiv({ cls: "lilbee-catalog-results lilbee-catalog-tab-content" });
this.resultsEl.addEventListener("scroll", this.onScroll);
this.renderDrawer(this.bodyEl);
this.bodyEl.addEventListener("focusin", this.onCardFocus);
this.bodyEl.addEventListener("pointerover", this.onCardFocus);
contentEl.addEventListener("keydown", this.onKeyDown);
this.applyDrawerVisibility();
this.applyTabToFilter();
this.resetAndFetch();
}
private renderDrawer(parent: HTMLElement): void {
this.drawerEl = parent.createDiv({ cls: "lilbee-catalog-drawer" });
const header = this.drawerEl.createDiv({ cls: "lilbee-catalog-drawer-header" });
this.drawerToggleBtn = header.createEl("button", {
cls: "lilbee-catalog-drawer-toggle",
text: MESSAGES.BUTTON_DRAWER_TOGGLE,
});
this.drawerToggleBtn.addEventListener("click", () => this.toggleDrawer());
this.drawerContentEl = this.drawerEl.createDiv({ cls: "lilbee-catalog-drawer-content" });
this.drawerContentEl.createEl("p", {
cls: "lilbee-catalog-drawer-empty",
text: MESSAGES.LABEL_DRAWER_NO_SELECTION,
});
}
private toggleDrawer(): void {
this.drawerCollapsedByUser = !this.drawerCollapsedByUser;
this.applyDrawerVisibility();
}
private applyDrawerVisibility(): void {
/* v8 ignore next 2 */
if (!this.drawerEl || !this.bodyEl) return;
const narrow = typeof window !== "undefined" && window.innerWidth < DRAWER_BREAKPOINT_PX;
const collapsed = narrow || this.drawerCollapsedByUser;
this.drawerEl.toggleClass("lilbee-catalog-drawer-collapsed", collapsed);
this.bodyEl.toggleClass("lilbee-catalog-body-with-drawer", !collapsed);
}
private onCardFocus = (e: Event): void => {
const card = findCardElement(e.target);
if (!card) return;
const repo = card.dataset.repo;
if (!repo || repo === this.focusedRepo) return;
if (this.focusDebounceTimeout !== null) window.clearTimeout(this.focusDebounceTimeout);
this.focusDebounceTimeout = window.setTimeout(() => {
this.focusedRepo = repo;
this.updateDrawerForRepo(repo);
}, DRAWER_FOCUS_DEBOUNCE_MS);
};
private updateDrawerForRepo(repo: string): void {
/* v8 ignore next 2 */
if (!this.drawerContentEl) return;
const entry = this.entries.find((e) => e.hf_repo === repo);
if (!entry) return;
renderModelDetail(entry, this.drawerContentEl);
}
private focusedEntry(): CatalogEntry | null {
if (this.focusedRepo === null) return null;
return this.entries.find((e) => e.hf_repo === this.focusedRepo) ?? null;
}
private renderMainTabBar(parent: HTMLElement): void {
this.mainTabBarEl = parent.createDiv({ cls: "lilbee-catalog-tab-bar lilbee-catalog-main-tab-bar" });
for (const spec of TAB_SPECS) {
const btn = this.mainTabBarEl.createEl("button", { cls: "lilbee-catalog-tab" });
btn.dataset.tabId = spec.id;
btn.createSpan({ text: spec.label });
btn.setAttribute("aria-selected", spec.id === this.activeTab ? "true" : "false");
if (spec.id === this.activeTab) btn.addClass("lilbee-catalog-tab-active");
btn.addEventListener("click", () => this.switchMainTab(spec.id));
}
}
private switchMainTab(tab: CatalogTab): void {
if (this.activeTab === tab) return;
this.activeTab = tab;
if (this.mainTabBarEl) {
for (const btn of Array.from(this.mainTabBarEl.children) as HTMLElement[]) {
const isActive = btn.dataset.tabId === tab;
btn.toggleClass("lilbee-catalog-tab-active", isActive);
btn.setAttribute("aria-selected", isActive ? "true" : "false");
}
}
this.plugin.settings.lastCatalogTab = tab;
void this.plugin.saveSettings();
// Reset to the local sub-tab when leaving a task tab — hosted state shouldn't persist.
this.currentTab = SUB_TAB.LOCAL;
this.applyTabToFilter();
this.updateSubTabBarVisibility();
this.updateViewToggleVisibility();
this.resetAndFetch();
}
private updateViewToggleVisibility(): void {
if (!this.viewToggleBtn) return;
// Discover renders horizontal rails — list/grid doesn't apply.
const showToggle = this.activeTab !== CATALOG_TAB.DISCOVER;
this.viewToggleBtn.style.display = showToggle ? "" : "none";
}
private applyTabToFilter(): void {
const task = tabIdToTask(this.activeTab);
this.filterTask = task ?? "";
}
private renderSubTabBar(parent: HTMLElement): void {
this.subTabBarEl = parent.createDiv({ cls: "lilbee-catalog-tab-bar lilbee-catalog-sub-tab-bar" });
const localBtn = this.subTabBarEl.createEl("button", {
text: MESSAGES.TAB_LOCAL,
cls: "lilbee-catalog-tab lilbee-catalog-tab-active",
});
localBtn.setAttribute("aria-selected", "true");
localBtn.addEventListener("click", () => this.switchSubTab(SUB_TAB.LOCAL));
this.hostedTabBtn = this.subTabBarEl.createEl("button", {
text: MESSAGES.TAB_FRONTIER,
cls: "lilbee-catalog-tab",
});
this.hostedTabBtn.setAttribute("aria-selected", "false");
this.hostedTabBtn.hide();
this.hostedTabBtn.addEventListener("click", () => this.switchSubTab(SUB_TAB.HOSTED));
this.updateSubTabBarVisibility();
}
private updateSubTabBarVisibility(): void {
/* v8 ignore next 2 */
if (!this.subTabBarEl) return;
const showSubTabs = tabIdToTask(this.activeTab) !== null;
this.subTabBarEl.style.display = showSubTabs ? "" : "none";
}
private switchSubTab(tab: SubTab): void {
if (this.currentTab === tab) return;
this.currentTab = tab;
/* v8 ignore next 2 */
if (!this.subTabBarEl) return;
for (const btn of Array.from(this.subTabBarEl.children) as HTMLElement[]) {
const isActive =
(tab === SUB_TAB.LOCAL && btn.textContent === MESSAGES.TAB_LOCAL) ||
(tab === SUB_TAB.HOSTED && btn.textContent === MESSAGES.TAB_FRONTIER);
btn.toggleClass("lilbee-catalog-tab-active", isActive);
btn.setAttribute("aria-selected", isActive ? "true" : "false");
}
this.renderResults();
}
private updateHostedTabVisibility(): void {
/* v8 ignore next 2 */
if (!this.hostedTabBtn) return;
const showHosted = tabIdToTask(this.activeTab) !== null && hasReadyHostedRow(this.entries);
if (showHosted) {
this.hostedTabBtn.show();
return;
}
this.hostedTabBtn.hide();
// Bounce the user home if a refetch revoked the only ready hosted row.
if (this.currentTab === SUB_TAB.HOSTED) this.switchSubTab(SUB_TAB.LOCAL);
}
onClose(): void {
this.modalClosed = true;
this.cancelDebouncedSearch();
this.catalogController?.abort();
this.resultsEl?.removeEventListener("scroll", this.onScroll);
this.bodyEl?.removeEventListener("focusin", this.onCardFocus);
this.bodyEl?.removeEventListener("pointerover", this.onCardFocus);
this.contentEl.removeEventListener("keydown", this.onKeyDown);
if (this.focusDebounceTimeout !== null) {
window.clearTimeout(this.focusDebounceTimeout);
this.focusDebounceTimeout = null;
}
this.dismissed?.();
this.dismissed = null;
}
private onScroll = (): void => {
if (!this.resultsEl || this.isFetching || !this.hasMore) return;
const { scrollTop, clientHeight, scrollHeight } = this.resultsEl;
if (scrollTop + clientHeight >= scrollHeight - SCROLL_BOTTOM_THRESHOLD_PX) {
void this.fetchPage();
}
};
private onKeyDown = (e: KeyboardEvent): void => {
if (e.key === "i" && !isTextInputTarget(e.target)) {
const entry = this.focusedEntry();
if (entry) {
e.preventDefault();
e.stopPropagation();
new ModelInfoModal(this.app, this.plugin, { kind: MODEL_INFO_SOURCE.CATALOG, entry }).open();
}
}
};
private renderFilterBar(parent: HTMLElement): void {
const filters = parent.createDiv({ cls: "lilbee-catalog-filters" });
this.renderSelect(filters, "lilbee-catalog-filter-size", CATALOG_FILTERS.SIZE, (v) => {
this.filterSize = v as SizeFilter;
this.resetAndFetch();
});
this.renderSelect(filters, "lilbee-catalog-filter-sort", CATALOG_FILTERS.SORT, (v) => {
this.filterSort = v as SortFilter;
this.resetAndFetch();
});
const searchInput = filters.createEl("input", {
cls: "lilbee-catalog-search",
placeholder: MESSAGES.PLACEHOLDER_SEARCH_MODELS,
attr: { type: "text" },
});
searchInput.addEventListener("input", () => {
this.filterSearch = searchInput.value;
this.debouncedSearch();
});
this.viewToggleBtn = filters.createEl("button", {
text: MESSAGES.LABEL_SWITCH_TO_LIST,
cls: "lilbee-catalog-view-toggle",
});
this.viewToggleBtn.addEventListener("click", () => this.toggleView());
this.updateViewToggleVisibility();
}
private renderSelect(
parent: HTMLElement,
cls: string,
options: ReadonlyArray<readonly [string, string]>,
onChange: (value: string) => void,
): void {
const select = parent.createEl("select", { cls });
for (const [value, label] of options) {
const opt = select.createEl("option", { text: label });
opt.value = value;
}
select.addEventListener("change", () => onChange(select.value));
}
private toggleView(): void {
this.viewMode = this.viewMode === CATALOG_VIEW_MODE.GRID ? CATALOG_VIEW_MODE.LIST : CATALOG_VIEW_MODE.GRID;
this.updateToggleLabel();
this.renderResults();
}
private updateToggleLabel(): void {
if (!this.viewToggleBtn) return;
this.viewToggleBtn.textContent =
this.viewMode === CATALOG_VIEW_MODE.GRID ? MESSAGES.LABEL_SWITCH_TO_LIST : MESSAGES.LABEL_SWITCH_TO_GRID;
}
private clearResults(): void {
this.entries = [];
this.canLoadMore = false;
if (this.resultsEl) this.resultsEl.empty();
}
private resetAndFetch(): void {
this.fetchGeneration++;
this.catalogController?.abort();
this.offset = 0;
this.clearResults();
void this.fetchPage();
}
private pageLimit(query: string): number {
return query ? SEARCH_PAGE_SIZE : PAGE_SIZE;
}
/** The server has rows the active view may need: the hosted prefix, then one page of native rows. */
private wantsMoreRows(): boolean {
if (!this.hasMore) return false;
if (!this.pastHostedRows) return true;
return localRowsOnly(this.entries).length < this.pageLimit(this.fetchedQuery);
}
/** The Library's installed-only pages past the hosted rows are sparse: they load only on request, until one adds a row. */
private mayFetchAutomatically(followUps: number, trigger: FillTrigger, addedRows: number): boolean {
if (followUps <= 0) return false;
if (!(this.pastHostedRows && this.activeTab === CATALOG_TAB.LIBRARY)) return true;
return trigger === FILL_TRIGGER.LOAD_MORE && addedRows === 0;
}
private catalogParams(query: string): Parameters<typeof this.plugin.api.catalog>[0] {
const params: Parameters<typeof this.plugin.api.catalog>[0] = {
limit: this.pageLimit(query),
offset: this.offset,
sort: this.filterSort,
};
if (this.filterTask) params.task = this.filterTask;
if (this.filterSize) params.size = this.filterSize;
if (query) params.search = query;
if (this.activeTab === CATALOG_TAB.LIBRARY) params.installed = true;
return params;
}
/** Returns the number of native rows the page added. */
private applyPage(response: CatalogResponse): number {
this.hasMore = response.has_more;
this.canLoadMore = false;
this.pastHostedRows = hostedRowsOnly(response.models).length < response.limit;
// Filtered by task again; some servers and frontier providers tag rows loosely.
const filtered = this.filterTask ? response.models.filter((m) => m.task === this.filterTask) : response.models;
this.entries.push(...filtered);
// The server's window, not the rows received: a page can hold fewer rows than limit.
this.offset = response.offset + response.limit;
this.updateHostedTabVisibility();
this.renderResults();
return localRowsOnly(filtered).length;
}
private async fetchPage(followUps = MAX_FILL_FOLLOW_UPS, trigger: FillTrigger = FILL_TRIGGER.AUTO): Promise<void> {
if (this.isFetching) return;
const query = this.filterSearch;
// The offset belongs to one query; a different term restarts the result set.
if (query !== this.fetchedQuery) {
this.fetchedQuery = query;
this.offset = 0;
this.clearResults();
}
this.isFetching = true;
// Capture the request generation so a stale response (a filter changed
// while this page was in flight) can be discarded instead of rendering
// under the new filter.
const generation = this.fetchGeneration;
const controller = new AbortController();
this.catalogController = controller;
let superseded = false;
let added: number | null = null;
try {
const result = await this.plugin.api.catalog({
...this.catalogParams(query),
signal: controller.signal,
});
if (controller.signal.aborted || generation !== this.fetchGeneration) {
superseded = true;
} else if (result.isErr()) {
new Notice(noticeForResultError(result.error, MESSAGES.ERROR_LOAD_CATALOG));
} else {
added = this.applyPage(result.value);
}
} finally {
this.isFetching = false;
this.catalogController = null;
}
if (this.modalClosed) return;
if (superseded) return this.fetchPage();
if (added !== null) await this.continueFill(followUps, trigger, added);
}
private async continueFill(followUps: number, trigger: FillTrigger, addedRows: number): Promise<void> {
if (!this.wantsMoreRows()) return;
if (this.mayFetchAutomatically(followUps, trigger, addedRows)) return this.fetchPage(followUps - 1, trigger);
this.canLoadMore = true;
this.renderResults();
}
private renderResults(): void {
if (!this.resultsEl) return;
this.resultsEl.empty();
this.renderActiveView();
// Hosted rows lead the listing, so the Hosted sub-tab is complete once shown.
if (this.canLoadMore && this.currentTab !== SUB_TAB.HOSTED) this.renderLoadMore(this.resultsEl);
}
private renderLoadMore(parent: HTMLElement): void {
const btn = parent.createEl("button", { cls: "lilbee-catalog-load-more", text: MESSAGES.BUTTON_LOAD_MORE });
btn.addEventListener("click", () => void this.fetchPage(MAX_FILL_FOLLOW_UPS, FILL_TRIGGER.LOAD_MORE));
}
/** Empty-state text: nothing matches only once the server has no more rows. */
private renderEmpty(parent: HTMLElement): void {
parent.createDiv({
cls: "lilbee-catalog-empty",
text: this.hasMore ? MESSAGES.LABEL_NO_MODELS_LOADED_YET : MESSAGES.LABEL_NO_MODELS_FOUND,
});
}
private renderActiveView(): void {
if (this.activeTab === CATALOG_TAB.DISCOVER) {
this.renderDiscoverTab();
return;
}
if (this.activeTab === CATALOG_TAB.LIBRARY) {
this.renderLibraryTab();
return;
}
if (this.currentTab === SUB_TAB.HOSTED) {
this.renderHostedResults();
return;
}
this.renderTaskTabLocal();
}
private renderTaskTabLocal(): void {
/* v8 ignore next 2 */
if (!this.resultsEl) return;
const localEntries = localRowsOnly(this.entries);
if (localEntries.length === 0) {
this.renderEmpty(this.resultsEl);
return;
}
if (this.viewMode === CATALOG_VIEW_MODE.GRID) {
this.renderGridView(localEntries);
} else {
this.renderListView(localEntries);
}
}
private renderDiscoverTab(): void {
/* v8 ignore next 2 */
if (!this.resultsEl) return;
const rails: RailSpec[] = [
{
heading: MESSAGES.RAIL_FOR_YOU,
help: MESSAGES.RAIL_FOR_YOU_HELP,
rows: forYouRail(this.entries, this.plugin.settings.serverMode),
},
{
heading: MESSAGES.RAIL_YOUR_COLLECTION,
help: MESSAGES.RAIL_YOUR_COLLECTION_HELP,
rows: yourCollectionRail(this.entries),
},
{
heading: MESSAGES.RAIL_FRESH,
help: MESSAGES.RAIL_FRESH_HELP,
rows: freshRail(this.entries),
},
];
for (const rail of rails) {
this.renderRail(rail);
}
}
private renderRail(rail: RailSpec): void {
/* v8 ignore next 2 */
if (!this.resultsEl) return;
const railEl = this.resultsEl.createDiv({ cls: "lilbee-discover-rail" });
const heading = railEl.createDiv({ cls: "lilbee-discover-rail-heading" });
heading.createSpan({ text: rail.heading });
heading.createSpan({ cls: "lilbee-discover-rail-heading-help", text: rail.help });
const cards = railEl.createDiv({ cls: "lilbee-discover-rail-cards" });
if (rail.rows.length === 0) {
cards.createDiv({ cls: "lilbee-discover-rail-empty", text: MESSAGES.RAIL_NO_ITEMS });
return;
}
for (const entry of rail.rows) {
this.renderCard(cards, entry);
}
}
private renderLibraryTab(): void {
/* v8 ignore next 2 */
if (!this.resultsEl) return;
// Hosted rows are installed=true server-side; the Library is the on-disk view.
const installed = localRowsOnly(this.entries).filter((e) => e.installed);
if (installed.length === 0) {
this.renderEmpty(this.resultsEl);
return;
}
if (this.viewMode === CATALOG_VIEW_MODE.GRID) {
this.renderGridView(installed);
} else {
this.renderListView(installed);
}
}
private renderHostedResults(): void {
/* v8 ignore next 2 */
if (!this.resultsEl) return;
// Sub-toggle is only visible on task tabs, so taskForTab is always non-null here.
const taskForTab = tabIdToTask(this.activeTab);
const allHosted = hostedRowsOnly(this.entries);
/* v8 ignore next 2 */
const rows = taskForTab === null ? allHosted : allHosted.filter((r) => r.task === taskForTab);
if (rows.length === 0) {
this.resultsEl.createDiv({
cls: "lilbee-catalog-empty",
text: MESSAGES.LABEL_NO_MODELS_FOUND,
});
return;
}
for (const [provider, group] of groupByProvider(rows)) {
this.resultsEl.createDiv({ cls: "lilbee-catalog-section-heading", text: provider });
const list = this.resultsEl.createDiv({ cls: "lilbee-catalog-frontier-list" });
for (const row of group) {
this.renderHostedRow(list, row);
}
}
}
private renderHostedRow(parent: HTMLElement, row: CatalogEntry): void {
const rowEl = parent.createDiv({ cls: "lilbee-frontier-row" });
const nameEl = rowEl.createSpan({ cls: "lilbee-frontier-row-name", text: row.display_name });
const provider = row.provider ?? "";
renderProviderPill(nameEl, provider);
// Local-server rows (Ollama, LM Studio) need no API key — provider pill only.
const keyStatus: KeyStatus = row.key_status ?? KEY_STATUS.MISSING_KEY;
if (row.source === CATALOG_SOURCE.FRONTIER) {
renderKeyStatusPill(nameEl, keyStatus);
}
rowEl.addEventListener("click", () => {
if (row.source === CATALOG_SOURCE.FRONTIER && keyStatus === KEY_STATUS.MISSING_KEY) {
this.close();
deepLinkToApiKeySettings(this.app, provider);
return;
}
void this.handleUseHosted(row);
});
}
private async handleUseHosted(row: CatalogEntry): Promise<void> {
const result = await this.setActiveFor(row);
if (result.isErr()) {
new Notice(noticeForResultError(result.error, MESSAGES.ERROR_SET_MODEL.replace("{model}", row.hf_repo)));
return;
}
void this.plugin.fetchActiveModel();
this.plugin.refreshSettingsTab();
this.plugin.refreshOpenChatRails();
new Notice(MESSAGES.NOTICE_MODEL_ACTIVATED(this.activatedRefFor(row)));
this.close();
}
private renderGridView(entries: CatalogEntry[]): void {
if (!this.resultsEl) return;
const picks = entries.filter((e) => e.featured);
const installed = entries.filter((e) => !e.featured && e.installed);
const rest = entries.filter((e) => !e.featured && !e.installed);
if (picks.length > 0)
this.renderSection(MESSAGES.LABEL_OUR_PICKS, picks, "lilbee-catalog-section-heading-featured");
if (installed.length > 0) this.renderSection(MESSAGES.LABEL_SECTION_INSTALLED, installed);
for (const [task, group] of this.groupByTask(rest)) {
this.renderSection(TASK_SECTION_LABEL[task] ?? task, group);
}
this.renderViewToggleCta();
}
private groupByTask(entries: CatalogEntry[]): [ModelTask, CatalogEntry[]][] {
const groups = new Map<ModelTask, CatalogEntry[]>();
for (const entry of entries) {
const group = groups.get(entry.task);
if (group) {
group.push(entry);
} else {
groups.set(entry.task, [entry]);
}
}
return [...groups.entries()];
}
private renderSection(heading: string, entries: CatalogEntry[], headingCls?: string): void {
if (!this.resultsEl) return;
const headingEl = this.resultsEl.createDiv({
cls: "lilbee-catalog-section-heading",
text: heading,
});
if (headingCls) headingEl.addClass(headingCls);
const grid = this.resultsEl.createDiv({ cls: "lilbee-catalog-grid" });
for (const entry of entries) {
this.renderCard(grid, entry);
}
}
private renderCard(container: HTMLElement, entry: CatalogEntry): void {
const isActive = this.isActiveEntry(entry);
renderModelCard(container, entry, {
showActions: true,
isActive,
onPull: (e) => this.handlePull(e),
onUse: (e, btn) => void this.handleUse(e, btn),
onRemove: (e, btn) => this.handleRemove(e, btn),
onInfo: (e) =>
new ModelInfoModal(this.app, this.plugin, { kind: MODEL_INFO_SOURCE.CATALOG, entry: e }).open(),
});
}
private isActiveEntry(entry: CatalogEntry): boolean {
return extractHfRepo(this.plugin.activeModel) === entry.hf_repo;
}
private renderViewToggleCta(): void {
if (!this.resultsEl) return;
const cta = this.resultsEl.createDiv({ cls: "lilbee-view-toggle-cta" });
cta.createSpan({ text: MESSAGES.LABEL_VIEW_TOGGLE_CTA });
const btn = cta.createEl("button", { text: MESSAGES.LABEL_SWITCH_TO_LIST });
btn.addEventListener("click", () => this.toggleView());
}
private renderListView(entries: CatalogEntry[]): void {
if (!this.resultsEl) return;
const listEl = this.resultsEl.createDiv({ cls: "lilbee-catalog-list" });
this.renderListHeader(listEl);
const sorted = this.sortEntries(entries);
for (const entry of sorted) {
this.renderListRow(listEl, entry);
}
}
private renderListHeader(listEl: HTMLElement): void {
const header = listEl.createDiv({ cls: "lilbee-catalog-list-header" });
const cols = [
{ key: "name", label: MESSAGES.LABEL_NAME, cls: "lilbee-catalog-list-col-name" },
{ key: "task", label: MESSAGES.LABEL_TASK, cls: "lilbee-catalog-list-col-task" },
{ key: "size", label: MESSAGES.LABEL_SIZE, cls: "lilbee-catalog-list-col-size" },
{ key: "downloads", label: MESSAGES.LABEL_DOWNLOADS, cls: "lilbee-catalog-list-col-downloads" },
{ key: "info", label: "", cls: "lilbee-catalog-list-col-info" },
{ key: "action", label: "", cls: "lilbee-catalog-list-col-action" },
];
for (const col of cols) {
const el = header.createSpan({ text: col.label, cls: col.cls });
if (col.key !== "action" && col.key !== "info") {
el.addEventListener("click", () => this.handleSort(col.key));
}
}
}
private renderListRow(listEl: HTMLElement, entry: CatalogEntry): void {
const row = listEl.createDiv({ cls: "lilbee-catalog-list-row" });
if (entry.compat === MODEL_COMPAT.UNSUPPORTED) row.addClass("is-unsupported");
const nameText = entry.featured ? `★ ${entry.display_name}` : entry.display_name;
const nameEl = row.createSpan({ text: nameText, cls: "lilbee-catalog-list-col-name" });
nameEl.setAttribute("title", entry.display_name);
renderCompatTag(nameEl, entry);
row.createSpan({ text: entry.task, cls: "lilbee-catalog-list-col-task" });
row.createSpan({ text: `${entry.size_gb} GB`, cls: "lilbee-catalog-list-col-size" });
row.createSpan({
text: formatAbbreviatedCount(entry.downloads),
cls: "lilbee-catalog-list-col-downloads",
});
const infoEl = row.createDiv({ cls: "lilbee-catalog-list-col-info" });
const infoBtn = infoEl.createEl("button", {
cls: "lilbee-model-card-info",
attr: {
type: "button",
"aria-label": MESSAGES.LABEL_MODEL_INFO_BTN,
title: MESSAGES.LABEL_MODEL_INFO_BTN,
},
});
setIcon(infoBtn, "info");
infoBtn.addEventListener("click", (e: Event) => {
e.stopPropagation();
new ModelInfoModal(this.app, this.plugin, { kind: MODEL_INFO_SOURCE.CATALOG, entry }).open();
});
const actionEl = row.createDiv({ cls: "lilbee-catalog-list-col-action" });
const isActive = this.isActiveEntry(entry);
if (isActive) {
actionEl.createSpan({ text: MESSAGES.LABEL_ACTIVE, cls: "lilbee-catalog-active" });
} else if (entry.installed) {
const useBtn = actionEl.createEl("button", { text: MESSAGES.BUTTON_USE, cls: "lilbee-catalog-use" });
useBtn.addEventListener("click", () => void this.handleUse(entry, useBtn));
const removeBtn = actionEl.createEl("button", {
text: MESSAGES.BUTTON_REMOVE,
cls: "lilbee-catalog-remove",
});
removeBtn.addEventListener("click", () => this.handleRemove(entry, removeBtn));
} else if (entry.compat === MODEL_COMPAT.UNSUPPORTED) {
actionEl.createEl("button", {
text: MESSAGES.BUTTON_PULL,
cls: "lilbee-catalog-pull is-gated",
attr: { disabled: "true", title: MESSAGES.TOOLTIP_PULL_UNSUPPORTED },
});
} else {
const pullBtn = actionEl.createEl("button", { text: MESSAGES.BUTTON_PULL, cls: "lilbee-catalog-pull" });
pullBtn.addEventListener("click", () => this.handlePull(entry));
}
}
private handleSort(column: string): void {
if (this.sortColumn === column) {
this.sortAscending = !this.sortAscending;
} else {
this.sortColumn = column;
this.sortAscending = true;
}
this.renderResults();
}
private sortEntries(entries: CatalogEntry[]): CatalogEntry[] {
if (!this.sortColumn) return entries;
const sorted = [...entries];
const dir = this.sortAscending ? 1 : -1;
sorted.sort((a, b) => {
const va = this.getSortValue(a, this.sortColumn);
const vb = this.getSortValue(b, this.sortColumn);
if (typeof va === "number" && typeof vb === "number") return (va - vb) * dir;
return String(va).localeCompare(String(vb)) * dir;
});
return sorted;
}
private getSortValue(entry: CatalogEntry, column: string): string | number {
switch (column) {
case "name":
return entry.display_name;
case "task":
return entry.task;
case "size":
return entry.size_gb;
case "downloads":
return entry.downloads;
default:
return "";
}
}
private handleRemove(entry: CatalogEntry, btn: HTMLElement): void {
const confirmModal = new ConfirmModal(this.app, MESSAGES.NOTICE_CONFIRM_REMOVE(entry.hf_repo));
confirmModal.open();
void confirmModal.result.then((confirmed) => {
if (!confirmed) return;
void this.executeRemove(entry, btn);
});
}
private async executeRemove(entry: CatalogEntry, btn: HTMLElement): Promise<void> {
const taskId = this.plugin.taskQueue.enqueue(`Remove ${entry.hf_repo}`, TASK_TYPE.DELETE);
if (taskId === null) {
new Notice(MESSAGES.NOTICE_QUEUE_FULL);
return;
}
btn.setText(MESSAGES.STATUS_REMOVING);
(btn as HTMLButtonElement).disabled = true;
this.plugin.taskQueue.update(taskId, -1, entry.hf_repo);
const result = await this.plugin.api.deleteModel(entry.hf_repo, entry.source);
if (result.isErr()) {
new Notice(
noticeForResultError(result.error, MESSAGES.ERROR_REMOVE_MODEL.replace("{model}", entry.hf_repo)),
);
this.plugin.taskQueue.fail(taskId, errorMessage(result.error, result.error.message));
btn.setText(MESSAGES.BUTTON_REMOVE);
(btn as HTMLButtonElement).disabled = false;
return;
}
this.plugin.taskQueue.complete(taskId);
new Notice(MESSAGES.NOTICE_REMOVED(entry.hf_repo));
void this.plugin.fetchActiveModel();
this.resetAndFetch();
}
private async handleUse(entry: CatalogEntry, btn: HTMLElement): Promise<void> {
btn.setText(MESSAGES.STATUS_SETTING);
(btn as HTMLButtonElement).disabled = true;
const result = await this.setActiveFor(entry);
if (result.isErr()) {
new Notice(noticeForResultError(result.error, MESSAGES.ERROR_SET_MODEL.replace("{model}", entry.hf_repo)));
btn.setText(MESSAGES.BUTTON_USE);
(btn as HTMLButtonElement).disabled = false;
return;
}
void this.plugin.fetchActiveModel();
this.plugin.refreshSettingsTab();
this.plugin.refreshOpenChatRails();
new Notice(MESSAGES.NOTICE_MODEL_ACTIVATED(this.activatedRefFor(entry)));
this.resetAndFetch();
}
/** Identifier to surface in user-facing toasts. */
private activatedRefFor(entry: CatalogEntry): string {
return entry.display_name;
}
private async setActiveFor(entry: CatalogEntry): ReturnType<typeof this.plugin.api.setChatModel> {
// Activate by the concrete GGUF file ref: the server resolves a bare
// multi-quant repo to whichever quant sorts first, which is not
// necessarily the one the user clicked.
const ref = nativeModelRef(entry.hf_repo, entry.gguf_filename);
if (entry.task === MODEL_TASK.EMBEDDING) {
return applyEmbeddingModel(this.plugin, ref);
}
if (entry.task === MODEL_TASK.RERANK) {
return this.plugin.api.setRerankerModel(ref);
}
if (entry.task === MODEL_TASK.VISION) {
const visionResult = await this.plugin.api.setVisionModel(ref);
if (visionResult.isOk()) noticeModelWarnings(visionResult.value);
return visionResult;
}
const result = await this.plugin.api.setChatModel(ref);
if (result.isOk()) this.plugin.activeModel = ref;
return result;
}
private handlePull(entry: CatalogEntry): void {
// Safety net: every pull path (grid card, list row) funnels through
// here, so refuse an unsupported model even if a gated button is ever
// bypassed. The buttons are also disabled in the UI.
if (entry.compat === MODEL_COMPAT.UNSUPPORTED) {
new Notice(MESSAGES.TOOLTIP_PULL_UNSUPPORTED);
return;
}
const confirmModal = new ConfirmPullModal(this.app, {
displayName: entry.display_name,
sizeGb: entry.size_gb,
minRamGb: entry.min_ram_gb,
systemMemGb: getRelevantSystemMemoryGB(this.plugin.settings.serverMode),
});
confirmModal.open();
void confirmModal.result.then((confirmed) => {
if (!confirmed) return;
void this.executePull(entry);
});
}
private async executePull(entry: CatalogEntry): Promise<void> {
const taskId = this.plugin.enqueuePull(`Pull ${entry.hf_repo}`);
if (taskId === null) {
new Notice(MESSAGES.NOTICE_QUEUE_FULL);
return;
}
const controller = new AbortController();
this.plugin.taskQueue.registerAbort(taskId, controller);
const pullErrorPrefix = MESSAGES.ERROR_PULL_MODEL.replace("{model}", entry.hf_repo);
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.hf_repo, {
current: d.current,
total: d.total,
});
}
} else if (event.event === SSE_EVENT.ERROR) {
const d = event.data as { message?: string } | string;
const msg = extractSseErrorMessage(d, MESSAGES.ERROR_UNKNOWN);
new Notice(`${pullErrorPrefix}: ${msg}`);
this.plugin.taskQueue.fail(taskId, msg);
return;
}
}
} 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 msg = errorMessage(err, MESSAGES.ERROR_UNKNOWN);
new Notice(`${pullErrorPrefix}: ${msg}`);
this.plugin.taskQueue.fail(taskId, msg);
}
return;
}
this.plugin.taskQueue.complete(taskId);
const result = await this.setActiveFor(entry);
if (result.isErr()) {
new Notice(noticeForResultError(result.error, MESSAGES.ERROR_SET_MODEL.replace("{model}", entry.hf_repo)));
void this.plugin.fetchActiveModel();
this.resetAndFetch();
return;
}
void this.plugin.fetchActiveModel();
this.plugin.refreshSettingsTab();
this.plugin.refreshOpenChatRails();
new Notice(MESSAGES.NOTICE_MODEL_ACTIVATED_FULL(this.activatedRefFor(entry)));
this.resetAndFetch();
}
}
function findCardElement(target: EventTarget | null): HTMLElement | null {
let el = target as (HTMLElement & { dataset?: Record<string, string> }) | null;
while (el) {
if (el.dataset?.repo) return el;
el = (el.parentElement ?? null) as (HTMLElement & { dataset?: Record<string, string> }) | null;
}
return null;
}
function isTextInputTarget(target: EventTarget | null): boolean {
const el = target as { tagName?: string } | null;
if (!el?.tagName) return false;
const tag = el.tagName;
return tag === "INPUT" || tag === "TEXTAREA";
}
|