-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
923 lines (800 loc) · 31.6 KB
/
app.js
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
const chatContainer = document.getElementById('chat-container');
const messagesContainer = document.getElementById('messages');
const chatForm = document.getElementById('chat-form');
const userInput = document.getElementById('user-input');
const serverUrlInput = document.getElementById('server-url');
const systemPromptInput = document.getElementById('system-prompt');
const clearChatButton = document.getElementById('clear-chat');
const loadingIndicator = document.getElementById('loading-indicator');
const sidebar = document.getElementById('sidebar');
const newChatButton = document.getElementById('new-chat');
const chatHistory = document.getElementById('chat-history');
const settingsButton = document.getElementById('settings-btn');
const settingsModal = document.getElementById('settings-modal');
const closeSettingsButton = document.getElementById('close-settings');
const welcomeMessage = document.getElementById('welcome-message');
const sidebarToggle = document.getElementById('sidebar-toggle');
const closeSidebarButton = document.getElementById('close-sidebar');
const loadedModelDisplay = document.getElementById('loaded-model');
// New variables for send and stop buttons
const sendButton = document.getElementById('send-button');
const stopButton = document.getElementById('stop-button');
// New variables for confirmation modal
const confirmationModal = document.getElementById('confirmation-modal');
const confirmActionButton = document.getElementById('confirm-action');
const cancelActionButton = document.getElementById('cancel-action');
const confirmationMessage = document.getElementById('confirmation-message');
// New variables for context menu
const contextMenu = document.getElementById('context-menu');
const copyTextButton = document.getElementById('copy-text');
const regenerateTextButton = document.getElementById('regenerate-text');
// New variables for exit functionality
const exitButton = document.getElementById('exit-btn');
let API_URL = serverUrlInput ? serverUrlInput.value + '/v1/chat/completions' : '';
let currentChatId = Date.now();
let chatHistoryData = {};
let systemPrompt = '';
let temperature = 0.9;
let availableModels = [];
let isFirstMessage = true;
let chatToDelete = null; // New variable to store the chat ID to be deleted
let longPressTimer;
let selectedText = '';
let selectedMessageElement = null;
let actionToPerform = null;
// New variable for AbortController
let abortController = null;
// Prevent default touch behavior except for the messages container
document.body.addEventListener('touchmove', function(e) {
if (e.target.closest('#messages') === null) {
e.preventDefault();
}
}, { passive: false });
// Allow scrolling within the messages container
if (messagesContainer) {
messagesContainer.addEventListener('touchmove', function(e) {
e.stopPropagation();
}, { passive: true });
}
if (serverUrlInput) {
serverUrlInput.addEventListener('change', () => {
API_URL = serverUrlInput.value + '/v1/chat/completions';
localStorage.setItem('serverUrl', serverUrlInput.value);
fetchAvailableModels();
});
}
if (systemPromptInput) {
systemPromptInput.addEventListener('change', () => {
systemPrompt = systemPromptInput.value;
localStorage.setItem('systemPrompt', systemPrompt);
});
}
function initializeTemperature() {
const temperatureInput = document.getElementById('temperature');
const temperatureValue = document.getElementById('temperature-value');
const temperatureLock = document.getElementById('temperature-lock');
if (temperatureInput && temperatureValue && temperatureLock) {
temperatureInput.addEventListener('input', () => {
const inputValue = temperatureInput.value;
const parsedValue = parseFloat(inputValue);
if (!isNaN(parsedValue) && parsedValue >= 0 && parsedValue <= 2.0 && /^\d*\.?\d{0,1}$/.test(inputValue)) {
temperature = parsedValue;
temperatureValue.textContent = temperature.toFixed(1);
localStorage.setItem('temperature', temperature);
} else {
temperatureInput.value = temperature.toFixed(1);
}
});
temperatureLock.addEventListener('click', () => {
const isLocked = temperatureInput.disabled;
temperatureInput.disabled = !isLocked;
temperatureLock.innerHTML = isLocked ? '<i class="fas fa-unlock"></i>' : '<i class="fas fa-lock"></i>';
});
// Load saved temperature
const savedTemperature = localStorage.getItem('temperature');
if (savedTemperature) {
const parsedTemperature = parseFloat(savedTemperature);
if (!isNaN(parsedTemperature) && parsedTemperature >= 0 && parsedTemperature <= 2.0) {
temperatureInput.value = parsedTemperature.toFixed(1);
temperature = parsedTemperature;
temperatureValue.textContent = temperature.toFixed(1);
} else {
// If saved temperature is invalid, set to default
temperatureInput.value = '0.9';
temperature = 0.9;
temperatureValue.textContent = '0.9';
}
} else {
// Set default temperature to 0.9
temperatureInput.value = '0.9';
temperature = 0.9;
temperatureValue.textContent = '0.9';
}
}
}
function updateLoadedModelDisplay(modelName) {
if (loadedModelDisplay) {
loadedModelDisplay.textContent = `Loaded Model: ${modelName}`;
loadedModelDisplay.style.display = 'block';
}
}
async function fetchAvailableModels() {
try {
const response = await fetch(`${serverUrlInput.value}/v1/models`);
if (!response.ok) {
throw new Error('Failed to fetch models');
}
const data = await response.json();
availableModels = data.data.map(model => model.id);
console.log('Available models:', availableModels);
if (availableModels.length > 0) {
updateLoadedModelDisplay(availableModels[0]);
}
} catch (error) {
console.error('Error fetching models:', error);
appendMessage('error', 'Failed to fetch available models. Please check your LM Studio server connection.');
}
}
if (chatForm) {
chatForm.addEventListener('submit', async (e) => {
e.preventDefault();
const message = userInput.value.trim();
if (!message) return;
hideWelcomeMessage();
appendMessage('user', message);
userInput.value = '';
showLoadingIndicator();
toggleSendStopButton();
if (isFirstMessage) {
if (loadedModelDisplay) {
loadedModelDisplay.style.display = 'none';
}
isFirstMessage = false;
}
try {
if (!(await isServerRunning())) {
throw new Error('LM Studio server is not running');
}
if (availableModels.length === 0) {
await fetchAvailableModels();
}
if (availableModels.length === 0) {
throw new Error('No models available');
}
const currentChat = chatHistoryData[currentChatId] || [];
const messages = [
{ role: 'system', content: systemPrompt },
...currentChat.map(msg => ({ role: msg.role, content: msg.content })),
{ role: 'user', content: message }
];
abortController = new AbortController();
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: availableModels[0], // Use the first available model
messages: messages,
temperature: temperature,
stream: true, // Enable streaming
}),
signal: abortController.signal,
});
if (!response.ok) {
throw new Error('API request failed');
}
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let aiMessage = '';
const aiMessageElement = appendMessage('ai', '');
let isFirstChunk = true;
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (isFirstChunk) {
hideLoadingIndicator();
isFirstChunk = false;
}
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
const parsedLines = lines
.map(line => line.replace(/^data: /, '').trim())
.filter(line => line !== '' && line !== '[DONE]')
.map(line => JSON.parse(line));
for (const parsedLine of parsedLines) {
const { choices } = parsedLine;
const { delta } = choices[0];
const { content } = delta;
if (content) {
aiMessage += content;
aiMessageElement.innerHTML = sanitizeInput(aiMessage);
initializeCodeMirror(aiMessageElement);
scrollToBottom();
}
}
}
updateChatHistory(message, aiMessage);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Error:', error);
appendMessage('error', 'An error occurred while fetching the response. Please check your LM Studio server connection.');
}
} finally {
hideLoadingIndicator();
toggleSendStopButton();
abortController = null;
}
});
}
// New function to toggle between send and stop buttons
function toggleSendStopButton() {
if (sendButton && stopButton) {
sendButton.classList.toggle('hidden');
stopButton.classList.toggle('hidden');
}
}
// Add click event listener for stop button
if (stopButton) {
stopButton.addEventListener('click', () => {
if (abortController) {
abortController.abort();
}
});
}
async function isServerRunning() {
try {
const response = await fetch(`${serverUrlInput.value}/v1/models`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
return response.ok;
} catch (error) {
return false;
}
}
if (clearChatButton) {
clearChatButton.addEventListener('click', () => {
actionToPerform = 'clearAllChats';
showConfirmationModal('Are you sure you want to clear all chats? This action cannot be undone.');
});
}
function clearAllChats() {
messagesContainer.innerHTML = '';
showWelcomeMessage();
chatHistoryData = {};
updateChatHistoryUI();
settingsModal.classList.add('hidden');
localStorage.removeItem('chatHistory');
}
if (newChatButton) {
newChatButton.addEventListener('click', () => {
currentChatId = Date.now();
messagesContainer.innerHTML = '';
showWelcomeMessage();
userInput.focus();
if (window.innerWidth <= 768) {
toggleSidebar();
}
settingsModal.classList.add('hidden');
});
}
if (settingsButton) {
settingsButton.addEventListener('click', () => {
if (window.innerWidth <= 768) {
sidebar.classList.add('hidden');
sidebar.classList.remove('active');
document.body.classList.remove('sidebar-open');
}
settingsModal.classList.remove('hidden');
settingsModal.classList.add('animate-fade-in');
});
}
if (closeSettingsButton) {
closeSettingsButton.addEventListener('click', () => {
settingsModal.classList.add('animate-fade-out');
setTimeout(() => {
settingsModal.classList.add('hidden');
settingsModal.classList.remove('animate-fade-out');
}, 300);
});
}
function toggleSidebar() {
if (!sidebar) return; // Ensure sidebar element exists
sidebar.classList.toggle('hidden');
sidebar.classList.toggle('active');
document.body.classList.toggle('sidebar-open');
settingsModal.classList.add('hidden');
if (sidebar.classList.contains('active')) {
sidebar.classList.add('animate-slide-in');
sidebar.classList.remove('animate-slide-out');
} else {
sidebar.classList.add('animate-slide-out');
sidebar.classList.remove('animate-slide-in');
setTimeout(() => {
sidebar.classList.remove('animate-slide-out');
}, 300);
}
}
function appendMessage(sender, message) {
const messageElement = document.createElement('div');
messageElement.classList.add(sender, 'animate-fade-in', 'mb-4', 'p-4', 'rounded-lg');
messageElement.innerHTML = sanitizeInput(message);
// Add long-press event listeners for AI messages
if (sender === 'ai') {
messageElement.addEventListener('touchstart', handleTouchStart);
messageElement.addEventListener('touchend', handleTouchEnd);
messageElement.addEventListener('touchmove', handleTouchMove);
messageElement.addEventListener('mousedown', handleMouseDown);
messageElement.addEventListener('mouseup', handleMouseUp);
messageElement.addEventListener('mouseleave', handleMouseLeave);
}
messagesContainer.insertBefore(messageElement, messagesContainer.firstChild);
initializeCodeMirror(messageElement);
scrollToBottom();
return messageElement;
}
function sanitizeInput(input) {
const div = document.createElement('div');
div.textContent = input;
let sanitized = div.innerHTML;
// Replace code blocks with pre and code tags
sanitized = sanitized.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, language, code) => {
return `<pre><code class="language-${language || 'plaintext'}">${code.trim()}</code></pre>`;
});
return sanitized;
}
function initializeCodeMirror(element) {
const codeBlocks = element.querySelectorAll('pre code');
codeBlocks.forEach((block, index) => {
const language = block.className.replace('language-', '');
const codeMirrorContainer = document.createElement('div');
codeMirrorContainer.className = 'code-mirror-container';
block.parentNode.replaceWith(codeMirrorContainer);
const editor = CodeMirror(codeMirrorContainer, {
value: block.textContent,
mode: language,
theme: 'monokai',
lineNumbers: true,
readOnly: true,
});
const copyButton = document.createElement('button');
copyButton.textContent = 'Copy';
copyButton.className = 'copy-button';
copyButton.addEventListener('click', () => copyToClipboard(editor.getValue()));
codeMirrorContainer.appendChild(copyButton);
});
}
function copyToClipboard(text) {
navigator.clipboard.writeText(text).then(() => {
console.log('Text copied to clipboard');
}).catch(err => {
console.error('Error copying text: ', err);
});
}
function showLoadingIndicator() {
if (!loadingIndicator) {
loadingIndicator = document.createElement('div');
loadingIndicator.id = 'loading-indicator';
loadingIndicator.innerHTML = '<span class="loading-ellipsis">...</span>';
}
loadingIndicator.classList.remove('hidden');
loadingIndicator.classList.add('animate-fade-in');
messagesContainer.insertBefore(loadingIndicator, messagesContainer.firstChild);
scrollToBottom();
}
function hideLoadingIndicator() {
if (loadingIndicator && loadingIndicator.parentNode) {
loadingIndicator.parentNode.removeChild(loadingIndicator);
}
}
function showWelcomeMessage() {
if (welcomeMessage) welcomeMessage.style.display = 'flex';
if (messagesContainer) messagesContainer.style.display = 'none';
}
function hideWelcomeMessage() {
if (welcomeMessage) welcomeMessage.style.display = 'none';
if (messagesContainer) messagesContainer.style.display = 'flex';
}
function updateChatHistory(userMessage, aiMessage) {
if (!chatHistoryData[currentChatId]) {
chatHistoryData[currentChatId] = [];
}
chatHistoryData[currentChatId].push({ role: 'user', content: userMessage });
chatHistoryData[currentChatId].push({ role: 'assistant', content: aiMessage });
updateChatHistoryUI();
saveChatHistory();
}
function updateChatHistoryUI() {
if (!chatHistory) return;
chatHistory.innerHTML = '';
Object.entries(chatHistoryData).forEach(([id, messages]) => {
const button = document.createElement('button');
button.classList.add('w-full', 'text-left', 'py-2', 'px-4', 'hover:bg-gray-700', 'focus:outline-none', 'focus:ring-2', 'focus:ring-gray-500', 'text-gray-300', 'animate-fade-in');
const chatTitle = document.createElement('span');
chatTitle.textContent = messages[0].content.substring(0, 30) + (messages[0].content.length > 30 ? '...' : '');
button.appendChild(chatTitle);
const trashIcon = document.createElement('i');
trashIcon.classList.add('fas', 'fa-trash', 'trash-icon');
trashIcon.addEventListener('click', (e) => {
e.stopPropagation();
showDeleteConfirmation(id);
if (window.innerWidth <= 768 && sidebar && sidebar.classList.contains('active')) {
toggleSidebar();
}
});
button.appendChild(trashIcon);
button.addEventListener('click', () => loadChat(id));
chatHistory.appendChild(button);
});
}
function showDeleteConfirmation(id) {
chatToDelete = id;
actionToPerform = 'deleteChat';
showConfirmationModal('Are you sure you want to delete this chat? This action cannot be undone.');
}
function showExitConfirmation() {
actionToPerform = 'exit';
showConfirmationModal('Are you sure you want to exit the application?');
}
function showConfirmationModal(message) {
if (confirmationModal && confirmationMessage) {
confirmationMessage.textContent = message;
confirmationModal.classList.remove('hidden');
confirmationModal.classList.add('animate-fade-in');
}
}
function hideConfirmationModal() {
if (confirmationModal) {
confirmationModal.classList.add('animate-fade-out');
setTimeout(() => {
confirmationModal.classList.add('hidden');
confirmationModal.classList.remove('animate-fade-out');
}, 300);
}
}
function deleteChatHistory(id) {
delete chatHistoryData[id];
updateChatHistoryUI();
saveChatHistory();
if (id === currentChatId) {
messagesContainer.innerHTML = '';
showWelcomeMessage();
currentChatId = Date.now();
}
hideConfirmationModal();
}
function loadChat(id) {
currentChatId = id;
messagesContainer.innerHTML = '';
hideWelcomeMessage();
const messages = chatHistoryData[id];
lazyLoadMessages(messages, 0);
if (window.innerWidth <= 768) {
toggleSidebar();
}
settingsModal.classList.add('hidden');
}
function lazyLoadMessages(messages, startIndex, chunkSize = 10) {
const endIndex = Math.min(startIndex + chunkSize, messages.length);
for (let i = startIndex; i < endIndex; i++) {
appendMessage(messages[i].role, messages[i].content);
}
if (endIndex < messages.length) {
setTimeout(() => lazyLoadMessages(messages, endIndex), 100);
} else {
scrollToBottom();
}
}
// Close sidebar when clicking outside on mobile
document.addEventListener('click', (e) => {
if (window.innerWidth <= 768 && sidebar && sidebar.classList.contains('active') &&
!sidebar.contains(e.target) && !sidebarToggle.contains(e.target)) {
toggleSidebar();
}
});
// Handle window resize
window.addEventListener('resize', () => {
if (window.innerWidth > 768) {
if (sidebar) {
sidebar.classList.remove('hidden');
sidebar.classList.remove('active');
}
document.body.classList.remove('sidebar-open');
} else {
if (sidebar) sidebar.classList.add('hidden');
}
});
// Save chat history to local storage
function saveChatHistory() {
localStorage.setItem('chatHistory', JSON.stringify(chatHistoryData));
}
// Load chat history from local storage
function loadChatHistory() {
const savedHistory = localStorage.getItem('chatHistory');
if (savedHistory) {
chatHistoryData = JSON.parse(savedHistory);
updateChatHistoryUI();
}
}
// Load saved server URL
function loadServerUrl() {
const savedUrl = localStorage.getItem('serverUrl');
if (savedUrl && serverUrlInput) {
serverUrlInput.value = savedUrl;
API_URL = savedUrl + '/v1/chat/completions';
}
}
// Load saved system prompt
function loadSystemPrompt() {
const savedPrompt = localStorage.getItem('systemPrompt');
if (savedPrompt && systemPromptInput) {
systemPromptInput.value = savedPrompt;
systemPrompt = savedPrompt;
}
}
// Scroll to bottom of chat container
function scrollToBottom() {
if (messagesContainer) messagesContainer.scrollTop = 0;
}
// Add scroll to bottom button
const scrollToBottomBtn = document.createElement('button');
scrollToBottomBtn.textContent = '↓';
scrollToBottomBtn.classList.add('fixed', 'bottom-20', 'right-4', 'bg-blue-600', 'text-white', 'rounded-full', 'w-10', 'h-10', 'flex', 'items-center', 'justify-center', 'shadow-lg', 'hidden', 'animate-fade-in');
document.body.appendChild(scrollToBottomBtn);
scrollToBottomBtn.addEventListener('click', () => {
if (messagesContainer) {
messagesContainer.scrollTo({
top: 0,
behavior: 'smooth'
});
}
});
if (messagesContainer) {
messagesContainer.addEventListener('scroll', () => {
const isScrolledToBottom = messagesContainer.scrollTop === 0;
scrollToBottomBtn.classList.toggle('hidden', isScrolledToBottom);
});
}
// Long-press handling functions
function handleTouchStart(e) {
startLongPress(e);
}
function handleTouchEnd(e) {
clearLongPress();
}
function handleTouchMove(e) {
clearLongPress();
}
function handleMouseDown(e) {
startLongPress(e);
}
function handleMouseUp(e) {
clearLongPress();
}
function handleMouseLeave(e) {
clearLongPress();
}
function startLongPress(e) {
clearLongPress();
longPressTimer = setTimeout(() => {
const selection = window.getSelection();
if (selection.toString().length > 0) {
selectedText = selection.toString();
selectedMessageElement = e.currentTarget;
showContextMenu(e);
}
}, 500); // 500ms for long-press
}
function clearLongPress() {
if (longPressTimer) {
clearTimeout(longPressTimer);
longPressTimer = null;
}
}
function showContextMenu(e) {
if (contextMenu) {
const rect = e.target.getBoundingClientRect();
contextMenu.style.display = 'block';
contextMenu.style.left = `${e.clientX}px`;
contextMenu.style.top = `${e.clientY}px`;
e.preventDefault();
}
}
// Hide context menu when clicking outside
document.addEventListener('click', (e) => {
if (contextMenu && !contextMenu.contains(e.target)) {
contextMenu.style.display = 'none';
}
});
// Copy text functionality
if (copyTextButton) {
copyTextButton.addEventListener('click', () => {
if (selectedText) {
navigator.clipboard.writeText(selectedText).then(() => {
console.log('Text copied to clipboard');
contextMenu.style.display = 'none';
}).catch(err => {
console.error('Error copying text: ', err);
});
}
});
}
// Regenerate text functionality
if (regenerateTextButton) {
regenerateTextButton.addEventListener('click', async () => {
if (selectedMessageElement) {
const messageIndex = Array.from(messagesContainer.children).indexOf(selectedMessageElement);
if (messageIndex !== -1) {
// Remove this message and all subsequent messages
while (messagesContainer.children.length > messageIndex) {
messagesContainer.removeChild(messagesContainer.firstChild);
}
// Remove corresponding messages from chatHistoryData
chatHistoryData[currentChatId] = chatHistoryData[currentChatId].slice(0, messageIndex * 2);
// Get the last user message
const lastUserMessage = chatHistoryData[currentChatId][chatHistoryData[currentChatId].length - 2].content;
// Regenerate the AI response
contextMenu.style.display = 'none';
await generateAIResponse(lastUserMessage);
}
}
});
}
async function generateAIResponse(userMessage) {
showLoadingIndicator();
toggleSendStopButton();
try {
if (!(await isServerRunning())) {
throw new Error('LM Studio server is not running');
}
if (availableModels.length === 0) {
await fetchAvailableModels();
}
if (availableModels.length === 0) {
throw new Error('No models available');
}
const currentChat = chatHistoryData[currentChatId] || [];
const messages = [
{ role: 'system', content: systemPrompt },
...currentChat.map(msg => ({ role: msg.role, content: msg.content })),
{ role: 'user', content: userMessage }
];
abortController = new AbortController();
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: availableModels[0], // Use the first available model
messages: messages,
temperature: temperature,
stream: true, // Enable streaming
}),
signal: abortController.signal,
});
if (!response.ok) {
throw new Error('API request failed');
}
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let aiMessage = '';
const aiMessageElement = appendMessage('ai', '');
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
const parsedLines = lines
.map(line => line.replace(/^data: /, '').trim())
.filter(line => line !== '' && line !== '[DONE]')
.map(line => JSON.parse(line));
for (const parsedLine of parsedLines) {
const { choices } = parsedLine;
const { delta } = choices[0];
const { content } = delta;
if (content) {
aiMessage += content;
aiMessageElement.innerHTML = sanitizeInput(aiMessage);
initializeCodeMirror(aiMessageElement);
scrollToBottom();
}
}
}
updateChatHistory(userMessage, aiMessage);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Error:', error);
appendMessage('error', 'An error occurred while fetching the response. Please check your LM Studio server connection.');
}
} finally {
hideLoadingIndicator();
toggleSendStopButton();
abortController = null;
}
}
function closeApplication() {
// Send a message to the main process to close the application
if (window.electron) {
window.electron.send('close-app');
} else {
console.log('Electron not available. Unable to close the application.');
alert('This function is only available in the desktop application.');
}
}
// Initialize the UI
document.addEventListener('DOMContentLoaded', () => {
loadChatHistory();
loadServerUrl();
loadSystemPrompt();
initializeTemperature();
updateChatHistoryUI();
fetchAvailableModels();
// Set initial sidebar state
if (window.innerWidth <= 768 && sidebar) {
sidebar.classList.add('hidden');
}
// Add animation classes
document.body.classList.add('animate-fade-in');
if (chatContainer) chatContainer.classList.add('animate-fade-in');
if (sidebar) sidebar.classList.add('animate-fade-in');
// Add smooth scrolling to the chat container
if (messagesContainer) messagesContainer.style.scrollBehavior = 'smooth';
// Show welcome message on initial load
showWelcomeMessage();
// Ensure sidebar toggle button exists before adding event listener
if (sidebarToggle) {
sidebarToggle.addEventListener('click', (e) => {
e.stopPropagation();
toggleSidebar();
});
}
// Ensure close sidebar button exists before adding event listener
if (closeSidebarButton) {
closeSidebarButton.addEventListener('click', (e) => {
e.stopPropagation();
toggleSidebar();
});
}
if (confirmActionButton) {
confirmActionButton.addEventListener('click', () => {
if (actionToPerform === 'deleteChat' && chatToDelete) {
deleteChatHistory(chatToDelete);
chatToDelete = null;
} else if (actionToPerform === 'clearAllChats') {
clearAllChats();
} else if (actionToPerform === 'exit') {
closeApplication();
}
hideConfirmationModal();
actionToPerform = null; // Reset the action
});
}
if (cancelActionButton) {
cancelActionButton.addEventListener('click', hideConfirmationModal);
}
// Add event listener for the Exit button
if (exitButton) {
exitButton.addEventListener('click', () => {
showExitConfirmation();
if (window.innerWidth <= 768 && sidebar && sidebar.classList.contains('active')) {
toggleSidebar();
}
});
}
});
// New function to hide loading indicator on page load
function hideLoadingIndicatorOnLoad() {
if (loadingIndicator && loadingIndicator.parentNode) {
loadingIndicator.parentNode.removeChild(loadingIndicator);
}
}
// Add event listener to hide loading indicator when the page loads
window.addEventListener('load', hideLoadingIndicatorOnLoad);