import { Check, ChevronLeft, ChevronRight, Loader2, Pin, RotateCw, Search, Star } from 'lucide-react'; import React, { useEffect, useMemo, useState } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; import { canonicalizeEffortEncodedModelId, filterComposerModels, resolveComposerEnterModelId, resolvePinnedAndRecentModels, type ComposerModelPrefEntry, type ComposerModelPrefs, type ComposerPickerModel, } from '../../infrastructure/ai/composerPicker'; import type { AgentModelPreset, ProviderConfig } from '../../infrastructure/ai/types'; import { formatRelativeTime } from '../AIChatSessionHistoryDrawer'; import { ProviderIconBadge } from '../settings/tabs/ai/ProviderIconBadge'; import { useProviderModelCatalog } from './useProviderModelCatalog'; export const COMPOSER_PROVIDER_PICKER_WIDTH = 260; export const COMPOSER_MODEL_PICKER_WIDTH = 260; export interface ComposerModelPickerProps { providers?: ProviderConfig[]; selectedProviderId?: string; selectedModelId?: string; modelPresets?: AgentModelPreset[]; /** * The host's live model catalog (external SDK agents like OpenCode) is still * loading. Show the loading row instead of an empty/placeholder list. */ loading?: boolean; /** * Provenance of the model list behind this picker: a live SDK fetch, the * persisted last-known-good catalog, or the build-time preset fallback. * Rendered as a small muted status footer; omit (provider switcher mode) * to hide the chip. */ catalogSource?: 'live' | 'last-known-good' | 'presets'; /** ISO timestamp of the successful fetch backing `catalogSource`. */ catalogFetchedAt?: string; /** * The catalog warning text behind the host's retry banner, when present. * Together with `catalogSource` it decides whether the manual refresh * button renders: any fetched catalog (live or last-known-good) or a * degraded preset fallback offers a refresh; a plain preset list does not. */ catalogWarning?: string | null; /** * Manual refresh action (LKG-first policy: the picker hydrates from disk * and the user refreshes explicitly). Triggers the host's force refresh. */ onRefreshCatalog?: () => void; prefs: ComposerModelPrefs; /** * Offer the "use custom model" action. Disable when the host locks the * model (e.g. a managed Codex config's `model` field overrides every * selection), so the action never becomes a silent no-op. */ allowCustomEntry?: boolean; onSelectProviderModel?: (providerId: string, modelId: string, contextWindow?: number) => void; onSelectModel?: (modelId: string, options?: { custom?: boolean }) => void; onTogglePinned: (entry: ComposerModelPrefEntry) => void; } const rowClassName = 'flex h-8 w-full items-center gap-2 px-2.5 text-left text-[12px] hover:bg-muted/30 transition-colors cursor-pointer'; const SectionLabel: React.FC<{ children: React.ReactNode }> = ({ children }) => (
{children}
); const ModelRow: React.FC<{ model: ComposerPickerModel; selected: boolean; pinned: boolean; onSelect: () => void; onTogglePinned: () => void; pinLabel: string; unpinLabel: string; }> = ({ model, selected, pinned, onSelect, onTogglePinned, pinLabel, unpinLabel }) => (
); export const ComposerModelPicker: React.FC = ({ providers = [], selectedProviderId, selectedModelId, modelPresets = [], loading = false, catalogSource, catalogFetchedAt, catalogWarning, onRefreshCatalog, prefs, allowCustomEntry = true, onSelectProviderModel, onSelectModel, onTogglePinned, }) => { const { t } = useI18n(); const hasProviders = providers.length > 0; const [previewProviderId, setPreviewProviderId] = useState( selectedProviderId || providers[0]?.id || '', ); const [query, setQuery] = useState(''); const [view, setView] = useState<'models' | 'providers'>('models'); useEffect(() => { if (selectedProviderId) setPreviewProviderId(selectedProviderId); }, [selectedProviderId]); const previewProvider = hasProviders ? providers.find((provider) => provider.id === previewProviderId) ?? providers[0] : undefined; const catalog = useProviderModelCatalog(previewProvider, hasProviders); const models = useMemo(() => { if (hasProviders) return catalog.models; return modelPresets.map((preset) => ({ id: preset.id, name: preset.name, description: preset.description, })); }, [catalog.models, hasProviders, modelPresets]); const filtered = useMemo(() => filterComposerModels(models, query), [models, query]); const grouped = useMemo( () => resolvePinnedAndRecentModels({ models: filtered, prefs, providerId: previewProvider?.id, allowMissing: Boolean(previewProvider?.id) && !query.trim(), }), [filtered, prefs, previewProvider?.id, query], ); const pinnedKeys = useMemo( () => new Set( prefs.pinned .filter((entry) => !previewProvider || !entry.providerId || entry.providerId === previewProvider.id) .map((entry) => entry.modelId), ), [prefs.pinned, previewProvider], ); const trimmedQuery = query.trim(); // Uniform catalog status chip (all SDK backends). While the live fetch is // in flight the spinner row replaces the chip, so it renders only for a // resolved list; an unknown source renders nothing (provider mode). const catalogChipText = useMemo(() => { if (loading || !catalogSource) return null; if (catalogSource === 'live') return t('ai.chat.modelCatalogSourceLive'); if (catalogSource === 'presets') return t('ai.chat.modelCatalogSourcePresets'); const parsed = catalogFetchedAt ? new Date(catalogFetchedAt) : null; const time = parsed && !Number.isNaN(parsed.getTime()) ? formatRelativeTime(parsed, t) : ''; return time ? t('ai.chat.modelCatalogSourceCached').replace('{time}', time) : t('ai.chat.modelCatalogSourceCachedNoTime'); }, [loading, catalogSource, catalogFetchedAt, t]); // Manual refresh (LKG-first): offered whenever a fetched catalog (any // source) or the degraded-preset warning is present. Hidden while loading — // the spinner row is the in-flight feedback — and in provider mode, where // neither a catalog chip nor a host refresh action exists. const showRefreshButton = useMemo(() => ( !loading && Boolean(onRefreshCatalog) && (catalogSource === 'live' || catalogSource === 'last-known-good' || Boolean(catalogWarning)) ), [loading, onRefreshCatalog, catalogSource, catalogWarning]); const refreshLabel = t('ai.chat.refreshModelList'); // Manual model ids are accepted in both modes: provider-bound catalogs and // preset lists from external CLI agents whose catalogs lag new models. const showCustom = Boolean( allowCustomEntry && trimmedQuery && !models.some((model) => model.id.toLowerCase() === trimmedQuery.toLowerCase()), ); // Ids the prefs already mark as custom. A saved custom model that was // appended to the preset list is selectable from Recent/Pinned while // showCustom is false (query empty, id present in the list); the callback // must keep the custom provenance or the host overwrites the pref entry // without it and resolveComposerCustomModelIds drops the model (#3534). const customPrefIds = useMemo(() => { const ids = new Set(); for (const entry of [...prefs.pinned, ...prefs.recent]) { if (entry.providerId || entry.custom !== true) continue; ids.add(canonicalizeEffortEncodedModelId(entry.modelId).trim().toLowerCase()); } return ids; }, [prefs]); const selectModel = (modelId: string) => { const contextWindow = models.find((model) => model.id === modelId)?.contextWindow; if (hasProviders && previewProvider) { onSelectProviderModel?.(previewProvider.id, modelId, contextWindow); return; } // showCustom is only true when no catalog id matches the query, so a // matching pick here came from the manual-entry action (row or Enter). // Otherwise preserve provenance already recorded in the prefs. const custom = Boolean( (showCustom && modelId.toLowerCase() === trimmedQuery.toLowerCase()) || customPrefIds.has(modelId.toLowerCase()), ); onSelectModel?.(modelId, custom ? { custom: true } : undefined); }; const prefEntryFor = (modelId: string): ComposerModelPrefEntry => ( previewProvider ? { providerId: previewProvider.id, modelId } // Preserve custom provenance on pin/unpin: a manual model pinned while // other selections evict its unmarked recent twin would otherwise lose // the custom marker and fall back to a catalog model (#3534). : { modelId, ...(customPrefIds.has(modelId.toLowerCase()) ? { custom: true as const } : {}) } ); if (hasProviders && view === 'providers') { return (
{providers.map((provider) => { const isBound = provider.id === selectedProviderId; return ( ); })}
); } return (
{hasProviders && previewProvider && ( <> )}
setQuery(event.target.value)} onKeyDown={(event) => { if (event.key === 'Enter' && trimmedQuery) { event.preventDefault(); const nextId = resolveComposerEnterModelId({ query: trimmedQuery, models, grouped, filtered, showCustom, }); if (nextId) selectModel(nextId); } }} placeholder={t('ai.chat.searchModels')} className="h-full w-full bg-transparent text-[12px] text-foreground/88 outline-none placeholder:text-muted-foreground/40" />
{(catalog.loading || (loading && !hasProviders)) && (
{t('ai.chat.loadingModels')}
)} {showCustom && ( )} {grouped.pinned.length > 0 && ( <> {t('ai.chat.pinned')} {grouped.pinned.map((model) => ( selectModel(model.id)} onTogglePinned={() => onTogglePinned(prefEntryFor(model.id))} pinLabel={t('ai.chat.pinModel')} unpinLabel={t('ai.chat.unpinModel')} /> ))} )} {grouped.recent.length > 0 && ( <> {t('ai.chat.recent')} {grouped.recent.map((model) => ( selectModel(model.id)} onTogglePinned={() => onTogglePinned(prefEntryFor(model.id))} pinLabel={t('ai.chat.pinModel')} unpinLabel={t('ai.chat.unpinModel')} /> ))} )} {(grouped.pinned.length > 0 || grouped.recent.length > 0) && grouped.rest.length > 0 && ( {t('ai.chat.models')} )} {grouped.rest.map((model) => ( selectModel(model.id)} onTogglePinned={() => onTogglePinned(prefEntryFor(model.id))} pinLabel={t('ai.chat.pinModel')} unpinLabel={t('ai.chat.unpinModel')} /> ))} {!catalog.loading && !loading && filtered.length === 0 && !showCustom && (
{catalog.error || t('ai.chat.noMatchingModels')}
)}
{(catalogChipText || showRefreshButton) && (
{catalogChipText && ( {catalogChipText} )} {showRefreshButton && ( )}
)}
); }; export default React.memo(ComposerModelPicker);