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 | 2x 2x 2x 2x 1154x 2x 3x 1x 48x 29x 19x 52x 46x 46x 194x 194x 194x 194x 194x 194x 194x 194x 194x 194x 194x 194x 194x 194x 194x 194x 194x 194x 194x 2x 194x 194x 194x 194x 194x 1x 1x 1x 190x 190x 190x 190x 190x 190x 25x 25x 25x 11x 11x 25x 190x 190x 190x 190x 190x 190x 190x 190x 17x 190x 190x 190x 190x 190x 190x 13x 190x 190x 190x 190x 190x 1x 190x 190x 190x 190x 190x 1x 190x 188x 188x 188x 564x 564x 1x 1x 3x 1x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 190x 64x 64x 63x 63x 60x 60x 1x 1x 190x 62x 1x 61x 190x 5x 3x 3x 214x 19x 22x 20x 22x 22x 193x 5x 5x 193x 193x 193x 193x 193x 193x 193x 193x 193x 6x 6x 187x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 3x 21x 193x 193x 193x 9x 9x 193x 193x 193x 18x 18x 18x 18x 6x 6x 6x 18x 5x 3x 3x 3x 2x 2x 1x 1x 2x 2x 2x 4x 2x 194x 194x 160x 194x 208x 208x 208x 9x 208x 209x 376x 209x 209x 209x 22x 22x 209x 8x 6x 209x 376x 209x 209x 376x 178x 354x 354x 354x 17x 1x 23x 16x 12x 12x 12x 12x 11x 12x 4x 4x 2x 2x 2x 2x 2x 13x 3x 6x 6x 6x 6x 6x 1x 1x 5x 5x 3x 3x 3x 2x 2x 2x 2x 2x 1152x 1152x 1152x 1152x 1152x 57x 40x 38x 38x 39x 39x 74x 74x 12x 11x 11x 38x 193x 193x 193x 193x 193x 386x 386x 772x 782x 782x 782x 782x 782x 2x 782x 782x 782x 782x 782x 326x 782x 782x 772x 772x 772x 772x 772x 772x 772x 772x 772x 10x 7x 772x 7x 3x 3x 4x 4x 1x 1x 3x 3x 3x 3x 6x 5x 5x 3x 3x 2x 14x 14x 1x 1x 13x 13x 13x 13x 13x 9x 5x 5x 5x 4x 4x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 3x 3x 10x 10x 7x 7x 7x 1x 6x 6x 6x 7x 7x 1x 3x 3x 63x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 93x 93x 93x 50x 50x 50x 62x 31x 30x 30x 30x 30x 62x 62x 100x 11x 5x 5x 5x 2x 2x 3x 6x 2x 4x 2x 2x 62x 62x 62x 62x 61x 62x 100x 31x 31x 28x 28x 31x 31x 31x 12x 12x 12x 12x 12x 4x 4x 45x 45x 45x 45x 5x 5x 5x 45x 45x 45x 45x 45x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x 3x 3x 2x 2x 3x 17x 7x 7x 7x 7x 7x 7x 7x 7x 12x 10x 10x 9x 9x 135x 135x 132x 134x 134x 134x 130x 91x 91x 91x 6x 6x 6x 6x 6x 6x 6x 7x 7x 7x 1x 7x 7x 3x 7x 7x 1x 7x 7x 1x 7x 45x 45x 45x 45x 45x 45x 42x 2x 1x 1x 42x 42x 45x 45x 1x 1x 1x 44x 4x 4x 3x 2x 1x 2x 6x 5x 5x 5x 5x 5x 5x 1x 187x 1x 1x 4x 1x 1x 3x 15x 3x 3x 3x 3x 3x 3x 6x 6x 3x 3x 3x 3x 3x 2x 3x 2x 1x 4x 4x 4x 4x 4x 45x 45x 1x 1x 1x 4x 4x 4x 1x 1x 2x | import {
FuzzySuggestModal,
ItemView,
MarkdownRenderer,
Menu,
Notice,
Platform,
setIcon,
type TFile,
WorkspaceLeaf,
} from "obsidian";
import type LilbeePlugin from "../main";
import {
CATALOG_SOURCE,
CHAT_MODE,
CONFIG_KEY,
HOSTED_SOURCES,
MODEL_TASK,
SSE_EVENT,
TASK_TYPE,
ERROR_NAME,
} from "../types";
import type {
CatalogEntry,
ChatMode,
InstalledModel,
MemoryExtractedData,
Message,
SearchChunkType,
Source,
SSEEvent,
} from "../types";
import { RateLimitedError } from "../api";
import { renderAggregatedSourceChips } from "./results";
import { displayLabelForRef, extractHfRepo } from "../utils/model-ref";
import { ConfirmPullModal } from "./confirm-pull-modal";
import { ConfirmModal } from "./confirm-modal";
import { CatalogModal } from "./catalog-modal";
import { CrawlModal } from "./crawl-modal";
import { MESSAGES } from "../locales/en";
import {
RETRY_INTERVAL_MS,
SPINNER_MIN_DISPLAY_MS,
percentFromSse,
errorMessage,
extractSseErrorMessage,
extractSseErrorCode,
isModelUnavailableError,
noticeForResultError,
getRelevantSystemMemoryGB,
configString,
isStreamInterruptedError,
streamInterruptedMessage,
} from "../utils";
import { SetupWizard } from "./setup-wizard";
import { hostedOptions, isUsableHostedRow } from "./catalog-helpers";
import { electronDialog } from "../utils/file-dialog";
export const VIEW_TYPE_CHAT = "lilbee-chat";
/** Within this distance of the bottom the view counts as pinned and follows the stream. */
const SCROLL_FOLLOW_THRESHOLD_PX = 80;
/** Sentinel option value: selecting it opens the catalog instead of switching models. */
const RAIL_BROWSE_KEY = "__lilbee_browse__";
/** Option value that turns an optional role off (matches the server's empty model ref). */
const RAIL_DISABLED_KEY = "";
/** One pickable entry in a rail role's menu. */
interface RailOption {
value: string;
label: string;
checked: boolean;
}
/** Label shown on a chip trigger: the checked option, else the first (matching a native select). */
function railTriggerLabel(options: RailOption[]): string {
return (options.find((o) => o.checked) ?? options[0])?.label ?? "";
}
/** Static description of an optional rail role (Vision, Rerank). Dynamic state lives on the view. */
interface OptionalRoleSpec {
key: "vision" | "rerank";
task: typeof MODEL_TASK.VISION | typeof MODEL_TASK.RERANK;
label: string;
dotClass: string;
triggerClass: string;
disabledLabel: string;
tooltip: string;
configKey: string;
setActive: (api: LilbeePlugin["api"], model: string) => Promise<{ isErr(): boolean }>;
failNotice: string;
}
/** Per-message streaming state: accumulated text and the live reasoning DOM. */
interface StreamState {
fullContent: string;
reasoningContent: string;
sources: Source[];
renderPending: boolean;
reasoningRenderPending: boolean;
reasoningContentEl: HTMLElement | null;
reasoningDetailsEl: HTMLElement | null;
answerStarted: boolean;
}
const OPTIONAL_ROLE_SPECS: OptionalRoleSpec[] = [
{
key: "vision",
task: MODEL_TASK.VISION,
label: MESSAGES.RAIL_LABEL_VISION,
dotClass: "is-vision",
triggerClass: "lilbee-vision-model-select",
disabledLabel: MESSAGES.LABEL_VISION_DISABLED,
tooltip: MESSAGES.TOOLTIP_ROLE_VISION,
configKey: "vision_model",
setActive: (api, model) => api.setVisionModel(model),
failNotice: MESSAGES.RAIL_LABEL_VISION,
},
{
key: "rerank",
task: MODEL_TASK.RERANK,
label: MESSAGES.RAIL_LABEL_RERANK,
dotClass: "is-rerank",
triggerClass: "lilbee-rerank-model-select",
disabledLabel: MESSAGES.LABEL_RERANKER_DISABLED,
tooltip: MESSAGES.TOOLTIP_ROLE_RERANK,
configKey: "reranker_model",
setActive: (api, model) => api.setRerankerModel(model),
failNotice: MESSAGES.RAIL_LABEL_RERANK,
},
];
function extractString(data: unknown, field: string): string {
if (typeof data === "object" && data !== null && field in data) {
return String((data as Record<string, unknown>)[field]);
}
return String(data);
}
export function extractBanner(data: unknown): string | null {
if (data === null || typeof data !== "object") return null;
const banner = (data as Record<string, unknown>).banner;
return typeof banner === "string" && banner.length > 0 ? banner : null;
}
export class ChatView extends ItemView {
private plugin: LilbeePlugin;
private history: Message[] = [];
private messagesEl: HTMLElement | null = null;
private sendBtn: HTMLButtonElement | null = null;
private textareaEl: HTMLTextAreaElement | null = null;
private sending = false;
private streamController: AbortController | null = null;
private pullController: AbortController | null = null;
private chatCatalogEntries: CatalogEntry[] = [];
private chatInstalled: InstalledModel[] = [];
private chatActive = "";
private chatTriggerTextEl: HTMLElement | null = null;
private embeddingTriggerTextEl: HTMLElement | null = null;
private embeddingModels: CatalogEntry[] = [];
private activeEmbeddingModel = "";
private chatModeContainer: HTMLElement | null = null;
private chatModeCurrent: ChatMode | null = null;
// Optional model roles (Vision, Rerank) surfaced in the rail. Keyed by the
// spec's `key`; data refreshed alongside the chat/embed selectors. Options
// come from the per-task catalog (so only role-capable models show), exactly
// like the Settings model manager.
private optionalRailEl: HTMLElement | null = null;
private optionalCatalog: Record<string, CatalogEntry[]> = { vision: [], rerank: [] };
private optionalActive: Record<string, string> = { vision: "", rerank: "" };
private static readonly OFFLINE_THRESHOLD = 3;
private retryTimer: number | null = null;
private retryCount = 0;
private emptyStateEl: HTMLElement | null = null;
constructor(leaf: WorkspaceLeaf, plugin: LilbeePlugin) {
super(leaf);
this.plugin = plugin;
}
getViewType(): string {
return VIEW_TYPE_CHAT;
}
getDisplayText(): string {
return MESSAGES.LABEL_CHAT_VIEW;
}
getIcon(): string {
return "message-circle";
}
async onOpen(): Promise<void> {
const container = this.containerEl.children[1] as HTMLElement;
container.empty();
container.addClass("lilbee-chat-container");
this.createToolbar(container);
this.messagesEl = container.createDiv({ cls: "lilbee-chat-messages" });
this.createInputArea(container);
}
async onClose(): Promise<void> {
this.streamController?.abort();
this.pullController?.abort();
if (this.retryTimer) {
window.clearTimeout(this.retryTimer);
this.retryTimer = null;
}
this.retryCount = 0;
}
private createToolbar(container: HTMLElement): void {
const toolbar = container.createDiv({ cls: "lilbee-chat-toolbar" });
// Model rail (line 1): the four roles as content-sized chips that wrap
// when the panel is narrow. Each chip is a colored dot (filled = on,
// hollow = off) + a clear label + the model picker. All four read the
// same way — bb-72pq parity, no role is icon-only.
const rail = toolbar.createDiv({ cls: "lilbee-model-rail" });
const chatChip = rail.createDiv({ cls: "lilbee-model-chip lilbee-toolbar-group" });
chatChip.setAttribute("aria-label", MESSAGES.TOOLTIP_ROLE_CHAT);
chatChip.setAttribute("aria-label-position", "top");
chatChip.createSpan({ cls: "lilbee-model-chip-dot is-chat is-active" });
chatChip.createSpan({ cls: "lilbee-model-chip-label", text: MESSAGES.RAIL_LABEL_CHAT });
this.chatTriggerTextEl = this.createRailTrigger(chatChip, "lilbee-chat-model-select", (event) =>
this.openChatMenu(event),
);
const embedChip = rail.createDiv({ cls: "lilbee-model-chip lilbee-toolbar-group lilbee-toolbar-group-embed" });
embedChip.setAttribute("aria-label", MESSAGES.TOOLTIP_ROLE_EMBED);
embedChip.setAttribute("aria-label-position", "top");
embedChip.createSpan({ cls: "lilbee-model-chip-dot is-embed is-active" });
embedChip.createSpan({ cls: "lilbee-model-chip-label", text: MESSAGES.RAIL_LABEL_EMBED });
this.embeddingTriggerTextEl = this.createRailTrigger(embedChip, "lilbee-embed-model-select", (event) =>
this.openEmbeddingMenu(event),
);
// Optional roles (Vision, Rerank) are chips in the same wrapping rail.
this.optionalRailEl = rail.createDiv({ cls: "lilbee-model-rail-optional" });
this.fillOptionalRoles();
// "Browse more" sits at the far right of the rail and opens the full
// model catalog (all roles) — not tied to any one chip.
const railBrowseBtn = rail.createEl("button", {
text: MESSAGES.BUTTON_BROWSE_MORE,
cls: "lilbee-embed-browse lilbee-rail-browse",
});
railBrowseBtn.setAttribute("aria-label", MESSAGES.BUTTON_BROWSE_MORE);
railBrowseBtn.addEventListener("click", () => {
new CatalogModal(this.app, this.plugin).open();
});
// Controls (line 2): mode toggles on the left, save/clear on the right.
const actions = toolbar.createDiv({ cls: "lilbee-chat-toolbar-actions" });
this.chatModeContainer = actions.createDiv({ cls: "lilbee-chat-mode-container" });
this.fetchAndFillSelectors();
// Search mode toggle (only shown when wiki feature is enabled)
const wikiEnabled = this.plugin.settings.wikiEnabled;
if (!wikiEnabled && this.plugin.settings.searchChunkType === "wiki") {
this.plugin.settings.searchChunkType = "all";
}
if (wikiEnabled) {
const modeGroup = actions.createDiv({ cls: "lilbee-search-mode" });
const modes: { value: SearchChunkType; label: string }[] = [
{ value: "all", label: MESSAGES.LABEL_SEARCH_ALL },
{ value: "wiki", label: MESSAGES.LABEL_SEARCH_WIKI },
{ value: "raw", label: MESSAGES.LABEL_SEARCH_RAW },
];
for (const mode of modes) {
const btn = modeGroup.createEl("button", {
text: mode.label,
cls: `lilbee-search-mode-btn${this.plugin.settings.searchChunkType === mode.value ? " active" : ""}`,
});
btn.addEventListener("click", () => {
this.plugin.settings.searchChunkType = mode.value;
void this.plugin.saveSettings();
modeGroup.querySelectorAll(".lilbee-search-mode-btn").forEach((b) => b.removeClass("active"));
btn.addClass("active");
});
}
}
actions.createDiv({ cls: "lilbee-toolbar-spacer" });
const saveBtn = actions.createEl("button", { cls: "lilbee-chat-save" });
setIcon(saveBtn, "save");
saveBtn.setAttribute("aria-label", MESSAGES.LABEL_SAVE_VAULT);
saveBtn.addEventListener("click", () => void this.saveToVault());
const clearBtn = actions.createEl("button", { cls: "lilbee-chat-clear" });
setIcon(clearBtn, "eraser");
clearBtn.setAttribute("aria-label", MESSAGES.BUTTON_CLEAR_CHAT);
clearBtn.addEventListener("click", () => this.clearChat());
}
private createInputArea(container: HTMLElement): void {
const inputArea = container.createDiv({ cls: "lilbee-chat-input" });
const addBtn = inputArea.createEl("button", { cls: "lilbee-chat-add-file" });
addBtn.setAttribute("aria-label", MESSAGES.LABEL_ADD_FILE);
setIcon(addBtn, "paperclip");
addBtn.addEventListener("click", (e) => this.openFilePicker(e));
const textarea = inputArea.createEl("textarea", {
placeholder: MESSAGES.PLACEHOLDER_ASK_SOMETHING,
cls: "lilbee-chat-textarea",
});
this.textareaEl = textarea;
this.sendBtn = inputArea.createEl("button", {
text: MESSAGES.BUTTON_SEND,
cls: "lilbee-chat-send",
});
const handleSend = (): void => {
// Defensively wrap in try/catch — exceptions in the click/keydown
// path used to bubble out silently because Obsidian swallows them
// at the event-listener boundary, leaving the user staring at a
// chat with their question echoed back but no fetch fired.
try {
if (this.sending) return;
const text = textarea.value.trim();
if (!text) return;
textarea.value = "";
void this.sendMessage(text);
} catch (err) {
const reason = errorMessage(err, MESSAGES.ERROR_UNKNOWN, this.plugin.settings.serverMode);
new Notice(MESSAGES.ERROR_CHAT_FAILED(reason));
}
};
this.sendBtn.addEventListener("click", () => {
if (this.sending) {
this.streamController?.abort();
} else {
handleSend();
}
});
textarea.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
});
}
private fetchAndFillSelectors(): void {
Promise.all([
this.plugin.api.catalog({ task: MODEL_TASK.CHAT }),
this.plugin.api.installedModels({ task: MODEL_TASK.CHAT }).catch(() => ({ models: [] })),
this.plugin.api.catalog({ task: MODEL_TASK.EMBEDDING }).catch(() => null),
this.plugin.api.config().catch(() => null),
this.plugin.api.catalog({ task: MODEL_TASK.VISION }).catch(() => null),
this.plugin.api.catalog({ task: MODEL_TASK.RERANK }).catch(() => null),
])
.then(([chatCatalogResult, chatInstalled, embeddingResult, serverConfig, visionCatalog, rerankCatalog]) => {
if (this.retryTimer) {
window.clearTimeout(this.retryTimer);
this.retryTimer = null;
}
this.retryCount = 0;
this.chatCatalogEntries = chatCatalogResult.isOk() ? chatCatalogResult.value.models : [];
this.chatInstalled = chatInstalled.models;
this.chatActive = serverConfig ? configString(serverConfig, "chat_model") : "";
this.chatTriggerTextEl?.setText(railTriggerLabel(this.chatOptionGroups().flat()));
this.fillEmbeddingSelector(embeddingResult, serverConfig);
this.fillOptionalRoleData(
visionCatalog && visionCatalog.isOk() ? visionCatalog.value.models : [],
rerankCatalog && rerankCatalog.isOk() ? rerankCatalog.value.models : [],
serverConfig,
);
this.renderChatModeToggle(serverConfig);
if (this.chatInstalled.length === 0) {
this.showEmptyState();
this.retryTimer = window.setTimeout(() => this.fetchAndFillSelectors(), RETRY_INTERVAL_MS);
} else {
this.hideEmptyState();
}
})
.catch(() => {
this.retryCount++;
const connecting = this.retryCount < ChatView.OFFLINE_THRESHOLD;
const label = connecting ? MESSAGES.LABEL_CONNECTING : MESSAGES.LABEL_OFFLINE;
// Clear option state so the menus offer nothing while unreachable.
this.chatCatalogEntries = [];
this.chatInstalled = [];
this.embeddingModels = [];
this.activeEmbeddingModel = "";
this.chatTriggerTextEl?.setText(label);
this.embeddingTriggerTextEl?.setText(label);
if (this.retryCount === ChatView.OFFLINE_THRESHOLD) {
new Notice(MESSAGES.ERROR_SERVER_UNREACHABLE);
}
this.retryTimer = window.setTimeout(() => this.fetchAndFillSelectors(), RETRY_INTERVAL_MS);
});
}
private renderChatModeToggle(serverConfig: Record<string, unknown> | null): void {
/* v8 ignore next 2 */
if (!this.chatModeContainer) return;
this.chatModeContainer.empty();
const rawMode = serverConfig?.chat_mode;
if (rawMode !== CHAT_MODE.SEARCH && rawMode !== CHAT_MODE.CHAT) return;
this.chatModeCurrent = rawMode;
const embeddingModel = typeof serverConfig?.embedding_model === "string" ? serverConfig.embedding_model : "";
const noEmbedding = embeddingModel === "";
const segments: { mode: ChatMode; label: string; tooltip: string }[] = [
{ mode: CHAT_MODE.SEARCH, label: MESSAGES.LABEL_CHAT_MODE_SEARCH, tooltip: MESSAGES.TOOLTIP_MODE_SEARCH },
{ mode: CHAT_MODE.CHAT, label: MESSAGES.LABEL_CHAT_MODE_CHAT, tooltip: MESSAGES.TOOLTIP_MODE_CHAT },
];
for (const seg of segments) {
const btn = this.chatModeContainer.createEl("button", {
text: seg.label,
cls: `lilbee-chat-mode-btn${seg.mode === rawMode ? " active" : ""}`,
});
btn.setAttribute("aria-label", seg.tooltip);
btn.setAttribute("aria-label-position", "top");
if (noEmbedding) {
btn.disabled = true;
btn.setAttribute("title", MESSAGES.TOOLTIP_CHAT_MODE_NEEDS_EMBEDDING);
btn.addClass("lilbee-disabled");
}
btn.addEventListener("click", () => {
if (noEmbedding || seg.mode === this.chatModeCurrent) return;
void this.persistChatMode(seg.mode);
});
}
}
private async persistChatMode(mode: ChatMode): Promise<void> {
try {
await this.plugin.api.updateConfig({ [CONFIG_KEY.CHAT_MODE]: mode });
this.chatModeCurrent = mode;
this.applyActiveClassToChatModeButtons(mode);
} catch (err) {
const reason = errorMessage(err, MESSAGES.ERROR_UNKNOWN, this.plugin.settings.serverMode);
new Notice(MESSAGES.NOTICE_FAILED_UPDATE(`${MESSAGES.LABEL_CHAT_MODE}: ${reason}`));
}
}
private applyActiveClassToChatModeButtons(mode: ChatMode): void {
/* v8 ignore next 2 */
if (!this.chatModeContainer) return;
const buttons = this.chatModeContainer.querySelectorAll(".lilbee-chat-mode-btn");
const activeIdx = mode === CHAT_MODE.SEARCH ? 0 : 1;
for (let i = 0; i < buttons.length; i++) {
if (i === activeIdx) buttons[i].addClass("active");
else buttons[i].removeClass("active");
}
}
private fillEmbeddingSelector(
embeddingResult: import("../result").Result<import("../types").CatalogResponse, Error> | null,
serverConfig: Record<string, unknown> | null,
): void {
this.activeEmbeddingModel = serverConfig ? configString(serverConfig, "embedding_model") : "";
this.embeddingModels =
embeddingResult && embeddingResult.isOk() ? embeddingResult.value.models.filter((m) => m.installed) : [];
this.embeddingTriggerTextEl?.setText(railTriggerLabel(this.embeddingOptions()));
}
/** Embedding menu entries: installed builds, or the bare active ref when none are installed. */
private embeddingOptions(): RailOption[] {
const activeRepo = extractHfRepo(this.activeEmbeddingModel);
const options = this.embeddingModels.map((m) => ({
value: m.hf_repo,
label: m.display_name,
checked: m.hf_repo === activeRepo,
}));
if (options.length === 0 && this.activeEmbeddingModel) {
options.push({
value: this.activeEmbeddingModel,
label: displayLabelForRef(this.activeEmbeddingModel),
checked: true,
});
}
return options;
}
/** Chat menu entries: [featured installed + hosted rows, other installed builds]. */
private chatOptionGroups(): RailOption[][] {
return [this.chatPrimaryOptions(), this.chatOtherOptions()];
}
/** Featured rows that have an installed quant, then hosted rows not already listed. */
private chatPrimaryOptions(): RailOption[] {
const installedRepos = new Set(this.chatInstalled.map((m) => extractHfRepo(m.name)));
const activeRepo = extractHfRepo(this.chatActive);
const primary: RailOption[] = [];
for (const entry of this.chatCatalogEntries.filter((e) => installedRepos.has(e.hf_repo))) {
const sourceTag = HOSTED_SOURCES.has(entry.source) ? ` [${entry.provider ?? entry.source}]` : "";
primary.push({
value: entry.hf_repo,
label: `${entry.display_name}${sourceTag}`,
checked: entry.hf_repo === activeRepo,
});
}
// Hosted rows (frontier/ollama) 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 (an ollama model can
// be both hosted and registered as installed).
for (const [ref, label] of hostedOptions(this.chatCatalogEntries)) {
if (installedRepos.has(ref)) continue;
primary.push({ value: ref, label, checked: ref === activeRepo });
}
return primary;
}
/** Installed builds that aren't in the featured catalog (manually pulled, ollama/, openai/, …). */
private chatOtherOptions(): RailOption[] {
const sourceMap = new Map(this.chatInstalled.map((m) => [m.name, m.source]));
const featuredRepos = new Set(this.chatCatalogEntries.map((e) => e.hf_repo));
return this.chatInstalled
.filter((m) => !featuredRepos.has(extractHfRepo(m.name)))
.sort((a, b) => a.name.localeCompare(b.name))
.map((m) => {
const source = sourceMap.get(m.name);
const suffix = source && source !== CATALOG_SOURCE.NATIVE ? ` [${source}]` : "";
return {
value: m.name,
label: `${displayLabelForRef(m.name)}${suffix}`,
checked: m.name === this.chatActive,
};
});
}
private openChatMenu(event: MouseEvent): void {
this.openRailMenu(event, this.chatTriggerTextEl, this.chatOptionGroups(), (value) =>
this.handleChatSelection(value),
);
}
private handleChatSelection(value: string): void {
const uninstalled = this.chatCatalogEntries.find((e) => e.hf_repo === value && !e.installed);
if (uninstalled) {
const modal = new ConfirmPullModal(this.plugin.app, {
displayName: uninstalled.display_name,
sizeGb: uninstalled.size_gb,
minRamGb: uninstalled.min_ram_gb,
systemMemGb: getRelevantSystemMemoryGB(this.plugin.settings.serverMode),
});
modal.open();
void modal.result.then((confirmed) => {
if (confirmed) {
void this.autoPullAndSet(uninstalled);
}
});
return;
}
void this.plugin.api.setChatModel(value).then((result) => {
if (result.isOk()) {
// Keep the menu's checkmark in sync without waiting for a refetch.
this.chatActive = value;
this.plugin.activeModel = value;
void this.plugin.fetchActiveModel();
this.plugin.refreshSettingsTab();
} else {
new Notice(MESSAGES.ERROR_SWITCH_MODEL);
}
});
}
private openEmbeddingMenu(event: MouseEvent): void {
this.openRailMenu(event, this.embeddingTriggerTextEl, [this.embeddingOptions()], (value) =>
this.handleEmbeddingSelection(value),
);
}
private handleEmbeddingSelection(value: string): void {
const previous = this.activeEmbeddingModel;
const modal = new ConfirmModal(this.plugin.app, MESSAGES.DESC_EMBEDDING_REINDEX_WARNING);
modal.open();
void modal.result.then(async (confirmed) => {
if (!confirmed) {
this.revertEmbeddingTrigger(previous);
return;
}
const result = await this.plugin.api.setEmbeddingModel(value);
if (result.isErr()) {
new Notice(noticeForResultError(result.error, MESSAGES.NOTICE_FAILED_EMBEDDING));
this.revertEmbeddingTrigger(previous);
return;
}
this.activeEmbeddingModel = value;
new Notice(MESSAGES.NOTICE_EMBEDDING_UPDATED);
new Notice(MESSAGES.NOTICE_REINDEX_REQUIRED);
this.plugin.refreshSettingsTab();
void this.plugin.triggerSync();
});
}
/** Chip trigger button: current model text + caret; click opens the role's menu. */
private createRailTrigger(
chip: HTMLElement,
cls: string,
onOpen: (event: MouseEvent, textEl: HTMLElement) => void,
): HTMLElement {
const trigger = chip.createEl("button", { cls: `lilbee-model-chip-select ${cls}` });
const text = trigger.createSpan({ cls: "lilbee-model-chip-select-text" });
setIcon(trigger.createSpan({ cls: "lilbee-model-chip-select-caret" }), "chevron-down");
trigger.addEventListener("click", (event) => onOpen(event, text));
return text;
}
/** In-window menu of rail options; the checked entry is the active one. */
private openRailMenu(
event: MouseEvent,
textEl: HTMLElement | null,
groups: RailOption[][],
onPick: (value: string) => void,
): void {
const nonEmpty = groups.filter((group) => group.length > 0);
if (nonEmpty.length === 0) return;
const menu = new Menu();
nonEmpty.forEach((group, index) => {
if (index > 0) menu.addSeparator();
for (const opt of group) {
menu.addItem((item) => {
item.setTitle(opt.label)
.setChecked(opt.checked)
.onClick(() => {
// Re-picking the active item is a no-op (matches a native select's change event).
if (opt.checked) return;
// Browse opens the catalog; the chip keeps showing the current model.
if (opt.value !== RAIL_BROWSE_KEY) textEl?.setText(opt.label);
onPick(opt.value);
});
});
}
});
this.showMenu(menu, event);
}
/** Store the latest per-task catalog + active model for the optional roles, then re-render. */
private fillOptionalRoleData(
visionCatalog: CatalogEntry[],
rerankCatalog: CatalogEntry[],
serverConfig: Record<string, unknown> | null,
): void {
this.optionalCatalog.vision = visionCatalog;
this.optionalCatalog.rerank = rerankCatalog;
this.optionalActive.vision = serverConfig ? configString(serverConfig, "vision_model") : "";
this.optionalActive.rerank = serverConfig ? configString(serverConfig, "reranker_model") : "";
this.fillOptionalRoles();
}
/** Rebuild the optional (Vision, Rerank) rail rows from current catalog/active state. */
private fillOptionalRoles(): void {
/* v8 ignore next 2 */
if (!this.optionalRailEl) return;
this.optionalRailEl.empty();
for (const spec of OPTIONAL_ROLE_SPECS) {
this.renderOptionalRoleRow(this.optionalRailEl, spec);
}
}
/**
* Selectable models for a role: local installed builds + hosted (LiteLLM)
* entries — mirroring the Settings model manager so only role-capable
* models appear. Un-installed catalog builds are reached via "Browse catalog".
*/
private optionalRoleOptions(spec: OptionalRoleSpec): { value: string; label: string }[] {
const entries = this.optionalCatalog[spec.key];
const localInstalled = entries.filter((e) => !HOSTED_SOURCES.has(e.source) && e.installed);
const hosted = entries.filter(isUsableHostedRow);
const options = localInstalled.map((e) => ({ value: e.hf_repo, label: e.display_name }));
for (const e of hosted) {
options.push({ value: e.hf_repo, label: `${e.display_name} — ${MESSAGES.LABEL_VISION_HOSTED_GROUP}` });
}
return options;
}
/** Full menu entry list for an optional role: Disabled, role-capable models, Browse catalog. */
private optionalRoleMenuOptions(spec: OptionalRoleSpec): RailOption[] {
const active = this.optionalActive[spec.key];
const activeRepo = extractHfRepo(active);
// "Disabled" turns the role off (model ref ""); the role stays visible
// even with nothing installed, and "Browse catalog" downloads one.
const options: RailOption[] = [{ value: RAIL_DISABLED_KEY, label: spec.disabledLabel, checked: !active }];
for (const opt of this.optionalRoleOptions(spec)) {
options.push({ ...opt, checked: opt.value === active || opt.value === activeRepo });
}
options.push({ value: RAIL_BROWSE_KEY, label: MESSAGES.RAIL_BROWSE_CATALOG, checked: false });
return options;
}
private renderOptionalRoleRow(rail: HTMLElement, spec: OptionalRoleSpec): void {
const active = this.optionalActive[spec.key];
const chip = rail.createDiv({ cls: "lilbee-model-chip lilbee-model-chip-optional" });
chip.setAttribute("aria-label", spec.tooltip);
chip.setAttribute("aria-label-position", "top");
if (!active) chip.addClass("is-off");
const dot = chip.createSpan({ cls: `lilbee-model-chip-dot ${spec.dotClass}` });
if (active) dot.addClass("is-active");
chip.createSpan({ cls: "lilbee-model-chip-label", text: spec.label });
const textEl = this.createRailTrigger(chip, spec.triggerClass, (event, text) =>
this.openRailMenu(event, text, [this.optionalRoleMenuOptions(spec)], (value) =>
this.handleOptionalRoleSelection(spec, value),
),
);
textEl.setText(railTriggerLabel(this.optionalRoleMenuOptions(spec)));
}
private handleOptionalRoleSelection(spec: OptionalRoleSpec, value: string): void {
if (value === RAIL_BROWSE_KEY) {
new CatalogModal(this.app, this.plugin, spec.task).open();
return;
}
// RAIL_DISABLED_KEY disables the role; any other value activates it.
void spec.setActive(this.plugin.api, value).then((result) => {
if (result.isErr()) {
new Notice(MESSAGES.NOTICE_FAILED_UPDATE(spec.failNotice));
return;
}
this.optionalActive[spec.key] = value;
this.fillOptionalRoles();
void this.plugin.fetchActiveModel();
this.plugin.refreshSettingsTab();
});
}
private revertEmbeddingTrigger(previousValue: string): void {
if (!this.embeddingTriggerTextEl) return;
// Restore the previous label only when that value still exists in the
// option set; otherwise fall back to a server refresh.
const option = this.embeddingOptions().find((opt) => opt.value === previousValue);
if (option) {
this.embeddingTriggerTextEl.setText(option.label);
return;
}
void this.fetchAndFillSelectors();
}
private async autoPullAndSet(entry: CatalogEntry): Promise<void> {
const taskId = this.plugin.taskQueue.enqueue(`Pull ${entry.display_name}`, TASK_TYPE.PULL);
if (taskId === null) {
new Notice(MESSAGES.NOTICE_QUEUE_FULL);
return;
}
this.pullController = new AbortController();
this.plugin.taskQueue.registerAbort(taskId, this.pullController);
let pullFailed = false;
try {
for await (const event of this.plugin.api.pullModel(entry.hf_repo, "native", this.pullController.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 d = event.data as { message?: string } | string;
const msg = extractSseErrorMessage(d, MESSAGES.ERROR_UNKNOWN);
new Notice(MESSAGES.ERROR_PULL_MODEL.replace("{model}", entry.display_name));
this.plugin.taskQueue.fail(taskId, msg);
pullFailed = true;
break;
}
}
} 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);
}
this.pullController = null;
return;
}
this.pullController = null;
if (pullFailed) return;
this.plugin.taskQueue.complete(taskId);
const result = await this.plugin.api.setChatModel(entry.hf_repo);
if (result.isErr()) {
new Notice(
noticeForResultError(result.error, MESSAGES.ERROR_SET_MODEL.replace("{model}", entry.display_name)),
);
} else {
this.plugin.activeModel = entry.hf_repo;
new Notice(MESSAGES.NOTICE_MODEL_ACTIVATED_FULL(entry.display_name));
this.plugin.refreshSettingsTab();
}
void this.plugin.fetchActiveModel();
this.fetchAndFillSelectors();
}
// Re-sync the rail pills with the server's active models, for callers
// outside this view (e.g. the catalog) that switch a model.
refreshRail(): void {
this.fetchAndFillSelectors();
}
private clearChat(): void {
this.history = [];
if (this.messagesEl) this.messagesEl.empty();
}
private async sendMessage(text: string): Promise<void> {
if (!this.messagesEl || this.sending) return;
this.sending = true;
this.streamController = new AbortController();
this.plugin.notifyChatStart();
if (this.sendBtn) this.sendBtn.textContent = MESSAGES.BUTTON_STOP;
if (this.textareaEl) this.textareaEl.disabled = true;
const userBubble = this.messagesEl.createDiv({ cls: "lilbee-chat-message user" });
userBubble.createEl("p", { text });
this.history.push({ role: "user", content: text });
const assistantBubble = this.messagesEl.createDiv({ cls: "lilbee-chat-message assistant" });
const spinner = assistantBubble.createDiv({ cls: "lilbee-thinking-dots" });
spinner.createDiv({ cls: "lilbee-thinking-dot" });
spinner.createDiv({ cls: "lilbee-thinking-dot" });
spinner.createDiv({ cls: "lilbee-thinking-dot" });
const textEl = assistantBubble.createDiv({ cls: "lilbee-chat-content" });
textEl.hide();
this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
const state: StreamState = {
fullContent: "",
reasoningContent: "",
sources: [],
renderPending: false,
reasoningRenderPending: false,
reasoningContentEl: null,
reasoningDetailsEl: null,
answerStarted: false,
};
const spinnerCreatedAt = Date.now();
const revealContent = (): void => {
const elapsed = Date.now() - spinnerCreatedAt;
const delay = Math.max(0, SPINNER_MIN_DISPLAY_MS - elapsed);
window.setTimeout(() => {
// Revealing the hidden content grows the bubble; keep the view pinned.
void this.renderFollowing(() => {
if (spinner.parentElement) spinner.remove();
textEl.show();
});
}, delay);
};
const scheduleRender = (): void => {
if (state.renderPending) return;
state.renderPending = true;
window.requestAnimationFrame(() => {
state.renderPending = false;
void this.renderFollowing(() => this.renderMarkdown(textEl, state.fullContent));
});
};
try {
for await (const event of this.plugin.api.chatStream(
text,
this.history.slice(0, -1),
this.plugin.settings.topK,
this.streamController.signal,
undefined,
this.plugin.settings.searchChunkType,
)) {
this.handleStreamEvent(event, textEl, assistantBubble, state, revealContent, scheduleRender);
}
} catch (err) {
if (err instanceof Error && err.name === ERROR_NAME.ABORT_ERROR) {
revealContent();
state.reasoningDetailsEl?.removeAttribute("open");
if (state.fullContent) {
void this.renderMarkdown(textEl, `${state.fullContent}\n\n${MESSAGES.LABEL_STOPPED_MD}`);
this.history.push({ role: "assistant", content: state.fullContent });
} else {
textEl.textContent = MESSAGES.LABEL_STOPPED;
}
} else if (err instanceof RateLimitedError) {
this.renderInlineError(assistantBubble, MESSAGES.ERROR_RATE_LIMITED(err.retryAfterSeconds));
} else if (isStreamInterruptedError(err)) {
this.renderInlineError(assistantBubble, streamInterruptedMessage(this.plugin.settings.serverMode));
} else {
this.renderInlineError(
assistantBubble,
MESSAGES.ERROR_CHAT_FAILED(
errorMessage(err, MESSAGES.ERROR_UNKNOWN, this.plugin.settings.serverMode),
),
);
}
} finally {
this.sending = false;
this.streamController = null;
this.plugin.notifyChatEnd();
if (this.sendBtn) {
this.sendBtn.textContent = MESSAGES.BUTTON_SEND;
}
if (this.textareaEl) this.textareaEl.disabled = false;
}
}
private handleStreamEvent(
event: SSEEvent,
textEl: HTMLElement,
assistantBubble: HTMLElement,
state: StreamState,
revealContent: () => void,
scheduleRender: () => void,
): void {
switch (event.event) {
case SSE_EVENT.TOKEN: {
revealContent();
// First answer token: collapse the reasoning block.
if (!state.answerStarted) {
state.answerStarted = true;
state.reasoningDetailsEl?.removeAttribute("open");
}
state.fullContent += extractString(event.data, "token");
scheduleRender();
break;
}
case SSE_EVENT.REASONING: {
// Stream reasoning live into an expanded block above the answer.
revealContent();
const el = this.ensureReasoningBlock(assistantBubble, textEl, state);
state.reasoningContent += extractString(event.data, "token");
this.scheduleReasoningRender(state, el);
break;
}
case SSE_EVENT.SOURCES:
state.sources.push(...(event.data as Source[]));
break;
case SSE_EVENT.DONE: {
revealContent();
const rendered = state.fullContent;
// Banner and sources grow the bubble after the last token; render
// them inside one follow so the view ends pinned to the bottom.
void this.renderFollowing(async () => {
if (state.reasoningContent) {
const el = this.ensureReasoningBlock(assistantBubble, textEl, state);
await this.renderMarkdown(el, state.reasoningContent);
state.reasoningDetailsEl?.removeAttribute("open");
}
this.renderBannerIfPresent(event.data, assistantBubble);
await this.renderMarkdown(textEl, rendered);
if (state.sources.length > 0) this.renderSources(assistantBubble, state.sources);
});
this.history.push({ role: "assistant", content: rendered });
break;
}
case SSE_EVENT.ERROR: {
const errMsg = extractString(event.data, "message");
assistantBubble.empty();
// Match the thrown-error path: drop the assistant skin so the
// error bubble doesn't inherit the assistant background colour
// from .lilbee-chat-message.assistant.
assistantBubble.removeClass("assistant");
assistantBubble.addClass("lilbee-chat-message-error");
assistantBubble.setAttribute("role", "alert");
assistantBubble.createDiv({
cls: "lilbee-chat-error-text",
text: MESSAGES.ERROR_STREAM(errMsg),
});
new Notice(MESSAGES.ERROR_STREAM(errMsg));
if (isModelUnavailableError(extractSseErrorCode(event.data), errMsg)) {
new Notice(MESSAGES.NOTICE_MODEL_UNAVAILABLE_SETUP);
new SetupWizard(this.app, this.plugin).open();
}
break;
}
case SSE_EVENT.MEMORY_EXTRACTED: {
const extracted = event.data as MemoryExtractedData;
if (extracted.count > 0) {
new Notice(MESSAGES.MEMORY_EXTRACTED_NOTICE(extracted.count));
this.plugin.refreshMemoryViews();
}
break;
}
}
}
/** Create the reasoning block above the answer on first use; return its content div. */
private ensureReasoningBlock(assistantBubble: HTMLElement, textEl: HTMLElement, state: StreamState): HTMLElement {
if (state.reasoningContentEl) return state.reasoningContentEl;
const details = assistantBubble.createEl("details", { cls: "lilbee-reasoning" });
// Expanded while thinking; collapsed if the answer already started.
if (!state.answerStarted) details.setAttribute("open", "");
details.createEl("summary", { text: MESSAGES.LABEL_REASONING });
const content = details.createDiv({ cls: "lilbee-reasoning-content" });
// Move the reasoning block above the answer div.
assistantBubble.insertBefore(details, textEl);
state.reasoningDetailsEl = details;
state.reasoningContentEl = content;
return content;
}
/** Coalesce live reasoning re-renders to one per frame. */
private scheduleReasoningRender(state: StreamState, el: HTMLElement): void {
if (state.reasoningRenderPending) return;
state.reasoningRenderPending = true;
window.requestAnimationFrame(() => {
state.reasoningRenderPending = false;
void this.renderFollowing(() => this.renderMarkdown(el, state.reasoningContent));
});
}
/** True when the message list is scrolled to (or near) the bottom. */
private isNearBottom(): boolean {
const el = this.messagesEl;
if (!el) return false;
return el.scrollHeight - el.scrollTop - el.clientHeight < SCROLL_FOLLOW_THRESHOLD_PX;
}
/** Run a DOM-growing render; re-pin the view to the bottom only if it was pinned before. */
private async renderFollowing(run: () => Promise<void> | void): Promise<void> {
const follow = this.isNearBottom();
await run();
if (follow && this.messagesEl) {
this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
}
}
private async renderMarkdown(el: HTMLElement, markdown: string): Promise<void> {
el.empty();
await MarkdownRenderer.render(this.app, markdown, el, "", this);
el.addClass("markdown-rendered");
}
private renderInlineError(assistantBubble: HTMLElement, text: string): void {
this.history.pop();
assistantBubble.empty();
assistantBubble.removeClass("assistant");
assistantBubble.addClass("lilbee-chat-message-error");
assistantBubble.setAttribute("role", "alert");
assistantBubble.createDiv({ cls: "lilbee-chat-error-text", text });
new Notice(text);
}
private openFilePicker(event: MouseEvent): void {
const menu = new Menu();
menu.addItem((item) => {
item.setTitle(MESSAGES.WIZARD_FILE_PICKER_VAULT)
.setIcon("vault")
.onClick(() => {
new VaultFilePickerModal(this.app, (file) => this.enqueueAddFile(file)).open();
});
});
menu.addItem((item) => {
item.setTitle(MESSAGES.WIZARD_FILE_PICKER_DISK)
.setIcon("file-plus")
.onClick(() => this.openNativeFilePicker(false));
});
menu.addItem((item) => {
item.setTitle(MESSAGES.WIZARD_FOLDER_PICKER_DISK)
.setIcon("folder-plus")
.onClick(() => this.openNativeFilePicker(true));
});
menu.addItem((item) => {
item.setTitle(MESSAGES.WIZARD_CRAWL_WEB)
.setIcon("globe")
.onClick(() => {
new CrawlModal(this.app, this.plugin).open();
});
});
this.showMenu(menu, event);
}
/** The core "Native menus" appearance setting; unset falls back to the platform default (native on macOS). */
private prefersNativeMenu(): boolean {
const vault = this.app.vault as unknown as { getConfig?: (key: string) => unknown };
const value = vault.getConfig?.("nativeMenus");
return typeof value === "boolean" ? value : Platform.isMacOS;
}
/** Show a menu, native when the vault prefers it; the in-window menu gets capture-phase ESC dismissal. */
private showMenu(menu: Menu, event: MouseEvent): void {
const useNative = this.prefersNativeMenu();
menu.setUseNativeMenu(useNative);
if (!useNative) {
// Capture-phase ESC: a focused input can otherwise swallow the keypress.
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
menu.hide();
}
};
activeDocument.addEventListener("keydown", onKey, true);
menu.onHide(() => activeDocument.removeEventListener("keydown", onKey, true));
}
// Keyboard-synthesized clicks (detail 0) carry no coordinates; anchor to the trigger instead.
const trigger = event.detail === 0 ? (event.currentTarget as HTMLElement | null) : null;
if (trigger) {
const rect = trigger.getBoundingClientRect();
menu.showAtPosition({ x: rect.left, y: rect.bottom });
return;
}
menu.showAtMouseEvent(event);
}
private openNativeFilePicker(directory: boolean): void {
const properties = directory ? ["openDirectory"] : ["openFile", "multiSelections"];
electronDialog
.showOpenDialog({ properties })
.then((result) => {
if (result.canceled || result.filePaths.length === 0) return;
void this.plugin.addExternalFiles(result.filePaths);
})
.catch(() => {
new Notice(MESSAGES.ERROR_FILE_PICKER);
});
}
private enqueueAddFile(file: TFile): void {
void this.plugin.addToLilbee(file);
}
private showEmptyState(): void {
if (this.emptyStateEl || !this.messagesEl) return;
this.emptyStateEl = this.messagesEl.createDiv({ cls: "lilbee-chat-empty-state" });
this.emptyStateEl.createDiv({ cls: "lilbee-chat-empty-icon", text: "🔬" });
this.emptyStateEl.createDiv({ cls: "lilbee-chat-empty-heading", text: MESSAGES.NOTICE_NO_MODELS_INSTALLED });
this.emptyStateEl.createEl("p", { text: MESSAGES.NOTICE_NO_MODELS_DESCRIPTION });
const btn = this.emptyStateEl.createEl("button", { text: MESSAGES.BUTTON_BROWSE_CATALOG, cls: "mod-cta" });
btn.addEventListener("click", () => {
new CatalogModal(this.app, this.plugin).open();
});
}
private hideEmptyState(): void {
if (this.emptyStateEl) {
this.emptyStateEl.remove();
this.emptyStateEl = null;
}
}
private async saveToVault(): Promise<void> {
if (this.history.length === 0) {
new Notice(MESSAGES.NOTICE_NOTHING_SAVE);
return;
}
const now = new Date();
const pad = (n: number) => String(n).padStart(2, "0");
const stamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
const filename = `chat-${stamp}.md`;
const folder = "lilbee";
const path = `${folder}/${filename}`;
const lines = [`# ${MESSAGES.LABEL_CHAT_VIEW} — ${now.toLocaleDateString()}`, ""];
for (const msg of this.history) {
const label = msg.role === "user" ? "User" : "Assistant";
lines.push(`**${label}**: ${msg.content}`, "");
}
const content = lines.join("\n");
try {
const vault = this.app.vault;
const existing = vault.getAbstractFileByPath(folder);
if (!existing) {
await vault.createFolder(folder);
}
await vault.create(path, content);
new Notice(MESSAGES.NOTICE_SAVED(path));
} catch {
new Notice(MESSAGES.ERROR_SAVE_CHAT);
}
}
private renderSources(container: HTMLElement, sources: Source[]): void {
const sourcesEl = container.createDiv({ cls: "lilbee-chat-sources" });
const details = sourcesEl.createEl("details");
details.createEl("summary", { text: MESSAGES.LABEL_SOURCES });
const chipsEl = details.createDiv({ cls: "lilbee-chat-source-chips" });
renderAggregatedSourceChips(chipsEl, sources, this.app, this.plugin.api);
}
private renderBannerIfPresent(data: unknown, assistantBubble: HTMLElement): void {
const banner = extractBanner(data);
if (banner === null || !this.messagesEl) return;
const bannerEl = this.messagesEl.createDiv({ cls: "lilbee-chat-banner" });
bannerEl.setText(banner);
this.messagesEl.insertBefore(bannerEl, assistantBubble);
}
}
export class VaultFilePickerModal extends FuzzySuggestModal<TFile> {
private onChoose: (file: TFile) => void;
constructor(app: import("obsidian").App, onChoose: (file: TFile) => void) {
super(app);
this.onChoose = onChoose;
this.setPlaceholder(MESSAGES.PLACEHOLDER_PICK_VAULT_FILE);
}
getItems(): TFile[] {
return this.app.vault.getFiles();
}
getItemText(item: TFile): string {
return item.path;
}
onChooseItem(item: TFile): void {
this.onChoose(item);
}
}
|