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.

19.8 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 { isTauri } from "@/lib/api-base";
import { isAudioCppFolderId } from "../../audio/audio-cpp-catalog";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import {
  DEFAULT_STT_CONTEXT_LENGTH,
  normalizeSttContextLength,
} from "./stt-context";
import {
  DEFAULT_STT_MODEL,
  type DefaultSttModel,
  STT_MODELS,
  STT_MODEL_LANGUAGES,
  STT_MODEL_REPOS,
  type SttModel,
  migrateVoiceSettings,
} from "./stt-model-catalog";
import { syncSttDevicePreference } from "../api/stt-device";

export * from "./stt-model-catalog";
export * from "./stt-context";

// Adapters read these at call time, so changes apply without reloading the chat runtime.

export interface RecentDictation {
  id: string;
  text: string;
  at: number;
  chatId?: string;
}

// pagination keeps full history; quota failures trim it to QUOTA_TRIM_KEEP.
const QUOTA_TRIM_KEEP = 200;
// transcript caps prevent synchronous localStorage quota failures.
const MAX_RECENT_DICTATION_LENGTH = 2000;
const MAX_DICTIONARY_ENTRIES = 100;
const MAX_DICTIONARY_ENTRY_LENGTH = 120;

const HF_REPO_ID =
  /^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/;

export function isSttModelId(value: string): boolean {
  const normalized = value.trim();
  return (
    (STT_MODELS as readonly string[]).includes(normalized) ||
    HF_REPO_ID.test(normalized) ||
    isAudioCppFolderId(normalized)
  );
}

export function normalizeSttModel(value: unknown): SttModel {
  if (typeof value !== "string") {
    return DEFAULT_STT_MODEL;
  }
  const normalized = value.trim();
  return isSttModelId(normalized) ? normalized : DEFAULT_STT_MODEL;
}

export function getSttModelRepo(model: SttModel): string {
  return STT_MODEL_REPOS[model as DefaultSttModel] ?? normalizeSttModel(model);
}

// Custom `.en` checkpoints are treated as English-only.

export function isSttModelLanguageCompatible(
  model: SttModel,
  language: string,
): boolean {
  const allowed =
    STT_MODEL_LANGUAGES.get(model) ??
    (getSttModelRepo(model).toLowerCase().endsWith(".en") ? ["en"] : null);
  if (!allowed) {
    return true;
  }
  const normalized = language.trim().replaceAll("_", "-").toLowerCase();
  // Auto sends no forced language, which every checkpoint accepts.
  return normalized === "auto" || allowed.includes(normalized.split("-", 1)[0]);
}

export type DictationEngine = "browser" | "model" | "custom";

/** "model" attaches a clip for an audio-input model, else falls back to "asr". */
export type MicTarget = "asr" | "model";

/** Mirrors the backend `SttLoadRequest.device`; "gpu" is not offered since it adds nothing. */
export type SttDevice = "auto" | "cpu";

export const DEFAULT_STT_DEVICE: SttDevice = "auto";

function normalizeSttDevice(value: unknown): SttDevice {
  return value === "cpu" ? "cpu" : DEFAULT_STT_DEVICE;
}

export type TtsEngine = "system" | "studio" | "custom";

/** Custom repos run safetensors on Transformers. */
export function isCuratedSttModel(model: SttModel): boolean {
  return (STT_MODELS as readonly string[]).includes(model.trim());
}

export interface VoiceSettingsState {
  /** input device; "default" selects the system microphone. */
  micDeviceId: string;
  setMicDeviceId: (value: string) => void;

  /** "browser" uses Web Speech API; "model" chooses the local backend from the model. */
  dictationEngine: DictationEngine;
  setDictationEngine: (value: DictationEngine) => void;

  micTarget: MicTarget;
  setMicTarget: (value: MicTarget) => void;

  /** STT model used when dictationEngine is "model". */
  sttModel: SttModel;
  setSttModel: (value: SttModel) => void;

  /** quant for a package folder `sttModel`; "" uses its resident or default quant. */
  sttGgufVariant: string;
  setSttGgufVariant: (value: string) => void;

  /** "cpu" keeps the model in system RAM; loads and transcriptions apply the current value. */
  sttDevice: SttDevice;
  setSttDevice: (value: SttDevice) => void;

  /** Qwen3-ASR context: zero fits each recording; a positive value is a fixed limit. */
  sttContextLength: number;
  setSttContextLength: (value: number) => void;

  sttProviderId: string;
  setSttProviderId: (value: string) => void;
  sttProviderModel: string;
  setSttProviderModel: (value: string) => void;

  /** BCP 47 tag, or "auto" for engine-specific language detection. */
  dictationLanguage: string;
  setDictationLanguage: (value: string) => void;

  /** exact spellings applied to matching transcript words and phrases. */
  dictionary: string[];
  addDictionaryEntry: (value: string) => void;
  updateDictionaryEntry: (index: number, value: string) => void;
  commitDictionaryEntry: (index: number) => void;
  removeDictionaryEntry: (index: number) => void;

  recentDictations: RecentDictation[];
  addRecentDictation: (text: string, chatId?: string) => void;
  removeRecentDictation: (id: string) => void;
  clearRecentDictations: () => void;

  ttsEnabled: boolean;
  setTtsEnabled: (value: boolean) => void;

  /** Speak each finished assistant reply without a click. Off by default. */
  autoReadAloud: boolean;
  setAutoReadAloud: (value: boolean) => void;

  /** "system": speechSynthesis voices. "studio": the loaded TTS audio model.
   * "custom": a saved connection's /audio/speech endpoint. */
  ttsEngine: TtsEngine;
  setTtsEngine: (value: TtsEngine) => void;

  ttsProviderId: string;
  setTtsProviderId: (value: string) => void;
  ttsProviderModel: string;
  setTtsProviderModel: (value: string) => void;
  /** Blank defaults to alloy. */
  ttsProviderVoice: string;
  setTtsProviderVoice: (value: string) => void;

  /** Saved Audio voice id the "studio" engine speaks in; "" for the model's own voice. */
  ttsStudioVoiceId: string;
  setTtsStudioVoiceId: (value: string) => void;

  /** speechSynthesis voiceURI, or "default" for the system voice. */
  ttsVoiceURI: string;
  setTtsVoiceURI: (value: string) => void;

  ttsRate: number;
  setTtsRate: (value: number) => void;
  ttsPitch: number;
  setTtsPitch: (value: number) => void;
  ttsVolume: number;
  setTtsVolume: (value: number) => void;
}

/** On quota errors drop the oldest dictations instead of losing the whole save. */
const quotaSafeLocalStorage = {
  getItem: (key: string) => localStorage.getItem(key),
  removeItem: (key: string) => localStorage.removeItem(key),
  setItem: (key: string, value: string) => {
    try {
      localStorage.setItem(key, value);
      return;
    } catch {
      // Quota exceeded: trim dictation history, oldest first, and retry.
    }
    let parsed: { state?: { recentDictations?: RecentDictation[] } };
    try {
      parsed = JSON.parse(value) as typeof parsed;
    } catch {
      return;
    }
    const state = parsed.state;
    const recents = state?.recentDictations;
    if (!state || !Array.isArray(recents)) return;
    // Halve down to empty, since another store may already have consumed the quota.
    let keep = Math.min(QUOTA_TRIM_KEEP, recents.length);
    for (;;) {
      keep = keep >= recents.length ? Math.floor(recents.length / 2) : keep;
      try {
        state.recentDictations = recents.slice(0, keep);
        localStorage.setItem(key, JSON.stringify(parsed));
        return;
      } catch {
        // Still over quota: trim harder.
      }
      if (keep === 0) return;
      keep = Math.floor(keep / 2);
    }
  },
};

export const useVoiceSettingsStore = create<VoiceSettingsState>()(
  persist(
    (set) => ({
      micDeviceId: "default",
      setMicDeviceId: (micDeviceId) => set({ micDeviceId }),

      dictationEngine: isTauri ? "model" : "browser",
      setDictationEngine: (dictationEngine) => set({ dictationEngine }),

      micTarget: "asr",
      setMicTarget: (micTarget) => set({ micTarget }),

      sttModel: DEFAULT_STT_MODEL,
      setSttModel: (value) =>
        set((state) => {
          const normalized = normalizeSttModel(value);
          const sttModel = isSttModelLanguageCompatible(
            normalized,
            state.dictationLanguage,
          )
            ? normalized
            : DEFAULT_STT_MODEL;
          // a quant belongs to the model it was selected for.
          return sttModel === state.sttModel
            ? { sttModel }
            : { sttModel, sttGgufVariant: "" };
        }),

      sttGgufVariant: "",
      setSttGgufVariant: (sttGgufVariant) => set({ sttGgufVariant }),

      sttDevice: DEFAULT_STT_DEVICE,
      setSttDevice: (value) => {
        const sttDevice = normalizeSttDevice(value);
        set({ sttDevice });
        // Server default for cold /v1/audio/transcriptions loads (#15280).
        syncSttDevicePreference(sttDevice);
      },

      sttContextLength: DEFAULT_STT_CONTEXT_LENGTH,
      setSttContextLength: (value) =>
        set({ sttContextLength: normalizeSttContextLength(value) }),

      sttProviderId: "",
      setSttProviderId: (sttProviderId) => set({ sttProviderId }),
      sttProviderModel: "",
      setSttProviderModel: (sttProviderModel) => set({ sttProviderModel }),

      dictationLanguage: "auto",
      setDictationLanguage: (dictationLanguage) =>
        set((state) =>
          isSttModelLanguageCompatible(state.sttModel, dictationLanguage)
            ? { dictationLanguage }
            : {
                dictationLanguage,
                sttModel: DEFAULT_STT_MODEL,
                sttGgufVariant: "",
              },
        ),

      dictionary: [],
      addDictionaryEntry: (value) =>
        set((state) => {
          const trimmed = value.trim().slice(0, MAX_DICTIONARY_ENTRY_LENGTH);
          if (!trimmed) return state;
          if (state.dictionary.length >= MAX_DICTIONARY_ENTRIES) return state;
          if (
            state.dictionary.some(
              (entry) => entry.toLowerCase() === trimmed.toLowerCase(),
            )
          ) {
            return state;
          }
          return { dictionary: [...state.dictionary, trimmed] };
        }),
      // Raw value while editing; commitDictionaryEntry finalizes on blur.
      updateDictionaryEntry: (index, value) =>
        set((state) => {
          const dictionary = [...state.dictionary];
          if (index < 0 || index >= dictionary.length) return state;
          dictionary[index] = value.slice(0, MAX_DICTIONARY_ENTRY_LENGTH);
          return { dictionary };
        }),
      commitDictionaryEntry: (index) =>
        set((state) => {
          const dictionary = [...state.dictionary];
          if (index < 0 || index >= dictionary.length) return state;
          const trimmed = dictionary[index]?.trim() ?? "";
          if (trimmed) {
            dictionary[index] = trimmed;
          } else {
            dictionary.splice(index, 1);
          }
          return { dictionary };
        }),
      removeDictionaryEntry: (index) =>
        set((state) => ({
          dictionary: state.dictionary.filter((_, i) => i !== index),
        })),

      recentDictations: [],
      addRecentDictation: (text, chatId) =>
        set((state) => {
          const trimmed = text.trim().slice(0, MAX_RECENT_DICTATION_LENGTH);
          if (!trimmed) {
            return state;
          }
          const at = Date.now();
          return {
            recentDictations: [
              {
                id: `${at}-${Math.random().toString(36).slice(2, 10)}`,
                text: trimmed,
                at,
                ...(chatId ? { chatId } : {}),
              },
              ...state.recentDictations,
            ],
          };
        }),
      removeRecentDictation: (id) =>
        set((state) => ({
          recentDictations: state.recentDictations.filter(
            (dictation) => dictation.id !== id,
          ),
        })),
      clearRecentDictations: () => set({ recentDictations: [] }),

      ttsEnabled: true,
      setTtsEnabled: (ttsEnabled) => set({ ttsEnabled }),
      autoReadAloud: false,
      setAutoReadAloud: (autoReadAloud) => set({ autoReadAloud }),

      ttsEngine: "system",
      setTtsEngine: (ttsEngine) => set({ ttsEngine }),

      ttsProviderId: "",
      setTtsProviderId: (ttsProviderId) => set({ ttsProviderId }),
      ttsProviderModel: "",
      setTtsProviderModel: (ttsProviderModel) => set({ ttsProviderModel }),
      ttsProviderVoice: "",
      setTtsProviderVoice: (ttsProviderVoice) => set({ ttsProviderVoice }),

      ttsStudioVoiceId: "",
      setTtsStudioVoiceId: (ttsStudioVoiceId) => set({ ttsStudioVoiceId }),

      ttsVoiceURI: "default",
      setTtsVoiceURI: (ttsVoiceURI) => set({ ttsVoiceURI }),

      ttsRate: 1,
      setTtsRate: (ttsRate) => set({ ttsRate }),
      ttsPitch: 1,
      setTtsPitch: (ttsPitch) => set({ ttsPitch }),
      ttsVolume: 1,
      setTtsVolume: (ttsVolume) => set({ ttsVolume }),
    }),
    {
      name: "unsloth_voice_settings",
      storage: createJSONStorage(() => quotaSafeLocalStorage),
      version: 1,
      migrate: migrateVoiceSettings,
      merge: (persisted, current) => {
        const saved = persisted as Partial<VoiceSettingsState> | undefined;
        const dictationLanguage = asString(saved?.dictationLanguage, "auto");
        // "gguf" was a short-lived separate engine; both local backends now live under "model".
        const savedEngine = saved?.dictationEngine as string | undefined;
        const dictationEngine: DictationEngine =
          savedEngine === "custom"
            ? "custom"
            : isTauri || savedEngine === "model" || savedEngine === "gguf"
              ? "model"
              : "browser";
        const savedSttModel = normalizeSttModel(saved?.sttModel);
        const sttModel = isSttModelLanguageCompatible(
          savedSttModel,
          dictationLanguage,
        )
          ? savedSttModel
          : DEFAULT_STT_MODEL;
        return {
          ...current,
          micDeviceId: asString(saved?.micDeviceId, "default"),
          dictationEngine,
          micTarget: saved?.micTarget === "model" ? "model" : "asr",
          sttModel,
          sttGgufVariant:
            sttModel === savedSttModel
              ? asString(saved?.sttGgufVariant, "")
              : "",
          sttDevice: normalizeSttDevice(saved?.sttDevice),
          sttContextLength: normalizeSttContextLength(saved?.sttContextLength),
          sttProviderId: asString(saved?.sttProviderId, ""),
          sttProviderModel: asString(saved?.sttProviderModel, ""),
          dictationLanguage,
          dictionary: Array.isArray(saved?.dictionary)
            ? saved.dictionary
                .filter((v): v is string => typeof v === "string" && !!v.trim())
                .map((v) => v.trim().slice(0, MAX_DICTIONARY_ENTRY_LENGTH))
                .slice(0, MAX_DICTIONARY_ENTRIES)
            : [],
          recentDictations: normalizeRecentDictations(saved?.recentDictations),
          ttsEnabled:
            typeof saved?.ttsEnabled === "boolean" ? saved.ttsEnabled : true,
          autoReadAloud: saved?.autoReadAloud === true,
          ttsEngine:
            saved?.ttsEngine === "studio" || saved?.ttsEngine === "custom"
              ? saved.ttsEngine
              : "system",
          ttsProviderId: asString(saved?.ttsProviderId, ""),
          ttsProviderModel: asString(saved?.ttsProviderModel, ""),
          ttsProviderVoice: asString(saved?.ttsProviderVoice, ""),
          ttsStudioVoiceId: asString(saved?.ttsStudioVoiceId, ""),
          ttsVoiceURI: asString(saved?.ttsVoiceURI, "default"),
          ttsRate: clampNumber(saved?.ttsRate, 0.5, 2, 1),
          ttsPitch: clampNumber(saved?.ttsPitch, 0, 2, 1),
          ttsVolume: clampNumber(saved?.ttsVolume, 0, 1, 1),
        };
      },
    },
  ),
);
if (typeof window !== "undefined") {
  window.addEventListener("storage", (event) => {
    if (event.key === useVoiceSettingsStore.persist.getOptions().name) {
      void useVoiceSettingsStore.persist.rehydrate();
    }
  });
}

function asString(value: unknown, fallback: string): string {
  return typeof value === "string" && value ? value : fallback;
}

function normalizeRecentDictations(value: unknown): RecentDictation[] {
  if (!Array.isArray(value)) {
    return [];
  }

  const normalized: RecentDictation[] = [];
  for (const [index, entry] of value.entries()) {
    if (!entry || typeof entry !== "object") {
      continue;
    }
    const candidate = entry as Partial<RecentDictation>;
    if (
      typeof candidate.text !== "string" ||
      !candidate.text.trim() ||
      typeof candidate.at !== "number" ||
      !Number.isFinite(candidate.at)
    ) {
      continue;
    }
    normalized.push({
      id:
        typeof candidate.id === "string" && candidate.id
          ? candidate.id
          : `legacy-${candidate.at}-${index}`,
      text: candidate.text.trim().slice(0, MAX_RECENT_DICTATION_LENGTH),
      at: candidate.at,
      ...(typeof candidate.chatId === "string" && candidate.chatId
        ? { chatId: candidate.chatId }
        : {}),
    });
  }
  return normalized;
}

function clampNumber(
  value: unknown,
  min: number,
  max: number,
  fallback: number,
): number {
  if (typeof value !== "number" || Number.isNaN(value)) return fallback;
  return Math.min(max, Math.max(min, value));
}

export function resolveDictationLanguage(setting?: string): string {
  const value = setting ?? useVoiceSettingsStore.getState().dictationLanguage;
  if (value && value !== "auto") return value;
  return typeof navigator !== "undefined" && navigator.language
    ? navigator.language
    : "en-US";
}

// transformers `LANGUAGES` plus stt_sidecar.py `_WHISPER_LANGUAGE_ALIASES`. Keep in sync with
// `_known_whisper_languages()`.
const WHISPER_DICTATION_LANGUAGES = new Set([
  "af", "am", "ar", "as", "az", "ba", "be", "bg", "bn", "bo", "br", "bs",
  "ca", "cmn", "cs", "cy", "da", "de", "el", "en", "es", "et", "eu", "fa",
  "fi", "fil", "fo", "fr", "gl", "gu", "ha", "haw", "he", "hi", "hr", "ht",
  "hu", "hy", "id", "in", "is", "it", "iw", "ja", "ji", "jw", "ka", "kk",
  "km", "kn", "ko", "la", "lb", "ln", "lo", "lt", "lv", "mg", "mi", "mk",
  "ml", "mn", "mr", "ms", "mt", "my", "nb", "ne", "nl", "nn", "no", "oc",
  "pa", "pl", "ps", "pt", "ro", "ru", "sa", "sd", "si", "sk", "sl", "sn",
  "so", "sq", "sr", "su", "sv", "sw", "ta", "te", "tg", "th", "tk", "tl",
  "tr", "tt", "uk", "ur", "uz", "vi", "yi", "yo", "yue", "zh",
]);

/** Only literal "auto" resolves, and only to a language both the model and Whisper honor;
 * otherwise it stays auto-detect rather than 422ing every dictation. */
export function resolveModelDictationLanguage(
  model: SttModel,
  requested: string,
): string {
  if (requested !== "auto") return requested;
  const resolved = resolveDictationLanguage(requested);
  const primary = resolved
    .trim()
    .replaceAll("_", "-")
    .toLowerCase()
    .split("-", 1)[0];
  return isSttModelLanguageCompatible(model, resolved) &&
    WHISPER_DICTATION_LANGUAGES.has(primary)
    ? resolved
    : requested;
}

function escapeRegExp(value: string): string {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

/** Case-insensitive, word-bounded ("jane doe" -> "Jane Doe"). */
export function applyDictationDictionary(
  transcript: string,
  dictionary?: string[],
): string {
  const entries = dictionary ?? useVoiceSettingsStore.getState().dictionary;
  if (!transcript || entries.length === 0) return transcript;
  let result = transcript;
  for (const entry of entries) {
    const trimmed = entry.trim();
    if (!trimmed) continue;
    const pattern = trimmed.split(/\s+/).map(escapeRegExp).join("\\s+");
    try {
      // Capture the boundary instead of a lookbehind, which Safari < 16.4 cannot compile.
      const regex = new RegExp(
        `(^|[^\\p{L}\\p{N}])(${pattern})(?![\\p{L}\\p{N}])`,
        "giu",
      );
      // Callback form avoids $-pattern expansion.
      result = result.replace(regex, (_match, prefix) => `${prefix}${trimmed}`);
    } catch {
      // Skip entries that produce an invalid pattern.
    }
  }
  return result;
}

export function recordRecentDictation(text: string, chatId?: string): void {
  useVoiceSettingsStore.getState().addRecentDictation(text, chatId);
}