Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
2095 lines (1857 loc) · 85.9 KB
/
Copy pathbackground.js
File metadata and controls
2095 lines (1857 loc) · 85.9 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
// Listen for messages from the options page
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'refreshGeminiUsage') {
refreshGeminiUsageCounters().then(sendResponse);
return true;
} else if (message.action === "applyLabels") {
applyLabelsToMessages(message.messages, message.label);
} else if (message.action === "analyzeEmail") {
analyzeEmailContent(message.emailContent).then(label => {
sendResponse({ label: label });
});
return true; // Required for async response
} else if (message.action === 'batchCancel') {
if (batchState.running) {
batchState.cancelRequested = true;
sendResponse({ ok: true, cancelling: true });
} else {
sendResponse({ ok: true, cancelling: false });
}
} else if (message.action === 'batchSync') {
if (batchState.running && batchState.snapshot) {
sendResponse(Object.assign({ running: true }, batchState.snapshot));
} else if (batchState.lastSnapshot) {
sendResponse(Object.assign({ running: false }, batchState.lastSnapshot));
} else {
sendResponse(null);
}
} else if (message.action === 'batchRetry') {
handleBatchRetry(message).then(sendResponse);
return true; // Required for async response
} else if (message.action === 'startOllamaPull') {
(async () => {
try {
const { ollamaUrl, model, headers } = message;
const { response } = await callOllamaViaTab(ollamaUrl, {
action: 'ollamaFetch',
fetchAction: 'pull',
model,
headers
});
sendResponse(response || { ok: true });
} catch (e) {
sendResponse({ ok: false, error: e.message });
}
})();
return true;
}
});
const GEMINI_USAGE_REFRESH_ALARM = 'autosort-gemini-usage-refresh';
// Reconcile counters against their locally stored reset deadlines. Google does
// not expose actual per-key quota through this extension's API permissions.
async function refreshGeminiUsageCounters() {
return withGeminiRateLimitLock(async () => {
const data = await browser.storage.local.get([
'geminiApiKeys', 'geminiRateLimits', 'geminiRateLimit'
]);
const now = Date.now();
const makeFresh = () => ({
requests: [],
dailyCount: 0,
pendingCount: 0,
dailyResetTime: null
});
let changed = false;
let resetKeys = 0;
if (Array.isArray(data.geminiApiKeys) && data.geminiApiKeys.length) {
const existing = Array.isArray(data.geminiRateLimits) ? data.geminiRateLimits : [];
const limits = data.geminiApiKeys.map((_, index) => {
const stored = existing[index];
if (!stored || typeof stored !== 'object') {
changed = true;
return makeFresh();
}
// Older versions started the countdown on first use. The
// deadline belongs only to keys that have actually hit cap.
if ((stored.dailyCount || 0) < 20 && stored.dailyResetTime != null) {
changed = true;
return Object.assign({}, stored, { dailyResetTime: null });
}
if (typeof stored.dailyResetTime === 'number' && now >= stored.dailyResetTime) {
changed = true;
if ((stored.dailyCount || 0) > 0) resetKeys++;
return makeFresh();
}
if ((stored.dailyCount || 0) > 20) {
changed = true;
return Object.assign({}, stored, {
dailyCount: 20,
dailyResetTime: typeof stored.dailyResetTime === 'number'
? stored.dailyResetTime
: now + (24 * 60 * 60 * 1000)
});
}
if ((stored.dailyCount || 0) === 20 && typeof stored.dailyResetTime !== 'number') {
changed = true;
return Object.assign({}, stored, { dailyResetTime: now + (24 * 60 * 60 * 1000) });
}
return stored;
});
if (existing.length !== limits.length) changed = true;
if (changed) await browser.storage.local.set({ geminiRateLimits: limits });
} else if (data.geminiRateLimit && typeof data.geminiRateLimit === 'object') {
const legacy = data.geminiRateLimit;
if ((legacy.dailyCount || 0) < 20 && legacy.dailyResetTime != null) {
await browser.storage.local.set({
geminiRateLimit: Object.assign({}, legacy, { dailyResetTime: null })
});
changed = true;
} else if (typeof legacy.dailyResetTime === 'number' && now >= legacy.dailyResetTime) {
await browser.storage.local.set({ geminiRateLimit: makeFresh() });
changed = true;
if ((legacy.dailyCount || 0) > 0) resetKeys = 1;
} else if ((legacy.dailyCount || 0) > 20) {
await browser.storage.local.set({
geminiRateLimit: Object.assign({}, legacy, {
dailyCount: 20,
dailyResetTime: typeof legacy.dailyResetTime === 'number'
? legacy.dailyResetTime
: now + (24 * 60 * 60 * 1000)
})
});
changed = true;
} else if ((legacy.dailyCount || 0) === 20 && typeof legacy.dailyResetTime !== 'number') {
await browser.storage.local.set({
geminiRateLimit: Object.assign({}, legacy, { dailyResetTime: now + (24 * 60 * 60 * 1000) })
});
changed = true;
}
}
if (resetKeys > 0) {
const settings = await browser.storage.local.get('geminiResetNotifications');
if (settings.geminiResetNotifications) {
const keyLabel = resetKeys === 1 ? 'A used Gemini key is ready again.' : `${resetKeys} used Gemini keys are ready again.`;
await showNotification('AutoSort+ quota reset', `${keyLabel} You can run email sorting again.`);
}
}
return { ok: true, changed };
});
}
function scheduleGeminiUsageRefresh() {
if (!browser.alarms) return;
// Alarms are a fallback; the persistent MV2 background runs the 10s loop.
browser.alarms.create(GEMINI_USAGE_REFRESH_ALARM, { periodInMinutes: 1 });
}
if (browser.alarms) {
browser.alarms.onAlarm.addListener(alarm => {
if (alarm.name === GEMINI_USAGE_REFRESH_ALARM) refreshGeminiUsageCounters();
});
if (browser.runtime.onStartup) browser.runtime.onStartup.addListener(scheduleGeminiUsageRefresh);
if (browser.runtime.onInstalled) browser.runtime.onInstalled.addListener(scheduleGeminiUsageRefresh);
scheduleGeminiUsageRefresh();
}
setInterval(() => {
refreshGeminiUsageCounters().catch(error => {
console.warn('[AutoSort+] Automatic Gemini usage refresh failed:', error.message);
});
}, 10000);
// Click handler for browser action icon - opens settings
browser.browserAction.onClicked.addListener(() => {
browser.runtime.openOptionsPage();
});
// Ollama handling using tab injection (runs fetch in browser context)
async function ollamaChatViaTab(ollamaUrl, model, prompt, authToken) {
// Open a hidden tab at localhost to make the fetch (browser context, not restricted)
const tab = await browser.tabs.create({ url: ollamaUrl, active: false });
// Wait for tab to load
await new Promise(resolve => setTimeout(resolve, 500));
try {
// Build the request headers
const headers = { 'Content-Type': 'application/json' };
if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
// Inject code to make the fetch and store result
const scriptCode = `
(async () => {
try {
const headers = ${JSON.stringify(headers)};
const response = await fetch(window.location.origin + '/api/chat', {
method: 'POST',
headers,
body: JSON.stringify({
model: ${JSON.stringify(model)},
messages: [{ role: 'user', content: ${JSON.stringify(prompt)} }],
stream: false
})
});
if (!response.ok) {
throw new Error('HTTP ' + response.status + ': ' + response.statusText);
}
const data = await response.json();
window.__ollama_result = { ok: true, data };
} catch (error) {
window.__ollama_result = { ok: false, error: error.message };
}
})();
`;
await browser.tabs.executeScript(tab.id, { code: scriptCode });
// Wait for result (with polling to be safe)
let result = null;
for (let i = 0; i < 60; i++) { // 30 seconds max
await new Promise(resolve => setTimeout(resolve, 500));
try {
const results = await browser.tabs.executeScript(tab.id, {
code: 'window.__ollama_result || null'
});
if (results && results[0]) {
result = results[0];
break;
}
} catch (e) {
// Tab might be closing
break;
}
}
if (!result) {
throw new Error('Ollama request timed out (30s) - no response from API');
}
if (!result.ok) {
throw new Error(result.error || 'Ollama API error');
}
return result.data;
} finally {
// Close the tab
try { await browser.tabs.remove(tab.id); } catch (e) {}
}
}
// Normalize the LM Studio server URL to its root. Users often paste the
// OpenAI-compatible base (http://host:1234/v1) or the native base
// (http://host:1234/api/v1); we always append /api/v1/* ourselves, so strip
// those suffixes to avoid paths like /v1/api/v1/models.
function normalizeLmStudioBaseUrl(rawUrl) {
let url = (rawUrl || 'http://localhost:1234').trim().replace(/\/+$/, '');
url = url.replace(/\/(?:api\/v[01]|v1)$/i, '');
return url.replace(/\/+$/, '') || 'http://localhost:1234';
}
// LM Studio replies HTTP 200 with a JSON `error` body for unknown endpoints,
// so an OK status alone is not enough to know the request succeeded.
function lmStudioErrorFromBody(data) {
if (!data || !data.error) return null;
const err = data.error;
if (typeof err === 'string') return err;
return err.message || JSON.stringify(err);
}
// Throw a helpful error if LM Studio returned a 200-with-error body.
function assertLmStudioResponse(data) {
const errMsg = lmStudioErrorFromBody(data);
if (errMsg) {
const hint = /unexpected endpoint|not found/i.test(errMsg)
? ' Check the LM Studio URL in settings - use the server root (e.g. http://localhost:1234), not the /v1 OpenAI-compatible base.'
: '';
throw new Error(`LM Studio error: ${errMsg}.${hint}`);
}
return data;
}
// LM Studio native REST API chat (POST /api/v1/chat).
// Tries a direct fetch first (host permission + LM Studio's default CORS),
// then falls back to tab injection for setups where the background fetch is blocked.
async function lmStudioChat(lmUrl, model, prompt, authToken) {
const base = normalizeLmStudioBaseUrl(lmUrl);
const headers = { 'Content-Type': 'application/json' };
if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
const body = {
model,
input: prompt,
system_prompt: 'You are an email classification assistant. Respond with only the label.',
max_output_tokens: 512,
temperature: 0.2,
stream: false
};
let response;
try {
response = await fetch(`${base}/api/v1/chat`, {
method: 'POST',
headers,
body: JSON.stringify(body)
});
} catch (netErr) {
console.warn('[LM Studio] Direct fetch failed, falling back to tab injection:', netErr.message);
const fallbackData = await localChatViaTab(base, '/api/v1/chat', body, authToken);
return assertLmStudioResponse(fallbackData);
}
if (!response.ok) {
const text = await response.text().catch(() => '');
let detail = text;
try { detail = JSON.parse(text).error || text; } catch (e) { /* keep raw text */ }
throw new Error(`LM Studio HTTP ${response.status}: ${(detail || '').substring(0, 200)}`);
}
// LM Studio returns HTTP 200 even for unknown endpoints - detect that here.
return assertLmStudioResponse(await response.json());
}
// Generic helper: POST JSON from a hidden tab at the local server's origin
// (browser context) to avoid background-script network restrictions.
async function localChatViaTab(baseUrl, path, body, authToken) {
const tab = await browser.tabs.create({ url: baseUrl, active: false });
await new Promise(resolve => setTimeout(resolve, 800));
try {
const headers = { 'Content-Type': 'application/json' };
if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
const scriptCode = `
(async () => {
try {
const response = await fetch(${JSON.stringify(baseUrl + path)}, {
method: 'POST',
headers: ${JSON.stringify(headers)},
body: ${JSON.stringify(JSON.stringify(body))}
});
const text = await response.text();
window.__local_result = { ok: response.ok, status: response.status, text: text };
} catch (error) {
window.__local_result = { ok: false, error: error.message };
}
})();
`;
await browser.tabs.executeScript(tab.id, { code: scriptCode });
let result = null;
for (let i = 0; i < 60; i++) { // 30 seconds max
await new Promise(resolve => setTimeout(resolve, 500));
try {
const results = await browser.tabs.executeScript(tab.id, {
code: 'window.__local_result || null'
});
if (results && results[0]) {
result = results[0];
break;
}
} catch (e) {
break;
}
}
if (!result) {
throw new Error('LM Studio request timed out (30s) - no response from API');
}
if (result.error) {
throw new Error(result.error);
}
if (!result.ok) {
throw new Error(`LM Studio HTTP ${result.status}: ${(result.text || '').substring(0, 200)}`);
}
return JSON.parse(result.text);
} finally {
try { await browser.tabs.remove(tab.id); } catch (e) {}
}
}
async function callOllamaViaTab(ollamaUrl, payload) {
// Deprecated function kept for backward compatibility
// Now routes to direct API call via fetch
const { fetchAction, model, prompt, headers } = payload;
if (fetchAction === 'chat') {
// For direct chat, we make a simple fetch call
const ollamaHeaders = Object.assign({}, headers, { 'Content-Type': 'application/json' });
try {
const res = await fetch(`${ollamaUrl}/api/chat`, {
method: 'POST',
headers: ollamaHeaders,
body: JSON.stringify({
model,
messages: [{ role: 'user', content: prompt }],
stream: false
})
});
if (!res.ok) {
return {
correlationId: '',
response: { ok: false, error: `HTTP ${res.status}: ${res.statusText}` }
};
}
const data = await res.json();
return { correlationId: '', response: { ok: true, data } };
} catch (err) {
return {
correlationId: '',
response: { ok: false, error: err.message }
};
}
} else if (fetchAction === 'pull') {
// For pull operations
const ollamaHeaders = Object.assign({}, headers, { 'Content-Type': 'application/json' });
try {
const res = await fetch(`${ollamaUrl}/api/pull`, {
method: 'POST',
headers: ollamaHeaders,
body: JSON.stringify({ name: model, stream: true })
});
const text = await res.text();
return { correlationId: '', response: { ok: true, data: text } };
} catch (err) {
return { correlationId: '', response: { ok: false, error: err.message } };
}
}
}
// Serializes all Gemini rate-limit read/modify/write operations. Batch
// processing fires several requests concurrently, so without this lock the
// per-key counters would repeatedly read the same value and clobber each
// other's increments (e.g. 10 emails only adding +1).
let geminiRateLimitQueue = Promise.resolve();
function withGeminiRateLimitLock(task) {
const run = geminiRateLimitQueue.then(task, task);
geminiRateLimitQueue = run.then(() => {}, () => {});
return run;
}
// Gemini rate limiting functions (free tier: 5/min, 20/day per key)
async function checkGeminiRateLimit() {
return withGeminiRateLimitLock(() => checkGeminiRateLimitInner());
}
async function checkGeminiRateLimitInner() {
const now = Date.now();
const data = await browser.storage.local.get([
'geminiApiKeys',
'geminiRateLimits',
'currentGeminiKeyIndex',
'geminiPaidPlan',
'geminiRateLimit' // Legacy single-key support
]);
// Handle paid plan - no limits
if (data.geminiPaidPlan) {
return { allowed: true, waitTime: 0 };
}
// Multi-key mode
if (data.geminiApiKeys && data.geminiApiKeys.length > 0) {
const keys = data.geminiApiKeys;
const rawRateLimits = Array.isArray(data.geminiRateLimits) ? data.geminiRateLimits : [];
const rateLimits = keys.map((_, i) => {
const rl = rawRateLimits[i];
if (rl && typeof rl === 'object') {
return {
requests: Array.isArray(rl.requests) ? rl.requests : [],
dailyCount: typeof rl.dailyCount === 'number' ? rl.dailyCount : 0,
pendingCount: Math.max(0, Number(rl.pendingCount) || 0),
dailyResetTime: typeof rl.dailyCount === 'number' && rl.dailyCount >= 20 &&
typeof rl.dailyResetTime === 'number' ? rl.dailyResetTime : null
};
}
return { requests: [], dailyCount: 0, pendingCount: 0, dailyResetTime: null };
});
let currentIndex = (data.currentGeminiKeyIndex || 0) % keys.length;
// Try to find an available key
const startIndex = currentIndex;
let attempts = 0;
while (attempts < keys.length) {
const rateLimit = rateLimits[currentIndex];
// Reset daily count if it's a new day
if (typeof rateLimit.dailyResetTime === 'number' && now >= rateLimit.dailyResetTime) {
rateLimit.dailyCount = 0;
rateLimit.dailyResetTime = null;
rateLimit.requests = [];
}
// Remove requests older than 1 minute
const oneMinuteAgo = now - 60000;
rateLimit.requests = rateLimit.requests.filter(time => time > oneMinuteAgo);
// Check if this key is available
if (rateLimit.dailyCount + rateLimit.pendingCount < 20) {
// Reserve a daily slot and a spaced request time atomically,
// before another parallel batch item can claim the same slot.
const lastRequest = rateLimit.requests.length ? Math.max(...rateLimit.requests) : 0;
const scheduledAt = Math.max(now, lastRequest + 12000);
const waitTime = Math.ceil((scheduledAt - now) / 1000);
rateLimit.requests.push(scheduledAt);
rateLimit.pendingCount += 1;
await browser.storage.local.set({
currentGeminiKeyIndex: currentIndex,
geminiRateLimits: rateLimits
});
return {
allowed: true,
waitTime,
keyIndex: currentIndex,
reserved: true
};
}
// This key has reached its limit, try next one
currentIndex = (currentIndex + 1) % keys.length;
attempts++;
}
// All keys have reached their limits
const pendingRequests = rateLimits.some(limit => limit.dailyCount < 20 && limit.pendingCount > 0);
return {
allowed: false,
pending: pendingRequests,
waitTime: pendingRequests ? 1 : 0,
message: pendingRequests
? 'Gemini requests are already using the remaining daily slots. Waiting for one to finish.'
: `All ${keys.length} Gemini API keys have reached their daily limit (20/day each). Please wait for reset or add more API keys in settings.`
};
}
// Legacy single-key mode (backward compatibility)
const storedRateLimit = data.geminiRateLimit;
const rateLimit = (storedRateLimit && typeof storedRateLimit === 'object')
? {
requests: Array.isArray(storedRateLimit.requests) ? storedRateLimit.requests : [],
dailyCount: typeof storedRateLimit.dailyCount === 'number' ? storedRateLimit.dailyCount : 0,
pendingCount: Math.max(0, Number(storedRateLimit.pendingCount) || 0),
dailyResetTime: typeof storedRateLimit.dailyCount === 'number' && storedRateLimit.dailyCount >= 20 &&
typeof storedRateLimit.dailyResetTime === 'number' ? storedRateLimit.dailyResetTime : null
}
: { requests: [], dailyCount: 0, pendingCount: 0, dailyResetTime: null };
// Reset daily count if it's a new day
if (typeof rateLimit.dailyResetTime === 'number' && now >= rateLimit.dailyResetTime) {
rateLimit.dailyCount = 0;
rateLimit.dailyResetTime = null;
}
// Check daily limit (20 per day), including slots reserved by in-flight calls.
if (rateLimit.dailyCount + rateLimit.pendingCount >= 20) {
const pending = rateLimit.pendingCount > 0 && rateLimit.dailyCount < 20;
if (pending) {
await browser.storage.local.set({ geminiRateLimit: rateLimit });
return {
allowed: false,
pending: true,
waitTime: 1,
message: 'Gemini requests are already using the remaining daily slots. Waiting for one to finish.'
};
}
}
if (rateLimit.dailyCount >= 20) {
if (typeof rateLimit.dailyResetTime !== 'number') {
rateLimit.dailyResetTime = now + (24 * 60 * 60 * 1000);
await browser.storage.local.set({ geminiRateLimit: rateLimit });
}
const hoursUntilReset = Math.ceil((rateLimit.dailyResetTime - now) / (1000 * 60 * 60));
return {
allowed: false,
message: `Gemini free tier daily limit reached (20/day). Resets in ${hoursUntilReset} hours. Upgrade to paid plan or add multiple API keys in settings to remove limits.`
};
}
// Reserve the next daily slot and space this call from concurrent requests.
const oneMinuteAgo = now - 60000;
rateLimit.requests = rateLimit.requests.filter(time => time > oneMinuteAgo);
const lastRequest = rateLimit.requests.length ? Math.max(...rateLimit.requests) : 0;
const scheduledAt = Math.max(now, lastRequest + 12000);
const waitTime = Math.ceil((scheduledAt - now) / 1000);
rateLimit.requests.push(scheduledAt);
rateLimit.pendingCount += 1;
await browser.storage.local.set({ geminiRateLimit: rateLimit });
return {
allowed: true,
waitTime,
keyIndex: null,
reserved: true
};
}
async function trackGeminiRequest(keyIndex = null) {
return withGeminiRateLimitLock(() => trackGeminiRequestInner(keyIndex));
}
async function trackGeminiRequestInner(keyIndex = null) {
const now = Date.now();
// Always fetch the latest rate limit state from storage to prevent race conditions
const data = await browser.storage.local.get([
'geminiApiKeys',
'geminiRateLimits',
'currentGeminiKeyIndex',
'geminiRateLimit' // Legacy
]);
// Multi-key mode
if (data.geminiApiKeys && data.geminiApiKeys.length > 0 && keyIndex !== null) {
const keys = data.geminiApiKeys;
const rawRateLimits = Array.isArray(data.geminiRateLimits) ? data.geminiRateLimits : [];
let rateLimits = keys.map((_, i) => {
const rl = rawRateLimits[i];
if (rl && typeof rl === 'object') {
return {
requests: Array.isArray(rl.requests) ? rl.requests : [],
dailyCount: typeof rl.dailyCount === 'number' ? rl.dailyCount : 0,
pendingCount: Math.max(0, Number(rl.pendingCount) || 0),
dailyResetTime: typeof rl.dailyCount === 'number' && rl.dailyCount >= 20 &&
typeof rl.dailyResetTime === 'number' ? rl.dailyResetTime : null
};
}
return { requests: [], dailyCount: 0, pendingCount: 0, dailyResetTime: null };
});
const rateLimit = rateLimits[keyIndex];
// Add current request
rateLimit.pendingCount = Math.max(0, rateLimit.pendingCount - 1);
rateLimit.dailyCount = Math.min(20, rateLimit.dailyCount + 1);
if (rateLimit.dailyCount >= 20 && typeof rateLimit.dailyResetTime !== 'number') {
rateLimit.dailyResetTime = now + (24 * 60 * 60 * 1000);
}
// Clean old requests (older than 1 minute)
const oneMinuteAgo = now - 60000;
rateLimit.requests = rateLimit.requests.filter(time => time > oneMinuteAgo);
// Update in the array
rateLimits[keyIndex] = rateLimit;
await browser.storage.local.set({ geminiRateLimits: rateLimits });
console.log(`Gemini Key #${keyIndex + 1}: ${rateLimit.dailyCount}/20 today, ${rateLimit.requests.length} in last minute`);
} else {
// Legacy single-key mode
const storedRateLimit = data.geminiRateLimit;
let rateLimit = (storedRateLimit && typeof storedRateLimit === 'object')
? {
requests: Array.isArray(storedRateLimit.requests) ? storedRateLimit.requests : [],
dailyCount: typeof storedRateLimit.dailyCount === 'number' ? storedRateLimit.dailyCount : 0,
pendingCount: Math.max(0, Number(storedRateLimit.pendingCount) || 0),
dailyResetTime: typeof storedRateLimit.dailyCount === 'number' && storedRateLimit.dailyCount >= 20 &&
typeof storedRateLimit.dailyResetTime === 'number' ? storedRateLimit.dailyResetTime : null
}
: { requests: [], dailyCount: 0, pendingCount: 0, dailyResetTime: null };
// Add current request
rateLimit.pendingCount = Math.max(0, rateLimit.pendingCount - 1);
rateLimit.dailyCount = Math.min(20, rateLimit.dailyCount + 1);
if (rateLimit.dailyCount >= 20 && typeof rateLimit.dailyResetTime !== 'number') {
rateLimit.dailyResetTime = now + (24 * 60 * 60 * 1000);
}
// Clean old requests (older than 1 minute)
const oneMinuteAgo = now - 60000;
rateLimit.requests = rateLimit.requests.filter(time => time > oneMinuteAgo);
await browser.storage.local.set({ geminiRateLimit: rateLimit });
console.log(`Gemini requests: ${rateLimit.dailyCount}/20 today, ${rateLimit.requests.length} in last minute`);
}
}
async function releaseGeminiRequestReservation(keyIndex = null) {
return withGeminiRateLimitLock(async () => {
const data = await browser.storage.local.get(['geminiApiKeys', 'geminiRateLimits', 'geminiRateLimit']);
if (Array.isArray(data.geminiApiKeys) && data.geminiApiKeys.length && keyIndex !== null) {
const limits = data.geminiApiKeys.map((_, index) => {
const stored = Array.isArray(data.geminiRateLimits) ? data.geminiRateLimits[index] : null;
if (!stored || typeof stored !== 'object') {
return { requests: [], dailyCount: 0, pendingCount: 0, dailyResetTime: null };
}
return Object.assign({}, stored, {
pendingCount: Math.max(0, (Number(stored.pendingCount) || 0) - (index === keyIndex ? 1 : 0))
});
});
await browser.storage.local.set({ geminiRateLimits: limits });
} else if (data.geminiRateLimit && typeof data.geminiRateLimit === 'object') {
await browser.storage.local.set({
geminiRateLimit: Object.assign({}, data.geminiRateLimit, {
pendingCount: Math.max(0, (Number(data.geminiRateLimit.pendingCount) || 0) - 1)
})
});
}
});
}
// Function to show notification
async function showNotification(title, message, type = "basic") {
// Log to console if desktop notifications are unavailable.
console.log(`[AutoSort+] ${title}: ${message}`);
// Try to show notification if API is available
try {
if (browser.notifications && browser.notifications.create) {
const id = `autosort-${Date.now()}`;
await browser.notifications.create(id, {
type: type,
iconUrl: browser.runtime.getURL("icons/icon-48.png"),
title: title,
message: message,
eventTime: Date.now(),
priority: 2,
requireInteraction: true
});
return id;
}
} catch (error) {
// Silently fail - notifications not supported
}
return null;
}
async function playSortingCompletionSound() {
try {
const AudioContextConstructor = typeof AudioContext !== 'undefined'
? AudioContext
: (typeof webkitAudioContext !== 'undefined' ? webkitAudioContext : null);
if (!AudioContextConstructor) return;
const context = new AudioContextConstructor();
if (context.state === 'suspended') await context.resume();
const startAt = context.currentTime + 0.03;
const master = context.createGain();
master.gain.value = 0.7;
master.connect(context.destination);
// Three clear, two-tone chime notes, about two seconds long.
[0, 0.68, 1.36].forEach((offset, index) => {
const noteStart = startAt + offset;
const noteLength = 0.52;
[index === 1 ? 784 : 659, index === 1 ? 988 : 784].forEach((frequency, toneIndex) => {
const oscillator = context.createOscillator();
const envelope = context.createGain();
const toneStart = noteStart + toneIndex * 0.1;
oscillator.type = 'triangle';
oscillator.frequency.value = frequency;
envelope.gain.setValueAtTime(0.0001, toneStart);
envelope.gain.linearRampToValueAtTime(0.42, toneStart + 0.025);
envelope.gain.setValueAtTime(0.42, toneStart + noteLength - 0.08);
envelope.gain.exponentialRampToValueAtTime(0.0001, toneStart + noteLength);
oscillator.connect(envelope);
envelope.connect(master);
oscillator.start(toneStart);
oscillator.stop(toneStart + noteLength + 0.02);
});
});
setTimeout(() => context.close().catch(() => {}), 2400);
} catch (error) {
console.warn('[AutoSort+] Could not play sorting completion sound:', error.message);
}
}
// Function to update existing notification
async function updateNotification(id, title, message) {
// Log to console
console.log(`[AutoSort+] ${title}: ${message}`);
// Try to update notification if API is available
try {
if (browser.notifications && browser.notifications.clear && id) {
await browser.notifications.clear(id);
}
} catch (error) {
// Silently fail - notifications not supported
}
return await showNotification(title, message);
}
// Build a Gemini generationConfig that matches the selected model family.
// Gemini 3.x uses `thinkingLevel`; Gemini 2.5.x uses `thinkingBudget`.
// Sending both (or the wrong one) causes a 400 error.
function buildGeminiGenerationConfig(geminiModel) {
const config = {
// Gemini 3 counts thinking tokens against this budget as well. 50 is
// often exhausted before it emits even a short classification label.
maxOutputTokens: 512,
responseMimeType: "text/plain"
};
if (/^gemini-3/.test(geminiModel)) {
// Gemini 3.x: sampling params are deprecated; "low" thinking minimizes cost/latency.
config.thinkingConfig = { thinkingLevel: "low" };
} else {
config.temperature = 0.2;
config.topK = 1;
config.topP = 1;
if (geminiModel.includes("2.5")) {
// Gemini 2.5.x: 0 disables thinking (Flash/Lite only).
config.thinkingConfig = { thinkingBudget: 0 };
}
}
return config;
}
function getGeminiRetryDelayMs(response, errorData, retryAttempt) {
const retryAfter = response.headers && response.headers.get('Retry-After');
if (retryAfter) {
const seconds = Number(retryAfter);
if (Number.isFinite(seconds)) return Math.max(1000, seconds * 1000);
const dateDelay = Date.parse(retryAfter) - Date.now();
if (Number.isFinite(dateDelay) && dateDelay > 0) return dateDelay;
}
const details = errorData && errorData.error && errorData.error.details;
if (Array.isArray(details)) {
const retryInfo = details.find(item => item && /RetryInfo/.test(item['@type'] || ''));
const match = retryInfo && String(retryInfo.retryDelay || '').match(/([\d.]+)s/);
if (match) return Math.max(1000, Math.ceil(Number(match[1]) * 1000));
}
const message = errorData && errorData.error && errorData.error.message || '';
const messageMatch = message.match(/retry in\s+([\d.]+)s/i);
if (messageMatch) return Math.max(1000, Math.ceil(Number(messageMatch[1]) * 1000));
// No provider delay was supplied: use a bounded exponential backoff.
return Math.min(60000, 10000 * Math.pow(2, retryAttempt));
}
// Function to analyze email content using AI
async function analyzeEmailContent(emailContent, notify) {
// `notify(title, message)` routes status updates to a custom sink when
// provided (batch processing forwards them to the progress panel);
// default to desktop notifications.
const notifyFn = typeof notify === 'function' ? notify : showNotification;
let geminiReservationActive = false;
let geminiReservationKeyIndex = null;
const releaseReservation = async () => {
if (!geminiReservationActive) return;
await releaseGeminiRequestReservation(geminiReservationKeyIndex);
geminiReservationActive = false;
};
try {
const notificationId = await notifyFn(
"AutoSort+ AI Analysis",
"Starting email analysis..."
);
const settings = await browser.storage.local.get([
'apiKey',
'geminiApiKeys',
'currentGeminiKeyIndex',
'aiProvider',
'labels',
'enableAi',
'geminiPaidPlan',
'geminiRateLimit',
'geminiRateLimits',
'geminiModel',
'providerModel'
]);
const provider = settings.aiProvider || 'gemini';
// Check Gemini rate limits (free tier only)
let keyIndexToUse = null;
if (provider === 'gemini' && !settings.geminiPaidPlan) {
let rateLimitCheck;
while (true) {
rateLimitCheck = await checkGeminiRateLimit();
if (rateLimitCheck.allowed) break;
if (rateLimitCheck.pending) {
await new Promise(resolve => setTimeout(resolve, (rateLimitCheck.waitTime || 1) * 1000));
continue;
}
// Show persistent notification for limit reached
const isSingleKey = !settings.geminiApiKeys || settings.geminiApiKeys.length <= 1;
const notifTitle = isSingleKey ? "⛔ Gemini API Limit Reached" : "⛔ All Gemini Keys at Limit";
const notifId = await notifyFn(
notifTitle,
rateLimitCheck.message,
"list"
);
// Also try to update the current notification
await notifyFn(
notificationId,
"AutoSort+ Rate Limit",
rateLimitCheck.message
);
throw new Error(rateLimitCheck.message);
}
keyIndexToUse = rateLimitCheck.keyIndex;
geminiReservationKeyIndex = keyIndexToUse;
geminiReservationActive = rateLimitCheck.reserved === true;
if (rateLimitCheck.waitTime > 0) {
await notifyFn(
notificationId,
"AutoSort+ Rate Limit",
`Rate limit reached. Waiting ${rateLimitCheck.waitTime} seconds...`
);
await new Promise(resolve => setTimeout(resolve, rateLimitCheck.waitTime * 1000));
}
}
console.log("Settings retrieved:", {
hasApiKey: !!(settings.apiKey || (settings.geminiApiKeys && settings.geminiApiKeys.length > 0)),
provider: provider,
labels: settings.labels,
enableAi: settings.enableAi !== false
});
if (settings.enableAi === false) {
console.error("AI is disabled");
await notifyFn(
notificationId,
"AutoSort+ Error",
"AI analysis is disabled in settings."
);
await releaseReservation();
return null;
}
// Check API key availability based on provider
let apiKeyToUse = null;
if (provider === 'gemini') {
if (settings.geminiApiKeys && settings.geminiApiKeys.length > 0) {
const keyIndex = keyIndexToUse !== null ? keyIndexToUse : (settings.currentGeminiKeyIndex || 0);
apiKeyToUse = settings.geminiApiKeys[keyIndex];
console.log(`Using Gemini API Key #${keyIndex + 1} of ${settings.geminiApiKeys.length}`);
} else if (settings.apiKey) {
// Legacy single key
apiKeyToUse = settings.apiKey;
}
} else if (provider !== 'ollama' && provider !== 'lmstudio') {
// Local providers don't need an API key; other providers do
apiKeyToUse = settings.apiKey;
}
if (!apiKeyToUse && provider !== 'ollama' && provider !== 'lmstudio') {
console.error("Missing API key");
await notifyFn(
notificationId,
"AutoSort+ Error",
`${provider.charAt(0).toUpperCase() + provider.slice(1)} API key not configured. Please add your API key in settings.`
);
await releaseReservation();
return null;
}
if (!settings.labels || settings.labels.length === 0) {
console.error("No labels configured");
await notifyFn(
notificationId,
"AutoSort+ Error",
"No folders/labels configured. Please go to settings and either load folders from your mail account or add custom labels."
);
await releaseReservation();
return null;
}
const prompt = `You are an email classification assistant. Analyze this email content and choose the most appropriate label from this list: ${settings.labels.join(', ')}.
Consider the following:
1. The main topic and purpose of the email
2. The sender and recipient context
3. The urgency and importance of the content
4. The type of communication (e.g., notification, request, update)
Only respond with the exact label name that best fits the content. If no label fits well, respond with "null".
Email content:
${emailContent}`;
await notifyFn(
notificationId,
"AutoSort+ AI Analysis",
`Sending request to ${provider.charAt(0).toUpperCase() + provider.slice(1)} AI...`
);
let response;
let data;
if (provider === 'gemini') {
// Gemini model is configurable (new API keys can no longer use 2.5 models)
const geminiModel = settings.geminiModel || 'gemini-3.5-flash-lite';