-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
1720 lines (1454 loc) · 53.3 KB
/
background.js
File metadata and controls
1720 lines (1454 loc) · 53.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
// GodTabs Background Service Worker
// Handles extension lifecycle, tab management, and storage operations
// Initialize extension on installation
chrome.runtime.onInstalled.addListener(async (details) => {
console.log('GodTabs extension installed/updated');
// Initialize default settings
const defaultSettings = {
autoCloseDuplicates: false,
sessionBackupInterval: 30, // minutes
maxTabHistory: 100,
theme: 'auto',
enableKeyboardShortcuts: true,
showTabCount: true,
autoSaveEnabled: true,
autoSaveInterval: 60, // seconds
maxAutoSaveSnapshots: 10,
enableCrashRecovery: true,
autoRestoreOnStartup: true,
showRecoveryNotifications: true,
// Auto-close inactive tabs settings
autoCloseInactiveTabs: false,
inactiveTabTimeoutMinutes: 60, // 1 hour default
excludePinnedFromAutoClose: true,
excludeAudibleFromAutoClose: true,
notifyBeforeAutoClose: true,
protectedDomains: [] // Domains to never auto-close
};
// Set default settings if not already present
const existingSettings = await chrome.storage.sync.get('settings');
if (!existingSettings.settings) {
await chrome.storage.sync.set({ settings: defaultSettings });
}
// Initialize session storage
const sessions = await chrome.storage.local.get('sessions');
if (!sessions.sessions) {
await chrome.storage.local.set({ sessions: [] });
}
// Initialize workspace storage
const workspaces = await chrome.storage.local.get('workspaces');
if (!workspaces.workspaces) {
await chrome.storage.local.set({ workspaces: [] });
}
// Initialize auto-save storage
const autoSaveSnapshots = await chrome.storage.local.get('autoSaveSnapshots');
if (!autoSaveSnapshots.autoSaveSnapshots) {
await chrome.storage.local.set({ autoSaveSnapshots: [] });
}
const recoveryData = await chrome.storage.local.get('recoveryData');
if (!recoveryData.recoveryData) {
await chrome.storage.local.set({ recoveryData: {} });
}
// Initialize tab activity tracking storage
const tabActivity = await chrome.storage.local.get('tabActivity');
if (!tabActivity.tabActivity) {
await chrome.storage.local.set({ tabActivity: {} });
}
});
// Handle extension startup
chrome.runtime.onStartup.addListener(async () => {
console.log('GodTabs extension started');
// Crash detection and recovery
await detectAndRecoverFromCrash();
// Set extension running flag
await chrome.storage.local.set({ extensionRunning: true });
// Restore any auto-backup sessions if enabled
const settings = await chrome.storage.sync.get('settings');
if (settings.settings?.sessionBackupInterval > 0) {
scheduleSessionBackup(settings.settings.sessionBackupInterval);
}
// Initialize auto-save if enabled
if (settings.settings?.autoSaveEnabled) {
initializeAutoSave();
}
// Initialize inactive tab cleanup if enabled
if (settings.settings?.autoCloseInactiveTabs) {
initializeInactiveTabCleanup();
}
});
// Handle tab updates for various features
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.url) {
// Check for duplicate tabs if auto-close is enabled
const settings = await chrome.storage.sync.get('settings');
if (settings.settings?.autoCloseDuplicates) {
await closeDuplicateTabs(tab);
}
// Update tab history
await updateTabHistory(tab);
// Update tab activity tracking
await updateTabActivity(tabId);
}
});
// Handle tab activation for activity tracking
chrome.tabs.onActivated.addListener(async (activeInfo) => {
await updateTabActivity(activeInfo.tabId);
});
// Handle tab creation for activity tracking
chrome.tabs.onCreated.addListener(async (tab) => {
await updateTabActivity(tab.id);
});
// Handle tab removal to clean up activity data
chrome.tabs.onRemoved.addListener(async (tabId) => {
await cleanupTabActivity(tabId);
});
// Handle keyboard commands
chrome.commands.onCommand.addListener(async (command) => {
console.log('Command received:', command);
switch (command) {
case 'save_session':
await saveCurrentSession();
break;
case 'create_workspace':
await createCurrentWorkspace();
break;
case 'switch_workspace':
await cycleThroughWorkspaces();
break;
default:
console.log('Unknown command:', command);
}
});
// Tab management functions
async function closeDuplicateTabs(currentTab) {
try {
const tabs = await chrome.tabs.query({});
const duplicates = tabs.filter(tab =>
tab.url === currentTab.url &&
tab.id !== currentTab.id &&
!tab.pinned
);
if (duplicates.length > 0) {
const tabIds = duplicates.map(tab => tab.id);
await chrome.tabs.remove(tabIds);
console.log(`Closed ${duplicates.length} duplicate tabs`);
}
} catch (error) {
console.error('Error closing duplicate tabs:', error);
}
}
async function closeAllDuplicates() {
try {
const tabs = await chrome.tabs.query({});
const urlMap = new Map();
const duplicates = [];
tabs.forEach(tab => {
if (tab.url && !tab.pinned) {
if (urlMap.has(tab.url)) {
duplicates.push(tab.id);
} else {
urlMap.set(tab.url, tab.id);
}
}
});
if (duplicates.length > 0) {
await chrome.tabs.remove(duplicates);
showNotification(`Closed ${duplicates.length} duplicate tabs`);
}
} catch (error) {
console.error('Error closing all duplicates:', error);
}
}
// Session management functions
async function saveCurrentSession() {
try {
const tabs = await chrome.tabs.query({});
const session = {
id: Date.now().toString(),
name: `Session ${new Date().toLocaleString()}`,
timestamp: Date.now(),
tabs: tabs.map(tab => ({
url: tab.url,
title: tab.title,
pinned: tab.pinned,
active: tab.active
}))
};
const { sessions = [] } = await chrome.storage.local.get('sessions');
sessions.unshift(session);
// Keep only the latest 50 sessions
if (sessions.length > 50) {
sessions.splice(50);
}
await chrome.storage.local.set({ sessions });
showNotification('Session saved successfully');
} catch (error) {
console.error('Error saving session:', error);
}
}
async function restoreLastSession() {
try {
const { sessions = [] } = await chrome.storage.local.get('sessions');
if (sessions.length === 0) {
showNotification('No saved sessions found');
return;
}
const lastSession = sessions[0];
for (const tabData of lastSession.tabs) {
await chrome.tabs.create({
url: tabData.url,
pinned: tabData.pinned,
active: false
});
}
showNotification(`Restored session: ${lastSession.name}`);
} catch (error) {
console.error('Error restoring session:', error);
}
}
// Tab history management
async function updateTabHistory(tab) {
try {
const { tabHistory = [] } = await chrome.storage.local.get('tabHistory');
// Remove existing entry for this URL
const filteredHistory = tabHistory.filter(entry => entry.url !== tab.url);
// Add new entry at the beginning
filteredHistory.unshift({
url: tab.url,
title: tab.title,
timestamp: Date.now(),
favicon: tab.favIconUrl
});
// Keep only the latest entries based on settings
const settings = await chrome.storage.sync.get('settings');
const maxHistory = settings.settings?.maxTabHistory || 100;
if (filteredHistory.length > maxHistory) {
filteredHistory.splice(maxHistory);
}
await chrome.storage.local.set({ tabHistory: filteredHistory });
} catch (error) {
console.error('Error updating tab history:', error);
}
}
// Tab activity tracking for auto-suspend inactive tabs
async function updateTabActivity(tabId) {
try {
const now = Date.now();
const { tabActivity = {} } = await chrome.storage.local.get('tabActivity');
// Update the last accessed time for this tab
tabActivity[tabId] = {
lastAccessed: now,
createdAt: tabActivity[tabId]?.createdAt || now,
suspended: false, // Mark as active when accessed
suspendedAt: null
};
await chrome.storage.local.set({ tabActivity });
} catch (error) {
console.error('Error updating tab activity:', error);
}
}
async function cleanupTabActivity(tabId) {
try {
const { tabActivity = {} } = await chrome.storage.local.get('tabActivity');
if (tabActivity[tabId]) {
delete tabActivity[tabId];
await chrome.storage.local.set({ tabActivity });
}
} catch (error) {
console.error('Error cleaning up tab activity:', error);
}
}
// Session backup scheduling
function scheduleSessionBackup(intervalMinutes) {
setInterval(async () => {
await saveCurrentSession();
}, intervalMinutes * 60 * 1000);
}
// Auto-save functionality
let autoSaveTimer = null;
let autoSaveInitMutex = false;
const AUTO_SAVE_DEBOUNCE_MS = 5000; // Minimum time between auto-save attempts
/**
* Initializes the auto-save system with efficient, non-blocking operation
* Sets up interval timer and handles configuration changes gracefully
* Uses mutex pattern to prevent race conditions
*/
async function initializeAutoSave() {
// Prevent concurrent initialization
if (autoSaveInitMutex) {
console.log('Auto-save initialization already in progress, skipping');
return;
}
autoSaveInitMutex = true;
try {
// Get current settings with fallback defaults
const settings = await chrome.storage.sync.get('settings');
const interval = Math.max(settings.settings?.autoSaveInterval || 60, 10); // Minimum 10 seconds
// Clear existing timer to prevent multiple timers
if (autoSaveTimer) {
clearInterval(autoSaveTimer);
autoSaveTimer = null;
}
// Only initialize if auto-save is enabled
if (!settings.settings?.autoSaveEnabled) {
console.log('Auto-save is disabled, skipping initialization');
return;
}
// Start non-blocking auto-save timer
autoSaveTimer = setInterval(() => {
// Use setTimeout to make the snapshot creation non-blocking
setTimeout(() => {
createWorkspaceSnapshot().catch(error => {
console.error('Auto-save snapshot creation failed:', error);
});
}, 0);
}, interval * 1000);
console.log(`Auto-save initialized with ${interval}s interval`);
} catch (error) {
console.error('Error initializing auto-save:', error);
// Ensure timer is cleared on error
if (autoSaveTimer) {
clearInterval(autoSaveTimer);
autoSaveTimer = null;
}
} finally {
autoSaveInitMutex = false;
}
}
/**
* Creates a workspace snapshot with efficient, atomic operation
* Prevents data corruption by using temporary storage and atomic swaps
* Implements debouncing to avoid excessive snapshot creation
*/
async function createWorkspaceSnapshot() {
// Check if auto-save is temporarily disabled due to failures
const now = Date.now();
if (autoSaveDisabledUntil > now) {
console.log(`Auto-save disabled until ${new Date(autoSaveDisabledUntil).toISOString()}, skipping snapshot`);
return;
}
// Debounce: Skip if another save is in progress or too recent
if (isAutoSaveInProgress || (now - lastAutoSaveAttempt) < AUTO_SAVE_DEBOUNCE_MS) {
console.log('Auto-save skipped: operation in progress or too recent');
return;
}
// Set flags to prevent concurrent operations
isAutoSaveInProgress = true;
lastAutoSaveAttempt = now;
let tempSnapshot = null;
try {
// Step 1: Check if auto-save is still enabled (settings might have changed)
const settings = await chrome.storage.sync.get('settings');
if (!settings.settings?.autoSaveEnabled) {
console.log('Auto-save disabled during snapshot creation, aborting');
return;
}
// Step 2: Gather data efficiently using Promise.all for parallel operations
const [tabs, workspaces] = await Promise.all([
chrome.tabs.query({}),
chrome.storage.local.get('workspaces')
]);
// Step 3: Filter and process tabs efficiently
const validTabs = tabs.filter(tab =>
tab.url &&
!tab.url.startsWith('chrome://') &&
!tab.url.startsWith('chrome-extension://') &&
!tab.url.startsWith('moz-extension://')
);
// Step 4: Create snapshot object with comprehensive metadata
const snapshotId = `snapshot_${now}_${Math.random().toString(36).substr(2, 9)}`;
tempSnapshot = {
id: snapshotId,
timestamp: now,
sessionId: `session_${now}`,
version: '1.1', // Updated version for new format
workspaces: workspaces.workspaces || [],
tabs: validTabs.map(tab => ({
id: tab.id,
url: tab.url,
title: tab.title,
favIconUrl: tab.favIconUrl,
pinned: tab.pinned,
windowId: tab.windowId,
index: tab.index,
active: tab.active
})),
metadata: {
totalTabs: validTabs.length,
totalWorkspaces: (workspaces.workspaces || []).length,
userAgent: navigator.userAgent,
extensionVersion: chrome.runtime.getManifest().version,
createdAt: new Date(now).toISOString(),
platform: 'chrome-extension'
}
};
// Step 5: Validate snapshot integrity before saving
if (!validateWorkspaceSnapshot(tempSnapshot)) {
throw new Error('Snapshot validation failed');
}
// Step 6: Save using atomic operation to prevent corruption
await saveWorkspaceSnapshotAtomic(tempSnapshot);
console.log(`Auto-save completed successfully: ${snapshotId} (${validTabs.length} tabs, ${(workspaces.workspaces || []).length} workspaces)`);
} catch (error) {
console.error('Error creating workspace snapshot:', error);
// Step 7: Attempt cleanup of any partial data if temp snapshot was created
if (tempSnapshot) {
try {
await cleanupFailedSnapshot(tempSnapshot.id);
} catch (cleanupError) {
console.error('Failed to cleanup after snapshot error:', cleanupError);
}
}
// Optional: Disable auto-save temporarily if there are repeated failures
await handleAutoSaveFailure(error);
} finally {
// Always reset the progress flag
isAutoSaveInProgress = false;
}
}
/**
* Enhanced snapshot validation with comprehensive checks
* Ensures data integrity before storage operations
*/
function validateWorkspaceSnapshot(snapshot) {
try {
// Basic structure validation
if (!snapshot || typeof snapshot !== 'object') {
console.error('Snapshot validation failed: invalid snapshot object');
return false;
}
// Required field validation
const requiredFields = ['id', 'timestamp', 'sessionId', 'version', 'workspaces', 'tabs', 'metadata'];
for (const field of requiredFields) {
if (!(field in snapshot)) {
console.error(`Snapshot validation failed: missing required field '${field}'`);
return false;
}
}
// Type validation
if (!Array.isArray(snapshot.workspaces)) {
console.error('Snapshot validation failed: workspaces must be an array');
return false;
}
if (!Array.isArray(snapshot.tabs)) {
console.error('Snapshot validation failed: tabs must be an array');
return false;
}
if (typeof snapshot.timestamp !== 'number' || snapshot.timestamp <= 0) {
console.error('Snapshot validation failed: invalid timestamp');
return false;
}
// Data size validation (prevent excessive memory usage)
const maxTabs = 1000;
const maxWorkspaces = 100;
if (snapshot.tabs.length > maxTabs) {
console.warn(`Snapshot has ${snapshot.tabs.length} tabs, exceeding maximum of ${maxTabs}`);
return false;
}
if (snapshot.workspaces.length > maxWorkspaces) {
console.warn(`Snapshot has ${snapshot.workspaces.length} workspaces, exceeding maximum of ${maxWorkspaces}`);
return false;
}
// Tab validation
for (const tab of snapshot.tabs) {
if (!tab.url || typeof tab.url !== 'string') {
console.error('Snapshot validation failed: tab missing valid URL');
return false;
}
}
return true;
} catch (error) {
console.error('Error during snapshot validation:', error);
return false;
}
}
/**
* Atomic snapshot saving operation to prevent data corruption
* Uses temporary storage and atomic swaps to ensure data integrity
*/
async function saveWorkspaceSnapshotAtomic(snapshot) {
const tempKey = `temp_snapshot_${snapshot.id}`;
try {
// Step 1: Get current snapshots and settings
const [currentData, settings] = await Promise.all([
chrome.storage.local.get('autoSaveSnapshots'),
chrome.storage.sync.get('settings')
]);
const autoSaveSnapshots = currentData.autoSaveSnapshots || [];
const maxSnapshots = Math.max(settings.settings?.maxAutoSaveSnapshots || 10, 1);
// Step 2: Save snapshot to temporary location first
await chrome.storage.local.set({ [tempKey]: snapshot });
// Step 3: Verify temporary save was successful
const tempVerification = await chrome.storage.local.get(tempKey);
if (!tempVerification[tempKey] || tempVerification[tempKey].id !== snapshot.id) {
throw new Error('Temporary snapshot save verification failed');
}
// Step 4: Prepare new snapshots array
const newSnapshots = [snapshot, ...autoSaveSnapshots];
// Step 5: Trim to maximum allowed snapshots
if (newSnapshots.length > maxSnapshots) {
newSnapshots.splice(maxSnapshots);
}
// Step 6: Atomically update the main snapshots array
await chrome.storage.local.set({ autoSaveSnapshots: newSnapshots });
// Step 7: Verify main save was successful
const verification = await chrome.storage.local.get('autoSaveSnapshots');
const savedSnapshot = verification.autoSaveSnapshots?.[0];
if (!savedSnapshot || savedSnapshot.id !== snapshot.id) {
throw new Error('Main snapshot save verification failed');
}
// Step 8: Clean up temporary storage
await chrome.storage.local.remove(tempKey);
// Step 9: Reset failure tracking on successful save
resetAutoSaveFailureTracking();
console.log(`Snapshot saved atomically: ${snapshot.id} (${newSnapshots.length}/${maxSnapshots} snapshots)`);
} catch (error) {
// Cleanup temporary storage on error
try {
await chrome.storage.local.remove(tempKey);
} catch (cleanupError) {
console.error('Failed to cleanup temporary snapshot:', cleanupError);
}
throw new Error(`Atomic snapshot save failed: ${error.message}`);
}
}
/**
* Legacy snapshot saving function - kept for backward compatibility
* @deprecated Use saveWorkspaceSnapshotAtomic instead
*/
async function saveWorkspaceSnapshot(snapshot) {
console.warn('Using deprecated saveWorkspaceSnapshot - consider upgrading to saveWorkspaceSnapshotAtomic');
return saveWorkspaceSnapshotAtomic(snapshot);
}
/**
* Cleans up failed snapshot data to prevent storage pollution
* Removes any temporary or corrupted snapshot entries
*/
async function cleanupFailedSnapshot(snapshotId) {
try {
const tempKey = `temp_snapshot_${snapshotId}`;
// Remove any temporary storage
await chrome.storage.local.remove(tempKey);
// Check if the failed snapshot made it into the main array
const { autoSaveSnapshots = [] } = await chrome.storage.local.get('autoSaveSnapshots');
const filteredSnapshots = autoSaveSnapshots.filter(snapshot =>
snapshot && snapshot.id !== snapshotId
);
// Update storage if we found and removed the corrupted snapshot
if (filteredSnapshots.length !== autoSaveSnapshots.length) {
await chrome.storage.local.set({ autoSaveSnapshots: filteredSnapshots });
console.log(`Cleaned up corrupted snapshot: ${snapshotId}`);
}
} catch (error) {
console.error(`Failed to cleanup snapshot ${snapshotId}:`, error);
}
}
/**
* Handles auto-save failures with intelligent retry and fallback mechanisms
* Implements exponential backoff and temporary disabling for repeated failures
*/
let autoSaveFailureCount = 0;
let autoSaveDisabledUntil = 0;
const MAX_CONSECUTIVE_FAILURES = 3;
const FAILURE_TIMEOUT_MS = 300000; // 5 minutes
async function handleAutoSaveFailure(error) {
try {
autoSaveFailureCount++;
const now = Date.now();
console.error(`Auto-save failure #${autoSaveFailureCount}:`, error.message);
// If we've had too many consecutive failures, temporarily disable auto-save
if (autoSaveFailureCount >= MAX_CONSECUTIVE_FAILURES) {
autoSaveDisabledUntil = now + FAILURE_TIMEOUT_MS;
// Clear the auto-save timer to stop further attempts
if (autoSaveTimer) {
clearInterval(autoSaveTimer);
autoSaveTimer = null;
}
console.warn(`Auto-save temporarily disabled due to ${autoSaveFailureCount} consecutive failures. Will re-enable at ${new Date(autoSaveDisabledUntil).toISOString()}`);
// Schedule re-initialization
setTimeout(() => {
initializeAutoSave().catch(err => {
console.error('Failed to re-initialize auto-save after failure timeout:', err);
});
}, FAILURE_TIMEOUT_MS);
} else {
// For sporadic failures, just log and continue
console.log(`Auto-save will continue, failure count: ${autoSaveFailureCount}/${MAX_CONSECUTIVE_FAILURES}`);
}
} catch (handlingError) {
console.error('Error while handling auto-save failure:', handlingError);
}
}
/**
* Resets auto-save failure tracking when a successful save occurs
* Called internally by saveWorkspaceSnapshotAtomic on success
*/
function resetAutoSaveFailureTracking() {
if (autoSaveFailureCount > 0) {
console.log(`Auto-save recovered after ${autoSaveFailureCount} failures`);
autoSaveFailureCount = 0;
autoSaveDisabledUntil = 0;
}
}
/**
* Manually triggers an auto-save snapshot creation
* Can be called from popup or options page for immediate backup
*/
async function triggerManualAutoSave() {
try {
console.log('Manual auto-save triggered');
// Temporarily reset failure tracking for manual saves
const originalFailureCount = autoSaveFailureCount;
autoSaveFailureCount = 0;
autoSaveDisabledUntil = 0;
await createWorkspaceSnapshot();
console.log('Manual auto-save completed successfully');
return { success: true, message: 'Auto-save completed successfully' };
} catch (error) {
// Restore original failure count if manual save fails
autoSaveFailureCount = originalFailureCount;
console.error('Manual auto-save failed:', error);
return { success: false, message: `Auto-save failed: ${error.message}` };
}
}
/**
* Handles auto-save settings changes and reinitializes if needed
* Called when user changes auto-save settings in options page
*/
async function handleAutoSaveSettingsChange(newSettings) {
try {
console.log('Auto-save settings changed, reinitializing...');
// Clear existing timer
if (autoSaveTimer) {
clearInterval(autoSaveTimer);
autoSaveTimer = null;
}
// Reset failure tracking on settings change
resetAutoSaveFailureTracking();
// Reinitialize with new settings if enabled
if (newSettings.autoSaveEnabled) {
await initializeAutoSave();
} else {
console.log('Auto-save disabled by user settings');
}
} catch (error) {
console.error('Error handling auto-save settings change:', error);
}
}
// Inactive tabs cleanup functionality
let inactiveTabsTimer = null;
let inactiveTabsInitMutex = false;
/**
* Initializes the inactive tabs cleanup system
* Sets up periodic checks to suspend tabs that exceed the inactivity timeout
* Uses mutex pattern to prevent race conditions
*/
async function initializeInactiveTabCleanup() {
// Prevent concurrent initialization
if (inactiveTabsInitMutex) {
console.log('Inactive tabs cleanup initialization already in progress, skipping');
return;
}
inactiveTabsInitMutex = true;
try {
const settings = await chrome.storage.sync.get('settings');
// Clear existing timer if any
if (inactiveTabsTimer) {
clearInterval(inactiveTabsTimer);
inactiveTabsTimer = null;
}
// Only initialize if auto-suspend is enabled
if (!settings.settings?.autoCloseInactiveTabs) {
console.log('Auto-suspend inactive tabs is disabled, skipping initialization');
return;
}
// Check for inactive tabs every 5 minutes
const checkInterval = 5 * 60 * 1000; // 5 minutes
inactiveTabsTimer = setInterval(async () => {
await checkAndCloseInactiveTabs();
}, checkInterval);
console.log('Inactive tabs cleanup initialized with 5-minute check interval');
} catch (error) {
console.error('Error initializing inactive tabs cleanup:', error);
if (inactiveTabsTimer) {
clearInterval(inactiveTabsTimer);
inactiveTabsTimer = null;
}
} finally {
inactiveTabsInitMutex = false;
}
}
/**
* Checks for inactive tabs and suspends them based on user settings
* Implements smart exclusions for pinned tabs, audio tabs, and protected domains
*/
async function checkAndCloseInactiveTabs() {
try {
const settings = await chrome.storage.sync.get('settings');
// Double-check if feature is still enabled
if (!settings.settings?.autoCloseInactiveTabs) {
return;
}
const timeoutMinutes = settings.settings?.inactiveTabTimeoutMinutes || 60;
const timeoutMs = timeoutMinutes * 60 * 1000;
const now = Date.now();
// Get all tabs and activity data
const [tabs, { tabActivity = {} }] = await Promise.all([
chrome.tabs.query({}),
chrome.storage.local.get('tabActivity')
]);
const tabsToSuspend = [];
const protectedDomains = settings.settings?.protectedDomains || [];
for (const tab of tabs) {
// Skip if tab should be excluded or is already discarded
if (shouldExcludeFromAutoClose(tab, settings.settings, protectedDomains) || tab.discarded) {
continue;
}
// Check if tab is inactive
const activity = tabActivity[tab.id];
if (!activity) {
// If no activity record, assume it's old and create one
await updateTabActivity(tab.id);
continue;
}
const inactiveTime = now - activity.lastAccessed;
if (inactiveTime > timeoutMs) {
tabsToSuspend.push(tab);
}
}
if (tabsToSuspend.length > 0) {
await processInactiveTabsForSuspension(tabsToSuspend, settings.settings);
}
} catch (error) {
console.error('Error checking inactive tabs:', error);
}
}
/**
* Determines if a tab should be excluded from auto-suspend
*/
function shouldExcludeFromAutoClose(tab, settings, protectedDomains) {
// Always exclude special Chrome pages
if (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://')) {
return true;
}
// Always exclude the active tab
if (tab.active) {
return true;
}
// Exclude pinned tabs if setting is enabled
if (settings.excludePinnedFromAutoClose && tab.pinned) {
return true;
}
// Exclude audible tabs (playing audio) if setting is enabled
if (settings.excludeAudibleFromAutoClose && tab.audible) {
return true;
}
// Exclude tabs with important states
if (tab.status === 'loading') {
return true;
}
// Exclude protected domains
if (protectedDomains.length > 0) {
try {
const url = new URL(tab.url);
const domain = url.hostname;
if (protectedDomains.some(protected => {
// Support wildcard matching
if (protected.startsWith('*.')) {
const baseDomain = protected.substring(2);
return domain.endsWith(baseDomain);
}
return domain === protected;
})) {
return true;
}
} catch (error) {
// Invalid URL, skip protection check
}
}
return false;
}
/**
* Processes inactive tabs for suspension with optional notifications
*/
async function processInactiveTabsForSuspension(tabsToSuspend, settings) {
try {
if (settings.notifyBeforeAutoClose) {
// Show notification before suspending tabs
await showInactiveTabsNotification(tabsToSuspend.length, 'suspend');
// Delay suspension to give user time to see notification
setTimeout(async () => {
await suspendInactiveTabs(tabsToSuspend);
}, 3000); // 3 second delay
} else {
// Suspend immediately without notification
await suspendInactiveTabs(tabsToSuspend);
}
} catch (error) {
console.error('Error processing inactive tabs for suspension:', error);
}
}
/**
* Suspends (discards) inactive tabs to free memory while preserving tab state
*/
async function suspendInactiveTabs(tabsToSuspend) {
try {
const tabIds = tabsToSuspend.map(tab => tab.id);
if (tabIds.length > 0) {
// Suspend the tabs using chrome.tabs.discard API
for (const tabId of tabIds) {
try {
await chrome.tabs.discard(tabId);
} catch (error) {
console.error(`Failed to suspend tab ${tabId}:`, error);
}
}
// Update activity data to mark as suspended (don't clean up completely)
const { tabActivity = {} } = await chrome.storage.local.get('tabActivity');
for (const tabId of tabIds) {
if (tabActivity[tabId]) {
tabActivity[tabId].suspended = true;
tabActivity[tabId].suspendedAt = Date.now();
}
}
await chrome.storage.local.set({ tabActivity });
console.log(`Auto-suspended ${tabIds.length} inactive tabs`);
}
} catch (error) {
console.error('Error suspending inactive tabs:', error);
}
}
/**
* Shows notification about inactive tabs being suspended or closed
*/
async function showInactiveTabsNotification(count, action = 'suspend') {
try {
const actionText = action === 'suspend' ? 'Suspending' : 'Closing';
const description = action === 'suspend' ?
'due to inactivity. Click to restore when needed.' :
'due to inactivity.';
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon48.png',
title: 'GodTabs Auto-Suspend',
message: `${actionText} ${count} inactive tab${count > 1 ? 's' : ''} ${description}`
});
} catch (error) {
console.error('Error showing inactive tabs notification:', error);
}
}
/**
* Handles inactive tabs settings changes and reinitializes if needed
*/
async function handleInactiveTabsSettingsChange(newSettings) {
try {