| 1 | import React, { useEffect, useState } from "react"; |
| 2 | |
| 3 | import { services } from "../services/index.js"; |
| 4 | |
| 5 | import { Selector, SelectorOption } from "./Selector.js"; |
| 6 | |
| 7 | interface ModelOption extends SelectorOption { |
| 8 | index: number; |
| 9 | provider: string; |
| 10 | } |
| 11 | |
| 12 | interface ModelSelectorProps { |
| 13 | onSelect: (model: ModelOption) => void; |
| 14 | onCancel: () => void; |
| 15 | } |
| 16 | |
| 17 | const ModelSelector: React.FC<ModelSelectorProps> = ({ |
| 18 | onSelect, |
| 19 | onCancel, |
| 20 | }) => { |
| 21 | const [models, setModels] = useState<ModelOption[]>([]); |
| 22 | const [selectedIndex, setSelectedIndex] = useState(0); |
| 23 | const [loading, setLoading] = useState(true); |
| 24 | const [error, setError] = useState<string | null>(null); |
| 25 | const [currentModelIndex, setCurrentModelIndex] = useState<number>(-1); |
| 26 | |
| 27 | useEffect(() => { |
| 28 | const loadModels = async () => { |
| 29 | try { |
| 30 | const availableModels = services.model.getAvailableChatModels(); |
| 31 | const currentIndex = services.model.getCurrentModelIndex(); |
| 32 | |
| 33 | if (availableModels.length === 0) { |
| 34 | setError("No chat models available in the configuration"); |
| 35 | setLoading(false); |
| 36 | return; |
| 37 | } |
| 38 | |
| 39 | const modelOptions: ModelOption[] = availableModels.map((model) => ({ |
| 40 | id: `${model.provider}-${model.name}-${model.index}`, |
| 41 | name: model.name, |
| 42 | index: model.index, |
| 43 | provider: model.provider, |
| 44 | })); |
| 45 | |
| 46 | setModels(modelOptions); |
| 47 | setCurrentModelIndex(currentIndex); |
| 48 | setSelectedIndex(Math.max(0, currentIndex)); |
| 49 | setLoading(false); |
| 50 | } catch (err: any) { |
| 51 | setError(err.message || "Failed to load models"); |
| 52 | setLoading(false); |
| 53 | } |
| 54 | }; |
| 55 | |
| 56 | loadModels(); |
| 57 | }, []); |
| 58 | |
| 59 | return ( |
| 60 | <Selector |
| 61 | title="Select Model" |
| 62 | options={models} |
| 63 | selectedIndex={selectedIndex} |
| 64 | loading={loading} |
| 65 | error={error} |
| 66 | loadingMessage="Loading available models..." |
| 67 | currentId={ |
| 68 | currentModelIndex >= 0 && models[currentModelIndex] |
| 69 | ? models[currentModelIndex].id |
| 70 | : null |
| 71 | } |
| 72 | onSelect={onSelect} |
| 73 | onCancel={onCancel} |
| 74 | onNavigate={setSelectedIndex} |
| 75 | /> |
| 76 | ); |
| 77 | }; |
| 78 | |
| 79 | export { ModelSelector }; |