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.

1.8 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 { useCallback, useEffect, useRef, useState } from "react";
import { subscribeResidentStatusRefresh } from "@/features/hub/lib/resident-status-refresh";
import { type ProfileStats, loadProfileStats } from "../api/profile-stats";

type ProfileStatsState = {
  stats: ProfileStats | null;
  loading: boolean;
  error: string | null;
  reload: () => void;
};

export function useProfileStats(): ProfileStatsState {
  const [stats, setStats] = useState<ProfileStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  // A refresh aborts the in-flight request so a slow first load cannot overwrite the newer one.
  const abortRef = useRef<AbortController | null>(null);

  const load = useCallback(async () => {
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    setLoading(true);
    try {
      const next = await loadProfileStats(controller.signal);
      if (controller.signal.aborted) return;
      setStats(next);
      setError(null);
    } catch (cause: unknown) {
      if (controller.signal.aborted) return;
      setError(cause instanceof Error ? cause.message : String(cause));
    } finally {
      if (!controller.signal.aborted) setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
    return () => abortRef.current?.abort();
  }, [load]);

  // Tokens move while backgrounded, so a watcher is needed; reopen needs none (not force-mounted).
  useEffect(() => subscribeResidentStatusRefresh(load), [load]);

  const reload = useCallback(() => {
    void load();
  }, [load]);

  return { stats, loading, error, reload };
}