-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathmodelCache.spec.ts
More file actions
1084 lines (887 loc) · 35.8 KB
/
Copy pathmodelCache.spec.ts
File metadata and controls
1084 lines (887 loc) · 35.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
// Mocks must come first, before imports
// Mock TelemetryService
vi.mock("@roo-code/telemetry", () => ({
TelemetryService: {
instance: {
captureEvent: vi.fn(),
isTelemetryEnabled: vi.fn().mockReturnValue(true),
},
},
}))
// Mock NodeCache to allow controlling cache behavior
vi.mock("node-cache", () => {
const mockGet = vi.fn().mockReturnValue(undefined)
const mockSet = vi.fn()
const mockDel = vi.fn()
return {
default: vi.fn().mockImplementation(function () {
return {
get: mockGet,
set: mockSet,
del: mockDel,
}
}),
}
})
// Mock fs/promises to avoid file system operations
vi.mock("fs/promises", () => ({
writeFile: vi.fn().mockResolvedValue(undefined),
readFile: vi.fn().mockResolvedValue("{}"),
mkdir: vi.fn().mockResolvedValue(undefined),
}))
// Mock fs (synchronous) for disk cache fallback
vi.mock("fs", () => ({
existsSync: vi.fn().mockReturnValue(false),
readFileSync: vi.fn().mockReturnValue("{}"),
}))
// Mock all the model fetchers
vi.mock("../litellm")
vi.mock("../openrouter")
vi.mock("../requesty")
vi.mock("../kenari")
vi.mock("../moonshot")
vi.mock("../zoo-gateway")
// Mock ContextProxy with a simple static instance
vi.mock("../../../core/config/ContextProxy", () => ({
ContextProxy: {
instance: {
globalStorageUri: {
fsPath: "/mock/storage/path",
},
},
},
}))
// Then imports
import type { Mock, Mocked } from "vitest"
import { providerIdentifiers } from "@roo-code/types"
import * as fsSync from "fs"
import NodeCache from "node-cache"
import { TelemetryService } from "@roo-code/telemetry"
import { getModels, getModelsFromCache } from "../modelCache"
import { getLiteLLMModels } from "../litellm"
import { getOpenRouterModels } from "../openrouter"
import { getRequestyModels } from "../requesty"
import { getKenariModels } from "../kenari"
import { getMoonshotModels } from "../moonshot"
import { getZooGatewayModels } from "../zoo-gateway"
const mockGetLiteLLMModels = getLiteLLMModels as Mock<typeof getLiteLLMModels>
const mockGetOpenRouterModels = getOpenRouterModels as Mock<typeof getOpenRouterModels>
const mockGetRequestyModels = getRequestyModels as Mock<typeof getRequestyModels>
const mockGetKenariModels = getKenariModels as Mock<typeof getKenariModels>
const mockGetMoonshotModels = getMoonshotModels as Mock<typeof getMoonshotModels>
const mockGetZooGatewayModels = getZooGatewayModels as Mock<typeof getZooGatewayModels>
const DUMMY_REQUESTY_KEY = "requesty-key-for-testing"
describe("getModels with new GetModelsOptions", () => {
beforeEach(() => {
vi.clearAllMocks()
})
it("calls getLiteLLMModels with correct parameters", async () => {
const mockModels = {
"claude-3-sonnet": {
maxTokens: 4096,
contextWindow: 200000,
supportsPromptCache: false,
description: "Claude 3 Sonnet via LiteLLM",
},
}
mockGetLiteLLMModels.mockResolvedValue(mockModels)
const result = await getModels({
provider: providerIdentifiers.litellm,
apiKey: "test-api-key",
baseUrl: "http://localhost:4000",
})
expect(mockGetLiteLLMModels).toHaveBeenCalledWith("test-api-key", "http://localhost:4000")
expect(result).toEqual(mockModels)
})
it("calls getOpenRouterModels for openrouter provider", async () => {
const mockModels = {
"openrouter/model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: false,
description: "OpenRouter model",
},
}
mockGetOpenRouterModels.mockResolvedValue(mockModels)
const result = await getModels({ provider: providerIdentifiers.openrouter })
expect(mockGetOpenRouterModels).toHaveBeenCalled()
expect(result).toEqual(mockModels)
})
it("dispatches OpenRouter through its canonical provider identifier", async () => {
const mockModels = {
"openrouter/canonical-model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: false,
},
}
mockGetOpenRouterModels.mockResolvedValue(mockModels)
const result = await getModels({ provider: providerIdentifiers.openrouter })
expect(mockGetOpenRouterModels).toHaveBeenCalled()
expect(result).toEqual(mockModels)
})
it("calls getRequestyModels with optional API key", async () => {
const mockModels = {
"requesty/model": {
maxTokens: 4096,
contextWindow: 8192,
supportsPromptCache: false,
description: "Requesty model",
},
}
mockGetRequestyModels.mockResolvedValue(mockModels)
const result = await getModels({ provider: providerIdentifiers.requesty, apiKey: DUMMY_REQUESTY_KEY })
expect(mockGetRequestyModels).toHaveBeenCalledWith(undefined, DUMMY_REQUESTY_KEY)
expect(result).toEqual(mockModels)
})
it("dispatches credentialed fetchers through canonical provider identifiers", async () => {
const mockModels = {
"requesty/canonical-model": {
maxTokens: 4096,
contextWindow: 8192,
supportsPromptCache: false,
},
}
mockGetRequestyModels.mockResolvedValue(mockModels)
const result = await getModels({
provider: providerIdentifiers.requesty,
apiKey: DUMMY_REQUESTY_KEY,
baseUrl: "https://router.requesty.ai/v1",
})
expect(mockGetRequestyModels).toHaveBeenCalledWith("https://router.requesty.ai/v1", DUMMY_REQUESTY_KEY)
expect(result).toEqual(mockModels)
})
it("calls getKenariModels with optional API key", async () => {
const mockModels = {
"glm-5-2": {
maxTokens: 32768,
contextWindow: 1048576,
supportsPromptCache: false,
description: "GLM 5.2 via Kenari",
},
}
mockGetKenariModels.mockResolvedValue(mockModels)
const result = await getModels({ provider: providerIdentifiers.kenari, apiKey: "kenari-key-for-testing" })
expect(mockGetKenariModels).toHaveBeenCalledWith("kenari-key-for-testing")
expect(result).toEqual(mockModels)
})
it("handles errors and re-throws them", async () => {
const expectedError = new Error("LiteLLM connection failed")
mockGetLiteLLMModels.mockRejectedValue(expectedError)
await expect(
getModels({
provider: providerIdentifiers.litellm,
apiKey: "test-api-key",
baseUrl: "http://localhost:4000",
}),
).rejects.toThrow("LiteLLM connection failed")
})
it("calls getMoonshotModels with correct parameters", async () => {
const mockModels = {
"kimi-k2-0905-preview": {
maxTokens: 16384,
contextWindow: 262144,
supportsPromptCache: true,
description: "Moonshot Kimi K2",
},
}
mockGetMoonshotModels.mockResolvedValue(mockModels)
const result = await getModels({
provider: providerIdentifiers.moonshot,
apiKey: "test-key",
baseUrl: "https://api.moonshot.ai/v1",
})
expect(mockGetMoonshotModels).toHaveBeenCalledWith("https://api.moonshot.ai/v1", "test-key")
expect(result).toEqual(mockModels)
})
it("validates exhaustive provider checking with unknown provider", async () => {
// This test ensures TypeScript catches unknown providers at compile time
// In practice, the discriminated union should prevent this at compile time
const unknownProvider = "unknown" as typeof providerIdentifiers.openrouter
await expect(
getModels({
provider: unknownProvider,
}),
).rejects.toThrow("Unknown provider: unknown")
})
})
describe("getModelsFromCache disk fallback", () => {
let mockCache: Mocked<NodeCache>
beforeEach(() => {
vi.clearAllMocks()
// Get the mock cache instance
const MockedNodeCache = vi.mocked(NodeCache)
mockCache = vi.mocked(new MockedNodeCache())
// Reset memory cache to always miss
mockCache.get.mockReturnValue(undefined)
// Reset fs mocks
vi.mocked(fsSync.existsSync).mockReturnValue(false)
vi.mocked(fsSync.readFileSync).mockReturnValue("{}")
})
it("returns undefined when both memory and disk cache miss", () => {
vi.mocked(fsSync.existsSync).mockReturnValue(false)
const result = getModelsFromCache(providerIdentifiers.openrouter)
expect(result).toBeUndefined()
})
it("returns memory cache data without checking disk when available", () => {
const memoryModels = {
"memory-model": {
maxTokens: 8192,
contextWindow: 200000,
supportsPromptCache: false,
},
}
mockCache.get.mockReturnValue(memoryModels)
const result = getModelsFromCache(providerIdentifiers.openrouter)
expect(result).toEqual(memoryModels)
// Disk should not be checked when memory cache hits
expect(fsSync.existsSync).not.toHaveBeenCalled()
})
it("isolates authenticated users through the canonical Zoo Gateway identifier", () => {
const previousUserModels = {
"previous-user/model": {
maxTokens: 4096,
contextWindow: 128000,
supportsPromptCache: false,
},
}
mockCache.get.mockReturnValue(previousUserModels)
const result = getModelsFromCache(providerIdentifiers.zooGateway)
expect(result).toBeUndefined()
expect(mockCache.get).not.toHaveBeenCalled()
})
it("returns disk cache data when memory cache misses and context is available", () => {
// Note: This test validates the logic but the ContextProxy mock in test environment
// returns undefined for getCacheDirectoryPathSync, which is expected behavior
// when the context is not fully initialized. The actual disk cache loading
// is validated through integration tests.
const diskModels = {
"disk-model": {
maxTokens: 4096,
contextWindow: 128000,
supportsPromptCache: false,
},
}
vi.mocked(fsSync.existsSync).mockReturnValue(true)
vi.mocked(fsSync.readFileSync).mockReturnValue(JSON.stringify(diskModels))
const result = getModelsFromCache(providerIdentifiers.openrouter)
// In the test environment, ContextProxy.instance may not be fully initialized,
// so getCacheDirectoryPathSync returns undefined and disk cache is not attempted
expect(result).toBeUndefined()
})
it("handles disk read errors gracefully", () => {
vi.mocked(fsSync.existsSync).mockReturnValue(true)
vi.mocked(fsSync.readFileSync).mockImplementation(function () {
throw new Error("Disk read failed")
})
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(function () {})
const result = getModelsFromCache(providerIdentifiers.openrouter)
expect(result).toBeUndefined()
expect(consoleErrorSpy).toHaveBeenCalled()
consoleErrorSpy.mockRestore()
})
it("handles invalid JSON in disk cache gracefully", () => {
vi.mocked(fsSync.existsSync).mockReturnValue(true)
vi.mocked(fsSync.readFileSync).mockReturnValue("invalid json{")
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(function () {})
const result = getModelsFromCache(providerIdentifiers.openrouter)
expect(result).toBeUndefined()
expect(consoleErrorSpy).toHaveBeenCalled()
consoleErrorSpy.mockRestore()
})
})
describe("empty cache protection", () => {
let mockCache: Mocked<NodeCache>
let mockGet: Mocked<NodeCache>["get"]
let mockSet: Mocked<NodeCache>["set"]
beforeEach(() => {
vi.clearAllMocks()
// Get the mock cache instance
const MockedNodeCache = vi.mocked(NodeCache)
mockCache = vi.mocked(new MockedNodeCache())
mockGet = mockCache.get
mockSet = mockCache.set
// Reset memory cache to always miss by default
mockGet.mockReturnValue(undefined)
})
describe("getModels", () => {
it("does not cache empty API responses", async () => {
// API returns empty object (simulating failure)
mockGetOpenRouterModels.mockResolvedValue({})
const result = await getModels({ provider: providerIdentifiers.openrouter })
// Should return empty but NOT cache it
expect(result).toEqual({})
expect(mockSet).not.toHaveBeenCalled()
})
it("caches non-empty API responses", async () => {
const mockModels = {
"openrouter/model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: false,
description: "OpenRouter model",
},
}
mockGetOpenRouterModels.mockResolvedValue(mockModels)
const result = await getModels({ provider: providerIdentifiers.openrouter })
expect(result).toEqual(mockModels)
expect(mockSet).toHaveBeenCalledWith("openrouter", mockModels)
})
it("reuses an in-flight fetch for concurrent getModels() calls to the same provider", async () => {
const mockModels = {
"openrouter/model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: false,
description: "OpenRouter model",
},
}
let resolvePromise: (value: typeof mockModels) => void
const delayedPromise = new Promise<typeof mockModels>((resolve) => {
resolvePromise = resolve
})
mockGetOpenRouterModels.mockReturnValue(delayedPromise)
mockGet.mockReturnValue(undefined)
const promise1 = getModels({ provider: providerIdentifiers.openrouter })
const promise2 = getModels({ provider: providerIdentifiers.openrouter })
expect(mockGetOpenRouterModels).toHaveBeenCalledTimes(1)
resolvePromise!(mockModels)
const [result1, result2] = await Promise.all([promise1, promise2])
expect(result1).toEqual(mockModels)
expect(result2).toEqual(mockModels)
})
it("shares a single in-flight fetch between getModels() and refreshModels() for the same key", async () => {
// Both entry points converge on the same coordinator so a getModels() cache miss
// racing a concurrent refreshModels() call can't produce two unordered cache writes.
const mockModels = {
"openrouter/model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: false,
description: "OpenRouter model",
},
}
let resolvePromise: (value: typeof mockModels) => void
const delayedPromise = new Promise<typeof mockModels>((resolve) => {
resolvePromise = resolve
})
mockGetOpenRouterModels.mockReturnValue(delayedPromise)
mockGet.mockReturnValue(undefined)
const { refreshModels } = await import("../modelCache")
const getPromise = getModels({ provider: providerIdentifiers.openrouter })
const refreshPromise = refreshModels({ provider: providerIdentifiers.openrouter })
expect(mockGetOpenRouterModels).toHaveBeenCalledTimes(1)
resolvePromise!(mockModels)
const [getResult, refreshResult] = await Promise.all([getPromise, refreshPromise])
expect(getResult).toEqual(mockModels)
expect(refreshResult).toEqual(mockModels)
})
it("does not share an in-flight fetch between different endpoints/keys", async () => {
const mockModelsA = {
"litellm/model-a": {
maxTokens: 4096,
contextWindow: 64000,
supportsPromptCache: false,
description: "Server A model",
},
}
const mockModelsB = {
"litellm/model-b": {
maxTokens: 4096,
contextWindow: 64000,
supportsPromptCache: false,
description: "Server B model",
},
}
mockGetLiteLLMModels.mockResolvedValueOnce(mockModelsA).mockResolvedValueOnce(mockModelsB)
mockGet.mockReturnValue(undefined)
const [resultA, resultB] = await Promise.all([
getModels({ provider: providerIdentifiers.litellm, apiKey: "key-a", baseUrl: "http://server-a:4000" }),
getModels({ provider: providerIdentifiers.litellm, apiKey: "key-b", baseUrl: "http://server-b:4000" }),
])
expect(mockGetLiteLLMModels).toHaveBeenCalledTimes(2)
expect(resultA).toEqual(mockModelsA)
expect(resultB).toEqual(mockModelsB)
})
it("re-arms the empty-response throttle after a non-empty response from an auth-scoped provider", async () => {
// zoo-gateway is auth-scoped and skips caching entirely, but a non-empty response
// must still clear the throttle so a later empty response is reported again.
mockGetZooGatewayModels.mockResolvedValueOnce({})
await getModels({ provider: providerIdentifiers.zooGateway, apiKey: "test-key" })
expect(TelemetryService.instance.captureEvent).toHaveBeenCalledTimes(1)
const mockModels = {
"zoo-gateway/model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: false,
description: "Zoo Gateway model",
},
}
mockGetZooGatewayModels.mockResolvedValueOnce(mockModels)
await getModels({ provider: providerIdentifiers.zooGateway, apiKey: "test-key" })
// Auth-scoped providers never populate the cache.
expect(mockSet).not.toHaveBeenCalled()
mockGetZooGatewayModels.mockResolvedValueOnce({})
await getModels({ provider: providerIdentifiers.zooGateway, apiKey: "test-key" })
// The throttle should have been re-armed by the non-empty response above, so this
// second empty response is reported again instead of being suppressed.
expect(TelemetryService.instance.captureEvent).toHaveBeenCalledTimes(2)
})
})
describe("refreshModels", () => {
it("keeps existing cache when API returns empty response", async () => {
const existingModels = {
"openrouter/existing-model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: false,
description: "Existing cached model",
},
}
// Memory cache has existing data
mockGet.mockReturnValue(existingModels)
// API returns empty (failure)
mockGetOpenRouterModels.mockResolvedValue({})
const { refreshModels } = await import("../modelCache")
const result = await refreshModels({ provider: providerIdentifiers.openrouter })
// Should return existing cache, not empty
expect(result).toEqual(existingModels)
// Should NOT update cache with empty data
expect(mockSet).not.toHaveBeenCalled()
})
it("updates cache when API returns valid non-empty response", async () => {
const existingModels = {
"openrouter/old-model": {
maxTokens: 4096,
contextWindow: 64000,
supportsPromptCache: false,
description: "Old model",
},
}
const newModels = {
"openrouter/new-model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: true,
description: "New model",
},
}
mockGet.mockReturnValue(existingModels)
mockGetOpenRouterModels.mockResolvedValue(newModels)
const { refreshModels } = await import("../modelCache")
const result = await refreshModels({ provider: providerIdentifiers.openrouter })
// Should return new models
expect(result).toEqual(newModels)
// Should update cache with new data
expect(mockSet).toHaveBeenCalledWith("openrouter", newModels)
})
it("returns existing cache on API error", async () => {
const existingModels = {
"openrouter/cached-model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: false,
description: "Cached model",
},
}
mockGet.mockReturnValue(existingModels)
mockGetOpenRouterModels.mockRejectedValue(new Error("API error"))
const { refreshModels } = await import("../modelCache")
const result = await refreshModels({ provider: providerIdentifiers.openrouter })
// Should return existing cache on error
expect(result).toEqual(existingModels)
})
it("returns empty object when API errors and no cache exists", async () => {
mockGet.mockReturnValue(undefined)
mockGetOpenRouterModels.mockRejectedValue(new Error("API error"))
const { refreshModels } = await import("../modelCache")
const result = await refreshModels({ provider: providerIdentifiers.openrouter })
// Should return empty when no cache and API fails
expect(result).toEqual({})
})
it("does not cache empty response when no existing cache", async () => {
// Both memory and disk cache are empty (initial state)
mockGet.mockReturnValue(undefined)
// API returns empty (failure/rate limit)
mockGetOpenRouterModels.mockResolvedValue({})
const { refreshModels } = await import("../modelCache")
const result = await refreshModels({ provider: providerIdentifiers.openrouter })
// Should return empty but NOT cache it
expect(result).toEqual({})
expect(mockSet).not.toHaveBeenCalled()
})
it("reuses in-flight request for concurrent calls to same provider", async () => {
const mockModels = {
"openrouter/model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: false,
description: "OpenRouter model",
},
}
// Create a delayed response to simulate API latency
let resolvePromise: (value: typeof mockModels) => void
const delayedPromise = new Promise<typeof mockModels>((resolve) => {
resolvePromise = resolve
})
mockGetOpenRouterModels.mockReturnValue(delayedPromise)
mockGet.mockReturnValue(undefined)
const { refreshModels } = await import("../modelCache")
// Start two concurrent refresh calls
const promise1 = refreshModels({ provider: providerIdentifiers.openrouter })
const promise2 = refreshModels({ provider: providerIdentifiers.openrouter })
// API should only be called once (second call reuses in-flight request)
expect(mockGetOpenRouterModels).toHaveBeenCalledTimes(1)
// Resolve the API call
resolvePromise!(mockModels)
// Both promises should resolve to the same result
const [result1, result2] = await Promise.all([promise1, promise2])
expect(result1).toEqual(mockModels)
expect(result2).toEqual(mockModels)
})
it("scopes in-flight dedup by API key for key-scoped providers", async () => {
// In-flight dedup is keyed on the compound cache key, so concurrent refreshes for a
// key-scoped provider must dedup only when the API key matches. Two different keys
// (different compound keys) each trigger their own fetch; the same key shares one.
const mockModels = {
"requesty/model": {
maxTokens: 4096,
contextWindow: 200000,
supportsPromptCache: false,
description: "Requesty model",
},
}
mockGetRequestyModels.mockResolvedValue(mockModels)
const { refreshModels } = await import("../modelCache")
// Different keys -> separate compound keys -> two distinct fetches.
const [a, b] = await Promise.all([
refreshModels({ provider: providerIdentifiers.requesty, apiKey: "key-one" }),
refreshModels({ provider: providerIdentifiers.requesty, apiKey: "key-two" }),
])
expect(mockGetRequestyModels).toHaveBeenCalledTimes(2)
expect(a).toEqual(mockModels)
expect(b).toEqual(mockModels)
mockGetRequestyModels.mockClear()
// Same key -> same compound key -> a single shared in-flight fetch.
let resolveShared: (value: typeof mockModels) => void
mockGetRequestyModels.mockReturnValue(
new Promise<typeof mockModels>((resolve) => {
resolveShared = resolve
}),
)
const shared1 = refreshModels({ provider: providerIdentifiers.requesty, apiKey: "same-key" })
const shared2 = refreshModels({ provider: providerIdentifiers.requesty, apiKey: "same-key" })
expect(mockGetRequestyModels).toHaveBeenCalledTimes(1)
resolveShared!(mockModels)
const [s1, s2] = await Promise.all([shared1, shared2])
expect(s1).toEqual(mockModels)
expect(s2).toEqual(mockModels)
})
})
})
describe("MODEL_CACHE_EMPTY_RESPONSE throttling", () => {
type ModelCacheModule = typeof import("../modelCache")
let freshGetModels: ModelCacheModule["getModels"]
let freshRefreshModels: ModelCacheModule["refreshModels"]
let freshMockGetOpenRouterModels: Mock<typeof getOpenRouterModels>
let freshMockGetLiteLLMModels: Mock<typeof getLiteLLMModels>
let freshMockGetZooGatewayModels: Mock<typeof getZooGatewayModels>
beforeEach(async () => {
// The empty-response throttle is deliberately module-level, persistent state (once per
// cache key per session). Reset modules per test so each test starts with a clean gate.
vi.resetModules()
vi.clearAllMocks()
const modelCacheModule: ModelCacheModule = await import("../modelCache")
const openRouterModule = await import("../openrouter")
const liteLLMModule = await import("../litellm")
const zooGatewayModule = await import("../zoo-gateway")
freshGetModels = modelCacheModule.getModels
freshRefreshModels = modelCacheModule.refreshModels
freshMockGetOpenRouterModels = openRouterModule.getOpenRouterModels as Mock<typeof getOpenRouterModels>
freshMockGetLiteLLMModels = liteLLMModule.getLiteLLMModels as Mock<typeof getLiteLLMModels>
freshMockGetZooGatewayModels = zooGatewayModule.getZooGatewayModels as Mock<typeof getZooGatewayModels>
const NodeCacheModule = await import("node-cache")
const MockedNodeCache = vi.mocked(NodeCacheModule.default)
const mockCache = vi.mocked(new MockedNodeCache())
mockCache.get.mockReturnValue(undefined)
})
it("fires MODEL_CACHE_EMPTY_RESPONSE only once for repeated empty getModels responses from the same provider", async () => {
freshMockGetOpenRouterModels.mockResolvedValue({})
await freshGetModels({ provider: providerIdentifiers.openrouter })
await freshGetModels({ provider: providerIdentifiers.openrouter })
await freshGetModels({ provider: providerIdentifiers.openrouter })
const { TelemetryService: FreshTelemetryService } = await import("@roo-code/telemetry")
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledTimes(1)
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledWith(
"Model Cache Empty Response",
expect.objectContaining({ provider: providerIdentifiers.openrouter, context: "getModels" }),
)
})
it("fires again after a non-empty response resets the throttle", async () => {
const { TelemetryService: FreshTelemetryService } = await import("@roo-code/telemetry")
freshMockGetOpenRouterModels.mockResolvedValue({})
await freshGetModels({ provider: providerIdentifiers.openrouter })
await freshGetModels({ provider: providerIdentifiers.openrouter })
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledTimes(1)
freshMockGetOpenRouterModels.mockResolvedValue({
"openrouter/model": {
maxTokens: 8192,
contextWindow: 128000,
supportsPromptCache: false,
description: "OpenRouter model",
},
})
await freshGetModels({ provider: providerIdentifiers.openrouter })
freshMockGetOpenRouterModels.mockResolvedValue({})
await freshGetModels({ provider: providerIdentifiers.openrouter })
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledTimes(2)
})
it("throttles independently per provider", async () => {
const { TelemetryService: FreshTelemetryService } = await import("@roo-code/telemetry")
freshMockGetOpenRouterModels.mockResolvedValue({})
freshMockGetLiteLLMModels.mockResolvedValue({})
await freshGetModels({ provider: providerIdentifiers.openrouter })
await freshGetModels({ provider: providerIdentifiers.litellm, apiKey: "key", baseUrl: "http://localhost:4000" })
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledTimes(2)
})
it("throttles empty responses from refreshModels using the same per-key gate", async () => {
const { TelemetryService: FreshTelemetryService } = await import("@roo-code/telemetry")
freshMockGetOpenRouterModels.mockResolvedValue({})
await freshRefreshModels({ provider: providerIdentifiers.openrouter })
await freshRefreshModels({ provider: providerIdentifiers.openrouter })
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledTimes(1)
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledWith(
"Model Cache Empty Response",
expect.objectContaining({
provider: providerIdentifiers.openrouter,
context: "refreshModels",
hasExistingCache: false,
existingCacheSize: 0,
}),
)
})
it("throttles independently per distinct endpoint, not just per provider name", async () => {
// Two different LiteLLM servers share the "litellm" provider name but are a different
// cache identity (see getCacheKey) -- an empty response from one must not suppress the
// signal for the other.
const { TelemetryService: FreshTelemetryService } = await import("@roo-code/telemetry")
freshMockGetLiteLLMModels.mockResolvedValue({})
await freshGetModels({
provider: providerIdentifiers.litellm,
apiKey: "key-a",
baseUrl: "http://server-a:4000",
})
await freshGetModels({
provider: providerIdentifiers.litellm,
apiKey: "key-a",
baseUrl: "http://server-a:4000",
})
await freshGetModels({
provider: providerIdentifiers.litellm,
apiKey: "key-b",
baseUrl: "http://server-b:4000",
})
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledTimes(2)
})
it("throttles zoo-gateway independently per session token, even though caching itself is skipped", async () => {
// zoo-gateway is auth-scoped (see AUTH_SCOPED_PROVIDERS) and never persists to the
// memory/disk cache, but the empty-response throttle must still discriminate by
// identity: a sign-out/sign-in cycle to a different account carries a different
// session token (apiKey) on the same gateway URL, and must not have its empty-response
// signal suppressed by the previous account's throttle entry.
const { TelemetryService: FreshTelemetryService } = await import("@roo-code/telemetry")
freshMockGetZooGatewayModels.mockResolvedValue({})
await freshGetModels({ provider: providerIdentifiers.zooGateway, apiKey: "account-a-token" })
await freshGetModels({ provider: providerIdentifiers.zooGateway, apiKey: "account-a-token" })
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledTimes(1)
await freshGetModels({ provider: providerIdentifiers.zooGateway, apiKey: "account-b-token" })
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledTimes(2)
})
it("throttles zoo-gateway independently per gateway baseUrl", async () => {
// Same session token, different gateway endpoint (e.g. staging vs. production) --
// must also be treated as a distinct identity for throttle purposes.
const { TelemetryService: FreshTelemetryService } = await import("@roo-code/telemetry")
freshMockGetZooGatewayModels.mockResolvedValue({})
await freshGetModels({
provider: providerIdentifiers.zooGateway,
apiKey: "token",
baseUrl: "https://gateway-a.example.com",
})
await freshGetModels({
provider: providerIdentifiers.zooGateway,
apiKey: "token",
baseUrl: "https://gateway-b.example.com",
})
expect(FreshTelemetryService.instance.captureEvent).toHaveBeenCalledTimes(2)
})
it("never shares results across different zoo-gateway credentials (auth isolation)", async () => {
// The in-flight fetch map must key on the full compound identity for auth-scoped
// providers too, so a slow fetch for one account's session token can never resolve
// into a concurrent call carrying a different account's token.
const accountAModels = {
"zoo-gateway/account-a-model": {
maxTokens: 4096,
contextWindow: 64000,
supportsPromptCache: false,
description: "Account A model",
},
}
const accountBModels = {
"zoo-gateway/account-b-model": {
maxTokens: 4096,
contextWindow: 64000,
supportsPromptCache: false,
description: "Account B model",
},
}
let resolveA: (value: typeof accountAModels) => void
let resolveB: (value: typeof accountBModels) => void
freshMockGetZooGatewayModels
.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveA = resolve
}),
)
.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveB = resolve
}),
)
const promiseA = freshGetModels({ provider: providerIdentifiers.zooGateway, apiKey: "account-a-token" })
const promiseB = freshGetModels({ provider: providerIdentifiers.zooGateway, apiKey: "account-b-token" })
expect(freshMockGetZooGatewayModels).toHaveBeenCalledTimes(2)
resolveB!(accountBModels)
resolveA!(accountAModels)
const [resultA, resultB] = await Promise.all([promiseA, promiseB])
expect(resultA).toEqual(accountAModels)
expect(resultB).toEqual(accountBModels)
})
})
describe("key-scoped cache key derivation", () => {
// Exercises the per-API-key cache discriminator that all KEY_SCOPED_PROVIDERS share.
// Requesty is used only because it is a key-scoped provider with a mocked fetcher; the
// behavior under test is provider-agnostic.
const keyScopedProvider = providerIdentifiers.requesty
let mockCache: Mocked<NodeCache>
let mockSet: Mocked<NodeCache>["set"]
const mockModels = {
"key-scoped/model": {
maxTokens: 4096,
contextWindow: 200000,
supportsPromptCache: false,
description: "Key-scoped provider model",
},
}
beforeEach(() => {
vi.clearAllMocks()
const MockedNodeCache = vi.mocked(NodeCache)
mockCache = vi.mocked(new MockedNodeCache())
mockCache.get.mockReturnValue(undefined)
mockSet = mockCache.set
mockGetRequestyModels.mockResolvedValue(mockModels)
})
// Returns the cache key the result was written under (first arg of the matching set call).
const writtenCacheKey = (): string => {
const call = mockSet.mock.calls.find((c) => c[1] === mockModels)
return call?.[0] as string
}
it("writes different cache keys for different API keys", async () => {
await getModels({ provider: keyScopedProvider, apiKey: "key-one" })
const firstKey = writtenCacheKey()
mockSet.mockClear()
await getModels({ provider: keyScopedProvider, apiKey: "key-two" })
const secondKey = writtenCacheKey()
expect(firstKey).toBeDefined()
expect(secondKey).toBeDefined()
expect(firstKey).not.toEqual(secondKey)
})
it("writes the same cache key for repeated calls with the same API key", async () => {
await getModels({ provider: keyScopedProvider, apiKey: "stable-key" })
const firstKey = writtenCacheKey()
mockSet.mockClear()
await getModels({ provider: keyScopedProvider, apiKey: "stable-key" })
const secondKey = writtenCacheKey()
expect(firstKey).toEqual(secondKey)
})
it("does not embed the raw API key in the cache key and truncates the discriminator", async () => {
const apiKey = "super-secret-api-key-value"
await getModels({ provider: keyScopedProvider, apiKey })
const cacheKey = writtenCacheKey()
// The raw secret must never appear in the on-disk-bound cache key.
expect(cacheKey).not.toContain(apiKey)
// The discriminator is the trailing key-component: an 8-char (32-bit) hex string.
const discriminator = cacheKey.split(":").pop() as string
expect(discriminator).toMatch(/^[0-9a-f]{8}$/)