The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
import type { ModelOptionProvider, ModelOptionsResult, ModelPricing } from '@hermes/shared'
import {
DEFAULT_REASONING_EFFORT,
planBlocks,
sectionAt,
splitRecommended,
usageLevel,
usageTag
} from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { useQuery } from '@tanstack/react-query'
import {
createContext,
Fragment,
type ReactElement,
type ReactNode,
useContext,
useEffect,
useMemo,
useRef,
useState
} from 'react'
import { PlanLimitLine, UsageLevelTag } from '@/components/model-picker'
import { ProviderStatusChip } from '@/components/provider-status-chip'
import { Badge } from '@/components/ui/badge'
import { Codicon } from '@/components/ui/codicon'
import { DisclosureCaret } from '@/components/ui/disclosure-caret'
import {
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
dropdownMenuRow,
DropdownMenuSearch,
dropdownMenuSectionLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubTrigger
} from '@/components/ui/dropdown-menu'
import { HighlightMatches } from '@/components/ui/highlight-matches'
import { Skeleton } from '@/components/ui/skeleton'
import { Tip, TipHintLabel } from '@/components/ui/tooltip'
import type { HermesGateway } from '@/hermes'
import { useI18n } from '@/i18n'
import { triggerHaptic } from '@/lib/haptics'
import { isSubmitEnter } from '@/lib/ime'
import { catalogProviderMatches, modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'
import { displayModelName, modelDisplayParts } from '@/lib/model-status-label'
import { accountResetMs, formatReset, modelResetMs } from '@/lib/provider-limit'
import { reasoningEffortLabel } from '@/lib/reasoning-effort'
import { foldIncludes, normalize } from '@/lib/text'
import { cn } from '@/lib/utils'
import { $customModels, addCustomModel, customModelCandidate, withCustomModels } from '@/store/custom-models'
import { $favoriteModels, favoriteModelKey, toggleFavoriteModel } from '@/store/favorite-models'
import { $localModelsEnabled } from '@/store/local-models-flag'
import {
type LocalModelsOwner,
runningModelDownloads,
useLocalModelsOwner,
useLocalModelsStatus,
useLocalRuntimeJobs
} from '@/store/local-runtime-jobs'
import { $showModelPricing } from '@/store/model-pricing'
import {
$visibleModels,
collapseModelFamilies,
DEFAULT_VISIBLE_PER_PROVIDER,
effectiveVisibleKeys,
type ModelFamily,
modelVisibilityKey,
seedKnownModels,
setModelVisibilityOpen
} from '@/store/model-visibility'
import { $collapsedProviders, toggleCollapsedProvider } from '@/store/provider-collapse'
import { $defaultReasoningEffort } from '@/store/session'
import type { LocalModelLoadProgress, LocalRuntimeJob } from '@/types/hermes'
import { type FastControl, ModelEditSubmenu, resolveFastControl } from './model-edit-submenu'
import { ModelMenuRowIcon, useModelMenuRowDecoration } from './model-menu-row-decorations'
// Lets the host dropdown (model-pill, a kanban field trigger, …) hand the panel
// a way to dismiss itself so clicking a model row commits + closes, while the
// hover-revealed edit submenu (reasoning/fast) stays open to play with (its
// items preventDefault on select).
export const ModelMenuCloseContext = createContext<() => void>(() => {})
/** Compact per-row price: `$in/$out` per Mtok (cached read appended when the
* provider ships it), "free", and a sale tag when the portal reports a
* discounted list price. Rendered only when the provider's payload carries
* pricing (Nous Portal and others that ship it). */
function ModelPrice({ pricing }: { pricing: ModelPricing }) {
const { t } = useI18n()
const copy = t.shell.modelMenu
// Partial payloads: `_apply_pricing` ships "" for unknown, but a provider
// can report null — render nothing rather than "null/null" or "—/—".
const input = pricing.input || null
const output = pricing.output || null
// Cached-input rate (`cache`, from the backend's `input_cache_read`); the
// inline `input` rate is the uncached read, so together they cover the
// cached-vs-uncached comparison without a tooltip round-trip (#63125).
const cache = pricing.cache || null
if (pricing.free) {
return <span className="shrink-0 pl-2 text-[0.625rem] text-(--ui-green)">{copy.free}</span>
}
if (!input && !output) {
return null
}
const discount =
typeof pricing.discount_percent === 'number' && pricing.discount_percent > 0 ? pricing.discount_percent : null
return (
<span
className="flex shrink-0 items-center gap-1.5 pl-2 text-[0.625rem] tabular-nums text-(--ui-text-tertiary)"
title={copy.priceTitle(input ?? '—', output ?? '—', cache ?? '')}
>
<span>
{input ?? '—'}/{output ?? '—'}
</span>
{cache ? (
<span className="text-(--ui-text-quaternary)" title={`${copy.cacheRead} ${cache}/Mtok`}>
·{cache}
</span>
) : null}
{discount ? (
<span className="rounded bg-(--ui-green)/10 px-1 py-px font-medium text-(--ui-green)">−{discount}%</span>
) : null}
</span>
)
}
/** One model choice, everything a caller needs to act on a selection.
* `effort` is '' for "inherit the default" and 'none' for thinking off. */
export interface ModelChoice {
effort: string
/** `effort` is not reported yet, so '' is unknown rather than the default (#79807). */
effortPending?: boolean
/** Level the route actually sends for `effort` (`session.info.reasoning_effort_wire`); '' = unknown. */
effortWire?: string
fast: boolean
serviceTier?: string
model: string
provider: string
}
/**
* What a surface DOES with the catalog. The menu renders and navigates; the
* controller owns meaning — the composer writes through to a live session,
* the kanban override just holds a value in dialog state.
*
* `presetFor` supplies the remembered settings shown on a non-active row.
* Returning `{}` is fine — the row then shows Hermes' defaults.
*/
export interface ModelMenuController {
/** Detached task pickers can edit effort but have no speed write path. */
allowSpeed?: boolean
/** Restore a model's remembered settings after it is selected. Separate from
* `setOptions` because it is one atomic "apply this model's preset" write,
* not a user editing one control — surfaces that write through to a session
* need to batch it. Values are already capability-gated by the menu. */
applyPreset: (
preset: { effort?: string; fast?: boolean; serviceTier?: string },
row: { model: string; provider: string }
) => void
current: ModelChoice
presetFor: (provider: string, model: string) => { effort?: string; fast?: boolean; serviceTier?: string }
/** Commit a model row. Return false to abort (a failed session switch). */
select: (model: string, provider: string) => Promise<boolean | void> | void
/** Edit ONE option on a row. `isActive` says whether it's the current model. */
setOptions: (
patch: { effort?: string; fast?: boolean; serviceTier?: string },
row: { isActive: boolean; model: string; provider: string }
) => void
}
interface ModelCatalogMenuProps {
controller: ModelMenuController
/** Rows appended under the catalog (Refresh Models, Edit Models, …). */
footer?: ReactNode
/** Rows above the search, outside the keyboard list (the local-setup offer). */
header?: ReactNode
gateway?: HermesGateway
/** Owner-routed RPC for catalog reads. Preferred over `gateway.request` so
* a tile's menu queries the session owner's backend, not chrome's. */
request?: <T>(method: string, params?: Record<string, unknown>) => Promise<T>
/** Render the virtual `moa` provider's presets as a selectable section.
* Off for override surfaces, where a MoA preset isn't a worker model. */
includeMoa?: boolean
/** Registry source owning this catalog. Profile/session names are not unique
* across sources, so this participates in the React Query cache key. */
ownerConnectionId?: string
profile?: string
/** Session whose catalog to fetch. A live session's catalog can differ from
* the profile-global one, and the app invalidates the SESSION-scoped query
* key on model changes — a surface bound to a session must pass it or its
* menu goes stale. Detached surfaces (per-task overrides) omit it. */
sessionId?: null | string
}
interface ProviderGroup {
families: ModelFamily[]
provider: ModelOptionProvider
}
function queryErrorMessage(error: unknown): null | string {
return error ? (error instanceof Error ? error.message : String(error)) : null
}
function useDownloadRows(owner: LocalModelsOwner, localModelsEnabled: boolean) {
const downloadsKey: string = useLocalRuntimeJobs(
owner,
(jobs: readonly LocalRuntimeJob[]): string =>
localModelsEnabled
? runningModelDownloads(jobs)
.map(job => `${job.job_id}\u0000${job.target}`)
.join('\u0001')
: '',
localModelsEnabled
)
return useMemo(
() =>
downloadsKey === ''
? []
: downloadsKey.split('\u0001').map(pair => {
const [jobId, target] = pair.split('\u0000')
return { jobId, target }
}),
[downloadsKey]
)
}
/**
* THE model catalog menu: searchable, provider-grouped, `-fast` families
* collapsed to one row, per-row hover submenu for thinking/effort/fast, full
* keyboard selection. Shared verbatim by the composer's model pill and by
* plugin surfaces that pick a model without a session behind it — so the two
* can never drift apart.
*/
// health: allow CC -- usage-window plans: section headings and the limit line in the existing list render; this component was over target on main
export function ModelCatalogMenu({
controller,
footer,
header,
gateway,
includeMoa = false,
ownerConnectionId,
profile = 'default',
request,
sessionId = null
}: ModelCatalogMenuProps): ReactElement {
const { t } = useI18n()
const copy = t.shell.modelMenu
const copyPicker = t.modelPicker
const closeMenu = useContext(ModelMenuCloseContext)
const [search, setSearch] = useState<string>('')
// "Add custom model…" turns the search box into slug entry: the catalog
// steps aside until something is typed, and the placeholder says what to
// type. Typing a slug without this works too; the row just makes it findable.
const [slugEntry, setSlugEntry] = useState(false)
const searchRef = useRef<HTMLInputElement>(null)
const collapsedProviders = useStoreCollapsed()
const defaultEffort = useDefaultEffort()
// Which models the user curated in Edit Models. Read HERE rather than taken
// as a prop: it's one global preference, so every surface that shows a
// catalog must show the same shortlist. A per-caller opt-in is how the board
// and the composer would end up disagreeing about what "my models" means.
const visibleModels = useStore($visibleModels)
const customModels = useStore($customModels)
// Favorite models, same reasoning as the shortlist above: one global
// preference owned by the catalog, so the composer pill, session tiles and
// the kanban override all show the same Favorites section.
const favoriteKeys = useStore($favoriteModels)
const modelOptions = useQuery({
queryKey: modelOptionsQueryKey(profile, sessionId, ownerConnectionId),
// Gateway-first even with no session: a connected (possibly remote)
// gateway owns the model catalog, including virtual providers the local
// REST fallback can't know about (#53817).
queryFn: (): Promise<ModelOptionsResult> => requestModelOptions({ gateway, profile, request, sessionId }),
refetchOnMount: query => nousRefetchOnMount(query.state.data),
refetchInterval: query => nousPricingPoll(query.state.data, query.state.dataUpdateCount)
})
const loading = modelOptions.isPending && !modelOptions.data
// Every local-models read in this menu sits behind the --local launch
// flag: no status polling, no download rows, and the llamacpp provider
// group hides even when models are staged (the flag is strict).
const localModelsEnabled = $localModelsEnabled.get()
// Live load state for the managed local server: which model is loading
// into memory right now, with a REAL percent (per-tensor callback relayed
// over the router's SSE stream). Polled only while this menu is mounted
// (it unmounts on close); errors read as "nothing loading" — remote-only
// installs have no local-models routes.
const owner: LocalModelsOwner = useLocalModelsOwner(profile, ownerConnectionId)
const localStatus = useLocalModelsStatus(owner, localModelsEnabled, true)
const loadingModels: Record<string, LocalModelLoadProgress> = localStatus.data?.loading ?? {}
// Models on their way into the local library (downloads + quickstart runs
// still fetching bytes) — rendered as disabled progress rows so the user
// sees the model coming instead of wondering where it went. The jobs store
// republishes every ~700ms with fresh byte counts while anything runs; a
// whole-store subscription here would re-render the entire menu per tick
// (breaking open submenus and focus — the #72163 class). Subscribe to a
// STABLE identity projection instead: it changes only when a download
// starts or ends. Each row selects its own percent scalar.
const downloads = useDownloadRows(owner, localModelsEnabled)
const error = queryErrorMessage(modelOptions.error)
const providers = modelOptions.data?.providers
// The catalog carries MoA presets as a virtual `moa` provider row. Keep it
// out of the main groups so presets never show up twice.
const moaPresets = useMemo(
() => (includeMoa ? (providers?.find(p => p.slug.toLowerCase() === 'moa')?.models ?? []) : []),
[providers, includeMoa]
)
const pickerProviders = useMemo(
() =>
withCustomModels(
providers?.filter(
provider =>
provider.slug.toLowerCase() !== 'moa' &&
// Strict --local gate: staged local models exist on disk, but
// without the flag the GUI doesn't offer them.
(localModelsEnabled || provider.slug !== LOCAL_PROVIDER_SLUG)
) ?? [],
customModels
),
[providers, localModelsEnabled, customModels]
)
const current = controller.current
const q = normalize(search)
// In-flight downloads render inside the Local provider group when it
// exists, else as their own trailing 'Local' group (first download —
// nothing staged yet, so the catalog has no local provider row).
const shownDownloads = q ? downloads.filter(job => foldIncludes(job.target || '', q)) : downloads
const hasLocalGroup = pickerProviders.some(provider => provider.slug === LOCAL_PROVIDER_SLUG)
// Resolve visibility HERE, against the catalog we actually fetched: an empty
// provider list would otherwise resolve to an empty key set that reads as
// "user hid everything" and blanks the menu on first open.
useEffect(() => seedKnownModels(pickerProviders), [pickerProviders])
const shownKeys = useMemo(
() => effectiveVisibleKeys(visibleModels, pickerProviders),
[visibleModels, pickerProviders]
)
// Favorites paint their own section ABOVE the provider groups — the whole
// point of starring one. Resolved against the catalog we actually fetched,
// so a favorite whose provider is not connected (or whose model the lab
// retired) has no row to show; it is KEPT, not dropped, for when it returns.
// Favorites ignore the Edit Models shortlist on purpose: a star IS an
// explicit "always show me this one". A search turns the section off — a
// query means "show me every match", listed in their provider's place.
const favoriteRows = useMemo(
() => (q ? [] : resolveFavoriteRows(pickerProviders, favoriteKeys)),
[pickerProviders, favoriteKeys, q]
)
// The same rows are dropped from the provider groups, so no model is ever
// listed twice in one open menu. Not while searching: a query lists every
// match in its provider's place.
const favoriteSet = useMemo(() => new Set(favoriteKeys), [favoriteKeys])
// Favorites that mix providers name each provider once, as a quiet label
// over its rows (two labs can serve the same model name). With one provider
// the label would only repeat the section.
const favoritesSpanProviders = new Set(favoriteRows.map(row => row.provider.slug)).size > 1
const groups = useMemo(
() =>
groupModels(
pickerProviders,
search,
{ model: current.model, provider: current.provider },
shownKeys,
q ? null : favoriteSet
),
[pickerProviders, search, current.model, current.provider, shownKeys, q, favoriteSet]
)
// Presets are searchable rows like everything else — an unfiltered preset
// sitting under zero model matches would otherwise become the "first match"
// Enter commits.
const shownMoaPresets = useMemo(
() => (q ? moaPresets.filter(preset => foldIncludes(`moa ${preset}`, q)) : moaPresets),
[moaPresets, q]
)
const hideCatalog = slugEntry && !search
// The scrolling catalog list only mounts when it has rows; otherwise a
// section below it (MoA, custom slug) would sit under two separators.
// Favorites count: a catalog whose every curated family is starred has
// groups but no group rows, and the section must still paint.
const hasList = !hideCatalog && (groups.length > 0 || shownDownloads.length > 0 || favoriteRows.length > 0)
// A typed id no provider lists is still a model to the backend. Offer it as
// a row per configured provider (the current one first) so a slug the
// catalog lacks is one Enter away, then remember it as a normal row. While
// the query still matches catalog rows the section stays out of the way
// unless the user asked for it via "Add custom model…".
const customSlug =
slugEntry || (!hasList && shownMoaPresets.length === 0) ? customModelCandidate(search, pickerProviders) : null
const customProviders = useMemo(
() =>
customSlug
? pickerProviders
.filter(provider => (provider.models ?? []).length > 0)
.sort(
(a, b) =>
Number(catalogProviderMatches(b, current.provider)) -
Number(catalogProviderMatches(a, current.provider))
)
: [],
[customSlug, pickerProviders, current.provider]
)
const selectFamily = async (family: ModelFamily, provider: ModelOptionProvider): Promise<boolean> => {
const caps = provider.capabilities?.[family.id]
const preset = controller.presetFor(provider.slug, family.id)
// Variant-fast models (no speed param) express "fast" as a separate `-fast`
// id, so honor the remembered preset by selecting that sibling. Param-fast
// is applied through setOptions below instead.
const variantFast = !(caps?.fast ?? false) && !!family.fastId
const targetId = variantFast && preset.fast === true ? family.fastId! : family.id
if ((await controller.select(targetId, provider.slug)) === false) {
return false
}
const rememberedTier = preset.serviceTier ?? (preset.fast ? 'priority' : 'normal')
const tier =
rememberedTier === 'ultrafast'
? caps?.ultrafast
? 'ultrafast'
: 'normal'
: rememberedTier === 'priority' && caps?.fast
? 'priority'
: 'normal'
controller.applyPreset(
{
effort: (caps?.reasoning ?? true) ? (preset.effort ?? defaultEffort) : undefined,
...(controller.allowSpeed !== false ? { serviceTier: tier, fast: tier !== 'normal' } : {})
},
{ model: family.id, provider: provider.slug }
)
return true
}
const selectMoaPreset = async (preset: string) => {
if ((await controller.select(preset, 'moa')) === false) {
return
}
closeMenu()
}
const selectCustom = async (slug: string, provider: ModelOptionProvider) => {
if (!(await selectFamily({ fastId: null, id: slug }, provider))) {
return
}
addCustomModel(provider.slug, slug, provider)
closeMenu()
}
// ── Keyboard selection (cmdk semantics on a Radix menu) ───────────────────
// One flat list mirroring EXACTLY what's rendered (Favorites section,
// collapse, filter, presets), so the selection can never sit on a hidden row.
type KbRow =
| { key: string; kind: 'custom'; provider: ModelOptionProvider; slug: string }
| { family: ModelFamily; key: string; kind: 'family'; provider: ModelOptionProvider }
| { key: string; kind: 'moa'; preset: string }
const kbRows = useMemo<KbRow[]>(
() => [
...favoriteRows.map(({ family, provider }): KbRow => ({
family,
key: `${provider.slug}:${family.id}`,
kind: 'family',
provider
})),
...groups.flatMap(group =>
collapsedProviders.includes(group.provider.slug) && !search
? []
: group.families.map((family): KbRow => ({
family,
key: `${group.provider.slug}:${family.id}`,
kind: 'family',
provider: group.provider
}))
),
...shownMoaPresets.map((preset): KbRow => ({ key: `moa:${preset}`, kind: 'moa', preset })),
...(customSlug
? customProviders.map((provider): KbRow => ({
key: `custom:${provider.slug}`,
kind: 'custom',
provider,
slug: customSlug
}))
: [])
],
[favoriteRows, groups, collapsedProviders, search, shownMoaPresets, customSlug, customProviders]
)
// The row the arrows (or a Shift+Enter star) last put the highlight on,
// held by KEY: a starred row moves into or out of Favorites, and the
// highlight follows it rather than staying on the old index.
const [kbOverride, setKbOverride] = useState<null | string>(null)
// Searchable DropdownMenu rows already cancel Radix's hover-to-focus while
// the search owns focus (#53980). Keep rows hit-testable so the first
// deliberate click works even before the pointer has moved (#123040).
const rowIsCurrent = (row: KbRow) =>
row.kind === 'moa'
? current.provider === 'moa' && row.preset === current.model
: row.kind === 'custom'
? false
: catalogProviderMatches(row.provider, current.provider) &&
(row.family.id === current.model || row.family.fastId === current.model)
const autoIndex = q ? (kbRows.length > 0 ? 0 : -1) : kbRows.findIndex(row => rowIsCurrent(row))
const overrideIndex = kbOverride === null ? -1 : kbRows.findIndex(row => row.key === kbOverride)
const kbIndex = overrideIndex >= 0 ? overrideIndex : autoIndex
const kbActiveKey = kbIndex >= 0 ? kbRows[kbIndex].key : null
const stepKb = (delta: -1 | 1) => {
if (kbRows.length === 0) {
return
}
const from = kbIndex >= 0 ? kbIndex : delta === 1 ? -1 : 0
setKbOverride(kbRows[(from + delta + kbRows.length) % kbRows.length].key)
}
const commitKbRow = () => {
const row = kbIndex >= 0 ? kbRows[kbIndex] : undefined
if (!row) {
return
}
if (row.kind === 'moa') {
void selectMoaPreset(row.preset)
return
}
if (row.kind === 'custom') {
void selectCustom(row.slug, row.provider)
return
}
if (!rowIsCurrent(row)) {
void selectFamily(row.family, row.provider)
}
closeMenu()
}
// Shift+Enter stars the highlighted model — the keyboard twin of
// shift-clicking a row. Pinning the highlight to its key lets it follow
// the row to its new slot.
const toggleKbFavorite = () => {
const row = kbIndex >= 0 ? kbRows[kbIndex] : undefined
if (row?.kind !== 'family') {
return
}
setKbOverride(row.key)
triggerHaptic('selection')
toggleFavoriteModel(row.provider.slug, row.family.id)
}
// ── Keyboard path into a row's edit submenu (#86966) ─────────────────────
// Rows are HIGHLIGHTED, not DOM-focused (focus stays in the search input so
// typing keeps working), which is why Radix's own ArrowRight-on-the-trigger
// never fires. ArrowRight therefore hands focus to the highlighted trigger
// and replays the key there: from that point Radix owns everything — opening
// the sub, focusing its first item, and returning focus to the trigger when
// ArrowLeft closes it. `handleSubOpenChange` below finishes that round trip
// by putting focus back in the search field. (Escape is not part of it:
// inside a sub, Radix dismisses the WHOLE menu rather than just the sub.)
//
// ArrowRight is hard-coded rather than direction-aware because Radix's own
// binding is: the app installs no `DirectionProvider` and passes no `dir`,
// so `useDirection` resolves to `ltr` and Radix opens subs on ArrowRight in
// every locale, RTL included. Matching that keeps the two in step; whoever
// wires up a `DirectionProvider` has to teach this handler the same
// direction Radix reads, or the sub goes unreachable again in Arabic.
// WHICH row we opened from the keyboard, not merely THAT we opened one: a
// bare flag is still set when a keyboard-opened sub closes because the mouse
// moved on to another row, and refocusing search there pulls focus out from
// under a pointer interaction that has already taken the menu over.
const keyboardSubRef = useRef<null | { key: string; trigger: HTMLElement }>(null)
const openActiveSubmenu = (): boolean => {
const trigger = listRef.current?.querySelector<HTMLElement>('[data-kb-active]')
if (!trigger || !kbActiveKey) {
return false
}
keyboardSubRef.current = { key: kbActiveKey, trigger }
trigger.focus()
trigger.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowRight' }))
// Highlight also lands on rows that are plain items rather than submenu
// triggers (the MoA presets), which swallow the key; an open can also be
// interrupted. Either way, don't strand focus on a row where typing no
// longer reaches the search field.
requestAnimationFrame(() => {
// Only while the claim is still ours and untouched: a sub that opened
// and closed inside this one frame has already been handled below, and
// a stale frame reaching in afterwards would move focus twice.
if (keyboardSubRef.current?.trigger !== trigger) {
return
}
if (trigger.getAttribute('data-state') !== 'open') {
keyboardSubRef.current = null
searchRef.current?.focus()
}
})
return true
}
// Only the sub THIS row opened from the keyboard owes focus back to the
// search field; during mouse use focus never left it, and hover open/close
// fires constantly.
const handleSubOpenChange = (open: boolean, key: string) => {
const claim = keyboardSubRef.current
if (open || claim?.key !== key) {
return
}
keyboardSubRef.current = null
// Deferred one frame because Radix restores focus to the trigger straight
// AFTER this callback — and that restore is the signal we need. Radix does
// it only for a keyboard close (ArrowLeft); a sub closed because the
// pointer moved to another row leaves focus where it fell, and grabbing it
// then would fight the mouse. So finish the round trip only if the trigger
// really is holding focus.
requestAnimationFrame(() => {
if (document.activeElement === claim.trigger) {
searchRef.current?.focus()
}
})
}
// Keep the selected row in view while arrowing through the scrollable list. Window plans open at
// the top (their Recommended picks); the current row stays highlighted and is scrolled to once the
// user arrows or searches. Every other account keeps opening on the current model.
const listRef = useRef<HTMLDivElement>(null)
const opensAtTop = Boolean(providers?.some(p => p.plan_usage))
const followKb = !opensAtTop || kbOverride !== null || Boolean(q)
useEffect(() => {
if (followKb) {
listRef.current?.querySelector('[data-kb-active]')?.scrollIntoView({ block: 'nearest' })
}
}, [followKb, kbActiveKey])
const kbRowProps = (key: string) => {
const active = kbActiveKey === key
return {
className: cn(dropdownMenuRow, active && 'bg-(--ui-control-active-background) text-foreground'),
...(active ? { 'data-kb-active': '' } : {})
}
}
return (
<>
{header}
<DropdownMenuSearch
aria-label={copy.search}
onKeyDown={event => {
// Claim arrows and Enter from Radix so DOM focus stays in the input
// and Enter commits the highlighted row without a DownArrow first.
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault()
event.stopPropagation()
stepKb(event.key === 'ArrowDown' ? 1 : -1)
} else if (isSubmitEnter(event) && event.shiftKey) {
event.preventDefault()
event.stopPropagation()
toggleKbFavorite()
} else if (isSubmitEnter(event)) {
event.preventDefault()
event.stopPropagation()
commitKbRow()
} else if (event.key === 'ArrowRight' && caretAtEnd(event.currentTarget)) {
// Claimed only with the caret parked at the end of the query, where
// ArrowRight has nothing left to do as a text cursor.
if (openActiveSubmenu()) {
event.preventDefault()
event.stopPropagation()
}
}
}}
onValueChange={value => {
setSearch(value)
setKbOverride(null)
}}
placeholder={slugEntry ? copyPicker.customModelPlaceholder : copy.search}
ref={searchRef}
value={search}
/>
{!hideCatalog && <DropdownMenuSeparator className="mx-0" />}
{hideCatalog ? null : loading ? (
<DropdownMenuGroup className="py-1">
{Array.from({ length: 4 }, (_, index) => (
<DropdownMenuItem
className={dropdownMenuRow}
disabled
key={index}
onSelect={event => event.preventDefault()}
>
<Skeleton className="h-4 w-full" />
</DropdownMenuItem>
))}
</DropdownMenuGroup>
) : error ? (
<DropdownMenuItem className={dropdownMenuRow} disabled>
{error}
</DropdownMenuItem>
) : groups.length === 0 &&
favoriteRows.length === 0 &&
moaPresets.length === 0 &&
shownDownloads.length === 0 &&
!customSlug ? (
<DropdownMenuItem className={dropdownMenuRow} disabled>
{copy.noModels}
</DropdownMenuItem>
) : hasList ? (
<div className="max-h-[max(150px,30dvh)] overflow-y-auto py-0.5" ref={listRef}>
{/* Favorites first — the shortcut the star exists for. The section
paints nothing with no favorites, and nothing while searching,
where every match is listed in its provider's place instead. */}
{favoriteRows.length > 0 ? (
<DropdownMenuGroup className="py-0.5">
<DropdownMenuLabel className={catalogGroupLabel}>{copy.favorites}</DropdownMenuLabel>
{favoriteRows.map(({ family, provider }, index) => (
<Fragment key={`${provider.slug}:${family.id}`}>
{favoritesSpanProviders && favoriteRows[index - 1]?.provider.slug !== provider.slug ? (
<DropdownMenuLabel className={favoriteProviderLabel}>{provider.name}</DropdownMenuLabel>
) : null}
<ModelFamilyRow
controller={controller}
current={current}
defaultEffort={defaultEffort}
family={family}
favorite
kbProps={kbRowProps(`${provider.slug}:${family.id}`)}
loadingModels={loadingModels}
onSelect={selectFamily}
onSubOpenChange={handleSubOpenChange}
provider={provider}
search={search}
/>
</Fragment>
))}
</DropdownMenuGroup>
) : null}
{groups.map(group => {
const slug = group.provider.slug
// Collapsed when the user stored it (and not while searching, which
// spans every model regardless of collapse state).
const collapsed = collapsedProviders.includes(slug) && !search
return (
<DropdownMenuGroup className="py-0.5" key={slug}>
<DropdownMenuItem
className={cn(
catalogGroupLabel,
'group/label flex w-full cursor-pointer items-center gap-1 !bg-transparent focus:!bg-transparent'
)}
onSelect={event => {
event.preventDefault()
toggleCollapsedProvider(slug)
}}
textValue=""
>
<span className="truncate">
<HighlightMatches foldSeparators query={search} text={group.provider.name} />
</span>
<DisclosureCaret
className="shrink-0 text-(--ui-text-tertiary) opacity-0 transition group-hover/label:opacity-100"
open={!collapsed}
size="0.625rem"
/>
<ProviderStatusChip className="ml-auto mr-0.5" provider={group.provider} />
</DropdownMenuItem>
{/* Window plans past an allowance: one line saying what happens next (pay as you go
or wait for the reset) instead of a note on every row. */}
{!collapsed && !search ? <PlanLimitLine className="px-2 pb-1" provider={group.provider} /> : null}
{!collapsed &&
group.families.map((family, familyIdx) => (
<Fragment key={`${group.provider.slug}:${family.id}`}>
{!search && sectionTitle(group, familyIdx, copyPicker) ? (
<DropdownMenuLabel className="px-2 pb-0.5 pt-1.5 text-[0.6rem] font-medium uppercase tracking-wide text-(--ui-text-tertiary)">
{sectionTitle(group, familyIdx, copyPicker)}
</DropdownMenuLabel>
) : null}
<ModelFamilyRow
controller={controller}
current={current}
defaultEffort={defaultEffort}
family={family}
favorite={favoriteSet.has(favoriteModelKey(group.provider.slug, family.id))}
kbProps={kbRowProps(`${group.provider.slug}:${family.id}`)}
loadingModels={loadingModels}
onSelect={selectFamily}
onSubOpenChange={handleSubOpenChange}
provider={group.provider}
search={search}
/>
</Fragment>
))}
{!collapsed &&
slug === LOCAL_PROVIDER_SLUG &&
shownDownloads.map(job => (
<DownloadingModelRow jobId={job.jobId} key={job.jobId} owner={owner} target={job.target} />
))}
</DropdownMenuGroup>
)
})}
{!hasLocalGroup && shownDownloads.length > 0 && (
<DropdownMenuGroup className="py-0.5" key="local-downloads">
<DropdownMenuLabel className={catalogGroupLabel}>{copyPicker.localDownloadsHeading}</DropdownMenuLabel>
{shownDownloads.map(job => (
<DownloadingModelRow jobId={job.jobId} key={job.jobId} owner={owner} target={job.target} />
))}
</DropdownMenuGroup>
)}
</div>
) : null}
{!hideCatalog && shownMoaPresets.length > 0 ? (
<div>
{hasList ? <DropdownMenuSeparator className="mx-0" /> : null}
<DropdownMenuLabel className={dropdownMenuSectionLabel}>MoA presets</DropdownMenuLabel>
{shownMoaPresets.map(preset => {
const isCurrentMoa = current.provider === 'moa' && current.model === preset
return (
<DropdownMenuItem
key={`moa:${preset}`}
onSelect={event => {
event.preventDefault()
void selectMoaPreset(preset)
}}
{...kbRowProps(`moa:${preset}`)}
>
<span className="min-w-0 flex-1 truncate">
MoA: <HighlightMatches foldSeparators query={search} text={preset} />
</span>
{isCurrentMoa ? <Codicon className="ml-auto text-foreground" name="check" size="0.75rem" /> : null}
</DropdownMenuItem>
)
})}
</div>
) : null}
{customSlug && customProviders.length > 0 ? (
<div>
{hasList || shownMoaPresets.length > 0 ? <DropdownMenuSeparator className="mx-0" /> : null}
<DropdownMenuLabel className={dropdownMenuSectionLabel}>{copyPicker.customModel}</DropdownMenuLabel>
{customProviders.map(provider => (
<DropdownMenuItem
key={`custom:${provider.slug}`}
onSelect={event => {
event.preventDefault()
void selectCustom(customSlug, provider)
}}
{...kbRowProps(`custom:${provider.slug}`)}
>
<span className="min-w-0 flex-1 truncate">
{customSlug}
<span className="text-(--ui-text-tertiary)"> {provider.name}</span>
</span>
</DropdownMenuItem>
))}
</div>
) : null}
{/* Curation belongs to the catalog, not to one host: wherever you can
pick a model you can say which models you want, and the shortlist is
the same everywhere because it's one stored preference. It shares the
host footer's group rather than opening a second one, so a host that
contributes rows (the composer's Refresh Models) keeps the single
trailing block it has always rendered. */}
<DropdownMenuSeparator className="mx-0" />
{footer}
<DropdownMenuItem
className={cn(dropdownMenuRow, 'text-(--ui-text-tertiary)', slugEntry && 'text-foreground')}
onSelect={event => {
event.preventDefault()
setSearch('')
setKbOverride(null)
setSlugEntry(true)
// Radix hands focus back to the row after onSelect; refocus after.
window.setTimeout(() => searchRef.current?.focus(), 0)
}}
>
<Codicon name="add" size="0.75rem" />
{copyPicker.addCustomModelAction}
</DropdownMenuItem>
<DropdownMenuItem
className={cn(dropdownMenuRow, 'text-(--ui-text-tertiary)')}
onSelect={() => setModelVisibilityOpen(true)}
>
<Codicon name="settings-gear" size="0.75rem" />
{copy.editModels}
</DropdownMenuItem>
</>
)
}
/** Re-exported so callers building a footer row match the catalog's rows. */
export { dropdownMenuRow }
/** Row props the flat keyboard selection paints onto whichever trigger is
* active — shared by the Favorites section and the provider groups. */
interface KbRowProps {
'data-kb-active'?: string
className: string
}
/** One favorite model, resolved against the live catalog. */
interface FavoriteRow {
family: ModelFamily
provider: ModelOptionProvider
}
/** Resolve stored favorites into paintable rows, in the order the user
* starred them, gathered under the provider each first appeared with so the
* section can name a provider once rather than on every row. A key with no
* family in THIS catalog yields no row — and is not dropped, so it comes back
* when its provider reconnects. */
function resolveFavoriteRows(providers: readonly ModelOptionProvider[], keys: readonly string[]): FavoriteRow[] {
const byKey = new Map<string, FavoriteRow>()
for (const provider of providers) {
for (const family of collapseModelFamilies(provider.models ?? [])) {
byKey.set(favoriteModelKey(provider.slug, family.id), { family, provider })
}
}
const byProvider = new Map<string, FavoriteRow[]>()
for (const key of keys) {
const row = byKey.get(key)
if (row) {
byProvider.set(row.provider.slug, [...(byProvider.get(row.provider.slug) ?? []), row])
}
}
return [...byProvider.values()].flat()
}
interface ModelFamilyRowProps {
controller: ModelMenuController
current: ModelChoice
defaultEffort: string
family: ModelFamily
/** Whether this model is starred — paints the filled star. */
favorite: boolean
/** Keyboard/hover props built by the host, so the Favorites section and
* the provider groups share ONE flat selection order. */
kbProps: KbRowProps
loadingModels: Record<string, LocalModelLoadProgress>
/** Commit this family — what a click means belongs to the host that owns it. */
onSelect: (family: ModelFamily, provider: ModelOptionProvider) => Promise<boolean | void> | void
/** Keyboard-focus round trip for the sub this row opens (#86966). */
onSubOpenChange?: (open: boolean, key: string) => void
provider: ModelOptionProvider
search: string
}
/** One model family row: the favorite star, the trigger that commits the
* model, plus the hover-revealed options submenu. Shared by the Favorites
* section and the provider groups, so the two can never paint a model
* differently. */
// health: allow CC -- usage-window plans: the Large/Free tag replaces the price on tagged rows; this row was over target on main
function ModelFamilyRow({
controller,
current,
defaultEffort,
family,
favorite,
kbProps,
loadingModels,
onSelect,
onSubOpenChange,
provider,
search
}: ModelFamilyRowProps): ReactElement {
const { t } = useI18n()
const copy = t.shell.modelMenu
const copyPicker = t.modelPicker
const closeMenu = useContext(ModelMenuCloseContext)
const showPricing = useStore($showModelPricing)
const rowKey = `${provider.slug}:${family.id}`
// The active id may be the base or its -fast sibling; either way this one
// family row represents both.
const activeId =
catalogProviderMatches(provider, current.provider) &&
(current.model === family.id || current.model === family.fastId)
? current.model
: null
const isCurrent = activeId !== null
const { name, tag } = modelDisplayParts(family.id)
const decoration = useModelMenuRowDecoration({ label: name, model: family.id, provider: provider.slug })
const caps = provider.capabilities?.[family.id]
const limit = familyLimit(provider, family, isCurrent)
// Live per-model $/Mtok pricing (Nous Portal and other providers that ship
// it). A `-fast` sibling shares the base id's price: the collapsed row
// fronts the base, so fall back to it when only the fast variant is unpriced.
const pricing = provider.pricing?.[family.id] ?? (family.fastId ? provider.pricing?.[family.fastId] : undefined)
// Window plans: no price (the plan covers it); the tag shows only for Large / Free.
const rowLevel = usageLevel(provider, family.id)
// Managed local model loading into memory right now: real load percent,
// keyed by exact model id (remote providers never collide with GGUF stems).
const loadProgress = loadingModels[family.id] ?? (family.fastId ? loadingModels[family.fastId] : undefined)
// Effective settings for this row: the live choice when it's the active
// model, otherwise its remembered preset. Row label AND submenu read from
// these so they never disagree.
const preset = controller.presetFor(provider.slug, family.id)
const effEffort = isCurrent ? current.effort : (preset.effort ?? '')
const effFast = isCurrent ? current.fast : (preset.fast ?? false)
const effTier = isCurrent ? current.serviceTier : preset.serviceTier
const fastControl: FastControl =
controller.allowSpeed === false
? { kind: 'none' }
: resolveFastControl(activeId ?? family.id, provider.models ?? [], caps?.fast ?? false, effFast)
// Identity on the left, settings on the right. The name and its variant tag
// (`…-flash`, `…-preview`: WHICH model) lead; fast and effort are how this
// row is SET, so they sit by the caret that edits them instead of queueing
// after the name (#130349). The provider is never a per-row chip; a mixed
// Favorites section names it once over its rows. An inherited effort would
// be the same chip on every row, so it shows only on the active model and
// on a row whose remembered preset chose one.
const settings = [
fastControl.kind !== 'none' && fastControl.on && !(fastControl.kind === 'param' && fastControl.canEnable === false)
? effTier === 'ultrafast'
? t.shell.modelOptions.ultrafast
: copy.fast
: null,
(caps?.reasoning ?? true) && (isCurrent ? !current.effortPending : Boolean(effEffort))
? reasoningEffortLabel(effEffort || defaultEffort, isCurrent ? current.effortWire : undefined)
: null
].filter((setting): setting is string => Boolean(setting))
// Clicking the row commits the model and closes; the edit submenu
// (reasoning/fast) is reached by HOVER, so you can tweak those without
// the click dismissing everything. The trailing caret is what advertises
// that submenu — without it the row's effort badge reads as a fixed
// model+effort combo rather than an editable setting (#86966).
const activate = () => {
if (!isCurrent) {
void onSelect(family, provider)
}
closeMenu()
}
const toggleFavorite = () => {
triggerHaptic('selection')
toggleFavoriteModel(provider.slug, family.id)
}
const favoriteLabel = favorite ? copy.removeFavorite : copy.addFavorite
return (
<DropdownMenuSub onOpenChange={open => onSubOpenChange?.(open, rowKey)}>
<DropdownMenuSubTrigger
onClick={event => {
// Shift-click stars, the same gesture that pins a chat row in the
// sidebar. Nothing is picked and the menu stays open, so a second
// shift-click (on the row, now under Favorites) undoes it.
if (event.shiftKey) {
event.preventDefault()
toggleFavorite()
return
}
activate()
}}
onKeyDown={event => {
if (event.key === 'Enter' || event.key === ' ') {
activate()
}
}}
{...kbProps}
className={cn(kbProps.className, 'group/model')}
>
{/* The star IS the favorite control: filled when starred, a quiet
outline otherwise. Its click never reaches the row, so starring
neither selects the model nor closes the menu. Not a tab stop —
the search field owns keyboard focus (Shift+Enter stars). */}
<Tip label={<TipHintLabel hint={favorite ? undefined : copy.favoriteShortcut} text={favoriteLabel} />}>
<button
aria-label={favoriteLabel}
aria-pressed={favorite}
className={cn(
'-mx-0.5 grid size-4 shrink-0 place-items-center rounded-sm transition-colors duration-100 hover:text-foreground hover:transition-none',
favorite
? 'text-(--ui-text-secondary)'
: 'text-(--ui-text-quaternary) group-hover/model:text-(--ui-text-tertiary) group-hover/model:transition-none group-data-[kb-active]/model:text-(--ui-text-tertiary)'
)}
onClick={event => {
event.preventDefault()
event.stopPropagation()
toggleFavorite()
}}
tabIndex={-1}
type="button"
>
<Codicon name={favorite ? 'star-full' : 'star-empty'} size="0.75rem" />
</button>
</Tip>
<span className={cn('flex min-w-0 flex-1 items-center gap-1.5', limit.tone)}>
{decoration.icon !== undefined ? <ModelMenuRowIcon icon={decoration.icon} /> : null}
<span className="min-w-0 truncate">
<HighlightMatches foldSeparators query={search} text={name} />
</span>
{tag ? <ModelChip>{tag}</ModelChip> : null}
{decoration.badge ? (
<Badge className="shrink-0 uppercase tracking-wide" data-model-menu-row-badge="" size="xs" variant="muted">
{decoration.badge}
</Badge>
) : null}
</span>
<ModelResetBadge time={limit.reset} />
{loadProgress ? (
<span className="flex shrink-0 items-center gap-1.5" title={copyPicker.loadingIntoMemory}>
<span className="h-1 w-14 overflow-hidden rounded-full bg-(--ui-bg-tertiary)">
<span
className="block h-full rounded-full bg-primary transition-[width] duration-500"
style={{ width: `${Math.max(2, loadProgress.percent)}%` }}
/>
</span>
<span className="text-[0.62rem] tabular-nums text-(--ui-text-tertiary)">{loadProgress.percent}%</span>
</span>
) : null}
{showPricing && pricing && !rowLevel ? <ModelPrice pricing={pricing} /> : null}
{rowLevel ? <UsageLevelTag level={usageTag(provider, family.id)} /> : null}
{settings.map(setting => (
<ModelChip key={setting} setting>
{setting}
</ModelChip>
))}
{isCurrent ? <Codicon className="text-foreground" name="check" size="0.75rem" /> : null}
</DropdownMenuSubTrigger>
<ModelEditSubmenu
canDisableReasoning={caps?.can_disable_reasoning ?? undefined}
defaultEffort={defaultEffort}
effort={effEffort}
effortWire={isCurrent ? current.effortWire : undefined}
fastControl={fastControl}
isActive={isCurrent}
model={family.id}
onSelectModel={nextModel => controller.select(nextModel, provider.slug)}
onSetOptions={patch =>
controller.setOptions(patch, { isActive: isCurrent, model: family.id, provider: provider.slug })
}
provider={provider.slug}
reasoning={caps?.reasoning ?? true}
serviceTier={effTier}
ultrafastSupported={controller.allowSpeed !== false && (caps?.ultrafast ?? false)}
/>
</DropdownMenuSub>
)
}
/** True when the text cursor sits at the very end with nothing selected — the
* only state where ArrowRight is free for the menu to claim. */
function caretAtEnd(input: HTMLInputElement): boolean {
const { selectionEnd, selectionStart, value } = input
return selectionStart === value.length && selectionEnd === value.length
}
// The backend's provider row for staged local models (inventory.py's
// _local_runtime_row). Downloads-in-flight attach to this group.
const LOCAL_PROVIDER_SLUG = 'llamacpp'
// Heading for every row group in the list (Favorites, providers, downloads).
const catalogGroupLabel =
'px-2 pb-0.5 pt-0.5 text-[0.625rem] font-semibold uppercase tracking-wider text-(--ui-text-secondary)'
// A provider inside a mixed Favorites section: the group heading's ink, set
// in normal case and indented to the model names it labels, so it reads as
// a sub-group rather than a sibling section.
const favoriteProviderLabel = 'pt-1.5 pb-0 pr-2 pl-7.75 text-[0.625rem] text-(--ui-text-tertiary)'
/** The picker's chips: a filled tag for what the model IS (its variant), an
* outlined one for how this row is SET (fast, effort), so the two read as
* different kinds of fact at a glance. */
function ModelChip({ children, setting = false }: { children: ReactNode; setting?: boolean }): ReactElement {
return (
<Badge className="shrink-0 uppercase tracking-wide" size="xs" variant={setting ? 'outline' : 'muted'}>
{children}
</Badge>
)
}
/** A limited provider stays pickable: the account-wide case dims every row
* (the group heading says why), the per-model case dims and tags only the
* rows cooling down, so a sibling reads as the way to keep working. The
* current row stays bright so the selection still reads. */
function familyLimit(
provider: ModelOptionProvider,
family: ModelFamily,
isCurrent: boolean
): { reset: null | string; tone?: string } {
const ms = modelResetMs(provider, family.id) ?? (family.fastId ? modelResetMs(provider, family.fastId) : null)
const reset = ms === null ? null : formatReset(ms)
// Window plans: a model a full allowance stops dims too; the limit line under the provider says why.
const dim = !isCurrent && (reset !== null || accountResetMs(provider) !== null || planBlocks(provider, family.id))
return { reset, tone: dim ? 'text-(--ui-text-tertiary)' : undefined }
}
function ModelResetBadge({ time }: { time: null | string }): null | ReactElement {
const { t } = useI18n()
const copy = t.shell.modelMenu
return time ? (
<Tip label={copy.modelLimitedTip(time)}>
<Badge className="shrink-0 tabular-nums" size="xs" variant="warn">
{copy.modelResets(time)}
</Badge>
</Tip>
) : null
}
// A model still downloading: visible so the user knows it's coming (and
// where it will land), disabled so it can't be selected early, with the
// same byte progress the Local Models pane shows. Percent is selected HERE,
// per row, so the 700ms byte ticks repaint this leaf only — the menu tree
// above subscribes to download identity, not progress.
function DownloadingModelRow({
owner,
jobId,
target
}: {
owner: LocalModelsOwner
jobId: string
target: string
}): ReactElement {
const { t } = useI18n()
const copyPicker = t.modelPicker
const copyLocal = t.settings.localModels
// The row's own scalar slice: percent for live rows, status for the
// paused fork (a paused download must stay listed with its Paused pill,
// not vanish — progress loss is information loss).
const percent: number | null = useLocalRuntimeJobs(
owner,
(jobs: readonly LocalRuntimeJob[]): number | null =>
jobs.find((job: LocalRuntimeJob): boolean => job.job_id === jobId)?.percent ?? null,
false
)
const paused: boolean = useLocalRuntimeJobs(
owner,
(jobs: readonly LocalRuntimeJob[]): boolean =>
jobs.find((job: LocalRuntimeJob): boolean => job.job_id === jobId)?.status === 'paused',
false
)
return (
<DropdownMenuItem
className={cn(dropdownMenuRow, 'opacity-60')}
disabled
onSelect={event => event.preventDefault()}
textValue=""
>
<span className="min-w-0 flex-1 truncate">{target}</span>
<span
className="ml-auto flex shrink-0 items-center gap-1.5"
title={paused ? copyLocal.downloadPausedLabel : copyPicker.downloading}
>
<span className="h-1 w-14 overflow-hidden rounded-full bg-(--ui-bg-tertiary)">
<span
className={cn(
'block h-full rounded-full',
paused ? 'bg-muted-foreground/60' : 'bg-primary transition-[width] duration-500'
)}
style={{ width: `${Math.max(2, percent ?? 0)}%` }}
/>
</span>
<span className="text-[0.62rem] tabular-nums text-(--ui-text-tertiary)">
{paused
? copyLocal.downloadPausedLabel
: typeof percent === 'number'
? `${percent}%`
: copyPicker.downloading}
</span>
</span>
</DropdownMenuItem>
)
}
// Collapsed we show the user's chosen models (or the curated default); typing
// spans every available model so anything is reachable past the cut. A search
// is itself a narrowing action, so we do NOT cap per-provider matches.
function groupModels(
providers: readonly ModelOptionProvider[],
search: string,
current: { model: string; provider: string },
visible: Set<string> | null,
/** Favorites to leave out (they paint in their own section); null lists every row. */
favorites: ReadonlySet<string> | null
): ProviderGroup[] {
const q = normalize(search)
const groups: ProviderGroup[] = []
for (const provider of providers) {
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 = recommendedFirst(provider, [{ fastId: null, id: current.model }, ...allFamilies])
}
if (allFamilies.length === 0) {
continue
}
const matches = (family: ModelFamily) =>
foldIncludes(
`${family.id} ${family.fastId ?? ''} ${provider.name} ${provider.slug} ${displayModelName(family.id)}`,
q
)
let shown: Set<string>
if (q) {
// Search spans every family, regardless of visibility.
shown = new Set(allFamilies.filter(matches).map(family => family.id))
} else if (visible) {
// User has customized which models show — honor their selection exactly.
shown = new Set(
allFamilies.filter(family => visible.has(modelVisibilityKey(provider.slug, family.id))).map(family => family.id)
)
} else {
shown = new Set(allFamilies.slice(0, DEFAULT_VISIBLE_PER_PROVIDER).map(family => family.id))
}
// Always include the active model — but keep every row in the provider's
// stable curated order, so selecting a model can't shuffle the list. While
// SEARCHING the pin is skipped: a query means "show me matches".
const activeId =
!q && catalogProviderMatches(provider, current.provider) && current.model
? allFamilies.find(family => family.id === current.model || family.fastId === current.model)?.id
: undefined
// Favorites already paint in the Favorites section, so drop them here:
// an open menu never lists the same model twice.
const families = allFamilies.filter(
family =>
(shown.has(family.id) || family.id === activeId) && !favorites?.has(favoriteModelKey(provider.slug, family.id))
)
if (families.length > 0) {
groups.push({ families, provider })
}
}
// Stable, logical group order: alphabetical by provider name. (The backend
// floats the current provider first, which would reshuffle on every switch.)
groups.sort((a, b) => a.provider.name.localeCompare(b.provider.name))
return groups
}
// The Nous row: the only one the menu re-reads on open or while its pricing warms (window-plan labels).
function isNous(provider: ModelOptionProvider): boolean {
return provider.slug === 'nous'
}
// Nous only: re-read on every open (cached list shows instantly, the re-read swaps in when it
// lands). The plan (usage-window labels, used-up notes) loads with the first turn, after the
// list was first fetched at boot, so the 60s cache would hide it until "Refresh models".
// A cheap local cache-only read (the plan may not be known yet, so any Nous row); every other
// provider keeps the 60s cache.
function nousRefetchOnMount(data: ModelOptionsResult | undefined): 'always' | true {
return data?.providers?.some(isNous) ? 'always' : true
}
// A cache-only open on a fresh backend ships rows marked pending while pricing warms in the
// background; re-read a few times so window-plan labels appear without "Refresh models".
// Bounded (~10s): a failed pricing fetch can leave rows pending, and an open menu must not
// poll forever. Only runs while the menu is mounted and a row is pending.
function nousPricingPoll(data: ModelOptionsResult | undefined, updates: number): false | number {
return updates < 6 && data?.providers?.some(p => isNous(p) && p.pricing_pending) ? 2_000 : false
}
// Window plans: the plan's featured picks lead (the backend lists them first). Re-applied after the
// current-model pin above, so a pinned custom model lands under "Other models" instead of taking the
// first pick's "Recommended" heading.
function recommendedFirst(provider: ModelOptionProvider, families: ModelFamily[]): ModelFamily[] {
const split = splitRecommended(provider, families.map(family => family.id))
if (!split) {
return families
}
const byId = new Map(families.map(family => [family.id, family]))
return [...split.recommended, ...split.other].flatMap(id => byId.get(id) ?? [])
}
// Window plans, no query: "Recommended" above the first of the plan's featured families and
// "Other models" above the first family after them. The backend already lists the picks first.
function sectionTitle(
group: ProviderGroup,
familyIdx: number,
words: { sectionOther: string; sectionRecommended: string }
): null | string {
const section = sectionAt(
group.provider,
group.families.map(family => family.id),
familyIdx
)
return section === 'recommended' ? words.sectionRecommended : section === 'other' ? words.sectionOther : null
}
// Small hooks kept at the bottom so the component reads top-down.
function useStoreCollapsed(): string[] {
return useStore($collapsedProviders)
}
function useDefaultEffort(): string {
return useStore($defaultReasoningEffort) || DEFAULT_REASONING_EFFORT
}