-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathModelPicker.tsx
More file actions
325 lines (295 loc) · 10.1 KB
/
Copy pathModelPicker.tsx
File metadata and controls
325 lines (295 loc) · 10.1 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
import { useMemo, useState, useCallback, useEffect, useRef } from "react"
import { VSCodeLink } from "@vscode/webview-ui-toolkit/react"
import { Trans } from "react-i18next"
import { ChevronsUpDown, Check, X, Info } from "lucide-react"
import { type ProviderSettings, type ModelInfo, type OrganizationAllowList, isRetiredProvider } from "@roo-code/types"
import { useAppTranslation } from "@src/i18n/TranslationContext"
import { useSelectedModel } from "@/components/ui/hooks/useSelectedModel"
import { filterModels } from "./utils/organizationFilters"
import { cn } from "@src/lib/utils"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
Popover,
PopoverContent,
PopoverTrigger,
Button,
} from "@src/components/ui"
import { useEscapeKey } from "@src/hooks/useEscapeKey"
import { ModelInfoView } from "./ModelInfoView"
import { ApiErrorMessage } from "./ApiErrorMessage"
type ModelIdKey = keyof Pick<
ProviderSettings,
| "openRouterModelId"
| "requestyModelId"
| "unboundModelId"
| "openAiModelId"
| "litellmModelId"
| "vercelAiGatewayModelId"
| "opencodeGoModelId"
| "zooGatewayModelId"
| "apiModelId"
| "ollamaModelId"
| "lmStudioModelId"
| "lmStudioDraftModelId"
| "vsCodeLmModelSelector"
>
interface ModelPickerProps {
defaultModelId: string
models: Record<string, ModelInfo> | null
modelIdKey: ModelIdKey
serviceName: string
serviceUrl: string
apiConfiguration: ProviderSettings
setApiConfigurationField: <K extends keyof ProviderSettings>(
field: K,
value: ProviderSettings[K],
isUserAction?: boolean,
) => void
organizationAllowList?: OrganizationAllowList
errorMessage?: string
simplifySettings?: boolean
hidePricing?: boolean
/** Label for the model picker field - defaults to "Model" */
label?: string
/** Transform model ID string to the value stored in configuration (for compound types like VSCodeLM selector) */
valueTransform?: (modelId: string) => unknown
/** Transform stored configuration value back to display string */
displayTransform?: (value: unknown) => string
/** Callback when model changes - useful for side effects like clearing related fields */
onModelChange?: (modelId: string) => void
}
export const ModelPicker = ({
defaultModelId,
models,
modelIdKey,
serviceName,
serviceUrl,
apiConfiguration,
setApiConfigurationField,
organizationAllowList,
errorMessage,
simplifySettings,
hidePricing,
label,
valueTransform,
displayTransform,
onModelChange,
}: ModelPickerProps) => {
const { t } = useAppTranslation()
const [open, setOpen] = useState(false)
const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false)
const isInitialized = useRef(false)
const searchInputRef = useRef<HTMLInputElement>(null)
const selectTimeoutRef = useRef<NodeJS.Timeout | null>(null)
const closeTimeoutRef = useRef<NodeJS.Timeout | null>(null)
const { id: selectedModelId, info: selectedModelInfo } = useSelectedModel(apiConfiguration)
// Get the display value for the current selection
// If displayTransform is provided, use it to convert the stored value to a display string
const displayValue = useMemo(() => {
if (displayTransform) {
const storedValue = apiConfiguration[modelIdKey]
return storedValue ? displayTransform(storedValue) : undefined
}
return selectedModelId
}, [displayTransform, apiConfiguration, modelIdKey, selectedModelId])
const activeProvider =
apiConfiguration.apiProvider && isRetiredProvider(apiConfiguration.apiProvider)
? undefined
: apiConfiguration.apiProvider
const modelIds = useMemo(() => {
const filteredModels = filterModels(models, activeProvider, organizationAllowList)
// Include the currently selected model even if deprecated (so users can see what they have selected)
// But filter out other deprecated models from being newly selectable
const availableModels = Object.entries(filteredModels ?? {})
.filter(([modelId, modelInfo]) => {
// Always include the currently selected model
if (modelId === selectedModelId) return true
// Filter out deprecated models that aren't currently selected
return !modelInfo.deprecated
})
.reduce(
(acc, [modelId, modelInfo]) => {
acc[modelId] = modelInfo
return acc
},
{} as Record<string, ModelInfo>,
)
return Object.keys(availableModels).sort((a, b) => a.localeCompare(b))
}, [models, activeProvider, organizationAllowList, selectedModelId])
const [searchValue, setSearchValue] = useState("")
const onSelect = useCallback(
(modelId: string) => {
if (!modelId) {
return
}
setOpen(false)
// Apply value transform if provided (e.g., for VSCodeLM selector)
const valueToStore = valueTransform ? valueTransform(modelId) : modelId
setApiConfigurationField(modelIdKey, valueToStore as ProviderSettings[ModelIdKey])
// Call the optional change callback
onModelChange?.(modelId)
// Clear any existing timeout
if (selectTimeoutRef.current) {
clearTimeout(selectTimeoutRef.current)
}
// Delay to ensure the popover is closed before setting the search value.
selectTimeoutRef.current = setTimeout(() => setSearchValue(""), 100)
},
[modelIdKey, setApiConfigurationField, valueTransform, onModelChange],
)
const onOpenChange = useCallback((open: boolean) => {
setOpen(open)
// Abandon the current search if the popover is closed.
if (!open) {
// Clear any existing timeout
if (closeTimeoutRef.current) {
clearTimeout(closeTimeoutRef.current)
}
// Clear the search value when closing instead of prefilling it
closeTimeoutRef.current = setTimeout(() => setSearchValue(""), 100)
}
}, [])
const onClearSearch = useCallback(() => {
setSearchValue("")
searchInputRef.current?.focus()
}, [])
useEffect(() => {
if (!selectedModelId && !isInitialized.current) {
const initialValue = modelIds.includes(selectedModelId) ? selectedModelId : defaultModelId
setApiConfigurationField(modelIdKey, initialValue, false) // false = automatic initialization
}
isInitialized.current = true
}, [modelIds, setApiConfigurationField, modelIdKey, selectedModelId, defaultModelId])
// Cleanup timeouts on unmount to prevent test flakiness
useEffect(() => {
return () => {
if (selectTimeoutRef.current) {
clearTimeout(selectTimeoutRef.current)
}
if (closeTimeoutRef.current) {
clearTimeout(closeTimeoutRef.current)
}
}
}, [])
// Use the shared ESC key handler hook
useEscapeKey(open, () => setOpen(false))
return (
<>
<div>
<label className="block font-medium mb-1">{label ?? t("settings:modelPicker.label")}</label>
<Popover open={open} onOpenChange={onOpenChange}>
<PopoverTrigger asChild>
<Button
variant="combobox"
role="combobox"
aria-expanded={open}
className="w-full justify-between"
data-testid="model-picker-button">
<div className="truncate">{displayValue ?? t("settings:common.select")}</div>
<ChevronsUpDown className="opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0 w-[var(--radix-popover-trigger-width)]">
<Command>
<div className="relative">
<CommandInput
ref={searchInputRef}
value={searchValue}
onValueChange={setSearchValue}
placeholder={t("settings:modelPicker.searchPlaceholder")}
className="h-9 mr-4"
data-testid="model-input"
/>
{searchValue.length > 0 && (
<div className="absolute right-2 top-0 bottom-0 flex items-center justify-center">
<X
className="text-vscode-input-foreground opacity-50 hover:opacity-100 size-4 p-0.5 cursor-pointer"
onClick={onClearSearch}
/>
</div>
)}
</div>
<CommandList>
<CommandEmpty>
{searchValue && (
<div className="py-2 px-1 text-sm">
{t("settings:modelPicker.noMatchFound")}
</div>
)}
</CommandEmpty>
<CommandGroup>
{modelIds.map((model) => (
<CommandItem
key={model}
value={model}
onSelect={onSelect}
data-testid={`model-option-${model}`}>
<span className="truncate" title={model}>
{model}
</span>
<Check
className={cn(
"size-4 p-0.5 ml-auto",
model === displayValue ? "opacity-100" : "opacity-0",
)}
/>
</CommandItem>
))}
</CommandGroup>
</CommandList>
{searchValue && !modelIds.includes(searchValue) && (
<div className="p-1 border-t border-vscode-input-border">
<CommandItem data-testid="use-custom-model" value={searchValue} onSelect={onSelect}>
{t("settings:modelPicker.useCustomModel", { modelId: searchValue })}
</CommandItem>
</div>
)}
</Command>
</PopoverContent>
</Popover>
</div>
{errorMessage && <ApiErrorMessage errorMessage={errorMessage} />}
{selectedModelInfo?.deprecated && (
<ApiErrorMessage errorMessage={t("settings:validation.modelDeprecated")} />
)}
{simplifySettings ? (
<p className="text-xs text-vscode-descriptionForeground m-0">
<Info className="size-3 inline mr-1" />
{t("settings:modelPicker.simplifiedExplanation")}
</p>
) : (
<div>
{selectedModelId && selectedModelInfo && !selectedModelInfo.deprecated && (
<ModelInfoView
apiProvider={apiConfiguration.apiProvider}
selectedModelId={selectedModelId}
modelInfo={selectedModelInfo}
isDescriptionExpanded={isDescriptionExpanded}
setIsDescriptionExpanded={setIsDescriptionExpanded}
hidePricing={hidePricing}
/>
)}
{!hidePricing && apiConfiguration.apiProvider !== "mimo" && (
<div className="text-sm text-vscode-descriptionForeground" data-testid="automatic-fetch-hint">
<Trans
i18nKey="settings:modelPicker.automaticFetch"
components={{
serviceLink: <VSCodeLink href={serviceUrl} className="text-sm" />,
defaultModelLink: (
<VSCodeLink onClick={() => onSelect(defaultModelId)} className="text-sm" />
),
}}
values={{ serviceName, defaultModelId }}
/>
</div>
)}
</div>
)}
</>
)
}