-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice_worker.js
More file actions
1858 lines (1690 loc) · 76.8 KB
/
Copy pathservice_worker.js
File metadata and controls
1858 lines (1690 loc) · 76.8 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
import deriveSystemTotals from './src/lib/utils/deriveSystemTotals.js';
import isTrackableUrl from './src/lib/utils/isTrackableUrl.js';
import samePageKey from './src/lib/utils/samePageKey.js';
import pruneDeletedUrls from './src/lib/utils/pruneDeletedUrls.js';
import appendGroupingLog from './src/lib/utils/groupingLog.js';
import healDriftedLabelSlot from './src/lib/utils/healDriftedLabelSlot.js';
import navigatedAwayFromRecordedSlot from './src/lib/utils/navigatedAwayFromRecordedSlot.js';
import { buildGroupRemovalEntry, GROUP_REMOVAL_LOG_KEY, GROUP_REMOVAL_LOG_CAP, RemovalSource } from './src/lib/utils/groupRemovalLog.js';
import { buildGroupAdditionEntry, GROUP_ADDITION_LOG_KEY, GROUP_ADDITION_LOG_CAP, AdditionSource } from './src/lib/utils/groupAdditionLog.js';
import { buildGroupMoveEntry, GROUP_MOVE_LOG_KEY, GROUP_MOVE_LOG_CAP, MoveSource } from './src/lib/utils/groupMoveLog.js';
import { needsGroupCall, needsUngroupCall, bucketTabsByWindow } from './src/lib/utils/tabPlacement.js';
import findLabelForUrlKey from './src/lib/utils/findLabelForUrlKey.js';
import deletedLabelTitles from './src/lib/utils/deletedLabelTitles.js';
import { areaForKey } from './src/lib/utils/storageAreas.js';
import { readByArea, writeByArea } from './src/lib/utils/storageAccess.js';
import { migrateLabelsToSync } from './src/lib/utils/migrateLabelsToSync.js';
let listening = true;
let removing;
// Tab ids whose `chrome.tabs.ungroup` is in flight. A navigated tab leaving a
// named group is added here before the async ungroup and removed in its
// callback; while present, the capture paths (`groupTabs` /
// `handleActiveTabsGroupChanges`) must refuse to record the tab into the group
// it is on its way out of, otherwise the new URL is permanently pushed into the
// old group's label during the async gap.
const pendingUngroups = new Set();
// Tab ids that Chrome placed into a group at creation time (native "a tab opened
// from a grouped tab inherits that group" behavior). Detected in onCreated when a
// brand-new tab is already in a group. These memberships are NOT user intent, so
// `groupTabs` must never record their URLs into a label (which would make them
// permanently sticky); instead it ungroups them once their real URL has loaded,
// unless that URL is already a deliberate member of the label.
const autoGroupedTabs = new Set();
// Label titles the user has deleted during this worker's lifetime. Deleting a
// group dissolves its Chrome tab group (see `dissolveDeletedLabelGroups`), but
// that is async and unreliable in the tail cases — a second window's group
// queried later, an ungroup that fails — and any tab still sitting in a titled
// Chrome group with no matching label reaches `recordInGroupTab`, which
// helpfully re-creates the label the user just deleted. This is the belt to that
// suspenders: while a title is in here, the record path refuses to seed it.
//
// Keyed by TITLE rather than tab id (unlike the two Sets above) because that is
// what a deletion actually identifies. A title is removed again the moment it
// reappears in `labels`, so deliberately re-creating a group with the same name
// works immediately. Startup sync of a genuinely pre-existing Chrome group is
// untouched: its title was never deleted here, so it was never added.
const userDeletedLabels = new Set();
// Diagnostic logging for the tab-grouping decision points. The prototype proved
// the auto-group stickiness bug with unconditional `[TC-GROUP]` console noise;
// keep that instrumentation behind a flag so it can be flipped on for future
// diagnosis without shipping console spam. Flip to `true` to trace to console.
const DEBUG_GROUPING = false;
// Cap for the persisted `groupingLog` ring buffer (see debugGroup).
const GROUPING_LOG_CAP = 200;
// Records a grouping decision breadcrumb. In addition to the compile-time
// console trace (`DEBUG_GROUPING`), it persists the breadcrumb to a capped ring
// buffer in `chrome.storage.local` when the runtime `debugGrouping` flag is set
// — MV3 recycles the worker constantly, so a bug that spans a restart (a doc
// recorded under one `?tab=` key, ejected after the worker died) is invisible to
// `console.log` alone. The persisted trail is inspectable after the fact via
// `chrome.storage.local.get('groupingLog')`, and enabled with no reload/source
// edit via `chrome.storage.local.set({ debugGrouping: true })`. Fire-and-forget:
// the async storage round-trip never blocks the caller.
function debugGroup(event, details) {
if (DEBUG_GROUPING) console.log(`[TC-GROUP] ${event}`, details);
getStorage(['debugGrouping', 'groupingLog'], (result) => {
if (!DEBUG_GROUPING && !result.debugGrouping) return;
const groupingLog = appendGroupingLog(
result.groupingLog,
{ t: Date.now(), event, details },
GROUPING_LOG_CAP
);
update({ groupingLog });
});
}
// Records a group-membership removal to an always-on audit trail. Unlike
// `debugGroup`, this is NOT gated by `DEBUG_GROUPING`/`debugGrouping` — member
// removals are rare and low-volume, and the whole reason the CodeYam Fleet drop
// was undiagnosable is that the only trail was behind a default-off flag. The
// trail persists to a dedicated `groupRemovalLog` key (never buried by, or
// trimmed with, the noisy auto-group breadcrumbs in `groupingLog`) and is
// inspectable after the fact with no flag and no reload:
// chrome.storage.local.get('groupRemovalLog', console.log)
// Fire-and-forget: the async storage round-trip never blocks the caller, and it
// only records removals — it never changes removal behavior.
function recordRemoval(source, details) {
getStorage([GROUP_REMOVAL_LOG_KEY], (result) => {
update({
[GROUP_REMOVAL_LOG_KEY]: appendGroupingLog(
result[GROUP_REMOVAL_LOG_KEY],
buildGroupRemovalEntry(source, { ...details, t: Date.now() }),
GROUP_REMOVAL_LOG_CAP
)
});
});
}
// Records a group-membership ADDITION to an always-on audit trail — the mirror
// image of `recordRemoval`, and unconditional for the same reason. The phantom
// "App Store Connect" members that kept appearing in the CodeYam group could
// only be diagnosed by reading the code, because nothing recorded which path
// appended them; this trail names the exact source on every add. Persists to its
// own `groupAdditionLog` key so it is never buried by, or trimmed with, the
// noisy auto-group breadcrumbs in `groupingLog`:
// chrome.storage.local.get('groupAdditionLog', console.log)
// Fire-and-forget: the async storage round-trip never blocks the caller, and it
// only records additions — it never changes grouping behavior.
function recordAddition(source, details) {
getStorage([GROUP_ADDITION_LOG_KEY], (result) => {
update({
[GROUP_ADDITION_LOG_KEY]: appendGroupingLog(
result[GROUP_ADDITION_LOG_KEY],
buildGroupAdditionEntry(source, { ...details, t: Date.now() }),
GROUP_ADDITION_LOG_CAP
)
});
});
}
// Records an issued tab MOVE to an always-on audit trail — the third sibling of
// `recordRemoval` / `recordAddition`, and unconditional for the same reason.
// Those two trail label MEMBERSHIP; neither sees the thing the user actually
// notices, which is the tab jumping position in the strip. `chrome.tabs.group`
// and `chrome.tabs.ungroup` reposition a tab on every call, so "TabCommand keeps
// moving my tabs" is a report about issued calls — and it was undiagnosable
// without a trail of them.
//
// Called ONLY after the `needsGroupCall` / `needsUngroupCall` guards pass, i.e.
// only where a real move is about to happen. A suppressed no-op leaves no entry,
// so a quiet steady state reads as an empty trail rather than a guess. Persists
// to its own `groupMoveLog` key so it is never buried by, or trimmed with, the
// noisy auto-group breadcrumbs in `groupingLog`:
// chrome.storage.local.get('groupMoveLog', console.log)
// Fire-and-forget: the async storage round-trip never blocks the caller, and it
// only records moves — it never changes placement behavior. The write cannot
// re-enter the grouping loop: `storage.onChanged` bails unless `labels` or
// `activeTabs` changed, and this touches neither.
function recordMove(source, details) {
getStorage([GROUP_MOVE_LOG_KEY], (result) => {
update({
[GROUP_MOVE_LOG_KEY]: appendGroupingLog(
result[GROUP_MOVE_LOG_KEY],
buildGroupMoveEntry(source, { ...details, t: Date.now() }),
GROUP_MOVE_LOG_CAP
)
});
});
}
// Record one move entry per tab actually handed to `chrome.tabs.group`. Both
// grouping branches (create-a-new-group and add-to-an-existing-group) need the
// identical loop, and a batched Chrome call moves every tab in it — so the trail
// records per tab, not per call.
function recordGroupMoves(tabs, toGroupId, labelTitle) {
for (const tab of tabs) {
recordMove(MoveSource.WORKER_AUTO_GROUP, {
action: 'group',
tabId: parseTabId(tab),
fromGroupId: tab.groupId,
toGroupId,
labelTitle,
urlKey: tab.urlKey
});
}
}
// Resolve a group id to its label title, preferring the in-memory `groups` map
// and falling back to Chrome. The fallback is not an optimization detail: right
// after an MV3 service-worker restart the map is COLD, and both onUpdated
// branches that need a title run in exactly that window.
async function resolveGroupTitle(groupId) {
const cached = groups[groupId];
if (cached) return cached;
const group = await getTabGroup(groupId);
return group && group.title;
}
// Stamp an `activeTabs` entry with the label slot its URL was just filed under.
// This is what lets a later grouping sync tell "the tab I already recorded has
// navigated" apart from "a genuinely new URL joined the group" — without it,
// every navigation of a grouped tab looked like a brand-new member and got
// appended (the phantom "App Store Connect" rows).
//
// It has to live ON the activeTabs entry rather than in a module-level Map:
// MV3 tears the worker down constantly, and the post-teardown sync is exactly
// the window where the bogus append happens, so an in-memory map would be empty
// precisely when it is needed. `activeTabs` already persists to
// `chrome.storage.local` and its entries vanish when the tab closes, so cleanup
// is free. Returns whether the stamp actually changed, so a caller on a hot path
// does not write `activeTabs` on every pass (see the write-loop note in groupTabs).
function stampLabelMembership(activeTab, labelTitle, urlKey) {
if (activeTab.labelTitle === labelTitle && activeTab.labelUrlKey === urlKey) return false;
activeTab.labelTitle = labelTitle;
activeTab.labelUrlKey = urlKey;
return true;
}
// Whether `urlKey` is a deliberate, recorded member of `label`. Centralizes the
// "is this URL bound to this label" check used across the grouping paths so the
// auto-group ejection logic and the recording logic share one definition.
function urlKeyIsMember(label, urlKey) {
return !!(label && label.urlKeys.indexOf(urlKey) > -1);
}
// The LoadMeter gauge's scale, mirrored from src/lib/components/LoadMeter so the
// system fallback normalizes to the same 0→max range the gauge already renders.
// (The two runtimes — classic web app vs. service worker — can't share a module
// of plain constants, so this small duplication is intentional and commented.)
const GAUGE = {
max: { cpu: 150, memory: 5 * 1024 * 1024 * 1024 },
base: { cpu: 0, memory: 500 * 1024 * 1024 }
};
const SYSTEM_POLL_INTERVAL_MS = 5000;
let systemPollTimer = null;
let previousCpuSample = null;
// Auto-close ("Closer") engine tunables, mirrored from src/Constants.jsx
// (`AutoCloseMinutes` / `MaxAutoClosedTime`) for the same reason GAUGE is
// duplicated above: the service-worker runtime can't share the ES module of
// plain constants. AUTO_CLOSE_MINUTES is the default inactivity threshold used
// when the user hasn't set `settings.autoCloseMinutes`; MAX_AUTO_CLOSED_TIME is
// how long a closed entry lingers in the "Automatically Closed" list before the
// sweep prunes it (the UI filters by the same window).
const AUTO_CLOSE_MINUTES = 120;
const MAX_AUTO_CLOSED_TIME = 1000 * 60 * 60 * 24 * 5;
const AUTO_CLOSE_ALARM = 'auto-close-sweep';
// Per-visit history tunables, mirrored from src/lib/utils/visitDecay.js (the
// service-worker runtime can't import that ES module, same as the GAUGE /
// AUTO_CLOSE constants above). VISIT_RETENTION_MS: drop visit timestamps older
// than this on write; MAX_VISITS: cap retained timestamps per site. Retention is
// sized to the longest usage view the Favorites page draws (the 7-week
// sparkline) plus a week of margin — 8 weeks; old visits contribute negligible
// decayed weight to the rank but back the weekly usage-over-time view.
const VISIT_RETENTION_MS = 1000 * 60 * 60 * 24 * 56;
const MAX_VISITS = 50;
// How many url-* keys the recency list (`allUrls`) tracks. Keys past this cap are
// evicted from the tail and their records deleted. This is a DISPLAY/storage cap
// for History and Search — it deliberately no longer bounds visit stats, which
// live in the site-keyed `siteVisits` store below and are pruned only by
// VISIT_RETENTION_MS / MAX_VISITS.
const MAX_TRACKED_URLS = 500;
// How long a `deletedUrls` tombstone is honored. A tombstone exists for exactly
// one reason: to outlive an IN-FLIGHT `chrome.tabs.onRemoved` -> `closeUrl` that
// already read a pre-delete `allUrls` snapshot and would otherwise write the
// just-deleted key back at index 0. That window is milliseconds; an hour is
// generous slack for a throttled/suspended service worker. It is NOT a blocklist
// — `newUrl` clears the entry the moment the user deliberately visits the page
// again, and prunes anything past this age so the map cannot grow without bound.
const DELETED_URL_TTL_MS = 60 * 60 * 1000;
// A tab you switch back to earns a visit too, not just an open/navigation — so
// Favorites rewards sites you keep open and return to. But debounce it: rapid
// alt-tabbing between the same two tabs, or the open→immediately-activate
// sequence a brand-new tab produces, must not inflate a rank. At most one
// access-driven visit per site per this window.
const ACCESS_THROTTLE_MS = 1000 * 60 * 30;
// Drop visits older than the retention horizon and cap to the newest MAX_VISITS.
// Mirror of pruneVisits() in visitDecay.js; kept pure so it's obviously correct.
function pruneVisits(visits, now) {
if (!Array.isArray(visits)) return [];
const cutoff = now - VISIT_RETENTION_MS;
const kept = visits
.map(Number)
.filter((ts) => Number.isFinite(ts) && ts > cutoff)
.sort((a, b) => a - b);
return kept.length > MAX_VISITS ? kept.slice(-MAX_VISITS) : kept;
}
// The canonical site key (host, lowercased, leading `www.` stripped) a URL's
// visits accumulate under. Mirror of siteKey() in src/lib/utils/siteKey.js —
// THAT FILE IS THE SOURCE OF TRUTH; this duplicate exists only because the
// service-worker runtime can't import the ES module, same as pruneVisits above
// and the GAUGE / AUTO_CLOSE constants. Keep the two in step.
function siteKey(url) {
if (typeof url !== 'string') return '';
const raw = url.trim();
if (raw.length === 0) return '';
let parsed;
try {
parsed = new URL(raw);
} catch {
return '';
}
return parsed.host.toLowerCase().replace(/^www\./, '');
}
// Mirror of isSearchEngineUrl() in src/lib/utils/isSearchEngineUrl.js — THAT FILE
// IS THE SOURCE OF TRUTH; this duplicate exists only because the service-worker
// runtime can't import the ES module, same as siteKey / pruneVisits above. Keep
// SEARCH_ENGINE_HOSTS byte-identical (alphabetized) to the canonical set so the
// two don't drift. Used by newUrl to stop accumulating Favorites scoring signal
// (per-record `visits` + the durable `siteVisits[host]`) for search engines,
// which rankFavorites discards anyway.
const SEARCH_ENGINE_HOSTS = new Set([
'ask.com',
'baidu.com',
'bing.com',
'duckduckgo.com',
'ecosia.org',
'kagi.com',
'qwant.com',
'search.brave.com',
'search.yahoo.com',
'startpage.com',
'yandex.com',
'yandex.ru',
]);
const GOOGLE_SEARCH_HOST = /^google\.[a-z.]+$/;
function isSearchEngineUrl(url) {
const host = siteKey(url);
if (!host) return false;
return SEARCH_ENGINE_HOSTS.has(host) || GOOGLE_SEARCH_HOST.test(host);
}
let groups = {};
function trackGroup(group) {
groups[parseInt(group.id)] = group.title;
}
chrome.tabGroups.onCreated.addListener((group) => trackGroup(group))
chrome.tabGroups.onUpdated.addListener((group) => trackGroup(group))
chrome.tabGroups.query({}, (groups) => {
for (let i=0; i<groups.length; ++i) {
trackGroup(groups[i]);
}
});
initLoadSource();
// The Closer: a periodic alarm wakes the (ephemeral MV3) worker once a minute to
// sweep inactive tabs. Guarded because the test harness's chrome stub omits
// chrome.alarms; in the packaged extension the "alarms" permission makes it present.
if (chrome.alarms) {
chrome.alarms.create(AUTO_CLOSE_ALARM, { periodInMinutes: 1 });
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm && alarm.name === AUTO_CLOSE_ALARM) autoCloseSweep();
});
}
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
let updates = await tabUpdates(tab);
const checkRemoving = () => {
if (removing === tabId) {
removing = null;
return true;
}
};
const activeTabs = (await getStorage('activeTabs')).activeTabs || [];
if (changeInfo.url) {
if (checkRemoving()) return true;
const oldTabUrl = activeTabs.filter(
tabUrl => tabUrl.tabKey === `tab-${tabId}`
)[0];
if (oldTabUrl) {
closeUrl(oldTabUrl.urlKey);
// Only eject a grouped tab on a REAL navigation. A URL change that keeps
// the same origin + pathname (only the query string or fragment moved) is
// an in-page rewrite — most visibly Google Docs churning `?tab=t.…` via
// the History API — and the tab must stay in its group. `oldTabUrl.urlKey`
// is `url-<old-url-without-fragment>` (see getUrlKey), so strip the `url-`
// prefix to recover the old URL for the comparison.
const oldUrl = oldTabUrl.urlKey.replace(/^url-/, '');
const isNavigation = samePageKey(oldUrl) !== samePageKey(changeInfo.url);
if (tab.groupId > -1 && isNavigation) {
// A real navigation ejects the tab from its group — but not when the tab
// simply moved to ANOTHER URL the same label already claims. Sites that
// rewrite their own path with no user input (auth bounces, redirect
// chains, chat/doc apps) hit this constantly, and ejecting there is
// pure churn: groupTabs pulls the tab straight back in on the next pass,
// so the user watches it pop out and snap back. Resolve the label title
// the same way the in-page branch below does.
const currentLabelTitle = await resolveGroupTitle(tab.groupId);
const stillAMember = urlKeyIsMember(
labels[currentLabelTitle],
getUrlKey(changeInfo.url)
);
if (stillAMember) {
debugGroup('onUpdated: keep grouped tab (navigated to another member URL)', {
tabId: tab.id,
oldUrl,
newUrl: changeInfo.url,
label: currentLabelTitle,
groupId: tab.groupId
});
} else if (needsUngroupCall(tab)) {
debugGroup('onUpdated: eject grouped tab (navigation)', {
tabId: tab.id,
oldUrl,
newUrl: changeInfo.url,
groupId: tab.groupId
});
recordMove(MoveSource.WORKER_NAVIGATION_EJECT, {
action: 'ungroup',
tabId: tab.id,
fromGroupId: tab.groupId,
toGroupId: -1,
labelTitle: currentLabelTitle,
urlKey: getUrlKey(changeInfo.url)
});
pendingUngroups.add(tab.id);
chrome.tabs.ungroup(tab.id, () => {
void (chrome.runtime && chrome.runtime.lastError);
pendingUngroups.delete(tab.id);
});
}
} else if (tab.groupId > -1 && !isNavigation) {
// In-page URL change on a grouped tab (e.g. Google Docs rewriting
// `?tab=t.…` via the History API). The tab stays grouped, but its live
// urlKey has now drifted away from the key recorded in the group's
// label — every downstream exact-key comparison (groupTabs eject,
// handleActiveTabsGroupChanges, post-restart reconciliation) would then
// conclude the URL is no longer a member and drop it. Heal by rewriting
// the drifted label slot to follow the live URL. We LOCATE the drifted
// slot by page identity (samePageKey) — which also catches the case
// where the recorded key is a third `?tab=` variant — but the
// membership/eject paths still compare exact keys, so samePageKey never
// becomes the membership test.
const labelTitle = await resolveGroupTitle(tab.groupId);
const label = labels[labelTitle];
if (label) {
const newUrlKey = getUrlKey(changeInfo.url);
const { mutated, previousKey, removed } = healDriftedLabelSlot(
label,
newUrlKey,
changeInfo.url
);
if (mutated) {
labels[labelTitle] = label;
updates = { ...updates, labels: labels };
debugGroup('onUpdated: heal drifted label urlKey', {
tabId: tab.id,
oldUrlKey: previousKey,
newUrlKey,
label: labelTitle,
groupId: tab.groupId
});
// A drift-heal dedup is a splice (a duplicate slot collapsed), not a
// loss — but it removes a member slot, so it belongs in the trail.
if (removed) {
recordRemoval(RemovalSource.WORKER_DRIFT_HEAL_DEDUP, {
labelTitle,
urlKeys: [previousKey],
tabId: tab.id,
remaining: label.urlKeys.length
});
} else {
// The position-preserving rewrite put a key into a slot that did
// not hold it before — an add-in-place. Record both keys so the
// rewrite chain behind a surprising member is readable.
recordAddition(AdditionSource.WORKER_DRIFT_HEAL, {
labelTitle,
urlKeys: [newUrlKey],
previousKey,
tabId: tab.id,
total: label.urlKeys.length
});
}
}
}
}
}
// This branch records the navigation directly (it does not pass through
// validTab), so guard it so an incognito navigation never enters allUrls
// or bumps visitCount. See validTab for the broader incognito policy.
if (!tab.incognito) {
updates = {
...updates,
...(await newUrl(tabId, changeInfo.url))
};
}
}
if (changeInfo.groupId === -1) {
const activeTabIndex = activeTabs.findIndex(
tabUrl => tabUrl.tabKey === `tab-${tabId}`
);
const activeTab = activeTabs[activeTabIndex];
if (activeTab) {
const oldGroupId = activeTab.groupId
if (oldGroupId && oldGroupId > -1) {
// A tab leaving all groups — Chrome's native ungroup gesture, a
// navigation-eject (chrome.tabs.ungroup on a mismatched navigation), or
// MV3 restart flicker — ungroups the *tab* visually but must NOT delete
// the recorded member. Membership is sticky: a urlKey leaves a label
// only through an explicit user action (the remove-URL button, chip
// drag-out, delete-group) or a genuine re-home (see
// handleActiveTabsGroupChanges). This is consistent with groupTabs,
// which already treats members as sticky by auto-regrouping a matching
// tab back into its label. So we mark the tab ungrouped in activeTabs
// and leave `labels` untouched; reopening the URL auto-regroups it.
activeTabs[activeTabIndex].groupId = -1;
updates = {
...updates,
activeTabs: activeTabs
};
}
}
}
if (checkRemoving()) return true;
update(updates);
if (changeInfo.pinned || changeInfo.groupId) {
updateActiveTabs();
}
if (listening) return;
listenToProcesses();
});
chrome.tabs.onActivated.addListener(async (tabInfo) => {
updateActiveTabs();
const updates = await recordAccess(tabInfo.tabId);
if (updates) update(updates);
});
chrome.tabs.onCreated.addListener(async (tab) => {
// If groupId is already > -1 here, Chrome placed this brand-new tab into a
// group before our code ran (native "open from group" inheritance). If it's
// -1, any later grouping of this tab came from us (groupTabs).
debugGroup('onCreated', {
tabId: tab.id,
url: tab.url,
urlKey: getUrlKey(tab.url || ''),
groupId: tab.groupId,
pinned: tab.pinned,
openerTabId: tab.openerTabId
});
// Chrome inherited this brand-new tab into a group on its own. Flag it so
// groupTabs pulls it back out instead of permanently recording its URL.
if (!tab.pinned && tab.groupId != null && tab.groupId > -1) {
autoGroupedTabs.add(tab.id);
}
const updates = {
...(await tabUpdates(tab)),
...(await newUrl(tab.id, tab.url))
}
update(updates);
if (listening) return;
listenToProcesses();
});
chrome.tabs.onReplaced.addListener((addedTabId, removedTabId) => {
updateActiveTabs();
if (listening) return;
listenToProcesses();
});
chrome.tabs.onMoved.addListener((tabId, moveInfo) => {
updateActiveTabs();
});
chrome.tabs.onRemoved.addListener(async (tabId, removeInfo) => {
removing = tabId;
autoGroupedTabs.delete(tabId);
const activeTabs = (await getStorage('activeTabs')).activeTabs || [];
const oldTabUrl = activeTabs.filter(
tabUrl => tabUrl.tabKey === `tab-${tabId}`
)[0];
if (oldTabUrl) {
closeUrl(oldTabUrl.urlKey, updateActiveTabs);
}
});
let waitingToUpdate = false;
updateActiveTabs();
async function updateActiveTabs() {
if (waitingToUpdate) return;
chrome.tabs.query({ windowType: chrome.tabs.WindowType.NORMAL }, async (tabs) => {
if (!tabs) {
waitingToUpdate = true;
setTimeout(() => {
waitingToUpdate = false;
updateActiveTabs();
}, 100);
return;
}
getStorage(['activeTabs', 'autoClosed', 'labels'], (result) => {
const activeTabs = result.activeTabs || [];
const autoClosed = result.autoClosed || {};
// Read straight from storage rather than the module-level `labels`: this
// callback can run before that binding is initialized, and the membership
// test below only needs a fresh snapshot.
const storedLabels = result.labels || {};
// A Chrome `Tab` has `index`, not `tabIndex` — the old comparator returned
// NaN for every pair, so the sort was a silent no-op.
const newActiveTabs = tabs.sort(
(a, b) => a.index - b.index
);
const updatedActiveTabs = newActiveTabs.filter(validTab).map(
(tab) => {
const existingTab = (activeTabs || []).filter(
(activeTab) => activeTab.tabKey === `tab-${tab.id}`
)[0];
return {
tabKey: `tab-${tab.id}`,
urlKey: getUrlKey(tab.url),
pinned: tab.pinned,
groupId: tab.groupId,
// Which window the tab lives in. groupTabs needs it to scope its
// `chrome.tabGroups.query` — an unscoped query can return a group in
// ANOTHER window, and grouping into it physically drags the tab
// across windows.
windowId: tab.windowId,
activeAt: (tab.active ? Date.now() : (existingTab ?? {}).activeAt),
openedAt: (existingTab ?? { openedAt: Date.now() }).openedAt,
tabCommandPinned: (existingTab ?? {}).tabCommandPinned,
autoClosedAt: (autoClosed || {})[getUrlKey(tab.url)],
active: tab.active,
// Carry the group-membership stamp forward. This rebuild constructs
// a fresh object per tab, so any field it does not name is erased —
// and this one is erased on the very NEXT tab update, long before the
// sync that needs it, leaving the append guard blind.
labelTitle: (existingTab ?? {}).labelTitle,
labelUrlKey: (existingTab ?? {}).labelUrlKey
}
}
);
for (const activeTab of updatedActiveTabs) {
if (activeTab.active && autoClosed[activeTab.urlKey]) {
// Returning to a page the Closer had closed. Clearing the autoClosed
// entry is the point; the ungroup is not. If this URL is a label
// member, ejecting it only has groupTabs pull it straight back in on
// the next pass — the visible out-and-back jump users report every
// time they revisit a closed page. Only eject a non-member.
const isMember = !!findLabelForUrlKey(storedLabels, activeTab.urlKey);
if (!isMember && needsUngroupCall(activeTab)) {
recordMove(MoveSource.WORKER_AUTO_CLOSE_REVISIT, {
action: 'ungroup',
tabId: parseTabId(activeTab),
fromGroupId: activeTab.groupId,
toGroupId: -1,
urlKey: activeTab.urlKey
});
chrome.tabs.ungroup(parseTabId(activeTab));
}
delete autoClosed[activeTab.urlKey];
} else if (activeTab.groupId !== autoClosed.groupId && autoClosed[activeTab.urlKey]) {
delete autoClosed[activeTab.urlKey];
}
}
const updates = {
activeTabs: updatedActiveTabs,
autoClosed: autoClosed
};
update(updates);
});
});
}
// Resolve the active inactivity threshold (in minutes) from the user's settings,
// falling back to the AUTO_CLOSE_MINUTES default when unset. A value of 0 (the
// "Off" position on the Settings slider) disables auto-closing entirely — return
// 0 so the sweep skips the closing pass but still prunes stale entries.
function autoCloseThresholdMinutes(settings) {
const configured = settings && settings.autoCloseMinutes;
if (configured === undefined || configured === null || configured === '') {
return AUTO_CLOSE_MINUTES;
}
const minutes = Number(configured);
return Number.isFinite(minutes) && minutes > 0 ? minutes : 0;
}
// A tab is eligible for auto-close when it is not Chrome-pinned, not
// thumbtack-pinned (tabCommandPinned), not the currently active tab, and its
// last activity (activeAt, falling back to openedAt) is at or before the cutoff.
// activeTabs entries are already validTab-filtered by updateActiveTabs, so no
// scheme check is needed here.
function isAutoCloseEligible(tab, cutoff) {
if (!tab) return false;
if (tab.pinned) return false;
if (tab.tabCommandPinned) return false;
if (tab.active) return false;
const lastActive = tab.activeAt || tab.openedAt;
if (!lastActive) return false;
return lastActive <= cutoff;
}
// Drop auto-closed entries older than the retention window so the map (and the
// "Automatically Closed" list it feeds) doesn't grow unbounded. Mutates in place.
function pruneAutoClosed(autoClosed, now) {
const maxTime = autoClosed.maxTime || MAX_AUTO_CLOSED_TIME;
for (const urlKey of Object.keys(autoClosed)) {
if (urlKey === 'maxTime') continue;
if (now - autoClosed[urlKey] >= maxTime) {
delete autoClosed[urlKey];
}
}
}
// The sweep itself: record + close every eligible inactive tab, then persist the
// updated autoClosed map. Writing autoClosed in this same synchronous pass (before
// the async chrome.tabs.remove callbacks fire onRemoved -> closeUrl -> updateActiveTabs)
// guarantees the downstream reconciliation reads our entries rather than clobbering them.
function autoCloseSweep() {
getStorage(['activeTabs', 'autoClosed', 'settings'], (result) => {
const activeTabs = result.activeTabs || [];
const autoClosed = result.autoClosed || {};
const settings = result.settings || {};
const now = Date.now();
pruneAutoClosed(autoClosed, now);
const minutes = autoCloseThresholdMinutes(settings);
if (minutes > 0) {
const cutoff = now - minutes * 60 * 1000;
for (const tab of activeTabs) {
if (!isAutoCloseEligible(tab, cutoff)) continue;
autoClosed[tab.urlKey] = now;
try {
chrome.tabs.remove(parseTabId(tab), () => {
// Swallow "No tab with id" — a stale tabId must not abort the sweep.
void (chrome.runtime && chrome.runtime.lastError);
});
} catch (e) {
console.log('Unable to auto-close tab', e);
}
}
}
update({ autoClosed });
});
}
// The last `labels` value this worker persisted, serialized. `labels` now lives
// in `chrome.storage.sync`, which enforces MAX_WRITE_OPERATIONS_PER_MINUTE = 120
// and MAX_WRITE_OPERATIONS_PER_HOUR = 1800 — ceilings the local area never had.
// `recordInGroupTab` runs per tab from `groupTabs`, which the `storage.onChanged`
// listener invokes on every `activeTabs` change, and `updateActiveTabs()` fires
// from eight different tab events. Writing `labels` unchanged on every tab event
// would breach the per-minute quota within a minute of normal browsing.
//
// So a write whose `labels` is byte-identical to the last one persisted is
// dropped. Dropping it is safe by construction: identical content means storage
// already holds exactly this value. It also breaks the self-sustaining
// write -> onChanged -> groupTabs -> write loop that made the churn quadratic.
let lastPersistedLabels = null;
function update(updates) {
const outgoing = { ...updates };
if (Object.prototype.hasOwnProperty.call(outgoing, 'labels')) {
const serialized = JSON.stringify(outgoing.labels);
if (serialized === lastPersistedLabels) {
delete outgoing.labels;
} else {
lastPersistedLabels = serialized;
}
}
if (Object.keys(outgoing).length === 0) return;
writeByArea(outgoing);
}
async function newUrl(tabId, url) {
updateActiveTabs();
if (!tabId) return;
if (!url) return;
// Only real websites belong in history/Favorites. Gating here (rather than at
// each call site) means a non-http(s) navigation — about:blank, file://,
// chrome://, data:, etc. — never enters allUrls, never evicts older keys, and
// never bumps visitCount. Sits alongside the incognito/validTab policy:
// about:blank previously slipped through because newUrl never consulted them.
if (!isTrackableUrl(url)) return;
return new Promise((resolve, reject) => {
const updates = {};
const urlKey = getUrlKey(url);
getStorage(['allUrls', 'labels', 'siteVisits', 'deletedUrls', urlKey], (result) => {
const allUrls = result.allUrls || [];
// A real visit UN-FORGETS the page. Deleting from History means "forget
// this", not "block this" — a deliberate return to the page is the user
// asking for it back, so the tombstone is cleared before the move-to-front
// below re-adds the key. Prune on the same pass (mirroring the allUrls
// eviction) so the map stays bounded by DELETED_URL_TTL_MS rather than
// accumulating one entry per page ever deleted.
const deletedUrls = pruneDeletedUrls(result.deletedUrls, Date.now(), DELETED_URL_TTL_MS);
delete deletedUrls[urlKey];
updates.deletedUrls = deletedUrls;
// MOVE-TO-FRONT on every visit, not just the first. `allUrls` is the
// recency list every consumer already treats it as — and the list the
// eviction below trims from the TAIL. Inserting only when absent ordered it
// by first-seen instead, so a site visited daily still drifted toward the
// tail as new URLs arrived, got evicted, and had its whole url-* record
// (visits and all) deleted — resurfacing later as "1 visit".
const existingIndex = allUrls.indexOf(urlKey);
if (existingIndex > -1) allUrls.splice(existingIndex, 1);
allUrls.unshift(urlKey);
if (allUrls.length >= MAX_TRACKED_URLS) {
let allLabelUrlKeys = [];
for (const label in result.labels) {
allLabelUrlKeys += result.labels[label].urlKeys;
}
const removeUrlKeys = allUrls.slice(MAX_TRACKED_URLS);
for (const removeUrlKey of removeUrlKeys) {
if (allLabelUrlKeys.indexOf(removeUrlKey) === -1) {
chrome.storage.local.remove(removeUrlKey);
}
}
}
updates.allUrls = allUrls.slice(0, MAX_TRACKED_URLS);
// Track WHEN and how often each site is visited so Favorites can rank by a
// time-decayed sum of visits. Append a fresh timestamp and prune the array
// (retention horizon + length cap) so per-site history stays bounded.
// Additive: existing url-* fields are preserved, visitCount keeps
// incrementing for backward-compat/display, and records without a `visits`
// array are seeded lazily downstream (see rankFavorites).
const now = Date.now();
// Search engines stay in history (allUrls + visitCount) but stop
// accumulating the Favorites scoring signal — the per-record `visits` and
// the durable `siteVisits[host]` below — since rankFavorites now discards
// search-engine hosts anyway. Gating here keeps those stores from growing
// wasteful (but now-invisible) entries going forward.
const isSearchEngine = isSearchEngineUrl(url);
const urlRecord = result[urlKey] || { url };
updates[urlKey] = {
...urlRecord,
visitCount: (urlRecord.visitCount || 0) + 1,
// Display-recency only, and deliberately OUTSIDE the isSearchEngine
// gate below: the History page needs a date for every visited URL,
// including search engines, whose `visits` array stays empty by design.
// Nothing in rankFavorites reads `lastVisit` and nothing should start —
// scoring runs off `visits`/`siteVisits`, which is what keeps search
// engines out of Favorites.
lastVisit: now,
visits: isSearchEngine
? urlRecord.visits || []
: pruneVisits([...(urlRecord.visits || []), now], now),
};
// The DURABLE half of the same visit: accumulate it under the site's host
// in `siteVisits`, which the eviction branch above never touches. Evicting
// a url-* key can therefore no longer destroy a site's stats — the advertised
// 56-day window is bounded only by retention, not by how many other URLs the
// user happened to browse. Keying by host also means every article on a
// content site credits the SITE rather than minting its own orphan record.
// Written into the same `updates` object, so the visit lands atomically with
// the url-* record in one chrome.storage.local.set.
const host = siteKey(url);
if (host && !isSearchEngine) {
const siteVisits = result.siteVisits || {};
siteVisits[host] = pruneVisits([...(siteVisits[host] || []), now], now);
updates.siteVisits = siteVisits;
}
resolve(updates)
});
});
}
// Record a visit when a tab is ACTIVATED (switched to), throttled per site.
// Resolves the activated tab, ignores untrackable/missing tabs, and only counts
// the access as a visit when the site's most recent visit is older than
// ACCESS_THROTTLE_MS — otherwise the open→activate sequence and alt-tabbing
// would double-count. Delegates the actual write to newUrl so access-visits and
// open-visits stay identical in shape (allUrls maintenance, visits/visitCount,
// pruning). Returns newUrl's updates object, or undefined when throttled/ineligible.
async function recordAccess(tabId) {
let tab;
try {
tab = await chrome.tabs.get(tabId);
} catch (e) {
return; // tab gone / lastError — nothing to record
}
if (!tab || !tab.url || !isTrackableUrl(tab.url)) return;
const urlKey = getUrlKey(tab.url);
const result = await getStorage(urlKey);
const record = result[urlKey];
const visits = (record && record.visits) || [];
const lastVisit = visits.length ? Math.max(...visits.map(Number)) : 0;
const now = Date.now();
if (now - lastVisit < ACCESS_THROTTLE_MS) return; // within throttle window
return newUrl(tab.id, tab.url);
}
function closeUrl(urlKey, callback) {
getStorage(['allUrls', 'deletedUrls'], (result) => {
const allUrls = result.allUrls || [];
const deletedUrls = result.deletedUrls || {};
// The page was JUST deleted from History in the popup process, but this
// handler is running off `chrome.tabs.onRemoved` in the service worker with
// a pre-delete snapshot in hand. Without this check the move-to-front below
// writes the key straight back at index 0 — and since the delete already
// removed the `url-*` record, the resurrected row renders as a bare URL.
// Skipping costs nothing: closeUrl only ever REORDERS an existing key.
if (deletedUrls[urlKey]) {
if (callback) return callback();
return;
}
const oldIndex = allUrls.indexOf(urlKey);
// An untracked key has oldIndex -1, and `splice(-1, 1)` removes the LAST
// element — so the unguarded move-to-front below would silently promote the
// OLDEST key to the front, corrupting the recency order the eviction trim in
// `newUrl` depends on. Nothing to reorder for a key we never tracked.
if (oldIndex === -1) {
if (callback) return callback();
return;
}
allUrls.splice(0, 0, allUrls.splice(oldIndex, 1)[0]);
update({ allUrls: allUrls });
if (callback) return callback();
});
}
function processesApiAvailable() {
return !!(typeof chrome !== 'undefined' && chrome.processes && chrome.processes.onUpdatedWithMemory);
}
function systemApiAvailable() {
return !!(
typeof chrome !== 'undefined' &&
chrome.system && chrome.system.cpu && chrome.system.memory
);
}
// Channel-based degradation for the Browser Load gauge:
// - Dev/Canary (chrome.processes present): true per-process + per-tab data,
// loadDataSource written as 'processes' alongside processTotals.
// - Stable Chrome (chrome.system.* present): whole-browser/OS load drives the
// gauge, loadDataSource 'system'. Per-tab data is unavailable by necessity.
// - Neither (permissions denied): loadDataSource 'none' so the UI can say so.
function initLoadSource() {
if (processesApiAvailable()) {
// processProcesses writes loadDataSource:'processes' with the first totals,
// so there is no storage write at load time on this path.
listenToProcesses();
return;
}
if (systemApiAvailable()) {
startSystemLoadPolling();
return;
}
update({ loadDataSource: 'none' });
}
function listenToProcesses() {
try {
chrome.processes.onUpdatedWithMemory.addListener(processProcesses);
} catch (e) {
console.log("Unable to listen to processes", e);
}
}
function getSystemCpuInfo() {
return Promise.resolve().then(() => chrome.system.cpu.getInfo());
}
function getSystemMemoryInfo() {
return Promise.resolve().then(() => chrome.system.memory.getInfo());
}
function startSystemLoadPolling() {
if (systemPollTimer) return;
const poll = async () => {
// Defensive: if the richer processes API appears mid-session, switch to it.
if (processesApiAvailable()) {
stopSystemLoadPolling();
listenToProcesses();
return;
}
await pollSystemLoad();
systemPollTimer = setTimeout(poll, SYSTEM_POLL_INTERVAL_MS);
};