Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

64.9 KB
Raw Blame
import { useState, useEffect, useCallback, useMemo, useRef, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "./ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Download, Trash2, Cloud, Lock, X, Zap, Check, CircleAlert } from "./icons";
import { ProviderIcon } from "./ui/ProviderIcon";
import { ProviderTabs } from "./ui/ProviderTabs";
import ModelCardList from "./ui/ModelCardList";
import { DownloadProgressBar } from "./ui/DownloadProgressBar";
import { ConfirmDialog } from "./ui/dialog";
import { useDialogs } from "../hooks/useDialogs";
import { useModelDownload, type DownloadProgress } from "../hooks/useModelDownload";
import {
  getTranscriptionProviders,
  getMeetingStreamingTranscriptionProviders,
  TranscriptionProviderData,
  WHISPER_MODEL_INFO,
  PARAKEET_MODEL_INFO,
  isSherpaLocalProvider,
} from "../models/ModelRegistry";
import {
  MODEL_PICKER_COLORS,
  type ColorScheme,
  type ModelPickerStyles,
} from "../utils/modelPickerStyles";
import { useSettingsStore } from "../stores/settingsStore";
import {
  filterByokProviderOptionsByPolicy,
  isProviderAllowedByPolicy,
  reconcileCloudProviderSelection,
  shouldPersistProviderFallback,
  type TranscriptionPolicyContext,
} from "../stores/policyRules";
import { usePolicySnapshot } from "../hooks/usePolicy";
import {
  LOCAL_ASR_ORGANIZATIONS,
  getASRModelOrganization,
  getSelectedASROrganization,
  usesParakeetManager,
} from "../helpers/localASROrganization";
import { STREAMING_ONLY_PROVIDERS } from "../helpers/transcriptionRoute";
import { getRemoteProviderIcon } from "../utils/providerIcons";
import { createExternalLinkHandler } from "../utils/externalLinks";
import { API_ENDPOINTS, normalizeBaseUrl } from "../config/constants";
import { isAzureOpenAIEndpoint } from "../utils/urlUtils";
import { GetApiKeyLink } from "./ui/GetApiKeyLink";
import { ConnectionCheckAnnouncer } from "./ui/ConnectionCheckAnnouncer";
import { ProviderCheckField } from "./ui/ProviderCheckField";
import { usePanelVisible } from "./ui/usePanelVisible";
import { useCredentialDraft } from "../hooks/useCredentialDraft";
import { useFocusHold } from "../hooks/useFocusHold";
import { useTypingPause } from "../hooks/useTypingPause";
import {
  useConnectionAutoCheck,
  type ProviderConnectionConfig,
} from "../hooks/useConnectionAutoCheck";
import { getCachedPlatform } from "../utils/platform";
import { pickWhisperGpuBackend } from "../utils/whisperGpuPack";
import logger from "../utils/logger";
import type { ParakeetCheckResult } from "../types/electron";

interface LocalModel {
  model: string;
  size_mb?: number;
  downloaded?: boolean;
}

interface LocalModelCardProps {
  modelId: string;
  name: string;
  description: string;
  size: string;
  actualSizeMb?: number;
  isSelected: boolean;
  isDownloaded: boolean;
  isDownloading: boolean;
  isCancelling: boolean;
  isInstalling: boolean;
  recommended?: boolean;
  provider: string;
  languageLabel?: string;
  modelCardUrl?: string;
  onSelect: () => void;
  onDelete: () => void;
  onDownload: () => void;
  onCancel: () => void;
  styles: ModelPickerStyles;
}

function LocalModelCard({
  modelId,
  name,
  description,
  size,
  actualSizeMb,
  isSelected,
  isDownloaded,
  isDownloading,
  isCancelling,
  isInstalling,
  recommended,
  provider,
  languageLabel,
  modelCardUrl,
  onSelect,
  onDelete,
  onDownload,
  onCancel,
  styles: cardStyles,
}: LocalModelCardProps) {
  const { t } = useTranslation();
  const handleClick = () => {
    if (isDownloaded && !isSelected) {
      onSelect();
    }
  };

  return (
    <div
      onClick={handleClick}
      className={`relative w-full text-start overflow-hidden rounded-md border transition-colors duration-200 group ${
        isSelected ? cardStyles.modelCard.selected : cardStyles.modelCard.default
      } ${isDownloaded && !isSelected ? "cursor-pointer" : ""}`}
    >
      <div className="flex items-center gap-1.5 p-2">
        <div className="shrink-0">
          {isDownloaded ? (
            <div
              className={`w-1.5 h-1.5 rounded-full ${
                isSelected
                  ? "bg-primary shadow-[0_0_6px_oklch(0.62_0.22_260/0.6)] animate-[pulse-glow_2s_ease-in-out_infinite]"
                  : "bg-success shadow-[0_0_4px_rgba(34,197,94,0.5)]"
              }`}
            />
          ) : isDownloading ? (
            <div className="w-1.5 h-1.5 rounded-full bg-amber-500 shadow-[0_0_4px_rgba(245,158,11,0.5)] animate-[spinner-rotate_1s_linear_infinite]" />
          ) : (
            <div className="w-1.5 h-1.5 rounded-full bg-muted-foreground/20" />
          )}
        </div>

        <div className="flex-1 min-w-0 flex items-center gap-1.5">
          <ProviderIcon provider={provider} className="w-3.5 h-3.5 shrink-0" />
          <span className="font-semibold text-sm text-foreground truncate tracking-tight">
            {name}
          </span>
          <span className="text-xs text-muted-foreground/70 tabular-nums shrink-0">
            {actualSizeMb ? `${actualSizeMb}MB` : size}
          </span>
          {recommended && (
            <span className={cardStyles.badges.recommended}>{t("common.recommended")}</span>
          )}
          {languageLabel && (
            <span className="text-xs text-muted-foreground/70 font-medium shrink-0">
              {languageLabel}
            </span>
          )}
        </div>

        <div className="flex items-center gap-1.5 shrink-0">
          {isDownloaded ? (
            <>
              {isSelected && (
                <span className="text-xs font-medium text-primary px-2 py-0.5 bg-primary/10 rounded-sm">
                  {t("common.active")}
                </span>
              )}
              <Button
                onClick={(e) => {
                  e.stopPropagation();
                  onDelete();
                }}
                size="icon"
                variant="ghost"
                className="size-6 text-muted-foreground/70 hover:text-destructive opacity-0 group-hover:opacity-100 transition-[color,opacity,transform] active:scale-95"
              >
                <Trash2 size={12} />
              </Button>
            </>
          ) : isDownloading ? (
            <Button
              onClick={(e) => {
                e.stopPropagation();
                onCancel();
              }}
              disabled={isCancelling || isInstalling}
              size="sm"
              variant="outline"
              className="h-6 px-2.5 text-xs text-destructive border-destructive/25 hover:bg-destructive/8"
            >
              <X size={11} className="me-0.5" />
              {isCancelling ? "..." : t("common.cancel")}
            </Button>
          ) : (
            <Button
              onClick={(e) => {
                e.stopPropagation();
                onDownload();
              }}
              size="sm"
              variant="default"
              className="h-6 px-2.5 text-xs"
            >
              <Download size={11} className="me-1" />
              {t("common.download")}
            </Button>
          )}
        </div>
      </div>
      {modelCardUrl && (
        <a
          href={modelCardUrl}
          target="_blank"
          rel="noopener noreferrer"
          onClick={(event) => {
            event.stopPropagation();
            createExternalLinkHandler(modelCardUrl)(event);
          }}
          className="inline-block ms-7 mb-2 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2"
        >
          {t("transcription.modelCard")}
        </a>
      )}
    </div>
  );
}

interface TranscriptionModelPickerProps {
  /** Settings scope whose provider/model keys this picker edits. */
  transcriptionContext?: TranscriptionPolicyContext;
  selectedCloudProvider: string;
  /**
   * Policy reconciliation only — a user-driven pick goes through
   * switchCloudTranscriptionProvider so the outgoing model survives the swap.
   */
  onCloudProviderSelect: (providerId: string) => void;
  selectedCloudModel: string;
  onCloudModelSelect: (modelId: string) => void;
  selectedLocalModel: string;
  onLocalModelSelect: (modelId: string, providerId?: string) => void;
  selectedLocalProvider?: string;
  onLocalProviderSelect?: (providerId: string) => void;
  useLocalWhisper: boolean;
  onModeChange: (useLocal: boolean) => void;
  cloudTranscriptionBaseUrl?: string;
  setCloudTranscriptionBaseUrl?: (url: string) => void;
  className?: string;
  variant?: "onboarding" | "settings";
  mode?: "cloud" | "local";
  streamingOnly?: boolean;
}

const CLOUD_PROVIDER_TABS = [
  { id: "openai", name: "OpenAI" },
  { id: "groq", name: "Groq" },
  { id: "xai", name: "xAI" },
  { id: "mistral", name: "Mistral" },
  { id: "gemini", name: "Gemini" },
  { id: "corti", name: "Corti" },
  { id: "tinfoil", name: "Tinfoil" },
  { id: "deepgram", name: "Deepgram" },
  { id: "assemblyai", name: "AssemblyAI" },
  { id: "custom", name: "Custom" },
];

interface ProviderCredentialField {
  key:
    | "openaiApiKey"
    | "groqApiKey"
    | "xaiApiKey"
    | "mistralApiKey"
    | "geminiApiKey"
    | "cortiClientId"
    | "cortiClientSecret"
    | "cortiEnvironment"
    | "cortiTenant"
    | "tinfoilApiKey"
    | "deepgramApiKey"
    | "assemblyaiApiKey";
  input: "secret" | "text" | "select";
  labelKey?: string;
  placeholder?: string;
  options?: Array<{ value: string; label: string }>;
}

const PROVIDER_CREDENTIALS: Record<
  string,
  { consoleUrl: string; fields: ProviderCredentialField[] }
> = {
  openai: {
    consoleUrl: "https://platform.openai.com/api-keys",
    fields: [{ key: "openaiApiKey", input: "secret" }],
  },
  groq: {
    consoleUrl: "https://console.groq.com/keys",
    fields: [{ key: "groqApiKey", input: "secret" }],
  },
  xai: {
    consoleUrl: "https://console.x.ai",
    fields: [{ key: "xaiApiKey", input: "secret" }],
  },
  mistral: {
    consoleUrl: "https://console.mistral.ai/api-keys",
    fields: [{ key: "mistralApiKey", input: "secret" }],
  },
  gemini: {
    consoleUrl: "https://aistudio.google.com/apikey",
    fields: [{ key: "geminiApiKey", input: "secret" }],
  },
  corti: {
    consoleUrl: "https://www.corti.ai/?utm_source=referral&utm_content=&utm_campaign=openwhispr",
    fields: [
      { key: "cortiClientId", input: "text", labelKey: "transcription.corti.clientId" },
      { key: "cortiClientSecret", input: "secret", labelKey: "transcription.corti.clientSecret" },
      {
        key: "cortiEnvironment",
        input: "select",
        labelKey: "transcription.corti.environment",
        options: [
          { value: "us", label: "US" },
          { value: "eu", label: "EU" },
        ],
      },
      {
        key: "cortiTenant",
        input: "text",
        labelKey: "transcription.corti.tenant",
        placeholder: "base",
      },
    ],
  },
  tinfoil: {
    consoleUrl: "https://tinfoil.sh/inference?utm_source=referral&utm_campaign=openwhispr",
    fields: [{ key: "tinfoilApiKey", input: "secret" }],
  },
  deepgram: {
    consoleUrl: "https://console.deepgram.com/",
    fields: [{ key: "deepgramApiKey", input: "secret" }],
  },
  assemblyai: {
    consoleUrl: "https://www.assemblyai.com/dashboard/api-keys",
    fields: [{ key: "assemblyaiApiKey", input: "secret" }],
  },
};

const TINFOIL_AUDIO_DOCS_URL = "https://docs.tinfoil.sh/models/audio";

const LOCAL_PROVIDER_TABS: Array<{ id: string; name: string; disabled?: boolean }> =
  LOCAL_ASR_ORGANIZATIONS;

interface ModeToggleProps {
  useLocalWhisper: boolean;
  onModeChange: (useLocal: boolean) => void;
}

function ModeToggle({ useLocalWhisper, onModeChange }: ModeToggleProps) {
  const { t } = useTranslation();
  return (
    <div className="relative flex p-0.5 rounded-lg bg-surface-1/80 backdrop-blur-xl dark:bg-surface-1 border border-border/70 dark:border-white/10 shadow-(--shadow-metallic-light) dark:shadow-(--shadow-metallic-dark)">
      <div
        className={`absolute top-0.5 bottom-0.5 w-[calc(50%-2px)] rounded-md bg-card border border-border/70 dark:border-border-subtle shadow-(--shadow-metallic-light) dark:shadow-(--shadow-metallic-dark) transition-transform duration-200 ease-out ${
          useLocalWhisper
            ? "translate-x-[calc(100%)] rtl:-translate-x-[calc(100%)]"
            : "translate-x-0"
        }`}
      />
      <button
        onClick={() => onModeChange(false)}
        className={`relative z-10 flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md transition-colors duration-150 ${
          !useLocalWhisper ? "text-foreground" : "text-muted-foreground hover:text-foreground"
        }`}
      >
        <Cloud className="w-3.5 h-3.5" />
        <span className="text-xs font-medium">{t("common.cloud")}</span>
      </button>
      <button
        onClick={() => onModeChange(true)}
        className={`relative z-10 flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md transition-colors duration-150 ${
          useLocalWhisper ? "text-foreground" : "text-muted-foreground hover:text-foreground"
        }`}
      >
        <Lock className="w-3.5 h-3.5" />
        <span className="text-xs font-medium">{t("common.local")}</span>
      </button>
    </div>
  );
}

interface GpuWarningRowProps {
  title: string;
  description: string;
  actionLabel: string;
  onAction: () => void;
  onRemove: () => void;
  children?: ReactNode;
}

function GpuWarningRow({
  title,
  description,
  actionLabel,
  onAction,
  onRemove,
  children,
}: GpuWarningRowProps) {
  const { t } = useTranslation();
  return (
    <div className="flex items-start justify-between gap-3">
      <div className="flex min-w-0 items-start gap-2">
        <CircleAlert size={15} className="mt-0.5 shrink-0 text-warning" />
        <div className="min-w-0">
          <p className="text-xs font-medium text-foreground">{title}</p>
          <p className="mt-0.5 text-xs leading-snug text-muted-foreground">{description}</p>
          {children}
          <Button onClick={onAction} size="sm" className="mt-2 h-7 px-3 text-xs">
            {actionLabel}
          </Button>
        </div>
      </div>
      <Button
        onClick={onRemove}
        size="sm"
        variant="ghost"
        className="h-6 shrink-0 px-2 text-xs text-muted-foreground hover:text-destructive"
      >
        {t("gpu.remove")}
      </Button>
    </div>
  );
}

export default function TranscriptionModelPicker({
  transcriptionContext = "dictation",
  selectedCloudProvider,
  onCloudProviderSelect,
  selectedCloudModel,
  onCloudModelSelect,
  selectedLocalModel,
  onLocalModelSelect,
  selectedLocalProvider = "whisper",
  onLocalProviderSelect,
  useLocalWhisper,
  onModeChange,
  cloudTranscriptionBaseUrl = "",
  setCloudTranscriptionBaseUrl,
  className = "",
  variant = "settings",
  mode,
  streamingOnly = false,
}: TranscriptionModelPickerProps) {
  const { t } = useTranslation();
  const switchCloudTranscriptionProvider = useSettingsStore(
    (s) => s.switchCloudTranscriptionProvider
  );
  const openaiApiKey = useSettingsStore((s) => s.openaiApiKey);
  const setOpenaiApiKey = useSettingsStore((s) => s.setOpenaiApiKey);
  const groqApiKey = useSettingsStore((s) => s.groqApiKey);
  const setGroqApiKey = useSettingsStore((s) => s.setGroqApiKey);
  const xaiApiKey = useSettingsStore((s) => s.xaiApiKey);
  const setXaiApiKey = useSettingsStore((s) => s.setXaiApiKey);
  const mistralApiKey = useSettingsStore((s) => s.mistralApiKey);
  const setMistralApiKey = useSettingsStore((s) => s.setMistralApiKey);
  const geminiApiKey = useSettingsStore((s) => s.geminiApiKey);
  const setGeminiApiKey = useSettingsStore((s) => s.setGeminiApiKey);
  const cortiClientId = useSettingsStore((s) => s.cortiClientId);
  const setCortiClientId = useSettingsStore((s) => s.setCortiClientId);
  const cortiClientSecret = useSettingsStore((s) => s.cortiClientSecret);
  const setCortiClientSecret = useSettingsStore((s) => s.setCortiClientSecret);
  const cortiEnvironment = useSettingsStore((s) => s.cortiEnvironment);
  const setCortiEnvironment = useSettingsStore((s) => s.setCortiEnvironment);
  const cortiTenant = useSettingsStore((s) => s.cortiTenant);
  const setCortiTenant = useSettingsStore((s) => s.setCortiTenant);
  const tinfoilApiKey = useSettingsStore((s) => s.tinfoilApiKey);
  const setTinfoilApiKey = useSettingsStore((s) => s.setTinfoilApiKey);
  const deepgramApiKey = useSettingsStore((s) => s.deepgramApiKey);
  const setDeepgramApiKey = useSettingsStore((s) => s.setDeepgramApiKey);
  const assemblyaiApiKey = useSettingsStore((s) => s.assemblyaiApiKey);
  const setAssemblyaiApiKey = useSettingsStore((s) => s.setAssemblyaiApiKey);
  const customTranscriptionApiKey = useSettingsStore((s) => s.customTranscriptionApiKey);
  const setCustomTranscriptionApiKey = useSettingsStore((s) => s.setCustomTranscriptionApiKey);
  const isSignedIn = useSettingsStore((s) => s.isSignedIn);
  const effectiveLocal = mode === "local" ? true : mode === "cloud" ? false : useLocalWhisper;
  const [localModels, setLocalModels] = useState<LocalModel[]>([]);
  const [parakeetModels, setParakeetModels] = useState<LocalModel[]>([]);
  const [parakeetCapability, setParakeetCapability] = useState<ParakeetCheckResult | null>(null);
  const [browsedCloudProvider, setBrowsedCloudProvider] = useState<string | null>(null);
  const [internalLocalProvider, setInternalLocalProvider] = useState(
    getSelectedASROrganization(selectedLocalProvider, selectedLocalModel)
  );
  const hasLoadedRef = useRef(false);
  const hasLoadedParakeetRef = useRef(false);
  const [gpuBackend, setGpuBackend] = useState<"cuda" | "vulkan" | null>(null);
  const [gpuDownloaded, setGpuDownloaded] = useState(false);
  const [gpuDownloading, setGpuDownloading] = useState(false);
  const [gpuProgress, setGpuProgress] = useState<DownloadProgress>({
    downloadedBytes: 0,
    totalBytes: 0,
    percentage: 0,
  });
  const [gpuDismissed, setGpuDismissed] = useState(false);
  // The pack fell back to CPU on this machine (persisted by main until retried)
  const [gpuFailed, setGpuFailed] = useState(false);
  // The whisper-server error line main saved with that failure (#1736)
  const [gpuFailReason, setGpuFailReason] = useState<string | null>(null);
  // An older release installed the pack and this version can't use it (#2424)
  const [gpuNeedsUpdate, setGpuNeedsUpdate] = useState(false);
  // Why the last pack download failed (cleared by the next attempt)
  const [gpuDownloadError, setGpuDownloadError] = useState<string | null>(null);
  // The running download was started before Settings was last opened, so no
  // pending call here will report its end: its status is polled instead
  const [gpuResumedDownload, setGpuResumedDownload] = useState(false);
  const gpuDownloadCancelledRef = useRef(false);
  // A server reload with the new backend is in flight (Vulkan cold starts are slow)
  const [gpuActivating, setGpuActivating] = useState(false);
  // Live truth from the running server; "active" is never inferred from a download
  const [gpuActive, setGpuActive] = useState(false);
  const gpuBackendName = gpuBackend === "cuda" ? "CUDA" : "Vulkan";

  useEffect(() => {
    const organization = getSelectedASROrganization(selectedLocalProvider, selectedLocalModel);
    if (organization !== internalLocalProvider) {
      setInternalLocalProvider(organization);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- sync prop→state: only re-run when the prop changes
  }, [selectedLocalProvider, selectedLocalModel]);

  useEffect(() => {
    let cancelled = false;

    window.electronAPI
      ?.checkParakeetInstallation?.()
      .then((capability) => {
        if (!cancelled) setParakeetCapability(capability);
      })
      .catch((error) => {
        logger.error("Failed to check Parakeet compatibility", { error }, "models");
      });

    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    if (parakeetCapability?.supported !== false) return;

    // Tabs are pure browse state, so the browsed tab and the committed
    // provider must each leave the sherpa tabs on their own: moving the tab off
    // the disabled entry keeps the UI usable, while committing "whisper"
    // is what actually reroutes transcription on unsupported Macs.
    if (usesParakeetManager(internalLocalProvider)) setInternalLocalProvider("whisper");
    if (isSherpaLocalProvider(selectedLocalProvider)) onLocalProviderSelect?.("whisper");
  }, [internalLocalProvider, onLocalProviderSelect, parakeetCapability, selectedLocalProvider]);

  const localModelsLoadQueueRef = useRef<Promise<void>>(Promise.resolve());
  const parakeetModelsLoadQueueRef = useRef<Promise<void>>(Promise.resolve());
  const loadLocalModelsRef = useRef<(() => Promise<void>) | null>(null);
  const loadParakeetModelsRef = useRef<(() => Promise<void>) | null>(null);
  const selectedLocalModelRef = useRef(selectedLocalModel);
  const onLocalModelSelectRef = useRef(onLocalModelSelect);

  const { confirmDialog, showConfirmDialog, hideConfirmDialog } = useDialogs();
  const colorScheme: ColorScheme = variant === "settings" ? "purple" : "blue";
  const styles = useMemo(() => MODEL_PICKER_COLORS[colorScheme], [colorScheme]);
  const policyState = usePolicySnapshot();
  const providerAllowed = useCallback(
    (providerId: string) => isProviderAllowedByPolicy(policyState, "transcription", providerId),
    [policyState]
  );
  // streamingOnly is Note Recording's picker, so it offers the streaming
  // providers note recording can actually run — not every streaming provider.
  // Upload is always http-batch, and the realtime-only providers have no batch
  // route at all (transcriptionRoute fails them closed), so they are hidden there.
  const availableCloudProviders = useMemo(() => {
    if (streamingOnly) return getMeetingStreamingTranscriptionProviders();
    const providers = getTranscriptionProviders();
    if (transcriptionContext !== "upload") return providers;
    return providers.filter((provider) => !STREAMING_ONLY_PROVIDERS.has(provider.id));
  }, [streamingOnly, transcriptionContext]);
  const cloudProviders = useMemo(
    () => filterByokProviderOptionsByPolicy(availableCloudProviders, "transcription", policyState),
    [availableCloudProviders, policyState]
  );
  const cloudProviderTabs = useMemo(() => {
    const availableIds = new Set(availableCloudProviders.map((p) => p.id));
    if (!streamingOnly) availableIds.add("custom");
    const tabs = CLOUD_PROVIDER_TABS.filter((provider) => availableIds.has(provider.id)).map(
      (provider) =>
        provider.id === "custom"
          ? { ...provider, name: t("transcription.customProvider") }
          : provider
    );
    return filterByokProviderOptionsByPolicy(tabs, "transcription", policyState);
  }, [availableCloudProviders, policyState, streamingOnly, t]);
  const localProviderTabs = useMemo(
    () =>
      LOCAL_PROVIDER_TABS.map((provider) =>
        usesParakeetManager(provider.id) && parakeetCapability?.supported === false
          ? {
              ...provider,
              disabled: true,
              disabledLabel: parakeetCapability.minimumMacOSVersion
                ? t("transcription.parakeet.requiresMacOS", {
                    version: parakeetCapability.minimumMacOSVersion,
                  })
                : t("transcription.parakeet.unavailable"),
            }
          : provider
      ),
    [parakeetCapability, t]
  );

  useEffect(() => {
    selectedLocalModelRef.current = selectedLocalModel;
  }, [selectedLocalModel]);
  useEffect(() => {
    onLocalModelSelectRef.current = onLocalModelSelect;
  }, [onLocalModelSelect]);

  const validateAndSelectModel = useCallback((loadedModels: LocalModel[]) => {
    const current = selectedLocalModelRef.current;
    if (!current) return;

    // The whisper list loads on a mere browse of the Whisper tab, so the
    // committed selection can be a foreign id (a Parakeet model while nvidia
    // is committed) — only replace ids this list owns.
    const currentEntry = loadedModels.find((m) => m.model === current);
    if (!currentEntry || currentEntry.downloaded) return;

    const downloaded = loadedModels.filter((m) => m.downloaded);
    onLocalModelSelectRef.current(downloaded[0]?.model ?? "", "whisper");
  }, []);

  const loadLocalModels = useCallback(() => {
    const load = async () => {
      try {
        const result = await window.electronAPI?.listWhisperModels();
        if (result?.success) {
          setLocalModels(result.models);
          validateAndSelectModel(result.models);
        }
      } catch (error) {
        logger.error("Failed to load models", { error }, "models");
        setLocalModels([]);
      }
    };

    const queuedLoad = localModelsLoadQueueRef.current.then(load);
    localModelsLoadQueueRef.current = queuedLoad;
    return queuedLoad;
  }, [validateAndSelectModel]);

  const loadParakeetModels = useCallback(() => {
    const load = async () => {
      try {
        const result = await window.electronAPI?.listParakeetModels();
        if (result?.success) {
          setParakeetModels(result.models);
        }
      } catch (error) {
        logger.error("Failed to load Parakeet models", { error }, "models");
        setParakeetModels([]);
      }
    };

    const queuedLoad = parakeetModelsLoadQueueRef.current.then(load);
    parakeetModelsLoadQueueRef.current = queuedLoad;
    return queuedLoad;
  }, []);

  const effectiveCloudSelection = useMemo(() => {
    // Every provider's URL counts as known, including policy-blocked ones and
    // the ones this scope does not offer: otherwise such a provider's stored URL
    // reads as a custom endpoint and reconciliation would keep pointing "custom"
    // at what policy — or this scope — just denied.
    const knownProviderUrls = new Set(
      getTranscriptionProviders().map((provider) => normalizeBaseUrl(provider.baseUrl))
    );
    const normalizedBaseUrl = normalizeBaseUrl(cloudTranscriptionBaseUrl);
    const hasCustomUrl = Boolean(
      normalizedBaseUrl &&
      normalizedBaseUrl !== normalizeBaseUrl(API_ENDPOINTS.TRANSCRIPTION_BASE) &&
      !knownProviderUrls.has(normalizedBaseUrl)
    );
    // Reconcile null means the input needs no correction — echo the browsed
    // input, not the committed pair, or browsing to the Custom tab (always
    // reconciled as valid) would never display it.
    return (
      reconcileCloudProviderSelection({
        selectedProvider: browsedCloudProvider ?? selectedCloudProvider,
        selectedModel: selectedCloudModel,
        allowedProviders: cloudProviders,
        customAllowed: !streamingOnly && providerAllowed("custom"),
        hasCustomUrl,
      }) ?? {
        provider: browsedCloudProvider ?? selectedCloudProvider,
        model: selectedCloudModel,
      }
    );
  }, [
    cloudProviders,
    cloudTranscriptionBaseUrl,
    browsedCloudProvider,
    selectedCloudProvider,
    selectedCloudModel,
    providerAllowed,
    streamingOnly,
  ]);
  const displayedCloudProvider = effectiveCloudSelection.provider;
  const displayedCloudModel = effectiveCloudSelection.model;

  useEffect(() => {
    if (
      effectiveLocal ||
      browsedCloudProvider ||
      !shouldPersistProviderFallback(policyState, isSignedIn) ||
      (effectiveCloudSelection.provider === selectedCloudProvider &&
        effectiveCloudSelection.model === selectedCloudModel)
    ) {
      return;
    }
    if (effectiveCloudSelection.provider !== selectedCloudProvider) {
      onCloudProviderSelect(effectiveCloudSelection.provider);
    }
    if (effectiveCloudSelection.model !== selectedCloudModel) {
      onCloudModelSelect(effectiveCloudSelection.model);
    }
  }, [
    effectiveCloudSelection,
    effectiveLocal,
    browsedCloudProvider,
    isSignedIn,
    onCloudModelSelect,
    onCloudProviderSelect,
    policyState,
    selectedCloudModel,
    selectedCloudProvider,
  ]);

  useEffect(() => {
    loadLocalModelsRef.current = loadLocalModels;
  }, [loadLocalModels]);
  useEffect(() => {
    loadParakeetModelsRef.current = loadParakeetModels;
  }, [loadParakeetModels]);
  useEffect(() => {
    if (!effectiveLocal) return;

    if (internalLocalProvider === "whisper" && !hasLoadedRef.current) {
      hasLoadedRef.current = true;
      loadLocalModelsRef.current?.();
    } else if (usesParakeetManager(internalLocalProvider) && !hasLoadedParakeetRef.current) {
      hasLoadedParakeetRef.current = true;
      loadParakeetModelsRef.current?.();
    }
  }, [effectiveLocal, internalLocalProvider]);

  useEffect(() => {
    if (effectiveLocal) return;

    hasLoadedRef.current = false;
    hasLoadedParakeetRef.current = false;
  }, [effectiveLocal]);

  useEffect(() => {
    const handleModelsCleared = () => {
      loadLocalModels();
      loadParakeetModels();
    };
    window.addEventListener("openwhispr-models-cleared", handleModelsCleared);
    return () => window.removeEventListener("openwhispr-models-cleared", handleModelsCleared);
  }, [loadLocalModels, loadParakeetModels]);

  const readGpuStatus = useCallback(async () => {
    try {
      const [cuda, vulkan] = await Promise.all([
        window.electronAPI?.getCudaWhisperStatus?.(),
        window.electronAPI?.getVulkanWhisperStatus?.(),
      ]);
      // No pack to show or offer hides the card. A re-read can land here after
      // another card removed the pack this one shows, so reset, never keep it.
      const backend = pickWhisperGpuBackend(cuda, vulkan);
      const status = backend === "cuda" ? cuda : backend === "vulkan" ? vulkan : null;
      setGpuBackend(backend);
      setGpuDownloaded(!!status?.downloaded);
      setGpuFailed(!!status?.gpuFailed);
      setGpuFailReason(status?.gpuFailReason ?? null);
      setGpuNeedsUpdate(!!status?.needsUpdate);
      // A failed attempt's error must not outlive the state it was about
      setGpuDownloadError(null);
      // A download is still running that no pending call here may report the
      // end of: one started before Settings was opened, or on another card
      if (status?.downloading) {
        setGpuDownloading(true);
        setGpuResumedDownload(true);
      }
    } catch {}
  }, []);

  useEffect(() => {
    if (!effectiveLocal || internalLocalProvider !== "whisper") return;
    if (getCachedPlatform() === "darwin") return;
    readGpuStatus();
    // Retry on the fallback pop-up, or Remove on another card, changes the
    // packs or the saved failure while this card stays mounted (#1736)
    return window.electronAPI?.onWhisperGpuStatusChanged?.(readGpuStatus);
  }, [effectiveLocal, internalLocalProvider, readGpuStatus]);

  useEffect(() => {
    if (!gpuDownloading || !gpuBackend) return;
    const subscribe =
      gpuBackend === "cuda"
        ? window.electronAPI?.onCudaDownloadProgress
        : window.electronAPI?.onVulkanWhisperDownloadProgress;
    return subscribe?.((data) => setGpuProgress(data));
  }, [gpuDownloading, gpuBackend]);

  useEffect(() => {
    if (!gpuResumedDownload || !gpuBackend) return;
    const id = setInterval(async () => {
      try {
        const status =
          gpuBackend === "cuda"
            ? await window.electronAPI?.getCudaWhisperStatus?.()
            : await window.electronAPI?.getVulkanWhisperStatus?.();
        if (!status || status.downloading) return;
        setGpuResumedDownload(false);
        setGpuDownloading(false);
        setGpuDownloaded(status.downloaded);
        setGpuFailed(!!status.gpuFailed);
        setGpuNeedsUpdate(!!status.needsUpdate);
      } catch {}
    }, 1000);
    return () => clearInterval(id);
  }, [gpuResumedDownload, gpuBackend]);

  // Live server state: "GPU acceleration active" reflects what the server is
  // actually running on, not just that a pack is on disk (a crashed GPU server
  // silently falls back to CPU). Faster poll while an activation is in flight.
  // Polls again at once when a re-read switches the card to another pack.
  useEffect(() => {
    if (!effectiveLocal || internalLocalProvider !== "whisper" || !gpuDownloaded) return;
    const poll = () => {
      window.electronAPI
        ?.whisperServerStatus?.()
        .then((status) => {
          setGpuActive(!!status?.gpuAccelerated);
          if (status?.gpuAccelerated) setGpuActivating(false);
        })
        .catch(() => {});
    };
    poll();
    const id = setInterval(poll, gpuActivating ? 1000 : 5000);
    return () => clearInterval(id);
  }, [effectiveLocal, internalLocalProvider, gpuDownloaded, gpuActivating, gpuBackend]);

  // Safety valve: a Vulkan cold start can take up to ~2 minutes (see #698);
  // past that the live status or a fallback notification settles the state.
  useEffect(() => {
    if (!gpuActivating) return;
    const timeout = setTimeout(() => setGpuActivating(false), 150_000);
    return () => clearTimeout(timeout);
  }, [gpuActivating]);

  // Main falls back to CPU (and remembers it) when a GPU server crashes. It
  // saves the failure before it notifies, so the re-read shows the pack main
  // now reports in use, exactly as reopening Settings would (#1736).
  useEffect(() => {
    const onFallback = () => {
      setGpuFailed(true);
      // Never show the previous failure's reason while the new one loads
      setGpuFailReason(null);
      setGpuActivating(false);
      setGpuActive(false);
      readGpuStatus();
    };
    const disposeCuda = window.electronAPI?.onCudaFallbackNotification?.(onFallback);
    const disposeVulkan = window.electronAPI?.onGpuFallbackNotification?.(onFallback);
    return () => {
      disposeCuda?.();
      disposeVulkan?.();
    };
  }, [readGpuStatus]);

  const handleGpuDownload = async () => {
    setGpuDownloading(true);
    setGpuDownloadError(null);
    gpuDownloadCancelledRef.current = false;
    try {
      const result =
        gpuBackend === "cuda"
          ? await window.electronAPI?.downloadCudaWhisperBinary?.()
          : await window.electronAPI?.downloadVulkanWhisperBinary?.();
      if (result?.success) {
        setGpuDownloaded(true);
        setGpuFailed(false);
        setGpuNeedsUpdate(false);
        // Main reloads the server with the new backend only when one is loaded;
        // otherwise the pack simply engages on the next dictation.
        setGpuActivating(!!result.willRestart);
      } else if (result && !gpuDownloadCancelledRef.current) {
        setGpuDownloadError(result.error ?? "");
      }
    } finally {
      setGpuDownloading(false);
    }
  };

  const handleGpuRetry = async () => {
    setGpuFailed(false);
    const result = await window.electronAPI?.whisperGpuRetry?.();
    setGpuActivating(!!result?.willRestart);
  };

  const handleGpuDelete = async () => {
    const result =
      gpuBackend === "cuda"
        ? await window.electronAPI?.deleteCudaWhisperBinary?.()
        : await window.electronAPI?.deleteVulkanWhisperBinary?.();
    if (result?.success) {
      setGpuDownloaded(false);
      setGpuFailed(false);
      setGpuNeedsUpdate(false);
      setGpuDownloadError(null);
      setGpuActivating(false);
      setGpuActive(false);
    }
  };

  const handleGpuCancel = async () => {
    gpuDownloadCancelledRef.current = true;
    if (gpuBackend === "cuda") await window.electronAPI?.cancelCudaWhisperDownload?.();
    else await window.electronAPI?.cancelVulkanWhisperDownload?.();
    setGpuDownloading(false);
  };

  const {
    downloads: whisperDownloads,
    downloadModel,
    deleteModel,
    isDownloadingModel,
    cancelDownload,
    isCancellingModel,
  } = useModelDownload({
    modelType: "whisper",
    onDownloadComplete: loadLocalModels,
  });

  const {
    downloads: parakeetDownloads,
    downloadModel: downloadParakeetModel,
    deleteModel: deleteParakeetModel,
    isDownloadingModel: isDownloadingParakeetModel,
    cancelDownload: cancelParakeetDownload,
    isCancellingModel: isCancellingParakeetModel,
  } = useModelDownload({
    modelType: "parakeet",
    onDownloadComplete: loadParakeetModels,
  });

  const handleModeChange = useCallback(
    (isLocal: boolean) => {
      onModeChange(isLocal);
    },
    [onModeChange]
  );

  const handleCloudProviderChange = useCallback(
    (providerId: string) => {
      if (!providerAllowed(providerId)) return;
      setBrowsedCloudProvider(providerId);
    },
    [providerAllowed]
  );

  const handleLocalProviderChange = useCallback(
    (providerId: string) => {
      const tab = localProviderTabs.find((candidate) => candidate.id === providerId);
      if (tab?.disabled) return;
      setInternalLocalProvider(providerId);
    },
    [localProviderTabs]
  );

  const handleCloudModelSelect = useCallback(
    (modelId: string) => {
      if (displayedCloudProvider !== selectedCloudProvider) {
        switchCloudTranscriptionProvider(transcriptionContext, displayedCloudProvider);
      }
      onCloudModelSelect(modelId);
      setBrowsedCloudProvider(null);
    },
    [
      displayedCloudProvider,
      onCloudModelSelect,
      selectedCloudProvider,
      switchCloudTranscriptionProvider,
      transcriptionContext,
    ]
  );

  const handleWhisperModelSelect = useCallback(
    (modelId: string) => {
      setInternalLocalProvider("whisper");
      onLocalProviderSelect?.("whisper");
      onLocalModelSelect(modelId, "whisper");
    },
    [onLocalModelSelect, onLocalProviderSelect]
  );

  const handleParakeetModelSelect = useCallback(
    (modelId: string) => {
      const organization = getASRModelOrganization(modelId);
      const provider = organization === "cohere" ? "cohere" : "nvidia";
      setInternalLocalProvider(organization);
      onLocalProviderSelect?.(provider);
      onLocalModelSelect(modelId, provider);
    },
    [onLocalModelSelect, onLocalProviderSelect]
  );

  const handleBaseUrlBlur = useCallback(() => {
    if (!setCloudTranscriptionBaseUrl || selectedCloudProvider !== "custom") return;

    const trimmed = (cloudTranscriptionBaseUrl || "").trim();
    if (!trimmed) return;

    const normalized = normalizeBaseUrl(trimmed);

    if (normalized && normalized !== cloudTranscriptionBaseUrl) {
      setCloudTranscriptionBaseUrl(normalized);
    }
    if (normalized) {
      for (const provider of cloudProviders) {
        const providerNormalized = normalizeBaseUrl(provider.baseUrl);
        if (normalized === providerNormalized) {
          switchCloudTranscriptionProvider(transcriptionContext, provider.id);
          break;
        }
      }
    }
  }, [
    cloudTranscriptionBaseUrl,
    selectedCloudProvider,
    setCloudTranscriptionBaseUrl,
    switchCloudTranscriptionProvider,
    transcriptionContext,
    cloudProviders,
  ]);

  const handleDelete = useCallback(
    (modelId: string) => {
      showConfirmDialog({
        title: t("transcription.deleteModel.title"),
        description: t("transcription.deleteModel.description"),
        onConfirm: async () => {
          await deleteModel(modelId, async () => {
            const result = await window.electronAPI?.listWhisperModels();
            if (result?.success) {
              setLocalModels(result.models);
              validateAndSelectModel(result.models);
            }
          });
        },
        variant: "destructive",
      });
    },
    [showConfirmDialog, deleteModel, validateAndSelectModel, t]
  );

  const currentCloudProvider = useMemo<TranscriptionProviderData | undefined>(
    () => cloudProviders.find((p) => p.id === displayedCloudProvider),
    [cloudProviders, displayedCloudProvider]
  );

  const providerCredentials =
    PROVIDER_CREDENTIALS[displayedCloudProvider] ?? PROVIDER_CREDENTIALS.openai;
  const keyDraft = useCredentialDraft();
  const credentialValues: Record<ProviderCredentialField["key"], string> = {
    openaiApiKey: keyDraft.value("openaiApiKey", openaiApiKey),
    groqApiKey: keyDraft.value("groqApiKey", groqApiKey),
    xaiApiKey: keyDraft.value("xaiApiKey", xaiApiKey),
    mistralApiKey: keyDraft.value("mistralApiKey", mistralApiKey),
    geminiApiKey: keyDraft.value("geminiApiKey", geminiApiKey),
    cortiClientId: keyDraft.value("cortiClientId", cortiClientId),
    cortiClientSecret: keyDraft.value("cortiClientSecret", cortiClientSecret),
    cortiEnvironment,
    cortiTenant: keyDraft.value("cortiTenant", cortiTenant),
    tinfoilApiKey: keyDraft.value("tinfoilApiKey", tinfoilApiKey),
    deepgramApiKey: keyDraft.value("deepgramApiKey", deepgramApiKey),
    assemblyaiApiKey: keyDraft.value("assemblyaiApiKey", assemblyaiApiKey),
  };
  const customKey = keyDraft.value("customTranscriptionApiKey", customTranscriptionApiKey);
  const credentialSetters: Record<ProviderCredentialField["key"], (value: string) => void> = {
    openaiApiKey: setOpenaiApiKey,
    groqApiKey: setGroqApiKey,
    xaiApiKey: setXaiApiKey,
    mistralApiKey: setMistralApiKey,
    geminiApiKey: setGeminiApiKey,
    cortiClientId: setCortiClientId,
    cortiClientSecret: setCortiClientSecret,
    cortiEnvironment: setCortiEnvironment,
    cortiTenant: setCortiTenant,
    tinfoilApiKey: setTinfoilApiKey,
    deepgramApiKey: setDeepgramApiKey,
    assemblyaiApiKey: setAssemblyaiApiKey,
  };

  const endpointHold = useFocusHold();
  const editing = useFocusHold();
  const visible = usePanelVisible();
  // A tab that is only being browsed has no model of this panel's: the key alone is checked.
  const panelModel = selectedCloudProvider === displayedCloudProvider ? displayedCloudModel : "";
  const isCustom = displayedCloudProvider === "custom";
  const isCorti = displayedCloudProvider === "corti";
  const providerKey = credentialValues[providerCredentials.fields[0].key];
  // `typed` is what is typed into this provider's fields (a speech server's address and
  // model name included); `context` is what is chosen instead.
  const connection: {
    config: ProviderConnectionConfig;
    ready: boolean;
    typed: string;
    context: unknown[];
  } = isCustom
    ? {
        config: {
          scope: "transcription",
          provider: "custom",
          baseUrl: cloudTranscriptionBaseUrl,
          apiKey: customKey,
          model: panelModel,
        },
        // The check speaks only OpenAI's API; Azure gets its own URL and `api-key` header.
        ready:
          Boolean(cloudTranscriptionBaseUrl.trim() && panelModel.trim()) &&
          !isAzureOpenAIEndpoint(cloudTranscriptionBaseUrl),
        typed: `${cloudTranscriptionBaseUrl}\n${customKey}\n${panelModel}`,
        context: [],
      }
    : isCorti
      ? {
          config: {
            scope: "transcription",
            provider: "corti",
            clientId: credentialValues.cortiClientId,
            clientSecret: credentialValues.cortiClientSecret,
            environment: cortiEnvironment,
            tenant: credentialValues.cortiTenant,
          },
          ready: Boolean(
            credentialValues.cortiClientId.trim() && credentialValues.cortiClientSecret.trim()
          ),
          typed: `${credentialValues.cortiClientId}\n${credentialValues.cortiClientSecret}`,
          context: [cortiEnvironment, credentialValues.cortiTenant],
        }
      : {
          config: {
            scope: "transcription",
            provider: displayedCloudProvider,
            apiKey: providerKey,
            model: panelModel,
          },
          ready: Boolean(providerKey.trim()),
          typed: providerKey,
          context: [panelModel],
        };
  const delayMs = useTypingPause({
    typed: connection.typed,
    context: JSON.stringify([
      displayedCloudProvider,
      visible,
      effectiveLocal,
      ...connection.context,
    ]),
    held: editing.held,
  });
  const check = useConnectionAutoCheck({
    config: connection.config,
    // A hidden panel is not ready to ask; a shown one asks again, and the main process answers
    // a check it remembers at once.
    ready:
      !effectiveLocal && providerAllowed(displayedCloudProvider) && connection.ready && visible,
    // A half-typed address may belong to someone else: nothing is sent while it is edited.
    hold: isCustom && endpointHold.held,
    delayMs,
  });
  // The field that completes the connection carries the status.
  const checkedCredential = isCorti ? "cortiClientSecret" : providerCredentials.fields[0].key;
  const refused = check.failure?.errorCode === "credentialsRejected";
  // The typed values the check carries, as one string so the effect sees each new set.
  const checkedFields = JSON.stringify(
    isCustom
      ? { customTranscriptionApiKey: customKey }
      : Object.fromEntries(
          providerCredentials.fields.map((field) => [field.key, credentialValues[field.key]])
        )
  );
  const followKeyDraft = keyDraft.follow;
  useEffect(() => {
    followKeyDraft({
      phase: check.phase,
      checked: JSON.parse(checkedFields),
      // Someone's own server may refuse a key for other reasons, so its refusal holds nothing back.
      refused: refused && !isCustom,
    });
  }, [check.phase, checkedFields, isCustom, refused, followKeyDraft]);
  const customFailureReason =
    !customKey.trim() && refused ? t("reasoning.custom.endpointUnauthorized") : undefined;

  const cloudModelOptions = useMemo(() => {
    if (!currentCloudProvider) return [];
    const { icon, invertInDark } = getRemoteProviderIcon(displayedCloudProvider);
    return currentCloudProvider.models.map((m) => ({
      value: m.id,
      label: m.name,
      description: m.descriptionKey
        ? t(m.descriptionKey, { defaultValue: m.description })
        : m.description,
      icon,
      invertInDark,
    }));
  }, [currentCloudProvider, displayedCloudProvider, t]);

  const progressDisplay = useMemo(() => {
    if (!effectiveLocal) return null;

    const activeDownloads = [
      ...Object.values(whisperDownloads),
      ...Object.values(parakeetDownloads),
    ];
    if (activeDownloads.length === 0) return null;

    return (
      <div className="space-y-2">
        {activeDownloads.map((status) => {
          const modelInfo =
            status.modelType === "whisper"
              ? WHISPER_MODEL_INFO[status.modelId]
              : PARAKEET_MODEL_INFO[status.modelId];
          return (
            <DownloadProgressBar
              key={`${status.modelType}:${status.modelId}`}
              modelName={modelInfo?.name || status.modelId}
              progress={{
                percentage: status.progress,
                downloadedBytes: status.downloadedBytes,
                totalBytes: status.totalBytes,
              }}
              isInstalling={status.phase === "installing"}
            />
          );
        })}
      </div>
    );
  }, [effectiveLocal, whisperDownloads, parakeetDownloads]);

  const renderLocalModels = () => {
    const modelsToRender =
      localModels.length === 0
        ? Object.entries(WHISPER_MODEL_INFO).map(([modelId, info]) => ({
            model: modelId,
            downloaded: false,
            size_mb: info.sizeMb,
          }))
        : localModels;

    return (
      <div className="space-y-0.5">
        {modelsToRender.map((model) => {
          const modelId = model.model;
          const info = WHISPER_MODEL_INFO[modelId] ?? {
            name: modelId,
            description: t("transcription.fallback.whisperModelDescription"),
            size: t("common.unknown"),
            recommended: false,
          };

          return (
            <LocalModelCard
              key={modelId}
              modelId={modelId}
              name={info.name}
              description={info.description}
              size={info.size}
              actualSizeMb={model.size_mb}
              isSelected={modelId === selectedLocalModel}
              isDownloaded={model.downloaded ?? false}
              isDownloading={isDownloadingModel(modelId)}
              isCancelling={isCancellingModel(modelId)}
              isInstalling={whisperDownloads[modelId]?.phase === "installing"}
              recommended={info.recommended}
              provider="whisper"
              onSelect={() => handleWhisperModelSelect(modelId)}
              onDelete={() => handleDelete(modelId)}
              onDownload={() =>
                downloadModel(modelId, (downloadedId) => {
                  setLocalModels((prev) =>
                    prev.map((m) => (m.model === downloadedId ? { ...m, downloaded: true } : m))
                  );
                  handleWhisperModelSelect(downloadedId);
                })
              }
              onCancel={() => cancelDownload(modelId)}
              styles={styles}
            />
          );
        })}
      </div>
    );
  };

  const handleParakeetDelete = useCallback(
    (modelId: string) => {
      showConfirmDialog({
        title: t("transcription.deleteModel.title"),
        description: t("transcription.deleteModel.description"),
        onConfirm: async () => {
          await deleteParakeetModel(modelId, async () => {
            const result = await window.electronAPI?.listParakeetModels();
            if (result?.success) {
              setParakeetModels(result.models);
            }
          });
        },
        variant: "destructive",
      });
    },
    [showConfirmDialog, deleteParakeetModel, t]
  );

  // Organization tabs share the sherpa-onnx inventory and installation backend.
  const renderParakeetModels = () => {
    const modelsToRender = (
      parakeetModels.length === 0
        ? Object.entries(PARAKEET_MODEL_INFO).map(([modelId, info]) => ({
            model: modelId,
            downloaded: false,
            size_mb: info.sizeMb,
          }))
        : parakeetModels
    ).filter((model) => getASRModelOrganization(model.model) === internalLocalProvider);

    return (
      <div className="space-y-0.5">
        {modelsToRender.map((model) => {
          const modelId = model.model;
          const info = PARAKEET_MODEL_INFO[modelId] ?? {
            name: modelId,
            description: t("transcription.fallback.parakeetModelDescription"),
            modelCardUrl: undefined,
            size: t("common.unknown"),
            language: "en",
            recommended: false,
          };

          return (
            <LocalModelCard
              key={modelId}
              modelId={modelId}
              name={info.name}
              description={info.description}
              size={info.size}
              actualSizeMb={model.size_mb}
              isSelected={modelId === selectedLocalModel}
              isDownloaded={model.downloaded ?? false}
              isDownloading={isDownloadingParakeetModel(modelId)}
              isCancelling={isCancellingParakeetModel(modelId)}
              isInstalling={parakeetDownloads[modelId]?.phase === "installing"}
              recommended={info.recommended}
              provider={getASRModelOrganization(modelId)}
              modelCardUrl={info.modelCardUrl}
              onSelect={() => handleParakeetModelSelect(modelId)}
              onDelete={() => handleParakeetDelete(modelId)}
              onDownload={() =>
                downloadParakeetModel(modelId, (downloadedId) => {
                  setParakeetModels((prev) =>
                    prev.map((m) => (m.model === downloadedId ? { ...m, downloaded: true } : m))
                  );
                  handleParakeetModelSelect(downloadedId);
                })
              }
              onCancel={() => cancelParakeetDownload(modelId)}
              styles={styles}
            />
          );
        })}
      </div>
    );
  };

  return (
    <div className={`space-y-2 ${className}`}>
      <ConnectionCheckAnnouncer announcement={check.announcement} />
      {!mode && <ModeToggle useLocalWhisper={effectiveLocal} onModeChange={handleModeChange} />}

      {!effectiveLocal ? (
        <>
          {cloudProviderTabs.length > 0 && (
            <ProviderTabs
              providers={cloudProviderTabs}
              selectedId={displayedCloudProvider}
              onSelect={handleCloudProviderChange}
              colorScheme="purple"
              wrap
            />
          )}

          {providerAllowed(displayedCloudProvider) && (
            <div>
              {displayedCloudProvider === "custom" ? (
                <div className="space-y-2" onFocus={editing.onFocus} onBlur={editing.onBlur}>
                  <div className="space-y-1.5">
                    <label className="block text-xs font-medium text-foreground">
                      {t("transcription.endpointUrl")}
                    </label>
                    <ProviderCheckField
                      aria-label={t("transcription.endpointUrl")}
                      value={cloudTranscriptionBaseUrl}
                      onChange={(e) => setCloudTranscriptionBaseUrl?.(e.target.value)}
                      onFocus={endpointHold.onFocus}
                      onBlur={(event) => {
                        endpointHold.onBlur(event);
                        handleBaseUrlBlur();
                      }}
                      placeholder="https://your-api.example.com/v1"
                      autoComplete="off"
                      spellCheck={false}
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="block text-xs font-medium text-foreground">
                      {t("transcription.apiKeyOptional")}
                    </label>
                    <ProviderCheckField
                      aria-label={t("transcription.apiKeyOptional")}
                      type="password"
                      value={customKey}
                      onChange={(e) =>
                        keyDraft.change(
                          "customTranscriptionApiKey",
                          e.target.value.trim(),
                          setCustomTranscriptionApiKey
                        )
                      }
                      onBlur={keyDraft.save}
                      placeholder={t("apiKeyInput.placeholder")}
                      autoComplete="off"
                      spellCheck={false}
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="block text-xs font-medium text-foreground">
                      {t("common.model")}
                    </label>
                    <ProviderCheckField
                      aria-label={t("common.model")}
                      check={check}
                      invalidOn="modelNotFound"
                      failureReason={customFailureReason}
                      value={panelModel}
                      onChange={(e) => handleCloudModelSelect(e.target.value)}
                      placeholder="whisper-1"
                      autoComplete="off"
                      spellCheck={false}
                    />
                  </div>

                  {/azure\.com/i.test(cloudTranscriptionBaseUrl || "") && (
                    <p className="text-xs text-muted-foreground">{t("transcription.azureHint")}</p>
                  )}
                </div>
              ) : (
                <div className="space-y-2">
                  {providerCredentials.fields.map((field, index) => {
                    const label = field.labelKey ? t(field.labelKey) : t("common.apiKey");
                    return (
                      <div key={field.key} className="space-y-1.5">
                        <div className="flex items-center justify-between">
                          <label className="text-xs font-medium text-foreground">{label}</label>
                          {index === 0 && (
                            <GetApiKeyLink
                              url={providerCredentials.consoleUrl}
                              labelKey="transcription.getKey"
                              className="text-xs text-primary/70 hover:text-primary transition-colors cursor-pointer"
                            />
                          )}
                        </div>
                        {field.input === "select" ? (
                          <Select
                            value={credentialValues[field.key]}
                            onValueChange={credentialSetters[field.key]}
                          >
                            <SelectTrigger className="h-8 text-sm">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {field.options?.map((option) => (
                                <SelectItem key={option.value} value={option.value}>
                                  {option.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        ) : (
                          <ProviderCheckField
                            aria-label={label}
                            check={field.key === checkedCredential ? check : undefined}
                            invalidOn="credentialsRejected"
                            type={field.input === "secret" ? "password" : "text"}
                            value={credentialValues[field.key]}
                            onChange={(e) =>
                              keyDraft.change(
                                field.key,
                                e.target.value.trim(),
                                credentialSetters[field.key]
                              )
                            }
                            onFocus={editing.onFocus}
                            onBlur={(event) => {
                              editing.onBlur(event);
                              keyDraft.save();
                            }}
                            placeholder={
                              field.input === "secret"
                                ? t("apiKeyInput.placeholder")
                                : field.placeholder
                            }
                            autoComplete="off"
                            spellCheck={false}
                          />
                        )}
                      </div>
                    );
                  })}

                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-foreground">
                      {t("common.model")}
                    </label>
                    <ModelCardList
                      models={cloudModelOptions}
                      selectedModel={
                        selectedCloudProvider === displayedCloudProvider ? displayedCloudModel : ""
                      }
                      onModelSelect={handleCloudModelSelect}
                      colorScheme="purple"
                    />
                    {displayedCloudProvider === "tinfoil" && (
                      <p className="text-xs text-muted-foreground/70">
                        {t("transcription.tinfoil.transportNote")}{" "}
                        <a
                          href={TINFOIL_AUDIO_DOCS_URL}
                          onClick={createExternalLinkHandler(TINFOIL_AUDIO_DOCS_URL)}
                          className="text-primary/70 hover:text-primary transition-colors"
                        >
                          {t("transcription.tinfoil.docsLink")}
                        </a>
                      </p>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}
        </>
      ) : (
        <>
          <ProviderTabs
            providers={localProviderTabs}
            selectedId={internalLocalProvider}
            onSelect={handleLocalProviderChange}
            colorScheme="purple"
          />

          {progressDisplay}

          {gpuDownloading && internalLocalProvider === "whisper" && (
            <div>
              <DownloadProgressBar modelName="GPU acceleration" progress={gpuProgress} />
              <div className="px-2.5 pb-1 flex justify-end">
                <button
                  onClick={handleGpuCancel}
                  className="text-xs text-muted-foreground hover:text-foreground transition-colors"
                >
                  {t("gpu.cancel")}
                </button>
              </div>
            </div>
          )}

          {internalLocalProvider === "whisper" &&
            !gpuDismissed &&
            !gpuDownloading &&
            gpuBackend && (
              <div
                className={`rounded-md border p-2.5 ${
                  (gpuDownloaded ? gpuFailed : gpuNeedsUpdate)
                    ? "border-warning/40 bg-warning/5"
                    : "border-border bg-surface-1"
                }`}
              >
                {gpuDownloaded ? (
                  gpuFailed ? (
                    <GpuWarningRow
                      title={t("gpu.activationFailed")}
                      description={t("gpu.activationFailedDescription")}
                      actionLabel={t("gpu.retryActivation")}
                      onAction={handleGpuRetry}
                      onRemove={handleGpuDelete}
                    >
                      {gpuFailReason && (
                        <p
                          dir="ltr"
                          className="mt-1 wrap-break-word font-mono text-[11px] leading-snug text-muted-foreground"
                        >
                          {gpuFailReason}
                        </p>
                      )}
                    </GpuWarningRow>
                  ) : (
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5">
                        {gpuActivating ? (
                          <>
                            <span className="inline-block w-1.5 h-1.5 rounded-full shrink-0 bg-primary animate-pulse" />
                            <span className="text-xs font-medium text-foreground">
                              {t("gpu.activatingBackend", { backend: gpuBackendName })}
                            </span>
                          </>
                        ) : gpuActive ? (
                          <>
                            <Check size={13} className="text-success" />
                            <span className="text-xs font-medium text-foreground">
                              {t("gpu.activeBackend", { backend: gpuBackendName })}
                            </span>
                          </>
                        ) : (
                          <>
                            <span className="inline-block w-1.5 h-1.5 rounded-full shrink-0 bg-primary" />
                            <span className="text-xs font-medium text-foreground">
                              {t("gpu.readyBackend", { backend: gpuBackendName })}
                            </span>
                          </>
                        )}
                      </div>
                      <Button
                        onClick={handleGpuDelete}
                        size="sm"
                        variant="ghost"
                        className="h-6 px-2 text-xs text-muted-foreground hover:text-destructive"
                      >
                        {t("gpu.remove")}
                      </Button>
                    </div>
                  )
                ) : gpuNeedsUpdate ? (
                  <GpuWarningRow
                    title={t("gpu.redownloadNeeded")}
                    description={t("gpu.redownloadNeededDescription")}
                    actionLabel={t("gpu.redownloadButton")}
                    onAction={handleGpuDownload}
                    onRemove={handleGpuDelete}
                  />
                ) : (
                  <div className="flex items-start gap-2.5">
                    <Zap size={13} className="text-primary shrink-0 mt-0.5" />
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-medium text-foreground">
                        {t("gpu.transcriptionBanner")}
                      </p>
                      <p className="mt-0.5 text-xs leading-snug text-muted-foreground">
                        {t(gpuBackend === "cuda" ? "gpu.cudaDescription" : "gpu.vulkanDescription")}
                      </p>
                      <div className="flex items-center gap-2 mt-1.5">
                        <Button
                          onClick={handleGpuDownload}
                          size="sm"
                          variant="default"
                          className="h-6 px-2.5 text-xs"
                        >
                          {t("gpu.enableBackend", { backend: gpuBackendName })}
                        </Button>
                        <button
                          onClick={() => setGpuDismissed(true)}
                          className="text-xs text-muted-foreground hover:text-foreground transition-colors"
                        >
                          {t("gpu.dismiss")}
                        </button>
                      </div>
                    </div>
                  </div>
                )}
                {!gpuDownloaded && gpuDownloadError !== null && (
                  <p className="mt-2 text-xs leading-snug text-destructive">
                    {t("gpu.downloadFailed")}
                    {gpuDownloadError && ` ${gpuDownloadError}`}
                  </p>
                )}
              </div>
            )}

          <div>
            {internalLocalProvider === "whisper" && renderLocalModels()}
            {usesParakeetManager(internalLocalProvider) && renderParakeetModels()}
          </div>
        </>
      )}

      <ConfirmDialog
        open={confirmDialog.open}
        onOpenChange={(open) => !open && hideConfirmDialog()}
        title={confirmDialog.title}
        description={confirmDialog.description}
        confirmText={confirmDialog.confirmText}
        cancelText={confirmDialog.cancelText}
        onConfirm={confirmDialog.onConfirm}
        variant={confirmDialog.variant}
      />
    </div>
  );
}