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.

Model hub: report why Hugging Face is unreachable instead of claiming you are offline (#7829)

Daniel Hanb79b8418a7a8
diff --git a/studio/frontend/src/features/hub/catalog/catalog-states.tsx b/studio/frontend/src/features/hub/catalog/catalog-states.tsx
index 513f1c21c83..8d7a581a51b 100644
--- a/studio/frontend/src/features/hub/catalog/catalog-states.tsx
+++ b/studio/frontend/src/features/hub/catalog/catalog-states.tsx
@@ -12,25 +12,72 @@ import type { IconSvgElement } from "@hugeicons/react";
import { HugeiconsIcon } from "@hugeicons/react";
import type { ReactNode } from "react";
import { useLayoutEffect, useRef, useState } from "react";
+import type { HubFailure } from "@/features/hub/lib/network";
+
+// Only a browser reporting itself offline earns "You're offline". Calling a DNS
+// filter or extension block "offline" is what made these bugs undiagnosable.
+function describeFailure(
+ failure: HubFailure | null | undefined,
+ online: boolean,
+ resourceLabel: "models" | "datasets",
+): { title: string; body: string; offlineLike: boolean } {
+ switch (failure?.kind) {
+ case "browser-offline":
+ return {
+ title: "You're offline",
+ body: `Reconnect to the internet to browse ${resourceLabel} from Hugging Face.`,
+ offlineLike: true,
+ };
+ case "timeout":
+ return {
+ title: "Hugging Face timed out",
+ body: failure.message,
+ offlineLike: false,
+ };
+ case "network-opaque":
+ case "unknown":
+ return {
+ title: "Can't reach Hugging Face",
+ body: failure.message,
+ offlineLike: false,
+ };
+ default:
+ break;
+ }
+ return online
+ ? {
+ title: "Couldn't reach Hugging Face",
+ body: "The discovery feed couldn't load. Check your connection or try again.",
+ offlineLike: false,
+ }
+ : {
+ title: "Can't reach Hugging Face",
+ body: `Studio couldn't load ${resourceLabel} from Hugging Face.`,
+ offlineLike: false,
+ };
+}
export function NetworkErrorState({
online,
message,
+ failure,
onRetry,
onSwitchDevice,
resourceLabel = "models",
}: {
online: boolean;
message: string;
+ failure?: HubFailure | null;
onRetry: () => void;
onSwitchDevice?: () => void;
resourceLabel?: "models" | "datasets";
}) {
- const title = online ? "Couldn't reach Hugging Face" : "You're offline";
- const body = online
- ? "The discovery feed couldn't load. Check your connection or try again."
- : `Reconnect to the internet to browse ${resourceLabel} from Hugging Face.`;
- const icon = online ? CloudOffIcon : WifiDisconnected02Icon;
+ const { title, body, offlineLike } = describeFailure(
+ failure,
+ online,
+ resourceLabel,
+ );
+ const icon = offlineLike ? WifiDisconnected02Icon : CloudOffIcon;
return (
<div className="flex min-h-[260px] flex-col items-center justify-center gap-3 px-6 text-center">
@@ -132,10 +179,19 @@ export function DiscoverFetchMoreFooter({
hasActiveFilters,
isLoadingMore,
onFetchMore,
+ failed = false,
+ failureText,
+ onRetry,
}: {
hasActiveFilters: boolean;
isLoadingMore: boolean;
onFetchMore: () => void;
+ /** The last attempt failed, so this is the only recovery left on screen. */
+ failed?: boolean;
+ /** The classified, already sanitized cause. Shown here because this footer
+ * outlives the toast that would otherwise be the only place it appeared. */
+ failureText?: string;
+ onRetry?: () => void;
}) {
return (
<div className="relative z-10 flex flex-col items-center gap-2 rounded-[16px] bg-card px-4 py-4 text-center">
@@ -145,9 +201,18 @@ export function DiscoverFetchMoreFooter({
Some results may be hidden by your filters.
</p>
)}
+ {/* Rows stay on screen when the feed fails, so without this the outage is
+ invisible and there is nothing left to click once the toast goes. The
+ cause goes here too: naming it is the whole point, and the toast is
+ transient, so reducing this to "out of date" threw it away again. */}
+ {failed && (
+ <p className="max-w-md text-ui-11p5 leading-4 text-muted-foreground">
+ {failureText || "These results may be out of date."}
+ </p>
+ )}
<button
type="button"
- onClick={onFetchMore}
+ onClick={failed && onRetry ? onRetry : onFetchMore}
disabled={isLoadingMore}
className="inline-flex h-8 items-center gap-1.5 rounded-full bg-foreground/[0.06] px-3 text-ui-12 font-medium text-foreground transition-colors hover:bg-foreground/[0.1] disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white/[0.06] dark:hover:bg-white/[0.1]"
>
@@ -156,7 +221,7 @@ export function DiscoverFetchMoreFooter({
strokeWidth={1.75}
className="size-3.5"
/>
- {isLoadingMore ? "Loading..." : "Load more"}
+ {isLoadingMore ? "Loading..." : failed ? "Try again" : "Load more"}
</button>
</div>
);
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
index dceaa789268..2530586d822 100644
--- a/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
@@ -15,6 +15,7 @@ import {
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import type { Ref } from "react";
+import type { HubFailure } from "@/features/hub/lib/network";
import { useLayoutEffect, useMemo, useState } from "react";
import {
inventoryRowMatches,
@@ -96,6 +97,7 @@ export function DiscoverList({
suppressEmptyState = false,
sentinelRef,
searchError,
+ searchFailure,
online,
isDataset,
deviceType,
@@ -120,6 +122,7 @@ export function DiscoverList({
suppressEmptyState?: boolean;
sentinelRef: Ref<HTMLDivElement>;
searchError: string | null;
+ searchFailure?: HubFailure | null;
online: boolean;
isDataset: boolean;
deviceType: string | null;
@@ -150,7 +153,8 @@ export function DiscoverList({
return (
<>
- {online ? (
+ {/* Keep fetched results on screen when the Hub becomes unreachable. */}
+ {online || discoverRows.length > 0 ? (
discoverRows.length > 0 ? (
<>
<VirtualRows
@@ -187,11 +191,22 @@ export function DiscoverList({
)
}
/>
- {hasMore && (
+ {/* searchFailure, not `online`: that is the backoff TTL, which
+ lapses on a timer, so the notice and its Retry vanished before
+ anything had proved recovery. The cause clears on success. It
+ covers the avatar and card case too, which marks the same origin
+ without the listing ever failing. */}
+ {(hasMore || searchError || searchFailure) && (
<DiscoverFetchMoreFooter
hasActiveFilters={hasActiveFilters}
isLoadingMore={isLoadingMore}
onFetchMore={onFetchMore}
+ // searchFailure too: the footer is retained over an outage the
+ // listing never saw, and useHubInfiniteScroll is gated on
+ // reachability, so the button was visible and inert meanwhile.
+ failed={Boolean(searchError || searchFailure)}
+ failureText={searchFailure?.message ?? searchError ?? ""}
+ onRetry={onRetry}
/>
)}
</>
@@ -199,6 +214,7 @@ export function DiscoverList({
<NetworkErrorState
online={online}
message={searchError}
+ failure={searchFailure}
onRetry={onRetry}
resourceLabel={isDataset ? "datasets" : "models"}
/>
@@ -230,7 +246,10 @@ export function DiscoverList({
) : suppressEmptyState ? null : (
<NetworkErrorState
online={online}
- message="Discovery is unavailable while offline."
+ // The classified failure supplies the wording; the raw SDK error
+ // appends the request URL, which carries the query.
+ message={searchFailure ? "" : (searchError ?? "")}
+ failure={searchFailure}
onRetry={onRetry}
onSwitchDevice={onSwitchDevice}
resourceLabel={isDataset ? "datasets" : "models"}
diff --git a/studio/frontend/src/features/hub/catalog/models-catalog.tsx b/studio/frontend/src/features/hub/catalog/models-catalog.tsx
index bae7a989126..0d94d335ddc 100644
--- a/studio/frontend/src/features/hub/catalog/models-catalog.tsx
+++ b/studio/frontend/src/features/hub/catalog/models-catalog.tsx
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { usePlatformStore } from "@/config/env";
+import type { HubFailure } from "@/features/hub/lib/network";
import { cn } from "@/lib/utils";
import {
type ReactNode,
@@ -48,6 +49,7 @@ export interface ModelsCatalogState {
activeCheckpoint: string | null;
activeGgufVariant: string | null;
searchError: string | null;
+ searchFailure?: HubFailure | null;
online: boolean;
isDataset: boolean;
inventoryTokens: readonly string[];
@@ -114,6 +116,7 @@ export const ModelsCatalog = memo(function ModelsCatalog({
activeCheckpoint,
activeGgufVariant,
searchError,
+ searchFailure,
online,
isDataset,
inventoryTokens,
@@ -422,6 +425,7 @@ export const ModelsCatalog = memo(function ModelsCatalog({
suppressEmptyState={suppressEmptyState}
sentinelRef={sentinelRef}
searchError={searchError}
+ searchFailure={searchFailure}
online={online}
isDataset={isDataset}
deviceType={deviceType}
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 a11a40ee9b2..ffd2662435c 100644
--- a/studio/frontend/src/features/hub/hooks/use-discover-search.ts
+++ b/studio/frontend/src/features/hub/hooks/use-discover-search.ts
@@ -3,6 +3,8 @@
import { useCallback, useEffect, useRef } from "react";
import { toast } from "@/lib/toast";
+import { clearRemoteBackoff, type HubFailure } from "@/features/hub/lib/network";
+import { useHubAvailability } from "./use-online-status";
import {
type HfModelResult,
type HfModelSearchChannel,
@@ -24,10 +26,17 @@ export interface DiscoverSearch {
hasMore: boolean;
fetchMore: () => boolean;
searchError: string | null;
+ /** Classified cause of the last failure, for a diagnosable error panel. */
+ searchFailure: HubFailure | null;
handleRetrySearch: () => void;
}
-type DiscoverErrorKind = "offline" | "auth" | "rate-limited" | "server" | "unknown";
+type DiscoverErrorKind =
+ | "offline"
+ | "auth"
+ | "rate-limited"
+ | "server"
+ | "unknown";
const RECONNECT_RETRY_COOLDOWN_MS = 90_000;
@@ -69,7 +78,7 @@ function classifyDiscoverError(
function discoverErrorTitle(kind: DiscoverErrorKind): string {
switch (kind) {
case "offline":
- return "You're offline";
+ return "Can't reach Hugging Face";
case "auth":
return "Hugging Face auth failed";
case "rate-limited":
@@ -88,7 +97,6 @@ export function useDiscoverSearch({
direction,
channel,
ownerScope,
- online,
}: {
debouncedQuery: string;
accessToken: string | undefined;
@@ -98,21 +106,36 @@ export function useDiscoverSearch({
direction: HfSortDirection;
channel: HfModelSearchChannel | null;
ownerScope: "unsloth" | "all";
- online: boolean;
}): DiscoverSearch {
+ const { phase, failure } = useHubAvailability();
+ // "probing" counts: a lapsed backoff is exactly when the next request should
+ // be allowed to test the network. Only a live backoff ("unavailable") holds it.
+ const canProbe = phase !== "unavailable";
+ // Only a success promotes to "available". A lapsed backoff is "probing", so a
+ // stale window can no longer announce "Back online" without a working request.
+ const online = phase === "available";
+
+ // Gated on the live backoff only, never on "probing". Gating on availability
+ // is what discarded the error and made every cause render the same, and that
+ // is now safe because the disabled path preserves it; but leaving it ungated
+ // let a user typing through an outage issue a request per debounce tick, each
+ // one re-arming the window it was meant to be waiting out.
const modelSearch = useHubModelSearch(debouncedQuery, {
accessToken,
sortBy,
sortDirection: direction,
pinUnslothFirst: true,
ownerScope,
- enabled: online && isDiscoverTab && !isDatasetMode,
+ enabled: canProbe && isDiscoverTab && !isDatasetMode,
keepUnsupportedTags: true,
channel,
});
const datasetSearch = useHubDatasetSearch(debouncedQuery, {
accessToken,
- enabled: online && isDiscoverTab && isDatasetMode,
+ // Not folded into `enabled`: that one also means "this tab is showing",
+ // and returns [] when false, so a backoff blanked every rendered row.
+ enabled: isDiscoverTab && isDatasetMode,
+ paused: !canProbe,
sortBy,
sortDirection: direction,
});
@@ -129,26 +152,35 @@ export function useDiscoverSearch({
const rawFetchMore = isDatasetMode
? datasetSearch.fetchMore
: modelSearch.fetchMore;
+ // Already sanitized in useHubPaginatedSearch, where every consumer reads it.
const rawSearchError = isDatasetMode ? datasetSearch.error : modelSearch.error;
const retrySearch = isDatasetMode ? datasetSearch.retry : modelSearch.retry;
- const searchError = isDiscoverTab && online ? rawSearchError : null;
+ const needsRestart = isDatasetMode
+ ? datasetSearch.needsRestart
+ : modelSearch.needsRestart;
+ // Surfaced regardless of availability: the failure IS the thing worth showing.
+ const searchError = isDiscoverTab ? rawSearchError : null;
+ const searchFailure = isDiscoverTab ? failure : null;
const fetchMore = useCallback(() => {
- if (!online || !hasMore) return false;
+ if (!canProbe || !hasMore) return false;
+ // A page that failed took the iterator with it, so resuming would resolve
+ // done and quietly end pagination, leaving Load more inert on screen.
+ if (needsRestart()) {
+ retrySearch();
+ return true;
+ }
return rawFetchMore();
- }, [online, hasMore, rawFetchMore]);
+ }, [canProbe, hasMore, needsRestart, rawFetchMore, retrySearch]);
const handleRetrySearch = useCallback(() => {
- if (!online) {
- toast.error("You're offline", {
- description: "Reconnect to the internet to browse Hugging Face.",
- });
- return;
- }
+ // Always re-probe: refusing during the backoff left users unable to test a
+ // firewall, DNS or certificate change without waiting out the timer.
+ clearRemoteBackoff();
retrySearch();
toast.message("Retrying…", {
description: "Reaching Hugging Face for the latest models.",
});
- }, [online, retrySearch]);
+ }, [retrySearch]);
const lastErrorRef = useRef<DiscoverErrorKind | null>(null);
useEffect(() => {
@@ -164,27 +196,45 @@ export function useDiscoverSearch({
if (lastErrorRef.current === errorKind) return;
lastErrorRef.current = errorKind;
toast.error(discoverErrorTitle(errorKind), {
- description: online
- ? searchError
- : "Reconnect to the internet to browse models.",
+ // The classified failure names the cause; the raw message covers HTTP
+ // errors that never reach the network layer.
+ description: searchFailure?.message ?? searchError,
action: { label: "Retry", onClick: handleRetrySearch },
});
- }, [isDiscoverTab, searchError, online, handleRetrySearch]);
+ }, [isDiscoverTab, searchError, searchFailure, online, handleRetrySearch]);
- const wasOfflineRef = useRef(!online);
+ // Driven by a successful request, never a lapsed timer. Announcing recovery
+ // on TTL expiry produced a permanent offline/back-online loop.
+ const wasUnavailableRef = useRef(phase !== "available");
const lastReconnectAtRef = useRef(0);
+ // Whether this feed is the one probing. Latched while it has a request in
+ // flight and cleared once it is idle and unavailable, so the reconnect effect
+ // can tell its own recovery from another surface's.
+ const selfProbedRef = useRef(false);
+ useEffect(() => {
+ if (isLoading || isLoadingMore) {
+ selfProbedRef.current = true;
+ } else if (!online) {
+ selfProbedRef.current = false;
+ }
+ }, [online, isLoading, isLoadingMore]);
useEffect(() => {
- if (online && wasOfflineRef.current && isDiscoverTab) {
+ if (online && wasUnavailableRef.current && isDiscoverTab) {
const now = Date.now();
if (now - lastReconnectAtRef.current > RECONNECT_RETRY_COOLDOWN_MS) {
lastReconnectAtRef.current = now;
+ const selfProbed = selfProbedRef.current;
+ selfProbedRef.current = false;
toast.success("Back online", {
description: "Refreshing the discovery feed.",
});
- retrySearch();
+ // Only when something else proved the Hub reachable. Our own successful
+ // request is what usually clears the window, and its results are already
+ // rendered, so retrying would discard them and re-issue the same call.
+ if (!selfProbed) retrySearch();
}
}
- wasOfflineRef.current = !online;
+ wasUnavailableRef.current = !online;
}, [online, retrySearch, isDiscoverTab]);
return {
@@ -196,6 +246,7 @@ export function useDiscoverSearch({
hasMore,
fetchMore,
searchError,
+ searchFailure,
handleRetrySearch,
};
}
diff --git a/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts b/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts
index 40e1696decb..b3f363ee818 100644
--- a/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts
+++ b/studio/frontend/src/features/hub/hooks/use-hub-dataset-search.ts
@@ -401,6 +401,9 @@ export function useHubDatasetSearch(
modelType?: HubModelType | null;
accessToken?: string;
enabled?: boolean;
+ /** Hold new requests without hiding what is already on screen. `enabled`
+ * means "this tab is showing", and returns [] when false. */
+ paused?: boolean;
sortBy?: DatasetSortKey;
sortDirection?: DatasetSortDirection;
},
@@ -409,6 +412,7 @@ export function useHubDatasetSearch(
modelType,
accessToken,
enabled = true,
+ paused = false,
sortBy = "trendingScore",
sortDirection = "desc",
} = options ?? {};
@@ -429,7 +433,9 @@ export function useHubDatasetSearch(
[useCuratedOnly, hasQuery, query, accessToken, sortBy, sortDirection],
);
- const search = useHubPaginatedSearch(createIter, mapDataset, { enabled });
+ const search = useHubPaginatedSearch(createIter, mapDataset, {
+ enabled: enabled && !paused,
+ });
const results = useMemo(() => {
if (!enabled) return [];
diff --git a/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.ts b/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.ts
index d598065d17e..4ea42357b00 100644
--- a/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.ts
+++ b/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { sanitizeHubErrorMessage } from "../lib/network";
interface HfPaginatedState<T> {
results: T[];
@@ -56,7 +57,16 @@ export async function pullBatch<T>(
return { items, done: true, scanned };
}
scanned += 1;
- const mapped = mapItem(result.value);
+ // mapItem already returns null to mean "skip", so a throw is the same
+ // answer arriving the hard way. Letting it out marked the generator dead
+ // over an item next() had already handed us, and every restart then hit
+ // the same row at the same position.
+ let mapped: T | null = null;
+ try {
+ mapped = mapItem(result.value);
+ } catch {
+ continue;
+ }
if (mapped !== null) {
items.push(mapped);
}
@@ -68,6 +78,14 @@ function isAbortError(err: unknown): boolean {
return err instanceof DOMException && err.name === "AbortError";
}
+// The SDK appends the request URL to its message, and for a proxied request
+// that URL carries the user's search query, which some pickers render raw.
+function hubErrorText(err: unknown, fallback: string): string {
+ return err instanceof Error
+ ? sanitizeHubErrorMessage(err.message)
+ : fallback;
+}
+
function isDocumentHidden(): boolean {
return typeof document !== "undefined" && document.hidden;
}
@@ -76,9 +94,16 @@ export function useHubPaginatedSearch<T>(
createIter: (signal: AbortSignal) => AsyncGenerator<unknown>,
mapItem: (raw: unknown) => T | null,
options?: { enabled?: boolean },
-): HfPaginatedState<T> & { fetchMore: () => boolean; retry: () => void } {
+): HfPaginatedState<T> & {
+ fetchMore: () => boolean;
+ retry: () => void;
+ needsRestart: () => boolean;
+} {
const enabled = options?.enabled ?? true;
const [retryNonce, setRetryNonce] = useState(0);
+ // An async generator that throws is closed: the next next() resolves done
+ // without a request, so a failed page cannot be resumed, only restarted.
+ const iterDeadRef = useRef(false);
const queryKey = useMemo(
() => ({ createIter, mapItem, retryNonce }),
[createIter, mapItem, retryNonce],
@@ -157,13 +182,14 @@ export function useHubPaginatedSearch<T>(
busyRef.current = false;
busyKindRef.current = null;
}
+ // `error` is deliberately preserved: disabling the feed must not erase why
+ // the last attempt failed, leaving only a generic "you're offline" panel.
setState((prev) =>
- prev.isLoading || prev.isLoadingMore || prev.error
+ prev.isLoading || prev.isLoadingMore
? {
...prev,
isLoading: false,
isLoadingMore: false,
- error: null,
}
: prev,
);
@@ -201,6 +227,7 @@ export function useHubPaginatedSearch<T>(
const iter = createIter(controller.signal);
iterRef.current = iter;
+ iterDeadRef.current = false;
pullBatch(iter, mapItem, BATCH)
.then(({ items, done, scanned }) => {
@@ -224,7 +251,7 @@ export function useHubPaginatedSearch<T>(
isLoading: false,
isLoadingMore: false,
hasMore: false,
- error: err instanceof Error ? err.message : "Search failed",
+ error: hubErrorText(err, "Search failed"),
queryKey,
});
})
@@ -247,6 +274,9 @@ export function useHubPaginatedSearch<T>(
clearDeferredFetch,
]);
+ // A thrown generator is closed, so continuing needs a new one.
+ const needsRestart = useCallback(() => iterDeadRef.current, []);
+
const retry = useCallback(() => {
setRetryNonce((n) => n + 1);
}, []);
@@ -269,6 +299,15 @@ export function useHubPaginatedSearch<T>(
return false;
}
+ // A generator that threw is finished; hasMore stays true only to keep the
+ // footer and its error. Pulling again returns done, which clears both, so
+ // the auto-fill would swallow the failure. Only a restart resumes.
+ if (iterDeadRef.current) {
+ queuedAfterBusyRef.current = false;
+ queuedWhileHiddenRef.current = false;
+ return false;
+ }
+
const iter = iterRef.current;
const { hasMore } = stateRef.current;
if (!iter || !hasMore) {
@@ -332,13 +371,13 @@ export function useHubPaginatedSearch<T>(
.catch((err) => {
if (versionRef.current !== v || isAbortError(err)) return;
shouldScheduleFollowUp = false;
+ // The generator threw, so it is finished. Keep the rows and hasMore so
+ // the footer survives, but record that continuing now needs a restart.
+ iterDeadRef.current = true;
setState((prev) => ({
...prev,
isLoadingMore: false,
- // Keep results and hasMore=true: the iterator is still valid, so the
- // next fetchMore() resumes the failed page without discarding the list
- // (retry() restarts from page 1).
- error: err instanceof Error ? err.message : "Failed to load more",
+ error: hubErrorText(err, "Failed to load more"),
}));
})
.finally(() => {
@@ -394,5 +433,6 @@ export function useHubPaginatedSearch<T>(
error: visibleState.error,
fetchMore,
retry,
+ needsRestart,
};
}
diff --git a/studio/frontend/src/features/hub/hooks/use-online-status.ts b/studio/frontend/src/features/hub/hooks/use-online-status.ts
index cf73a74fc81..e1cc05ed09c 100644
--- a/studio/frontend/src/features/hub/hooks/use-online-status.ts
+++ b/studio/frontend/src/features/hub/hooks/use-online-status.ts
@@ -3,6 +3,10 @@
import {
getBrowserOfflineRetryDelayMs,
+ getHubPhase,
+ getLastHubFailure,
+ type HubFailure,
+ type HubPhase,
isHuggingFaceOffline,
subscribeNetworkStatus,
} from "@/features/hub/lib/network";
@@ -44,6 +48,11 @@ function subscribeOnlineStatus(onStoreChange: () => void): () => void {
};
}
+/**
+ * Legacy boolean view. Prefer useHubAvailability() in UI: this collapses
+ * "backing off" and "proven reachable" into one bit, so every failure looked
+ * identical on screen.
+ */
export function useOnlineStatus(): boolean {
return useSyncExternalStore(
subscribeOnlineStatus,
@@ -51,3 +60,42 @@ export function useOnlineStatus(): boolean {
getServerOnlineSnapshot,
);
}
+
+export interface HubAvailability {
+ phase: HubPhase;
+ failure: HubFailure | null;
+}
+
+function getPhaseSnapshot(): HubPhase {
+ return getHubPhase();
+}
+
+function getServerPhaseSnapshot(): HubPhase {
+ return "available";
+}
+
+function getFailureSnapshot(): HubFailure | null {
+ return getLastHubFailure();
+}
+
+function getServerFailureSnapshot(): HubFailure | null {
+ return null;
+}
+
+/**
+ * Availability plus the reason for the last failure. The failure outlives the
+ * backoff and clears only on success, so the UI keeps naming the real cause.
+ */
+export function useHubAvailability(): HubAvailability {
+ const phase = useSyncExternalStore(
+ subscribeOnlineStatus,
+ getPhaseSnapshot,
+ getServerPhaseSnapshot,
+ );
+ const failure = useSyncExternalStore(
+ subscribeOnlineStatus,
+ getFailureSnapshot,
+ getServerFailureSnapshot,
+ );
+ return { phase, failure };
+}
diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsx
index ccf56e0751a..320f226d7db 100644
--- a/studio/frontend/src/features/hub/hub-page.tsx
+++ b/studio/frontend/src/features/hub/hub-page.tsx
@@ -11,7 +11,7 @@ import {
useChatModelRuntime,
useChatRuntimeStore,
} from "@/features/chat";
-import { useOnlineStatus } from "@/features/hub";
+import { useOnlineStatus } from "@/features/hub/hooks/use-online-status";
import { useHubInfiniteScroll } from "@/features/hub";
import {
type ModelPickTarget,
@@ -368,6 +368,10 @@ export function ModelsPage() {
const navigate = useNavigate();
const gpu = useGpuInfo();
const inferenceGpu = useInferenceGpuInfo();
+ // Browser reachability, which is what every client here asks about: the
+ // selected model's metadata and the cached feed each issue their own request.
+ // On the discovery phase they would stay blocked at "probing" until a
+ // *listing* succeeded, and the Downloaded tab has no Retry to make that happen.
const online = useOnlineStatus();
const deviceType = usePlatformStore((s) => s.deviceType);
const hubSearch = useSearch({ from: "/hub" });
@@ -732,6 +736,7 @@ export function ModelsPage() {
hasMore,
fetchMore,
searchError,
+ searchFailure,
handleRetrySearch,
} = useDiscoverSearch({
debouncedQuery,
@@ -742,7 +747,6 @@ export function ModelsPage() {
direction: effectiveDirection,
channel: listChannel,
ownerScope,
- online,
});
const cachedListEntry = useHubFeedStore((state) =>
@@ -1076,6 +1080,8 @@ export function ModelsPage() {
scannedCount,
{
enabled: online && isDiscoverTab && hasMore,
+ // No phase gate: the footer renders on hasMore and so outlives the failed
+ // page, and fetchMoreDiscoverManual clears the backoff itself.
isFetching: isLoading || isLoadingMore,
resultCount: filteredDiscoverRows.length,
maxAutoFillFetches: 5,
@@ -1624,6 +1630,7 @@ export function ModelsPage() {
activeCheckpoint,
activeGgufVariant,
searchError,
+ searchFailure,
online,
isDataset: isDatasetMode,
inventoryTokens,
@@ -1650,6 +1657,7 @@ export function ModelsPage() {
activeCheckpoint,
activeGgufVariant,
searchError,
+ searchFailure,
online,
inventoryTokens,
scannedCount,
diff --git a/studio/frontend/src/features/hub/lib/network.ts b/studio/frontend/src/features/hub/lib/network.ts
index a0bdf6598da..003f33871fe 100644
--- a/studio/frontend/src/features/hub/lib/network.ts
+++ b/studio/frontend/src/features/hub/lib/network.ts
@@ -7,15 +7,53 @@ export function isBrowserOffline(): boolean {
const NETWORK_STATUS_EVENT = "unsloth-network-status";
const REMOTE_OFFLINE_TTL_MS = 30_000;
-// Discovery and repository pages are served by the main Hugging Face origin.
-// Keep optional services such as datasets-server separate so an outage there
-// cannot make the whole Hub appear offline.
const HUGGING_FACE_ORIGIN = "https://huggingface.co";
const noopUnsubscribe = () => undefined;
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.
+ */
+export type HubFailureKind =
+ | "aborted"
+ | "timeout"
+ | "browser-offline"
+ | "network-opaque"
+ | "unknown";
+
+export interface HubFailure {
+ kind: HubFailureKind;
+ /** Already sanitised: safe to render. Never contains a full URL or a token. */
+ message: string;
+ /** Origin only, never the full request URL (which carries the search query). */
+ origin: string | null;
+ status?: number;
+ retryable: boolean;
+}
+
+/** Error thrown by fetchWithTimeout carrying a classified, renderable failure. */
+export class HubFetchError extends Error {
+ readonly failure: HubFailure;
+
+ constructor(failure: HubFailure, options?: { cause?: unknown }) {
+ super(failure.message, options);
+ this.name = "HubFetchError";
+ this.failure = failure;
+ }
+}
+
+export function isHubFetchError(error: unknown): error is HubFetchError {
+ return error instanceof HubFetchError;
+}
+
const remoteOfflineUntilByOrigin = new Map<string, number>();
+// The TTL controls when we retry; this controls what we tell the user. Cleared
+// only by a success, so the cause outlives the backoff window and the panel can
+// still say why after the window has lapsed.
+const lastFailureByOrigin = new Map<string, HubFailure>();
function isNavigatorOffline(): boolean {
return typeof navigator !== "undefined" && navigator.onLine === false;
@@ -31,9 +69,11 @@ function emitNetworkStatusChange(): void {
export function getBrowserOfflineRetryDelayMs(): number {
// Keyed off the empirical remote-offline TTL, not navigator.onLine, so
// recovery doesn't stall on platforms where navigator.onLine is stuck false.
+ // The earliest live window, not the latest: the phase reads one feed's, so
+ // waking on the longest would leave it reporting a state it had already left.
return Math.max(
0,
- getRemoteOfflineUntil(HUGGING_FACE_ORIGIN) - Date.now(),
+ getEarliestRemoteOfflineUntil() - Date.now(),
);
}
@@ -41,16 +81,35 @@ function normalizeScope(scope: RemoteNetworkScope): readonly string[] {
return typeof scope === "string" ? [scope] : scope;
}
+function offlineUntil(origin: string): number {
+ const value = remoteOfflineUntilByOrigin.get(origin) ?? 0;
+ if (value <= Date.now()) {
+ remoteOfflineUntilByOrigin.delete(origin);
+ return 0;
+ }
+ return value;
+}
+
function getRemoteOfflineUntil(scope: RemoteNetworkScope): number {
- const now = Date.now();
let until = 0;
for (const origin of normalizeScope(scope)) {
- const value = remoteOfflineUntilByOrigin.get(origin) ?? 0;
+ until = Math.max(until, offlineUntil(origin));
+ }
+ return until;
+}
+
+/** The soonest live window anywhere, or 0 when nothing is backing off. */
+function getEarliestRemoteOfflineUntil(): number {
+ const now = Date.now();
+ let until = 0;
+ for (const [origin, value] of remoteOfflineUntilByOrigin) {
if (value <= now) {
remoteOfflineUntilByOrigin.delete(origin);
continue;
}
- until = Math.max(until, value);
+ if (until === 0 || value < until) {
+ until = value;
+ }
}
return until;
}
@@ -69,16 +128,42 @@ export function isHuggingFaceOffline(): boolean {
return isRemoteNetworkOffline(HUGGING_FACE_ORIGIN);
}
+/**
+ * Availability of a Hub origin. A lapsed backoff means "probing", not
+ * "available": only a success promotes an origin, which stops the flapping.
+ */
+export type HubPhase = "available" | "probing" | "unavailable";
+
+export function getHubPhase(origin: string = HUGGING_FACE_ORIGIN): HubPhase {
+ if (!lastFailureByOrigin.has(origin)) {
+ return "available";
+ }
+ return isRemoteNetworkOffline(origin) ? "unavailable" : "probing";
+}
+
+export function getLastHubFailure(
+ origin: string = HUGGING_FACE_ORIGIN,
+): HubFailure | null {
+ return lastFailureByOrigin.get(origin) ?? null;
+}
+
export function markRemoteNetworkOnline(origin?: string): void {
if (origin === undefined) {
- if (remoteOfflineUntilByOrigin.size === 0) {
+ if (
+ remoteOfflineUntilByOrigin.size === 0 &&
+ lastFailureByOrigin.size === 0
+ ) {
return;
}
remoteOfflineUntilByOrigin.clear();
+ lastFailureByOrigin.clear();
emitNetworkStatusChange();
return;
}
- if (!remoteOfflineUntilByOrigin.delete(origin)) {
+ // The cause goes with the window: a success is what proves the block lifted.
+ const hadWindow = remoteOfflineUntilByOrigin.delete(origin);
+ const hadFailure = lastFailureByOrigin.delete(origin);
+ if (!hadWindow && !hadFailure) {
return;
}
emitNetworkStatusChange();
@@ -87,20 +172,45 @@ export function markRemoteNetworkOnline(origin?: string): void {
export function markRemoteNetworkOffline(
originOrTtl: string | number = HUGGING_FACE_ORIGIN,
ttlMs = REMOTE_OFFLINE_TTL_MS,
+ failure?: HubFailure,
): void {
const origin =
- typeof originOrTtl === "string"
- ? originOrTtl
- : HUGGING_FACE_ORIGIN;
+ typeof originOrTtl === "string" ? originOrTtl : HUGGING_FACE_ORIGIN;
const ttl = typeof originOrTtl === "number" ? originOrTtl : ttlMs;
const nextUntil = Date.now() + ttl;
- if (nextUntil <= (remoteOfflineUntilByOrigin.get(origin) ?? 0)) {
+ const previousUntil = remoteOfflineUntilByOrigin.get(origin) ?? 0;
+ // The cause has to describe the window in force: recording a newer cause while
+ // keeping a longer window left the panel naming a spent failure while a
+ // different, still-live one held it unavailable. A first cause is always
+ // taken, so nothing the user sees goes unexplained.
+ const takesWindow = nextUntil > previousUntil;
+ const records =
+ failure !== undefined && (takesWindow || !lastFailureByOrigin.has(origin));
+ const failureChanged =
+ records && lastFailureByOrigin.get(origin)?.kind !== failure?.kind;
+ if (records && failure !== undefined) {
+ lastFailureByOrigin.set(origin, failure);
+ }
+ if (!takesWindow) {
+ if (failureChanged) {
+ emitNetworkStatusChange();
+ }
return;
}
remoteOfflineUntilByOrigin.set(origin, nextUntil);
emitNetworkStatusChange();
}
+/** Let Retry re-probe now. The failure stays until a request succeeds. */
+export function clearRemoteBackoff(
+ origin: string = HUGGING_FACE_ORIGIN,
+): void {
+ if (!remoteOfflineUntilByOrigin.delete(origin)) {
+ return;
+ }
+ emitNetworkStatusChange();
+}
+
export function subscribeNetworkStatus(listener: () => void): () => void {
if (typeof window === "undefined") {
return noopUnsubscribe;
@@ -144,6 +254,78 @@ function originFromFetchInput(
}
}
+function hostLabel(origin: string | null): string {
+ if (!origin) {
+ return "Hugging Face";
+ }
+ try {
+ return new URL(origin).host;
+ } catch {
+ return origin;
+ }
+}
+
+/**
+ * Build a renderable failure. Drops the request URL: it carries the search query
+ * and can carry an internal hostname. Only the origin's host survives.
+ */
+export function classifyFetchFailure(
+ error: unknown,
+ origin: string | null,
+ options: { timedOut?: boolean } = {},
+): HubFailure {
+ const host = hostLabel(origin);
+ if (options.timedOut) {
+ return {
+ kind: "timeout",
+ message: `The request to ${host} timed out.`,
+ origin,
+ retryable: true,
+ };
+ }
+ if (isAbortError(error)) {
+ return {
+ kind: "aborted",
+ message: "The request was cancelled.",
+ origin,
+ retryable: true,
+ };
+ }
+ if (isNetworkFetchError(error)) {
+ if (isNavigatorOffline()) {
+ return {
+ kind: "browser-offline",
+ message: "This browser reports no network connection.",
+ origin,
+ retryable: true,
+ };
+ }
+ return {
+ kind: "network-opaque",
+ message: `The browser could not reach ${host}. A DNS or content filter, TLS-inspecting antivirus, a browser extension, or a CORS policy can all cause this, and the browser does not say which.`,
+ origin,
+ retryable: true,
+ };
+ }
+ return {
+ kind: "unknown",
+ message: `The request to ${host} failed.`,
+ origin,
+ 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
+ * search query, and on a private deployment the mirror's hostname.
+ */
+export function sanitizeHubErrorMessage(message: string): string {
+ if (!message) return message;
+ const cleaned = message.replace(/\.?\s*URL:\s*\S+(\.\s*Request ID:\s*\S+)?\.?\s*$/, "");
+ return cleaned.trim() || message;
+}
+
export async function fetchWithTimeout(
input: Parameters<typeof fetch>[0],
init: Parameters<typeof fetch>[1] = {},
@@ -173,13 +355,19 @@ export async function fetchWithTimeout(
}
return response;
} catch (error) {
- if (timedOut) {
- throw new Error("Request timed out");
+ // A superseded query must not blacklist the Hub or overwrite a diagnosis.
+ if (parentSignal?.aborted && !timedOut) {
+ throw error;
}
- if (origin && isNetworkFetchError(error)) {
- markRemoteNetworkOffline(origin);
+ const failure = classifyFetchFailure(error, origin, { timedOut });
+ // Connectivity failures only. A timeout is per-request, and the short ones
+ // belong to optional assets (avatar, README, dataset size), so one slow
+ // endpoint would take the whole origin down for 30s while the API was fine.
+ // The caller still gets the classified timeout and can retry at once.
+ if (origin && !timedOut && isNetworkFetchError(error)) {
+ markRemoteNetworkOffline(origin, REMOTE_OFFLINE_TTL_MS, failure);
}
- throw error;
+ throw new HubFetchError(failure, { cause: error });
} finally {
clearTimeout(timeout);
parentSignal?.removeEventListener("abort", abortFromParent);
diff --git a/studio/frontend/tests/hub-failure-panel-coverage.test.ts b/studio/frontend/tests/hub-failure-panel-coverage.test.ts
new file mode 100644
index 00000000000..994f49b11aa
--- /dev/null
+++ b/studio/frontend/tests/hub-failure-panel-coverage.test.ts
@@ -0,0 +1,42 @@
+// 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 test from "node:test";
+import { readFile } from "node:fs/promises";
+
+// The whole point of this change is that the panel names the cause. A kind the
+// renderer does not handle falls through to the generic wording, and because the
+// catalog blanks `message` whenever a failure exists, the classified text is not
+// shown anywhere else either. So every kind that can reach the panel must have a
+// case, and this is asserted against the type rather than a list, so adding a
+// kind without a branch fails here instead of silently degrading the panel.
+
+// A superseded request is never rendered: it is not a failure the user caused.
+const NOT_RENDERED = new Set(["aborted"]);
+
+function read(path: string): Promise<string> {
+ return readFile(new URL(path, import.meta.url), "utf8");
+}
+
+test("every renderable Hub failure kind has a branch in the panel", async () => {
+ const network = await read("../src/features/hub/lib/network.ts");
+ const decl = /export type HubFailureKind =([\s\S]*?);/.exec(network);
+ assert.ok(decl, "could not find HubFailureKind in network.ts");
+ const kinds = [...decl[1].matchAll(/"([a-z-]+)"/g)].map((m) => m[1]);
+ assert.ok(kinds.length >= 5, `parsed too few kinds: ${kinds.join(", ")}`);
+
+ const states = await read("../src/features/hub/catalog/catalog-states.tsx");
+ const start = states.indexOf("function describeFailure");
+ assert.notEqual(start, -1, "could not find describeFailure");
+ const body = states.slice(start, states.indexOf("\nexport function", start));
+
+ const missing = kinds.filter(
+ (kind) => !NOT_RENDERED.has(kind) && !body.includes(`case "${kind}":`),
+ );
+ assert.deepEqual(
+ missing,
+ [],
+ `these kinds fall through to the generic panel: ${missing.join(", ")}`,
+ );
+});
diff --git a/studio/frontend/tests/hub-network-availability.test.ts b/studio/frontend/tests/hub-network-availability.test.ts
new file mode 100644
index 00000000000..bfdeb00e862
--- /dev/null
+++ b/studio/frontend/tests/hub-network-availability.test.ts
@@ -0,0 +1,367 @@
+// 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 test from "node:test";
+import { readFile } from "node:fs/promises";
+
+import {
+ classifyFetchFailure,
+ clearRemoteBackoff,
+ fetchWithTimeout,
+ getHubPhase,
+ getBrowserOfflineRetryDelayMs,
+ getLastHubFailure,
+ isHuggingFaceOffline,
+ isHubFetchError,
+ isRemoteNetworkOffline,
+ markRemoteNetworkOffline,
+ markRemoteNetworkOnline,
+ sanitizeHubErrorMessage,
+} from "../src/features/hub/lib/network.ts";
+
+const HF = "https://huggingface.co";
+
+// Installing a window exercises the same event path the app uses, not the
+// no-op branch network.ts falls back to.
+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" },
+ };
+ return listeners;
+}
+
+function reset() {
+ installWindow();
+ markRemoteNetworkOnline();
+}
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+test("a lapsed backoff window means probing, never proven-available", async () => {
+ reset();
+ markRemoteNetworkOffline(HF, 10, {
+ kind: "network-opaque",
+ message: "blocked",
+ origin: HF,
+ retryable: true,
+ });
+ assert.equal(getHubPhase(HF), "unavailable");
+
+ await sleep(30);
+
+ // The old code flipped straight back to "online" here, fired a "Back online"
+ // toast, retried, failed, and looped. Only a successful request may promote.
+ assert.equal(
+ getHubPhase(HF),
+ "probing",
+ "TTL expiry must not be mistaken for a successful probe",
+ );
+});
+
+test("only a success clears the recorded failure", async () => {
+ reset();
+ markRemoteNetworkOffline(HF, 10, {
+ kind: "timeout",
+ message: "timed out",
+ origin: HF,
+ retryable: true,
+ });
+ await sleep(30);
+
+ assert.equal(
+ getLastHubFailure(HF)?.kind,
+ "timeout",
+ "the cause must outlive the backoff window or the panel goes generic",
+ );
+
+ markRemoteNetworkOnline(HF);
+ assert.equal(getLastHubFailure(HF), null);
+ assert.equal(getHubPhase(HF), "available");
+});
+
+test("Retry clears the backoff but keeps the diagnosis on screen", () => {
+ reset();
+ markRemoteNetworkOffline(HF, 60_000, {
+ kind: "network-opaque",
+ message: "could not reach",
+ origin: HF,
+ retryable: true,
+ });
+ assert.equal(getHubPhase(HF), "unavailable");
+
+ clearRemoteBackoff(HF);
+
+ assert.equal(
+ getHubPhase(HF),
+ "probing",
+ "Retry must be able to re-probe immediately, not wait out the timer",
+ );
+ assert.equal(getLastHubFailure(HF)?.kind, "network-opaque");
+});
+
+test("classification separates timeout, abort, offline and opaque failures", () => {
+ reset();
+ assert.equal(
+ classifyFetchFailure(new Error("x"), HF, { timedOut: true }).kind,
+ "timeout",
+ );
+
+ const abort = new DOMException("aborted", "AbortError");
+ assert.equal(classifyFetchFailure(abort, HF).kind, "aborted");
+
+ // No navigator.onLine === false in Node, so a bare TypeError stays opaque
+ // rather than being reported as a confirmed loss of connectivity.
+ const opaque = classifyFetchFailure(new TypeError("Failed to fetch"), HF);
+ assert.equal(opaque.kind, "network-opaque");
+ assert.match(opaque.message, /huggingface\.co/);
+ assert.match(opaque.message, /extension|antivirus|filter/i);
+});
+
+test("a browser reporting itself offline is named as such", () => {
+ reset();
+ const original = Object.getOwnPropertyDescriptor(globalThis, "navigator");
+ Object.defineProperty(globalThis, "navigator", {
+ value: { onLine: false },
+ configurable: true,
+ });
+ try {
+ assert.equal(
+ classifyFetchFailure(new TypeError("Failed to fetch"), HF).kind,
+ "browser-offline",
+ );
+ } finally {
+ if (original) Object.defineProperty(globalThis, "navigator", original);
+ else delete (globalThis as Record<string, unknown>).navigator;
+ }
+});
+
+test("the failure never leaks the request URL or its query", async () => {
+ reset();
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () => {
+ throw new TypeError("Failed to fetch");
+ }) as typeof fetch;
+ try {
+ await assert.rejects(
+ fetchWithTimeout(
+ `${HF}/api/models?search=my-private-project&author=acme`,
+ {},
+ 1_000,
+ ),
+ (err: unknown) => {
+ assert.ok(isHubFetchError(err), "should throw a classified HubFetchError");
+ const { message, origin } = err.failure;
+ assert.ok(
+ !message.includes("my-private-project"),
+ "the search query must never reach a rendered message",
+ );
+ assert.ok(!message.includes("/api/models"), "no request path in message");
+ assert.equal(origin, HF, "only the origin is retained");
+ return true;
+ },
+ );
+ } finally {
+ globalThis.fetch = original;
+ }
+});
+
+test("a caller-driven abort does not blacklist the origin", async () => {
+ reset();
+ const original = globalThis.fetch;
+ const controller = new AbortController();
+ globalThis.fetch = (async () => {
+ controller.abort();
+ throw new DOMException("aborted", "AbortError");
+ }) as unknown as typeof fetch;
+ try {
+ await assert.rejects(
+ fetchWithTimeout(`${HF}/api/models`, { signal: controller.signal }, 1_000),
+ );
+ assert.equal(
+ getHubPhase(HF),
+ "available",
+ "superseding a query must not mark the Hub unreachable",
+ );
+ assert.equal(getLastHubFailure(HF), null);
+ } finally {
+ globalThis.fetch = original;
+ }
+});
+
+test("a slow optional asset does not take the whole origin down", async () => {
+ reset();
+ const original = globalThis.fetch;
+ // Never resolves: fetchWithTimeout's own AbortController fires the timeout.
+ globalThis.fetch = ((_input: unknown, init: { signal?: AbortSignal }) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () =>
+ reject(new DOMException("aborted", "AbortError")),
+ );
+ })) as unknown as typeof fetch;
+ try {
+ await assert.rejects(
+ fetchWithTimeout(`${HF}/api/organizations/unsloth/avatar`, {}, 10),
+ (err: unknown) => {
+ assert.ok(isHubFetchError(err), "the caller still gets the diagnosis");
+ assert.equal(err.failure.kind, "timeout");
+ return true;
+ },
+ );
+ // The avatar, README and dataset-size fetches all use a 10s timeout against
+ // huggingface.co. Arming the 30s window here paused discovery and disabled
+ // the metadata and download controls while the API itself was reachable.
+ assert.equal(
+ getHubPhase(HF),
+ "available",
+ "one slow endpoint is not evidence the origin is unreachable",
+ );
+ assert.equal(getLastHubFailure(HF), null, "and records no origin-wide cause");
+ } finally {
+ globalThis.fetch = original;
+ }
+});
+
+test("a connectivity failure still does", async () => {
+ reset();
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () => {
+ throw new TypeError("Failed to fetch");
+ }) as typeof fetch;
+ try {
+ await assert.rejects(fetchWithTimeout(`${HF}/api/models`, {}, 1_000));
+ assert.equal(getHubPhase(HF), "unavailable", "this is the case worth backing off");
+ assert.equal(getLastHubFailure(HF)?.kind, "network-opaque");
+ } finally {
+ globalThis.fetch = original;
+ }
+});
+
+test("a successful response clears a prior failure", async () => {
+ reset();
+ markRemoteNetworkOffline(HF, 60_000, {
+ kind: "network-opaque",
+ message: "could not reach",
+ origin: HF,
+ retryable: true,
+ });
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () => new Response("{}", { status: 200 })) as typeof fetch;
+ try {
+ await fetchWithTimeout(`${HF}/api/models`, {}, 1_000);
+ assert.equal(getHubPhase(HF), "available");
+ assert.equal(getLastHubFailure(HF), null);
+ } finally {
+ globalThis.fetch = original;
+ }
+});
+
+test("an unrelated origin failing does not take the Hub down", () => {
+ reset();
+ markRemoteNetworkOffline("https://datasets-server.huggingface.co", 60_000, {
+ kind: "network-opaque",
+ message: "dataset viewer down",
+ origin: "https://datasets-server.huggingface.co",
+ retryable: true,
+ });
+ assert.equal(
+ getHubPhase(HF),
+ "available",
+ "a datasets-server outage must not make the model hub look offline",
+ );
+});
+
+test("the SDK's URL trailer never survives into a rendered message", () => {
+ // Exact shape from @huggingface/hub createApiError: message, then
+ // ". URL: <url>. Request ID: <id>".
+ const raw =
+ "Api error with status 502. URL: https://huggingface.co/api/models?search=my-private-project&limit=100. Request ID: abc123";
+ const clean = sanitizeHubErrorMessage(raw);
+ assert.ok(
+ !clean.includes("my-private-project"),
+ "the search query must not reach the screen",
+ );
+ assert.ok(!clean.includes("URL:"), "no URL trailer");
+ assert.equal(clean, "Api error with status 502");
+});
+
+test("sanitizing leaves a message with no trailer alone", () => {
+ assert.equal(sanitizeHubErrorMessage("Search failed"), "Search failed");
+ assert.equal(sanitizeHubErrorMessage(""), "");
+});
+
+test("the cause on screen describes the window that is in force", async () => {
+ markRemoteNetworkOnline();
+ const live = {
+ kind: "network-opaque" as const,
+ message: "boom",
+ origin: HF,
+ retryable: true,
+ };
+ markRemoteNetworkOffline(HF, 30_000, live);
+
+ // A concurrent request records a second cause with no window of its own.
+ // Taking that cause while keeping the longer window left the panel naming a
+ // spent failure while a different, still-live one held it unavailable.
+ markRemoteNetworkOffline(
+ HF,
+ 0,
+ { kind: "timeout", message: "timed out", origin: HF, retryable: true },
+ );
+ assert.equal(getHubPhase(HF), "unavailable");
+ assert.equal(
+ getLastHubFailure(HF)?.kind,
+ "network-opaque",
+ "the older answer must not explain a newer failure's backoff",
+ );
+ markRemoteNetworkOnline();
+});
+
+
+test("a generator that threw is not pulled again", async () => {
+ // @huggingface/hub awaits the fetch inside the generator body, so a failed
+ // page finishes the generator and every later next() resolves done. The
+ // auto-fill then cleared the error with it, which undoes the whole point of
+ // keeping the failure on screen.
+ let requests = 0;
+ async function* listing() {
+ for (const page of [1, 2]) {
+ requests += 1;
+ if (page === 2) throw new Error("Failed to fetch");
+ yield page;
+ }
+ }
+ const iter = listing();
+ assert.deepEqual(await iter.next(), { value: 1, done: false });
+ await assert.rejects(iter.next());
+ assert.equal((await iter.next()).done, true, "it is finished once it throws");
+ assert.equal(requests, 2, "reusing it issues no request, so done is a lie");
+
+ const src = await readFile(
+ new URL("../src/features/hub/hooks/use-hub-paginated-search.ts", import.meta.url),
+ "utf8",
+ );
+ // Set on the failure path, cleared only where a new generator is built.
+ assert.match(src, /iterDeadRef\.current = true;/);
+ assert.match(src, /iterRef\.current = iter;\s*\n\s*iterDeadRef\.current = false;/);
+ const at = src.indexOf("const fetchMore = useCallback");
+ assert.notEqual(at, -1);
+ const guard = src.slice(at, src.indexOf("const iter = iterRef.current;", at));
+ assert.match(guard, /if \(iterDeadRef\.current\) \{/);
+ assert.ok(
+ guard.slice(guard.indexOf("if (iterDeadRef.current) {")).includes("return false;"),
+ "a dead feed starts nothing, so its error survives",
+ );
+});
diff --git a/studio/frontend/tests/hub-recovery-paths.test.ts b/studio/frontend/tests/hub-recovery-paths.test.ts
new file mode 100644
index 00000000000..a46d13bc5f0
--- /dev/null
+++ b/studio/frontend/tests/hub-recovery-paths.test.ts
@@ -0,0 +1,225 @@
+// 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 test from "node:test";
+import { readFile } from "node:fs/promises";
+
+// Making a lapsed backoff mean "probing" fixed the flapping, but "probing" only
+// clears when a *listing* succeeds. Anything else gated on it, or on the dead
+// iterator that a failed page leaves behind, has to keep a way back on its own.
+
+function read(path: string): Promise<string> {
+ return readFile(new URL(path, import.meta.url), "utf8");
+}
+
+/** A callback body, so a dependency array cannot satisfy an assertion. */
+function body(source: string, start: string, end: string): string {
+ const at = source.indexOf(start);
+ assert.notEqual(at, -1, `could not find ${start}`);
+ const to = source.indexOf(end, at);
+ assert.ok(to > at, `could not find ${end} after ${start}`);
+ return source.slice(at, to);
+}
+
+test("clients with their own request keep their own reachability", async () => {
+ const page = await read("../src/features/hub/hub-page.tsx");
+ // This value reaches useHubFeed and, through useModelsSelection, the selected
+ // model's metadata lookup. Those are independent requests: on the discovery
+ // phase they stayed blocked at "probing" until a listing succeeded, and the
+ // Downloaded tab has no Retry to make one happen.
+ assert.match(page, /const online = useOnlineStatus\(\);/);
+ assert.ok(
+ !/useHubAvailability\(\)\.phase/.test(page),
+ "the feed's phase must not gate a client that never runs a listing",
+ );
+});
+
+test("the panel still reads the classified cause, not that boolean", async () => {
+ const page = await read("../src/features/hub/hub-page.tsx");
+ // Reverting `online` must not quietly revert the diagnosis with it: the panel
+ // is driven by searchFailure, which useDiscoverSearch reads off the phase.
+ assert.match(page, /searchFailure,/);
+ const search = await read("../src/features/hub/hooks/use-discover-search.ts");
+ assert.match(search, /const \{ phase, failure \} = useHubAvailability\(\);/);
+ assert.match(search, /const online = phase === "available";/);
+});
+
+test("a dead feed is restarted by Load more, not left inert", async () => {
+ const search = await read("../src/features/hub/hooks/use-discover-search.ts");
+ const fn = body(search, "const fetchMore = useCallback", "\n }, [");
+ // hasMore is kept so the footer survives the failed page, so the button stays
+ // on screen. Without this it called a fetchMore that returned false forever.
+ assert.ok(fn.includes("needsRestart()"), "it has to notice the dead iterator");
+ assert.ok(fn.includes("retrySearch()"), "and rebuild rather than resume");
+ // Not on `online`: that is `phase === "available"`, which a lapsed backoff
+ // never reaches without a successful listing, so the restart could never run.
+ assert.ok(fn.includes("canProbe"), "a lapsed backoff must be allowed to probe");
+ assert.match(search, /const canProbe = phase !== "unavailable";/);
+});
+
+test("the restart is not allowed to defeat the backoff", async () => {
+ const search = await read("../src/features/hub/hooks/use-discover-search.ts");
+ const fn = body(search, "const fetchMore = useCallback", "\n }, [");
+ // Only the explicit Retry clears the window. Clearing it from a path the
+ // scroll observer can reach would re-probe a dead origin on every scroll.
+ assert.ok(!fn.includes("clearRemoteBackoff"), "the auto path must not clear it");
+ const retry = body(search, "const handleRetrySearch = useCallback", "\n }, [");
+ assert.ok(retry.includes("clearRemoteBackoff()"), "an explicit click does");
+});
+
+test("rows on screen do not hide that the feed failed", async () => {
+ const lists = await read("../src/features/hub/catalog/models-catalog-lists.tsx");
+ // A cached feed substituted after a failed refresh renders rows with
+ // hasMore false, which skipped the footer and the panel alike: once the toast
+ // went there was nothing on screen saying so and nothing left to click.
+ assert.match(lists, /\{\(hasMore \|\| searchError \|\| searchFailure\) && \(/);
+ const footer = body(lists, "<DiscoverFetchMoreFooter", "/>");
+ assert.ok(footer.includes("failed={Boolean(searchError || searchFailure)}"));
+ assert.ok(footer.includes("onRetry={onRetry}"));
+
+ const states = await read("../src/features/hub/catalog/catalog-states.tsx");
+ // To the next declaration: the prop destructuring contains a "\n}" of its own.
+ const fn = body(
+ states,
+ "export function DiscoverFetchMoreFooter",
+ "\nexport function InventoryErrorState",
+ );
+ assert.ok(fn.includes('failed && onRetry ? onRetry : onFetchMore'), "it must retry");
+ assert.ok(fn.includes('failed ? "Try again" : "Load more"'), "and say so");
+});
+
+test("a live backoff is not bypassed by typing", async () => {
+ const search = await read("../src/features/hub/hooks/use-discover-search.ts");
+ // Ungating `enabled` is what let the error reach the panel, but it also let a
+ // changed query, sort or channel build a new iterator and fire immediately.
+ // Each attempt failed and re-armed the 30s window, so it never elapsed.
+ // Either term does it. The dataset hook splits them because its `enabled`
+ // also empties the rendered rows; `paused` holds the request on its own.
+ for (const m of search.matchAll(/enabled: ([^,\n]+),/g)) {
+ const gate = m[1].includes("canProbe") || search.includes("paused: !canProbe");
+ assert.ok(gate, `an automatic search must respect the live backoff: ${m[1]}`);
+ }
+ // Only "unavailable" holds it: gating on `online` would never let a lapsed
+ // window re-probe, since that requires a listing to have already succeeded.
+ assert.match(search, /const canProbe = phase !== "unavailable";/);
+});
+
+test("gating the search again does not re-hide the error", async () => {
+ // This is only safe because the disabled path stopped clearing it. Pin both
+ // halves together: restoring the null would silently undo the whole fix.
+ const paginated = await read(
+ "../src/features/hub/hooks/use-hub-paginated-search.ts",
+ );
+ const disabled = body(paginated, "if (!enabled) {", "\n // Same query");
+ assert.ok(!/error: null/.test(disabled), "disabling must not erase the cause");
+ const search = await read("../src/features/hub/hooks/use-discover-search.ts");
+ assert.match(search, /const searchError = isDiscoverTab \? rawSearchError : null;/);
+});
+
+test("a footer retained over an outage can still act", async () => {
+ const lists = await read("../src/features/hub/catalog/models-catalog-lists.tsx");
+ const footer = body(lists, "<DiscoverFetchMoreFooter", "/>");
+ // An avatar or card failure marks the same origin, so the listing keeps its
+ // rows and no searchError, and useHubInfiniteScroll is gated on `online`:
+ // the button rendered enabled and did nothing for the whole window.
+ assert.ok(
+ footer.includes("failed={Boolean(searchError || searchFailure)}"),
+ "unreachable is as good a reason to offer a re-probe as a failed page",
+ );
+ // And the same condition has to reach the render, or the prop is decorative:
+ // with pagination exhausted, hasMore is false and no searchError is recorded,
+ // so on `(hasMore || searchError)` the footer never appeared at all.
+ assert.ok(
+ lists.includes("{(hasMore || searchError || searchFailure) && ("),
+ "an exhausted listing still has to show the outage",
+ );
+});
+
+test("the retained footer names the cause, not just the staleness", async () => {
+ const lists = await read("../src/features/hub/catalog/models-catalog-lists.tsx");
+ const footer = body(lists, "<DiscoverFetchMoreFooter", "/>");
+ // This footer outlives the toast, so it is where the diagnosis has to live.
+ // Reducing it to "out of date" threw away the thing this change exists for.
+ assert.ok(
+ footer.includes("failureText={searchFailure?.message ?? searchError ?? \"\"}"),
+ "the classified cause has to reach the one control that persists",
+ );
+ const states = await read("../src/features/hub/catalog/catalog-states.tsx");
+ const fn = body(
+ states,
+ "export function DiscoverFetchMoreFooter",
+ "\nexport function InventoryErrorState",
+ );
+ assert.ok(
+ fn.includes('{failureText || "These results may be out of date."}'),
+ "shown when there is one, with the generic line only as a fallback",
+ );
+});
+
+test("the notice outlives the backoff window, not the other way round", async () => {
+ const lists = await read("../src/features/hub/catalog/models-catalog-lists.tsx");
+ // `online` is the 30s TTL. It flips back on a timer with nothing proven, so
+ // the notice and its Retry disappeared while getHubPhase() still said
+ // "probing" and searchFailure still held the cause. Keying on the cause ties
+ // the notice to what clears it: a request that worked.
+ const footer = body(lists, "<DiscoverFetchMoreFooter", "/>");
+ assert.ok(!/failed=\{[^}]*!online/.test(footer), "a timer must not retire it");
+ assert.ok(
+ !/\{\(hasMore \|\| searchError \|\| !online\) && \(/.test(lists),
+ "nor take the whole footer off screen",
+ );
+ // And the cause is only cleared by markRemoteNetworkOnline, which only
+ // fetchWithTimeout calls, and only on a resolved response.
+ const network = await read("../src/features/hub/lib/network.ts");
+ const online = body(network, "export function markRemoteNetworkOnline", "\nexport function markRemoteNetworkOffline");
+ assert.ok(online.includes("lastFailureByOrigin.delete(origin)"), "success clears it");
+ const fetchFn = body(network, "export async function fetchWithTimeout", "\n } catch");
+ assert.ok(fetchFn.includes("markRemoteNetworkOnline(origin)"), "on a response");
+});
+
+test("a row the mapper rejects is not treated as an outage", async () => {
+ const paginated = await read(
+ "../src/features/hub/hooks/use-hub-paginated-search.ts",
+ );
+ // next() already handed the item over, so the generator is fine. Letting the
+ // throw out reached the same catch as a network error, which set iterDeadRef
+ // and made needsRestart() true; every restart then re-read the same page and
+ // hit the same row, so the feed could not get past it.
+ const pull = body(paginated, " let scanned = 0;", "\n return { items, done: false");
+ assert.ok(pull.includes("try {"), "the mapper call has to be guarded");
+ assert.ok(pull.includes("mapped = mapItem(result.value);"), "inside the loop");
+ assert.ok(pull.includes("continue;"), "and a bad row skipped, like a null one");
+ // Only the mapper is inside it: widening the try to cover the await would
+ // swallow the real network error this dead-iterator machinery exists for.
+ const guarded = body(pull, "try {", "} catch");
+ assert.ok(!guarded.includes("iter.next()"), "next() stays outside the guard");
+ assert.ok(!guarded.includes("result.done"), "and so does the done check");
+});
+
+test("pausing dataset fetches leaves the rendered rows alone", async () => {
+ const datasets = await read(
+ "../src/features/hub/hooks/use-hub-dataset-search.ts",
+ );
+ // This hook's `enabled` does double duty: it gates the request AND returns []
+ // from the results memo, so gating it on the backoff blanked every visible
+ // dataset row for the window. The model hook has no such line, which is why
+ // only datasets went blank.
+ assert.match(datasets, /if \(!enabled\) return \[\];/);
+ assert.ok(
+ datasets.includes("enabled: enabled && !paused"),
+ "the pause has to reach the request and stop there",
+ );
+
+ const search = await read("../src/features/hub/hooks/use-discover-search.ts");
+ const call = body(search, "const datasetSearch = useHubDatasetSearch", "\n });");
+ assert.ok(
+ call.includes("enabled: isDiscoverTab && isDatasetMode"),
+ "visibility is what `enabled` means here",
+ );
+ assert.ok(call.includes("paused: !canProbe"), "the backoff goes to `paused`");
+ // The model hook keeps the single gate: without the blanking memo there is
+ // nothing to split, and folding it in would be a behaviour change.
+ const model = body(search, "const modelSearch = useHubModelSearch", "\n });");
+ assert.ok(model.includes("enabled: canProbe &&"), "models are gated as before");
+});