-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.test.js
More file actions
1079 lines (870 loc) · 37.8 KB
/
sync.test.js
File metadata and controls
1079 lines (870 loc) · 37.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
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { readFileSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const SYNC_CODE = readFileSync(resolve(__dirname, 'sync.js'), 'utf8');
// --- Helpers ---
const tick = () => vi.advanceTimersByTimeAsync(0);
const flush = async (n = 10) => { for (let i = 0; i < n; i++) await tick(); };
function state(overrides = {}) {
return {
isFocus: true, isRunning: false, startedAt: null,
remainingAtStart: 1500, completedPomodoros: 0, completedBreaks: 0,
date: '2026-04-08',
settings: { goal: 8, focusMin: 25, breakMin: 5, autoFocus: false, autoBreak: false },
log: {},
...overrides
};
}
function runningTimer(overrides = {}) {
return state({ isRunning: true, startedAt: Date.now(), remainingAtStart: 1200, ...overrides });
}
function createDOM() {
document.body.innerHTML = '';
const ids = [
'sync-modal', 'sync-btn', 'sync-close', 'sync-status', 'sync-indicator',
'sync-signin', 'sync-signout', 'sync-desc', 'conflict-modal', 'conflict-local',
'conflict-cloud', 'conflict-local-detail', 'conflict-cloud-detail', 'sync-spin'
];
for (const id of ids) {
const el = document.createElement('div');
el.id = id;
document.body.appendChild(el);
}
// sync-modal needs .modal-backdrop child
const backdrop = document.createElement('div');
backdrop.className = 'modal-backdrop';
document.getElementById('sync-modal').appendChild(backdrop);
// Start hidden
document.getElementById('conflict-modal').classList.add('hidden');
document.getElementById('sync-spin').classList.add('hidden');
document.getElementById('sync-indicator').classList.add('hidden');
}
// --- Test environment factory ---
function setup() {
createDOM();
let stateChangeCbs = [];
let appState = state();
let authCb = null;
let snapshotCb = null;
let cloudDoc = null;
const txWrites = [];
// window.app (normally set up by app.js)
window.app = {
onStateChange: vi.fn(cb => stateChangeCbs.push(cb)),
getState: vi.fn(() => JSON.parse(JSON.stringify(appState))),
applyRemoteState: vi.fn(),
initWithState: vi.fn(),
onWake: vi.fn(),
loadLocal: vi.fn(() => Promise.resolve(null)),
showToast: vi.fn()
};
// Firebase mocks
const mockTx = {
get: vi.fn(() => Promise.resolve({
exists: !!cloudDoc,
data: () => cloudDoc ? JSON.parse(JSON.stringify(cloudDoc)) : null
})),
set: vi.fn((_, data) => txWrites.push(data))
};
const mockDocRef = {
get: vi.fn(() => Promise.resolve({
exists: !!cloudDoc,
data: () => cloudDoc ? JSON.parse(JSON.stringify(cloudDoc)) : null
})),
onSnapshot: vi.fn((cb, _err) => { snapshotCb = cb; return vi.fn(); })
};
const mockDb = {
enablePersistence: vi.fn(() => Promise.resolve()),
doc: vi.fn(() => mockDocRef),
runTransaction: vi.fn(async fn => fn(mockTx))
};
const mockAuth = {
onAuthStateChanged: vi.fn(cb => { authCb = cb; }),
currentUser: null,
signOut: vi.fn(() => Promise.resolve())
};
window.firebase = {
initializeApp: vi.fn(),
auth: Object.assign(vi.fn(() => mockAuth), { GoogleAuthProvider: vi.fn() }),
firestore: Object.assign(vi.fn(() => mockDb), {
FieldValue: { serverTimestamp: vi.fn(() => 'SERVER_TS') }
})
};
// Execute sync.js IIFE
eval(SYNC_CODE);
const env = {
app: window.app,
auth: mockAuth,
db: mockDb,
docRef: mockDocRef,
tx: mockTx,
writes() { return txWrites; },
setCloud(doc) { cloudDoc = doc; },
setState(s) { appState = s; },
signIn(uid = 'u1') {
mockAuth.currentUser = { uid, displayName: 'Test', email: 't@t.com' };
authCb({ uid });
},
snapshot(data) {
if (snapshotCb) snapshotCb({ exists: !!data, data: () => data });
},
fireStateChange() {
stateChangeCbs.forEach(cb => cb(appState));
},
setVisibility(value) {
Object.defineProperty(document, 'visibilityState', { value, configurable: true });
document.dispatchEvent(new Event('visibilitychange'));
},
clearMocks() {
txWrites.length = 0;
mockTx.set.mockClear();
mockTx.get.mockClear();
mockDb.runTransaction.mockClear();
mockDocRef.get.mockClear();
window.app.applyRemoteState.mockClear();
window.app.initWithState.mockClear();
window.app.onWake.mockClear();
}
};
return env;
}
/** Sign in and complete initial sync at given version. Clears mocks after. */
async function synced(env, version = 1, cloudState = state()) {
env.setCloud({ _version: version, state: cloudState });
env.setState(cloudState); // match local to cloud so pushIfChanged is a no-op
env.signIn();
await flush();
env.clearMocks();
}
// =============================================================================
// Tests
// =============================================================================
describe('sync', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
document.body.innerHTML = '';
delete window.firebase;
delete window.app;
});
// ---------------------------------------------------------------------------
// pushState version guard (the main safety net)
// ---------------------------------------------------------------------------
describe('pushState version guard', () => {
it('blocks write when cloud version is ahead of known version', async () => {
const env = setup();
await synced(env, 3);
// Cloud advanced to v7 while device was out of sync
env.setCloud({ _version: 7, state: runningTimer() });
// Local change triggers debounced push
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
// Transaction ran but did NOT write — version guard blocked it
expect(env.db.runTransaction).toHaveBeenCalled();
expect(env.tx.set).not.toHaveBeenCalled();
});
it('applies cloud state locally when stale push is blocked', async () => {
const env = setup();
await synced(env, 3);
const cloud = runningTimer({ completedPomodoros: 2 });
env.setCloud({ _version: 7, state: cloud });
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.app.applyRemoteState).toHaveBeenCalledWith(
expect.objectContaining({ isRunning: true, completedPomodoros: 2 })
);
});
it('allows write when cloud version matches known version', async () => {
const env = setup();
await synced(env, 3);
// Cloud still at v3 — same as knownVersion
env.setCloud({ _version: 3, state: state() });
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.tx.set).toHaveBeenCalled();
const written = env.writes().pop();
expect(written._version).toBe(4);
});
it('merges logs during write', async () => {
const env = setup();
await synced(env, 1);
// Cloud has a log entry the local doesn't
env.setCloud({
_version: 1,
state: state({ log: { '2026-04-07': { completed: 5, goal: 8 } } })
});
// Local also has a log entry
env.setState(state({ log: { '2026-04-08': { completed: 3, goal: 8 } } }));
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.tx.set).toHaveBeenCalled();
const written = env.writes().pop();
expect(written.state.log['2026-04-07'].completed).toBe(5); // from cloud
expect(written.state.log['2026-04-08'].completed).toBe(3); // from local
});
});
// ---------------------------------------------------------------------------
// Dirty flag
// ---------------------------------------------------------------------------
describe('dirty flag', () => {
it('is not set during remote state application (no echo push)', async () => {
const env = setup();
await synced(env, 1);
// Remote update via onSnapshot
env.snapshot({ _sender: 'device-b', _version: 2, state: runningTimer() });
// Wait well past debounce — should NOT trigger a push
await vi.advanceTimersByTimeAsync(5000);
await flush();
expect(env.db.runTransaction).not.toHaveBeenCalled();
});
it('is set on local state change and triggers debounced push', async () => {
const env = setup();
await synced(env, 1);
env.setCloud({ _version: 1, state: state() });
env.fireStateChange();
// Push should NOT happen before 2s
await vi.advanceTimersByTimeAsync(1000);
await flush();
expect(env.db.runTransaction).not.toHaveBeenCalled();
// Push happens at 2s
await vi.advanceTimersByTimeAsync(1000);
await flush();
expect(env.db.runTransaction).toHaveBeenCalled();
});
});
// ---------------------------------------------------------------------------
// Visibility change — kill stale timeouts
// ---------------------------------------------------------------------------
describe('visibility change', () => {
it('clears pending push timeout when page goes to background', async () => {
const env = setup();
await synced(env, 1);
env.setCloud({ _version: 1, state: state() });
env.fireStateChange(); // schedules push in 2s
// Lock screen / go to background before push fires
env.setVisibility('hidden');
// Advance well past debounce
await vi.advanceTimersByTimeAsync(5000);
await flush();
// Push should NOT have fired — timeout was cleared
expect(env.db.runTransaction).not.toHaveBeenCalled();
});
});
// ---------------------------------------------------------------------------
// onSnapshot
// ---------------------------------------------------------------------------
describe('onSnapshot', () => {
it('cancels pending push and applies remote state', async () => {
const env = setup();
await synced(env, 1);
// Local change → push scheduled
env.fireStateChange();
// Before 2s, remote update arrives
env.snapshot({ _sender: 'device-b', _version: 2, state: runningTimer() });
// Advance past debounce
await vi.advanceTimersByTimeAsync(3000);
await flush();
// Push was cancelled — transaction never ran
expect(env.db.runTransaction).not.toHaveBeenCalled();
// Remote state was applied
expect(env.app.applyRemoteState).toHaveBeenCalledWith(
expect.objectContaining({ isRunning: true })
);
});
});
// ---------------------------------------------------------------------------
// Resync (wake / reconnect)
// ---------------------------------------------------------------------------
describe('resync', () => {
it('accepts cloud when local is clean and cloud changed', async () => {
const env = setup();
await synced(env, 3);
// Cloud advanced while device slept
env.setCloud({ _version: 5, state: runningTimer({ completedPomodoros: 2 }) });
env.setVisibility('hidden');
env.setVisibility('visible');
await flush();
expect(env.app.initWithState).toHaveBeenCalledWith(
expect.objectContaining({ isRunning: true, completedPomodoros: 2 })
);
});
it('pushes local when cloud is unchanged and local is dirty', async () => {
const env = setup();
await synced(env, 3);
// Cloud still at v3
env.setCloud({ _version: 3, state: state() });
// User made local changes
env.fireStateChange(); // dirty = true
// Go to background (kills timeout), come back (triggers resync)
env.setVisibility('hidden');
env.setVisibility('visible');
await flush();
// Should push local changes
expect(env.db.runTransaction).toHaveBeenCalled();
expect(env.tx.set).toHaveBeenCalled();
});
it('shows conflict dialog when both sides changed', async () => {
const env = setup();
await synced(env, 3);
// User made local changes
env.fireStateChange(); // dirty = true
// Cloud also advanced
env.setCloud({ _version: 5, state: runningTimer() });
env.setVisibility('hidden');
env.setVisibility('visible');
await flush();
const modal = document.getElementById('conflict-modal');
expect(modal.classList.contains('hidden')).toBe(false);
});
it('calls onWake when nothing changed on either side', async () => {
const env = setup();
await synced(env, 3);
// Cloud unchanged
env.setCloud({ _version: 3, state: state() });
env.setVisibility('hidden');
env.setVisibility('visible');
await flush();
expect(env.db.runTransaction).not.toHaveBeenCalled();
expect(env.app.onWake).toHaveBeenCalled();
});
it('uses cache when server is unreachable and local is clean', async () => {
const env = setup();
await synced(env, 3);
// Server will fail, cache returns data
const cached = runningTimer();
env.docRef.get
.mockRejectedValueOnce(new Error('offline'))
.mockResolvedValueOnce({ exists: true, data: () => ({ _version: 4, state: cached }) });
env.setVisibility('hidden');
env.setVisibility('visible');
await flush();
// Should apply cache for display
expect(env.app.initWithState).toHaveBeenCalledWith(
expect.objectContaining({ isRunning: true })
);
// Should NOT push (cache might be stale)
expect(env.tx.set).not.toHaveBeenCalled();
});
});
// ---------------------------------------------------------------------------
// Initial sync
// ---------------------------------------------------------------------------
describe('initial sync', () => {
it('does not force-push when cloud state comes from cache', async () => {
const env = setup();
// Server unreachable, cache also empty
env.docRef.get
.mockRejectedValueOnce(new Error('offline'))
.mockResolvedValueOnce({ exists: false, data: () => null });
env.app.loadLocal.mockResolvedValue(state({ completedPomodoros: 3 }));
env.signIn();
await flush();
// Should init with local data
expect(env.app.initWithState).toHaveBeenCalled();
// Should NOT push (cache miss — cloud doc might exist)
expect(env.tx.set).not.toHaveBeenCalled();
});
it('pushes local when server confirms no cloud doc exists', async () => {
const env = setup();
env.setCloud(null);
env.app.loadLocal.mockResolvedValue(state({ completedPomodoros: 3 }));
env.signIn();
await flush();
expect(env.app.initWithState).toHaveBeenCalled();
expect(env.db.runTransaction).toHaveBeenCalled();
});
it('applies cloud state when no conflict with local', async () => {
const env = setup();
const cloud = runningTimer({ completedPomodoros: 4 });
env.setCloud({ _version: 5, state: cloud });
env.app.loadLocal.mockResolvedValue(state()); // fresh local
env.signIn();
await flush();
expect(env.app.initWithState).toHaveBeenCalledWith(
expect.objectContaining({ completedPomodoros: 4, isRunning: true })
);
// No conflict dialog
expect(document.getElementById('conflict-modal').classList.contains('hidden')).toBe(true);
});
});
// ---------------------------------------------------------------------------
// Conflict detection
// ---------------------------------------------------------------------------
describe('conflict detection', () => {
it('fresh local (0 pomodoros) is never a conflict', async () => {
const env = setup();
env.setCloud({ _version: 1, state: runningTimer({ completedPomodoros: 5 }) });
env.app.loadLocal.mockResolvedValue(state({ completedPomodoros: 0 }));
env.signIn();
await flush();
// Cloud should be applied directly — no conflict dialog
expect(env.app.initWithState).toHaveBeenCalledWith(
expect.objectContaining({ completedPomodoros: 5 })
);
expect(document.getElementById('conflict-modal').classList.contains('hidden')).toBe(true);
});
it('different completedPomodoros with progress is a conflict', async () => {
const env = setup();
env.setCloud({ _version: 1, state: state({ completedPomodoros: 3 }) });
env.app.loadLocal.mockResolvedValue(state({ completedPomodoros: 5 }));
env.signIn();
await flush();
expect(document.getElementById('conflict-modal').classList.contains('hidden')).toBe(false);
});
it('different dates is a conflict', async () => {
const env = setup();
env.setCloud({ _version: 1, state: state({ date: '2026-04-07', completedPomodoros: 2 }) });
env.app.loadLocal.mockResolvedValue(state({ date: '2026-04-08', completedPomodoros: 2 }));
env.signIn();
await flush();
expect(document.getElementById('conflict-modal').classList.contains('hidden')).toBe(false);
});
});
// ===========================================================================
// Multi-peer scenarios
// ===========================================================================
describe('multi-peer scenarios', () => {
// -------------------------------------------------------------------------
// The original bug that caused data loss
// -------------------------------------------------------------------------
it('the original bug: stale phone push is blocked after desktop starts timer', async () => {
// Phone syncs at v1 (stopped timer, 25min, 0 pomodoros)
const env = setup();
await synced(env, 1, state());
// Phone user pauses or interacts → state change → push scheduled (2s)
env.fireStateChange();
// Phone goes to background immediately — timeout cleared by visibility handler
env.setVisibility('hidden');
// Desktop starts a 25-min timer → pushes v2 to Firebase
// Phone's onSnapshot listener is dead (sleeping), so phone never receives v2
env.setCloud({ _version: 2, state: runningTimer({ remainingAtStart: 1200 }) });
// Phone wakes up — resync fires
env.setVisibility('visible');
await flush();
// Phone's stale stopped-timer state must NOT reach Firebase
// Check: any tx.set that happened should NOT contain the stale stopped state
const staleWrites = env.writes().filter(w => w.state && w.state.isRunning === false);
expect(staleWrites).toHaveLength(0);
});
it('the original bug: even if stale push fires, version guard blocks it', async () => {
// This tests the safety net: if somehow a stale push reaches the transaction
const env = setup();
await synced(env, 1, state());
// Desktop pushed v2 with running timer (phone missed the snapshot)
env.setCloud({ _version: 2, state: runningTimer() });
// Force a state change and let debounce fire (simulates frozen timeout edge case)
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
// Version guard: cloud v2 > knownVersion v1 → write blocked
expect(env.tx.set).not.toHaveBeenCalled();
// Cloud state applied locally — phone now shows the running timer
expect(env.app.applyRemoteState).toHaveBeenCalledWith(
expect.objectContaining({ isRunning: true })
);
});
// -------------------------------------------------------------------------
// Sequential updates from multiple devices
// -------------------------------------------------------------------------
it('snapshots from 3 different devices: version tracks to the latest', async () => {
const env = setup();
await synced(env, 1, state());
// Device B starts timer → v2
env.snapshot({ _sender: 'B', _version: 2, state: runningTimer() });
// Device C completes first pomodoro → v3
env.snapshot({ _sender: 'C', _version: 3, state: state({ completedPomodoros: 1 }) });
// Device D starts break → v4
env.snapshot({ _sender: 'D', _version: 4, state: state({ isFocus: false, completedPomodoros: 1 }) });
// Now local push should write at v5
env.setCloud({ _version: 4, state: state({ isFocus: false, completedPomodoros: 1 }) });
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.tx.set).toHaveBeenCalled();
const written = env.writes().pop();
expect(written._version).toBe(5);
});
it('3 snapshots in sequence: each applied, no spurious pushes', async () => {
const env = setup();
await synced(env, 1, state());
env.snapshot({ _sender: 'B', _version: 2, state: runningTimer() });
env.snapshot({ _sender: 'C', _version: 3, state: state({ completedPomodoros: 1 }) });
env.snapshot({ _sender: 'D', _version: 4, state: state({ completedPomodoros: 2 }) });
// Wait — no push should happen (all changes are remote)
await vi.advanceTimersByTimeAsync(5000);
await flush();
expect(env.db.runTransaction).not.toHaveBeenCalled();
// All 3 remote states were applied in order
expect(env.app.applyRemoteState).toHaveBeenCalledTimes(3);
const lastCall = env.app.applyRemoteState.mock.calls[2][0];
expect(lastCall.completedPomodoros).toBe(2);
});
// -------------------------------------------------------------------------
// Concurrent push races
// -------------------------------------------------------------------------
it('concurrent push: other device writes between local change and push firing', async () => {
const env = setup();
await synced(env, 5, state({ completedPomodoros: 2 }));
// Cloud matches what we know (v5)
env.setCloud({ _version: 5, state: state({ completedPomodoros: 2 }) });
// Local change → push scheduled for 2s
env.fireStateChange();
// At ~1s, another device pushes v6 (we don't receive snapshot — listener lag)
await vi.advanceTimersByTimeAsync(1000);
env.setCloud({ _version: 6, state: state({ completedPomodoros: 3 }) });
// At 2s, our push fires → tx.get reads v6 > knownVersion(5) → blocked!
await vi.advanceTimersByTimeAsync(1000);
await flush();
expect(env.tx.set).not.toHaveBeenCalled();
expect(env.app.applyRemoteState).toHaveBeenCalledWith(
expect.objectContaining({ completedPomodoros: 3 })
);
});
it('concurrent push from 2 peers: only the first write succeeds', async () => {
// Simulates: A and B both at v5, both make changes
// A's push fires first → writes v6
// B's push fires second → tx.get sees v6 > knownVersion(5) → blocked
// We test from B's perspective
const env = setup();
await synced(env, 5);
// Both A and B make changes. A pushes first → cloud now v6
env.setCloud({ _version: 6, state: runningTimer({ completedPomodoros: 1 }) });
// B (us) tries to push
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
// B's write blocked
expect(env.tx.set).not.toHaveBeenCalled();
// B gets A's state
expect(env.app.applyRemoteState).toHaveBeenCalledWith(
expect.objectContaining({ isRunning: true, completedPomodoros: 1 })
);
});
// -------------------------------------------------------------------------
// Recovery after blocked push
// -------------------------------------------------------------------------
it('after stale push is blocked, next legitimate push succeeds', async () => {
const env = setup();
await synced(env, 3);
// Cloud advances to v7 (missed updates)
env.setCloud({ _version: 7, state: runningTimer({ completedPomodoros: 2 }) });
// Stale push fires → blocked, cloud applied, knownVersion updated to 7
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.tx.set).not.toHaveBeenCalled();
env.clearMocks();
// Cloud still at v7 (no one else wrote)
env.setCloud({ _version: 7, state: runningTimer({ completedPomodoros: 2 }) });
// New legitimate local change → push should succeed at v8
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.tx.set).toHaveBeenCalled();
expect(env.writes().pop()._version).toBe(8);
});
it('two consecutive blocked pushes, then successful push', async () => {
const env = setup();
await synced(env, 1);
// First blocked push: cloud at v3
env.setCloud({ _version: 3, state: state({ completedPomodoros: 1 }) });
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.tx.set).not.toHaveBeenCalled();
env.clearMocks();
// Second blocked push: cloud advanced to v5
env.setCloud({ _version: 5, state: state({ completedPomodoros: 2 }) });
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.tx.set).not.toHaveBeenCalled();
env.clearMocks();
// Now cloud stable at v5, our push goes through at v6
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.tx.set).toHaveBeenCalled();
expect(env.writes().pop()._version).toBe(6);
});
// -------------------------------------------------------------------------
// Background / wake lifecycle with other peers
// -------------------------------------------------------------------------
it('background with pending change, peer writes, wake triggers conflict', async () => {
const env = setup();
await synced(env, 3, state({ completedPomodoros: 2 }));
// User changes state (e.g. pauses timer)
env.setState(state({ completedPomodoros: 2, isRunning: false }));
env.fireStateChange(); // dirty = true
// Phone goes to background — timeout killed but dirty stays true
env.setVisibility('hidden');
await vi.advanceTimersByTimeAsync(5000);
expect(env.db.runTransaction).not.toHaveBeenCalled();
// Meanwhile, another device completes a session and pushes v5
env.setCloud({ _version: 5, state: state({ completedPomodoros: 3 }) });
// Phone wakes → resync: dirty=true + cloud v5 > knownVersion v3 → CONFLICT
env.setVisibility('visible');
await flush();
expect(document.getElementById('conflict-modal').classList.contains('hidden')).toBe(false);
});
it('background clean, peer writes multiple times, wake accepts latest', async () => {
const env = setup();
await synced(env, 2);
// No local changes — go to background
env.setVisibility('hidden');
// Other devices push v3, v4, v5, v6 while we sleep
// We only see the final state on wake
env.setCloud({ _version: 6, state: state({ completedPomodoros: 4, isFocus: false }) });
env.setVisibility('visible');
await flush();
// Should silently accept cloud — no conflict (local clean)
expect(document.getElementById('conflict-modal').classList.contains('hidden')).toBe(true);
expect(env.app.initWithState).toHaveBeenCalledWith(
expect.objectContaining({ completedPomodoros: 4, isFocus: false })
);
});
// -------------------------------------------------------------------------
// Snapshot interleaved with local changes
// -------------------------------------------------------------------------
it('snapshot cancels pending push, new local change re-schedules and succeeds', async () => {
const env = setup();
await synced(env, 1);
// Round 1: local change → push scheduled
env.setCloud({ _version: 1, state: state() });
env.fireStateChange();
// Snapshot from peer arrives at 1s → cancels our push
await vi.advanceTimersByTimeAsync(1000);
env.snapshot({ _sender: 'B', _version: 2, state: state({ completedPomodoros: 1 }) });
// Our cancelled push should not fire
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.db.runTransaction).not.toHaveBeenCalled();
env.clearMocks();
// Round 2: new local change after accepting B's state
env.setCloud({ _version: 2, state: state({ completedPomodoros: 1 }) });
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
// This time push succeeds at v3
expect(env.tx.set).toHaveBeenCalled();
expect(env.writes().pop()._version).toBe(3);
});
it('3 interleaved: change → snapshot → change → snapshot → change → push', async () => {
const env = setup();
await synced(env, 1);
// Change 1
env.fireStateChange();
await vi.advanceTimersByTimeAsync(500);
// Snapshot 1 from B (v2) — cancels pending push
env.snapshot({ _sender: 'B', _version: 2, state: state({ completedPomodoros: 1 }) });
// Change 2
env.fireStateChange();
await vi.advanceTimersByTimeAsync(500);
// Snapshot 2 from C (v3) — cancels pending push again
env.snapshot({ _sender: 'C', _version: 3, state: state({ completedPomodoros: 2 }) });
// Change 3
env.setCloud({ _version: 3, state: state({ completedPomodoros: 2 }) });
env.fireStateChange();
// This time no more snapshots — push fires at 2s
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.tx.set).toHaveBeenCalled();
expect(env.writes().pop()._version).toBe(4);
});
// -------------------------------------------------------------------------
// Rapid-fire state changes (debounce coalescing)
// -------------------------------------------------------------------------
it('5 rapid local changes within 2s result in exactly 1 push', async () => {
const env = setup();
await synced(env, 1);
env.setCloud({ _version: 1, state: state() });
// 5 changes in rapid succession — each resets the 2s timer
for (let i = 0; i < 5; i++) {
env.fireStateChange();
await vi.advanceTimersByTimeAsync(300);
}
// Only 1.5s since last change — no push yet
await flush();
expect(env.db.runTransaction).not.toHaveBeenCalled();
// Advance remaining time for debounce
await vi.advanceTimersByTimeAsync(2000);
await flush();
// Exactly 1 push
expect(env.db.runTransaction).toHaveBeenCalledTimes(1);
});
// -------------------------------------------------------------------------
// Log merging across peers
// -------------------------------------------------------------------------
it('logs from 3 devices merge correctly through snapshots and pushes', async () => {
const env = setup();
// Start with device A's log
await synced(env, 1, state({ log: { '2026-04-06': { completed: 3, goal: 8 } } }));
// Device B sends snapshot with B's log
env.snapshot({
_sender: 'B', _version: 2,
state: state({ log: {
'2026-04-06': { completed: 3, goal: 8 },
'2026-04-07': { completed: 6, goal: 8 }
}})
});
// Now local device pushes with its own log entry for today
// Cloud includes logs from A and B
env.setCloud({
_version: 2,
state: state({ log: {
'2026-04-06': { completed: 3, goal: 8 },
'2026-04-07': { completed: 6, goal: 8 }
}})
});
env.setState(state({ log: { '2026-04-08': { completed: 2, goal: 8 } } }));
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
expect(env.tx.set).toHaveBeenCalled();
const written = env.writes().pop();
// All 3 days present
expect(written.state.log['2026-04-06'].completed).toBe(3);
expect(written.state.log['2026-04-07'].completed).toBe(6);
expect(written.state.log['2026-04-08'].completed).toBe(2);
});
it('log merge keeps higher count when devices have different values', async () => {
const env = setup();
await synced(env, 1);
// Cloud has 5 sessions for today, local has 3
env.setCloud({
_version: 1,
state: state({ log: { '2026-04-08': { completed: 5, goal: 8 } } })
});
env.setState(state({ log: { '2026-04-08': { completed: 3, goal: 8 } } }));
env.fireStateChange();
await vi.advanceTimersByTimeAsync(2000);
await flush();
const written = env.writes().pop();
expect(written.state.log['2026-04-08'].completed).toBe(5); // higher count wins
});
// -------------------------------------------------------------------------
// Resync edge cases with multiple peers
// -------------------------------------------------------------------------
it('double wake: second resync is rejected while first is in progress', async () => {
const env = setup();
await synced(env, 3);
// Make first docRef.get return a pending Promise (slow server)
let resolveGet;
env.docRef.get.mockReturnValueOnce(new Promise(r => { resolveGet = r; }));
// First wake → resync starts, waiting on server
env.setVisibility('hidden');
env.setVisibility('visible');
// Second wake while first is still in-flight → rejected by !ready guard
env.setVisibility('hidden');
env.setVisibility('visible');
// Only one server fetch was made
expect(env.docRef.get).toHaveBeenCalledTimes(1);
// Resolve the pending get → first resync completes
resolveGet({
exists: true,
data: () => ({ _version: 5, state: runningTimer() })
});
await flush();
expect(env.app.initWithState).toHaveBeenCalledWith(
expect.objectContaining({ isRunning: true })
);
});
it('resync while server is down, then online event triggers successful resync', async () => {
const env = setup();
await synced(env, 3);
// First wake: server unreachable
env.docRef.get
.mockRejectedValueOnce(new Error('offline'))
.mockResolvedValueOnce({ exists: false, data: () => null });
env.setVisibility('hidden');
env.setVisibility('visible');
await flush();
// Should not crash, should recover
env.clearMocks();
// Now network comes back with cloud at v5
env.setCloud({ _version: 5, state: runningTimer({ completedPomodoros: 2 }) });
// online event triggers resync
window.dispatchEvent(new Event('online'));
await flush();
expect(env.app.initWithState).toHaveBeenCalledWith(
expect.objectContaining({ completedPomodoros: 2, isRunning: true })
);
});
// -------------------------------------------------------------------------
// End-to-end multi-step sequences
// -------------------------------------------------------------------------
it('full session: start → sync → sleep → peer writes → wake → accept → work → push', async () => {
const env = setup();
// Step 1: Initial sync at v1
await synced(env, 1, state());