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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Say why a Xet download sits at 0% until it finishes (#9159)
Michael Han3bf9bff5dd0e
diff --git a/studio/backend/hub/schemas/downloads.py b/studio/backend/hub/schemas/downloads.pyindex 904e5bcd951..dd8d0430cd3 100644--- a/studio/backend/hub/schemas/downloads.py+++ b/studio/backend/hub/schemas/downloads.py@@ -77,6 +77,9 @@ class DownloadStartResponse(BaseModel):job_key: strstate: straccepted: bool+ # True when this start attached to a job already running rather than+ # starting one. Accepted either way.+ attached: bool = Falsegeneration: int# The transport the job is really on: the one the backend resolved for a# fresh start, or the running job's own when this start adopted one.@@ -214,6 +217,8 @@ class DatasetDownloadStartResponse(BaseModel):repo_id: strstate: straccepted: bool+ # Attached to a job already running, rather than starting one (see above).+ attached: bool = Falsegeneration: int# The transport the job is really on, and its cancel marker (see above).transport: Optional[str] = Nonediff --git a/studio/backend/hub/services/datasets/downloads.py b/studio/backend/hub/services/datasets/downloads.pyindex ddd90c4b675..c99c7d6d0cb 100644--- a/studio/backend/hub/services/datasets/downloads.py+++ b/studio/backend/hub/services/datasets/downloads.py@@ -188,12 +188,15 @@ async def download_dataset_response()generation = _registry.current_generation(key)if not claimed:- # Pollable when rejected by this repo's own in-flight job; an- # in-progress delete leaves no job, so flag it via ``adoptable``.+ # Pollable when rejected by this repo's own in-flight job, and that is+ # also the only case that attached to anything; an in-progress delete+ # leaves no job, so both come from ``adoptable``.+ adoptable = _registry.adoptable(key)return {"repo_id": repo_id,"state": claim_state,- "accepted": _registry.adoptable(key),+ "accepted": adoptable,+ "attached": adoptable,"generation": generation,# An adopted job keeps the transport it started on, so report it# rather than let the caller assume the one it asked for.@@ -234,6 +237,7 @@ async def download_dataset_response("repo_id": repo_id,"state": state,"accepted": True,+ "attached": False,"generation": generation,# See models: the resolved transport, which a downgrade can make# different from the one requested.diff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.pyindex 00ffaf54996..47ecf0ce008 100644--- a/studio/backend/hub/services/models/downloads.py+++ b/studio/backend/hub/services/models/downloads.py@@ -303,13 +303,15 @@ async def download_model_response("this one."),)- # claim_state is the blocking job's state. The client can attach only- # when the blocker is this key's own in-flight job (adoptable); a- # cross-variant conflict or in-progress delete is not accepted.+ # claim_state is the blocking job's state. Attaching and accepting are+ # one verdict: only this key's own in-flight job can be joined, and a+ # cross-variant conflict or in-progress delete joined nothing.+ adoptable = _registry.adoptable(key)return {"job_key": key,"state": claim_state,- "accepted": _registry.adoptable(key),+ "accepted": adoptable,+ "attached": adoptable,"generation": generation,# An adopted job keeps the transport it started on, so report it# rather than let the caller assume the one it asked for.@@ -357,6 +359,7 @@ async def download_model_response("job_key": key,"state": state,"accepted": True,+ "attached": False,"generation": generation,# The transport that was actually resolved: an explicit "xet" is# downgraded to HTTP where hf_xet is unavailable, and a client thatdiff --git a/studio/backend/tests/test_scoped_download_job.py b/studio/backend/tests/test_scoped_download_job.pyindex 23e4a9814b3..209d8428a99 100644--- a/studio/backend/tests/test_scoped_download_job.py+++ b/studio/backend/tests/test_scoped_download_job.py@@ -25,7 +25,7 @@ if _BACKEND_DIR not in sys.path:from fastapi import HTTPException-from hub.schemas.downloads import DownloadModelRequest+from hub.schemas.downloads import DownloadModelRequest, DownloadStartResponsefrom hub.services import download_lifecyclefrom hub.services.models import downloads as dlfrom hub.utils.paths import is_valid_gguf_variant@@ -166,6 +166,40 @@ def test_a_different_file_set_is_not_adopted(monkeypatch):dl._registry.set_job(key, "complete")+def test_a_start_reports_whether_it_attached_to_a_live_job(monkeypatch):+ # A second client starting the same download is accepted and gets the live job's+ # transport, which reads exactly like a fresh Xet start. Only this flag separates+ # them, and the Studio download notice keys off it.+ monkeypatch.setattr(dl, "_reject_if_load_in_flight", lambda repo_id: None)+ monkeypatch.setattr(dl, "resolve_cached_repo_id_case", lambda repo, **k: repo)+ monkeypatch.setattr(dl, "scoped_file_blob_hashes", lambda *a, **k: frozenset())+ monkeypatch.setattr(download_lifecycle, "launch_worker", lambda *a, **k: "running")++ repo = "unsloth/attach-flag-probe"+ key = dl._download_job_key(repo, dl._scope_variant("diffusion"))+ try:+ started = asyncio.run(dl.download_model_response(_request(repo_id = repo)))+ assert started["accepted"] is True and started["attached"] is False++ attached = asyncio.run(dl.download_model_response(_request(repo_id = repo)))+ assert attached["accepted"] is True and attached["attached"] is True+ assert attached["job_key"] == key++ # The route declares response_model, which drops any key the schema does+ # not name, so the flag has to survive that too or it never ships.+ assert DownloadStartResponse(**attached).model_dump()["attached"] is True+ assert DownloadStartResponse(**started).model_dump()["attached"] is False++ # A rejection that is not adoptable (cross-variant conflict, delete in+ # progress) joined nothing, so it must not claim it attached.+ monkeypatch.setattr(dl._registry, "claim", lambda *a, **k: (False, "repository_owned"))+ monkeypatch.setattr(dl._registry, "adoptable", lambda *a, **k: False)+ refused = asyncio.run(dl.download_model_response(_request(repo_id = repo)))+ assert refused["accepted"] is False and refused["attached"] is False+ finally:+ dl._registry.set_job(key, "complete")++def test_the_http_retry_keeps_the_scoped_file_list_on_the_record(monkeypatch):# The retry reclaims the slot with replace_active, which OVERWRITES the stored metadata. Dropping the file list there left# the record claiming an empty scope, so the next identical scoped start compared [] against the real list and 409'd.diff --git a/studio/frontend/src/features/hub/download-manager/api.ts b/studio/frontend/src/features/hub/download-manager/api.tsindex 035df8094dd..ea931ca413e 100644--- a/studio/frontend/src/features/hub/download-manager/api.ts+++ b/studio/frontend/src/features/hub/download-manager/api.ts@@ -56,6 +56,9 @@ export interface DownloadStartResult {state: DownloadStartState;accepted: boolean;generation?: number;+ // True when the start attached to a job another client had already begun,+ // rather than starting one. Accepted either way.+ attached?: boolean;// Present only when the start adopted a job another client had already// begun: the transport it is really running on.transport?: TransportMode | null;diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.tsindex 9ae111c7a06..26ab696197a 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -64,6 +64,15 @@ import type {ProgressLike,Terminal,} from "./download-manager-types";+import {+ XET_NOTICE_DESCRIPTION,+ XET_NOTICE_DESCRIPTION_CLASS,+ XET_NOTICE_DURATION_MS,+ XET_NOTICE_TITLE,+ reserveXetNotice,+ shouldShowXetNotice,+ xetNoticesShown,+} from "./xet-progress-notice";import {getState,hasActiveRepoPeer,@@ -680,6 +689,29 @@ export async function startJob(}const started = transportAfterStart(mode, result.transport);if (started !== activeTransport) patchJob(key, { transport: started });+ // Explain the 0%-then-done shape of a Xet transfer, for the first few only.+ if (+ shouldShowXetNotice({+ kind: req.kind,+ transport: started,+ attached: result.attached === true,+ // A cancel can land while this start is in flight, and the reissue+ // above is the giveaway. Do not promise a download that is stopping.+ live: result.state === "running" && !rt.cancelRequested,+ shown: xetNoticesShown(),+ })+ ) {+ // Reserving is async (a cross-tab lock), and nothing below waits on a+ // toast, so let the download get on with it.+ void reserveXetNotice().then((reserved) => {+ if (!reserved) return;+ toast.info(XET_NOTICE_TITLE, {+ description: XET_NOTICE_DESCRIPTION,+ duration: XET_NOTICE_DURATION_MS,+ classNames: { description: XET_NOTICE_DESCRIPTION_CLASS },+ });+ });+ }// An adopted job can already have fallen back from Xet to HTTP, which// keeps its original cancel marker and so its stop control.if (isResolvedTransport(result.cancel_transport)) {diff --git a/studio/frontend/src/features/hub/download-manager/xet-progress-notice.ts b/studio/frontend/src/features/hub/download-manager/xet-progress-notice.tsnew file mode 100644index 00000000000..6990f4196a6--- /dev/null+++ b/studio/frontend/src/features/hub/download-manager/xet-progress-notice.ts@@ -0,0 +1,104 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Xet writes chunks out of order, so progress reads 0% and then completes at+// once, which looks like a hang. No toast import here: poll-loop shows it.++import {+ DOWNLOAD_KIND,+ type DownloadKind,+ type ResolvedTransport,+ TRANSPORT,+} from "./constants";++export const XET_NOTICE_LIMIT = 3;+export const XET_NOTICE_STORAGE_KEY = "unsloth.studio.xetNoticeCount";++// Longer than the Toaster's 5s default, like the explanatory toasts in chat.+export const XET_NOTICE_DURATION_MS = 8000;++export const XET_NOTICE_TITLE =+ "Download progress may appear slow, but the download is still running.";+export const XET_NOTICE_DESCRIPTION =+ "Hugging Face Xet enables faster downloads by fetching model data as parallel chunks. Because chunks are written out of order and committed in batches, the progress indicator may appear stuck or update unevenly even while data is actively downloading.\n\nFor smoother progress updates, go to 'Model Hub' and switch transport to HTTP.";+// The blank line needs pre-line. Per-toast classNames replace the Toaster's+// description class instead of merging, so repeat it.+export const XET_NOTICE_DESCRIPTION_CLASS =+ "!text-muted-foreground whitespace-pre-line";++// Carries the count when the write fails (private mode, quota), which would+// otherwise repeat the toast on every download.+let sessionShown = 0;++function readStoredCount(): number {+ if (typeof window === "undefined") return 0;+ try {+ const parsed = Number.parseInt(+ window.localStorage.getItem(XET_NOTICE_STORAGE_KEY) ?? "",+ 10,+ );+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : 0;+ } catch {+ return 0;+ }+}++export function xetNoticesShown(): number {+ return Math.max(sessionShown, readStoredCount());+}++export function recordXetNoticeShown(): void {+ const next = xetNoticesShown() + 1;+ sessionShown = next;+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(XET_NOTICE_STORAGE_KEY, String(next));+ } catch {+ // Counted in memory above, so this session still stops at the limit.+ }+}++/** Take one of the three, or report that none are left.+ *+ * localStorage has no compare-and-set, so two tabs starting a download at the+ * same moment can both read the same count and both show the toast. Web Locks+ * are cross-tab, so the read and the write happen as one. Browsers without+ * them fall back to the plain check, which is the race above and still bounded+ * at one extra toast. */+export async function reserveXetNotice(): Promise<boolean> {+ const take = () => {+ if (xetNoticesShown() >= XET_NOTICE_LIMIT) return false;+ recordXetNoticeShown();+ return true;+ };+ const locks = globalThis.navigator?.locks;+ if (!locks) return take();+ try {+ return await locks.request(XET_NOTICE_STORAGE_KEY, take);+ } catch {+ return take();+ }+}++/** Only the transport that behaves this way, and only while it is news.+ *+ * A start that attached to a job another tab or client already owns is+ * accepted and reports that job's transport, but this user started nothing.+ * `live` is the backend calling the job running with no cancel pending: a+ * start the user already cancelled has nothing to reassure them about.+ * Neither shows the notice nor spends one of the three. */+export function shouldShowXetNotice(args: {+ kind: DownloadKind;+ transport: ResolvedTransport;+ attached: boolean;+ live: boolean;+ shown: number;+}): boolean {+ return (+ args.kind === DOWNLOAD_KIND.MODEL &&+ args.transport === TRANSPORT.XET &&+ !args.attached &&+ args.live &&+ args.shown < XET_NOTICE_LIMIT+ );+}diff --git a/studio/frontend/tests/xet-notice-reservation.test.ts b/studio/frontend/tests/xet-notice-reservation.test.tsnew file mode 100644index 00000000000..f134d36e3b0--- /dev/null+++ b/studio/frontend/tests/xet-notice-reservation.test.ts@@ -0,0 +1,53 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Two tabs starting a Xet download at the same moment used to read the same+// count and both toast. Its own file: the module's session counter is process+// wide, so these need a fresh instance of it.++import assert from "node:assert/strict";+import test from "node:test";++import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";++const { store } = installLocalStorageFake();++// A Web Locks stand-in that really serialises: each request queues behind the+// last one for that name, which is the property the reservation leans on.+const lockTails = new Map<string, Promise<unknown>>();+// globalThis.navigator is getter-only in node, so define over it.+Object.defineProperty(globalThis, "navigator", {+ configurable: true,+ value: {+ locks: {+ request: (name: string, fn: () => boolean | Promise<boolean>) => {+ const tail = lockTails.get(name) ?? Promise.resolve();+ const run = tail.then(() => fn());+ lockTails.set(+ name,+ run.catch(() => undefined),+ );+ return run;+ },+ },+ },+});++registerBundlerResolver();++const { XET_NOTICE_LIMIT, XET_NOTICE_STORAGE_KEY, reserveXetNotice } =+ await import("../src/features/hub/download-manager/xet-progress-notice.ts");++test("a concurrent burst never hands out more than three", async () => {+ // Five reservations in flight at once, all reading the count before any+ // writes. Without the lock the tabs sharing a read would each toast; here+ // the fourth and fifth lose, which is the two-tabs-on-the-last-slot case.+ const taken = await Promise.all(+ Array.from({ length: 5 }, () => reserveXetNotice()),+ );+ assert.deepEqual(taken, [true, true, true, false, false]);+ assert.equal(store.get(XET_NOTICE_STORAGE_KEY), String(XET_NOTICE_LIMIT));+});diff --git a/studio/frontend/tests/xet-progress-notice.test.ts b/studio/frontend/tests/xet-progress-notice.test.tsnew file mode 100644index 00000000000..2f220ec9de8--- /dev/null+++ b/studio/frontend/tests/xet-progress-notice.test.ts@@ -0,0 +1,131 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Xet writes chunks out of order, so progress reads 0% and then completes at+// once, which looks like a hang. The first few model downloads now say so.++import assert from "node:assert/strict";+import test from "node:test";++import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";++const { store, storage } = installLocalStorageFake();+registerBundlerResolver();++const {+ XET_NOTICE_DESCRIPTION,+ XET_NOTICE_DESCRIPTION_CLASS,+ XET_NOTICE_DURATION_MS,+ XET_NOTICE_LIMIT,+ XET_NOTICE_STORAGE_KEY,+ XET_NOTICE_TITLE,+ recordXetNoticeShown,+ shouldShowXetNotice,+ xetNoticesShown,+} = await import("../src/features/hub/download-manager/xet-progress-notice.ts");++const XET_MODEL = {+ kind: "model",+ transport: "xet",+ attached: false,+ live: true,+} as const;++test("the notice is for Xet model downloads and nothing else", () => {+ assert.ok(shouldShowXetNotice({ ...XET_MODEL, shown: 0 }));+ // HTTP reports steady progress, so the explanation would be wrong there.+ assert.ok(+ !shouldShowXetNotice({ ...XET_MODEL, transport: "http", shown: 0 }),+ );+ assert.ok(!shouldShowXetNotice({ ...XET_MODEL, kind: "dataset", shown: 0 }));+});++test("attaching to someone else's job shows nothing", () => {+ // The backend accepts the start and reports that job's transport, but this+ // client began no transfer, so it must not spend one of the three either.+ assert.ok(!shouldShowXetNotice({ ...XET_MODEL, attached: true, shown: 0 }));+});++test("a start that is already stopping shows nothing", () => {+ // Cancelling while the start POST is in flight still returns an accepted+ // start. Promising a running download there would be a lie, and it would+ // spend one of the three on it.+ assert.ok(!shouldShowXetNotice({ ...XET_MODEL, live: false, shown: 0 }));+});++test("it stops after the first three", () => {+ assert.equal(XET_NOTICE_LIMIT, 3);+ assert.ok(shouldShowXetNotice({ ...XET_MODEL, shown: XET_NOTICE_LIMIT - 1 }));+ assert.ok(!shouldShowXetNotice({ ...XET_MODEL, shown: XET_NOTICE_LIMIT }));+ // A count already past the limit (an older, larger value) still stops.+ assert.ok(!shouldShowXetNotice({ ...XET_MODEL, shown: 99 }));+});++// Before anything is recorded, so the session count cannot mask the read.+test("a missing or junk stored count reads as none shown", () => {+ store.clear();+ assert.equal(xetNoticesShown(), 0);+ store.set(XET_NOTICE_STORAGE_KEY, "not a number");+ assert.equal(xetNoticesShown(), 0);+ store.set(XET_NOTICE_STORAGE_KEY, "-4");+ assert.equal(xetNoticesShown(), 0);+});++test("the count persists across sessions", () => {+ store.clear();+ recordXetNoticeShown();+ assert.equal(store.get(XET_NOTICE_STORAGE_KEY), "1");+ recordXetNoticeShown();+ assert.equal(store.get(XET_NOTICE_STORAGE_KEY), "2");+ assert.equal(xetNoticesShown(), 2);++ // What a later session reads back, including one past this session's count.+ store.set(XET_NOTICE_STORAGE_KEY, "3");+ assert.equal(xetNoticesShown(), 3);+ assert.ok(!shouldShowXetNotice({ ...XET_MODEL, shown: xetNoticesShown() }));+});++test("a storage that refuses writes still advances the count", () => {+ // Private mode: setItem throws. Without the in-memory carry, every download+ // would show the toast again.+ store.clear();+ const before = xetNoticesShown();+ const setItem = storage.setItem;+ storage.setItem = () => {+ throw new Error("QuotaExceededError");+ };+ try {+ recordXetNoticeShown();+ } finally {+ storage.setItem = setItem;+ }+ assert.equal(xetNoticesShown(), before + 1);+ assert.equal(store.get(XET_NOTICE_STORAGE_KEY), undefined);+});++test("the copy says it is running and where to switch", () => {+ // The reassurance is the point of the toast, so it leads.+ assert.match(XET_NOTICE_TITLE, /still running/);+ assert.match(XET_NOTICE_DESCRIPTION, /actively downloading/);+ // The control is the transport toggle in Model Hub, labelled HTTP.+ assert.match(+ XET_NOTICE_DESCRIPTION,+ /'Model Hub' and switch transport to HTTP/,+ );+});++test("the closing advice renders as its own paragraph", () => {+ // A blank line needs pre-line, and the per-toast class replaces the+ // Toaster's rather than merging.+ assert.match(XET_NOTICE_DESCRIPTION, /\n\nFor smoother progress/);+ assert.match(XET_NOTICE_DESCRIPTION_CLASS, /whitespace-pre-line/);+ assert.match(XET_NOTICE_DESCRIPTION_CLASS, /text-muted-foreground/);+});++test("it stays up longer than the Toaster default", () => {+ // The copy does not fit in the 5s every other toast gets.+ assert.ok(XET_NOTICE_DURATION_MS > 5000);+});