| 1 | import { SettingsSelect } from "./SettingsSelect"; |
| 2 | import { protocolsForCatalog } from "../lib/providerCatalog"; |
| 3 | import { RotateCcw } from "lucide-react"; |
| 4 | import { providerProtocolLabel } from "../lib/providerProtocol"; |
| 5 | import { providerBrandIcons } from "../lib/providerBrandIcons"; |
| 6 | import { useId, useMemo, useState } from "react"; |
| 7 | import { useT, type DictKey } from "../lib/i18n"; |
| 8 | import type { ProviderCatalog } from "../lib/types"; |
| 9 | |
| 10 | export interface CatalogChoice { |
| 11 | id: string; |
| 12 | label?: string; |
| 13 | catalog: ProviderCatalog; |
| 14 | keyEnv: string; |
| 15 | keySet: boolean; |
| 16 | models: string[]; |
| 17 | canAdd: boolean; |
| 18 | status: string; |
| 19 | statusLabel: string; |
| 20 | actionLabel: string; |
| 21 | conflictName?: string; |
| 22 | } |
| 23 | |
| 24 | export const apiFormatLabel = providerProtocolLabel; |
| 25 | |
| 26 | const regionKeys: Record<string, DictKey> = { |
| 27 | cn: "settings.catalog.regionChina", global: "settings.catalog.regionGlobal", |
| 28 | sgp: "settings.catalog.regionSingapore", ams: "settings.catalog.regionEurope", |
| 29 | local: "settings.catalog.regionLocal", |
| 30 | }; |
| 31 | const productKeys: Record<string, DictKey> = { |
| 32 | api: "settings.catalog.productAPI", coding: "settings.catalog.productCoding", token: "settings.catalog.productToken", |
| 33 | go: "settings.catalog.productGo", zen: "settings.catalog.productZen", local: "settings.catalog.productLocal", |
| 34 | }; |
| 35 | |
| 36 | export function ProviderCatalogPicker({ choices, busy, onConnect, onView, onReset }: { |
| 37 | choices: CatalogChoice[]; |
| 38 | busy: boolean; |
| 39 | onConnect: (id: string, key: string, baseURL?: string, format?: string) => void; |
| 40 | onView: (name: string) => void; |
| 41 | onReset: (id: string) => void; |
| 42 | }) { |
| 43 | const t = useT(); |
| 44 | const uid = useId(); |
| 45 | const [selectedID, setSelectedID] = useState(choices.find(c => c.canAdd)?.id ?? choices[0]?.id ?? ""); |
| 46 | const [keyDraft, setKeyDraft] = useState({ id: "", keyEnv: "", value: "" }); |
| 47 | const [urlDrafts, setUrlDrafts] = useState<Record<string, string>>({}); |
| 48 | const [formatDrafts, setFormatDrafts] = useState<Record<string, string>>({}); |
| 49 | const [query, setQuery] = useState(""); |
| 50 | const [confirmReset, setConfirmReset] = useState(false); |
| 51 | const selected = choices.find(c => c.id === selectedID) ?? choices[0]; |
| 52 | const brands = useMemo(() => [...new Map(choices.map(c => [c.catalog.brandId, |
| 53 | c.catalog.brandId === "token-rhythm" ? t("settings.addProvider.preset.tokenRhythmLabel") : c.catalog.brandLabel])).entries()], [choices, t]); |
| 54 | if (!selected) return null; |
| 55 | const genericFormat = (value: string) => value === "dashscope-responses" ? "responses" : value; |
| 56 | // The official DeepSeek connection starts with Chat Completions regardless |
| 57 | // of which protocol-specific preset supplied the brand's first catalog row. |
| 58 | const defaultFormat = selected.catalog.brandId === "deepseek" && selected.catalog.product === "api" |
| 59 | ? "openai" : genericFormat(selected.catalog.format); |
| 60 | const format = formatDrafts[selected.id] ?? defaultFormat; |
| 61 | const protocols = protocolsForCatalog(selected.catalog); |
| 62 | const defaultURL = protocols[format]?.baseUrl ?? selected.catalog.baseUrl ?? ""; |
| 63 | const baseURL = urlDrafts[selected.id] ?? defaultURL; |
| 64 | let validURL = !selected.catalog.baseUrl; |
| 65 | try { const u = new URL(baseURL); validURL = (u.protocol === "https:" || u.protocol === "http:") && Boolean(u.hostname) && !u.username && !u.password; } catch { /* invalid draft */ } |
| 66 | const key = keyDraft.id === selected.id && keyDraft.keyEnv === selected.keyEnv ? keyDraft.value : ""; |
| 67 | const siblings = choices.filter(c => c.catalog.brandId === selected.catalog.brandId); |
| 68 | const regionChoices = siblings.filter(c => c.catalog.region === selected.catalog.region); |
| 69 | const formatChoices = regionChoices.filter(c => c.catalog.product === selected.catalog.product); |
| 70 | const pick = (choice: CatalogChoice | undefined) => { |
| 71 | if (!choice) return; |
| 72 | setSelectedID(choice.id); |
| 73 | setKeyDraft({id: "", keyEnv: "", value: ""}); |
| 74 | setConfirmReset(false); |
| 75 | }; |
| 76 | const chooseDimension = (dimension: "region" | "product" | "format", value: string) => { |
| 77 | const candidates = (dimension === "region" ? siblings : dimension === "product" ? regionChoices : formatChoices) |
| 78 | .filter(c => c.catalog[dimension] === value); |
| 79 | pick(candidates.find(c => c.catalog.product === selected.catalog.product && c.catalog.format === selected.catalog.format) |
| 80 | ?? candidates.find(c => c.catalog.format === selected.catalog.format) ?? candidates[0]); |
| 81 | }; |
| 82 | const field = (dimension: "region" | "product" | "format", label: DictKey, candidates: CatalogChoice[]) => { |
| 83 | const values = [...new Set(candidates.map(c => c.catalog[dimension]))]; |
| 84 | return <div className="provider-catalog__field"> |
| 85 | <label className="set-label" htmlFor={`${uid}-${dimension}`}>{t(label)}</label> |
| 86 | <SettingsSelect id={`${uid}-${dimension}`} className="mem-select" disabled={busy || values.length < 2} |
| 87 | value={selected.catalog[dimension]} onValueChange={value => chooseDimension(dimension, value)}> |
| 88 | {values.map(value => <option key={value} value={value}>{dimension === "format" |
| 89 | ? value === "bundle" ? t("settings.catalog.formatBundle") : apiFormatLabel(value) |
| 90 | : (dimension === "region" ? regionKeys[value] : productKeys[value]) |
| 91 | ? t((dimension === "region" ? regionKeys[value] : productKeys[value])) : value}</option>)} |
| 92 | </SettingsSelect> |
| 93 | </div>; |
| 94 | }; |
| 95 | return <div className="provider-catalog"> |
| 96 | <aside className="provider-catalog__sidebar"> |
| 97 | <input className="mem-input" aria-label={t("settings.catalog.search")} placeholder={t("settings.catalog.search")} |
| 98 | value={query} onChange={e => setQuery(e.target.value)} /> |
| 99 | <div className="provider-catalog__brands" aria-label={t("settings.catalog.providers")}> |
| 100 | {brands.filter(([id, label]) => `${id} ${label}`.toLowerCase().includes(query.trim().toLowerCase())).map(([id, label]) => |
| 101 | <button key={id} type="button" className="provider-catalog__brand" aria-pressed={selected.catalog.brandId === id} |
| 102 | disabled={busy} onClick={() => pick(choices.find(c => c.catalog.brandId === id && c.canAdd) ?? choices.find(c => c.catalog.brandId === id))}> |
| 103 | {providerBrandIcons.has(id) |
| 104 | ? <span className="provider-catalog__icon" aria-hidden="true" style={{maskImage: `url(/provider-icons/${id}.svg)`, WebkitMaskImage: `url(/provider-icons/${id}.svg)`}} /> |
| 105 | : <span className="provider-catalog__monogram" aria-hidden="true">{label.slice(0, 1)}</span>}<span>{label}</span> |
| 106 | </button>)} |
| 107 | </div> |
| 108 | </aside> |
| 109 | <section className="provider-catalog__detail" aria-label={selected.catalog.brandLabel}> |
| 110 | <strong className="provider-catalog__title">{selected.catalog.brandLabel}</strong> |
| 111 | {(new Set(siblings.map(c => c.catalog.region)).size > 1 || new Set(regionChoices.map(c => c.catalog.product)).size > 1) && <div className="provider-catalog__options"> |
| 112 | {new Set(siblings.map(c => c.catalog.region)).size > 1 && field("region", "settings.catalog.region", siblings)} |
| 113 | {new Set(regionChoices.map(c => c.catalog.product)).size > 1 && field("product", "settings.catalog.product", regionChoices)} |
| 114 | </div>} |
| 115 | <div className="provider-catalog__field"> |
| 116 | <label className="set-label" htmlFor={`${uid}-format`}>{t("settings.providerProtocol")}</label> |
| 117 | <SettingsSelect id={`${uid}-format`} className="mem-select" disabled={busy} value={format} |
| 118 | onValueChange={value => { |
| 119 | const next = value; |
| 120 | const match = formatChoices.find(c => genericFormat(c.catalog.format) === next); |
| 121 | if (match) { |
| 122 | if (Object.prototype.hasOwnProperty.call(urlDrafts, selected.id)) setUrlDrafts(prev => ({...prev, [match.id]: baseURL})); |
| 123 | else setUrlDrafts(prev => { const copy = {...prev}; delete copy[match.id]; return copy; }); |
| 124 | setKeyDraft({id: match.id, keyEnv: match.keyEnv, value: key}); |
| 125 | setSelectedID(match.id); |
| 126 | setFormatDrafts(prev => ({...prev, [match.id]: next})); |
| 127 | } else setFormatDrafts(prev => ({...prev, [selected.id]: next})); |
| 128 | }}> |
| 129 | {["openai", "responses", "anthropic"].map(value => <option key={value} value={value}>{apiFormatLabel(value)}</option>)} |
| 130 | {selected.catalog.format === "bundle" && <option value="bundle">{t("settings.catalog.formatBundle")}</option>} |
| 131 | </SettingsSelect> |
| 132 | {!protocols[format] && !formatChoices.some(c => genericFormat(c.catalog.format) === format) && <div className="mem-hint">{t("settings.catalog.verifyFormat")}</div>} |
| 133 | </div> |
| 134 | {formatChoices.filter(c => c.catalog.format === selected.catalog.format).length > 1 && <div className="provider-catalog__field"> |
| 135 | <label className="set-label" htmlFor={`${uid}-variant`}>{t("settings.catalog.variant")}</label> |
| 136 | <SettingsSelect id={`${uid}-variant`} className="mem-select" value={selected.id} disabled={busy} onValueChange={value => pick(choices.find(c => c.id === value))}> |
| 137 | {formatChoices.filter(c => c.catalog.format === selected.catalog.format).map(c => <option key={c.id} value={c.id}>{c.label || c.id}</option>)} |
| 138 | </SettingsSelect> |
| 139 | </div>} |
| 140 | {selected.catalog.brandId === "anthropic" && <div className="mem-hint">{t("settings.catalog.anthropicHint")}</div>} |
| 141 | {selected.catalog.region === "local" && <div className="mem-hint">{t("settings.catalog.localHint")}</div>} |
| 142 | {selected.catalog.baseUrl && <div className="provider-catalog__field"> |
| 143 | <label className="set-label" htmlFor={`${uid}-url`}>Base URL</label> |
| 144 | <div className="provider-catalog__url-control"> |
| 145 | <input id={`${uid}-url`} className="mem-input" value={baseURL} disabled={busy} aria-invalid={!validURL} onChange={e => setUrlDrafts(prev => ({...prev, [selected.id]:e.target.value}))} /> |
| 146 | {baseURL !== defaultURL && <button type="button" className="provider-catalog__restore" disabled={busy} aria-label={t("settings.catalog.restoreURL")} title={t("settings.catalog.restoreURL")} onClick={() => setUrlDrafts(prev => { const next = {...prev}; delete next[selected.id]; return next; })}><RotateCcw size={16}/></button>} |
| 147 | </div> |
| 148 | <div className="mem-hint">{t("settings.catalog.endpointHint")}</div> |
| 149 | </div>} |
| 150 | <label className="set-label" htmlFor={`${uid}-key`}>API Key</label> |
| 151 | <input id={`${uid}-key`} className="mem-input" type="password" autoComplete="off" |
| 152 | placeholder={t("settings.setKey", {env: selected.keyEnv})} value={key} |
| 153 | disabled={busy || !selected.canAdd} onChange={e => setKeyDraft({id: selected.id, keyEnv: selected.keyEnv, value: e.target.value})} /> |
| 154 | {selected.keySet && <div className="mem-hint">{t("settings.catalog.savedKey")}</div>} |
| 155 | <div className="provider-catalog__models"><span className="set-label">{t("settings.catalog.models")}</span> |
| 156 | <span>{selected.models.join(", ") || t("settings.catalog.modelsAfterConnect")}</span> |
| 157 | </div> |
| 158 | {selected.statusLabel && <div role="status" className="mem-hint">{selected.statusLabel}</div>} |
| 159 | <div className="prov-card__actions"> |
| 160 | {selected.conflictName && <button type="button" className="btn btn--small" disabled={busy} onClick={() => onView(selected.conflictName!)}>{t("settings.addProvider.viewPresetProvider")}</button>} |
| 161 | {(selected.status === "name_conflict" || selected.status === "installed_modified") && <button type="button" className="btn btn--small" disabled={busy} |
| 162 | onClick={() => { if (confirmReset) { onReset(selected.id); setConfirmReset(false); } else setConfirmReset(true); }}> |
| 163 | {t(confirmReset ? "settings.addProvider.confirmResetPreset" : "settings.addProvider.resetPreset")} |
| 164 | </button>} |
| 165 | <button type="button" className="btn btn--small btn--primary" disabled={busy || !selected.canAdd || !validURL} |
| 166 | onClick={() => onConnect(selected.id, key.trim(), baseURL.trim() || undefined, format === genericFormat(selected.catalog.format) ? undefined : format)}>{selected.actionLabel}</button> |
| 167 | </div> |
| 168 | </section> |
| 169 | </div>; |
| 170 | } |
| 171 |