Repository navigation
Expand file tree
/
Copy pathservice_worker.test.js
More file actions
2277 lines (2029 loc) · 101 KB
/
Copy pathservice_worker.test.js
File metadata and controls
2277 lines (2029 loc) · 101 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 fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
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 { 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 findLabelForUrlKey from './src/lib/utils/findLabelForUrlKey.js';
import deletedLabelTitles from './src/lib/utils/deletedLabelTitles.js';
import { mergeTrackingUpdates } from './src/lib/utils/urlRecordDisplay.js';
import { getUrlKey, newUrl, recordAccess, tabUpdates } from './src/lib/worker/urlTracking.js';
// service_worker.js is a vanilla (non-module) background script: it declares
// top-level functions and immediately registers chrome.*
// listeners / queries at load time. To exercise the functions without editing
// the source, we read the file and evaluate it in a sloppy-mode Function
// wrapper with a stubbed `chrome` injected, then return the top-level
// declarations plus getters onto the module-level mutable state. The chrome
// stub's callback-taking methods are no-ops by default so the load-time side
// effects register listeners but never run their async bodies; individual
// tests reconfigure the stubs they need.
const SW_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), 'service_worker.js');
function makeChrome() {
const evt = () => ({ addListener: vi.fn(), removeListener: vi.fn() });
return {
tabGroups: {
onCreated: evt(),
onUpdated: evt(),
query: vi.fn(),
get: vi.fn(),
update: vi.fn(),
},
tabs: {
WindowType: { NORMAL: 'normal' },
onUpdated: evt(),
onActivated: evt(),
onCreated: evt(),
onReplaced: evt(),
onMoved: evt(),
onRemoved: evt(),
query: vi.fn(),
get: vi.fn(),
group: vi.fn(),
ungroup: vi.fn(),
remove: vi.fn(),
create: vi.fn(),
update: vi.fn(),
},
processes: { onUpdatedWithMemory: evt() },
alarms: {
create: vi.fn(),
onAlarm: evt(),
},
storage: {
local: { get: vi.fn(), set: vi.fn(), remove: vi.fn() },
onChanged: evt(),
},
runtime: { getURL: vi.fn((p) => `chrome-extension://abc/${p}`) },
};
}
// service_worker.js is shipped as an ES-module service worker (crxjs sets
// `"type": "module"` at build), so it `import`s the pure deriveSystemTotals util.
// The Function wrapper here can't hold a top-level `import`, so we strip the
// import line and inject the REAL util as a parameter — the worker tests then
// exercise the same util that deriveSystemTotals.test.js covers.
//
// ES modules are always strict, so the wrapper body opens with 'use strict'.
// Without it an undeclared assignment such as `for (tabId of tabIds)` silently
// creates a global here while throwing ReferenceError in the shipped worker.
function loadWorker(chrome) {
// The worker's `update` / `getStorage` delegate to the storageAccess module,
// which is a REAL import here and therefore reads the ambient global `chrome`
// — not the mock passed as a Function parameter below. In the shipped service
// worker those are the same object; the parameter injection is an artifact of
// the sloppy-mode Function wrapper. Publishing the mock globally HERE (rather
// than in beforeEach) keeps them in step for the several tests that build
// their own chrome and call loadWorker directly.
//
// Note the mocks deliberately expose NO `chrome.storage.sync`, which exercises
// storageAccess's degrade-to-local path — the behavior a host without a sync
// area gets, identical to this worker's pre-sync behavior.
globalThis.chrome = chrome;
const raw = fs.readFileSync(SW_PATH, 'utf8');
const code = raw.replace(/^\s*import\s.*$/gm, '');
const factory = new Function(
'chrome',
'console',
'deriveSystemTotals',
'samePageKey',
'appendGroupingLog',
'healDriftedLabelSlot',
'navigatedAwayFromRecordedSlot',
'buildGroupRemovalEntry',
'GROUP_REMOVAL_LOG_KEY',
'GROUP_REMOVAL_LOG_CAP',
'RemovalSource',
'buildGroupAdditionEntry',
'GROUP_ADDITION_LOG_KEY',
'GROUP_ADDITION_LOG_CAP',
'AdditionSource',
'buildGroupMoveEntry',
'GROUP_MOVE_LOG_KEY',
'GROUP_MOVE_LOG_CAP',
'MoveSource',
'needsGroupCall',
'needsUngroupCall',
'bucketTabsByWindow',
'findLabelForUrlKey',
'deletedLabelTitles',
'areaForKey',
'readByArea',
'writeByArea',
'migrateLabelsToSync',
'mergeTrackingUpdates',
'getUrlKey',
'newUrl',
'recordAccess',
'tabUpdates',
`'use strict';
${code}
;return {
fns: { trackGroup, listenToProcesses, updateActiveTabs, update,
closeUrl, processProcesses, updateTotals, associateProcess,
validTab, getTabGroup, mapColors,
getStorage, parseTabId, handleActiveTabsGroupChanges, groupTabs,
initLoadSource, processesApiAvailable, systemApiAvailable,
startSystemLoadPolling, stopSystemLoadPolling, pollSystemLoad,
autoCloseSweep, isAutoCloseEligible, pruneAutoClosed,
autoCloseThresholdMinutes, urlKeyIsMember, ejectAutoGroupedTab,
recordInGroupTab, debugGroup, stampLabelMembership,
dissolveDeletedLabelGroups },
state: {
get groups() { return groups; },
get samples() { return samples; },
get processesIndex() { return processesIndex; },
get pendingUngroups() { return pendingUngroups; },
get autoGroupedTabs() { return autoGroupedTabs; },
get userDeletedLabels() { return userDeletedLabels; },
}
};`
);
return factory(chrome, { log: vi.fn(), error: vi.fn() }, deriveSystemTotals, samePageKey, appendGroupingLog, healDriftedLabelSlot, navigatedAwayFromRecordedSlot, buildGroupRemovalEntry, GROUP_REMOVAL_LOG_KEY, GROUP_REMOVAL_LOG_CAP, RemovalSource, buildGroupAdditionEntry, GROUP_ADDITION_LOG_KEY, GROUP_ADDITION_LOG_CAP, AdditionSource, buildGroupMoveEntry, GROUP_MOVE_LOG_KEY, GROUP_MOVE_LOG_CAP, MoveSource, needsGroupCall, needsUngroupCall, bucketTabsByWindow, findLabelForUrlKey, deletedLabelTitles, areaForKey, readByArea, writeByArea, migrateLabelsToSync, mergeTrackingUpdates, getUrlKey, newUrl, recordAccess, tabUpdates);
}
describe('service_worker.js', () => {
let chrome;
let fns;
let state;
beforeEach(() => {
chrome = makeChrome();
const loaded = loadWorker(chrome);
fns = loaded.fns;
state = loaded.state;
});
afterEach(() => {
delete globalThis.chrome;
});
// registers chrome listeners at load without throwing
it('loads and registers chrome event listeners on import', () => {
expect(chrome.tabs.onUpdated.addListener).toHaveBeenCalled();
expect(chrome.tabGroups.onCreated.addListener).toHaveBeenCalled();
expect(chrome.storage.onChanged.addListener).toHaveBeenCalled();
expect(chrome.processes.onUpdatedWithMemory.addListener).toHaveBeenCalled();
});
describe('mapColors', () => {
// maps a Chrome named color to its hex value (used when seeding a label's color)
it('maps a named color to hex', () => {
expect(fns.mapColors('blue')).toBe('#1873E4');
expect(fns.mapColors('grey')).toBe('#5F6367');
});
// maps a hex value back to its Chrome named color (used when grouping from a label)
it('maps a hex value back to a named color', () => {
expect(fns.mapColors('#1F8E43')).toBe('green');
expect(fns.mapColors('#007B82')).toBe('cyan');
});
// an unknown color (neither a known name nor hex) resolves to undefined
it('returns undefined for an unknown color', () => {
expect(fns.mapColors('chartreuse')).toBeUndefined();
expect(fns.mapColors('#ABCDEF')).toBeUndefined();
});
});
describe('validTab', () => {
// accepts ordinary web URLs
it('accepts http and https tabs', () => {
expect(fns.validTab({ url: 'https://example.com' })).toBeTruthy();
});
// rejects empty and browser-internal schemes
it('rejects empty and internal-scheme tabs', () => {
expect(fns.validTab({ url: '' })).toBeFalsy();
expect(fns.validTab({ url: 'chrome://settings' })).toBe(false);
expect(fns.validTab({ url: 'devtools://devtools/x' })).toBe(false);
expect(fns.validTab({ url: 'chrome-extension://abc/index.html' })).toBe(false);
});
// incognito tabs are invalid everywhere validTab is consulted, so their
// visits never reach activeTabs or the url-* process records.
it('rejects incognito tabs', () => {
expect(fns.validTab({ url: 'https://secret.com', incognito: true })).toBe(false);
});
});
// Incognito navigations must leave no trace: the onUpdated handler's direct
// changeInfo.url recording path (which bypasses validTab) is guarded so an
// incognito navigation never enters allUrls or bumps visitCount, while a
// normal-tab navigation still records as before.
describe('onUpdated incognito guard', () => {
// A storage mock that answers each query shape with sensible empties so the
// handler (and the newUrl it may call) can run to completion.
const emptyStorage = (chrome) => {
chrome.storage.local.get.mockImplementation((query, cb) => {
const keys =
typeof query === 'string'
? [query]
: Array.isArray(query)
? query
: Object.keys(query);
const res = {};
for (const k of keys) {
if (k === 'allUrls') res.allUrls = [];
else if (k === 'activeTabs') res.activeTabs = [];
else if (k === 'autoClosed') res.autoClosed = {};
else if (k === 'labels') res.labels = {};
// url-* keys stay absent (undefined), as on a first visit.
}
cb(res);
});
chrome.tabs.query.mockImplementation((_q, cb) => cb([]));
};
const getHandler = (chrome) =>
chrome.tabs.onUpdated.addListener.mock.calls[0][0];
// Did any storage write add this urlKey to allUrls (i.e. record the visit)?
const recordedAllUrls = (chrome, urlKey) =>
chrome.storage.local.set.mock.calls.some(
(c) => Array.isArray(c[0].allUrls) && c[0].allUrls.includes(urlKey)
);
// A normal navigation records the url; the incognito one must not.
it('records a normal-tab navigation but not an incognito one', async () => {
emptyStorage(chrome);
const onUpdated = getHandler(chrome);
// Normal tab navigating to a new URL → recorded into allUrls.
chrome.storage.local.set.mockClear();
await onUpdated(
1,
{ url: 'https://normal.com' },
{ id: 1, url: 'https://normal.com', incognito: false }
);
expect(recordedAllUrls(chrome, 'url-https://normal.com')).toBe(true);
// Incognito tab navigating to a new URL → never recorded.
chrome.storage.local.set.mockClear();
await onUpdated(
2,
{ url: 'https://secret.com' },
{ id: 2, url: 'https://secret.com', incognito: true }
);
expect(recordedAllUrls(chrome, 'url-https://secret.com')).toBe(false);
});
});
describe('parseTabId', () => {
// extracts the integer tab id from a "tab-<n>" key
it('parses the numeric id from a tabKey', () => {
expect(fns.parseTabId({ tabKey: 'tab-42' })).toBe(42);
});
});
describe('updateTotals', () => {
// accumulates each process metric into the running totals
it('sums process metrics into processTotals', () => {
const updates = { processTotals: { cpu: 1, network: 1, privateMemory: 0, jsMemoryAllocated: 0, jsMemoryUsed: 0 } };
const out = fns.updateTotals(
{ cpu: 2, network: 3, privateMemory: 4, jsMemoryAllocated: 5, jsMemoryUsed: 6 },
updates
);
expect(out.processTotals).toEqual({ cpu: 3, network: 4, privateMemory: 4, jsMemoryAllocated: 5, jsMemoryUsed: 6 });
});
// treats missing metrics as zero
it('defaults missing metrics to 0', () => {
const updates = { processTotals: { cpu: 0, network: 0, privateMemory: 0, jsMemoryAllocated: 0, jsMemoryUsed: 0 } };
const out = fns.updateTotals({}, updates);
expect(out.processTotals.cpu).toBe(0);
});
});
describe('update', () => {
// writes the supplied object straight to chrome.storage.local
it('persists updates to chrome.storage.local', () => {
fns.update({ allUrls: ['url-a'] });
expect(chrome.storage.local.set).toHaveBeenCalledWith({ allUrls: ['url-a'] });
});
// labels now lives in chrome.storage.sync, which caps writes at 120/minute.
// recordInGroupTab runs per tab from groupTabs on every activeTabs change, so
// re-persisting an identical labels map would breach the quota within a
// minute of ordinary browsing.
it('drops a labels write identical to the last one persisted', () => {
fns.update({ labels: { Work: { title: 'Work' } } });
chrome.storage.local.set.mockClear();
fns.update({ labels: { Work: { title: 'Work' } } });
expect(chrome.storage.local.set).not.toHaveBeenCalled();
});
// the guard must only suppress genuinely-identical content — a real group
// edit still has to reach storage
it('persists a labels write whose content changed', () => {
fns.update({ labels: { Work: { title: 'Work' } } });
chrome.storage.local.set.mockClear();
fns.update({ labels: { Work: { title: 'Renamed' } } });
expect(chrome.storage.local.set).toHaveBeenCalledWith({ labels: { Work: { title: 'Renamed' } } });
});
// dropping a redundant labels key must not drop its co-written keys — the
// activeTabs membership stamp rides along in the same call
it('still writes companion keys when the labels key is dropped', () => {
const labels = { Work: { title: 'Work' } };
fns.update({ labels });
chrome.storage.local.set.mockClear();
fns.update({ labels, activeTabs: [{ tabKey: 'tab-1' }] });
expect(chrome.storage.local.set).toHaveBeenCalledWith({ activeTabs: [{ tabKey: 'tab-1' }] });
});
// when the redundant labels key was the ONLY key, no write should be issued
// at all rather than an empty set
it('issues no write when the dropped labels key was the only key', () => {
const labels = { Work: { title: 'Work' } };
fns.update({ labels });
chrome.storage.local.set.mockClear();
fns.update({ labels });
expect(chrome.storage.local.set).not.toHaveBeenCalled();
});
});
describe('getStorage', () => {
// invokes the callback form with the chrome result
it('invokes the callback with the storage result', () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ activeTabs: [1] }));
const cb = vi.fn();
fns.getStorage('activeTabs', cb);
expect(cb).toHaveBeenCalledWith({ activeTabs: [1] });
});
// resolves a promise with the result when no callback is given
it('resolves with the result when no callback is passed', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ labels: {} }));
await expect(fns.getStorage('labels')).resolves.toEqual({ labels: {} });
});
});
describe('getTabGroup', () => {
// short-circuits to null for absent / sentinel ids
it('resolves null for id -1 or null', async () => {
await expect(fns.getTabGroup(-1)).resolves.toBeNull();
await expect(fns.getTabGroup(null)).resolves.toBeNull();
});
// resolves the chrome.tabGroups.get result for a real id
it('resolves the group for a real id', async () => {
chrome.tabGroups.get.mockImplementation((_id, cb) => cb({ id: 3, title: 'Work' }));
await expect(fns.getTabGroup(3)).resolves.toEqual({ id: 3, title: 'Work' });
});
});
describe('trackGroup', () => {
// records the group title keyed by its integer id
it('stores the group title by id', () => {
fns.trackGroup({ id: '5', title: 'Reading' });
expect(state.groups[5]).toBe('Reading');
});
});
describe('listenToProcesses', () => {
// subscribes processProcesses to the memory-update event
it('registers the processes listener', () => {
chrome.processes.onUpdatedWithMemory.addListener.mockClear();
fns.listenToProcesses();
expect(chrome.processes.onUpdatedWithMemory.addListener).toHaveBeenCalledWith(fns.processProcesses);
});
// swallows the error when the processes API is unavailable
it('does not throw when the processes API throws', () => {
chrome.processes.onUpdatedWithMemory.addListener.mockImplementation(() => {
throw new Error('no processes API');
});
expect(() => fns.listenToProcesses()).not.toThrow();
});
});
describe('closeUrl', () => {
// moves the closed url to the front of allUrls and runs the callback
it('reorders allUrls, persists, and invokes the callback', () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ allUrls: ['url-a', 'url-b', 'url-c'] }));
const done = vi.fn();
fns.closeUrl('url-c', done);
expect(chrome.storage.local.set).toHaveBeenCalledWith({ allUrls: ['url-c', 'url-a', 'url-b'] });
expect(done).toHaveBeenCalled();
});
// REGRESSION: an UNTRACKED key has indexOf -1, and splice at -1 removes the
// LAST element — so the unguarded move-to-front silently promoted the OLDEST
// key to the front, corrupting the recency order the eviction trim relies on.
// Nothing to reorder for a key we never tracked: leave allUrls alone.
it('leaves allUrls untouched when the key is not tracked', () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ allUrls: ['url-a', 'url-b', 'url-c'] }));
const done = vi.fn();
fns.closeUrl('url-never-seen', done);
expect(chrome.storage.local.set).not.toHaveBeenCalled();
expect(done).toHaveBeenCalled();
});
// REGRESSION: deleting a page from History splices it out of allUrls, but the
// tab close that accompanies the delete fires onRemoved -> closeUrl in the
// service worker process. closeUrl read allUrls before the delete landed, so
// its move-to-front wrote the key straight back at index 0 -- the row
// reappeared at the top of History, titleless because the url-* record was
// already gone. A deletedUrls tombstone makes closeUrl skip the key.
it('leaves allUrls untouched when the key was just deleted', () => {
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ allUrls: ['url-a', 'url-b', 'url-c'], deletedUrls: { 'url-c': 1 } })
);
const done = vi.fn();
fns.closeUrl('url-c', done);
expect(chrome.storage.local.set).not.toHaveBeenCalled();
expect(done).toHaveBeenCalled();
});
// The tombstone is checked by PRESENCE of the specific key, not by "is the
// map non-empty" — an unrelated deletion must not freeze every other row's
// recency ordering.
it('still reorders a tracked key when a different key is tombstoned', () => {
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ allUrls: ['url-a', 'url-b', 'url-c'], deletedUrls: { 'url-a': 1 } })
);
const done = vi.fn();
fns.closeUrl('url-c', done);
expect(chrome.storage.local.set).toHaveBeenCalledWith({ allUrls: ['url-c', 'url-a', 'url-b'] });
expect(done).toHaveBeenCalled();
});
});
describe('updateActiveTabs', () => {
// queries normal-window tabs and writes the rebuilt activeTabs list
it('queries tabs and persists the rebuilt active list', () => {
chrome.tabs.query.mockImplementation((_q, cb) =>
cb([{ id: 1, url: 'https://a.com', pinned: false, groupId: -1, active: true, tabIndex: 0 }])
);
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ activeTabs: [], autoClosed: {} }));
fns.updateActiveTabs();
expect(chrome.tabs.query).toHaveBeenCalled();
expect(chrome.storage.local.set).toHaveBeenCalled();
const written = chrome.storage.local.set.mock.calls.at(-1)[0];
expect(written.activeTabs[0].urlKey).toBe('url-https://a.com');
});
// A Chrome Tab exposes `index`, not `tabIndex`. The old comparator subtracted
// two undefineds, returned NaN for every pair, and the sort silently did
// nothing — so activeTabs never actually reflected tab-strip order.
it('sorts tabs by their tab-strip index', () => {
chrome.tabs.query.mockImplementation((_q, cb) =>
cb([
{ id: 3, url: 'https://c.com', pinned: false, groupId: -1, index: 2 },
{ id: 1, url: 'https://a.com', pinned: false, groupId: -1, index: 0 },
{ id: 2, url: 'https://b.com', pinned: false, groupId: -1, index: 1 },
])
);
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ activeTabs: [], autoClosed: {} }));
fns.updateActiveTabs();
const written = chrome.storage.local.set.mock.calls.at(-1)[0];
expect(written.activeTabs.map((t) => t.urlKey)).toEqual([
'url-https://a.com',
'url-https://b.com',
'url-https://c.com',
]);
});
// Returning to a page the Closer had closed used to ungroup it unconditionally.
// When the URL is a label member, groupTabs pulls it straight back in on the
// next pass — a visible out-and-back jump on every revisit. Clearing the
// autoClosed entry is the point; the eject is not.
it('does not eject a revisited auto-closed tab whose url is a label member', () => {
chrome.tabs.query.mockImplementation((_q, cb) =>
cb([{ id: 1, url: 'https://a.com', pinned: false, groupId: 5, index: 0, active: true }])
);
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({
activeTabs: [],
autoClosed: { 'url-https://a.com': 123 },
labels: { Work: { title: 'Work', urlKeys: ['url-https://a.com'] } },
})
);
fns.updateActiveTabs();
expect(chrome.tabs.ungroup).not.toHaveBeenCalled();
// The autoClosed entry is still cleared — only the move is suppressed.
const written = chrome.storage.local.set.mock.calls.at(-1)[0];
expect(written.autoClosed['url-https://a.com']).toBeUndefined();
});
// Guards against over-suppression: a revisited auto-closed tab that no label
// claims is still ejected, exactly as before.
it('still ejects a revisited auto-closed tab that no label claims', () => {
chrome.tabs.query.mockImplementation((_q, cb) =>
cb([{ id: 1, url: 'https://a.com', pinned: false, groupId: 5, index: 0, active: true }])
);
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({
activeTabs: [],
autoClosed: { 'url-https://a.com': 123 },
labels: { Work: { title: 'Work', urlKeys: ['url-https://zzz.com'] } },
})
);
fns.updateActiveTabs();
expect(chrome.tabs.ungroup).toHaveBeenCalledWith(1);
});
});
describe('onUpdated navigation eject', () => {
// Build a worker whose storage answers the load-time labels/activeTabs read and
// the per-url reads onUpdated performs, then hand back its onUpdated listener.
const loadForNavigation = ({ labels, recordedUrlKey }) => {
const nav = makeChrome();
nav.tabGroups.get.mockImplementation((id, cb) => cb({ id, title: 'Work', color: 'blue' }));
nav.storage.local.get.mockImplementation((query, cb) => {
// Boot now reads the two keys SEPARATELY: `labels` through the
// local -> sync migration (this mock exposes no sync area, so the
// migration falls back to a local ['labels'] read) and `activeTabs`
// through the ordinary bootstrap. They used to arrive as one combined
// ['labels','activeTabs'] query.
if (Array.isArray(query) && query.includes('labels')) {
cb({ labels });
return;
}
if (Array.isArray(query) && query.includes('activeTabs')) {
cb({ activeTabs: [] });
return;
}
if (query === 'activeTabs') {
cb({
activeTabs: [
{ tabKey: 'tab-7', urlKey: recordedUrlKey, pinned: false, groupId: 5, windowId: 1 },
],
});
return;
}
cb({});
});
const loaded = loadWorker(nav);
return { nav, listener: nav.tabs.onUpdated.addListener.mock.calls[0][0], loaded };
};
// Sites that rewrite their own path with no user input (auth bounces, redirect
// chains, chat and doc apps) tripped the navigation eject on every rewrite. If
// the new URL is ALSO a member of the tab's label, ejecting it only has
// groupTabs pull it straight back in — the user watches the tab pop out of the
// group and snap back, having touched nothing.
it('does not eject when the tab navigates to another url in the same label', async () => {
const { nav, listener } = loadForNavigation({
labels: {
Work: {
title: 'Work',
urlKeys: ['url-https://a.com/apps', 'url-https://a.com/other'],
},
},
recordedUrlKey: 'url-https://a.com/apps',
});
await listener(
7,
{ url: 'https://a.com/other' },
{ id: 7, url: 'https://a.com/other', groupId: 5, windowId: 1, title: 'A' }
);
expect(nav.tabs.ungroup).not.toHaveBeenCalled();
});
// Guards against over-suppression: a genuine navigation to a URL no label
// claims must still eject the tab, which is the whole point of the eject path.
it('still ejects when the tab navigates to a url no label claims', async () => {
const { nav, listener } = loadForNavigation({
labels: { Work: { title: 'Work', urlKeys: ['url-https://a.com/apps'] } },
recordedUrlKey: 'url-https://a.com/apps',
});
await listener(
7,
{ url: 'https://elsewhere.com/page' },
{ id: 7, url: 'https://elsewhere.com/page', groupId: 5, windowId: 1, title: 'E' }
);
expect(nav.tabs.ungroup).toHaveBeenCalled();
expect(nav.tabs.ungroup.mock.calls[0][0]).toBe(7);
});
});
describe('cold start grouping', () => {
// Chrome tab ids are unique only within a browser session. After a restart the
// PERSISTED activeTabs snapshot holds ids that now belong to entirely different
// tabs, and MV3 wakes this worker constantly — so grouping from that snapshot
// moved unrelated tabs with the user doing nothing at all. The first pass must
// wait for live tabs, which updateActiveTabs re-reads and writes.
it('does not group from the persisted snapshot when the worker wakes', async () => {
const cold = makeChrome();
cold.tabGroups.query.mockImplementation((_q, cb) => cb([{ id: 5, windowId: 1, title: 'Work' }]));
cold.storage.local.get.mockImplementation((query, cb) => {
if (Array.isArray(query) && query.includes('labels') && query.includes('activeTabs')) {
cb({
labels: { Work: { title: 'Work', urlKeys: ['url-https://a.com'] } },
// A stale id: tab 99 was a member last session; it is some other tab now.
activeTabs: [
{ tabKey: 'tab-99', urlKey: 'url-https://a.com', pinned: false, groupId: -1, windowId: 1 },
],
});
}
});
loadWorker(cold);
await Promise.resolve();
expect(cold.tabs.group).not.toHaveBeenCalled();
expect(cold.tabs.ungroup).not.toHaveBeenCalled();
});
});
describe('processProcesses', () => {
// increments the sample counter and writes accumulated totals
it('bumps samples and persists process totals', async () => {
const before = state.samples;
await fns.processProcesses({}); // no pids → totals only
expect(state.samples).toBe(before + 1);
expect(chrome.storage.local.set).toHaveBeenCalled();
});
// a process that owns a tab must persist both the totals and that tab's
// per-url stats — the write associateProcess used to abort before reaching
it('persists per-tab url stats and totals for a process with a tab task', async () => {
chrome.tabs.get.mockResolvedValue({ url: 'https://a.com', status: 'complete', title: 'A', groupId: -1 });
chrome.storage.local.get.mockImplementation((_q, cb) => cb({}));
chrome.storage.local.set.mockClear();
await fns.processProcesses({ 7: { tasks: [{ tabId: 1 }], cpu: 3 } });
const written = chrome.storage.local.set.mock.calls.map(([arg]) => arg);
const payload = written.find((arg) => arg.loadDataSource === 'processes');
expect(payload.processTotals.cpu).toBe(3);
expect(payload['url-https://a.com']).toBeTruthy();
});
});
describe('associateProcess', () => {
// merges per-tab url updates for each task tab id in the process
it('fetches each task tab and merges its url updates', async () => {
chrome.tabs.get.mockResolvedValue({ url: 'https://a.com', status: 'complete', title: 'A', groupId: -1 });
chrome.storage.local.get.mockImplementation((_q, cb) => cb({}));
const out = await fns.associateProcess(
{ tasks: [{ tabId: 1 }], cpu: 1 },
{ processTotals: {} }
);
expect(chrome.tabs.get).toHaveBeenCalledWith(1);
expect(out['url-https://a.com']).toBeTruthy();
});
});
describe('handleActiveTabsGroupChanges', () => {
// returns early when there is no previous value to diff against
it('no-ops when oldValue is missing', async () => {
await expect(
fns.handleActiveTabsGroupChanges({ newValue: [], oldValue: undefined })
).resolves.toBeUndefined();
expect(chrome.storage.local.set).not.toHaveBeenCalled();
});
// The add path must seed a label that does not exist yet rather than throwing
// on `labels[title].urlKeys.push` (the previous `|| { urlKeys: [] }` fallback
// was never written back).
it('seeds a missing label on the add path without throwing', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) =>
cb(id === 5 ? { id: 5, title: 'NewGroup', color: 'blue' }
: { id: 2, title: 'OldGroup', color: 'red' })
);
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ labels: {} }));
await expect(
fns.handleActiveTabsGroupChanges({
oldValue: [{ tabKey: 'tab-1', urlKey: 'url-z', groupId: 2, pinned: false }],
newValue: [{ tabKey: 'tab-1', urlKey: 'url-z', groupId: 5, pinned: false }],
})
).resolves.not.toThrow();
const written = chrome.storage.local.set.mock.calls
.map((c) => c[0])
.find((o) => o && o.labels);
expect(written.labels.NewGroup.urlKeys).toContain('url-z');
// The seeded label carries the group's color, mapped to hex via mapColors.
expect(written.labels.NewGroup.color).toBe('#1873E4');
});
// A genuine re-home (tab moves directly from group A into group B) is
// unambiguous re-parent intent: it adds the member to B AND removes it from
// A, so a URL never accumulates membership in every group it passed through.
it('re-home A→B adds the member to B and removes it from A', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) =>
cb(id === 5 ? { id: 5, title: 'GroupB', color: 'blue' }
: { id: 2, title: 'GroupA', color: 'red' })
);
const labels = {
GroupA: { title: 'GroupA', urlKeys: ['url-z'] },
GroupB: { title: 'GroupB', urlKeys: [] },
};
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ labels }));
await fns.handleActiveTabsGroupChanges({
oldValue: [{ tabKey: 'tab-1', urlKey: 'url-z', groupId: 2, pinned: false }],
newValue: [{ tabKey: 'tab-1', urlKey: 'url-z', groupId: 5, pinned: false }],
});
const written = chrome.storage.local.set.mock.calls
.map((c) => c[0])
.find((o) => o && o.labels);
expect(written.labels.GroupB.urlKeys).toContain('url-z');
expect(written.labels.GroupA.urlKeys).not.toContain('url-z');
});
// Ungroup-to-nothing (newTab.groupId → -1, so there is no destination group)
// is NOT a re-home: membership is sticky, so the old group keeps the member.
it('ungroup-to-nothing keeps the member in the old group', async () => {
// getTabGroup(-1) resolves null, so the guard skips the whole diff body —
// no label is ever written.
chrome.tabGroups.get.mockImplementation((id, cb) =>
cb(id === 2 ? { id: 2, title: 'GroupA', color: 'red' } : null)
);
const labels = { GroupA: { title: 'GroupA', urlKeys: ['url-z'] } };
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ labels }));
await fns.handleActiveTabsGroupChanges({
oldValue: [{ tabKey: 'tab-1', urlKey: 'url-z', groupId: 2, pinned: false }],
newValue: [{ tabKey: 'tab-1', urlKey: 'url-z', groupId: -1, pinned: false }],
});
expect(labels.GroupA.urlKeys).toContain('url-z');
const wroteLabels = chrome.storage.local.set.mock.calls
.map((c) => c[0])
.find((o) => o && o.labels);
expect(wroteLabels).toBeUndefined();
});
// The sibling append site needs the same navigated-away guard recordInGroupTab
// has. Note this site is only ever reached on a group-to-group move: the
// function bails at `if !oldGroup || !newGroup`, so an ungroup-to-nothing
// followed by a regroup never arrives here. The reachable case is a tab still
// stamped under the DESTINATION label, sitting in another group, moved back in
// after navigating. Its live URL must not become a second permanent member.
it('refuses the append for a stamped tab moved back into the label it is filed under', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) =>
cb(id === 5 ? { id: 5, title: 'GroupB', color: 'blue' }
: { id: 2, title: 'GroupA', color: 'red' })
);
const labels = {
GroupA: { title: 'GroupA', urlKeys: [] },
GroupB: { title: 'GroupB', urlKeys: ['url-https://b.com/one'] },
};
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ labels }));
await fns.handleActiveTabsGroupChanges({
oldValue: [{ tabKey: 'tab-1', urlKey: 'url-https://b.com/two', groupId: 2, pinned: false }],
newValue: [{
tabKey: 'tab-1',
urlKey: 'url-https://b.com/two',
groupId: 5,
pinned: false,
labelTitle: 'GroupB',
labelUrlKey: 'url-https://b.com/one',
}],
});
expect(labels.GroupB.urlKeys).toEqual(['url-https://b.com/one']);
const wroteLabels = chrome.storage.local.set.mock.calls
.map((c) => c[0])
.find((o) => o && o.labels);
expect(wroteLabels).toBeUndefined();
});
// The guard is per-tab and must not block a genuine re-home: a tab stamped under
// GroupA moved by hand into GroupB is still recorded into B and removed from A.
it('still re-homes a stamped tab moved into a different label', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) =>
cb(id === 5 ? { id: 5, title: 'GroupB', color: 'blue' }
: { id: 2, title: 'GroupA', color: 'red' })
);
const labels = {
GroupA: { title: 'GroupA', urlKeys: ['url-z'] },
GroupB: { title: 'GroupB', urlKeys: [] },
};
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ labels }));
await fns.handleActiveTabsGroupChanges({
oldValue: [{ tabKey: 'tab-1', urlKey: 'url-z', groupId: 2, pinned: false }],
newValue: [{
tabKey: 'tab-1',
urlKey: 'url-z',
groupId: 5,
pinned: false,
labelTitle: 'GroupA',
labelUrlKey: 'url-z',
}],
});
const written = chrome.storage.local.set.mock.calls
.map((c) => c[0])
.find((o) => o && o.labels);
expect(written.labels.GroupB.urlKeys).toContain('url-z');
expect(written.labels.GroupA.urlKeys).not.toContain('url-z');
});
});
describe('groupTabs', () => {
// ungroups a tab that no longer matches any label
it('ungroups an unlabeled grouped tab', async () => {
await fns.groupTabs([{ tabKey: 'tab-9', urlKey: 'url-x', pinned: false, groupId: -1 }], {});
// groupId -1 (no group) and not pinned → no ungroup; assert it does not throw
expect(chrome.tabs.ungroup).not.toHaveBeenCalled();
});
// skips pinned tabs entirely
it('ignores pinned tabs', async () => {
await fns.groupTabs([{ tabKey: 'tab-1', urlKey: 'url-y', pinned: true, groupId: 2 }], {});
expect(chrome.tabs.group).not.toHaveBeenCalled();
});
// A tab on its way OUT of a group (ungroup in flight) must never be recorded
// into the group it is leaving — this is the core navigate-out bug fix.
it('does not capture a tab whose ungroup is pending', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) => cb({ id, title: 'Work', color: 'blue' }));
state.pendingUngroups.add(7);
const labels = { Work: { title: 'Work', urlKeys: [] } };
await fns.groupTabs(
[{ tabKey: 'tab-7', urlKey: 'url-https://b.com', pinned: false, groupId: 5 }],
labels
);
expect(labels.Work.urlKeys).not.toContain('url-https://b.com');
});
// Guards against over-suppression: a tab that genuinely sits in a group is
// still recorded into that group's label.
it('captures a genuinely grouped tab', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) => cb({ id, title: 'Work', color: 'blue' }));
const labels = { Work: { title: 'Work', urlKeys: [] } };
await fns.groupTabs(
[{ tabKey: 'tab-7', urlKey: 'url-https://b.com', pinned: false, groupId: 5 }],
labels
);
expect(labels.Work.urlKeys).toContain('url-https://b.com');
});
// A tab already inside its group must never be handed to chrome.tabs.group. On the
// refuse-append path (recordInGroupTab returns without recording, because the tab
// merely navigated away from its recorded slot) the tab's state is unchanged, so a
// group call here repositions it in the tab strip on EVERY pass — the user-visible
// "my tabs keep jumping around" loop, fed by onMoved -> updateActiveTabs ->
// storage.onChanged -> groupTabs.
it('never re-groups a tab that is already in the target group', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) => cb({ id, title: 'Work', color: 'blue' }));
chrome.tabGroups.query.mockImplementation((_q, cb) => cb([{ id: 5, windowId: 1, title: 'Work' }]));
const labels = { Work: { title: 'Work', urlKeys: ['url-https://a.com/apps'] } };
await fns.groupTabs(
[{
tabKey: 'tab-7',
urlKey: 'url-https://a.com/apps/123',
pinned: false,
groupId: 5,
windowId: 1,
labelTitle: 'Work',
labelUrlKey: 'url-https://a.com/apps',
}],
labels
);
expect(chrome.tabs.group).not.toHaveBeenCalled();
});
});
// Every test here pins one of the paths that moved a tab with NO user input.
// chrome.tabs.group and chrome.tabs.ungroup are repositions, not assertions, so
// each suppressed call is a tab that stops jumping in the strip.
describe('groupTabs tab placement', () => {
// The steady state, and the property that damps the whole feedback loop: when
// every tab already sits in its label's group, a pass must issue ZERO Chrome
// calls. Any call here fires onMoved -> updateActiveTabs -> storage.onChanged
// -> groupTabs and the cycle sustains itself.
it('issues no chrome calls when every tab is already correctly grouped', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) => cb({ id, title: 'Work', color: 'blue' }));
chrome.tabGroups.query.mockImplementation((_q, cb) => cb([{ id: 5, windowId: 1, title: 'Work' }]));
const labels = { Work: { title: 'Work', urlKeys: ['url-https://a.com'] } };
await fns.groupTabs(
[{ tabKey: 'tab-7', urlKey: 'url-https://a.com', pinned: false, groupId: 5, windowId: 1 }],
labels
);
expect(chrome.tabs.group).not.toHaveBeenCalled();
expect(chrome.tabs.ungroup).not.toHaveBeenCalled();
});
// A tab already inside a group must never be handed to groupLabeledTab AT ALL,
// not merely be caught by the idempotence guard afterwards. If the recording
// path still queued it, a label whose Chrome group resolves to a DIFFERENT id
// would relocate the tab out of the group it is sitting in.
it('never relocates an in-group tab to another group', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) => cb({ id, title: 'Work', color: 'blue' }));
// The label's group in this window resolves to 9, but the tab sits in 5.
chrome.tabGroups.query.mockImplementation((_q, cb) => cb([{ id: 9, windowId: 1, title: 'Work' }]));
const labels = { Work: { title: 'Work', urlKeys: [] } };
await fns.groupTabs(
[{ tabKey: 'tab-7', urlKey: 'url-https://b.com', pinned: false, groupId: 5, windowId: 1 }],
labels
);
expect(chrome.tabs.group).not.toHaveBeenCalled();
});
// Guards against over-suppression: an ungrouped tab whose urlKey is a recorded
// member is still auto-grouped exactly once. Without this the placement guards
// would have silently disabled the feature they were added to fix.
it('still auto-groups an ungrouped tab whose urlKey is a member', async () => {
chrome.tabGroups.query.mockImplementation((_q, cb) => cb([{ id: 5, windowId: 1, title: 'Work' }]));
const labels = { Work: { title: 'Work', urlKeys: ['url-https://a.com'] } };
await fns.groupTabs(
[{ tabKey: 'tab-7', urlKey: 'url-https://a.com', pinned: false, groupId: -1, windowId: 1 }],
labels
);
expect(chrome.tabs.group).toHaveBeenCalledTimes(1);
expect(chrome.tabs.group).toHaveBeenCalledWith({ tabIds: [7], groupId: 5 });
});
// Cross-window pull. The title-only tabGroups.query was not window-scoped and
// the code took groups[0], so grouping into it physically DRAGGED tabs into
// the other window. Each window must resolve its own group.
it('scopes the group lookup to each tab window so tabs never cross windows', async () => {
chrome.tabGroups.query.mockImplementation((query, cb) => {
cb([{ id: query.windowId === 1 ? 5 : 6, windowId: query.windowId, title: 'Work' }]);
});
const labels = { Work: { title: 'Work', urlKeys: ['url-https://a.com', 'url-https://b.com'] } };
await fns.groupTabs(
[