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.

2.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 type { GgufVariantDetail, GgufVariantsResponse } from "@/features/chat";

/** Hub-only state the disk answer cannot know: a newer revision or a companion the Hub added. */
function withHubState<V extends GgufVariantDetail>(
  local: V,
  published: V | undefined,
): V {
  const drafter = local.pending_drafter_filename ? local : published;
  return {
    ...published,
    ...local,
    update_available: published?.update_available ?? local.update_available,
    pending_drafter_filename: drafter?.pending_drafter_filename,
    pending_drafter_size_bytes: drafter?.pending_drafter_size_bytes,
    ...(published
      ? {
          size_bytes: published.size_bytes,
          download_size_bytes: published.download_size_bytes,
        }
      : {}),
    // A newer revision's reading wins, even 0; else local, with the Hub filling an unread 0.
    lookup_table_bytes: published?.update_available
      ? (published.lookup_table_bytes ?? 0)
      : published
        ? local.lookup_table_bytes || published.lookup_table_bytes
        : local.lookup_table_bytes,
  };
}

export async function loadPickerGgufVariants<T extends GgufVariantsResponse>(
  list: (localOnly: boolean) => Promise<T>,
  options: {
    onDevice: boolean;
    canDiscoverRemote: () => boolean;
    signal?: AbortSignal;
  },
  onCached: (response: T) => void,
): Promise<T> {
  if (!options.onDevice) return list(false);

  let cached: T;
  try {
    cached = await list(true);
  } catch (error) {
    if (options.signal?.aborted || !options.canDiscoverRemote()) throw error;
    return list(false);
  }
  onCached(cached);
  // Remote discovery still runs with All quantizations off: update badges come only from the Hub.
  if (options.signal?.aborted || !options.canDiscoverRemote()) {
    return cached;
  }

  try {
    const remote = await list(false);
    const variants = new Map(
      remote.variants.map((v) => [v.quant.toLowerCase(), v]),
    );
    for (const local of cached.variants) {
      const key = local.quant.toLowerCase();
      variants.set(key, withHubState(local, variants.get(key)));
    }
    return {
      ...cached,
      variants: [...variants.values()],
      has_vision: cached.has_vision || remote.has_vision,
      default_variant: remote.default_variant ?? cached.default_variant,
    };
  } catch {
    // A remote error must not replace the usable disk answer.
    return cached;
  }
}