Repository navigation
Expand file tree
/
Copy pathservice_worker.js
More file actions
1579 lines (1437 loc) · 64.9 KB
/
Copy pathservice_worker.js
File metadata and controls
1579 lines (1437 loc) · 64.9 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 samePageKey from './src/lib/utils/samePageKey.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';
import { mergeTrackingUpdates } from './src/lib/utils/urlRecordDisplay.js';
import { getUrlKey, newUrl, recordAccess, tabUpdates } from './src/lib/worker/urlTracking.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';
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(urlTrackingDeps, 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 = mergeTrackingUpdates(updates, await newUrl(urlTrackingDeps, 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(urlTrackingDeps, 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 = mergeTrackingUpdates(await tabUpdates(urlTrackingDeps, tab), await newUrl(urlTrackingDeps, 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);
}
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);
};
poll();
}
function stopSystemLoadPolling() {
if (systemPollTimer) {
clearTimeout(systemPollTimer);
systemPollTimer = null;
}
}
async function pollSystemLoad() {
try {
const cpuInfo = await getSystemCpuInfo();
const memoryInfo = await getSystemMemoryInfo();
const processTotals = deriveSystemTotals(
previousCpuSample,
cpuInfo,
memoryInfo,
GAUGE
);
previousCpuSample = cpuInfo;
update({ processTotals, loadDataSource: 'system' });
} catch (e) {
console.log("Unable to sample system load", e);
stopSystemLoadPolling();
update({ loadDataSource: 'none' });
}
}
let samples = 0;
let processesIndex = { global: 0 };
// What the url-* record write paths in urlTracking.js need from this worker.
const urlTrackingDeps = {
getStorage: (query, callback) => getStorage(query, callback),
getTab: (tabId) => chrome.tabs.get(tabId),
removeRecord: (urlKey) => chrome.storage.local.remove(urlKey),
validTab: (tab) => validTab(tab),
processesIndex,
onVisit: () => updateActiveTabs(),
};
async function processProcesses(processes) {
samples += 1;
processesIndex.global += 1;
let updates = {
loadDataSource: 'processes',
processTotals: {
cpu: 0,
network: 0,
privateMemory: 0,
jsMemoryAllocated: 0,
jsMemoryUsed: 0
}
}
for (const pid in processes) {
updates = updateTotals(processes[pid], updates);
updates = await associateProcess(processes[pid], updates);
}
update(updates);
if (samples > 10) {
samples = 0;
try {
chrome.processes.onUpdatedWithMemory.removeListener(processProcesses);
} catch (e) {
console.log("Unable to remove processes listener", e);
}
listening = false;
setTimeout(() => {
if (!listening) {
listenToProcesses();
}
}, 15000);
}
}
function updateTotals(process, updates) {
updates.processTotals.cpu += process.cpu || 0;
updates.processTotals.network += process.network || 0;
updates.processTotals.privateMemory += process.privateMemory || 0;
updates.processTotals.jsMemoryAllocated += process.jsMemoryAllocated || 0;
updates.processTotals.jsMemoryUsed += process.jsMemoryUsed || 0;
return updates;
}
async function associateProcess(process, updates) {
const tabIds = process.tasks.map(
(task) => task.tabId
).filter(
(tabId) => tabId !== undefined
);
for (const tabId of tabIds) {
try {
const tab = await chrome.tabs.get(tabId);
updates = {
...updates,
...(await tabUpdates(urlTrackingDeps, tab, process, updates))
};
} catch (e) {
}
}
return updates;
}
// Bidirectional Chrome group-color <-> hex map. Lifted to module scope so both
// `groupTabs` (group.color -> hex when seeding a label) and
// `handleActiveTabsGroupChanges` (seeding a missing label on the add path) share
// one definition. Passing a hex returns the named color and vice versa.
function mapColors(labelColor) {
const map = {
'#5F6367': 'grey',
'#1873E4': 'blue',
'#DA2F25': 'red',
'#E47415': 'yellow',
'#1F8E43': 'green',
'#D01882': 'pink',
'#9334E2': 'purple',
'#007B82': 'cyan'
};
for (const key of Object.keys(map)) map[map[key]] = key;
return map[labelColor];
}
function validTab(tab) {
// Incognito visits are intentionally never persisted — they must leave no
// trace in history/activeTabs, so they can never surface in Search or
// Favorites. Treat them as invalid everywhere validTab is consulted.
return tab.url &&
tab.url.length &&
!tab.incognito &&
tab.url.indexOf('chrome://') === -1 &&
tab.url.indexOf('devtools://') === -1 &&
tab.url.indexOf('chrome-extension://') === -1
}
let labels = {};
let activeTabs = [];
// Resolve `labels` through the migration FIRST — it is the only place that reads
// both areas and decides which copy wins (sync when populated, local otherwise,
// copying local -> sync when sync is empty). Running it ahead of the bootstrap
// read means the session always starts from the durable copy, and a first boot
// after the upgrade backs up the user's existing groups before anything can
// touch them. `activeTabs` is local and unaffected, so it still comes from the
// ordinary read.
migrateLabelsToSync((migration) => {
labels = migration.labels || {};
// Seed the coalescing memo with what storage now holds, so the first ordinary
// tab event after boot doesn't re-persist an identical `labels`.
lastPersistedLabels = JSON.stringify(labels);
debugGroup('boot: labels migration resolved', {
outcome: migration.outcome,
groupCount: Object.keys(labels).length
});
});
getStorage(['activeTabs'], (result) => {
activeTabs = result.activeTabs || [];
// Deliberately does NOT call groupTabs here. `activeTabs` is a PERSISTED
// snapshot, and Chrome tab ids are unique only within a browser session — after
// a restart those ids refer to different tabs entirely. MV3 wakes this worker
// constantly, so grouping from the snapshot means `chrome.tabs.group` /
// `chrome.tabs.ungroup` firing at unrelated tabs on the first wake, moving them
// with the user doing nothing at all.
//
// Nothing is lost by dropping it: the module-level `updateActiveTabs()` call
// re-reads LIVE tabs and writes `activeTabs`, and that write re-enters
// `storage.onChanged` -> `groupTabs` with live tab ids and live group ids. The
// only cost is one storage round-trip of latency on the first grouping pass
// after a worker wake.
});
chrome.storage.onChanged.addListener(
(changes, areaName) => {
// The two keys now live in different areas, so a single change event carries
// only one of them. Gate each against ITS OWN area rather than against a
// single hardcoded `'local'` — that check would have dropped every `labels`
// event once labels moved to sync, leaving the in-memory copy stale.
const labelsChanged = areaName === areaForKey('labels') && !!changes.labels;
const activeTabsChanged = areaName === areaForKey('activeTabs') && !!changes.activeTabs;
if (!labelsChanged && !activeTabsChanged) return;
if (labelsChanged) {
// Coerce a removal to `{}`. `changes.labels.newValue` is undefined when the
// key is removed, and while `findLabelForUrlKey` is null-tolerant by
// contract, the bare `labels[group.title]` dereferences in `groupTabs` and
// `recordInGroupTab` are not. Cross-area transitions — a sync area that is
// unavailable, garbage-collected, or simply not yet populated — make an
// absent `labels` materially more likely than it was when everything was
// local.
const priorLabels = changes.labels.oldValue || {};
labels = changes.labels.newValue || {};
// Titles present before this change and absent after it are exactly the
// groups the user just deleted. Both bookkeeping steps run BEFORE the
// `groupTabs` call below, because groupTabs on THIS pass is the thing that
// would otherwise re-record a deleted label — `dissolveDeletedLabelGroups`
// is async and its `pendingUngroups` marks cannot land in time to stop it.
const deletedTitles = deletedLabelTitles(priorLabels, labels);
for (const title of deletedTitles) userDeletedLabels.add(title);
// A title back in `labels` is no longer deleted, however it got there —
// re-created by hand, or pushed in by sync from another device.
for (const title of Object.keys(labels)) userDeletedLabels.delete(title);
if (deletedTitles.length > 0) dissolveDeletedLabelGroups(deletedTitles);
}
if (activeTabsChanged) {
activeTabs = changes.activeTabs.newValue;
handleActiveTabsGroupChanges(changes.activeTabs);
}
groupTabs(activeTabs, labels);
if (labelsChanged) {
const previous = changes.labels.oldValue;
getStorage('previousLabels', (result) => {
const previousLabels = result.previousLabels || [];