Skip to content

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

Merged
danielhanchen merged 73 commits into
mainfrom
fix/hub-offline-diagnostics
Aug 6, 2026
Merged

danielhanchen merged 73 commits into
mainfrom
fix/hub-offline-diagnostics

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Problem

Reported on r/unsloth: the Model hub sits permanently on "You're offline - Reconnect to the internet to browse models from Hugging Face", occasionally flashing "Back online" and going straight back, on a Windows 10 machine that is online. Fresh install, v0.1.511-beta. The user spent hours on it because nothing in the UI said what was actually wrong.

Discovery is a direct cross-origin browser fetch to huggingface.co (use-hub-model-search.ts, via @huggingface/hub listModels). Anything that stops the browser reaching the Hub - a DNS or content filter, TLS-inspecting antivirus, an extension, a CSP - arrives as an opaque TypeError, and Studio reported all of them as loss of internet connectivity.

Their blocker is local, and no code change makes a blocked host reachable. Two defects made it undiagnosable.

1. Every failure rendered identically. The first failed fetch blacklisted the origin for 30s. That flipped online false, which disabled the search hook, which cleared the error explaining the failure. models-catalog-lists.tsx then fell back to a hardcoded "Discovery is unavailable while offline." The branch that would have shown the real error was unreachable for connectivity failures, because the same first failure both set the error and disabled the hook.

2. The offline/online flapping. use-online-status.ts treated a lapsed backoff window as proof the Hub was reachable. It announced "Back online", retried, failed, and blacklisted again, forever.

Changes

The failure survives to the panel. Three places had to change together or it was still gone by render time: use-hub-paginated-search.ts no longer nulls error when disabled, use-discover-search.ts no longer gates enabled or searchError on availability, and the catalog renders the classified cause instead of the hardcoded offline line.

Only a browser that reports itself offline gets "You're offline". network.ts classifies a failure as timeout / aborted / browser-offline / network-opaque and throws a HubFetchError carrying a sanitized cause. An opaque TypeError is now labelled honestly: "The browser could not reach huggingface.co. 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." That is the sentence the reporter needed.

No more flapping. A lapsed backoff yields a probing phase rather than a fabricated "available", so only a successful response announces recovery. Retry always re-probes instead of refusing while the backoff is open, so a firewall, DNS or certificate change can be tested immediately rather than after waiting out a timer.

Redaction. The error is rendered now, so the SDK's URL: ... Request ID: ... trailer is stripped before display: it carries the user's search query.

A failed page is not silently resumed. @huggingface/hub's generators await the fetch inside the generator body, so a page that throws finishes the generator and every later next() resolves done with no request. The auto-fill would pull it again and clear the error along with it, undoing the fix 30 seconds later. A dead feed is restarted rather than resumed, and Load more stays live so the user is not left with an inert button.

Clients with their own reachability are not gated on the feed's. The selected model's metadata lookup is an independent request, so it asks whether the browser can reach the Hub rather than whether the discovery feed has succeeded since its last failure. Gating it on the feed left the Downloaded tab, which has no discovery Retry, unable to load metadata at all.

Scope

This is the reported bug and nothing else. A backend discovery proxy and HF_ENDPOINT mirror support were built on this branch and have been dropped: they were never likely to help the reporter, whose block reaches the Python backend as readily as the browser.

One consequence, stated rather than left to be found: with a single backoff window per origin, a failed avatar or repo-card fetch can put a cause on the catalog panel that came from an asset request. That same event renders "You're offline" today, so it is not a regression, and the named cause is still the more useful of the two.

No backend files are touched.

Tests

node:test. There was no coverage of network.ts, use-online-status.ts or use-discover-search.ts before this.

  • classification of timeout vs caller abort vs navigator.onLine vs opaque TypeError
  • a lapsed window is probing, never proven-available, and only a success clears the recorded cause
  • Retry clears the backoff but keeps the diagnosis on screen
  • redaction: no request URL, query or SDK trailer reaches a rendered message
  • a caller-driven abort does not blacklist the origin, and an unrelated origin failing does not take the Hub down
  • every renderable failure kind has a branch in the panel
  • a thrown generator resolves done without a request, so the fetch path refuses it and the manual control restarts instead

danielhanchen and others added 2 commits August 4, 2026 09:28
…he server

The Model hub could sit permanently on "You're offline" while flapping to
"Back online" and straight back, on machines that were online. Discovery is a
direct cross-origin browser fetch to huggingface.co, so anything blocking the
browser (DNS or content filter, TLS-inspecting antivirus, an extension, CSP)
produced an opaque TypeError that was reported as loss of internet.

Three problems, all fixed here.

1. Every failure looked identical. The first failed fetch blacklisted the
   origin for 30s, which disabled the search hook, which cleared the error that
   explained the failure, so the catalog fell back to a hardcoded
   "Discovery is unavailable while offline." The branch that would have shown
   the real cause was unreachable for connectivity failures.

   Failures are now classified (timeout / aborted / csp-blocked /
   browser-offline / network-opaque), survive the backoff window, and are
   rendered. A securitypolicyviolation listener names CSP blocks, the one class
   a browser will identify. Messages keep only the origin host, never the
   request URL, which carries the search query.

2. The flapping. A lapsed backoff was treated as proof the Hub was reachable,
   firing "Back online" and a retry that failed again. It now yields a probing
   state; only a successful response announces recovery. Retry also always
   re-probes instead of refusing while the backoff is open.

3. No way through. Added GET /api/hub/discovery/{models,datasets}, used only
   after a transport failure, never after a real HTTP status. The destination
   comes from hf_endpoint_url() server-side and cannot be influenced by the
   request, the query is rebuilt from an allowlist, redirects are refused, and
   size and timeout are bounded. Upstream 401/403 maps to 424: passing it
   through would hit authFetch's 401 handler and log the user out of Studio.

This also makes HF_ENDPOINT mirrors work. The frontend hardcoded huggingface.co
while the backend was endpoint-aware, so a mirror looked permanently offline.
hub_endpoint now ships in the authed /api/health payload and a non-official
endpoint uses the proxy from the first request, which is what lets mirrors work
on desktop, where the Tauri CSP is fixed at build time.

Tests: 16 new frontend (node:test), 31 new backend (pytest).
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 4, 2026 11:11
…avigator veto

Five fixes from review of the discovery fallback.

Model-info requests were retargeted at the listing proxy. makeHfFetch is passed
to cachedModelInfo, and toProxyRequest kept only the query, so on fallback
/api/models/{repo}/revision/HEAD became the /api/models listing and the SDK
parsed an array as one repo, caching a model with no id. The transport now
proxies only URLs whose path is exactly /api/{resource}; anything else stays on
the direct route.

Proxy pagination stopped after one page. The Hub SDK's parseLinkHeader only
matches an http(s) target, so the relative Link the route emitted yielded no
next. The route now builds it from request.base_url, and isProxyUrl matches on
pathname so the absolute link is still recognised as already proxying.

A successful fallback left the Hub marked unavailable. fetchWithTimeout records
the direct failure before throwing and nothing cleared it, so the catalog
refused to paginate and rendered fallback results as a connection error. The
backend path now clears the origin's failure, but only when the response is ok,
so a failing proxy keeps the diagnosis.

browser-offline no longer vetoes the fallback. navigator.onLine is advisory and
reads false on WSL2 and some Tauri/WebKitGTK webviews, which network.ts already
documents; letting it gate the fallback made the one untrusted signal
authoritative.

The offline panel no longer echoes the raw SDK error. createApiError appends
"URL: <url>", which carries the user's search query.

Also bind the discovery_router re-export so the import-hoist verifier counts it
as used, matching routes/__init__.py.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 4, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…rror trailer

Preserved results could not retry. Keeping rows on screen when the Hub goes
unavailable left Load more gated on `online`, and the phase only leaves probing
on a success, so that footer was the only request the view could make and it
refused to make it. Load more now proceeds once the backoff has lapsed; the
unavailable window still blocks it.

A mirror emitting an RFC 8288 relative next target had its link dropped. The
same-origin check ran on the unresolved value, so an empty scheme and authority
never matched and mirror pagination stopped after the first page. The target is
resolved against HF_ENDPOINT first; an absolute off-endpoint link is still
rejected.

The proxy-first path leaked the SDK's URL trailer. With a mirror the listing
goes through the backend, so an upstream HTTP error records no classified
failure and the raw message, which ends in "URL: <full request url>", reached
both the toast and the catalog. It is now sanitized where it enters our state,
which covers every render path rather than one branch.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 4, 2026 12:02
…eam reads

With HF_ENDPOINT set to a mirror, model-info still went to the public Hub. The
SDK builds those URLs on huggingface.co and the listing-only guard sent them
straight out, so a mirror user's repo ids and Authorization token reached the
wrong service, and if that origin is blocked the pinned and priority lookups
were silently dropped instead.

Adds GET /api/hub/discovery-info/{resource}, which keeps the repo path the
listing route discards. The repo is checked with is_valid_repo_id and the
revision against a conservative pattern, then both are re-encoded rather than
forwarded, and only expand is accepted so this cannot become a second listing
route. The transport uses it only when a mirror is configured or after a
fallback; otherwise model-info stays direct as before.

Also bound the streaming read. requests' timeout limits inactivity between
chunks, not total duration, so an upstream drip-feeding within the window could
hold a worker thread well past _REQUEST_TIMEOUT_SECONDS. The read loop now
tracks a monotonic deadline and returns 504.

The model-info test now asserts what it always meant, that such a request never
reaches the listing route, rather than that it never reaches the backend.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The URL trailer was stripped in useDiscoverSearch, but useHubModelSearch and
useHubDatasetSearch feed the training and dataset pickers too, and those render
the hook error raw. On a proxied request Response.url is our own route carrying
the user's search query, so a blocked or mirror user could see it there.

Moved into useHubPaginatedSearch, at the single point the message becomes state.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Clearing the huggingface.co failure on a successful fallback said the browser
could reach the Hub when only the backend had. useOnlineStatus() then re-enabled
the direct clients, the README and owner-avatar fetches, which failed against the
still-blocked origin and marked it unavailable again, recreating the flapping in
exactly the environments the fallback exists for.

The transport now records that the backend is serving us and leaves the origin
state alone. getHubPhase reports available while that holds, so the catalog uses
the proxied feed, and isHuggingFaceOffline stays origin-based so the direct
clients remain suppressed. The hub page follows content availability rather than
browser reachability.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

An HF_ENDPOINT written with a different case or an explicit default port is the
same origin, but the raw netloc comparison treated the mirror's canonical next
link as off-endpoint and dropped it, stopping proxy pagination after one page.
Scheme, host and effective port are compared instead.
tests/studio/test_model_picker_contracts.py pins the exact call text in
chat-api, and this branch predated that file, so the rename only failed once CI
merged with main. The contract is unchanged: the caller still hands its options
to the builder. What it names is now shouldPreferLocalCache, because the request
goes to our own backend and a proxy already serving discovery proves the server
can reach the Hub.
# Conflicts:
#	tests/studio/test_model_picker_contracts.py
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 6, 2026 09:16
…s back

Six review findings from the last round.

Frontend:
- A README that fell back to the backend set the origin-wide directHubBlocked
  flag, so a filter on /raw pushed the listing, avatars and dataset sizes onto
  the proxy too. It now records a card-scoped flag instead.
- hubProxyFirst compared origins, so a mirror mounted on the Hub's own host
  (HF_ENDPOINT=https://huggingface.co/hf) was taken for the default and fetched
  direct, reading the wrong repo. The comparison now includes the path.
- The auto-fill kept pulling a generator that had already thrown. That pull
  returns done, which clears the error and drops hasMore, so the failure
  disappeared and the list silently ended. Only a restart resumes now.

Backend:
- Timed-out fetches are left running, since a thread cannot be cancelled. They
  ran on the loop's shared executor, where a stalled resolver starved every
  other asyncio.to_thread user in the process. They get their own bounded pool.
- The card proxy asked for application/json on a /raw path, which a
  content-negotiating mirror may answer with 406 or with JSON.
- A 200 whose JSON was the wrong shape (an error object, an SSO page) was
  passed on as a working feed and threw inside the SDK's iteration. Listings
  must be arrays and repo lookups objects.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The proxy and the HF_ENDPOINT mirror support it carries are a separate change
from the diagnosis fix, and they are the part that keeps growing: every round
turns up another direct fetch that has to be routed through it. They go in a
follow-up so this PR is the state-machine and panel fix on its own.

Removes studio/backend/hub/routes/discovery.py and its tests, and restores
hub/routes/__init__.py, hub/dependencies.py and main.py to upstream.
The other half of the same split. What is left is the diagnosis fix on its own:
the failure taxonomy, the CSP correlation, the per-feed backoff windows and the
phase machine that stops a lapsed window claiming the Hub is reachable, plus the
panel that names the cause.

Removes hub-transport.ts, hub-endpoint.ts, endpoint-key.ts and their tests, and
restores the search hooks, hf-readme, use-selected-model-metadata, env.ts,
use-hf-dataset-splits, hub-token-header and the picker contract to upstream.
The proxy-served flags come out of network.ts, so shouldPreferLocalCache and
useBackendHubOnline go back to isHuggingFaceOffline and useOnlineStatus.

The "http" failure kind goes with them: hub-transport was its only producer, so
keeping it would leave a branch in the panel that nothing can reach.
hf-readme keeps its service: "other" tag, which belongs to the panel half - a
filter can block /raw alone, and the card's failure must not name the catalog.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ur own recovery

Two findings from the round on the reduced diff.

cachedModelInfo runs in parallel with listModels and went through makeHfFetch,
which left it on the feed's own key. Its response, a 404 included, then called
markRemoteNetworkOnline and deleted the listing's failure and backoff: the panel
lost the classified cause and the phase read available while the listing was
still blocked, which is the generic-panel bug arriving by another door. A repo
lookup is not the listing, so it is tagged "other" like the card and the avatar.
makeSortFetch, which is what listModels is handed, keeps "discovery".

The reconnect effect refreshed the feed whenever availability was restored, but
the request that restores it is usually the feed's own retry. That fired a second
retrySearch, discarding the results that had just arrived and re-issuing the same
call. It now tracks whether this feed was the one probing and only refreshes when
another surface proved the Hub reachable. The announcement is unconditional.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Tagging cachedModelInfo "other" stopped it retiring the listing's diagnosis but
handed it the asset clients instead: a 15s timeout on the pinned-publisher
lookup blanked every card and avatar for 30s, over a request whose rejection
mergedModelIterator catches and nobody waits on.

It gets "info" of its own. Retry still sweeps it, since a window no reset can
touch would sit out its full TTL and keep delaying the wake timer, but the
origin-wide reachability question reads GATING_SERVICES and skips it: a lookup
no client is waiting on must not answer "can this browser reach the Hub".
# Conflicts:
#	studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx
#	studio/frontend/src/features/hub/hooks/use-hub-infinite-scroll.ts
#	studio/frontend/src/features/hub/hub-page.tsx
#	studio/frontend/src/features/hub/index.ts
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The proxy is out for good, and so is everything that only existed to keep it
honest. What is left is the two defects behind the report.

Dropped: the securitypolicyviolation listener and the "csp-blocked" kind, the
per-feed service keying and every gate built on it, the Load-more-while-probing
work, and the changes to the repo card, avatars, dataset sizes, dataset splits
and the model picker. Those files are back at upstream.

One consequence, stated rather than papered over: with a single window per
origin, a failed avatar or repo-card fetch can put a cause on the catalog panel
that came from an asset request. That same event renders "You're offline" today,
so it is not a regression, and the panel is still the more useful of the two.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Making a lapsed backoff mean "probing" fixed the flapping, but "probing" only
clears when a listing succeeds, and a failed page leaves a closed generator
behind. Three things were stranded by that.

The selected model's metadata lookup and the cached feed each issue their own
request, and hub-page was gating both on the discovery phase. Neither can make a
listing succeed, and the Downloaded tab has no Retry, so metadata for an
on-device model never loaded. They are back on browser reachability, which is
what they actually ask about; the panel still reads the classified cause.

Load more stayed on screen after a failed page, since hasMore is deliberately
kept, but called a fetchMore that returned false forever. It now restarts the
feed rather than resuming a generator that is finished. Allowed while probing,
which is exactly when the next page should test the network, and never while the
backoff is live, so only the explicit Retry clears a window.

A cached feed substituted after a failed refresh rendered rows with hasMore
false, which skipped the footer and the panel alike: once the toast went there
was nothing saying the results were stale and nothing left to click. The footer
now survives an error and offers Try again.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ause

Ungating the search hook is what let the error reach the panel, but it also
meant a changed query, sort or channel built a new iterator and fired straight
away. Typing through an outage issued a request per debounce tick, each failing
and re-arming the 30s window, so it never elapsed. Automatic searches are gated
on the live backoff again, which is safe now only because the disabled path
stopped clearing `error`. Gated on "unavailable" alone, never on `online`: a
lapsed window has to be allowed to probe, and reaching "available" requires a
listing to have already succeeded.

The retained footer had the same shape of problem from the other direction. A
failed avatar or repo card marks the same origin, so the listing keeps its rows
and records no error of its own, and useHubInfiniteScroll is gated on `online`:
the Load more button rendered enabled and did nothing for the whole window. It
now offers a re-probe whenever it cannot fetch, not just after a failed page.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two gaps in the retained footer from the last round.

The `failed` prop was reached only when `hasMore` or a `searchError` already put
the footer on screen. With pagination exhausted and the outage coming from an
avatar or repo card, neither holds, so there was no notice and no control at
all. `!online` joins the render condition, not just the prop.

And the footer reduced everything to "These results may be out of date". This is
the persistent surface once the toast closes, so that threw away the classified
cause, which is the thing this change exists to keep. It now shows the sanitized
failure text, with the generic line only as a fallback.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…om stranding recovery

The footer keyed on the 30s backoff TTL, which lapses on a timer with nothing
proven, so the notice and its Retry vanished while the phase was still probing.
Key it on the recorded cause, which only a successful request clears.

pullBatch called mapItem outside any guard, so a malformed row reached the catch
that marks the iterator dead. The item was already consumed and the generator
still usable, and every restart hit the same row again. A throw now skips the
row, like the null the mapper already returns for one.

useHubDatasetSearch's enabled also empties its results memo, so gating it on the
backoff blanked every rendered dataset row for the window. Split the two: enabled
still means the tab is showing, and a new paused holds only the request.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ddf2f28e3e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +363 to +364
if (origin && (timedOut || isNetworkFetchError(error))) {
markRemoteNetworkOffline(origin, REMOTE_OFFLINE_TTL_MS, failure);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid blacklisting the Hub for ancillary timeouts

When a same-origin request merely exceeds its local timeout—for example, the 10-second owner-avatar or README requests in hf-owner-avatar.ts and hf-readme.ts—the new timedOut arm marks all of huggingface.co unavailable for 30 seconds. A slow optional asset endpoint therefore pauses discovery and disables metadata/download controls even when the main Hub API remains reachable; previously the timeout branch threw without changing origin-wide availability. Only connectivity failures, or timeouts explicitly associated with a reachability probe, should blacklist the whole origin.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in eb460a5. Checked against origin/main: its timeout branch threw before reaching markRemoteNetworkOffline, so adding timedOut || to that condition was a behaviour change, not a carry-over. And the three ancillary call sites you name all pass 10s (AVATAR_FETCH_TIMEOUT_MS, README_FETCH_TIMEOUT_MS, FETCH_TIMEOUT_MS) against huggingface.co, against 15s for the listing, so the optional assets were the ones most likely to arm the window.

The condition is now !timedOut && isNetworkFetchError(error). The caller still gets the classified timeout failure, so a timing-out listing surfaces its own message and Retry through searchError with no backoff to wait out. Regression tests both ways in hub-network-availability.test.ts: a timeout leaves the phase available and records no origin-wide cause, an opaque network error still marks it unavailable.

The avatar, README and dataset-size fetches all run a 10s timeout against
huggingface.co. Treating a timeout as evidence the origin is down meant one slow
optional endpoint armed the 30s window, which paused discovery and disabled the
metadata and download controls while the API itself was reachable. Timeouts are
per-request, so the caller keeps the classified failure and can retry at once;
only an opaque network error still backs the origin off.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: eb460a53b1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants