Elffuss BraidHub

kikocis/continue public

93a8eb04e36c · 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 { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
15import { updateSelectedModelByRole } from "../../redux/thunks/updateSelectedModelByRole";
16import {
17 fontSize,
18 getMetaKeyLabel,
19 isMetaEquivalentKeyPressed,
20} from "../../util";
21import {
22 Listbox,
23 ListboxButton,
24 ListboxOption,
25 ListboxOptions,
26} from "../ui/Listbox";
27
28interface ModelOptionProps {
29 option: Option;
30 idx: number;
31 showMissingApiKeyMsg: boolean;
32 isSelected?: boolean;
33}
34
35interface Option {
36 value: string;
37 title: string;
38 apiKey?: string;
39 sourceFile?: 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 function handleOptionClick(e: any) {
60 if (showMissingApiKeyMsg) {
61 e.preventDefault();
62 e.stopPropagation();
63 }
64 }
65
66 return (
67 <ListboxOption
68 key={idx}
69 disabled={showMissingApiKeyMsg}
70 value={option.value}
71 onClick={handleOptionClick}
72 >
73 <div className="flex w-full items-center justify-between">
74 <div className="flex items-center gap-2">
75 <CubeIcon className="h-3 w-3 flex-shrink-0" />
76 <span className="line-clamp-1">
77 {option.title}
78 {showMissingApiKeyMsg && (
79 <span className="ml-2 text-[10px] italic">(Missing API key)</span>
80 )}
81 </span>
82 </div>
83 <CheckIcon
84 className={`h-3 w-3 flex-shrink-0 ${isSelected ? "" : "invisible"}`}
85 />
86 </div>
87 </ListboxOption>
88 );
89}
90
91function ModelSelect() {
92 const dispatch = useAppDispatch();
93
94 const isInEdit = useAppSelector((store) => store.session.isInEdit);
95 const config = useAppSelector((state) => state.config.config);
96 const isConfigLoading = useAppSelector((state) => state.config.loading);
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 }, [allModels]);
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 hasNoModels = allModels?.length === 0;
196
197 return (
198 <Listbox
199 onChange={async (val: string) => {
200 if (val === selectedModel?.title) return;
201 void dispatch(
202 updateSelectedModelByRole({
203 selectedProfile,
204 role: isInEdit ? "edit" : "chat",
205 modelTitle: val,
206 }),
207 );
208 }}
209 >
210 <div className="relative flex">
211 <ListboxButton
212 data-testid="model-select-button"
213 ref={buttonRef}
214 className="text-description h-[18px] gap-1 border-none"
215 >
216 <span className="line-clamp-1 break-all hover:brightness-110">
217 {modelSelectTitle(selectedModel) || "Select model"}
218 </span>
219 <ChevronDownIcon
220 className="hidden h-2 w-2 flex-shrink-0 hover:brightness-110 min-[200px]:flex"
221 aria-hidden="true"
222 />
223 </ListboxButton>
224 <ListboxOptions className="min-w-[160px]">
225 <div className="flex items-center justify-between gap-1 px-2 py-1">
226 <span className="font-semibold">Models</span>
227 <Cog6ToothIcon
228 className="text-description h-3 w-3 cursor-pointer hover:brightness-125"
229 onClick={() =>
230 ideMessenger.post("config/openProfile", {
231 profileId: undefined,
232 element: { sourceFile: selectedModel?.sourceFile },
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;