Repository navigation
Expand file tree
/
Copy pathoptions.js
More file actions
2027 lines (1804 loc) · 93.7 KB
/
Copy pathoptions.js
File metadata and controls
2027 lines (1804 loc) · 93.7 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 geminiResetNotificationsCheckbox = document.getElementById('gemini-reset-notifications');
const importLabelsButton = document.getElementById('import-labels');
const bulkImportGeminiKeysTextarea = document.getElementById('bulk-import-gemini-keys-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');
const geminiModelInput = document.getElementById('gemini-model');
const geminiModelCustomInput = document.getElementById('gemini-model-custom');
const geminiModelStatus = document.getElementById('gemini-model-status');
const loadGeminiModelsButton = document.getElementById('load-gemini-models');
const providerModelInput = document.getElementById('provider-model');
const providerModelHelp = document.getElementById('provider-model-help');
const batchChunkSizeInput = document.getElementById('batch-chunk-size');
// 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');
// LM Studio-specific elements
const lmStudioUrlInput = document.getElementById('lmstudio-url');
const lmStudioModelSelect = document.getElementById('lmstudio-model');
const lmStudioCustomModelInput = document.getElementById('lmstudio-custom-model');
const lmStudioAuthTokenInput = document.getElementById('lmstudio-auth-token');
const testLmStudioButton = document.getElementById('test-lmstudio');
const listLmStudioModelsButton = document.getElementById('list-lmstudio-models');
const lmStudioTestResult = document.getElementById('lmstudio-test-result');
const LMSTUDIO_CUSTOM_VALUE = '__custom__';
// 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>✓ Model: configurable below (default: Gemini 3.5 Flash-Lite)<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
},
lmstudio: {
name: 'LM Studio (Local LLM)',
signupUrl: 'https://lmstudio.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>✓ Uses LM Studio\'s native REST API (<code>/api/v1/chat</code>)<br>✓ Requires: <a href="https://lmstudio.ai/" target="_blank">LM Studio</a> installed with the local server enabled (default <code>http://localhost:1234</code>)<br>✓ Setup: In LM Studio open Settings → Local Model API, toggle the server on and load a chat model',
isFree: true
}
};
// Default model per provider (references may be overridden in settings)
// Note: Gemini 2.5 models are no longer available to NEW API keys (404),
// so new installs default to a current model.
const DEFAULT_GEMINI_MODEL = 'gemini-3.5-flash-lite';
const CUSTOM_MODEL_VALUE = '__custom__';
const GEMINI_MODEL_LABELS = {
'gemini-3.5-flash-lite': 'Gemini 3.5 Flash-Lite — recommended (fast & cheap)',
'gemini-3.8-flash': 'Gemini 3.8 Flash — latest, most capable',
'gemini-3.7-flash': 'Gemini 3.7 Flash',
'gemini-3.6-flash': 'Gemini 3.6 Flash',
'gemini-3.1-flash-lite': 'Gemini 3.1 Flash-Lite',
'gemini-2.5-flash': 'Gemini 2.5 Flash — existing users only',
'gemini-2.5-flash-lite': 'Gemini 2.5 Flash-Lite — existing users only'
};
const defaultProviderModels = {
openai: 'gpt-4o-mini',
anthropic: 'claude-3-haiku-20240307',
groq: 'openai/gpt-oss-120b',
mistral: 'mistral-small-latest'
};
// Human-friendly label for a Gemini model id
function geminiModelLabel(id) {
return GEMINI_MODEL_LABELS[id] || id;
}
// Escape text before injecting into option markup
function escapeOptionHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
// Rebuild the Gemini model dropdown and select the given value.
// When the value is not in the list (or is a known custom pick) the
// "Custom model..." option is selected and the text field is shown.
function setGeminiModelSelect(models, selected) {
if (!geminiModelInput) return;
const list = (models && models.length) ? models : Object.keys(GEMINI_MODEL_LABELS);
const customSelected = typeof selected === 'string' && selected !== '' && !list.includes(selected);
let html = list
.map(id => `<option value="${escapeOptionHtml(id)}">${escapeOptionHtml(geminiModelLabel(id))}</option>`)
.join('');
html += `<option value="${CUSTOM_MODEL_VALUE}">Custom model… (type your own)</option>`;
geminiModelInput.innerHTML = html;
if (customSelected) {
geminiModelInput.value = CUSTOM_MODEL_VALUE;
if (geminiModelCustomInput) {
geminiModelCustomInput.value = selected;
geminiModelCustomInput.style.display = 'block';
}
} else {
const fallback = list.includes(DEFAULT_GEMINI_MODEL) ? DEFAULT_GEMINI_MODEL : list[0];
geminiModelInput.value = selected || fallback;
if (geminiModelCustomInput) {
geminiModelCustomInput.value = '';
geminiModelCustomInput.style.display = 'none';
}
}
}
// Resolve the Gemini model to use, falling back to the default
function getSelectedGeminiModel() {
if (geminiModelInput && geminiModelInput.value === CUSTOM_MODEL_VALUE) {
const custom = (geminiModelCustomInput && geminiModelCustomInput.value.trim()) || '';
return custom || DEFAULT_GEMINI_MODEL;
}
const selected = (geminiModelInput && geminiModelInput.value) || '';
return selected || DEFAULT_GEMINI_MODEL;
}
// Toggle the custom model text field and track save-state changes
if (geminiModelInput) {
geminiModelInput.addEventListener('change', () => {
if (geminiModelInput.value === CUSTOM_MODEL_VALUE) {
if (geminiModelCustomInput) {
geminiModelCustomInput.style.display = 'block';
geminiModelCustomInput.focus();
}
} else if (geminiModelCustomInput) {
geminiModelCustomInput.style.display = 'none';
}
updateSaveButtonState();
});
}
if (geminiModelCustomInput) {
geminiModelCustomInput.addEventListener('input', updateSaveButtonState);
}
// 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 lmStudioSubsection = document.getElementById('lmstudio-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 geminiModelSubsection = document.getElementById('gemini-model-subsection');
const rateLimitWarning = document.getElementById('rate-limit-warning');
const isLocalProvider = provider === 'ollama' || provider === 'lmstudio';
// Show/hide rate limit warning (not for local providers)
if (rateLimitWarning) {
rateLimitWarning.style.display = isLocalProvider ? 'none' : 'block';
}
// Show/hide provider-specific elements
if (provider === 'gemini') {
geminiPaidContainer.style.display = 'block';
if (geminiMultiKeysSubsection) geminiMultiKeysSubsection.style.display = 'block';
if (geminiUsageSubsection) geminiUsageSubsection.style.display = 'block';
if (geminiModelSubsection) geminiModelSubsection.style.display = 'block';
if (apiKeySubsection) apiKeySubsection.style.display = 'none';
if (ollamaSubsection) ollamaSubsection.style.display = 'none';
if (lmStudioSubsection) lmStudioSubsection.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 (geminiModelSubsection) geminiModelSubsection.style.display = 'none';
if (apiKeySubsection) apiKeySubsection.style.display = 'none';
if (ollamaSubsection) ollamaSubsection.style.display = 'block';
if (lmStudioSubsection) lmStudioSubsection.style.display = 'none';
} else if (provider === 'lmstudio') {
// Show LM Studio settings, hide API key and Gemini sections
geminiPaidContainer.style.display = 'none';
if (geminiMultiKeysSubsection) geminiMultiKeysSubsection.style.display = 'none';
if (geminiUsageSubsection) geminiUsageSubsection.style.display = 'none';
if (geminiModelSubsection) geminiModelSubsection.style.display = 'none';
if (apiKeySubsection) apiKeySubsection.style.display = 'none';
if (ollamaSubsection) ollamaSubsection.style.display = 'none';
if (lmStudioSubsection) lmStudioSubsection.style.display = 'block';
} else {
geminiPaidContainer.style.display = 'none';
if (geminiMultiKeysSubsection) geminiMultiKeysSubsection.style.display = 'none';
if (geminiUsageSubsection) geminiUsageSubsection.style.display = 'none';
if (geminiModelSubsection) geminiModelSubsection.style.display = 'none';
if (apiKeySubsection) apiKeySubsection.style.display = 'block';
if (ollamaSubsection) ollamaSubsection.style.display = 'none';
if (lmStudioSubsection) lmStudioSubsection.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 (!isLocalProvider) {
apiKeyInput.placeholder = `Enter your ${config.name} API key`;
}
// Show the default model / optional override for single-key providers
if (providerModelInput) {
const defaultModel = defaultProviderModels[provider];
if (defaultModel) {
providerModelInput.placeholder = `Default: ${defaultModel}`;
if (providerModelHelp) {
providerModelHelp.textContent = `Leave blank to use the default model (${defaultModel}).`;
}
} else {
providerModelInput.placeholder = 'Leave blank to use the default model';
if (providerModelHelp) {
providerModelHelp.textContent = '';
}
}
}
}
// Update Gemini usage display
let geminiCountdownTimer = null;
let geminiUsageRefreshTimer = null;
async function updateGeminiUsageDisplay() {
await browser.runtime.sendMessage({ action: 'refreshGeminiUsage' });
const data = await browser.storage.local.get(['geminiRateLimits', 'currentGeminiKeyIndex', 'geminiApiKeys', 'geminiRateLimit']);
const currentIndex = data.currentGeminiKeyIndex || 0;
const keys = geminiKeys.length ? geminiKeys : (data.geminiApiKeys || []);
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 = Array.isArray(data.geminiRateLimits) ? 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 = Array.isArray(data.geminiRateLimits) ? data.geminiRateLimits : [];
updateSingleKeyUsageDisplay(rateLimits[0] || { requests: [], dailyCount: 0, dailyResetTime: null });
} else {
// Legacy single-key mode (backward compatibility)
document.getElementById('single-key-usage').style.display = 'block';
document.getElementById('multi-key-usage').style.display = 'none';
const storedLegacy = data.geminiRateLimit;
const rateLimit = (storedLegacy && typeof storedLegacy === 'object')
? storedLegacy
: { requests: [], dailyCount: 0, dailyResetTime: null };
updateSingleKeyUsageDisplay(rateLimit);
}
if (geminiCountdownTimer) clearInterval(geminiCountdownTimer);
geminiCountdownTimer = setInterval(() => {
if (keys.length > 1) {
const limits = Array.isArray(data.geminiRateLimits) ? data.geminiRateLimits : [];
updateMultiKeyUsageDisplay(keys, limits, currentIndex);
} else if (keys.length === 1) {
const limits = Array.isArray(data.geminiRateLimits) ? data.geminiRateLimits : [];
updateSingleKeyUsageDisplay(limits[0] || { requests: [], dailyCount: 0, dailyResetTime: null });
} else {
updateSingleKeyUsageDisplay(data.geminiRateLimit || { requests: [], dailyCount: 0, dailyResetTime: null });
}
if (Date.now() >= getEarliestGeminiResetTime(data, keys.length)) {
updateGeminiUsageDisplay();
}
}, 1000);
if (!geminiUsageRefreshTimer) {
geminiUsageRefreshTimer = setInterval(() => {
if (aiProviderSelect.value === 'gemini') updateGeminiUsageDisplay();
}, 10000);
}
}
function getEarliestGeminiResetTime(data, keyCount) {
const limits = keyCount > 0
? (Array.isArray(data.geminiRateLimits) ? data.geminiRateLimits : [])
: [data.geminiRateLimit || {}];
const deadlines = limits.map(limit => limit && limit.dailyResetTime).filter(time => typeof time === 'number');
return deadlines.length ? Math.min(...deadlines) : Infinity;
}
function formatGeminiCountdown(resetTime) {
const remaining = Math.max(0, Math.ceil((resetTime - Date.now()) / 1000));
const hours = Math.floor(remaining / 3600);
const minutes = Math.floor((remaining % 3600) / 60);
const seconds = remaining % 60;
return `In ${hours}h ${minutes}m ${seconds}s`;
}
// 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.dailyCount >= 20 && typeof rateLimit.dailyResetTime === 'number' && rateLimit.dailyResetTime > now) {
document.getElementById('gemini-reset-time').textContent = formatGeminiCountdown(rateLimit.dailyResetTime);
} else if (rateLimit.dailyCount >= 20) {
document.getElementById('gemini-reset-time').textContent = 'Resetting…';
browser.runtime.sendMessage({ action: 'refreshGeminiUsage' }).then(() => updateGeminiUsageDisplay());
} else {
document.getElementById('gemini-reset-time').textContent = 'Starts when limit is reached';
}
// 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.style.display = '';
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.style.display = '';
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: null };
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.dailyCount >= 20 && typeof rateLimit.dailyResetTime === 'number' && rateLimit.dailyResetTime > now) {
resetText = formatGeminiCountdown(rateLimit.dailyResetTime);
} else if (rateLimit.dailyCount >= 20) {
resetText = 'Resetting…';
} else {
resetText = 'Starts at limit';
}
// 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 visibilityButton = document.createElement('button');
visibilityButton.type = 'button';
visibilityButton.className = 'button gemini-key-visibility';
visibilityButton.textContent = 'Show';
visibilityButton.setAttribute('aria-label', `Show API key ${index + 1}`);
visibilityButton.addEventListener('click', () => {
const reveal = input.type === 'password';
input.type = reveal ? 'text' : 'password';
visibilityButton.textContent = reveal ? 'Hide' : 'Show';
visibilityButton.setAttribute('aria-label', `${reveal ? 'Hide' : 'Show'} API key ${index + 1}`);
});
const testButton = document.createElement('button');
testButton.className = 'button';
testButton.textContent = 'Test';
testButton.addEventListener('click', () => {
const keyValue = input.value.trim();
if (!keyValue) {
setKeyTestStatus(statusSpan, '⚠️ Enter key first', 'key-test-result error', 'Enter an API key before testing.');
return;
}
// Check for duplicates before testing
const isDuplicate = geminiKeys.some((key, i) => i !== index && key.trim() === keyValue);
if (isDuplicate) {
setKeyTestStatus(statusSpan, '⚠️ Duplicate key', 'key-test-result error', '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(visibilityButton);
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();
browser.storage.local.get(['geminiRateLimits', 'currentGeminiKeyIndex']).then(data => {
const rateLimits = Array.isArray(data.geminiRateLimits) ? data.geminiRateLimits.slice() : [];
rateLimits.splice(index, 1);
const currentIndex = data.currentGeminiKeyIndex || 0;
const nextIndex = Math.max(0, Math.min(currentIndex > index ? currentIndex - 1 : currentIndex, geminiKeys.length - 1));
return browser.storage.local.set({
geminiApiKeys: geminiKeys.slice(),
geminiRateLimits: rateLimits,
currentGeminiKeyIndex: nextIndex
});
}).then(() => updateGeminiUsageDisplay()).catch(error => {
console.error('Could not synchronize removed Gemini key usage:', error);
});
}
}
// Refresh Gemini keys list display
function refreshGeminiKeysList() {
geminiKeysList.innerHTML = '';
geminiKeys.forEach((key, index) => {
addGeminiKeyInput(key, index);
});
}
// Update a key test badge (text, color and hover tooltip) in one place so
// the tooltip always reflects the most recent test result.
function setKeyTestStatus(statusSpan, text, className, title = '') {
statusSpan.textContent = text;
statusSpan.className = className;
statusSpan.title = title;
}
// Test individual Gemini key
async function testGeminiKey(apiKey, index, keyItemElement) {
const statusSpan = keyItemElement.querySelector('.key-test-result');
if (!apiKey) {
setKeyTestStatus(statusSpan, '⚠️ Enter key first', 'key-test-result error', 'Enter an API key before testing.');
return;
}
try {
setKeyTestStatus(statusSpan, 'Testing...', 'key-test-result testing');
const model = getSelectedGeminiModel();
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
contents: [{ parts: [{ text: "Test" }] }],
generationConfig: { maxOutputTokens: 10 }
})
});
if (response.ok) {
setKeyTestStatus(statusSpan, '✓ Valid', 'key-test-result success', `API key is valid for model "${model}".`);
} else if (response.status === 429) {
setKeyTestStatus(statusSpan, '⚠️ Limit reached', 'key-test-result error', '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) {
setKeyTestStatus(statusSpan, '✗ Invalid key', 'key-test-result error', 'API key is invalid or expired. Check your key in Google AI Studio.');
console.error(`Key #${index + 1} test failed: ${response.status}`);
} else {
// Try to show the API's own error message (e.g. model not found)
let detail = `✗ Failed (${response.status})`;
try {
const errBody = await response.json();
const apiMsg = errBody.error?.message;
if (apiMsg) detail = `✗ ${apiMsg}`;
} catch (e) { /* ignore parse errors */ }
setKeyTestStatus(statusSpan, detail, 'key-test-result error', detail);
console.error(`Key #${index + 1} test failed:`, response.status, detail);
}
} catch (error) {
const detail = `Connection error: ${error.message}`;
setKeyTestStatus(statusSpan, '✗ Error', 'key-test-result error', detail);
console.error(`Key #${index + 1} test error:`, error);
}
}
// Initialize provider info
updateProviderInfo();
aiProviderSelect.addEventListener('change', updateProviderInfo);
// Add Gemini key button
addGeminiKeyButton.addEventListener('click', () => {
addGeminiKeyInput('');
});
const testAllGeminiKeysButton = document.getElementById('test-all-gemini-keys');
testAllGeminiKeysButton.addEventListener('click', async () => {
const rows = Array.from(geminiKeysList.querySelectorAll('.gemini-key-item'));
const configured = rows.map((row, index) => ({
row,
index,
key: row.querySelector('input').value.trim()
})).filter(item => item.key);
if (!configured.length) {
showMessage('Add at least one Gemini API key before testing.', false);
return;
}
testAllGeminiKeysButton.disabled = true;
testAllGeminiKeysButton.textContent = 'Testing keys...';
try {
for (const item of configured) {
await testGeminiKey(item.key, item.index, item.row);
}
} finally {
testAllGeminiKeysButton.disabled = false;
testAllGeminiKeysButton.textContent = 'Test All Keys';
}
});
// Bulk import Gemini API keys button
const bulkImportKeysButton = document.getElementById('bulk-import-keys-button');
if (bulkImportKeysButton) {
bulkImportKeysButton.addEventListener('click', () => {
const bulkText = bulkImportGeminiKeysTextarea.value.trim();
const keys = bulkText.split('\n').map(k => k.trim()).filter(k => k !== '');
// Validation
if (keys.length === 0) {
showMessage('Please add at least one Gemini API key. Enter keys one per line.', false);
return;
}
// Check for duplicate keys
const uniqueKeys = new Set(keys.map(key => key.trim().toLowerCase()));
if (uniqueKeys.size !== keys.length) {
showMessage('⚠️ Duplicate API keys detected! Each key must be unique. Please remove duplicates before importing.', false);
return;
}
// Update Gemini keys
geminiKeys = keys;
refreshGeminiKeysList();
// Save settings automatically
const provider = aiProviderSelect.value;
if (provider === 'gemini') {
const apiKey = geminiKeys.find(key => key && key.trim() !== '');
if (apiKey) {
browser.storage.local.set({
geminiApiKeys: geminiKeys,
currentGeminiKeyIndex: 0,
aiProvider: provider
}).then(() => {
showMessage(`✓ Imported ${keys.length} Gemini API keys successfully!`, true);
updateSaveButtonState();
}).catch(error => {
showMessage('Error saving keys: ' + error, false);
});
}
}
});
}
// Load available Gemini models for the entered API key
if (loadGeminiModelsButton) {
loadGeminiModelsButton.addEventListener('click', async () => {
const apiKey = (geminiKeys.find(key => key && key.trim() !== '') || '').trim();
if (!apiKey) {
geminiModelStatus.textContent = '⚠️ Add at least one Gemini API key first.';
geminiModelStatus.className = 'api-test-result error';
return;
}
geminiModelStatus.textContent = 'Loading models...';
geminiModelStatus.className = 'api-test-result';
try {
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(apiKey)}`);
if (!response.ok) {
let detail = `HTTP ${response.status}`;
try {
const errBody = await response.json();
detail = errBody.error?.message || detail;
} catch (e) { /* ignore */ }
throw new Error(detail);
}
const data = await response.json();
const models = (data.models || [])
.filter(m => (m.supportedGenerationMethods || []).includes('generateContent'))
.map(m => m.name.replace(/^models\//, ''));
if (models.length === 0) {
geminiModelStatus.textContent = 'No models supporting generateContent were returned for this key.';
geminiModelStatus.className = 'api-test-result error';
return;
}
const wasCustom = geminiModelInput && geminiModelInput.value === CUSTOM_MODEL_VALUE;
const current = getSelectedGeminiModel();
// If the current value isn't available for this key, offer a sensible default
// (but keep a user-typed custom model as-is).
let chosen = current;
if (!wasCustom && !models.includes(current)) {
chosen = models.find(m => m === DEFAULT_GEMINI_MODEL)
|| models.find(m => m.includes('flash-lite'))
|| models.find(m => m.includes('flash'))
|| models[0];
}
setGeminiModelSelect(models, chosen);
geminiModelStatus.textContent = `✓ Found ${models.length} available model(s). Choose one above.`;
geminiModelStatus.className = 'api-test-result success';
} catch (error) {
geminiModelStatus.textContent = `✗ Could not load models: ${error.message}`;
geminiModelStatus.className = 'api-test-result error';
}
});
}
// 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.')) {
const makeFresh = () => ({ requests: [], dailyCount: 0, pendingCount: 0, dailyResetTime: null });
const data = await browser.storage.local.get(['geminiRateLimits', 'geminiApiKeys']);
const keys = data.geminiApiKeys || geminiKeys || [];
const updates = {};
// The live counter is stored per-key in geminiRateLimits (array).
if (keys.length > 0) {
const rateLimits = (data.geminiRateLimits && data.geminiRateLimits.length)
? data.geminiRateLimits.slice()
: keys.map(() => makeFresh());
for (let i = 0; i < keys.length; i++) {
rateLimits[i] = makeFresh();
}
updates.geminiRateLimits = rateLimits;
}
// Keep the legacy single-key field in sync for older installs
updates.geminiRateLimit = makeFresh();
await browser.storage.local.set(updates);
await updateGeminiUsageDisplay();
const usageMessage = document.getElementById('usage-message');
usageMessage.className = 'usage-message info';
usageMessage.style.display = '';
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.style.display = '';
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' && provider !== 'lmstudio') {
// Cloud providers (OpenAI, Anthropic, Groq, Mistral) require an API key
const apiKey = apiKeyInput.value.trim();
hasValidApiKey = !!apiKey;
}
// Ollama and LM Studio are local providers and don'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 = '';
}
}
// Read and clamp the parallel batch size (1–20, default 5)
function getBatchChunkSize() {
const raw = batchChunkSizeInput ? parseInt(batchChunkSizeInput.value, 10) : NaN;
if (isNaN(raw)) return 5;
return Math.min(20, Math.max(1, raw));
}
// Load saved settings
browser.storage.local.get(['labels', 'apiKey', 'geminiApiKeys', 'aiProvider', 'enableAi', 'completionSoundEnabled', 'geminiPaidPlan', 'geminiResetNotifications', 'geminiModel', 'providerModel', 'ollamaUrl', 'ollamaModel', 'ollamaCustomModel', 'ollamaCpuOnly', 'ollamaAuthToken', 'lmstudioUrl', 'lmstudioModel', 'lmstudioCustomModel', 'lmstudioAuthToken', 'batchChunkSize']).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);
}