Skip to content

feat(studio): Hub + Download Manager - #5916

Merged
danielhanchen merged 37 commits into
unslothai:mainfrom
Sneakr:feat/hub-clean
Jun 9, 2026
Merged

danielhanchen merged 37 commits into
unslothai:mainfrom
Sneakr:feat/hub-clean

Conversation

@Sneakr

@Sneakr Sneakr commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator

Adds a new /hub route that consolidates model and dataset browsing, discovery, and on-device inventory under a single surface. Replaces the abandoned model-hub branch (PR #5783) with a clean, modular implementation isolated from upstream features.

Highlights:

  • Browse HuggingFace models and datasets with extended filtering, sort, Unsloth-support classification, and on-device detection.
  • Download GGUF variants, safetensors snapshots, and dataset snapshots over HTTP (byte-range resume) or XET (full retransfer on retry). Per-row transport label adapts so the user sees the retry semantics that actually apply.
  • Custom on-device folder import: scan user-specified directories for existing model and dataset assets and surface them alongside cached repos in the inventory.
  • Partial-download detection via a per-(repo_type, repo_id, variant) manifest persisted under the studio cache. Cancelled downloads write a marker so partial state survives backend restart and doesn't masquerade as on-device. Q8+Q4 mixed states on the same repo resolve correctly per-variant.
  • Worker post-download verification: on-disk file sizes are checked against the manifest before reporting success, so a resume that no-ops against a cached but incomplete snapshot now errors clearly instead of silently reporting complete.
  • Hub-aware Content Security Policy: img-src and media-src widened to https: so HuggingFace model-card assets and dataset previews render in both the web UI and the desktop app.

Structure:

  • All new feature code lives in isolated trees: studio/backend/hub/ and studio/frontend/src/features/hub/. Upstream code is touched only in a small set of glue files for router registration, sidebar nav, CSP, locale entries, tauri config, and a synthetic storage event in the chat store so token changes propagate same-tab to subscribed features.
  • Hub-owned hooks and libraries (use-hub-model-search, use-hub-paginated-search, use-hub-infinite-scroll, etc.) are written fresh for Hub's needs rather than forking upstream equivalents.

Follow-ups planned as separate PRs:

  • Per-model config page.
  • Chat model picker integration (Hub-aware picker with External tab).
  • Training pickers + resource flow integration.

Adds a new /hub route that consolidates model and dataset browsing,
discovery, and on-device inventory under a single surface. Replaces
the abandoned model-hub branch (PR unslothai#5783) with a clean, modular
implementation isolated from upstream features.

Highlights:
- Browse HuggingFace models and datasets with extended filtering,
  sort, Unsloth-support classification, and on-device detection.
- Download GGUF variants, safetensors snapshots, and dataset
  snapshots over HTTP (byte-range resume) or XET (full retransfer
  on retry). Per-row transport label adapts so the user sees the
  retry semantics that actually apply.
- Custom on-device folder import: scan user-specified directories
  for existing model and dataset assets and surface them alongside
  cached repos in the inventory.
- Partial-download detection via a per-(repo_type, repo_id, variant)
  manifest persisted under the studio cache. Cancelled downloads
  write a marker so partial state survives backend restart and
  doesn't masquerade as on-device. Q8+Q4 mixed states on the same
  repo resolve correctly per-variant.
- Worker post-download verification: on-disk file sizes are checked
  against the manifest before reporting success, so a resume that
  no-ops against a cached but incomplete snapshot now errors
  clearly instead of silently reporting complete.
- Hub-aware Content Security Policy: img-src and media-src widened
  to https: so HuggingFace model-card assets and dataset previews
  render in both the web UI and the desktop app.

Structure:
- All new feature code lives in isolated trees: studio/backend/hub/
  and studio/frontend/src/features/hub/. Upstream code is touched
  only in a small set of glue files for router registration,
  sidebar nav, CSP, locale entries, tauri config, and a synthetic
  storage event in the chat store so token changes propagate
  same-tab to subscribed features.
- Hub-owned hooks and libraries (use-hub-model-search,
  use-hub-paginated-search, use-hub-infinite-scroll, etc.) are
  written fresh for Hub's needs rather than forking upstream
  equivalents.

Follow-ups planned as separate PRs:
- Per-model config page.
- Chat model picker integration (Hub-aware picker with External
  tab).
- Training pickers + resource flow integration.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a self-contained Hub and Download Manager module for managing model inventories and HuggingFace downloads, integrating routers, schemas, and background workers into the FastAPI application. Feedback on the changes highlights critical issues in GGUF variant handling, specifically regarding cross-snapshot size inflation, case-sensitivity mismatches during cache lookups, and the need for hardlink deduplication when calculating cached file sizes. Additionally, a redundant and potentially buggy case-sensitive prefix check was identified in the cache path resolution utility.

Comment thread studio/backend/hub/utils/paths.py Resolved

@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: a9a12885cc

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if (typeof fromTraining === "string" && fromTraining.length > 0) {
window.localStorage.setItem(HF_TOKEN_KEY, fromTraining);
if (parsed.state && "hfToken" in parsed.state) {
delete parsed.state.hfToken;

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 Preserve the training HF token during migration

When an existing user only has an HF token persisted in unsloth_training_config_v1, this store is imported at startup via the download manager and deletes that legacy field. The training config store still owns its own hfToken and training API calls still use config.hfToken, so after this migration the Train flow loses access to private/gated Hugging Face repos even though the token was copied to the new Hub key. Keep the legacy value until training reads the shared token store, or backfill it when training loads.

Useful? React with 👍 / 👎.

models-catalog-rows.tsx imports useVirtualizer from @tanstack/react-virtual,
but the package was never declared in studio/frontend/package.json. The
frontend build failed typecheck with TS2307 (cannot find module) plus the
downstream implicit-any errors, which cascaded into every CI job that builds
the Studio frontend.

Pin to 3.13.25 (exact, per the repo's save-exact npmrc policy; published
2026-05-20, well outside the 7-day release-age cooldown) and update the
lockfile. Verified locally: typecheck and full vite build both pass.

@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: 10a533b8a3

ℹ️ 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 thread studio/backend/main.py
"/api/inference",
"/api/data-recipe",
"/api/datasets",
"/api/hub",

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 buffering Hub uploads in MaxBodyMiddleware

With /api/hub added to the protected prefixes, POST /api/hub/datasets/upload now goes through MaxBodyMiddleware, which reads every incoming chunk into chunks and replays a single joined body before the UploadFile handler runs. For the new dataset upload endpoint this means allowed uploads up to the 500 MB cap are fully buffered in backend memory, defeating the chunked write logic in upload_dataset_response and risking large memory spikes; consider exempting the upload route or counting bytes while streaming through.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Resolved in f383f30. /api/hub/datasets/upload is now in the upload-passthrough prefixes, so MaxBodyMiddleware validates the declared Content-Length and streams the body through instead of buffering and replaying it. It is mapped to the dataset upload cap (LOCAL_UPLOAD_MAX_BYTES plus multipart overhead) rather than the generic protected-body cap, mirroring /api/datasets/upload. Added a regression test (test_hub_dataset_upload_is_streaming_passthrough).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reverted f383f30 from this PR. Per @Sneakr this is intentional and deferred on purpose: the Hub dataset upload shares the buffering behavior with the original training upload path, so it will be handled holistically as part of the Training PR rather than patched in isolation here. Reopening this thread so it is tracked there.

…anup, worker reaper

- hf-token-store: copy the legacy HF token instead of deleting it, so the
  training config keeps its own persisted hfToken for private/gated repos.
- gguf_variants: scope incomplete-blob cleanup to the destructive exact-case
  cache iterator so a case-variant sibling repo is never touched.
- gguf_variants: account for downloaded variants per snapshot and lowercase
  quant keys, so cross-snapshot byte sums and case mismatches no longer
  mislabel a variant as downloaded.
- download_registry: match the worker repo-id argument exactly instead of by
  substring, so a stale breadcrumb cannot reap an unrelated live worker.
- paths: drop the redundant case-sensitive prefix check in the cache-case
  resolver so mixed-case imported dirs resolve.
@danielhanchen

danielhanchen commented Jun 1, 2026 •

Copy link
Copy Markdown
Member

Pushed fixes for the CI break and the review findings.

CI

The frontend build was failing because models-catalog-rows.tsx imports useVirtualizer from @tanstack/react-virtual, which was not declared in studio/frontend/package.json. That broke typecheck (TS2307) and cascaded into every job that builds Studio. Added the dependency (pinned 3.13.25, exact, lockfile updated). npm run typecheck and the full vite build pass locally.

Review findings

Training HF token migration: fixed. hf-token-store.loadInitial() deleted state.hfToken from unsloth_training_config_v1 after copying it to the new key, but training-config-store still persists and reads its own hfToken (it is not in NON_PERSISTED_STATE_KEYS, and training calls read config.hfToken). After migration the training config rehydrated hfToken as empty, losing access to private and gated repos. Changed the migration to copy only.

GGUF variant detection: fixed. The downloaded check now accounts per snapshot instead of summing across all snapshots, and lowercases quant keys. This removes three issues on the cache fallback path: cross-snapshot byte sums marking an incomplete variant as downloaded, split shards being satisfied from different snapshots, and the case-sensitive cached_bytes_by_quant.get(variant.quant) lookup missing a lowercase on-disk filename. Behavior is unchanged for the common single-snapshot case.

Variant incomplete-blob cleanup: fixed. delete_variant_incomplete_blobs_result used iter_repo_cache_dirs (case-insensitive, yields every case variant), while purge_partial_repo uses the guarded iter_destructive_repo_cache_dirs. With both models--Org--Repo and models--org--repo present it unlinked partials from both. Switched it to the destructive iterator so only the exact-case match is touched.

Orphan worker reaper: fixed. _is_our_worker used repo_id in cmdline, so a stale breadcrumb for Org/Model could match and kill a live worker for Org/Model-v2. It now parses the worker --repo-id argument and compares it exactly.

Cache-case resolver: fixed. Dropped the redundant case-sensitive startswith(prefix) check in resolve_cached_repo_id_case; the lowercased full-name match already proves the prefix, and the old check rejected mixed-case imported dirs such as Models--Org--Repo.

Each fix was reproduced against the current code before and after the change, and the existing test_cache_case_resolution, test_offline_gguf_cache_fallback, and test_model_services suites pass (130 tests).

@danielhanchen

Copy link
Copy Markdown
Member

Validated the Hub locally on this branch. I installed Studio four times into isolated UNSLOTH_STUDIO_HOME trees, pinned each to its own GPU (CUDA_VISIBLE_DEVICES 0-3), and drove the Hub in all four in parallel with Playwright. No page errors and no backend errors in any of the four; the only console noise was external huggingface.co org-overview 404s, which just fall back to generated avatars.

Four Studios, one per GPU, on the Hub Discover tab at the same time:

Four Studios on four GPUs

Discover browse: live search, Unsloth-support badges, model card, format and transport (HTTP/Xet) filters:

Hub browse

On-device inventory: cached repos are detected with their exact on-disk paths. This exercises the cache-case resolver and the GGUF variant detection from this PR:

On-device inventory

@danielhanchen

Copy link
Copy Markdown
Member

Download lifecycle, driven through the same endpoints the UI calls, to exercise the worker, the manifest, the variant detection, and the cancel cleanup path:

Download lifecycle

For SmolLM2-360M-Instruct-GGUF, gguf-variants listed all seven variants as not downloaded, I started Q2_K, watched progress, cancelled (cleanup path runs), restarted, and it completed. Afterwards only Q2_K reported downloaded while the other six stayed false, which is the per-snapshot and lowercased-key behavior working against a real cache.

Discover detail and the variant download control:

Discover detail

Download detail

@danielhanchen

Copy link
Copy Markdown
Member

Ran a 4-GPU parallel validation: four isolated Studios (GPUs 0-3) driven at once, each with its own Playwright suite, screenshots and video. Across all four: 0 page errors and 0 backend 4xx/5xx. Console noise was only external Hugging Face org-overview 404s (the avatar lookups) and a correct CSP block of a plain-HTTP shields.io badge embedded in a model README.

Hub scope is browse + download + inventory (by design)

The post-download Run / Use-in-chat / Train actions are gated off (HUB_POST_DOWNLOAD_ACTIONS_VISIBLE = false), there is no Export action in the Hub, and selecting a model in the Hub then opening Chat does not hand the model off yet (handleUseInChat just navigates). This matches the stated follow-ups.

Hub scope

Lifecycle: download cancel, delete, select another

Download cancel goes running to cancelled and leaves the variant clean; deleting an on-device model through the UI confirm dialog removes it from inventory; clicking another row updates the inspector each time.

Lifecycle

Hub is reachable from every tab

The Hub nav works from Chat, Compare, Recipes, Train and Export.

Hub reachable from tabs

@danielhanchen

Copy link
Copy Markdown
Member

The standalone Chat, Train and Export tabs still work and are not broken by this PR.

Chat with real GPU inference: the picker loaded SmolLM2-360M-Instruct-GGUF (Q2_K) on GPU 0 via llama.cpp and returned a real reply at around 509 tokens/sec, with the active model verified through the inference status endpoint. The tool-calling pills (Think, Search, Code, Artifacts) plus Tools and MCP Servers are present; a local GGUF reports no tool support so those pills are disabled for that model.

Chat turn on GPU 0

Train wizard (model picker, HF dataset autocomplete, QLoRA/LoRA/Full/CPT, params), Export (Merged / LoRA / GGUF with the full quant grid), Compare and Recipes all render and accept input. No real training or export run was launched.

Standalone tabs

One non-Hub note for visibility: on a cold start the first model auto-load can hit a transient llama.cpp load error, after which the app falls back to the smallest cached model (an embedding model) and a chat turn then returns an opaque internal error. A direct reload of the intended model works. This lives in the inference loader, outside this PR's scope, but the embedding-model fallback plus the unclear error is a rough edge worth smoothing later.

danielhanchen and others added 2 commits June 1, 2026 13:35
Map repo-not-found/gated/bad-token errors to 404/403/401 instead of a blanket 500 so the Hub can show the right message.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed a small follow-up in 4aef4cc.

GET /api/hub/gguf-variants was wrapping every upstream Hugging Face error in a generic 500, so a mistyped or removed repo, a gated repo, or a bad token all showed up as "Internal Server Error" in the Hub. These are client errors, so they now pass through with the correct status:

  • repo / revision / file not found: 404
  • gated repo: 403
  • invalid token: 401
  • valid repo: 200 (unchanged)
  • real server or parse failures: 500 (unchanged)

Verified on a live Studio: a nonexistent repo now returns 404 instead of 500, and listing a valid repo still returns its variants. The success path is untouched, only the error mapping changed.

danielhanchen and others added 3 commits June 1, 2026 14:19
…othai#5916

Share the HF client-error classifier and use it for gguf-variants and the
dataset format check. Invalid repo_ids now 400, missing/gated repos and
datasets 404, gated 403, bad token 401, instead of a blanket 500.
Skip unreadable entries when scanning local GGUF dirs so a path like
/proc no longer 500s, reject registering the filesystem root, and guard
the scan-folder id against out-of-range integers.
@danielhanchen

Copy link
Copy Markdown
Member

Two more follow-ups after wider testing of the Hub endpoints: 574ec6e and 2b1df6d.

574ec6e extends the error-status mapping. The dataset format check and gguf-variants were still wrapping client-side errors in a generic 500. They now return the right status:

  • invalid repo_id / dataset name: 400
  • missing repo or dataset: 404
  • gated repo: 403 (gated datasets resolve to 404, matching the Hub's own behavior)
  • bad token: 401
  • valid: 200 (unchanged)

The classifier is shared so both paths stay consistent.

2b1df6d hardens local folder handling:

  • scanning a local GGUF directory now skips unreadable entries, so pointing it at a path like /proc no longer 500s
  • registering the filesystem root is rejected, so the browse allowlist cannot be widened to system directories
  • the scan-folder id is range-checked, so an out-of-range value returns cleanly instead of 500

Verified on a fresh install: invalid repo_ids and dataset names return 400, missing return 404, the local scan and the oversized id no longer 500, and valid repos and datasets still return their data.

danielhanchen and others added 2 commits June 1, 2026 15:09
…5916

Cap the recursive local model scan so a huge or system path cannot walk
unbounded, and add the HF, Kaggle, NGC and ModelScope token directories
to the folder denylist.
@danielhanchen

Copy link
Copy Markdown
Member

Follow-up hardening in 26f4732:

  • the recursive scan of a local model directory is now bounded, so pointing it at a very large or system path cannot walk unbounded
  • added the Hugging Face, Kaggle, NGC and ModelScope token directories to the folder denylist, alongside the existing .ssh / .aws / .gnupg entries

Verified on a fresh install: those credential directories are rejected with 400, a normal model folder still registers and scans, and the local scan no longer hangs or 500s on a path like /proc.

Sneakr added 2 commits June 2, 2026 19:19
Returning to the Hub showed a blank list (visible on the On Device tab)
until you toggled tabs. Made the list virtualizer's scroll element
reactive (state-backed in ModelsCatalog via ref callback, passed to
VirtualRows) so it binds on mount.
Two production bugs in the Hub:

1. Dataset inventory swallowed errors. listCachedDatasets caught
   404s and JSON parse failures into an empty list, so a real
   backend/routing failure rendered as a confident "no datasets on
   device." The model and GGUF fetchers already throw on any
   error. Unified datasets with them so genuine failures now
   surface a proper Datasets error state instead of looking empty.

2. Cancelling a GGUF download could orphan it. A GGUF download
   resolves blob hashes before the backend claims the job. If you
   hit Cancel during that window, the cancel was dropped (no
   active job yet) and the existing re-issue safeguard got
   skipped, so the UI showed "cancelled" while the download kept
   running. Fixed so the cancel is correctly re-issued once the
   job is claimed, and the download actually stops.
@Sneakr

Sneakr commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

Two more fixes after testing the Hub: 080c263 and 1e2a0e8.
080c263 fixes a blank On Device list after returning to the Hub. The virtualizer's scroll element wasn't binding on mount; it's now state-backed via a ref callback so it binds reactively.
1e2a0e8 fixes two bugs:

listCachedDatasets swallowed 404s and parse errors into an empty list, hiding real failures. Now throws like the model and GGUF fetchers, so errors surface properly.
Cancelling a GGUF during blob-hash resolution was dropped (no active job yet) and the re-issue safeguard was skipped. Cancel is now re-issued once the job is claimed.

Search results in the On Device tab now rank by match quality
instead of source order:
- name prefix match: highest weight
- name substring match: medium weight
- haystack (tags / metadata) match: lowest weight
A row must match every search token somewhere, otherwise it
scores zero and is filtered out — same semantics as the existing
matchTokens filter.
@Sneakr

Sneakr commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

4fd44d9 improves On Device search relevance. Results now rank by match quality — name-prefix > name-substring > metadata — instead of source order. A row must still match every token to appear.

@Sneakr

Sneakr commented Jun 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

Edge/rare cases fixes below.

70e50e1

Makes offline resume honest about partial downloads. Resuming with no manifest could previously mark a half-finished download as complete; it now fails cleanly instead.

Also fixes the cancel watchdog, which could label a download that finished while hidden as “cancelled”; it now re-checks the backend before finalizing.

The rest is cleanup: removed dead registry code, dropped an always-true snapshot progress parameter, stopped persisting a write-only field in the download manager state, and added tests for the offline resume path.

bb93a06

Fixes the GGUF progress bar jumping backward for a brief moment when two quants from the same repo download at once. The bar now stays bound to its own download across a refetch instead of rebinding to a still-downloading sibling.

A finished quant also stays “On device” if the refetch afterward lags or fails, rather than reverting to “Partial”; and a failed refetch shows a Retry instead of a silent stale list, with the Run button left enabled.

On the backend, HF repo-case resolution now runs off the event loop across the async hub handlers; the in-progress blob scan is scoped per variant so a sibling’s bytes can’t leak into its progress; and the Windows liveness probes use the correct ctypes setup.

Also removed dead inventory plumbing and added regression tests for the two-quant case.

…it matching

- inventory_scan: defer snapshot resolve in is_snapshot_partial so the cheap cancel-marker check short-circuits first (restores cheapest-first ordering)
- datasets/cache_inventory: dedupe hardlink-shared blobs in the size_on_disk fallback to stop 2-5x dataset size over-reporting
- gguf: include the mmproj companion in offline partial download size so vision GGUFs don't change size on offline->online toggle
- dataset_cache/formatting: share one alias-aware split matcher so cached and remote file selection agree (validation/valid/val, eval)
- gguf: rename _GGUF_SPLIT_RE -> _GGUF_SPLIT_SUFFIX_RE to end the name collision with inventory_scan's distinct two-group regex
@Sneakr

Sneakr commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator Author

62de08d

Correctness fixes: datasets no longer over-report their on-disk size,
vision GGUFs keep a consistent size when toggling offline and online, and
cached vs remote dataset split matching now agree. Plus a couple of small
internal cleanups.

- worker: wrap the watchdog's stderr diagnostic in try/except so a broken pipe on a dead parent can't kill the thread before os._exit(130)
- registry: _repo_active is now a set[str] read from the authoritative _metadata (drops the redundant transport copy), and the 64-job cap eviction moves into _put_terminal_job_locked so the claim/register cancel path enforces it too
- lifecycle: read cancel metadata before the terminal set_job so eviction can't drop it first
- progress: subtract the companion baseline only while it is still counted in completed_bytes and the variant is not yet verified complete (a departed companion was zeroing genuine progress)
- tests: cover the cancel/eviction ordering and the progress-baseline cases
@Sneakr

Sneakr commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

b0152f7

Hardening for downloads. The watchdog now reliably self-terminates an
orphaned worker even if writing its diagnostic to a dead parent fails.
Some registry bookkeeping cleanup, with the job cap now enforced on the
cancel path too. Also fixes a progress case where a departed companion
file could briefly read a download as zero progress.

…g, GGUF dropdown click-through

- re-adopt: explicit backend state now wins in adoptingCancel, so a running download no longer sticks on "Cancelling" with a disabled button after a refresh; the epoch guard applies even when cancel was issued before adoption (drops the now-unused applyCancelResult param)
- cancel/crash: snapshot cancel_requested before drop_process so a cancel landing in the finalize gap can't mislabel an OOM/SIGKILL crash as "cancelled" or persist a spurious resume marker
- external links: route protocol-relative //host README links through the confirmation modal (was only matching ://, mailto:), match case-insensitively, and harden the dialog's host display
- GGUF card: tags and status marks in the download-bar dropdown no longer swallow clicks and selections
- refactor: promote gguf_variant_blob_hashes / gguf_variant_requirements to public so download orchestration stops reaching into private helpers (updates call sites and tests)
@Sneakr

Sneakr commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

4ca7f50

A running download no longer gets stuck showing
"Cancelling" with a disabled button after a refresh, and a cancel that
lands just as a download crashes no longer mislabels the crash as
cancelled. README links of the //host form now go through the
external-link confirmation modal instead of slipping past it, and clicks
on the tags and status marks in the GGUF download dropdown register
properly now. Also a small internal refactor so download orchestration
uses public helpers instead of reaching into private ones.

- app: hoist a single global TooltipProvider (provider.tsx + tooltip.tsx) instead of mounting one per tooltip; this is app-wide, not Hub-only
- catalog: trim the virtualized list overscan to cut scroll jank
- gguf card: memoize the variant menu rows and precompute their fit/label/size data, pass stable callbacks, and arm tooltips lazily on hover/focus so opening the dropdown no longer mounts every tooltip up front
@Sneakr

Sneakr commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

ecd999b

Performance pass on the Hub catalog.

Scrolling the model list, navigations in the hub, and opening the GGUF variant dropdown are both smoother now: the dropdown rows are memoized and their tooltips load lazily instead of all at once, and the list overscan is trimmed.

Heads up that this also hoists a single global TooltipProvider at the app level for better performance.

@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: ecd999b208

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if (!canUseStorage()) return "";
try {
const direct = window.localStorage.getItem(HF_TOKEN_KEY);
if (direct !== null) return direct;

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 Normalize stored HF token before hydrating the store

When unsloth_hf_token already exists in localStorage, this returns it before applying the store's normalize() helper. The chat settings path writes this same key without normalization and only normalizes the in-memory Hub store via the synthetic storage event, so after a reload a token pasted with surrounding quotes/whitespace is sent raw to Hugging Face from Hub requests and private/gated repo access fails until the user re-saves the token. Return normalize(direct) here, and ideally persist the cleaned value.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

1dd8103 fixed

@Sneakr

Sneakr commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

1dd8103

Small fix: persisted Hugging Face tokens are now normalized both when
they are loaded and when storage syncs, so a saved token with stray
whitespace or odd formatting no longer gets used as is.

…ame-tab token sync

- gguf: prefer the real quant token over the float-precision infix so *-BF16-Q4_K_M variants no longer collapse into one BF16 entry
- discover: reset the discover selection on Models/Datasets switch so the inspector no longer strands a model in dataset mode
- shutdown: persist the cancel marker only after observing a non-clean exit (kill, wait, classify), removing the race that stranded markers on completed downloads
- token: sync the same-tab HF token via CustomEvent instead of a non-portable synthetic StorageEvent
- tests: quant-extraction infix cases, realigned shutdown ordering test, clean-exit no-marker regression
@Sneakr

Sneakr commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

b04e84a

A few Hub fixes. GGUF variants with a float-precision tag like
BF16-Q4_K_M no longer collapse into a single BF16 entry. Switching
between Models and Datasets in Discover now resets the selection, so the
inspector can't get stuck showing a model in dataset mode. On shutdown,
the cancel marker is only written after a download actually exits
uncleanly, which stops stray markers landing on completed downloads. And
same-tab HF token updates now sync through a CustomEvent instead of a
synthetic storage event that didn't behave consistently.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen and others added 2 commits June 8, 2026 12:52
Resolve conflicts from upstream main (through unslothai#6079):

- studio/backend/main.py: keep both the Hub router/imports and the new
  settings_router import; adopt main's single-line ruff formatting for the
  training_history_router registration and append the Hub inventory/datasets
  routers after it.
- studio/backend/tests/test_middleware.py: keep the Hub version of
  test_img_and_media_allow_https_sources. main widened img-src/media-src to
  the broad "https:" source, so the old per-host assertions (gstatic /
  www.google.com) no longer match the merged _build_csp output.
- studio/frontend/src/components/app-sidebar.tsx: integrate the Hub nav item
  into main's restructured scrollable sidebar. The Hub entry sits in the
  Projects group as an always-visible top-level destination; Train/Recipes/
  Export keep main's new collapsible section.

Validated: backend test_middleware.py (18 passed) and hub/tests (100 passed);
frontend tsc typecheck and vite build both pass.

@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: e92b12e465

ℹ️ 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 thread studio/backend/main.py
"/api/inference",
"/api/data-recipe",
"/api/datasets",
"/api/hub",

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 Give Hub uploads multipart headroom

Separate from the earlier streaming/buffering discussion, protecting all of /api/hub here makes POST /api/hub/datasets/upload use default_request_body_limit_bytes() instead of the upload-specific upload_request_limit_bytes(). The default cap is exactly the configured file limit (500 MiB by default) and does not include multipart overhead, while upload_dataset_response accepts files up to 500 MiB, so a valid near-limit dataset upload is rejected with 413 before the endpoint can process it. Give the Hub upload route the same multipart headroom, even if it remains buffered, or lower the endpoint's advertised file limit.

Useful? React with 👍 / 👎.

Make comments across the Hub feature succinct: remove the few that restate the
code or the filename, shorten docstrings on small internal helpers, and condense
verbose multi-line rationale blocks to 1-2 lines while preserving intent
(download/cancel races, HF-cache accounting, Tauri/WebKit quirks, prior-bug
notes). SPDX headers and tool directives are left untouched.

Scope: studio/backend/hub/** and studio/frontend/src/features/hub/**, plus two
PR-added comment blocks in studio/backend/main.py.

Verified comment/whitespace-only with comment_tools.py check --strip-docstrings
(73/73 files code-unchanged). Backend pytest (18 + 100), frontend tsc typecheck,
and vite build all pass. Net reduction ~600 lines.
Sync with latest main (through unslothai#6099/unslothai#6095/unslothai#6029 comment-reduction PRs, unslothai#6100).
Resolve conflicts in the shared glue files, all caused by main and this branch
independently editing the same comments/CSP:

- studio/backend/main.py: keep the hub shutdown cleanup
  (await asyncio.to_thread(terminate_hub_downloads)); keep this branch's broad
  img/media-src https CSP (the Hub feature) since the merged _build_csp uses
  "https:" (a superset of main's gstatic/google favicon hosts), and keep the
  matching comment.
- studio/backend/tests/test_middleware.py: keep test_img_and_media_allow_https_sources
  (asserts the broad https: img/media-src). main's test_img_src_allows_google_favicons
  asserts specific hosts that the broad policy replaced, so it would fail here;
  favicons remain covered by the broad-https assertion.
- studio/frontend/src/components/app-sidebar.tsx: keep the Hub nav item and adopt
  main's shorter one-line Train comment.

Validated: backend test_middleware.py (18) and hub/tests (100) pass; frontend tsc
typecheck and vite build pass.
Follow-up to the first comment-reduction pass: delete docstrings on small
internal helpers whose name and signature already make them obvious
(_hf_hub_cache_roots, _repo_has_gguf_files, _denied_path_prefixes, etc.), and
condense the remaining multi-line internal-helper docstrings to a single line
while preserving their intent (sandbox/symlink-escape rationale, fail-open vs
fail-closed delete contract, blob reference-counting, resume/cancel semantics).
Public-function, FastAPI route-handler, and Pydantic schema docstrings are
untouched.

Verified code-only with an AST check that treats docstring removal as
comment-equivalent (16/16 Python files code-unchanged) and the TS compiler-API
verifier (2/2 frontend). Public docstrings 96 and class docstrings 15 both
unchanged. Backend pytest (18 + 100), frontend tsc, and vite build all pass.

@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: 72a4c09f2b

ℹ️ 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 +84 to +86
owner, sep, repo = encoded.partition("--")
if not sep or not owner or not repo:
return None

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 Recognize single-segment dataset cache dirs

For Hub datasets whose repo id has no namespace (for example wikitext/imdb-style IDs, which DownloadDatasetRequest otherwise accepts), the Hugging Face cache folder is encoded as datasets--<repo> and this parser returns None because there is no -- separator after the prefix. That means _scan_hub_dataset_cache_dirs() drops blob-only or partial cache entries for these valid dataset repos, so a cancelled download can disappear from the On Device list and the user loses the resume/delete affordances this fallback scanner is meant to provide. Treat the whole encoded suffix as a valid one-segment repo id when the separator is absent.

Useful? React with 👍 / 👎.

Browsing and downloading models and datasets needs only HTTP and local
file access, so the Hub does not depend on a GPU or torch. It was gated
behind chat-only mode together with Train and Export, which hid it on CPU
and Mac hosts even though it works there.

Drop the chatOnly gate on the Hub nav item and allow /hub through the
chat-only route guard. Train and Export stay gated.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed a small frontend change so the Hub is available in chat-only mode (CPU and Mac hosts).

Context: CHAT_ONLY is derived purely from GPU detection (torch.cuda.is_available()), and both the Hub nav item and the /hub route were gated on it, so the Hub was hidden whenever no GPU was present. The Hub backend has no torch imports and only needs HTTP plus local file access to browse and download models and datasets, so it works fine without a GPU.

Change (frontend only, no backend change):

  • app-sidebar.tsx: drop the disabled={chatOnly} gate on the Hub nav item.
  • __root.tsx: add /hub to the chat-only allowlist so the route guard stops redirecting it to /chat.

Train and Export stay gated behind chat-only, and the post-download Train/Run actions inside the Hub remain hidden by HUB_POST_DOWNLOAD_ACTIONS_VISIBLE. Verified with tsc -b typecheck and vite build, both pass.

@danielhanchen
danielhanchen merged commit aec41d1 into unslothai:main Jun 9, 2026
36 of 38 checks passed
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