Elffuss BraidHub

kikocis/continue public

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