Elffuss BraidHub

kikocis/continue public

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