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.

Studio: tell a rejected Hugging Face token apart from an unreachable Hub (#12159)

Daniel Han32f806efcc02
diff --git a/studio/frontend/src/features/hf-auth/api.ts b/studio/frontend/src/features/hf-auth/api.ts
index 5f41bb73e35..ee7c34883c0 100644
--- a/studio/frontend/src/features/hf-auth/api.ts
+++ b/studio/frontend/src/features/hf-auth/api.ts
@@ -36,8 +36,11 @@ export async function validateHfToken(
status?: HfTokenValidationStatus;
retry_after_seconds?: number | null;
};
+ const status = body.status ?? "unavailable";
+ // A "valid" here may be the backend's cached verdict from before the token was revoked,
+ // so it never clears a refusal a real read saw; a read the token answers again does.
return {
- status: body.status ?? "unavailable",
+ status,
retryAfterSeconds: body.retry_after_seconds ?? null,
};
}
diff --git a/studio/frontend/src/features/hf-auth/hf-token-warning-dialog.tsx b/studio/frontend/src/features/hf-auth/hf-token-warning-dialog.tsx
index 4370c396934..7bf5fef2bb2 100644
--- a/studio/frontend/src/features/hf-auth/hf-token-warning-dialog.tsx
+++ b/studio/frontend/src/features/hf-auth/hf-token-warning-dialog.tsx
@@ -14,8 +14,10 @@ import {
import { Button } from "@/components/ui/button";
import { AlertTriangle } from "lucide-react";
import { useHfTokenWarningStore } from "./store";
+import { useHfTokenRejectedToast } from "./use-hf-token-rejected-toast";
export function HfTokenWarningDialog() {
+ useHfTokenRejectedToast();
const open = useHfTokenWarningStore((state) => state.open);
const allowAnonymous = useHfTokenWarningStore(
(state) => state.allowAnonymous,
diff --git a/studio/frontend/src/features/hf-auth/use-hf-token-rejected-toast.ts b/studio/frontend/src/features/hf-auth/use-hf-token-rejected-toast.ts
new file mode 100644
index 00000000000..5d68e9a7989
--- /dev/null
+++ b/studio/frontend/src/features/hf-auth/use-hf-token-rejected-toast.ts
@@ -0,0 +1,25 @@
+// 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 { useT } from "@/i18n";
+import { subscribeHfTokenRejected } from "@/lib/hf-token-rejection";
+import { toast } from "@/lib/toast";
+import { useEffect } from "react";
+
+/** One toast when the Hub first refuses the saved token and a read recovers without it. The
+ * store notifies once per token, so a page of refused requests is one message, not many. */
+export function useHfTokenRejectedToast(): void {
+ const t = useT();
+ useEffect(
+ () =>
+ subscribeHfTokenRejected((event) => {
+ // A cleared refusal is good news, even while another Hub still refuses the token.
+ if (event !== "rejected") return;
+ toast.error(t("studio.modelPicker.tokenRejectedTitle"), {
+ id: "hf-token-rejected",
+ description: t("studio.modelPicker.tokenRejectedAnonymousBody"),
+ });
+ }),
+ [t],
+ );
+}
diff --git a/studio/frontend/src/features/hub/catalog/catalog-states.tsx b/studio/frontend/src/features/hub/catalog/catalog-states.tsx
index a4ff1af1c6d..aadff5e8456 100644
--- a/studio/frontend/src/features/hub/catalog/catalog-states.tsx
+++ b/studio/frontend/src/features/hub/catalog/catalog-states.tsx
@@ -15,9 +15,13 @@ import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";
import { useLayoutEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { useHubAvailability } from "../hooks/use-online-status";
-import { clearRemoteBackoff, type HubFailure } from "../lib/network";
+import {
+ clearRemoteBackoff,
+ hubAuthFailure,
+ type HubFailure,
+} from "../lib/network";
import { useIsAccountOwner } from "@/features/auth";
-import { updateHubSource } from "@/features/settings";
+import { updateHubSource, useSettingsDialogStore } from "@/features/settings";
import { useT } from "@/i18n";
import { useHubName, useHubSource } from "@/lib/hf-endpoint";
@@ -28,7 +32,12 @@ function describeFailure(
online: boolean,
resourceLabel: "models" | "datasets",
hub: string,
-): { title: string; body: string; offlineLike: boolean } {
+): {
+ title: string;
+ body: string;
+ offlineLike: boolean;
+ tokenRejected?: boolean;
+} {
switch (failure?.kind) {
case "browser-offline":
return {
@@ -49,6 +58,14 @@ function describeFailure(
body: failure.message,
offlineLike: false,
};
+ // Reached and refused: the fix is the token, not the connection or the hub.
+ case "auth-rejected":
+ return {
+ title: `${hub} rejected your token`,
+ body: failure.message,
+ offlineLike: false,
+ tokenRejected: true,
+ };
default:
break;
}
@@ -98,6 +115,20 @@ function UseModelScopeButton() {
);
}
+function UpdateTokenButton() {
+ const t = useT();
+ const openSettings = useSettingsDialogStore((s) => s.openDialog);
+ return (
+ <Button
+ size="sm"
+ onClick={() => openSettings("general")}
+ className="h-8 rounded-full"
+ >
+ {t("picker.updateToken")}
+ </Button>
+ );
+}
+
export function NetworkErrorState({
online,
message,
@@ -113,8 +144,11 @@ export function NetworkErrorState({
onSwitchDevice?: () => void;
resourceLabel?: "models" | "datasets";
}) {
- const { title, body, offlineLike } = describeFailure(
- failure,
+ // An SDK error the network layer never saw (the Hub answered 401) carries only
+ // its text, so the refusal is recovered from it rather than called unreachable.
+ const shown = failure ?? hubAuthFailure({ message });
+ const { title, body, offlineLike, tokenRejected } = describeFailure(
+ shown,
online,
resourceLabel,
useHubName(),
@@ -133,11 +167,14 @@ export function NetworkErrorState({
<p className="max-w-md text-ui-12p5 leading-5 text-muted-foreground">
{body}
</p>
- <p className="text-ui-11 text-muted-foreground/70">{message}</p>
+ {tokenRejected ? null : (
+ <p className="text-ui-11 text-muted-foreground/70">{message}</p>
+ )}
</div>
<div className="flex flex-wrap items-center justify-center gap-2">
+ {tokenRejected ? <UpdateTokenButton /> : null}
{/* A reachable hub answering an HTTP error is no reason to switch hubs. */}
- {failure && !offlineLike ? <UseModelScopeButton /> : null}
+ {shown && !offlineLike && !tokenRejected ? <UseModelScopeButton /> : null}
{onSwitchDevice ? (
<button
type="button"
@@ -171,8 +208,9 @@ export function HubFailureHint({
message: string | null;
onRetry: () => void;
}) {
- const { phase, failure } = useHubAvailability();
- const { title, body, offlineLike } = describeFailure(
+ const { phase, failure: availabilityFailure } = useHubAvailability();
+ const failure = availabilityFailure ?? hubAuthFailure({ message });
+ const { title, body, offlineLike, tokenRejected } = describeFailure(
failure,
phase === "available",
"models",
@@ -189,7 +227,8 @@ export function HubFailureHint({
)}
</div>
<div className="flex flex-wrap items-center gap-2">
- {failure && !offlineLike ? <UseModelScopeButton /> : null}
+ {tokenRejected ? <UpdateTokenButton /> : null}
+ {failure && !offlineLike && !tokenRejected ? <UseModelScopeButton /> : null}
<Button
variant="ghost"
size="sm"
diff --git a/studio/frontend/src/features/hub/hooks/use-discover-search.ts b/studio/frontend/src/features/hub/hooks/use-discover-search.ts
index 8c5762cb796..900d1a0bd03 100644
--- a/studio/frontend/src/features/hub/hooks/use-discover-search.ts
+++ b/studio/frontend/src/features/hub/hooks/use-discover-search.ts
@@ -1,10 +1,14 @@
// 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 } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import { useHubName } from "@/lib/hf-endpoint";
import { toast } from "@/lib/toast";
-import { clearRemoteBackoff, type HubFailure } from "@/features/hub/lib/network";
+import {
+ clearRemoteBackoff,
+ hubAuthFailure,
+ type HubFailure,
+} from "../lib/network";
import { useHubAvailability } from "./use-online-status";
import {
type HfModelResult,
@@ -161,7 +165,15 @@ export function useDiscoverSearch({
: modelSearch.needsRestart;
// Surfaced regardless of availability: the failure IS the thing worth showing.
const searchError = isDiscoverTab ? rawSearchError : null;
- const searchFailure = isDiscoverTab ? failure : null;
+ // A 401 is not a network failure, so the panel would otherwise say "Couldn't reach".
+ // Memoised: the toast effect below depends on it.
+ const searchFailure = useMemo(
+ () =>
+ isDiscoverTab
+ ? (failure ?? hubAuthFailure({ message: rawSearchError }))
+ : null,
+ [isDiscoverTab, failure, rawSearchError],
+ );
const fetchMore = useCallback(() => {
if (!canProbe || !hasMore) return false;
// A page that failed took the iterator with it, so resuming would resolve
diff --git a/studio/frontend/src/features/hub/lib/network.ts b/studio/frontend/src/features/hub/lib/network.ts
index 42fd507529e..22890baa800 100644
--- a/studio/frontend/src/features/hub/lib/network.ts
+++ b/studio/frontend/src/features/hub/lib/network.ts
@@ -28,12 +28,15 @@ type RemoteNetworkScope = string | readonly string[];
* Why a Hub request failed. Browsers collapse CORS, DNS, TLS interception and
* real outages into one opaque TypeError, so "network-opaque" says what we can
* prove, not what happened. Only CSP can be named, via its violation event.
+ * "auth-rejected" is the Hub answering, and refusing the credential: it never
+ * backs the origin off, since the Hub is reachable and a retry can succeed.
*/
export type HubFailureKind =
| "aborted"
| "timeout"
| "browser-offline"
| "network-opaque"
+ | "auth-rejected"
| "unknown";
export interface HubFailure {
@@ -325,6 +328,38 @@ export function classifyFetchFailure(
};
}
+// What the Hub says when it refuses the credential itself: an expired or revoked
+// OAuth token ("OAuth token verification failed"), a bad key ("Invalid credentials
+// in Authorization header"), or a bare 401. A 403 is left out on purpose: it is
+// the answer for a gated or private repo the token is valid for, not a rejection.
+const HUB_TOKEN_REJECTED_RE =
+ /invalid credentials|invalid (?:user )?(?:access )?token|oauth token verification failed|token (?:has )?(?:expired|been revoked)/i;
+
+/**
+ * The failure for a Hub that answered and refused the saved token. Built from
+ * the HTTP status when the caller has it, else from the SDK's error text, which
+ * is all a paginated listing keeps. Null for anything else, including 403, 404,
+ * 429 and 5xx, so those keep their own wording.
+ */
+export function hubAuthFailure(
+ error: { status?: number | null; message?: string | null },
+ origin: string | null = defaultHubOrigin(),
+): HubFailure | null {
+ const rejected =
+ error.status === 401 ||
+ (error.status == null && HUB_TOKEN_REJECTED_RE.test(error.message ?? ""));
+ if (!rejected) {
+ return null;
+ }
+ return {
+ kind: "auth-rejected",
+ message: `${hostLabel(origin)} refused the saved Hugging Face token. It may have expired or been revoked. Update or clear it in Settings, then try again.`,
+ origin,
+ status: 401,
+ retryable: true,
+ };
+}
+
/**
* Drop the trailer @huggingface/hub's createApiError appends to every message
* ("... URL: <full request url>. Request ID: ..."). The URL carries the user's
diff --git a/studio/frontend/src/hooks/use-hf-token-validation.ts b/studio/frontend/src/hooks/use-hf-token-validation.ts
index b37fc1f5ab5..ee23923481a 100644
--- a/studio/frontend/src/hooks/use-hf-token-validation.ts
+++ b/studio/frontend/src/hooks/use-hf-token-validation.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { validateHfToken } from "@/features/hf-auth";
+import { isCompleteHfTokenShape } from "@/lib/hf-token-shape";
import { useEffect, useRef, useState } from "react";
import { useDebouncedValue } from "./use-debounced-value";
@@ -26,10 +27,6 @@ const NO_COMPLETED_VALIDATION: CompletedValidation = {
token: "",
};
-// Current user access tokens contain 34 characters after the hf_ prefix. Action-time
-// validation still accepts legacy shapes without spending quota on every keystroke.
-const COMPLETE_HF_TOKEN = /^hf_[A-Za-z0-9]{34}$/;
-
/** Validates the HF token via the whoami-v2 API, debounced to avoid excessive requests
* while typing. isValid is null until checked. */
export function useHfTokenValidation(token: string): HfTokenValidationState {
@@ -39,7 +36,7 @@ export function useHfTokenValidation(token: string): HfTokenValidationState {
NO_COMPLETED_VALIDATION,
);
const versionRef = useRef(0);
- const shouldValidate = COMPLETE_HF_TOKEN.test(debouncedToken);
+ const shouldValidate = isCompleteHfTokenShape(debouncedToken);
useEffect(() => {
if (!shouldValidate) {
@@ -104,7 +101,7 @@ export function useHfTokenValidation(token: string): HfTokenValidationState {
isChecking: false,
};
}
- if (!COMPLETE_HF_TOKEN.test(normalizedToken)) return INITIAL;
+ if (!isCompleteHfTokenShape(normalizedToken)) return INITIAL;
if (completed.token !== normalizedToken) {
return { isValid: null, error: null, isChecking: true };
}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 6389006c0e1..6c9f75f04ab 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -95,6 +95,7 @@ export const ar = {
useModelScope: "استخدام ModelScope",
useModelScopeHint: "ابحث ونزّل من ModelScope بدلًا من ذلك. يمكنك العودة من الإعدادات.",
useModelScopeFailed: "تعذّر التبديل إلى ModelScope.",
+ updateToken: "تحديث الرمز",
hfToken: {
label: "توكن HF",
saved: "محفوظ",
@@ -2429,6 +2430,8 @@ export const ar = {
tokenRejectedTitle: "رُفض توكن Hugging Face",
tokenRejectedBody:
"حدّث التوكن في الإعدادات ← عام، ثم أعد المحاولة.",
+ tokenRejectedAnonymousBody:
+ "تُعرض النماذج العامة بدونه. حدّث التوكن في الإعدادات ← عام للوصول إلى النماذج الخاصة والمقيّدة.",
hubUnreachable: "تعذّر الوصول إلى Hugging Face",
cantUseModel: "لا يمكن استخدام النموذج للتدريب",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 141299594bf..c079adcc15b 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -96,6 +96,7 @@ export const de = {
useModelScope: "ModelScope verwenden",
useModelScopeHint: "Stattdessen über ModelScope suchen und herunterladen. Sie können in den Einstellungen zurückwechseln.",
useModelScopeFailed: "Wechsel zu ModelScope fehlgeschlagen.",
+ updateToken: "Token aktualisieren",
hfToken: {
label: "HF-Token",
saved: "Gespeichert",
@@ -2478,6 +2479,8 @@ export const de = {
tokenRejectedTitle: "Hugging Face-Token abgelehnt",
tokenRejectedBody:
"Aktualisieren Sie Ihr Token unter Einstellungen → Allgemein und versuchen Sie es erneut.",
+ tokenRejectedAnonymousBody:
+ "Öffentliche Modelle werden ohne das Token angezeigt. Aktualisieren Sie Ihr Token unter Einstellungen → Allgemein, um private und zugangsbeschränkte Modelle zu erreichen.",
hubUnreachable: "Hugging Face ist nicht erreichbar",
cantUseModel: "Modell kann nicht für das Training verwendet werden",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 7bcd0866a62..b3c2143dda5 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -96,6 +96,7 @@ export const en = {
useModelScope: "Use ModelScope",
useModelScopeHint: "Search and download from ModelScope instead. You can switch back in Settings.",
useModelScopeFailed: "Couldn't switch to ModelScope.",
+ updateToken: "Update token",
hfToken: {
label: "HF token",
saved: "Saved",
@@ -2417,6 +2418,8 @@ export const en = {
noModelsFound: "No models found.",
tokenRejectedTitle: "Hugging Face token rejected",
tokenRejectedBody: "Update your token in Settings → General, then retry.",
+ tokenRejectedAnonymousBody:
+ "Public models are shown without it. Update your token in Settings → General to reach private and gated models.",
hubUnreachable: "Couldn't reach Hugging Face",
cantUseModel: "Can't use model for training",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index d1ad0bf4475..8b34caf4db2 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -96,6 +96,7 @@ export const es = {
useModelScope: "Usar ModelScope",
useModelScopeHint: "Busca y descarga desde ModelScope en su lugar. Puedes volver a cambiarlo en Ajustes.",
useModelScopeFailed: "No se pudo cambiar a ModelScope.",
+ updateToken: "Actualizar token",
hfToken: {
label: "Token de HF",
saved: "Guardado",
@@ -2469,6 +2470,8 @@ export const es = {
tokenRejectedTitle: "Hugging Face rechazó el token",
tokenRejectedBody:
"Actualiza el token en Configuración → General y vuelve a intentarlo.",
+ tokenRejectedAnonymousBody:
+ "Los modelos públicos se muestran sin él. Actualiza el token en Configuración → General para acceder a modelos privados y restringidos.",
hubUnreachable: "No se pudo acceder a Hugging Face",
cantUseModel: "No se puede usar el modelo para entrenar",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 072bcd0f5be..221020062bb 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -96,6 +96,7 @@ export const fr = {
useModelScope: "Utiliser ModelScope",
useModelScopeHint: "Rechercher et télécharger depuis ModelScope à la place. Vous pouvez revenir en arrière dans les Paramètres.",
useModelScopeFailed: "Impossible de passer à ModelScope.",
+ updateToken: "Mettre à jour le jeton",
hfToken: {
label: "Token HF",
saved: "Enregistré",
@@ -2481,6 +2482,8 @@ export const fr = {
tokenRejectedTitle: "Token Hugging Face refusé",
tokenRejectedBody:
"Mettez à jour votre token dans Paramètres → Général, puis réessayez.",
+ tokenRejectedAnonymousBody:
+ "Les modèles publics s'affichent sans lui. Mettez à jour votre token dans Paramètres → Général pour accéder aux modèles privés et restreints.",
hubUnreachable: "Impossible de joindre Hugging Face",
cantUseModel: "Impossible d'utiliser le modèle pour l'entraînement",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 724c73ac171..291d24dfe6e 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -96,6 +96,7 @@ export const hi = {
useModelScope: "ModelScope इस्तेमाल करें",
useModelScopeHint: "इसके बजाय ModelScope से खोजें और डाउनलोड करें। आप सेटिंग्स में वापस बदल सकते हैं।",
useModelScopeFailed: "ModelScope पर स्विच नहीं हो सका।",
+ updateToken: "टोकन अपडेट करें",
hfToken: {
label: "HF टोकन",
saved: "सहेजा गया",
@@ -2436,6 +2437,8 @@ export const hi = {
tokenRejectedTitle: "Hugging Face टोकन अस्वीकार किया गया",
tokenRejectedBody:
"सेटिंग्स → सामान्य में अपना टोकन अपडेट करें, फिर पुनः प्रयास करें।",
+ tokenRejectedAnonymousBody:
+ "सार्वजनिक मॉडल इसके बिना दिखाए जा रहे हैं। निजी और प्रतिबंधित मॉडल तक पहुंचने के लिए सेटिंग्स → सामान्य में अपना टोकन अपडेट करें।",
hubUnreachable: "Hugging Face तक नहीं पहुंच सके",
cantUseModel: "मॉडल को ट्रेनिंग के लिए उपयोग नहीं कर सकते",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 3e952185bb7..6982f56c352 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -2332,6 +2332,7 @@ export const it = {
useModelScope: "Usa ModelScope",
useModelScopeHint: "Cerca e scarica da ModelScope. Puoi tornare indietro nelle Impostazioni.",
useModelScopeFailed: "Impossibile passare a ModelScope.",
+ updateToken: "Aggiorna token",
hfToken: {
label: "Token HF",
saved: "Salvato",
@@ -2478,6 +2479,8 @@ export const it = {
tokenRejectedTitle: "Token Hugging Face rifiutato",
tokenRejectedBody:
"Aggiorna il token in Impostazioni → Generali, quindi riprova.",
+ tokenRejectedAnonymousBody:
+ "I modelli pubblici vengono mostrati senza il token. Aggiorna il token in Impostazioni → Generali per accedere ai modelli privati e con accesso limitato.",
hubUnreachable: "Impossibile raggiungere Hugging Face",
cantUseModel: "Impossibile usare il modello per l'addestramento",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 6c79ac2efd3..aeb58f0b277 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -96,6 +96,7 @@ export const ja = {
useModelScope: "ModelScope を使う",
useModelScopeHint: "代わりに ModelScope で検索・ダウンロードします。設定からいつでも戻せます。",
useModelScopeFailed: "ModelScope に切り替えられませんでした。",
+ updateToken: "トークンを更新",
hfToken: {
label: "HF トークン",
saved: "保存済み",
@@ -2403,6 +2404,8 @@ export const ja = {
tokenRejectedTitle: "Hugging Face トークンが拒否されました",
tokenRejectedBody:
"「設定」→「一般」でトークンを更新してから、再試行してください。",
+ tokenRejectedAnonymousBody:
+ "公開モデルはトークンなしで表示しています。非公開モデルやアクセス制限付きモデルを使うには、「設定」→「一般」でトークンを更新してください。",
hubUnreachable: "Hugging Face に接続できませんでした",
cantUseModel: "このモデルはトレーニングに使用できません",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 9a50159ec41..ea87879e5d1 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -94,6 +94,7 @@ export const ko = {
useModelScope: "ModelScope 사용",
useModelScopeHint: "대신 ModelScope에서 검색하고 다운로드합니다. 설정에서 다시 바꿀 수 있습니다.",
useModelScopeFailed: "ModelScope로 전환하지 못했습니다.",
+ updateToken: "토큰 업데이트",
hfToken: {
label: "HF 토큰",
saved: "저장됨",
@@ -2429,6 +2430,8 @@ export const ko = {
tokenRejectedTitle: "Hugging Face 토큰이 거부되었습니다",
tokenRejectedBody:
"설정 → 일반에서 토큰을 업데이트한 후 다시 시도하세요.",
+ tokenRejectedAnonymousBody:
+ "공개 모델은 토큰 없이 표시됩니다. 비공개 및 접근 제한 모델을 사용하려면 설정 → 일반에서 토큰을 업데이트하세요.",
hubUnreachable: "Hugging Face에 연결하지 못했습니다",
cantUseModel: "이 모델은 학습에 사용할 수 없습니다",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 4c4225539c8..923985c06d9 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -96,6 +96,7 @@ export const ptBR = {
useModelScope: "Usar ModelScope",
useModelScopeHint: "Pesquise e baixe pelo ModelScope. Você pode voltar nas Configurações.",
useModelScopeFailed: "Não foi possível mudar para o ModelScope.",
+ updateToken: "Atualizar token",
hfToken: {
label: "Token do HF",
saved: "Salvo",
@@ -2450,6 +2451,8 @@ export const ptBR = {
tokenRejectedTitle: "Token do Hugging Face rejeitado",
tokenRejectedBody:
"Atualize seu token em Configurações → Geral e tente novamente.",
+ tokenRejectedAnonymousBody:
+ "Os modelos públicos são exibidos sem ele. Atualize seu token em Configurações → Geral para acessar modelos privados e restritos.",
hubUnreachable: "Não foi possível acessar o Hugging Face",
cantUseModel: "Não é possível usar o modelo para treinamento",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 3918c8fd0c1..a1fdf7728c6 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -96,6 +96,7 @@ export const ru = {
useModelScope: "Использовать ModelScope",
useModelScopeHint: "Искать и скачивать через ModelScope. Вернуть можно в настройках.",
useModelScopeFailed: "Не удалось переключиться на ModelScope.",
+ updateToken: "Обновить токен",
hfToken: {
label: "Токен HF",
saved: "Сохранён",
@@ -2455,6 +2456,8 @@ export const ru = {
tokenRejectedTitle: "Токен Hugging Face отклонён",
tokenRejectedBody:
"Обновите токен в разделе «Настройки» → «Общие», затем повторите попытку.",
+ tokenRejectedAnonymousBody:
+ "Публичные модели показаны без него. Обновите токен в разделе «Настройки» → «Общие», чтобы получить доступ к приватным и закрытым моделям.",
hubUnreachable: "Не удалось подключиться к Hugging Face",
cantUseModel: "Модель нельзя использовать для обучения",
reasonTypeMismatch:
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 225e6aee113..9eff0fce65d 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -93,6 +93,7 @@ export const zhCN = {
useModelScope: "使用 ModelScope",
useModelScopeHint: "改为从 ModelScope 搜索和下载。可随时在设置中切换回来。",
useModelScopeFailed: "无法切换到 ModelScope。",
+ updateToken: "更新令牌",
hfToken: {
label: "HF token",
saved: "已保存",
@@ -2374,6 +2375,8 @@ export const zhCN = {
noModelsFound: "未找到模型。",
tokenRejectedTitle: "Hugging Face token 被拒绝",
tokenRejectedBody: "请在“设置”→“常规”中更新 token,然后重试。",
+ tokenRejectedAnonymousBody:
+ "公开模型已在不使用 token 的情况下显示。请在“设置”→“常规”中更新 token,以访问私有和受限模型。",
hubUnreachable: "无法连接 Hugging Face",
cantUseModel: "无法使用此模型进行训练",
reasonTypeMismatch: "此模型与上一步选择的训练类型不匹配。",
diff --git a/studio/frontend/src/lib/hf-token-rejection.ts b/studio/frontend/src/lib/hf-token-rejection.ts
new file mode 100644
index 00000000000..d82b586a2c8
--- /dev/null
+++ b/studio/frontend/src/lib/hf-token-rejection.ts
@@ -0,0 +1,121 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Which saved Hugging Face token the Hub refused (a 401 that then succeeded anonymously).
+ * Keyed by a fingerprint, never the token; dependency free so hub-fetch runs under bare node. */
+
+/** "rejected" when a token is newly refused, "cleared" when a refusal is forgotten. */
+export type HfTokenRejectionEvent = "rejected" | "cleared";
+
+type Listener = (event: HfTokenRejectionEvent) => void;
+
+/** After this long the token is tried again, so a briefly failing verifier cannot hide private
+ * repos for the whole session. */
+export const HF_TOKEN_REJECTION_RECHECK_MS = 10 * 60 * 1000;
+
+// One refusal per Hub (scope): a mirror can refuse a token another endpoint accepts.
+const refusals = new Map<string | null, { fingerprint: string; at: number }>();
+let version = 0;
+const listeners = new Set<Listener>();
+// Accepted-token evidence: a refusal older than a newer success is ignored.
+let successes = 0;
+const lastSuccess = new Map<string | null, number>();
+let lastSuccessEverywhere = 0;
+
+/** FNV-1a over the token: enough to tell two tokens apart, useless for recovering one. */
+function fingerprint(token: string): string {
+ let hash = 0x811c9dc5;
+ for (let i = 0; i < token.length; i += 1) {
+ hash ^= token.charCodeAt(i);
+ hash = Math.imul(hash, 0x01000193) >>> 0;
+ }
+ return `${token.length}:${hash.toString(16)}`;
+}
+
+function normalized(token: string | null | undefined): string {
+ return token?.trim() ?? "";
+}
+
+function notify(event: HfTokenRejectionEvent): void {
+ version += 1;
+ for (const listener of listeners) {
+ try {
+ listener(event);
+ } catch {
+ // One broken subscriber must not stop the others hearing about it.
+ }
+ }
+}
+
+/** A mark to pass to ``noteHfTokenRejected`` from a request that is about to start. */
+export function hfTokenRejectionMark(): number {
+ return successes;
+}
+
+/** Record that the Hub at *scope* refused *token*. True only when this is news for that Hub.
+ * With *since* (a mark taken when the request started), a refusal that Hub has answered with
+ * an accepted token after that mark is stale and ignored. */
+export function noteHfTokenRejected(
+ token: string | null | undefined,
+ scope: string | null = null,
+ since?: number,
+): boolean {
+ const value = normalized(token);
+ if (!value) return false;
+ if (since !== undefined && Math.max(lastSuccessEverywhere, lastSuccess.get(scope) ?? 0) > since) {
+ return false;
+ }
+ const next = fingerprint(value);
+ const known = refusals.get(scope);
+ refusals.set(scope, { fingerprint: next, at: Date.now() });
+ if (known?.fingerprint === next) return false;
+ notify("rejected");
+ return true;
+}
+
+/** Whether the Hub at *scope* refused *token* recently enough to skip it. Without a scope:
+ * whether any Hub has refused it this session. A different token starts clean. */
+export function isHfTokenRejected(
+ token: string | null | undefined,
+ scope?: string | null,
+): boolean {
+ const value = normalized(token);
+ if (!value) return false;
+ const wanted = fingerprint(value);
+ if (scope === undefined) {
+ return [...refusals.values()].some((entry) => entry.fingerprint === wanted);
+ }
+ const entry = refusals.get(scope);
+ return (
+ entry?.fingerprint === wanted && Date.now() - entry.at < HF_TOKEN_REJECTION_RECHECK_MS
+ );
+}
+
+/** Whether any token is currently recorded as refused. */
+export function hasRejectedHfToken(): boolean {
+ return refusals.size > 0;
+}
+
+/** Forget the refusal by *scope* (every refusal without one) and record the success. */
+export function clearHfTokenRejected(scope?: string | null): void {
+ successes += 1;
+ if (scope === undefined) lastSuccessEverywhere = successes;
+ else lastSuccess.set(scope, successes);
+ const changed = scope === undefined ? refusals.size > 0 : refusals.has(scope);
+ if (!changed) return;
+ if (scope === undefined) refusals.clear();
+ else refusals.delete(scope);
+ notify("cleared");
+}
+
+/** For useSyncExternalStore: changes whenever the rejected token does. */
+export function hfTokenRejectionVersion(): number {
+ return version;
+}
+
+export function subscribeHfTokenRejected(listener: Listener): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
diff --git a/studio/frontend/src/lib/hf-token-shape.ts b/studio/frontend/src/lib/hf-token-shape.ts
new file mode 100644
index 00000000000..ab96b39624f
--- /dev/null
+++ b/studio/frontend/src/lib/hf-token-shape.ts
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Current user access tokens contain 34 characters after the hf_ prefix; OAuth access tokens
+// (Sign in with Hugging Face) carry hf_oauth_ and a longer body. Only these are checked while
+// typing; action-time validation still accepts legacy shapes without spending quota on every
+// keystroke.
+const COMPLETE_HF_TOKEN = /^hf_(?:[A-Za-z0-9]{34}|oauth_[A-Za-z0-9]{30,})$/;
+
+/** Whether *token* is a whole token worth asking the Hub about while the user types. */
+export function isCompleteHfTokenShape(token: string): boolean {
+ return COMPLETE_HF_TOKEN.test(token);
+}
diff --git a/studio/frontend/src/lib/hub-fetch.ts b/studio/frontend/src/lib/hub-fetch.ts
index b01034aef1b..1a0b9ac9532 100644
--- a/studio/frontend/src/lib/hub-fetch.ts
+++ b/studio/frontend/src/lib/hub-fetch.ts
@@ -4,10 +4,19 @@
/** Hub fetch: the adapter and relays take the Unsloth session; a relay forwards the HF token in `X-HF-Authorization`. */
import {
+ getHfDatasetsServerBase,
+ getHfEndpoint,
+ getHubSource,
isModelScopeHubUrl,
isProxiedHubUrl,
refreshHubSession,
} from "@/lib/hf-endpoint";
+import {
+ clearHfTokenRejected,
+ hfTokenRejectionMark,
+ isHfTokenRejected,
+ noteHfTokenRejected,
+} from "@/lib/hf-token-rejection";
// Set by the relay on the endpoint's own answers, whose 401 is about the Hugging Face token.
const UPSTREAM_HEADER = "X-Hub-Upstream";
@@ -20,6 +29,14 @@ function requestUrl(input: Parameters<typeof fetch>[0]): string {
: input.url;
}
+/** The headers this call sends: as fetch does, `init.headers` replaces a Request input's own. */
+function requestHeaders(input: Parameters<typeof fetch>[0], init: RequestInit): Headers {
+ if (init.headers !== undefined) return new Headers(init.headers);
+ return new Headers(
+ typeof Request !== "undefined" && input instanceof Request ? input.headers : undefined,
+ );
+}
+
function takesSession(url: string): boolean {
return isModelScopeHubUrl(url) || isProxiedHubUrl(url);
}
@@ -30,7 +47,7 @@ function withHubAuth(
): RequestInit {
const url = requestUrl(input);
if (!takesSession(url)) return init;
- const headers = new Headers(init.headers);
+ const headers = requestHeaders(input, init);
const hfToken = headers.get("Authorization");
if (hfToken && isProxiedHubUrl(url)) headers.set("X-HF-Authorization", hfToken);
let token: string | null = null;
@@ -44,11 +61,38 @@ function withHubAuth(
return { ...init, headers };
}
-export async function fetchHub(
+/** The Hugging Face token this request would send the Hub, or null. ModelScope is excluded:
+ * its relay takes the Unsloth session and drops the HF token. */
+function sentHfToken(
input: Parameters<typeof fetch>[0],
- init: RequestInit = {},
+ init: RequestInit,
+ url: string,
+): string | null {
+ if (isModelScopeHubUrl(url)) return null;
+ const header = requestHeaders(input, init).get("Authorization");
+ const token = header?.replace(/^Bearer\s+/i, "").trim();
+ return token || null;
+}
+
+/** Explicit headers, so a Request input's own Authorization cannot come back later. */
+function withoutHfToken(input: Parameters<typeof fetch>[0], init: RequestInit): RequestInit {
+ const headers = requestHeaders(input, init);
+ headers.delete("Authorization");
+ return { ...init, headers };
+}
+
+function isRetryableRead(input: Parameters<typeof fetch>[0], init: RequestInit): boolean {
+ const method = (
+ init.method ?? (typeof input === "object" && "method" in input ? input.method : "GET")
+ ).toUpperCase();
+ return method === "GET" || method === "HEAD";
+}
+
+async function fetchWithSession(
+ input: Parameters<typeof fetch>[0],
+ init: RequestInit,
+ url: string,
): Promise<Response> {
- const url = requestUrl(input);
let response = await fetch(input, withHubAuth(input, init));
if (
response.status === 401 &&
@@ -58,6 +102,100 @@ export async function fetchHub(
) {
response = await fetch(input, withHubAuth(input, init));
}
+ return response;
+}
+
+/** A 401 that came from the Hub itself: direct, or the relay passing on the endpoint's answer. */
+function isHubRefusal(response: Response, url: string): boolean {
+ if (response.status !== 401) return false;
+ return isProxiedHubUrl(url) ? response.headers.has(UPSTREAM_HEADER) : !takesSession(url);
+}
+
+/** The Hub read the token and answered: a success, or a 403/404 for the resource (a token the
+ * Hub refuses gets 401). Through the relay only the endpoint's own answer counts. */
+function tokenAccepted(response: Response, url: string): boolean {
+ if (isProxiedHubUrl(url) && !response.headers.has(UPSTREAM_HEADER) && !response.ok) return false;
+ return response.ok || response.status === 403 || response.status === 404;
+}
+
+/** Which Hub a token refusal belongs to: the endpoint or datasets server the request went to
+ * (its origin for any other URL), so a refusal by one never skips the token on another. */
+export function hubRejectionScope(url?: string): string {
+ const endpoint = getHfEndpoint();
+ let target = endpoint;
+ if (url !== undefined) {
+ // The most specific base first: a datasets server can live under the model endpoint.
+ target =
+ [endpoint, getHfDatasetsServerBase()]
+ .sort((a, b) => b.length - a.length)
+ .find((base) => url === base || url.startsWith(`${base.replace(/\/+$/, "")}/`)) ??
+ urlOrigin(url);
+ }
+ return `${getHubSource()}|${target}`;
+}
+
+function urlOrigin(url: string): string {
+ try {
+ return new URL(url, globalThis.location?.href).origin;
+ } catch {
+ return url;
+ }
+}
+
+/** A second, optional attempt: a network error or timeout there must not replace the answer
+ * the first request already got. */
+async function probe(
+ input: Parameters<typeof fetch>[0],
+ init: RequestInit,
+ url: string,
+): Promise<Response | null> {
+ try {
+ return await fetchWithSession(input, init, url);
+ } catch (error) {
+ // The caller's abort or timeout is the answer, not a probe that happened to fail.
+ const signal = init.signal ?? (input instanceof Request ? input.signal : undefined);
+ if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) {
+ throw error;
+ }
+ return null;
+ }
+}
+
+export async function fetchHub(
+ input: Parameters<typeof fetch>[0],
+ init: RequestInit = {},
+): Promise<Response> {
+ const url = requestUrl(input);
+ const hfToken = sentHfToken(input, init, url);
+ const retryable = hfToken !== null && isRetryableRead(input, init);
+ // Already refused this session: every read with it would 401 again, so ask anonymously.
+ const scope = hubRejectionScope(url);
+ const skipToken = retryable && isHfTokenRejected(hfToken, scope);
+ const started = hfTokenRejectionMark();
+ let response = await fetchWithSession(input, skipToken ? withoutHfToken(input, init) : init, url);
+ if (skipToken && !response.ok && [401, 403, 404].includes(response.status)) {
+ // Anonymous could not read it: try the token again in case the refusal was transient.
+ const withToken = await probe(input, init, url);
+ if (withToken) {
+ // Keep the token's answer: an anonymous 404 would be cached as the repo being missing.
+ void response.body?.cancel().catch(() => undefined);
+ if (tokenAccepted(withToken, url)) clearHfTokenRejected(scope);
+ response = withToken;
+ }
+ } else if (retryable && !skipToken && tokenAccepted(response, url)) {
+ // Past the recheck window the token was accepted again.
+ clearHfTokenRejected(scope);
+ } else if (retryable && !skipToken && isHubRefusal(response, url)) {
+ // A valid token gets 404 for a repo it cannot see, so this 401 is the token being refused.
+ const anonymous = await probe(input, withoutHfToken(input, init), url);
+ if (anonymous?.ok) {
+ void response.body?.cancel().catch(() => undefined);
+ noteHfTokenRejected(hfToken, scope, started);
+ response = anonymous;
+ } else {
+ void anonymous?.body?.cancel().catch(() => undefined);
+ }
+ }
// The relay's own 502 means it could not reach the endpoint: fail as a direct fetch would.
if (response.status === 502 && !response.headers.has(UPSTREAM_HEADER) && isProxiedHubUrl(url)) {
throw new TypeError("The Hub endpoint could not be reached.");
diff --git a/studio/frontend/src/lib/native-notifications.ts b/studio/frontend/src/lib/native-notifications.ts
index 641421f6eaa..9cbe5ddd9e0 100644
--- a/studio/frontend/src/lib/native-notifications.ts
+++ b/studio/frontend/src/lib/native-notifications.ts
@@ -5,7 +5,7 @@ import { isTauri } from "@/lib/api-base";
const MAX_BODY_LENGTH = 200;
const MAX_SENT_KEYS = 200;
-const HF_TOKEN_PATTERN = /\bhf_[A-Za-z0-9]{20,}\b/g;
+const HF_TOKEN_PATTERN = /\bhf_(?:oauth_)?[A-Za-z0-9]{20,}\b/g;
const GITHUB_TOKEN_PATTERN = /\bghp_[A-Za-z0-9_]{20,}\b/g;
const GITHUB_PAT_PATTERN = /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g;
const OPENAI_KEY_PATTERN = /\bsk-[A-Za-z0-9_-]{20,}\b/g;
@@ -20,7 +20,7 @@ const WHITESPACE_PATTERN = /\s+/g;
const LOCAL_PATH_PATTERN = /^(?:\/|~[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/]|\\\\)/;
const PATH_SEPARATOR_PATTERN = /[\\/]/;
const SENSITIVE_TOKEN_PATTERN =
- /\bhf_[A-Za-z0-9]{20,}\b|\bghp_[A-Za-z0-9_]{20,}\b|\bgithub_pat_[A-Za-z0-9_]{20,}\b|\bsk-[A-Za-z0-9_-]{20,}\b/;
+ /\bhf_(?:oauth_)?[A-Za-z0-9]{20,}\b|\bghp_[A-Za-z0-9_]{20,}\b|\bgithub_pat_[A-Za-z0-9_]{20,}\b|\bsk-[A-Za-z0-9_-]{20,}\b/;
type PermissionState = "unknown" | "granted" | "denied";
diff --git a/studio/frontend/src/lib/tauri-diagnostics.ts b/studio/frontend/src/lib/tauri-diagnostics.ts
index 2e3b6b2ba25..e37f88b0cd2 100644
--- a/studio/frontend/src/lib/tauri-diagnostics.ts
+++ b/studio/frontend/src/lib/tauri-diagnostics.ts
@@ -41,7 +41,7 @@ export function redactDiagnosticsText(text: string): string {
/\b(authorization\s*[:=]\s*)(bearer|basic)\s+[^\s,;]+/gi,
"$1$2 <redacted>",
);
- redacted = redacted.replace(/\bhf_[A-Za-z0-9]{20,}\b/g, "hf_<redacted>");
+ redacted = redacted.replace(/\bhf_(?:oauth_)?[A-Za-z0-9]{20,}\b/g, "hf_<redacted>");
redacted = redacted.replace(/\bghp_[A-Za-z0-9_]{20,}\b/g, "ghp_<redacted>");
redacted = redacted.replace(/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g, "github_pat_<redacted>");
redacted = redacted.replace(/\bsk-[A-Za-z0-9_-]{20,}\b/g, "sk-<redacted>");
diff --git a/studio/frontend/tests/hf-endpoint.test.ts b/studio/frontend/tests/hf-endpoint.test.ts
index de3dc70652d..787f7340be0 100644
--- a/studio/frontend/tests/hf-endpoint.test.ts
+++ b/studio/frontend/tests/hf-endpoint.test.ts
@@ -235,5 +235,8 @@ test("a relay to a custom endpoint gets the session, and the Hugging Face token
assert.equal(refreshes, 1);
const both = ["Bearer session", "Bearer hf_x"];
const fresh = ["Bearer fresh1", "Bearer hf_x"];
- assert.deepEqual(sent, [both, ["Bearer session", null], both, both, fresh, fresh, ["Bearer hf_x", null]]);
+ // The gated 401 came from the endpoint with a token, so it is asked once more without it,
+ // still carrying the session; that also 401s and the original answer is returned.
+ const anonymous = ["Bearer session", null];
+ assert.deepEqual(sent, [both, anonymous, both, anonymous, both, fresh, fresh, ["Bearer hf_x", null]]);
});
diff --git a/studio/frontend/tests/hf-token-rejection.test.ts b/studio/frontend/tests/hf-token-rejection.test.ts
new file mode 100644
index 00000000000..37e24e365f2
--- /dev/null
+++ b/studio/frontend/tests/hf-token-rejection.test.ts
@@ -0,0 +1,591 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * A saved Hugging Face token the Hub refuses (an expired OAuth token, a revoked key) gets 401 on
+ * every read, public ones included, and the browser used to report that as "Couldn't reach
+ * Hugging Face". A token the Hub accepts gets 404 for what it cannot see, so a tokened 401 that
+ * succeeds anonymously is the token being refused: fetchHub answers with the anonymous result
+ * and records the refusal once per token.
+ */
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { register } from "node:module";
+import test from "node:test";
+
+register("./bundler-resolver.mjs", import.meta.url);
+
+const { resetHfEndpoints, setHfEndpoints, setHubSessionRefresh } = await import(
+ "../src/lib/hf-endpoint.ts"
+);
+const { fetchHub, hubRejectionScope } = await import("../src/lib/hub-fetch.ts");
+const {
+ HF_TOKEN_REJECTION_RECHECK_MS,
+ clearHfTokenRejected,
+ hasRejectedHfToken,
+ hfTokenRejectionVersion,
+ isHfTokenRejected,
+ noteHfTokenRejected,
+ subscribeHfTokenRejected,
+} = await import("../src/lib/hf-token-rejection.ts");
+const { isCompleteHfTokenShape } = await import("../src/lib/hf-token-shape.ts");
+
+const OAUTH = `hf_oauth_${"A1b2C3d4E5".repeat(4)}`;
+const CLASSIC = `hf_${"a".repeat(34)}`;
+const API = "https://huggingface.co/api/models?search=qwen";
+
+type Sent = { url: string; authorization: string | null; hfAuthorization: string | null };
+
+/** A Hub that refuses *rejectedToken* with the headers the real one sends, and answers
+ * anonymous reads with *anonymousStatus*. */
+function stubHub(opts: {
+ rejectedToken?: string;
+ anonymousStatus?: number;
+ tokenStatus?: number;
+ relay?: string;
+}) {
+ const sent: Sent[] = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async (input: string | Request, init?: RequestInit) => {
+ // As fetch does: init.headers, when given, replace a Request's own.
+ const isRequest = input instanceof Request;
+ const headers = new Headers(init?.headers ?? (isRequest ? input.headers : undefined));
+ const url = isRequest ? input.url : String(input);
+ const authorization = headers.get("authorization");
+ const hfAuthorization = headers.get("x-hf-authorization");
+ sent.push({ url, authorization, hfAuthorization });
+ const viaRelay = opts.relay !== undefined && url.startsWith(opts.relay);
+ const hubToken = viaRelay ? hfAuthorization : authorization;
+ const upstream: Record<string, string> = viaRelay ? { "X-Hub-Upstream": "1" } : {};
+ if (hubToken) {
+ if (opts.tokenStatus !== undefined) {
+ return new Response("{}", { status: opts.tokenStatus, headers: upstream });
+ }
+ if (opts.rejectedToken && hubToken === `Bearer ${opts.rejectedToken}`) {
+ return new Response('{"error":"Invalid credentials in Authorization header"}', {
+ status: 401,
+ headers: {
+ ...upstream,
+ "X-Error-Message": "OAuth token verification failed: Invalid Compact JWS",
+ "WWW-Authenticate": 'Bearer realm="Authentication required"',
+ },
+ });
+ }
+ return new Response('[{"id":"private/model"}]', { status: 200, headers: upstream });
+ }
+ const status = opts.anonymousStatus ?? 200;
+ return new Response(status === 200 ? '[{"id":"unsloth/Qwen3-0.6B-GGUF"}]' : "{}", {
+ status,
+ headers: upstream,
+ });
+ }) as typeof fetch;
+ return {
+ sent,
+ restore: () => {
+ globalThis.fetch = realFetch;
+ },
+ };
+}
+
+function withToken(token: string): RequestInit {
+ return { headers: { Authorization: `Bearer ${token}` } };
+}
+
+test.beforeEach(() => {
+ resetHfEndpoints();
+ clearHfTokenRejected();
+});
+
+test("OAuth tokens are validated like classic tokens instead of never being checked", () => {
+ assert.equal(isCompleteHfTokenShape(OAUTH), true);
+ assert.equal(isCompleteHfTokenShape(CLASSIC), true);
+ // Still not while typing: a prefix or a partial body is not worth a Hub request.
+ assert.equal(isCompleteHfTokenShape("hf_oauth_abc"), false);
+ assert.equal(isCompleteHfTokenShape("hf_abc"), false);
+ assert.equal(isCompleteHfTokenShape(`hf_${"a".repeat(33)}`), false);
+ const hook = readFileSync(
+ new URL("../src/hooks/use-hf-token-validation.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(hook, /isCompleteHfTokenShape\(debouncedToken\)/);
+ assert.match(hook, /isCompleteHfTokenShape\(normalizedToken\)/);
+});
+
+test("a refused token is retried once without it and the public answer is returned", async () => {
+ const hub = stubHub({ rejectedToken: OAUTH });
+ let notified = 0;
+ const unsubscribe = subscribeHfTokenRejected(() => {
+ notified += 1;
+ });
+ try {
+ const response = await fetchHub(API, withToken(OAUTH));
+ assert.equal(response.status, 200);
+ assert.deepEqual(await response.json(), [{ id: "unsloth/Qwen3-0.6B-GGUF" }]);
+ assert.deepEqual(
+ hub.sent.map((s) => s.authorization),
+ [`Bearer ${OAUTH}`, null],
+ );
+ assert.equal(isHfTokenRejected(OAUTH), true);
+ // Later reads skip the refused token instead of paying a 401 round trip each.
+ const again = await fetchHub(API, withToken(OAUTH));
+ assert.equal(again.status, 200);
+ assert.deepEqual(
+ hub.sent.map((s) => s.authorization),
+ [`Bearer ${OAUTH}`, null, null],
+ );
+ assert.equal(notified, 1, "one notice per token, not per request");
+ } finally {
+ unsubscribe();
+ hub.restore();
+ }
+});
+
+test("when anonymous access fails too, the original 401 is returned and nothing is recorded", async () => {
+ const hub = stubHub({ rejectedToken: OAUTH, anonymousStatus: 401 });
+ try {
+ const response = await fetchHub(API, withToken(OAUTH));
+ assert.equal(response.status, 401);
+ assert.equal(
+ response.headers.get("X-Error-Message"),
+ "OAuth token verification failed: Invalid Compact JWS",
+ );
+ assert.equal(hub.sent.length, 2);
+ assert.equal(isHfTokenRejected(OAUTH), false);
+ } finally {
+ hub.restore();
+ }
+});
+
+test("403, 404, 429 and 5xx answer for the resource, not the token, and are never retried", async () => {
+ for (const status of [403, 404, 429, 500, 503]) {
+ const hub = stubHub({ tokenStatus: status });
+ try {
+ const response = await fetchHub(API, withToken(CLASSIC));
+ assert.equal(response.status, status);
+ assert.equal(hub.sent.length, 1, `status ${status}`);
+ assert.equal(isHfTokenRejected(CLASSIC), false);
+ } finally {
+ hub.restore();
+ }
+ }
+});
+
+test("a network failure propagates without a retry", async () => {
+ const realFetch = globalThis.fetch;
+ let calls = 0;
+ globalThis.fetch = (async () => {
+ calls += 1;
+ throw new TypeError("Failed to fetch");
+ }) as typeof fetch;
+ try {
+ await assert.rejects(fetchHub(API, withToken(OAUTH)), TypeError);
+ assert.equal(calls, 1);
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+});
+
+test("an anonymous 401 is not retried and flags nothing", async () => {
+ const hub = stubHub({ anonymousStatus: 401 });
+ try {
+ const response = await fetchHub(API, {});
+ assert.equal(response.status, 401);
+ assert.equal(hub.sent.length, 1);
+ } finally {
+ hub.restore();
+ }
+});
+
+test("a write is never replayed without the token", async () => {
+ const hub = stubHub({ rejectedToken: OAUTH });
+ try {
+ const response = await fetchHub("https://huggingface.co/api/repos/create", {
+ ...withToken(OAUTH),
+ method: "POST",
+ body: "{}",
+ });
+ assert.equal(response.status, 401);
+ assert.equal(hub.sent.length, 1);
+ assert.equal(isHfTokenRejected(OAUTH), false);
+ } finally {
+ hub.restore();
+ }
+});
+
+test("through the Studio relay, only the endpoint's own 401 retries, and the session stays", async () => {
+ const relay = "http://127.0.0.1:8888/api/hub/proxy";
+ const hub = stubHub({ rejectedToken: OAUTH, relay });
+ Object.defineProperty(globalThis, "localStorage", {
+ configurable: true,
+ value: { getItem: () => "session" },
+ });
+ setHubSessionRefresh(async () => false);
+ try {
+ setHfEndpoints(relay, null, "huggingface", { endpoint: true });
+ const response = await fetchHub(`${relay}/api/models?search=qwen`, withToken(OAUTH));
+ assert.equal(response.status, 200);
+ assert.deepEqual(
+ hub.sent.map((s) => [s.authorization, s.hfAuthorization]),
+ [
+ ["Bearer session", `Bearer ${OAUTH}`],
+ ["Bearer session", null],
+ ],
+ );
+ assert.equal(isHfTokenRejected(OAUTH), true);
+ } finally {
+ hub.restore();
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+test("a relay 401 without the upstream marker is the session, not the token", async () => {
+ const relay = "http://127.0.0.1:8888/api/hub/proxy";
+ const realFetch = globalThis.fetch;
+ let calls = 0;
+ globalThis.fetch = (async () => {
+ calls += 1;
+ return new Response("{}", { status: 401 });
+ }) as typeof fetch;
+ Object.defineProperty(globalThis, "localStorage", {
+ configurable: true,
+ value: { getItem: () => "session" },
+ });
+ setHubSessionRefresh(async () => false);
+ try {
+ setHfEndpoints(relay, null, "huggingface", { endpoint: true });
+ const response = await fetchHub(`${relay}/api/models`, withToken(OAUTH));
+ assert.equal(response.status, 401);
+ assert.equal(calls, 1);
+ assert.equal(isHfTokenRejected(OAUTH), false);
+ } finally {
+ globalThis.fetch = realFetch;
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+test("a different token starts clean", () => {
+ const before = hfTokenRejectionVersion();
+ assert.equal(noteHfTokenRejected(OAUTH), true);
+ assert.equal(noteHfTokenRejected(OAUTH), false);
+ assert.equal(isHfTokenRejected(OAUTH), true);
+ assert.equal(isHfTokenRejected(CLASSIC), false);
+ assert.equal(isHfTokenRejected(null), false);
+ assert.ok(hfTokenRejectionVersion() > before);
+ clearHfTokenRejected();
+ assert.equal(isHfTokenRejected(OAUTH), false);
+});
+
+test("OAuth tokens are redacted from notifications and diagnostics", async () => {
+ for (const file of ["../src/lib/native-notifications.ts", "../src/lib/tauri-diagnostics.ts"]) {
+ const source = readFileSync(new URL(file, import.meta.url), "utf8");
+ const patterns = [...source.matchAll(/\/(\\bhf_[^/]+)\/g?/g)].map((m) => new RegExp(m[1]));
+ assert.ok(patterns.length > 0, file);
+ for (const pattern of patterns) {
+ const match = `token ${OAUTH} end`.match(pattern);
+ assert.equal(match?.[0], OAUTH, `${file}: ${pattern} must cover the whole OAuth token`);
+ assert.equal(`token ${CLASSIC} end`.match(pattern)?.[0], CLASSIC);
+ }
+ }
+});
+
+test("after a refusal, a read anonymous access cannot answer still tries the token once", async () => {
+ noteHfTokenRejected(OAUTH, hubRejectionScope());
+ // The verifier recovered: the token works again and the private repo answers with it.
+ const hub = stubHub({ anonymousStatus: 404 });
+ try {
+ const response = await fetchHub("https://huggingface.co/api/models/me/private", withToken(OAUTH));
+ assert.equal(response.status, 200);
+ assert.deepEqual(
+ hub.sent.map((s) => s.authorization),
+ [null, `Bearer ${OAUTH}`],
+ );
+ assert.equal(isHfTokenRejected(OAUTH), false);
+ } finally {
+ hub.restore();
+ }
+});
+
+test("after a refusal, a token that is still refused answers with its 401, not a cacheable 404", async () => {
+ noteHfTokenRejected(OAUTH, hubRejectionScope());
+ const hub = stubHub({ rejectedToken: OAUTH, anonymousStatus: 404 });
+ try {
+ const response = await fetchHub("https://huggingface.co/api/models/me/private", withToken(OAUTH));
+ // A size lookup caches a model 404 for the session; a 401 is only a transient miss.
+ assert.equal(response.status, 401);
+ assert.equal(hub.sent.length, 2);
+ assert.equal(isHfTokenRejected(OAUTH), true);
+ } finally {
+ hub.restore();
+ }
+});
+
+
+test("a refusal recorded against one Hub endpoint does not skip the token on another", async () => {
+ noteHfTokenRejected(OAUTH, "huggingface|https://mirror.example");
+ const hub = stubHub({});
+ try {
+ const response = await fetchHub("https://huggingface.co/api/models/me/private", withToken(OAUTH));
+ assert.equal(response.status, 200);
+ assert.deepEqual(
+ hub.sent.map((s) => s.authorization),
+ [`Bearer ${OAUTH}`],
+ );
+ } finally {
+ hub.restore();
+ clearHfTokenRejected();
+ }
+});
+
+test("a refusal by the datasets server does not skip the token on the model Hub", async () => {
+ const datasetsScope = hubRejectionScope("https://datasets-server.huggingface.co/size?dataset=x");
+ assert.notEqual(datasetsScope, hubRejectionScope("https://huggingface.co/api/models"));
+ assert.equal(hubRejectionScope("https://huggingface.co/api/models"), hubRejectionScope());
+ noteHfTokenRejected(OAUTH, datasetsScope);
+ const hub = stubHub({});
+ try {
+ const response = await fetchHub("https://huggingface.co/api/models/me/private", withToken(OAUTH));
+ assert.equal(response.status, 200);
+ assert.deepEqual(
+ hub.sent.map((s) => s.authorization),
+ [`Bearer ${OAUTH}`],
+ );
+ } finally {
+ hub.restore();
+ clearHfTokenRejected();
+ }
+});
+
+test("a token carried by a Request input is retried and recorded like an init header", async () => {
+ const hub = stubHub({ rejectedToken: OAUTH });
+ try {
+ const request = new Request(API, { headers: { Authorization: `Bearer ${OAUTH}`, "X-Probe": "1" } });
+ const response = await fetchHub(request);
+ assert.equal(response.status, 200);
+ assert.deepEqual(
+ hub.sent.map((s) => s.authorization),
+ [`Bearer ${OAUTH}`, null],
+ );
+ assert.equal(isHfTokenRejected(OAUTH, hubRejectionScope(API)), true);
+ } finally {
+ hub.restore();
+ clearHfTokenRejected();
+ }
+});
+
+test("through the relay, a Request's own token is dropped from the anonymous retry", async () => {
+ const relay = "http://127.0.0.1:8888/api/hub/proxy";
+ const hub = stubHub({ rejectedToken: OAUTH, relay });
+ Object.defineProperty(globalThis, "localStorage", {
+ configurable: true,
+ value: { getItem: () => "session" },
+ });
+ setHubSessionRefresh(async () => false);
+ try {
+ setHfEndpoints(relay, null, "huggingface", { endpoint: true });
+ const request = new Request(`${relay}/api/models?search=qwen`, {
+ headers: { Authorization: `Bearer ${OAUTH}` },
+ });
+ const response = await fetchHub(request);
+ assert.equal(response.status, 200);
+ assert.deepEqual(
+ hub.sent.map((s) => [s.authorization, s.hfAuthorization]),
+ [
+ ["Bearer session", `Bearer ${OAUTH}`],
+ ["Bearer session", null],
+ ],
+ );
+ assert.equal(isHfTokenRejected(OAUTH, hubRejectionScope(request.url)), true);
+ } finally {
+ hub.restore();
+ resetHfEndpoints();
+ clearHfTokenRejected();
+ Reflect.deleteProperty(globalThis, "localStorage");
+ }
+});
+
+test("a cached valid verdict does not clear a refusal a read just saw", () => {
+ const source = readFileSync(new URL("../src/features/hf-auth/api.ts", import.meta.url), "utf8");
+ assert.equal(source.includes("clearHfTokenRejected("), false);
+});
+
+test("refusals by two Hubs are both kept", () => {
+ const models = hubRejectionScope("https://huggingface.co/api/models");
+ const datasets = hubRejectionScope("https://datasets-server.huggingface.co/size?dataset=x");
+ try {
+ noteHfTokenRejected(OAUTH, models);
+ noteHfTokenRejected(OAUTH, datasets);
+ assert.equal(isHfTokenRejected(OAUTH, models), true);
+ assert.equal(isHfTokenRejected(OAUTH, datasets), true);
+ clearHfTokenRejected(datasets);
+ assert.equal(isHfTokenRejected(OAUTH, models), true);
+ assert.equal(isHfTokenRejected(OAUTH, datasets), false);
+ } finally {
+ clearHfTokenRejected();
+ }
+});
+
+test("a datasets server under the model endpoint gets its own scope", () => {
+ setHfEndpoints("https://mirror.example", "https://mirror.example/datasets-server", "huggingface");
+ try {
+ assert.notEqual(
+ hubRejectionScope("https://mirror.example/datasets-server/size?dataset=x"),
+ hubRejectionScope("https://mirror.example/api/models"),
+ );
+ assert.equal(
+ hubRejectionScope("https://mirror.example/datasets-server/size?dataset=x"),
+ "huggingface|https://mirror.example/datasets-server",
+ );
+ } finally {
+ resetHfEndpoints();
+ }
+});
+
+test("after the recheck window the token is tried again, and an answer clears the refusal", async (t) => {
+ t.mock.timers.enable({ apis: ["Date"], now: 1_000_000 });
+ const scope = hubRejectionScope(API);
+ noteHfTokenRejected(OAUTH, scope);
+ const hub = stubHub({});
+ try {
+ await fetchHub(API, withToken(OAUTH));
+ assert.equal(hub.sent[0].authorization, null, "skipped while the refusal is fresh");
+ t.mock.timers.tick(HF_TOKEN_REJECTION_RECHECK_MS + 1);
+ await fetchHub(API, withToken(OAUTH));
+ assert.equal(hub.sent[1].authorization, `Bearer ${OAUTH}`);
+ assert.equal(hasRejectedHfToken(), false);
+ } finally {
+ hub.restore();
+ clearHfTokenRejected();
+ }
+});
+
+test("a token still refused after the recheck is recorded again without a new notification", async (t) => {
+ t.mock.timers.enable({ apis: ["Date"], now: 1_000_000 });
+ const scope = hubRejectionScope(API);
+ noteHfTokenRejected(OAUTH, scope);
+ const before = hfTokenRejectionVersion();
+ const hub = stubHub({ rejectedToken: OAUTH });
+ try {
+ t.mock.timers.tick(HF_TOKEN_REJECTION_RECHECK_MS + 1);
+ const response = await fetchHub(API, withToken(OAUTH));
+ assert.equal(response.status, 200);
+ assert.equal(isHfTokenRejected(OAUTH, scope), true);
+ assert.equal(hfTokenRejectionVersion(), before);
+ } finally {
+ hub.restore();
+ clearHfTokenRejected();
+ }
+});
+
+test("clearing one Hub's refusal while another still refuses is reported as a clear", () => {
+ const models = hubRejectionScope("https://huggingface.co/api/models");
+ const datasets = hubRejectionScope("https://datasets-server.huggingface.co/size?dataset=x");
+ const events: string[] = [];
+ const unsubscribe = subscribeHfTokenRejected((event) => events.push(event));
+ try {
+ noteHfTokenRejected(OAUTH, models);
+ noteHfTokenRejected(OAUTH, datasets);
+ clearHfTokenRejected(models);
+ // The toast listens for "rejected" only, so this recovery raises no warning.
+ assert.deepEqual(events, ["rejected", "rejected", "cleared"]);
+ assert.equal(hasRejectedHfToken(), true);
+ } finally {
+ unsubscribe();
+ clearHfTokenRejected();
+ }
+});
+
+test("clearing a refusal is not reported as a new one", () => {
+ noteHfTokenRejected(OAUTH, hubRejectionScope());
+ assert.equal(hasRejectedHfToken(), true);
+ clearHfTokenRejected();
+ assert.equal(hasRejectedHfToken(), false);
+});
+
+test("a failed anonymous probe keeps the Hub's 401 instead of throwing", async () => {
+ const realFetch = globalThis.fetch;
+ let calls = 0;
+ globalThis.fetch = (async () => {
+ calls += 1;
+ if (calls === 1) {
+ return new Response("{}", {
+ status: 401,
+ headers: { "X-Error-Message": "OAuth token verification failed: Invalid Compact JWS" },
+ });
+ }
+ throw new TypeError("Failed to fetch");
+ }) as typeof fetch;
+ try {
+ const response = await fetchHub("https://huggingface.co/api/models", withToken(OAUTH));
+ assert.equal(response.status, 401);
+ assert.equal(isHfTokenRejected(OAUTH), false);
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+});
+
+test("after a refusal, a token answered with a 404 for a missing repo is accepted again", async () => {
+ noteHfTokenRejected(OAUTH, hubRejectionScope());
+ const hub = stubHub({ tokenStatus: 404, anonymousStatus: 404 });
+ try {
+ const response = await fetchHub("https://huggingface.co/api/models/me/gone", withToken(OAUTH));
+ assert.equal(response.status, 404);
+ assert.equal(isHfTokenRejected(OAUTH), false);
+ } finally {
+ hub.restore();
+ }
+});
+
+test("a slow anonymous probe does not reinstate a refusal a newer tokened success cleared", async () => {
+ const realFetch = globalThis.fetch;
+ let releaseProbe: () => void = () => undefined;
+ const probeGate = new Promise<void>((resolve) => {
+ releaseProbe = resolve;
+ });
+ let tokenReads = 0;
+ globalThis.fetch = (async (_input: string | Request, init?: RequestInit) => {
+ const authorization = new Headers(init?.headers).get("authorization");
+ if (!authorization) {
+ await probeGate;
+ return new Response("[]", { status: 200 });
+ }
+ tokenReads += 1;
+ // The verifier fails once, then accepts the token again.
+ return tokenReads === 1
+ ? new Response("{}", { status: 401, headers: { "X-Error-Message": "Invalid credentials" } })
+ : new Response("[]", { status: 200 });
+ }) as typeof fetch;
+ try {
+ const slow = fetchHub(API, withToken(OAUTH));
+ while (tokenReads < 1) await new Promise((resolve) => setTimeout(resolve, 0));
+ const fresh = await fetchHub(API, withToken(OAUTH));
+ assert.equal(fresh.status, 200);
+ releaseProbe();
+ await slow;
+ assert.equal(isHfTokenRejected(OAUTH), false);
+ assert.equal(hasRejectedHfToken(), false);
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+});
+
+test("an abort while the anonymous probe is in flight rejects instead of returning the 401", async () => {
+ const realFetch = globalThis.fetch;
+ const controller = new AbortController();
+ globalThis.fetch = (async (_input: string | Request, init?: RequestInit) => {
+ const authorization = new Headers(init?.headers).get("authorization");
+ if (authorization) {
+ return new Response("{}", { status: 401, headers: { "X-Error-Message": "Invalid credentials" } });
+ }
+ controller.abort();
+ throw new DOMException("The operation was aborted.", "AbortError");
+ }) as typeof fetch;
+ try {
+ await assert.rejects(
+ fetchHub(API, { ...withToken(OAUTH), signal: controller.signal }),
+ (error: Error) => error.name === "AbortError",
+ );
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+});
diff --git a/studio/frontend/tests/hub-auth-rejected-failure.test.ts b/studio/frontend/tests/hub-auth-rejected-failure.test.ts
new file mode 100644
index 00000000000..b06901c7c20
--- /dev/null
+++ b/studio/frontend/tests/hub-auth-rejected-failure.test.ts
@@ -0,0 +1,139 @@
+// 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 assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+// A Hub that answers 401 is reachable and refusing the saved token (an expired
+// or revoked OAuth token makes every read 401, public listings included). The
+// panel used to call that "Couldn't reach Hugging Face", which sends the user to
+// check a connection that works.
+register("./store-stub-resolver.mjs", import.meta.url);
+const {
+ classifyFetchFailure,
+ fetchWithTimeout,
+ getHubPhase,
+ getLastHubFailure,
+ hubAuthFailure,
+ markRemoteNetworkOnline,
+} = await import("../src/features/hub/lib/network.ts");
+
+import { readText } from "./helpers/kit.ts";
+
+const HF = "https://huggingface.co";
+
+function installWindow() {
+ const listeners = new Map<string, Set<() => void>>();
+ (globalThis as Record<string, unknown>).window = {
+ addEventListener(type: string, fn: () => void) {
+ if (!listeners.has(type)) listeners.set(type, new Set());
+ listeners.get(type)?.add(fn);
+ },
+ removeEventListener(type: string, fn: () => void) {
+ listeners.get(type)?.delete(fn);
+ },
+ dispatchEvent(event: { type: string }) {
+ for (const fn of listeners.get(event.type) ?? []) fn();
+ return true;
+ },
+ location: { href: "http://127.0.0.1:8888/hub" },
+ };
+}
+
+test("a 401 is a refused token; 403, 404, 429 and 5xx are not", () => {
+ const rejected = hubAuthFailure({ status: 401 }, HF);
+ assert.equal(rejected?.kind, "auth-rejected");
+ assert.equal(rejected?.status, 401);
+ assert.equal(rejected?.origin, HF);
+ assert.match(rejected?.message ?? "", /refused the saved Hugging Face token/);
+ // A gated or private repo answers 403/404 to a token that is perfectly valid.
+ for (const status of [403, 404, 429, 500, 502, 503]) {
+ assert.equal(hubAuthFailure({ status }, HF), null, `status ${status}`);
+ }
+});
+
+test("the SDK's error text is enough when the status was not kept", () => {
+ // What @huggingface/hub's createApiError leaves in `message` for a 401: the
+ // Hub's JSON error when there is one, else "Api error with status 401".
+ for (const message of [
+ "OAuth token verification failed: Invalid Compact JWS",
+ "Invalid credentials in Authorization header",
+ ]) {
+ assert.equal(hubAuthFailure({ message }, HF)?.kind, "auth-rejected", message);
+ }
+ // A bare 401 can be the Studio relay's own session answer, so text alone that names no
+ // token is not a refusal of the Hugging Face token.
+ for (const message of [
+ "Api error with status 401",
+ "Unauthorized",
+ "Api error with status 403",
+ "Api error with status 404",
+ "Api error with status 429",
+ "You have exceeded our hourly quotas for action: api. Too many requests",
+ "Api error with status 503",
+ "Failed to fetch",
+ "Unexpected token < in JSON at position 0",
+ "",
+ ]) {
+ assert.equal(hubAuthFailure({ message }, HF), null, message);
+ }
+ assert.equal(hubAuthFailure({ message: null }, HF), null);
+});
+
+test("an explicit status wins over the text", () => {
+ // "Unauthorized" in a 403 body is still a 403: a gated repo, not a dead token.
+ assert.equal(hubAuthFailure({ status: 403, message: "Unauthorized" }, HF), null);
+});
+
+test("network failures keep their own kinds", () => {
+ assert.equal(
+ classifyFetchFailure(new TypeError("Failed to fetch"), HF).kind,
+ "network-opaque",
+ );
+ assert.equal(classifyFetchFailure(new Error("x"), HF, { timedOut: true }).kind, "timeout");
+});
+
+test("a 401 answer does not back the Hub off or record an outage", async () => {
+ installWindow();
+ markRemoteNetworkOnline();
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () =>
+ new Response(JSON.stringify({ error: "OAuth token verification failed" }), {
+ status: 401,
+ headers: { "Content-Type": "application/json" },
+ })) as typeof fetch;
+ try {
+ const response = await fetchWithTimeout(`${HF}/api/models?search=qwen`, {}, 1_000);
+ assert.equal(response.status, 401);
+ // The Hub is reachable: on-device paths, the offline fallbacks and the
+ // backoff all key off this phase, and a refused token must not trip them.
+ assert.equal(getHubPhase(HF), "available");
+ assert.equal(getLastHubFailure(HF), null);
+ } finally {
+ globalThis.fetch = original;
+ }
+});
+
+test("the discovery feed names a refused token instead of an unreachable Hub", async () => {
+ const search = await readText("../src/features/hub/hooks/use-discover-search.ts");
+ assert.match(
+ search,
+ /isDiscoverTab\s*\?\s*\(failure \?\? hubAuthFailure\(\{ message: rawSearchError \}\)\)\s*:\s*null,/,
+ );
+ const states = await readText("../src/features/hub/catalog/catalog-states.tsx");
+ const describe = states.slice(
+ states.indexOf("function describeFailure"),
+ states.indexOf("\nfunction UseModelScopeButton"),
+ );
+ const branch = describe.slice(describe.indexOf('case "auth-rejected":'));
+ assert.match(branch, /rejected your token/);
+ assert.match(branch, /offlineLike: false/);
+ assert.match(branch, /tokenRejected: true/);
+ // Both panels recover the refusal from an SDK error the network layer never saw.
+ assert.equal(states.match(/hubAuthFailure\(\{ message \}\)/g)?.length, 2);
+ // The fix is the token: offer it, and do not suggest switching hubs over it.
+ assert.equal(states.match(/\{tokenRejected \? <UpdateTokenButton \/> : null\}/g)?.length, 2);
+ assert.equal(states.match(/!offlineLike && !tokenRejected \? <UseModelScopeButton \/>/g)?.length, 2);
+ assert.match(states, /openSettings\("general"\)/);
+});
diff --git a/studio/src-tauri/src/diagnostics/redaction.rs b/studio/src-tauri/src/diagnostics/redaction.rs
index 0e3b1bca61b..066b5dba4da 100644
--- a/studio/src-tauri/src/diagnostics/redaction.rs
+++ b/studio/src-tauri/src/diagnostics/redaction.rs
@@ -134,7 +134,7 @@ fn cookie_re() -> &'static Regex {
fn token_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
- RE.get_or_init(|| Regex::new(r"(?i)\b(hf_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,}|ghp_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9]{20,})\b").unwrap())
+ RE.get_or_init(|| Regex::new(r"(?i)\b(hf_(?:oauth_)?[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,}|ghp_[A-Za-z0-9]{20,}|sk-[A-Za-z0-9]{20,})\b").unwrap())
}
fn env_secret_re() -> &'static Regex {
@@ -185,6 +185,16 @@ fn email_re() -> &'static Regex {
mod tests {
use super::*;
+ #[test]
+ fn redacts_hugging_face_oauth_tokens_whole() {
+ let token = "hf_oauth_A1b2C3d4E5A1b2C3d4E5A1b2C3d4E5A1b2C3d4E5";
+ let input = format!("download failed while using {token} for org/model\n");
+ let mut report = RedactionReport::default();
+ let redacted = redact_text(&input, &mut report);
+ assert!(!redacted.contains("A1b2C3d4E5"));
+ assert!(redacted.contains("for org/model"));
+ }
+
#[test]
fn redacts_common_secret_and_path_patterns() {
let input = concat!(