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.

54.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 { SegmentedPill } from "@/components/segmented-control";
import { getClientPlatform } from "@/components/tauri/window-titlebar";
import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { fetchDeviceType, usePlatformStore } from "@/config/env";
import {
  type BackendModelDetails,
  type GgufVariantDetail,
  type InferenceStatusResponse,
  type LocalModelInfo,
  getInferenceStatus,
  listCachedGguf,
  listGgufVariants,
  listLocalModels,
  listModels,
} from "@/features/chat";
import {
  EMBEDDING_TAGS,
  type HfModelResult,
  ggufVariantDisplayLabel,
  hfApiToken,
  useHfTokenStore,
  useHubModelSearch,
  useOnlineStatus,
} from "@/features/hub";
import type { TranslationKey } from "@/i18n";
import { useT } from "@/i18n";
import { getApiBase, isTauri } from "@/lib/api-base";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { Tick02Icon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
import { ArrowUpRight01Icon } from "@hugeicons/core-free-icons";
import { Copy01Icon } from "@/lib/copy-icon";
import { HugeiconsIcon } from "@hugeicons/react";
import {
  useCallback,
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
} from "react";
import { loadCodingAgents } from "../api/coding-agents";
import {
  buildAgentShellCommands,
  isLoopbackHost,
  normalizeHost,
  pickAgentVariant,
  quoteShellArg,
} from "../components/agent-command";
import {
  AgentIcon,
  CommandBlock,
  useCopyButton,
} from "../components/agent-command-block";
import {
  type AgentDetails,
  NOT_AUTO_PICKED_AGENTS,
  SUPPORTED_AGENTS,
  UNSLOTH_START_DOCS_URL,
  detailsFor,
} from "../components/coding-agent-list";
import { McpAccessSection } from "../components/mcp-access-section";
import { SettingsSection } from "../components/settings-section";
import {
  isChatGenerativeHubModel,
  isClassifierOrRerankerHubModel,
  isSpeechOnlyHubModel,
} from "../lib/agent-hub-model.ts";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import {
  type ExampleOs,
  useSettingsPanelPrefsStore,
} from "../stores/settings-panel-prefs-store";
import { useFreshApiKeyStore } from "../stores/fresh-api-key-store";
import { LineBox } from "@/components/ui/line-box";

const DOCS_URL = UNSLOTH_START_DOCS_URL;
const FLAGS_DOCS_URL = `${DOCS_URL}#flags--options`;
const EXAMPLE_MODEL_REPO = "unsloth/Qwen3.8-27B-GGUF";
const EXAMPLE_MODEL_VARIANT = "UD-Q4_K_XL";
const EXAMPLE_MODEL_FLAGS = "--reasoning-effort medium";
const MODEL_RESULT_LIMIT = 7;
const STATUS_POLL_MS = 5000;
const HUGGING_FACE_REPO_PATTERN = /^[^/\\:\s]+\/[^/\\:\s]+$/;
const SEARCH_TOKEN_PATTERN = /\s+/;
const SUBAGENT_AGENT_IDS = new Set(["claude", "codex", "opencode", "pi"]);

function isLoopbackBase(base: string): boolean {
  try {
    return isLoopbackHost(normalizeHost(new URL(base).hostname));
  } catch {
    return false;
  }
}

// Desktop-only: a browser loopback URL may be a port forward to another host.
function canUseLocalAgentDetection(base: string): boolean {
  return isTauri && isLoopbackBase(base);
}

type ParsedModel = {
  repo: string;
  variant: string | null;
};

const FALLBACK_AGENT = SUPPORTED_AGENTS[0];

function splitModelVariant(model: string): ParsedModel {
  const value = model.trim();
  if (
    !value ||
    value.startsWith("/") ||
    value.startsWith("./") ||
    value.startsWith("../") ||
    value.startsWith("~") ||
    (value.length >= 2 && value[1] === ":")
  ) {
    return { repo: value, variant: null };
  }

  const separator = value.lastIndexOf(":");
  if (separator < 0) {
    return { repo: value, variant: null };
  }
  const repo = value.slice(0, separator);
  const variant = value.slice(separator + 1);
  if (!(repo && variant) || variant.includes("/")) {
    return { repo: value, variant: null };
  }
  return { repo, variant };
}

function looksLikePath(value: string): boolean {
  return (
    value.includes("\\") ||
    value.startsWith("/") ||
    value.startsWith("~") ||
    value.startsWith("./") ||
    value.startsWith("../") ||
    (value.length >= 2 && value[1] === ":") ||
    value.split("/").length > 2
  );
}

// hugging face ids fold case; a path does not, since Linux paths are sensitive.
function modelKey(model: string): string {
  return looksLikePath(model) ? model : model.toLowerCase();
}

function mergeModelOrder(primary: string[], fallback: string[]): string[] {
  const ordered: string[] = [];
  const seen = new Set<string>();
  for (const model of [...primary, ...fallback]) {
    const key = modelKey(model);
    if (seen.has(key)) {
      continue;
    }
    seen.add(key);
    ordered.push(model);
  }
  return ordered;
}

function isHuggingFaceRepo(model: string): boolean {
  return HUGGING_FACE_REPO_PATTERN.test(model);
}

function isEmbeddingHubModel(
  model: Pick<HfModelResult, "pipelineTag" | "tags">,
): boolean {
  return [model.pipelineTag, ...(model.tags ?? [])].some(
    (tag) => tag != null && EMBEDDING_TAGS.has(tag.toLowerCase()),
  );
}

function formatBytes(bytes: number): string {
  if (!Number.isFinite(bytes) || bytes <= 0) {
    return "";
  }
  const units = ["B", "KB", "MB", "GB", "TB"];
  const unitIndex = Math.min(
    Math.floor(Math.log(bytes) / Math.log(1024)),
    units.length - 1,
  );
  const value = bytes / 1024 ** unitIndex;
  return `${value >= 10 || unitIndex === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[unitIndex]}`;
}

function discoverGgufModels(
  items: BackendModelDetails[],
  cachedRepos: string[],
): {
  models: string[];
  variants: Record<string, string>;
} {
  const models = [EXAMPLE_MODEL_REPO];
  const variants: Record<string, string> = {};
  // Catalog and cache can disagree on casing; two rows would leave the load id on only one.
  const seen = new Set(models.map(modelKey));
  const add = (model: string) => {
    const key = modelKey(model);
    if (seen.has(key)) {
      return;
    }
    seen.add(key);
    models.push(model);
  };
  for (const model of items) {
    // A native grant's id is a host path status withholds, so drop path-shaped ids.
    if (!model.is_gguf || looksLikePath(model.id)) {
      continue;
    }
    const parsed = splitModelVariant(model.id);
    if (parsed.repo) {
      add(parsed.repo);
    }
    if (parsed.variant && !variants[parsed.repo]) {
      variants[parsed.repo] = parsed.variant;
    }
  }
  for (const repo of cachedRepos) {
    add(repo);
  }

  return { models, variants };
}

// Scanned local GGUFs the caches miss; the id is the on-disk load path.
function isLocalGguf(model: LocalModelInfo): boolean {
  // Unset format means "not GGUF": a safetensors folder named Foo-GGUF must not pass.
  return (model.model_format ?? "").toLowerCase() === "gguf";
}

function localGgufEntries(
  models: LocalModelInfo[],
): { id: string; label: string }[] {
  const entries: { id: string; label: string }[] = [];
  for (const model of models) {
    // partial = interrupted sharded download; the command would fail on load.
    if (model.partial || !(model.id && isLocalGguf(model))) {
      continue;
    }
    // The path is the identity: basenames can collide and --model needs the path.
    entries.push({
      id: model.id,
      label: model.model_id || model.display_name || model.id,
    });
  }
  return entries;
}

function activeAgentModelSelection(
  status: InferenceStatusResponse | null,
): { model: string; variant: string | null; named: boolean } | null {
  if (!(status?.is_gguf || status?.is_mlx)) {
    return null;
  }
  if (!status.model_identifier) {
    // A native file grant withholds the host path, so attach with a bare command.
    return status.active_model
      ? {
          model: status.active_model,
          variant: status.gguf_variant ?? null,
          named: false,
        }
      : null;
  }
  const active = splitModelVariant(status.model_identifier);
  if (!active.repo) {
    return null;
  }
  return {
    // Status reports the quant for path loads too, whose id has no ":variant" suffix.
    model: active.repo,
    variant: status.gguf_variant ?? active.variant,
    named: true,
  };
}

// Flag tokens are literal; only the descriptions are localized.
const OPTION_ROWS: { flag: string; descKey: TranslationKey }[] = [
  { flag: "--model, -m", descKey: "settings.agents.options.model" },
  {
    flag: "--context-length",
    descKey: "settings.agents.options.contextLength",
  },
  { flag: "--gguf-variant", descKey: "settings.agents.options.ggufVariant" },
  {
    flag: "--load-in-4bit / --no-load-in-4bit",
    descKey: "settings.agents.options.loadIn4bit",
  },
  {
    flag: "--tensor-parallel / --no-tensor-parallel",
    descKey: "settings.agents.options.tensorParallel",
  },
  { flag: "--serve / --no-serve", descKey: "settings.agents.options.serve" },
  { flag: "--reasoning", descKey: "settings.agents.options.reasoning" },
  {
    flag: "--reasoning-effort",
    descKey: "settings.agents.options.reasoningEffort",
  },
  {
    flag: "--launch / --no-launch",
    descKey: "settings.agents.options.launch",
  },
  {
    flag: "--persist / --no-persist",
    descKey: "settings.agents.options.persist",
  },
  { flag: "--as-subagent", descKey: "settings.agents.options.asSubagent" },
  { flag: "--api-key", descKey: "settings.agents.options.apiKey" },
  { flag: "--yolo", descKey: "settings.agents.options.yolo" },
];

/** Copy state stays with the caller so existing resets still apply. */
function CopyableCode({
  value,
  copyLabel,
  copied,
  onCopy,
  breakAll = true,
  sensitive = false,
}: {
  value: string;
  copyLabel: string;
  copied: boolean;
  onCopy: () => void;
  breakAll?: boolean;
  /** Holds a real API key: reload-snapshot.js clears it instead of saving it to sessionStorage. */
  sensitive?: boolean;
}) {
  const t = useT();

  return (
    <div className="relative min-w-0">
      <LineBox
        as="code"
        className={cn(
          "block min-w-0 whitespace-pre-wrap border border-border bg-background/70 py-2.5 pr-9 pl-4 font-mono text-ui-11 leading-relaxed text-foreground dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.05*var(--contrast-wash-gain,1)))]",
          breakAll ? "break-all" : "break-words",
        )}
        data-reload-snapshot-sensitive={sensitive ? "" : undefined}
      >
        {value}
      </LineBox>
      <button
        type="button"
        onClick={onCopy}
        aria-label={copyLabel}
        className="absolute top-1.5 right-1.5 flex size-6 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
      >
        <HugeiconsIcon
          icon={copied ? Tick02Icon : Copy01Icon}
          className={cn("size-3.5", copied && "text-control-accent")}
          strokeWidth={2}
        />
      </button>
      <output className="sr-only" aria-live="polite">
        {copied ? t("settings.agents.copied") : ""}
      </output>
    </div>
  );
}

function SubagentSection({
  agent,
  command,
  sensitive,
}: {
  agent: AgentDetails;
  command: string;
  sensitive: boolean;
}) {
  const t = useT();
  const prompt =
    agent.id === "opencode"
      ? t("settings.agents.subagent.opencodePrompt")
      : t("settings.agents.subagent.defaultPrompt");
  const commandCopy = useCopyButton(command);
  const promptCopy = useCopyButton(prompt);

  if (!SUBAGENT_AGENT_IDS.has(agent.id)) {
    return null;
  }

  return (
    <div className="flex min-w-0 flex-col gap-4">
      <div className="flex flex-col gap-1">
        <span
          data-settings-label={t("settings.agents.subagent.title")}
          className="text-xs font-medium text-foreground"
        >
          {t("settings.agents.subagent.title")}
        </span>
        <p className="text-ui-11 leading-relaxed text-muted-foreground">
          {t("settings.agents.subagent.description", { agent: agent.name })}
        </p>
      </div>

      <div className="flex min-w-0 flex-col gap-2">
        <span className="text-ui-11 font-medium text-foreground">
          {t("settings.agents.subagent.setupCommand")}
        </span>
        <CopyableCode
          value={command}
          copyLabel={t("settings.agents.subagent.copySetupCommand")}
          copied={commandCopy.copied}
          onCopy={commandCopy.copy}
          sensitive={sensitive}
        />
      </div>

      <div className="flex min-w-0 flex-col gap-2">
        <span className="text-ui-11 font-medium text-foreground">
          {t("settings.agents.subagent.usagePrompt", { agent: agent.name })}
        </span>
        <CopyableCode
          value={prompt}
          copyLabel={t("settings.agents.subagent.copyUsagePrompt")}
          copied={promptCopy.copied}
          onCopy={promptCopy.copy}
          breakAll={false}
        />
      </div>
    </div>
  );
}

export function AgentsTab() {
  const t = useT();
  const pillId = useId();
  const serverUrl = usePlatformStore((s) => s.serverUrl);
  const hfToken = useHfTokenStore((s) => s.token);
  const hfAccessToken = hfApiToken(hfToken);
  const online = useOnlineStatus();
  const deviceType = usePlatformStore((s) => s.deviceType);
  const { results: trendingGgufs } = useHubModelSearch("", {
    channel: { owner: "unsloth", tags: ["gguf"] },
    sortBy: "trendingScore",
    sortDirection: "desc",
    accessToken: hfAccessToken,
    keepUnsupportedTags: false,
    enabled: online,
  });
  // The shell selector can override this. Anchored: includes("win") would match "darwin".
  const [isWindowsClient] = useState(() => {
    const p = getClientPlatform();
    return p.startsWith("win") || p.includes("windows");
  });
  const origin = typeof window !== "undefined" ? window.location.origin : "";
  // A Tauri origin is unreachable for the CLI, so use the backend URL; on loopback deviceType
  // decides (it can report wsl).
  const studioBase = isTauri ? (serverUrl ?? getApiBase()) : origin;
  const freshApiKey = useFreshApiKeyStore((s) => s.key);
  const inferredCommandOs: ExampleOs = (
    isLoopbackBase(studioBase)
      ? deviceType === "windows"
      : isWindowsClient
  )
    ? "windows"
    : "unix";
  const localDetection = canUseLocalAgentDetection(serverUrl ?? origin);
  const setStoredAgent = useSettingsPanelPrefsStore((s) => s.setAgentsAgent);
  const setStoredModel = useSettingsPanelPrefsStore((s) => s.setAgentsModel);
  const setStoredOs = useSettingsPanelPrefsStore((s) => s.setAgentsOs);
  const setStoredVariant = useSettingsPanelPrefsStore(
    (s) => s.setAgentsVariant,
  );
  // read once: these seed the controls, which write back through the handlers.
  const [storedPrefs] = useState(() => useSettingsPanelPrefsStore.getState());
  // Detection is only a default: the command may be pasted into SSH, WSL or a container.
  const [commandOsOverride, setCommandOsOverride] = useState<ExampleOs | null>(
    storedPrefs.agentsOs,
  );
  const commandOs = commandOsOverride ?? inferredCommandOs;
  const [agents, setAgents] = useState<string[]>(
    SUPPORTED_AGENTS.map((agent) => agent.id),
  );
  const [selectedAgent, setSelectedAgent] = useState(
    storedPrefs.agentsAgent ?? FALLBACK_AGENT.id,
  );
  // a restored pick counts as explicit, or detection would overwrite it.
  const agentSelectionChanged = useRef(storedPrefs.agentsAgent != null);
  const [detectedAgents, setDetectedAgents] = useState<Set<string>>(new Set());
  const [loaded, setLoaded] = useState(false);
  // list the restored model until the discovery scan confirms or retires it.
  const [models, setModels] = useState<string[]>(
    storedPrefs.agentsModel && storedPrefs.agentsModel !== EXAMPLE_MODEL_REPO
      ? [storedPrefs.agentsModel, EXAMPLE_MODEL_REPO]
      : [EXAMPLE_MODEL_REPO],
  );
  const [cachedLoadIds, setCachedLoadIds] = useState<Record<string, string>>(
    {},
  );
  const [modelLabels, setModelLabels] = useState<Record<string, string>>({});
  // So the command attaches to the resident model rather than another cached copy.
  const [activeStatusModel, setActiveStatusModel] = useState<string | null>(
    null,
  );
  const [attachOnlyModel, setAttachOnlyModel] = useState<string | null>(null);
  const [knownVariants, setKnownVariants] = useState<Record<string, string>>({
    [EXAMPLE_MODEL_REPO]: EXAMPLE_MODEL_VARIANT,
  });
  const initialModel = storedPrefs.agentsModel ?? EXAMPLE_MODEL_REPO;
  const [selectedModel, setSelectedModel] = useState(initialModel);
  const modelSelectionChanged = useRef(storedPrefs.agentsModel != null);
  const restoredModel = useRef<string | null>(storedPrefs.agentsModel);
  const [discoveredKeys, setDiscoveredKeys] = useState<Set<string> | null>(
    null,
  );
  const [statusSettled, setStatusSettled] = useState(false);
  // State, not the ref: status can land after the variants listing and must re-pick then.
  const [rootMlxResident, setRootMlxResident] = useState<string | null>(null);
  const activeModelRef = useRef<{
    model: string;
    variant: string | null;
  } | null>(null);
  // Only the newest status request may apply.
  const statusSeq = useRef(0);
  // Scoped to its repo: polling must not overwrite it, and it must not follow onto another repo.
  const chosenVariant = useRef<{ model: string; variant: string } | null>(
    storedPrefs.agentsVariantModel && storedPrefs.agentsVariant
      ? {
          model: storedPrefs.agentsVariantModel,
          variant: storedPrefs.agentsVariant,
        }
      : null,
  );
  const [modelSearch, setModelSearch] = useState("");
  const [modelPickerOpen, setModelPickerOpen] = useState(false);
  const [variants, setVariants] = useState<GgufVariantDetail[]>([]);
  const [selectedVariant, setSelectedVariant] = useState<string | null>(
    chosenVariant.current &&
    modelKey(chosenVariant.current.model) === modelKey(initialModel)
      ? chosenVariant.current.variant
      : initialModel === EXAMPLE_MODEL_REPO
        ? EXAMPLE_MODEL_VARIANT
        : null,
  );
  const [variantsLoading, setVariantsLoading] = useState(true);
  const [variantsFailed, setVariantsFailed] = useState(false);

  const labelFor = (model: string) => modelLabels[model] ?? model;
  const trendingModels = useMemo(
    () =>
      trendingGgufs
        .filter(
          (model) =>
            model.isGguf &&
            isChatGenerativeHubModel(model) &&
            !isEmbeddingHubModel(model) &&
            !isSpeechOnlyHubModel(model) &&
            !isClassifierOrRerankerHubModel(model),
        )
        .map((model) => model.id),
    [trendingGgufs],
  );
  const orderedModels = useMemo(
    () => mergeModelOrder(trendingModels, models),
    [models, trendingModels],
  );
  const matchingModels = useMemo(() => {
    const tokens = modelSearch
      .trim()
      .toLowerCase()
      .split(SEARCH_TOKEN_PATTERN)
      .filter(Boolean);
    const matches =
      tokens.length === 0
        ? orderedModels
        : orderedModels.filter((model) => {
            const haystack =
              `${model} ${modelLabels[model] ?? ""}`.toLowerCase();
            return tokens.every((token) => haystack.includes(token));
          });

    if (tokens.length === 0) {
      const selectedKey = modelKey(selectedModel);
      const selectedIndex = matches.findIndex(
        (model) => modelKey(model) === selectedKey,
      );
      if (selectedIndex > 0) {
        return [
          matches[selectedIndex],
          ...matches.filter((_, index) => index !== selectedIndex),
        ];
      }
    }
    return matches;
  }, [modelLabels, modelSearch, orderedModels, selectedModel]);

  const visibleModels = matchingModels.slice(0, MODEL_RESULT_LIMIT);
  const preferredVariant = knownVariants[selectedModel] ?? null;
  const selectedAgentDetails = detailsFor(selectedAgent);
  // Name the snapshot path for a GGUF outside the active cache; the resident model is exempt since
  // the largest-copy snapshot could switch cache or quant under it.
  const selectedModelIsActive =
    activeStatusModel != null &&
    modelKey(selectedModel) === modelKey(activeStatusModel);
  const cachedLoadId = selectedModelIsActive
    ? null
    : (cachedLoadIds[selectedModel] ??
      cachedLoadIds[selectedModel.toLowerCase()] ??
      null);
  const modelId = cachedLoadId ?? selectedModel;
  const suffixVariant = isHuggingFaceRepo(modelId);
  const commandModel =
    selectedVariant && suffixVariant
      ? `${modelId}:${selectedVariant}`
      : modelId;
  const commandModelArg = quoteShellArg(commandModel, commandOs);
  // Bare `unsloth start` attaches to whatever is loaded, the only way to reach a native-grant GGUF.
  const attachOnly = selectedModel === attachOnlyModel;
  const selectedModelArgs =
    selectedVariant && !suffixVariant
      ? `--model ${commandModelArg} --gguf-variant ${quoteShellArg(selectedVariant, commandOs)}`
      : `--model ${commandModelArg}`;
  const selectedModelFlags =
    modelKey(selectedModel) === modelKey(EXAMPLE_MODEL_REPO)
      ? EXAMPLE_MODEL_FLAGS
      : "";
  const modelArgs = attachOnly
    ? ""
    : [selectedModelArgs, selectedModelFlags].filter(Boolean).join(" ");
  const shellCommands = buildAgentShellCommands(
    studioBase,
    commandOs,
    selectedAgent,
    modelArgs,
    freshApiKey,
  );
  const command = shellCommands.primary;
  const {
    copied,
    copy: handleCopy,
    reset: resetCopied,
  } = useCopyButton(command);

  useEffect(() => {
    void fetchDeviceType({ force: true });
  }, []);

  // A remote backend's PATH says nothing about the machine running the command.
  useEffect(() => {
    if (!localDetection) {
      return;
    }
    let cancelled = false;
    loadCodingAgents()
      .then((next) => {
        if (cancelled) {
          return;
        }
        if (next.agents.length > 0) {
          setAgents(next.agents);
          setSelectedAgent((current) => {
            if (agentSelectionChanged.current) {
              return current;
            }
            const detected = next.detected.find(
              (agent) =>
                next.agents.includes(agent) &&
                !NOT_AUTO_PICKED_AGENTS.has(agent),
            );
            return (
              detected ??
              (next.agents.includes(current) ? current : next.agents[0])
            );
          });
        }
        setDetectedAgents(new Set(next.detected));
      })
      .catch(() => {
        // Best-effort; the tab still works without PATH detection.
      })
      .finally(() => {
        if (!cancelled) {
          setLoaded(true);
        }
      });
    return () => {
      cancelled = true;
    };
  }, [localDetection]);

  useEffect(() => {
    if (!agentSelectionChanged.current) return;
    if (localDetection && !loaded) return;
    if (agents.includes(selectedAgent)) return;
    agentSelectionChanged.current = false;
    setStoredAgent(null);
    setSelectedAgent(
      agents.find(
        (agent) =>
          detectedAgents.has(agent) && !NOT_AUTO_PICKED_AGENTS.has(agent),
      ) ??
        agents[0] ??
        FALLBACK_AGENT.id,
    );
  }, [
    agents,
    detectedAgents,
    loaded,
    localDetection,
    selectedAgent,
    setStoredAgent,
  ]);

  useEffect(() => {
    let cancelled = false;
    // A failed endpoint has not proved a model absent, which the retire assumes.
    let discoveryComplete = true;
    const note = <T,>(fallback: T) => (): T => {
      discoveryComplete = false;
      return fallback;
    };
    Promise.all([
      listModels().catch(note(null)),
      listCachedGguf().catch(note([])),
      listLocalModels().catch(note(null)),
    ])
      .then(([info, cachedGgufs, local]) => {
        if (cancelled) {
          return;
        }
        const localEntries = localGgufEntries(local?.models ?? []);
        const discovered = discoverGgufModels(info?.models ?? [], [
          ...cachedGgufs
            .filter((cached) => !cached.umbrella_folder)
            .map((cached) => cached.repo_id),
          ...localEntries.map((entry) => entry.id),
        ]);
        const loadIds: Record<string, string> = {};
        for (const cached of cachedGgufs) {
          if (cached.load_id && cached.load_id !== cached.repo_id) {
            // Key both spellings: the merge kept whichever casing arrived first.
            loadIds[cached.repo_id] = cached.load_id;
            loadIds[cached.repo_id.toLowerCase()] = cached.load_id;
          }
        }
        const labels: Record<string, string> = {};
        for (const entry of localEntries) {
          if (entry.label !== entry.id) {
            labels[entry.id] = entry.label;
          }
        }
        if (discoveryComplete) {
          setDiscoveredKeys(new Set(discovered.models.map(modelKey)));
        }
        // Keep whatever model status already adopted when this slower scan lands.
        setModels(() => {
          const active = activeModelRef.current?.model;
          return active && !discovered.models.includes(active)
            ? [active, ...discovered.models]
            : discovered.models;
        });
        setCachedLoadIds(loadIds);
        setModelLabels(labels);
        setKnownVariants((current) => ({
          ...current,
          ...discovered.variants,
        }));
      })
      .catch(() => {
      });
    return () => {
      cancelled = true;
    };
  }, []);

  // Matched through modelKey since endpoints disagree on repo-id casing.
  const rememberedVariant = useCallback((model: string): string | null => {
    const chosen = chosenVariant.current;
    return chosen && modelKey(chosen.model) === modelKey(model)
      ? chosen.variant
      : null;
  }, []);

  const adoptActiveModel = useCallback(
    (active: { model: string; variant: string | null }) => {
      setModels((current) =>
        current.includes(active.model) ? current : [active.model, ...current],
      );
      if (active.variant) {
        setKnownVariants((current) => ({
          ...current,
          [active.model]: active.variant as string,
        }));
      }
      if (!modelSelectionChanged.current) {
        setSelectedModel(active.model);
        // A remembered quant wins; it may be adopted before the variants fetch applies it.
        setSelectedVariant(rememberedVariant(active.model) ?? active.variant);
      }
    },
    [rememberedVariant],
  );

  // Once replaced, a native-grant label names nothing, so drop it even if picked by hand.
  const retireAttachOnly = useCallback((label: string, replacement: string) => {
    setModels((current) => current.filter((model) => model !== label));
    setSelectedModel((current) => {
      if (current !== label) {
        return current;
      }
      // Drop the quant in the same update: it belonged to the label; an explicit pick blocks correction.
      chosenVariant.current = null;
      setSelectedVariant(null);
      return replacement;
    });
  }, []);

  // Follow the resident model away too, or the command would switch the shared server back.
  // An explicit pick wins, except a native-grant label, which is not loadable.
  const dropActiveModel = useCallback(
    (attachOnly: string | null, wasActive: string | null) => {
      if (attachOnly) {
        setModels((current) => current.filter((model) => model !== attachOnly));
        setSelectedModel((current) =>
          current === attachOnly ? EXAMPLE_MODEL_REPO : current,
        );
      }
      if (modelSelectionChanged.current || !wasActive) {
        return;
      }
      setSelectedModel((current) =>
        current === wasActive ? EXAMPLE_MODEL_REPO : current,
      );
      setSelectedVariant((current) => (current === null ? current : null));
    },
    [],
  );

  const applyStatus = useCallback(
    (status: InferenceStatusResponse) => {
      const active = activeAgentModelSelection(status);
      activeModelRef.current = active
        ? { model: active.model, variant: active.variant }
        : null;
      setRootMlxResident(
        active && status.is_mlx && active.variant === null
          ? modelKey(active.model)
          : null,
      );
      const wasAttachOnly = attachOnlyModel;
      setActiveStatusModel(active?.model ?? null);
      setAttachOnlyModel(active && !active.named ? active.model : null);
      if (!active) {
        dropActiveModel(wasAttachOnly, activeStatusModel);
        return;
      }
      if (wasAttachOnly && wasAttachOnly !== active.model) {
        retireAttachOnly(wasAttachOnly, active.model);
      }
      adoptActiveModel(active);
    },
    [
      activeStatusModel,
      adoptActiveModel,
      attachOnlyModel,
      dropActiveModel,
      retireAttachOnly,
    ],
  );

  // Keep tracking the shared server's resident model, or the command would switch it back.
  useEffect(() => {
    let cancelled = false;
    const sync = () => {
      const seq = ++statusSeq.current;
      getInferenceStatus()
        .then((status) => {
          if (!cancelled && seq === statusSeq.current) {
            applyStatus(status);
            // Only a current, answered poll is evidence for the retire.
            setStatusSettled(true);
          }
        })
        .catch(() => {
          // Not settled: a request that never answered proves nothing about
          // what is resident, so the retire below must keep waiting.
        });
    };
    sync();
    const timer = window.setInterval(sync, STATUS_POLL_MS);
    return () => {
      cancelled = true;
      window.clearInterval(timer);
    };
  }, [applyStatus]);

  // Retiring a restored pick needs both reads; either alone can miss a model.
  useEffect(() => {
    const restored = restoredModel.current;
    if (!(restored && discoveredKeys && statusSettled)) return;
    const active = activeModelRef.current;
    restoredModel.current = null;
    // modelKey both sides for casing; a path is never in discoveredKeys but is still valid.
    if (
      looksLikePath(restored) ||
      isHuggingFaceRepo(restored) ||
      discoveredKeys.has(modelKey(restored)) ||
      (active && modelKey(active.model) === modelKey(restored))
    ) {
      return;
    }
    // an uncached pick would pin the builder to a model the CLI cannot load.
    modelSelectionChanged.current = false;
    chosenVariant.current = null;
    setStoredModel(null, null);
    // Adopt now: a command copied before the next poll would switch the server off its model.
    if (active) {
      adoptActiveModel(active);
      return;
    }
    setSelectedModel(EXAMPLE_MODEL_REPO);
    setSelectedVariant(EXAMPLE_MODEL_VARIANT);
  }, [adoptActiveModel, discoveredKeys, statusSettled, setStoredModel]);

  useEffect(() => {
    let cancelled = false;
    const keepRoot = rootMlxResident === modelKey(selectedModel);

    // After discovery a scanned directory's path is its identity; only a loose .gguf is variantless.
    const localDir =
      cachedLoadId ??
      (looksLikePath(selectedModel) &&
      !selectedModel.toLowerCase().endsWith(".gguf")
        ? selectedModel
        : null);
    if (!(isHuggingFaceRepo(selectedModel) || localDir)) {
      // A loose .gguf is already one quant; adding --gguf-variant would not resolve.
      const standaloneFile = selectedModel.toLowerCase().endsWith(".gguf");
      queueMicrotask(() => {
        if (cancelled) {
          return;
        }
        setVariants([]);
        setSelectedVariant(standaloneFile ? null : preferredVariant);
        setVariantsFailed(false);
        setVariantsLoading(false);
      });
      return () => {
        cancelled = true;
      };
    }

    setVariants([]);
    setVariantsLoading(true);
    // Offer quants from where the command loads, not remote-only ones.
    listGgufVariants(selectedModel, hfToken || undefined, {
      preferLocalCache: localDir != null,
      localPath: localDir,
    })
      .then((info) => {
        if (cancelled) {
          return;
        }
        setVariantsFailed(false);
        // Drop partial quants: the command would fail on the missing shards.
        const uniqueVariants = Array.from(
          new Map(
            info.variants
              .filter((variant) => !variant.partial)
              .map((variant) => [variant.quant, variant]),
          ).values(),
        );
        setVariants(uniqueVariants);
        const available = new Set(
          uniqueVariants.map((variant) => variant.quant),
        );
        // Drop a remembered quant this repo no longer offers, in memory only: `partial` and offline
        // replies are no grounds to delete the saved one.
        const remembered = rememberedVariant(selectedModel);
        if (remembered && !available.has(remembered)) {
          chosenVariant.current = null;
        }
        const nextVariant = pickAgentVariant(available, {
          remembered: rememberedVariant(selectedModel),
          preferred: preferredVariant,
          defaultVariant: info.default_variant,
          first: uniqueVariants[0]?.quant ?? null,
          keepRoot,
        });
        setSelectedVariant(nextVariant);
      })
      .catch(() => {
        if (cancelled) {
          return;
        }
        setVariantsFailed(true);
        setVariants([]);
        const fallback = keepRoot ? null : preferredVariant;
        setSelectedVariant(fallback);
        if (fallback) {
          setVariants([
            {
              filename: "",
              quant: fallback,
              // biome-ignore lint/style/useNamingConvention: API response field
              size_bytes: 0,
            },
          ]);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setVariantsLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [
    cachedLoadId,
    hfToken,
    preferredVariant,
    rememberedVariant,
    rootMlxResident,
    selectedModel,
  ]);

  // No GGUF warning for `codex`/`claude`: the picker only offers GGUF models and a resident MLX one.

  return (
    <div className="settings-page">
      <header className="flex min-w-0 flex-col gap-1">
        <div className="flex min-w-0 items-baseline gap-2">
          <h1
            data-settings-label={t("settings.agents.title")}
            className="text-xl font-semibold font-heading"
          >
            {t("settings.agents.title")}
          </h1>
          {/* title, not aria-label, so the accessible name stays the visible text. */}
          <a
            href={DOCS_URL}
            target="_blank"
            rel="noopener noreferrer"
            title={t("settings.agents.docsLabel")}
            className="inline-flex shrink-0 items-center gap-1 rounded-full px-1.5 py-0.5 text-ui-11 font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
          >
            {t("settings.agents.docs")}
            <HugeiconsIcon icon={ArrowUpRight01Icon} className="size-3" />
          </a>
        </div>
        <p
          data-settings-label={t("settings.agents.description")}
          className="text-xs text-muted-foreground"
        >
          {t("settings.agents.description")}
        </p>
      </header>

      <p
        data-settings-label={t("settings.agents.intro")}
        className="text-sm text-muted-foreground leading-relaxed"
      >
        {/* No aria-label: it would replace the visible "unsloth start" as the
            accessible name, leaving voice control unable to target it. */}
        <a
          href={DOCS_URL}
          target="_blank"
          rel="noopener noreferrer"
          title={t("settings.agents.readDocs")}
          className="rounded-full bg-muted px-1 py-0.5 font-mono text-[0.85em] text-foreground underline decoration-border decoration-dotted underline-offset-2 transition-colors hover:decoration-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:bg-[rgb(255_255_255_/_calc(0.08*var(--contrast-wash-gain,1)))]"
        >
          unsloth start
        </a>{" "}
        {t("settings.agents.intro")}
      </p>

      {/* Shared track + pill selector. The legend is sr-only: the two shell
          names already say what the control picks. */}
      <fieldset className="flex min-w-0">
        <legend className="sr-only">
          {t("settings.agents.commandShell")}
        </legend>
        <div className="hub-tab-toggle inline-flex h-8 items-center rounded-full">
          <button
            type="button"
            onClick={() => {
              setCommandOsOverride("unix");
              setStoredOs("unix");
              resetCopied();
            }}
            aria-pressed={commandOs === "unix"}
            className={cn(
              "relative inline-flex h-8 items-center rounded-full px-3.5 text-ui-12 font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
              commandOs === "unix"
                ? "text-foreground"
                : "text-muted-foreground hover:text-foreground",
            )}
          >
            {commandOs === "unix" && (
              <SegmentedPill group={`${pillId}-shell`} />
            )}
            {t("settings.apiKeys.osUnix")}
          </button>
          <button
            type="button"
            onClick={() => {
              setCommandOsOverride("windows");
              setStoredOs("windows");
              resetCopied();
            }}
            aria-pressed={commandOs === "windows"}
            className={cn(
              "relative inline-flex h-8 items-center rounded-full px-3.5 text-ui-12 font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
              commandOs === "windows"
                ? "text-foreground"
                : "text-muted-foreground hover:text-foreground",
            )}
          >
            {commandOs === "windows" && (
              <SegmentedPill group={`${pillId}-shell`} />
            )}
            {t("settings.apiKeys.osWindows")}
          </button>
        </div>
      </fieldset>

      <section
        aria-label={t("settings.agents.commandBuilder")}
        className="flex w-full flex-col gap-6"
      >
        {/* Keyed to this pane, not the viewport. The dialog leaves the tab
            about 440px at a 768px window, where three columns crush the agent
            and model controls; 34rem is the point all three stay usable. */}
        <div className="@container">
          <div className="grid grid-cols-1 items-start gap-3 @[34rem]:grid-cols-[minmax(0,0.8fr)_minmax(0,1fr)_minmax(9rem,0.5fr)]">
            <div className="flex min-w-0 flex-col gap-1.5">
              {/* Fixed height on every column header, so the padded docs link
                  here cannot push this control below the other two. */}
              <div className="flex h-5 items-center justify-between gap-3">
                <span
                  data-settings-label={t("settings.agents.agent")}
                  className="text-xs font-medium text-foreground"
                >
                  {t("settings.agents.agent")}
                </span>
                <a
                  href={selectedAgentDetails.docsUrl}
                  target="_blank"
                  rel="noreferrer"
                  aria-label={t("settings.agents.agentDocs", {
                    agent: selectedAgentDetails.name,
                  })}
                  className="inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-ui-11 font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
                >
                  {t("settings.agents.docs")}
                  <HugeiconsIcon icon={ArrowUpRight01Icon} className="size-3" />
                </a>
              </div>
              <Select
                value={selectedAgent}
                onValueChange={(agent) => {
                  agentSelectionChanged.current = true;
                  setSelectedAgent(agent);
                  setStoredAgent(agent);
                  resetCopied();
                }}
              >
                <SelectTrigger
                  aria-label={t("settings.agents.agent")}
                  className="w-full rounded-full"
                >
                  <SelectValue>
                    <span className="flex min-w-0 items-center gap-2">
                      <AgentIcon
                        logo={selectedAgentDetails.logo}
                        icon={selectedAgentDetails.icon}
                        darkIcon={selectedAgentDetails.darkIcon}
                        color={selectedAgentDetails.color}
                        mark={selectedAgentDetails.mark}
                        compact={selectedAgentDetails.compact}
                      />
                      <span className="truncate">
                        {selectedAgentDetails.name}
                      </span>
                    </span>
                  </SelectValue>
                </SelectTrigger>
                {/* Seven 36px rows plus the 4px surface padding. */}
                <SelectContent
                  align="start"
                  className="max-h-[min(var(--radix-select-content-available-height),calc(7*2.25rem+0.5rem))] [&_[data-slot=select-scroll-down-button]]:hidden [&_[data-slot=select-scroll-up-button]]:hidden"
                >
                  {agents.map((agentId) => {
                    const agent = detailsFor(agentId);
                    return (
                      <SelectItem key={agent.id} value={agent.id}>
                        <span className="flex min-w-0 items-center gap-2">
                          <AgentIcon
                            logo={agent.logo}
                            icon={agent.icon}
                            darkIcon={agent.darkIcon}
                            color={agent.color}
                            mark={agent.mark}
                            compact={agent.compact}
                          />
                          <span className="truncate">{agent.name}</span>
                          {localDetection &&
                          loaded &&
                          detectedAgents.has(agent.id) ? (
                            <span className="shrink-0 rounded-full bg-control-accent/10 px-2 py-1 text-ui-10 leading-none font-semibold text-control-accent">
                              {t("settings.agents.quickstart.installed")}
                            </span>
                          ) : null}
                        </span>
                      </SelectItem>
                    );
                  })}
                </SelectContent>
              </Select>
            </div>

            <div className="flex min-w-0 flex-col gap-1.5">
              <div className="flex h-5 items-center">
                <span
                  data-settings-label={t("settings.agents.model")}
                  className="text-xs font-medium text-foreground"
                >
                  {t("settings.agents.model")}
                </span>
              </div>
              <Popover
                open={modelPickerOpen}
                onOpenChange={(open) => {
                  setModelPickerOpen(open);
                  if (!open) {
                    setModelSearch("");
                  }
                }}
              >
                <PopoverTrigger asChild={true}>
                  <button
                    type="button"
                    aria-label={t("settings.agents.model")}
                    aria-expanded={modelPickerOpen}
                    title={selectedModel}
                    className="flex h-9 w-full items-center justify-between gap-2 rounded-full border border-border bg-background px-3 text-left transition-colors hover:bg-accent/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))] dark:hover:bg-[rgb(255_255_255_/_calc(0.1*var(--contrast-wash-gain,1)))]"
                  >
                    <span className="min-w-0 truncate font-mono text-xs">
                      {labelFor(selectedModel)}
                    </span>
                    <HugeiconsIcon
                      icon={ChevronDownStandardIcon}
                      strokeWidth={2}
                      className="size-4 shrink-0 text-muted-foreground"
                    />
                  </button>
                </PopoverTrigger>
                <PopoverContent
                  align="start"
                  sideOffset={4}
                  className="w-[var(--radix-popover-trigger-width)] max-w-[calc(100vw-2rem)] gap-0 rounded-lg p-1"
                >
                  <Command
                    shouldFilter={false}
                    className="rounded-none bg-transparent p-0"
                  >
                    <CommandInput
                      value={modelSearch}
                      onValueChange={setModelSearch}
                      aria-label={t("settings.agents.searchModels")}
                      placeholder={t("settings.agents.searchModels")}
                      className="font-mono text-xs"
                    />
                    <CommandList>
                      <CommandEmpty>
                        {t("settings.agents.noModels")}
                      </CommandEmpty>
                      {visibleModels.map((model) => (
                        <CommandItem
                          key={model}
                          value={model}
                          data-checked={
                            modelKey(model) === modelKey(selectedModel)
                          }
                          onSelect={() => {
                            modelSelectionChanged.current = true;
                            restoredModel.current = null;
                            const variant =
                              rememberedVariant(model) ?? knownVariants[model] ?? null;
                            setSelectedModel(model);
                            setSelectedVariant(variant);
                            setStoredModel(
                              model === attachOnlyModel ? null : model,
                              model === attachOnlyModel ? null : variant,
                            );
                            setVariants([]);
                            setVariantsFailed(false);
                            setVariantsLoading(isHuggingFaceRepo(model));
                            setModelSearch("");
                            setModelPickerOpen(false);
                            resetCopied();
                          }}
                          className="cursor-pointer font-mono text-xs"
                        >
                          <span className="min-w-0 truncate" title={model}>
                            {labelFor(model)}
                          </span>
                        </CommandItem>
                      ))}
                    </CommandList>
                    {matchingModels.length > visibleModels.length ? (
                      <p className="border-t border-border/60 px-3 py-2 text-ui-11 text-muted-foreground">
                        {t("settings.agents.showingModels", {
                          shown: visibleModels.length,
                          total: matchingModels.length,
                        })}
                      </p>
                    ) : null}
                  </Command>
                </PopoverContent>
              </Popover>
            </div>

            <div className="flex min-w-0 flex-col gap-1.5">
              <div className="flex h-5 min-w-0 items-center">
                <span
                  data-settings-label={t("settings.agents.quantization")}
                  className="truncate text-xs font-medium text-foreground"
                >
                  {t("settings.agents.quantization")}
                </span>
              </div>
              <Select
                value={selectedVariant ?? undefined}
                onValueChange={(variant) => {
                  chosenVariant.current = { model: selectedModel, variant };
                  setSelectedVariant(variant);
                  // Stored per model: a quant picked while following the resident model does not pin it.
                  if (selectedModel !== attachOnlyModel) {
                    setStoredVariant(selectedModel, variant);
                  }
                  resetCopied();
                }}
                disabled={variantsLoading || variants.length === 0}
              >
                <SelectTrigger
                  aria-label={t("settings.agents.quantization")}
                  className="w-full rounded-full font-mono text-xs"
                >
                  <SelectValue
                    placeholder={
                      variantsLoading
                        ? t("settings.agents.loadingQuantizations")
                        : t("settings.agents.noQuantizations")
                    }
                  >
                    {/* The closed trigger is where the choice is READ, so it shows the label
                        too; SelectValue renders this instead of the raw item text. The value
                        bound to the Select is still the key. */}
                    {ggufVariantDisplayLabel(
                      variants.find((v) => v.quant === selectedVariant) ?? {
                        quant: selectedVariant ?? "",
                      },
                    )}
                  </SelectValue>
                </SelectTrigger>
                <SelectContent align="start" className="min-w-[min(calc(16rem*var(--ui-space-scale,1)),calc(100vw-32px))]">
                  {variants.map((variant) => {
                    const size = formatBytes(
                      variant.download_size_bytes ?? variant.size_bytes,
                    );
                    return (
                      <SelectItem
                        key={variant.quant}
                        value={variant.quant}
                        className="[&>span:last-child]:w-full [&>span:last-child]:justify-between"
                      >
                        <span className="font-mono text-xs whitespace-nowrap">
                          {/* The key is the selection identity and can be path-qualified; the
                              label is what it reads as. The SelectItem value stays the key. */}
                          {ggufVariantDisplayLabel(variant)}
                        </span>
                        {size ? (
                          <span className="text-ui-10 whitespace-nowrap text-muted-foreground">
                            {size}
                          </span>
                        ) : null}
                      </SelectItem>
                    );
                  })}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>

        {variantsFailed ? (
          <p className="text-ui-11 leading-relaxed text-amber-700 dark:text-amber-400">
            {t("settings.agents.quantizationLoadError")}
          </p>
        ) : null}

        <div className="flex min-w-0 flex-col gap-2.5">
          <span className="text-xs font-medium text-foreground">
            {t("settings.agents.generatedCommand")}
          </span>
          <p className="text-ui-11 leading-relaxed text-muted-foreground">
            {t("settings.agents.automaticSettingsNote")}
          </p>
          <CopyableCode
            value={command}
            copyLabel={t("settings.agents.copyGeneratedCommand")}
            copied={copied}
            onCopy={handleCopy}
            sensitive={freshApiKey !== null}
          />
          {selectedAgent === "vscode" && (
            <p className="text-ui-11 leading-relaxed text-muted-foreground">
              {t("settings.agents.vscodeNote")}
            </p>
          )}
          <p className="text-ui-11 leading-relaxed text-muted-foreground">
            {t("settings.agents.configurationNote")}{" "}
            <a
              href={FLAGS_DOCS_URL}
              target="_blank"
              rel="noopener noreferrer"
              className="rounded-full text-foreground underline decoration-border decoration-dotted underline-offset-2 transition-colors hover:decoration-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
            >
              {t("settings.agents.configurationDocs")}
            </a>{" "}
            {t("settings.agents.configurationFlagsSuffix")}
          </p>
        </div>

        <SubagentSection
          key={`${selectedAgent}:${commandModel}`}
          command={shellCommands.subagent}
          agent={selectedAgentDetails}
          sensitive={freshApiKey !== null}
        />

        <p className="text-ui-11 leading-relaxed text-muted-foreground">
          {t("settings.agents.modelNote")}
        </p>
      </section>

      <SettingsSection
        title={t("settings.agents.options.title")}
        description={t("settings.agents.options.description")}
      >
        <div className="mt-1 flex flex-col divide-y divide-border/60">
          {OPTION_ROWS.map((row) => (
            <div
              key={row.flag}
              className="grid grid-cols-[minmax(0,11rem)_1fr] items-start gap-x-5 gap-y-1 py-2.5 max-sm:grid-cols-1"
            >
              <code className="min-w-0 break-words font-mono text-xs font-medium text-foreground">
                {row.flag}
              </code>
              <span className="text-xs leading-relaxed text-muted-foreground">
                {t(row.descKey)}
              </span>
            </div>
          ))}
        </div>
      </SettingsSection>

      <SettingsSection
        title={t("settings.agents.remote.title")}
        description={t("settings.agents.remote.description")}
      >
        <div className="pt-3">
          <CommandBlock command={shellCommands.remoteSetup} />
        </div>
      </SettingsSection>

      <SettingsSection
        title={t("settings.agents.passthrough.title")}
        description={t("settings.agents.passthrough.description")}
      >
        <div className="flex flex-col gap-3 pt-3">
          {shellCommands.passThrough.map((passThroughCommand) => (
            <CommandBlock
              key={passThroughCommand}
              command={passThroughCommand}
            />
          ))}
        </div>
      </SettingsSection>

      <SettingsSection
        title={t("settings.agents.dryRun.title")}
        description={t("settings.agents.dryRun.description")}
      >
        <div className="pt-3">
          <CommandBlock command={shellCommands.dryRun} />
        </div>
      </SettingsSection>

      <SettingsSection title={t("settings.mcp.title")}>
        <McpAccessSection apiKey={freshApiKey} />
        <p className="pt-1 text-xs leading-snug text-muted-foreground">
          {t("settings.mcp.keyHint")}{" "}
          <button
            type="button"
            className="rounded-sm font-medium text-foreground underline underline-offset-2 transition-colors hover:text-primary focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
            onClick={() =>
              useSettingsDialogStore.getState().setActiveTab("api-keys")
            }
          >
            {t("settings.mcp.createKey")}
          </button>
        </p>
      </SettingsSection>
    </div>
  );
}