-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice_worker.test.js
More file actions
2638 lines (2361 loc) · 118 KB
/
Copy pathservice_worker.test.js
File metadata and controls
2638 lines (2361 loc) · 118 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 isTrackableUrl from './src/lib/utils/isTrackableUrl.js';
import samePageKey from './src/lib/utils/samePageKey.js';
import pruneDeletedUrls from './src/lib/utils/pruneDeletedUrls.js';
import appendGroupingLog from './src/lib/utils/groupingLog.js';
import healDriftedLabelSlot from './src/lib/utils/healDriftedLabelSlot.js';
import navigatedAwayFromRecordedSlot from './src/lib/utils/navigatedAwayFromRecordedSlot.js';
import {
buildGroupRemovalEntry,
GROUP_REMOVAL_LOG_KEY,
GROUP_REMOVAL_LOG_CAP,
RemovalSource,
} from './src/lib/utils/groupRemovalLog.js';
import {
buildGroupAdditionEntry,
GROUP_ADDITION_LOG_KEY,
GROUP_ADDITION_LOG_CAP,
AdditionSource,
} from './src/lib/utils/groupAdditionLog.js';
import {
buildGroupMoveEntry,
GROUP_MOVE_LOG_KEY,
GROUP_MOVE_LOG_CAP,
MoveSource,
} from './src/lib/utils/groupMoveLog.js';
import { needsGroupCall, needsUngroupCall, bucketTabsByWindow } from './src/lib/utils/tabPlacement.js';
import { 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';
// 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) {
// 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',
'isTrackableUrl',
'samePageKey',
'pruneDeletedUrls',
'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',
`${code}
;return {
fns: { trackGroup, listenToProcesses, updateActiveTabs, update,
newUrl, recordAccess, closeUrl, processProcesses, updateTotals, associateProcess,
tabUpdates, urlUpdates, getUrlKey, validTab, getTabGroup, mapColors,
getStorage, parseTabId, handleActiveTabsGroupChanges, groupTabs,
initLoadSource, processesApiAvailable, systemApiAvailable,
startSystemLoadPolling, stopSystemLoadPolling, pollSystemLoad,
autoCloseSweep, isAutoCloseEligible, pruneAutoClosed,
autoCloseThresholdMinutes, urlKeyIsMember, ejectAutoGroupedTab,
recordInGroupTab, debugGroup, pruneVisits, 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, isTrackableUrl, samePageKey, pruneDeletedUrls, 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);
}
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('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');
});
// an edited record keeps its user title/favicon instead of taking the live tab's values
it('preserves an edited title and favicon', () => {
const out = fns.urlUpdates(
{ url: 'https://a.com', title: 'My Title', favicon: 'mine.png', edited: true },
{ status: 'complete', title: 'Live Title', favIconUrl: 'live.png', groupId: -1, url: 'https://a.com' }
);
expect(out.title).toBe('My Title');
expect(out.favicon).toBe('mine.png');
});
// a non-edited record still takes the live tab's title/favicon (guards the flag's scope)
it('still copies the live title and favicon when not edited', () => {
const out = fns.urlUpdates(
{ url: 'https://a.com', title: 'Old', favicon: 'old.png' },
{ status: 'complete', title: 'Live Title', favIconUrl: 'live.png', groupId: -1, url: 'https://a.com' }
);
expect(out.title).toBe('Live Title');
expect(out.favicon).toBe('live.png');
});
});
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('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');
});
// REGRESSION: a REVISIT must move the url key back to the front of allUrls.
// allUrls is the recency list the tracked-URL cap trims from the TAIL, so a
// key that never moves on revisit drifts out, gets evicted, and has its whole
// url-* record — visits and all — deleted. That is what reset a daily-visited
// site to "1 visit". Previously newUrl only inserted when the key was ABSENT,
// so for an already-present key it never touched allUrls at all.
it('moves a revisited url key to the front of allUrls', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({
allUrls: ['url-https://new.com', 'url-https://a.com', 'url-https://b.com'],
labels: {},
})
);
const updates = await fns.newUrl(1, 'https://b.com');
expect(updates.allUrls[0]).toBe('url-https://b.com');
expect(updates.allUrls).toHaveLength(3);
});
// Deleting from History means "forget this", not "block this" — a deliberate
// return to the page is the user asking for it back, so a real visit clears
// the tombstone and the key is re-added to allUrls as normal.
it('clears the deletedUrls tombstone when the page is revisited', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ allUrls: [], labels: {}, deletedUrls: { 'url-https://b.com': Date.now() } })
);
const updates = await fns.newUrl(1, 'https://b.com');
expect(updates.deletedUrls['url-https://b.com']).toBeUndefined();
expect(updates.allUrls[0]).toBe('url-https://b.com');
});
// Tombstones are pruned on the same pass that already prunes allUrls, so the
// map is bounded by DELETED_URL_TTL_MS instead of growing one entry per
// page ever deleted. An unrelated FRESH tombstone must survive the prune.
it('prunes expired tombstones but keeps fresh ones', async () => {
const now = Date.now();
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({
allUrls: [],
labels: {},
deletedUrls: {
'url-https://stale.com': now - 2 * 60 * 60 * 1000,
'url-https://fresh.com': now - 1000,
},
})
);
const updates = await fns.newUrl(1, 'https://b.com');
expect(updates.deletedUrls['url-https://stale.com']).toBeUndefined();
expect(updates.deletedUrls['url-https://fresh.com']).toBe(now - 1000);
});
// The durable half of a visit: it accumulates under the site's HOST in
// siteVisits, which the eviction branch never touches.
it('records the visit under the site host in siteVisits', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ allUrls: [], labels: {} }));
const before = Date.now();
const updates = await fns.newUrl(1, 'https://www.espn.com/nfl/story/id/1');
expect(updates.siteVisits['espn.com']).toHaveLength(1);
expect(updates.siteVisits['espn.com'][0]).toBeGreaterThanOrEqual(before);
});
// Every page of a content site credits the SITE, not its own orphan key: a
// second article on the same host appends to the same siteVisits bucket.
it('accumulates visits from different pages of one site under one host', async () => {
const earlier = Date.now() - 1000 * 60 * 60;
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ allUrls: [], labels: {}, siteVisits: { 'espn.com': [earlier] } })
);
const updates = await fns.newUrl(1, 'https://espn.com/nba/standings');
expect(updates.siteVisits['espn.com']).toHaveLength(2);
expect(updates.siteVisits['espn.com'][0]).toBe(earlier);
});
// siteVisits must SURVIVE the eviction that deletes url-* records: the
// durable store is written even while the tracked-URL cap is trimming keys,
// so a site's stats outlive its record. This is the whole point of the store.
it('keeps siteVisits history for a site whose url record is evicted', async () => {
const history = [Date.now() - 1000 * 60 * 60 * 24 * 3, Date.now() - 1000 * 60 * 60];
// A full recency list, so this visit pushes the tail past the cap.
const allUrls = Array.from({ length: 500 }, (_, i) => `url-https://pad-${i}.com`);
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ allUrls, labels: {}, siteVisits: { 'wikipedia.org': history } })
);
const updates = await fns.newUrl(1, 'https://wikipedia.org/wiki/Main_Page');
// Keys past the cap were evicted...
expect(updates.allUrls).toHaveLength(500);
// ...but the site's history is intact and grew by this visit.
expect(updates.siteVisits['wikipedia.org']).toHaveLength(history.length + 1);
expect(updates.siteVisits['wikipedia.org'].slice(0, 2)).toEqual(history);
});
// Search engines stay in history (allUrls + visitCount) but stop
// accumulating the Favorites scoring signal: no siteVisits[host] write and no
// per-record `visits` append, since rankFavorites discards search hosts anyway.
// Red if the isSearchEngine gate is removed: siteVisits['google.com'] appears.
it('records a search engine in history but not in the Favorites scoring stores', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ allUrls: [], labels: {} }));
const url = 'https://www.google.com/search?q=weather';
const updates = await fns.newUrl(1, url);
const urlKey = fns.getUrlKey(url);
// Still in history: allUrls + visitCount.
expect(updates.allUrls).toContain(urlKey);
expect(updates[urlKey].visitCount).toBe(1);
// But NOT in the Favorites scoring stores.
expect(updates.siteVisits).toBeUndefined();
expect(updates[urlKey].visits).toEqual([]);
});
// A search engine with an existing siteVisits bucket does not grow it — the
// durable store stops accumulating search hosts going forward.
it('does not append to an existing siteVisits bucket for a search engine', async () => {
const earlier = Date.now() - 1000 * 60 * 60;
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ allUrls: [], labels: {}, siteVisits: { 'google.com': [earlier] } })
);
const updates = await fns.newUrl(1, 'https://www.google.com/search?q=x');
// siteVisits is left untouched (no write into updates for this host).
expect(updates.siteVisits).toBeUndefined();
});
// 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();
});
// A brand-new url records a first visit timestamp alongside visitCount 1, so
// Favorites can rank by a time-decayed sum of visits.
it('records a first visit timestamp and visitCount on a new url', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ allUrls: [], labels: {} }));
const before = Date.now();
const updates = await fns.newUrl(1, 'https://new.com');
const record = updates['url-https://new.com'];
expect(record.visitCount).toBe(1);
expect(record.visits).toHaveLength(1);
expect(record.visits[0]).toBeGreaterThanOrEqual(before);
});
// Every visit stamps `lastVisit` on the url-* record. This is the recency
// signal the History page dates rows by; `autoClosed` alone only covers
// tabs the inactivity sweep closed, so a manually-closed or still-open page
// had no timestamp and fell into "Earlier this week".
it('stamps lastVisit on the url record for every visit', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ allUrls: [], labels: {} }));
const before = Date.now();
const updates = await fns.newUrl(1, 'https://new.com');
const record = updates['url-https://new.com'];
expect(record.lastVisit).toBeGreaterThanOrEqual(before);
expect(record.lastVisit).toBeLessThanOrEqual(Date.now());
});
// The case that motivated putting `lastVisit` OUTSIDE the isSearchEngine
// gate: a search engine keeps an empty `visits` array (so it stays out of
// Favorites scoring) but must still be datable on the History page.
// Red if `lastVisit` is moved inside the gate.
it('stamps lastVisit on a search engine while leaving visits empty', async () => {
chrome.storage.local.get.mockImplementation((_q, cb) => cb({ allUrls: [], labels: {} }));
const before = Date.now();
const url = 'https://www.google.com/search?q=weather';
const updates = await fns.newUrl(1, url);
const record = updates[fns.getUrlKey(url)];
expect(record.visits).toEqual([]);
expect(record.lastVisit).toBeGreaterThanOrEqual(before);
});
// A repeat visit appends a fresh timestamp and increments visitCount while
// preserving the prior visits and other url-* fields.
it('appends a visit timestamp on a repeat visit', async () => {
const oldTs = Date.now() - 1000 * 60 * 60; // an hour ago
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({
allUrls: ['url-https://a.com'],
labels: {},
'url-https://a.com': { url: 'https://a.com', title: 'A', visitCount: 2, visits: [oldTs] },
})
);
const updates = await fns.newUrl(1, 'https://a.com');
const record = updates['url-https://a.com'];
expect(record.title).toBe('A'); // existing fields preserved
expect(record.visitCount).toBe(3);
expect(record.visits).toHaveLength(2);
expect(record.visits[0]).toBe(oldTs);
});
// Visits older than the retention horizon are pruned on write, so per-site
// history stays bounded.
it('prunes visits older than the retention horizon on write', async () => {
const ancient = Date.now() - 1000 * 60 * 60 * 24 * 60; // 60 days ago
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({
allUrls: ['url-https://a.com'],
labels: {},
'url-https://a.com': { url: 'https://a.com', visitCount: 5, visits: [ancient] },
})
);
const updates = await fns.newUrl(1, 'https://a.com');
const record = updates['url-https://a.com'];
// The ancient visit is dropped; only the fresh one survives.
expect(record.visits).toHaveLength(1);
expect(record.visits).not.toContain(ancient);
});
});
describe('recordAccess', () => {
// Mirror of the worker's ACCESS_THROTTLE_MS (not exported through fns).
const ACCESS_THROTTLE_MS_TEST = 1000 * 60 * 30;
// Switching back to a tab whose last visit is older than the throttle
// window records a visit (delegating to newUrl), so a kept-open favorite
// you return to earns rank credit.
it('records a visit when the last visit is older than the throttle', async () => {
const stale = Date.now() - ACCESS_THROTTLE_MS_TEST - 1000; // just past the window
chrome.tabs.get.mockResolvedValue({ id: 7, url: 'https://a.com' });
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({
allUrls: ['url-https://a.com'],
labels: {},
'url-https://a.com': { url: 'https://a.com', title: 'A', visitCount: 2, visits: [stale] },
})
);
const updates = await fns.recordAccess(1);
const record = updates['url-https://a.com'];
expect(record.visitCount).toBe(3);
expect(record.visits).toHaveLength(2);
});
// Re-activating the same site within the throttle window records nothing, so
// rapid alt-tabbing and the open→activate sequence can't inflate a rank.
it('records nothing within the throttle window', async () => {
const recent = Date.now() - 1000 * 60; // a minute ago, well inside 30 min
chrome.tabs.get.mockResolvedValue({ id: 7, url: 'https://a.com' });
chrome.storage.local.get.mockImplementation((_q, cb) =>
cb({ 'url-https://a.com': { url: 'https://a.com', visitCount: 2, visits: [recent] } })
);
await expect(fns.recordAccess(1)).resolves.toBeUndefined();
expect(chrome.storage.local.set).not.toHaveBeenCalled();
});
// A missing tab (rejected get) or a non-trackable URL is ignored — no read,
// no write.
it('ignores missing tabs and non-trackable URLs', async () => {
chrome.tabs.get.mockRejectedValueOnce(new Error('No tab with id'));
await expect(fns.recordAccess(999)).resolves.toBeUndefined();
chrome.tabs.get.mockResolvedValueOnce({ id: 8, url: 'chrome://extensions' });
await expect(fns.recordAccess(8)).resolves.toBeUndefined();
expect(chrome.storage.local.set).not.toHaveBeenCalled();
});
});
describe('pruneVisits', () => {
// A non-array or empty input yields an empty array, never a throw.
it('returns [] for non-array or empty input', () => {
const now = Date.now();
expect(fns.pruneVisits(undefined, now)).toEqual([]);
expect(fns.pruneVisits([], now)).toEqual([]);
});
// Visits older than the retention horizon are dropped.
it('drops visits older than the retention horizon', () => {
const now = Date.now();
const day = 1000 * 60 * 60 * 24;
const fresh = now - day;
const stale = now - 60 * day;
expect(fns.pruneVisits([stale, fresh], now)).toEqual([fresh]);
});
// The result is sorted ascending and drops non-finite entries.
it('sorts ascending and filters non-finite entries', () => {
const now = Date.now();
const day = 1000 * 60 * 60 * 24;
const a = now - 3 * day;
const b = now - 1 * day;
expect(fns.pruneVisits([b, a, NaN, 'x'], now)).toEqual([a, b]);
});
// More than 50 entries keep only the newest 50.
it('caps length to the newest 50 visits', () => {
const now = Date.now();
const many = [];
for (let i = 0; i < 60; i++) many.push(now - i * 1000);
const result = fns.pruneVisits(many, now);
expect(result).toHaveLength(50);
expect(result[result.length - 1]).toBe(now);
});
});
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(