Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

34.6 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"use client";

import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { TooltipProvider } from "@/components/ui/tooltip";
import { ApiProviderLogo } from "@/features/chat/api-provider-logo";

import type { HubCapabilityFilter } from "@/features/hub";
import type { HfTaskFilter } from "@/features/hub/hooks/use-hub-model-search";
// eslint-disable-next-line no-restricted-imports -- The settings barrel imports this feature back.
import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";
import { isNpuModelId, NPU_MODEL_PREFIX, useNpuStatus } from "@/features/npu";
import { useT } from "@/i18n";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { cn } from "@/lib/utils";
import {
  CheckmarkCircle02Icon,
  CloudIcon,
  Download01Icon,
  RemoveCircleIcon,
  StarIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useNavigate } from "@tanstack/react-router";
import {
  type KeyboardEvent,
  type ReactNode,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import {
  type ModelConfigFocus,
  type ModelConfigHandoffRequest,
  modelConfigTarget,
  modelConfigTargetIsResident,
  modelConfigTargetMatchesSelection,
} from "../model-config/model-config-handoff";
import { modelConfigInstanceKey } from "../model-config/config-signature";
import {
  ggufVariantsMatch,
  modelDisplayName,
} from "../model-config/model-identity";
import {
  type PerModelConfig,
  resolveInitialConfig,
} from "../model-config/per-model-config";
import { ModelConfigPage } from "./model-config-page";
import {
  type ExternalConnectionRef,
  missingExternalModel,
} from "./model-selector/missing-external-model";
import type { CommunityModelPolicy } from "./model-selector/audio-picker-policy";
import {
  artifactForRepoId,
  type CatalogGroup,
} from "./model-selector/model-catalog";
import {
  HubModelPicker,
  hasDownloadedModels,
  type ModelPickerRowFilter,
} from "./model-selector/pickers";
import {
  type HubSection,
  resolveHubSection,
} from "./model-selector/hub-section";
import { PillTabs } from "./model-selector/pill-tabs";
import { loraOptionLabel } from "./model-selector/row-meta";
import { isFineTunedSource } from "./model-selector/source-tabs";
import type {
  DeletedModelRef,
  ExternalModelOption,
  LoraModelOption,
  ModelDownloadFootprintResolver,
  ModelOption,
  ModelPickTarget,
  ModelSelectorChangeMeta,
} from "./model-selector/types";

export type {
  DeletedModelRef,
  ExternalModelOption,
  LoraModelOption,
  ModelOption,
  ModelSelectorChangeMeta,
} from "./model-selector/types";
export type { ExternalConnectionRef } from "./model-selector/missing-external-model";
export type { ModelPickerRowFilter } from "./model-selector/pickers";

interface ModelSelectorProps {
  models: ModelOption[];
  /** Models a task runtime confirms are loadable though absent from the generic Hub inventory. */
  additionalOnDeviceModels?: ModelOption[];
  /** Task-owned runtime residency when it is separate from Chat's main slot. */
  loadedModelIdOverride?: string;
  /** Task-owned loaded quant, paired with `loadedModelIdOverride`; null means none. */
  loadedGgufVariantOverride?: string | null;
  loraModels?: LoraModelOption[];
  externalModels?: ExternalModelOption[];
  /** Carries each connection's cached catalogue, which tells a user-unticked model from a withdrawn one. */
  externalConnections?: ExternalConnectionRef[];
  value?: string;
  defaultValue?: string;
  /** Whether the selection is actually resident. Omitted means a selection is a load. */
  loaded?: boolean;
  activeGgufVariant?: string | null;
  activeVariantIsMlx?: boolean;
  activeModelConfig?: PerModelConfig | null;
  activeLoadedContextLength?: number | null;
  selectedConfig?: PerModelConfig | null;
  selectedGgufVariant?: string | null;
  configRequest?: ModelConfigHandoffRequest | null;
  onConfigRequestAdopted?: (requestId: string) => void;
  onValueChange?: (value: string, meta: ModelSelectorChangeMeta) => void;
  /** Optional task-specific resolver for companion assets a GGUF row alone cannot describe. */
  resolveDownloadFootprint?: ModelDownloadFootprintResolver;
  onEject?: (modelId?: string) => void;
  onEjectAll?: () => void;
  loadedCount?: number;
  loadedNames?: string[];
  onFoldersChange?: () => void;
  onModelsChange?: (deletedModel?: DeletedModelRef) => void;
  deleteDisabled?: boolean;
  variant?: "outline" | "ghost" | "muted";
  size?: "sm" | "default" | "lg";
  className?: string;
  triggerLabelClassName?: string;
  contentClassName?: string;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
  triggerDataTour?: string;
  contentDataTour?: string;
  showCloudIndicator?: boolean;
  /** Restrict the Hub tab to a pipeline task (e.g. text-to-image). */
  task?: HfTaskFilter;
  /** Canonical model groups (Images / Video): one row per model with a format second level. */
  catalog?: CatalogGroup[];
  /** Also list community (non-unsloth) models for `task`; only for runtimes loading any publisher. */
  communityModelPolicy?: CommunityModelPolicy;
  /** The one opaque on-device artifact kind this task runtime may load. */
  opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";
  rowFilter?: ModelPickerRowFilter;
  /** Audio's "Load model into: CPU RAM": audio.cpp variants skip their GPU estimate. */
  cpuLoad?: boolean;
  /** A second Recommended group under its own label, e.g. "More models". */
  moreModels?: {
    label: string;
    models: (ModelOption & { sizeBytes?: number | null })[];
  };
  /** Hub filter the Search Hub button opens with. Also shows Search Hub on curated task pickers. */
  hubCapability?: HubCapabilityFilter;
  /** Tasks the Search Hub link narrows the Audio filter to, when the page's runs differ from `task`. */
  hubTask?: HfTaskFilter;
  /** Trigger text when nothing is loaded. Defaults to "Select model"; task pages name what they
   *  pick so it reads as separate from the chat model. */
  placeholder?: string;
}

// Drawn inside the text box so the gap truncates away with the text.
const GAP_BEFORE = "before:inline-block before:w-2 before:content-['']";

function ModelSelectorTrigger({
  currentModel,
  isLoaded,
  showCloudIndicator = false,
  variant = "outline",
  size = "default",
  className,
  triggerLabelClassName,
  dataTour,
  onEject,
  loadedCount = 0,
  loadedNames,
  // Task pages name what they pick ("Select image model"), so the choice reads as separate from the chat model.
  placeholder = "Select model",
}: {
  loadedCount?: number;
  loadedNames?: string[];
  currentModel?: ModelOption;
  isLoaded: boolean;
  showCloudIndicator?: boolean;
  variant?: "outline" | "ghost" | "muted";
  size?: "sm" | "default" | "lg";
  className?: string;
  triggerLabelClassName?: string;
  dataTour?: string;
  onEject?: () => void;
  placeholder?: string;
}) {
  const severalLoaded = loadedCount > 1;
  const listsNames = severalLoaded && (loadedNames?.length ?? 0) > 1;
  const triggerTitle = listsNames
    ? loadedNames?.join(" • ")
    : severalLoaded
      ? `${loadedCount} models loaded`
      : (currentModel?.name ?? placeholder);
  const subtitle = listsNames
    ? undefined
    : severalLoaded
      ? currentModel?.name
      : currentModel?.description;
  return (
    <PopoverTrigger asChild={true}>
      <button
        type="button"
        data-tour={dataTour}
        className={cn(
          "unsloth-model-selector-trigger group/trigger flex min-w-0 items-center gap-2 transition-colors",
          variant === "outline" &&
            "rounded-full border border-border hover:bg-accent has-[[data-eject-hit]:hover]:!bg-transparent",
          // Header rows: same corners and hover wash as the icon buttons beside it.
          variant === "ghost" &&
            "rounded-[10px] hover:bg-nav-surface-hover has-[[data-eject-hit]:hover]:!bg-transparent",
          variant === "muted" &&
            "rounded-full bg-muted hover:bg-muted has-[[data-eject-hit]:hover]:!bg-muted",
          // Height stays pinned to --studio-chat-control-height.
          size === "sm" && "h-8 pl-3 pr-1.5 text-xs",
          size === "default" && "h-9 pl-4 pr-2 text-sm",
          size === "lg" && "h-10 pl-4.5 pr-2.5 text-sm",
          className,
        )}
      >
        {isLoaded &&
          (onEject ? (
            // Mouse-only eject shortcut; keyboard and SR users use the "Eject model" button.
            // A span keeps it out of the button's content model; pointer-events-none on touch.
            <span
              aria-hidden={true}
              title="Eject model"
              data-eject-hit={true}
              onPointerDown={(event) => event.stopPropagation()}
              onClick={(event) => {
                event.stopPropagation();
                onEject();
              }}
              className="-m-1 flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-full transition-colors hover:bg-[rgb(0_0_0_/_calc(0.1*var(--contrast-wash-gain,1)))] dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))] [@media(hover:none)]:pointer-events-none"
            >
              <HugeiconsIcon
                icon={CheckmarkCircle02Icon}
                strokeWidth={1.75}
                className="size-3.5 text-emerald-500 group-hover/trigger:hidden"
              />
              <HugeiconsIcon
                icon={RemoveCircleIcon}
                strokeWidth={1.75}
                className="hidden size-3.5 text-red-500 group-hover/trigger:block"
              />
            </span>
          ) : (
            <span className="size-2 shrink-0 rounded-full bg-emerald-500" />
          ))}
        {currentModel?.icon ? (
          <span className="flex shrink-0 items-center">
            {currentModel.icon}
          </span>
        ) : null}
        <span className="flex min-w-0 flex-1 items-baseline">
          <span className="flex min-w-0 items-baseline">
            <span
              className={cn(
                "flex max-w-full shrink-0 items-baseline whitespace-nowrap font-heading text-ui-16 font-medium leading-tight text-black dark:text-foreground",
                triggerLabelClassName,
              )}
            >
              <span className="min-w-0 truncate">{triggerTitle}</span>
              {showCloudIndicator ? (
                <HugeiconsIcon
                  icon={CloudIcon}
                  strokeWidth={1.75}
                  className="relative top-[0.15625rem] ml-1.5 mr-[calc(0.36rem*var(--ui-space-scale,1))] size-3.5 shrink-0 text-muted-foreground"
                />
              ) : null}
            </span>
            {subtitle && (
              <span
                className={cn(
                  "min-w-0 shrink-[1000] truncate text-xs leading-tight text-muted-foreground",
                  !showCloudIndicator && GAP_BEFORE,
                )}
              >
                {subtitle}
              </span>
            )}
          </span>
          {!listsNames && currentModel?.descriptionSuffix && (
            <span
              className={cn(
                "min-w-0 shrink-[1000000] truncate whitespace-nowrap text-xs leading-tight text-muted-foreground",
                !subtitle && !showCloudIndicator && GAP_BEFORE,
              )}
            >
              {/* Its own span: a flex item drops the leading space of its text. */}
              {subtitle ? <span className="whitespace-pre"> - </span> : null}
              {currentModel.descriptionSuffix}
            </span>
          )}
        </span>
        <span className="-ml-1 flex size-4 shrink-0 items-center justify-center">
          <HugeiconsIcon
            icon={ChevronDownStandardIcon}
            strokeWidth={1.75}
            className="size-3.5 text-muted-foreground"
          />
        </span>
      </button>
    </PopoverTrigger>
  );
}

// The user's most recently clicked Hub section, restored on every open.
const HUB_SECTION_KEY = "unsloth_model_selector_section";
// Only On Device / Recommended persist.
function loadLastHubSection(): HubSection | null {
  try {
    const raw = localStorage.getItem(HUB_SECTION_KEY);
    return raw === "downloaded" || raw === "recommended" ? raw : null;
  } catch {
    return null;
  }
}
function saveLastHubSection(section: HubSection): void {
  if (section !== "downloaded" && section !== "recommended") return;
  try {
    localStorage.setItem(HUB_SECTION_KEY, section);
  } catch {
    // Ignore unavailable storage.
  }
}
// Preserve saved choices until the task-scoped inventory settles.
function defaultHubSection(hasAdditionalOnDeviceModels = false): HubSection {
  return (
    loadLastHubSection() ??
    (hasDownloadedModels() || hasAdditionalOnDeviceModels
      ? "downloaded"
      : "recommended")
  );
}

const HUB_SECTION_TABS: { value: string; label: string; icon?: ReactNode }[] = [
  {
    value: "recommended",
    label: "Recommended",
    icon: <HugeiconsIcon icon={StarIcon} className="size-3.5 shrink-0" />,
  },
  {
    value: "downloaded",
    label: "On Device",
    icon: <HugeiconsIcon icon={Download01Icon} className="size-3.5 shrink-0" />,
  },
];

function ModelSelectorContent({
  open,
  models,
  additionalOnDeviceModels,
  loadedModelIdOverride,
  loadedGgufVariantOverride,
  loraModels,
  externalModels,
  value,
  loaded,
  activeGgufVariant,
  activeModelConfig,
  activeLoadedContextLength,
  selectedConfig,
  selectedGgufVariant,
  configRequest,
  onConfigRequestAdopted,
  onSelect,
  resolveDownloadFootprint,
  onEject,
  onEjectAll,
  onFoldersChange,
  onBrowseHub,
  onConfigureConnection,
  onModelsChange,
  deleteDisabled,
  className,
  dataTour,
  task,
  catalog,
  communityModelPolicy,
  opaqueKind,
  rowFilter,
  cpuLoad,
  moreModels,
}: {
  open: boolean;
  models: ModelOption[];
  additionalOnDeviceModels?: ModelOption[];
  loadedModelIdOverride?: string;
  loadedGgufVariantOverride?: string | null;
  loraModels: LoraModelOption[];
  externalModels: ExternalModelOption[];
  value?: string;
  loaded?: boolean;
  activeGgufVariant?: string | null;
  activeModelConfig?: PerModelConfig | null;
  activeLoadedContextLength?: number | null;
  selectedConfig?: PerModelConfig | null;
  selectedGgufVariant?: string | null;
  configRequest?: ModelConfigHandoffRequest | null;
  onConfigRequestAdopted?: (requestId: string) => void;
  onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;
  resolveDownloadFootprint?: ModelDownloadFootprintResolver;
  onEject?: (modelId?: string) => void;
  onEjectAll?: () => void;
  onFoldersChange?: () => void;
  onBrowseHub?: () => void;
  onConfigureConnection?: (providerId: string) => void;
  onModelsChange?: (deletedModel?: DeletedModelRef) => void;
  deleteDisabled?: boolean;
  className?: string;
  dataTour?: string;
  task?: HfTaskFilter;
  catalog?: CatalogGroup[];
  communityModelPolicy?: CommunityModelPolicy;
  opaqueKind?: "diffusers_pipeline" | "diffusers_modular_pipeline";
  rowFilter?: ModelPickerRowFilter;
  cpuLoad?: boolean;
  moreModels?: {
    label: string;
    models: (ModelOption & { sizeBytes?: number | null })[];
  };
}) {
  const t = useT();
  const hasSelection = Boolean(value);
  const hasExternal = externalModels.length > 0;
  // Local models (LM Studio, Ollama, custom folders) live in Hub, not Fine-tuned.
  const fineTunedModels = useMemo(
    () => loraModels.filter((model) => isFineTunedSource(model.source)),
    [loraModels],

  );
  const [npuStatus, setNpuStatus] = useNpuStatus(open && !task);
  const npu =
    !task && npuStatus?.supported === true
      ? { status: npuStatus, onStatusChange: setNpuStatus }
      : undefined;
  const hubSectionTabs = useMemo(
    () =>
      hasExternal
        ? [
            ...HUB_SECTION_TABS,
            {
              value: "connected",
              label: "Connected",
              icon: (
                <HugeiconsIcon icon={CloudIcon} className="size-3.5 shrink-0" />
              ),
            },
          ]
        : HUB_SECTION_TABS,
    [hasExternal],

  );
  const wantsConnectedDefault = Boolean(
    value && externalModels.some((model) => model.id === value),
  );
  const hasAdditionalOnDeviceModels =
    (additionalOnDeviceModels?.length ?? 0) > 0;
  const [hubSection, setHubSection] = useState<HubSection>(() =>
    wantsConnectedDefault
      ? "connected"
      : defaultHubSection(hasAdditionalOnDeviceModels),
  );
  const [sectionChosenThisOpen, setSectionChosenThisOpen] = useState(false);
  const [hasDeviceModels, setHasDeviceModels] = useState<boolean | null>(null);
  // Inventory is scoped to this picker's task. A remembered On Device tab must not
  // open empty just because another page has downloaded models.
  const effectiveHubSection = resolveHubSection({
    section: hubSection,
    hasExternal,
    hasDeviceModels,
    sectionChosenThisOpen,
  });

  const [configTarget, setConfigTarget] = useState<ModelPickTarget | null>(
    null,
  );
  const [adoptedConfigRequestId, setAdoptedConfigRequestId] = useState<
    string | null
  >(null);
  const [configFocus, setConfigFocus] = useState<ModelConfigFocus | null>(null);
  const [configStandalone, setConfigStandalone] = useState(false);

  // Cleared during render, not in an effect: a reopen inside the exit animation dropped the adopted target.
  const [renderedOpen, setRenderedOpen] = useState(open);
  if (renderedOpen !== open) {
    setRenderedOpen(open);
    if (!open) {
      setSectionChosenThisOpen(false);
      setConfigTarget(null);
      setConfigFocus(null);
      setConfigStandalone(false);
    }
  }

  // The picker remounts on each open but this state does not, so re-derive on the open edge.
  const wasOpen = useRef(open);
  useEffect(() => {
    if (open && !wasOpen.current) {
      setHubSection(
        wantsConnectedDefault
          ? "connected"
          : defaultHubSection(hasAdditionalOnDeviceModels),
      );
    }
    wasOpen.current = open;
  }, [open, wantsConnectedDefault, hasAdditionalOnDeviceModels]);

  function focusActiveModelOption(root: HTMLElement): boolean {
    const option =
      root.querySelector<HTMLElement>(
        '[role="tabpanel"]:not([hidden]) [data-model-picker-active-option="true"]',
      ) ??
      root.querySelector<HTMLElement>(
        '[data-model-picker-active-option="true"]',
      ) ??
      root.querySelector<HTMLElement>(
        '[role="tabpanel"]:not([hidden]) [data-model-picker-option]',
      ) ??
      root.querySelector<HTMLElement>("[data-model-picker-option]");
    if (!option) {
      return false;
    }
    option.focus();
    return true;
  }

  function handlePickerEntryKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    if (event.key !== "ArrowDown") {
      return;
    }

    const target = event.target;
    if (!(target instanceof HTMLElement)) {
      return;
    }
    const isPickerSearchInput = target.matches(
      "[data-model-picker-search-input]",
    );
    const isTabTrigger = Boolean(target.closest('[role="tab"]'));
    if (!isPickerSearchInput && !isTabTrigger) {
      return;
    }

    if (focusActiveModelOption(event.currentTarget)) {
      event.preventDefault();
    }
  }

  const openConfigPage = (id: string, meta: ModelSelectorChangeMeta) => {
    const displayName = isNpuModelId(id)
      ? id.slice(NPU_MODEL_PREFIX.length)
      : undefined;
    setConfigTarget(modelConfigTarget(id, meta, displayName));
    setConfigFocus(null);
    setConfigStandalone(false);
  };
  const requestedConfigTarget = useMemo(
    () =>
      open && configRequest
        ? modelConfigTarget(
            configRequest.id,
            configRequest.meta,
            configRequest.displayName,
          )
        : null,
    [configRequest, open],
  );
  const visibleConfigTarget = open
    ? (requestedConfigTarget ?? configTarget)
    : null;
  const visibleConfigMatchesSelection =
    visibleConfigTarget !== null &&
    modelConfigTargetMatchesSelection(visibleConfigTarget, value);
  const visibleConfigIsResident =
    visibleConfigTarget !== null &&
    modelConfigTargetIsResident({
      target: visibleConfigTarget,
      selectedId: value,
      activeGgufVariant,
      loaded,
    });
  const visibleLoadedConfig = visibleConfigIsResident
    ? (activeModelConfig ?? null)
    : null;
  if (
    configRequest &&
    requestedConfigTarget &&
    adoptedConfigRequestId !== configRequest.requestId
  ) {
    setAdoptedConfigRequestId(configRequest.requestId);
    setConfigTarget(requestedConfigTarget);
    setConfigFocus(configRequest.focus ?? null);
    setConfigStandalone(configRequest.standalone === true);
  }
  useEffect(() => {
    if (!configRequest || adoptedConfigRequestId !== configRequest.requestId) {
      return;
    }
    onConfigRequestAdopted?.(configRequest.requestId);
  }, [adoptedConfigRequestId, configRequest, onConfigRequestAdopted]);
  const handlePick = (id: string, meta: ModelSelectorChangeMeta) => {
    if (meta.source === "external") {
      onSelect(id, meta);
      return;
    }
    const resolved = resolveInitialConfig(id, meta.ggufVariant);
    onSelect(id, {
      ...meta,
      ...(resolved.remembered ? { config: resolved.config } : {}),
    });
  };

  return (
    <PopoverContent
      align="start"
      alignOffset={10}
      dropdownGlow="picker"
      // Read by the model list, which sets its right inset against the panel's own.
      data-external={hasExternal || undefined}
      aria-label={
        visibleConfigTarget
          ? `Run settings for ${visibleConfigTarget.displayName}`
          : undefined
      }
      data-tour={dataTour}
      onKeyDown={handlePickerEntryKeyDown}
      className={cn(
        "unsloth-model-selector-menu menu-soft-surface ring-0 max-w-[calc(100vw-1rem)] min-w-0 gap-0",
        visibleConfigTarget
          ? // Clips, never scrolls: as the scroller, the always-on scrollbar squared off its corners.
            // !px-0: the list view's snapped inline padding would hold the scrollbar 8px off the edge.
            cn(
              "max-h-[var(--radix-popover-content-available-height)] overflow-hidden p-0 !px-0",
              hasExternal
                ? "w-[min(var(--picker-panel-w-external),calc(100vw-1rem))]"
                : "w-[min(var(--picker-panel-w),calc(100vw-1rem))]",
            )
          : cn(
              "pt-4 pb-0 pl-4",
              // Widths track the controls they hold so the row does not wrap.
              hasExternal
                ? "w-[min(var(--picker-panel-w-external),calc(100vw-1rem))] pr-4"
                : "w-[min(var(--picker-panel-w),calc(100vw-1rem))] pr-2",
            ),
        className,
      )}
    >
      <TooltipProvider
        delayDuration={0}
        skipDelayDuration={0}
        disableHoverableContent={true}
      >
        {visibleConfigTarget ? (
          // 28px sides like the list's text; the right is 20px plus the bar, an overlay strip capped at 8px.
          <div className="min-h-0 w-full overflow-y-auto pt-4.5 pr-[calc(var(--spacing)*5+min(var(--overlay-scrollbar-gutter,0px),var(--spacing)*2))] pb-4.5 pl-7 [scrollbar-gutter:stable]">
            <ModelConfigPage
              key={modelConfigInstanceKey(
                visibleConfigTarget.configId ?? visibleConfigTarget.id,
                visibleConfigTarget.ggufVariant,
                visibleLoadedConfig,
              )}
              target={visibleConfigTarget}
              onBack={
                configStandalone
                  ? undefined
                  : () => {
                      setConfigTarget(null);
                      setConfigFocus(null);
                    }
              }
              focusField={configFocus ?? undefined}
              onRun={(config, isDiffusion) =>
                onSelect(
                  visibleConfigTarget.configId ?? visibleConfigTarget.id,
                  {
                    ...visibleConfigTarget.meta,
                    config,
                    isDiffusion,
                    forceReload: true,
                  },
                )
              }
              loadedConfig={visibleLoadedConfig}
              loadedContextLength={
                visibleConfigIsResident
                  ? (activeLoadedContextLength ?? null)
                  : null
              }
              initialConfig={
                visibleConfigMatchesSelection &&
                ggufVariantsMatch(
                  selectedGgufVariant,
                  visibleConfigTarget.ggufVariant,
                )
                  ? (selectedConfig ?? null)
                  : null
              }
            />
          </div>
        ) : (
          <>
            <HubModelPicker
              open={open}
              models={models}
              additionalOnDeviceModels={additionalOnDeviceModels}
              loadedModelIdOverride={loadedModelIdOverride}
              loadedGgufVariantOverride={loadedGgufVariantOverride}
              loraModels={fineTunedModels}
              externalModels={externalModels}
              value={value}
              valueLoaded={loaded}
              onSelect={handlePick}
              resolveDownloadFootprint={resolveDownloadFootprint}
              onFoldersChange={onFoldersChange}
              onBrowseHub={onBrowseHub}
              onConfigureConnection={onConfigureConnection}
              onModelsChange={onModelsChange}
              onConfigure={openConfigPage}
              deleteDisabled={deleteDisabled}
              onEject={hasSelection && onEject ? onEject : undefined}
              onEjectAll={onEjectAll}
              task={task}
              catalog={catalog}
              communityModelPolicy={communityModelPolicy}
              opaqueKind={opaqueKind}
              rowFilter={rowFilter}
              cpuLoad={cpuLoad}
              moreModels={moreModels}
              npu={npu}
              onDeviceInventoryChange={setHasDeviceModels}
              section={effectiveHubSection}
              sectionToggle={
                <PillTabs
                  // The panel reserves --picker-tab-pad per pill, so keep the two in step.
                  className="[&_[role=tab]]:px-[calc(0.75rem*var(--ui-space-scale,1)_+_var(--picker-tab-pad)/2)]"
                  ariaLabel={t("picker.hubSectionAriaLabel")}
                  tabs={hubSectionTabs}
                  value={effectiveHubSection}
                  onValueChange={(next) => {
                    const section = next as HubSection;
                    setSectionChosenThisOpen(true);
                    setHubSection(section);
                    saveLastHubSection(section);
                  }}
                  fit={true}
                />
              }
            />
          </>
        )}
      </TooltipProvider>
    </PopoverContent>
  );
}

export function ModelSelector({
  models,
  additionalOnDeviceModels = [],
  loadedModelIdOverride,
  loadedGgufVariantOverride,
  loraModels = [],
  externalModels = [],
  externalConnections = [],
  value,
  defaultValue,
  activeGgufVariant,
  activeVariantIsMlx = false,
  activeModelConfig,
  activeLoadedContextLength,
  selectedConfig,
  selectedGgufVariant,
  configRequest,
  onConfigRequestAdopted,
  onValueChange,
  resolveDownloadFootprint,
  onEject,
  onEjectAll,
  onFoldersChange,
  onModelsChange,
  deleteDisabled,
  variant = "outline",
  size = "default",
  className,
  triggerLabelClassName,
  contentClassName,
  open: controlledOpen,
  onOpenChange,
  triggerDataTour,
  contentDataTour,
  showCloudIndicator = false,
  task,
  catalog,
  communityModelPolicy = "none",
  opaqueKind,
  rowFilter,
  cpuLoad,
  moreModels,
  hubCapability,
  hubTask,
  placeholder,
  loaded,
  loadedCount,
  loadedNames,
}: ModelSelectorProps) {
  const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
  const open = controlledOpen ?? uncontrolledOpen;
  const setOpen = onOpenChange ?? setUncontrolledOpen;
  const navigate = useNavigate();
  const t = useT();
  const [uncontrolled, setUncontrolled] = useState(defaultValue ?? "");

  const selected = value ?? uncontrolled;
  // The chat model can be evicted by an image or video load while the pick survives.
  const isLoaded = selected !== "" && (loaded ?? true);

  const optionById = useMemo(() => {
    const all = new Map<string, ModelOption>();
    for (const model of moreModels?.models ?? []) {
      all.set(model.id, model);
    }
    for (const model of models) {
      all.set(model.id, model);
    }
    for (const lora of loraModels) {
      const displayName = loraOptionLabel(lora);
      const isLocal = lora.source === "local";
      const isTraining = lora.source === "training";
      const isExported = lora.source === "exported";
      const isMerged = lora.exportType === "merged";
      const isGguf = lora.exportType === "gguf";
      const tag = isLocal
        ? isGguf
          ? "GGUF"
          : "Local"
        : isTraining && isMerged
          ? "Full finetune"
          : isExported
            ? isMerged
              ? "Merged · Exported"
              : "LoRA · Exported"
            : "LoRA";
      all.set(lora.id, {
        ...lora,
        name: displayName,
        description: tag,
      });
    }
    for (const externalModel of externalModels) {
      all.set(externalModel.id, {
        ...externalModel,
        description: externalModel.providerName,
        icon: (
          <ApiProviderLogo
            providerType={externalModel.providerType}
            className="size-4"
            title={externalModel.providerName}
          />
        ),
      });
    }
    return all;
  }, [externalModels, loraModels, models, moreModels]);

  // A task-owned quant names the trigger only while the trigger shows that loaded model.
  const triggerGgufVariant =
    loadedGgufVariantOverride !== undefined
      ? selected &&
        loadedModelIdOverride &&
        selected.toLowerCase() === loadedModelIdOverride.toLowerCase()
        ? loadedGgufVariantOverride
        : null
      : activeGgufVariant;
  const currentModel = useMemo(() => {
    if (!selected) return undefined;
    // A cached vendor copy loads for its unsloth mirror; name it by the mirror's option.
    const mirrorId =
      catalog && artifactForRepoId(selected, catalog)?.artifact.repoId;
    const found =
      optionById.get(selected) ??
      (mirrorId ? optionById.get(mirrorId) : undefined);
    // A pick the connection no longer offers keeps its `external::` id; name it and say why it is
    // unusable rather than letting the generic fallback hide the failure.
    const missingExternal = found
      ? null
      : missingExternalModel(selected, externalModels, externalConnections);
    // A cached GGUF's checkpoint is a snapshot path; the leaf matches the later catalog row.
    const fallbackName = missingExternal?.modelName ?? modelDisplayName(selected);
    if (triggerGgufVariant) {
      // The variant is the quant, so it goes in the suffix.
      const isMlx =
        activeVariantIsMlx && loadedGgufVariantOverride === undefined;
      const desc = `${isMlx ? "MLX" : "GGUF"} · ${triggerGgufVariant}`;
      return found
        ? { ...found, description: undefined, descriptionSuffix: desc }
        : { id: selected, name: fallbackName, descriptionSuffix: desc };
    }
    if (missingExternal) {
      const disabled = missingExternal.state === "disabled";
      return {
        id: selected,
        name: fallbackName,
        description: missingExternal.providerName
          ? t(
              disabled
                ? "picker.modelDisabledByProvider"
                : "picker.modelDroppedByProvider",
              { provider: missingExternal.providerName },
            )
          : t(disabled ? "picker.modelDisabled" : "picker.modelDropped"),
      };
    }
    return found ?? { id: selected, name: fallbackName };
  }, [
    selected,
    optionById,
    catalog,
    triggerGgufVariant,
    activeVariantIsMlx,
    loadedGgufVariantOverride,
    externalModels,
    externalConnections,
    t,
  ]);

  function handleSelect(id: string, meta: ModelSelectorChangeMeta) {
    if (onValueChange) {
      onValueChange(id, meta);
    } else {
      setUncontrolled(id);
    }
    setOpen(false);
  }

  function handleEject(modelId?: string) {
    onEject?.(modelId);
    if (!modelId) setOpen(false);
  }

  function handleEjectAll() {
    onEjectAll?.();
    setOpen(false);
  }

  function handleBrowseHub() {
    setOpen(false);
    const linkedTask = hubTask ?? task;
    void navigate({
      to: "/hub",
      search: {
        tab: "discover",
        capability: hubCapability,
        audioTask:
          hubCapability === "audio" && linkedTask ? [linkedTask].flat() : undefined,
      },
    });
  }

  // Remote model settings live on its connection, not ModelConfigPage's local load settings.
  function handleConfigureConnection(providerId: string) {
    setOpen(false);
    useSettingsDialogStore.getState().openConnectionSettings(providerId);
  }

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <ModelSelectorTrigger
        currentModel={currentModel}
        isLoaded={isLoaded}
        showCloudIndicator={showCloudIndicator}
        variant={variant}
        size={size}
        className={className}
        triggerLabelClassName={triggerLabelClassName}
        dataTour={triggerDataTour}
        onEject={onEject ? () => handleEject() : undefined}
        loadedCount={loadedCount}
        loadedNames={loadedNames}
        placeholder={placeholder}
      />
      <ModelSelectorContent
        open={open}
        models={models}
        additionalOnDeviceModels={additionalOnDeviceModels}
        loadedModelIdOverride={loadedModelIdOverride}
        loadedGgufVariantOverride={loadedGgufVariantOverride}
        loraModels={loraModels}
        externalModels={externalModels}
        value={selected}
        loaded={loaded}
        activeGgufVariant={activeGgufVariant}
        activeModelConfig={activeModelConfig}
        activeLoadedContextLength={activeLoadedContextLength}
        selectedConfig={selectedConfig}
        selectedGgufVariant={selectedGgufVariant}
        configRequest={configRequest}
        onConfigRequestAdopted={onConfigRequestAdopted}
        onSelect={handleSelect}
        resolveDownloadFootprint={resolveDownloadFootprint}
        onEject={onEject ? handleEject : undefined}
        onEjectAll={onEjectAll ? handleEjectAll : undefined}
        onFoldersChange={onFoldersChange}
        onBrowseHub={
          task && communityModelPolicy === "none" && !hubCapability
            ? undefined
            : handleBrowseHub
        }
        onConfigureConnection={handleConfigureConnection}
        onModelsChange={onModelsChange}
        deleteDisabled={deleteDisabled}
        className={contentClassName}
        dataTour={contentDataTour}
        task={task}
        catalog={catalog}
        communityModelPolicy={communityModelPolicy}
        opaqueKind={opaqueKind}
        rowFilter={rowFilter}
        cpuLoad={cpuLoad}
        moreModels={moreModels}
      />
    </Popover>
  );
}

ModelSelector.Trigger = ModelSelectorTrigger;
ModelSelector.Content = ModelSelectorContent;