-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2258 lines (1974 loc) · 92.1 KB
/
Copy pathscript.js
File metadata and controls
2258 lines (1974 loc) · 92.1 KB
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
// External Libraries are loaded in index.html:
// - marked.js: For Markdown parsing
// - highlight.js: For syntax highlighting
// --- 1. CONFIGURATION & STATE MANAGEMENT ---
const config = {
defaultLogLevel: 'info',
dbName: 'gChatDB',
dbVersion: 1, // Remember to increment this if you change DB schema with new stores/indexes
geminiApiUrl: 'https://esm.run/@google/generative-ai'
};
const state = {
currentChatId: null,
isGenerating: false,
settings: {},
chats: [], // This will hold all chat metadata from the DB
activeItemMenu: null,
editingPromptId: null, // To track which prompt is being edited
};
// --- 2. UTILS & HELPERS ---
const logger = {
debug: (...args) => state.settings.logLevel === 'debug' && console.log('[DEBUG]', ...args),
info: (...args) => ['debug', 'info'].includes(state.settings.logLevel) && console.info('[INFO]', ...args),
warn: (...args) => ['debug', 'info', 'warn'].includes(state.settings.logLevel) && console.warn('[WARN]', ...args),
error: (...args) => console.error('[ERROR]', ...args),
};
// DOM Elements
const dom = {
// Main layout
appContainer: document.querySelector('.app-container'),
sidebar: document.querySelector('.sidebar'),
mainContent: document.querySelector('.main-content'),
configPanel: document.querySelector('.config-panel'),
closeSidebarBtn: document.getElementById('close-sidebar-btn'),
openSidebarBtn: document.getElementById('open-sidebar-btn'),
speedNewChatBtn: document.getElementById('speed-new-chat-btn'),
// Chat
chatWindow: document.querySelector('.chat-window'),
userInput: document.getElementById('userInput'),
sendButton: document.getElementById('sendButton'),
newChatBtn: document.getElementById('new-chat-btn'),
// Sidebar
chatHistoryContainer: document.getElementById('chat-history-container'),
searchChatsInput: document.getElementById('search-chats-input'),
// Main chat header controls
copyChatBtn: document.getElementById('copy-chat-btn'),
exportChatBtn: document.getElementById('export-chat-btn'),
exportOptions: document.getElementById('export-options'),
// Config Panel
configToggleBtn: document.getElementById('config-toggle-btn'),
closeConfigPanelBtn: document.getElementById('close-config-panel-btn'),
systemPromptSelect: document.getElementById('system-prompt-select'),
customSystemPromptText: document.getElementById('custom-system-prompt-text'),
apiKeySelect: document.getElementById('api-key-select'),
modelSelect: document.getElementById('model-select'),
temperatureSlider: document.getElementById('temperature-slider'),
tempValueDisplay: document.getElementById('temp-value'),
topPSlider: document.getElementById('top-p-slider'),
topPValueDisplay: document.getElementById('top-p-value'),
maxLengthInput: document.getElementById('max-length-input'),
googleSearchSwitcher: document.getElementById('google-search-switcher'),
urlContextSwitcher: document.getElementById('url-context-switcher'),
thinkingSwitcher: document.getElementById('thinking-switcher'),
dynamicThinkingSwitcher: document.getElementById('dynamic-thinking-switcher'),
thinkingBudgetSlider: document.getElementById('thinking-budget-slider'),
thinkingBudgetValueDisplay: document.getElementById('thinking-budget-value'),
disableThinkingSwitcher: document.getElementById('disable-thinking-switcher'),
// Settings Modal
settingsModal: document.getElementById('settings-modal'),
openSettingsBtn: document.getElementById('open-settings-btn'),
closeSettingsBtn: document.getElementById('close-settings-btn'),
settingsNav: document.querySelector('.modal-nav'),
settingsTabs: document.querySelectorAll('.modal-tab'),
// Settings - General
themeSelect: document.getElementById('theme-select'),
contextSizeSlider: document.getElementById('context-window-slider'),
contextSizeLabel: document.getElementById('context-window-label'),
unlimitedContextCheckbox: document.getElementById('unlimited-context-checkbox'),
apiKeyList: document.getElementById('api-key-list'),
addApiKeyBtn: document.getElementById('add-api-key-btn'),
newApiKeyName: document.getElementById('new-api-key-name'),
newApiKeyValue: document.getElementById('new-api-key-value'),
// Settings - Models
fetchModelsBtn: document.getElementById('fetch-models-btn'),
modelList: document.getElementById('model-list'),
// Settings - Prompts
promptTitleInput: document.getElementById('prompt-title'),
promptTextInput: document.getElementById('prompt-text'),
savePromptBtn: document.getElementById('save-prompt-btn'),
cancelEditPromptBtn: document.getElementById('cancel-edit-prompt-btn'),
promptList: document.getElementById('prompt-list'),
// Settings - Chats
addFolderBtn: document.getElementById('add-folder-btn'),
newFolderNameInput: document.getElementById('new-folder-name'),
folderList: document.getElementById('folder-list'),
deleteAllChatsBtn: document.getElementById('delete-all-chats-btn'),
// Notification
notificationContainer: document.querySelector('.notification-container'),
// Custom Input Modal
customInputModal: document.getElementById('custom-input-modal'),
customInputModalTitle: document.getElementById('custom-input-modal-title'),
customInputModalLabel: document.getElementById('custom-input-modal-label'),
customInputModalField: document.getElementById('custom-input-modal-field'),
customInputModalOkBtn: document.getElementById('custom-input-modal-ok-btn'),
customInputModalCancelBtn: document.getElementById('custom-input-modal-cancel-btn'),
customInputModalCloseBtn: document.getElementById('custom-input-modal-close-btn'),
};
// Notification System
function showNotification(message, type = 'info', duration = 3000) {
const notification = document.createElement('div');
notification.className = `toast-notification ${type}`;
notification.textContent = message;
dom.notificationContainer.appendChild(notification);
setTimeout(() => notification.classList.add('show'), 10);
setTimeout(() => {
notification.classList.remove('show');
notification.addEventListener('transitionend', () => notification.remove());
}, duration);
}
// --- 3. DATABASE (IndexedDB) ---
let db;
function initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(config.dbName, config.dbVersion);
request.onupgradeneeded = event => {
const db = event.target.result;
if (!db.objectStoreNames.contains('chats')) {
db.createObjectStore('chats', { keyPath: 'id' });
}
if (!db.objectStoreNames.contains('messages')) {
const messageStore = db.createObjectStore('messages', { keyPath: 'id' });
messageStore.createIndex('chatId', 'chatId', { unique: false });
}
if (!db.objectStoreNames.contains('system_prompts')) {
db.createObjectStore('system_prompts', { keyPath: 'id' });
}
};
request.onsuccess = event => {
db = event.target.result;
logger.info('Database initialized successfully.');
resolve(db);
};
request.onerror = event => {
logger.error('Database error:', event.target.errorCode);
reject(event.target.error);
};
});
}
const dbManager = {
add: (storeName, data) => performDBTransaction(storeName, 'readwrite', store => store.add(data)),
put: (storeName, data) => performDBTransaction(storeName, 'readwrite', store => store.put(data)),
get: (storeName, id) => performDBTransaction(storeName, 'readonly', store => store.get(id)),
getAll: (storeName) => performDBTransaction(storeName, 'readonly', store => store.getAll()),
delete: (storeName, id) => performDBTransaction(storeName, 'readwrite', store => store.delete(id)),
clear: (storeName) => performDBTransaction(storeName, 'readwrite', store => store.clear()),
getMessagesForChat: (chatId) => {
return new Promise((resolve, reject) => {
const transaction = db.transaction('messages', 'readonly');
const store = transaction.objectStore('messages');
const index = store.index('chatId');
const request = index.getAll(chatId);
request.onsuccess = () => resolve(request.result.sort((a, b) => a.timestamp - b.timestamp));
request.onerror = (event) => reject(event.target.error);
});
}
};
function performDBTransaction(storeName, mode, operation) {
return new Promise((resolve, reject) => {
if (!db) return reject('Database not initialized');
const transaction = db.transaction(storeName, mode);
const store = transaction.objectStore(storeName);
const request = operation(store);
request.onsuccess = () => resolve(request.result);
request.onerror = event => {
logger.error(`DB transaction error on ${storeName}:`, event.target.error);
reject(event.target.error);
};
});
}
// --- 4. SETTINGS MANAGEMENT (localStorage & Folders) ---
const settingsManager = {
_defaults: {
theme: 'system',
contextWindowSize: 10,
unlimitedContext: false,
apiKeys: [],
logLevel: 'info',
models: { list: [] },
folders: [],
enableGoogleSearchGrounding: false,
enableUrlContext: false,
enableThinking: false,
enableDynamicThinking: false,
thinkingBudget: 0,
disableThinking: false,
},
load() {
let storedSettings = {};
try {
storedSettings = JSON.parse(localStorage.getItem('gChatSettings')) || {};
} catch (e) {
logger.error("Could not parse settings, resetting to default.", e);
storedSettings = {};
}
state.settings = { ...this._defaults, ...storedSettings, models: { ...this._defaults.models, ...(storedSettings.models || {}) } };
logger.info('Settings loaded:', state.settings);
},
save() {
localStorage.setItem('gChatSettings', JSON.stringify(state.settings));
logger.debug('Settings saved.');
},
get: (key) => state.settings[key],
set(key, value) {
state.settings[key] = value;
this.save();
},
getApiKeys: () => settingsManager.get('apiKeys') || [],
getDefaultApiKey: () => settingsManager.getApiKeys().find(k => k.isDefault) || settingsManager.getApiKeys()[0],
addApiKey(name, key) {
const keys = this.getApiKeys();
const newKey = { id: crypto.randomUUID(), name, key, isDefault: keys.length === 0 };
this.set('apiKeys', [...keys, newKey]);
return newKey;
},
deleteApiKey(id) {
let keys = this.getApiKeys().filter(k => k.id !== id);
if (keys.length > 0 && !keys.some(k => k.isDefault)) keys[0].isDefault = true;
this.set('apiKeys', keys);
},
setDefaultApiKey(id) {
const keys = this.getApiKeys().map(k => ({ ...k, isDefault: k.id === id }));
this.set('apiKeys', keys);
},
getModels: () => settingsManager.get('models').list || [],
getActiveModels: () => settingsManager.getModels().filter(m => m.isActive),
setModels(modelsList) {
const newSettings = { ...state.settings.models, list: modelsList };
this.set('models', newSettings);
},
getFolders: () => settingsManager.get('folders') || [],
addFolder(name) {
const folders = this.getFolders();
const newFolder = { id: crypto.randomUUID(), name };
this.set('folders', [...folders, newFolder]);
return newFolder;
},
updateFolder(id, newName) {
const folders = this.getFolders().map(f => f.id === id ? { ...f, name: newName } : f);
this.set('folders', folders);
},
deleteFolder(id) {
const folders = this.getFolders().filter(f => f.id !== id);
this.set('folders', folders);
}
};
// --- 5. UI RENDERING & DYNAMIC CONTENT ---
function applyTheme(theme) {
if (theme === 'system') {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
document.body.classList.toggle('dark-theme', prefersDark);
} else {
document.body.classList.toggle('dark-theme', theme === 'dark');
}
}
function renderMarkdown(element, text) {
if (window.marked && window.hljs) {
element.innerHTML = window.marked.parse(text, { breaks: true, gfm: true });
element.querySelectorAll('pre code').forEach((block) => {
const pre = block.parentElement;
if (pre.querySelector('.code-header')) return;
const header = document.createElement('div');
header.className = 'code-header';
const langName = block.className.match(/language-(\w+)/)?.[1] || 'text';
const langSpan = document.createElement('span');
langSpan.textContent = langName;
const copyBtn = document.createElement('button');
copyBtn.className = 'copy-code-btn';
copyBtn.textContent = 'Copy';
copyBtn.onclick = () => {
navigator.clipboard.writeText(block.textContent);
copyBtn.textContent = 'Copied!';
setTimeout(() => { copyBtn.textContent = 'Copy'; }, 2000);
};
header.append(langSpan, copyBtn);
pre.prepend(header);
window.hljs.highlightElement(block);
});
} else {
logger.warn('marked.js or hljs not loaded. Cannot render markdown.');
element.textContent = text;
}
}
function adjustTextareaHeight(textareaElement) {
textareaElement.style.height = 'auto'; // Reset height
const computedStyle = getComputedStyle(textareaElement);
const paddingTop = parseFloat(computedStyle.paddingTop);
const paddingBottom = parseFloat(computedStyle.paddingBottom);
const scrollHeight = textareaElement.scrollHeight;
let lineHeight = parseFloat(computedStyle.lineHeight);
if (isNaN(lineHeight) || computedStyle.lineHeight === 'normal') {
// Fallback for 'normal' or if parsing failed.
// Create a temporary element to measure line height.
const temp = document.createElement('div');
temp.style.font = computedStyle.font;
temp.style.visibility = 'hidden';
temp.style.position = 'absolute';
temp.textContent = 'M'; // Single character for measurement
document.body.appendChild(temp);
lineHeight = temp.offsetHeight;
document.body.removeChild(temp);
}
if (lineHeight <= 0) { // Another fallback if line height is still invalid
lineHeight = parseFloat(computedStyle.fontSize) * 1.2;
}
// Calculate content height excluding top/bottom padding
const contentHeight = scrollHeight - paddingTop - paddingBottom;
let numberOfLines = 0;
if (contentHeight > 0 && lineHeight > 0) {
numberOfLines = Math.round(contentHeight / lineHeight);
} else if (textareaElement.value === '') { // Handle empty textarea
numberOfLines = 0;
} else { // Fallback if contentHeight or lineHeight is zero with content
numberOfLines = 1;
}
// Ensure textarea is at least one line high, even if empty, matching rows="1"
if (textareaElement.value === '' && numberOfLines === 0) {
textareaElement.style.height = lineHeight + paddingTop + paddingBottom + 'px';
} else if (numberOfLines > 0) {
const targetLines = Math.min(5, Math.max(1, numberOfLines)); // Ensure at least 1 line
const targetHeight = (targetLines * lineHeight) + paddingTop + paddingBottom;
textareaElement.style.height = targetHeight + 'px';
} else {
// Default to single line height if other conditions don't specify
textareaElement.style.height = lineHeight + paddingTop + paddingBottom + 'px';
}
// overflow-y: auto is already set in CSS
}
async function renderChat(chatId) {
dom.chatWindow.innerHTML = '';
if (!chatId) return;
try {
const messages = await dbManager.getMessagesForChat(chatId);
const fragment = document.createDocumentFragment();
messages.forEach(msg => {
const msgEl = createMessageElement(msg);
fragment.appendChild(msgEl);
});
dom.chatWindow.appendChild(fragment);
dom.chatWindow.scrollTop = dom.chatWindow.scrollHeight;
} catch (err) {
logger.error(`Failed to render chat ${chatId}:`, err);
showNotification('Could not load messages for this chat.', 'error');
}
}
// --- MESSAGE ELEMENT & CONTROLS ---
function createMessageElement(message) {
const template = document.getElementById('message-template').content.cloneNode(true);
const messageEl = template.querySelector('.message');
const avatar = template.querySelector('.avatar');
const messageBody = template.querySelector('.message-body');
const timestampEl = template.querySelector('.timestamp');
const modelNameEl = template.querySelector('.model-name');
const editedIndicator = template.querySelector('.edited-indicator');
const controlsContainer = template.querySelector('.message-controls');
messageEl.dataset.messageId = message.id;
messageEl.classList.add(message.role);
avatar.textContent = message.role === 'user' ? 'U' : 'AI';
if (message.role === 'model') {
modelNameEl.textContent = message.modelUsed || 'gemini';
renderMarkdown(messageBody, message.content);
} else {
messageBody.textContent = message.content;
modelNameEl.remove();
}
const date = new Date(message.timestamp);
timestampEl.textContent = date.toLocaleString();
if (message.isEdited) {
editedIndicator.textContent = '(edited)';
}
// --- Render Thinking Process ---
if (message.usage && message.usage.thoughtsTokenCount > 0) {
const thinkingDetails = document.createElement('details');
thinkingDetails.className = 'thinking-process';
const thinkingSummary = document.createElement('summary');
thinkingSummary.className = 'thinking-summary';
thinkingSummary.innerHTML = `
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: middle; margin-right: 5px;"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path></svg>
<span>Thinking (${(message.usage.responseTime / 1000).toFixed(2)}s, ${message.usage.thoughtsTokenCount} tokens)</span>
`;
thinkingDetails.appendChild(thinkingSummary);
const thinkingContent = document.createElement('div');
thinkingContent.className = 'thinking-content';
if (message.thinkingContent) {
renderMarkdown(thinkingContent, message.thinkingContent);
} else if (message.thinkingSteps && message.thinkingSteps.length > 0) {
message.thinkingSteps.forEach(step => {
const stepDiv = document.createElement('div');
stepDiv.className = 'thinking-step';
const toolName = step.name;
const toolArgs = JSON.stringify(step.args, null, 2);
const toolHeader = document.createElement('div');
toolHeader.className = 'tool-call-header';
toolHeader.innerHTML = `Tool Call: <strong>${toolName}</strong>`;
const codeBlock = document.createElement('pre');
const codeElement = document.createElement('code');
codeElement.textContent = toolArgs;
codeBlock.appendChild(codeElement);
stepDiv.appendChild(toolHeader);
stepDiv.appendChild(codeBlock);
thinkingContent.appendChild(stepDiv);
});
} else {
const noStepsP = document.createElement('p');
noStepsP.innerHTML = '<i>The model performed internal thinking without explicit tool calls.</i>';
thinkingContent.appendChild(noStepsP);
}
thinkingDetails.appendChild(thinkingContent);
// Insert after the message header but before the body
messageEl.querySelector('.message-content-wrapper').insertBefore(thinkingDetails, messageBody);
}
populateMessageControls(controlsContainer, message, messageEl);
return messageEl;
}
function populateMessageControls(container, message, messageEl) {
const copyBtn = document.createElement('button');
copyBtn.title = 'Copy';
copyBtn.innerHTML = '📋';
copyBtn.onclick = () => {
navigator.clipboard.writeText(message.content);
showNotification('Copied to clipboard!', 'success');
};
const editBtn = document.createElement('button');
editBtn.title = 'Edit';
editBtn.innerHTML = '✏️';
editBtn.onclick = () => enableMessageEditing(messageEl, message);
const deleteBtn = document.createElement('button');
deleteBtn.title = 'Delete';
deleteBtn.innerHTML = '🗑️';
deleteBtn.onclick = async () => {
if (confirm('Are you sure you want to delete this message?')) {
await dbManager.delete('messages', message.id);
messageEl.remove();
showNotification('Message deleted.', 'info');
}
};
container.append(copyBtn, editBtn, deleteBtn);
if (message.role === 'model' && message.usage) {
const infoBtn = document.createElement('button');
infoBtn.title = 'Info';
infoBtn.innerHTML = 'ℹ️';
container.appendChild(infoBtn);
const popupTemplate = document.getElementById('info-popup-template').content.cloneNode(true);
const infoPopup = popupTemplate.querySelector('.info-popup');
let usageHTML = `
Time: ${(message.usage.responseTime / 1000).toFixed(2)} sec<br>
Prompt Tokens: ${message.usage.promptTokenCount}<br>
Completion Tokens: ${message.usage.completionTokenCount}<br>
`;
if (message.usage.thoughtsTokenCount > 0) {
usageHTML += `Thinking Tokens: ${message.usage.thoughtsTokenCount}<br>`;
}
usageHTML += `
Other Tokens: ${message.usage.otherTokenCount}<br>
Total Tokens: ${message.usage.totalTokenCount}<br>
Speed: ${message.usage.tokensPerSecond} t/s
`;
infoPopup.innerHTML = usageHTML;
messageEl.querySelector('.message-content-wrapper').appendChild(infoPopup);
infoBtn.onclick = (e) => {
e.stopPropagation();
infoPopup.classList.toggle('visible');
};
}
}
function enableMessageEditing(messageEl, message) {
const body = messageEl.querySelector('.message-body');
const controls = messageEl.querySelector('.message-controls');
const originalHeight = body.offsetHeight;
body.innerHTML = '';
controls.innerHTML = '';
const textArea = document.createElement('textarea');
textArea.className = 'message-edit-area';
textArea.value = message.content;
const saveBtn = document.createElement('button');
saveBtn.textContent = 'Save';
saveBtn.className = 'btn btn-sm btn-primary';
saveBtn.style.marginRight = '5px';
saveBtn.onclick = async () => {
const newContent = textArea.value.trim();
if (newContent && newContent !== message.content) {
const updatedMessage = { ...message, content: newContent, isEdited: true };
await dbManager.put('messages', updatedMessage);
const newElement = createMessageElement(updatedMessage);
messageEl.replaceWith(newElement);
showNotification('Message updated.', 'success');
} else {
const originalElement = createMessageElement(message);
messageEl.replaceWith(originalElement);
}
};
const cancelBtn = document.createElement('button');
cancelBtn.textContent = 'Cancel';
cancelBtn.className = 'btn btn-sm';
cancelBtn.onclick = () => {
const originalElement = createMessageElement(message);
messageEl.replaceWith(originalElement);
};
body.appendChild(textArea);
controls.style.display = 'flex';
controls.append(saveBtn, cancelBtn);
textArea.style.minHeight = `${originalHeight}px`;
textArea.focus();
}
// ---- Settings Rendering Functions ----
function renderModelsList() {
const models = settingsManager.getModels();
dom.modelList.innerHTML = '';
if (!models || models.length === 0) {
dom.modelList.innerHTML = '<li>Click "Fetch..." to load available models.</li>';
return;
}
const template = document.getElementById('model-item-template');
models.forEach(model => {
const item = template.content.cloneNode(true);
const li = item.querySelector('.model-item');
const nameLabel = item.querySelector('.model-name-label');
nameLabel.textContent = model.name;
if (model.status === 'new') li.classList.add('new-model');
else if (model.status === 'stale') li.classList.add('stale-model');
const favToggle = item.querySelector('.fav-toggle');
if (model.isFavorite) favToggle.classList.add('favorited');
favToggle.onclick = () => {
model.isFavorite = !model.isFavorite;
settingsManager.setModels(models);
renderModelsList();
updateModelDropdowns();
};
const activeToggleInput = item.querySelector('.active-toggle');
activeToggleInput.checked = model.isActive;
activeToggleInput.onchange = () => {
model.isActive = activeToggleInput.checked;
if (model.status === 'new' && model.isActive) model.status = 'ok';
settingsManager.setModels(models);
renderModelsList();
updateModelDropdowns();
};
item.querySelector('.delete-model-btn').onclick = () => {
if (confirm(`Delete model "${model.name}"?`)) {
let updatedModels = settingsManager.getModels().filter(m => m.name !== model.name);
settingsManager.setModels(updatedModels);
renderModelsList();
updateModelDropdowns();
}
};
if (model.status === 'stale') {
favToggle.disabled = true;
activeToggleInput.disabled = true;
li.title = 'This model was not found and may be deprecated.';
}
dom.modelList.appendChild(item);
});
}
async function renderSystemPromptsList() {
const prompts = await dbManager.getAll('system_prompts');
dom.promptList.innerHTML = '';
const template = document.getElementById('prompt-item-template');
prompts.forEach(prompt => {
const item = template.content.cloneNode(true);
item.querySelector('.prompt-title-text').textContent = prompt.title;
item.querySelector('.edit-prompt-btn').onclick = () => {
state.editingPromptId = prompt.id;
dom.promptTitleInput.value = prompt.title;
dom.promptTextInput.value = prompt.text;
dom.savePromptBtn.textContent = 'Update Prompt';
dom.cancelEditPromptBtn.style.display = 'inline-block';
};
item.querySelector('.delete-prompt-btn').onclick = async () => {
if (confirm(`Delete prompt "${prompt.title}"?`)) {
await dbManager.delete('system_prompts', prompt.id);
showNotification('Prompt deleted.', 'success');
await renderSystemPromptsList();
await updateSystemPromptDropdowns();
}
};
dom.promptList.appendChild(item);
});
}
function renderFolderListSettings() {
const folders = settingsManager.getFolders();
dom.folderList.innerHTML = '';
const template = document.getElementById('folder-item-template');
folders.forEach(folder => {
const item = template.content.cloneNode(true);
const nameSpan = item.querySelector('.folder-name-text');
nameSpan.textContent = folder.name;
item.querySelector('.edit-folder-btn').onclick = () => { // No longer async here
showInputModal('Rename Folder', 'Enter new folder name:', folder.name, async (newName) => {
if (newName && newName.trim() !== folder.name) {
settingsManager.updateFolder(folder.id, newName.trim());
await renderChatHistory(); // Ensure this is awaited
renderFolderListSettings(); // Re-render the folder list in settings
showNotification('Folder renamed.', 'success');
}
});
};
item.querySelector('.delete-folder-btn').onclick = async () => {
if (confirm(`Delete folder "${folder.name}"? Chats in this folder will not be deleted.`)) {
settingsManager.deleteFolder(folder.id);
const chatsToUpdate = state.chats.filter(c => c.folderId === folder.id);
for (const chat of chatsToUpdate) {
await dbManager.put('chats', { ...chat, folderId: null });
}
await renderChatHistory();
renderFolderListSettings();
}
};
dom.folderList.appendChild(item);
});
}
function renderApiKeyList() {
const keys = settingsManager.getApiKeys();
dom.apiKeyList.innerHTML = '';
if (keys.length === 0) {
dom.apiKeyList.innerHTML = '<li>No API keys configured. Please add one.</li>';
return;
}
const fragment = document.createDocumentFragment();
keys.forEach(key => {
const li = document.createElement('li');
li.className = 'api-key-item';
const radioLabel = document.createElement('label');
radioLabel.style.flexGrow = 1;
radioLabel.style.display = 'flex';
radioLabel.style.alignItems = 'center';
radioLabel.style.cursor = 'pointer';
const radio = document.createElement('input');
radio.type = 'radio';
radio.name = 'default-api-key';
radio.value = key.id;
radio.checked = key.isDefault;
radio.style.marginRight = '10px';
radio.onchange = () => {
settingsManager.setDefaultApiKey(key.id);
updateApiKeyDropdowns();
showNotification(`"${key.name}" is now the default key.`, 'success');
};
const nameSpan = document.createElement('span');
nameSpan.textContent = `${key.name} (...${key.key.slice(-4)})`;
radioLabel.append(radio, nameSpan);
const actionsDiv = document.createElement('div');
actionsDiv.className = 'item-actions';
const deleteBtn = document.createElement('button');
deleteBtn.title = 'Delete';
deleteBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>`;
deleteBtn.onclick = (e) => {
e.stopPropagation();
if (confirm(`Are you sure you want to delete the key "${key.name}"?`)) {
settingsManager.deleteApiKey(key.id);
renderApiKeyList();
updateApiKeyDropdowns();
showNotification('API Key deleted.', 'info');
}
};
actionsDiv.appendChild(deleteBtn);
li.append(radioLabel, actionsDiv);
fragment.appendChild(li);
});
dom.apiKeyList.appendChild(fragment);
}
function updateApiKeyDropdowns() {
const keys = settingsManager.getApiKeys();
dom.apiKeySelect.innerHTML = '';
keys.forEach(key => {
const option = document.createElement('option');
option.value = key.id;
option.textContent = `${key.name}${key.isDefault ? ' (Default)' : ''}`;
dom.apiKeySelect.appendChild(option);
});
}
function updateModelDropdowns() {
let models = settingsManager.getActiveModels();
dom.modelSelect.innerHTML = '';
models.sort((a, b) => (b.isFavorite ? 1 : 0) - (a.isFavorite ? 1 : 0));
models.forEach(model => {
const option = document.createElement('option');
option.value = model.name;
option.textContent = `${model.name}${model.isFavorite ? ' ★' : ''}`;
dom.modelSelect.appendChild(option);
});
}
async function updateSystemPromptDropdowns() {
const prompts = await dbManager.getAll('system_prompts');
dom.systemPromptSelect.innerHTML = '<option value="default">Default</option>';
prompts.forEach(prompt => {
const option = document.createElement('option');
option.value = prompt.id;
option.textContent = prompt.title;
dom.systemPromptSelect.appendChild(option);
});
// Add event listener for system prompt select change
dom.systemPromptSelect.addEventListener('change', async (event) => {
const selectedId = event.target.value;
const customPromptTextArea = dom.customSystemPromptText;
if (selectedId === 'default') {
customPromptTextArea.value = '';
} else {
const prompt = await dbManager.get('system_prompts', selectedId);
if (prompt) {
customPromptTextArea.value = prompt.text;
} else {
customPromptTextArea.value = ''; // Should not happen if ID is from DB
}
}
});
// Dispatch change event to populate textarea initially after dropdowns are updated
// This ensures the textarea is populated when the app loads or settings are updated.
dom.systemPromptSelect.dispatchEvent(new Event('change'));
}
function updateSettingsUI() {
// General Tab
const theme = settingsManager.get('theme');
dom.themeSelect.value = theme;
const contextSize = settingsManager.get('contextWindowSize');
const unlimited = settingsManager.get('unlimitedContext');
dom.contextSizeSlider.value = contextSize;
dom.contextSizeLabel.textContent = unlimited ? 'Unlimited' : contextSize;
dom.unlimitedContextCheckbox.checked = unlimited;
dom.contextSizeSlider.disabled = unlimited;
renderApiKeyList();
updateApiKeyDropdowns();
// Models Tab
renderModelsList();
updateModelDropdowns();
// Prompts Tab
renderSystemPromptsList();
updateSystemPromptDropdowns();
// Chats Tab
renderFolderListSettings();
// FR?: New switchers in config panel
if (dom.googleSearchSwitcher) { // Check if element exists
dom.googleSearchSwitcher.checked = settingsManager.get('enableGoogleSearchGrounding');
}
if (dom.urlContextSwitcher) { // Check if element exists
dom.urlContextSwitcher.checked = settingsManager.get('enableUrlContext');
}
// Thinking controls
if (dom.thinkingSwitcher) {
dom.thinkingSwitcher.checked = settingsManager.get('enableThinking');
}
if (dom.disableThinkingSwitcher) {
dom.disableThinkingSwitcher.checked = settingsManager.get('disableThinking');
}
if (dom.dynamicThinkingSwitcher) {
dom.dynamicThinkingSwitcher.checked = settingsManager.get('enableDynamicThinking');
dom.dynamicThinkingSwitcher.disabled = !settingsManager.get('enableThinking');
}
if (dom.thinkingBudgetSlider) {
const budget = settingsManager.get('thinkingBudget');
dom.thinkingBudgetSlider.value = budget;
if (dom.thinkingBudgetValueDisplay) {
dom.thinkingBudgetValueDisplay.textContent = budget;
}
dom.thinkingBudgetSlider.disabled = !settingsManager.get('enableThinking') || settingsManager.get('enableDynamicThinking');
}
}
// --- 6. CORE LOGIC ---
async function handleSendMessage() {
const content = dom.userInput.value.trim();
if (!content || state.isGenerating) return;
// Use the key selected in the config panel, fallback to default
const selectedKeyId = dom.apiKeySelect.value;
const keys = settingsManager.getApiKeys();
let apiKeyData = keys.find(k => k.id === selectedKeyId) || settingsManager.getDefaultApiKey();
if (!apiKeyData || !apiKeyData.key) {
showNotification('Please select a valid API key in the config panel or set a default in Settings.', 'error');
return;
}
state.isGenerating = true;
dom.sendButton.disabled = true;
dom.sendButton.classList.add('sending');
const userMessage = {
id: crypto.randomUUID(),
chatId: state.currentChatId,
role: 'user',
content: content,
timestamp: Date.now(),
};
try {
await dbManager.add('messages', userMessage);
dom.chatWindow.appendChild(createMessageElement(userMessage));
dom.chatWindow.scrollTop = dom.chatWindow.scrollHeight;
dom.userInput.value = '';
adjustTextareaHeight(dom.userInput); // Reset height after clearing
await getAIResponse(apiKeyData.key);
} catch (err) {
logger.error('Error sending message:', err);
showNotification('Failed to send message.', 'error');
state.isGenerating = false;
dom.sendButton.disabled = false;
}
}
async function getAIResponse(apiKey) {
// Create a placeholder message for the AI response
const modelUsed = dom.modelSelect.value;
const aiMessage = {
id: crypto.randomUUID(),
chatId: state.currentChatId,
role: 'model',
content: '...',
timestamp: Date.now(),
modelUsed: modelUsed,
usage: null
};
const aiMessageElement = createMessageElement(aiMessage);
const aiMessageBody = aiMessageElement.querySelector('.message-body');
dom.chatWindow.appendChild(aiMessageElement);
dom.chatWindow.scrollTop = dom.chatWindow.scrollHeight;
try {
// Dynamically import the SDK
const { GoogleGenerativeAI } = await import(config.geminiApiUrl);
const genAI = new GoogleGenerativeAI(apiKey);
// Get generation config from UI
const generationConfig = {
temperature: parseFloat(dom.temperatureSlider.value),
topP: parseFloat(dom.topPSlider.value),
maxOutputTokens: parseInt(dom.maxLengthInput.value, 10),
};
// Handle thinkingConfig based on new logic
const disableThinking = settingsManager.get('disableThinking');
const enableThinking = settingsManager.get('enableThinking');
if (disableThinking) {
generationConfig.thinkingConfig = { thinkingBudget: 0 };
} else {
if (enableThinking) {
const enableDynamicThinking = settingsManager.get('enableDynamicThinking');
const thinkingBudgetSetting = settingsManager.get('thinkingBudget');
const thConfig = { includeThoughts: true }; // Tell the API to send the thinking content
if (enableDynamicThinking) {
thConfig.thinkingBudget = -1; // Dynamic budget
} else {
thConfig.thinkingBudget = parseInt(thinkingBudgetSetting, 10);
}
generationConfig.thinkingConfig = thConfig;
} else {
// If disableThinking is false AND enableThinking is false,
// no thinkingConfig should be added.
}
}
// Get system prompt from the text area
const customPromptText = dom.customSystemPromptText.value.trim();
let systemInstruction = null;
if (customPromptText) {
systemInstruction = { parts: [{ text: customPromptText }] };
}
let tools = [];
if (settingsManager.get('enableGoogleSearchGrounding')) {
tools.push({ "google_search": {} });
}
if (settingsManager.get('enableUrlContext')) {
tools.push({ "url_context": {} });
}
const modelParams = {
model: modelUsed,
generationConfig,
systemInstruction
};
if (tools.length > 0) {
modelParams.tools = tools;
}
const model = genAI.getGenerativeModel(modelParams);
// Prepare chat history for the API
let dbHistory = await dbManager.getMessagesForChat(state.currentChatId);
dbHistory = dbHistory.slice(0, -1);
const contextLimit = settingsManager.get('contextWindowSize');
const isUnlimited = settingsManager.get('unlimitedContext');
if (!isUnlimited && dbHistory.length > contextLimit) {
dbHistory = dbHistory.slice(-contextLimit);
}
const sanitizedHistoryForApi = [];
if (dbHistory.length > 0) {
let firstUserIndex = -1;
for (let i = 0; i < dbHistory.length; i++) {
if (dbHistory[i].role === 'user') {
firstUserIndex = i;
break;
}
}