Files
Netcatty/components/ai/ComposerModelPicker.tsx
T
GOUKI9999 02f8c798f7 feat(ai): hydrate model pickers from last-known-good and fetch only on demand
The list-models pipeline already served LKG on failure; this wires the
rest of the LKG-first, manual-refresh policy end to end.

Main: the list-models IPC accepts a force flag — manual refresh always
skips the in-memory cache and the persisted entry and goes live, and a
forced success overwrites the persisted catalog.

Renderer: the panel passes force only from the retry banner and the
picker's refresh button; panel-visibility and send-preflight loads stay
non-force and replay the renderer cache, so with a persisted catalog
main answers them without spending the live-fetch budget.

Picker: a footer refresh icon-button next to the status chip, visible
whenever any fetched catalog (live or last-known-good) or the degraded
warning is present; the spinner row remains the in-flight feedback.
Tooltip localized as ai.chat.refreshModelList in en/es/ru/zh-CN/zh-TW.

Fresh installs are unchanged (no persisted entry → live fetch as
before); existing users stop seeing jitter warnings on panel open and
pick up new CLI models via the refresh button.
2026-10-23 17:22:25 +08:00

436 lines
17 KiB
TypeScript

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 }) => (
<div className="px-2.5 pt-1.5 pb-0.5 text-[10px] tracking-wide text-muted-foreground/45">
{children}
</div>
);
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 }) => (
<div className="group/row relative">
<button
type="button"
role="option"
aria-selected={selected}
onClick={onSelect}
className={rowClassName}
>
{selected
? <Check size={11} className="text-primary shrink-0" />
: <span className="w-[11px] shrink-0" />}
<span className="min-w-0 flex-1 truncate text-foreground/88" title={model.name}>{model.name}</span>
</button>
<button
type="button"
aria-label={pinned ? unpinLabel : pinLabel}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
onTogglePinned();
}}
className={`absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-0.5 transition-opacity ${
pinned
? 'text-amber-400/90 opacity-100'
: 'text-muted-foreground/45 opacity-0 group-hover/row:opacity-100 hover:text-foreground/70'
}`}
>
<Star size={11} fill={pinned ? 'currentColor' : 'none'} />
</button>
</div>
);
export const ComposerModelPicker: React.FC<ComposerModelPickerProps> = ({
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<ComposerPickerModel[]>(() => {
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<string>();
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 (
<div className="w-[260px] max-w-[calc(100vw-16px)] py-1">
<button
type="button"
onClick={() => setView('models')}
className={rowClassName}
>
<ChevronLeft size={12} className="text-muted-foreground/60 shrink-0" />
<span className="min-w-0 flex-1 truncate text-[11px] text-muted-foreground/70">
{t('ai.chat.providers')}
</span>
</button>
<div className="mx-2 my-1 border-t border-border/40" />
{providers.map((provider) => {
const isBound = provider.id === selectedProviderId;
return (
<button
key={provider.id}
type="button"
role="option"
aria-selected={isBound}
onClick={() => {
setPreviewProviderId(provider.id);
setQuery('');
setView('models');
}}
className={rowClassName}
>
<ProviderIconBadge provider={provider} size="xs" />
<span className="min-w-0 flex-1 truncate text-foreground/88">{provider.name}</span>
{isBound && <Check size={11} className="text-primary shrink-0" />}
</button>
);
})}
</div>
);
}
return (
<div className="w-[260px] max-w-[calc(100vw-16px)] py-1">
{hasProviders && previewProvider && (
<>
<button
type="button"
aria-label={t('ai.chat.selectProvider')}
onClick={() => setView('providers')}
className={rowClassName}
>
<ProviderIconBadge provider={previewProvider} size="xs" />
<span className="min-w-0 flex-1 truncate text-foreground/88">{previewProvider.name}</span>
<ChevronRight size={12} className="text-muted-foreground/50 shrink-0" />
</button>
</>
)}
<div className="px-2 pb-1">
<div className="flex h-7 items-center gap-1.5 rounded-md bg-muted/40 px-2">
<Search size={11} className="text-muted-foreground/50 shrink-0" />
<input
autoFocus
value={query}
onChange={(event) => 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"
/>
</div>
</div>
<div className="max-h-[280px] overflow-y-auto">
{(catalog.loading || (loading && !hasProviders)) && (
<div className="flex h-8 items-center gap-1.5 px-2.5 text-[11px] text-muted-foreground/55">
<Loader2 size={11} className="animate-spin" />
{t('ai.chat.loadingModels')}
</div>
)}
{showCustom && (
<button
type="button"
onClick={() => selectModel(trimmedQuery)}
className={rowClassName}
>
<Pin size={11} className="text-muted-foreground/55 shrink-0" />
<span className="min-w-0 truncate text-foreground/85">
{t('ai.chat.useCustomModel').replace('{id}', trimmedQuery)}
</span>
</button>
)}
{grouped.pinned.length > 0 && (
<>
<SectionLabel>{t('ai.chat.pinned')}</SectionLabel>
{grouped.pinned.map((model) => (
<ModelRow
key={`pin-${model.id}`}
model={model}
selected={model.id === selectedModelId && (!hasProviders || previewProvider?.id === selectedProviderId)}
pinned
onSelect={() => selectModel(model.id)}
onTogglePinned={() => onTogglePinned(prefEntryFor(model.id))}
pinLabel={t('ai.chat.pinModel')}
unpinLabel={t('ai.chat.unpinModel')}
/>
))}
</>
)}
{grouped.recent.length > 0 && (
<>
<SectionLabel>{t('ai.chat.recent')}</SectionLabel>
{grouped.recent.map((model) => (
<ModelRow
key={`recent-${model.id}`}
model={model}
selected={model.id === selectedModelId && (!hasProviders || previewProvider?.id === selectedProviderId)}
pinned={pinnedKeys.has(model.id)}
onSelect={() => 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 && (
<SectionLabel>{t('ai.chat.models')}</SectionLabel>
)}
{grouped.rest.map((model) => (
<ModelRow
key={model.id}
model={model}
selected={model.id === selectedModelId && (!hasProviders || previewProvider?.id === selectedProviderId)}
pinned={pinnedKeys.has(model.id)}
onSelect={() => 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 && (
<div className="px-2.5 py-2 text-[11px] text-muted-foreground/50">
{catalog.error || t('ai.chat.noMatchingModels')}
</div>
)}
</div>
{(catalogChipText || showRefreshButton) && (
<div className="flex items-center gap-1 border-t border-border/40 px-2.5 py-1 text-[10px] text-muted-foreground/45">
{catalogChipText && (
<span className="min-w-0 flex-1 truncate" title={catalogChipText}>{catalogChipText}</span>
)}
{showRefreshButton && (
<button
type="button"
aria-label={refreshLabel}
title={refreshLabel}
onClick={onRefreshCatalog}
className="shrink-0 rounded p-0.5 text-muted-foreground/55 transition-colors hover:bg-muted/40 hover:text-foreground/75 cursor-pointer"
>
<RotateCw size={11} />
</button>
)}
</div>
)}
</div>
);
};
export default React.memo(ComposerModelPicker);