-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground-memory.js
More file actions
942 lines (896 loc) · 43.5 KB
/
Copy pathbackground-memory.js
File metadata and controls
942 lines (896 loc) · 43.5 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
/* WardenOne — Copyright (C) 2026 iri
Licensed under the GNU General Public License v3 or later. See LICENSE.
Official source: https://github.com/iri-dev/WardenOne
Upstream filter-list attribution: CREDITS.md
Redistributing a modified copy? GPLv3 section 5(a) requires you to mark it as changed,
with the date, and to keep these notices intact. */
/*
* WardenOne Memory Shield runtime
* =================================
* Owns tab sleeping, RAM scoring, duplicate/zombie tab helpers, tab-limit
* enforcement, and popup-facing memory actions. Loaded by background.js with
* importScripts() so the MV3 worker keeps a smaller main file.
*/
// ======================= Memory Shield =======================
// Saves RAM by DISCARDING (sleeping) inactive tabs via chrome.tabs.discard().
// A discarded tab stays in the tab strip and reloads when clicked -- nothing is
// closed or lost. We track per-tab last-active time and, on a periodic sweep,
// discard tabs that are safe AND have been inactive past the mode's threshold.
const MEMORY_MODES = {
gentle: { minutes: 120 },
balanced: { minutes: 30 },
aggressive: { minutes: 10 },
emergency: { minutes: 1 },
};
const MEMORY_DEFAULTS = {
memoryShield: true,
memoryMode: 'balanced',
memoryMinutesOverride: 0, // 0 = use the mode's default; else explicit minutes
memoryNeverPinned: true,
memoryNeverAudio: true,
memoryNeverForms: true,
memoryNeverPayment: true,
// Sites the reader marked "never sleep this" themselves, from the right-click menu.
// Exact hosts only -- see MEMORY_NEVER_SLEEP_MAX for why it is not a wildcard.
memoryNeverSleepHosts: [],
// Tab Limit: keep tab count under a user cap by sleeping (or, opt-in,
// closing) the oldest inactive tab when a new tab crosses the limit.
tabLimitGuard: false,
tabLimitMax: 20,
tabLimitClose: false, // false = sleep (safe default); true = close (aggressive)
tabLimitMinIdleMinutes: 30, // a tab must be idle at least this long to be eligible
tabLimitWarn: true, // notify when a tab is closed
};
// last-active timestamp per tabId (in-memory; wiped on every SW restart)
const tabActivity = Object.create(null);
const markTabActive = (tabId) => { if (tabId != null) tabActivity[tabId] = Date.now(); };
// The single definition of "when was this tab last used", for every path that measures idle time.
//
// tabActivity is heap-only, and MV3 tears the worker down constantly -- the five-minute sweep alarm
// is itself what wakes a fresh one. Reading only that map meant a cold sweep saw no timestamps at
// all, fell back to "now", and concluded every tab had just been used. A 30-minute threshold was
// never reached, so automatic sleeping did essentially nothing while reporting success. Chrome's
// tab.lastAccessed survives restarts and is available from Chrome 121, which is the manifest
// minimum, so it is the durable half of the answer.
//
// The NEWER of the two, not "lastAccessed if it is set": the map also records navigations and audio
// in background tabs, which Chrome does not count as an access. Preferring lastAccessed outright
// would report such a tab as staler than it is, and that error runs in the direction that sleeps a
// tab someone is still using.
function tabLastUsedOrNull(tab) {
let best = null;
const persisted = Number(tab && tab.lastAccessed);
if (Number.isFinite(persisted) && persisted > 0) best = persisted;
const id = tab && tab.id;
const seen = id == null ? NaN : Number(tabActivity[id]);
if (Number.isFinite(seen) && seen > 0 && (best == null || seen > best)) best = seen;
return best;
}
// Unknown age counts as "just used", so a tab we know nothing about is never slept on that basis.
function tabLastUsed(tab, now) {
const known = tabLastUsedOrNull(tab);
return known == null ? (Number(now) || Date.now()) : known;
}
// keep activity fresh on the signals that mean "the user is using this tab"
try {
chrome.tabs.onActivated.addListener((info) => markTabActive(info.tabId));
chrome.tabs.onUpdated.addListener((tabId, change) => {
// A navigation, load or audio start is activity. Nothing else is.
//
// This used to also seed any tab it had never seen with "now", which mattered when the map was
// the only source of recency. With tab.lastAccessed in the picture it became harmful: the seed
// is the NEWER value, so a background tab that merely changed its title -- and plenty do, on a
// timer -- had its real idle age erased, once per service-worker restart.
if (change.status === 'loading' || change.url || change.audible) markTabActive(tabId);
});
chrome.tabs.onCreated.addListener((tab) => markTabActive(tab.id));
chrome.tabs.onRemoved.addListener((tabId) => { delete tabActivity[tabId]; });
// when a window gains focus, its active tab is "active"
chrome.windows?.onFocusChanged.addListener((winId) => {
if (winId === chrome.windows.WINDOW_ID_NONE) return;
chrome.tabs.query({ active: true, windowId: winId }, (tabs) => { if (tabs && tabs[0]) markTabActive(tabs[0].id); });
});
} catch (_) {}
async function getMemoryConfig() {
const store = await localGet('wardenone_config');
const cfg = (store && store.wardenone_config) || {};
const m = {};
for (const k in MEMORY_DEFAULTS) m[k] = (cfg[k] === undefined ? MEMORY_DEFAULTS[k] : cfg[k]);
// resolve threshold minutes
const mode = MEMORY_MODES[m.memoryMode] ? m.memoryMode : 'balanced';
m._minutes = m.memoryMinutesOverride > 0 ? m.memoryMinutesOverride : MEMORY_MODES[mode].minutes;
m._mode = mode;
// share the allowlist already used by the rest of the extension
m._allowlist = normalizeAllowlistHosts(cfg.allowlist || []);
m._neverSleep = normalizeAllowlistHosts(m.memoryNeverSleepHosts || [], MEMORY_NEVER_SLEEP_MAX);
return m;
}
// ---- "Never sleep this site" ------------------------------------------------------
//
// The reader's own keep-awake list, added and removed from the right-click menu.
//
// EXACT hosts, deliberately -- this is the one host list in the extension that does not
// match subdomains. Everywhere else a wildcard is a convenience; here it would make the
// menu lie. The entry has to say what removing it does, and with subdomain matching a
// right-click on mail.google.com could read "Never sleep mail.google.com" while it was
// already being kept awake by a google.com entry, and taking that entry away would
// silently change every other Google tab too. One host, one entry, one thing removed.
//
// Capped because it is written from a menu click, which is cheap to repeat, and this list
// is consulted on every sweep of every tab.
const MEMORY_NEVER_SLEEP_MAX = 300;
function memoryNeverSleepHas(list, host) {
// The empty case first. This runs per tab on every sweep, and for nearly every reader
// the list is empty forever -- there is no reason to normalise a hostname to compare it
// against nothing.
if (!Array.isArray(list) || !list.length) return false;
const h = normalizeAllowlistHost(host);
return !!h && list.indexOf(h) >= 0;
}
// Read the stored list on its own, for the menu title -- the sweep reads it through
// getMemoryConfig() like everything else.
async function memoryNeverSleepList() {
try {
const store = await localGet('wardenone_config');
const cfg = (store && store.wardenone_config) || {};
return normalizeAllowlistHosts(cfg.memoryNeverSleepHosts || [], MEMORY_NEVER_SLEEP_MAX);
} catch (_) { return []; }
}
// Add or remove one host. Read-modify-write against storage rather than against a cached
// copy, so a popup save that landed in between is not reverted by this one.
async function memoryToggleNeverSleep(host) {
const h = normalizeAllowlistHost(host);
if (!h) return { ok: false, error: 'WardenOne could not read a site from this page.' };
try {
const store = await localGet('wardenone_config');
const cfg = (store && store.wardenone_config) || {};
const list = normalizeAllowlistHosts(cfg.memoryNeverSleepHosts || [], MEMORY_NEVER_SLEEP_MAX);
const on = list.indexOf(h) >= 0;
if (!on && list.length >= MEMORY_NEVER_SLEEP_MAX) {
return { ok: false, error: 'Your never-sleep list is full at ' + MEMORY_NEVER_SLEEP_MAX
+ ' sites. Take one off it before adding another.' };
}
cfg.memoryNeverSleepHosts = on ? list.filter((d) => d !== h) : list.concat([h]);
await localSet({ wardenone_config: cfg });
return { ok: true, on: !on, host: h, shieldOn: cfg.memoryShield !== false };
} catch (e) { return { ok: false, error: String(e) }; }
}
// Is a tab safe to put to sleep? Returns null if safe, else a reason it was kept.
function tabKeepReason(tab, cfg) {
if (!tab || tab.discarded) return 'already asleep';
if (tab.active) return 'active tab';
if (tab.audible) return 'playing audio';
if (cfg.memoryNeverPinned && tab.pinned) return 'pinned';
const url = tab.url || tab.pendingUrl || '';
if (!/^https?:\/\//i.test(url)) return 'browser/internal page'; // chrome://, about:, extension pages, new tab
try {
const host = new URL(url).hostname;
// Asked for by name, so it outranks every rule below it -- including the ones that
// would have slept the tab for a reason the reader has already overruled.
if (memoryNeverSleepHas(cfg._neverSleep, host)) return 'you set never sleep';
if (isVideoPlatformHost(host)) return 'video/live playback site';
} catch (_) {}
// payment / banking / login pages -- never sleep mid-transaction
if (cfg.memoryNeverPayment && /(checkout|payment|pay|billing|bank|signin|sign-in|login|account\/|secure|wallet|paypal|stripe)/i.test(url)) return 'login/payment page';
// allowlisted sites (shared allowlist)
try {
const host = new URL(url).hostname;
if (hostMatchesAllowlist(host, cfg._allowlist || [])) return 'allowlisted';
} catch (_) {}
return null; // safe to discard (audio/camera covered by audible + the content-side form check below is best-effort)
}
// Ask a tab's bridge whether it has unsaved form input or active camera/mic.
//
// `ok` answers a different question from the other two: did we actually get an answer at all. It
// used not to exist, and every way of failing -- the 400ms timeout, runtime.lastError, a thrown
// send, a missing or malformed reply -- resolved to {formDirty:false, mediaActive:false}, which
// every caller then read as "checked it, the tab is clean". So a tab whose bridge was merely
// unreachable, because the extension had just reloaded or injection had not landed yet, was
// discarded as verified-safe. Discarding reloads the tab, so whatever was typed into it is gone,
// and the popup promises without qualification that unsaved-form tabs are never touched.
//
// Unknown is now unknown. Destructive callers must keep the tab; a caller that only throttles may
// still fail open, because the cost of being wrong there is a paused video.
const MEMORY_LIVE_CHECK_TIMEOUT_MS = 1000;
function tabLiveState(tabId) {
return new Promise((resolve) => {
let done = false;
let timer = 0;
const finish = (v) => {
if (done) return;
done = true;
if (timer) {
try { clearTimeout(timer); } catch (_) {}
timer = 0;
}
resolve(v);
};
const unknown = (why) => finish({ ok: false, why, formDirty: false, mediaActive: false });
// Longer than it was. 400ms was a fair budget while a timeout meant "sleep it anyway" -- being
// impatient cost nothing. Now a timeout keeps the tab, so the same impatience would quietly
// switch the feature off on exactly the busy tabs it exists for.
timer = setTimeout(() => unknown('timeout'), MEMORY_LIVE_CHECK_TIMEOUT_MS);
try {
chrome.tabs.sendMessage(tabId, { kind: 'memory-form-check' }, (res) => {
if (chrome.runtime.lastError) return unknown('unreachable');
if (!res || typeof res !== 'object') return unknown('malformed');
finish({ ok: true, why: '', formDirty: !!res.formDirty, mediaActive: !!res.mediaActive });
});
} catch (_) { unknown('send-failed'); }
});
}
const MEMORY_LIVE_CHECK_CONCURRENCY = 4;
async function mapLimited(items, limit, worker) {
const list = Array.isArray(items) ? items : [];
const max = Math.max(1, Math.min(Number(limit) || 1, list.length || 1));
const results = new Array(list.length);
let next = 0;
async function run() {
while (next < list.length) {
const index = next++;
try {
results[index] = await worker(list[index], index);
} catch (e) {
results[index] = { ok: false, error: String(e) };
}
}
}
const workers = [];
for (let i = 0; i < max; i++) workers.push(run());
await Promise.all(workers);
return results;
}
// Discard tabs that are safe and inactive past the threshold.
async function memorySweep(reason, cfgArg) {
try {
const cfg = cfgArg || await getMemoryConfig();
if (!cfg.memoryShield) return { ok: false, disabled: true };
const tabs = await chrome.tabs.query({});
const now = Date.now();
const thresholdMs = cfg._minutes * 60000;
const candidates = [];
for (const tab of tabs) {
const keep = tabKeepReason(tab, cfg);
if (keep) continue;
const last = tabLastUsed(tab, now);
const idleMs = now - last;
if (idleMs < thresholdMs) continue;
candidates.push({ tab, idleMs });
}
const results = await mapLimited(candidates, MEMORY_LIVE_CHECK_CONCURRENCY, async ({ tab, idleMs }) => {
// Check the tab's live state once. We always check active camera/mic (a live
// media tab must never be slept); the form-dirty check only applies when the
// user has form protection enabled.
const live = await tabLiveState(tab.id);
if (!live.ok) return null; // could not ask -- an unanswered tab is not a verified-clean one
if (live.mediaActive) return null; // active camera/mic -- never sleep
if (cfg.memoryNeverForms && live.formDirty) return null; // unsaved form input
try {
await chrome.tabs.discard(tab.id);
const host = (() => { try { return new URL(tab.url).hostname; } catch { return tab.url || ''; } })();
queueHistory({
type: 'memory_tab_slept',
detail: { host, idleMin: Math.round(idleMs / 60000), mode: cfg._mode },
url: host,
at: Date.now(),
});
return host;
} catch (_) { return null; /* tab may have closed or be undiscardable */ }
});
const sleptUrls = results.filter(Boolean);
const slept = sleptUrls.length;
return { ok: true, slept, sleptUrls, mode: cfg._mode, minutes: cfg._minutes };
} catch (e) {
return { ok: false, error: String(e) };
}
}
// Free RAM Now: sleep ALL safe inactive tabs immediately (ignores the time
// threshold, but still respects the protection rules).
async function freeRamNow() {
try {
const cfg = await getMemoryConfig();
const tabs = await chrome.tabs.query({});
let slept = 0, kept = 0; const keptReasons = {};
const candidates = [];
for (const tab of tabs) {
const keep = tabKeepReason(tab, cfg);
if (keep) { kept++; keptReasons[keep] = (keptReasons[keep] || 0) + 1; continue; }
candidates.push(tab);
}
const results = await mapLimited(candidates, MEMORY_LIVE_CHECK_CONCURRENCY, async (tab) => {
const live = await tabLiveState(tab.id);
if (!live.ok) return { kept: "couldn't check for unsaved work" };
if (cfg.memoryNeverForms && live.formDirty) return { kept: 'unsaved form' };
if (live.mediaActive) return { kept: 'camera/mic in use' };
try { await chrome.tabs.discard(tab.id); return { slept: true }; } catch (_) { return null; }
});
for (const result of results) {
if (result && result.slept) slept++;
else if (result && result.kept) {
kept++;
keptReasons[result.kept] = (keptReasons[result.kept] || 0) + 1;
}
}
queueHistory({ type: 'memory_free_ram', detail: { slept, kept }, url: '', at: Date.now() });
return { ok: true, slept, kept, keptReasons };
} catch (e) {
return { ok: false, error: String(e) };
}
}
// Duplicate-tab detector: group tabs by normalized URL.
async function findDuplicateTabs() {
try {
const tabs = await chrome.tabs.query({});
const byUrl = Object.create(null);
for (const tab of tabs) {
const u = (tab.url || '').split('#')[0];
if (!/^https?:/i.test(u)) continue;
(byUrl[u] = byUrl[u] || []).push({ id: tab.id, title: tab.title, active: tab.active });
}
const dups = [];
for (const u in byUrl) { if (byUrl[u].length > 1) dups.push({ url: u, count: byUrl[u].length, tabs: byUrl[u] }); }
const extra = dups.reduce((n, d) => n + (d.count - 1), 0);
return { ok: true, groups: dups, extraCount: extra };
} catch (e) { return { ok: false, error: String(e) }; }
}
// Close all-but-one of each duplicate URL (keeps the active one if present).
async function closeDuplicateTabs() {
try {
const { groups } = await findDuplicateTabs();
let closed = 0;
for (const g of (groups || [])) {
// keep the active tab, else the first
const keepId = (g.tabs.find((t) => t.active) || g.tabs[0]).id;
for (const t of g.tabs) {
if (t.id !== keepId) { try { await chrome.tabs.remove(t.id); closed++; } catch (_) {} }
}
}
if (closed) queueHistory({ type: 'memory_dupes_closed', detail: { closed }, url: '', at: Date.now() });
return { ok: true, closed };
} catch (e) { return { ok: false, error: String(e) }; }
}
// RAM score: a simple, honest rating from tab counts (we can't read real RAM).
const HEAVY_HOSTS = /(youtube\.com|twitch\.tv|discord\.com|docs\.google\.com|canva\.com|figma\.com|netflix\.com|hulu\.com|disneyplus\.com|spotify\.com|meet\.google\.com|teams\.microsoft\.com|notion\.so)/i;
async function memoryScore() {
try {
const tabs = await chrome.tabs.query({});
let total = 0, sleeping = 0, heavy = 0;
const now = Date.now();
const cfg = await getMemoryConfig();
const thresholdMs = cfg._minutes * 60000;
let sleepable = 0;
for (const tab of tabs) {
if (!/^https?:/i.test(tab.url || tab.pendingUrl || '') && !tab.discarded) { total++; continue; }
total++;
if (tab.discarded) { sleeping++; continue; }
if (HEAVY_HOSTS.test(tab.url || '')) heavy++;
const keep = tabKeepReason(tab, cfg);
const last = tabLastUsed(tab, now);
if (!keep && (now - last) >= thresholdMs) sleepable++;
}
const awake = total - sleeping;
// rough memory pressure label from awake + heavy tabs
let level = 'Low';
if (awake >= 25 || heavy >= 4) level = 'High';
else if (awake >= 10 || heavy >= 2) level = 'Medium';
// estimated savings available from sleeping the sleepable ones
let saved = 'Low';
if (sleepable >= 8 || (heavy >= 2 && sleepable >= 3)) saved = 'High';
else if (sleepable >= 3) saved = 'Medium';
return { ok: true, total, awake, sleeping, heavy, sleepable, level, saved, mode: cfg._mode, minutes: cfg._minutes };
} catch (e) { return { ok: false, error: String(e) }; }
}
// The five-minute wake-up exists for Memory Shield, so it should exist only when Memory Shield
// does. It used to be created at load whatever the setting said, so someone who had turned the
// feature off still paid for a service-worker wake every five minutes, forever, to look at the
// config and go back to sleep. Reconciled here and again whenever the setting changes.
//
// An unreadable config keeps the alarm rather than dropping it: failing to read storage should not
// quietly uninstall a feature the user turned on.
const MEMORY_SWEEP_ALARM = 'wardenone-memory-sweep';
async function reconcileMemorySweepAlarm(cfgArg) {
let wanted = true;
try {
const cfg = cfgArg || await getMemoryConfig();
wanted = !!(cfg && cfg.memoryShield);
} catch (_) {}
try {
if (wanted) chrome.alarms.create(MEMORY_SWEEP_ALARM, { periodInMinutes: 5 });
else await chrome.alarms.clear(MEMORY_SWEEP_ALARM);
} catch (_) {}
return wanted;
}
reconcileMemorySweepAlarm();
// ---- Tab Limit --------------------------------------------------------------
// When a newly-opened tab pushes a window past the user's limit, act on the
// oldest tab that has been inactive past the minimum idle time: sleep it
// (default, reversible) or close it (aggressive, opt-in). Every Memory Shield
// protection still applies via tabKeepReason() + tabLiveState(), so active,
// pinned, audio, unsaved-form, login/payment, allowlisted, and internal tabs are
// never touched. Sleeping doesn't reduce the tab count, so we only relieve the
// single stalest tab per trigger; closing brings the count back down to the cap.
const TAB_LIMIT_ENFORCE_TIMERS = Object.create(null);
const TAB_LIMIT_MAX_ACTIONS_PER_RUN = 5;
function fmtIdleMinutes(min) {
const m = Math.max(0, Math.round(min || 0));
if (m < 60) return m + 'm';
const h = Math.floor(m / 60);
const r = m % 60;
return r ? h + 'h ' + r + 'm' : h + 'h';
}
async function notifyTabLimitClosed(host, idleMin) {
if (!(await extensionUiAllowed())) return;
try {
await showWardenSystemNotification('wo-tablimit-' + Date.now(), {
type: 'basic',
iconUrl: 'icons/icon128.png',
title: 'Tab Limit',
message: 'Closed an old tab to stay under your limit: ' + (host || 'a tab')
+ (idleMin ? ' (inactive ' + fmtIdleMinutes(idleMin) + ')' : ''),
priority: 1,
}, 'tab_limit_closed');
} catch (_) {}
}
// A window can close inside the debounce. Nothing cleared its timer, so the handle and the window
// id stayed reachable until it fired and enforced a limit on a window that no longer exists.
try {
chrome.windows.onRemoved.addListener((windowId) => {
const timer = TAB_LIMIT_ENFORCE_TIMERS[windowId];
if (timer) clearTimeout(timer);
delete TAB_LIMIT_ENFORCE_TIMERS[windowId];
});
} catch (_) {}
function scheduleTabLimitCheck(windowId) {
if (windowId == null || windowId < 0) return;
if (TAB_LIMIT_ENFORCE_TIMERS[windowId]) clearTimeout(TAB_LIMIT_ENFORCE_TIMERS[windowId]);
// small debounce so opening several links at once enforces a single time
TAB_LIMIT_ENFORCE_TIMERS[windowId] = setTimeout(() => {
delete TAB_LIMIT_ENFORCE_TIMERS[windowId];
enforceTabLimit(windowId).catch(() => {});
}, 700);
}
async function enforceTabLimit(windowId) {
const cfg = await getMemoryConfig();
if (!cfg.tabLimitGuard) return;
const max = Math.max(2, parseInt(cfg.tabLimitMax, 10) || 0);
if (!max) return;
const close = !!cfg.tabLimitClose;
const minIdleMs = Math.max(0, Number(cfg.tabLimitMinIdleMinutes) || 0) * 60000;
const now = Date.now();
// only enforce in normal browser windows (not popups, panels, devtools)
try { const win = await chrome.windows.get(windowId); if (win && win.type && win.type !== 'normal') return; } catch (_) {}
let tabs;
try { tabs = await chrome.tabs.query({ windowId }); } catch (_) { return; }
if (!tabs || tabs.length <= max) return;
// Safe-to-act tabs (never active/pinned/audio/login/internal/allowlisted). Idle time
// comes from Chrome's PERSISTENT tab.lastAccessed -- the in-memory tabActivity map is
// wiped whenever the service worker restarts, which made every tab look "just active"
// (idle 0) so nothing ever qualified. Sorted most-stale (least-recently-used) first.
// Empty "New tab" / blank placeholder pages are disposable -- in CLOSE mode they are
// fair game for the cap even though they're internal pages (so a window full of New
// tabs actually gets trimmed). Never the active or pinned one.
const isDisposableTab = (tab) => {
const u = tab.url || tab.pendingUrl || '';
return u === '' || u === 'about:blank'
|| /^(chrome|edge|brave|chrome-search|about):\/?\/?(newtab|new-tab-page|local-ntp|blank)\b/i.test(u);
};
const safe = [];
for (const tab of tabs) {
const disposable = close && isDisposableTab(tab) && !tab.active && !tab.pinned;
if (tabKeepReason(tab, cfg) && !disposable) continue; // protected unless a disposable new-tab
if (!close && tab.discarded) continue; // already asleep -> its RAM is freed
const last = tabLastUsed(tab, now);
safe.push({ tab, idleMs: now - last, disposable });
}
if (!safe.length) return;
// close empty new-tab pages first, then the most-idle (least-recently-used) real tabs.
safe.sort((a, b) => (a.disposable !== b.disposable ? (a.disposable ? -1 : 1) : b.idleMs - a.idleMs));
const over = tabs.length - max;
let candidates;
if (close) {
// CLOSE is the aggressive hard cap the user opted into: enforce the limit by closing
// the least-recently-used non-protected tabs (idle ones first, since they're sorted
// that way), even if everything is recent. minIdle only gates SLEEP mode below.
candidates = safe.slice(0, Math.min(over, TAB_LIMIT_MAX_ACTIONS_PER_RUN));
} else {
// SLEEP stays gentle: only a genuinely-idle tab, just one per trigger.
candidates = safe.filter((s) => s.idleMs >= minIdleMs).slice(0, 1);
if (!candidates.length) return;
}
for (const { tab, idleMs } of candidates) {
// final live-state check right before acting (camera/mic, unsaved form)
const live = await tabLiveState(tab.id);
if (!live.ok) continue; // no answer is not the same as a clean answer, and this path can close
if (live.mediaActive) continue;
if (cfg.memoryNeverForms && live.formDirty) continue;
const host = (() => { try { return new URL(tab.url).hostname.replace(/^www\./, ''); } catch { return tab.url || ''; } })();
const idleMin = Math.round(idleMs / 60000);
try {
if (close) {
await chrome.tabs.remove(tab.id);
queueHistory({ type: 'tab_limit_closed', detail: { host, idleMin, max, count: tabs.length }, url: host, at: Date.now() });
if (cfg.tabLimitWarn) notifyTabLimitClosed(host, idleMin);
} else {
await chrome.tabs.discard(tab.id);
queueHistory({ type: 'tab_limit_slept', detail: { host, idleMin, max, count: tabs.length }, url: host, at: Date.now() });
}
} catch (_) { /* tab closed or can't be discarded -- skip */ }
}
}
// Enforce the tab limit across every normal window now -- used when the user enables
// the guard or changes the limit, so excess tabs are trimmed immediately instead of
// only on the next tab you open.
async function enforceTabLimitAllWindows() {
try {
const wins = await chrome.windows.getAll({ windowTypes: ['normal'] });
for (const w of wins) { if (w && w.id != null) enforceTabLimit(w.id).catch(() => {}); }
} catch (_) {}
}
try {
chrome.tabs.onCreated.addListener((tab) => { if (tab) scheduleTabLimitCheck(tab.windowId); });
} catch (_) {}
// ---- Heavy-tab detector: list currently-open heavy tabs (awake) ----
async function listHeavyTabs() {
try {
const tabs = await chrome.tabs.query({});
const heavy = [];
for (const tab of tabs) {
if (tab.discarded) continue;
const url = tab.url || '';
if (!/^https?:/i.test(url)) continue;
let host = ''; try { host = new URL(url).hostname.replace(/^www\./, ''); } catch (_) { continue; }
if (HEAVY_HOSTS.test(url)) {
heavy.push({ id: tab.id, host, title: (tab.title || host).slice(0, 60), active: tab.active, audible: !!tab.audible });
}
}
return { ok: true, heavy };
} catch (e) { return { ok: false, error: String(e) }; }
}
function tabMemoryPressure(tab, cfg, now) {
const url = tab.url || tab.pendingUrl || '';
let host = '';
try { host = new URL(url).hostname.replace(/^www\./, ''); } catch (_) {}
const last = tabLastUsed(tab, now);
const idleMin = Math.max(0, Math.round((now - last) / 60000));
const keep = tabKeepReason(tab, cfg);
let score = 0;
const reasons = [];
if (tab.discarded) {
reasons.push('already sleeping');
score -= 5;
}
if (tab.frozen) reasons.push('Chrome frozen');
if (HEAVY_HOSTS.test(url)) { score += 4; reasons.push('known heavy site'); }
if (/video|stream|canvas|editor|meeting|call|figma|canva|docs|spreadsheet|discord|teams|meet/i.test(String(tab.title || '') + ' ' + url)) {
score += 2;
if (!reasons.includes('known heavy site')) reasons.push('heavy-page signal');
}
if (idleMin >= 360) { score += 3; reasons.push('idle ' + fmtIdleMinutes(idleMin)); }
else if (idleMin >= 60) { score += 2; reasons.push('idle ' + fmtIdleMinutes(idleMin)); }
else if (idleMin >= 15) { score += 1; reasons.push('idle ' + fmtIdleMinutes(idleMin)); }
if (tab.audible) { score += 1; reasons.push('audio'); }
if (tab.pinned) reasons.push('pinned');
if (tab.active) reasons.push('active');
if (tab.autoDiscardable === false) reasons.push('Chrome auto-discard off');
if (keep && !reasons.includes(keep)) reasons.push(keep);
const impact = tab.discarded ? 'Sleeping' : score >= 6 ? 'High' : score >= 3 ? 'Medium' : 'Low';
return {
id: tab.id,
windowId: tab.windowId,
host,
title: (tab.title || host || 'Untitled tab').slice(0, 90),
url: url.slice(0, 500),
active: !!tab.active,
pinned: !!tab.pinned,
audible: !!tab.audible,
discarded: !!tab.discarded,
frozen: !!tab.frozen,
autoDiscardable: tab.autoDiscardable !== false,
idleMin,
idle: fmtIdleMinutes(idleMin),
impact,
score,
protected: !!keep,
keepReason: keep || '',
sleepable: !keep && !tab.discarded,
reasons: reasons.slice(0, 5),
};
}
async function listMemoryTabs() {
try {
const cfg = await getMemoryConfig();
const tabs = await chrome.tabs.query({});
const now = Date.now();
const rows = [];
for (const tab of tabs) {
const url = tab.url || tab.pendingUrl || '';
if (!tab.discarded && !/^https?:\/\//i.test(url)) continue;
rows.push(tabMemoryPressure(tab, cfg, now));
}
rows.sort((a, b) => {
if (a.discarded !== b.discarded) return a.discarded ? 1 : -1;
if (a.sleepable !== b.sleepable) return a.sleepable ? -1 : 1;
if (b.score !== a.score) return b.score - a.score;
return b.idleMin - a.idleMin;
});
const summary = { total: rows.length, sleepable: 0, high: 0, sleeping: 0 };
for (const row of rows) {
if (row.sleepable) summary.sleepable++;
if (row.impact === 'High') summary.high++;
if (row.discarded) summary.sleeping++;
}
return {
ok: true,
summary,
tabs: rows.slice(0, 30),
};
} catch (e) { return { ok: false, error: String(e) }; }
}
// ---- Zombie-tab detector: awake tabs idle for a long time (default 6h) ----
async function listZombieTabs(hours) {
try {
const h = hours || 6;
const cutoff = Date.now() - h * 3600000;
const tabs = await chrome.tabs.query({});
const cfg = await getMemoryConfig();
const zombies = [];
for (const tab of tabs) {
if (tab.discarded || tab.active) continue;
if (!/^https?:/i.test(tab.url || '')) continue;
const last = tabLastUsedOrNull(tab);
if (last == null) continue; // unknown age -> don't accuse
if (last > cutoff) continue;
const keep = tabKeepReason(tab, cfg);
let host = ''; try { host = new URL(tab.url).hostname.replace(/^www\./, ''); } catch (_) {}
zombies.push({ id: tab.id, host, title: (tab.title || host).slice(0, 60), idleHours: Math.floor((Date.now() - last) / 3600000), protected: !!keep, keepReason: keep || null });
}
return { ok: true, zombies, hours: h };
} catch (e) { return { ok: false, error: String(e) }; }
}
async function memoryActOnTab(tabId, action, opts) {
const id = Number(tabId);
if (!Number.isInteger(id) || id < 0) return { ok: false, error: 'Invalid tab.' };
const tab = await tabsGet(id);
if (!tab) return { ok: false, error: 'Tab no longer exists.' };
const cfg = await getMemoryConfig();
const keep = tabKeepReason(tab, cfg);
if (keep) return { ok: false, error: 'Protected tab: ' + keep };
const requireIdleHours = opts && Number(opts.requireIdleHours) >= 0 ? Number(opts.requireIdleHours) : 6;
const last = tabLastUsedOrNull(tab) || 0;
if (requireIdleHours > 0 && (!last || (Date.now() - last) < requireIdleHours * 3600000)) return { ok: false, error: 'Tab is no longer idle enough.' };
const live = await tabLiveState(id);
if (!live.ok) return { ok: false, error: "Couldn't check this tab for unsaved work. Try again, or reload the tab first." };
if (cfg.memoryNeverForms && live.formDirty) return { ok: false, error: 'Protected tab: unsaved form' };
if (live.mediaActive) return { ok: false, error: 'Protected tab: camera/mic in use' };
try {
if (action === 'sleep') {
if (!tab.discarded) await chrome.tabs.discard(id);
return { ok: true, action: 'sleep', tabId: id };
}
if (action === 'close') {
await chrome.tabs.remove(id);
return { ok: true, action: 'close', tabId: id };
}
return { ok: false, error: 'Unknown memory action.' };
} catch (e) {
return { ok: false, error: String(e) };
}
}
// ---- Right-click actions on the tab you are looking at -----------------------------
//
// Sleep it, close it, or mark its site never-sleep. These are the same two verbs the
// automatic shield uses, aimed by hand at one named tab.
//
// The safety rules are NOT the sweep's rules, and that difference is the whole design.
// tabKeepReason exists because the sweep acts on tabs nobody is looking at: "active
// tab", "pinned", "allowlisted" and the rest are all guesses about what the reader would
// have wanted, and a sweep that guesses wrong should keep the tab. None of that applies
// to a menu entry opened on the tab in front of them -- refusing to sleep the active tab
// because it is the active tab would refuse every single click, since that is the only
// tab you can right-click. So this path ignores tabKeepReason entirely and keeps exactly
// the two guards that protect something unrecoverable: unsaved typing, and a live
// camera or microphone.
// Definite answers only.
//
// The sweep treats "could not ask" as a refusal, and must: an unanswered tab is not a
// verified-clean one, and the cost of being wrong is a draft someone had forgotten
// about. Here the same rule would break the entry far more often than it would save
// anything -- the bridge is unreachable on a paused site, on a page loaded before the
// extension was installed, and on every chrome:// and PDF page, none of which are
// evidence of unsaved work. So a definite "there is something here" stops the action;
// silence does not.
async function tabWorkInProgressReason(tab, cfg) {
if (!tab || typeof tab.id !== 'number') return '';
// Nothing of ours runs outside http(s), so there is nobody to ask and nothing it
// could have seen.
if (!/^https?:\/\//i.test(String(tab.url || tab.pendingUrl || ''))) return '';
const live = await tabLiveState(tab.id);
if (!live.ok) return '';
// Unconditional: there is no switch that means "close my video call for me".
if (live.mediaActive) return 'this tab is using your camera or microphone';
// This one follows the reader's own setting, because that switch is exactly the
// question "should unsaved typing stop a tab being thrown away".
if (cfg && cfg.memoryNeverForms === false) return '';
if (live.formDirty) return 'this tab has unsaved text typed into it';
return '';
}
// The tab Chrome would have put you on anyway: the next one to the right, else the
// nearest to the left. Jumping to the far end of the strip is disorienting.
async function neighbourTabOf(tab) {
try {
const tabs = await chrome.tabs.query({ windowId: tab.windowId });
const others = (tabs || []).filter((t) => t && typeof t.id === 'number' && t.id !== tab.id);
if (!others.length) return null;
const index = Number(tab.index);
if (!Number.isFinite(index)) return others[0];
const right = others.filter((t) => t.index > index).sort((a, b) => a.index - b.index)[0];
if (right) return right;
return others.filter((t) => t.index < index).sort((a, b) => b.index - a.index)[0] || others[0];
} catch (_) { return null; }
}
async function memorySleepTabByHand(tabArg) {
const id = tabArg && typeof tabArg.id === 'number' ? tabArg.id : null;
if (id === null) return { ok: false, error: 'Chrome gave WardenOne no tab to sleep.' };
const tab = (await tabsGet(id)) || tabArg;
if (tab.discarded) return { ok: false, error: 'This tab is already asleep. Click it to wake it up.' };
const cfg = await getMemoryConfig();
const busy = await tabWorkInProgressReason(tab, cfg);
if (busy) {
return { ok: false, error: 'Not slept, because ' + busy
+ '. Sleeping reloads the tab, so that would be gone.' };
}
// Move off it first, when there is somewhere to move to.
//
// Measured in Chromium 150 rather than assumed, because the obvious guess is wrong
// in both directions. chrome.tabs.discard DOES work on the tab you are looking at,
// and it stays unloaded afterwards -- what it does not do is look like anything. The
// page you were reading goes blank where it stands and comes back only when you click
// it, which is indistinguishable from having broken the tab. Activating the
// neighbour first turns that into the outcome people mean by "sleep this tab": you
// are on the next tab along, and the one you slept is greyed out in the strip behind
// you.
//
// With no neighbour to move to it is still done. It works there too -- refusing
// would be refusing something the browser is perfectly willing to do, and "it did
// nothing" is the worse answer.
if (tab.active) {
const neighbour = await neighbourTabOf(tab);
if (neighbour) { try { await chrome.tabs.update(neighbour.id, { active: true }); } catch (_) {} }
}
// The return value decides it, and it is also where the tab now lives.
//
// Measured alongside the above: a discarded tab comes back with a DIFFERENT id, every
// time, and the id we asked about is gone from chrome.tabs.get by the time discard
// resolves. Confirming the sleep by re-reading that id would therefore report a
// failure on every single success.
let discarded = null;
try { discarded = await chrome.tabs.discard(tab.id); } catch (_) { discarded = null; }
if (!discarded) return { ok: false, error: 'Chrome refused to sleep this tab.' };
// Read from the tab as it was before the discard, which is the copy already in hand.
const host = (() => { try { return new URL(tab.url).hostname.replace(/^www\./, ''); } catch (_) { return ''; } })();
// Its own row type, not the sweep's. The sweep's reads "Slept an inactive tab", which
// would be a plain lie about a tab the reader was looking at a second earlier -- and
// Activity must not present someone's own decision as something WardenOne worked out.
queueHistory({ type: 'memory_tab_slept_by_hand', detail: { host }, url: host, at: Date.now() });
return { ok: true, host };
}
async function memoryCloseTabByHand(tabArg) {
const id = tabArg && typeof tabArg.id === 'number' ? tabArg.id : null;
if (id === null) return { ok: false, error: 'Chrome gave WardenOne no tab to close.' };
const tab = (await tabsGet(id)) || tabArg;
const cfg = await getMemoryConfig();
const busy = await tabWorkInProgressReason(tab, cfg);
if (busy) {
// chrome.tabs.remove does not run the page's beforeunload, so this entry would close
// harder than Chrome's own close does -- no "Leave site?", no way back. That is the
// reason the guard is here at all, and the reason it points at Ctrl+W: the reader
// keeps the ability to close it, they just get the browser's warning with it.
return { ok: false, error: 'Not closed, because ' + busy + '. Ctrl+W still closes it.' };
}
try { await chrome.tabs.remove(tab.id); } catch (_) { return { ok: false, error: 'Chrome refused to close this tab.' }; }
return { ok: true };
}
// ---- Tab-group sleeping: discard all safe tabs in groups idle past threshold ----
async function sleepIdleGroups(cfgArg) {
try {
// No chrome.tabGroups guard here, because nothing below calls chrome.tabGroups. The grouping
// is read from tab.groupId, which belongs to chrome.tabs and is present whether or not that
// namespace is -- so the old check tested one capability and used a different one, and would
// have answered wrong in both directions had they ever come apart.
// A browser with no grouped tabs now falls through the groupId filter and reports
// { ok: true, sleptGroups: 0, sleptTabs: 0 }, which is true, rather than claiming the whole
// feature is unsupported.
const cfg = cfgArg || await getMemoryConfig();
if (!cfg.memoryShield) return { ok: false, disabled: true };
const tabs = await chrome.tabs.query({});
const now = Date.now();
const thresholdMs = cfg._minutes * 60000;
// group tabs by groupId (>-1 means grouped)
const groups = Object.create(null);
for (const tab of tabs) {
if (tab.groupId == null || tab.groupId < 0) continue;
(groups[tab.groupId] = groups[tab.groupId] || []).push(tab);
}
let sleptGroups = 0, sleptTabs = 0;
for (const gid in groups) {
const gtabs = groups[gid];
// a group is "idle" only if EVERY tab in it is idle past threshold and none active
const allIdle = gtabs.every((t) => {
if (t.active) return false;
const last = tabLastUsed(t, now);
return (now - last) >= thresholdMs;
});
if (!allIdle) continue;
const candidates = [];
for (const t of gtabs) {
const keep = tabKeepReason(t, cfg);
if (keep) continue;
candidates.push(t);
}
const results = await mapLimited(candidates, MEMORY_LIVE_CHECK_CONCURRENCY, async (t) => {
const live = await tabLiveState(t.id);
if (!live.ok) return false;
if ((cfg.memoryNeverForms && live.formDirty) || live.mediaActive) return false;
try { await chrome.tabs.discard(t.id); return true; } catch (_) { return false; }
});
const groupSlept = results.filter(Boolean).length;
sleptTabs += groupSlept;
const groupSleptAny = groupSlept > 0;
if (groupSleptAny) sleptGroups++;
}
if (sleptTabs) queueHistory({ type: 'memory_group_slept', detail: { groups: sleptGroups, tabs: sleptTabs }, url: '', at: Date.now() });
return { ok: true, sleptGroups, sleptTabs };
} catch (e) { return { ok: false, error: String(e) }; }
}
// ---- Background throttle: pause autoplay media in inactive tabs (the honest,
// achievable part of "reduce background activity before discard"). We can't flush
// a tab's RAM cache or strip already-loaded scripts -- no extension can -- but we
// CAN tell an inactive tab to pause autoplaying audio/video, which cuts real CPU.
async function throttleInactiveTabs(cfgArg) {
try {
const cfg = cfgArg || await getMemoryConfig();
if (!cfg.memoryShield) return;
// throttle tabs idle past HALF the sleep threshold (the "freeze" stage before
// the later discard). e.g. balanced(30m) -> pause media at 15m, discard at 30m.
const halfMs = (cfg._minutes * 60000) / 2;
const now = Date.now();
const tabs = await chrome.tabs.query({});
for (const tab of tabs) {
if (tab.active || tab.discarded || tab.audible) continue;
if (!/^https?:/i.test(tab.url || '')) continue;
try {
if (isVideoPlatformHost(new URL(tab.url).hostname)) continue;
} catch (_) {}
const keep = tabKeepReason(tab, cfg);
if (keep) continue;
// Throttling stays fail-open on purpose -- the worst outcome here is a paused video, not a
// lost draft, so this path never consults live state and never needs to.
const last = tabLastUsed(tab, now);
if ((now - last) < halfMs) continue;
try { chrome.tabs.sendMessage(tab.id, { kind: 'memory-throttle' }, () => { void chrome.runtime.lastError; }); } catch (_) {}
}
} catch (_) {}
}
try {
if (globalThis.__WARDENONE_TEST__) {
globalThis.__woMemoryTest = Object.freeze({
MEMORY_DEFAULTS,
MEMORY_MODES,
MEMORY_NEVER_SLEEP_MAX,
memoryNeverSleepHas,
tabWorkInProgressReason,
neighbourTabOf,
tabKeepReason,
tabMemoryPressure,
mapLimited,
fmtIdleMinutes,
tabActivity,
tabLastUsed,
tabLastUsedOrNull,
tabLiveState,
reconcileMemorySweepAlarm,
MEMORY_SWEEP_ALARM,
MEMORY_LIVE_CHECK_TIMEOUT_MS,
});
}
} catch (_) {}