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.

35.3 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 { resetChatBackground } from "@/features/chat-background";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { useChatRuntimeStore } from "@/features/chat";
// From the keys module, not the barrel or the store: both are in an import cycle with this file,
// so the key was still in its temporal dead zone when the module-scope list below read it, killing
// the module graph. The keys module imports nothing, so it is always evaluated first.
import { SIDEBAR_ORGANIZATION_STORAGE_KEY } from "@/features/chat/stores/sidebar-organization-keys";
import {
  LOADED_MODELS_PREFERENCE_KEYS,
  setShowLoadedModels,
  useShowLoadedModels,
} from "@/features/loaded-models";

import { useHfTokenStore } from "@/features/hub";
import {
  emitTrainingRunsChanged,
  TRAINING_UI_PREFERENCE_KEYS,
} from "@/features/training";
import { FLOATING_PANEL_POSITION_KEYS } from "@/hooks/floating-panel-position";
import {
  NOTIFICATION_PREF_KEYS,
  type NotificationChannel,
} from "@/hooks/use-notification-frequency";
import { useHfTokenValidation } from "@/hooks";
import { LOCALE_STORAGE_KEY, getLocale, translate, type TranslationKey, useT } from "@/i18n";
import { isTauri } from "@/lib/api-base";
import {
  SPELLCHECK_STORAGE_KEY,
  setSpellCheck,
  useSpellCheck,
} from "@/lib/spellcheck";
import {
  TIME_FORMAT_STORAGE_KEY,
  type TimeFormat,
  setTimeFormat,
  useTimeFormat,
} from "@/lib/time-format";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { useEffect, useRef, useState } from "react";
import {
  type HelperPrecacheSettings,
  loadHelperPrecacheSettings,
  updateHelperPrecacheSettings,
} from "../api/helper-precache";
import {
  type PreviewSharingSettings,
  loadPreviewSharing,
  rotatePreviewLinks,
  updatePreviewSharing,
} from "../api/preview-sharing";
import {
  DEFAULT_UPLOAD_LIMIT_MB,
  type UploadLimitSettings,
  loadUploadLimitSettings,
  updateUploadLimitSettings,
} from "../api/upload-limit";
import { loadCloseToTray, updateCloseToTray } from "../api/close-to-tray";
import { loadTrayIconVisible, updateTrayIconVisible } from "../api/tray-icon";
import { loadLaunchAtLogin, updateLaunchAtLogin } from "../api/launch-at-login";
import { useIsAccountOwner } from "@/features/auth";
import {
  LIBRARY_CHATS_PREFS_STORAGE_KEY,
  LIBRARY_SETTINGS_STORAGE_KEY,
  LIBRARY_VIEW_STORAGE_KEY,
} from "@/features/library";
import { readPending, writePending } from "../lib/client-prefs-pending";
import { DesktopInstallTypeControl } from "../components/full-install-dialog";
import { ChangePasswordDialog } from "../components/change-password-dialog";
import { DesktopRepairControl } from "../components/desktop-repair-control";
import { DesktopUpdateControl } from "../components/desktop-update-control";
import { DocumentsRagSection } from "../components/documents-rag-section";
import { LanguageSelect } from "../components/language-select";
import {
  DOWNLOAD_DIR_STORAGE_KEY,
  TRANSPORT_MODE_STORAGE_KEY,
} from "@/features/hub";
import { DownloadSpeedLimitRow } from "../components/download-speed-limit-row";
import { DownloadTransportRow } from "../components/download-transport-row";
import { HubSettingsSection } from "../components/hub-settings-section";
import { MlWarmupSection } from "../components/ml-warmup-section";
import { NotificationFrequencySelect } from "../components/notification-frequency-select";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
import { StudioVersionSection } from "../components/studio-version-section";
import { useDesktopBooleanSetting } from "../hooks/use-desktop-boolean-setting";
import { KEYBOARD_SHORTCUTS_STORAGE_KEY } from "../stores/keyboard-shortcuts-store";
import { INTERFACE_SCALE_STORAGE_KEY } from "../stores/interface-scale-store";
import { SETTINGS_PANEL_PREFS_STORAGE_KEY } from "../stores/settings-panel-prefs-store";
import { CHAT_PROJECT_ATTACHMENT_TARGET_KEY } from "@/features/chat/utils/project-attachment-target";
import { Tick02Icon } from "@/lib/tick-icon";
import { HugeiconsIcon } from "@hugeicons/react";
import { ViewIcon, ViewOffSlashIcon } from "@hugeicons/core-free-icons";

// whisper.cpp rides along with llama.cpp's card, so it has no line of its own.
const UPDATE_REMINDER_CHANNELS: {
  channel: NotificationChannel;
  name: string;
  hintKey?: TranslationKey;
}[] = [
  { channel: "unsloth", name: "Unsloth" },
  {
    channel: "llama",
    name: "llama.cpp",
    hintKey: "settings.general.notifications.llamaHint",
  },
  {
    channel: "audio",
    name: "audio.cpp",
    hintKey: "settings.general.notifications.audioHint",
  },
];

// Keys cleared by "Reset all local preferences". NEVER include auth/session keys here -- that
// would log the user out (unsloth_auth_token, unsloth_auth_refresh_token, and
// unsloth_auth_must_change_password are excluded).
const PREFS_KEYS: string[] = [
  "theme",
  "palette",
  "unsloth_appearance_customization",
  "unsloth_window_material",
  INTERFACE_SCALE_STORAGE_KEY,
  LOCALE_STORAGE_KEY,
  SPELLCHECK_STORAGE_KEY,
  TIME_FORMAT_STORAGE_KEY,
  // UI state
  "sidebar_pinned",
  "sidebar_width",
  "chat_settings_width",
  "unsloth_sidebar_navigate_open",
  LIBRARY_SETTINGS_STORAGE_KEY,
  LIBRARY_VIEW_STORAGE_KEY,
  LIBRARY_CHATS_PREFS_STORAGE_KEY,
  SIDEBAR_ORGANIZATION_STORAGE_KEY,
  "unsloth_settings_active_tab",
  SETTINGS_PANEL_PREFS_STORAGE_KEY,
  // Rebound chords, so a bad binding has an escape hatch.
  KEYBOARD_SHORTCUTS_STORAGE_KEY,
  // Outranks the install-wide setting, so it must be cleared too.
  TRANSPORT_MODE_STORAGE_KEY,
  DOWNLOAD_DIR_STORAGE_KEY,
  // Chat runtime prefs
  CHAT_PROJECT_ATTACHMENT_TARGET_KEY,
  "unsloth_chat_auto_title",
  "unsloth_chat_permission_mode",
  "unsloth_chat_sandbox_level",
  // Legacy confirm key: loadPermissionMode falls back to it, so clear both or a reset restores it.
  "unsloth_chat_confirm_tool_calls",
  "unsloth_hf_token",
  "unsloth_auto_heal_tool_calls",
  "unsloth_nudge_tool_calls",
  "unsloth_max_tool_calls_per_message",
  "unsloth_tool_call_timeout",
  "unsloth_chat_inference_params",
  "unsloth_chat_collapsible_state",
  "unsloth_chat_preferences",
  "unsloth_model_configs",
  "unsloth_model_configs_migrated",
  "unsloth_model_config_stamps",
  "unsloth_load_settings",
  "unsloth_model_advanced_settings",
  "unsloth_chat_load_on_selection",
  "unsloth_chat_expand_quantizations",
  "unsloth_chat_show_all_quantizations",
  // Spelled out, not CHAT_SHOW_MEMORY_BAR_KEY: chat-runtime-store is in an import cycle with this
  // file. A test pins this literal against the store's constant.
  "unsloth_chat_show_memory_bar",
  "unsloth_models_fit_on_device_only",
  "unsloth_chat_custom_presets",
  "unsloth_chat_active_preset",
  "unsloth_chat_system_prompts",
  "unsloth_chat_system_prompts_migrated",
  "unsloth_training_config_v1",
  "unsloth_prev_max_steps",
  "unsloth_prev_save_steps",
  ...TRAINING_UI_PREFERENCE_KEYS,
  "unsloth_user_profile",
  "unsloth_profile_activity_chart",
  // Guided tour flags
  "tour:studio:v1",
  // Update notifications
  ...NOTIFICATION_PREF_KEYS,
  "unsloth_llama_update_offer_suppression",
  "unsloth_monitor_overlay",
  LOADED_MODELS_PREFERENCE_KEYS.show,
  LOADED_MODELS_PREFERENCE_KEYS.collapsed,
  LOADED_MODELS_PREFERENCE_KEYS.position,
  LOADED_MODELS_PREFERENCE_KEYS.dismissed,
  ...Object.values(FLOATING_PANEL_POSITION_KEYS),
  // Voice settings
  "unsloth_voice_settings",
  // Retired keys: installs that ran the old onboarding wizard still carry its flag.
  "unsloth_onboarding_done",
];

// Set by resetAllPrefs so the unmount commit skips writing back the in-memory draft.
let resetInProgress = false;

async function resetAllPrefs() {
  if (!(await resetChatBackground())) {
    toast.error(translate("chatBackground.storageError", {}, getLocale()));
    return;
  }
  resetInProgress = true;
  for (const key of PREFS_KEYS) {
    try {
      localStorage.removeItem(key);
    } catch {
      // ignore
    }
  }
  // Unsent, so the defaults beat the account's saved copy after the reload.
  writePending({
    ...readPending(),
    scale: true,
    chat: true,
    timeFormat: true,
    spellcheck: true,
  });
  window.location.reload();
}

export function GeneralTab() {
  const isOwner = useIsAccountOwner();
  const t = useT();
  const hfToken = useChatRuntimeStore((s) => s.hfToken);
  const setHfToken = useChatRuntimeStore((s) => s.setHfToken);

  const hfTokenPersistenceError = useHfTokenStore(
    (s) => s.persistenceError,
  );
  const hfTokenIsPersisting = useHfTokenStore((s) => s.isPersisting);
  const showLoadedModels = useShowLoadedModels();
  const spellCheck = useSpellCheck();
  const timeFormat = useTimeFormat();

  const [draftToken, setDraftToken] = useState(hfToken ?? "");
  const [showToken, setShowToken] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [uploadLimit, setUploadLimit] = useState<UploadLimitSettings | null>(
    null,
  );
  const [draftUploadLimit, setDraftUploadLimit] = useState(
    String(DEFAULT_UPLOAD_LIMIT_MB),
  );
  const [uploadLimitError, setUploadLimitError] = useState<string | null>(null);
  const [isSavingUploadLimit, setIsSavingUploadLimit] = useState(false);
  const [helperPrecache, setHelperPrecache] =
    useState<HelperPrecacheSettings | null>(null);
  const [helperPrecacheError, setHelperPrecacheError] = useState<string | null>(
    null,
  );
  const [isSavingHelperPrecache, setIsSavingHelperPrecache] = useState(false);
  const [previewSharing, setPreviewSharing] =
    useState<PreviewSharingSettings | null>(null);
  const [previewSharingError, setPreviewSharingError] = useState<string | null>(
    null,
  );
  const [isSavingPreviewSharing, setIsSavingPreviewSharing] = useState(false);
  const [revokePreviewOpen, setRevokePreviewOpen] = useState(false);
  const [isRevokingPreview, setIsRevokingPreview] = useState(false);
  const launchAtLoginSetting = useDesktopBooleanSetting({
    enabled: isTauri,
    load: loadLaunchAtLogin,
    save: updateLaunchAtLogin,
    loadError: t("settings.general.startup.loadError"),
    saveError: t("settings.general.startup.saveError"),
  });
  const closeToTraySetting = useDesktopBooleanSetting({
    enabled: isTauri,
    load: loadCloseToTray,
    save: updateCloseToTray,
    loadError: t("settings.general.startup.loadError"),
    saveError: t("settings.general.startup.closeToTraySaveError"),
  });
  const trayIconSetting = useDesktopBooleanSetting({
    enabled: isTauri,
    load: loadTrayIconVisible,
    save: updateTrayIconVisible,
    loadError: t("settings.general.startup.loadError"),
    saveError: t("settings.general.startup.menuBarIconSaveError"),
  });

  const draftRef = useRef(draftToken);
  const tokenEditedRef = useRef(false);
  const tokenEditRevisionRef = useRef(0);
  const submittedTokenRevisionRef = useRef<number | null>(null);
  useEffect(() => {
    draftRef.current = draftToken;
  }, [draftToken]);

  // Commit on unmount (dialog close / tab switch), skipped during reset.
  useEffect(() => {
    return () => {
      if (resetInProgress || !tokenEditedRef.current) return;
      const credential = useHfTokenStore.getState();
      if (
        submittedTokenRevisionRef.current !== null &&
        submittedTokenRevisionRef.current === tokenEditRevisionRef.current &&
        !credential.isPersisting &&
        !credential.persistenceError
      ) {
        return;
      }
      const trimmed = draftRef.current.trim();
      const current = useChatRuntimeStore.getState().hfToken;
      if (trimmed !== current) {
        useChatRuntimeStore.getState().setHfToken(trimmed);
      }
    };
  }, []);

  useEffect(() => {
    const current = hfToken ?? "";
    if (tokenEditedRef.current) {
      if (hfTokenIsPersisting) return;
      if (hfTokenPersistenceError) {
        submittedTokenRevisionRef.current = null;
        return;
      }
      if (
        submittedTokenRevisionRef.current !== tokenEditRevisionRef.current &&
        draftRef.current.trim() !== current
      ) {
        return;
      }
      tokenEditedRef.current = false;
      submittedTokenRevisionRef.current = null;
    }
    draftRef.current = current;
    setDraftToken(current);
  }, [hfToken, hfTokenIsPersisting, hfTokenPersistenceError]);

  const commitToken = () => {
    if (!tokenEditedRef.current) return;
    const trimmed = draftRef.current.trim();
    draftRef.current = trimmed;
    if (trimmed !== draftToken) setDraftToken(trimmed);
    const current = useChatRuntimeStore.getState().hfToken;
    if (trimmed === current) {
      tokenEditedRef.current = false;
      submittedTokenRevisionRef.current = null;
      return;
    }
    submittedTokenRevisionRef.current = tokenEditRevisionRef.current;
    setHfToken(trimmed);
  };

  const clearHfToken = () => {
    tokenEditRevisionRef.current += 1;
    tokenEditedRef.current = true;
    submittedTokenRevisionRef.current = tokenEditRevisionRef.current;
    draftRef.current = "";
    setDraftToken("");
    setHfToken("");
  };

  // Only after the validation endpoint confirms the token: a saved one may be expired or revoked.
  const tokenIsCurrent =
    draftToken.trim().length > 0 && draftToken.trim() === (hfToken ?? "");
  const tokenValidation = useHfTokenValidation(hfToken ?? "");
  const tokenValidated = tokenIsCurrent && tokenValidation.isValid === true;

  useEffect(() => {
    if (!isOwner) return;
    let cancelled = false;
    void loadUploadLimitSettings()
      .then((settings) => {
        if (cancelled) return;
        setUploadLimit(settings);
        setDraftUploadLimit(String(settings.maxUploadSizeMb));
      })
      .catch((error) => {
        if (cancelled) return;
        setUploadLimitError(
          error instanceof Error
            ? error.message
            : "Failed to load upload limit.",
        );
      });
    return () => {
      cancelled = true;
    };
  }, [isOwner]);

  useEffect(() => {
    if (!isOwner) return;
    let cancelled = false;
    void loadHelperPrecacheSettings()
      .then((settings) => {
        if (cancelled) return;
        setHelperPrecache(settings);
        setHelperPrecacheError(null);
      })
      .catch((error) => {
        if (cancelled) return;
        setHelperPrecacheError(
          error instanceof Error
            ? error.message
            : t("settings.general.helperLlm.loadError"),
        );
      });
    return () => {
      cancelled = true;
    };
  }, [t, isOwner]);

  useEffect(() => {
    if (!isOwner) return;
    let cancelled = false;
    void loadPreviewSharing()
      .then((settings) => {
        if (cancelled) return;
        setPreviewSharing(settings);
        setPreviewSharingError(null);
      })
      .catch((error) => {
        if (cancelled) return;
        setPreviewSharingError(
          error instanceof Error
            ? error.message
            : t("settings.general.previewSharing.loadError"),
        );
      });
    return () => {
      cancelled = true;
    };
  }, [t, isOwner]);

  const saveHelperPrecache = async (enabled: boolean) => {
    setIsSavingHelperPrecache(true);
    setHelperPrecacheError(null);
    try {
      const settings = await updateHelperPrecacheSettings(enabled);
      setHelperPrecache(settings);
    } catch (error) {
      setHelperPrecacheError(
        error instanceof Error
          ? error.message
          : t("settings.general.helperLlm.saveError"),
      );
    } finally {
      setIsSavingHelperPrecache(false);
    }
  };

  const savePreviewSharing = async (enabled: boolean) => {
    setIsSavingPreviewSharing(true);
    setPreviewSharingError(null);
    try {
      const settings = await updatePreviewSharing(enabled);
      setPreviewSharing(settings);
      // Sharing toggles whether /api/train/runs returns preview_sig.
      emitTrainingRunsChanged();
    } catch (error) {
      setPreviewSharingError(
        error instanceof Error
          ? error.message
          : t("settings.general.previewSharing.saveError"),
      );
    } finally {
      setIsSavingPreviewSharing(false);
    }
  };

  const revokePreviewLinks = async () => {
    setIsRevokingPreview(true);
    try {
      await rotatePreviewLinks();
      // The secret rotated, so held preview_sig values are stale.
      emitTrainingRunsChanged();
      setRevokePreviewOpen(false);
      toast.success(t("settings.general.previewSharing.revoked"));
    } catch (error) {
      toast.error(t("settings.general.previewSharing.revokeError"), {
        description: error instanceof Error ? error.message : undefined,
      });
    } finally {
      setIsRevokingPreview(false);
    }
  };


  const saveUploadLimit = async () => {
    const parsed = Number(draftUploadLimit);
    if (!Number.isInteger(parsed)) {
      setUploadLimitError("Enter a whole number of MB.");
      return;
    }
    const min = uploadLimit?.minUploadSizeMb ?? 1;
    const max = uploadLimit?.maxAllowedUploadSizeMb ?? 8192;
    if (parsed < min || parsed > max) {
      setUploadLimitError(`Enter a value from ${min} to ${max} MB.`);
      return;
    }
    setIsSavingUploadLimit(true);
    setUploadLimitError(null);
    try {
      const settings = await updateUploadLimitSettings(parsed);
      setUploadLimit(settings);
      setDraftUploadLimit(String(settings.maxUploadSizeMb));
    } catch (error) {
      setUploadLimitError(
        error instanceof Error ? error.message : "Failed to save upload limit.",
      );
    } finally {
      setIsSavingUploadLimit(false);
    }
  };

  return (
    <div className="settings-page">
      <header className="flex flex-col gap-1">
        <h1 className="text-xl font-semibold font-heading">
          {t("settings.general.title")}
        </h1>
        <p className="text-xs text-muted-foreground">
          {t("settings.general.description")}
        </p>
      </header>

      {/* Desktop-only, and self-gating: outside the desktop app these render
          nothing and the section keeps just the version rows. */}
      <StudioVersionSection>
        {isTauri ? (
          <div data-settings-label={t("settings.about.updates")}>
            <DesktopUpdateControl />
          </div>
        ) : null}
        <DesktopInstallTypeControl />
      </StudioVersionSection>

      <SettingsSection title={t("settings.general.account")}>
        <SettingsRow
          label={t("settings.general.huggingFaceToken")}
          description={t("settings.general.huggingFaceTokenDescription")}
          below={
            hfTokenPersistenceError ? (
              <p className="max-w-[calc(330px*var(--ui-space-scale,1))] text-right text-xs text-destructive">
                {hfTokenPersistenceError}
              </p>
            ) : tokenValidation.isChecking ? (
              <p className="text-xs text-muted-foreground">
                {t("settings.general.checkingToken")}
              </p>
            ) : tokenValidation.error ? (
              <p className="max-w-[calc(330px*var(--ui-space-scale,1))] text-right text-xs text-destructive">
                {tokenValidation.error}
              </p>
            ) : null
          }
        >
          <div className="flex max-w-full items-center gap-2">
            <div className="relative w-[calc(260px*var(--ui-space-scale,1))] min-w-0">
              <Input
                type={showToken ? "text" : "password"}
                name="hf-token"
                autoComplete="new-password"
                spellCheck={false}
                placeholder="hf_…"
                value={draftToken}
                onChange={(e) => {
                  const value = e.target.value;
                  tokenEditRevisionRef.current += 1;
                  tokenEditedRef.current = value.trim() !== (hfToken ?? "");
                  submittedTokenRevisionRef.current = null;
                  draftRef.current = value;
                  setDraftToken(value);
                }}
                onBlur={commitToken}
                className={cn(
                  "h-control w-full font-mono text-xs",
                  tokenValidated ? "pr-14" : "pr-8",
                )}
              />
              {tokenValidated ? (
                <span
                  className="pointer-events-none absolute right-7 top-1/2 flex size-5 -translate-y-1/2 items-center justify-center text-emerald-600 duration-150 animate-in fade-in zoom-in dark:text-emerald-500"
                  role="img"
                  aria-label={t("settings.general.tokenValidated")}
                >
                  <HugeiconsIcon icon={Tick02Icon} className="size-4" strokeWidth={2.5} />
                </span>
              ) : null}
              <button
                type="button"
                onClick={() => setShowToken((s) => !s)}
                className="absolute right-1.5 top-1/2 flex size-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground transition-colors hover:text-foreground"
                aria-label={
                  showToken
                    ? t("settings.general.hideToken")
                    : t("settings.general.showToken")
                }
                tabIndex={-1}
              >
                {showToken ? (
                  <HugeiconsIcon icon={ViewOffSlashIcon} className="size-3.5" />
                ) : (
                  <HugeiconsIcon icon={ViewIcon} className="size-3.5" />
                )}
              </button>
            </div>
            <Button
              type="button"
              variant="outline"
              size="sm"
              disabled={!draftToken && !hfToken}
              onClick={clearHfToken}
            >
              {t("settings.general.clearToken")}
            </Button>
          </div>
        </SettingsRow>
        {/* The desktop owner authenticates via desktop auto-auth with a generated
            secret, so the owner password only governs remote browsers and is
            managed in Remote access instead. Managed accounts sign in here. */}
        {isTauri && isOwner ? null : (
          <SettingsRow
            label={t("settings.general.password")}
            description={t("settings.general.passwordDescription")}
          >
            <ChangePasswordDialog />
          </SettingsRow>
        )}
      </SettingsSection>

      <SettingsSection title={t("settings.general.display.title")}>
        <SettingsRow
          label={t("settings.appearance.language.label")}
          description={t("settings.appearance.language.description")}
        >
          <LanguageSelect />
        </SettingsRow>
        <SettingsRow
          label={t("settings.general.display.timeFormat")}
          description={t("settings.general.display.timeFormatDescription")}
        >
          <Select
            value={timeFormat}
            onValueChange={(next) => setTimeFormat(next as TimeFormat)}
          >
            <SelectTrigger
              size="sm"
              className="w-48"
              aria-label={t("settings.general.display.timeFormat")}
            >
              <SelectValue />
            </SelectTrigger>
            <SelectContent align="end">
              <SelectItem value="system">
                {t("settings.general.display.timeFormatSystem")}
              </SelectItem>
              <SelectItem value="12h">
                {t("settings.general.display.timeFormat12")}
              </SelectItem>
              <SelectItem value="24h">
                {t("settings.general.display.timeFormat24")}
              </SelectItem>
            </SelectContent>
          </Select>
        </SettingsRow>
        <SettingsRow
          label={t("settings.appearance.language.spellCheck")}
          description={t("settings.appearance.language.spellCheckDescription")}
        >
          <Switch checked={spellCheck} onCheckedChange={setSpellCheck} />
        </SettingsRow>
      </SettingsSection>

      {/* Owner-only like the installation-wide block below: its routes are. */}
      {isOwner ? <DocumentsRagSection /> : null}

      <SettingsSection title={t("settings.general.notifications.sectionTitle")}>
        <SettingsRow
          label={t("settings.general.notifications.showLoadedModels")}
          description={t(
            "settings.general.notifications.showLoadedModelsDescription",
          )}
        >
          <Switch
            checked={showLoadedModels}
            onCheckedChange={setShowLoadedModels}
          />
        </SettingsRow>
        <SettingsRow
          label={t("settings.general.notifications.updateReminders")}
          description={t(
            "settings.general.notifications.updateRemindersDescription",
          )}
          className="pb-1"
        />
        <div className="flex flex-col pb-3">
          {UPDATE_REMINDER_CHANNELS.map(({ channel, name, hintKey }) => (
            <div
              key={channel}
              data-settings-label={name}
              className="flex items-start justify-between gap-4 py-1.5"
            >
              <div className="flex min-w-0 items-baseline gap-2">
                <span className="text-sm text-foreground">{name}</span>
                {hintKey ? (
                  <span className="truncate text-xs text-muted-foreground">
                    {t(hintKey)}
                  </span>
                ) : null}
              </div>
              <NotificationFrequencySelect
                channel={channel}
                label={`${t("settings.general.notifications.updateReminders")}: ${name}`}
              />
            </div>
          ))}
        </div>
      </SettingsSection>

      {isOwner ? (
        <>
      <SettingsSection
        title={t("settings.general.previewSharing.sectionTitle")}
      >
        <SettingsRow
          label={t("settings.general.previewSharing.enableLabel")}
          description={t("settings.general.previewSharing.enableDescription")}
          below={
            previewSharingError ? (
              <span className="max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs text-destructive">
                {previewSharingError}
              </span>
            ) : null
          }
        >
          <Switch
            checked={previewSharing?.enabled ?? false}
            disabled={!previewSharing || isSavingPreviewSharing}
            onCheckedChange={(enabled) => void savePreviewSharing(enabled)}
          />
        </SettingsRow>
        <SettingsRow
          label={t("settings.general.previewSharing.revokeLabel")}
          description={t("settings.general.previewSharing.revokeDescription")}
        >
          <Button
            variant="destructive"
            size="sm"
            onClick={() => setRevokePreviewOpen(true)}
            className="text-destructive hover:text-destructive"
          >
            {t("settings.general.previewSharing.revokeAction")}
          </Button>
        </SettingsRow>
      </SettingsSection>

      <HubSettingsSection />

      <SettingsSection title={t("settings.general.downloads.sectionTitle")}>
        <DownloadTransportRow />
        <DownloadSpeedLimitRow />
      </SettingsSection>

      <SettingsSection title={t("settings.general.uploads.sectionTitle")}>
        <SettingsRow
          label={t("settings.general.uploads.maxUploadSize")}
          description={t("settings.general.uploads.maxUploadSizeDescription", {
            defaultSize: String(
              uploadLimit?.defaultUploadSizeMb ?? DEFAULT_UPLOAD_LIMIT_MB,
            ),
          })}
          below={
            uploadLimitError ? (
              <span className="max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs text-destructive">
                {uploadLimitError}
              </span>
            ) : null
          }
        >
          <div className="flex items-center gap-2">
            <div className="flex items-center gap-1.5">
              <Input
                type="number"
                min={uploadLimit?.minUploadSizeMb ?? 1}
                max={uploadLimit?.maxAllowedUploadSizeMb ?? 8192}
                step={1}
                value={draftUploadLimit}
                aria-label={t("settings.general.uploads.maxUploadSize")}
                onChange={(event) => setDraftUploadLimit(event.target.value)}
                className="h-control w-24"
              />
              <span className="text-xs font-medium text-muted-foreground">
                MB
              </span>
            </div>
            <Button
              variant="outline"
              size="sm"
              disabled={isSavingUploadLimit}
              onClick={() => void saveUploadLimit()}
            >
              {isSavingUploadLimit ? t("common.saving") : t("common.save")}
            </Button>
          </div>
        </SettingsRow>
      </SettingsSection>


      <MlWarmupSection />

      <SettingsSection title={t("settings.general.helperLlm.sectionTitle")}>
        <SettingsRow
          label={t("settings.general.helperLlm.preloadOnStartup")}
          description={t(
            "settings.general.helperLlm.preloadOnStartupDescription",
          )}
          below={
            helperPrecache?.disabledByEnv ? (
              <span className="max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs text-muted-foreground">
                {t("settings.general.helperLlm.disabledByEnv")}
              </span>
            ) : helperPrecacheError ? (
              <span className="max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs text-destructive">
                {helperPrecacheError}
              </span>
            ) : null
          }
        >
          <Switch
            checked={helperPrecache?.enabled ?? false}
            disabled={
              !helperPrecache ||
              isSavingHelperPrecache ||
              helperPrecache.disabledByEnv
            }
            onCheckedChange={(enabled) => void saveHelperPrecache(enabled)}
          />
        </SettingsRow>
      </SettingsSection>

        </>
      ) : null}

      {isTauri ? (
        <SettingsSection title={t("settings.general.startup.sectionTitle")}>
          <SettingsRow
            label={t("settings.general.startup.launchAtLogin")}
            description={t("settings.general.startup.launchAtLoginDescription")}
            below={
              launchAtLoginSetting.error ? (
                <span className="max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs text-destructive">
                  {launchAtLoginSetting.error}
                </span>
              ) : null
            }
          >
            <Switch
              checked={launchAtLoginSetting.value ?? false}
              disabled={
                launchAtLoginSetting.value === null || launchAtLoginSetting.saving
              }
              onCheckedChange={(enabled) => void launchAtLoginSetting.update(enabled)}
            />
          </SettingsRow>

          {closeToTraySetting.supported ? (
            <SettingsRow
              label={t("settings.general.startup.closeToTray")}
              description={t("settings.general.startup.closeToTrayDescription")}
              below={
                closeToTraySetting.error ? (
                  <span className="max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs text-destructive">
                    {closeToTraySetting.error}
                  </span>
                ) : null
              }
            >
              <Switch
                checked={closeToTraySetting.value ?? false}
                disabled={
                  closeToTraySetting.value === null || closeToTraySetting.saving
                }
                onCheckedChange={(enabled) => void closeToTraySetting.update(enabled)}
              />
            </SettingsRow>
          ) : null}

          {trayIconSetting.supported ? (
            <SettingsRow
              label={t("settings.general.startup.menuBarIcon")}
              description={t("settings.general.startup.menuBarIconDescription")}
            >
              <div className="flex flex-col items-end gap-1">
                <Switch
                  checked={trayIconSetting.value ?? false}
                  disabled={
                    trayIconSetting.value === null || trayIconSetting.saving
                  }
                  onCheckedChange={(enabled) => void trayIconSetting.update(enabled)}
                />
                {trayIconSetting.error ? (
                  <span className="max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs text-destructive">
                    {trayIconSetting.error}
                  </span>
                ) : null}
              </div>
            </SettingsRow>
          ) : null}
        </SettingsSection>
      ) : null}

      <SettingsSection
        danger={true}
        title={t("settings.general.resetPreferences.sectionTitle")}
      >
        <SettingsRow
          label={t("settings.general.resetPreferences.label")}
          description={t("settings.general.resetPreferences.description")}
        >
          <Button
            variant="outline"
            size="sm"
            onClick={() => setConfirmOpen(true)}
            className="text-destructive hover:text-destructive"
          >
            {t("settings.general.resetPreferences.action")}
          </Button>
        </SettingsRow>
        {/* Same section as the reset row: both rewrite state the user cannot easily put
            back, and the desktop-only repair renders nothing on the web build, which
            would leave a section header with no rows under it if it had its own. */}
        <DesktopRepairControl />
      </SettingsSection>

      <Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>
              {t("settings.general.resetPreferences.confirmTitle")}
            </DialogTitle>
            <DialogDescription>
              {t("settings.general.resetPreferences.confirmDescription")}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setConfirmOpen(false)}>
              {t("common.cancel")}
            </Button>
            <Button
              onClick={resetAllPrefs}
              variant="destructive"
            >
              {t("settings.general.resetPreferences.confirmAction")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={revokePreviewOpen} onOpenChange={setRevokePreviewOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>
              {t("settings.general.previewSharing.revokeConfirmTitle")}
            </DialogTitle>
            <DialogDescription>
              {t("settings.general.previewSharing.revokeConfirmDescription")}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setRevokePreviewOpen(false)}
            >
              {t("common.cancel")}
            </Button>
            <Button
              variant="destructive"
              onClick={() => void revokePreviewLinks()}
              disabled={isRevokingPreview}
            >
              {isRevokingPreview
                ? t("settings.general.previewSharing.revoking")
                : t("settings.general.previewSharing.revokeConfirmAction")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}