-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbackground.js
More file actions
2030 lines (1755 loc) · 76.3 KB
/
background.js
File metadata and controls
2030 lines (1755 loc) · 76.3 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
// === ENHANCED CONFIGURATION ===
const CONFIG = {
API_ENDPOINTS: {
'gpt-4o-mini': "https://api.openai.com/v1/chat/completions",
'gpt-4o': "https://api.openai.com/v1/chat/completions",
'gpt-3.5-turbo': "https://api.openai.com/v1/chat/completions"
},
DEFAULT_MODEL: 'amazon/nova-micro',
DEFAULT_ENDPOINT: "https://api.openai.com/v1/chat/completions",
MAX_TEXT_LENGTH: 8000,
MIN_TEXT_LENGTH: 3,
MAX_RETRIES: 3,
RETRY_DELAY: 1000,
REQUEST_TIMEOUT: 30000,
RATE_LIMIT: {
requests: 60,
windowMs: 60000, // 1 minute
burstLimit: 5, // Max 5 requests in 10 seconds
burstWindow: 10000
},
CACHE: {
enabled: true,
maxSize: 100,
ttl: 300000 // 5 minutes
},
RESTRICTED_URLS: [
'chrome://',
'chrome-extension://',
'moz-extension://',
'edge://',
'opera://',
'about:',
'file://',
'data:',
'javascript:'
],
SUPPORTED_ELEMENTS: {
tags: ['TEXTAREA', 'INPUT'],
inputTypes: ['text', 'search', 'email', 'url', 'password', 'tel'],
contentEditable: true
}
};
// === CONTEXT MENU SETUP ===
const CONTEXT_MENU_ID = "GEMINI_REWRITE";
// Built-in modes with enhanced prompts and metadata
const BUILT_IN_MODES = {
humanize: {
name: "Humanize (Make Natural)",
description: "Make text sound more natural and conversational",
icon: "🧑",
category: "style"
},
grammar: {
name: "Fix Grammar & Spelling",
description: "Correct grammatical errors and typos",
icon: "✏️",
category: "correction"
},
professional: {
name: "Professional Tone",
description: "Formal business communication style",
icon: "💼",
category: "tone"
},
polite: {
name: "Polite & Courteous",
description: "Soften language with respectful phrasing",
icon: "🙏",
category: "tone"
},
casual: {
name: "Casual & Friendly",
description: "Informal, conversational style",
icon: "😊",
category: "tone"
},
confident: {
name: "Confident & Assertive",
description: "Strong, decisive language",
icon: "💪",
category: "tone"
},
empathetic: {
name: "Empathetic & Understanding",
description: "Caring and emotionally aware tone",
icon: "❤️",
category: "tone"
},
persuasive: {
name: "Persuasive & Compelling",
description: "Convincing and motivating language",
icon: "🎯",
category: "style"
},
concise: {
name: "Concise & Clear",
description: "Remove fluff, get to the point",
icon: "⚡",
category: "structure"
},
detailed: {
name: "Detailed & Comprehensive",
description: "Add depth and explanations",
icon: "📚",
category: "structure"
},
creative: {
name: "Creative & Engaging",
description: "Vivid, imaginative language",
icon: "🎨",
category: "style"
},
technical: {
name: "Technical & Precise",
description: "Accurate technical terminology",
icon: "⚙️",
category: "specialized"
},
academic: {
name: "Academic & Scholarly",
description: "Formal academic writing style",
icon: "🎓",
category: "specialized"
},
marketing: {
name: "Marketing & Sales",
description: "Promotional and engaging copy",
icon: "📢",
category: "specialized"
},
cheeky: {
name: "Cheeky & Playful",
description: "Witty and slightly sarcastic",
icon: "😏",
category: "fun"
},
newby: {
name: "Beginner-Friendly",
description: "Simple language for newcomers",
icon: "🌱",
category: "fun"
},
composer: {
name: "Compose from Instruction",
description: "Generate new content from prompts",
icon: "✨",
category: "generation"
},
translate: {
name: "Translate to English",
description: "Convert text to clear English",
icon: "🌍",
category: "utility"
},
summarize: {
name: "Summarize Key Points",
description: "Extract main ideas concisely",
icon: "📝",
category: "utility"
},
expand: {
name: "Expand & Elaborate",
description: "Add more detail and context",
icon: "🔍",
category: "structure"
},
simplify: {
name: "Simplify & Clarify",
description: "Make complex text easier to understand",
icon: "🔧",
category: "utility"
}
};
// === ENHANCED STATE MANAGEMENT ===
let rewriteHistory = [];
let requestCount = 0;
let lastRequestTime = 0;
let burstRequestCount = 0;
let lastBurstTime = 0;
let responseCache = new Map();
let activeRequests = new Set();
let contextMenusSetup = false;
let setupInProgress = false;
// Performance monitoring
let performanceMetrics = {
totalRequests: 0,
successfulRequests: 0,
failedRequests: 0,
averageResponseTime: 0,
cacheHits: 0
};
// === INSTALLATION & SETUP ===
chrome.runtime.onInstalled.addListener(async () => {
console.log("AI Rewriter Extension Installed/Updated");
// Initialize default settings
await initializeDefaultSettings();
// Setup context menus
await setupContextMenus();
// Check API key and notify if needed
await checkApiKeyStatus();
// Verify keyboard shortcuts are registered
await verifyKeyboardShortcuts();
});
// === STARTUP HANDLER ===
chrome.runtime.onStartup.addListener(async () => {
console.log("AI Rewriter Extension Starting Up");
// Ensure context menus are set up on browser startup
if (!contextMenusSetup) {
await setupContextMenus();
}
});
async function initializeDefaultSettings() {
return new Promise((resolve) => {
chrome.storage.sync.get([
'openaiApiKey',
'openaiBaseUrl',
'selectedModel',
'customModes',
'enabledModes',
'maxTextLength',
'enableUndo',
'enablePreviewMode',
'enableUsageTracking',
'enableKeyboardShortcuts',
'darkMode'
], (result) => {
const defaults = {
selectedModel: result.selectedModel || CONFIG.DEFAULT_MODEL,
customModes: result.customModes || {},
enabledModes: result.enabledModes || Object.keys(BUILT_IN_MODES),
maxTextLength: result.maxTextLength || CONFIG.MAX_TEXT_LENGTH,
enableUndo: result.enableUndo !== false,
enablePreviewMode: result.enablePreviewMode !== false,
enableUsageTracking: result.enableUsageTracking !== false,
enableKeyboardShortcuts: result.enableKeyboardShortcuts !== false,
darkMode: result.darkMode || false
};
chrome.storage.sync.set(defaults, () => {
console.log("Default settings initialized");
resolve();
});
});
});
}
async function setupContextMenus() {
// Prevent concurrent setup calls
if (setupInProgress) {
console.log("Context menu setup already in progress, skipping...");
return;
}
setupInProgress = true;
return new Promise((resolve, reject) => {
// Remove existing menus first
chrome.contextMenus.removeAll(() => {
if (chrome.runtime.lastError) {
console.error("Error removing context menus:", chrome.runtime.lastError);
setupInProgress = false;
reject(new Error(chrome.runtime.lastError.message));
return;
}
console.log("Removed old context menus.");
// Get current settings
chrome.storage.sync.get(['enabledModes', 'customModes'], (result) => {
if (chrome.runtime.lastError) {
console.error("Error getting storage:", chrome.runtime.lastError);
setupInProgress = false;
reject(new Error(chrome.runtime.lastError.message));
return;
}
try {
const enabledModes = result.enabledModes || Object.keys(BUILT_IN_MODES);
const customModes = result.customModes || {};
// Create parent menu
chrome.contextMenus.create({
id: CONTEXT_MENU_ID,
title: "✨ Rewrite with AI",
contexts: ["editable"]
}, () => {
if (chrome.runtime.lastError) {
console.error("Error creating parent menu:", chrome.runtime.lastError);
setupInProgress = false;
reject(new Error(chrome.runtime.lastError.message));
return;
}
let menuItemsCreated = 0;
let totalMenuItems = enabledModes.length + Object.keys(customModes).length + 3; // +3 for separator, undo, settings
const checkComplete = () => {
menuItemsCreated++;
if (menuItemsCreated >= totalMenuItems) {
contextMenusSetup = true;
setupInProgress = false;
console.log("Context menus created successfully.");
resolve();
}
};
// Add built-in modes
enabledModes.forEach(modeKey => {
if (BUILT_IN_MODES[modeKey]) {
chrome.contextMenus.create({
id: `${CONTEXT_MENU_ID}_${modeKey}`,
parentId: CONTEXT_MENU_ID,
title: `${BUILT_IN_MODES[modeKey].icon} ${BUILT_IN_MODES[modeKey].name}`,
contexts: ["editable"]
}, () => {
if (chrome.runtime.lastError) {
console.error(`Error creating menu for ${modeKey}:`, chrome.runtime.lastError);
}
checkComplete();
});
} else {
checkComplete();
}
});
// Add custom modes
Object.entries(customModes).forEach(([key, mode]) => {
chrome.contextMenus.create({
id: `${CONTEXT_MENU_ID}_custom_${key}`,
parentId: CONTEXT_MENU_ID,
title: `🎨 ${mode.name}`,
contexts: ["editable"]
}, () => {
if (chrome.runtime.lastError) {
console.error(`Error creating custom menu for ${key}:`, chrome.runtime.lastError);
}
checkComplete();
});
});
// Add separator and utility options
chrome.contextMenus.create({
id: "separator1",
parentId: CONTEXT_MENU_ID,
type: "separator",
contexts: ["editable"]
}, () => {
if (chrome.runtime.lastError) {
console.error("Error creating separator:", chrome.runtime.lastError);
}
checkComplete();
});
chrome.contextMenus.create({
id: `${CONTEXT_MENU_ID}_undo`,
parentId: CONTEXT_MENU_ID,
title: "↶ Undo Last Rewrite",
contexts: ["editable"]
}, () => {
if (chrome.runtime.lastError) {
console.error("Error creating undo menu:", chrome.runtime.lastError);
}
checkComplete();
});
chrome.contextMenus.create({
id: `${CONTEXT_MENU_ID}_settings`,
parentId: CONTEXT_MENU_ID,
title: "⚙️ Settings",
contexts: ["editable"]
}, () => {
if (chrome.runtime.lastError) {
console.error("Error creating settings menu:", chrome.runtime.lastError);
}
checkComplete();
});
});
} catch (error) {
console.error("Error creating context menus:", error);
setupInProgress = false;
reject(error);
}
});
});
});
}
async function checkApiKeyStatus() {
return new Promise((resolve) => {
chrome.storage.sync.get(['openaiApiKey'], (result) => {
if (!result.openaiApiKey) {
console.log("OpenAI API Key not found. User needs to configure.");
// Show notification to configure API key
showApiKeyNotification();
} else {
console.log("OpenAI API Key found.");
}
resolve();
});
});
}
async function verifyKeyboardShortcuts() {
try {
const commands = await chrome.commands.getAll();
console.log("Registered keyboard shortcuts:", commands);
const missingShortcuts = commands.filter(cmd => !cmd.shortcut);
if (missingShortcuts.length > 0) {
console.warn("Some keyboard shortcuts are not assigned:", missingShortcuts.map(c => c.name));
console.log("Users can configure shortcuts at chrome://extensions/shortcuts");
} else {
console.log("All keyboard shortcuts are properly registered");
}
} catch (error) {
console.error("Error verifying keyboard shortcuts:", error);
}
}
// Show notification when API key is not configured
function showApiKeyNotification() {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon48.png',
title: 'AI Text Rewriter - Setup Required',
message: 'Please configure your OpenAI API key in the extension settings to start rewriting text.',
buttons: [
{ title: 'Open Settings' },
{ title: 'Dismiss' }
],
priority: 1
}, (notificationId) => {
// Store notification ID for handling clicks
chrome.storage.local.set({ 'setupNotificationId': notificationId });
});
}
// Handle notification button clicks
chrome.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => {
chrome.storage.local.get(['setupNotificationId'], (result) => {
if (result.setupNotificationId === notificationId) {
if (buttonIndex === 0) {
// Open Settings button clicked
chrome.runtime.openOptionsPage();
}
// Clear notification
chrome.notifications.clear(notificationId);
chrome.storage.local.remove('setupNotificationId');
}
});
});
// Handle notification clicks (entire notification)
chrome.notifications.onClicked.addListener((notificationId) => {
chrome.storage.local.get(['setupNotificationId'], (result) => {
if (result.setupNotificationId === notificationId) {
// Open settings when notification is clicked
chrome.runtime.openOptionsPage();
chrome.notifications.clear(notificationId);
chrome.storage.local.remove('setupNotificationId');
}
});
});
// === ENHANCED CONTEXT MENU HANDLER ===
// Helper function to validate if a tab is valid for rewriting
function isValidTab(tab) {
if (!tab || !tab.url) {
return false;
}
// Check against restricted URLs
return !CONFIG.RESTRICTED_URLS.some(restrictedUrl =>
tab.url.startsWith(restrictedUrl)
);
}
// Helper function to parse mode information from menu item ID
function parseModeFromMenuId(menuItemId) {
if (!menuItemId || !menuItemId.startsWith(CONTEXT_MENU_ID)) {
return null;
}
// Remove the base context menu ID and underscore
const modeKey = menuItemId.replace(`${CONTEXT_MENU_ID}_`, '');
// Check if it's a custom mode
if (modeKey.startsWith('custom_')) {
const customKey = modeKey.replace('custom_', '');
return { type: 'custom', key: customKey };
}
// Check if it's a built-in mode
if (BUILT_IN_MODES[modeKey]) {
return { type: 'builtin', key: modeKey };
}
return null;
}
// Helper function to get settings from storage
async function getSettings() {
return new Promise((resolve) => {
chrome.storage.sync.get([
'openaiApiKey',
'openaiBaseUrl',
'selectedModel',
'customModes',
'enabledModes',
'maxTextLength',
'enableUndo',
'enablePreviewMode',
'enableUsageTracking',
'enableKeyboardShortcuts'
], (result) => {
resolve({
openaiApiKey: result.openaiApiKey || '',
openaiBaseUrl: result.openaiBaseUrl || '',
selectedModel: result.selectedModel || CONFIG.DEFAULT_MODEL,
customModes: result.customModes || {},
enabledModes: result.enabledModes || Object.keys(BUILT_IN_MODES),
maxTextLength: result.maxTextLength || CONFIG.MAX_TEXT_LENGTH,
enableUndo: result.enableUndo !== false,
enablePreviewMode: result.enablePreviewMode !== false,
enableUsageTracking: result.enableUsageTracking !== false,
enableKeyboardShortcuts: result.enableKeyboardShortcuts !== false
});
});
});
}
// Helper function to get user-friendly error messages
function getUserFriendlyError(error) {
if (!error) return "Unknown error occurred";
const errorMsg = error.message || error.toString();
if (errorMsg.includes('API key') || errorMsg.includes('invalid key') || errorMsg.includes('authentication')) {
return "API key error - Please check your Gemini API key in settings";
}
if (errorMsg.includes('quota') || errorMsg.includes('rate limit') || errorMsg.includes('429')) {
return "API rate limit reached - Please try again in a few minutes";
}
if (errorMsg.includes('network') || errorMsg.includes('fetch') || errorMsg.includes('NetworkError')) {
return "Network error - Please check your internet connection";
}
if (errorMsg.includes('timeout') || errorMsg.includes('AbortError')) {
return "Request timed out - Please try again";
}
if (errorMsg.includes('blocked') || errorMsg.includes('safety') || errorMsg.includes('SAFETY')) {
return "Content blocked by safety filters - Try rephrasing your text";
}
if (errorMsg.includes('400')) {
return "Invalid request - Please check your text and try again";
}
if (errorMsg.includes('401') || errorMsg.includes('403')) {
return "API key invalid or expired - Please update your API key in settings";
}
if (errorMsg.includes('404')) {
return "API endpoint not found - The selected model may not be available";
}
if (errorMsg.includes('500') || errorMsg.includes('502') || errorMsg.includes('503')) {
return "Server error - Please try again later";
}
return "Something went wrong - Please try again";
}
// Helper function to track usage statistics
async function trackUsage(mode, originalLength, rewrittenLength) {
try {
const stats = await new Promise((resolve) => {
chrome.storage.local.get(['usageStats'], (result) => {
resolve(result.usageStats || {
totalRewrites: 0,
modeUsage: {},
charactersProcessed: 0,
charactersGenerated: 0
});
});
});
stats.totalRewrites++;
stats.modeUsage[mode] = (stats.modeUsage[mode] || 0) + 1;
stats.charactersProcessed += originalLength;
stats.charactersGenerated += rewrittenLength;
chrome.storage.local.set({ usageStats: stats });
} catch (error) {
console.error("Error tracking usage:", error);
}
}
// Helper function to store text for undo functionality
function storeForUndo(tabId, frameId, originalText) {
const undoData = {
tabId,
frameId,
originalText,
timestamp: Date.now()
};
// Store in memory for quick access
rewriteHistory.unshift(undoData);
// Keep only last 10 items
if (rewriteHistory.length > 10) {
rewriteHistory = rewriteHistory.slice(0, 10);
}
}
// Helper function to handle undo functionality
async function handleUndo(tabId, frameId) {
const undoItem = rewriteHistory.find(item =>
item.tabId === tabId && item.frameId === (frameId || 0)
);
if (!undoItem) {
notifyUser(tabId, "⚠️ No text to undo", true);
return;
}
try {
await injectTextIntoPage(tabId, frameId || 0, undoItem.originalText);
// Remove from history
const index = rewriteHistory.indexOf(undoItem);
if (index > -1) {
rewriteHistory.splice(index, 1);
}
notifyUser(tabId, "↶ Text restored", false, 2000);
} catch (error) {
console.error("Undo failed:", error);
notifyUser(tabId, "❌ Undo failed", true);
}
}
// Helper function to check rate limiting
function checkRateLimit() {
const now = Date.now();
// Check burst rate limiting (max 5 requests in 10 seconds)
if (now - lastBurstTime > CONFIG.RATE_LIMIT.burstWindow) {
burstRequestCount = 0;
lastBurstTime = now;
}
if (burstRequestCount >= CONFIG.RATE_LIMIT.burstLimit) {
return false;
}
// Check overall rate limiting (max 60 requests per minute)
if (now - lastRequestTime > CONFIG.RATE_LIMIT.windowMs) {
requestCount = 0;
lastRequestTime = now;
}
if (requestCount >= CONFIG.RATE_LIMIT.requests) {
return false;
}
// Increment counters
requestCount++;
burstRequestCount++;
return true;
}
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
// Handle special actions
if (info.menuItemId === `${CONTEXT_MENU_ID}_undo`) {
await handleUndo(tab.id, info.frameId);
return;
}
if (info.menuItemId === `${CONTEXT_MENU_ID}_settings`) {
chrome.runtime.openOptionsPage();
return;
}
// Ensure the click is one of our rewrite menus
if (!info.parentMenuItemId || info.parentMenuItemId !== CONTEXT_MENU_ID) {
return;
}
// Validate tab and URL
if (!isValidTab(tab)) {
console.warn(`AI Rewriter cannot run on this URL: ${tab?.url || 'unknown'}`);
notifyUser(tab.id, "❌ Cannot rewrite text on this page (restricted URL)", true);
return;
}
// Validate text selection
if (!info.selectionText || info.selectionText.trim() === "") {
const isComposer = info.menuItemId.includes('composer');
const message = isComposer
? "Please select an instruction first (e.g., 'write email asking for update')"
: "Please select text to rewrite";
notifyUser(tab.id, `⚠️ ${message}`, true);
return;
}
// Check text length
const settings = await getSettings();
if (info.selectionText.length > settings.maxTextLength) {
notifyUser(tab.id, `⚠️ Text too long (max ${settings.maxTextLength} characters)`, true);
return;
}
// Parse mode
const modeInfo = parseModeFromMenuId(info.menuItemId);
if (!modeInfo) {
notifyUser(tab.id, "❌ Unknown rewrite mode", true);
return;
}
console.log(`Rewrite requested: Mode='${modeInfo.key}', Text length=${info.selectionText.length}, URL: ${tab.url}`);
// Check rate limiting
if (!checkRateLimit()) {
notifyUser(tab.id, "⏳ Too many requests. Please wait a moment.", true);
return;
}
// Perform rewrite
await performRewrite(tab, info, modeInfo, settings);
});
async function performRewrite(tab, info, modeInfo, settings) {
try {
// Validate API key first
if (!settings.openaiApiKey || settings.openaiApiKey.trim() === '') {
notifyUser(tab.id, "❌ No API key configured - Click to open settings", true, 6000);
// Show setup notification
showApiKeyNotification();
return;
}
// Show progress notification
const modeName = modeInfo.type === 'builtin'
? BUILT_IN_MODES[modeInfo.key]?.name || modeInfo.key
: modeInfo.name || modeInfo.key;
notifyUser(tab.id, `🤖 Rewriting (${modeName})...`, false, 2000);
// Store original text for undo
if (settings.enableUndo) {
storeForUndo(tab.id, info.frameId || 0, info.selectionText);
}
// Call API
const resultText = await callOpenAIApiWithRetry(
settings.openaiApiKey,
settings.openaiBaseUrl,
info.selectionText,
modeInfo,
settings
);
if (resultText && resultText.trim()) {
// Check if preview mode is enabled
if (settings.enablePreviewMode) {
// Show preview popover instead of directly injecting
await showPreviewPopover(tab.id, info.frameId || 0, info.selectionText, resultText, modeInfo.key, settings);
} else {
// Direct injection (old behavior)
await injectTextIntoPage(tab.id, info.frameId || 0, resultText);
if (settings.enableUsageTracking) {
await trackUsage(modeInfo.key, info.selectionText.length, resultText.length);
}
notifyUser(tab.id, "✅ Text rewritten successfully!", false, 2000);
}
} else {
throw new Error("Empty response from AI");
}
} catch (error) {
console.error(`Context menu rewrite failed:`, error);
const errorMsg = getUserFriendlyError(error);
notifyUser(tab.id, `❌ ${errorMsg}`, true);
// Show additional help for common errors
if (error.message && (error.message.includes('API key') || error.message.includes('401') || error.message.includes('403'))) {
setTimeout(() => {
showApiKeyNotification();
}, 2000);
}
}
}
// === ENHANCED API FUNCTIONS ===
async function callOpenAIApiWithRetry(apiKey, baseUrl, text, modeInfo, settings) {
// Validate API key
if (!apiKey || apiKey.trim() === '') {
throw new Error('API key not configured - Please add your OpenAI API key in settings');
}
// Basic API key format validation (OpenAI keys typically start with 'sk-')
if (!apiKey.startsWith('sk-') && !apiKey.startsWith('sess-')) {
console.warn('API key format might be incorrect - OpenAI keys typically start with sk-');
}
let lastError;
for (let attempt = 1; attempt <= CONFIG.MAX_RETRIES; attempt++) {
try {
console.log(`API call attempt ${attempt}/${CONFIG.MAX_RETRIES}`);
const result = await callOpenAIApi(apiKey, baseUrl, text, modeInfo, settings);
if (result && result.trim()) {
return result;
}
throw new Error("Empty response from API");
} catch (error) {
lastError = error;
console.warn(`API call attempt ${attempt} failed:`, error.message);
// Don't retry on certain errors
if (error.message.includes('401') || error.message.includes('403') ||
error.message.includes('API key') || error.message.includes('authentication') ||
error.message.includes('invalid key') || attempt === CONFIG.MAX_RETRIES) {
throw error;
}
// Wait before retry
if (attempt < CONFIG.MAX_RETRIES) {
await new Promise(resolve => setTimeout(resolve, CONFIG.RETRY_DELAY * attempt));
}
}
}
throw lastError;
}
async function callOpenAIApi(apiKey, baseUrl, text, modeInfo, settings) {
const model = settings.selectedModel || CONFIG.DEFAULT_MODEL;
// Use custom base URL if provided, otherwise use default OpenAI endpoint
// This allows any model name when using custom endpoints
const endpoint = baseUrl && baseUrl.trim() !== ''
? `${baseUrl.replace(/\/$/, '')}/chat/completions`
: (CONFIG.API_ENDPOINTS[model] || CONFIG.DEFAULT_ENDPOINT);
const prompt = await generatePrompt(text, modeInfo, settings);
const requestBody = {
model: model,
messages: [
{
role: "system",
content: "You are a helpful AI assistant that rewrites text according to specific instructions. Always respond with only the rewritten text, no explanations or additional formatting."
},
{
role: "user",
content: prompt
}
],
temperature: getTemperatureForMode(modeInfo.key),
max_tokens: 4096,
top_p: 0.8
};
console.log(`Sending request to OpenAI (${model})...`);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), CONFIG.REQUEST_TIMEOUT);
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify(requestBody),
signal: controller.signal
});
clearTimeout(timeout);
if (!response.ok) {
let errorBody = "Could not read error response";
try {
const errorData = await response.json();
errorBody = errorData.error?.message || JSON.stringify(errorData);
} catch (e) {
errorBody = await response.text();
}
throw new Error(`API request failed (${response.status}): ${errorBody}`);
}
const data = await response.json();
if (data.choices?.[0]?.message?.content) {
let resultText = data.choices[0].message.content.trim();
return postProcessResult(resultText, modeInfo.key);
} else {
throw new Error("Invalid API response structure");
}
} catch (error) {
clearTimeout(timeout);
if (error.name === 'AbortError') {
throw new Error("Request timeout - please try again");
}
throw error;
}
}
// === ENHANCED PROMPT GENERATION ===
async function generatePrompt(text, modeInfo, settings) {
const baseInstruction = `IMPORTANT: Respond with ONLY the final text result. No explanations, no markdown formatting, no bullet points, no preambles, no quotes around the result. Just the direct text output. CRITICAL: Preserve the original language of the input text - if the input is in a specific language, respond in that same language.`;
if (modeInfo.type === 'custom') {
const customMode = settings.customModes[modeInfo.key];
return `${customMode.prompt}\n\n${baseInstruction}\n\nInput text:\n"${text}"\n\nOutput:`;
}
// Enhanced built-in prompts with better context awareness
const prompts = {
humanize: `Rewrite this text to sound more natural and human-like. Use conversational language, vary sentence structures, and make it feel like a real person wrote it. Avoid overly formal or robotic phrasing. Add natural flow and personality while preserving the core message.`,
grammar: `Fix only the grammar, spelling, and punctuation errors in this text. Keep the original meaning, tone, and style exactly the same. Make minimal changes - only correct actual errors without changing the author's voice or intent.`,
professional: `Rewrite this text in a professional business tone. Use formal language, clear structure, and maintain credibility. Be concise and respectful while ensuring the message is authoritative and appropriate for a business context.`,
polite: `Rewrite this text to be more polite and courteous. Soften any direct language, add respectful phrasing like "please" and "thank you" where appropriate, and ensure a warm, considerate tone throughout.`,
casual: `Rewrite this text in a casual, friendly tone. Use informal language, contractions, and make it sound like a conversation between friends. Keep it relaxed and approachable while maintaining clarity.`,
confident: `Rewrite this text to sound more confident and assertive. Use strong, decisive language while maintaining professionalism. Eliminate uncertainty and make statements clear and authoritative.`,
empathetic: `Rewrite this text with an empathetic and understanding tone. Show care, consideration, and emotional awareness. Use language that demonstrates you understand and relate to the reader's situation.`,
persuasive: `Rewrite this text to be more persuasive and compelling. Use convincing language, logical flow, and motivating phrases. Structure arguments effectively and include compelling reasons to strengthen the message.`,
concise: `Rewrite this text to be more concise and clear. Remove unnecessary words, eliminate redundancy, simplify complex sentences, and get straight to the point while preserving all essential information.`,
detailed: `Rewrite this text to be more detailed and comprehensive. Add relevant information, examples, explanations, and context to make it more complete and informative without losing focus.`,
creative: `Rewrite this text to be more creative and engaging. Use vivid language, interesting metaphors, varied sentence structures, and captivating phrasing while keeping the core message intact.`,
technical: `Rewrite this text in a technical and precise manner. Use accurate terminology, clear specifications, proper technical language, and maintain professional technical standards appropriate for the subject matter.`,
academic: `Rewrite this text in an academic and scholarly style. Use formal academic language, proper citation style markers where appropriate, objective tone, and structured argumentation suitable for academic writing.`,
marketing: `Rewrite this text as engaging marketing copy. Use persuasive language, highlight benefits, create urgency or excitement, and make it compelling for the target audience while maintaining authenticity.`,
cheeky: `Rewrite this text with a playful, cheeky, and slightly sarcastic tone. Add wit and humor while keeping it appropriately irreverent. Make it entertaining while preserving the essential message.`,
newby: `Rewrite this text as if written by someone new to the topic. Use simpler language, show enthusiasm and curiosity, and include the perspective of someone learning about the subject for the first time.`,
composer: `Generate new content based on this instruction. Create original text that fulfills the request clearly and completely. If it's a request like "write email about...", create the full email content. If it's "ideas for...", provide a well-structured list.`,
translate: `Translate this text to clear, natural English. If it's already in English, improve the clarity, natural flow, and readability while preserving the original meaning and intent.`,
summarize: `Create a concise summary of this text. Extract the key points, main ideas, and essential information, presenting them clearly and briefly while maintaining the logical structure.`,
expand: `Expand and elaborate on this text. Add more detail, context, examples, and explanations to make it more comprehensive and thorough while maintaining the original focus and direction.`,
simplify: `Simplify this text to make it easier to understand. Use plain language, shorter sentences, common words, and clear explanations while preserving all the important information and meaning.`
};
const modePrompt = prompts[modeInfo.key] || prompts.humanize;
return `${modePrompt}\n\n${baseInstruction}\n\nInput text:\n"${text}"\n\nOutput:`;
}
function getTemperatureForMode(mode) {
const temperatures = {
grammar: 0.7,
professional: 0.8,
technical: 0.8,
academic: 0.8,
polite: 0.9,
translate: 0.9,
summarize: 0.9,
simplify: 0.9,
humanize: 1.0,
casual: 1.0,
confident: 1.0,
empathetic: 1.0,