Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

29.5 KB
Raw Blame
import { Predicate } from "effect";
import {
  type ProviderDriverKind,
  type ProviderInstanceId,
  type ResolvedKeybindingsConfig,
} from "@akeru/contracts";
import { resolveSelectableModel } from "@akeru/shared/model";
import { LegendList } from "@legendapp/list/react";
import { ChevronRightIcon, SearchIcon } from "lucide-react";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
import { useI18n } from "~/i18n";
import { cn } from "~/lib/utils";
import {
  modelPickerJumpCommandForIndex,
  modelPickerJumpIndexFromCommand,
  resolveShortcutCommand,
  shortcutLabelForCommand,
} from "../../keybindings";
import { providerModelKey, sortProviderModelItems } from "../../modelOrdering";
import {
  isProviderInstancePickerSelectable,
  isProviderInstancePickerVisible,
  providerInstancePickerBlockReason,
  providerInstanceUnavailableReason,
  type ProviderInstanceEntry,
} from "../../providerInstances";
import { Combobox, ComboboxInput, ComboboxItem, ComboboxListVirtualized } from "../ui/combobox";
import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";
import { TooltipProvider } from "../ui/tooltip";
import { ModelListRow } from "./ModelListRow";
import { ModelPickerSidebar } from "./ModelPickerSidebar";
import { modelPickerEmptyMessage } from "./modelPickerEmptyState";
import { flattenModelPickerItems, type ModelPickerItem } from "./modelPickerItems";
import {
  modelPickerLegacySectionKey,
  modelPickerModelKey,
  parseModelPickerLegacySectionKey,
  parseModelPickerModelKey,
} from "./modelPickerKeys";
import { isModelPickerNewModel } from "./modelPickerModelHighlights";
import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch";
import { ModelEsque } from "./providerIconUtils";
import { useModelPickerViewport } from "./useModelPickerViewport";

const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();

function ModelListSeparator() {
  return <div className="h-0.5" />;
}

export const ModelPickerContent = memo(function ModelPickerContent(props: {
  /** The instance currently selected in the composer (combobox "value"). */
  activeInstanceId: ProviderInstanceId;
  model: string;
  /**
   * When set, the picker is locked to the given driver kind — typically
   * because the user is editing a previously-sent message and can't change
   * which driver served the turn. Multiple instances of the same kind
   * remain selectable (e.g. locked to `codex` still lets the user switch
   * between the default Codex and a custom Codex Personal).
   */
  lockedProvider: ProviderDriverKind | null;
  lockedContinuationGroupKey?: string | null;
  /**
   * All configured provider instances in display order. Used to render
   * the sidebar (one button per instance) and to resolve display names
   * for the locked-mode header.
   */
  instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
  keybindings?: ResolvedKeybindingsConfig;
  /**
   * Model options per instance. Keyed by `ProviderInstanceId` so the
   * default Codex instance and any custom Codex instances each have their
   * own list (custom instances typically start with the same built-in
   * model set but are free to diverge via customModels).
   */
  modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
  onRequestClose?: () => void;
  getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
  onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
}) {
  const {
    keybindings: providedKeybindings,
    modelOptionsByInstance,
    instanceEntries,
    getModelDisabledReason,
    onInstanceModelChange,
  } = props;

  const { t, plural } = useI18n();
  const [searchQuery, setSearchQuery] = useState("");
  const searchInputRef = useRef<HTMLInputElement>(null);
  const highlightedModelKeyRef = useRef<string | null>(null);
  const favorites = useClientSettings((s) => s.favorites ?? []);

  const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | "favorites">(
    () => {
      if (props.lockedProvider !== null) {
        // When locked, prime the sidebar to the currently-active instance
        // so jumping into the picker keeps the focused instance visible.
        return props.activeInstanceId;
      }

      return favorites.length > 0 ? "favorites" : props.activeInstanceId;
    },
  );

  const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
    () =>
      new Set<ProviderInstanceId>(
        modelOptionsByInstance
          .get(props.activeInstanceId)
          ?.some((model) => model.slug === props.model && model.isLegacy)
          ? [props.activeInstanceId]
          : [],
      ),
  );

  const keybindings = useMemo<ResolvedKeybindingsConfig>(
    () => providedKeybindings ?? [],
    [providedKeybindings],
  );

  const updateSettings = useUpdateClientSettings();

  const focusSearchInput = useCallback(() => {
    searchInputRef.current?.focus({ preventScroll: true });
  }, []);

  const handleSelectInstance = useCallback(
    (instanceId: ProviderInstanceId | "favorites") => {
      setSelectedInstanceId(instanceId);
      window.requestAnimationFrame(() => {
        focusSearchInput();
      });
    },
    [focusSearchInput],
  );

  useLayoutEffect(() => {
    focusSearchInput();

    const frame = window.requestAnimationFrame(() => {
      focusSearchInput();
    });

    const timeout = window.setTimeout(() => {
      focusSearchInput();
    }, 0);

    return () => {
      window.cancelAnimationFrame(frame);
      window.clearTimeout(timeout);
    };
  }, [focusSearchInput]);

  // Create a Set for efficient lookup. Favorites are keyed by
  // `${instanceId}:${slug}`; the storage schema widened from ProviderDriverKind
  // to ProviderInstanceId so pre-migration favorites keyed by driver slugs
  // (e.g. `"codex:gpt-5"`) still resolve — the default instance id equals
  // the driver slug.
  const favoritesSet = useMemo(() => {
    return new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model)));
  }, [favorites]);

  /**
   * Lookup table keyed by `instanceId`. Used for display name + driver
   * kind enrichment and for `ready`/enabled filtering before flattening
   * models into the search list.
   */
  const entryByInstanceId = useMemo(
    () => new Map(instanceEntries.map((entry) => [entry.instanceId, entry])),
    [instanceEntries],
  );

  const matchesLockedProvider = useCallback(
    (entry: Pick<ProviderInstanceEntry, "driverKind" | "continuationGroupKey">): boolean => {
      if (props.lockedProvider === null) return true;

      if (entry.driverKind !== props.lockedProvider) return false;

      if (!props.lockedContinuationGroupKey) return true;

      return entry.continuationGroupKey === props.lockedContinuationGroupKey;
    },
    [props.lockedContinuationGroupKey, props.lockedProvider],
  );

  // Instances the user turned on but that cannot run right now (missing
  // login, limit reached) still list their models, disabled with the reason.
  const blockReasonByInstance = useMemo(() => {
    const reasons = new Map<ProviderInstanceId, string | null>();

    for (const entry of instanceEntries) {
      if (!isProviderInstancePickerVisible(entry)) continue;
      reasons.set(
        entry.instanceId,
        isProviderInstancePickerSelectable(entry)
          ? null
          : (providerInstancePickerBlockReason(entry, t) ??
              providerInstanceUnavailableReason(entry, { t }) ??
              t("{name} is not available right now.", { name: entry.displayName })),
      );
    }

    return reasons;
  }, [instanceEntries, t]);

  const modelDisabledReason = useCallback(
    (instanceId: ProviderInstanceId, modelSlug: string): string | null =>
      blockReasonByInstance.get(instanceId) ??
      getModelDisabledReason?.(instanceId, modelSlug) ??
      null,
    [blockReasonByInstance, getModelDisabledReason],
  );

  // Flatten models into a searchable array. One pass over the
  // instance-keyed map; each model carries its instance id + driver kind
  // so the list row can render the right icon and display name without
  // another lookup.
  const flatModels = useMemo(
    () => flattenModelPickerItems(modelOptionsByInstance, entryByInstanceId, blockReasonByInstance),
    [modelOptionsByInstance, entryByInstanceId, blockReasonByInstance],
  );

  const isLocked = props.lockedProvider !== null;
  const isSearching = searchQuery.trim().length > 0;

  const lockedDisabledInstanceIds = useMemo(() => {
    if (!isLocked) {
      return undefined;
    }

    const disabled = new Set<ProviderInstanceId>();

    for (const entry of instanceEntries) {
      if (!matchesLockedProvider(entry)) {
        disabled.add(entry.instanceId);
      }
    }

    return disabled;
  }, [instanceEntries, isLocked, matchesLockedProvider]);

  const sidebarInstanceEntries = useMemo(() => {
    const enabledEntries = instanceEntries.filter(isProviderInstancePickerVisible);

    if (!isLocked) {
      return enabledEntries;
    }

    const available: ProviderInstanceEntry[] = [];
    const disabled: ProviderInstanceEntry[] = [];

    for (const entry of enabledEntries) {
      if (matchesLockedProvider(entry)) {
        available.push(entry);
      } else {
        disabled.push(entry);
      }
    }

    return [...available, ...disabled];
  }, [instanceEntries, isLocked, matchesLockedProvider]);

  const showSidebar = !isSearching && sidebarInstanceEntries.length > 0;

  const instanceOrder = useMemo(
    () => instanceEntries.map((entry) => entry.instanceId),
    [instanceEntries],
  );

  // Filter models based on search query and selected instance
  const filteredModels = useMemo(() => {
    let result = flatModels;

    // Apply tokenized fuzzy search across the combined provider/model search fields.
    if (searchQuery.trim()) {
      const rankedMatches = result
        .map((model) => ({
          model,
          score: scoreModelPickerSearch(
            {
              name: model.name,
              ...(model.shortName ? { shortName: model.shortName } : {}),
              ...(model.subProvider ? { subProvider: model.subProvider } : {}),
              driverKind: model.driverKind,
              providerDisplayName: model.instanceDisplayName,
              isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
            },
            searchQuery,
          ),
          isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)),
          tieBreaker: buildModelPickerSearchText({
            name: model.name,
            ...(model.shortName ? { shortName: model.shortName } : {}),
            ...(model.subProvider ? { subProvider: model.subProvider } : {}),
            driverKind: model.driverKind,
            providerDisplayName: model.instanceDisplayName,
          }),
        }))
        .filter(
          (
            rankedModel,
          ): rankedModel is {
            model: ModelPickerItem;
            score: number;
            isFavorite: boolean;
            tieBreaker: string;
          } => rankedModel.score !== null,
        );

      // When searching, we only respect locked provider (by driver kind),
      // ignoring sidebar selection so account-scoped searches can find a
      // model before the user chooses a specific instance rail item.
      if (props.lockedProvider !== null) {
        const lockedProviderMatches: Array<(typeof rankedMatches)[number]> = [];

        for (const rankedModel of rankedMatches) {
          if (matchesLockedProvider(rankedModel.model)) {
            lockedProviderMatches.push(rankedModel);
          }
        }

        return lockedProviderMatches
          .toSorted((a, b) => {
            const scoreDelta = a.score - b.score;

            if (scoreDelta !== 0) {
              return scoreDelta;
            }

            if (a.isFavorite !== b.isFavorite) {
              return a.isFavorite ? -1 : 1;
            }

            return a.tieBreaker.localeCompare(b.tieBreaker);
          })
          .map((rankedModel) => rankedModel.model);
      }

      return rankedMatches
        .toSorted((a, b) => {
          const scoreDelta = a.score - b.score;

          if (scoreDelta !== 0) {
            return scoreDelta;
          }

          if (a.isFavorite !== b.isFavorite) {
            return a.isFavorite ? -1 : 1;
          }

          return a.tieBreaker.localeCompare(b.tieBreaker);
        })
        .map((rankedModel) => rankedModel.model);
    }

    if (props.lockedProvider !== null) {
      result = result.filter((m) => matchesLockedProvider(m));

      if (selectedInstanceId === "favorites") {
        result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
      } else {
        result = result.filter((m) => m.instanceId === selectedInstanceId);
      }
    } else if (selectedInstanceId === "favorites") {
      result = result.filter((m) => favoritesSet.has(providerModelKey(m.instanceId, m.slug)));
    } else {
      result = result.filter((m) => m.instanceId === selectedInstanceId);
    }

    return sortProviderModelItems(result, {
      favoriteModelKeys: favoritesSet,
      groupFavorites: selectedInstanceId !== "favorites",
      instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [],
    });
  }, [
    favoritesSet,
    flatModels,
    instanceOrder,
    matchesLockedProvider,
    props.lockedProvider,
    searchQuery,
    selectedInstanceId,
  ]);

  const legacySection = useMemo(() => {
    if (isSearching || selectedInstanceId === "favorites") {
      return null;
    }

    const currentModels = filteredModels.filter((model) => !model.isLegacy);
    const legacyModels = filteredModels.filter((model) => model.isLegacy);

    if (legacyModels.length === 0) {
      return null;
    }

    return {
      key: modelPickerLegacySectionKey(selectedInstanceId),
      currentModels,
      legacyModels,
      isExpanded: expandedLegacyInstances.has(selectedInstanceId),
    };
  }, [expandedLegacyInstances, filteredModels, isSearching, selectedInstanceId]);

  const visibleModels = useMemo(() => {
    if (!legacySection) {
      return filteredModels;
    }

    return [
      ...legacySection.currentModels,
      ...(legacySection.isExpanded ? legacySection.legacyModels : []),
    ];
  }, [filteredModels, legacySection]);

  const toggleLegacySection = useCallback((instanceId: ProviderInstanceId) => {
    setExpandedLegacyInstances((expanded) => {
      const next = new Set(expanded);

      if (next.has(instanceId)) {
        next.delete(instanceId);
      } else {
        next.add(instanceId);
      }

      return next;
    });
  }, []);

  const handleModelSelect = useCallback(
    (modelSlug: string, instanceId: ProviderInstanceId) => {
      if (modelDisabledReason(instanceId, modelSlug)) {
        return;
      }

      const options = modelOptionsByInstance.get(instanceId);

      if (!options) {
        return;
      }

      const entry = entryByInstanceId.get(instanceId);

      if (!entry) {
        return;
      }

      // `resolveSelectableModel` uses the driver kind for normalization
      // (slug casing etc.). Custom instances share their driver's
      // normalization rules, so pass the driver kind here.
      const resolvedModel = resolveSelectableModel(entry.driverKind, modelSlug, options);

      if (resolvedModel) {
        onInstanceModelChange(instanceId, resolvedModel);
      }
    },
    [entryByInstanceId, modelDisabledReason, modelOptionsByInstance, onInstanceModelChange],
  );

  const toggleFavorite = useCallback(
    (instanceId: ProviderInstanceId, model: string) => {
      const newFavorites = [...favorites];
      const index = newFavorites.findIndex((f) => f.provider === instanceId && f.model === model);

      if (index >= 0) {
        newFavorites.splice(index, 1);
      } else {
        newFavorites.push({ provider: instanceId, model });
      }

      updateSettings({ favorites: newFavorites });
    },
    [favorites, updateSettings],
  );

  const modelJumpCommandByKey = useMemo(() => {
    const mapping = new Map<
      string,
      NonNullable<ReturnType<typeof modelPickerJumpCommandForIndex>>
    >();

    let selectableModelIndex = 0;

    for (const model of visibleModels) {
      if (modelDisabledReason(model.instanceId, model.slug)) {
        continue;
      }

      const jumpCommand = modelPickerJumpCommandForIndex(selectableModelIndex);

      if (!jumpCommand) {
        return mapping;
      }

      mapping.set(modelPickerModelKey(model.instanceId, model.slug), jumpCommand);
      selectableModelIndex += 1;
    }

    return mapping;
  }, [modelDisabledReason, visibleModels]);

  const modelJumpModelKeys = useMemo(
    () => [...modelJumpCommandByKey.keys()],
    [modelJumpCommandByKey],
  );

  const allItemKeys = useMemo(
    (): string[] => [
      ...flatModels.map((model) => modelPickerModelKey(model.instanceId, model.slug)),
      ...new Set(
        flatModels.flatMap((model) =>
          model.isLegacy ? [modelPickerLegacySectionKey(model.instanceId)] : [],
        ),
      ),
    ],
    [flatModels],
  );

  const filteredItemKeys = useMemo((): string[] => {
    const modelKeys = visibleModels.map((model) =>
      modelPickerModelKey(model.instanceId, model.slug),
    );

    if (!legacySection) {
      return modelKeys;
    }

    modelKeys.splice(legacySection.currentModels.length, 0, legacySection.key);

    return modelKeys;
  }, [legacySection, visibleModels]);

  const hasResults = filteredItemKeys.length > 0;

  const emptyMessage = modelPickerEmptyMessage(
    {
      searchQuery,
      selectedInstanceId,
      hasAnyModels: flatModels.length > 0,
      selectedInstanceModelsLoaded:
        selectedInstanceId === "favorites" || modelOptionsByInstance.has(selectedInstanceId),
    },
    t,
  );

  const filteredModelByKey = useMemo(
    (): ReadonlyMap<string, ModelPickerItem> =>
      new Map(
        visibleModels.map(
          (model) => [modelPickerModelKey(model.instanceId, model.slug), model] as const,
        ),
      ),
    [visibleModels],
  );

  const { modelListRef, showTopScrollFade, showBottomScrollFade, updateModelListScrollFades } =
    useModelPickerViewport(filteredItemKeys);

  const modelJumpShortcutContext = useMemo(() => ({ modelPickerOpen: true }) as const, []);

  const modelJumpLabelByKey = useMemo((): ReadonlyMap<string, string> => {
    if (modelJumpCommandByKey.size === 0) {
      return EMPTY_MODEL_JUMP_LABELS;
    }

    const shortcutLabelOptions = {
      platform: navigator.platform,
      context: modelJumpShortcutContext,
    };

    const mapping = new Map<string, string>();

    for (const [modelKey, command] of modelJumpCommandByKey) {
      const label = shortcutLabelForCommand(keybindings, command, shortcutLabelOptions);

      if (label) {
        mapping.set(modelKey, label);
      }
    }

    return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
  }, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]);

  const modelListExtraData = useMemo(
    () => ({ favoritesSet, modelJumpLabelByKey, t }),
    [favoritesSet, modelJumpLabelByKey, t],
  );

  useEffect(() => {
    const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
      if (event.defaultPrevented || event.repeat) {
        return;
      }

      const command = resolveShortcutCommand(event, keybindings, {
        platform: navigator.platform,
        context: modelJumpShortcutContext,
      });

      const jumpIndex = modelPickerJumpIndexFromCommand(command ?? "");

      if (jumpIndex === null) {
        return;
      }

      const targetModelKey = modelJumpModelKeys[jumpIndex];

      if (!targetModelKey) {
        return;
      }

      const model = parseModelPickerModelKey(targetModelKey);

      if (!model) {
        return;
      }

      event.preventDefault();
      event.stopPropagation();
      handleModelSelect(model.slug, model.instanceId);
    };

    window.addEventListener("keydown", onWindowKeyDown, true);

    return () => {
      window.removeEventListener("keydown", onWindowKeyDown, true);
    };
  }, [handleModelSelect, keybindings, modelJumpModelKeys, modelJumpShortcutContext]);

  return (
    <TooltipProvider delay={0}>
      <div
        className={cn(
          "relative flex w-min-22.5rem-vw-2rem max-h-min-21.625rem-dvh-2rem flex-row overflow-hidden",
          hasResults ? "h-min-21.625rem-dvh-2rem" : "min-h-32",
        )}
        data-model-picker-content="true"
      >
        {/* Sidebar */}
        {showSidebar && (
          <ModelPickerSidebar
            selectedInstanceId={selectedInstanceId}
            onSelectInstance={handleSelectInstance}
            instanceEntries={sidebarInstanceEntries}
            showFavorites
            {...(lockedDisabledInstanceIds
              ? {
                  disabledInstanceIds: lockedDisabledInstanceIds,
                  getDisabledInstanceTooltip: (entry: ProviderInstanceEntry) =>
                    t("{name} is unavailable in this chat. Start a new chat to switch providers.", {
                      name: entry.displayName,
                    }),
                }
              : {})}
          />
        )}

        {/* Main content area */}
        <Combobox
          inline
          items={allItemKeys}
          filteredItems={filteredItemKeys}
          filter={null}
          autoHighlight
          open
          virtualized
          value={modelPickerModelKey(props.activeInstanceId, props.model)}
          onItemHighlighted={(modelKey, eventDetails) => {
            highlightedModelKeyRef.current = Predicate.isString(modelKey) ? modelKey : null;

            if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
              void modelListRef.current?.scrollIndexIntoView?.({
                index: eventDetails.index,
                animated: false,
              });
            }
          }}
          onValueChange={(modelKey) => {
            if (!Predicate.isString(modelKey)) {
              return;
            }

            const legacyInstanceId = parseModelPickerLegacySectionKey(modelKey);

            if (legacyInstanceId) {
              toggleLegacySection(legacyInstanceId);

              return;
            }

            const model = parseModelPickerModelKey(modelKey);

            if (model) {
              handleModelSelect(model.slug, model.instanceId);
            }
          }}
        >
          <div
            className={cn(
              "flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/30",
              showSidebar && "border-l border-border/70",
            )}
          >
            {/* Search bar */}
            <div className="px-2 pt-2">
              <div className="border-b border-border/70 pb-2.5 transition-colors focus-within:border-foreground/30">
                <ComboboxInput
                  ref={searchInputRef}
                  presentation="model-search"
                  placeholder={t("Search models…")}
                  aria-label={t("Search models")}
                  showTrigger={false}
                  startAddon={
                    <SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground opacity-70" />
                  }
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Escape") {
                      e.preventDefault();
                      e.stopPropagation();

                      if (searchQuery) setSearchQuery("");
                      else props.onRequestClose?.();

                      return;
                    }

                    if (
                      e.key === "Enter" &&
                      highlightedModelKeyRef.current &&
                      filteredItemKeys.includes(highlightedModelKeyRef.current)
                    ) {
                      if (
                        "preventBaseUIHandler" in e &&
                        Predicate.isFunction(e.preventBaseUIHandler)
                      )
                        e.preventBaseUIHandler();
                      e.preventDefault();
                      e.stopPropagation();

                      const legacyInstanceId = parseModelPickerLegacySectionKey(
                        highlightedModelKeyRef.current,
                      );

                      if (legacyInstanceId) {
                        toggleLegacySection(legacyInstanceId);

                        return;
                      }

                      const model = parseModelPickerModelKey(highlightedModelKeyRef.current);

                      if (model) {
                        handleModelSelect(model.slug, model.instanceId);
                      }

                      return;
                    }

                    e.stopPropagation();
                  }}
                  onMouseDown={(e) => e.stopPropagation()}
                  onTouchStart={(e) => e.stopPropagation()}
                  size="sm"
                  unstyled
                />
              </div>
            </div>

            {/* Model list */}
            {hasResults ? (
              <div className="relative min-h-0 flex-1 overflow-hidden pr-px">
                <ComboboxListVirtualized presentation="model-list">
                  <LegendList<string>
                    ref={modelListRef}
                    data={filteredItemKeys}
                    extraData={modelListExtraData}
                    keyExtractor={(modelKey) => modelKey}
                    renderItem={({ item: modelKey, index }) => {
                      if (legacySection?.key === modelKey) {
                        return (
                          <ComboboxItem
                            hideIndicator
                            index={index}
                            value={modelKey}
                            aria-expanded={legacySection.isExpanded}
                            variant="model-row"
                            className="group w-full cursor-pointer"
                            contentClassName="flex w-full items-center"
                          >
                            <div className="min-w-0 flex-1 text-left">
                              <div className="text-xs font-medium leading-snug">
                                {t("Legacy models")}
                              </div>
                              <div className="mt-1 text-xs font-normal leading-snug text-muted-foreground/70">
                                {plural(legacySection.legacyModels.length, {
                                  one: "{count} model",
                                  other: "{count} models",
                                })}
                              </div>
                            </div>
                            <ChevronRightIcon
                              className={cn(
                                "size-4 transition-transform",
                                legacySection.isExpanded && "rotate-90",
                              )}
                            />
                          </ComboboxItem>
                        );
                      }

                      const model = filteredModelByKey.get(modelKey);

                      if (!model) {
                        return null;
                      }

                      const disabledReason = modelDisabledReason(model.instanceId, model.slug);

                      return (
                        <ModelListRow
                          key={modelKey}
                          index={index}
                          model={model}
                          instanceId={model.instanceId}
                          driverKind={model.driverKind}
                          providerDisplayName={model.instanceDisplayName}
                          providerAccentColor={model.instanceAccentColor}
                          isFavorite={favoritesSet.has(
                            providerModelKey(model.instanceId, model.slug),
                          )}
                          isSelected={
                            modelKey === modelPickerModelKey(props.activeInstanceId, props.model)
                          }
                          showProvider
                          preferShortName={!isLocked}
                          useTriggerLabel={false}
                          showNewBadge={isModelPickerNewModel(model.driverKind, model.slug)}
                          jumpLabel={modelJumpLabelByKey.get(modelKey) ?? null}
                          disabledReason={disabledReason}
                          onToggleFavorite={() => toggleFavorite(model.instanceId, model.slug)}
                        />
                      );
                    }}
                    estimatedItemSize={52}
                    drawDistance={480}
                    recycleItems
                    contentContainerClassName="pl-2 pr-px"
                    ItemSeparatorComponent={ModelListSeparator}
                    onLayout={updateModelListScrollFades}
                    onScroll={updateModelListScrollFades}
                    className={cn(
                      "scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [&::-webkit-scrollbar-track]:my-2",
                      getVirtualizedScrollFadeClassName({
                        top: showTopScrollFade,
                        bottom: showBottomScrollFade,
                      }),
                    )}
                  />
                </ComboboxListVirtualized>
              </div>
            ) : (
              <div
                role="status"
                className="flex min-h-20 items-center px-4 py-4 text-sm leading-snug text-muted-foreground"
              >
                {emptyMessage}
              </div>
            )}
          </div>
        </Combobox>
      </div>
    </TooltipProvider>
  );
});