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.

31.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

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogMedia,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { usePlatformStore } from "@/config/env";
import {
  DOWNLOAD_KIND,
  downloadManager,
  formatBytes,
  jobKeyOf,
  scopedVariant,
  useDownloadManagerStore,
} from "@/features/hub";
import { translate, useT } from "@/i18n";
import { isTauri } from "@/lib/api-base";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import {
  ApiExampleBox,
  useApiExampleChoices,
} from "../../api-monitor/components/api-example-box";
import { scrollIntoPane } from "../lib/scroll-into-pane";
import { ArrowUpRight01Icon, TaskDone01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { type ReactElement, useEffect, useRef, useState } from "react";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import type {
  KeylessApiAccessExposure,
  KeylessApiAccessScope,
} from "../api/keyless-api-access";
import {
  type SystemOneBackend,
  decisionRuntimeLabel,
  type SystemOneConnection,
  type SystemOneDevice,
  type SystemOneDownloadPlan,
  type SystemOneSettings,
  loadSystemOneConnections,
  loadSystemOneSettings,
  resolveSystemOneDownload,
  unloadSystemOneModel,
  updateSystemOneSettings,
  validateSystemOneSettings,
} from "../api/systemone";
import {
  DECISION_MODEL_LABELS,
  isClefDecisionModel,
} from "../lib/decision-model-labels";
import {
  buildDecisionApiSnippet,
  decisionApiKey,
  decisionMcpUrl,
} from "./decision-api-snippets";
import { DecisionTryDialog } from "./decision-try-dialog";
import { SettingsRow } from "./settings-row";
import { UrlPill } from "./url-pill";
import { PlayIcon } from "lucide-react";

const DOWNLOAD_SCOPE = "systemone";
const DOCS_URL = "https://unsloth.ai/docs/models/decision-laya";
const POLL_MS = 5000;
const RECOMMENDED_MODEL = "laya-multilingual";
const ENV_DISABLE = "UNSLOTH_SYSTEMONE_DISABLE";
const ENV_MODEL = "UNSLOTH_SYSTEMONE_MODEL";
const ENV_DEVICE = "UNSLOTH_SYSTEMONE_DEVICE";

function deviceLabel(device: string | null): string {
  return device && device !== "cpu" ? "GPU" : "CPU";
}

function errorMessage(error: unknown): string | null {
  return error instanceof Error ? error.message : null;
}

export function DecisionApiSection({
  showHeading = true,
  apiKey,
  useTunnel = false,
  keylessScope = "off",
  keylessExposure = null,
}: {
  showHeading?: boolean;
  apiKey?: string | null;
  useTunnel?: boolean;
  keylessScope?: KeylessApiAccessScope;
  keylessExposure?: KeylessApiAccessExposure | null;
} = {}): ReactElement | null {
  const t = useT();
  const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
  const serverUrl = usePlatformStore((s) => s.serverUrl);
  const origin = typeof window !== "undefined" ? window.location.origin : "";
  const base =
    useTunnel && cloudflareUrl
      ? cloudflareUrl
      : isTauri
        ? (serverUrl ?? origin)
        : origin;
  const exampleKey = decisionApiKey(apiKey, {
    base,
    tunnel: useTunnel && !!cloudflareUrl,
    scope: keylessScope,
    exposure: keylessExposure,
  });
  const choices = useApiExampleChoices(base, "curl");
  const [settings, setSettings] = useState<SystemOneSettings | null>(null);
  const [connections, setConnections] = useState<SystemOneConnection[] | null>(
    null,
  );
  const [planState, setPlanState] = useState<{
    model: string;
    backend: SystemOneBackend;
    plan: SystemOneDownloadPlan;
  } | null>(null);
  const [confirm, setConfirm] = useState<{
    plan: SystemOneDownloadPlan;
    patch: Parameters<typeof updateSystemOneSettings>[0];
    model: string;
  } | null>(null);
  const [busy, setBusy] = useState(false);
  const [tryOpen, setTryOpen] = useState(false);
  const [tryModel, setTryModel] = useState<string | undefined>();
  const [error, setError] = useState<string | null>(null);
  const sectionRef = useRef<HTMLElement | null>(null);
  const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
  const decisionTryRequested = useSettingsDialogStore(
    (s) => s.decisionTryRequested,
  );

  const enabled = settings?.enabled ?? false;
  if (tryOpen && !enabled) setTryOpen(false);

  useEffect(() => {
    if (!decisionTryRequested || !settings) return;
    useSettingsDialogStore.getState().consumeDecisionTryRequest();
    if (settings.enabled && settings.model === decisionTryRequested) {
      setTryModel(decisionTryRequested);
      setTryOpen(true);
    }
  }, [decisionTryRequested, settings]);
  const model = settings?.model ?? null;
  const backend = settings?.backend ?? "auto";
  const mlxAvailable = settings?.mlxAvailable ?? false;
  // llama.cpp serves a GGUF, MLX and PyTorch the safetensors: the download follows the runtime.
  const plan =
    planState?.model === model && planState?.backend === backend
      ? planState.plan
      : null;

  useEffect(() => {
    let live = true;
    loadSystemOneSettings().then(
      (next) => live && setSettings(next),
      (err) =>
        live &&
        setError(
          errorMessage(err) ??
            translate("settings.apiKeys.decisionApi.loadError"),
        ),
    );
    loadSystemOneConnections().then(
      (next) => live && setConnections(next),
      () => live && setConnections([]),
    );
    return () => {
      live = false;
    };
  }, []);

  useEffect(() => {
    // The API page's copy (no heading) must not answer, or the dialog's never scrolls.
    if (!showHeading || scrollTarget !== "api-keys-decision-api" || !settings)
      return;
    const frame = window.requestAnimationFrame(() => {
      if (sectionRef.current) scrollIntoPane(sectionRef.current);
      useSettingsDialogStore
        .getState()
        .consumeScrollTarget("api-keys-decision-api");
    });
    return () => window.cancelAnimationFrame(frame);
  }, [scrollTarget, settings, showHeading]);

  useEffect(() => {
    if (!enabled) return;
    const timer = window.setInterval(() => {
      if (document.visibilityState !== "visible") return;
      loadSystemOneSettings().then(setSettings, () => undefined);
    }, POLL_MS);
    return () => window.clearInterval(timer);
  }, [enabled]);

  const jobKey =
    plan?.repo && !plan.cached && plan.files.length > 0
      ? jobKeyOf(DOWNLOAD_KIND.MODEL, plan.repo, scopedVariant(DOWNLOAD_SCOPE))
      : null;
  const jobState = useDownloadManagerStore((s) =>
    jobKey ? (s.jobs[jobKey]?.state ?? null) : null,
  );
  const downloading = jobState === "running" || jobState === "cancelling";
  const downloadDone = jobState === "complete";

  useEffect(() => {
    if (!enabled || !model) return;
    let live = true;
    resolveSystemOneDownload(model, backend).then(
      (next) => live && setPlanState({ model, backend, plan: next }),
      (err) => live && setError(errorMessage(err)),
    );
    return () => {
      live = false;
    };
    // MLX coming or going, as on a device change, changes what the runtime serves from.
  }, [enabled, model, backend, mlxAvailable, downloadDone]);

  const modelLabel = (name: string) => {
    const connection = connections?.find((c) => c.name === name);
    if (connection) return `${connection.provider} · ${connection.model}`;
    const option = settings?.models.find((m) => m.name === name);
    if (option?.label) return option.label;
    return DECISION_MODEL_LABELS[name] ? t(DECISION_MODEL_LABELS[name]) : name;
  };

  const resyncSettingsAfterError = async (message: string) => {
    try {
      setSettings(await loadSystemOneSettings());
    } catch (refreshError) {
      console.warn(
        "Couldn't refresh Decision API settings after a rejected change.",
        refreshError,
      );
    }
    setError(message);
  };

  const startDownload = async (next: SystemOneDownloadPlan) => {
    if (!next.repo || next.cached || next.files.length === 0) return false;
    const downloadKey = jobKeyOf(
      DOWNLOAD_KIND.MODEL,
      next.repo,
      scopedVariant(DOWNLOAD_SCOPE),
    );
    try {
      const outcome = await downloadManager.requestStart({
        kind: DOWNLOAD_KIND.MODEL,
        repoId: next.repo,
        variant: scopedVariant(DOWNLOAD_SCOPE),
        scopeId: DOWNLOAD_SCOPE,
        files: next.files,
        inventoryKind: "model",
        expectedBytes: next.sizeBytes,
      });
      if (outcome === "started") {
        const acceptedState =
          useDownloadManagerStore.getState().jobs[downloadKey]?.state;
        if (acceptedState === "running" || acceptedState === "complete") {
          return true;
        }
      }
      if (outcome === "conflict" || outcome === "busy") {
        toast.info(t("settings.apiKeys.decisionApi.downloadBusy"));
      } else if (outcome === "started") {
        toast.info(t("settings.apiKeys.decisionApi.downloadBusy"));
      } else {
        toast.error(t("settings.apiKeys.decisionApi.downloadFailed"));
      }
    } catch (err) {
      toast.error(t("settings.apiKeys.decisionApi.downloadFailed"), {
        description: errorMessage(err) ?? undefined,
      });
    }
    return false;
  };

  const apply = async (
    patch: Parameters<typeof updateSystemOneSettings>[0],
    downloadAfter: boolean,
  ) => {
    setBusy(true);
    setError(null);
    try {
      // Offer the download on the switch so a first API call does not wait on a 700 MB transfer.
      const nextEnabled = patch.enabled ?? settings?.enabled;
      const nextModel = patch.model ?? settings?.model;
      const nextBackend = patch.backend ?? backend;
      const settingsPatch =
        downloadAfter && settings
          ? {
              ...patch,
              expectedEnabled: settings.enabled,
              expectedModel: settings.model,
            }
          : patch;
      let resolvedPlan: typeof planState = null;
      if (nextEnabled && nextModel && downloadAfter) {
        const nextPlan = await resolveSystemOneDownload(nextModel, nextBackend);
        if (!nextPlan.cached) {
          if (nextPlan.error || !nextPlan.repo || nextPlan.files.length === 0) {
            throw new Error(
              nextPlan.error ??
                t("settings.apiKeys.decisionApi.downloadFailed"),
            );
          }
          setConfirm({
            plan: nextPlan,
            patch: settingsPatch,
            model: nextModel,
          });
          return;
        }
        resolvedPlan = {
          model: nextModel,
          backend: nextBackend,
          plan: nextPlan,
        };
      }
      const next = await updateSystemOneSettings(settingsPatch);
      setSettings(next);
      if (resolvedPlan?.model === next.model) setPlanState(resolvedPlan);
    } catch (err) {
      await resyncSettingsAfterError(
        errorMessage(err) ?? t("settings.apiKeys.decisionApi.saveFailed"),
      );
    } finally {
      setBusy(false);
    }
  };

  const acceptDownload = async (accepted: NonNullable<typeof confirm>) => {
    setBusy(true);
    setError(null);
    try {
      await validateSystemOneSettings(accepted.patch);
      if (!(await startDownload(accepted.plan))) return;
      const next = await updateSystemOneSettings(accepted.patch);
      setSettings(next);
      if (next.model === accepted.model) {
        setPlanState({
          model: accepted.model,
          backend: next.backend,
          plan: accepted.plan,
        });
      }
    } catch (err) {
      await resyncSettingsAfterError(
        errorMessage(err) ?? t("settings.apiKeys.decisionApi.saveFailed"),
      );
    } finally {
      setBusy(false);
    }
  };

  const unload = async () => {
    setBusy(true);
    setError(null);
    try {
      setSettings(await unloadSystemOneModel());
    } catch (err) {
      setError(errorMessage(err));
    } finally {
      setBusy(false);
    }
  };

  // title, not aria-label, so the accessible name stays the visible text.
  const docsLink = (
    <a
      href={DOCS_URL}
      target="_blank"
      rel="noreferrer"
      title={t("settings.apiKeys.decisionApi.docsLabel")}
      className="inline-flex shrink-0 items-center gap-1 rounded-full font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
    >
      {t("settings.apiKeys.decisionApi.docs")}
      <HugeiconsIcon icon={ArrowUpRight01Icon} className="size-3" />
    </a>
  );
  const header = (
    <div className="flex items-start justify-between gap-3">
      <div className="flex min-w-0 flex-col gap-1">
        {/* Centred, not baseline: the h2 is a flex box, so its baseline is the icon's foot. */}
        {showHeading && (
          <div className="flex min-w-0 items-center gap-3">
            <h2 className="settings-heading flex items-center gap-2 text-base font-semibold font-heading">
              <HugeiconsIcon
                icon={TaskDone01Icon}
                strokeWidth={1.75}
                className="size-[calc(18px*var(--ui-space-scale,1))] shrink-0 text-muted-foreground"
              />
              {t("settings.apiKeys.decisionApi.title")}
            </h2>
            <span className="text-ui-11">{docsLink}</span>
          </div>
        )}
        <p className="text-xs leading-relaxed text-muted-foreground">
          {t("settings.apiKeys.decisionApi.description")}
          {showHeading ? null : <span className="ml-1.5 inline-flex align-baseline">{docsLink}</span>}
        </p>
      </div>
      {settings ? (
        <Tooltip>
          <TooltipTrigger asChild={true}>
            <span
              className={cn(
                "shrink-0",
                // Top edge on the h2's cap top (text-base at leading 1.5; Hellix: 0.372em).
                showHeading && "mt-[calc(var(--text-base)*0.372)]",
              )}
            >
              <Button
                size="sm"
                className="shrink-0 gap-1.5"
                disabled={!enabled}
                onClick={() => setTryOpen(true)}
              >
                <PlayIcon strokeWidth={2} className="size-3.5" />
                {t("decisions.tryIt")}
              </Button>
            </span>
          </TooltipTrigger>
          {enabled ? null : (
            <TooltipContent side="bottom">
              {t("decisions.tryItOff")}
            </TooltipContent>
          )}
        </Tooltip>
      ) : null}
    </div>
  );
  const errorLine = error ? (
    <p className="py-2.5 text-xs leading-snug text-destructive">{error}</p>
  ) : null;

  if (!settings) {
    return (
      <section
        data-settings-label={t("settings.apiKeys.decisionApi.title")}
        className="flex min-w-0 max-w-full flex-col gap-4"
      >
        {header}
        <div>
          {errorLine ?? (
            <p
              role="status"
              className="flex items-center gap-2 py-3 text-xs text-muted-foreground"
            >
              <Spinner />
              {t("settings.apiKeys.decisionApi.loading")}
            </p>
          )}
        </div>
      </section>
    );
  }

  const current = settings.models.find((m) => m.name === settings.model);
  const isRemote = settings.model.startsWith("connection:");
  const remote = connections?.find((c) => c.name === settings.model);
  const knownModel = current !== undefined || isRemote;
  const longLabel = isRemote || current?.kind === "fine_tune";
  // Laya is PyTorch only unless exported; Clef runs on any runtime, a GGUF-only model on llama.cpp or MLX.
  const runtimeChoice =
    isClefDecisionModel(settings.model) ||
    settings.layout === "clef" ||
    settings.hasGgufForm ||
    !!current?.llamaCppOnly;
  const connectionGroups = [
    ...new Set(connections?.map((c) => c.providerId)),
  ].map((id) => connections?.filter((c) => c.providerId === id) ?? []);
  const sizeBytes = plan?.sizeBytes || current?.downloadBytes || 0;

  let tone: "pending" | "ready" | "error" | null = null;
  let status = "";
  let action: "download" | "unload" | null = null;
  if (remote) {
    status = t("settings.apiKeys.decisionApi.sendsTo", {
      provider: remote.provider,
    });
  } else if (isRemote) {
    tone = connections ? "error" : "pending";
    status = connections
      ? t("settings.apiKeys.decisionApi.connectionMissing")
      : t("settings.apiKeys.decisionApi.checking");
  } else if (settings.error) {
    tone = "error";
    status = settings.error;
  } else if (settings.installing) {
    tone = "pending";
    status = t("settings.apiKeys.decisionApi.installing");
  } else if (downloading) {
    tone = "pending";
    status = t("settings.apiKeys.decisionApi.downloading");
  } else if (settings.loadingModel === settings.model) {
    tone = "pending";
    status = t("settings.apiKeys.decisionApi.loading");
  } else if (settings.loadedModel === settings.model) {
    tone = "ready";
    status = t("settings.apiKeys.decisionApi.loadedOn", {
      device: deviceLabel(settings.loadedDevice),
    });
    action = "unload";
  } else if (plan === null) {
    tone = "pending";
    status = t("settings.apiKeys.decisionApi.checking");
  } else if (!plan.cached && plan.error) {
    tone = "error";
    status = plan.error;
  } else if (!plan.cached) {
    status = t("settings.apiKeys.decisionApi.notDownloaded", {
      size: formatBytes(sizeBytes),
    });
    action = "download";
  } else {
    tone = "ready";
    status =
      current?.kind === "fine_tune"
        ? t("settings.apiKeys.decisionApi.ready")
        : t("settings.apiKeys.decisionApi.downloaded");
  }

  return (
    <section
      ref={sectionRef}
      data-settings-label={t("settings.apiKeys.decisionApi.title")}
      className="flex min-w-0 max-w-full scroll-mt-6 flex-col gap-4"
    >
      {header}

      <div>
        {errorLine}
        <div className="py-1">
          <SettingsRow
            label={t("settings.apiKeys.decisionApi.enable")}
            description={
              settings.enabledLocked
                ? t("settings.apiKeys.decisionApi.lockedByEnv", {
                    name: ENV_DISABLE,
                  })
                : isRemote
                  ? t("settings.apiKeys.decisionApi.enableRemoteDescription")
                  : t("settings.apiKeys.decisionApi.enableDescription")
            }
          >
            <Switch
              checked={enabled}
              disabled={busy || settings.enabledLocked}
              onCheckedChange={(on) => void apply({ enabled: on }, on)}
              aria-label={t("settings.apiKeys.decisionApi.enable")}
            />
          </SettingsRow>

          <SettingsRow
            label={t("settings.apiKeys.decisionApi.model")}
            hint={
              settings.modelLocked
                ? t("settings.apiKeys.decisionApi.lockedByEnv", {
                    name: ENV_MODEL,
                  })
                : undefined
            }
            description={
              (enabled || isRemote) && status ? (
                <span
                  className={cn(
                    "flex min-w-0 items-center gap-2",
                    tone === "error" && "text-destructive",
                  )}
                >
                  {tone ? (
                    <span
                      className={cn(
                        "size-1.5 shrink-0 rounded-full",
                        tone === "pending"
                          ? "animate-pulse bg-current"
                          : tone === "ready"
                            ? "bg-emerald-500"
                            : "bg-destructive",
                      )}
                    />
                  ) : null}
                  <span className="truncate" title={status}>
                    {status}
                  </span>
                </span>
              ) : undefined
            }
            className="max-[420px]:flex-col max-[420px]:items-stretch max-[420px]:gap-3"
          >
            <div className="flex items-center gap-2 max-[420px]:w-full">
              {action === "download" ? (
                <Button
                  variant="outline"
                  size="sm"
                  className="shrink-0 text-xs"
                  disabled={busy || downloading}
                  onClick={() => plan && void startDownload(plan)}
                >
                  {downloading ? <Spinner className="mr-1.5" /> : null}
                  {t("settings.apiKeys.decisionApi.download")}
                </Button>
              ) : action === "unload" ? (
                <Button
                  variant="outline"
                  size="sm"
                  className="shrink-0 text-xs"
                  disabled={busy}
                  onClick={() => void unload()}
                >
                  {t("settings.apiKeys.decisionApi.unload")}
                </Button>
              ) : null}
              {knownModel ? (
                <Select
                  value={settings.model}
                  disabled={busy || settings.modelLocked}
                  onValueChange={(name) => void apply({ model: name }, true)}
                >
                  <SelectTrigger
                    className={cn(
                      longLabel ? "w-64" : "w-48",
                      "max-[420px]:flex-1",
                    )}
                    aria-label={t("settings.apiKeys.decisionApi.model")}
                    title={longLabel ? modelLabel(settings.model) : undefined}
                  >
                    <SelectValue className="min-w-0">
                      <span className="truncate">
                        {modelLabel(settings.model)}
                      </span>
                    </SelectValue>
                  </SelectTrigger>
                  <SelectContent>
                    <SelectGroup>
                      <SelectLabel>
                        {t("settings.apiKeys.decisionApi.thisMachine")}
                      </SelectLabel>
                      {settings.models.map((option) => (
                        <SelectItem
                          key={option.name}
                          value={option.name}
                          disabled={!option.available}
                          title={option.unavailableReason ?? option.description}
                        >
                          <span className="flex items-center gap-2">
                            {modelLabel(option.name)}
                            {option.kind === "fine_tune" ? null : (
                              <span className="text-ui-10 tabular-nums text-muted-foreground">
                                {formatBytes(option.downloadBytes)}
                              </span>
                            )}
                            {option.name === RECOMMENDED_MODEL ? (
                              <span className="rounded-full bg-emerald-500/12 px-1.5 py-px text-ui-9 font-medium text-emerald-600 dark:text-emerald-400">
                                {t("settings.apiKeys.decisionApi.recommended")}
                              </span>
                            ) : null}
                          </span>
                        </SelectItem>
                      ))}
                    </SelectGroup>
                    {connectionGroups.map((group) => (
                      <SelectGroup key={group[0].providerId}>
                        <SelectLabel>{group[0].provider}</SelectLabel>
                        {group.map((option) => (
                          <SelectItem key={option.name} value={option.name}>
                            {option.model}
                          </SelectItem>
                        ))}
                      </SelectGroup>
                    ))}
                  </SelectContent>
                </Select>
              ) : (
                <span className="font-mono text-xs text-foreground">
                  {settings.model}
                </span>
              )}
            </div>
          </SettingsRow>

          {runtimeChoice ? (
            <>
              <SettingsRow
                label={t("settings.apiKeys.decisionApi.backend")}
                description={t(
                  settings.mlxAvailable
                    ? "settings.apiKeys.decisionApi.backendDescriptionMlx"
                    : "settings.apiKeys.decisionApi.backendDescription",
                )}
              >
                <Select
                  value={backend}
                  disabled={busy}
                  onValueChange={(value) =>
                    void apply({ backend: value as SystemOneBackend }, true)
                  }
                >
                  <SelectTrigger
                    className="w-36"
                    aria-label={t("settings.apiKeys.decisionApi.backend")}
                  >
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="auto">
                      {t("settings.apiKeys.decisionApi.backendAuto")}
                    </SelectItem>
                    <SelectItem value="llama.cpp">llama.cpp</SelectItem>
                    {settings.mlxAvailable || backend === "mlx" ? (
                      <SelectItem value="mlx">
                        {decisionRuntimeLabel("mlx")}
                      </SelectItem>
                    ) : null}
                    <SelectItem value="pytorch">PyTorch</SelectItem>
                  </SelectContent>
                </Select>
              </SettingsRow>
              <p
                className="pb-3 text-xs text-muted-foreground leading-relaxed"
                data-decision-backend
              >
                {t("settings.apiKeys.decisionApi.backendStatus", {
                  backend: decisionRuntimeLabel(
                    (settings.loadedModel === settings.model
                      ? settings.loadedBackend
                      : settings.effectiveBackend) ??
                      t("settings.apiKeys.decisionApi.backendNone"),
                  ),
                })}
                {settings.fallbackReason ? ` · ${settings.fallbackReason}` : ""}{" "}
                {t(
                  settings.inputModalities.includes("image")
                    ? "settings.apiKeys.decisionApi.mediaImages"
                    : "settings.apiKeys.decisionApi.mediaText",
                )}
              </p>
            </>
          ) : null}

          {isRemote ? null : (
            <SettingsRow
              label={t("settings.apiKeys.decisionApi.device")}
              description={
                settings.deviceLocked
                  ? t("settings.apiKeys.decisionApi.lockedByEnv", {
                      name: ENV_DEVICE,
                    })
                  : t("settings.apiKeys.decisionApi.deviceDescription")
              }
            >
              <Select
                value={settings.device}
                disabled={busy || settings.deviceLocked}
                onValueChange={(device) =>
                  void apply({ device: device as SystemOneDevice }, false)
                }
              >
                <SelectTrigger
                  className="w-36"
                  aria-label={t("settings.apiKeys.decisionApi.device")}
                >
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="cpu">
                    {t("settings.apiKeys.decisionApi.deviceCpu")}
                  </SelectItem>
                  <SelectItem value="gpu" disabled={!settings.gpuAvailable}>
                    {t("settings.apiKeys.decisionApi.deviceGpu")}
                  </SelectItem>
                </SelectContent>
              </Select>
            </SettingsRow>
          )}

          {connections?.length === 0 && !settings.modelLocked ? (
            <p className="pb-3 text-xs text-muted-foreground">
              {t("settings.apiKeys.decisionApi.addConnection")}
              <button
                type="button"
                className="text-foreground underline underline-offset-2 hover:text-primary"
                // openDialog, not setActiveTab: the API page shows this card with no dialog open.
                onClick={() =>
                  useSettingsDialogStore.getState().openDialog("connections")
                }
              >
                {t("settings.apiKeys.decisionApi.connectionsLink")}
              </button>
              {t("settings.apiKeys.decisionApi.addConnectionSuffix")}
            </p>
          ) : null}
        </div>
      </div>

      <div className="flex min-w-0 flex-col gap-3">
        <h3 className="text-ui-13 font-medium text-foreground">
          {t("settings.apiKeys.decisionApi.codeTitle")}
        </h3>
        {enabled ? null : (
          <p className="text-xs text-muted-foreground">
            {t("decisions.tryItOff")}
          </p>
        )}
        <ApiExampleBox
          choices={choices}
          hasRealKey={Boolean(apiKey)}
          code={buildDecisionApiSnippet({
            base,
            apiKey: exampleKey,
            language: choices.language,
            os: choices.os,
          })}
        />
        <div className="flex min-w-0 flex-col gap-1.5">
          <span className="text-xs font-medium text-foreground">
            {t("settings.apiKeys.decisionApi.mcpUrl")}
          </span>
          <UrlPill url={decisionMcpUrl(base, settings.mcpUrl)} />
          <p className="text-xs text-muted-foreground">
            {t("settings.apiKeys.decisionApi.mcpUrlDescription")}
          </p>
        </div>
      </div>

      <DecisionTryDialog
        open={tryOpen && enabled}
        onOpenChange={setTryOpen}
        initialModel={tryModel}
        settings={settings}
        connections={connections ?? []}
        curlTarget={{ base, apiKey: exampleKey, os: choices.os }}
        onRun={() => {
          loadSystemOneSettings().then(setSettings, () => undefined);
        }}
      />

      <AlertDialog
        open={confirm !== null}
        onOpenChange={(open) => {
          if (!open && confirm) {
            setConfirm(null);
          }
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogMedia>
              <HugeiconsIcon icon={TaskDone01Icon} strokeWidth={1.75} />
            </AlertDialogMedia>
            <AlertDialogTitle>
              {t(
                isClefDecisionModel(confirm?.model ?? settings.model) ||
                  settings.models.find(
                    (m) => m.name === (confirm?.model ?? settings.model),
                  )?.llamaCppOnly
                  ? "settings.apiKeys.decisionApi.downloadConfirmTitleModel"
                  : "settings.apiKeys.decisionApi.downloadConfirmTitle",
                { model: modelLabel(confirm?.model ?? settings.model) },
              )}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t("settings.apiKeys.decisionApi.downloadConfirmBody", {
                size: formatBytes(confirm?.plan.sizeBytes || sizeBytes),
              })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
            <AlertDialogAction
              onClick={(event) => {
                event.preventDefault();
                const accepted = confirm;
                setConfirm(null);
                if (accepted) void acceptDownload(accepted);
              }}
            >
              {t("settings.apiKeys.decisionApi.download")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </section>
  );
}