-
Notifications
You must be signed in to change notification settings - Fork 384
Expand file tree
/
Copy pathsynchronize.test.ts
More file actions
4074 lines (3785 loc) · 131 KB
/
Copy pathsynchronize.test.ts
File metadata and controls
4074 lines (3785 loc) · 131 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 { describe, it, expect, vi, beforeEach } from "vitest";
import { SynchronizeService } from "./synchronize";
import { initTestEnv } from "@Tests/utils";
import type FileSystem from "@Packages/filesystem/filesystem";
import type { FileInfo } from "@Packages/filesystem/filesystem";
import { FileSystemError } from "@Packages/filesystem/error";
import type { CloudSyncConfig, SystemConfig } from "@App/pkg/config/config";
import type { ScriptDAO } from "@App/app/repo/scripts";
import { stackAsyncTask } from "@App/pkg/utils/async_queue";
import { md5OfText } from "@App/pkg/utils/crypto";
import FileSystemFactory from "@Packages/filesystem/factory";
import { AgentModelRepo } from "@App/app/repo/agent_model";
import ChromeStorage from "@App/pkg/config/chrome_storage";
import { createMockOPFS } from "@App/app/repo/test-helpers";
import { cacheInstance } from "@App/app/cache";
initTestEnv();
beforeEach(() => createMockOPFS());
const syncConfig: CloudSyncConfig = {
enable: true,
syncDelete: true,
syncStatus: true,
filesystem: "webdav",
params: {},
};
const createFs = (overrides: Partial<FileSystem> = {}): FileSystem =>
({
verify: vi.fn().mockResolvedValue(undefined),
list: vi.fn().mockResolvedValue([]),
open: vi.fn(),
openDir: vi.fn(),
create: vi.fn().mockResolvedValue({
write: vi.fn().mockResolvedValue(undefined),
}),
createDir: vi.fn().mockResolvedValue(undefined),
delete: vi.fn().mockResolvedValue(undefined),
getDirUrl: vi.fn().mockResolvedValue(""),
...overrides,
}) as unknown as FileSystem;
// 等待若干轮微任务,确保所有已就绪的 await 都被推进
// (syncOnceInternal 开头有 pending_sync_ops 存储读取,轮数须覆盖它引入的额外 await)
const flushMicrotasks = async (rounds = 30) => {
for (let i = 0; i < rounds; i++) {
await Promise.resolve();
}
};
describe("SynchronizeService", () => {
beforeEach(() => {
vi.clearAllMocks();
chrome.storage.local.clear();
chrome.storage.sync?.clear?.();
});
it("下载 API 失败时仍返回手动下载所需的信息", async () => {
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any
);
vi.spyOn(service, "backup").mockResolvedValue(undefined);
const createObjectURLSpy = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:scriptcat-backup");
const downloadSpy = vi.spyOn(chrome.downloads, "download").mockRejectedValue(new Error("API unavailable"));
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
try {
const result = await service.requestExport();
await flushMicrotasks();
expect(result).toEqual({
url: "blob:scriptcat-backup",
filename: expect.stringMatching(/^scriptcat-backup-.*\.zip$/),
});
expect(downloadSpy).toHaveBeenCalled();
} finally {
createObjectURLSpy.mockRestore();
downloadSpy.mockRestore();
consoleErrorSpy.mockRestore();
}
});
it("手动云端备份与本地导出一样包含设置", async () => {
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{ scriptCodeDAO: {} } as any
);
const backupSpy = vi.spyOn(service, "backup").mockResolvedValue(undefined);
const cloudFs = createFs({
openDir: vi
.fn()
.mockResolvedValue(
createFs({ create: vi.fn().mockResolvedValue({ write: vi.fn().mockResolvedValue(undefined) }) })
),
});
const factorySpy = vi.spyOn(FileSystemFactory, "create").mockResolvedValue(cloudFs);
try {
await service.backupToCloud({ type: "webdav", params: {} });
expect(backupSpy).toHaveBeenCalledWith(expect.anything(), undefined, true);
} finally {
factorySpy.mockRestore();
}
});
it("设置备份往返默认模型与摘要模型选择", async () => {
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{ scriptCodeDAO: {} } as any
);
const modelRepo = new AgentModelRepo();
await modelRepo.setDefaultModelId("default-model");
await modelRepo.setSummaryModelId("summary-model");
const bundle = await service.getConfigBundle();
expect(bundle.agent.defaultModelId).toBe("default-model");
expect(bundle.agent.summaryModelId).toBe("summary-model");
await modelRepo.setDefaultModelId("");
await modelRepo.setSummaryModelId("");
await service.restoreConfigBundle(bundle);
expect(await modelRepo.getDefaultModelId()).toBe("default-model");
expect(await modelRepo.getSummaryModelId()).toBe("summary-model");
});
it("getConfigBundle 产出扁平 systemConfig 且不含本机相关键", async () => {
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{ scriptCodeDAO: {} } as any
);
// 往 system sync storage 写入 1 个可备份键 + 1 个本机键(language 属 STORAGE_LOCAL_KEYS)
const sync = new ChromeStorage("system", true);
await sync.set("menu_expand_num", 8);
await sync.set("language", "zh-CN");
const bundle = await service.getConfigBundle();
expect(bundle.systemConfig).toMatchObject({ menu_expand_num: 8 });
expect(bundle.systemConfig.language).toBeUndefined();
expect((bundle.systemConfig as any).sync).toBeUndefined();
});
it("restoreConfigBundle 把 systemConfig 键写回 sync storage", async () => {
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{ scriptCodeDAO: {} } as any
);
await service.restoreConfigBundle({
version: 1,
systemConfig: { menu_expand_num: 12 },
agent: { models: [], mcp: [], tasks: [], defaultModelId: "", summaryModelId: "" },
});
const sync = new ChromeStorage("system", true);
expect(await sync.get("menu_expand_num")).toBe(12);
});
it("serializes concurrent syncOnce calls", async () => {
let releaseFirst!: () => void;
const firstGate = new Promise<void>((resolve) => {
releaseFirst = resolve;
});
const order: string[] = [];
// gate 放在第一轮的最后一步(updateFileDigest 内部的 fs.list)
// 这样如果未来锁粒度被改小,第二轮提前进入也会被这个测试捕获
const fs1List = vi
.fn()
.mockImplementationOnce(async () => {
order.push("first:list");
return [];
})
.mockImplementationOnce(async () => {
order.push("first:digest");
await firstGate;
order.push("first:end");
return [];
});
const fs1 = createFs({ list: fs1List });
const fs2 = createFs({
list: vi.fn().mockImplementation(async () => {
order.push("second:list");
return [];
}),
});
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{
scriptCodeDAO: {},
all: vi.fn().mockResolvedValue([]),
} as any
);
const first = service.syncOnce(syncConfig, fs1);
const second = service.syncOnce(syncConfig, fs2);
await flushMicrotasks();
// 第一轮已经跑到末尾的 updateFileDigest,第二轮一步都没开始
expect(order).toEqual(["first:list", "first:digest"]);
expect((fs2.list as any).mock.calls.length).toBe(0);
releaseFirst();
await Promise.all([first, second]);
// 第一轮整体结束(first:end)后第二轮才能开始(second:list)
expect(order.slice(0, 4)).toEqual(["first:list", "first:digest", "first:end", "second:list"]);
});
it("does not delete orphan cloud script without meta", async () => {
const fs = createFs({
list: vi.fn().mockResolvedValue([
{
name: "orphan.user.js",
path: "orphan.user.js",
size: 1,
digest: "d1",
createtime: 1,
updatetime: 1,
},
]),
});
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{
scriptCodeDAO: {},
all: vi.fn().mockResolvedValue([]),
} as any
);
await service.syncOnce(syncConfig, fs);
expect(fs.delete).not.toHaveBeenCalled();
});
it("preserves cloudStatus for skipped orphan uuid when writing scriptcat-sync.json", async () => {
const orphanStatus = { enable: false, sort: 7, updatetime: 100 };
const writeMock = vi.fn().mockResolvedValue(undefined);
const fs = createFs({
list: vi.fn().mockResolvedValue([
{
name: "orphan.user.js",
path: "orphan.user.js",
size: 1,
digest: "d1",
createtime: 1,
updatetime: 1,
},
{
name: "scriptcat-sync.json",
path: "scriptcat-sync.json",
size: 1,
digest: "d2",
createtime: 1,
updatetime: 1,
},
]),
open: vi.fn().mockResolvedValue({
read: vi.fn().mockResolvedValue(
JSON.stringify({
version: "1.0.0",
status: { scripts: { orphan: orphanStatus } },
})
),
}),
create: vi.fn().mockResolvedValue({ write: writeMock }),
});
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{
scriptCodeDAO: {},
all: vi.fn().mockResolvedValue([]),
} as any
);
await service.syncOnce(syncConfig, fs);
// 第一次 write 是 scriptcat-sync.json 的内容
expect(writeMock).toHaveBeenCalled();
const writtenContent = writeMock.mock.calls[0][0] as string;
const written = JSON.parse(writtenContent);
expect(written.status.scripts.orphan).toEqual(orphanStatus);
});
it("兼容缺少 status.scripts 的旧版 scriptcat-sync.json", async () => {
const writeMock = vi.fn().mockResolvedValue(undefined);
const fs = createFs({
list: vi.fn().mockResolvedValue([
{
name: "scriptcat-sync.json",
path: "scriptcat-sync.json",
size: 1,
digest: "sync-digest",
createtime: 1,
updatetime: 1,
},
]),
open: vi.fn().mockResolvedValue({
read: vi.fn().mockResolvedValue(JSON.stringify({ version: "1.0.0" })),
}),
create: vi.fn().mockResolvedValue({ write: writeMock }),
});
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{
scriptCodeDAO: {},
all: vi.fn().mockResolvedValue([]),
} as any
);
await service.syncOnce(syncConfig, fs);
expect(writeMock).toHaveBeenCalledTimes(1);
const written = JSON.parse(writeMock.mock.calls[0][0] as string);
expect(written.status.scripts).toEqual({});
});
it("scriptcat-sync.json 损坏时不阻塞脚本同步且不覆盖状态文件", async () => {
const createMock = vi.fn().mockResolvedValue({
write: vi.fn().mockResolvedValue(undefined),
});
const fs = createFs({
list: vi
.fn()
.mockResolvedValueOnce([
{
name: "scriptcat-sync.json",
path: "scriptcat-sync.json",
size: 1,
digest: "sync-digest",
createtime: 1,
updatetime: 1,
},
])
.mockResolvedValueOnce([
{
name: "ok.user.js",
path: "ok.user.js",
size: 1,
digest: "cloud-ok-user",
createtime: 1,
updatetime: 1,
},
{
name: "ok.meta.json",
path: "ok.meta.json",
size: 1,
digest: "cloud-ok-meta",
createtime: 1,
updatetime: 1,
},
]),
open: vi.fn().mockResolvedValue({
read: vi.fn().mockResolvedValue("{"),
}),
create: createMock,
});
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{
scriptCodeDAO: {},
all: vi.fn().mockResolvedValue([
{
uuid: "ok",
name: "ok",
updatetime: 1,
createtime: 1,
status: 1,
sort: 0,
metadata: {},
},
]),
} as any
);
vi.spyOn(service, "pushScript").mockResolvedValue({
"ok.user.js": "pushed-ok-user",
"ok.meta.json": "pushed-ok-meta",
});
await service.syncOnce(syncConfig, fs);
expect(service.pushScript).toHaveBeenCalledTimes(1);
expect(createMock).not.toHaveBeenCalled();
await expect((service as any).storage.get("file_digest")).resolves.toEqual({
"ok.user.js": "cloud-ok-user",
"ok.meta.json": "cloud-ok-meta",
});
});
it("写回 scriptcat-sync.json 前重新读取远端状态,避免覆盖其他设备更新", async () => {
const initialStatus = { enable: false, sort: 7, updatetime: 200 };
const latestStatus = { enable: true, sort: 9, updatetime: 300 };
const writeMock = vi.fn().mockResolvedValue(undefined);
const syncFile = {
name: "scriptcat-sync.json",
path: "scriptcat-sync.json",
size: 1,
digest: "sync-digest",
createtime: 1,
updatetime: 1,
};
const fs = createFs({
list: vi.fn().mockResolvedValue([
{
name: "status-uuid.user.js",
path: "status-uuid.user.js",
size: 1,
digest: "script-digest",
createtime: 1,
updatetime: 1,
},
{
name: "status-uuid.meta.json",
path: "status-uuid.meta.json",
size: 1,
digest: "meta-digest",
createtime: 1,
updatetime: 1,
},
syncFile,
]),
open: vi
.fn()
.mockResolvedValueOnce({
read: vi.fn().mockResolvedValue(
JSON.stringify({
version: "1.0.0",
status: { scripts: { "status-uuid": initialStatus } },
})
),
})
.mockResolvedValueOnce({
read: vi.fn().mockResolvedValue(
JSON.stringify({
version: "1.0.0",
status: { scripts: { "status-uuid": latestStatus } },
})
),
}),
create: vi.fn().mockResolvedValue({ write: writeMock }),
});
const scriptDAO = {
scriptCodeDAO: {},
all: vi.fn().mockResolvedValue([
{
uuid: "status-uuid",
name: "status",
updatetime: 100,
createtime: 1,
status: 1,
sort: 1,
metadata: {},
},
]),
update: vi.fn().mockResolvedValue(undefined),
};
const service = new SynchronizeService(
{} as any,
{} as any,
{
enableScript: vi.fn().mockResolvedValue(undefined),
} as any,
{} as any,
{} as any,
{} as any,
{} as any,
scriptDAO as any
);
await (service as any).storage.set("file_digest", {
"status-uuid.user.js": "script-digest",
});
await service.syncOnce(syncConfig, fs);
expect(fs.open).toHaveBeenCalledTimes(2);
const written = JSON.parse(writeMock.mock.calls[0][0] as string);
expect(written.status.scripts["status-uuid"]).toEqual(latestStatus);
});
it("写回 scriptcat-sync.json 时本地较新的状态仍覆盖远端旧状态", async () => {
const initialStatus = { enable: false, sort: 7, updatetime: 100 };
const latestStatus = { enable: false, sort: 8, updatetime: 150 };
const localStatus = { enable: true, sort: 1, updatetime: 200 };
const writeMock = vi.fn().mockResolvedValue(undefined);
const fs = createFs({
list: vi.fn().mockResolvedValue([
{
name: "status-uuid.user.js",
path: "status-uuid.user.js",
size: 1,
digest: "script-digest",
createtime: 1,
// 云端文件与本地同版本(digest 一致、更新时间不早于本地),仅同步状态差异,不触发文件推送
updatetime: 200,
},
{
name: "status-uuid.meta.json",
path: "status-uuid.meta.json",
size: 1,
digest: "meta-digest",
createtime: 1,
updatetime: 1,
},
{
name: "scriptcat-sync.json",
path: "scriptcat-sync.json",
size: 1,
digest: "sync-digest",
createtime: 1,
updatetime: 1,
},
]),
open: vi
.fn()
.mockResolvedValueOnce({
read: vi.fn().mockResolvedValue(
JSON.stringify({
version: "1.0.0",
status: { scripts: { "status-uuid": initialStatus } },
})
),
})
.mockResolvedValueOnce({
read: vi.fn().mockResolvedValue(
JSON.stringify({
version: "1.0.0",
status: { scripts: { "status-uuid": latestStatus } },
})
),
}),
create: vi.fn().mockResolvedValue({ write: writeMock }),
});
const service = new SynchronizeService(
{} as any,
{} as any,
{
enableScript: vi.fn().mockResolvedValue(undefined),
} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{
scriptCodeDAO: {},
all: vi.fn().mockResolvedValue([
{
uuid: "status-uuid",
name: "status",
updatetime: localStatus.updatetime,
createtime: 1,
status: 1,
sort: localStatus.sort,
metadata: {},
},
]),
update: vi.fn().mockResolvedValue(undefined),
} as any
);
await (service as any).storage.set("file_digest", {
"status-uuid.user.js": "script-digest",
});
await service.syncOnce(syncConfig, fs);
expect(fs.open).toHaveBeenCalledTimes(2);
const written = JSON.parse(writeMock.mock.calls[0][0] as string);
expect(written.status.scripts["status-uuid"]).toEqual(localStatus);
});
it("排序待同步状态应独立覆盖旧排序且保留远端较新的启用状态", async () => {
const cloudStatus = { enable: false, sort: 8, updatetime: 300, sortUpdatetime: 100 };
const writeMock = vi.fn().mockResolvedValue(undefined);
const syncFile = {
name: "scriptcat-sync.json",
path: "scriptcat-sync.json",
size: 1,
digest: "sync-digest",
createtime: 1,
updatetime: 1,
};
const fs = createFs({
list: vi.fn().mockResolvedValue([syncFile]),
open: vi.fn().mockResolvedValue({
read: vi.fn().mockResolvedValue(JSON.stringify({ version: "1.0.0", status: { scripts: { u1: cloudStatus } } })),
}),
create: vi.fn().mockResolvedValue({ write: writeMock }),
});
const scriptDAO = {
scriptCodeDAO: {},
all: vi
.fn()
.mockResolvedValue([
{ uuid: "u1", name: "t", updatetime: 200, createtime: 1, status: 1, sort: 1, metadata: {} },
]),
get: vi.fn().mockResolvedValue(undefined),
update: vi.fn().mockResolvedValue(undefined),
};
const recordingService = new SynchronizeService(
{} as any,
{} as any,
{ enableScript: vi.fn().mockResolvedValue(undefined) } as any,
{} as any,
{} as any,
{} as any,
{} as any,
scriptDAO as any
);
const now = vi.spyOn(Date, "now").mockReturnValue(200);
try {
await recordingService.scriptsSorted([{ uuid: "u1", sort: 1, sortUpdatetime: 200 }]);
} finally {
now.mockRestore();
}
// 用新实例模拟 MV3 Service Worker 被回收后重新启动。
const service = new SynchronizeService(
{} as any,
{} as any,
{ enableScript: vi.fn().mockResolvedValue(undefined) } as any,
{} as any,
{} as any,
{} as any,
{} as any,
scriptDAO as any
);
vi.spyOn(service, "pushScript").mockResolvedValue({});
await service.syncOnce(syncConfig, fs);
const written = JSON.parse(writeMock.mock.calls[0][0] as string);
expect(written.status.scripts.u1).toEqual({
enable: false,
sort: 1,
updatetime: 300,
sortUpdatetime: 200,
});
await expect((service as any).storage.get("pending_sort_status")).resolves.toEqual({});
});
it("脚本删除后不应永久保留无主的排序待同步状态", async () => {
const writeMock = vi.fn().mockResolvedValue(undefined);
const syncFile = {
name: "scriptcat-sync.json",
path: "scriptcat-sync.json",
size: 1,
digest: "sync-digest",
createtime: 1,
updatetime: 1,
};
const fs = createFs({
list: vi.fn().mockResolvedValue([syncFile]),
open: vi.fn().mockResolvedValue({
read: vi.fn().mockResolvedValue(JSON.stringify({ version: "1.0.0", status: { scripts: {} } })),
}),
create: vi.fn().mockResolvedValue({ write: writeMock }),
});
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{
scriptCodeDAO: {},
all: vi.fn().mockResolvedValue([]),
} as any
);
await service.scriptsSorted([{ uuid: "deleted", sort: 0, sortUpdatetime: 200 }]);
await service.syncOnce(syncConfig, fs);
await expect((service as any).storage.get("pending_sort_status")).resolves.toEqual({});
});
it("失败脚本的同钟不同排序不得误清除排序待同步状态", async () => {
const writeMock = vi.fn().mockResolvedValue(undefined);
const syncFile = {
name: "scriptcat-sync.json",
path: "scriptcat-sync.json",
size: 1,
digest: "sync-digest",
createtime: 1,
updatetime: 1,
};
const fs = createFs({
list: vi.fn().mockResolvedValue([
{
name: "u1.meta.json",
path: "u1.meta.json",
size: 1,
digest: "meta-digest",
createtime: 1,
updatetime: 1,
},
syncFile,
]),
open: vi.fn().mockImplementation(async (file: FileInfo) => ({
read: vi.fn().mockResolvedValue(
file.name === "u1.meta.json"
? JSON.stringify({ uuid: "u1" })
: JSON.stringify({
version: "1.0.0",
status: { scripts: { u1: { enable: true, sort: 8, updatetime: 300, sortUpdatetime: 200 } } },
})
),
})),
create: vi.fn().mockResolvedValue({ write: writeMock }),
});
const service = new SynchronizeService(
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{} as any,
{
scriptCodeDAO: {},
all: vi
.fn()
.mockResolvedValue([
{ uuid: "u1", name: "t", updatetime: 300, createtime: 1, status: 1, sort: 1, metadata: {} },
]),
} as any
);
vi.spyOn(service, "pushScript").mockRejectedValue(new Error("push failed"));
const now = vi.spyOn(Date, "now").mockReturnValue(200);
try {
await service.scriptsSorted([{ uuid: "u1", sort: 1, sortUpdatetime: 200 }]);
await service.syncOnce(syncConfig, fs);
} finally {
now.mockRestore();
}
await expect((service as any).storage.get("pending_sort_status")).resolves.toEqual({
u1: { sort: 1, sortUpdatetime: 200 },
});
});
it("写回 scriptcat-sync.json 时远端已删除的 uuid 不应被复活", async () => {
const initialStatus = { enable: true, sort: 1, updatetime: 100 };
const writeMock = vi.fn().mockResolvedValue(undefined);
const fs = createFs({
list: vi.fn().mockResolvedValue([
{
name: "kept-uuid.user.js",
path: "kept-uuid.user.js",
size: 1,
digest: "d",
createtime: 1,
updatetime: 1,
},
{
name: "kept-uuid.meta.json",
path: "kept-uuid.meta.json",
size: 1,
digest: "d",
createtime: 1,
updatetime: 1,
},
{
name: "scriptcat-sync.json",
path: "scriptcat-sync.json",
size: 1,
digest: "sync-d",
createtime: 1,
updatetime: 1,
},
]),
open: vi
.fn()
// initial read: both uuids present
.mockResolvedValueOnce({
read: vi.fn().mockResolvedValue(
JSON.stringify({
version: "1.0.0",
status: {
scripts: {
"kept-uuid": initialStatus,
"deleted-uuid": initialStatus,
},
},
})
),
})
// latest re-read: deleted-uuid removed by another device
.mockResolvedValueOnce({
read: vi.fn().mockResolvedValue(
JSON.stringify({
version: "1.0.0",
status: { scripts: { "kept-uuid": initialStatus } },
})
),
}),
create: vi.fn().mockResolvedValue({ write: writeMock }),
});
const service = new SynchronizeService(
{} as any,
{} as any,
{ enableScript: vi.fn().mockResolvedValue(undefined) } as any,
{} as any,
{} as any,
{} as any,
{} as any,
{
scriptCodeDAO: {},
all: vi.fn().mockResolvedValue([
{
uuid: "kept-uuid",
name: "kept",
updatetime: 100,
createtime: 1,
status: 1,
sort: 1,
metadata: {},
},
]),
update: vi.fn().mockResolvedValue(undefined),
} as any
);
// digest 与云端一致的稳态:本测试只考察 status 写回合并,不涉及方向判定
await (service as any).storage.set("file_digest", { "kept-uuid.user.js": "d", "kept-uuid.meta.json": "d" });
await service.syncOnce(syncConfig, fs);
const written = JSON.parse(writeMock.mock.calls[0][0] as string);
expect(written.status.scripts).not.toHaveProperty("deleted-uuid");
expect(written.status.scripts).toHaveProperty("kept-uuid");
});
it("syncStatus 单个脚本排序更新失败时不阻塞整轮同步", async () => {
const cloudStatus = { enable: true, sort: 9, updatetime: 200 };
const writeMock = vi.fn().mockResolvedValue(undefined);
const fs = createFs({
list: vi.fn().mockResolvedValue([
{
name: "status-uuid.user.js",
path: "status-uuid.user.js",
size: 1,
digest: "script-digest",
createtime: 1,
// 云端文件与本地同版本(digest 一致、更新时间不早于本地),仅同步状态差异,不触发文件推送
updatetime: 200,
},
{
name: "status-uuid.meta.json",
path: "status-uuid.meta.json",
size: 1,
digest: "meta-digest",
createtime: 1,
updatetime: 1,
},
{
name: "scriptcat-sync.json",
path: "scriptcat-sync.json",
size: 1,
digest: "sync-digest",
createtime: 1,
updatetime: 1,
},
]),
open: vi.fn().mockResolvedValue({
read: vi.fn().mockResolvedValue(
JSON.stringify({
version: "1.0.0",
status: { scripts: { "status-uuid": cloudStatus } },
})
),
}),
create: vi.fn().mockResolvedValue({ write: writeMock }),
});
const scriptDAO = {
scriptCodeDAO: {},
all: vi.fn().mockResolvedValue([
{
uuid: "status-uuid",
name: "status",
updatetime: 100,
createtime: 1,
status: 1,
sort: 1,
metadata: {},
},
]),
update: vi.fn().mockRejectedValue(new Error("sort update failed")),
};
const service = new SynchronizeService(
{} as any,
{} as any,
{
enableScript: vi.fn().mockResolvedValue(undefined),
} as any,
{} as any,
{} as any,
{} as any,
{} as any,
scriptDAO as any
);
await (service as any).storage.set("file_digest", {
"status-uuid.user.js": "script-digest",
"status-uuid.meta.json": "meta-digest",
"scriptcat-sync.json": "sync-digest",
});
await service.syncOnce(syncConfig, fs);
expect(scriptDAO.update).toHaveBeenCalledWith("status-uuid", { sort: cloudStatus.sort });
expect(writeMock).toHaveBeenCalledTimes(1);
const written = JSON.parse(writeMock.mock.calls[0][0] as string);
expect(written.status.scripts["status-uuid"]).toEqual(cloudStatus);
await expect((service as any).storage.get("file_digest")).resolves.toMatchObject({
"status-uuid.user.js": "script-digest",
"status-uuid.meta.json": "meta-digest",
"scriptcat-sync.json": "sync-digest",
});
});
it("脚本文件同步失败时仍可回写其它脚本的 syncStatus 并保留失败脚本云端状态", async () => {
const failedCloudStatus = { enable: false, sort: 3, updatetime: 300 };
const okCloudStatus = { enable: false, sort: 1, updatetime: 100 };
const okLocalStatus = { enable: true, sort: 9, updatetime: 200 };
const writeMock = vi.fn().mockResolvedValue(undefined);
const fs = createFs({
list: vi.fn().mockResolvedValue([
{
name: "failed.user.js",
path: "failed.user.js",
size: 1,
digest: "failed-new-digest",
createtime: 1,
updatetime: 300,
},
{
name: "failed.meta.json",
path: "failed.meta.json",
size: 1,
digest: "failed-meta-digest",
createtime: 1,
updatetime: 300,