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.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 {
  AUDIO_CPP_REPO,
  isAudioCppFolderId,
} from "../../audio/audio-cpp-catalog.ts";
import { looksLikeLocalPath } from "./local-path.ts";

const WINDOWS_DRIVE_PATH_RE = /^[A-Za-z]:/;
const WINDOWS_RELATIVE_PATH_RE = /^\.{1,2}\\/;
const WINDOWS_ROOTED_PATH_RE = /^\\/;
const WSL_DRIVE_PATH_RE = /^\/mnt\/[A-Za-z](?:\/|$)/;
const TILDE_PATH_RE = /^~[^\\/]*(?:[\\/]|$)/;

function trimTrailingSeparators(path: string, minLength: number): string {
  let end = path.length;
  while (end > minLength && path.charCodeAt(end - 1) === 47) {
    end -= 1;
  }
  return end === path.length ? path : path.slice(0, end);
}

function normalizeCaseInsensitivePath(path: string, minLength: number): string {
  return trimTrailingSeparators(
    path.replace(/\\/g, "/"),
    minLength,
  ).toLowerCase();
}

export function normalizeModelIdentity(modelId: string): string {
  const trimmed = modelId.trim();
  if (!looksLikeLocalPath(trimmed)) {
    return trimmed.toLowerCase();
  }
  const slashPath = trimmed.replace(/\\/g, "/");
  if (WINDOWS_DRIVE_PATH_RE.test(trimmed)) {
    return normalizeCaseInsensitivePath(trimmed, 3);
  }
  if (slashPath.startsWith("//")) {
    return normalizeCaseInsensitivePath(trimmed, 2);
  }
  if (WINDOWS_ROOTED_PATH_RE.test(trimmed)) {
    return normalizeCaseInsensitivePath(trimmed, 1);
  }
  if (WSL_DRIVE_PATH_RE.test(slashPath)) {
    return normalizeCaseInsensitivePath(trimmed, 6);
  }
  if (WINDOWS_RELATIVE_PATH_RE.test(trimmed)) {
    return trimTrailingSeparators(slashPath, 1);
  }
  if (TILDE_PATH_RE.test(trimmed)) {
    return trimTrailingSeparators(slashPath, 1);
  }
  return trimTrailingSeparators(trimmed, 1);
}

export function normalizeGgufVariantIdentity(
  ggufVariant?: string | null,
): string {
  return ggufVariant?.trim().toLowerCase() ?? "";
}

export function modelIdsMatch(
  left: string | null | undefined,
  right: string | null | undefined,
): boolean {
  if (!(left && right)) {
    return false;
  }
  return normalizeModelIdentity(left) === normalizeModelIdentity(right);
}

export function ggufVariantsMatch(
  left: string | null | undefined,
  right: string | null | undefined,
): boolean {
  return (
    normalizeGgufVariantIdentity(left) === normalizeGgufVariantIdentity(right)
  );
}

// Mirrors core/inference/model_ids.py _looks_like_path.
const PUBLIC_ID_PATH_PREFIX_RE = /^(?:[/\\]|\.{1,2}[\\/]|~)/;
const GGUF_SUFFIX_RE = /\.gguf$/i;
const BACKSLASHES_RE = /\\/g;
const TRAILING_SLASHES_RE = /\/+$/;

function looksLikeModelPath(identifier: string): boolean {
  if (GGUF_SUFFIX_RE.test(identifier)) {
    return true;
  }
  // An audio.cpp umbrella id names a folder of one Hub repo; mirrors model_ids._looks_like_path.
  if (isAudioCppFolderId(identifier)) {
    const parts = identifier
      .trim()
      .slice(AUDIO_CPP_REPO.length + 1)
      .replace(BACKSLASHES_RE, "/")
      .split("/")
      .filter(Boolean);
    if (parts.length > 0 && !parts.some((part) => part === "." || part === "..")) {
      return false;
    }
  }
  if (PUBLIC_ID_PATH_PREFIX_RE.test(identifier)) {
    return true;
  }
  if (identifier.length >= 2 && identifier[1] === ":") {
    return true;
  }
  return identifier.split("/").length - 1 >= 2 || identifier.includes("\\");
}

function hfCacheRepoId(path: string): string | null {
  const parts = path.replace(BACKSLASHES_RE, "/").split("/");
  for (let index = 0; index < parts.length; index += 1) {
    const part = parts[index];
    if (part.startsWith("models--") && parts[index + 1] === "snapshots") {
      return part.slice("models--".length).replaceAll("--", "/");
    }
  }
  return null;
}

/** Mirrors `hf_cache_repo_id` in core/inference/model_ids.py. */
export function isHfCacheSnapshotPath(
  identifier: string | null | undefined,
): boolean {
  return identifier != null && hfCacheRepoId(identifier) !== null;
}

/** Mirrors `public_model_id` in core/inference/model_ids.py (what /status reports). */
export function publicModelId(identifier: string): string {
  const trimmed = identifier.trim();
  if (!(trimmed && looksLikeModelPath(trimmed))) {
    return trimmed;
  }
  const repoId = hfCacheRepoId(trimmed);
  if (repoId) {
    return repoId;
  }
  const slashPath = trimmed
    .replace(BACKSLASHES_RE, "/")
    .replace(TRAILING_SLASHES_RE, "");
  const name = slashPath.slice(slashPath.lastIndexOf("/") + 1);
  return name.replace(GGUF_SUFFIX_RE, "") || trimmed;
}

/** A file reference carries a repo id plus a filename, so two or more slashes. */
function isHubRepoId(identifier: string): boolean {
  if (identifier.split("/").length - 1 !== 1) {
    return false;
  }
  return !looksLikeModelPath(identifier.replace(GGUF_SUFFIX_RE, ""));
}

/** Mirrors `display_model_name` in core/inference/model_ids.py; raw splits leak Windows paths. */
export function modelDisplayName(identifier: string): string {
  const trimmed = identifier.trim();
  if (isHubRepoId(trimmed)) {
    return trimmed.slice(trimmed.indexOf("/") + 1);
  }
  const clean = publicModelId(trimmed);
  return clean.slice(clean.lastIndexOf("/") + 1) || clean;
}

/** Compares literally, then by public id, but only when that id names a single model. */
export function residentModelIdMatches(
  activeModelId: string | null | undefined,
  ...candidates: (string | null | undefined)[]
): boolean {
  if (candidates.some((candidate) => modelIdsMatch(activeModelId, candidate))) {
    return true;
  }
  const active = activeModelId?.trim();
  if (!active || looksLikeModelPath(active)) {
    return false;
  }
  return candidates.some((candidate) => {
    const trimmed = candidate?.trim();
    if (!trimmed) {
      return false;
    }
    const publicId = publicModelId(trimmed);
    // Unambiguous only when the collapse produced a namespaced repo id.
    return publicId.includes("/") && modelIdsMatch(active, publicId);
  });
}

const OLLAMA_LINK_SEGMENTS = new Set([".studio_links", "ollama_links"]);
const OLLAMA_MANIFEST_REF_PREFIX = "ollama-manifest:";

/** The resolver refuses to index a materialized link, so settings must not mirror onto it. */
export function isOllamaLinkPath(modelId: string | null | undefined): boolean {
  if (!modelId) {
    return false;
  }
  return modelId
    .replace(BACKSLASHES_RE, "/")
    .split("/")
    .some((segment) => OLLAMA_LINK_SEGMENTS.has(segment));
}

export function isOllamaModelId(modelId: string | null | undefined): boolean {
  return (
    Boolean(modelId?.startsWith(OLLAMA_MANIFEST_REF_PREFIX)) ||
    isOllamaLinkPath(modelId)
  );
}

// Bare file names come from lease-backed loads whose host path /status withholds.
const NATIVE_FILE_LABEL_RE = /^[^/\\]+\.gguf$/i;

export function isNativeFileLabel(modelId: string | null | undefined): boolean {
  return modelId != null && NATIVE_FILE_LABEL_RE.test(modelId);
}

// A scanned standalone .gguf has no variant. Repo ids may end in .gguf too, so require a local path.
export function isStandaloneGgufPath(
  modelId: string | null | undefined,
): boolean {
  if (modelId == null || !GGUF_SUFFIX_RE.test(modelId)) {
    return false;
  }
  return (
    PUBLIC_ID_PATH_PREFIX_RE.test(modelId) ||
    (modelId.length >= 2 && modelId[1] === ":") ||
    modelId.includes("\\") ||
    modelId.split("/").length - 1 >= 2 ||
    isNativeFileLabel(modelId)
  );
}