Elffuss BraidHub

kikocis/continue public

6d66081d22d3 · 8.4 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}
41
42function modelSelectTitle(model: any): string {
43 if (model?.title) return model?.title;
44 if (model?.model !== undefined && model?.model.trim() !== "") {
45 if (model?.class_name) {
46 return `${model?.class_name} - ${model?.model}`;
47 }
48 return model?.model;
49 }
50 return model?.class_name;
51}
52
53function ModelOption({
54 option,
55 idx,
56 showMissingApiKeyMsg,
57 isSelected,
58}: ModelOptionProps) {
59 const ideMessenger = useContext(IdeMessengerContext);
60
61 function handleOptionClick(e: any) {
62 if (showMissingApiKeyMsg) {
63 e.preventDefault();
64 e.stopPropagation();
65 }
66 }
67
68 return (
69 <ListboxOption
70 key={idx}
71 disabled={showMissingApiKeyMsg}
72 value={option.value}
73 onClick={handleOptionClick}
74 >
75 <div className="flex w-full items-center justify-between">
76 <div className="flex items-center gap-2">
77 <CubeIcon className="h-3 w-3 flex-shrink-0" />
78 <span className="line-clamp-1">
79 {option.title}
80 {showMissingApiKeyMsg && (
81 <span className="ml-2 text-[10px] italic">(Missing API key)</span>
82 )}
83 </span>
84 </div>
85 <CheckIcon
86 className={`h-3 w-3 flex-shrink-0 ${isSelected ? "" : "invisible"}`}
87 />
88 </div>
89 </ListboxOption>
90 );
91}
92
93function ModelSelect() {
94 const dispatch = useAppDispatch();
95
96 const isInEdit = useAppSelector((store) => store.session.isInEdit);
97 const config = useAppSelector((state) => state.config.config);
98 const ideMessenger = useContext(IdeMessengerContext);
99 const buttonRef = useRef<HTMLButtonElement>(null);
100 const [options, setOptions] = useState<Option[]>([]);
101 const [sortedOptions, setSortedOptions] = useState<Option[]>([]);
102 const { selectedProfile } = useAuth();
103
104 let selectedModel = null;
105 let allModels = null;
106 if (isInEdit) {
107 allModels = config.modelsByRole.edit;
108 selectedModel = config.selectedModelByRole.edit;
109 }
110 if (!selectedModel) {
111 selectedModel = config.selectedModelByRole.chat;
112 }
113 if (!allModels || allModels.length === 0) {
114 allModels = config.modelsByRole.chat;
115 }
116
117 // Sort so that options without an API key are at the end
118 useEffect(() => {
119 const alphaSort = options.sort((a, b) => a.title.localeCompare(b.title));
120 const enabledOptions = alphaSort.filter((option) => option.apiKey !== "");
121 const disabledOptions = alphaSort.filter((option) => option.apiKey === "");
122
123 const sorted = [...enabledOptions, ...disabledOptions];
124
125 setSortedOptions(sorted);
126 }, [options]);
127
128 useEffect(() => {
129 setOptions(
130 allModels.map((model) => {
131 return {
132 value: model.title,
133 title: modelSelectTitle(model),
134 apiKey: model.apiKey,
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="h-2 w-2 flex-shrink-0 hover:brightness-110"
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 })
234 }
235 />
236 </div>
237
238 <div className="no-scrollbar max-h-[300px] overflow-y-auto">
239 {isConfigLoading ? (
240 <div className="text-description flex items-center gap-2 px-2 pb-2 pt-1 text-xs">
241 <ArrowPathIcon className="animate-spin-slow h-3 w-3" />
242 <span>Loading config</span>
243 </div>
244 ) : hasNoModels ? (
245 <div className="text-description-muted px-2 py-4 text-center text-sm">
246 No models configured
247 </div>
248 ) : (
249 sortedOptions.map((option, idx) => (
250 <ModelOption
251 option={option}
252 idx={idx}
253 key={idx}
254 showMissingApiKeyMsg={option.apiKey === ""}
255 isSelected={option.value === selectedModel?.title}
256 />
257 ))
258 )}
259 </div>
260
261 {!isConfigLoading && selectedProfile?.profileType === "local" && (
262 <ListboxOption
263 key={options.length}
264 onClick={onClickAddModel}
265 value={"addModel" as any}
266 className="border-border border-x-0 border-y border-solid"
267 >
268 <div
269 className="text-description flex items-center py-0.5 hover:text-inherit"
270 style={{
271 fontSize: fontSize(-3),
272 }}
273 >
274 <PlusIcon className="mr-2 h-3 w-3" />
275 Add Chat model
276 </div>
277 </ListboxOption>
278 )}
279
280 {!isConfigLoading && (
281 <div
282 className="text-description-muted px-2 py-1"
283 style={{ fontSize: fontSize(-3) }}
284 >
285 <code>{getMetaKeyLabel()}'</code> to toggle model
286 </div>
287 )}
288 </ListboxOptions>
289 </div>
290 </Listbox>
291 );
292}
293
294export default ModelSelect;