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
Xet notice: one toast carrying both messages, three times per install, gone when the download is (#9660)
Daniel Hanb1b700532794
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex af40fbd6b52..5482a2f7a59 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -40,6 +40,7 @@ from utils.upload_limits import (upload_limit_bytes,upload_limit_label,)+from utils.xet_notice_settings import reserve_xet_noticefrom utils.helper_precache_settings import (DEFAULT_HELPER_PRECACHE_ENABLED,get_helper_precache_enabled,@@ -568,6 +569,19 @@ class HelperPrecacheResponse(BaseModel):disabled_by_env: bool+class XetNoticeReservePayload(BaseModel):+ # A legacy localStorage count from a client that has not reported one before.+ # Can only raise the stored count (see reserve_xet_notice), so a client cannot+ # talk its own way back under the limit with it.+ seen_hint: int = 0+++class XetNoticeResponse(BaseModel):+ granted: bool+ shown: int+ limit: int++class ModelMemoryPayload(BaseModel):# None leaves the stored value untouched, so the switches save independently.keep_resident: Optional[bool] = None@@ -1066,6 +1080,24 @@ def update_helper_precache(return _helper_precache_response(enabled)[email protected]("/xet-notice/reserve", response_model = XetNoticeResponse)+def post_xet_notice_reserve(+ payload: XetNoticeReservePayload, current_subject: str = Depends(get_current_subject)+) -> XetNoticeResponse:+ """Take one of the remaining notices. POST because it mutates the count."""+ try:+ result = reserve_xet_notice(payload.seen_hint)+ except Exception as exc:+ raise log_and_http_error(+ exc,+ 500,+ safe_error_detail(exc, fallback = "Could not reserve the Xet download notice."),+ event = "settings.reserve_xet_notice_failed",+ log = logger,+ ) from exc+ return XetNoticeResponse(**result)++@router.get("/model-memory", response_model = ModelMemoryResponse)def get_model_memory(current_subject: str = Depends(get_current_subject)) -> ModelMemoryResponse:return _model_memory_response()diff --git a/studio/backend/tests/test_xet_notice_settings.py b/studio/backend/tests/test_xet_notice_settings.pynew file mode 100644index 00000000000..7a7eca990e4--- /dev/null+++ b/studio/backend/tests/test_xet_notice_settings.py@@ -0,0 +1,112 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The Xet notice counter: the count survives, and concurrency cannot beat the limit.++It lived in per-origin localStorage, and a Studio origin moves whenever port 8888 is+taken, so "three times" meant "three times per port, forever".+"""++from __future__ import annotations++import json+import sys+import threading+from pathlib import Path++_BACKEND = Path(__file__).resolve().parents[1]+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++import utils.xet_notice_settings as xet # noqa: E402+from storage import studio_db # noqa: E402+++def test_three_are_granted_and_the_fourth_is_not():+ assert xet.get_xet_notice_count() == 0+ granted = [xet.reserve_xet_notice()["granted"] for _ in range(5)]+ assert granted == [True, True, True, False, False]+ assert xet.get_xet_notice_count() == xet.XET_NOTICE_LIMIT+++def test_the_count_outlives_the_process_that_wrote_it():+ """A restart, on any port, must not hand out three more."""+ for _ in range(2):+ assert xet.reserve_xet_notice()["granted"] is True++ # A fresh connection is what a restarted backend gets: nothing is cached in+ # module state, the value comes back off disk.+ assert xet.get_xet_notice_count() == 2+ assert xet.reserve_xet_notice() == {"granted": True, "shown": 3, "limit": 3}+ assert xet.reserve_xet_notice()["granted"] is False+++def test_concurrent_reservations_never_exceed_the_limit():+ """Two tabs at once. Why the reserve is one transaction: a split read and write+ lets both callers read the same count and both be granted."""+ results: list[bool] = []+ lock = threading.Lock()+ start = threading.Barrier(8)++ def worker():+ start.wait()+ granted = xet.reserve_xet_notice()["granted"]+ with lock:+ results.append(granted)++ threads = [threading.Thread(target = worker) for _ in range(8)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ assert len(results) == 8+ assert sum(results) == xet.XET_NOTICE_LIMIT+ assert xet.get_xet_notice_count() == xet.XET_NOTICE_LIMIT+++def test_a_legacy_hint_raises_the_count_but_never_lowers_it():+ """Migration from localStorage, upwards only: it must not win back sightings."""+ assert xet.reserve_xet_notice(seen_hint = 2)["shown"] == 3+ assert xet.reserve_xet_notice()["granted"] is False++ # A client claiming it has seen none does not reset anything.+ assert xet.reserve_xet_notice(seen_hint = 0)["granted"] is False+ assert xet.get_xet_notice_count() == 3+++def test_a_hint_at_or_over_the_limit_grants_nothing():+ assert xet.reserve_xet_notice(seen_hint = 3)["granted"] is False+ assert xet.reserve_xet_notice(seen_hint = 99)["granted"] is False+ # The stored count is clamped by what was actually reserved, not by the claim.+ assert xet.get_xet_notice_count() >= xet.XET_NOTICE_LIMIT+++def test_an_unreadable_stored_value_reads_as_a_fresh_install():+ """A junk row must not wedge the notice off forever."""+ studio_db.upsert_app_settings({xet.XET_NOTICE_COUNT_KEY: "not a number"})+ assert xet.get_xet_notice_count() == 0+ assert xet.reserve_xet_notice()["granted"] is True++ studio_db.upsert_app_settings({xet.XET_NOTICE_COUNT_KEY: -5})+ assert xet.get_xet_notice_count() == 0++ # A bool is an int in Python; it is not a count.+ studio_db.upsert_app_settings({xet.XET_NOTICE_COUNT_KEY: True})+ assert xet.get_xet_notice_count() == 0+++def test_the_stored_shape_is_a_plain_json_int():+ """Other readers of app_settings should find a number, not a string."""+ xet.reserve_xet_notice()+ stored = studio_db.get_app_setting(xet.XET_NOTICE_COUNT_KEY, None)+ assert stored == 1+ conn = studio_db.get_connection()+ try:+ row = conn.execute(+ "SELECT value_json FROM app_settings WHERE key = ?",+ (xet.XET_NOTICE_COUNT_KEY,),+ ).fetchone()+ finally:+ conn.close()+ assert json.loads(row["value_json"]) == 1diff --git a/studio/backend/utils/xet_notice_settings.py b/studio/backend/utils/xet_notice_settings.pynew file mode 100644index 00000000000..c0407095e20--- /dev/null+++ b/studio/backend/utils/xet_notice_settings.py@@ -0,0 +1,97 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Lifetime count of the Xet "download is running" notice.++It lived in localStorage, which is per-origin, and a Studio origin is not stable:+run.py falls back past port 8888 when Jupyter has it, and Colab and the tunnel differ+again. Each new origin handed out a fresh three, so the notice never stopped.+"""++from __future__ import annotations++import json+from typing import Any++XET_NOTICE_COUNT_KEY = "xet_notice_shown_count"++# Enforced where the count is stored, so the two cannot disagree.+XET_NOTICE_LIMIT = 3+++def _coerce_count(value: Any) -> int:+ """Anything unparseable reads as zero, matching a fresh install."""+ if isinstance(value, bool):+ return 0+ if isinstance(value, int):+ return max(0, value)+ if isinstance(value, str):+ try:+ return max(0, int(value.strip()))+ except ValueError:+ return 0+ return 0+++def get_xet_notice_count() -> int:+ """Read the count. A missing or unreadable row means none have been shown."""+ try:+ from storage.studio_db import get_app_setting+ stored = get_app_setting(XET_NOTICE_COUNT_KEY, 0)+ except Exception:+ return 0+ return _coerce_count(stored)+++def reserve_xet_notice(seen_hint: int = 0) -> dict[str, Any]:+ """Take one of the remaining notices, or report that none are left.++ One transaction: get_app_setting and upsert_app_settings open a connection each,+ so splitting the read and write lets two tabs both be granted. BEGIN IMMEDIATE+ takes the write lock up front.++ seen_hint is a legacy localStorage count. It can only raise the stored value, so+ a client cannot talk its way back under the limit.+ """+ from storage.studio_db import get_connection++ hint = _coerce_count(seen_hint)+ conn = get_connection()+ try:+ conn.execute("BEGIN IMMEDIATE")+ row = conn.execute(+ "SELECT value_json FROM app_settings WHERE key = ?",+ (XET_NOTICE_COUNT_KEY,),+ ).fetchone()+ stored = 0+ if row is not None:+ try:+ stored = _coerce_count(json.loads(row["value_json"]))+ except (ValueError, TypeError):+ stored = 0+ shown = max(stored, hint)++ granted = shown < XET_NOTICE_LIMIT+ if granted:+ shown += 1+ if shown != stored:+ from datetime import datetime, timezone+ now = datetime.now(timezone.utc).isoformat()+ conn.execute(+ """+ INSERT INTO app_settings (key, value_json, updated_at)+ VALUES (?, ?, ?)+ ON CONFLICT(key) DO UPDATE SET+ value_json = excluded.value_json,+ updated_at = excluded.updated_at+ """,+ (XET_NOTICE_COUNT_KEY, json.dumps(shown), now),+ )+ conn.commit()+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.close()++ return {"granted": granted, "shown": shown, "limit": XET_NOTICE_LIMIT}diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsxindex 8d028ff9685..8972020a104 100644--- a/studio/frontend/src/app/provider.tsx+++ b/studio/frontend/src/app/provider.tsx@@ -19,7 +19,10 @@ import { WebUpdateBanner } from "@/components/web/update-banner";import { fetchDeviceType } from "@/config/env";import { getTauriAuthFailure, tauriAutoAuth } from "@/features/auth";import { DeepLinkHandler } from "@/features/deep-links";-import { DownloadManagerPanel } from "@/features/hub/download-manager";+import {+ DownloadManagerPanel,+ dismissStartToasts,+} from "@/features/hub/download-manager";import { LoadedModelsIndicator } from "@/features/loaded-models";import { NativeIntentDrain } from "@/features/native-intents/native-intent-drain";import {@@ -882,6 +885,11 @@ export function AppProvider({ children }: AppProviderProps) {const reduceMotion = useAppearanceCustomStore((s) => s.customization.reduceMotion,);+ // A start toast describes the surface it was raised on, and lasts 8s from a+ // root-level Toaster; see dismissStartToasts for what it lands on otherwise.+ useEffect(() => {+ dismissStartToasts();+ }, [pathname]);return (<MotionConfig reducedMotion={REDUCED_MOTION_MAP[reduceMotion]}><TooltipProvider>diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 1a85a0c765c..f2c4e852075 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -57,7 +57,9 @@ import { Tooltip, TooltipContent } from "@/components/ui/tooltip";import { useIsMobile } from "@/hooks/use-mobile";import {DOWNLOAD_KIND,+ dismissStartToast,downloadManager,+ jobKeyOf,useRepoDownload,} from "@/features/hub/download-manager";import {@@ -2748,13 +2750,14 @@ export function ChatPage({repoId: selection.id,variant: selection.ggufVariant ?? null,expectedBytes: selection.expectedBytes ?? 0,- });- if (outcome === "started") {- toast.info("Downloading in the background", {+ // Handed over, not raised here, so one start makes one toast.+ callerToast: {+ title: "Downloading in the background",description:"It'll be ready to load once the current model finishes.",- });- } else if (outcome === "conflict") {+ },+ });+ if (outcome === "conflict") {toast.info("Resume this download from Models", {description:"An earlier partial download used a different transport. Open the Model hub tab to resume or restart it.",@@ -2852,9 +2855,26 @@ export function ChatPage({}},});+ // The pending auto-load's job, for the context-change effect below. Written from+ // an effect, never during render.+ const pendingAutoLoadKeyRef = useRef<string | null>(null);+ // The live context, so a start still in flight can check it is still on screen.+ const chatContextKeyRef = useRef(chatContextKey);+ useEffect(() => {+ chatContextKeyRef.current = chatContextKey;+ }, [chatContextKey]);useEffect(() => {const pending = pendingHubAutoLoad;- if (!pending) return;+ if (!pending) {+ pendingAutoLoadKeyRef.current = null;+ return;+ }+ const pendingKey = jobKeyOf(+ DOWNLOAD_KIND.MODEL,+ pending.selection.id,+ pending.selection.ggufVariant ?? null,+ );+ pendingAutoLoadKeyRef.current = pendingKey;let active = true;void (async () => {const outcome = await downloadManager.requestStart({@@ -2862,11 +2882,21 @@ export function ChatPage({repoId: pending.selection.id,variant: pending.selection.ggufVariant ?? null,expectedBytes: pending.selection.expectedBytes ?? 0,+ // Notice-only: #9663 removed this surface's own toast, so it must not+ // return on an HTTP start or once the three notices are spent.+ callerToast: {+ title: "Downloading model",+ description: "It'll load automatically once the download finishes.",+ noticeOnly: true,+ // The cleanup below only reaches a toast that already exists; a raise+ // still in flight would promise an auto-load onComplete then refuses.+ stillValid: () => chatContextKeyRef.current === pending.contextKey,+ },});if (!active) return;if (outcome === "started") {- // No toast: the download panel already shows this download. The- // auto-load still runs from onComplete.+ // No toast here, and none from the manager unless the notice folds the+ // sentence in. The auto-load runs from onComplete.return;}if (outcome === "conflict") {@@ -2890,8 +2920,19 @@ export function ChatPage({})();return () => {active = false;+ // Another model was picked, so this one's completion loads nothing. A no-op+ // once the download finished, which dismisses the same id.+ dismissStartToast(pendingKey);};}, [pendingHubAutoLoad]);+ // Switching thread or project keeps the pathname and pendingHubAutoLoad, so neither+ // sweep above runs, yet onComplete refuses to load into a different contextKey.+ useEffect(() => {+ return () => {+ const pendingKey = pendingAutoLoadKeyRef.current;+ if (pendingKey) dismissStartToast(pendingKey);+ };+ }, [chatContextKey]);const loadNativeModelIntent = useCallback(async (intent: NativeIntent, loadingDescription: string) => {const label =diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts b/studio/frontend/src/features/hub/download-manager/download-manager-types.tsindex a549f4faa01..a8f161cd133 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts@@ -63,6 +63,24 @@ export interface DownloadRequest {files?: string[];/** See `ManagedDownload.checkpoint`. Carried on the request so the job records the role its stager already knew, rather than a surface re-deriving it from filenames. */checkpoint?: boolean;+ /** What this surface wants said about the start, for the download manager to raise.+ * Chat used to toast this itself while startJob raised the Xet notice, stacking two.+ * Suppressing one loses information, so the manager folds this into the notice, or+ * shows it alone when the notice does not fire. One start, one toast. */+ callerToast?: CallerToast;+}++export interface CallerToast {+ title: string;+ description: string;+ /** Fold into a granted Xet notice, never raise alone. #9663 removed chat's+ * auto-load toast as a duplicate of the download panel: the sentence is still worth+ * carrying inside the notice, but alone it would put that toast back. */+ noticeOnly?: boolean;+ /** Asked again just before the raise, several round trips after the request. False+ * drops this line and keeps the notice: chat moved to another thread so nothing+ * auto-loads, but the transfer is still running. Absent means always valid. */+ stillValid?: () => boolean;}/** The variant slot a scoped job occupies. Mirrors the backend's `_scope_variant`: no GGUF quant label starts with "@", so a scope collides with neither a real variant nor the repo's full snapshot. */diff --git a/studio/frontend/src/features/hub/download-manager/index.ts b/studio/frontend/src/features/hub/download-manager/index.tsindex 9068ba89e35..60b0eeef050 100644--- a/studio/frontend/src/features/hub/download-manager/index.ts+++ b/studio/frontend/src/features/hub/download-manager/index.ts@@ -49,6 +49,7 @@ export {type StagedDownloadEntry,} from "./use-staged-download";export { scopedVariant } from "./download-manager-types";+export { dismissStartToast, dismissStartToasts } from "./start-toast";export {getTransportMode,useDownloadTransportCapabilities,diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.tsindex d0409d1e45e..8d00cf7bf4b 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -65,14 +65,18 @@ import type {Terminal,} from "./download-manager-types";import {- XET_NOTICE_DESCRIPTION,- XET_NOTICE_DESCRIPTION_CLASS,- XET_NOTICE_DURATION_MS,XET_NOTICE_TITLE,- reserveXetNotice,+ composeNoticeDescription,shouldShowXetNotice,- xetNoticesShown,} from "./xet-progress-notice";+import { reserveXetNoticeFromServer } from "@/features/settings/api/xet-notice";+import {+ currentRoute,+ dismissStartToast,+ liveCallerToast,+ showCallerToast,+ showStartToast,+} from "./start-toast";import {getState,hasActiveRepoPeer,@@ -201,6 +205,10 @@ export function finalize(): void {const job = getState().jobs[key];teardownRuntime(key);+ // The 8s duration is a cap, not a description of the transfer: a finished download+ // left the toast still claiming it was running. Before the early returns below, so+ // a job already in a terminal display state still clears it.+ dismissStartToast(key);if (!job) return;if (TERMINAL_DISPLAY_STATES.has(job.state)) return;if (job.kind === DOWNLOAD_KIND.MODEL) {@@ -573,9 +581,13 @@ export async function startJob(state?: DownloadJobState;transport?: ResolvedTransport;cancelTransport?: ResolvedTransport | null;+ /** The surface this start was asked for, to hold its toast against. Passed by+ * `requestStart`, whose preflight is itself navigable; else taken here. */+ originRoute?: string;} = {},): Promise<void> {const key = jobKeyOf(req.kind, req.repoId, req.variant);+ const startRoute = opts.originRoute ?? currentRoute();// Peer guard stops a FRESH start from double-starting a variant already// downloading (or colliding with a no-variant snapshot). Skipped when ADOPTING:// the restored own entry would look like a peer and freeze the bar; adoptJob's@@ -734,28 +746,49 @@ 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.+ // One start, one toast: the only place a start is announced. A cancel can land+ // mid-flight (the reissue above is the giveaway), and neither message is true+ // of a start that is already stopping.+ const stopping = rt.cancelRequested;+ // Everything above was round trips the user could navigate during. Checked BEFORE+ // reserving, since a reservation is one of three for the life of the install:+ // spending one on a toast that will be discarded on arrival is how starting a+ // download and going to watch it burns all three unseen.+ const onOriginRoute = currentRoute() === startRoute;if (+ onOriginRoute &&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(),+ live: result.state === "running" && !stopping,})) {- // 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 },- });+ // Async (it asks the backend for one of the three) and nothing below waits on+ // a toast. A lost reservation still leaves the caller owed its message.+ void reserveXetNoticeFromServer().then(({ granted }) => {+ // This round trip can outlive the transfer: finalize() dismisses by id before+ // it resolves, so raising here would leave a finished or cancelled job claiming+ // to run for another 8s, or hand a restart on the same key a stale message.+ if (!isCurrent(key, epoch) || rt.cancelRequested) return;+ // The caller's line can go stale while the notice stays true: chat moved+ // thread, so nothing auto-loads, but the 0% still needs explaining.+ const caller = liveCallerToast(req.callerToast);+ if (granted) {+ showStartToast(+ key,+ {+ title: XET_NOTICE_TITLE,+ description: composeNoticeDescription(caller),+ },+ startRoute,+ );+ return;+ }+ showCallerToast(key, caller, startRoute);});+ } else if (!stopping && onOriginRoute) {+ showCallerToast(key, liveCallerToast(req.callerToast), startRoute);}// An adopted job can already have fallen back from Xet to HTTP, which// keeps its original cancel marker and so its stop control.diff --git a/studio/frontend/src/features/hub/download-manager/start-toast.ts b/studio/frontend/src/features/hub/download-manager/start-toast.tsnew file mode 100644index 00000000000..0c66aa8316b--- /dev/null+++ b/studio/frontend/src/features/hub/download-manager/start-toast.ts@@ -0,0 +1,90 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The one toast announcing a download start, and the one place it is dismissed.+//+// Chat used to raise its own alongside the Xet notice, so one download produced two+// stacked toasts; callers now hand their message over instead. The 8s duration says+// nothing about the transfer, so the id is derived from the job key and finalize()+// dismisses it (nothing can be stored: teardownRuntime runs first).++import { toast } from "@/lib/toast";++import type { CallerToast } from "./download-manager-types";+import {+ XET_NOTICE_DESCRIPTION_CLASS,+ XET_NOTICE_DURATION_MS,+} from "./xet-progress-notice";++/** Stable per-job toast id, so `finalize` can dismiss without carrying state. */+export function startToastId(jobKey: string): string {+ return `download-start:${jobKey}`;+}++// Id -> the route it was raised on. Keyed that way rather than dismissing everything+// live, because a start can itself navigate: that toast belongs where it landed.+const liveStartToasts = new Map<string, string>();++/** The route to hold a start against. Captured when the start begins, since the+ * preflight and the reservation are round trips a raise can outlive. */+export function currentRoute(): string {+ return typeof window === "undefined" ? "" : window.location.pathname;+}++export function showStartToast(+ jobKey: string,+ message: { title: string; description: string },+ originRoute: string = currentRoute(),+): void {+ // Raised late, surface gone: the route sweep has already run, so this would sit+ // on the new page for its full 8s.+ if (originRoute !== currentRoute()) return;+ liveStartToasts.set(startToastId(jobKey), originRoute);+ toast.info(message.title, {+ id: startToastId(jobKey),+ description: message.description,+ duration: XET_NOTICE_DURATION_MS,+ classNames: { description: XET_NOTICE_DESCRIPTION_CLASS },+ });+}++/** The caller's message if it still describes something true, else nothing. */+export function liveCallerToast(+ message: CallerToast | undefined,+): CallerToast | undefined {+ if (!message) return undefined;+ return (message.stillValid?.() ?? true) ? message : undefined;+}++/** The caller's own message, when the notice is not carrying it: HTTP transport,+ * the three spent, an attached job, or a lost reservation. A Hub start passes+ * nothing and stays silent, and so does a `noticeOnly` caller. */+export function showCallerToast(+ jobKey: string,+ message: CallerToast | undefined,+ originRoute?: string,+): void {+ if (!message || message.noticeOnly) return;+ showStartToast(jobKey, message, originRoute);+}++/** Drop the start toast once the transfer is over. Safe for a job that never raised+ * one: sonner ignores an unknown id. */+export function dismissStartToast(jobKey: string): void {+ const id = startToastId(jobKey);+ liveStartToasts.delete(id);+ toast.dismiss(id);+}++/** Drop the ones whose surface the user just left. The Toaster is root-level and+ * these live 8s, so chat's composed form (measured 167px tall against a hub filter+ * row at 158px, 1500x1000) would otherwise land on the toolbar, which is the overlap+ * #9293 reverted. Only ids raised here, so other toasts survive the navigation. */+export function dismissStartToasts(): void {+ const here = currentRoute();+ for (const [id, raisedOn] of liveStartToasts) {+ if (raisedOn === here) continue;+ liveStartToasts.delete(id);+ toast.dismiss(id);+ }+}diff --git a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts b/studio/frontend/src/features/hub/download-manager/transport-conflict.tsindex 87eae3c4ea5..595ea02333a 100644--- a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts+++ b/studio/frontend/src/features/hub/download-manager/transport-conflict.ts@@ -22,6 +22,7 @@ import {setConflict,} from "./download-manager-state";import { startJob } from "./poll-loop";+import { currentRoute, showCallerToast } from "./start-toast";import { runtimeRegistry } from "./runtime-registry";import { getTransportMode } from "./transport-preference";import { ACTIVE_STATES, TRANSPORT_STATUS_TIMEOUT_MS } from "./download-manager-config";@@ -127,7 +128,14 @@ async function runWithPendingStartGuard(// Already active or pending for the repo: only report "started" when this// exact request is the live transfer; a peer/snapshot/pending start has not.if (hasActiveOrPendingStart(req)) {- return isJobActiveFor(req) ? "started" : "busy";+ if (!isJobActiveFor(req)) return "busy";+ // Returns "started" WITHOUT running the action, so startJob never announces;+ // now the manager owns the message, this is the only feedback there is.+ showCallerToast(+ jobKeyOf(req.kind, req.repoId, req.variant),+ req.callerToast,+ );+ return "started";}runtimeRegistry.pendingStartRepoKeys.add(startKey);try {@@ -143,6 +151,9 @@ async function runWithPendingStartGuard(export async function requestStart(req: DownloadRequest,): Promise<DownloadStartOutcome> {+ // Before the preflight below, which is two round trips the user can navigate+ // during; read after them it would name the page they moved to.+ const originRoute = currentRoute();return runWithPendingStartGuard(req, async () => {let mode: TransportMode = getTransportMode();try {@@ -183,7 +194,9 @@ export async function requestStart(next: mode,resumable: status.resumable,},- pending: req,+ // Without the caller's line: resolved later from the Hub, where "it'll+ // load automatically" is a promise chat cannot keep. The notice stands.+ pending: { ...req, callerToast: undefined },});return "conflict";}@@ -208,7 +221,7 @@ export async function requestStart(description:"Starting with HTTP so an existing partial is not discarded. Switch transport to retry with Xet.",});- await startJob(req, { useXet: false });+ await startJob(req, { useXet: false, originRoute });return isJobActiveFor(req) ? "started" : "error";}toast.warning("Couldn't verify existing partial download", {@@ -216,7 +229,7 @@ export async function requestStart("Starting with the selected transport. If a partial from another transport exists, it may be restarted from the beginning.",});}- await startJob(req, { useXet: mode === TRANSPORT.XET });+ await startJob(req, { useXet: mode === TRANSPORT.XET, originRoute });return isJobActiveFor(req) ? "started" : "error";});}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.tsindex 879d5048b56..d1a582b4797 100644--- a/studio/frontend/src/features/hub/download-manager/xet-progress-notice.ts+++ b/studio/frontend/src/features/hub/download-manager/xet-progress-notice.ts@@ -11,88 +11,32 @@ import {TRANSPORT,} from "./constants";-export const XET_NOTICE_LIMIT = 3;-export const XET_NOTICE_STORAGE_KEY = "unsloth.studio.xetNoticeCount";+// The cap and the count live on the server (utils/xet_notice_settings.py); a copy+// here could only drift out of step with what is enforced.// Longer than the Toaster's 5s default, like the explanatory toasts in chat.export const XET_NOTICE_DURATION_MS = 8000;-// Kept SHORT on purpose, and this is a correctness constraint rather than a-// style preference. The first version of this notice ran 62 characters of-// title and 330 of description, which sonner rendered 235px tall in the-// top-right corner. That is where the Model hub keeps its own toolbar, so for-// the 8s the toast was up it sat on top of the capability filter, the sort-// dropdown, the Models and Datasets tabs and the repo action icons: measured-// by hit testing each control's own centre point, 4 to 6 of them resolved into-// the toast and could not be clicked. That is what got #9159 reverted in-// #9293. The toast has to end above the filter row to block nothing, which-// means roughly 158px, so title plus about two lines of description. Adding a-// sentence here is not free: re-measure before you do.+// SHORT on purpose, as a correctness constraint. At 62 + 330 chars sonner rendered+// this 235px tall over the Model hub toolbar, leaving 4 to 6 controls unclickable for+// 8s, which is what #9293 reverted. It must end above the filter row, near 158px, so+// title plus about two lines. Re-measure before adding a sentence.export const XET_NOTICE_TITLE = "Download is running";-// The "switch to HTTP in Model Hub" advice from the first version is gone on-// purpose. Measured, it cost two rendered lines and put the toast's bottom edge-// at y=126.5 with the hub filter row's centre at y=127: a 0.5px margin, which-// is not a margin. Any font, zoom level or translation longer than the English-// would have pushed it back over and re-broken the toolbar. Without it the-// toast ends around y=100 and stops intersecting the row at all. The transport-// control is two clicks away and discoverable; a toast that eats the toolbar is-// not worth the shortcut.+// The "switch to HTTP in Model Hub" advice is gone on purpose: it cost two lines and+// left the toast bottom at y=126.5 against a row centred at y=127, a margin any font+// or translation would have erased. Without it the toast ends near y=100.export const XET_NOTICE_DESCRIPTION ="Xet sends the file in small pieces, so the bar can sit at 0% and then jump to done. Nothing is stuck.";export const XET_NOTICE_DESCRIPTION_CLASS = "!text-muted-foreground";-// 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();- }+/** The notice, plus whatever the starting surface wanted to add. Chat auto-loads and+ * says so; the Hub does not, passes nothing, and gets the short form. The test budget+ * applies to that form alone, since only it renders over the hub toolbar. */+export function composeNoticeDescription(+ callerToast?: { description: string } | null,+): string {+ const extra = callerToast?.description?.trim();+ return extra ? `${XET_NOTICE_DESCRIPTION} ${extra}` : XET_NOTICE_DESCRIPTION;}/** Only the transport that behaves this way, and only while it is news.@@ -101,19 +45,21 @@ export async function reserveXetNotice(): Promise<boolean> {* 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. */+ * Neither shows the notice nor spends one of the three.+ *+ * No "the caller already toasted" clause: suppressing the notice whenever chat had+ * something to say removed the 0%-explanation where it is most useful. The caller's+ * line is folded in by composeNoticeDescription instead. */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+ args.live);}diff --git a/studio/frontend/src/features/settings/api/xet-notice.ts b/studio/frontend/src/features/settings/api/xet-notice.tsnew file mode 100644index 00000000000..8fcaf08c7cd--- /dev/null+++ b/studio/frontend/src/features/settings/api/xet-notice.ts@@ -0,0 +1,85 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Asking the backend for one of the three Xet notices. The count was in per-origin+// localStorage, and a Studio origin moves whenever port 8888 is taken, so every new+// origin handed out a fresh three and the notice never stopped.++import { authFetch } from "@/features/auth/api";++const LEGACY_COUNT_KEY = "unsloth.studio.xetNoticeCount";+const LEGACY_MIGRATED_KEY = "unsloth.studio.xetNoticeMigrated";++export interface XetNoticeReservation {+ granted: boolean;+ shown: number;+ limit: number;+}++/** A count recorded before the tally moved server-side. Sent until the server+ * confirms it, and it can only raise the stored value. */+function readLegacyCount(): number {+ if (typeof window === "undefined") return 0;+ try {+ if (window.localStorage.getItem(LEGACY_MIGRATED_KEY)) return 0;+ const parsed = Number.parseInt(+ window.localStorage.getItem(LEGACY_COUNT_KEY) ?? "",+ 10,+ );+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : 0;+ } catch {+ // Private mode, or storage disabled. Nothing to migrate.+ return 0;+ }+}++/** Only once a response proves the server took the hint. Marking it on the way out+ * dropped the floor on any failed POST, handing three fresh notices to someone who+ * had already spent them. */+function markLegacyMigrated(): void {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(LEGACY_MIGRATED_KEY, "1");+ } catch {+ // Nothing to record it in; the hint is re-sent next time, which is harmless.+ }+}++function isCount(value: unknown): value is number {+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;+}++/** Take one of the remaining notices, or report that none are left.+ *+ * FAILS CLOSED: an unreachable, older or erroring backend shows nothing. Falling back+ * to the browser count would restore the resetting bug on any failed request. */+export async function reserveXetNoticeFromServer(): Promise<XetNoticeReservation> {+ const denied: XetNoticeReservation = { granted: false, shown: 0, limit: 0 };+ try {+ const res = await authFetch(+ "/api/settings/xet-notice/reserve",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ seen_hint: readLegacyCount() }),+ },+ // This POST increments a counter, so a retry whose predecessor reached the+ // backend spends a second notice. Every other mutation here opts out too.+ { retryNetworkErrors: false },+ );+ if (!res.ok) return denied;+ const body = (await res.json()) as Partial<XetNoticeReservation>;+ // A proxy or older backend can answer this unknown route with a 200 and other+ // JSON, so `res.ok` is no proof the hint was stored. Only a reply reporting the+ // cap it enforced came from the reservation endpoint.+ if (typeof body.granted !== "boolean" || !isCount(body.limit)) return denied;+ markLegacyMigrated();+ return {+ granted: body.granted,+ shown: isCount(body.shown) ? body.shown : 0,+ limit: body.limit,+ };+ } catch {+ return denied;+ }+}diff --git a/studio/frontend/tests/download-start-toast.test.ts b/studio/frontend/tests/download-start-toast.test.tsnew file mode 100644index 00000000000..5c0da969e2e--- /dev/null+++ b/studio/frontend/tests/download-start-toast.test.ts@@ -0,0 +1,159 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The one toast a download start raises, and the three ways it goes away: the+// transfer ends, the user leaves the surface, or the caller never wanted it alone.++import assert from "node:assert/strict";+import test from "node:test";+import { register } from "node:module";++register("./helpers/toast-resolver.mjs", import.meta.url);++let route = "/chat";+Object.defineProperty(globalThis, "window", {+ configurable: true,+ value: {+ location: {+ get pathname() {+ return route;+ },+ },+ },+});++const { calls } = await import("./helpers/toast-stub.mjs");+const {+ dismissStartToast,+ dismissStartToasts,+ liveCallerToast,+ showCallerToast,+ showStartToast,+ startToastId,+} = await import("../src/features/hub/download-manager/start-toast.ts");++function reset(at = "/chat") {+ calls.length = 0;+ route = at;+ dismissStartToasts();+ calls.length = 0;+}++// Compared through a copy, never `calls` itself: node's assert types are `asserts+// actual is T`, so `deepEqual(calls, [])` narrows the shared array to never[] and every+// later read of it fails to typecheck.+function raised() {+ return calls.slice();+}++const MESSAGE = {+ title: "Download is running",+ description: "Nothing is stuck.",+};++test("a start toast is keyed on its job so finalize can drop it", () => {+ reset();+ showStartToast("model:repo:q4", MESSAGE);+ assert.equal(calls[0].kind, "info");+ assert.equal(calls[0].options?.id, startToastId("model:repo:q4"));++ dismissStartToast("model:repo:q4");+ assert.deepEqual(raised()[1], {+ kind: "dismiss",+ id: startToastId("model:repo:q4"),+ });+});++test("leaving the surface that raised it drops it", () => {+ // It lasts 8s from a root-level Toaster, so a start in chat followed by a click+ // on Models parks the composed form over the hub toolbar.+ reset("/chat");+ showStartToast("model:repo:q4", MESSAGE);+ calls.length = 0;++ route = "/hub";+ dismissStartToasts();+ assert.deepEqual(raised(), [+ { kind: "dismiss", id: startToastId("model:repo:q4") },+ ]);++ // Gone for good: a second navigation has nothing left to dismiss.+ calls.length = 0;+ route = "/settings";+ dismissStartToasts();+ assert.deepEqual(raised(), []);+});++test("a raise that lands after the user left is dropped", () => {+ // The Xet reservation is a round trip, so the raise can happen after navigation.+ // The route-change sweep has already run by then, and recording the destination+ // as the origin would leave the composed form on the hub toolbar for its full 8s.+ reset("/chat");+ const startedOn = "/chat";+ route = "/hub";+ showStartToast("model:repo:q4", MESSAGE, startedOn);+ assert.deepEqual(raised(), []);++ // And it is not resurrected by going back.+ route = "/chat";+ dismissStartToasts();+ assert.deepEqual(raised(), []);+});++test("a toast raised on the route it landed on stays", () => {+ // A start can itself navigate, and the toast then belongs where it appeared;+ // dismissing every live toast on any route change would take it straight back out.+ reset("/hub");+ showStartToast("model:repo:q4", MESSAGE);+ calls.length = 0;++ dismissStartToasts();+ assert.deepEqual(raised(), []);+});++test("a noticeOnly caller is folded in or not shown at all", () => {+ // #9663 removed chat's own auto-load toast as a duplicate of the download panel.+ // Its sentence still rides along for the Xet notice to fold in, but on an HTTP+ // start, or once the three notices are spent, it must not come back on its own.+ reset();+ showCallerToast("model:repo:q4", {+ title: "Downloading model",+ description: "It'll load automatically once the download finishes.",+ noticeOnly: true,+ });+ assert.deepEqual(raised(), []);++ showCallerToast("model:repo:q4", {+ title: "Downloading in the background",+ description: "It'll be ready to load once the current model finishes.",+ });+ assert.equal(calls.length, 1);+ assert.equal(calls[0].title, "Downloading in the background");+});++test("a caller line that has gone stale is dropped", () => {+ // Chat moved to another thread while the start was still in flight, so nothing+ // auto-loads any more. The transfer is still running, so the notice it would have+ // been folded into stays true; only the caller's promise goes.+ reset();+ let context = "thread-a";+ const caller = {+ title: "Downloading model",+ description: "It'll load automatically once the download finishes.",+ stillValid: () => context === "thread-a",+ };+ assert.equal(liveCallerToast(caller), caller);++ context = "thread-b";+ assert.equal(liveCallerToast(caller), undefined);++ // No predicate means always valid, which is every other surface.+ assert.equal(liveCallerToast(MESSAGE), MESSAGE);+ assert.equal(liveCallerToast(undefined), undefined);+});++test("a caller with nothing to say is silent", () => {+ reset();+ showCallerToast("model:repo:q4", undefined);+ assert.deepEqual(raised(), []);+});diff --git a/studio/frontend/tests/helpers/toast-resolver.mjs b/studio/frontend/tests/helpers/toast-resolver.mjsnew file mode 100644index 00000000000..e01bff965a3--- /dev/null+++ b/studio/frontend/tests/helpers/toast-resolver.mjs@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// bundler-resolver.mjs's two rules, plus "@/lib/toast" -> a local stub, so a module+// that only raises toasts can be tested without sonner or react.+import { existsSync } from "node:fs";+import { fileURLToPath, pathToFileURL } from "node:url";++const SRC = fileURLToPath(new URL("../../src/", import.meta.url));+const TOAST_STUB = new URL("./toast-stub.mjs", import.meta.url).href;++function firstExisting(base) {+ for (const candidate of [`${base}.ts`, `${base}/index.ts`, base]) {+ if (existsSync(candidate)) return pathToFileURL(candidate).href;+ }+ return null;+}++export function resolve(specifier, context, next) {+ if (specifier === "@/lib/toast") return next(TOAST_STUB, context);+ if (specifier.startsWith("@/")) {+ const resolved = firstExisting(SRC + specifier.slice(2));+ return next(resolved ?? specifier, context);+ }+ if (specifier.startsWith(".") && context.parentURL?.startsWith("file:")) {+ const resolved = firstExisting(+ fileURLToPath(new URL(specifier, context.parentURL)),+ );+ if (resolved) return next(resolved, context);+ }+ return next(specifier, context);+}diff --git a/studio/frontend/tests/helpers/toast-stub.d.mts b/studio/frontend/tests/helpers/toast-stub.d.mtsnew file mode 100644index 00000000000..6876c558d90--- /dev/null+++ b/studio/frontend/tests/helpers/toast-stub.d.mts@@ -0,0 +1,28 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Types for toast-stub.mjs so a .ts test can read the recorded calls without `any`.++export interface ToastCall {+ kind: "default" | "info" | "error" | "warning" | "success" | "dismiss";+ title?: string;+ options?: {+ id?: string;+ description?: string;+ duration?: number;+ classNames?: Record<string, string>;+ };+ id?: string;+}++export declare const calls: ToastCall[];++export declare const toast: ((title: string, options?: unknown) => void) & {+ info: (title: string, options?: unknown) => void;+ error: (title: string, options?: unknown) => void;+ warning: (title: string, options?: unknown) => void;+ success: (title: string, options?: unknown) => void;+ dismiss: (id?: string) => void;+};++export declare function createLoadingToastIcon(): null;diff --git a/studio/frontend/tests/helpers/toast-stub.mjs b/studio/frontend/tests/helpers/toast-stub.mjsnew file mode 100644index 00000000000..aab8f498d66--- /dev/null+++ b/studio/frontend/tests/helpers/toast-stub.mjs@@ -0,0 +1,23 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Stands in for "@/lib/toast", which pulls in sonner and a react component. A test+// that only cares which toasts were raised and dropped reads `calls` instead.+export const calls = [];++export const toast = Object.assign(+ (title, options) => calls.push({ kind: "default", title, options }),+ {+ info: (title, options) => calls.push({ kind: "info", title, options }),+ error: (title, options) => calls.push({ kind: "error", title, options }),+ warning: (title, options) =>+ calls.push({ kind: "warning", title, options }),+ success: (title, options) =>+ calls.push({ kind: "success", title, options }),+ dismiss: (id) => calls.push({ kind: "dismiss", id }),+ },+);++export function createLoadingToastIcon() {+ return null;+}diff --git a/studio/frontend/tests/xet-notice-reservation.test.ts b/studio/frontend/tests/xet-notice-reservation.test.tsindex f134d36e3b0..e064bfb02e5 100644--- a/studio/frontend/tests/xet-notice-reservation.test.ts+++ b/studio/frontend/tests/xet-notice-reservation.test.ts@@ -1,9 +1,14 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// 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.+// Reserving one of the three Xet notices.+//+// The count and limit moved to the server, which does the read and write in one+// transaction, so the Web Locks race this file used to cover is gone and the+// concurrency case lives in test_xet_notice_settings.py.+//+// What is left is the client half: send the legacy count once, and fail CLOSED. A+// local fallback on error would restore the resetting bug on any flaky request.import assert from "node:assert/strict";import test from "node:test";@@ -15,39 +20,156 @@ import {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", {+const LEGACY_COUNT_KEY = "unsloth.studio.xetNoticeCount";+const LEGACY_MIGRATED_KEY = "unsloth.studio.xetNoticeMigrated";++interface FetchCall {+ url: string;+ body: unknown;+}++const calls: FetchCall[] = [];+let respond: () => Promise<Response> = async () =>+ new Response(JSON.stringify({ granted: true, shown: 1, limit: 3 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });++// Stub global fetch, not the authFetch export: ES module namespaces are frozen. This+// also exercises the real header and URL handling. The Tauri retry it wraps only+// engages under Tauri, so a thrown error surfaces immediately.+Object.defineProperty(globalThis, "fetch", {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;- },- },+ value: async (input: RequestInfo | URL, init?: RequestInit) => {+ calls.push({+ url: String(input),+ body: typeof init?.body === "string" ? JSON.parse(init.body) : null,+ });+ return respond();},});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));+const { reserveXetNoticeFromServer } = await import(+ "../src/features/settings/api/xet-notice.ts"+);++function reset() {+ calls.length = 0;+ store.clear();+ respond = async () =>+ new Response(JSON.stringify({ granted: true, shown: 1, limit: 3 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+}++test("a granted reservation is reported as granted", async () => {+ reset();+ const result = await reserveXetNoticeFromServer();+ assert.equal(result.granted, true);+ assert.equal(calls.length, 1);+ assert.match(calls[0].url, /\/api\/settings\/xet-notice\/reserve$/);+});++test("a refused reservation is reported as refused", async () => {+ reset();+ respond = async () =>+ new Response(JSON.stringify({ granted: false, shown: 3, limit: 3 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ const result = await reserveXetNoticeFromServer();+ assert.equal(result.granted, false);+});++test("an error response shows nothing rather than falling back", async () => {+ // Fail closed: a local fallback would reinstate the resetting bug on every failure.+ reset();+ respond = async () => new Response("{}", { status: 500 });+ assert.equal((await reserveXetNoticeFromServer()).granted, false);++ reset();+ respond = async () => {+ throw new Error("network down");+ };+ assert.equal((await reserveXetNoticeFromServer()).granted, false);++ // An older backend has no such route, so the body is not what we expect.+ reset();+ respond = async () =>+ new Response(JSON.stringify({ detail: "Not Found" }), { status: 200 });+ assert.equal((await reserveXetNoticeFromServer()).granted, false);+});++test("a legacy count is sent once, as a floor", async () => {+ // Someone who spent their three in localStorage must not get three more.+ reset();+ store.set(LEGACY_COUNT_KEY, "3");+ await reserveXetNoticeFromServer();+ assert.deepEqual(calls[0].body, { seen_hint: 3 });+ assert.equal(store.get(LEGACY_MIGRATED_KEY), "1");++ // Second call does not resend it: the server is authoritative from here.+ await reserveXetNoticeFromServer();+ assert.deepEqual(calls[1].body, { seen_hint: 0 });+});++test("a legacy count survives a failed reservation", async () => {+ // Marking it migrated on the way out dropped the floor whenever the POST failed:+ // every later request sent 0, so a user who had spent their three got three more.+ reset();+ store.set(LEGACY_COUNT_KEY, "3");+ respond = async () => {+ throw new Error("network down");+ };+ await reserveXetNoticeFromServer();+ assert.equal(store.get(LEGACY_MIGRATED_KEY), undefined);++ respond = async () =>+ new Response(JSON.stringify({ granted: true, shown: 4, limit: 3 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ await reserveXetNoticeFromServer();+ assert.deepEqual(calls[1].body, { seen_hint: 3 });+ assert.equal(store.get(LEGACY_MIGRATED_KEY), "1");+});++test("a 200 that is not a reservation does not end the migration", async () => {+ // A proxy or an older backend can answer this unknown route with a 200 and some+ // other JSON. Treating that as proof the hint was stored drops the floor, and the+ // three notices come back on the next upgrade.+ reset();+ store.set(LEGACY_COUNT_KEY, "3");+ respond = async () =>+ new Response(JSON.stringify({ detail: "Not Found" }), { status: 200 });+ assert.equal((await reserveXetNoticeFromServer()).granted, false);+ assert.equal(store.get(LEGACY_MIGRATED_KEY), undefined);++ respond = async () =>+ new Response(JSON.stringify({ granted: true, shown: 4, limit: 3 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ await reserveXetNoticeFromServer();+ assert.deepEqual(calls[1].body, { seen_hint: 3 });+ assert.equal(store.get(LEGACY_MIGRATED_KEY), "1");+});++test("junk or absent legacy counts migrate as zero", async () => {+ reset();+ await reserveXetNoticeFromServer();+ assert.deepEqual(calls[0].body, { seen_hint: 0 });++ reset();+ store.set(LEGACY_COUNT_KEY, "not a number");+ await reserveXetNoticeFromServer();+ assert.deepEqual(calls[0].body, { seen_hint: 0 });++ reset();+ store.set(LEGACY_COUNT_KEY, "-4");+ await reserveXetNoticeFromServer();+ assert.deepEqual(calls[0].body, { seen_hint: 0 });});diff --git a/studio/frontend/tests/xet-progress-notice.test.ts b/studio/frontend/tests/xet-progress-notice.test.tsindex aa67e4b7e34..2fb38e05abe 100644--- a/studio/frontend/tests/xet-progress-notice.test.ts+++ b/studio/frontend/tests/xet-progress-notice.test.ts@@ -12,20 +12,20 @@ import {registerBundlerResolver,} from "./helpers/kit.ts";-const { store, storage } = installLocalStorageFake();+installLocalStorageFake();registerBundlerResolver();+const noticeModule = await import(+ "../src/features/hub/download-manager/xet-progress-notice.ts"+);const {XET_NOTICE_DESCRIPTION,XET_NOTICE_DESCRIPTION_CLASS,XET_NOTICE_DURATION_MS,- XET_NOTICE_LIMIT,- XET_NOTICE_STORAGE_KEY,XET_NOTICE_TITLE,- recordXetNoticeShown,+ composeNoticeDescription,shouldShowXetNotice,- xetNoticesShown,-} = await import("../src/features/hub/download-manager/xet-progress-notice.ts");+} = noticeModule;const XET_MODEL = {kind: "model",@@ -35,104 +35,49 @@ const XET_MODEL = {} as const;test("the notice is for Xet model downloads and nothing else", () => {- assert.ok(shouldShowXetNotice({ ...XET_MODEL, shown: 0 }));+ assert.ok(shouldShowXetNotice({ ...XET_MODEL }));// 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 }));+ assert.ok(!shouldShowXetNotice({ ...XET_MODEL, transport: "http" }));+ assert.ok(!shouldShowXetNotice({ ...XET_MODEL, kind: "dataset" }));});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 }));+ // Accepted, and it reports that job's transport, but this user started nothing.+ assert.ok(!shouldShowXetNotice({ ...XET_MODEL, attached: true }));});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() }));+ // Nothing to reassure the user about if the download is on its way out.+ assert.ok(!shouldShowXetNotice({ ...XET_MODEL, live: false }));});-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 predicate does not decide the cap", () => {+ // The limit lives on the server (utils/xet_notice_settings.py); a copy here could+ // only drift out of step with what is enforced. The predicate answers "is this+ // worth explaining", and the reservation is the only thing that counts.+ const notice = noticeModule as Record<string, unknown>;+ assert.equal(notice.XET_NOTICE_LIMIT, undefined);+ assert.equal(notice.XET_NOTICE_STORAGE_KEY, undefined);+ assert.equal(notice.xetNoticesShown, undefined);+ assert.equal(notice.recordXetNoticeShown, undefined);});test("the copy reassures, in plain words", () => {- // The reassurance is the whole point of the toast, so it leads and it is the- // only thing here. Explaining chunking, out-of-order writes and batched- // commits is what made the first version 330 characters.+ // The reassurance is the point. Explaining chunking and batched commits is what+ // made the first version 330 characters.assert.match(XET_NOTICE_TITLE, /running/);assert.match(XET_NOTICE_DESCRIPTION, /Nothing is stuck/);});test("the copy stays short enough to clear the hub toolbar", () => {- // This test IS the #9293 revert, written down.+ // This test IS the #9293 revert, written down. At 62 + 330 chars the toast rendered+ // 235px tall over the Model hub toolbar, leaving 4 to 6 controls unclickable for 8s.//- // The first version of this notice ran 62 characters of title and 330 of- // description. Sonner rendered that 235px tall in the top-right corner,- // which is where the Model hub keeps its own toolbar, so while the toast- // was up the capability filter, the sort dropdown, the Models and Datasets- // tabs and the repo action icons were underneath it. Hit testing each- // control's own centre point put 4 to 6 of them inside the toast, meaning- // unclickable, three times per install at 8s each.- //- // The budgets below are not guesses. At 149 characters the toast measured- // 114.5px tall, bottom edge y=126.5, against a filter row whose centre is- // y=127: clickable by half a pixel, which would not have survived a longer- // translation or a zoom level. At 101 it ends near y=100 and does not reach- // the row at all. So 110 is the real ceiling, not the point where it starts- // to break. Nothing else enforces this, and the failure is invisible to unit- // tests and to a screenshot taken at the wrong viewport, which is exactly how- // it shipped the first time.+ // The budgets are measured, not guessed. At 149 chars the bottom edge sat at y=126.5+ // against a filter row centred at y=127: clickable by half a pixel. At 101 it ends+ // near y=100 and never reaches the row, so 110 is the ceiling rather than the point+ // it breaks. Applies to the BASE description only; the composed form is chat-only+ // and has no toolbar beneath it.assert.ok(XET_NOTICE_TITLE.length <= 32,`title is ${XET_NOTICE_TITLE.length} chars, budget 32`,@@ -147,9 +92,33 @@ test("the copy stays short enough to clear the hub toolbar", () => {assert.match(XET_NOTICE_DESCRIPTION_CLASS, /text-muted-foreground/);});+test("the caller's line is folded in rather than raised as a second toast", () => {+ // Reported on main: chat produced the Xet notice AND its own "Downloading model",+ // stacked. Suppressing one loses information, so the sentence joins the notice.+ const composed = composeNoticeDescription({+ description: "It'll load automatically once the download finishes.",+ });+ assert.ok(composed.startsWith(XET_NOTICE_DESCRIPTION));+ assert.match(composed, /load automatically once the download finishes\.$/);+ // Exactly one space at the seam, not a double space or a missing one.+ assert.ok(+ composed.includes(`${XET_NOTICE_DESCRIPTION} It'll`),+ `bad seam: ${composed}`,+ );+});++test("a caller with nothing to add leaves the notice alone", () => {+ // The Hub passes none: nothing auto-loads there, so the sentence would be false.+ assert.equal(composeNoticeDescription(), XET_NOTICE_DESCRIPTION);+ assert.equal(composeNoticeDescription(null), XET_NOTICE_DESCRIPTION);+ assert.equal(+ composeNoticeDescription({ description: " " }),+ XET_NOTICE_DESCRIPTION,+ );+});+test("it stays up longer than the Toaster default", () => {- // Shorter than the first version, but still two sentences a user has to- // notice while looking at a progress bar, and it appears at most 3 times- // ever. 5s is enough to miss entirely.+ // Two sentences to notice while watching a progress bar, at most 3 times ever, so+ // 5s is enough to miss. An upper bound only: it is dismissed when the transfer ends.assert.ok(XET_NOTICE_DURATION_MS > 5000);});