The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(model-picker): keep custom provider rows and the current model honest across switches
Austin Pickett39a01d069d65
diff --git a/apps/desktop/src/app/settings/model-settings.test.tsx b/apps/desktop/src/app/settings/model-settings.test.tsxindex 5eeedabc74d..ede7e188677 100644--- a/apps/desktop/src/app/settings/model-settings.test.tsx+++ b/apps/desktop/src/app/settings/model-settings.test.tsx@@ -657,6 +657,92 @@ describe('ModelSettings', () => {})})+describe('ModelSettings provider switch', () => {+ // #59063: a provider's model list is per-provider. Switching must not carry+ // the previous provider's model over (ModelSelect's withActive() would keep+ // painting it), and an empty freshly-selected custom provider must be probed+ // via a refresh-scoped options fetch rather than left at 0 models.+ it('clears the selected model when the user switches provider', async () => {+ getGlobalModelOptions.mockResolvedValue({+ providers: [+ { name: 'Nous', slug: 'nous', models: ['hermes-4'], authenticated: true },+ {+ name: 'Custom endpoint',+ slug: 'custom:lab',+ api_url: 'http://10.0.0.2:8080/v1',+ is_user_defined: true,+ source: 'user-config',+ models: ['gemma-4-12b-omni'],+ authenticated: true+ }+ ]+ })++ renderModelSettings()+ await screen.findAllByRole('combobox')++ // The model select paints the current provider's model.+ expect(await screen.findByText('hermes-4')).toBeTruthy()++ // Switch provider through the main selector (first combobox opens the+ // provider dropdown).+ fireEvent.click(screen.getAllByRole('combobox')[0])+ fireEvent.click(await screen.findByRole('option', { name: /Custom endpoint/ }))++ // The previous provider's model must not carry over.+ await waitFor(() => expect(screen.queryByText('hermes-4')).toBeNull())+ })++ it('probes an empty custom provider with a refresh-scoped options fetch on switch', async () => {+ getGlobalModelOptions.mockResolvedValue({+ providers: [+ { name: 'Nous', slug: 'nous', models: ['hermes-4'], authenticated: true },+ {+ name: 'Lab',+ slug: 'custom:lab',+ api_url: 'http://10.0.0.2:8080/v1',+ is_user_defined: true,+ source: 'user-config',+ models: [],+ authenticated: true+ }+ ]+ })++ renderModelSettings()+ await screen.findAllByRole('combobox')++ // The refresh-scoped fetch repopulates the empty provider's models.+ getGlobalModelOptions.mockResolvedValueOnce({+ providers: [+ { name: 'Nous', slug: 'nous', models: ['hermes-4'], authenticated: true },+ {+ name: 'Lab',+ slug: 'custom:lab',+ api_url: 'http://10.0.0.2:8080/v1',+ is_user_defined: true,+ source: 'user-config',+ models: ['gemma-4-12b-omni'],+ authenticated: true+ }+ ]+ })++ fireEvent.click(screen.getAllByRole('combobox')[0])+ fireEvent.click(await screen.findByRole('option', { name: /Lab/ }))++ await waitFor(() => {+ // refresh-scoped, not the plain read the mount effect already made+ expect(getGlobalModelOptions).toHaveBeenCalledWith({ refresh: true }, undefined)+ })++ // The refreshed catalog repopulates the empty provider's models: open the+ // model select and the discovered model is offered.+ fireEvent.click(screen.getAllByRole('combobox')[1])+ expect(await screen.findByRole('option', { name: 'gemma-4-12b-omni' })).toBeTruthy()+ })+})+describe('ModelSettings MoA preset editor', () => {const moaConfig = () => ({default_preset: 'default',diff --git a/apps/desktop/src/app/settings/model-settings.tsx b/apps/desktop/src/app/settings/model-settings.tsxindex 60eae7b1de6..0608f251876 100644--- a/apps/desktop/src/app/settings/model-settings.tsx+++ b/apps/desktop/src/app/settings/model-settings.tsx@@ -2,6 +2,7 @@ import type { ModelOptionProvider } from '@hermes/shared'import { DEFAULT_REASONING_EFFORT, REASONING_EFFORT_VALUES } from '@hermes/shared'import { useStore } from '@nanostores/react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import type { Dispatch, SetStateAction } from 'react'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'@@ -31,7 +32,7 @@ import { useI18n } from '@/i18n'import { isCodeSkewRestartRequired } from '@/lib/code-skew-error'import { AlertTriangle, Cpu, Loader2 } from '@/lib/icons'import { isSubmitEnter } from '@/lib/ime'-import { findCatalogProvider } from '@/lib/model-options'+import { catalogProviderMatches, findCatalogProvider } from '@/lib/model-options'import { composerServiceTier } from '@/lib/model-status-label'import { cn } from '@/lib/utils'import { $customModels, withCustomModels } from '@/store/custom-models'@@ -104,6 +105,87 @@ function isProviderReady(p?: ModelOptionProvider): boolean {const NO_PROVIDERS: readonly ModelOptionProvider[] = [{ name: '—', slug: '', models: [] }]+// Options for the main provider Select: the full catalog, but a saved provider+// missing from it stays visible (Radix renders a blank trigger when the+// controlled value has no matching item) while remaining out of the real+// inventory used for readiness/setup metadata.+function mainProviderOptionsFor(providers: readonly ModelOptionProvider[], selectedProvider: string) {+ const options = providers.length ? providers : NO_PROVIDERS++ return selectedProvider && !findCatalogProvider(providers, selectedProvider)+ ? [{ name: selectedProvider, slug: selectedProvider, models: [] as string[] }, ...providers]+ : options+}++// True when the provider row is a configured endpoint the backend may know+// more models for than the normal (non-refresh) options load probed: that+// load probes only the CURRENT custom provider, so a named custom_providers+// entry the user just switched to arrives empty until an explicit refresh.+function mayDiscoverModels(row: ModelOptionProvider | undefined): boolean {+ if (!row || row.authenticated === false || (row.models?.length ?? 0) > 0) {+ return false+ }++ return !!row.api_url || row.source === 'model-config' || row.is_user_defined === true+}++// Switching to a configured endpoint whose models list is empty triggers one+// refresh-scoped options fetch so the row populates without blocking the+// switch (#59063). The normal (non-refresh) load probes only the CURRENT+// custom provider, so a freshly-selected one arrives empty. On failure the+// selection stays empty and the user can still type a custom model id in+// ModelSelect.+function refreshEmptyProviderModels(+ slug: string,+ providers: readonly ModelOptionProvider[],+ scopeProfile: string | undefined,+ isCurrentEpoch: () => boolean,+ apply: (providers: ModelOptionProvider[]) => void+): void {+ if (!mayDiscoverModels(providers.find(p => catalogProviderMatches(p, slug)))) {+ return+ }++ getGlobalModelOptions({ refresh: true }, scopeProfile)+ .then(options => {+ if (isCurrentEpoch()) {+ apply(options.providers || [])+ }+ })+ .catch(() => {})+}++// User-driven provider switch for the main picker: a provider's model list is+// per-provider, so switching must not carry the previous provider's model+// over — ModelSelect's withActive() would keep painting it as a selectable+// row, and Apply would pin the new provider to the old provider's model+// (#59063). Programmatic switches (initial load, profile switch,+// activate-key auto-select) set state directly and keep their own model+// restore semantics.+function switchProviderFor(+ providers: readonly ModelOptionProvider[],+ scopeProfile: string | undefined,+ profileEpoch: { current: number },+ setCatalogProviders: (rows: ModelOptionProvider[]) => void,+ setSelectedProvider: Dispatch<SetStateAction<string>>,+ setSelectedModel: Dispatch<SetStateAction<string>>+) {+ return (slug: string) => {+ const epoch = profileEpoch.current++ setSelectedProvider((prev: string) => {+ if (prev === slug) {+ return prev+ }++ setSelectedModel('')+ return slug+ })++ refreshEmptyProviderModels(slug, providers, scopeProfile, () => profileEpoch.current === epoch, setCatalogProviders)+ }+}+// A slot is complete when both halves are chosen. Changing a slot's provider// intentionally clears its model (see updateMoaSlot), so every provider change// passes through an incomplete state while the user picks the new model.@@ -375,16 +457,20 @@ export function ModelSettings({ onMainModelChanged, scopeProfile, subpage }: Mod})const providerOptions = providers.length ? providers : NO_PROVIDERS+ const mainProviderOptions = mainProviderOptionsFor(providers, selectedProvider)- // Radix renders a blank trigger when the controlled value has no matching- // item. Keep a missing saved provider visible in the main selector while- // leaving it out of the real inventory used for readiness/setup metadata.- const mainProviderOptions = useMemo(+ // User-driven switch: never carries the old provider's model over (#59063).+ const switchProvider = useMemo(() =>- selectedProvider && !findCatalogProvider(providers, selectedProvider)- ? [{ name: selectedProvider, slug: selectedProvider, models: [] }, ...providers]- : providerOptions,- [providerOptions, providers, selectedProvider]+ switchProviderFor(+ providers,+ scopeProfile,+ profileEpoch,+ setCatalogProviders,+ setSelectedProvider,+ setSelectedModel+ ),+ [providers, scopeProfile])// MoA reference/aggregator slots must never be the moa virtual provider —@@ -689,7 +775,7 @@ export function ModelSettings({ onMainModelChanged, scopeProfile, subpage }: Mod// custom / local endpoint is NOT an OAuth provider, so it gets the dedicated// local-endpoint form (URL + optional API key) instead of being dead-ended// on the OAuth picker (the original "booted back to the first screen" loop).- const startProviderSetup = useCallback(() => {+ const startProviderSetup = () => {const rowSlug = selectedProviderRow?.slug.trim() ?? ''const slug = rowSlug || selectedProvider.trim()@@ -708,7 +794,7 @@ export function ModelSettings({ onMainModelChanged, scopeProfile, subpage }: Mod// provider picker instead of deep-linking an unknown or stale slug.startManualOnboarding(undefined, scopeProfile)}- }, [scopeProfile, selectedProvider, selectedProviderRow])+ }const applyMainModel = useCallback(async () => {if (!selectedProvider || !selectedModel) {@@ -911,7 +997,7 @@ export function ModelSettings({ onMainModelChanged, scopeProfile, subpage }: Mod<section><p className="mb-3 text-xs text-muted-foreground">{m.appliesDesc}</p><div className="flex flex-wrap items-center gap-2">- <Select onValueChange={setSelectedProvider} value={selectedProviderRow?.slug ?? selectedProvider}>+ <Select onValueChange={switchProvider} value={selectedProviderRow?.slug ?? selectedProvider}><SelectTrigger className={cn('min-w-40', CONTROL_TEXT)}><SelectValue placeholder={m.provider} /></SelectTrigger>diff --git a/apps/desktop/src/app/shell/model-catalog-menu.test.tsx b/apps/desktop/src/app/shell/model-catalog-menu.test.tsxindex 5ef59c5e6c0..a183c74a174 100644--- a/apps/desktop/src/app/shell/model-catalog-menu.test.tsx+++ b/apps/desktop/src/app/shell/model-catalog-menu.test.tsx@@ -397,6 +397,34 @@ describe('the catalog owns favorite models', () => {})})+describe('the current model the catalog omits (#57534)', () => {+ it('renders the current model as a selectable row when the provider catalog lacks it', async () => {+ getGlobalModelOptions.mockResolvedValue({+ providers: [{ models: ['openai/gpt-4o-mini'], name: 'OpenRouter', slug: 'openrouter' }]+ })++ renderMenu({ model: 'qwen/qwen-2.5-72b-instruct', provider: 'openrouter' })++ // The current model paints as its own family row (humanized name), ahead+ // of the catalog's families, and stays selectable.+ const row = (await screen.findByText('Qwen 2.5 72B Instruct')).closest('[role="menuitem"]')!++ expect(row.textContent).toContain('Qwen 2.5 72B Instruct')+ })++ it('does not inject the current model into a provider that is not the current one', async () => {+ // current.provider has no row; the model must not leak into another group.+ getGlobalModelOptions.mockResolvedValue({+ providers: [{ models: ['openai/gpt-4o-mini'], name: 'OpenRouter', slug: 'openrouter' }]+ })++ renderMenu({ model: 'qwen/qwen-2.5-72b-instruct', provider: 'nous' })++ await screen.findByText('GPT-4o-mini')+ expect(screen.queryByText('Qwen 2.5 72B Instruct')).toBeNull()+ })+})+describe('in-flight local downloads', () => {const DOWNLOAD_JOB: LocalRuntimeJob = {job_id: 'dl1',diff --git a/apps/desktop/src/app/shell/model-catalog-menu.tsx b/apps/desktop/src/app/shell/model-catalog-menu.tsxindex 50b3c9f64e7..393879070e7 100644--- a/apps/desktop/src/app/shell/model-catalog-menu.tsx+++ b/apps/desktop/src/app/shell/model-catalog-menu.tsx@@ -1319,7 +1319,20 @@ function groupModels(const groups: ProviderGroup[] = []for (const provider of providers) {- const allFamilies = collapseModelFamilies(provider.models ?? [])+ let allFamilies = collapseModelFamilies(provider.models ?? [])++ // The catalog row is a hint, not the authority: an OpenRouter current+ // model the returned catalog omits must still render and stay selectable,+ // or the picker has no active-model row at all (#57534). The backend+ // injects current_model into the row when it can, but the renderer cannot+ // rely on that — the row may arrive from a cache that predates the switch.+ if (+ catalogProviderMatches(provider, current.provider) &&+ current.model &&+ !allFamilies.some(family => family.id === current.model || family.fastId === current.model)+ ) {+ allFamilies = [{ fastId: null, id: current.model }, ...allFamilies]+ }if (allFamilies.length === 0) {continuediff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.pyindex 0f80c72c5d1..270b98cddac 100644--- a/hermes_cli/model_switch_providers.py+++ b/hermes_cli/model_switch_providers.py@@ -1047,27 +1047,53 @@ def _lap_user_provider_rows(b: _PickerBuild, user_providers: dict) -> None:def _lap_bare_custom_row(b: _PickerBuild, custom_providers: list | None) -> None:"""Section 3b: ``model.provider: custom`` + ``model.base_url`` with no namedproviders:/custom_providers row — surface it so /model does not look like it ignored- config.yaml."""- if not (b.current_provider_norm == "custom" and b.current_base_url and "custom" not in b.seen_slugs):+ config.yaml.++ The endpoint comes from the caller's current-provider slice when the session is on it,+ and otherwise from the static config.yaml ``model:`` block: the row used to appear only+ while it happened to be the active provider, so switching away made it vanish and the+ unconfigured-canonical fallback substituted a misleading 0-model placeholder (#59702).+ ``is_current`` is then true only when the caller's slice points back at this URL."""+ if "custom" in b.seen_slugs:return+ base_url = default_model = ""+ if b.current_provider_norm == "custom" and b.current_base_url:+ base_url = b.current_base_url+ default_model = b.current_model+ else:+ try:+ from hermes_cli.config import load_config+ cfg_model = load_config().get("model")+ except Exception: # health: allow BLE001 -- config.yaml may be user-edited or mid-migration; a read failure must degrade to "no row", never crash the picker+ cfg_model = None+ # config.model can be a bare string in older configs (see load_picker_context);+ # only a mapping carries a provider/base_url to recover here.+ if not isinstance(cfg_model, dict):+ return+ base_url = str(cfg_model.get("base_url") or "").strip()+ if str(cfg_model.get("provider") or "").strip().lower() != "custom" or not base_url:+ return+ default_model = str(cfg_model.get("default", cfg_model.get("name", "")) or "").strip()if any(- isinstance(cp, dict) and _norm_url(_entry_base_url(cp)) == _norm_url(b.current_base_url)+ isinstance(cp, dict) and _norm_url(_entry_base_url(cp)) == _norm_url(base_url)for cp in (custom_providers or [])):return- api_url = str(b.current_base_url).strip().rstrip("/")- models = [b.current_model] if b.current_model else []+ api_url = base_url.strip().rstrip("/")+ is_current = b.current_provider_norm == "custom" and b.current_base_url_norm == _norm_url(api_url)+ models = [default_model] if default_model else []native_catalog_empty = Falsetry:discovered, native_catalog_empty = _discover_endpoint_models("", api_url, "custom", False, headers=None, api_mode=None,- probe_live=bool(b.refresh or b.probe_current_custom_provider), discovery_allowed=True,+ probe_live=bool(b.refresh or (b.probe_current_custom_provider and is_current)),+ discovery_allowed=True,fast_custom_probe=b.resolved_fast_custom_probe)if discovered is not None:models = discoveredexcept Exception:passb.add_endpoint_row(- "custom", "Custom endpoint", api_url, models, True, native_catalog_empty,+ "custom", "Custom endpoint", api_url, models, is_current, native_catalog_empty,source="model-config", shown=_cap_models(models, b.max_models))diff --git a/tests/hermes_cli/test_bare_custom_picker_row.py b/tests/hermes_cli/test_bare_custom_picker_row.pynew file mode 100644index 00000000000..bdb28b2f769--- /dev/null+++ b/tests/hermes_cli/test_bare_custom_picker_row.py@@ -0,0 +1,90 @@+"""The bare ``model.provider: custom`` picker row must survive switching away.++The row is built from the session's current-provider slice when the session is+on it; otherwise it is recovered from the static config.yaml ``model:`` block+(#59702). Before that fallback existed the row vanished whenever a different+provider was active, and the unconfigured-canonical fallback substituted a+misleading 0-model placeholder in its place.+"""++import hermes_cli.providers as providers_mod+from hermes_cli.model_switch import list_authenticated_providers+++def test_bare_custom_row_survives_switching_away_from_it(monkeypatch):+ """Regression for #59702: the bare ``model.provider: custom`` row must not+ vanish from the picker when the session's current provider is a different+ one."""+ monkeypatch.setattr("agent.models_dev.fetch_models_dev", lambda: {})+ monkeypatch.setattr(providers_mod, "HERMES_OVERLAYS", {})+ monkeypatch.setattr(+ "hermes_cli.config.load_config",+ lambda: {+ "model": {"default": "gpt-4o", "provider": "custom", "base_url": "https://www.ccsub.net/v1"}+ },+ )+ # The config-sourced branch serves the warm cache / falls back to the+ # config default; keep the test hermetic — no live probe.+ monkeypatch.setattr("hermes_cli.models.fetch_api_models", lambda *_a, **_kw: [])+ monkeypatch.setattr("hermes_cli.models.cached_fetch_api_models", lambda *_a, **_kw: None)++ providers = list_authenticated_providers(+ current_provider="xai",+ current_base_url="",+ current_model="grok-4",+ user_providers={},+ custom_providers=[],+ probe_custom_providers=False,+ )++ bare_custom = next((p for p in providers if p["slug"] == "custom"), None)+ assert bare_custom is not None, "bare custom endpoint row vanished after switching provider"+ assert bare_custom["name"] == "Custom endpoint"+ assert bare_custom["is_current"] is False+ assert bare_custom["models"] == ["gpt-4o"], "config default model must seed the row when no probe runs"+ assert bare_custom["api_url"] == "https://www.ccsub.net/v1"+ assert bare_custom["source"] == "model-config"+++def test_bare_custom_row_config_fallback_defers_to_matching_named_entry(monkeypatch):+ """The config-sourced bare row must not duplicate a named custom_providers+ entry that already covers the same base_url (#59702)."""+ monkeypatch.setattr("agent.models_dev.fetch_models_dev", lambda: {})+ monkeypatch.setattr(providers_mod, "HERMES_OVERLAYS", {})+ monkeypatch.setattr(+ "hermes_cli.config.load_config",+ lambda: {+ "model": {"default": "gpt-4o", "provider": "custom", "base_url": "https://www.ccsub.net/v1"}+ },+ )++ providers = list_authenticated_providers(+ current_provider="xai",+ current_base_url="",+ current_model="grok-4",+ user_providers={},+ custom_providers=[{"name": "my-endpoint", "base_url": "https://www.ccsub.net/v1", "model": "gpt-4o"}],+ probe_custom_providers=False,+ )++ assert not any(p["slug"] == "custom" for p in providers)+ assert any(p["slug"] == "custom:my-endpoint" for p in providers)+++def test_bare_custom_row_config_fallback_tolerates_legacy_scalar_model(monkeypatch):+ """A legacy bare-string ``model:`` config value must not crash the picker+ (the ConfigContext loader already tolerates it)."""+ monkeypatch.setattr("agent.models_dev.fetch_models_dev", lambda: {})+ monkeypatch.setattr(providers_mod, "HERMES_OVERLAYS", {})+ monkeypatch.setattr("hermes_cli.config.load_config", lambda: {"model": "gpt-4o"})++ providers = list_authenticated_providers(+ current_provider="xai",+ current_base_url="",+ current_model="grok-4",+ user_providers={},+ custom_providers=[],+ probe_custom_providers=False,+ )++ assert not any(p["slug"] == "custom" for p in providers)