-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice_worker.test.js
More file actions
1039 lines (933 loc) · 43.8 KB
/
Copy pathservice_worker.test.js
File metadata and controls
1039 lines (933 loc) · 43.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 fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, it, expect, beforeEach, vi } from 'vitest';
import deriveSystemTotals from './src/lib/utils/deriveSystemTotals.js';
import isTrackableUrl from './src/lib/utils/isTrackableUrl.js';
import samePageKey from './src/lib/utils/samePageKey.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 sloppy-mode 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.
function loadWorker(chrome) {
const raw = fs.readFileSync(SW_PATH, 'utf8');
const code = raw.replace(/^\s*import\s.*$/gm, '');
const factory = new Function(
'chrome',
'console',
'deriveSystemTotals',
'isTrackableUrl',
'samePageKey',
`${code}
;return {
fns: { trackGroup, listenToProcesses, updateActiveTabs, update,
newUrl, closeUrl, processProcesses, updateTotals, associateProcess,
tabUpdates, urlUpdates, getUrlKey, validTab, getTabGroup, mapColors,
getLocalStorage, parseTabId, handleActiveTabsGroupChanges, groupTabs,
initLoadSource, processesApiAvailable, systemApiAvailable,
startSystemLoadPolling, stopSystemLoadPolling, pollSystemLoad,
autoCloseSweep, isAutoCloseEligible, pruneAutoClosed,
autoCloseThresholdMinutes, urlKeyIsMember, ejectAutoGroupedTab,
recordInGroupTab, debugGroup },
state: {
get groups() { return groups; },
get samples() { return samples; },
get processesIndex() { return processesIndex; },
get pendingUngroups() { return pendingUngroups; },
get autoGroupedTabs() { return autoGroupedTabs; },
}
};`
);
return factory(chrome, { log: vi.fn(), error: vi.fn() }, deriveSystemTotals, isTrackableUrl, samePageKey);
}
describe('service_worker.js', () => {
let chrome;
let fns;
let state;
beforeEach(() => {
chrome = makeChrome();
const loaded = loadWorker(chrome);
fns = loaded.fns;
state = loaded.state;
});
// 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('getUrlKey', () => {
// builds a url- prefixed key, stripping any hash fragment
it('prefixes with url- and strips the fragment', () => {
expect(fns.getUrlKey('https://a.com/p')).toBe('url-https://a.com/p');
expect(fns.getUrlKey('https://a.com/p#section')).toBe('url-https://a.com/p');
});
});
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('urlUpdates', () => {
// initializes a processes bucket and copies tab metadata
it('initializes processes and copies title/favicon/groupId', () => {
const out = fns.urlUpdates(
{ url: 'https://a.com' },
{ status: 'complete', title: 'A', favIconUrl: 'a.png', groupId: 5, url: 'https://a.com' }
);
expect(out.title).toBe('A');
expect(out.favicon).toBe('a.png');
expect(out.groupId).toBe(5);
expect(out.processes.samples).toBe(0);
});
// accumulates process stats and bumps the sample counter
it('accumulates process stats when a process is supplied', () => {
const out = fns.urlUpdates(
{ url: 'https://b.com', title: 'B' },
{ status: 'complete', title: 'B', url: 'https://b.com', groupId: -1 },
{ cpu: 10, network: 2, privateMemory: 1, jsMemoryAllocated: 1, jsMemoryUsed: 1 }
);
expect(out.processes.samples).toBe(1);
expect(out.processes.cpu).toBe(10);
});
// falls back to the url as the title when the tab has none
it('uses the url as title when title is missing', () => {
const out = fns.urlUpdates({ url: 'https://c.com' }, { status: 'complete', url: 'https://c.com' });
expect(out.title).toBe('https://c.com');
});
});
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'] });
});
});
describe('getLocalStorage', () => {
// 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.getLocalStorage('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.getLocalStorage('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();
});
});
describe('newUrl', () => {
// returns undefined when called without a tab id or url
it('returns early without tabId/url', async () => {
await expect(fns.newUrl(undefined, 'https://a.com')).resolves.toBeUndefined();
await expect(fns.newUrl(1, undefined)).resolves.toBeUndefined();
});
// adds a brand-new url key to the front of allUrls
it('prepends an unseen url key to allUrls', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ allUrls: ['url-old'], labels: {} }));
const updates = await fns.newUrl(1, 'https://new.com');
expect(updates.allUrls[0]).toBe('url-https://new.com');
});
// Non-website navigations (about:blank, file://, chrome://, data:) are
// never recorded: newUrl returns before touching storage so they can't
// enter allUrls or bump visitCount.
it('does not record non-website URLs', async () => {
const get = vi.fn((_q, cb) => cb({ allUrls: [], labels: {} }));
chrome.storage.local.get.mockImplementation(get);
for (const url of [
'about:blank',
'file:///Users/x/doc.html',
'chrome://extensions',
'data:text/html,hi',
]) {
await expect(fns.newUrl(1, url)).resolves.toBeUndefined();
}
expect(get).not.toHaveBeenCalled();
expect(chrome.storage.local.set).not.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');
});
});
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();
});
});
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('tabUpdates', () => {
// resolves an empty object for tabs that fail the validity check
it('resolves {} for an invalid tab', async () => {
await expect(fns.tabUpdates({ url: 'chrome://settings' })).resolves.toEqual({});
});
// resolves keyed url updates for a valid tab
it('resolves keyed url updates for a valid tab', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({}));
const out = await fns.tabUpdates({ url: 'https://a.com', status: 'complete', title: 'A', groupId: -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');
});
});
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');
});
});
describe('urlKeyIsMember', () => {
// a urlKey recorded in the label's urlKeys is a member
it('is true when the urlKey is present in the label', () => {
const label = { title: 'Work', urlKeys: ['url-https://a.com', 'url-https://b.com'] };
expect(fns.urlKeyIsMember(label, 'url-https://b.com')).toBe(true);
});
// a urlKey absent from the label's urlKeys is not a member
it('is false when the urlKey is absent', () => {
const label = { title: 'Work', urlKeys: ['url-https://a.com'] };
expect(fns.urlKeyIsMember(label, 'url-https://b.com')).toBe(false);
});
// an empty urlKeys list claims no members
it('is false for a label with no urlKeys', () => {
expect(fns.urlKeyIsMember({ title: 'Work', urlKeys: [] }, 'url-https://a.com')).toBe(false);
});
// a missing/undefined label is treated as non-membership rather than throwing,
// so callers can pass labels[title] without a prior existence check
it('is false when the label is undefined or null', () => {
expect(fns.urlKeyIsMember(undefined, 'url-https://a.com')).toBe(false);
expect(fns.urlKeyIsMember(null, 'url-https://a.com')).toBe(false);
});
});
describe('recordInGroupTab', () => {
// seeds a brand-new label (carrying the group's mapped color) when none exists
it('seeds a missing label with the tab urlKey and mapped color', () => {
const labels = {};
fns.recordInGroupTab(
labels,
{ title: 'Work', color: 'blue' },
{ tabKey: 'tab-7', urlKey: 'url-https://b.com', groupId: 5 }
);
expect(labels.Work.urlKeys).toEqual(['url-https://b.com']);
expect(labels.Work.color).toBe('#1873E4');
});
// appends to an existing label's urlKeys rather than overwriting it
it('pushes the urlKey into an existing label', () => {
const labels = { Work: { title: 'Work', urlKeys: ['url-https://a.com'], color: '#1873E4' } };
fns.recordInGroupTab(
labels,
{ title: 'Work', color: 'blue' },
{ tabKey: 'tab-7', urlKey: 'url-https://b.com', groupId: 5 }
);
expect(labels.Work.urlKeys).toEqual(['url-https://a.com', 'url-https://b.com']);
});
// persists the updated labels object via update -> chrome.storage.local.set
it('persists the updated labels to storage', () => {
const labels = {};
fns.recordInGroupTab(
labels,
{ title: 'Work', color: 'blue' },
{ tabKey: 'tab-7', urlKey: 'url-https://b.com', groupId: 5 }
);
const written = chrome.storage.local.set.mock.calls.map((c) => c[0]).find((o) => o && o.labels);
expect(written.labels.Work.urlKeys).toContain('url-https://b.com');
});
});
describe('ejectAutoGroupedTab', () => {
// While the real URL has not loaded (urlKey is the bare 'url-' placeholder),
// ejection is deferred so we never act on the transient about:blank state.
it('returns wait and does nothing while the URL is still unloaded', async () => {
state.autoGroupedTabs.add(7);
const result = await fns.ejectAutoGroupedTab(
{ tabKey: 'tab-7', urlKey: 'url-', groupId: 5 },
'Work'
);
expect(result).toBe('wait');
expect(chrome.tabs.ungroup).not.toHaveBeenCalled();
expect(state.autoGroupedTabs.has(7)).toBe(true);
});
// Flicker guard: the in-memory snapshot said non-member, but FRESH storage
// shows the URL is a genuine member (an overlapping event just added it) —
// keep the tab grouped, clear the flag, and do not ungroup.
it('keeps the tab and clears the flag when fresh storage shows membership', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ labels: { Work: { title: 'Work', urlKeys: ['url-https://b.com'] } } })
);
state.autoGroupedTabs.add(7);
const result = await fns.ejectAutoGroupedTab(
{ tabKey: 'tab-7', urlKey: 'url-https://b.com', groupId: 5 },
'Work'
);
expect(result).toBe('kept');
expect(chrome.tabs.ungroup).not.toHaveBeenCalled();
expect(state.autoGroupedTabs.has(7)).toBe(false);
});
// The URL is a non-member in fresh storage too — eject: ungroup the tab,
// mark the in-flight ungroup in pendingUngroups, and clear the auto-group flag.
it('ungroups a confirmed non-member and tracks the in-flight ungroup', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ labels: { Work: { title: 'Work', urlKeys: [] } } })
);
state.autoGroupedTabs.add(7);
const result = await fns.ejectAutoGroupedTab(
{ tabKey: 'tab-7', urlKey: 'url-https://new.com', groupId: 5 },
'Work'
);
expect(result).toBe('ejected');
expect(chrome.tabs.ungroup).toHaveBeenCalledWith(7, expect.any(Function));
expect(state.pendingUngroups.has(7)).toBe(true);
expect(state.autoGroupedTabs.has(7)).toBe(false);
});
});
describe('auto-grouped stickiness fix integration', () => {
// The core bug fix: a tab Chrome auto-placed into a group whose URL is not a
// deliberate label member must be EJECTED, never recorded into the label.
it('ejects an auto-grouped non-member and does not record its URL', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) => cb({ id, title: 'Work', color: 'blue' }));
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ labels: { Work: { title: 'Work', urlKeys: [] } } })
);
state.autoGroupedTabs.add(7);
const labels = { Work: { title: 'Work', urlKeys: [] } };
await fns.groupTabs(
[{ tabKey: 'tab-7', urlKey: 'url-https://new.com', pinned: false, groupId: 5 }],
labels
);
expect(chrome.tabs.ungroup).toHaveBeenCalledWith(7, expect.any(Function));
expect(labels.Work.urlKeys).not.toContain('url-https://new.com');
});
// Membership beats the flag: an auto-grouped tab whose URL IS a deliberate
// member stays grouped, gets its flag cleared, and is never ungrouped.
it('keeps an auto-grouped tab whose URL is a deliberate member', async () => {
chrome.tabGroups.get.mockImplementation((id, cb) => cb({ id, title: 'Work', color: 'blue' }));
state.autoGroupedTabs.add(7);
const labels = { Work: { title: 'Work', urlKeys: ['url-https://b.com'] } };
await fns.groupTabs(
[{ tabKey: 'tab-7', urlKey: 'url-https://b.com', pinned: false, groupId: 5 }],
labels
);
expect(chrome.tabs.ungroup).not.toHaveBeenCalled();
expect(state.autoGroupedTabs.has(7)).toBe(false);
});
// An explicit groupId change is user intent and must clear an earlier
// auto-group flag so groupTabs won't later yank the deliberately-moved tab out.
it('clears the auto-group flag on a deliberate group change', 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: {} }));
state.autoGroupedTabs.add(1);
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 }],
});
expect(state.autoGroupedTabs.has(1)).toBe(false);
});
// onRemoved must clear the flag so the in-memory set never leaks stale tab ids
// after a flagged tab is closed.
it('clears the auto-group flag when a flagged tab is removed', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ activeTabs: [] }));
state.autoGroupedTabs.add(9);
const onRemoved = chrome.tabs.onRemoved.addListener.mock.calls[0][0];
await onRemoved(9, {});
expect(state.autoGroupedTabs.has(9)).toBe(false);
});
});
describe('debugGroup', () => {
// The grouping tracer is gated behind DEBUG_GROUPING (off in production), so a
// call is a safe no-op that never throws regardless of the payload shape.
it('is a no-op that does not throw when disabled', () => {
expect(() => fns.debugGroup('some-event', { tabId: 7, urlKey: 'url-x' })).not.toThrow();
expect(fns.debugGroup('some-event', {})).toBeUndefined();
});
});
describe('onUpdated group removal', () => {
// Sets the module-level `labels` by driving the storage.onChanged listener,
// which mirrors how the worker keeps `labels` in sync at runtime.
const setLabels = (chrome, labelsObj) => {
const onChanged = chrome.storage.onChanged.addListener.mock.calls[0][0];
onChanged({ labels: { newValue: labelsObj, oldValue: {} } }, 'local');
};
// The cleanup path keys removal off getUrlKey(tab.url), which strips the
// #fragment. A label storing the normalized key must be cleaned even when the
// tab's live URL still carries a fragment (the inline `url-${tab.url}` form
// missed these).
it('removes a hashed URL using the normalized key when a tab leaves a group', async () => {
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 === 'activeTabs') {
res.activeTabs = [{ tabKey: 'tab-3', urlKey: 'url-https://docs.com/page', groupId: 5 }];
} else if (k === 'allUrls') res.allUrls = [];
else if (k === 'autoClosed') res.autoClosed = {};
else if (k === 'labels') res.labels = {};
}
cb(res);
});
chrome.tabs.query.mockImplementation((_q, cb) => cb && cb([]));
const labelsObj = { Work: { title: 'Work', urlKeys: ['url-https://docs.com/page'] } };
setLabels(chrome, labelsObj);
fns.trackGroup({ id: 5, title: 'Work' });
const onUpdated = chrome.tabs.onUpdated.addListener.mock.calls[0][0];
await onUpdated(3, { groupId: -1 }, { id: 3, url: 'https://docs.com/page#section' });
// labelsObj is the same reference held module-level, so the splice is visible here.
expect(labelsObj.Work.urlKeys).not.toContain('url-https://docs.com/page');
});
});
describe('onUpdated in-page URL change keeps tab grouped', () => {
// Storage mock that reports a single grouped tab whose stored urlKey is
// `oldUrlKey`, so the handler's `oldTabUrl` lookup resolves and the eject
// path runs. Everything else answers empty so newUrl can complete.
const storageWithGroupedTab = (chrome, oldUrlKey) => {
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 === 'activeTabs') {
res.activeTabs = [{ tabKey: 'tab-3', urlKey: oldUrlKey, groupId: 5 }];
} else if (k === 'allUrls') res.allUrls = [oldUrlKey];
else if (k === 'autoClosed') res.autoClosed = {};
else if (k === 'labels') res.labels = {};
}
cb(res);
});
chrome.tabs.query.mockImplementation((_q, cb) => cb && cb([]));
};
const getHandler = (chrome) => chrome.tabs.onUpdated.addListener.mock.calls[0][0];
// The reported bug: a Google Docs tab in a group rewrites only its `?tab=`
// query string in-page. Origin + path are unchanged, so this is NOT a
// navigation and the tab must stay in its group — ungroup is not called.
it('does not ungroup a grouped tab on a query-string-only change', async () => {
const base = 'https://docs.google.com/document/d/1GMK/edit';
storageWithGroupedTab(chrome, `url-${base}?tab=t.whli3qfeqr1i`);
const onUpdated = getHandler(chrome);
await onUpdated(
3,
{ url: `${base}?tab=t.other` },
{ id: 3, url: `${base}?tab=t.other`, groupId: 5, incognito: false }
);
expect(chrome.tabs.ungroup).not.toHaveBeenCalled();
});
// A fragment-only change (SPA anchor navigation) is also in-page: same
// origin + path, so the tab stays grouped.
it('does not ungroup a grouped tab on a fragment-only change', async () => {
const base = 'https://app.example.com/board';
storageWithGroupedTab(chrome, `url-${base}`);
const onUpdated = getHandler(chrome);
await onUpdated(
3,
{ url: `${base}#card-42` },
{ id: 3, url: `${base}#card-42`, groupId: 5, incognito: false }
);
expect(chrome.tabs.ungroup).not.toHaveBeenCalled();
});
// Guards against over-correction: a real navigation to a different path is
// still a navigation, so the grouped tab is ejected exactly as before.
it('still ungroups a grouped tab that navigates to a different path', async () => {
storageWithGroupedTab(chrome, 'url-https://example.com/a');
const onUpdated = getHandler(chrome);
await onUpdated(
3,
{ url: 'https://example.com/b' },
{ id: 3, url: 'https://example.com/b', groupId: 5, incognito: false }
);
expect(chrome.tabs.ungroup).toHaveBeenCalledWith(3, expect.any(Function));
});
// A cross-origin navigation is likewise a real navigation and still ejects.
it('still ungroups a grouped tab that navigates to a different origin', async () => {
storageWithGroupedTab(chrome, 'url-https://example.com/page');
const onUpdated = getHandler(chrome);
await onUpdated(
3,
{ url: 'https://other.com/page' },
{ id: 3, url: 'https://other.com/page', groupId: 5, incognito: false }
);
expect(chrome.tabs.ungroup).toHaveBeenCalledWith(3, expect.any(Function));
});
});
// Channel-based degradation: the gauge's data source depends on which Chrome
// API is available. processProcesses (Dev/Canary) tags 'processes'; the
// system poll (stable Chrome) tags 'system'; neither tags 'none'.
describe('load source fallback', () => {
const cpuInfo = {
processors: [
{ usage: { kernel: 10, user: 10, idle: 80, total: 100 } },
{ usage: { kernel: 20, user: 10, idle: 70, total: 100 } },
],
};
const memoryInfo = { capacity: 1000, availableCapacity: 400 }; // 60% used
// Dev/Canary path: processes present → listener registered and the first
// totals write is tagged loadDataSource:'processes'
it("tags 'processes' and keeps processing when chrome.processes is present", async () => {
// default `chrome` from beforeEach has chrome.processes
expect(chrome.processes.onUpdatedWithMemory.addListener).toHaveBeenCalledWith(fns.processProcesses);
await fns.processProcesses({});
const writes = chrome.storage.local.set.mock.calls.map((c) => c[0]);
expect(writes.some((w) => w.loadDataSource === 'processes')).toBe(true);
});
// stable Chrome: no processes API, but chrome.system.* present → one poll
// writes a normalized processTotals tagged loadDataSource:'system'
it("falls back to chrome.system and tags 'system' when processes is absent", async () => {
const c = makeChrome();
delete c.processes;
c.system = {
cpu: { getInfo: vi.fn().mockResolvedValue(cpuInfo) },
memory: { getInfo: vi.fn().mockResolvedValue(memoryInfo) },
};
const loaded = loadWorker(c);
// let the load-time poll resolve and schedule its repeat, then silence it
await new Promise((r) => setTimeout(r, 0));
loaded.fns.stopSystemLoadPolling();
c.storage.local.set.mockClear();
await loaded.fns.pollSystemLoad();
loaded.fns.stopSystemLoadPolling();
const last = c.storage.local.set.mock.calls.at(-1)[0];
expect(last.loadDataSource).toBe('system');
expect(last.processTotals).toBeTruthy();
// memory pressure flows through on a single sample (never NaN)
expect(last.processTotals.privateMemory).toBeGreaterThan(0);
expect(Number.isNaN(last.processTotals.cpu)).toBe(false);
});
// neither API available → loadDataSource:'none', written once at init,
// and nothing throws
it("tags 'none' and never throws when no load API is available", () => {
const c = makeChrome();
delete c.processes;
// no c.system at all
expect(() => loadWorker(c)).not.toThrow();
expect(c.storage.local.set).toHaveBeenCalledWith({ loadDataSource: 'none' });
});
// a thrown system call degrades to 'none' rather than crashing the worker
it('degrades to none when a system call throws', async () => {
const c = makeChrome();
delete c.processes;
c.system = {
cpu: { getInfo: vi.fn().mockRejectedValue(new Error('denied')) },
memory: { getInfo: vi.fn().mockResolvedValue(memoryInfo) },
};
const loaded = loadWorker(c);
c.storage.local.set.mockClear();
await loaded.fns.pollSystemLoad();
loaded.fns.stopSystemLoadPolling();
expect(c.storage.local.set).toHaveBeenCalledWith({ loadDataSource: 'none' });
});
});
// The "Closer" engine: a periodic alarm sweeps inactive tabs, removing them and
// recording each into the autoClosed map so the "Automatically Closed" UI lights up.
describe('autoCloseSweep', () => {
const MINUTE = 60 * 1000;
// Drives one sweep against the supplied storage and returns the removed tab
// ids plus the autoClosed map that was persisted.
const runSweep = ({ activeTabs = [], autoClosed = {}, settings = {} }) => {
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ activeTabs, autoClosed, settings })
);
chrome.storage.local.set.mockClear();
chrome.tabs.remove.mockClear();
fns.autoCloseSweep();
const lastSet = chrome.storage.local.set.mock.calls.at(-1);
return {
written: lastSet ? lastSet[0].autoClosed : undefined,
removedIds: chrome.tabs.remove.mock.calls.map((c) => c[0]),
};
};
const tab = (over) => ({
tabKey: 'tab-1',
urlKey: 'url-https://x.com',
pinned: false,
groupId: -1,
tabCommandPinned: false,
active: false,
...over,
});
// a periodic alarm + onAlarm listener are wired up at load
it('registers the auto-close alarm at load', () => {
expect(chrome.alarms.create).toHaveBeenCalledWith('auto-close-sweep', { periodInMinutes: 1 });
expect(chrome.alarms.onAlarm.addListener).toHaveBeenCalled();
});
// an inactive ungrouped tab past the threshold is removed and recorded
it('closes and records an inactive ungrouped tab', () => {
const now = Date.now();
const t = tab({ tabKey: 'tab-5', urlKey: 'url-old', activeAt: now - 200 * MINUTE, openedAt: now - 300 * MINUTE });
const { written, removedIds } = runSweep({ activeTabs: [t] });
expect(removedIds).toContain(5);
expect(written['url-old']).toBeGreaterThan(0);
});
// pinned, thumbtack-pinned, and the active tab are exempt
it('never closes pinned, tabCommandPinned, or the active tab', () => {
const now = Date.now();
const old = now - 200 * MINUTE;
const { written, removedIds } = runSweep({
activeTabs: [
tab({ tabKey: 'tab-1', urlKey: 'url-pinned', pinned: true, activeAt: old }),
tab({ tabKey: 'tab-2', urlKey: 'url-thumb', tabCommandPinned: true, activeAt: old }),
tab({ tabKey: 'tab-3', urlKey: 'url-active', active: true, activeAt: old }),
],
});
expect(removedIds).toEqual([]);
expect(written['url-pinned']).toBeUndefined();
expect(written['url-thumb']).toBeUndefined();
expect(written['url-active']).toBeUndefined();
});
// a tab active within the threshold window is left open
it('keeps a tab that was active within the window', () => {
const now = Date.now();
const t = tab({ tabKey: 'tab-7', urlKey: 'url-recent', activeAt: now - 10 * MINUTE });
const { written, removedIds } = runSweep({ activeTabs: [t] });
expect(removedIds).toEqual([]);
expect(written['url-recent']).toBeUndefined();
});
// grouped/labeled inactive tabs are in scope and get closed
it('closes a grouped/labeled inactive tab', () => {
const now = Date.now();
const t = tab({ tabKey: 'tab-8', urlKey: 'url-grouped', groupId: 42, activeAt: now - 200 * MINUTE });
const { removedIds } = runSweep({ activeTabs: [t] });
expect(removedIds).toContain(8);
});
// a throwing chrome.tabs.remove for one tab does not abort the others
it('continues the sweep when one tab removal throws', () => {
chrome.tabs.remove.mockImplementation((id) => {
if (id === 1) throw new Error('No tab with id: 1');
});
const now = Date.now();
const old = now - 200 * MINUTE;
const { written, removedIds } = runSweep({
activeTabs: [
tab({ tabKey: 'tab-1', urlKey: 'url-a', activeAt: old }),
tab({ tabKey: 'tab-2', urlKey: 'url-b', activeAt: old }),
],
});
expect(removedIds).toContain(2);
expect(written['url-a']).toBeGreaterThan(0);
expect(written['url-b']).toBeGreaterThan(0);
});
// entries older than the retention window are pruned from the map
it('prunes autoClosed entries older than MAX_AUTO_CLOSED_TIME', () => {
const now = Date.now();
const { written } = runSweep({