-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathApiOptions.spec.tsx
More file actions
625 lines (544 loc) · 21.3 KB
/
Copy pathApiOptions.spec.tsx
File metadata and controls
625 lines (544 loc) · 21.3 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
// npx vitest src/components/settings/__tests__/ApiOptions.spec.tsx
import { render, screen, fireEvent, within } from "@/utils/test-utils"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { type ModelInfo, type ProviderSettings, openAiModelInfoSaneDefaults } from "@roo-code/types"
import { openAiCodexDefaultModelId, zooGatewayDefaultModelId } from "@roo-code/types"
import * as ExtensionStateContext from "@src/context/ExtensionStateContext"
const { ExtensionStateContextProvider } = ExtensionStateContext
import ApiOptions, { ApiOptionsProps } from "../ApiOptions"
// Mock VSCode components
vi.mock("@vscode/webview-ui-toolkit/react", () => ({
VSCodeTextField: ({ children, value, onBlur }: any) => (
<div>
{children}
<input type="text" value={value} onChange={onBlur} />
</div>
),
VSCodeLink: ({ children, href }: any) => <a href={href}>{children}</a>,
VSCodeRadio: ({ value, checked }: any) => <input type="radio" value={value} checked={checked} />,
VSCodeRadioGroup: ({ children }: any) => <div>{children}</div>,
VSCodeButton: ({ children }: any) => <div>{children}</div>,
VSCodeCheckbox: ({ children, checked, onChange }: any) => (
<label>
<input
type="checkbox"
checked={checked}
onChange={(e) => onChange && onChange({ target: { checked: e.target.checked } })}
/>
{children}
</label>
),
}))
// Mock other components
vi.mock("vscrui", () => ({
Checkbox: ({ children, checked, onChange }: any) => (
<label data-testid={`checkbox-${children?.toString().replace(/\s+/g, "-").toLowerCase()}`}>
<input
type="checkbox"
checked={checked}
onChange={(e) => onChange(e.target.checked)}
data-testid={`checkbox-input-${children?.toString().replace(/\s+/g, "-").toLowerCase()}`}
/>
{children}
</label>
),
}))
// Mock @shadcn/ui components
vi.mock("@/components/ui", () => ({
Select: ({ children, value, onValueChange }: any) => (
<div className="select-mock">
<select value={value} onChange={(e) => onValueChange && onValueChange(e.target.value)}>
{children}
</select>
</div>
),
SelectTrigger: ({ children }: any) => <div className="select-trigger-mock">{children}</div>,
SelectValue: ({ children }: any) => <div className="select-value-mock">{children}</div>,
SelectContent: ({ children }: any) => <div className="select-content-mock">{children}</div>,
SelectItem: ({ children, value }: any) => (
<option value={value} className="select-item-mock">
{children}
</option>
),
SelectSeparator: ({ children }: any) => <div className="select-separator-mock">{children}</div>,
Button: ({ children, onClick, _variant, role, className }: any) => (
<button onClick={onClick} className={`button-mock ${className || ""}`} role={role}>
{children}
</button>
),
StandardTooltip: ({ children, content }: any) => <div title={content}>{children}</div>,
// Add missing components used by ModelPicker
Command: ({ children }: any) => <div className="command-mock">{children}</div>,
CommandEmpty: ({ children }: any) => <div className="command-empty-mock">{children}</div>,
CommandGroup: ({ children }: any) => <div className="command-group-mock">{children}</div>,
CommandInput: ({ value, onValueChange, placeholder, className, _ref }: any) => (
<input
value={value}
onChange={(e) => onValueChange && onValueChange(e.target.value)}
placeholder={placeholder}
className={className}
/>
),
CommandItem: ({ children, value, onSelect }: any) => (
<div className="command-item-mock" onClick={() => onSelect && onSelect(value)}>
{children}
</div>
),
CommandList: ({ children }: any) => <div className="command-list-mock">{children}</div>,
Popover: ({ children, _open, _onOpenChange }: any) => <div className="popover-mock">{children}</div>,
PopoverContent: ({ children, _className }: any) => <div className="popover-content-mock">{children}</div>,
PopoverTrigger: ({ children, _asChild }: any) => <div className="popover-trigger-mock">{children}</div>,
Slider: ({ value, onChange }: any) => (
<div data-testid="slider">
<input type="range" value={value || 0} onChange={(e) => onChange(parseFloat(e.target.value))} />
</div>
),
SearchableSelect: ({ value, onValueChange, options, placeholder, "data-testid": dataTestId }: any) => (
<div className="searchable-select-mock" data-testid={dataTestId || "provider-popover-trigger"}>
<select value={value} onChange={(e) => onValueChange && onValueChange(e.target.value)}>
<option value="">{placeholder || "Select..."}</option>
{options?.map((option: any) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
</div>
),
// Add Collapsible components
Collapsible: ({ children, open }: any) => (
<div className="collapsible-mock" data-open={open}>
{children}
</div>
),
CollapsibleTrigger: ({ children, className, onClick }: any) => (
<div className={`collapsible-trigger-mock ${className || ""}`} onClick={onClick}>
{children}
</div>
),
CollapsibleContent: ({ children, className }: any) => (
<div className={`collapsible-content-mock ${className || ""}`}>{children}</div>
),
}))
vi.mock("../TemperatureControl", () => ({
TemperatureControl: ({ value, onChange }: any) => (
<div data-testid="temperature-control">
<input
type="range"
value={value || 0}
onChange={(e) => onChange(parseFloat(e.target.value))}
min={0}
max={2}
step={0.1}
/>
</div>
),
}))
vi.mock("../RateLimitSecondsControl", () => ({
RateLimitSecondsControl: ({ value, onChange }: any) => (
<div data-testid="rate-limit-seconds-control">
<input
type="range"
value={value || 0}
onChange={(e) => onChange(parseFloat(e.target.value))}
min={0}
max={60}
step={1}
/>
</div>
),
}))
// Mock TodoListSettingsControl for tests
vi.mock("../TodoListSettingsControl", () => ({
TodoListSettingsControl: ({ todoListEnabled, onChange }: any) => (
<div data-testid="todo-list-settings-control">
<label>
Enable todo list tool
<input
type="checkbox"
checked={todoListEnabled}
onChange={(e) => onChange("todoListEnabled", e.target.checked)}
/>
</label>
</div>
),
}))
// Mock ThinkingBudget component
vi.mock("../ThinkingBudget", () => ({
ThinkingBudget: ({ modelInfo, apiConfiguration, setApiConfigurationField }: any) => {
// Only render if model supports reasoning budget (thinking models)
if (modelInfo?.supportsReasoningBudget || modelInfo?.requiredReasoningBudget) {
return (
<div data-testid="reasoning-budget">
<div>Max Thinking Tokens</div>
<input type="range" min={1024} max={100000} step={1024} />
</div>
)
}
if (modelInfo?.supportsReasoningEffort) {
return (
<div data-testid="reasoning-effort">
<select
value={apiConfiguration?.reasoningEffort || ""}
onChange={(e) => setApiConfigurationField("reasoningEffort", e.target.value)}>
<option value="">Select...</option>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</select>
</div>
)
}
return null
},
}))
// Mock LiteLLM provider for tests
vi.mock("../providers/LiteLLM", () => ({
LiteLLM: ({ apiConfiguration, setApiConfigurationField }: any) => (
<div data-testid="litellm-provider">
<input
data-testid="litellm-base-url"
type="text"
value={apiConfiguration.litellmBaseUrl || ""}
onChange={(e) => setApiConfigurationField("litellmBaseUrl", e.target.value)}
placeholder="Base URL"
/>
<input
data-testid="litellm-api-key"
type="password"
value={apiConfiguration.litellmApiKey || ""}
onChange={(e) => setApiConfigurationField("litellmApiKey", e.target.value)}
placeholder="API Key"
/>
<button data-testid="litellm-refresh-models">Refresh Models</button>
</div>
),
}))
vi.mock("@src/components/ui/hooks/useSelectedModel", () => ({
useSelectedModel: vi.fn((apiConfiguration: ProviderSettings) => {
if (apiConfiguration.apiModelId?.includes("thinking")) {
const info: ModelInfo = {
contextWindow: 4000,
maxTokens: 128000,
supportsPromptCache: true,
requiredReasoningBudget: true,
supportsReasoningBudget: true,
}
return {
provider: apiConfiguration.apiProvider,
info,
}
} else {
const info: ModelInfo = { contextWindow: 4000, supportsPromptCache: true }
return {
provider: apiConfiguration.apiProvider,
info,
}
}
}),
}))
const renderApiOptions = (props: Partial<ApiOptionsProps> = {}) => {
const queryClient = new QueryClient()
render(
<ExtensionStateContextProvider>
<QueryClientProvider client={queryClient}>
<ApiOptions
errorMessage={undefined}
setErrorMessage={() => {}}
uriScheme={undefined}
apiConfiguration={{}}
setApiConfigurationField={() => {}}
{...props}
/>
</QueryClientProvider>
</ExtensionStateContextProvider>,
)
}
describe("ApiOptions", () => {
it("resets model to provider default when switching to openai-codex with an invalid prior apiModelId", () => {
const mockSetApiConfigurationField = vi.fn()
renderApiOptions({
apiConfiguration: {
apiProvider: "anthropic",
// Simulate a previously-selected model ID from another provider.
// When switching to OpenAI - ChatGPT Plus/Pro, this is invalid and should be reset.
apiModelId: "claude-3-5-sonnet-20241022",
},
setApiConfigurationField: mockSetApiConfigurationField,
})
const providerSelectContainer = screen.getByTestId("provider-select")
const providerSelect = providerSelectContainer.querySelector("select") as HTMLSelectElement
expect(providerSelect).toBeInTheDocument()
fireEvent.change(providerSelect, { target: { value: "openai-codex" } })
// Provider is updated
expect(mockSetApiConfigurationField).toHaveBeenCalledWith("apiProvider", "openai-codex")
// Model is reset to the provider default since the previous value is invalid for this provider
expect(mockSetApiConfigurationField).toHaveBeenCalledWith("apiModelId", openAiCodexDefaultModelId, false)
})
it("initializes zooGatewayModelId to its default when switching provider to zoo-gateway", () => {
// Regression: zoo-gateway was previously missing from PROVIDER_MODEL_CONFIG, so switching
// providers never seeded zooGatewayModelId. Configs were left without a model id, which
// blocked completion flows that require a dynamic-provider model id.
const mockSetApiConfigurationField = vi.fn()
renderApiOptions({
apiConfiguration: {
apiProvider: "anthropic",
// No prior zooGatewayModelId.
},
setApiConfigurationField: mockSetApiConfigurationField,
})
const providerSelectContainer = screen.getByTestId("provider-select")
const providerSelect = providerSelectContainer.querySelector("select") as HTMLSelectElement
fireEvent.change(providerSelect, { target: { value: "zoo-gateway" } })
expect(mockSetApiConfigurationField).toHaveBeenCalledWith("apiProvider", "zoo-gateway")
expect(mockSetApiConfigurationField).toHaveBeenCalledWith("zooGatewayModelId", zooGatewayDefaultModelId, false)
})
it("shows temperature and rate limit controls by default", () => {
renderApiOptions({
apiConfiguration: {},
})
expect(screen.getByTestId("temperature-control")).toBeInTheDocument()
expect(screen.getByTestId("rate-limit-seconds-control")).toBeInTheDocument()
})
it("hides all controls when fromWelcomeView is true", () => {
renderApiOptions({ fromWelcomeView: true })
expect(screen.queryByTestId("temperature-control")).not.toBeInTheDocument()
expect(screen.queryByTestId("rate-limit-seconds-control")).not.toBeInTheDocument()
})
describe("thinking functionality", () => {
it("should show ThinkingBudget for Anthropic models that support thinking", () => {
renderApiOptions({
apiConfiguration: {
apiProvider: "anthropic",
apiModelId: "claude-3-7-sonnet-20250219:thinking",
},
})
expect(screen.getByTestId("reasoning-budget")).toBeInTheDocument()
})
it("should show ThinkingBudget for Vertex models that support thinking", () => {
renderApiOptions({
apiConfiguration: {
apiProvider: "vertex",
apiModelId: "claude-3-7-sonnet@20250219:thinking",
},
})
expect(screen.getByTestId("reasoning-budget")).toBeInTheDocument()
})
it("should not show ThinkingBudget for models that don't support thinking", () => {
renderApiOptions({
apiConfiguration: {
apiProvider: "anthropic",
apiModelId: "claude-3-opus-20240229",
},
})
expect(screen.queryByTestId("reasoning-budget")).not.toBeInTheDocument()
})
// Note: We don't need to test the actual ThinkingBudget component functionality here
// since we have separate tests for that component. We just need to verify that
// it's included in the ApiOptions component when appropriate.
})
it("filters providers by search input and shows no match message when appropriate", () => {
renderApiOptions({
apiConfiguration: {},
setApiConfigurationField: () => {},
})
// The SearchableSelect mock renders inside a div with the test id
const providerSelectContainer = screen.getByTestId("provider-select")
expect(providerSelectContainer).toBeInTheDocument()
// Get the actual select element inside the container
const providerSelect = providerSelectContainer.querySelector("select") as HTMLSelectElement
expect(providerSelect).toBeInTheDocument()
// Check that we have options
const options = providerSelect.querySelectorAll("option")
expect(options.length).toBeGreaterThan(1) // Should have placeholder + actual options
// Check that OpenAI option exists
const optionTexts = Array.from(options).map((opt) => opt.textContent)
expect(optionTexts).toContain("OpenAI")
expect(optionTexts).toContain("Anthropic")
// Note: The mock doesn't implement search functionality, so we're just verifying
// that the select element is rendered with the expected options
})
describe("OpenAI provider tests", () => {
it("removes reasoningEffort from openAiCustomModelInfo when unchecked", () => {
const mockSetApiConfigurationField = vi.fn()
const initialConfig = {
apiProvider: "openai" as const,
enableReasoningEffort: true,
openAiCustomModelInfo: {
...openAiModelInfoSaneDefaults, // Start with defaults
reasoningEffort: "low" as const, // Set an initial value
},
// Add other necessary default fields for openai provider if needed
}
renderApiOptions({
apiConfiguration: initialConfig,
setApiConfigurationField: mockSetApiConfigurationField,
})
// Find the checkbox by its test ID instead of label text
// This is more reliable than using the label text which might be affected by translations
const checkbox =
screen.getByTestId("checkbox-input-settings:providers.setreasoninglevel") ||
screen.getByTestId("checkbox-input-set-reasoning-level")
// Simulate unchecking the checkbox
fireEvent.click(checkbox)
// 1. Check if enableReasoningEffort was set to false
expect(mockSetApiConfigurationField).toHaveBeenCalledWith("enableReasoningEffort", false)
// 2. Check if openAiCustomModelInfo was updated
const updateCall = mockSetApiConfigurationField.mock.calls.find(
(call) => call[0] === "openAiCustomModelInfo",
)
expect(updateCall).toBeDefined()
// 3. Check if reasoningEffort property is absent in the updated info
const updatedInfo = updateCall![1]
expect(updatedInfo).not.toHaveProperty("reasoningEffort")
// Optional: Check if other properties were preserved (example)
expect(updatedInfo).toHaveProperty("contextWindow", openAiModelInfoSaneDefaults.contextWindow)
})
it("does not render ReasoningEffort component when initially disabled", () => {
const mockSetApiConfigurationField = vi.fn()
const initialConfig = {
apiProvider: "openai" as const,
enableReasoningEffort: false, // Initially disabled
openAiCustomModelInfo: {
...openAiModelInfoSaneDefaults,
},
}
renderApiOptions({
apiConfiguration: initialConfig,
setApiConfigurationField: mockSetApiConfigurationField,
})
// Check that the ReasoningEffort select component is not rendered.
expect(screen.queryByTestId("reasoning-effort")).not.toBeInTheDocument()
})
it("renders ReasoningEffort component and sets flag when checkbox is checked", () => {
const mockSetApiConfigurationField = vi.fn()
const initialConfig = {
apiProvider: "openai" as const,
enableReasoningEffort: false, // Initially disabled
openAiCustomModelInfo: {
...openAiModelInfoSaneDefaults,
},
}
renderApiOptions({
apiConfiguration: initialConfig,
setApiConfigurationField: mockSetApiConfigurationField,
})
const checkbox = screen.getByTestId("checkbox-input-settings:providers.setreasoninglevel")
// Simulate checking the checkbox
fireEvent.click(checkbox)
// 1. Check if enableReasoningEffort was set to true
expect(mockSetApiConfigurationField).toHaveBeenCalledWith("enableReasoningEffort", true)
// We can't directly test the rendering of the ReasoningEffort component after the state change
// without a more complex setup involving state management mocks or re-rendering.
// However, we've tested the state update call.
})
it("updates reasoningEffort in openAiCustomModelInfo when select value changes", () => {
const mockSetApiConfigurationField = vi.fn()
const initialConfig = {
apiProvider: "openai" as const,
enableReasoningEffort: true, // Initially enabled
openAiCustomModelInfo: {
...openAiModelInfoSaneDefaults,
reasoningEffort: "low" as const,
},
}
renderApiOptions({
apiConfiguration: initialConfig,
setApiConfigurationField: mockSetApiConfigurationField,
})
// Find the reasoning effort select among all comboboxes by its current value
// const allSelects = screen.getAllByRole("combobox") as HTMLSelectElement[]
// const reasoningSelect = allSelects.find(
// (el) => el.value === initialConfig.openAiCustomModelInfo.reasoningEffort,
// )
// expect(reasoningSelect).toBeDefined()
const selectContainer = screen.getByTestId("reasoning-effort")
expect(selectContainer).toBeInTheDocument()
const reasoningSelect = within(selectContainer).getByRole("combobox")
expect(reasoningSelect).toHaveValue("low")
// Simulate changing the reasoning effort to 'high'
fireEvent.change(reasoningSelect, { target: { value: "high" } })
// Check if setApiConfigurationField was called correctly for openAiCustomModelInfo
expect(mockSetApiConfigurationField).toHaveBeenCalledWith(
"openAiCustomModelInfo",
expect.objectContaining({ reasoningEffort: "high" }),
)
// Check that other properties were preserved
expect(mockSetApiConfigurationField).toHaveBeenCalledWith(
"openAiCustomModelInfo",
expect.objectContaining({
contextWindow: openAiModelInfoSaneDefaults.contextWindow,
}),
)
})
})
describe("LiteLLM provider tests", () => {
it("renders LiteLLM component when provider is selected", () => {
renderApiOptions({
apiConfiguration: {
apiProvider: "litellm",
litellmBaseUrl: "http://localhost:4000",
litellmApiKey: "test-key",
},
})
expect(screen.getByTestId("litellm-provider")).toBeInTheDocument()
expect(screen.getByTestId("litellm-base-url")).toHaveValue("http://localhost:4000")
expect(screen.getByTestId("litellm-api-key")).toHaveValue("test-key")
})
it("calls setApiConfigurationField when LiteLLM inputs change", () => {
const mockSetApiConfigurationField = vi.fn()
renderApiOptions({
apiConfiguration: {
apiProvider: "litellm",
},
setApiConfigurationField: mockSetApiConfigurationField,
})
const baseUrlInput = screen.getByTestId("litellm-base-url")
const apiKeyInput = screen.getByTestId("litellm-api-key")
fireEvent.change(baseUrlInput, { target: { value: "http://new-url:8000" } })
fireEvent.change(apiKeyInput, { target: { value: "new-api-key" } })
expect(mockSetApiConfigurationField).toHaveBeenCalledWith("litellmBaseUrl", "http://new-url:8000")
expect(mockSetApiConfigurationField).toHaveBeenCalledWith("litellmApiKey", "new-api-key")
})
it("shows refresh models button for LiteLLM", () => {
renderApiOptions({
apiConfiguration: {
apiProvider: "litellm",
litellmBaseUrl: "http://localhost:4000",
litellmApiKey: "test-key",
},
})
expect(screen.getByTestId("litellm-refresh-models")).toBeInTheDocument()
})
it("does not render LiteLLM component when other provider is selected", () => {
renderApiOptions({
apiConfiguration: {
apiProvider: "anthropic",
},
})
expect(screen.queryByTestId("litellm-provider")).not.toBeInTheDocument()
})
})
it("renders retired provider message and hides provider-specific forms", () => {
renderApiOptions({
apiConfiguration: {
apiProvider: "groq",
},
})
expect(screen.getByTestId("retired-provider-message")).toHaveTextContent(
"settings:providers.retiredProviderMessage",
)
expect(screen.queryByTestId("litellm-provider")).not.toBeInTheDocument()
})
it("does not reintroduce retired providers into active provider options", () => {
renderApiOptions({
apiConfiguration: {
apiProvider: "groq",
},
})
const providerSelectContainer = screen.getByTestId("provider-select")
const providerSelect = providerSelectContainer.querySelector("select") as HTMLSelectElement
const providerOptions = Array.from(providerSelect.querySelectorAll("option")).map((option) => option.value)
expect(providerOptions).not.toContain("groq")
})
})