Elffuss BraidHub

kikocis/continue public

890519d0e11e · 10.0 KiBRawPermalink
1import {
2 ArrowPathIcon,
3 ChevronDownIcon,
4 Cog6ToothIcon,
5 CubeIcon,
6 PlusIcon,
7} from "@heroicons/react/24/outline";
8import { useContext, useEffect, useRef, useState } from "react";
9import { useNavigate } from "react-router-dom";
10import { useAuth } from "../../context/Auth";
11import { IdeMessengerContext } from "../../context/IdeMessenger";
12import { AddModelForm } from "../../forms/AddModelForm";
13import { useAppDispatch, useAppSelector } from "../../redux/hooks";
14import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
15import { updateSelectedModelByRole } from "../../redux/thunks/updateSelectedModelByRole";
16import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
17import { CONFIG_ROUTES } from "../../util/navigation";
18import { ToolTip } from "../gui/Tooltip";
19import {
20 Button,
21 Listbox,
22 ListboxButton,
23 ListboxOption,
24 ListboxOptions,
25 useFontSize,
26} from "../ui";
27import { Divider } from "../ui/Divider";
28
29interface ModelOptionProps {
30 option: Option;
31 idx: number;
32 showMissingApiKeyMsg: boolean;
33 isSelected?: boolean;
34}
35
36interface Option {
37 value: string;
38 title: string;
39 apiKey?: string;
40 sourceFile?: string;
41 isAutoDetected?: boolean;
42}
43
44function modelSelectTitle(model: any): string {
45 if (model?.title) return model?.title;
46 if (model?.model !== undefined && model?.model.trim() !== "") {
47 if (model?.class_name) {
48 return `${model?.class_name} - ${model?.model}`;
49 }
50 return model?.model;
51 }
52 return model?.class_name;
53}
54
55function ModelOption({
56 option,
57 idx,
58 showMissingApiKeyMsg,
59 isSelected,
60}: ModelOptionProps) {
61 const navigate = useNavigate();
62
63 function handleOptionClick(e: any) {
64 if (showMissingApiKeyMsg) {
65 e.preventDefault();
66 e.stopPropagation();
67 }
68 }
69
70 function handleConfigureClick(e: React.MouseEvent) {
71 e.stopPropagation();
72 navigate(CONFIG_ROUTES.MODELS);
73 }
74
75 return (
76 <ListboxOption
77 key={idx}
78 disabled={showMissingApiKeyMsg}
79 value={option.value}
80 onClick={handleOptionClick}
81 className={`group ${isSelected ? "bg-list-active text-list-active-foreground" : ""}`}
82 >
83 <div className="flex w-full items-center justify-between gap-5">
84 <div className="flex items-center gap-2 py-0.5">
85 <CubeIcon className="h-3 w-3 flex-shrink-0" />
86 <span className="line-clamp-1">
87 {option.title}
88 {option.isAutoDetected && (
89 <span className="text-description-muted ml-1.5 text-[10px] italic">
90 (autodetected)
91 </span>
92 )}
93 {showMissingApiKeyMsg && (
94 <span className="ml-1.5 text-[10px] italic">
95 (Missing API key)
96 </span>
97 )}
98 </span>
99 </div>
100 <Button
101 variant="ghost"
102 size="sm"
103 className="text-description-muted hover:enabled:text-foreground my-0 h-4 w-4 p-0 opacity-0 transition-opacity group-hover:opacity-100"
104 onClick={handleConfigureClick}
105 >
106 <Cog6ToothIcon className="h-3.5 w-3.5" />
107 </Button>
108 </div>
109 </ListboxOption>
110 );
111}
112
113function ModelSelect() {
114 const dispatch = useAppDispatch();
115 const navigate = useNavigate();
116
117 const isInEdit = useAppSelector((store) => store.session.isInEdit);
118 const config = useAppSelector((state) => state.config.config);
119 const isConfigLoading = useAppSelector((state) => state.config.loading);
120 const ideMessenger = useContext(IdeMessengerContext);
121 const buttonRef = useRef<HTMLButtonElement>(null);
122 const [options, setOptions] = useState<Option[]>([]);
123 const [sortedOptions, setSortedOptions] = useState<Option[]>([]);
124 const { selectedProfile } = useAuth();
125 const tinyFont = useFontSize(-4);
126
127 let selectedModel = null;
128 let allModels = null;
129 if (isInEdit) {
130 allModels = config.modelsByRole.edit;
131 selectedModel = config.selectedModelByRole.edit;
132 }
133 if (!selectedModel) {
134 selectedModel = config.selectedModelByRole.chat;
135 }
136 if (!allModels || allModels.length === 0) {
137 allModels = config.modelsByRole.chat;
138 }
139
140 // Sort so that options without an API key are at the end
141 useEffect(() => {
142 const alphaSort = options.sort((a, b) => a.title.localeCompare(b.title));
143 const enabledOptions = alphaSort.filter((option) => option.apiKey !== "");
144 const disabledOptions = alphaSort.filter((option) => option.apiKey === "");
145
146 const sorted = [...enabledOptions, ...disabledOptions];
147
148 setSortedOptions(sorted);
149 }, [options]);
150
151 useEffect(() => {
152 setOptions(
153 allModels.map((model) => {
154 return {
155 value: model.title,
156 title: modelSelectTitle(model),
157 apiKey: model.apiKey,
158 sourceFile: model.sourceFile,
159 isAutoDetected: model.isFromAutoDetect,
160 };
161 }),
162 );
163 }, [allModels]);
164
165 useEffect(() => {
166 const handleKeyDown = (event: KeyboardEvent) => {
167 if (
168 event.key === "'" &&
169 isMetaEquivalentKeyPressed(event as any) &&
170 !event.shiftKey // To prevent collisions w/ assistant toggle logic
171 ) {
172 if (!selectedProfile) {
173 return;
174 }
175
176 const direction = event.shiftKey ? -1 : 1;
177 const currentIndex = options.findIndex(
178 (option) => option.value === selectedModel?.title,
179 );
180 let nextIndex = (currentIndex + 1 * direction) % options.length;
181 if (nextIndex < 0) nextIndex = options.length - 1;
182 const newModelTitle = options[nextIndex].value;
183
184 void dispatch(
185 updateSelectedModelByRole({
186 selectedProfile,
187 role: "chat",
188 modelTitle: newModelTitle,
189 }),
190 );
191 }
192 };
193
194 window.addEventListener("keydown", handleKeyDown);
195 return () => {
196 window.removeEventListener("keydown", handleKeyDown);
197 };
198 }, [options, selectedModel]);
199
200 function onClickAddModel(e: MouseEvent) {
201 e.stopPropagation();
202 e.preventDefault();
203
204 // Close the dropdown
205 if (buttonRef.current) {
206 buttonRef.current.click();
207 }
208 dispatch(setShowDialog(true));
209 dispatch(
210 setDialogMessage(
211 <AddModelForm
212 onDone={() => {
213 dispatch(setShowDialog(false));
214 }}
215 />,
216 ),
217 );
218 }
219
220 function onClickConfigureModels(e: React.MouseEvent) {
221 e.stopPropagation();
222 e.preventDefault();
223
224 // Close the dropdown
225 if (buttonRef.current) {
226 buttonRef.current.click();
227 }
228
229 navigate(CONFIG_ROUTES.MODELS);
230 }
231
232 const hasNoModels = allModels?.length === 0;
233
234 return (
235 <Listbox
236 onChange={async (val: string) => {
237 if (val === selectedModel?.title) return;
238 void dispatch(
239 updateSelectedModelByRole({
240 selectedProfile,
241 role: isInEdit ? "edit" : "chat",
242 modelTitle: val,
243 }),
244 );
245 }}
246 >
247 <div className="relative flex">
248 <ListboxButton
249 data-testid="model-select-button"
250 ref={buttonRef}
251 className="text-description h-[18px] gap-1 border-none"
252 >
253 <span className="line-clamp-1 break-all hover:brightness-110">
254 {modelSelectTitle(selectedModel) || "Select model"}
255 </span>
256 <ChevronDownIcon
257 className="hidden h-2 w-2 flex-shrink-0 hover:brightness-110 min-[200px]:flex"
258 aria-hidden="true"
259 />
260 </ListboxButton>
261 <ListboxOptions className="min-w-[160px]">
262 <div className="flex items-center justify-between px-1.5 py-1">
263 <span className="text-description text-xs font-medium">Models</span>
264 <div className="flex items-center gap-0.5">
265 <Button
266 onClick={(e) => {
267 e.stopPropagation();
268 onClickConfigureModels(e);
269 }}
270 variant="ghost"
271 size="sm"
272 className="my-0 h-5 w-5 p-0"
273 >
274 <Cog6ToothIcon className="text-description h-3.5 w-3.5" />
275 </Button>
276 </div>
277 </div>
278
279 <div className="no-scrollbar max-h-[300px] overflow-y-auto">
280 {isConfigLoading ? (
281 <div className="text-description flex items-center gap-2 px-2 pb-2 pt-1 text-xs">
282 <ArrowPathIcon className="animate-spin-slow h-3 w-3" />
283 <span>Loading config</span>
284 </div>
285 ) : hasNoModels ? (
286 <div className="text-description-muted px-2 py-4 text-center text-sm">
287 No models configured
288 </div>
289 ) : (
290 sortedOptions.map((option, idx) => (
291 <ModelOption
292 option={option}
293 idx={idx}
294 key={idx}
295 showMissingApiKeyMsg={option.apiKey === ""}
296 isSelected={option.value === selectedModel?.title}
297 />
298 ))
299 )}
300 </div>
301
302 {!isConfigLoading && (
303 <>
304 {selectedProfile?.profileType === "local" && (
305 <>
306 <Divider className="!mb-0" />
307 <ListboxOption
308 key={options.length}
309 onClick={onClickAddModel}
310 value={"addModel" as any}
311 fontSizeModifier={-2}
312 className="px-2 py-2"
313 >
314 <span className="text-description text-2xs flex flex-row items-center">
315 <PlusIcon className="mr-1.5 h-3.5 w-3.5" />
316 Add Chat model
317 </span>
318 </ListboxOption>
319 </>
320 )}
321
322 <Divider className="!my-0" />
323 <div className="text-description flex items-center justify-start p-2">
324 <span className="block" style={{ fontSize: tinyFont }}>
325 <code>{getMetaKeyLabel()}'</code> to toggle model
326 </span>
327 </div>
328 </>
329 )}
330 </ListboxOptions>
331 </div>
332 </Listbox>
333 );
334}
335
336export default ModelSelect;