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.

7.1 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 { decodeDataUri, isDataUri } from "@/lib/data-uri";

export const NATIVE_FILE_NAME_HEADER = "x-unsloth-default-name";
const NATIVE_FILE_SAVE_TOKEN_HEADER = "x-unsloth-save-token";
const NATIVE_FILE_CHUNK_BYTES = 8 * 1024 * 1024;
export class DownloadCancelledError extends Error {
  constructor() {
    super("Save cancelled.");
    this.name = "DownloadCancelledError";
  }
}

export function isDownloadCancelled(error: unknown): boolean {
  return error instanceof DownloadCancelledError;
}

export function encodeNativeFilename(filename: string): string {
  const bytes = new TextEncoder().encode(filename);
  let binary = "";
  for (const byte of bytes) {
    binary += String.fromCharCode(byte);
  }
  return btoa(binary);
}

export interface NativeImportedTextFile {
  name: string;
  content: string;
}

export interface NativeChatImport {
  name: string;
  size: number;
  token: string;
}

export async function readNativeChatImportChunk(
  token: string,
  offset: number,
  length: number,
): Promise<Uint8Array> {
  const { invoke } = await import("@tauri-apps/api/core");
  const bytes = await invoke<ArrayBuffer | number[]>(
    "read_native_chat_import_chunk",
    { token, offset, length },
  );
  return bytes instanceof ArrayBuffer
    ? new Uint8Array(bytes)
    : new Uint8Array(bytes);
}

export function browserDownload(blob: Blob, filename: string): void {
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = filename;
  document.body.appendChild(anchor);
  anchor.click();
  anchor.remove();
  window.setTimeout(() => URL.revokeObjectURL(url), 0);
}

function browserUrlDownload(url: string, filename: string): void {
  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = filename;
  anchor.rel = "noopener";
  document.body.appendChild(anchor);
  anchor.click();
  anchor.remove();
}

async function fetchDownload(url: string): Promise<Response> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Download failed with status ${response.status}.`);
  }
  return response;
}

/** Returns the chosen basename after a native save; browsers do not report the final name. */
export async function downloadFile(
  content: string | Blob | Uint8Array,
  filename: string,
  mimeType = "application/octet-stream",
): Promise<string | undefined> {
  if (isTauri) {
    const { invoke } = await import("@tauri-apps/api/core");
    const bytes =
      typeof content === "string"
        ? new TextEncoder().encode(content)
        : content instanceof Blob
          ? new Uint8Array(await content.arrayBuffer())
          : content;
    const savedFileName = await invoke<string | null>("save_native_file", bytes, {
      headers: {
        [NATIVE_FILE_NAME_HEADER]: encodeNativeFilename(filename),
      },
    });
    if (savedFileName === null) {
      throw new DownloadCancelledError();
    }
    return savedFileName;
  }

  const browserContent =
    content instanceof Uint8Array ? Uint8Array.from(content).buffer : content;
  const blob =
    browserContent instanceof Blob
      ? browserContent
      : new Blob([browserContent], { type: mimeType });

  browserDownload(blob, filename);
  return;
}

/** Save a Blob through bounded IPC chunks in Tauri and retain normal downloads on web. */
export async function downloadBlobStreaming(
  content: Blob,
  filename: string,
): Promise<string | undefined> {
  if (!isTauri) {
    browserDownload(content, filename);
    return;
  }
  const { invoke } = await import("@tauri-apps/api/core");
  const token = await invoke<string | null>("begin_native_file_save", {
    fileName: filename,
  });
  if (token === null) {
    throw new DownloadCancelledError();
  }
  try {
    for (
      let offset = 0;
      offset < content.size;
      offset += NATIVE_FILE_CHUNK_BYTES
    ) {
      const bytes = new Uint8Array(
        await content
          .slice(offset, offset + NATIVE_FILE_CHUNK_BYTES)
          .arrayBuffer(),
      );
      await invoke<void>("append_native_file_save_chunk", bytes, {
        headers: { [NATIVE_FILE_SAVE_TOKEN_HEADER]: token },
      });
    }
    return await invoke<string>("finish_native_file_save", { token });
  } catch (error) {
    await invoke<void>("cancel_native_file_save", { token }).catch(
      () => undefined,
    );
    throw error;
  }
}

export async function pickNativeDownloadDirectory(): Promise<string> {
  const { invoke } = await import("@tauri-apps/api/core");
  const token = await invoke<string | null>("pick_native_download_directory");
  if (token === null) throw new DownloadCancelledError();
  return token;
}

export async function downloadUrlInDirectory(token: string, url: string, fileName: string): Promise<void> {
  const { invoke } = await import("@tauri-apps/api/core");
  await invoke<string>("save_native_file_in_directory", { token, url, fileName });
}

export async function releaseNativeDownloadDirectory(token: string): Promise<void> {
  const { invoke } = await import("@tauri-apps/api/core");
  await invoke<void>("release_native_download_directory", { token });
}

export async function urlToBlob(url: string): Promise<Blob> {
  if (isDataUri(url)) {
    const { bytes, mimeType } = decodeDataUri(url);
    return new Blob([Uint8Array.from(bytes).buffer], { type: mimeType });
  }
  return (await fetchDownload(url)).blob();
}

/** Opens the chooser first and Rust streams to the path, avoiding buffering across IPC. */
export async function downloadUrlStreaming(
  url: string,
  filename: string,
): Promise<string | undefined> {
  if (!isTauri) {
    browserUrlDownload(url, filename);
    return;
  }
  const { invoke } = await import("@tauri-apps/api/core");
  const savedFileName = await invoke<string | null>("save_native_file_from_url", {
    url,
    fileName: filename,
  });
  if (savedFileName === null) {
    throw new DownloadCancelledError();
  }
  return savedFileName;
}

export async function downloadUrl(
  url: string,
  filename: string,
): Promise<string | undefined> {
  if (isDataUri(url)) {
    const { bytes, mimeType } = decodeDataUri(url);
    return downloadFile(bytes, filename, mimeType);
  }
  if (!isTauri) {
    browserUrlDownload(url, filename);
    return;
  }
  const response = await fetchDownload(url);
  const bytes = new Uint8Array(await response.arrayBuffer());
  return downloadFile(
    bytes,
    filename,
    response.headers.get("content-type") || "application/octet-stream",
  );
}

export async function pickNativeChatImport(): Promise<NativeChatImport | null> {
  if (!isTauri) {
    return null;
  }
  const { invoke } = await import("@tauri-apps/api/core");
  return invoke<NativeChatImport | null>("pick_native_chat_import");
}

export async function pickNativeTrainingConfig(): Promise<NativeImportedTextFile | null> {
  if (!isTauri) {
    return null;
  }
  const { invoke } = await import("@tauri-apps/api/core");
  return invoke<NativeImportedTextFile | null>("pick_native_training_config");
}