diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index b55fc743..94cf1460 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -1740,6 +1740,68 @@ Here is the project's README to help you get started:\n\n${mcpDetails.readmeCont return models } + async getShengSuanModels() { + const parsePrice = (price: any) => { + if (price) { + return parseInt(price) / 10_000 + } + return undefined + } + + let models: Record = {} + try { + const uri = "https://api.shengsuanyun.com" + const xToken = await getGlobalState(this.context, "shengsuanyunToken") + const headers: any = { + "content-type": "application/json", + "x-token": xToken, + } + const res = await axios.get(`${uri}/modelrouter/list?page=1&pageSize=1000`, { headers }) + if (res.data?.data && Array.isArray(res.data?.data.infos)) { + const promises = res.data?.data.infos.map(async (it: any) => { + if (it.currency !== "USD") { + return + } + try { + const resd: any = await axios.get(`${uri}/modelrouter/${it.id}`, { headers }) + if (resd.data.data) { + return resd.data.data + } + } catch (error) { + console.error(`${it.api_name} 请求失败:`, error) + } + }) + const results = await Promise.all(promises) + for (const model of results) { + const modelInfo: ModelInfo = { + maxTokens: model.max_output_tokens || undefined, + contextWindow: model.context, + supportsImages: model.supports_vision || undefined, + supportsComputerUse: model.supports_computer_use || undefined, + supportsPromptCache: model.supports_caching || undefined, + inputPrice: parsePrice(model.input_price), + outputPrice: parsePrice(model.output_price), + cacheWritesPrice: parsePrice(model.caching_price), + cacheReadsPrice: parsePrice(model.cached_price), + description: model.description, + } + models[model.api_name] = modelInfo + } + console.log("ShengSuanYun models fetched", models) + } else { + console.error("Invalid response from ShengSuanYun API") + } + } catch (error) { + console.error("Error fetching ShengSuanYun models:", error) + } + + await this.postMessageToWebview({ + type: "ssyModels", + ssyModels: models, + }) + return models + } + // Context menus and code actions getFileMentionFromPath(filePath: string) { diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index 2f0f2416..95aa2bc6 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -50,6 +50,7 @@ export interface ExtensionMessage { | "relativePathsResponse" // Handles single and multiple path responses | "fileSearchResults" | "fetchUSDRate" + | "ssyModels" text?: string paths?: (string | null)[] // Used for relativePathsResponse action?: @@ -111,6 +112,7 @@ export interface ExtensionMessage { error?: string } tab?: McpViewTab + ssyModels?: Record } export type Invoke = "sendMessage" | "primaryButtonClick" | "secondaryButtonClick" diff --git a/src/shared/WebviewMessage.ts b/src/shared/WebviewMessage.ts index 68daa581..302d8a79 100644 --- a/src/shared/WebviewMessage.ts +++ b/src/shared/WebviewMessage.ts @@ -84,7 +84,8 @@ export interface WebviewMessage { | "fetchUSDRate" | "accountLoginClickedSSY" | "accountLogoutClickedSSY" - // | "relaunchChromeDebugMode" + // | "relaunchChromeDebugMode" + | "ssyModels" text?: string uris?: string[] // Used for getRelativePaths disabled?: boolean diff --git a/src/shared/api.ts b/src/shared/api.ts index c25e1e2c..0daa156c 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -79,6 +79,7 @@ export interface ApiHandlerOptions { sambanovaApiKey?: string shengsuanyunApiKey?: string shengsuanyunToken?: string + ssyModelId?: string } export type ApiConfiguration = ApiHandlerOptions & { diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index 707c70d9..66bd7922 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -883,7 +883,7 @@ const ApiOptions = ({ showModelOptions, apiErrorMessage, modelIdErrorMessage, is openAiModelInfo: modelInfo, }) }}> - Supports Images + 支持图片 { + const { apiConfiguration, setApiConfiguration, openAiModels } = useExtensionState() + const [searchTerm, setSearchTerm] = useState(apiConfiguration?.ssyModelId || "") + const [isDropdownVisible, setIsDropdownVisible] = useState(false) + const [selectedIndex, setSelectedIndex] = useState(-1) + const dropdownRef = useRef(null) + const itemRefs = useRef<(HTMLDivElement | null)[]>([]) + const dropdownListRef = useRef(null) + + const handleModelChange = (newModelId: string) => { + // could be setting invalid model id/undefined info but validation will catch it + setApiConfiguration({ + ...apiConfiguration, + ssyModelId: newModelId, + }) + setSearchTerm(newModelId) + } + + useEffect(() => { + vscode.postMessage({ type: "ssyModels" }) + }, [apiConfiguration?.openAiBaseUrl, apiConfiguration?.openAiApiKey]) + + useEffect(() => { + const handleClickOutside = (event: MouseEvent) => { + if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) { + setIsDropdownVisible(false) + } + } + + document.addEventListener("mousedown", handleClickOutside) + return () => { + document.removeEventListener("mousedown", handleClickOutside) + } + }, []) + + const modelIds = useMemo(() => { + return openAiModels.sort((a, b) => a.localeCompare(b)) + }, [openAiModels]) + + const searchableItems = useMemo(() => { + return modelIds.map((id) => ({ + id, + html: id, + })) + }, [modelIds]) + + const fuse = useMemo(() => { + return new Fuse(searchableItems, { + keys: ["html"], // highlight function will update this + threshold: 0.6, + shouldSort: true, + isCaseSensitive: false, + ignoreLocation: false, + includeMatches: true, + minMatchCharLength: 1, + }) + }, [searchableItems]) + + const modelSearchResults = useMemo(() => { + const results: { id: string; html: string }[] = searchTerm + ? highlight(fuse.search(searchTerm), "model-item-highlight") + : searchableItems + // results.sort((a, b) => a.id.localeCompare(b.id)) NOTE: sorting like this causes ids in objects to be reordered and mismatched + return results + }, [searchableItems, searchTerm, fuse]) + + const handleKeyDown = (event: KeyboardEvent) => { + if (!isDropdownVisible) return + + switch (event.key) { + case "ArrowDown": + event.preventDefault() + setSelectedIndex((prev) => (prev < modelSearchResults.length - 1 ? prev + 1 : prev)) + break + case "ArrowUp": + event.preventDefault() + setSelectedIndex((prev) => (prev > 0 ? prev - 1 : prev)) + break + case "Enter": + event.preventDefault() + if (selectedIndex >= 0 && selectedIndex < modelSearchResults.length) { + handleModelChange(modelSearchResults[selectedIndex].id) + setIsDropdownVisible(false) + } + break + case "Escape": + setIsDropdownVisible(false) + setSelectedIndex(-1) + break + } + } + + useEffect(() => { + setSelectedIndex(-1) + if (dropdownListRef.current) { + dropdownListRef.current.scrollTop = 0 + } + }, [searchTerm]) + + useEffect(() => { + if (selectedIndex >= 0 && itemRefs.current[selectedIndex]) { + itemRefs.current[selectedIndex]?.scrollIntoView({ + block: "nearest", + behavior: "smooth", + }) + } + }, [selectedIndex]) + + return ( + <> + +
+ + { + handleModelChange((e.target as HTMLInputElement)?.value?.toLowerCase()) + setIsDropdownVisible(true) + }} + onFocus={() => setIsDropdownVisible(true)} + onKeyDown={handleKeyDown} + style={{ width: "100%", zIndex: OPENAI_MODEL_PICKER_Z_INDEX, position: "relative" }}> + {searchTerm && ( +
{ + handleModelChange("") + setIsDropdownVisible(true) + }} + slot="end" + style={{ + display: "flex", + justifyContent: "center", + alignItems: "center", + height: "100%", + }} + /> + )} + + {isDropdownVisible && ( + + {modelSearchResults.map((item, index) => ( + (itemRefs.current[index] = el)} + isSelected={index === selectedIndex} + onMouseEnter={() => setSelectedIndex(index)} + onClick={() => { + handleModelChange(item.id) + setIsDropdownVisible(false) + }} + dangerouslySetInnerHTML={{ + __html: item.html, + }} + /> + ))} + + )} + +
+ + ) +} + +export default SSYModelPicker + +// Dropdown + +const DropdownWrapper = styled.div` + position: relative; + width: 100%; +` + +export const OPENAI_MODEL_PICKER_Z_INDEX = 1_000 + +const DropdownList = styled.div` + position: absolute; + top: calc(100% - 3px); + left: 0; + width: calc(100% - 2px); + max-height: 200px; + overflow-y: auto; + background-color: var(--vscode-dropdown-background); + border: 1px solid var(--vscode-list-activeSelectionBackground); + z-index: ${OPENAI_MODEL_PICKER_Z_INDEX - 1}; + border-bottom-left-radius: 3px; + border-bottom-right-radius: 3px; +` + +const DropdownItem = styled.div<{ isSelected: boolean }>` + padding: 5px 10px; + cursor: pointer; + word-break: break-all; + white-space: normal; + + background-color: ${({ isSelected }) => (isSelected ? "var(--vscode-list-activeSelectionBackground)" : "inherit")}; + + &:hover { + background-color: var(--vscode-list-activeSelectionBackground); + } +` + +// Markdown + +const StyledMarkdown = styled.div` + font-family: + var(--vscode-font-family), + system-ui, + -apple-system, + BlinkMacSystemFont, + "Segoe UI", + Roboto, + Oxygen, + Ubuntu, + Cantarell, + "Open Sans", + "Helvetica Neue", + sans-serif; + font-size: 12px; + color: var(--vscode-descriptionForeground); + + p, + li, + ol, + ul { + line-height: 1.25; + margin: 0; + } + + ol, + ul { + padding-left: 1.5em; + margin-left: 0; + } + + p { + white-space: pre-wrap; + } + + a { + text-decoration: none; + } + a { + &:hover { + text-decoration: underline; + } + } +` + +export const ModelDescriptionMarkdown = memo( + ({ + markdown, + key, + isExpanded, + setIsExpanded, + }: { + markdown?: string + key: string + isExpanded: boolean + setIsExpanded: (isExpanded: boolean) => void + }) => { + const [reactContent, setMarkdown] = useRemark() + // const [isExpanded, setIsExpanded] = useState(false) + const [showSeeMore, setShowSeeMore] = useState(false) + const textContainerRef = useRef(null) + const textRef = useRef(null) + + useEffect(() => { + setMarkdown(markdown || "") + }, [markdown, setMarkdown]) + + useEffect(() => { + if (textRef.current && textContainerRef.current) { + const { scrollHeight } = textRef.current + const { clientHeight } = textContainerRef.current + const isOverflowing = scrollHeight > clientHeight + setShowSeeMore(isOverflowing) + // if (!isOverflowing) { + // setIsExpanded(false) + // } + } + }, [reactContent, setIsExpanded]) + + return ( + +
+
+ {reactContent} +
+ {!isExpanded && showSeeMore && ( +
+
+ setIsExpanded(true)}> + 更多 + +
+ )} +
+ + ) + }, +)