-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1289 lines (1125 loc) · 50.2 KB
/
background.js
File metadata and controls
1289 lines (1125 loc) · 50.2 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 === "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 === '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;
}
});
// 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) {}
}
}
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 } };
}
}
}
// Gemini rate limiting functions (free tier: 5/min, 20/day per key)
async function checkGeminiRateLimit() {
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 rateLimits = data.geminiRateLimits || keys.map(() => ({
requests: [],
dailyCount: 0,
dailyResetTime: now + (24 * 60 * 60 * 1000)
}));
let currentIndex = data.currentGeminiKeyIndex || 0;
// 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 (now > rateLimit.dailyResetTime) {
rateLimit.dailyCount = 0;
rateLimit.dailyResetTime = now + (24 * 60 * 60 * 1000);
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 < 20) {
// Check if we need to wait
if (rateLimit.requests.length > 0) {
const lastRequest = Math.max(...rateLimit.requests);
const timeSinceLastRequest = now - lastRequest;
const minInterval = 12000; // 12 seconds
if (timeSinceLastRequest < minInterval) {
const waitTime = Math.ceil((minInterval - timeSinceLastRequest) / 1000);
return {
allowed: true,
waitTime: waitTime,
keyIndex: currentIndex
};
}
}
// This key is ready to use
await browser.storage.local.set({
currentGeminiKeyIndex: currentIndex,
geminiRateLimits: rateLimits
});
return {
allowed: true,
waitTime: 0,
keyIndex: currentIndex
};
}
// This key has reached its limit, try next one
currentIndex = (currentIndex + 1) % keys.length;
attempts++;
}
// All keys have reached their limits
return {
allowed: false,
message: `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 rateLimit = data.geminiRateLimit || { requests: [], dailyCount: 0, dailyResetTime: now };
// Reset daily count if it's a new day
if (now > rateLimit.dailyResetTime) {
rateLimit.dailyCount = 0;
rateLimit.dailyResetTime = now + (24 * 60 * 60 * 1000);
}
// Check daily limit (20 per day)
if (rateLimit.dailyCount >= 20) {
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.`
};
}
// Remove requests older than 1 minute
const oneMinuteAgo = now - 60000;
rateLimit.requests = rateLimit.requests.filter(time => time > oneMinuteAgo);
// Check if we need to wait (12 seconds between requests = 5 per minute)
if (rateLimit.requests.length > 0) {
const lastRequest = Math.max(...rateLimit.requests);
const timeSinceLastRequest = now - lastRequest;
const minInterval = 12000; // 12 seconds
if (timeSinceLastRequest < minInterval) {
const waitTime = Math.ceil((minInterval - timeSinceLastRequest) / 1000);
return {
allowed: true,
waitTime: waitTime
};
}
}
return {
allowed: true,
waitTime: 0
};
}
async function trackGeminiRequest(keyIndex = null) {
const now = Date.now();
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 rateLimits = data.geminiRateLimits || data.geminiApiKeys.map(() => ({
requests: [],
dailyCount: 0,
dailyResetTime: now + (24 * 60 * 60 * 1000)
}));
const rateLimit = rateLimits[keyIndex];
// Add current request
rateLimit.requests.push(now);
rateLimit.dailyCount += 1;
// Clean old requests
const oneMinuteAgo = now - 60000;
rateLimit.requests = rateLimit.requests.filter(time => time > oneMinuteAgo);
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 rateLimit = data.geminiRateLimit || { requests: [], dailyCount: 0, dailyResetTime: now + (24 * 60 * 60 * 1000) };
// Add current request
rateLimit.requests.push(now);
rateLimit.dailyCount += 1;
// Clean old requests
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`);
}
}
// Function to show notification
async function showNotification(title, message, type = "basic") {
// Log to console (Thunderbird doesn't support browser.notifications)
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;
}
// 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);
}
// Function to analyze email content using AI
async function analyzeEmailContent(emailContent) {
try {
const notificationId = await showNotification(
"AutoSort+ AI Analysis",
"Starting email analysis..."
);
const settings = await browser.storage.local.get([
'apiKey',
'geminiApiKeys',
'currentGeminiKeyIndex',
'aiProvider',
'labels',
'enableAi',
'geminiPaidPlan',
'geminiRateLimit',
'geminiRateLimits'
]);
const provider = settings.aiProvider || 'gemini';
// Check Gemini rate limits (free tier only)
let keyIndexToUse = null;
if (provider === 'gemini' && !settings.geminiPaidPlan) {
const rateLimitCheck = await checkGeminiRateLimit();
if (!rateLimitCheck.allowed) {
// 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 showNotification(
notifTitle,
rateLimitCheck.message,
"list"
);
// Also try to update the current notification
await updateNotification(
notificationId,
"AutoSort+ Rate Limit",
rateLimitCheck.message
);
throw new Error(rateLimitCheck.message);
}
if (rateLimitCheck.waitTime > 0) {
await updateNotification(
notificationId,
"AutoSort+ Rate Limit",
`Rate limit reached. Waiting ${rateLimitCheck.waitTime} seconds...`
); await new Promise(resolve => setTimeout(resolve, rateLimitCheck.waitTime * 1000));
}
keyIndexToUse = rateLimitCheck.keyIndex;
}
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 updateNotification(
notificationId,
"AutoSort+ Error",
"AI analysis is disabled in settings."
);
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') {
// Ollama doesn't need an API key; other providers do
apiKeyToUse = settings.apiKey;
}
if (!apiKeyToUse && provider !== 'ollama') {
console.error("Missing API key");
await updateNotification(
notificationId,
"AutoSort+ Error",
`${provider.charAt(0).toUpperCase() + provider.slice(1)} API key not configured. Please add your API key in settings.`
);
return null;
}
if (!settings.labels || settings.labels.length === 0) {
console.error("No labels configured");
await updateNotification(
notificationId,
"AutoSort+ Error",
"No folders/labels configured. Please go to settings and either load folders from your mail account or add custom labels."
);
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 updateNotification(
notificationId,
"AutoSort+ AI Analysis",
`Sending request to ${provider.charAt(0).toUpperCase() + provider.slice(1)} AI...`
);
let response;
let data;
if (provider === 'gemini') {
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKeyToUse}`;
console.log("Making API request to Gemini...");
// Track request for rate limiting (free tier only)
if (!settings.geminiPaidPlan) {
await trackGeminiRequest(keyIndexToUse);
}
await updateNotification(
notificationId,
"AutoSort+ AI Analysis",
"Analyzing email content with Gemini AI..."
);
const requestBody = {
contents: [{
role: "user",
parts: [{
text: prompt
}]
}],
generationConfig: {
temperature: 0.2,
topK: 1,
topP: 1,
maxOutputTokens: 50,
responseMimeType: "text/plain",
thinkingConfig: {
thinkingBudget: 0
}
},
safetySettings: [
{
category: "HARM_CATEGORY_HARASSMENT",
threshold: "BLOCK_NONE"
},
{
category: "HARM_CATEGORY_HATE_SPEECH",
threshold: "BLOCK_NONE"
},
{
category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
threshold: "BLOCK_NONE"
},
{
category: "HARM_CATEGORY_DANGEROUS_CONTENT",
threshold: "BLOCK_NONE"
}
]
};
response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
} else if (provider === 'openai') {
console.log("Making API request to OpenAI...");
await updateNotification(
notificationId,
"AutoSort+ AI Analysis",
"Analyzing email content with OpenAI..."
);
response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKeyToUse}`
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: prompt }],
max_tokens: 50,
temperature: 0.2
})
});
} else if (provider === 'anthropic') {
console.log("Making API request to Anthropic...");
await updateNotification(
notificationId,
"AutoSort+ AI Analysis",
"Analyzing email content with Claude..."
);
response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKeyToUse,
'anthropic-version': '2023-06-01'
},
body: JSON.stringify({
model: 'claude-3-haiku-20240307',
messages: [{ role: 'user', content: prompt }],
max_tokens: 50
})
});
} else if (provider === 'groq') {
console.log("Making API request to Groq...");
await updateNotification(
notificationId,
"AutoSort+ AI Analysis",
"Analyzing email content with Groq..."
);
response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKeyToUse}`
},
body: JSON.stringify({
model: 'llama-3.3-70b-versatile',
messages: [{ role: 'user', content: prompt }],
max_tokens: 50,
temperature: 0.2
})
});
} else if (provider === 'mistral') {
console.log("Making API request to Mistral...");
await updateNotification(
notificationId,
"AutoSort+ AI Analysis",
"Analyzing email content with Mistral..."
);
response = await fetch('https://api.mistral.ai/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKeyToUse}`
},
body: JSON.stringify({
model: 'mistral-small-latest',
messages: [{ role: 'user', content: prompt }],
max_tokens: 50,
temperature: 0.2
})
});
} else if (provider === 'ollama') {
console.log("Making API request to Ollama (local)...");
await updateNotification(
notificationId,
"AutoSort+ AI Analysis",
"Analyzing email content with local Ollama..."
);
// Get Ollama settings
const ollamaSettings = await browser.storage.local.get(['ollamaUrl', 'ollamaModel', 'ollamaCustomModel', 'ollamaCpuOnly', 'ollamaAuthToken', 'ollamaNumCtx']);
const ollamaUrl = ollamaSettings.ollamaUrl || 'http://localhost:11434';
let ollamaModel = ollamaSettings.ollamaModel || 'llama3.2';
const ollamaNumCtx = ollamaSettings.ollamaNumCtx || 0;
const cpuOnly = ollamaSettings.ollamaCpuOnly === true;
const ollamaAuthToken = ollamaSettings.ollamaAuthToken || '';
// Use custom model if selected
if (ollamaModel === 'custom' && ollamaSettings.ollamaCustomModel) {
ollamaModel = ollamaSettings.ollamaCustomModel;
}
console.log(`Using Ollama at ${ollamaUrl} with model ${ollamaModel}${cpuOnly ? ' (CPU-only)' : ''}`);
// Use tab injection to make the fetch (browser context, no restrictions)
try {
const ollamaResponse = await ollamaChatViaTab(ollamaUrl, ollamaModel, prompt, ollamaAuthToken);
if (!ollamaResponse.message || !ollamaResponse.message.content) {
throw new Error('Invalid Ollama response format');
}
data = ollamaResponse;
response = null; // Mark as handled
} catch (ollamaError) {
console.error('[Ollama] Tab injection chat failed:', ollamaError.message);
throw ollamaError;
}
} else {
throw new Error(`Unknown provider: ${provider}`);
}
if (response) {
console.log("API response status:", response.status);
if (!response.ok) {
let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
// Try to parse error response body
try {
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
const error = await response.json();
errorMessage = error.error?.message || error.message || errorMessage;
} else {
const text = await response.text();
if (text) errorMessage = text.substring(0, 200);
}
} catch (parseErr) {
console.warn('Could not parse error response:', parseErr.message);
}
console.error("API Error details:", errorMessage);
// Handle quota errors specifically
if (response.status === 429 || errorMessage.includes('quota') || errorMessage.includes('rate limit')) {
errorMessage = "API quota exceeded. Please wait a while before trying again, or upgrade to a paid API key.";
}
// Handle Ollama auth errors
if (response.status === 403) {
errorMessage = "Ollama authentication failed (403). Check your API key/token if Ollama requires authentication.";
}
await updateNotification(
notificationId,
"AutoSort+ Error",
`API Error: ${errorMessage}`
);
return null;
}
await updateNotification(
notificationId,
"AutoSort+ AI Analysis",
"Processing AI response..."
);
data = await response.json();
console.log("Full API response data:", JSON.stringify(data, null, 2));
} else if (data) {
await updateNotification(
notificationId,
"AutoSort+ AI Analysis",
"Processing AI response..."
);
console.log("Using response from native helper.");
} else {
await updateNotification(
notificationId,
"AutoSort+ Error",
"No response received from provider."
);
return null;
}
// Parse the response based on provider
let label = null;
const tryTrim = v => {
try {
return (v || '').toString().trim();
} catch (e) {
return null;
}
};
if (provider === 'gemini') {
if (data.candidates && data.candidates.length > 0) {
const candidate = data.candidates[0];
if (candidate.finishReason === "MAX_TOKENS") {
console.error("Response truncated");
await updateNotification(notificationId, "AutoSort+ Error", "AI response was cut off");
return null;
}
if (candidate.content && candidate.content.parts && candidate.content.parts.length > 0) {
label = tryTrim(candidate.content.parts[0].text);
}
}
} else if (provider === 'openai' || provider === 'groq' || provider === 'mistral') {
if (data.choices && data.choices.length > 0) {
label = tryTrim(data.choices[0].message?.content || data.choices[0].text);
}
} else if (provider === 'anthropic') {
if (data.content && data.content.length > 0) {
label = tryTrim(data.content[0].text);
}
} else if (provider === 'ollama') {
// Ollama responses may vary in shape: string, object, array of parts, etc.
try {
const msg = data.message;
if (!msg) {
// Some older/local versions may return data as string or have different keys
label = tryTrim(data.result || data.text || data.response);
} else {
const content = msg.content;
if (typeof content === 'string') {
label = tryTrim(content);
} else if (Array.isArray(content)) {
// Find first element that's a string or has text fields
const first = content.find(c => typeof c === 'string' || (c && (c.text || c.content)));
if (typeof first === 'string') label = tryTrim(first);
else if (first && first.text) label = tryTrim(first.text);
else if (first && first.content) {
if (typeof first.content === 'string') label = tryTrim(first.content);
else if (Array.isArray(first.content)) label = tryTrim(first.content.map(x => x.text || x).join(' '));
}
} else if (content && typeof content === 'object') {
// Content might be an object with text or parts
label = tryTrim(content.text || content.content || content[0]);
if (!label && content.parts && content.parts.length > 0) {
label = tryTrim(content.parts[0].text || content.parts[0]);
}
} else if (typeof msg === 'string') {
label = tryTrim(msg);
}
}
} catch (e) {
console.warn('Failed to parse Ollama response shape:', e.message);
label = null;
}
}
if (!label) {
console.error("No label extracted from response:", data);
await updateNotification(notificationId, "AutoSort+ Error", "No response from AI");
return null;
}
console.log("Raw generated label:", label);
// Normalize and try to match configured labels more forgivingly
const normalize = s => s.toString().trim().replace(/^['"`]+|['"`]+$/g, '');
const lower = normalize(label).toLowerCase();
// Exact match first
if (settings.labels.includes(label)) {
await updateNotification(notificationId, "AutoSort+ Success", `AI analysis complete. Selected label: ${label}`);
return label;
}
// Try to find a label that matches case-insensitively or is contained within the AI output
let matched = settings.labels.find(l => l.toLowerCase() === lower);
if (!matched) {
matched = settings.labels.find(l => lower.includes(l.toLowerCase()) || l.toLowerCase().includes(lower));
}
if (matched) {
console.log('Mapped AI output to configured label:', matched);
await updateNotification(notificationId, "AutoSort+ Success", `AI analysis complete. Selected label: ${matched}`);
return matched;
}
console.log("Label not found in configured labels. Generated:", label);
await updateNotification(notificationId, "AutoSort+ Warning", `AI suggested: "${label}" but it's not in your configured labels.`);
return null;
} catch (error) {
console.error("Error analyzing email:", error);
await showNotification(
"AutoSort+ Error",
`Error analyzing email: ${error.message}`
);
return null;
}
}
// Function to store move history
async function storeMoveHistory(result) {
try {
const data = await browser.storage.local.get('moveHistory');
const history = data.moveHistory || [];
history.unshift({
timestamp: new Date().toISOString(),
...result
});
// Keep only the last 100 entries
if (history.length > 100) {
history.pop();
}
await browser.storage.local.set({ moveHistory: history });
} catch (error) {
console.error("Error storing move history:", error);
}
}
// Function to apply labels to selected messages
async function applyLabelsToMessages(messages, label) {
try {
const messageCount = messages.length;
const notificationId = await showNotification(
"AutoSort+ Processing",
`Starting to process ${messageCount} message(s)...`
);
let successCount = 0;
let errorCount = 0;
const moveResults = [];
for (const message of messages) {
console.log("Processing message:", message.id);
console.log("Target label/folder:", label);
// Get all folders to find the destination folder
const account = await browser.accounts.get(message.folder.accountId);
console.log("Account info:", account);
await updateNotification(
notificationId,
"AutoSort+ Processing",
`Finding destination folder for message ${successCount + errorCount + 1}/${messageCount}...`
);
// Find the folder with matching name
const findFolder = (folders, targetName) => {
for (const folder of folders) {
console.log("Checking folder:", folder.name);
if (folder.name === targetName) {
return folder;
}
if (folder.subFolders) {
const found = findFolder(folder.subFolders, targetName);
if (found) return found;
}
}
return null;
};
// First try to find the category folder
const categories = [
"Financiën",
"Werk en Carrière",
"Persoonlijke Communicatie en Sociale Leven",
"Gezondheid en Welzijn",
"Online Activiteiten en E-commerce",
"Reizen en Evenementen",
"Informatie en Media",
"Beveiliging en IT",
"Klantensupport en Acties",
"Overheid en Gemeenschap"
];
let categoryFolder = null;
let targetFolder = null;
// Find the category and target folder
for (const category of categories) {
if (label.startsWith(category)) {
console.log("Found matching category:", category);
categoryFolder = findFolder(account.folders, category);
if (categoryFolder) {
console.log("Found category folder:", categoryFolder.name);
// Try to find the subfolder
const subfolderName = label.replace(category + "/", "");
console.log("Looking for subfolder:", subfolderName);
targetFolder = findFolder(categoryFolder.subFolders || [], subfolderName);
break;
} else {
console.log("Category folder not found:", category, "- skipping to next category");
continue;
}
}
}
// If no target folder found, try direct match
if (!targetFolder) {
console.log("No category match found, trying direct folder match");
targetFolder = findFolder(account.folders, label);
}
// Auto-create missing folder when it's a custom label (skip imported/structured labels)
if (!targetFolder) {
const looksImported = label.includes('/') || label.includes('\\');
if (looksImported) {
console.warn(`Folder "${label}" looks imported/structured; skipping auto-create.`);
} else {
try {
const parentFolder = account.folders && account.folders.length > 0 ? account.folders[0] : null;
if (parentFolder && browser.folders && browser.folders.create) {
console.log(`Creating missing folder "${label}" under ${parentFolder.name || 'root'}`);
const created = await browser.folders.create(parentFolder, label);
if (created) {