File size: 49,287 Bytes
af8ac78 e1c98c1 af8ac78 e1c98c1 af8ac78 e1c98c1 af8ac78 e1c98c1 af8ac78 03cfa1a af8ac78 03cfa1a af8ac78 03cfa1a af8ac78 03cfa1a af8ac78 03cfa1a af8ac78 03cfa1a af8ac78 03cfa1a af8ac78 bfd4772 af8ac78 bfd4772 af8ac78 bfd4772 af8ac78 bfd4772 af8ac78 | 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 | 'use strict';
// ββ Logging helper (browser console with timestamps) βββββββββββββββββββββββ
const LOG_PREFIX = '[HealthExpert]';
const diag = {
info: (...a) => console.info( `${LOG_PREFIX}`, ...a),
warn: (...a) => console.warn( `${LOG_PREFIX}`, ...a),
error: (...a) => console.error(`${LOG_PREFIX}`, ...a),
group: (label) => console.group(`${LOG_PREFIX} ${label}`),
groupEnd: () => console.groupEnd(),
};
// ββ Device detection ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Applies `body.is-mobile` when the device is a phone/touch device OR the
// viewport is narrower than 768px. Re-evaluated on every resize so the layout
// adapts when the window is resized (e.g. DevTools responsive mode).
const MOBILE_BREAKPOINT = 768;
function detectDevice() {
const isTouchDevice = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
const isNarrow = window.innerWidth <= MOBILE_BREAKPOINT;
const isMobileUA = /Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
const isMobile = isTouchDevice || isNarrow || isMobileUA;
if (isMobile) {
document.body.classList.add('is-mobile');
} else {
document.body.classList.remove('is-mobile');
}
diag.info(`Device detected β mobile: ${isMobile} (touch:${isTouchDevice}, narrow:${isNarrow}, mobileUA:${isMobileUA})`);
return isMobile;
}
// Run immediately so the correct class is present before first paint
detectDevice();
// Re-run on resize (debounced to avoid excessive calls)
let _resizeTimer = null;
window.addEventListener('resize', () => {
clearTimeout(_resizeTimer);
_resizeTimer = setTimeout(detectDevice, 150);
});
// ββ State ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const state = {
isQuerying: false,
isIngesting: false,
currentJobId: null,
lastAnswer: '',
isAdmin: false,
};
// ββ DOM refs βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const $ = id => document.getElementById(id);
const dropZone = $('drop-zone');
const fileInput = $('file-input');
const docList = $('doc-list');
const ingestProgress = $('ingest-progress');
const progressFill = $('progress-fill');
const ingestStatusTxt = $('ingest-status-text');
const ingestLog = $('ingest-log');
const ingestLogDetails= $('ingest-log-details');
const chatHistory = $('chat-history');
const queryInput = $('query-input');
const sendBtn = $('send-btn');
const outputContainer = $('output-container');
const copyBtn = $('copy-btn');
const citationsBlock = $('citations-block');
const metricsBanner = $('metrics-banner');
const notifContainer = $('notif-container');
const dockerModal = $('docker-modal');
const dockerModalTitle= $('docker-modal-title');
const dockerModalBody = $('docker-modal-body');
// ββ Notifications ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function notify(msg, type = 'info', duration = 5000) {
diag.info(`notify [${type}]`, msg);
const el = document.createElement('div');
el.className = `notif ${type}`;
el.textContent = msg;
notifContainer.appendChild(el);
setTimeout(() => el.remove(), duration);
}
// ββ Diagnostic log (ingestion accordion) ββββββββββββββββββββββββββββββββββββββ
function appendLog(msg) {
const line = document.createElement('div');
line.className = 'log-line';
line.textContent = `${new Date().toLocaleTimeString()} ${msg}`;
ingestLog.appendChild(line);
ingestLog.scrollTop = ingestLog.scrollHeight;
}
function clearLog() {
ingestLog.innerHTML = '';
}
// ββ Status bar βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function refreshStatus() {
diag.info('Refreshing statusβ¦');
try {
const r = await fetch('/api/status');
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const d = await r.json();
diag.info('Status response:', d);
const setPill = (id, ok, label) => {
const pill = $(id);
if (!pill) return;
pill.className = `status-pill ${ok ? 'ok' : 'warn'}`;
pill.querySelector('.status-label').textContent = label;
};
const vecOk = (d.vector_db?.chunks ?? -1) >= 0;
const graphOk = d.graph_db?.available;
const genOk = d.nvidia_llm?.online;
const embedOk = d.embed_llm?.online;
state.isAdmin = !!d.is_admin;
// Admin controls: only show if server reports admin mode enabled AND caller is admin
const adminMode = (window.APP_CONFIG && window.APP_CONFIG.adminMode !== false) ? true : false;
const showAdmin = state.isAdmin && adminMode;
const adminBadge = $('admin-badge');
if (adminBadge) adminBadge.style.display = showAdmin ? 'inline' : 'none';
const adminControls = $('admin-controls');
if (adminControls) adminControls.style.display = showAdmin ? 'flex' : 'none';
setPill('status-vector', vecOk, `Vector Β· ${d.vector_db?.chunks ?? '?'} chunks`);
setPill('status-graph', graphOk, graphOk ? `Kuzu DB Β· ${d.graph_db.nodes} nodes, ${d.graph_db.relationships} edges` : 'Kuzu DB Β· offline');
const genStatus = genOk
? `Gen Β· ${(d.nvidia_llm?.model || '').split('/').pop()} (GPU: ${d.nvidia_llm?.gpu_id} | KV: ${d.nvidia_llm?.kv_cache_length} tkns)`
: 'Gen LLM Β· offline';
setPill('status-gen', genOk, genStatus);
setPill('status-embed', embedOk, embedOk ? `Embed Β· ${(d.embed_llm?.model || '').split('/').pop()}` : 'Embed LLM Β· offline');
if (!genOk) diag.warn('nvidia_llm server is offline');
if (!embedOk) diag.warn('embed_llm server is offline');
} catch(err) {
diag.error('Status refresh failed:', err);
['status-vector','status-graph','status-gen','status-embed'].forEach(id => {
const p = $(id);
if (p) p.className = 'status-pill err';
});
}
}
// ββ Admin controls ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function dockerAction(action) {
const labels = { up: 'βΆ Starting', down: 'β Stopping' };
dockerModalTitle.textContent = `${labels[action] || action} Databasesβ¦`;
dockerModalBody.textContent = 'Running docker compose, please waitβ¦';
dockerModal.style.display = 'flex';
diag.info('Docker action:', action);
try {
const r = await fetch(`/api/docker/${action}`, { method: 'POST' });
const data = await r.json();
diag.info('Docker response:', data);
dockerModalBody.innerHTML =
`<pre class="modal-pre">${escHtml(data.output || 'No output')}</pre>`;
if (data.ok) {
notify(`Database ${action} succeeded`, 'success');
setTimeout(refreshStatus, 3000);
} else {
notify(`Database ${action} failed`, 'error', 8000);
}
} catch(err) {
diag.error('Docker action failed:', err);
dockerModalBody.textContent = `Error: ${err.message}`;
notify(`Docker ${action} error: ${err.message}`, 'error', 8000);
}
}
async function adminPurge() {
if (!confirm("Are you sure you want to completely wipe ChromaDB and Kuzu? This cannot be undone.")) return;
diag.info('Purge DB action');
try {
const r = await fetch(`/api/admin/purge`, { method: 'POST' });
const data = await r.json();
if (data.ok) {
notify(data.msg, 'success', 5000);
await loadDocuments();
await refreshStatus();
} else {
notify(`Purge failed: ${data.error}`, 'error', 8000);
}
} catch(err) {
notify(`Purge error: ${err.message}`, 'error', 8000);
}
}
async function adminKill() {
if (!confirm("EMERGENCY KILL SWITCH: This will stop all databases and instantly kill the application server. Are you sure?")) return;
diag.info('Kill switch activated');
try {
const r = await fetch(`/api/admin/kill`, { method: 'POST' });
const data = await r.json();
if (data.ok) {
notify(data.msg, 'success', 10000);
document.body.innerHTML = "<h1 style='color:red; text-align:center; margin-top:20%'>APPLICATION TERMINATED</h1><p style='text-align:center'>Please restart the server manually.</p>";
} else {
notify(`Kill switch failed: ${data.error}`, 'error', 8000);
}
} catch(err) {
notify(`Kill switch error: ${err.message}`, 'error', 8000);
}
}
if ($('db-up-btn')) $('db-up-btn').addEventListener('click', () => dockerAction('up'));
if ($('db-down-btn')) $('db-down-btn').addEventListener('click', () => dockerAction('down'));
if ($('db-purge-btn')) $('db-purge-btn').addEventListener('click', adminPurge);
if ($('app-kill-btn')) $('app-kill-btn').addEventListener('click', adminKill);
if ($('docker-modal-close')) $('docker-modal-close').addEventListener('click', () => { dockerModal.style.display = 'none'; });
// ββ Resource Monitor Banner ββββββββββββββββββββββββββββββββββββββββββββββββββββ
function _resBarClass(pct) {
if (pct >= 90) return 'crit';
if (pct >= 70) return 'warn';
return '';
}
async function pollSysInfo() {
try {
const r = await fetch('/api/sysinfo');
if (!r.ok) return;
const d = await r.json();
if (d.error) return;
// CPU
const cpuPct = d.cpu_pct ?? 0;
const cpuCls = _resBarClass(cpuPct);
const cpuBar = $('res-cpu-bar');
const cpuPctEl = $('res-cpu-pct');
const cpuLabel = $('res-cpu-label');
if (cpuBar) { cpuBar.style.width = cpuPct + '%'; cpuBar.className = 'res-bar ' + cpuCls; }
if (cpuPctEl) { cpuPctEl.textContent = cpuPct.toFixed(0) + '%'; cpuPctEl.className = 'res-pct ' + cpuCls; }
if (cpuLabel) {
// Shorten: show first word of brand + core count
const brand = (d.cpu_brand || 'CPU').split(' ').slice(0,2).join(' ');
const mhz = d.cpu_mhz ? ` @ ${(d.cpu_mhz/1000).toFixed(1)}GHz` : '';
cpuLabel.textContent = `${brand} Γ${d.cpu_cores}${mhz}`;
}
// RAM
const ramPct = d.ram_pct ?? 0;
const ramCls = _resBarClass(ramPct);
const ramBar = $('res-ram-bar');
const ramPctEl = $('res-ram-pct');
const ramLabel = $('res-ram-label');
if (ramBar) { ramBar.style.width = ramPct + '%'; ramBar.className = 'res-bar ' + ramCls; }
if (ramPctEl) { ramPctEl.textContent = ramPct.toFixed(0) + '%'; ramPctEl.className = 'res-pct ' + ramCls; }
if (ramLabel) ramLabel.textContent = `RAM: ${d.ram_used_gb} / ${d.ram_total_gb} GB`;
// Disk
const diskPct = d.disk_pct ?? 0;
const diskCls = _resBarClass(diskPct);
const diskBar = $('res-disk-bar');
const diskPctEl = $('res-disk-pct');
const diskLabel = $('res-disk-label');
if (diskBar) { diskBar.style.width = diskPct + '%'; diskBar.className = 'res-bar ' + diskCls; }
if (diskPctEl) { diskPctEl.textContent = diskPct.toFixed(0) + '%'; diskPctEl.className = 'res-pct ' + diskCls; }
if (diskLabel) diskLabel.textContent = `Disk: ${d.disk_free_gb} / ${d.disk_total_gb} GB free`;
// Mode badge
const badge = $('res-mode-badge');
if (badge) {
const isHf = d.hf_mode || (window.APP_CONFIG && window.APP_CONFIG.hfMode);
badge.textContent = isHf ? 'β‘ HF / CPU Mode' : 'π₯ GPU Mode';
badge.className = 'res-mode-badge ' + (isHf ? 'hf-mode' : 'gpu-mode');
}
// GPU checkbox β show only if GPU is available
const gpuItem = $('res-gpu');
if (gpuItem) {
gpuItem.style.display = d.gpu_available ? 'flex' : 'none';
}
// CPU cores β populate up to system max (powers of 2)
const cpuCoresSelect = $('cpu-cores-select');
if (cpuCoresSelect && d.cpu_cores) {
const maxCores = d.cpu_cores;
const current = parseInt(cpuCoresSelect.value || '2', 10);
cpuCoresSelect.innerHTML = '';
let n = 2;
while (n <= maxCores) {
const opt = document.createElement('option');
opt.value = String(n);
opt.textContent = String(n);
if (n === current || (n === 2 && current < 2)) opt.selected = true;
cpuCoresSelect.appendChild(opt);
n *= 2;
}
// Ensure at least value=2 is present even if cpu_cores < 2
if (!cpuCoresSelect.options.length) {
const opt = document.createElement('option');
opt.value = '2'; opt.textContent = '2'; opt.selected = true;
cpuCoresSelect.appendChild(opt);
}
}
// Graph Extraction Active
const activeGraph = $('status-graph-active');
const dbGraph = $('status-graph');
if (d.active_graph_tasks > 0) {
if (activeGraph) activeGraph.style.display = 'flex';
if (dbGraph) dbGraph.style.display = 'none';
} else {
if (activeGraph) activeGraph.style.display = 'none';
if (dbGraph) dbGraph.style.display = 'flex';
}
} catch(err) {
diag.warn('pollSysInfo failed:', err);
}
}
// ββ Document list ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const TYPE_ICONS = {
pdf:'π', docx:'π', txt:'π', xlsx:'π', csv:'π',
png:'πΌοΈ', jpg:'πΌοΈ', jpeg:'πΌοΈ', webp:'πΌοΈ',
};
async function loadDocuments() {
diag.info('Loading document listβ¦');
try {
const r = await fetch('/api/documents');
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const data = await r.json();
diag.info(`Document list: ${data.total} document(s)`);
docList.innerHTML = '';
if (!data.documents?.length) {
docList.innerHTML = '<div class="empty-state">π No documents ingested yet.<br>Upload files above to get started.</div>';
return;
}
data.documents.forEach(doc => {
const icon = TYPE_ICONS[doc.file_type] || 'π';
const item = document.createElement('div');
item.className = 'doc-item';
const tierBadge = doc.tier === 'foundation'
? `<span style="font-size:10px; background:var(--blue); color:#fff; padding:2px 4px; border-radius:4px; margin-left:8px;">FOUNDATION</span>`
: `<span style="font-size:10px; background:var(--bg-panel); border:1px solid var(--border); padding:2px 4px; border-radius:4px; margin-left:8px;">EXTENDED</span>`;
item.innerHTML = `
<button class="doc-delete" title="Remove document" data-source="${escHtml(doc.source)}" data-tier="${doc.tier}">β</button>
<span class="doc-icon">${icon}</span>
<div class="doc-info">
<div class="doc-name" title="${escHtml(doc.source)}">${escHtml(doc.source)} ${tierBadge}</div>
<div class="doc-type">${doc.file_type.toUpperCase()}</div>
</div>`;
docList.appendChild(item);
});
docList.querySelectorAll('.doc-delete').forEach(btn => {
btn.addEventListener('click', () => deleteDocument(btn.dataset.source, btn.dataset.tier));
});
} catch(err) {
diag.error('loadDocuments failed:', err);
notify(`Failed to load documents: ${err.message}`, 'error');
}
}
async function deleteDocument(source, tier) {
diag.info('Deleting document:', source, tier);
try {
const r = await fetch(`/api/documents/${encodeURIComponent(source)}?tier=${tier}`, { method: 'DELETE' });
const data = await r.json();
diag.info('Delete response:', data);
notify(`Removed "${source}" (${data.deleted_chunks} chunks)`, 'info');
await loadDocuments();
await refreshStatus();
} catch(err) {
diag.error('Delete failed:', err);
notify(`Delete failed: ${err.message}`, 'error');
}
}
$('refresh-docs-btn').addEventListener('click', loadDocuments);
// ββ Drag & Drop & Tier Selection βββββββββββββββββββββββββββββββββββββββββββ
let pendingFiles = [];
const tierModal = $('tier-modal');
const tierCancel = $('tier-modal-cancel');
const tierConfirm = $('tier-modal-confirm');
const tierFoundationLabel = $('tier-foundation-label');
function openTierModal(files) {
if (!files.length) return;
pendingFiles = files;
if (!state.isAdmin) {
if(tierFoundationLabel) {
tierFoundationLabel.style.opacity = '0.5';
tierFoundationLabel.querySelector('input').disabled = true;
}
document.querySelector('input[value="extended"]').checked = true;
} else {
if(tierFoundationLabel) {
tierFoundationLabel.style.opacity = '1';
tierFoundationLabel.querySelector('input').disabled = false;
}
}
if (tierModal) tierModal.style.display = 'flex';
}
if (tierCancel) {
tierCancel.addEventListener('click', () => {
tierModal.style.display = 'none';
pendingFiles = [];
});
}
let expectedCaptchaAnswer = 0;
const captchaModal = $('captcha-modal');
const captchaQuestion = $('captcha-question');
const captchaInput = $('captcha-input');
const captchaError = $('captcha-error');
const captchaCancel = $('captcha-modal-cancel');
const captchaVerify = $('captcha-modal-verify');
function generateCaptcha() {
const a = Math.floor(Math.random() * 10) + 1;
const b = Math.floor(Math.random() * 10) + 1;
expectedCaptchaAnswer = a + b;
if (captchaQuestion) captchaQuestion.textContent = `${a} + ${b} =`;
if (captchaInput) captchaInput.value = '';
if (captchaError) captchaError.style.display = 'none';
}
if (tierConfirm) {
tierConfirm.addEventListener('click', () => {
tierModal.style.display = 'none';
generateCaptcha();
if (captchaModal) captchaModal.style.display = 'flex';
if (captchaInput) captchaInput.focus();
});
}
if (captchaCancel) {
captchaCancel.addEventListener('click', () => {
captchaModal.style.display = 'none';
pendingFiles = [];
});
}
if (captchaVerify) {
const verifyAndProceed = () => {
const userAns = parseInt(captchaInput.value, 10);
if (userAns === expectedCaptchaAnswer) {
captchaModal.style.display = 'none';
const selectedTier = document.querySelector('input[name="kb_tier"]:checked').value;
ingestFiles(pendingFiles, selectedTier);
} else {
captchaError.style.display = 'block';
captchaInput.value = '';
captchaInput.focus();
}
};
captchaVerify.addEventListener('click', verifyAndProceed);
if (captchaInput) {
captchaInput.addEventListener('keydown', e => {
if (e.key === 'Enter') verifyAndProceed();
});
}
}
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('keydown', e => { if (e.key === 'Enter') fileInput.click(); });
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('drag-over'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
dropZone.addEventListener('drop', e => {
e.preventDefault();
dropZone.classList.remove('drag-over');
const files = Array.from(e.dataTransfer.files);
diag.info(`Dropped ${files.length} file(s):`, files.map(f => f.name));
openTierModal(files);
});
fileInput.addEventListener('change', () => {
const files = Array.from(fileInput.files);
diag.info(`Selected ${files.length} file(s):`, files.map(f => f.name));
openTierModal(files);
});
// ββ Ingestion ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function ingestFiles(files, tier) {
if (!files.length) {
notify('No files selected.', 'error');
return;
}
if (state.isIngesting) {
notify('Ingestion already in progress β please wait.', 'warn');
return;
}
state.isIngesting = true;
clearLog();
ingestLogDetails.open = true;
ingestProgress.style.display = 'block';
progressFill.style.width = '5%';
appendLog(`Starting upload of ${files.length} file(s)β¦`);
files.forEach(f => appendLog(` β ${f.name} (${(f.size/1024).toFixed(1)} KB)`));
const fd = new FormData();
files.forEach(f => fd.append('files', f));
fd.append('tier', tier);
diag.group('Ingestion');
diag.info('POST /api/ingest with', files.length, 'file(s) for tier:', tier);
try {
const r = await fetch('/api/ingest', { method: 'POST', body: fd });
const data = await r.json();
diag.info('Ingest response:', data);
if (!r.ok || data.error) {
const msg = data.error || `HTTP ${r.status}`;
appendLog(`β Upload rejected: ${msg}`);
notify(`Upload failed: ${msg}`, 'error', 8000);
diag.error('Ingest API error:', msg);
return;
}
if (data.rejected?.length) {
data.rejected.forEach(rej => {
appendLog(`β οΈ Rejected: ${rej}`);
notify(`Rejected: ${rej}`, 'warn', 7000);
});
}
appendLog(`β
Uploaded ${data.files.length} file(s). Job ID: ${data.job_id}`);
ingestStatusTxt.textContent = `Processing ${data.files.join(', ')}β¦`;
progressFill.style.width = '20%';
state.currentJobId = data.job_id;
pollJobStatus(data.job_id);
} catch(err) {
appendLog(`β Network error: ${err.message}`);
diag.error('Ingest fetch error:', err);
notify(`Upload failed: ${err.message}`, 'error', 8000);
state.isIngesting = false;
ingestProgress.style.display = 'none';
} finally {
diag.groupEnd();
}
}
async function pollJobStatus(jobId) {
const poll = async () => {
try {
const r = await fetch(`/api/ingest/status/${jobId}`);
if (!r.ok) throw new Error(`Status HTTP ${r.status}`);
const data = await r.json();
if (data.error) {
appendLog(`β Job error: ${data.error}`);
notify(data.error, 'error', 8000);
state.isIngesting = false;
ingestProgress.style.display = 'none';
return;
}
// Sync new log lines
const allLog = data.log || [];
const shown = ingestLog.childElementCount;
allLog.slice(shown).forEach(line => appendLog(line));
const pct = Math.min(20 + (data.results.length / Math.max(data.total, 1)) * 70, 90);
progressFill.style.width = `${pct}%`;
ingestStatusTxt.textContent = `Processing⦠${data.results.length}/${data.total} file(s) done`;
if (data.status === 'done') {
progressFill.style.width = '100%';
const ok = data.results.filter(r => r.ok).length;
const bad = data.results.filter(r => !r.ok).length;
// Show per-file results
data.results.forEach(res => {
if (res.ok) {
appendLog(`β
${res.file}: ${res.result}`);
} else {
appendLog(`β ${res.file}: FAILED β ${res.result}`);
diag.error('File failed:', res.file, res.result);
}
});
ingestStatusTxt.textContent = `Done β ${ok} succeeded${bad ? `, ${bad} failed` : ''}`;
if (ok) notify(`Ingested ${ok} file(s) successfully`, 'success', 5000);
if (bad) notify(`${bad} file(s) failed β see diagnostic log`, 'error', 8000);
if (data.rejected?.length)
notify(`${data.rejected.length} file(s) rejected (unsupported type)`, 'warn', 7000);
setTimeout(() => {
ingestProgress.style.display = 'none';
progressFill.style.width = '0%';
}, 3000);
state.isIngesting = false;
fileInput.value = '';
await loadDocuments();
await refreshStatus();
diag.info('Ingestion complete β ok:', ok, 'failed:', bad);
} else {
setTimeout(poll, 1200);
}
} catch(err) {
diag.error('pollJobStatus error:', err);
appendLog(`β οΈ Poll error: ${err.message} β retryingβ¦`);
setTimeout(poll, 3000);
}
};
poll();
}
// ββ Default prompt buttons βββββββββββββββββββββββββββββββββββββββββββββββββββββ
$('preset-gen').addEventListener('click', async () => {
diag.info('Probing nvidia_llm serverβ¦');
notify('Testing Gen LLM server (port 8002)β¦', 'info', 3000);
const btn = $('preset-gen');
btn.disabled = true;
try {
const r = await fetch('/api/probe/gen', { method: 'POST' });
const data = await r.json();
diag.info('Gen LLM probe result:', data);
if (data.ok) {
addChatMsg(
`π§ <strong>Gen LLM probe succeeded</strong><br>` +
`Model: <code>${escHtml(data.model)}</code><br>` +
`Response: <em>${escHtml(data.response)}</em>`,
'assistant'
);
renderOutput(`## Gen LLM Test β
\n**Model:** \`${data.model}\`\n\n**Response:** ${data.response}`);
notify('Gen LLM is online and responding!', 'success');
} else {
addChatMsg(`β Gen LLM offline: ${escHtml(data.error)}`, 'assistant');
notify(`Gen LLM probe failed: ${data.error}`, 'error', 8000);
}
} catch(err) {
diag.error('Gen probe fetch error:', err);
notify(`Gen LLM probe error: ${err.message}`, 'error', 8000);
}
btn.disabled = false;
});
// ββ Question dropdown βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const questionSelect = document.getElementById('question-select');
if (questionSelect) {
questionSelect.addEventListener('change', () => {
const val = questionSelect.value;
if (!val) return;
queryInput.value = val;
queryInput.style.height = 'auto';
queryInput.style.height = Math.min(queryInput.scrollHeight, 160) + 'px';
questionSelect.value = '';
submitQuery();
});
}
$('preset-embed').addEventListener('click', async () => {
diag.info('Probing embed_llm serverβ¦');
notify('Testing Embed LLM server (port 8003)β¦', 'info', 3000);
const btn = $('preset-embed');
btn.disabled = true;
try {
const r = await fetch('/api/probe/embed', { method: 'POST' });
const data = await r.json();
diag.info('Embed LLM probe result:', data);
if (data.ok) {
addChatMsg(
`π’ <strong>Embed LLM probe succeeded</strong><br>` +
`Model: <code>${escHtml(data.model)}</code><br>` +
`Dimension: <strong>${data.dim}</strong> Β· ` +
`Sample: <code>[${data.sample.map(v => v.toFixed(4)).join(', ')}β¦]</code>`,
'assistant'
);
renderOutput(
`## Embed LLM Test β
\n**Model:** \`${data.model}\`\n\n` +
`**Embedding dimension:** ${data.dim}\n\n` +
`**First 5 values:** \`[${data.sample.map(v => v.toFixed(6)).join(', ')}]\``
);
notify(`Embed LLM is online! Dim=${data.dim}`, 'success');
} else {
addChatMsg(`β Embed LLM offline: ${escHtml(data.error)}`, 'assistant');
notify(`Embed LLM probe failed: ${data.error}`, 'error', 8000);
}
} catch(err) {
diag.error('Embed probe fetch error:', err);
notify(`Embed LLM probe error: ${err.message}`, 'error', 8000);
}
btn.disabled = false;
});
// ββ Query / Chat βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
document.querySelectorAll('.prompt-fill-btn').forEach(btn => {
btn.addEventListener('click', () => {
queryInput.value = btn.innerText;
queryInput.style.height = 'auto';
queryInput.style.height = Math.min(queryInput.scrollHeight, 160) + 'px';
submitQuery();
});
});
queryInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
submitQuery();
}
});
queryInput.addEventListener('input', () => {
queryInput.style.height = 'auto';
queryInput.style.height = Math.min(queryInput.scrollHeight, 160) + 'px';
});
sendBtn.addEventListener('click', submitQuery);
function addChatMsg(html, role) {
const wrap = document.createElement('div');
wrap.className = `chat-msg ${role}`;
const avatar = role === 'user' ? 'π€' : 'π₯';
const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
wrap.innerHTML = `
<div class="chat-avatar">${avatar}</div>
<div>
<div class="chat-bubble">${role === 'user' ? escHtml(html) : html}</div>
<div class="chat-time">${time}</div>
</div>`;
chatHistory.appendChild(wrap);
wrap.scrollIntoView({ behavior: 'smooth', block: 'end' });
return wrap;
}
function addThinkingMsg(qId) {
const wrap = document.createElement('div');
wrap.className = 'chat-msg assistant';
wrap.innerHTML = `
<div class="chat-avatar">π₯</div>
<div>
<div class="chat-bubble">
<div class="milestone-graph" id="milestone-graph-${qId}">
<div class="milestone" id="ms-graph-${qId}">
<div class="milestone-dot"></div>
<div>
<span>GraphDB <span class="milestone-timer" data-time="0">(0.0s)</span></span>
<div class="milestone-chunks"></div>
</div>
</div>
<div class="milestone-line"></div>
<div class="milestone" id="ms-vector-${qId}">
<div class="milestone-dot"></div>
<div>
<span>Vector DB <span class="milestone-timer" data-time="0">(0.0s)</span></span>
<div class="milestone-chunks"></div>
</div>
</div>
<div class="milestone-line"></div>
<div class="milestone" id="ms-bm25-${qId}">
<div class="milestone-dot"></div>
<div>
<span>BM25 Search <span class="milestone-timer" data-time="0">(0.0s)</span></span>
<div class="milestone-chunks"></div>
</div>
</div>
<div class="milestone-line"></div>
<div class="milestone" id="ms-ranking-${qId}">
<div class="milestone-dot"></div>
<span>Cross-Encoder Reranking <span class="milestone-timer" data-time="0">(0.0s)</span></span>
</div>
<div class="milestone-line"></div>
<div class="milestone" id="ms-analysis-${qId}">
<div class="milestone-dot"></div>
<div>
<span>LLM Analysis <span class="milestone-timer" data-time="0">(0.0s)</span></span>
<div class="milestone-tokens"></div>
</div>
</div>
</div>
</div>
</div>`;
chatHistory.appendChild(wrap);
wrap.scrollIntoView({ behavior: 'smooth', block: 'end' });
return wrap;
}
async function submitQuery() {
const q = queryInput.value.trim();
if (!q || state.isQuerying) return;
state.isQuerying = true;
sendBtn.disabled = true;
queryInput.value = '';
queryInput.style.height = 'auto';
diag.group('Query');
diag.info('Query:', q);
addChatMsg(q, 'user');
// On mobile, scroll the chat panel into view so the user sees the response
if (document.body.classList.contains('is-mobile')) {
const chatPanel = document.getElementById('chat-panel');
if (chatPanel) chatPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
const qId = Date.now();
const thinkingEl = addThinkingMsg(qId);
outputContainer.innerHTML = `<div class="output-placeholder">
<div class="ph-icon">βοΈ</div>
<div>Analyzing healthcare policy documentsβ¦</div>
</div>`;
metricsBanner.style.display = 'none';
metricsBanner.innerHTML = '';
citationsBlock.innerHTML = '';
copyBtn.style.display = 'none';
let fullText = '';
let chunkCount = 0;
// Hoisted outside try{} so catch{} and finally{} can access them
// (let/function inside try{} are block-scoped and invisible to catch{})
let currentTimerInterval = null;
let currentMsId = null;
let currentStartTime = 0;
function startTimer(msId) {
if (currentTimerInterval) clearInterval(currentTimerInterval);
currentMsId = msId;
currentStartTime = Date.now();
currentTimerInterval = setInterval(() => {
const el = $(currentMsId);
if (!el) return;
const timerSpan = el.querySelector('.milestone-timer');
if (timerSpan) {
const s = (Date.now() - currentStartTime) / 1000;
timerSpan.innerText = `(${s.toFixed(1)}s)`;
timerSpan.dataset.time = s.toFixed(1);
}
}, 100);
}
function stopTimer() {
if (currentTimerInterval) clearInterval(currentTimerInterval);
currentTimerInterval = null;
}
try {
const topK = parseInt($('top-k-select')?.value || 10, 10);
const maxTokens = parseInt($('max-tokens-select')?.value || 1024, 10);
const useVector = $('chk-vector')?.checked ?? true;
const useGraph = $('chk-graph')?.checked ?? true;
const useBm25 = $('chk-bm25')?.checked ?? true;
const useGpu = $('chk-gpu')?.checked ?? false;
const cpuThreads = parseInt($('cpu-cores-select')?.value || 2, 10);
diag.info('POST /api/query', { query: q, top_k: topK, max_tokens: maxTokens, use_vector: useVector, use_graph: useGraph, use_bm25: useBm25, use_gpu: useGpu, cpu_threads: cpuThreads });
// Grey out disabled milestones
if (!useGraph) $(`ms-graph-${qId}`)?.classList.add('disabled');
if (!useVector) $(`ms-vector-${qId}`)?.classList.add('disabled');
if (!useBm25) $(`ms-bm25-${qId}`)?.classList.add('disabled');
const startResp = await fetch('/api/query/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: q, top_k: topK, max_tokens: maxTokens, use_vector: useVector, use_graph: useGraph, use_bm25: useBm25, use_gpu: useGpu, cpu_threads: cpuThreads }),
});
if (!startResp.ok) {
const errData = await startResp.json();
throw new Error(errData.error || `HTTP ${startResp.status}`);
}
const startData = await startResp.json();
const jobId = startData.job_id;
let currentOffset = 0;
let jobDone = false;
while (!jobDone) {
try {
const resp = await fetch(`/api/query/stream/${jobId}?offset=${currentOffset}`);
if (!resp.ok) {
const errData = await resp.json().catch(() => ({}));
if (resp.status === 404) throw new Error("Job not found or expired on server.");
throw new Error(errData.error || `HTTP ${resp.status}`);
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (!jobDone) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
let payload;
try { payload = JSON.parse(line.slice(6)); }
catch(pe) { diag.warn('SSE parse error:', pe, line); continue; }
// Successfully received a valid JSON payload, increment offset for next reconnect
currentOffset++;
if (payload.error) {
jobDone = true;
throw new Error(payload.error);
}
if (payload.status) {
diag.info('SSE status:', payload.status);
const msGraph = $(`ms-graph-${qId}`);
const msVector = $(`ms-vector-${qId}`);
const msBm25 = $(`ms-bm25-${qId}`);
const msRanking = $(`ms-ranking-${qId}`);
const msAnalysis = $(`ms-analysis-${qId}`);
if (!msGraph || !msAnalysis) continue;
// Mark previous executing dot as complete before starting next
[msGraph, msVector, msBm25, msRanking, msAnalysis].forEach(el => {
if (!el) return;
const dot = el.querySelector('.milestone-dot');
if (dot && dot.className.includes('executing')) {
dot.className = 'milestone-dot complete';
}
});
if (payload.status === 'graph') {
msGraph.querySelector('.milestone-dot').className = 'milestone-dot executing';
startTimer(`ms-graph-${qId}`);
} else if (payload.status === 'inference' || payload.status === 'vector') {
stopTimer();
if(msGraph) msGraph.querySelector('.milestone-dot').className = 'milestone-dot complete';
if(msVector) msVector.querySelector('.milestone-dot').className = 'milestone-dot executing';
startTimer(`ms-vector-${qId}`);
} else if (payload.status === 'bm25') {
stopTimer();
if(msVector) msVector.querySelector('.milestone-dot').className = 'milestone-dot complete';
if(msBm25) msBm25.querySelector('.milestone-dot').className = 'milestone-dot executing';
startTimer(`ms-bm25-${qId}`);
} else if (payload.status === 'reranking') {
stopTimer();
if(msBm25) msBm25.querySelector('.milestone-dot').className = 'milestone-dot complete';
if(msRanking) msRanking.querySelector('.milestone-dot').className = 'milestone-dot executing';
startTimer(`ms-ranking-${qId}`);
} else if (payload.status === 'gatekeeping') {
// Gatekeeper is instant
stopTimer();
if(msRanking) msRanking.querySelector('.milestone-dot').className = 'milestone-dot complete';
} else if (payload.status === 'analysis') {
stopTimer();
if(msRanking) msRanking.querySelector('.milestone-dot').className = 'milestone-dot complete';
if(msAnalysis) msAnalysis.querySelector('.milestone-dot').className = 'milestone-dot executing';
startTimer(`ms-analysis-${qId}`);
}
if (payload.chunks !== undefined) {
let targetMs = null;
if (payload.status === 'graph') targetMs = msGraph;
if (payload.status === 'vector') targetMs = msVector;
if (payload.status === 'bm25') targetMs = msBm25;
if (targetMs) {
const chunkDiv = targetMs.querySelector('.milestone-chunks');
if (chunkDiv) {
chunkDiv.innerText = `${payload.chunks} chunk(s) retrieved`;
chunkDiv.classList.add('visible');
}
}
}
}
// ββ Answer chunks β render output βββββββββββββββββββββββββββ
if (payload.chunk) {
// Mark analysis milestone complete on first chunk arrival
if (currentMsId) {
const el = $(currentMsId);
const dot = el ? el.querySelector('.milestone-dot') : null;
if (dot && dot.className.includes('executing')) {
dot.className = 'milestone-dot complete';
stopTimer();
}
}
fullText += payload.chunk;
chunkCount++;
renderOutput(fullText);
}
// ββ Metrics β banner at top of output panel βββββββββββββββββ
if (payload.metrics) {
const m = payload.metrics;
const min = Math.floor(m.time_seconds / 60);
const sec = Math.round(m.time_seconds % 60);
const timeStr = min > 0 ? `${min}m ${sec}s` : `${sec}s`;
const carbonStr = m.carbon_kg < 0.001 ? '< 1g' : (m.carbon_kg * 1000).toFixed(2) + 'g';
renderMetricsBanner(m.tokens_in, m.tokens_out, timeStr, carbonStr);
const localMsAnalysis = document.getElementById(`ms-analysis-${qId}`);
if (localMsAnalysis) {
const tokDiv = localMsAnalysis.querySelector('.milestone-tokens');
if (tokDiv) {
tokDiv.innerText = `In: ${m.tokens_in} | Out: ${m.tokens_out}`;
}
}
}
if (payload.done) {
diag.info('SSE: done');
jobDone = true;
break;
}
}
}
} catch (err) {
if (err.message.includes("Job not found") || jobDone) {
throw err;
}
diag.warn('Network dropped, reconnecting to job...', err);
await new Promise(r => setTimeout(r, 1500));
}
}
diag.info(`Query complete β ${chunkCount} SSE chunks, ${fullText.length} chars`);
stopTimer();
// Ensure all milestone dots are marked complete
[$(`ms-inference-${qId}`), $(`ms-kuzu-${qId}`), $(`ms-analysis-${qId}`)].forEach(el => {
if (!el) return;
const dot = el.querySelector('.milestone-dot');
if (dot && !dot.className.includes('failed')) dot.className = 'milestone-dot complete';
});
addChatMsg('Answer generated β see the Output panel β', 'assistant');
copyBtn.style.display = 'block';
state.lastAnswer = fullText;
notify('Answer ready!', 'success', 2500);
// On mobile, scroll to output panel after answer is ready
if (document.body.classList.contains('is-mobile')) {
const outputPanel = document.getElementById('output-panel');
if (outputPanel) setTimeout(() => outputPanel.scrollIntoView({ behavior: 'smooth', block: 'start' }), 300);
}
} catch(err) {
diag.error('Query error:', err);
stopTimer();
let errorMsg = err.message;
if (currentMsId) {
const el = $(currentMsId);
if (el) el.querySelector('.milestone-dot').className = 'milestone-dot failed';
}
addChatMsg(`β ${escHtml(errorMsg)}`, 'assistant');
outputContainer.innerHTML = `<div class="output-placeholder" style="color:var(--red)">
<div class="ph-icon">β οΈ</div><div>${escHtml(errorMsg)}</div>
</div>`;
notify(errorMsg, 'error', 8000);
} finally {
state.isQuerying = false;
sendBtn.disabled = false;
diag.groupEnd();
}
}
// ββ Output rendering βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function renderOutput(mdText) {
outputContainer.innerHTML = marked.parse(mdText);
outputContainer.scrollTop = outputContainer.scrollHeight;
}
// ββ Metrics banner (pinned at top of output panel) ββββββββββββββββββββββββββββ
function renderMetricsBanner(tokIn, tokOut, timeStr, carbonStr) {
metricsBanner.innerHTML = `
<div class="metrics-banner-inner">
<span class="metrics-title">π Inference Metrics</span>
<span class="metrics-pill">π’ <strong>${tokIn}</strong> in / <strong>${tokOut}</strong> out tokens</span>
<span class="metrics-pill">β± <strong>${timeStr}</strong></span>
<span class="metrics-pill">π± <strong>${carbonStr}</strong> COβ</span>
</div>`;
metricsBanner.style.display = 'block';
}
function extractAndShowCitations(mdText) {
const matches = [...new Set(mdText.match(/\[Source:\s*([^\]]+)\]/g) || [])];
if (!matches.length) return;
citationsBlock.innerHTML = '<div style="font-size:11px;color:var(--text-muted);margin-bottom:6px;">π Sources</div>'
+ matches.map(m => `<span class="citation-tag">π ${escHtml(m)}</span>`).join('');
}
// ββ Copy button ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
copyBtn.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(outputContainer.innerText);
copyBtn.textContent = 'β Copied!';
notify('Response copied to clipboard', 'info', 2000);
} catch(err) {
diag.error('Clipboard write failed:', err);
notify('Could not copy β try selecting text manually', 'warn');
}
setTimeout(() => { copyBtn.textContent = 'β Copy Response'; }, 2000);
});
// ββ Utils ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function escHtml(s) {
return String(s)
.replace(/&/g,'&').replace(/</g,'<')
.replace(/>/g,'>').replace(/"/g,'"');
}
// ββ Auto-ingest background progress banner βββββββββββββββββββββββββββββββββββββ
const autoIngestBanner = $('auto-ingest-banner');
const autoIngestBar = $('auto-ingest-bar');
const autoIngestLabel = $('auto-ingest-label');
const autoIngestSub = $('auto-ingest-sub');
const autoIngestCount = $('auto-ingest-count');
let _autoIngestPollTimer = null;
let _autoIngestDoneNotified = false;
async function pollAutoIngestStatus() {
try {
const r = await fetch('/api/auto-ingest/status');
if (!r.ok) return;
const d = await r.json();
const isActive = d.running || (d.total > 0 && !d.done);
const isDone = d.done && d.total > 0;
if (isActive) {
// Show and update banner
if (autoIngestBanner) {
autoIngestBanner.style.display = 'block';
document.body.classList.add('ingest-banner-visible');
}
const pct = d.total > 0 ? Math.round((d.completed / d.total) * 100) : 5;
if (autoIngestBar) autoIngestBar.style.width = pct + '%';
if (autoIngestLabel) autoIngestLabel.textContent = 'Indexing knowledge baseβ¦';
if (autoIngestSub) autoIngestSub.textContent = d.current_file ? `Processing: ${d.current_file}` : 'Preparingβ¦';
if (autoIngestCount) autoIngestCount.textContent = `${d.completed} / ${d.total}`;
} else if (isDone && !_autoIngestDoneNotified) {
// Show completion state briefly then hide
_autoIngestDoneNotified = true;
if (autoIngestBanner) autoIngestBanner.style.display = 'block';
if (autoIngestBar) autoIngestBar.style.width = '100%';
const ok = (d.results || []).filter(x => x.ok).length;
const bad = (d.results || []).filter(x => !x.ok).length;
if (autoIngestLabel) autoIngestLabel.textContent = `Knowledge base ready β ${ok} file${ok !== 1 ? 's' : ''} indexed`;
if (autoIngestSub) autoIngestSub.textContent = bad > 0 ? `β οΈ ${bad} file(s) failed` : 'β All files ingested successfully';
if (autoIngestCount) autoIngestCount.textContent = `${ok} / ${d.total}`;
if (ok > 0) notify(`Auto-ingest complete: ${ok} knowledge base file${ok !== 1 ? 's' : ''} indexed`, 'success', 6000);
if (bad > 0) notify(`Auto-ingest: ${bad} file(s) failed to ingest`, 'warn', 8000);
// Refresh document list to show newly ingested docs
await loadDocuments();
await refreshStatus();
// Fade out banner after 4 seconds
setTimeout(() => {
if (autoIngestBanner) autoIngestBanner.style.display = 'none';
document.body.classList.remove('ingest-banner-visible');
}, 4000);
// Stop polling
if (_autoIngestPollTimer) clearInterval(_autoIngestPollTimer);
_autoIngestPollTimer = null;
return;
} else if (d.error && !_autoIngestDoneNotified) {
_autoIngestDoneNotified = true;
notify(`Auto-ingest error: ${d.error}`, 'error', 8000);
if (_autoIngestPollTimer) clearInterval(_autoIngestPollTimer);
_autoIngestPollTimer = null;
return;
} else {
// Not started yet or no files β keep banner hidden
if (autoIngestBanner) autoIngestBanner.style.display = 'none';
document.body.classList.remove('ingest-banner-visible');
}
} catch (err) {
diag.warn('pollAutoIngestStatus error:', err);
}
}
// ββ Init βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
(async () => {
diag.info('App initialisingβ¦');
await refreshStatus();
await loadDocuments();
await pollSysInfo(); // Initial resource banner population
await pollAutoIngestStatus(); // Check if auto-ingest is already running
setInterval(refreshStatus, 30_000);
setInterval(pollSysInfo, 10_000); // Update resource banner every 10 s
// Poll auto-ingest every 2 s (self-cancels when done)
_autoIngestPollTimer = setInterval(pollAutoIngestStatus, 2000);
diag.info('App ready.');
})();
|