Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: warn when the disk is running low, and point at the caches (#11439)

Daniel Han18bc510097da
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 718f02c3b36..997a7991583 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -368,7 +368,8 @@ from routes.settings import router as settings_router
from routes.prompts import router as prompts_router
from routes.profile_stats import router as profile_stats_router
from auth import policy as auth_policy, storage
-from auth.authentication import get_current_subject
+from auth.authentication import authenticated_via_api_key, get_current_subject
+from hub.utils.host_paths import redact_inventory_host_paths
from utils.hardware import (
start_background_detection,
get_device,
@@ -2411,6 +2412,160 @@ def get_system_info(
}
[email protected]("/api/system/disk")
+def get_disk_space(
+ current_subject: str = Depends(get_current_subject),
+ via_api_key: bool = Depends(authenticated_via_api_key),
+):
+ """Free space where downloads land. One syscall, and nothing else.
+
+ Separate from /api/system because that route enumerates GPUs, reads package metadata and
+ samples CPU: fine for a screen the user is looking at, far too much to run on the chance
+ that a disk is filling. The low-disk notice asks for THIS instead, and only when a download
+ is about to start.
+
+ shutil.disk_usage is statvfs on Linux and macOS and GetDiskFreeSpaceExW on Windows, so this
+ is microseconds on every platform Studio runs on and needs no directory walk. Note that on
+ Windows it reports the quota available to the CALLING user, which is the number that decides
+ whether the download fits, so that difference is the correct one.
+
+ Measured at the models root rather than the filesystem root: those are different volumes
+ whenever HF_HUB_CACHE, or the Studio root, sits on another disk, and the free space that
+ matters is the one the bytes are going to.
+
+ Both roots that receive bytes are measured, not just the hub one. HF_XET_CACHE is resolved
+ independently of HF_HUB_CACHE and holds the Xet chunks every download now streams through,
+ so the two can sit on different volumes and the wrong one has ample room. The TIGHTEST
+ reading wins, because the volume that runs out first is the one that stops the download.
+ Deduplicated by device, so the ordinary install where both live on one disk still costs a
+ single syscall.
+ """
+ from utils.paths.storage_roots import hf_default_cache_dir, studio_root
+
+ # The ACTIVE caches, not the default ones. hf_default_cache_dir() is documented to ignore
+ # HF_HUB_CACHE and the Models Folder setting, so on a machine that moved its downloads to
+ # another volume it would answer about ~/.cache/huggingface, which has nothing to do with
+ # where the next model lands. One SQLite setting read, no walk.
+ roots = []
+ try:
+ from utils.hf_cache_settings import get_hf_cache_paths
+ paths = get_hf_cache_paths()
+ roots.extend((paths.hub_cache, paths.xet_cache))
+ except Exception as exc: # noqa: BLE001 - a settings read must not cost the reading
+ logger.debug(f"Could not resolve the active caches for the disk reading: {exc}")
+
+ def _locate(probe):
+ """(first existing ancestor, its device), or None when this root is unreadable.
+
+ Two failures that look alike and must not be treated alike. A MISSING directory is
+ ordinary, since the cache legitimately does not exist yet on a fresh install, and the
+ volume it would live on is its nearest existing parent. A permission error, an I/O
+ error or a network mount that is not answering is not missing: climbing past it would
+ report the parent filesystem's free space for a disk nothing could read, which is the
+ confidently wrong answer this route exists to avoid. Those leave the root unreadable.
+ """
+ try:
+ chain = [probe, *probe.parents]
+ except (OSError, ValueError, RuntimeError):
+ return None
+ for candidate in chain:
+ try:
+ return candidate, os.stat(candidate).st_dev
+ except (FileNotFoundError, NotADirectoryError):
+ continue
+ except OSError as exc:
+ logger.debug(f"Cache root {candidate} could not be read: {exc}")
+ return None
+ return None
+
+ def _read(candidate):
+ """The reading for one already-located directory, or None if it cannot be taken."""
+ try:
+ usage = shutil.disk_usage(candidate)
+ except (OSError, ValueError):
+ return None
+ return {
+ "path": str(candidate),
+ # Decimal GB, matching /api/system, so the two agree on screen.
+ "total_gb": round(usage.total / 1e9, 2),
+ "free_gb": round(usage.free / 1e9, 2),
+ "percent_used": (
+ round((usage.total - usage.free) / usage.total * 100, 1) if usage.total else 0
+ ),
+ }
+
+ # Locate first, THEN read. Deduplicating after the reading still paid a disk_usage per
+ # root, so the ordinary install with both caches on one disk was doing two probes to
+ # answer about one volume, which is the opposite of what the docstring promises and
+ # costs most on exactly the network mounts this is careful about.
+ located = []
+ seen = set()
+ unreadable = False
+ for root in roots:
+ found = _locate(root)
+ if found is None:
+ # An ACTIVE destination that cannot be read makes the whole answer unknown, rather
+ # than quietly leaving the other one to speak for it. Hub and Xet can sit on
+ # different volumes, so reporting the readable one's free space would be a
+ # confident number about a disk the download is not filling: the same mistake as
+ # climbing past an unreadable root, one level up.
+ unreadable = True
+ continue
+ candidate, device = found
+ if device in seen:
+ continue
+ seen.add(device)
+ located.append(candidate)
+
+ readings = [] if unreadable else [r for r in map(_read, located) if r is not None]
+ if not unreadable and len(readings) != len(located):
+ # A root that located but would not report is the same situation.
+ unreadable = True
+ readings = []
+
+ if unreadable:
+ # Nulls, not zeros, and not a fallback volume either: the caller reads this as
+ # "could not tell", which neither warns nor blocks a download.
+ return {"path": None, "total_gb": None, "free_gb": None, "percent_used": None}
+
+ if not readings:
+ # Nothing resolved: fall back to the same places the old reading used.
+ for probe in (hf_default_cache_dir(), studio_root(), Path(os.path.abspath(os.sep))):
+ found = _locate(probe)
+ reading = None if found is None else _read(found[0])
+ if reading is not None:
+ readings.append(reading)
+ break
+
+ if readings:
+ tightest = min(readings, key = lambda r: r["free_gb"])
+ answer = dict(tightest)
+ # An API key reaches this route through get_current_subject, and `path` is a raw host
+ # path naming the service account and its home layout. The repo already draws that
+ # boundary for the Hub inventory routes; a capacity reading is not a reason to cross
+ # it, and the low-disk client uses only the numbers.
+ #
+ # A managed account is the same disclosure by a different door: its session JWT also
+ # satisfies get_current_subject, and via_api_key is false for it, so the API-key test
+ # alone would hand it the owner's home layout. Resources is owner-only and
+ # /settings/caches sits behind _owner_settings_router, so the path is owner-only here
+ # too. Redacted rather than 403: requestStart and the poll loop call this for whoever
+ # is downloading, owner or not, and the numbers are what that caller needs. On a
+ # single-user install the context defaults to OWNER, so nothing changes.
+ #
+ # The INVENTORY redactor, not redact_host_paths: the latter runs _redact with
+ # redact_ambiguous_path=False and so leaves a field literally named "path" alone,
+ # which is the whole value here. Verified against the real helper, not assumed.
+ from utils.account_context import is_owner_context
+
+ return redact_inventory_host_paths(
+ answer, via_api_key = via_api_key or not is_owner_context()
+ )
+ # Every probe failed. Nulls, not zeros: diskPressure() reads a zero total as psutil having
+ # failed and a zero free as a full disk, and this is neither.
+ return {"path": None, "total_gb": None, "free_gb": None, "percent_used": None}
+
+
@app.get("/api/system/gpu-visibility")
async def get_gpu_visibility(current_subject: str = Depends(get_current_subject)):
# Off-loop: get_device() blocks on detection while the warm is still importing torch.
diff --git a/studio/backend/tests/test_system_disk_route.py b/studio/backend/tests/test_system_disk_route.py
new file mode 100644
index 00000000000..8ed9dbc0dd5
--- /dev/null
+++ b/studio/backend/tests/test_system_disk_route.py
@@ -0,0 +1,477 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""/api/system/disk: one syscall, at the volume the downloads land on.
+
+The low-disk notice used to poll /api/system every 60 s from the app shell. That route
+enumerates GPUs, reads package metadata and samples CPU, so it ran that work forever in every
+open tab to answer a question whose answer only changes when something writes to the disk. The
+notice now asks for this route instead, once on mount and once on the way into a download.
+
+Which means this route has to be cheap enough to sit in front of a download, and has to report
+the volume the bytes are actually going to, which is not the filesystem root whenever the model
+cache lives on another disk.
+"""
+
+from __future__ import annotations
+
+import ast
+import os
+import shutil
+import sys
+import time
+import types
+from pathlib import Path
+
+import pytest
+
+ROUTE_SOURCE = Path(__file__).resolve().parents[1] / "main.py"
+
+
+def _route_source() -> str:
+ src = ROUTE_SOURCE.read_text(encoding = "utf-8")
+ start = src.index('@app.get("/api/system/disk")')
+ return src[start : src.index('@app.get("/api/system/gpu-visibility")', start)]
+
+
+def _route_body() -> ast.FunctionDef:
+ """The route function, parsed. Structure, not text: a comment naming psutil is fine, a call
+ to it is not, and the two are indistinguishable to a grep."""
+ module = ast.parse(_route_source().split("\n", 1)[1])
+ function = module.body[0]
+ assert isinstance(function, ast.FunctionDef)
+ return function
+
+
+def test_the_route_walks_nothing():
+ """A directory walk here would put seconds in front of every download start.
+
+ cache_inventory measures cache sizes by walking, and its own comments call that "seconds on
+ a large uv or triton cache". None of that may be reachable from this route.
+ """
+ called = {
+ node.func.attr
+ for node in ast.walk(_route_body())
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
+ }
+ assert "disk_usage" in called
+ for banned in ("walk", "scandir", "rglob", "iterdir", "glob"):
+ assert banned not in called, f"the disk route calls {banned}"
+
+ names = {node.id for node in ast.walk(_route_body()) if isinstance(node, ast.Name)}
+ assert "psutil" not in names
+ # Imported inside the function, so the resolver is not pulled in at module import time.
+ imported = {
+ alias.name
+ for node in ast.walk(_route_body())
+ if isinstance(node, ast.ImportFrom)
+ for alias in node.names
+ }
+ assert (
+ "hf_default_cache_dir" in imported
+ ), "the route reports the filesystem root, not the models volume"
+ assert (
+ "get_hf_cache_paths" in imported
+ ), "the route reports the default cache, not the configured one"
+
+
+def _real_redactor():
+ """The SHIPPED redactor, not a stand-in.
+
+ A stub here is what let the first version of this guard pass while the route was still
+ handing out the path: it implemented the behaviour I assumed rather than the one the repo
+ has. redact_host_paths runs _redact with redact_ambiguous_path=False and leaves a field
+ named "path" untouched; only the inventory redactor treats it as a host path. Importing
+ the real thing is what makes this test able to fail.
+ """
+ from hub.utils.host_paths import redact_inventory_host_paths
+ return redact_inventory_host_paths
+
+
+def _load_route(
+ monkeypatch,
+ *,
+ hub_cache,
+ default_cache,
+ studio,
+ xet_cache = None,
+ via_api_key = False,
+ is_owner = True,
+):
+ """Run the real route body against stub resolvers, without importing main.py.
+
+ main.py pulls in the whole backend, which no unit test can afford, so the function is
+ compiled from its own source with a no-op decorator and the three modules it imports
+ inside itself replaced. What runs is the shipped code, not a paraphrase of it.
+ """
+ namespace = {
+ "app": types.SimpleNamespace(get = lambda _path: (lambda fn: fn)),
+ "Depends": lambda _dep: None,
+ "get_current_subject": lambda: "alice",
+ "shutil": shutil,
+ "os": os,
+ "Path": Path,
+ "logger": types.SimpleNamespace(debug = lambda *_a, **_k: None),
+ "authenticated_via_api_key": lambda: via_api_key,
+ "redact_inventory_host_paths": _real_redactor(),
+ }
+ storage = types.ModuleType("utils.paths.storage_roots")
+ storage.hf_default_cache_dir = lambda: default_cache
+ storage.studio_root = lambda: studio
+ settings = types.ModuleType("utils.hf_cache_settings")
+ settings.get_hf_cache_paths = lambda: types.SimpleNamespace(
+ hub_cache = hub_cache, xet_cache = hub_cache if xet_cache is None else xet_cache
+ )
+ accounts = types.ModuleType("utils.account_context")
+ accounts.is_owner_context = lambda: is_owner
+ monkeypatch.setitem(sys.modules, "utils.paths.storage_roots", storage)
+ monkeypatch.setitem(sys.modules, "utils.hf_cache_settings", settings)
+ monkeypatch.setitem(sys.modules, "utils.account_context", accounts)
+ exec(compile(_route_source(), "<route>", "exec"), namespace)
+ return namespace["get_disk_space"]
+
+
+def test_the_route_follows_the_configured_models_folder(monkeypatch, tmp_path):
+ """A user who moved the Models Folder to another volume is asking about THAT volume.
+
+ hf_default_cache_dir() is documented to ignore HF_HUB_CACHE and the Studio setting, and its
+ home ancestor always exists, so a route that started there would answer confidently about a
+ disk the download is not going to touch.
+ """
+ configured = tmp_path / "elsewhere" / "hub"
+ configured.mkdir(parents = True)
+ default = tmp_path / "home" / ".cache" / "huggingface" / "hub"
+ default.mkdir(parents = True)
+
+ route = _load_route(
+ monkeypatch, hub_cache = configured, default_cache = default, studio = tmp_path / "s"
+ )
+ assert route(current_subject = "alice")["path"] == str(configured)
+
+
+def test_the_route_still_answers_when_the_settings_read_fails(monkeypatch, tmp_path):
+ """The settings read touches SQLite, and a reading is worth less than a broken download."""
+ broken = types.ModuleType("utils.hf_cache_settings")
+
+ def _raise():
+ raise RuntimeError("no database")
+
+ broken.get_hf_cache_paths = _raise
+ default = tmp_path / "default"
+ default.mkdir()
+ monkeypatch.setitem(sys.modules, "utils.hf_cache_settings", broken)
+
+ storage = types.ModuleType("utils.paths.storage_roots")
+ storage.hf_default_cache_dir = lambda: default
+ storage.studio_root = lambda: tmp_path / "s"
+ monkeypatch.setitem(sys.modules, "utils.paths.storage_roots", storage)
+ namespace = {
+ "app": types.SimpleNamespace(get = lambda _path: (lambda fn: fn)),
+ "Depends": lambda _dep: None,
+ "get_current_subject": lambda: "alice",
+ "shutil": shutil,
+ "os": os,
+ "Path": Path,
+ "logger": types.SimpleNamespace(debug = lambda *_a, **_k: None),
+ "authenticated_via_api_key": lambda: False,
+ "redact_inventory_host_paths": _real_redactor(),
+ }
+ exec(compile(_route_source(), "<route>", "exec"), namespace)
+ assert namespace["get_disk_space"](current_subject = "alice")["path"] == str(default)
+
+
+def test_a_disk_reading_is_microseconds(tmp_path):
+ """The claim the design rests on, measured rather than asserted.
+
+ shutil.disk_usage is statvfs on Linux and macOS and GetDiskFreeSpaceExW on Windows. The
+ budget is deliberately loose, three orders of magnitude above what it costs here, so this
+ fails on a genuinely slow path (a stalled network mount) and not on a busy runner.
+ """
+ shutil.disk_usage(tmp_path) # warm any lazy loading, so the first call is not the sample
+ started = time.perf_counter()
+ for _ in range(200):
+ shutil.disk_usage(tmp_path)
+ per_call_ms = (time.perf_counter() - started) / 200 * 1000
+ assert per_call_ms < 5.0, f"disk_usage took {per_call_ms:.2f} ms per call"
+
+
+def test_a_missing_cache_dir_falls_back_to_a_real_ancestor(tmp_path):
+ """disk_usage raises on a path that does not exist, and the model cache legitimately does
+ not exist yet on a fresh install. The route walks up to the first ancestor that does."""
+ missing = tmp_path / "not" / "created" / "yet"
+ with pytest.raises(OSError):
+ shutil.disk_usage(missing)
+
+ for candidate in (missing, *missing.parents):
+ try:
+ usage = shutil.disk_usage(candidate)
+ except (OSError, ValueError):
+ continue
+ assert usage.total > 0
+ assert candidate in missing.parents
+ break
+ else:
+ pytest.fail("no ancestor of a tmp_path was readable")
+
+
+def test_an_unreadable_host_reports_null_not_zero():
+ """Zero is a different claim from unknown.
+
+ The frontend's diskPressure() reads a zero total as the host having failed and a zero free
+ as a full disk. A route that answered 0 for "I could not tell" would warn every user on a
+ platform where the probe fails.
+ """
+ source = _route_source()
+ assert '"total_gb": None' in source
+ assert '"free_gb": None' in source
+
+
+def test_the_route_reports_the_tighter_of_the_hub_and_xet_volumes(monkeypatch, tmp_path):
+ """HF_XET_CACHE is resolved independently of HF_HUB_CACHE, and every download now streams
+ its chunks through the Xet cache, so the two can sit on different volumes.
+
+ Reading only the hub volume lets an Xet download exhaust its own disk while the route keeps
+ reporting ample space, which is the one answer this endpoint exists to get right. The
+ tighter reading wins: the volume that runs out first is the one that stops the download.
+ """
+ hub = tmp_path / "roomy" / "hub"
+ hub.mkdir(parents = True)
+ xet = tmp_path / "cramped" / "xet"
+ xet.mkdir(parents = True)
+
+ roomy = shutil._ntuple_diskusage(1_000_000_000_000, 100_000_000_000, 900_000_000_000)
+ cramped = shutil._ntuple_diskusage(1_000_000_000_000, 998_000_000_000, 2_000_000_000)
+
+ def fake_usage(path):
+ return cramped if str(xet).startswith(str(path)) or path == xet else roomy
+
+ monkeypatch.setattr(shutil, "disk_usage", fake_usage)
+ # Distinct devices, so the two readings are not deduplicated onto one volume.
+ real_stat = os.stat
+ monkeypatch.setattr(
+ os,
+ "stat",
+ lambda p, *a, **k: types.SimpleNamespace(
+ st_dev = 2 if str(p).startswith(str(tmp_path / "cramped")) else 1
+ )
+ if str(p).startswith(str(tmp_path))
+ else real_stat(p, *a, **k),
+ )
+
+ route = _load_route(
+ monkeypatch,
+ hub_cache = hub,
+ xet_cache = xet,
+ default_cache = tmp_path / "default",
+ studio = tmp_path / "s",
+ )
+ reading = route(current_subject = "alice")
+
+ assert reading["free_gb"] == 2.0, "the roomy hub volume masked the full Xet volume"
+ assert reading["path"] == str(xet)
+
+
+def test_one_volume_is_read_once(monkeypatch, tmp_path):
+ """The negative control for the test above, and the cost claim in the docstring.
+
+ Hub and Xet share a volume on an ordinary install. The first version of this deduplicated
+ AFTER reading, so it still paid a disk_usage per root: two syscalls to answer about one
+ volume on every ordinary machine, which is what the docstring promises not to do and what
+ costs most on a network mount. The device is resolved first now.
+ """
+ both = tmp_path / "cache"
+ (both / "hub").mkdir(parents = True)
+ (both / "xet").mkdir(parents = True)
+
+ calls = []
+ real_usage = shutil.disk_usage
+ monkeypatch.setattr(shutil, "disk_usage", lambda p: (calls.append(str(p)), real_usage(p))[1])
+
+ route = _load_route(
+ monkeypatch,
+ hub_cache = both / "hub",
+ xet_cache = both / "xet",
+ default_cache = tmp_path / "default",
+ studio = tmp_path / "s",
+ )
+ route(current_subject = "alice")
+
+ assert (
+ len(calls) == 1
+ ), f"hub and xet share a volume, so one disk_usage should answer for both; got {calls}"
+
+
+def test_an_api_key_caller_is_not_told_the_host_path(monkeypatch, tmp_path):
+ """get_current_subject accepts an sk-unsloth key, and `path` is a raw host path naming the
+ service account and its home layout. hub/utils/host_paths draws that boundary for the Hub
+ inventory routes already; a capacity reading is not a reason to cross it, and the low-disk
+ client reads only the numbers."""
+ hub = tmp_path / "cache" / "hub"
+ hub.mkdir(parents = True)
+
+ route = _load_route(
+ monkeypatch,
+ hub_cache = hub,
+ default_cache = tmp_path / "d",
+ studio = tmp_path / "s",
+ via_api_key = True,
+ )
+ reading = route(current_subject = "alice", via_api_key = True)
+
+ assert not reading.get("path"), "the raw host path went out to an API-key caller"
+ assert reading["free_gb"] is not None, "the capacity fields must survive redaction"
+
+
+def test_a_ui_session_still_sees_the_path(monkeypatch, tmp_path):
+ """The control. Redacting for everyone would take the path off the Resources tab, which is
+ where a user checks WHICH volume the reading is about."""
+ hub = tmp_path / "cache" / "hub"
+ hub.mkdir(parents = True)
+
+ route = _load_route(
+ monkeypatch,
+ hub_cache = hub,
+ default_cache = tmp_path / "d",
+ studio = tmp_path / "s",
+ )
+ reading = route(current_subject = "alice", via_api_key = False)
+
+ assert reading["path"], "a UI session lost the path it needs to identify the volume"
+
+
+def test_a_managed_account_is_not_told_the_host_path(monkeypatch, tmp_path):
+ """The same disclosure as the API key, through a different door.
+
+ A managed user's session JWT satisfies get_current_subject and leaves via_api_key false,
+ so testing the key alone would hand a non-owner the owner's home layout. Resources is
+ owner-only and /settings/caches sits behind _owner_settings_router; the path is owner-only
+ here too. The numbers survive, because requestStart calls this for whoever downloads.
+ """
+ hub = tmp_path / "cache" / "hub"
+ hub.mkdir(parents = True)
+
+ route = _load_route(
+ monkeypatch,
+ hub_cache = hub,
+ default_cache = tmp_path / "d",
+ studio = tmp_path / "s",
+ is_owner = False,
+ )
+ reading = route(current_subject = "bob", via_api_key = False)
+
+ assert not reading.get("path"), "the raw host path went out to a managed account"
+ assert reading["free_gb"] is not None, "the capacity fields must survive redaction"
+
+
+def test_a_single_user_install_still_sees_the_path(monkeypatch, tmp_path):
+ """The non-vacuous control for the check above.
+
+ account_context defaults to OWNER, so an install that never made a managed account takes
+ the same branch it did before this guard existed. If this fails, the guard is redacting
+ for everybody and the test above passes for the wrong reason.
+ """
+ hub = tmp_path / "cache" / "hub"
+ hub.mkdir(parents = True)
+
+ route = _load_route(
+ monkeypatch,
+ hub_cache = hub,
+ default_cache = tmp_path / "d",
+ studio = tmp_path / "s",
+ is_owner = True,
+ )
+ reading = route(current_subject = "alice", via_api_key = False)
+
+ assert reading["path"], "the owner lost the path on a single-user install"
+
+
+def test_an_unreadable_cache_volume_is_not_reported_as_its_parent(monkeypatch, tmp_path):
+ """Missing and unreadable are different answers.
+
+ A cache directory that does not exist yet is ordinary, and the volume it would live on is
+ its nearest existing parent. A permission error, an I/O error or a network mount that is
+ not answering is not missing: climbing past it reports the parent filesystem's free space
+ for a disk nothing could read, which suppresses the warning with a confidently wrong
+ number. This route already refuses to turn an unreadable host into a zero for the same
+ reason.
+ """
+ roomy = tmp_path / "roomy"
+ roomy.mkdir()
+ cache = roomy / "cache"
+ cache.mkdir()
+
+ real_stat = os.stat
+ real_usage = shutil.disk_usage
+
+ def deny_stat(path, *args, **kwargs):
+ if str(path) == str(cache):
+ raise PermissionError(13, "Permission denied")
+ return real_stat(path, *args, **kwargs)
+
+ def deny_usage(path, *args, **kwargs):
+ # Both calls, because an unreadable volume refuses both and the two versions of this
+ # route fail at different ones: denying only os.stat left the old code reading the
+ # cache happily and the test passing against the bug.
+ if str(path) == str(cache):
+ raise PermissionError(13, "Permission denied")
+ return real_usage(path, *args, **kwargs)
+
+ monkeypatch.setattr(os, "stat", deny_stat)
+ monkeypatch.setattr(shutil, "disk_usage", deny_usage)
+
+ route = _load_route(
+ monkeypatch,
+ hub_cache = cache,
+ xet_cache = cache,
+ default_cache = tmp_path / "missing-default",
+ studio = tmp_path / "missing-studio",
+ )
+ reading = route(current_subject = "alice", via_api_key = False)
+
+ assert reading["path"] != str(
+ roomy
+ ), "an unreadable cache reported its parent volume's free space"
+
+
+def test_one_unreadable_root_does_not_let_the_other_answer_for_it(monkeypatch, tmp_path):
+ """Hub and Xet can be on different volumes, so the readable one is not a stand-in.
+
+ An unavailable network-mounted hub cache beside a local Xet cache would otherwise return
+ the Xet volume's free space: a confident number about a disk the download is not filling,
+ which is the same mistake as climbing past an unreadable root, one level up. Unknown is
+ the honest answer, and the client treats it as neither a warning nor a block.
+ """
+ hub = tmp_path / "mounted" / "hub"
+ hub.mkdir(parents = True)
+ xet = tmp_path / "local" / "xet"
+ xet.mkdir(parents = True)
+
+ real_stat = os.stat
+ real_usage = shutil.disk_usage
+
+ def deny_stat(path, *args, **kwargs):
+ if str(path) == str(hub):
+ raise OSError(5, "Input/output error")
+ return real_stat(path, *args, **kwargs)
+
+ def deny_usage(path, *args, **kwargs):
+ if str(path) == str(hub):
+ raise OSError(5, "Input/output error")
+ return real_usage(path, *args, **kwargs)
+
+ monkeypatch.setattr(os, "stat", deny_stat)
+ monkeypatch.setattr(shutil, "disk_usage", deny_usage)
+
+ route = _load_route(
+ monkeypatch,
+ hub_cache = hub,
+ xet_cache = xet,
+ default_cache = tmp_path / "d",
+ studio = tmp_path / "s",
+ )
+ reading = route(current_subject = "alice", via_api_key = False)
+
+ assert (
+ reading["free_gb"] is None
+ ), "the readable Xet volume answered for an unreadable hub cache"
+ assert reading["path"] is None
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 0651d6b5427..1b71daefab0 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -34,6 +34,7 @@ import {
useSettingsDialogStore,
useShortcut,
} from "@/features/settings";
+import { useLowDiskNotice } from "@/features/settings/hooks/use-low-disk-notice";
import { useTrainingUnloadGuard } from "@/features/training";
import { TransformersUpgradeDialog } from "@/features/transformers-upgrade";
import { useIsMobileShell } from "@/hooks/use-mobile";
@@ -155,6 +156,15 @@ function PersonalizationSyncMount() {
return null;
}
+// A full disk is not a training problem, so the warning cannot live on the
+// training route: it belongs to whichever route the user happens to be on when
+// space runs out. Mounted here it subscribes once for the session, and stays
+// subscribed across navigation, instead of coming and going with /studio.
+function LowDiskNoticeMount() {
+ useLowDiskNotice();
+ return null;
+}
+
// The chat settings are the installation's, and the Models page and the model
// picker read them too, so hydration cannot wait for ChatPage to mount.
function ChatSettingsHydrationMount() {
@@ -548,6 +558,7 @@ function RootLayout() {
<PersonalizationSyncMount />
<ReloadSnapshotPrivacy />
{!isAuthFlowRoute && <ChatSettingsHydrationMount />}
+ {!isAuthFlowRoute && <LowDiskNoticeMount />}
{/* Opens itself when API traffic arrives; hides on the full monitor page. */}
{!isAuthFlowRoute && <ApiMonitorOverlay />}
<HfTokenWarningDialog />
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 97fafde32f5..eaf52b0ae80 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -16,6 +16,8 @@ import { isHuggingFaceOffline } from "@/features/hub/lib/network";
import { dismissCarveoutAdviceForModel, showCarveoutAdvice } from "@/features/igpu-carveout";
// eslint-disable-next-line no-restricted-imports
import { consumeNativePathToken } from "@/features/native-intents/api";
+// eslint-disable-next-line no-restricted-imports
+import { checkDiskSpace } from "@/features/settings/low-disk-check";
import { formatApiErrorBody } from "@/lib/format-fastapi-error";
import {
type ModelRuntime,
@@ -286,25 +288,43 @@ export async function loadModel(
options?.runtime ?? "chat",
payload.model_path ?? null,
async () => {
- const response = await authFetch("/api/inference/load", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- ...payload,
- hf_token: preparedToken.token,
- native_path_lease: payload.nativePathLease ?? null,
- nativePathLease: undefined,
- }),
- signal: options?.signal,
- });
- const loaded = await parseJsonOrThrow<LoadModelResponse>(response, "Model load");
- // Unconditional: absent on nearly every load, anything malformed is ignored,
- // and the model is already resident by the time this runs. Both identities are
- // passed -- a cached Hub candidate is requested by its loadId while the runtime
- // keeps `loaded.model`, and the unload is issued with the second.
- showCarveoutAdvice(loaded.carveout_advice, loaded.model, payload.model_path);
- showLoadWarning(loaded.memory_warning);
- return loaded;
+ // The other way bytes reach the cache. The Hub download manager funnels its transfers
+ // through requestStart, but an uncached model selected here is fetched by the BACKEND
+ // inside this one request, by _maybe_auto_download_model in routes/inference.py, so it
+ // passes no funnel on this side. Without this a load is free to fill the disk between
+ // the mount reading and the next Hub operation, which is the case the notice is for.
+ // Throttled like every other caller, so picking through several models costs one read.
+ void checkDiskSpace();
+ try {
+ const response = await authFetch("/api/inference/load", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ ...payload,
+ hf_token: preparedToken.token,
+ native_path_lease: payload.nativePathLease ?? null,
+ nativePathLease: undefined,
+ }),
+ signal: options?.signal,
+ });
+ const loaded = await parseJsonOrThrow<LoadModelResponse>(response, "Model load");
+ // Unconditional: absent on nearly every load, anything malformed is ignored,
+ // and the model is already resident by the time this runs. Both identities are
+ // passed -- a cached Hub candidate is requested by its loadId while the runtime
+ // keeps `loaded.model`, and the unload is issued with the second.
+ showCarveoutAdvice(loaded.carveout_advice, loaded.model, payload.model_path);
+ showLoadWarning(loaded.memory_warning);
+ return loaded;
+ } finally {
+ // force, for the same reason the download manager's finalize does it: the reading has
+ // to be taken AFTER the write, and unforced it would be swallowed by the interval or
+ // handed the pre-load figure it exists to correct.
+ //
+ // finally, not after the await: a load that FAILED is the likeliest one to have filled
+ // the disk on the way, and telling the user their disk is full is most of the answer
+ // to why it failed. Never a gate, so a rejected load still rejects.
+ void checkDiskSpace({ force: true });
+ }
},
);
}
diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
index 35cf59a3f3e..79c60115634 100644
--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts
+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
@@ -7,6 +7,7 @@ import {
seededMeasuredTransfer,
} from "./adopt-rules";
import { invalidateGgufVariantsCache } from "../inventory/api";
+import { checkDiskSpace } from "@/features/settings/low-disk-check";
import { getHfToken } from "../stores/hf-token-store";
import { bumpInventoryVersion } from "../stores/inventory-events";
import { toast } from "@/lib/toast";
@@ -245,6 +246,16 @@ export function finalize(
dismissStartToast(key);
if (!job) return;
if (TERMINAL_DISPLAY_STATES.has(job.state)) return;
+ // The operation that used the space is the one that should surface the pressure. requestStart
+ // reads the disk before a download, which is the right moment to refuse one, but a download
+ // that STARTS with room and then eats it crosses the threshold with nobody looking: there is
+ // no interval, so without this the warning waits for the next download attempt.
+ //
+ // force, so the reading is taken AFTER the write. Unforced it would be swallowed by the
+ // interval for any download shorter than 30 s, or handed the in-flight pre-download figure
+ // this call exists to correct. Still bounded to one reading in flight and one waiting, so a
+ // queue finishing together costs two rather than one per file.
+ void checkDiskSpace({ force: true });
if (job.kind === DOWNLOAD_KIND.MODEL) {
invalidateGgufVariantsCache(job.repoId);
}
diff --git a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts b/studio/frontend/src/features/hub/download-manager/transport-conflict.ts
index d855ca9510b..600f57724cf 100644
--- a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts
+++ b/studio/frontend/src/features/hub/download-manager/transport-conflict.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { checkDiskSpace } from "@/features/settings/low-disk-check";
import { toast } from "@/lib/toast";
import { disposableTimeoutSignal } from "../lib/abort-signals";
import { getActiveModelDownloads } from "./api";
@@ -162,6 +163,11 @@ export async function requestStart(
// during; read after them it would name the page they moved to.
const originRoute = currentRoute();
const originSelectionEpoch = currentStartToastSelectionEpoch();
+ // The one funnel every download passes through, and the reason the low-disk notice needs no
+ // interval. Not awaited and never a gate: a download is not blocked on a disk reading, and a
+ // host that cannot answer must not stop one. The check throttles itself, so a page that
+ // starts several downloads at once still makes one request.
+ void checkDiskSpace();
return runWithPendingStartGuard(req, async () => {
const preferred: TransportMode = await resolveTransportMode();
let mode: TransportMode = preferred;
diff --git a/studio/frontend/src/features/settings/components/settings-section.tsx b/studio/frontend/src/features/settings/components/settings-section.tsx
index 5e358b37b34..ad56e16369b 100644
--- a/studio/frontend/src/features/settings/components/settings-section.tsx
+++ b/studio/frontend/src/features/settings/components/settings-section.tsx
@@ -1,21 +1,25 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import type { ReactNode } from "react";
+import type { ReactNode, Ref } from "react";
export function SettingsSection({
title,
description,
children,
+ ref,
hideHeading = false,
}: {
title: string;
hideHeading?: boolean;
description?: ReactNode;
children: ReactNode;
+ /** For deep links that scroll a section into view. Optional, so every
+ existing caller renders exactly as before. */
+ ref?: Ref<HTMLElement>;
}) {
return (
- <section data-settings-label={title} className="flex flex-col">
+ <section ref={ref} data-settings-label={title} className="flex flex-col">
{hideHeading ? null : (
<div className="mb-1 flex flex-col gap-0.5">
<h2 className="text-base font-semibold font-heading text-foreground">
diff --git a/studio/frontend/src/features/settings/hooks/use-low-disk-notice.ts b/studio/frontend/src/features/settings/hooks/use-low-disk-notice.ts
new file mode 100644
index 00000000000..758ca252a74
--- /dev/null
+++ b/studio/frontend/src/features/settings/hooks/use-low-disk-notice.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
+
+import { useIsAccountOwner } from "@/features/auth";
+import { useT } from "@/i18n";
+import { toast } from "@/lib/toast";
+import { useEffect } from "react";
+import { checkDiskSpace, setLowDiskNotifier } from "../low-disk-check";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+
+/** Decimal GB, matching /api/system; the unit is in the value because the copy interpolates it bare. */
+function formatGb(value: number | null | undefined): string {
+ if (typeof value !== "number" || !Number.isFinite(value)) return "?";
+ return `${value >= 100 ? value.toFixed(0) : value.toFixed(1)} GB`;
+}
+
+/**
+ * Warn when free disk crosses a threshold, and offer the caches as the thing to trim. Owns the
+ * WORDING, not the schedule: low-disk-check decides when to read.
+ *
+ * Owner only, because "resources" is in OWNER_ONLY_SETTINGS_TABS and resolveSettingsTab would
+ * send a managed account to General, making the action a dead end for state they cannot clear.
+ */
+export function useLowDiskNotice(): void {
+ const t = useT();
+ const isOwner = useIsAccountOwner();
+ const openDialog = useSettingsDialogStore((state) => state.openDialog);
+
+ useEffect(() => {
+ if (!isOwner) return;
+ setLowDiskNotifier((level, disk) => {
+ toast.warning(
+ level === "critical"
+ ? t("settings.resources.storage.lowDisk.criticalTitle")
+ : t("settings.resources.storage.lowDisk.title"),
+ {
+ description: t("settings.resources.storage.lowDisk.description", {
+ free: formatGb(disk.free_gb),
+ total: formatGb(disk.total_gb),
+ }),
+ action: {
+ label: t("settings.resources.storage.lowDisk.action"),
+ onClick: () =>
+ openDialog("resources", { scrollTarget: "resources-caches" }),
+ },
+ },
+ );
+ });
+ // force: a disk already full before Studio started is exactly who this is for.
+ void checkDiskSpace({ force: true });
+ return () => setLowDiskNotifier(null);
+ }, [isOwner, openDialog, t]);
+}
diff --git a/studio/frontend/src/features/settings/low-disk-check.ts b/studio/frontend/src/features/settings/low-disk-check.ts
new file mode 100644
index 00000000000..66879860882
--- /dev/null
+++ b/studio/frontend/src/features/settings/low-disk-check.ts
@@ -0,0 +1,120 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { authFetch } from "@/features/auth";
+// eslint-disable-next-line no-restricted-imports
+import { disposableTimeoutSignal } from "@/features/hub/lib/abort-signals";
+import { observeDiskPressure, type DiskPressure } from "./low-disk";
+
+/**
+ * Ask the host how much room is left, at the moments room matters: when a download is about to
+ * request bytes, plus once at app mount. No interval; /api/system/disk is one syscall.
+ */
+
+/** Registered by the mounted hook: the wording needs i18n and the store, neither reachable here. */
+type Notifier = (level: Exclude<DiskPressure, "ok">, disk: DiskReadingResponse) => void;
+
+let notifier: Notifier | null = null;
+
+export function setLowDiskNotifier(next: Notifier | null): void {
+ notifier = next;
+}
+
+export interface DiskReadingResponse {
+ path?: string | null;
+ total_gb: number | null;
+ free_gb: number | null;
+ percent_used?: number | null;
+}
+
+/** Long enough to collapse a burst of queued downloads, short enough to catch one that filled the disk. */
+const MIN_INTERVAL_MS = 30_000;
+
+let lastCheckedAt = 0;
+let inFlight: Promise<void> | null = null;
+/** At most one reading waiting behind the current one. See `force` below. */
+let queued: Promise<void> | null = null;
+
+export function __resetLowDiskCheckForTests(): void {
+ lastCheckedAt = 0;
+ inFlight = null;
+ queued = null;
+ notifier = null;
+}
+
+/** Long enough for a busy backend, short enough that a wedged read re-arms within one download. */
+const READ_TIMEOUT_MS = 10_000;
+
+async function readDisk(): Promise<DiskReadingResponse | null> {
+ // Bounded, because `inFlight` is the only slot: a fetch that never settles, or a body that
+ // never finishes reading, would hold it for the life of the page and every later reading
+ // would queue behind it or be handed it. The disk warning would then go quiet for the rest
+ // of the session, which is the one failure this feature cannot report on its own. Ten
+ // seconds is far above a syscall the route answers in microseconds.
+ const timeout = disposableTimeoutSignal(READ_TIMEOUT_MS);
+ try {
+ const response = await authFetch("/api/system/disk", { signal: timeout.signal });
+ if (!response.ok) return null;
+ return (await response.json()) as DiskReadingResponse;
+ } catch {
+ // A disk reading is advice, never a gate: a host that cannot answer must not stop a
+ // download or surface an error the user cannot act on. A timeout lands here too.
+ return null;
+ } finally {
+ // The helper's contract: dispose once the request settles, or abort listeners pile up.
+ timeout.dispose();
+ }
+}
+
+function runCheck(): Promise<void> {
+ lastCheckedAt = Date.now();
+ inFlight = (async () => {
+ const disk = await readDisk();
+ if (!disk) return;
+ // BEFORE observing: observeDiskPressure records the level it returns, so running it unheard
+ // spends the crossing and a later owner login hears nothing until free space re-arms.
+ if (!notifier) return;
+ const level = observeDiskPressure(disk);
+ if (level === null) return;
+ try {
+ notifier(level, disk);
+ } catch {
+ // observeDiskPressure has already spent the crossing, so a notifier that throws would
+ // otherwise lose the warning AND reject this detached promise as an unhandled rejection.
+ // Swallowed for the same reason a failed reading is: the disk is advice, and a toast
+ // that could not be shown is not something to fail a download over.
+ }
+ })().finally(() => {
+ inFlight = null;
+ });
+ return inFlight;
+}
+
+/**
+ * Read the disk and warn if a threshold was crossed. Never rejects, never blocks the caller.
+ *
+ * `force` needs a reading taken AFTER it asked, so it skips the interval AND declines to share
+ * an in-flight request, which may be the pre-download reading it is correcting; it chains
+ * behind instead. Bounded at one in flight plus one waiting.
+ */
+export function checkDiskSpace(options: { force?: boolean } = {}): Promise<void> {
+ if (!options.force && Date.now() - lastCheckedAt < MIN_INTERVAL_MS) {
+ return Promise.resolve();
+ }
+ if (inFlight) {
+ // Unforced callers arrive together; any reading answers them all.
+ if (!options.force) return inFlight;
+ if (!queued) {
+ queued = inFlight
+ .then(() => {
+ queued = null;
+ return runCheck();
+ })
+ .catch(() => {
+ queued = null;
+ });
+ }
+ return queued;
+ }
+ return runCheck();
+}
diff --git a/studio/frontend/src/features/settings/low-disk.ts b/studio/frontend/src/features/settings/low-disk.ts
new file mode 100644
index 00000000000..f61faa5cca7
--- /dev/null
+++ b/studio/frontend/src/features/settings/low-disk.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * When to say the disk is filling up, and how often. A level is announced on CROSSING and
+ * re-armed only once free space clears it by REARM_MARGIN_GB, so a disk on the line does not
+ * toast every reading. Thresholds are absolute: a percentage would nag on a 4 TB disk with
+ * 400 GB free.
+ */
+
+export const LOW_DISK_FREE_GB = 20;
+export const CRITICAL_DISK_FREE_GB = 5;
+export const REARM_MARGIN_GB = 5;
+
+export type DiskPressure = "ok" | "low" | "critical";
+
+export type DiskReading = {
+ /** Decimal GB, as /api/system reports it. */
+ free_gb: number | null | undefined;
+ total_gb: number | null | undefined;
+};
+
+export type LowDiskState = {
+ /** Highest level already announced, until free space re-arms it. */
+ notified: DiskPressure;
+};
+
+export const INITIAL_LOW_DISK_STATE: LowDiskState = { notified: "ok" };
+
+const RANK: Record<DiskPressure, number> = { ok: 0, low: 1, critical: 2 };
+
+const BY_RANK: DiskPressure[] = ["ok", "low", "critical"];
+
+const THRESHOLD_GB: Record<DiskPressure, number> = {
+ ok: Number.POSITIVE_INFINITY,
+ low: LOW_DISK_FREE_GB,
+ critical: CRITICAL_DISK_FREE_GB,
+};
+
+function isReadable(value: number | null | undefined): value is number {
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
+}
+
+/** null when the host did not report a usable disk reading. */
+export function diskPressure(disk: DiskReading): DiskPressure | null {
+ if (!isReadable(disk.free_gb) || !isReadable(disk.total_gb)) return null;
+ // A zero total is psutil having failed, not a full disk.
+ if (disk.total_gb <= 0) return null;
+ if (disk.free_gb <= CRITICAL_DISK_FREE_GB) return "critical";
+ if (disk.free_gb <= LOW_DISK_FREE_GB) return "low";
+ return "ok";
+}
+
+export type LowDiskDecision = {
+ state: LowDiskState;
+ notify: Exclude<DiskPressure, "ok"> | null;
+};
+
+/** Announce only an escalation; forget a level only past its re-arm margin. */
+export function nextLowDiskNotice(
+ state: LowDiskState,
+ disk: DiskReading,
+): LowDiskDecision {
+ const pressure = diskPressure(disk);
+ // An unreadable disk is not a recovery: leave the state exactly as it was.
+ if (pressure === null) return { state, notify: null };
+ if (pressure !== "ok" && RANK[pressure] > RANK[state.notified]) {
+ return { state: { notified: pressure }, notify: pressure };
+ }
+ if (RANK[pressure] < RANK[state.notified]) {
+ const forgotten = forgetRearmedLevels(
+ state.notified,
+ disk.free_gb as number,
+ );
+ if (forgotten !== state.notified) {
+ return { state: { notified: forgotten }, notify: null };
+ }
+ }
+ return { state, notify: null };
+}
+
+/** The highest level still armed at *free*. Instantaneous pressure would drop a level the disk
+ * has not cleared: 21 GB clears critical's re-arm point but not low's, earning a second low
+ * warning on the next dip. */
+function forgetRearmedLevels(
+ notified: DiskPressure,
+ free: number,
+): DiskPressure {
+ let level = notified;
+ while (level !== "ok" && free >= THRESHOLD_GB[level] + REARM_MARGIN_GB) {
+ level = BY_RANK[RANK[level] - 1];
+ }
+ return level;
+}
+
+// Per browser session, not per mount: reopening Settings must not re-warn.
+let sessionState: LowDiskState = INITIAL_LOW_DISK_STATE;
+
+export function observeDiskPressure(
+ disk: DiskReading,
+): Exclude<DiskPressure, "ok"> | null {
+ const decision = nextLowDiskNotice(sessionState, disk);
+ sessionState = decision.state;
+ return decision.notify;
+}
+
+export function resetLowDiskNotices(): void {
+ sessionState = INITIAL_LOW_DISK_STATE;
+}
diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
index 46bcdf51b4b..6b56c87aa4e 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -31,7 +31,8 @@ export type SettingsScrollTarget =
| "about-updates"
| "appearance-sidebar-nav"
| "chat-composer"
- | "chat-canvas-network";
+ | "chat-canvas-network"
+ | "resources-caches";
/** Which archive the Data tab should open straight into. */
export type ArchivedShelf = "chats" | "images" | "videos" | "audio";
@@ -118,6 +119,7 @@ const SCROLL_TARGET_TAB: Record<SettingsScrollTarget, SettingsTab> = {
"about-updates": "about",
"appearance-sidebar-nav": "appearance",
"chat-canvas-network": "chat",
+ "resources-caches": "resources",
};
/**
diff --git a/studio/frontend/src/features/settings/tabs/resources-tab.tsx b/studio/frontend/src/features/settings/tabs/resources-tab.tsx
index a7f30cab9f7..42df66a3c15 100644
--- a/studio/frontend/src/features/settings/tabs/resources-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/resources-tab.tsx
@@ -32,12 +32,13 @@ import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import {
type HuggingFaceCacheSettings,
loadHuggingFaceCacheSettings,
updateHuggingFaceCacheSettings,
} from "../api/hugging-face-cache";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import { CacheStorageRows } from "../components/cache-storage-rows";
import { LlamaBackendSection } from "../components/llama-backend-section";
import { ModelMemorySection } from "../components/model-memory-section";
@@ -252,6 +253,12 @@ export function ResourcesTab() {
const systemInfo = useSystemInfo({
pollMs: liveUpdates ? POLL_MS : undefined,
});
+ const storageSectionRef = useRef<HTMLElement | null>(null);
+ const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
+ const consumeScrollTarget = useSettingsDialogStore(
+ (s) => s.consumeScrollTarget,
+ );
+ const openDialog = useSettingsDialogStore((s) => s.openDialog);
const [hfCache, setHfCache] = useState<HuggingFaceCacheSettings | null>(null);
const [hfCacheLoaded, setHfCacheLoaded] = useState(false);
const [cacheBrowserOpen, setCacheBrowserOpen] = useState(false);
@@ -288,6 +295,19 @@ export function ResourcesTab() {
};
}, []);
+ useEffect(() => {
+ if (scrollTarget !== "resources-caches") return;
+ const frame = window.requestAnimationFrame(() => {
+ storageSectionRef.current?.scrollIntoView({
+ block: "start",
+ behavior: "smooth",
+ });
+ consumeScrollTarget("resources-caches");
+ });
+ return () => window.cancelAnimationFrame(frame);
+ }, [consumeScrollTarget, scrollTarget]);
+
+
const metrics = useMemo(() => {
const devices = displayedGpu?.devices ?? [];
const ramTotal = systemInfo.memory?.total_gb ?? 0;
@@ -798,7 +818,10 @@ export function ResourcesTab() {
<ModelMemorySection />
- <SettingsSection title={t("settings.resources.storage.title")}>
+ <SettingsSection
+ ref={storageSectionRef}
+ title={t("settings.resources.storage.title")}
+ >
<InfoRow
label={t("settings.resources.storage.systemDisk")}
value={t("settings.resources.storage.diskUsage", {
diff --git a/studio/frontend/src/features/training/api/train-api.ts b/studio/frontend/src/features/training/api/train-api.ts
index dcaaac69397..a9850c77ae3 100644
--- a/studio/frontend/src/features/training/api/train-api.ts
+++ b/studio/frontend/src/features/training/api/train-api.ts
@@ -3,6 +3,8 @@
import { authFetch } from "@/features/auth";
import { readFastApiError } from "@/lib/format-fastapi-error";
+// eslint-disable-next-line no-restricted-imports
+import { checkDiskSpace } from "@/features/settings/low-disk-check";
import { openStreamResponse } from "@/lib/open-stream-response";
import { createScopedSingleFlightRequest } from "@/lib/single-flight-request";
import {
@@ -150,6 +152,21 @@ export async function startTraining(
payload: TrainingStartRequest,
startRequestId: string,
): Promise<TrainingStartResponse> {
+ // A third way bytes reach the cache, and the largest of them. The worker this
+ // starts downloads the base model itself through FastLanguageModel.from_pretrained
+ // (core/training/trainer.py) and pulls remote datasets, none of which passes
+ // requestStart or loadModel, so a run begun with room and no warning is exactly
+ // the case this notice exists for.
+ //
+ // Only the PRE reading belongs here. The download happens asynchronously in the
+ // worker, long after this request returns, so a forced reading in a finally would
+ // report the disk as it was BEFORE the bytes landed and read as reassurance. The
+ // post-download side is in useTrainingCompletionWatch, which sees the run leave
+ // the active state whether it finished or failed.
+ //
+ // void and throttled, like every other caller: a disk reading must never gate or
+ // delay the start of a run.
+ void checkDiskSpace();
let result: TrainingStartResponse;
try {
result = await runRequestWithTimeout(
diff --git a/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts b/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts
index 3d161c6b813..79bae4d094c 100644
--- a/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts
+++ b/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts
@@ -4,6 +4,8 @@
import { useEffect } from "react";
import { getTrainingStatus } from "../api/train-api";
+// eslint-disable-next-line no-restricted-imports
+import { checkDiskSpace } from "@/features/settings/low-disk-check";
import { createSingleFlightRequest } from "@/lib/single-flight-request";
import {
isTrainingStatusRequestCurrent,
@@ -50,6 +52,17 @@ export function useTrainingCompletionWatch(): void {
return () => {
cancelled = true;
window.clearInterval(id);
+ // The post-download half of the training disk check. startTraining takes the
+ // reading BEFORE the run; the worker then downloads the base model and any
+ // remote dataset on its own time, so the only honest moment to look again is
+ // when the run stops being active. This cleanup is that moment, and it does
+ // not care whether the run finished or failed: a run that died because the
+ // disk filled is precisely the one worth reporting.
+ //
+ // forced, for the reason the download manager's finalize is forced: the
+ // reading has to be taken AFTER the write, and unforced it would be swallowed
+ // by the interval or handed a figure from before the run.
+ void checkDiskSpace({ force: true });
};
}, [active]);
}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 25ddc02079e..bd59f6772ad 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1442,6 +1442,13 @@ export const ar = {
hfHub: "ذاكرة نماذج Hugging Face المؤقتة",
},
},
+ lowDisk: {
+ title: "مساحة القرص على وشك النفاد",
+ criticalTitle: "مساحة القرص منخفضة بشكل حرج",
+ description:
+ "{free} متاحة من أصل {total}. مسح ذاكرات التخزين المؤقت يمكن أن يحرّر مساحة.",
+ action: "مراجعة ذاكرات التخزين المؤقت",
+ },
futureDownloads: "التنزيلات الجديدة فقط",
environmentManaged: "يُدار عبر متغيّر البيئة {variable}.",
locationFree: "{free} متاح",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index c2d07611293..cb4eddd954a 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1483,6 +1483,13 @@ export const de = {
hfHub: "Hugging Face-Modell-Cache",
},
},
+ lowDisk: {
+ title: "Der Speicherplatz wird knapp",
+ criticalTitle: "Der Speicherplatz ist kritisch knapp",
+ description:
+ "{free} frei von {total}. Das Leeren der Caches kann Speicherplatz freigeben.",
+ action: "Caches ansehen",
+ },
},
environment: {
title: "Umgebung",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 2ab63548c75..c07ff594ed0 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1452,6 +1452,12 @@ export const en = {
hfHub: "Hugging Face model cache",
},
},
+ lowDisk: {
+ title: "Disk space is running low",
+ criticalTitle: "Disk space is critically low",
+ description: "{free} free of {total}. Clearing caches can free space.",
+ action: "Review caches",
+ },
},
environment: {
title: "Environment",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 976f84ef0d2..7636ec188b4 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1466,6 +1466,13 @@ export const es = {
hfHub: "Caché de modelos de Hugging Face",
},
},
+ lowDisk: {
+ title: "Queda poco espacio en disco",
+ criticalTitle: "El espacio en disco es críticamente bajo",
+ description:
+ "{free} libres de {total}. Borrar las cachés puede liberar espacio.",
+ action: "Revisar cachés",
+ },
futureDownloads: "Solo las descargas nuevas",
environmentManaged: "Gestionado por la variable de entorno {variable}.",
locationFree: "{free} libres",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 3f99ac814d9..dfee6a2c7b8 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1470,6 +1470,13 @@ export const fr = {
hfHub: "Cache des modèles Hugging Face",
},
},
+ lowDisk: {
+ title: "L'espace disque est presque épuisé",
+ criticalTitle: "L'espace disque est critique",
+ description:
+ "{free} libres sur {total}. Vider les caches peut libérer de l'espace.",
+ action: "Voir les caches",
+ },
futureDownloads: "Nouveaux téléchargements uniquement",
environmentManaged: "Géré par la variable d'environnement {variable}.",
locationFree: "Espace libre : {free}",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 17afdb3f5b4..072a2c87cb0 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1445,6 +1445,13 @@ export const hi = {
hfHub: "Hugging Face मॉडल कैश",
},
},
+ lowDisk: {
+ title: "डिस्क स्पेस कम हो रहा है",
+ criticalTitle: "डिस्क स्पेस बेहद कम है",
+ description:
+ "{total} में से {free} खाली। कैश साफ़ करने से जगह खाली हो सकती है।",
+ action: "कैश देखें",
+ },
futureDownloads: "केवल नए डाउनलोड",
environmentManaged: "{variable} एनवायरनमेंट वेरिएबल द्वारा प्रबंधित।",
locationFree: "{free} खाली",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index bdaed25eedf..7fa806ff414 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1449,6 +1449,13 @@ export const it = {
hfHub: "Cache dei modelli Hugging Face",
},
},
+ lowDisk: {
+ title: "Lo spazio su disco sta per esaurirsi",
+ criticalTitle: "Lo spazio su disco è quasi esaurito",
+ description:
+ "{free} liberi su {total}. Svuotare le cache può liberare spazio.",
+ action: "Controlla le cache",
+ },
},
environment: {
title: "Ambiente",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index bcd578acf5a..1eb6f396c44 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1423,6 +1423,13 @@ export const ja = {
hfHub: "Hugging Faceモデルキャッシュ",
},
},
+ lowDisk: {
+ title: "ディスクの空き容量が少なくなっています",
+ criticalTitle: "ディスクの空き容量が非常に少なくなっています",
+ description:
+ "{total}中{free}が空きです。キャッシュを削除すると空き容量を増やせます。",
+ action: "キャッシュを確認",
+ },
futureDownloads: "新規ダウンロードのみ",
environmentManaged: "環境変数 {variable} で管理されています。",
locationFree: "{free} 空き",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index d8e58558962..b621a5bf453 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1438,6 +1438,13 @@ export const ko = {
hfHub: "Hugging Face 모델 캐시",
},
},
+ lowDisk: {
+ title: "디스크 공간이 부족합니다",
+ criticalTitle: "디스크 공간이 매우 부족합니다",
+ description:
+ "{total} 중 {free} 남음. 캐시를 정리하면 공간을 확보할 수 있습니다.",
+ action: "캐시 확인",
+ },
futureDownloads: "새 다운로드만",
environmentManaged: "{variable} 환경 변수로 관리됩니다.",
locationFree: "{free} 남음",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index bfa737ea368..694bd263a9e 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1454,6 +1454,13 @@ export const ptBR = {
hfHub: "Cache de modelos do Hugging Face",
},
},
+ lowDisk: {
+ title: "O espaço em disco está acabando",
+ criticalTitle: "O espaço em disco está criticamente baixo",
+ description:
+ "{free} livres de {total}. Limpar os caches pode liberar espaço.",
+ action: "Ver caches",
+ },
futureDownloads: "Apenas novos downloads",
environmentManaged: "Gerenciado pela variável de ambiente {variable}.",
locationFree: "{free} livres",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 285d2a7c753..96d9c4b3aa5 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1450,6 +1450,13 @@ export const ru = {
hfHub: "Кеш моделей Hugging Face",
},
},
+ lowDisk: {
+ title: "Заканчивается место на диске",
+ criticalTitle: "Критически мало места на диске",
+ description:
+ "Свободно {free} из {total}. Очистка кешей может освободить место.",
+ action: "Посмотреть кеши",
+ },
futureDownloads: "Только новые загрузки",
environmentManaged: "Управляется переменной окружения {variable}.",
locationFree: "{free} свободно",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index b5d398a36aa..c0608e866e4 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1411,6 +1411,12 @@ export const zhCN = {
hfHub: "Hugging Face 模型缓存",
},
},
+ lowDisk: {
+ title: "磁盘空间不足",
+ criticalTitle: "磁盘空间严重不足",
+ description: "{total}中剩余{free}。清理缓存可以释放空间。",
+ action: "查看缓存",
+ },
futureDownloads: "仅对新下载生效",
environmentManaged: "由环境变量 {variable} 管理。",
locationFree: "{free} 可用",
diff --git a/studio/frontend/tests/chat-save-conflict-detail.test.ts b/studio/frontend/tests/chat-save-conflict-detail.test.ts
index 1e33af2c6b5..df1ad9ae229 100644
--- a/studio/frontend/tests/chat-save-conflict-detail.test.ts
+++ b/studio/frontend/tests/chat-save-conflict-detail.test.ts
@@ -78,6 +78,9 @@ function harness(response: ReturnType<typeof jsonResponse>) {
"@/features/hub/lib/hub-token-header": { hubTokenHeader: () => ({}) },
"@/features/hub/lib/network": { isHuggingFaceOffline: () => false },
"@/features/native-intents/api": { consumeNativePathToken: () => undefined },
+ // loadModel reads the disk on the way in and out: a model the backend has to download
+ // writes to the cache inside that request, passing no download-manager funnel.
+ "@/features/settings/low-disk-check": { checkDiskSpace: () => Promise.resolve() },
"@/lib/model-lifecycle-events": {},
},
);
diff --git a/studio/frontend/tests/load-warning-toast.test.ts b/studio/frontend/tests/load-warning-toast.test.ts
index 12e354f0efa..01d011e124c 100644
--- a/studio/frontend/tests/load-warning-toast.test.ts
+++ b/studio/frontend/tests/load-warning-toast.test.ts
@@ -59,6 +59,9 @@ function chatApi(body: Record<string, unknown>) {
"@/features/hub/lib/hub-token-header": { hubTokenHeader: () => ({}) },
"@/features/hub/lib/network": { isHuggingFaceOffline: () => false },
"@/features/native-intents/api": { consumeNativePathToken: () => undefined },
+ // loadModel reads the disk on the way in and out: a model the backend has to download
+ // writes to the cache inside that request, passing no download-manager funnel.
+ "@/features/settings/low-disk-check": { checkDiskSpace: () => Promise.resolve() },
"@/lib/model-lifecycle-events": {
withModelLoadNotice: async (
_runtime: string,
diff --git a/studio/frontend/tests/low-disk-cache-notice.test.ts b/studio/frontend/tests/low-disk-cache-notice.test.ts
new file mode 100644
index 00000000000..aafae3cfe2b
--- /dev/null
+++ b/studio/frontend/tests/low-disk-cache-notice.test.ts
@@ -0,0 +1,471 @@
+// 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 property that matters is not "does it fire" but "how often": once per
+// crossing, and never again until free space climbs clear of that level.
+
+import assert from "node:assert/strict";
+import { readFileSync, readdirSync } from "node:fs";
+import test from "node:test";
+
+import { en } from "../src/i18n/locales/en.ts";
+
+import {
+ CRITICAL_DISK_FREE_GB,
+ INITIAL_LOW_DISK_STATE,
+ LOW_DISK_FREE_GB,
+ type LowDiskState,
+ REARM_MARGIN_GB,
+ diskPressure,
+ nextLowDiskNotice,
+ observeDiskPressure,
+ resetLowDiskNotices,
+} from "../src/features/settings/low-disk.ts";
+
+function sourceFiles(directory: URL): URL[] {
+ const found: URL[] = [];
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
+ const child = new URL(
+ `${entry.name}${entry.isDirectory() ? "/" : ""}`,
+ directory,
+ );
+ if (entry.isDirectory()) found.push(...sourceFiles(child));
+ else if (/\.tsx?$/.test(entry.name)) found.push(child);
+ }
+ return found;
+}
+
+function disk(freeGb: number, totalGb = 500) {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ return { free_gb: freeGb, total_gb: totalGb };
+}
+
+/** Feed a run of readings and collect only the levels that were announced. */
+function announce(readings: number[]): string[] {
+ let state: LowDiskState = INITIAL_LOW_DISK_STATE;
+ const said: string[] = [];
+ for (const free of readings) {
+ const decision = nextLowDiskNotice(state, disk(free));
+ state = decision.state;
+ if (decision.notify) said.push(decision.notify);
+ }
+ return said;
+}
+
+test("pressure is read from free space, not from percent used", () => {
+ assert.equal(diskPressure(disk(400, 4000)), "ok");
+ assert.equal(diskPressure(disk(LOW_DISK_FREE_GB + 1)), "ok");
+ assert.equal(diskPressure(disk(LOW_DISK_FREE_GB)), "low");
+ assert.equal(diskPressure(disk(CRITICAL_DISK_FREE_GB + 1)), "low");
+ assert.equal(diskPressure(disk(CRITICAL_DISK_FREE_GB)), "critical");
+ assert.equal(diskPressure(disk(0)), "critical");
+});
+
+test("a disk the host could not read is not a warning", () => {
+ assert.equal(diskPressure({ free_gb: null, total_gb: null }), null);
+ // /api/system reports zeros when psutil raised, which is not a full disk.
+ assert.equal(diskPressure(disk(0, 0)), null);
+ assert.equal(diskPressure({ free_gb: Number.NaN, total_gb: 100 }), null);
+});
+
+test("crossing the low threshold warns exactly once", () => {
+ // The same reading arrives on every poll.
+ const readings = [100, 30, 19, 18, 18, 17, 18, 19];
+ assert.deepEqual(announce(readings), ["low"]);
+});
+
+test("falling from low to critical is worth saying again", () => {
+ assert.deepEqual(announce([100, 15, 12, 4, 3]), ["low", "critical"]);
+});
+
+test("a critical disk does not re-warn as low when it recovers a little", () => {
+ // 6 GB clears critical and is still below low, which was already said.
+ assert.deepEqual(announce([3, 11, 4]), ["critical", "critical"]);
+ assert.deepEqual(announce([3, 8, 4]), ["critical"]);
+});
+
+test("recovering out of critical does not disarm the low warning too", () => {
+ // 21 GB clears critical's margin but not low's own re-arm point of 25 GB, and
+ // the instantaneous pressure forgot low there and re-toasted on the next dip.
+ assert.deepEqual(announce([3, 21, 19]), ["critical"]);
+ assert.deepEqual(announce([3, LOW_DISK_FREE_GB + REARM_MARGIN_GB, 19]), [
+ "critical",
+ "low",
+ ]);
+});
+
+test("hovering on the threshold does not toast on every reading", () => {
+ const hovering = [
+ LOW_DISK_FREE_GB - 0.1,
+ LOW_DISK_FREE_GB + 0.1,
+ LOW_DISK_FREE_GB - 0.1,
+ LOW_DISK_FREE_GB + 0.2,
+ LOW_DISK_FREE_GB - 0.2,
+ ];
+ assert.deepEqual(announce(hovering), ["low"]);
+});
+
+test("a real recovery re-arms the warning", () => {
+ const recovered = LOW_DISK_FREE_GB + REARM_MARGIN_GB;
+ assert.deepEqual(announce([10, recovered, 10]), ["low", "low"]);
+ // One byte short of the margin is not a recovery.
+ assert.deepEqual(announce([10, recovered - 0.1, 10]), ["low"]);
+});
+
+test("an unreadable reading in the middle does not re-arm anything", () => {
+ let state = nextLowDiskNotice(INITIAL_LOW_DISK_STATE, disk(10)).state;
+ const blind = nextLowDiskNotice(state, { free_gb: null, total_gb: null });
+ assert.equal(blind.notify, null);
+ state = blind.state;
+ assert.equal(nextLowDiskNotice(state, disk(10)).notify, null);
+});
+
+test("the session state is shared across mounts, not reset by them", () => {
+ resetLowDiskNotices();
+ assert.equal(observeDiskPressure(disk(10)), "low");
+ // Reopening Settings mounts the tab again; the warning was already given.
+ assert.equal(observeDiskPressure(disk(10)), null);
+ assert.equal(observeDiskPressure(disk(2)), "critical");
+ resetLowDiskNotices();
+ assert.equal(observeDiskPressure(disk(10)), "low");
+});
+
+test("the notice fetches its own readings rather than waiting to be told", () => {
+ const hook = readFileSync(
+ new URL(
+ "../src/features/settings/hooks/use-low-disk-notice.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // subscribeSystemInfo only adds a callback to a Set: it never requests
+ // /api/system, so a bare subscriber hears nothing unless the floating monitor
+ // or the resources tab happens to be open, which is not this notice's user.
+ // The notice asks for a reading itself, once, when the shell mounts.
+ assert.match(hook, /checkDiskSpace\(\{ force: true \}\)/);
+ assert.match(hook, /setLowDiskNotifier\(/);
+ assert.match(hook, /toast\.warning\(/);
+ // The description interpolates {free} and {total} bare, so the unit has to be
+ // in the value or the toast reads "4.0 free of 500".
+ assert.match(
+ hook,
+ /\$\{value >= 100 \? value\.toFixed\(0\) : value\.toFixed\(1\)\} GB/,
+ );
+ assert.match(
+ en.settings.resources.storage.lowDisk.description,
+ /\{free\} free of \{total\}/,
+ );
+ // The toast has to lead somewhere: the Storage section it is about.
+ assert.match(hook, /scrollTarget: "resources-caches"/);
+});
+
+test("nothing polls the disk on a timer", () => {
+ // The point of the redesign. An interval here runs in every open tab forever to answer a
+ // question whose answer only changes when something writes to the disk, and the route it used
+ // to poll, /api/system, enumerates GPUs and reads package metadata on the way.
+ for (const file of [
+ "../src/features/settings/hooks/use-low-disk-notice.ts",
+ "../src/features/settings/low-disk-check.ts",
+ ]) {
+ const src = readFileSync(new URL(file, import.meta.url), "utf8");
+ assert.doesNotMatch(src, /setInterval|pollMs|useSystemInfo/, file);
+ }
+});
+
+test("a download asks the disk on the way past", () => {
+ // requestStart is the single funnel every download goes through, which is what lets the
+ // notice drop its timer without going silent for the user who is actually filling the disk.
+ const funnel = readFileSync(
+ new URL(
+ "../src/features/hub/download-manager/transport-conflict.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(funnel, /import \{ checkDiskSpace \}/);
+ // void, not await: a disk reading is advice and must never gate or delay a download.
+ assert.match(funnel, /\n void checkDiskSpace\(\);/);
+
+ const check = readFileSync(
+ new URL("../src/features/settings/low-disk-check.ts", import.meta.url),
+ "utf8",
+ );
+ // One syscall, not the GPU-enumerating route.
+ assert.match(check, /"\/api\/system\/disk"/);
+ assert.doesNotMatch(check, /"\/api\/system"/);
+ // A burst of downloads is still one disk.
+ assert.match(check, /MIN_INTERVAL_MS/);
+ // A host that cannot answer must not surface an error or stop anything.
+ assert.match(check, /return null;/);
+});
+
+test("a reading that never settles cannot silence the feature for the session", () => {
+ // inFlight is the only slot. A fetch that never resolves, or a body that never finishes
+ // reading, would hold it for the life of the page: every later check either queues behind it
+ // or is handed it, so the disk warning goes quiet for the rest of the session. That is the
+ // one failure this feature cannot report on its own, so the read is bounded.
+ const check = readFileSync(
+ new URL("../src/features/settings/low-disk-check.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(check, /disposableTimeoutSignal/);
+ assert.match(check, /READ_TIMEOUT_MS/);
+ // The signal has to reach the request, not merely be constructed.
+ assert.match(check, /authFetch\("\/api\/system\/disk", \{ signal: timeout\.signal \}\)/);
+ // The helper's documented contract: dispose once settled, or abort listeners accumulate.
+ assert.match(check, /finally \{\s*\n\s*\/\/[^\n]*\n\s*timeout\.dispose\(\);/);
+ // A timeout must read as "could not tell", never as a full disk.
+ const read = check.slice(check.indexOf("async function readDisk"));
+ assert.match(read.slice(0, read.indexOf("\n}")), /return null;/);
+});
+
+test("a notifier that throws loses one toast, not the promise and not the session", () => {
+ // observeDiskPressure records the crossing BEFORE the notifier runs, so a throwing notifier
+ // would lose the warning and reject a detached promise nobody awaits.
+ const check = readFileSync(
+ new URL("../src/features/settings/low-disk-check.ts", import.meta.url),
+ "utf8",
+ );
+ const body = check.slice(check.indexOf("function runCheck"));
+ const observe = body.indexOf("observeDiskPressure(disk)");
+ const guarded = body.indexOf("try {\n notifier(level, disk);");
+ assert.ok(guarded !== -1, "the notifier call is not guarded");
+ assert.ok(observe < guarded, "the crossing is spent before the notifier is even attempted");
+ // and inFlight is still cleared, so one bad toast cannot wedge the slot either
+ assert.match(body, /\.finally\(\(\) => \{\s*\n\s*inFlight = null;/);
+});
+
+test("a model load asks the disk too, because the backend downloads inside it", () => {
+ // The download manager is not the only way bytes reach the cache, so requestStart is not the
+ // whole funnel. Selecting an uncached model in Chat calls loadModel, and the BACKEND fetches
+ // the repo inside that one request (_maybe_auto_download_model in routes/inference.py): no
+ // download job is created, so neither requestStart nor the poll loop's finalize ever runs.
+ // Left to the mount reading alone, a load that fills the disk warns nobody until the next
+ // Hub operation, which is exactly the user this notice is for.
+ const api = readFileSync(
+ new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(api, /import \{ checkDiskSpace \}/);
+
+ const load = api.slice(api.indexOf("export async function loadModel"));
+ const body = load.slice(0, load.indexOf("\nexport "));
+ // Before the request, throttled: picking through several models costs one reading.
+ assert.match(body, /void checkDiskSpace\(\);/);
+ // And after it, forced, for the reason finalize is forced: the reading has to be taken after
+ // the write, and unforced it is swallowed by the interval or handed the pre-load figure.
+ assert.match(body, /void checkDiskSpace\(\{ force: true \}\);/);
+ // In a finally: a load that FAILED is the likeliest one to have filled the disk doing it.
+ assert.ok(
+ body.indexOf("} finally {") < body.indexOf("void checkDiskSpace({ force: true })"),
+ "the post-load reading must be in the finally, so a failed load still reports",
+ );
+ // void, never awaited: a disk reading must not gate or delay a model load.
+ assert.doesNotMatch(body, /await checkDiskSpace/);
+});
+
+test("a training run asks the disk on both sides of the worker's download", () => {
+ // The third cache writer, and the largest. start-fresh-training-run and
+ // resume-training-run both call startTraining directly, and the worker then pulls
+ // the base model through FastLanguageModel.from_pretrained plus any remote dataset,
+ // passing neither requestStart nor loadModel.
+ const api = readFileSync(
+ new URL("../src/features/training/api/train-api.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(api, /import \{ checkDiskSpace \}/);
+ const start = api.slice(api.indexOf("export async function startTraining"));
+ const body = start.slice(0, start.indexOf("\nexport "));
+ assert.match(body, /void checkDiskSpace\(\);/);
+ // NOT forced here, and not in a finally: the download happens in the worker long
+ // after this request returns, so a reading taken on return describes the disk
+ // BEFORE the bytes landed and would read as reassurance.
+ assert.doesNotMatch(body, /checkDiskSpace\(\{ force: true \}\)/);
+
+ // The post-download half lives where the run leaves the active state, which
+ // happens whether it completed or failed.
+ const watch = readFileSync(
+ new URL(
+ "../src/features/training/hooks/use-training-completion-watch.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(watch, /import \{ checkDiskSpace \}/);
+ assert.match(watch, /void checkDiskSpace\(\{ force: true \}\);/);
+ // In the effect cleanup, so it fires on the active -> inactive transition rather
+ // than on every poll tick.
+ const cleanup = watch.slice(watch.indexOf("return () => {"));
+ assert.ok(
+ cleanup.indexOf("void checkDiskSpace({ force: true })") !== -1,
+ "the post-run reading must be in the watch cleanup, not on every tick",
+ );
+ assert.doesNotMatch(watch, /await checkDiskSpace/);
+});
+
+test("the disk route does one syscall and no directory walk", () => {
+ const main = readFileSync(
+ new URL("../../backend/main.py", import.meta.url),
+ "utf8",
+ );
+ const route = main.slice(
+ main.indexOf('@app.get("/api/system/disk")'),
+ main.indexOf('@app.get("/api/system/gpu-visibility")'),
+ );
+ assert.ok(route.length > 0, "the disk route is gone");
+ assert.match(route, /shutil\.disk_usage/);
+ // Comments and the docstring stripped first, or a comment merely NAMING one of these names
+ // fails the check below, and a comment explaining why psutil is absent is exactly the kind of
+ // comment this route wants.
+ const code = route
+ .replace(/"""[\s\S]*?"""/g, "")
+ .split("\n")
+ .filter((line) => !line.trim().startsWith("#"))
+ .join("\n");
+ // Not os.walk, not scandir, not the cache inventory: this is asked for on the way into a
+ // download and cannot afford to walk a multi-gigabyte cache.
+ assert.doesNotMatch(code, /os\.walk|scandir|cache_inventory|psutil/);
+ // Measured where the bytes land, which is a different volume whenever the model cache is on
+ // another disk from the filesystem root.
+ assert.match(route, /hf_default_cache_dir/);
+});
+
+test("the notice is mounted in the app shell, not on one route", () => {
+ // A full disk belongs to whichever route the user is on, and the root layout
+ // is the only thing that stays mounted across navigation.
+ const root = readFileSync(
+ new URL("../src/app/routes/__root.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(root, /function LowDiskNoticeMount\(\)/);
+ assert.match(root, /useLowDiskNotice\(\)/);
+ // Not during the auth flow: there is no session to warn, and no Settings to
+ // send the toast's action to.
+ assert.match(root, /!isAuthFlowRoute && <LowDiskNoticeMount \/>/);
+
+ // Exactly one mount in the whole app, or the toast arrives twice on the route
+ // that also mounts it.
+ const callers = sourceFiles(new URL("../src/", import.meta.url)).filter(
+ // The declaration itself reads "function useLowDiskNotice(): void".
+ (file) =>
+ /(?<!function )useLowDiskNotice\(\)/.test(readFileSync(file, "utf8")),
+ );
+ assert.deepEqual(
+ callers.map((file) => file.pathname.split("/src/")[1]),
+ ["app/routes/__root.tsx"],
+ );
+
+ const tab = readFileSync(
+ new URL("../src/features/settings/tabs/resources-tab.tsx", import.meta.url),
+ "utf8",
+ );
+ // ...and the level is still not observed a second time inside Settings.
+ assert.doesNotMatch(tab, /observeDiskPressure/);
+});
+
+test("the cache row is reachable from settings search", () => {
+ const search = readFileSync(
+ new URL("../src/features/settings/settings-search.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(search, /"settings\.resources\.storage\.caches\.label"/);
+ assert.match(search, /"settings\.resources\.storage\.caches\.keywords"/);
+});
+
+test("a forced reading is taken after the request that is already in flight", () => {
+ // The pre-start reading and the completion reading are different questions about the same
+ // disk, and returning the first as the answer to the second reports the space as it was
+ // BEFORE the download wrote anything.
+ const check = readFileSync(
+ new URL("../src/features/settings/low-disk-check.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(check, /if \(!options\.force\) return inFlight;/);
+ // Chained behind it, and coalesced: one waiting, not one per caller.
+ assert.match(check, /queued = inFlight/);
+ assert.match(check, /if \(!queued\)/);
+});
+
+test("the download that used the space is the one that reports it", () => {
+ // requestStart reads the disk BEFORE a download, which is the right moment to refuse one. A
+ // download that starts with room and then eats it crosses the threshold with nobody looking:
+ // there is no interval, so without a completion-side reading the warning waits for the next
+ // download attempt. finalize is the single terminal path for complete, cancelled and error.
+ const loop = readFileSync(
+ new URL("../src/features/hub/download-manager/poll-loop.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(loop, /import \{ checkDiskSpace \}/);
+ const finalize = loop.slice(loop.indexOf("export function finalize"));
+ const body = finalize.slice(0, finalize.indexOf("\nexport "));
+ // void, not await: a reading must never delay the teardown of a finished job. Forced, or the
+ // interval swallows it for any download shorter than 30 s and the in-flight pre-download
+ // reading is handed back in its place, which is the figure this call exists to correct.
+ assert.match(body, /\n void checkDiskSpace\(\{ force: true \}\);/);
+ // After the early returns, or a job that was already terminal asks again on every poll.
+ assert.ok(
+ body.indexOf("TERMINAL_DISPLAY_STATES") < body.indexOf("void checkDiskSpace("),
+ "the reading has to sit after the already-terminal guard, or a job that has already "
+ + "finished asks again on every poll",
+ );
+});
+
+test("the notice is owner only, because its action is", () => {
+ // The shell mounts this hook for every authenticated user, but "resources" is in
+ // OWNER_ONLY_SETTINGS_TABS, so resolveSettingsTab sends a managed account to General.
+ // Warning someone about a disk and handing them a button that lands somewhere else is
+ // worse than not warning them: the caches are install-wide state they cannot clear.
+ const hook = readFileSync(
+ new URL(
+ "../src/features/settings/hooks/use-low-disk-notice.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ hook,
+ /useIsAccountOwner\(\)/,
+ "the low-disk notice does not ask whether the account owns this installation",
+ );
+ assert.match(
+ hook,
+ /if \(!isOwner\) return;/,
+ "the notifier is registered before ownership is checked, so a managed account still gets the toast",
+ );
+
+ const visibility = readFileSync(
+ new URL(
+ "../src/features/settings/settings-tab-visibility.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ visibility,
+ /OWNER_ONLY_SETTINGS_TABS[\s\S]*"resources"/,
+ "resources stopped being owner-only, so this gate may no longer be the right one",
+ );
+});
+
+test("a reading with no notifier registered does not spend the crossing", () => {
+ // The notice is owner-only, but the download path calls checkDiskSpace for everyone.
+ // observeDiskPressure RECORDS the level it returns, so running it with nobody listening
+ // marks the disk as already warned about: a managed account's download, or a reading that
+ // lands after logout, would leave an owner signing in later in the same SPA session hearing
+ // nothing until free space recovered past the re-arm margin.
+ //
+ // Asserted on the source rather than by driving the module, because low-disk-check.ts
+ // imports through the "@/" alias and cannot be loaded by the bare node test runner.
+ const check = readFileSync(
+ new URL("../src/features/settings/low-disk-check.ts", import.meta.url),
+ "utf8",
+ );
+ const guard = check.indexOf("if (!notifier) return;");
+ const observe = check.indexOf("observeDiskPressure(disk)");
+ assert.ok(guard !== -1, "runCheck does not bail out when no notifier is registered");
+ assert.ok(observe !== -1, "runCheck no longer observes disk pressure at all");
+ assert.ok(
+ guard < observe,
+ "observeDiskPressure runs before the notifier check, so a crossing is spent unheard",
+ );
+});