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.

8.5 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 { requestSttDownload } from "@/features/settings/stores/stt-download-prompt-store";
import {
  type DictationEngine,
  sttModelVariant,
  useVoiceSettingsStore,
} from "@/features/settings/stores/voice-settings-store";
import { toast } from "@/lib/toast";
import type { DictationAdapter } from "@assistant-ui/react";
import { useChatRuntimeStore } from "../stores/chat-runtime-store";
import { useExternalProvidersStore } from "../stores/external-providers-store";
import { maxAudioFilesFor } from "@/lib/audio-utils";
import { micClipRoom, micSendsAudioToModel } from "../utils/mic-target";
import {
  currentDictationEntryMode,
  insecureDictationGuidance,
} from "../utils/dictation-entry";
import {
  StudioModelDictationAdapter,
  fetchSttStatus,
  sttEngineStatusFor,
  sttQuantDownloaded,
} from "./studio-model-dictation-adapter";
import { PcmRecorder } from "./pcm-recorder";
import {
  discardClipOnRelease,
  discardClipWhenModelChanges,
  listenForAudioClip,
} from "./studio-audio-clip-adapter";
import {
  type StudioDictationSession,
  StudioWebSpeechDictationAdapter,
} from "./studio-web-speech-dictation-adapter";

// one live session lets Escape cancel because assistant-ui only exposes stop, which transcribes.
let activeSession: StudioDictationSession | null = null;

/** discards the active dictation without transcribing; safe when idle. */
export function cancelActiveStudioDictation(): void {
  const session = activeSession;
  activeSession = null;
  session?.cancel();
}

type AudioClipTarget = {
  add: (file: File) => Promise<unknown> | unknown;
  attached: () => readonly { name: string; type: string; size: number }[];
};
type RegisteredClipTarget = AudioClipTarget & { onRelease: Set<() => void> };
// Compare registers none, so it keeps transcribing.
let audioClipTarget: RegisteredClipTarget | null = null;

export function setMicAudioClipTarget(target: AudioClipTarget): () => void {
  const entry: RegisteredClipTarget = { ...target, onRelease: new Set() };
  audioClipTarget = entry;
  return () => {
    if (audioClipTarget === entry) audioClipTarget = null;
    for (const listener of [...entry.onRelease]) listener();
  };
}

export function micRecordsForModel(chatId?: string | null): boolean {
  if (chatId === null || !audioClipTarget) return false;
  const { micTarget } = useVoiceSettingsStore.getState();
  const { params, models, modelLoading } = useChatRuntimeStore.getState();
  const activeModel = modelLoading
    ? undefined
    : models.find((model) => model.id === params.checkpoint);
  return micSendsAudioToModel(micTarget, activeModel?.hasAudioInput === true);
}

/** Local and custom transcription record through the media recorder. */
function usesRecordedAudio(dictationEngine: DictationEngine): boolean {
  return dictationEngine !== "browser";
}

function customSttConfigured(): boolean {
  const { sttProviderId, sttProviderModel } = useVoiceSettingsStore.getState();
  const { connectionsEnabled, providers } =
    useExternalProvidersStore.getState();
  const providerId = sttProviderId.trim();
  return Boolean(
    connectionsEnabled &&
    providerId &&
    sttProviderModel.trim() &&
    providers.some((provider) => provider.id === providerId),
  );
}

export class StudioDictationAdapter implements DictationAdapter {
  // undefined follows the active chat; null links no chat (e.g. Compare).
  private readonly chatId: string | null | undefined;

  constructor(options: { chatId?: string | null } = {}) {
    this.chatId = options.chatId;
  }

  static isSupported(
    dictationEngine: DictationEngine = useVoiceSettingsStore.getState()
      .dictationEngine,
  ): boolean {
    if (dictationEngine === "custom" && !customSttConfigured()) {
      return false;
    }
    return usesRecordedAudio(dictationEngine)
      ? StudioModelDictationAdapter.isSupported()
      : StudioWebSpeechDictationAdapter.isSupported();
  }

  listen(): StudioDictationSession {
    const session = this.createSession();
    // Cancel the old session so it cannot hold the mic or save an undiscardable transcript.
    cancelActiveStudioDictation();
    activeSession = session;
    const clear = () => {
      if (activeSession === session) {
        activeSession = null;
      }
    };
    session.onSpeechEnd(clear);
    session.onEnd?.(clear);
    return session;
  }

  private createSession(): StudioDictationSession {
    const clipTarget = audioClipTarget;
    if (clipTarget && micRecordsForModel(this.chatId)) {
      if (!PcmRecorder.isSupported()) {
        throw new Error("Voice recording is not supported in this browser.");
      }
      const { params, models, modelLoading, pendingAudioBase64 } =
        useChatRuntimeStore.getState();
      const activeModel = modelLoading
        ? undefined
        : models.find((model) => model.id === params.checkpoint);
      const room = micClipRoom(
        clipTarget.attached(),
        maxAudioFilesFor(activeModel),
        !!pendingAudioBase64,
      );
      const session = listenForAudioClip(clipTarget.add, room);
      discardClipWhenModelChanges(session, useChatRuntimeStore);
      discardClipOnRelease(session, clipTarget.onRelease);
      return session;
    }
    const { dictationEngine } = useVoiceSettingsStore.getState();
    if (usesRecordedAudio(dictationEngine)) {
      if (dictationEngine === "custom" && !customSttConfigured()) {
        throw new Error(
          "Custom transcription is not configured. Pick a connection and model in Settings → Voice.",
        );
      }
      if (StudioModelDictationAdapter.isSupported()) {
        return new StudioModelDictationAdapter({
          chatId: this.chatId,
        }).listen();
      }
      throw new Error(
        dictationEngine === "custom"
          ? "Voice recording is not supported in this browser."
          : "Local model dictation is not supported in this browser.",
      );
    }
    if (StudioWebSpeechDictationAdapter.isSupported()) {
      return new StudioWebSpeechDictationAdapter({
        chatId: this.chatId,
      }).listen();
    }
    throw new Error("Browser dictation is not supported in this browser.");
  }
}

export function isStudioDictationAvailable(
  dictationEngine: DictationEngine = useVoiceSettingsStore.getState()
    .dictationEngine,
): boolean {
  return StudioDictationAdapter.isSupported(dictationEngine);
}

export function notifyStudioDictationUnavailable(
  dictationEngine: DictationEngine = useVoiceSettingsStore.getState()
    .dictationEngine,
): void {
  // Both engines need a secure context (localhost or HTTPS).
  if (typeof window !== "undefined" && !window.isSecureContext) {
    toast.error("Voice typing needs a secure connection.", {
      description: insecureDictationGuidance(currentDictationEntryMode()),
    });
    return;
  }
  if (dictationEngine === "custom" && !customSttConfigured()) {
    toast.error("Custom transcription isn't configured.", {
      description: "Pick a connection and model in Voice settings.",
    });
    return;
  }
  if (usesRecordedAudio(dictationEngine)) {
    toast.error("Voice recording isn't available in this browser.");
    return;
  }
  // Firefox lacks Web Speech, so offer local dictation.
  void offerLocalDictation();
}

/** offers local dictation when Web Speech is missing, prompting before a needed download. */
async function offerLocalDictation(): Promise<void> {
  const { sttModel, sttGgufVariant, setDictationEngine } =
    useVoiceSettingsStore.getState();
  const ggufVariant = sttModelVariant(sttModel, sttGgufVariant);
  try {
    const status = await fetchSttStatus(undefined, sttModel);
    const engine = sttEngineStatusFor(status, sttModel);
    // avoid offering a large download when the runtime cannot load it.
    if (engine && !engine.available) {
      toast.error("Local transcription isn't installed on this server.", {
        description:
          "Run `unsloth studio update` to install it, then choose a model in Voice settings.",
      });
      return;
    }
    if (
      engine?.downloaded_models.includes(sttModel) &&
      (await sttQuantDownloaded(sttModel, ggufVariant))
    ) {
      setDictationEngine("model");
      toast.success("Switched to local transcription.", {
        description:
          "Voice typing isn't available in this browser. Press the mic again to dictate.",
      });
      return;
    }
  } catch {
    // the download path reports status or quant lookup failures.
  }
  requestSttDownload(sttModel, { selectLocalEngine: true, ggufVariant });
}