Elffuss BraidHub

kikocis/continue public

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