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.

10.7 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 type { useNavigate } from "@tanstack/react-router";
import { zipSync } from "fflate";
import { usePlatformStore } from "@/config/env";
import {
  isTtsAudioType,
  trainedTtsCheckpointIsLoadable,
  trainedTtsCheckpointIsRunnableOnMac,
} from "@/features/audio/audio-page-policy";
import { audioWorkflowForAudioType } from "@/features/audio/workflows";
import { getAuthSessionEpoch } from "@/features/auth";
import { listLoras } from "@/features/chat";
import {
  clearModelConfigHandoff,
  createModelConfigHandoffRequestId,
  requestModelConfigHandoff,
} from "@/features/model-picker";
import { translate } from "@/i18n";
import { useImageEditHandoffStore } from "@/stores/image-edit-handoff";
import { MAX_AUDIO_SIZE } from "@/lib/audio-utils";
import { isTauri } from "@/lib/api-base";
import { MAX_UPLOAD_IMAGE_SIDE, blobToDataUrl, fitImageDataUrl } from "@/lib/image-fit";
import { downloadFile, downloadUrlStreaming, downloadUrlInDirectory, pickNativeDownloadDirectory, releaseNativeDownloadDirectory, isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import { MAX_VIDEO_SIZE } from "@/lib/video-utils";
import {
  LibraryFileTooLarge,
  type LibraryItem,
  errorMessage,
  libraryDownloadUrl,
  libraryItemFile,
} from "./api";
import { fileKind } from "./file-kind";
import { hasOwnFile, libraryFileName, uniqueFileNames } from "./file-name";
import { MAX_IMAGE_OR_TEXT_BYTES, resetToNewChat, startLibraryChat } from "./start-chat";

type Navigate = ReturnType<typeof useNavigate>;

export const MAX_CHAT_FILES = 10;

const MAX_DOCUMENT_BYTES = 50 * 1024 * 1024;

function chatSizeLimit(item: LibraryItem): number {
  const kind = fileKind(item);
  if (kind === "audio") return MAX_AUDIO_SIZE;
  if (kind === "video") return MAX_VIDEO_SIZE;
  if (kind === "image" || kind === "code" || kind === "web" || item.textOnly) {
    return MAX_IMAGE_OR_TEXT_BYTES;
  }
  return item.contentType.startsWith("text/") ? MAX_IMAGE_OR_TEXT_BYTES : MAX_DOCUMENT_BYTES;
}

function fitsInChat(item: LibraryItem): boolean {
  return item.sizeBytes === null || item.sizeBytes <= chatSizeLimit(item);
}

export async function downloadLibraryItem(
  item: LibraryItem,
  epoch = getAuthSessionEpoch(),
  directory?: { token: string; fileName: string },
): Promise<boolean> {
  if (getAuthSessionEpoch() !== epoch) return false;
  try {
    if (isTauri && !item.textOnly && hasOwnFile(item.id)) {
      const url = await libraryDownloadUrl(item);
      if (getAuthSessionEpoch() !== epoch) return false;
      if (directory) await downloadUrlInDirectory(directory.token, url, directory.fileName);
      else await downloadUrlStreaming(url, libraryFileName(item));
      return true;
    }
    const file = await libraryItemFile(item);
    if (getAuthSessionEpoch() !== epoch) return false;
    await downloadFile(file, file.name, file.type);
    return true;
  } catch (error) {
    if (isDownloadCancelled(error)) return false;
    toast.error(translate("library.toast.downloadFailed", { name: item.name }), {
      description: errorMessage(error),
    });
    return true;
  }
}

const MAX_ZIP_BYTES = 256 * 1024 * 1024;

export async function downloadLibraryItems(items: LibraryItem[]): Promise<void> {
  const epoch = getAuthSessionEpoch();
  if (isTauri && items.length > 1 && items.every((item) => !item.textOnly && hasOwnFile(item.id))) {
    try {
      const token = await pickNativeDownloadDirectory();
      try {
        const width = String(items.length).length;
        for (const [index, item] of items.entries()) {
          const fileName = `${String(index + 1).padStart(width, "0")}-${libraryFileName(item)}`;
          if (!(await downloadLibraryItem(item, epoch, { token, fileName }))) break;
        }
      } finally {
        await releaseNativeDownloadDirectory(token);
      }
    } catch (error) {
      if (isDownloadCancelled(error)) return;
      toast.error(translate("library.toast.downloadManyFailed"), { description: errorMessage(error) });
    }
    return;
  }
  if (items.length <= 1 || isTauri) {
    for (const item of items) {
      if (!(await downloadLibraryItem(item, epoch))) break;
    }
    return;
  }
  // Unknown size counts as Infinity so it never goes into an in-memory zip.
  const bytes = items.reduce((sum, item) => sum + (item.sizeBytes ?? Infinity), 0);
  if (bytes > MAX_ZIP_BYTES) {
    toast(translate("library.toast.downloadingMany", { count: items.length }), {
      description: translate("library.toast.downloadingManyDescription"),
    });
    for (const item of items) {
      if (!(await downloadLibraryItem(item, epoch))) break;
    }
    return;
  }
  const progress = toast.loading(translate("library.toast.preparingMany", { count: items.length }));
  try {
    const files: File[] = [];
    let budget = MAX_ZIP_BYTES;
    for (const item of items) {
      let file: File;
      try {
        file = await libraryItemFile(item, budget);
      } catch (error) {
        if (!(error instanceof LibraryFileTooLarge)) throw error;
        toast.dismiss(progress);
        for (const each of items) {
          if (!(await downloadLibraryItem(each, epoch))) break;
        }
        return;
      }
      budget -= file.size;
      files.push(file);
      if (getAuthSessionEpoch() !== epoch) return;
    }
    const names = uniqueFileNames(["__proto__", ...files.map((file) => file.name)]).slice(1);
    const entries: Record<string, Uint8Array> = {};
    for (const [index, file] of files.entries()) {
      entries[names[index]!] = new Uint8Array(await file.arrayBuffer());
    }
    const archive = zipSync(entries, { level: 0 });
    if (getAuthSessionEpoch() !== epoch) return;
    await downloadFile(
      new Blob([archive], { type: "application/zip" }),
      `${translate("library.toast.zipFileName")}.zip`,
    );
  } catch (error) {
    toast.error(translate("library.toast.downloadManyFailed"), { description: errorMessage(error) });
  } finally {
    toast.dismiss(progress);
  }
}

export async function chatAboutItems(
  navigate: Navigate,
  items: LibraryItem[],
): Promise<void> {
  if (items.length === 0) {
    toast(translate("library.toast.nothingToChat"), {
      description: translate("library.toast.emptyFolder"),
    });
    return;
  }
  const fitting = items.filter(fitsInChat);
  let tooLarge = items.length - fitting.length;
  if (fitting.length === 0) {
    toast.error(
      items.length === 1
        ? translate("library.toast.tooLargeOne", { name: items[0].name })
        : translate("library.toast.tooLargeMany"),
    );
    return;
  }
  const chosen = fitting.slice(0, MAX_CHAT_FILES);
  const epoch = getAuthSessionEpoch();
  try {
    const files: File[] = [];
    // Size is bounded while reading: unknown or grown files are only caught here.
    for (const item of chosen) {
      try {
        files.push(await libraryItemFile(item, chatSizeLimit(item)));
      } catch (error) {
        if (!(error instanceof LibraryFileTooLarge)) throw error;
        tooLarge += 1;
      }
      if (getAuthSessionEpoch() !== epoch) return;
    }
    if (files.length === 0) {
      toast.error(
        chosen.length === 1
          ? translate("library.toast.tooLargeOne", { name: chosen[0].name })
          : translate("library.toast.tooLargeMany"),
      );
      return;
    }
    const leftOut = fitting.length - chosen.length;
    if (tooLarge > 0 || leftOut > 0) {
      const attached =
        files.length === 1 ? "library.toast.attachedOne" : "library.toast.attachedMany";
      toast(translate(attached, { count: files.length }), {
        description: [
          tooLarge > 0 && translate("library.toast.skippedTooLarge", { count: tooLarge }),
          leftOut > 0 &&
            translate("library.toast.skippedOverLimit", { count: leftOut, limit: MAX_CHAT_FILES }),
        ]
          .filter(Boolean)
          .join(" "),
      });
    }
    startLibraryChat(navigate, { files });
  } catch (error) {
    toast.error(translate("library.toast.openFilesFailed"), { description: errorMessage(error) });
  }
}

// Read whole before it is fitted to the 4096 px upload limit, so a large original still opens.
const MAX_EDIT_SOURCE_BYTES = 64 * 1024 * 1024;

let editRequest = 0;

export async function editLibraryImage(navigate: Navigate, item: LibraryItem): Promise<void> {
  const epoch = getAuthSessionEpoch();
  const claimed = ++editRequest;
  try {
    const file = await libraryItemFile(item, MAX_EDIT_SOURCE_BYTES);
    const dataUrl = await fitImageDataUrl(await blobToDataUrl(file), MAX_UPLOAD_IMAGE_SIDE);
    if (getAuthSessionEpoch() !== epoch || claimed !== editRequest) return;
    useImageEditHandoffStore.getState().offer(dataUrl);
    void navigate({ to: "/images" });
  } catch (error) {
    if (claimed !== editRequest) return;
    toast.error(translate("library.toast.editImageFailed"), { description: errorMessage(error) });
  }
}

export async function chatWithModel(
  navigate: Navigate,
  item: LibraryItem,
): Promise<void> {
  const model = item.model;
  if (!model) return;
  const epoch = getAuthSessionEpoch();
  const scanned = await listLoras()
    .then(({ loras }) => loras.find((lora) => lora.adapter_path === model.path))
    .catch(() => undefined);
  if (getAuthSessionEpoch() !== epoch) return;
  if (scanned?.audio_type) {
    const { audio_type: audioType, export_type: exportType } = scanned;
    if (
      isTtsAudioType(audioType, exportType === "gguf") &&
      trainedTtsCheckpointIsLoadable(audioType, exportType) &&
      // The Audio page's picker hides what the Mac runtime cannot run; never load it from here.
      (usePlatformStore.getState().deviceType !== "mac" ||
        trainedTtsCheckpointIsRunnableOnMac(audioType, exportType))
    ) {
      void navigate({
        to: "/audio",
        search: {
          model: model.path,
          loadId: model.path,
          // Native checkpoints need it for their custom-code approval and runtime checks.
          audioType,
          workflow: audioWorkflowForAudioType(audioType),
        },
      });
      return;
    }
    toast(translate("library.toast.speechModel", { name: item.name }), {
      description: translate("library.toast.speechModelDescription"),
    });
    void navigate({ to: "/audio" });
    return;
  }
  const requestId = createModelConfigHandoffRequestId();
  resetToNewChat();
  requestModelConfigHandoff({
    requestId,
    id: model.path,
    displayName: item.name,
    meta: {
      source: model.origin === "exported" ? "exported" : "lora",
      isLora: model.exportType === "lora",
      isDownloaded: true,
      isGguf: model.exportType === "gguf",
    },
  });
  void navigate({ to: "/chat", search: { new: requestId } }).catch(() =>
    clearModelConfigHandoff(requestId),
  );
}