File size: 40,970 Bytes
0f53af1 35909d0 0f53af1 35909d0 67ce4fe aed5ad1 35909d0 67ce4fe 35909d0 67ce4fe aed5ad1 67ce4fe aed5ad1 00d06b4 35909d0 84aba11 35909d0 0f53af1 35909d0 0f53af1 67ce4fe 0f53af1 35909d0 e71283a 0f53af1 aed5ad1 e71283a aed5ad1 e71283a aed5ad1 35909d0 aed5ad1 35909d0 aed5ad1 0f53af1 35909d0 0f53af1 35909d0 84aba11 35909d0 0f53af1 35909d0 0f53af1 35909d0 84aba11 35909d0 0f53af1 35909d0 0f53af1 aed5ad1 e71283a aed5ad1 67ce4fe aed5ad1 35909d0 67ce4fe 84aba11 aed5ad1 0f53af1 35909d0 0f53af1 aed5ad1 35909d0 aed5ad1 35909d0 aed5ad1 00d06b4 0f53af1 35909d0 0f53af1 35909d0 aed5ad1 35909d0 84aba11 35909d0 aed5ad1 0f53af1 aed5ad1 35909d0 aed5ad1 35909d0 84aba11 35909d0 aed5ad1 0f53af1 aed5ad1 0f53af1 35909d0 aed5ad1 67ce4fe 00d06b4 35909d0 aed5ad1 67ce4fe aed5ad1 73a2b92 00d06b4 35909d0 aed5ad1 0f53af1 aed5ad1 35909d0 aed5ad1 35909d0 00d06b4 aed5ad1 67ce4fe aed5ad1 35909d0 aed5ad1 0f53af1 35909d0 aed5ad1 73a2b92 aed5ad1 35909d0 e71283a 35909d0 73a2b92 35909d0 73a2b92 35909d0 84aba11 35909d0 67ce4fe e71283a 73a2b92 e71283a 73a2b92 e71283a 73a2b92 e71283a 73a2b92 e71283a 67ce4fe e71283a 35909d0 73a2b92 67ce4fe 35909d0 84aba11 73a2b92 35909d0 67ce4fe 35909d0 73a2b92 35909d0 e71283a 35909d0 73a2b92 35909d0 73a2b92 35909d0 73a2b92 84aba11 35909d0 73a2b92 35909d0 73a2b92 35909d0 73a2b92 84aba11 35909d0 aed5ad1 35909d0 73a2b92 35909d0 73a2b92 35909d0 73a2b92 35909d0 aed5ad1 35909d0 aed5ad1 35909d0 aed5ad1 35909d0 aed5ad1 73a2b92 35909d0 73a2b92 35909d0 aed5ad1 35909d0 73a2b92 35909d0 73a2b92 35909d0 aed5ad1 73a2b92 0f53af1 aed5ad1 35909d0 aed5ad1 35909d0 73a2b92 35909d0 aed5ad1 35909d0 73a2b92 35909d0 73a2b92 35909d0 84aba11 35909d0 84aba11 35909d0 aed5ad1 35909d0 84aba11 35909d0 84aba11 35909d0 aed5ad1 35909d0 aed5ad1 00d06b4 35909d0 aed5ad1 35909d0 aed5ad1 35909d0 aed5ad1 67ce4fe 35909d0 aed5ad1 73a2b92 35909d0 aed5ad1 35909d0 aed5ad1 73a2b92 35909d0 aed5ad1 35909d0 e71283a 35909d0 aed5ad1 35909d0 aed5ad1 35909d0 aed5ad1 73a2b92 84aba11 aed5ad1 35909d0 73a2b92 35909d0 aed5ad1 73a2b92 84aba11 aed5ad1 35909d0 73a2b92 35909d0 aed5ad1 35909d0 73a2b92 84aba11 35909d0 84aba11 35909d0 73a2b92 35909d0 e71283a 73a2b92 e71283a 35909d0 84aba11 35909d0 84aba11 35909d0 aed5ad1 35909d0 aed5ad1 35909d0 aed5ad1 00d06b4 35909d0 aed5ad1 35909d0 aed5ad1 35909d0 0f53af1 67ce4fe 35909d0 73a2b92 35909d0 e71283a 35909d0 73a2b92 35909d0 e71283a 35909d0 e71283a 35909d0 e71283a 35909d0 73a2b92 35909d0 aed5ad1 35909d0 0f53af1 35909d0 84aba11 35909d0 73a2b92 35909d0 73a2b92 35909d0 73a2b92 35909d0 73a2b92 35909d0 84aba11 0f53af1 35909d0 73a2b92 35909d0 73a2b92 84aba11 35909d0 84aba11 35909d0 67ce4fe 35909d0 67ce4fe 84aba11 67ce4fe 84aba11 35909d0 67ce4fe 84aba11 67ce4fe 84aba11 67ce4fe 35909d0 84aba11 67ce4fe 84aba11 67ce4fe 35909d0 84aba11 aed5ad1 35909d0 67ce4fe 0f53af1 67ce4fe 84aba11 0f53af1 35909d0 67ce4fe 84aba11 35909d0 84aba11 35909d0 84aba11 35909d0 84aba11 00d06b4 35909d0 84aba11 0f53af1 35909d0 73a2b92 35909d0 84aba11 0f53af1 35909d0 84aba11 0f53af1 35909d0 0f53af1 67ce4fe |
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 |
// SPDX-FileCopyrightText: Hadad <hadad@linuxmail.org>
// SPDX-License-Identifier: Apache-2.0
// Prism for code highlighting
Prism.plugins.autoloader.languages_path = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/';
// UI elements
const uiElements = {
chatArea: document.getElementById('chatArea'),
chatBox: document.getElementById('chatBox'),
initialContent: document.getElementById('initialContent'),
form: document.getElementById('footerForm'),
input: document.getElementById('userInput'),
sendBtn: document.getElementById('sendBtn'),
stopBtn: document.getElementById('stopBtn'),
fileBtn: document.getElementById('fileBtn'),
audioBtn: document.getElementById('audioBtn'),
fileInput: document.getElementById('fileInput'),
audioInput: document.getElementById('audioInput'),
filePreview: document.getElementById('filePreview'),
audioPreview: document.getElementById('audioPreview'),
promptItems: document.querySelectorAll('.prompt-item'),
chatHeader: document.getElementById('chatHeader'),
clearBtn: document.getElementById('clearBtn'),
messageLimitWarning: document.getElementById('messageLimitWarning'),
conversationTitle: document.getElementById('conversationTitle'),
sidebar: document.getElementById('sidebar'),
sidebarToggle: document.getElementById('sidebarToggle'),
conversationList: document.getElementById('conversationList'),
newConversationBtn: document.getElementById('newConversationBtn'),
swipeHint: document.getElementById('swipeHint'),
settingsBtn: document.getElementById('settingsBtn'),
settingsModal: document.getElementById('settingsModal'),
closeSettingsBtn: document.getElementById('closeSettingsBtn'),
settingsForm: document.getElementById('settingsForm'),
historyToggle: document.getElementBy AOS.init({
duration: 800,
easing: 'ease-out-cubic',
once: true,
offset: 50,
});
if (currentConversationId && checkAuth()) {
console.log('Loading conversation with ID:', currentConversationId);
await loadConversation(currentConversationId);
} else if (conversationHistory.length > 0) {
console.log('Restoring conversation history from sessionStorage:', conversationHistory);
enterChatView();
conversationHistory.forEach(msg => {
console.log('Adding message from history:', msg);
addMsg(msg.role, msg.content);
});
} else {
console.log('No conversation history or ID, starting fresh');
}
autoResizeTextarea();
updateSendButtonState();
if (uiElements.swipeHint) {
setTimeout(() => {
uiElements.swipeHint.style.display = 'none';
}, 3000);
}
setupTouchGestures();
});
// Check authentication token
function checkAuth() {
const token = localStorage.getItem('token');
console.log('Auth token:', token ? 'Found' : 'Not found');
return token;
}
// Handle session for non-logged-in users
async function handleSession() {
const sessionId = sessionStorage.getItem('session_id');
if (!sessionId) {
const newSessionId = crypto.randomUUID();
sessionStorage.setItem('session_id', newSessionId);
console.log('New session_id created:', newSessionId);
return newSessionId;
}
console.log('Existing session_id:', sessionId);
return sessionId;
}
// Update send button state
function updateSendButtonState() {
if (uiElements.sendBtn && uiElements.input && uiElements.fileInput && uiElements.audioInput) {
uiElements.sendBtn.disabled = uiElements.input.value.trim() === '' &&
uiElements.fileInput.files.length === 0 &&
uiElements.audioInput.files.length === 0;
}
}
// Render markdown content with RTL support
function renderMarkdown(el) {
const raw = el.dataset.text || '';
const isArabic = isArabicText(raw);
const html = marked.parse(raw, {
gfm: true,
breaks: true,
smartLists: true,
smartypants: false,
headerIds: false,
});
el.innerHTML = `<div class="md-content" style="direction: ${isArabic ? 'rtl' : 'ltr'}; text-align: ${isArabic ? 'right' : 'left'};">${html}</div>`;
const wrapper = el.querySelector('.md-content');
wrapper.querySelectorAll('table').forEach(t => {
if (!t.parentNode.classList?.contains('table-wrapper')) {
const div = document.createElement('div');
div.className = 'table-wrapper';
t.parentNode.insertBefore(div, t);
div.appendChild(t);
}
});
wrapper.querySelectorAll('hr').forEach(h => h.classList.add('styled-hr'));
Prism.highlightAllUnder(wrapper);
}
// Toggle chat view
function enterChatView() {
if (uiElements.chatHeader) {
uiElements.chatHeader.classList.remove('hidden');
uiElements.chatHeader.setAttribute('aria-hidden', 'false');
if (currentConversationTitle && uiElements.conversationTitle) {
uiElements.conversationTitle.textContent = currentConversationTitle;
}
}
if (uiElements.chatBox) uiElements.chatBox.classList.remove('hidden');
if (uiElements.initialContent) uiElements.initialContent.classList.add('hidden');
}
// Toggle home view
function leaveChatView() {
if (uiElements.chatHeader) {
uiElements.chatHeader.classList.add('hidden');
uiElements.chatHeader.setAttribute('aria-hidden', 'true');
}
if (uiElements.chatBox) uiElements.chatBox.classList.add('hidden');
if (uiElements.initialContent) uiElements.initialContent.classList.remove('hidden');
}
// Add chat bubble
function addMsg(who, text) {
const div = document.createElement('div');
div.className = `bubble ${who === 'user' ? 'bubble-user' : 'bubble-assist'} ${isArabicText(text) ? 'rtl' : ''}`;
div.dataset.text = text;
console.log('Adding message:', { who, text });
renderMarkdown(div);
if (uiElements.chatBox) {
uiElements.chatBox.appendChild(div);
uiElements.chatBox.classList.remove('hidden');
uiElements.chatBox.scrollTop = uiElements.chatBox.scrollHeight;
console.log('Message added to chatBox:', div);
} else {
console.error('chatBox is null');
}
return div;
}
// Clear all messages
function clearAllMessages() {
stopStream(true);
conversationHistory = [];
sessionStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
currentAssistantText = '';
if (streamMsg) {
streamMsg.querySelector('.loading')?.remove();
streamMsg = null;
}
if (uiElements.chatBox) uiElements.chatBox.innerHTML = '';
if (uiElements.input) uiElements.input.value = '';
if (uiElements.sendBtn) uiElements.sendBtn.disabled = true;
if (uiElements.stopBtn) uiElements.stopBtn.style.display = 'none';
if (uiElements.sendBtn) uiElements.sendBtn.style.display = 'inline-flex';
if (uiElements.filePreview) uiElements.filePreview.style.display = 'none';
if (uiElements.audioPreview) uiElements.audioPreview.style.display = 'none';
if (uiElements.messageLimitWarning) uiElements.messageLimitWarning.classList.add('hidden');
currentConversationId = null;
currentConversationTitle = null;
if (uiElements.conversationTitle) uiElements.conversationTitle.textContent = 'MGZon AI Assistant';
enterChatView();
autoResizeTextarea();
}
// File preview
function previewFile() {
if (uiElements.fileInput?.files.length > 0) {
const file = uiElements.fileInput.files[0];
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = e => {
if (uiElements.filePreview) {
uiElements.filePreview.innerHTML = `<img src="${e.target.result}" class="upload-preview">`;
uiElements.filePreview.style.display = 'block';
}
if (uiElements.audioPreview) uiElements.audioPreview.style.display = 'none';
updateSendButtonState();
};
reader.readAsDataURL(file);
}
}
if (uiElements.audioInput?.files.length > 0) {
const file = uiElements.audioInput.files[0];
if (file.type.startsWith('audio/')) {
const reader = new FileReader();
reader.onload = e => {
if (uiElements.audioPreview) {
uiElements.audioPreview.innerHTML = `<audio controls src="${e.target.result}"></audio>`;
uiElements.audioPreview.style.display = 'block';
}
if (uiElements.filePreview) uiElements.filePreview.style.display = 'none';
updateSendButtonState();
};
reader.readAsDataURL(file);
}
}
}
// Voice recording
function startVoiceRecording() {
if (isRequestActive || isRecording) {
console.log('Voice recording blocked: Request active or already recording');
return;
}
console.log('Starting voice recording...');
isRecording = true;
if (uiElements.sendBtn) uiElements.sendBtn.classList.add('recording');
navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.start();
console.log('MediaRecorder started');
mediaRecorder.addEventListener('dataavailable', event => {
audioChunks.push(event.data);
console.log('Audio chunk received:', event.data);
});
}).catch(err => {
console.error('Error accessing microphone:', err);
alert('Failed to access microphone. Please check permissions.');
isRecording = false;
if (uiElements.sendBtn) uiElements.sendBtn.classList.remove('recording');
});
}
function stopVoiceRecording() {
if (mediaRecorder?.state === 'recording') {
mediaRecorder.stop();
if (uiElements.sendBtn) uiElements.sendBtn.classList.remove('recording');
isRecording = false;
mediaRecorder.addEventListener('stop', async () => {
console.log('Stopping voice recording, sending audio...');
const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
const formData = new FormData();
formData.append('file', audioBlob, 'voice-message.webm');
await submitAudioMessage(formData);
});
}
}
// Send audio message
async function submitAudioMessage(formData) {
enterChatView();
addMsg('user', 'Voice message');
conversationHistory.push({ role: 'user', content: 'Voice message' });
sessionStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
streamMsg = addMsg('assistant', '');
const loadingEl = document.createElement('span');
loadingEl.className = 'loading';
streamMsg.appendChild(loadingEl);
updateUIForRequest();
isRequestActive = true;
abortController = new AbortController();
try {
const response = await sendRequest('/api/audio-transcription', formData);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();
if (!data.transcription) throw new Error('No transcription received from server');
const transcription = data.transcription || 'Error: No transcription generated.';
if (streamMsg) {
streamMsg.dataset.text = transcription;
renderMarkdown(streamMsg);
streamMsg.dataset.done = '1';
}
conversationHistory.push({ role: 'assistant', content: transcription });
sessionStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
if (checkAuth() && currentConversationId) {
await saveMessageToConversation(currentConversationId, 'assistant', transcription);
}
if (checkAuth() && data.conversation_id) {
currentConversationId = data.conversation_id;
currentConversationTitle = data.conversation_title || 'Untitled Conversation';
if (uiElements.conversationTitle) uiElements.conversationTitle.textContent = currentConversationTitle;
history.pushState(null, '', `/chat/${currentConversationId}`);
await loadConversations();
}
finalizeRequest();
} catch (error) {
handleRequestError(error);
}
}
// Helper to send API requests
async function sendRequest(endpoint, body, headers = {}) {
const token = checkAuth();
if (token) headers['Authorization'] = `Bearer ${token}`;
headers['X-Session-ID'] = await handleSession();
console.log('Sending request to:', endpoint, 'with headers:', headers);
try {
const response = await fetch(endpoint, {
method: 'POST',
body,
headers,
signal: abortController?.signal,
});
if (!response.ok) {
if (response.status === 403) {
if (uiElements.messageLimitWarning) uiElements.messageLimitWarning.classList.remove('hidden');
throw new Error('Message limit reached. Please log in to continue.');
}
if (response.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login';
throw new Error('Unauthorized. Please log in again.');
}
if (response.status === 503) {
throw new Error('Model not available. Please try another model.');
}
throw new Error(`Request failed with status ${response.status}`);
}
return response;
} catch (error) {
console.error('Send request error:', error);
throw error;
}
}
// Helper to update UI during request
function updateUIForRequest() {
if (uiElements.stopBtn) uiElements.stopBtn.style.display = 'inline-flex';
if (uiElements.sendBtn) uiElements.sendBtn.style.display = 'none';
if (uiElements.input) uiElements.input.value = '';
if (uiElements.sendBtn) uiElements.sendBtn.disabled = true;
if (uiElements.filePreview) uiElements.filePreview.style.display = 'none';
if (uiElements.audioPreview) uiElements.audioPreview.style.display = 'none';
autoResizeTextarea();
}
// Helper to finalize request
function finalizeRequest() {
streamMsg = null;
isRequestActive = false;
abortController = null;
if (uiElements.sendBtn) uiElements.sendBtn.style.display = 'inline-flex';
if (uiElements.stopBtn) uiElements.stopBtn.style.display = 'none';
}
// Helper to handle request errors
function handleRequestError(error) {
if (streamMsg) {
streamMsg.querySelector('.loading')?.remove();
streamMsg.dataset.text = `Error: ${error.message || 'An error occurred during the request.'}`;
const retryBtn = document.createElement('button');
retryBtn.innerText = 'Retry';
retryBtn.className = 'retry-btn text-sm text-blue-400 hover:text-blue-600';
retryBtn.onclick = () => submitMessage();
streamMsg.appendChild(retryBtn);
renderMarkdown(streamMsg);
streamMsg.dataset.done = '1';
streamMsg = null;
}
console.error('Request error:', error);
alert(`Error: ${error.message || 'An error occurred during the request.'}`);
isRequestActive = false;
abortController = null;
if (uiElements.sendBtn) uiElements.sendBtn.style.display = 'inline-flex';
if (uiElements.stopBtn) uiElements.stopBtn.style.display = 'none';
sessionStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
}
// Load conversations for sidebar
async function loadConversations() {
if (!checkAuth()) return;
try {
const response = await fetch('/api/conversations', {
headers: { 'Authorization': `Bearer ${checkAuth()}` }
});
if (!response.ok) throw new Error('Failed to load conversations');
const conversations = await response.json();
if (uiElements.conversationList) {
uiElements.conversationList.innerHTML = '';
conversations.forEach(conv => {
const li = document.createElement('li');
li.className = `flex items-center justify-between text-white hover:bg-gray-700 p-2 rounded cursor-pointer transition-colors ${conv.conversation_id === currentConversationId ? 'bg-gray-700' : ''}`;
li.dataset.conversationId = conv.conversation_id;
li.innerHTML = `
<div class="flex items-center flex-1" style="direction: ${isArabicText(conv.title) ? 'rtl' : 'ltr'};" data-conversation-id="${conv.conversation_id}">
<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"></path>
</svg>
<span class="truncate flex-1">${conv.title || 'Untitled Conversation'}</span>
</div>
<button class="delete-conversation-btn text-red-400 hover:text-red-600 p-1" title="Delete Conversation" data-conversation-id="${conv.conversation_id}">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5-4h4M3 7h18"></path>
</svg>
</button>
`;
li.querySelector('[data-conversation-id]').addEventListener('click', () => loadConversation(conv.conversation_id));
li.querySelector('.delete-conversation-btn').addEventListener('click', () => deleteConversation(conv.conversation_id));
uiElements.conversationList.appendChild(li);
});
}
} catch (error) {
console.error('Error loading conversations:', error);
alert('Failed to load conversations. Please try again.');
}
}
// Load conversation from API
async function loadConversation(conversationId) {
try {
const response = await fetch(`/api/conversations/${conversationId}`, {
headers: { 'Authorization': `Bearer ${checkAuth()}` }
});
if (!response.ok) {
if (response.status === 401) window.location.href = '/login';
throw new Error('Failed to load conversation');
}
const data = await response.json();
currentConversationId = data.conversation_id;
currentConversationTitle = data.title || 'Untitled Conversation';
conversationHistory = data.messages.map(msg => ({ role: msg.role, content: msg.content }));
if (uiElements.chatBox) uiElements.chatBox.innerHTML = '';
conversationHistory.forEach(msg => addMsg(msg.role, msg.content));
enterChatView();
if (uiElements.conversationTitle) uiElements.conversationTitle.textContent = currentConversationTitle;
history.pushState(null, '', `/chat/${currentConversationId}`);
toggleSidebar(false);
} catch (error) {
console.error('Error loading conversation:', error);
alert('Failed to load conversation. Please try again or log in.');
}
}
// Delete conversation
async function deleteConversation(conversationId) {
if (!confirm('Are you sure you want to delete this conversation?')) return;
try {
const response = await fetch(`/api/conversations/${conversationId}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${checkAuth()}` }
});
if (!response.ok) {
if (response.status === 401) window.location.href = '/login';
throw new Error('Failed to delete conversation');
}
if (conversationId === currentConversationId) {
clearAllMessages();
currentConversationId = null;
currentConversationTitle = null;
history.pushState(null, '', '/chat');
}
await loadConversations();
} catch (error) {
console.error('Error deleting conversation:', error);
alert('Failed to delete conversation. Please try again.');
}
}
// Save message to conversation
async function saveMessageToConversation(conversationId, role, content) {
try {
const response = await fetch(`/api/conversations/${conversationId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${checkAuth()}`
},
body: JSON.stringify({ role, content })
});
if (!response.ok) throw new Error('Failed to save message');
} catch (error) {
console.error('Error saving message:', error);
}
}
// Create new conversation
async function createNewConversation() {
if (!checkAuth()) {
alert('Please log in to create a new conversation.');
window.location.href = '/login';
return;
}
try {
const response = await fetch('/api/conversations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${checkAuth()}`
},
body: JSON.stringify({ title: 'New Conversation' })
});
if (!response.ok) {
if (response.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login';
}
throw new Error('Failed to create conversation');
}
const data = await response.json();
currentConversationId = data.conversation_id;
currentConversationTitle = data.title;
conversationHistory = [];
sessionStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
if (uiElements.chatBox) uiElements.chatBox.innerHTML = '';
if (uiElements.conversationTitle) uiElements.conversationTitle.textContent = currentConversationTitle;
history.pushState(null, '', `/chat/${currentConversationId}`);
enterChatView();
await loadConversations();
toggleSidebar(false);
} catch (error) {
console.error('Error creating conversation:', error);
alert('Failed to create new conversation. Please try again.');
}
}
// Update conversation title
async function updateConversationTitle(conversationId, newTitle) {
try {
const response = await fetch(`/api/conversations/${conversationId}/title`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${checkAuth()}`
},
body: JSON.stringify({ title: newTitle })
});
if (!response.ok) throw new Error('Failed to update title');
const data = await response.json();
currentConversationTitle = data.title;
if (uiElements.conversationTitle) uiElements.conversationTitle.textContent = currentConversationTitle;
await loadConversations();
} catch (error) {
console.error('Error updating title:', error);
alert('Failed to update conversation title.');
}
}
// Toggle sidebar
function toggleSidebar(show) {
if (uiElements.sidebar) {
if (window.innerWidth >= 768) {
isSidebarOpen = true;
uiElements.sidebar.style.transform = 'translateX(0)';
if (uiElements.swipeHint) uiElements.swipeHint.style.display = 'none';
} else {
isSidebarOpen = show !== undefined ? show : !isSidebarOpen;
uiElements.sidebar.style.transform = isSidebarOpen ? 'translateX(0)' : 'translateX(-100%)';
if (uiElements.swipeHint && !isSidebarOpen) {
uiElements.swipeHint.style.display = 'block';
setTimeout(() => {
uiElements.swipeHint.style.display = 'none';
}, 3000);
} else if (uiElements.swipeHint) {
uiElements.swipeHint.style.display = 'none';
}
}
}
}
// Setup touch gestures with Hammer.js
function setupTouchGestures() {
if (!uiElements.sidebar) return;
const hammer = new Hammer(uiElements.sidebar);
const mainContent = document.querySelector('.flex-1');
const hammerMain = new Hammer(mainContent);
hammer.get('pan').set({ direction: Hammer.DIRECTION_HORIZONTAL });
hammer.on('pan', e => {
if (!isSidebarOpen) return;
let translateX = Math.max(-uiElements.sidebar.offsetWidth, Math.min(0, e.deltaX));
uiElements.sidebar.style.transform = `translateX(${translateX}px)`;
});
hammer.on('panend', e => {
if (!isSidebarOpen) return;
if (e.deltaX < -50) {
toggleSidebar(false);
} else {
toggleSidebar(true);
}
});
hammerMain.get('pan').set({ direction: Hammer.DIRECTION_HORIZONTAL });
hammerMain.on('panstart', e => {
if (isSidebarOpen) return;
if (e.center.x < 50 || e.center.x > window.innerWidth - 50) {
uiElements.sidebar.style.transition = 'none';
}
});
hammerMain.on('pan', e => {
if (isSidebarOpen) return;
if (e.center.x < 50 || e.center.x > window.innerWidth - 50) {
let translateX = e.center.x < 50
? Math.min(uiElements.sidebar.offsetWidth, Math.max(0, e.deltaX))
: Math.max(-uiElements.sidebar.offsetWidth, Math.min(0, e.deltaX));
uiElements.sidebar.style.transform = `translateX(${translateX - uiElements.sidebar.offsetWidth}px)`;
}
});
hammerMain.on('panend', e => {
uiElements.sidebar.style.transition = 'transform 0.3s ease-in-out';
if (e.center.x < 50 && e.deltaX > 50) {
toggleSidebar(true);
} else if (e.center.x > window.innerWidth - 50 && e.deltaX < -50) {
toggleSidebar(true);
} else {
toggleSidebar(false);
}
});
}
// Send user message
async function submitMessage() {
if (isRequestActive || isRecording) return;
let message = uiElements.input?.value.trim() || '';
let payload = null;
let formData = null;
let endpoint = '/api/chat';
let headers = {};
let inputType = 'text';
let outputFormat = 'text';
let title = null;
if (!message && !uiElements.fileInput?.files.length && !uiElements.audioInput?.files.length) {
console.log('No message, file, or audio to send');
return;
}
if (uiElements.fileInput?.files.length > 0) {
const file = uiElements.fileInput.files[0];
if (file.type.startsWith('image/')) {
endpoint = '/api/image-analysis';
inputType = 'image';
message = 'Analyze this image';
formData = new FormData();
formData.append('file', file);
formData.append('output_format', 'text');
}
} else if (uiElements.audioInput?.files.length > 0) {
const file = uiElements.audioInput.files[0];
if (file.type.startsWith('audio/')) {
endpoint = '/api/audio-transcription';
inputType = 'audio';
message = 'Transcribe this audio';
formData = new FormData();
formData.append('file', file);
}
} else if (message) {
payload = {
message,
system_prompt: isArabicText(message)
? 'أنت مساعد ذكي تقدم إجابات مفصلة ومنظمة باللغة العربية، مع ضمان الدقة والوضوح.'
: 'You are an expert assistant providing detailed, comprehensive, and well-structured responses.',
history: conversationHistory,
temperature: 0.7,
max_new_tokens: 128000,
enable_browsing: true,
output_format: 'text',
title: title
};
headers['Content-Type'] = 'application/json';
}
enterChatView();
addMsg('user', message);
conversationHistory.push({ role: 'user', content: message });
sessionStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
streamMsg = addMsg('assistant', '');
const loadingEl = document.createElement('span');
loadingEl.className = 'loading';
streamMsg.appendChild(loadingEl);
updateUIForRequest();
isRequestActive = true;
abortController = new AbortController();
try {
const response = await sendRequest(endpoint, payload ? JSON.stringify(payload) : formData, headers);
if (endpoint === '/api/audio-transcription') {
const data = await response.json();
if (!data.transcription) throw new Error('No transcription received from server');
const transcription = data.transcription || 'Error: No transcription generated.';
if (streamMsg) {
streamMsg.dataset.text = transcription;
renderMarkdown(streamMsg);
streamMsg.dataset.done = '1';
}
conversationHistory.push({ role: 'assistant', content: transcription });
sessionStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
if (checkAuth() && currentConversationId) {
await saveMessageToConversation(currentConversationId, 'assistant', transcription);
}
if (checkAuth() && data.conversation_id) {
currentConversationId = data.conversation_id;
currentConversationTitle = data.conversation_title || 'Untitled Conversation';
if (uiElements.conversationTitle) uiElements.conversationTitle.textContent = currentConversationTitle;
history.pushState(null, '', `/chat/${currentConversationId}`);
await loadConversations();
}
} else if (endpoint === '/api/image-analysis') {
const data = await response.json();
const analysis = data.image_analysis || 'Error: No analysis generated.';
if (streamMsg) {
streamMsg.dataset.text = analysis;
renderMarkdown(streamMsg);
streamMsg.dataset.done = '1';
}
conversationHistory.push({ role: 'assistant', content: analysis });
sessionStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
if (checkAuth() && currentConversationId) {
await saveMessageToConversation(currentConversationId, 'assistant', analysis);
}
if (checkAuth() && data.conversation_id) {
currentConversationId = data.conversation_id;
currentConversationTitle = data.conversation_title || 'Untitled Conversation';
if (uiElements.conversationTitle) uiElements.conversationTitle.textContent = currentConversationTitle;
history.pushState(null, '', `/chat/${currentConversationId}`);
await loadConversations();
}
} else {
const contentType = response.headers.get('Content-Type');
if (contentType?.includes('application/json')) {
const data = await response.json();
const responseText = data.response || 'Error: No response generated.';
if (streamMsg) {
streamMsg.dataset.text = responseText;
renderMarkdown(streamMsg);
streamMsg.dataset.done = '1';
}
conversationHistory.push({ role: 'assistant', content: responseText });
sessionStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
if (checkAuth() && currentConversationId) {
await saveMessageToConversation(currentConversationId, 'assistant', responseText);
}
if (checkAuth() && data.conversation_id) {
currentConversationId = data.conversation_id;
currentConversationTitle = data.conversation_title || 'Untitled Conversation';
if (uiElements.conversationTitle) uiElements.conversationTitle.textContent = currentConversationTitle;
history.pushState(null, '', `/chat/${currentConversationId}`);
await loadConversations();
}
} else {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) {
if (!buffer.trim()) throw new Error('Empty response from server');
break;
}
buffer += decoder.decode(value, { stream: true });
if (streamMsg) {
streamMsg.dataset.text = buffer;
currentAssistantText = buffer;
streamMsg.querySelector('.loading')?.remove();
renderMarkdown(streamMsg);
if (uiElements.chatBox) uiElements.chatBox.scrollTop = uiElements.chatBox.scrollHeight;
}
}
if (streamMsg) streamMsg.dataset.done = '1';
conversationHistory.push({ role: 'assistant', content: buffer });
sessionStorage.setItem('conversationHistory', JSON.stringify(conversationHistory));
if (checkAuth() && currentConversationId) {
await saveMessageToConversation(currentConversationId, 'assistant', buffer);
}
}
}
finalizeRequest();
} catch (error) {
handleRequestError(error);
}
}
// Stop streaming
function stopStream(forceCancel = false) {
if (!isRequestActive && !isRecording) return;
if (isRecording) stopVoiceRecording();
isRequestActive = false;
if (abortController) {
abortController.abort();
abortController = null;
}
if (streamMsg && !forceCancel) {
streamMsg.querySelector('.loading')?.remove();
streamMsg.dataset.text += '';
renderMarkdown(streamMsg);
streamMsg.dataset.done = '1';
streamMsg = null;
}
if (uiElements.stopBtn) uiElements.stopBtn.style.display = 'none';
if (uiElements.sendBtn) uiElements.sendBtn.style.display = 'inline-flex';
if (uiElements.stopBtn) uiElements.stopBtn.style.pointerEvents = 'auto';
}
// Logout handler
const logoutBtn = document.getElementById('logoutBtn');
if (logoutBtn) {
logoutBtn.addEventListener('click', async () => {
console.log('Logout button clicked');
try {
const response = await fetch('/logout', {
method: 'GET',
credentials: 'include'
});
if (response.ok) {
localStorage.removeItem('token');
console.log('Token removed from localStorage');
window.location.href = '/login';
} else {
console.error('Logout failed:', response.status);
alert('Failed to log out. Please try again.');
}
} catch (error) {
console.error('Logout error:', error);
alert('Error during logout: ' + error.message);
}
});
}
// Settings Modal
if (uiElements.settingsBtn) {
uiElements.settingsBtn.addEventListener('click', () => {
if (!checkAuth()) {
alert('Please log in to access settings.');
window.location.href = '/login';
return;
}
uiElements.settingsModal.classList.remove('hidden');
fetch('/api/settings', {
headers: { 'Authorization': `Bearer ${checkAuth()}` }
})
.then(res => {
if (!res.ok) {
if (res.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login';
}
throw new Error('Failed to fetch settings');
}
return res.json();
})
.then(data => {
document.getElementById('display_name').value = data.user_settings.display_name || '';
document.getElementById('preferred_model').value = data.user_settings.preferred_model || 'standard';
document.getElementById('job_title').value = data.user_settings.job_title || '';
document.getElementById('education').value = data.user_settings.education || '';
document.getElementById('interests').value = data.user_settings.interests || '';
document.getElementById('additional_info').value = data.user_settings.additional_info || '';
document.getElementById('conversation_style').value = data.user_settings.conversation_style || 'default';
const modelSelect = document.getElementById('preferred_model');
modelSelect.innerHTML = '';
data.available_models.forEach(model => {
const option = document.createElement('option');
option.value = model.alias;
option.textContent = `${model.alias} - ${model.description}`;
modelSelect.appendChild(option);
});
const styleSelect = document.getElementById('conversation_style');
styleSelect.innerHTML = '';
data.conversation_styles.forEach(style => {
const option = document.createElement('option');
option.value = style;
option.textContent = style.charAt(0).toUpperCase() + style.slice(1);
styleSelect.appendChild(option);
});
})
.catch(err => {
console.error('Error fetching settings:', err);
alert('Failed to load settings. Please try again.');
});
});
}
if (uiElements.closeSettingsBtn) {
uiElements.closeSettingsBtn.addEventListener('click', () => {
uiElements.settingsModal.classList.add('hidden');
});
}
if (uiElements.settingsForm) {
uiElements.settingsForm.addEventListener('submit', (e) => {
e.preventDefault();
if (!checkAuth()) {
alert('Please log in to save settings.');
window.location.href = '/login';
return;
}
const formData = new FormData(uiElements.settingsForm);
const data = Object.fromEntries(formData);
fetch('/users/me', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${checkAuth()}`
},
body: JSON.stringify(data)
})
.then(res => {
if (!res.ok) {
if (res.status === 401) {
localStorage.removeItem('token');
window.location.href = '/login';
}
throw new Error('Failed to update settings');
}
return res.json();
})
.then(() => {
alert('Settings updated successfully!');
uiElements.settingsModal.classList.add('hidden');
toggleSidebar(false);
})
.catch(err => {
console.error('Error updating settings:', err);
alert('Error updating settings: ' + err.message);
});
});
}
// History Toggle
if (uiElements.historyToggle) {
uiElements.historyToggle.addEventListener('click', () => {
if (uiElements.conversationList) {
uiElements.conversationList.classList.toggle('hidden');
uiElements.historyToggle.innerHTML = uiElements.conversationList.classList.contains('hidden')
? `<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>Show History`
: `<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>Hide History`;
}
});
}
// Event listeners
uiElements.promptItems.forEach(p => {
p.addEventListener('click', e => {
e.preventDefault();
if (uiElements.input) {
uiElements.input.value = p.dataset.prompt;
autoResizeTextarea();
}
if (uiElements.sendBtn) uiElements.sendBtn.disabled = false;
submitMessage();
});
});
if (uiElements.fileBtn) uiElements.fileBtn.addEventListener('click', () => uiElements.fileInput?.click());
if (uiElements.audioBtn) uiElements.audioBtn.addEventListener('click', () => uiElements.audioInput?.click());
if (uiElements.fileInput) uiElements.fileInput.addEventListener('change', previewFile);
if (uiElements.audioInput) uiElements.audioInput.addEventListener('change', previewFile);
if (uiElements.sendBtn) {
uiElements.sendBtn.addEventListener('click', (e) => {
e.preventDefault();
if (uiElements.sendBtn.disabled || isRequestActive || isRecording) return;
if (uiElements.input.value.trim()) {
submitMessage();
}
});
let pressTimer;
uiElements.sendBtn.addEventListener('mousedown', (e) => {
if (uiElements.sendBtn.disabled || isRequestActive || isRecording) return;
pressTimer = setTimeout(() => {
startVoiceRecording();
}, 500);
});
uiElements.sendBtn.addEventListener('mouseup', () => {
clearTimeout(pressTimer);
if (isRecording) stopVoiceRecording();
});
uiElements.sendBtn.addEventListener('mouseleave', () => {
clearTimeout(pressTimer);
if (isRecording) stopVoiceRecording();
});
uiElements.sendBtn.addEventListener('touchstart', (e) => {
e.preventDefault();
if (uiElements.sendBtn.disabled || isRequestActive || isRecording) return;
pressTimer = setTimeout(() => {
startVoiceRecording();
}, 500);
});
uiElements.sendBtn.addEventListener('touchend', (e) => {
e.preventDefault();
clearTimeout(pressTimer);
if (isRecording) stopVoiceRecording();
});
uiElements.sendBtn.addEventListener('touchcancel', (e) => {
e.preventDefault();
clearTimeout(pressTimer);
if (isRecording) stopVoiceRecording();
});
}
if (uiElements.form) {
uiElements.form.addEventListener('submit', (e) => {
e.preventDefault();
if (!isRecording && uiElements.input.value.trim()) {
submitMessage();
}
});
}
if (uiElements.input) {
uiElements.input.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (!isRecording && !uiElements.sendBtn.disabled) submitMessage();
}
});
uiElements.input.addEventListener('input', () => {
autoResizeTextarea();
updateSendButtonState();
});
}
if (uiElements.stopBtn) {
uiElements.stopBtn.addEventListener('click', () => {
uiElements.stopBtn.style.pointerEvents = 'none';
stopStream();
});
}
if (uiElements.clearBtn) uiElements.clearBtn.addEventListener('click', clearAllMessages);
if (uiElements.conversationTitle) {
uiElements.conversationTitle.addEventListener('click', () => {
if (!checkAuth()) return alert('Please log in to edit the conversation title.');
const newTitle = prompt('Enter new conversation title:', currentConversationTitle || '');
if (newTitle && currentConversationId) {
updateConversationTitle(currentConversationId, newTitle);
}
});
}
if (uiElements.sidebarToggle) {
uiElements.sidebarToggle.addEventListener('click', () => toggleSidebar());
}
if (uiElements.newConversationBtn) {
uiElements.newConversationBtn.addEventListener('click', createNewConversation);
}
// Debug localStorage
const originalRemoveItem = localStorage.removeItem;
localStorage.removeItem = function(key) {
console.log('Removing from localStorage:', key);
originalRemoveItem.apply(this, arguments);
};
|