-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptions.js
More file actions
1345 lines (1192 loc) · 60.8 KB
/
options.js
File metadata and controls
1345 lines (1192 loc) · 60.8 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
document.addEventListener('DOMContentLoaded', async function() {
// Initialize collapsible sections
const sectionHeaders = document.querySelectorAll('.section-header');
sectionHeaders.forEach(header => {
header.addEventListener('click', function() {
const sectionId = this.getAttribute('data-section');
const content = document.getElementById(sectionId);
const section = this.parentElement;
const icon = this.querySelector('.collapse-icon');
if (section.classList.contains('collapsed')) {
// Expand
section.classList.remove('collapsed');
content.style.display = 'block';
icon.textContent = '▼';
// Trigger animation
setTimeout(() => {
content.style.animation = 'slideDown 0.3s ease-out';
}, 0);
} else {
// Collapse
section.classList.add('collapsed');
content.style.display = 'none';
icon.textContent = '▶';
}
});
});
const labelsContainer = document.getElementById('labels-container');
const addLabelButton = document.getElementById('add-label');
const saveButton = document.getElementById('save-settings');
const apiKeyInput = document.getElementById('api-key');
const aiProviderSelect = document.getElementById('ai-provider');
const providerInfo = document.getElementById('provider-info');
const getApiKeyButton = document.getElementById('get-api-key');
const testApiButton = document.getElementById('test-api');
const apiTestResult = document.getElementById('api-test-result');
const geminiPaidContainer = document.getElementById('gemini-paid-container');
const geminiPaidCheckbox = document.getElementById('gemini-paid-plan');
const importLabelsButton = document.getElementById('import-labels');
const bulkImportTextarea = document.getElementById('bulk-import-text');
const loadImapFoldersButton = document.getElementById('load-imap-folders');
const folderLoadingIndicator = document.getElementById('folder-loading');
const folderSelection = document.getElementById('folder-selection');
const foldersPreview = document.getElementById('folders-preview');
const folderCount = document.getElementById('folder-count');
const useImapFoldersButton = document.getElementById('use-imap-folders');
const useCustomFoldersButton = document.getElementById('use-custom-folders');
const geminiMultiKeysContainer = document.getElementById('gemini-multi-keys-container');
const geminiKeysList = document.getElementById('gemini-keys-list');
const addGeminiKeyButton = document.getElementById('add-gemini-key');
// Ollama-specific elements
const ollamaModelSelect = document.getElementById('ollama-model');
const ollamaCustomModelInput = document.getElementById('ollama-custom-model');
const ollamaUrlInput = document.getElementById('ollama-url');
const ollamaAuthTokenInput = document.getElementById('ollama-auth-token');
const ollamaCpuOnlyCheckbox = document.getElementById('ollama-cpu-only');
const testOllamaButton = document.getElementById('test-ollama');
const listOllamaModelsButton = document.getElementById('list-ollama-models');
const downloadOllamaModelButton = document.getElementById('download-ollama-model');
const ollamaDownloadModelInput = document.getElementById('ollama-download-model');
const ollamaDownloadStatus = document.getElementById('ollama-download-status');
const ollamaTestResult = document.getElementById('ollama-test-result');
const diagnoseOllamaButton = document.getElementById('diagnose-ollama');
const ollamaDiagnostics = document.getElementById('ollama-diagnostics');
// Update endpoint URLs when Ollama URL changes
if (ollamaUrlInput) {
ollamaUrlInput.addEventListener('input', () => {
const url = ollamaUrlInput.value.trim() || 'http://localhost:11434';
const chatEndpoint = document.getElementById('ollama-chat-endpoint');
const pullEndpoint = document.getElementById('ollama-pull-endpoint');
const tagsEndpoint = document.getElementById('ollama-tags-endpoint');
if (chatEndpoint) chatEndpoint.textContent = `${url}/api/chat`;
if (pullEndpoint) pullEndpoint.textContent = `${url}/api/pull`;
if (tagsEndpoint) tagsEndpoint.textContent = `${url}/api/tags`;
});
}
let loadedFolders = [];
let geminiKeys = []; // Array to store multiple Gemini API keys
// AI Provider configurations
const aiProviders = {
gemini: {
name: 'Google Gemini',
signupUrl: 'https://aistudio.google.com/app/apikey',
info: '✓ Free tier: 5 requests/minute, 20/day per API key (enforced by addon)<br>✓ Tip: Create multiple API keys in different projects, switch keys when limit reached<br>✓ Check usage: <a href="https://aistudio.google.com/usage" target="_blank">AI Studio Usage</a><br>✓ Best for: General use, multilingual support<br>✓ Models: Gemini 2.5 Flash<br>✓ Check "paid plan" option to remove limits',
isFree: true
},
openai: {
name: 'OpenAI',
signupUrl: 'https://platform.openai.com/signup',
info: '✓ Free trial: $5 credit<br>✓ Best for: High accuracy, English content<br>✓ Models: GPT-4o-mini ($0.15/1M tokens)',
isFree: false
},
anthropic: {
name: 'Anthropic Claude',
signupUrl: 'https://console.anthropic.com/',
info: '✓ Free tier: Limited requests<br>✓ Best for: Long emails, detailed analysis<br>✓ Models: Claude 3 Haiku',
isFree: true
},
groq: {
name: 'Groq',
signupUrl: 'https://console.groq.com/',
info: '✓ Free tier: 30 requests/minute<br>✓ Best for: Speed (fastest)<br>✓ Models: Llama 3.3 (Mixtral deprecated)',
isFree: true
},
mistral: {
name: 'Mistral AI',
signupUrl: 'https://console.mistral.ai/',
info: '✓ Free tier: Limited requests<br>✓ Best for: European users, GDPR compliance<br>✓ Models: Mistral Small',
isFree: true
},
ollama: {
name: 'Ollama (Local LLM)',
signupUrl: 'https://ollama.ai/',
info: '✓ 100% Free: Runs locally on your machine<br>✓ Privacy: No data sent to external servers<br>✓ No rate limits: Process unlimited emails<br>✓ Models: Llama 2/3, Mistral, Phi, Gemma, Qwen, and more<br>✓ Requires: <a href="https://ollama.ai/download" target="_blank">Ollama installed</a> and running locally<br>✓ Setup: Install Ollama, run "ollama pull llama3.2" to download a model',
isFree: true
}
};
// Update provider info when selection changes
function updateProviderInfo() {
const provider = aiProviderSelect.value;
const config = aiProviders[provider];
// Get subsection elements
const ollamaSubsection = document.getElementById('ollama-settings-subsection');
const apiKeySubsection = document.getElementById('api-key-subsection');
const geminiMultiKeysSubsection = document.getElementById('gemini-multi-keys-subsection');
const geminiUsageSubsection = document.getElementById('gemini-usage-subsection');
const rateLimitWarning = document.getElementById('rate-limit-warning');
// Show/hide rate limit warning (not for Ollama)
if (rateLimitWarning) {
rateLimitWarning.style.display = provider === 'ollama' ? 'none' : 'block';
}
// Show/hide Gemini-specific elements
if (provider === 'gemini') {
geminiPaidContainer.style.display = 'block';
if (geminiMultiKeysSubsection) geminiMultiKeysSubsection.style.display = 'block';
if (geminiUsageSubsection) geminiUsageSubsection.style.display = 'block';
if (apiKeySubsection) apiKeySubsection.style.display = 'none';
if (ollamaSubsection) ollamaSubsection.style.display = 'none';
updateGeminiUsageDisplay();
} else if (provider === 'ollama') {
// Show Ollama settings, hide API key and Gemini sections
geminiPaidContainer.style.display = 'none';
if (geminiMultiKeysSubsection) geminiMultiKeysSubsection.style.display = 'none';
if (geminiUsageSubsection) geminiUsageSubsection.style.display = 'none';
if (apiKeySubsection) apiKeySubsection.style.display = 'none';
if (ollamaSubsection) ollamaSubsection.style.display = 'block';
} else {
geminiPaidContainer.style.display = 'none';
if (geminiMultiKeysSubsection) geminiMultiKeysSubsection.style.display = 'none';
if (geminiUsageSubsection) geminiUsageSubsection.style.display = 'none';
if (apiKeySubsection) apiKeySubsection.style.display = 'block';
if (ollamaSubsection) ollamaSubsection.style.display = 'none';
}
providerInfo.innerHTML = `
<div class="provider-details">
<strong>${config.name}</strong> ${config.isFree ? '<span class="free-badge">FREE</span>' : '<span class="paid-badge">PAID</span>'}
<p>${config.info}</p>
</div>
`;
if (provider !== 'ollama') {
apiKeyInput.placeholder = `Enter your ${config.name} API key`;
}
}
// Update Gemini usage display
async function updateGeminiUsageDisplay() {
const data = await browser.storage.local.get(['geminiRateLimits', 'currentGeminiKeyIndex', 'geminiApiKeys', 'geminiRateLimit']);
const currentIndex = data.currentGeminiKeyIndex || 0;
const keys = data.geminiApiKeys || geminiKeys;
if (keys.length > 1) {
// Multi-key mode
document.getElementById('single-key-usage').style.display = 'none';
document.getElementById('multi-key-usage').style.display = 'block';
const rateLimits = data.geminiRateLimits || [];
updateMultiKeyUsageDisplay(keys, rateLimits, currentIndex);
} else if (keys.length === 1) {
// Single-key mode but stored in new format
document.getElementById('single-key-usage').style.display = 'block';
document.getElementById('multi-key-usage').style.display = 'none';
const rateLimits = data.geminiRateLimits || [{ requests: [], dailyCount: 0, dailyResetTime: Date.now() }];
updateSingleKeyUsageDisplay(rateLimits[0]);
} else {
// Legacy single-key mode (backward compatibility)
document.getElementById('single-key-usage').style.display = 'block';
document.getElementById('multi-key-usage').style.display = 'none';
const rateLimit = data.geminiRateLimit || { requests: [], dailyCount: 0, dailyResetTime: Date.now() };
updateSingleKeyUsageDisplay(rateLimit);
}
}
// Update single key usage display (backward compatibility)
async function updateSingleKeyUsageDisplay(rateLimit) {
const now = Date.now();
// Update daily count
document.getElementById('gemini-daily-count').textContent = rateLimit.dailyCount;
// Update last request time
if (rateLimit.requests && rateLimit.requests.length > 0) {
const lastRequest = Math.max(...rateLimit.requests);
const minutesAgo = Math.floor((now - lastRequest) / 60000);
if (minutesAgo < 1) {
document.getElementById('gemini-last-request').textContent = 'Just now';
} else if (minutesAgo < 60) {
document.getElementById('gemini-last-request').textContent = `${minutesAgo} minute${minutesAgo > 1 ? 's' : ''} ago`;
} else {
const hoursAgo = Math.floor(minutesAgo / 60);
document.getElementById('gemini-last-request').textContent = `${hoursAgo} hour${hoursAgo > 1 ? 's' : ''} ago`;
}
} else {
document.getElementById('gemini-last-request').textContent = 'Never';
}
// Update reset time
if (rateLimit.dailyResetTime > now) {
const hoursUntil = Math.ceil((rateLimit.dailyResetTime - now) / (1000 * 60 * 60));
document.getElementById('gemini-reset-time').textContent = `In ${hoursUntil} hour${hoursUntil > 1 ? 's' : ''}`;
} else {
document.getElementById('gemini-reset-time').textContent = 'Expired (will reset on next request)';
}
// Update status and show warnings
const usageMessage = document.getElementById('usage-message');
const statusSpan = document.getElementById('gemini-status');
if (rateLimit.dailyCount >= 20) {
statusSpan.textContent = '🔴 Limit Reached';
statusSpan.style.color = '#dc3545';
usageMessage.className = 'usage-message warning';
usageMessage.textContent = '⚠️ Daily limit reached! Create a new API key in a different project and update it above to continue processing emails.';
} else if (rateLimit.dailyCount >= 15) {
statusSpan.textContent = '🟡 Nearly Full';
statusSpan.style.color = '#ffc107';
usageMessage.className = 'usage-message warning';
usageMessage.textContent = `⚠️ Only ${20 - rateLimit.dailyCount} requests remaining today. Consider switching to a new API key soon.`;
} else {
statusSpan.textContent = '🟢 Ready';
statusSpan.style.color = '#28a745';
usageMessage.style.display = 'none';
}
}
// Update multi-key usage display
function updateMultiKeyUsageDisplay(keys, rateLimits, currentIndex) {
const container = document.getElementById('all-keys-usage-stats');
const now = Date.now();
container.innerHTML = '';
keys.forEach((key, index) => {
const rateLimit = rateLimits[index] || { requests: [], dailyCount: 0, dailyResetTime: now };
const isActive = index === currentIndex;
const card = document.createElement('div');
card.className = `key-usage-card${isActive ? ' active' : ''}`;
// Determine status
let statusBadge = '';
if (isActive) {
statusBadge = '<span class="key-status active">🔵 ACTIVE</span>';
} else if (rateLimit.dailyCount >= 20) {
statusBadge = '<span class="key-status limit">🔴 LIMIT</span>';
} else if (rateLimit.dailyCount >= 15) {
statusBadge = '<span class="key-status warning">🟡 NEAR LIMIT</span>';
} else {
statusBadge = '<span class="key-status ready">🟢 READY</span>';
}
// Calculate reset time
let resetText = '--';
if (rateLimit.dailyResetTime > now) {
const hoursUntil = Math.ceil((rateLimit.dailyResetTime - now) / (1000 * 60 * 60));
resetText = `${hoursUntil}h`;
}
// Last request time
let lastRequestText = 'Never';
if (rateLimit.requests && rateLimit.requests.length > 0) {
const lastRequest = Math.max(...rateLimit.requests);
const minutesAgo = Math.floor((now - lastRequest) / 60000);
if (minutesAgo < 1) {
lastRequestText = 'Just now';
} else if (minutesAgo < 60) {
lastRequestText = `${minutesAgo}m ago`;
} else {
lastRequestText = `${Math.floor(minutesAgo / 60)}h ago`;
}
}
// Mask key for display
const maskedKey = key ? `...${key.slice(-8)}` : 'Not set';
card.innerHTML = `
<div class="key-header">
<span class="key-title">Key ${index + 1}: ${maskedKey}</span>
${statusBadge}
</div>
<div class="key-stats">
<div class="stat-item">
<span class="stat-label">Usage:</span>
<span class="stat-value">${rateLimit.dailyCount}/20</span>
</div>
<div class="stat-item">
<span class="stat-label">Last:</span>
<span class="stat-value">${lastRequestText}</span>
</div>
<div class="stat-item">
<span class="stat-label">Resets:</span>
<span class="stat-value">${resetText}</span>
</div>
<div class="stat-item">
<span class="stat-label">Available:</span>
<span class="stat-value">${20 - rateLimit.dailyCount}</span>
</div>
</div>
`;
container.appendChild(card);
});
}
// Add Gemini key input field
function addGeminiKeyInput(value = '', index = -1) {
if (index === -1) {
index = geminiKeys.length;
geminiKeys.push(value);
}
const keyItem = document.createElement('div');
keyItem.className = 'gemini-key-item';
keyItem.dataset.index = index;
const keyIndex = document.createElement('span');
keyIndex.className = 'key-index';
keyIndex.textContent = `#${index + 1}`;
const input = document.createElement('input');
input.type = 'password';
input.className = 'gemini-api-key-input';
input.placeholder = 'Enter Gemini API key from another project';
input.value = value;
input.dataset.index = index;
input.addEventListener('input', (e) => {
const newKey = e.target.value.trim();
geminiKeys[index] = newKey;
// Check for duplicates in real-time
if (newKey) {
const isDuplicate = geminiKeys.some((key, i) => i !== index && key.trim() === newKey);
if (isDuplicate) {
input.style.borderColor = '#dc3545';
input.title = '⚠️ This key is already added!';
} else {
input.style.borderColor = '';
input.title = '';
}
} else {
input.style.borderColor = '';
input.title = '';
}
});
const testButton = document.createElement('button');
testButton.className = 'button';
testButton.textContent = 'Test';
testButton.addEventListener('click', () => {
const keyValue = input.value.trim();
if (!keyValue) {
statusSpan.textContent = '⚠️ Enter key first';
statusSpan.className = 'key-test-result error';
return;
}
// Check for duplicates before testing
const isDuplicate = geminiKeys.some((key, i) => i !== index && key.trim() === keyValue);
if (isDuplicate) {
statusSpan.textContent = '⚠️ Duplicate key';
statusSpan.className = 'key-test-result error';
statusSpan.title = 'This key is already added in the list';
return;
}
testGeminiKey(keyValue, index, keyItem);
});
const removeButton = document.createElement('button');
removeButton.className = 'button';
removeButton.textContent = '×';
removeButton.addEventListener('click', () => removeGeminiKey(index));
const statusSpan = document.createElement('span');
statusSpan.className = 'key-test-result';
statusSpan.dataset.index = index;
keyItem.appendChild(keyIndex);
keyItem.appendChild(input);
keyItem.appendChild(testButton);
keyItem.appendChild(removeButton);
keyItem.appendChild(statusSpan);
geminiKeysList.appendChild(keyItem);
}
// Remove Gemini key
function removeGeminiKey(index) {
if (geminiKeys.length <= 1) {
alert('You must have at least one API key configured.');
return;
}
if (confirm(`Remove API key #${index + 1}?`)) {
geminiKeys.splice(index, 1);
refreshGeminiKeysList();
}
}
// Refresh Gemini keys list display
function refreshGeminiKeysList() {
geminiKeysList.innerHTML = '';
geminiKeys.forEach((key, index) => {
addGeminiKeyInput(key, index);
});
}
// Test individual Gemini key
async function testGeminiKey(apiKey, index, keyItemElement) {
const statusSpan = keyItemElement.querySelector('.key-test-result');
if (!apiKey) {
statusSpan.textContent = '⚠️ Enter key first';
statusSpan.className = 'key-test-result error';
return;
}
try {
statusSpan.textContent = 'Testing...';
statusSpan.className = 'key-test-result testing';
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
contents: [{ parts: [{ text: "Test" }] }],
generationConfig: { maxOutputTokens: 10 }
})
});
if (response.ok) {
statusSpan.textContent = '✓ Valid';
statusSpan.className = 'key-test-result success';
} else if (response.status === 429) {
statusSpan.textContent = '⚠️ Limit reached';
statusSpan.className = 'key-test-result error';
statusSpan.title = 'This key has reached its daily rate limit (20/day). Will reset in ~24 hours.';
console.error(`Key #${index + 1} has reached rate limit (429)`);
} else if (response.status === 401 || response.status === 403) {
statusSpan.textContent = '✗ Invalid key';
statusSpan.className = 'key-test-result error';
statusSpan.title = 'API key is invalid or expired. Check your key in Google AI Studio.';
console.error(`Key #${index + 1} test failed: ${response.status}`);
} else {
statusSpan.textContent = `✗ Failed (${response.status})`;
statusSpan.className = 'key-test-result error';
console.error(`Key #${index + 1} test failed:`, response.status);
}
} catch (error) {
statusSpan.textContent = `✗ Error`;
statusSpan.className = 'key-test-result error';
console.error(`Key #${index + 1} test error:`, error);
}
}
// Initialize provider info
updateProviderInfo();
aiProviderSelect.addEventListener('change', updateProviderInfo);
// Add Gemini key button
addGeminiKeyButton.addEventListener('click', () => {
addGeminiKeyInput('');
});
// Reset Gemini counter button
document.getElementById('reset-gemini-counter').addEventListener('click', async () => {
if (confirm('Reset usage counter? Do this only after switching to a new API key.')) {
await browser.storage.local.set({
geminiRateLimit: {
requests: [],
dailyCount: 0,
dailyResetTime: Date.now() + (24 * 60 * 60 * 1000)
}
});
await updateGeminiUsageDisplay();
const usageMessage = document.getElementById('usage-message');
usageMessage.className = 'usage-message info';
usageMessage.textContent = '✓ Usage counter reset. You can now process up to 20 more emails today with your new API key.';
}
});
// Refresh usage button (single key)
document.getElementById('refresh-usage').addEventListener('click', async () => {
await updateGeminiUsageDisplay();
const usageMessage = document.getElementById('usage-message');
usageMessage.className = 'usage-message info';
usageMessage.textContent = '✓ Usage information refreshed.';
setTimeout(() => {
if (usageMessage.classList.contains('info')) {
usageMessage.style.display = 'none';
}
}, 3000);
});
// Refresh all usage button (multi key)
document.getElementById('refresh-all-usage').addEventListener('click', async () => {
await updateGeminiUsageDisplay();
showMessage('✓ All usage information refreshed.', true);
});
// Get API Key button
getApiKeyButton.addEventListener('click', async () => {
const provider = aiProviderSelect.value;
const config = aiProviders[provider];
try {
// Try to open in new tab
await browser.tabs.create({ url: config.signupUrl });
} catch (error) {
console.error('Failed to open tab:', error);
// Fallback: show URL and copy to clipboard
const url = config.signupUrl;
try {
await navigator.clipboard.writeText(url);
showMessage(`URL copied to clipboard:\n${url}`, true);
} catch (e) {
// Last resort: show alert with URL
alert(`Please visit:\n${url}`);
}
}
});
// Function to validate and update save button state
function updateSaveButtonState() {
const labels = Array.from(document.querySelectorAll('.label-input'))
.map(input => input.value.trim())
.filter(label => label !== '');
const provider = aiProviderSelect.value;
let hasValidApiKey = true; // Default to true for Ollama and other providers
if (provider === 'gemini') {
const validGeminiKeys = geminiKeys.filter(key => key && key.trim() !== '');
hasValidApiKey = validGeminiKeys.length > 0;
} else if (provider !== 'ollama') {
// Non-Ollama providers (OpenAI, Anthropic, Groq, Mistral) require API key
const apiKey = apiKeyInput.value.trim();
hasValidApiKey = !!apiKey;
}
// Ollama doesn't require an API key, so hasValidApiKey stays true
if (labels.length === 0 || !hasValidApiKey) {
saveButton.disabled = true;
saveButton.classList.add('disabled');
let missingItems = [];
if (labels.length === 0) missingItems.push('folders/labels');
if (!hasValidApiKey) missingItems.push('API key');
saveButton.title = `Please configure: ${missingItems.join(' and ')}`;
} else {
saveButton.disabled = false;
saveButton.classList.remove('disabled');
saveButton.title = '';
}
}
// Load saved settings
browser.storage.local.get(['labels', 'apiKey', 'geminiApiKeys', 'aiProvider', 'enableAi', 'geminiPaidPlan', 'ollamaUrl', 'ollamaModel', 'ollamaCustomModel', 'ollamaCpuOnly']).then(result => {
if (result.labels && result.labels.length > 0) {
result.labels.forEach(label => {
addLabelInput(label);
});
} else {
// Show instruction if no labels
labelsContainer.innerHTML = '<div class="instruction-message">No folders/labels configured. Click "Load Folders from Mail Account" above or add custom labels below.</div>';
}
// Load API keys
if (result.geminiApiKeys && result.geminiApiKeys.length > 0) {
// Multi-key mode
geminiKeys = result.geminiApiKeys;
geminiKeys.forEach((key, index) => {
addGeminiKeyInput(key, index);
});
} else if (result.apiKey) {
// Migrate from single key to multi-key
geminiKeys = [result.apiKey];
addGeminiKeyInput(result.apiKey, 0);
apiKeyInput.value = result.apiKey;
} else {
// No keys configured yet - add one empty field
addGeminiKeyInput('', 0);
}
// Load Ollama settings
if (result.ollamaUrl && ollamaUrlInput) {
ollamaUrlInput.value = result.ollamaUrl;
}
if (result.ollamaAuthToken && ollamaAuthTokenInput) {
ollamaAuthTokenInput.value = result.ollamaAuthToken;
}
if (result.ollamaModel && ollamaModelSelect) {
ollamaModelSelect.value = result.ollamaModel;
if (result.ollamaModel === 'custom' && result.ollamaCustomModel && ollamaCustomModelInput) {
ollamaCustomModelInput.value = result.ollamaCustomModel;
ollamaCustomModelInput.style.display = 'block';
}
}
if (ollamaCpuOnlyCheckbox) {
ollamaCpuOnlyCheckbox.checked = result.ollamaCpuOnly === true;
}
if (result.aiProvider) {
aiProviderSelect.value = result.aiProvider;
updateProviderInfo();
}
// Set enableAi to true by default if not set
document.getElementById('enable-ai').checked = result.enableAi !== false;
// Set gemini paid plan checkbox
geminiPaidCheckbox.checked = result.geminiPaidPlan === true;
updateSaveButtonState();
});
// Add input listeners for validation
apiKeyInput.addEventListener('input', updateSaveButtonState);
labelsContainer.addEventListener('input', updateSaveButtonState);
// Test API connection
testApiButton.addEventListener('click', async () => {
const apiKey = apiKeyInput.value.trim();
const provider = aiProviderSelect.value;
// Skip for Ollama as it has its own test button
if (provider === 'ollama') {
showApiTestResult('Please use the "Test Ollama Connection" button below', false);
return;
}
if (!apiKey) {
showApiTestResult('Please enter an API key', false);
return;
}
try {
showApiTestResult('Testing connection...', false);
let response;
if (provider === 'gemini') {
response = await fetch('https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': apiKey
},
body: JSON.stringify({
contents: [{ parts: [{ text: "Test" }] }],
generationConfig: { maxOutputTokens: 10 }
})
});
} else if (provider === 'openai') {
response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Test' }],
max_tokens: 10
})
});
} else if (provider === 'anthropic') {
response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01'
},
body: JSON.stringify({
model: 'claude-3-haiku-20240307',
messages: [{ role: 'user', content: 'Test' }],
max_tokens: 10
})
});
} else if (provider === 'groq') {
response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'llama-3.3-70b-versatile',
messages: [{ role: 'user', content: 'Test' }],
max_tokens: 10
})
});
} else if (provider === 'mistral') {
response = await fetch('https://api.mistral.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'mistral-small-latest',
messages: [{ role: 'user', content: 'Test' }],
max_tokens: 10
})
});
}
if (response.ok) {
showApiTestResult('✓ API connection successful!', true);
} else {
const error = await response.json();
showApiTestResult(`API Error: ${error.error?.message || error.message || 'Unknown error'}`, false);
}
} catch (error) {
showApiTestResult(`Connection Error: ${error.message}`, false);
}
});
// Load IMAP folders
loadImapFoldersButton.addEventListener('click', async () => {
folderLoadingIndicator.style.display = 'block';
folderSelection.style.display = 'none';
try {
const accounts = await browser.accounts.list();
const allFolders = [];
for (const account of accounts) {
const folders = await getAllFolders(account);
allFolders.push(...folders);
}
// Filter out system folders and duplicates
loadedFolders = [...new Set(allFolders
.filter(f => !['Inbox', 'Trash', 'Drafts', 'Sent', 'Spam', 'Junk', 'Templates', 'Outbox', 'Archives'].includes(f))
.map(f => f.replace(/^INBOX\./i, '').trim())
)].sort();
if (loadedFolders.length === 0) {
showMessage('No folders found. You can create custom folders instead.', false);
folderLoadingIndicator.style.display = 'none';
return;
}
// Show folder preview
folderCount.textContent = loadedFolders.length;
foldersPreview.innerHTML = loadedFolders
.slice(0, 10)
.map(f => `<div class="folder-preview-item">${f}</div>`)
.join('') + (loadedFolders.length > 10 ? `<div class="folder-preview-item">...and ${loadedFolders.length - 10} more</div>` : '');
folderSelection.style.display = 'block';
} catch (error) {
showMessage(`Error loading folders: ${error.message}`, false);
console.error('Error loading folders:', error);
} finally {
folderLoadingIndicator.style.display = 'none';
}
});
// Use IMAP folders
useImapFoldersButton.addEventListener('click', () => {
if (confirm(`This will replace any existing folders/labels with ${loadedFolders.length} folders from your mail account. Continue?`)) {
labelsContainer.innerHTML = '';
loadedFolders.forEach(folder => {
addLabelInput(folder);
});
folderSelection.style.display = 'none';
updateSaveButtonState();
showMessage(`Loaded ${loadedFolders.length} folders from your mail account. Don't forget to save!`, true);
}
});
// Use custom folders
useCustomFoldersButton.addEventListener('click', () => {
folderSelection.style.display = 'none';
showMessage('You can now add custom folders below', true);
});
// Helper function to recursively get all folders
async function getAllFolders(account) {
const folders = [];
async function processFolder(folder) {
if (folder.type !== 'inbox' && folder.type !== 'trash' && folder.type !== 'sent' &&
folder.type !== 'drafts' && folder.type !== 'junk' && folder.type !== 'templates' &&
folder.type !== 'outbox' && folder.type !== 'archives') {
folders.push(folder.name);
}
if (folder.subFolders) {
for (const subFolder of folder.subFolders) {
await processFolder(subFolder);
}
}
}
for (const folder of account.folders) {
await processFolder(folder);
}
return folders;
}
// Import categories/folders in bulk
importLabelsButton.addEventListener('click', () => {
const bulkText = bulkImportTextarea.value.trim();
const labels = bulkText.split('\n').map(l => l.trim()).filter(l => l !== '');
// Validation
if (labels.length === 0) {
showMessage('Please add at least one folder/label before importing. Enter labels one per line.', false);
return;
}
// Confirm if there are existing labels
const existingLabels = Array.from(document.querySelectorAll('.label-input'))
.map(input => input.value.trim())
.filter(label => label !== '');
if (existingLabels.length > 0) {
if (!confirm(`This will replace your ${existingLabels.length} existing folders/labels with ${labels.length} new ones. Continue?`)) {
return;
}
}
// Clear existing categories/folders
labelsContainer.innerHTML = '';
// Add each category/folder
labels.forEach(label => {
addLabelInput(label);
});
updateSaveButtonState();
showMessage(`Imported ${labels.length} categories/folders. Don't forget to save!`, true);
bulkImportTextarea.value = ''; // Clear the textarea
});
// Add new label input
// Show/hide custom model input based on selection
if (ollamaModelSelect) {
ollamaModelSelect.addEventListener('change', () => {
if (ollamaModelSelect.value === 'custom') {
ollamaCustomModelInput.style.display = 'block';
} else {
ollamaCustomModelInput.style.display = 'none';
}
});
}
// Test Ollama connection
if (testOllamaButton) {
testOllamaButton.addEventListener('click', async () => {
const ollamaUrl = ollamaUrlInput.value.trim() || 'http://localhost:11434';
let selectedModel = ollamaModelSelect.value;
if (selectedModel === 'custom') {
selectedModel = ollamaCustomModelInput.value.trim();
if (!selectedModel) {
ollamaTestResult.textContent = '⚠️ Please enter a custom model name first';
ollamaTestResult.className = 'api-test-result error';
return;
}
}
try {
ollamaTestResult.textContent = 'Testing connection and checking model...';
ollamaTestResult.className = 'api-test-result';
const testUrl = `${ollamaUrl}/api/tags`;
console.log('[Ollama Test] Connecting to:', testUrl);
const headers = {};
if (ollamaAuthTokenInput && ollamaAuthTokenInput.value.trim()) {
headers['Authorization'] = `Bearer ${ollamaAuthTokenInput.value.trim()}`;
}
const response = await fetch(testUrl, {
method: 'GET',
headers
});
console.log('[Ollama Test] Response status:', response.status);
if (response.ok) {
const data = await response.json();
console.log('[Ollama Test] Success:', data);
const installedModels = data.models && data.models.length > 0
? data.models.map(m => m.name)
: [];
if (installedModels.length === 0) {
ollamaTestResult.textContent = `⚠️ Ollama is running but no models installed. Enter a model name in "Download Model" and click "Download" to get started.`;
ollamaTestResult.className = 'api-test-result error';
} else {
// Extract base model name (before colon) for regex matching
const selectedBase = selectedModel.split(':')[0].toLowerCase();
const installedBases = installedModels.map(m => m.split(':')[0].toLowerCase());
const modelFound = installedBases.some(base => base === selectedBase);
if (modelFound) {
ollamaTestResult.textContent = `✓ Connected! Model "${selectedModel}" is installed and ready. Available: ${installedModels.join(', ')}`;
ollamaTestResult.className = 'api-test-result success';
} else {
ollamaTestResult.textContent = `✗ Model "${selectedModel}" not installed. Available models: ${installedModels.join(', ')}. Use "Download Model" to install it.`;
ollamaTestResult.className = 'api-test-result error';
}
}
} else {
const errorText = await response.text();
console.error('[Ollama Test] Error response:', errorText);
let errorMsg = 'Connection failed';
if (response.status === 403) {
errorMsg = 'Access denied (403). Check if Ollama is running and the URL is correct.';
} else if (response.status === 404) {
errorMsg = 'Ollama not found (404). Check the server URL.';
} else {
try {
const errorData = JSON.parse(errorText);
errorMsg = errorData.error || errorText;
} catch (e) {
errorMsg = errorText || `HTTP ${response.status}`;
}
}
ollamaTestResult.textContent = `✗ Error: ${errorMsg}`;
ollamaTestResult.className = 'api-test-result error';
}
} catch (error) {
console.error('[Ollama Test] Exception:', error);
ollamaTestResult.textContent = `✗ Connection failed: ${error.message}. Make sure Ollama is running (try: ollama serve)`;
ollamaTestResult.className = 'api-test-result error';
}
});
}
// Run comprehensive Ollama diagnostics
if (diagnoseOllamaButton) {
diagnoseOllamaButton.addEventListener('click', async () => {
const ollamaUrl = ollamaUrlInput.value.trim() || 'http://localhost:11434';
let diagnosticOutput = '🔍 OLLAMA DIAGNOSTICS\n' + '='.repeat(50) + '\n\n';
ollamaDiagnostics.style.display = 'block';
ollamaDiagnostics.className = 'diagnostics-result';
ollamaDiagnostics.textContent = diagnosticOutput + 'Running tests...\n';
try {
// Test 1: Check /api/tags endpoint
diagnosticOutput += '📋 Test 1: List Models Endpoint\n';
diagnosticOutput += ` URL: ${ollamaUrl}/api/tags\n`;
try {
const tagsResponse = await fetch(`${ollamaUrl}/api/tags`);
diagnosticOutput += ` Status: ${tagsResponse.status} ${tagsResponse.statusText}\n`;
if (tagsResponse.ok) {
const data = await tagsResponse.json();
diagnosticOutput += ` ✓ SUCCESS - Found ${data.models?.length || 0} models\n`;
if (data.models && data.models.length > 0) {
diagnosticOutput += ' Installed models: ' + data.models.map(m => m.name).join(', ') + '\n';
} else {
diagnosticOutput += ' ⚠️ No models installed\n';
}
} else {
diagnosticOutput += ` ✗ FAILED\n`;
}
} catch (error) {
diagnosticOutput += ` ✗ ERROR: ${error.message}\n`;
}