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: Library settings, storage and sortable list columns (#11771)

Michael Han953a2f4d2f7d
diff --git a/studio/backend/core/inference/audio_gallery.py b/studio/backend/core/inference/audio_gallery.py
index a5e58c46607..54a201e1bd2 100644
--- a/studio/backend/core/inference/audio_gallery.py
+++ b/studio/backend/core/inference/audio_gallery.py
@@ -21,7 +21,8 @@ from typing import Any, Optional
from core.inference import gallery_flags
from loggers import get_logger
from utils.account_context import is_owner_context
-from utils.paths import ensure_account_dir, ensure_dir, studio_root
+from utils.paths import ensure_account_dir, studio_root
+from utils.paths.relocations import location_dir
from utils.paths.storage_roots import account_path
logger = get_logger(__name__)
@@ -32,7 +33,8 @@ _ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
def gallery_dir() -> Path:
if is_owner_context():
- return ensure_dir(studio_root() / "audio")
+ # Settings > Library can move the owner's folder elsewhere.
+ return location_dir("audio", studio_root() / "audio")
return ensure_account_dir(account_path("audio"))
diff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.py
index 821411847d8..09739c036a8 100644
--- a/studio/backend/core/inference/image_gallery.py
+++ b/studio/backend/core/inference/image_gallery.py
@@ -23,7 +23,8 @@ from typing import Any, Optional
from core.inference import gallery_flags
from loggers import get_logger
from utils.account_context import is_owner_context
-from utils.paths import ensure_account_dir, ensure_dir, studio_root
+from utils.paths import ensure_account_dir, studio_root
+from utils.paths.relocations import location_dir
from utils.paths.storage_roots import account_path
logger = get_logger(__name__)
@@ -36,7 +37,7 @@ _ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
def gallery_dir() -> Path:
if is_owner_context():
- return ensure_dir(studio_root() / "images")
+ return location_dir("images", studio_root() / "images")
return ensure_account_dir(account_path("images"))
@@ -70,13 +71,16 @@ def _png_bytes(image: Any, meta: dict[str, Any]) -> bytes:
def save(image: Any, meta: dict[str, Any]) -> dict[str, Any]:
"""Persist a PIL image with its recipe embedded; return the gallery record."""
image_id = uuid.uuid4().hex
+ # Encoded before the folder is looked up: a Settings move during the encode would otherwise
+ # finish first, and the image land in the folder it left.
+ data = _png_bytes(image, meta)
directory = gallery_dir()
final_path = directory / f"{image_id}.png"
# Write to a dotted temp (skipped by the *.png glob) then atomically rename, so a crash mid-write never leaves a
# truncated {id}.png in the listing.
tmp_path = directory / f".{image_id}.png.tmp"
try:
- tmp_path.write_bytes(_png_bytes(image, meta))
+ tmp_path.write_bytes(data)
os.replace(tmp_path, final_path)
except BaseException:
try:
diff --git a/studio/backend/core/inference/video_gallery.py b/studio/backend/core/inference/video_gallery.py
index 741e18bb430..8ed827ffc21 100644
--- a/studio/backend/core/inference/video_gallery.py
+++ b/studio/backend/core/inference/video_gallery.py
@@ -23,6 +23,7 @@ from core.inference import gallery_flags
from loggers import get_logger
from utils.account_context import is_owner_context
from utils.paths import ensure_account_dir, ensure_dir, studio_root
+from utils.paths.relocations import location_dir
from utils.paths.storage_roots import account_path
logger = get_logger(__name__)
@@ -36,7 +37,7 @@ _THUMBNAIL_WIDTH = 192
def gallery_dir() -> Path:
if is_owner_context():
- return ensure_dir(studio_root() / "videos")
+ return location_dir("videos", studio_root() / "videos")
return ensure_account_dir(account_path("videos"))
diff --git a/studio/backend/core/library.py b/studio/backend/core/library.py
index c1515111753..066026dd9c0 100644
--- a/studio/backend/core/library.py
+++ b/studio/backend/core/library.py
@@ -22,14 +22,20 @@ and layers its overlay (name, favorite, folder) on top.
from __future__ import annotations
+import contextlib
+import errno
+import filecmp
import functools
import hashlib
import importlib
import io
import mimetypes
import os
+import platform
import re
+import shutil
import stat
+import tempfile
import threading
import time
import uuid
@@ -44,7 +50,7 @@ from urllib.parse import quote, unquote
from core.inference.gallery_projects import UNSAFE_NAME_CHARS, _bad_name
from loggers import get_logger
from storage import library_db
-from utils.paths import ensure_dir
+from utils.paths import relocations, storage_roots
from utils.paths.path_utils import is_path_within, same_path
from utils.paths.storage_roots import account_path
@@ -125,7 +131,76 @@ def _fingerprint(info: os.stat_result) -> str:
def uploads_dir() -> Path:
- return ensure_dir(account_path("library"))
+ return relocations.location_dir("uploads", account_path("library"))
+
+
+_SOURCE_ROOTS: dict[str, Callable[[], Path]] = {
+ "upload": lambda: uploads_dir(),
+ "attachment": lambda: storage_roots.studio_db_path().parent,
+ "image": lambda: _gallery("image").module.gallery_dir(),
+ "video": lambda: _gallery("video").module.gallery_dir(),
+ "audio": lambda: _gallery("audio").module.gallery_dir(),
+ "model:training": lambda: storage_roots.outputs_root(),
+ "model:exported": lambda: storage_roots.exports_root(),
+ "sandbox": lambda: Path(importlib.import_module("core.inference.tools").sandbox_root()),
+}
+
+
+def _nearest_existing(path) -> Path:
+ path = Path(path)
+ return next((candidate for candidate in (path, *path.parents) if candidate.exists()), path)
+
+
+def _device(path) -> Optional[int]:
+ """The filesystem holding ``path``, or its nearest existing parent."""
+ try:
+ return os.stat(_nearest_existing(path)).st_dev
+ except OSError:
+ return None
+
+
+def _disk(path) -> Optional[dict]:
+ try:
+ usage = shutil.disk_usage(_nearest_existing(path))
+ except OSError:
+ return None
+ return {"totalBytes": usage.total, "freeBytes": usage.free}
+
+
+_reported_unavailable: set[str] = set()
+
+
+def _log_unavailable(exc: Exception) -> None:
+ """Once per folder per process: every listing asks again while a drive is unplugged."""
+ if str(exc) not in _reported_unavailable:
+ _reported_unavailable.add(str(exc))
+ logger.info("library.location_unavailable: %s", exc)
+
+
+def disk_usage() -> Optional[dict]:
+ """The disk the Library's own files live on (Studio's while it is unplugged), which need not
+ be the system disk, and the sources on it, so the bar only counts bytes that disk holds. A
+ source that cannot say where it lives is left out rather than failing the listing."""
+ try:
+ home = uploads_dir()
+ except relocations.LocationUnavailable as exc:
+ _log_unavailable(exc)
+ home = storage_roots.studio_root()
+ except OSError:
+ return None
+ disk, device = _disk(home), _device(home)
+ if disk is None:
+ return None
+ sources = []
+ for source, root in _SOURCE_ROOTS.items():
+ try:
+ if _device(root()) == device:
+ sources.append(source)
+ except relocations.LocationUnavailable as exc:
+ _log_unavailable(exc)
+ except Exception:
+ logger.warning("library.source_root_failed: %s", source, exc_info = True)
+ return {**disk, "sources": sources}
def upload_path(upload_id: str) -> Optional[Path]:
@@ -137,15 +212,22 @@ def upload_path(upload_id: str) -> Optional[Path]:
def save_upload(name: str, content_type: str, chunks) -> dict:
"""Stream ``chunks`` to disk and record the upload."""
upload_id = uuid.uuid4().hex
- final_path = uploads_dir() / upload_id
tmp_path = uploads_dir() / f".{upload_id}.tmp"
+ final_path = tmp_path.with_name(upload_id)
size = 0
try:
with open(tmp_path, "wb") as handle:
for chunk in chunks:
size += len(chunk)
handle.write(chunk)
- os.replace(tmp_path, final_path)
+ # Settings > Library may have moved the uploads folder meanwhile. A move leaves `.tmp`
+ # files be, so the upload lands itself, never during a move, wherever uploads live now.
+ with _move_lock:
+ final_path = uploads_dir() / upload_id
+ if final_path.parent == tmp_path.parent:
+ os.replace(tmp_path, final_path)
+ else:
+ shutil.move(str(tmp_path), str(final_path))
return library_db.insert_upload(upload_id, name, content_type, size)
except BaseException:
tmp_path.unlink(missing_ok = True)
@@ -215,11 +297,13 @@ def write_upload_text(
) -> bool:
"""Write an edited note back in `encoding`. A BOM, if the note had one, is the text's first
character, which each of these codecs writes as that encoding's own BOM."""
- path = upload_path(upload_id)
- if path is None:
+ if upload_path(upload_id) is None:
return False
data = text.encode(encoding)
- with _upload_lock:
+ # Under the move lock, so the folder found is where the note stays: a move finishing between
+ # would leave this write in the folder it left.
+ with _move_lock, _upload_lock:
+ path = upload_path(upload_id)
if library_db.get_upload(upload_id) is None:
return False
# The old file stays on disk under a second name for the rollback, not in memory: an
@@ -288,10 +372,20 @@ def _sweep_leftovers() -> None:
def _upload_items() -> list[dict]:
try:
_sweep_leftovers()
+ except relocations.LocationUnavailable:
+ pass # Its drive is unplugged: the rows still list, and disk_usage reports it once.
except OSError:
logger.debug("library.leftover_sweep_failed", exc_info = True)
+ # A row whose file is not in the folder in use (left in one reset while its drive was away)
+ # stays, so copying the files back brings it back, but is not listed or counted meanwhile.
+ try:
+ present = set(os.listdir(uploads_dir()))
+ except OSError:
+ present = None
items = []
for upload in library_db.list_uploads():
+ if present is not None and upload["id"] not in present:
+ continue
item = _item(
f"upload:{upload['id']}",
name = upload["name"],
@@ -388,6 +482,12 @@ def _gallery_items(kind: str) -> list[dict]:
size = path.stat().st_size if path is not None else None
except OSError:
size = None
+ sidecar = None
+ if size is not None:
+ try:
+ sidecar = path.with_suffix(".json").stat().st_size
+ except OSError:
+ pass
items.append(
_item(
f"{kind}:{record['id']}",
@@ -402,6 +502,8 @@ def _gallery_items(kind: str) -> list[dict]:
archived = archived,
)
)
+ if sidecar is not None:
+ items[-1]["storageBytes"] = size + sidecar
return items
@@ -456,8 +558,13 @@ def _model_items() -> list[dict]:
)
items = []
for name, path, origin, model_type, base_model in found:
+ stats_path = Path(path)
+ if model_type == "gguf" and stats_path.is_file():
+ stats_path = stats_path.parent
try:
- size, modified, info = _tree_stats(Path(path))
+ size, modified, info = _tree_stats(stats_path)
+ if stats_path != Path(path):
+ info = os.stat(path)
except OSError:
continue
if base_model is None and origin == "training":
@@ -913,6 +1020,8 @@ def list_items() -> list[dict]:
for source in _SOURCES:
try:
items.extend(source())
+ except relocations.LocationUnavailable as exc:
+ _log_unavailable(exc)
except Exception:
logger.warning("library.source_failed: %s", source.__name__, exc_info = True)
adopt: list[tuple[str, str]] = []
@@ -931,6 +1040,7 @@ def list_items() -> list[dict]:
entry = None
item["favorite"] = bool(entry and entry["favorite"])
item["folderId"] = entry["folderId"] if entry else None
+ item["openedAt"] = entry["openedAt"] if entry else None
if entry and entry["name"]:
item["name"] = entry["name"]
try:
@@ -1251,22 +1361,599 @@ def item_exists(item_id: str, recorded: Optional[str] = None) -> bool:
return False
+_LOCATIONS = {
+ "uploads": "upload",
+ "images": "image",
+ "videos": "video",
+ "audio": "audio",
+ "fineTunes": "model:training",
+ "exports": "model:exported",
+}
+
+
+def _location_path(key: str) -> Path:
+ """Where `key` lives, also while its chosen folder is unavailable."""
+ try:
+ return _SOURCE_ROOTS[_LOCATIONS[key]]()
+ except relocations.LocationUnavailable:
+ return relocations.chosen(key)
+
+
def locations() -> list[dict]:
- """Where each kind of Library file lives, for Settings > Library."""
- from core.inference import audio_gallery, image_gallery, video_gallery
- from utils.paths.storage_roots import exports_root, outputs_root
+ """Where each kind of Library file lives, for Settings > Library. `movable` kinds can be moved
+ with ``move_location``; `custom` says the owner already has. `available` is false while a
+ chosen folder's drive is not there; `disk` is the free space where the folder is, and `device`
+ tells folders on one disk from folders on another (both null while unavailable)."""
+ entries = []
+ for key in _LOCATIONS:
+ path = _location_path(key)
+ available = key not in relocations.MOVABLE or relocations.is_available(key)
+ device = _device(path) if available else None
+ entries.append(
+ {
+ "key": key,
+ "path": str(path),
+ "movable": key in relocations.MOVABLE,
+ "custom": relocations.chosen(key) is not None,
+ "available": available,
+ "disk": _disk(path) if available else None,
+ # A string: a device number can be wider than a JavaScript number is exact.
+ "device": None if device is None else str(device),
+ }
+ )
+ return entries
+
- return [
- {"key": key, "path": str(resolve())}
- for key, resolve in (
- ("uploads", uploads_dir),
- ("images", image_gallery.gallery_dir),
- ("videos", video_gallery.gallery_dir),
- ("audio", audio_gallery.gallery_dir),
- ("fineTunes", outputs_root),
- ("exports", exports_root),
+_OS_CLUTTER = frozenset({".DS_Store", "Thumbs.db", "desktop.ini"})
+# Held for a whole move. A Library upload lands under it, in whichever folder the move leaves in use.
+# Reentrant: the first read of the chosen folders, made under it, can finish a move cut short.
+_move_lock = threading.RLock()
+
+
+def _in_progress(name: str) -> bool:
+ """A save still being written (`.<id>.tmp`, renamed into place when whole), a delete setting its
+ file aside, or the write test. Never moved: the writer renames it by the path it started with."""
+ return name.startswith(".") and (
+ name.endswith((".tmp", ".deleting")) or name.startswith(".unsloth-write-test-")
+ )
+
+
+def _identity(path) -> Optional[tuple[int, int]]:
+ try:
+ info = os.stat(path)
+ except (OSError, ValueError):
+ return None
+ # FAT and some network shares give every entry file id 0, which would make every folder "the
+ # same": those compare by spelling instead.
+ return (info.st_dev, info.st_ino) if info.st_ino else None
+
+
+def _loose(path: Path) -> str:
+ return os.path.normcase(str(path)).casefold()
+
+
+def _inside(path: Path, folder: Path) -> bool:
+ """Whether `path` (or its nearest existing parents) is `folder` or inside it, by what the disk
+ says: resolve() keeps the case it is given, so on a case-insensitive disk (macOS, exFAT, NTFS)
+ or through a bind mount two spellings name one folder."""
+ folder_id = _identity(folder)
+ if folder_id is None:
+ return any(_loose(candidate) == _loose(folder) for candidate in (path, *path.parents))
+ return any(_identity(candidate) == folder_id for candidate in (path, *path.parents))
+
+
+def _same_folder(a: Path, b: Path) -> bool:
+ a_id, b_id = _identity(a), _identity(b)
+ if a_id is None and b_id is None:
+ return _loose(a) == _loose(b)
+ return a_id == b_id
+
+
+def _location_default(key: str) -> Path:
+ return account_path("library") if key == "uploads" else storage_roots.studio_root() / key
+
+
+def _scratch_and_system_folders() -> list[str]:
+ """Folders Library files must not move to although the model download folder may be there:
+ temporary and cache folders the OS empties on its own, and system folders for programs."""
+ home = Path.home()
+ folders = [tempfile.gettempdir()]
+ system = platform.system()
+ if system == "Windows":
+ drive = os.environ.get("SystemDrive", "C:") + "\\"
+ folders += [
+ os.environ.get("TEMP", ""),
+ os.environ.get("TMP", ""),
+ os.path.join(os.environ.get("SystemRoot", drive + "Windows"), "Temp"),
+ os.path.join(os.environ.get("LOCALAPPDATA", str(home / "AppData" / "Local")), "Temp"),
+ os.environ.get("ProgramData", drive + "ProgramData"),
+ drive + "$Recycle.Bin",
+ ]
+ else:
+ folders += ["/tmp", "/var/tmp", "/dev/shm", "/usr", "/bin", "/sbin", "/var", "/snap"]
+ folders += ["/lib", "/lib32", "/lib64", "/libx32", "/private/var", "/private/tmp"]
+ if system == "Darwin":
+ folders += ["/Applications", "/opt/homebrew"]
+ folders += [str(home / "Library" / "Caches"), str(home / ".Trash")]
+ elif str(home) != "/root":
+ folders.append("/root") # Another account's home, where this one cannot keep files.
+ return [folder for folder in folders if folder]
+
+
+def _refuse_denied(resolved: Path) -> None:
+ from hub.storage.scan_folders import (
+ contains_sensitive_path_component,
+ is_denied_system_path,
+ is_within_any,
+ )
+ if is_denied_system_path(str(resolved)) or contains_sensitive_path_component(str(resolved)):
+ raise ValueError("System, credential and config folders cannot hold these files.")
+ if is_within_any(str(resolved), _scratch_and_system_folders()):
+ raise ValueError(
+ "Temporary, cache and program folders cannot hold these files: the system may empty them."
)
- ]
+
+
+def _move_target(raw: str) -> Path:
+ """An absolute, ordinary folder whose parent exists: the model download folder's rules, and no
+ temporary folders."""
+ value = raw.strip()
+ if not value:
+ raise ValueError("Choose a folder.")
+ candidate = Path(value).expanduser()
+ if not candidate.is_absolute():
+ raise ValueError("Choose an absolute folder path.")
+ try:
+ resolved = candidate.resolve(strict = False)
+ except (OSError, RuntimeError, ValueError) as exc:
+ raise ValueError("That folder path is invalid.") from exc
+ if resolved.parent == resolved:
+ raise ValueError("Choose a folder inside the drive, not the drive itself.")
+ _refuse_denied(resolved)
+ if not resolved.parent.is_dir():
+ raise ValueError("The parent folder does not exist.")
+ return resolved
+
+
+_SUBFOLDERS = {
+ "uploads": "Unsloth Library",
+ "images": "Unsloth Images",
+ "videos": "Unsloth Videos",
+ "audio": "Unsloth Audio",
+}
+
+
+def _is_empty(folder: Path) -> bool:
+ return not any(entry.name not in _OS_CLUTTER for entry in folder.iterdir())
+
+
+def _prepare_target(target: Path, key: str, current: Path) -> Path:
+ """The folder the files go to: `target` itself when empty, else a named folder made inside it,
+ and inside a drive's mount point too, so the files stay together on it. Created if needed and
+ checked writable. The named folder can already be `current` (a Reset after a Reset into a
+ default that held files), which is returned as is."""
+ try:
+ target.mkdir(exist_ok = True)
+ if not target.is_dir():
+ raise ValueError("That path is a file, not a folder.")
+ if os.path.ismount(target) or not _is_empty(target):
+ target = target / _SUBFOLDERS[key]
+ if _same_folder(target, current):
+ return target
+ # It can be a link out of the checked folder, so its destination is checked before use.
+ _refuse_denied(target.resolve(strict = False))
+ target.mkdir(exist_ok = True)
+ if not target.is_dir() or not _is_empty(target):
+ raise ValueError(f"{target} already holds files. Choose another folder.")
+ with tempfile.NamedTemporaryFile(prefix = ".unsloth-write-test-", dir = target):
+ pass
+ except PermissionError as exc:
+ raise ValueError("Unsloth cannot write to that folder.") from exc
+ except OSError as exc:
+ raise ValueError(f"Unsloth cannot use that folder: {exc.strerror or exc}") from exc
+ return target
+
+
+def _refuse_overlap(target: Path, key: str, final: bool) -> None:
+ """Refuse a target inside another kind's folder, a chat sandbox (its listing would show the
+ files as tool output, and clearing the chat would delete them), the current folder or Unsloth's
+ own home (the key's default aside). The `final` folder, the one files go into, also must not
+ hold any of them: moving a folder into itself empties it."""
+ current = _location_path(key)
+ others = [_location_path(other) for other in _LOCATIONS if other != key]
+ others.append(_SOURCE_ROOTS["sandbox"]())
+ if any(_inside(target, root) for root in (*others, current)):
+ raise ValueError("That folder is inside another Unsloth folder.")
+ home = storage_roots.studio_root()
+ if _inside(target, home) and not _inside(target, _location_default(key)):
+ raise ValueError("That folder is inside Unsloth's own folder. Choose one outside it.")
+ if final and any(_inside(root, target) for root in (*others, current, home)):
+ raise ValueError("That folder holds Unsloth's own folders. Choose another folder.")
+
+
+def _readable_size(size: int) -> str:
+ value = float(size)
+ for unit in ("B", "KB", "MB", "GB"):
+ if value < 1024:
+ return f"{value:.0f} {unit}" if unit == "B" else f"{value:.1f} {unit}"
+ value /= 1024
+ return f"{value:.1f} TB"
+
+
+def _refuse_short_space(current: Path, target: Path) -> None:
+ """Across disks every byte is copied before the originals go: refuse up front when the target
+ disk cannot hold them all, rather than fill it and undo."""
+ if _device(current) == _device(target):
+ return
+ try:
+ need = _tree_stats(current)[0]
+ except OSError:
+ return
+ free = (_disk(target) or {}).get("freeBytes")
+ if free is not None and need + max(need // 50, 64 * 1024 * 1024) > free:
+ raise ValueError(
+ f"The files take {_readable_size(need)} and that drive has {_readable_size(free)} "
+ "free. Free up space there or choose another drive."
+ )
+
+
+class _MoveLog:
+ """What a move did, so a failure can undo it: each (source, dest, kept) that landed, where
+ `kept` means an identical file was already at `dest` and the original was dropped, and each
+ folder the move made."""
+
+ def __init__(self) -> None:
+ self.moved: list[tuple[Path, Path, bool]] = []
+ self.created: list[Path] = []
+
+
+_rename = os.rename
+_unlink = os.remove
+
+
+def _discard(path: Path) -> None:
+ try:
+ path.unlink(missing_ok = True)
+ except OSError:
+ logger.error("library.move_cleanup_failed: %s", path, exc_info = True)
+
+
+def _in_use_error(path: Path, exc: OSError) -> OSError:
+ # ERROR_SHARING_VIOLATION / ERROR_LOCK_VIOLATION: Windows will not let go of an open file, and
+ # reports most other holds on one as access denied.
+ if getattr(exc, "winerror", None) in (32, 33) or (
+ os.name == "nt" and isinstance(exc, PermissionError)
+ ):
+ return OSError(exc.errno, f"{path} is in use by another program. Close it and try again.")
+ return OSError(exc.errno, f"{path} could not be moved: {exc.strerror or exc}")
+
+
+def _free_name(dest: Path) -> Path:
+ """`name (2).ext`, or the next number free, beside `dest`."""
+ for number in range(2, 10_000):
+ candidate = dest.with_name(f"{dest.stem} ({number}){dest.suffix}")
+ if not os.path.lexists(candidate):
+ return candidate
+ raise FileExistsError(errno.EEXIST, f"{dest} already exists")
+
+
+def _renamed(entry: Path, dest: Path, log: _MoveLog) -> Optional[bool]:
+ """True once `entry` is renamed to `dest`, None when it was deleted meanwhile, False when it
+ has to be copied instead (another drive)."""
+ try:
+ _rename(entry, dest)
+ except OSError as exc:
+ return None if isinstance(exc, FileNotFoundError) and not os.path.lexists(entry) else False
+ log.moved.append((entry, dest, False))
+ return True
+
+
+def _move_file(entry: Path, dest: Path, log: _MoveLog) -> None:
+ """Move one file (or link) to `dest`. Where something is already there, an identical file just
+ lets the original go, and a different one keeps both, the moved one renamed `name (2).ext`:
+ a move never overwrites or deletes a file it did not bring. Across drives the file is copied,
+ then the original removed; if the original cannot go (open in another program on Windows) the
+ copy goes instead, so each file is only ever in one place."""
+ if entry.name == _FLAGS_STORE and os.path.lexists(dest):
+ # Copied over before the switch and written there since: the one left behind is older.
+ _unlink(entry)
+ return
+ kept = os.path.lexists(dest) and _same_bytes(entry, dest)
+ if os.path.lexists(dest) and not kept:
+ dest = _free_name(dest)
+ if not kept:
+ if _renamed(entry, dest, log) is not False:
+ return
+ # Copied under a hidden name and renamed into place whole: a crash part way leaves no
+ # partial file under the real name, which the next pass would take for another file.
+ staged = _staging_name(dest)
+ try:
+ shutil.copy2(entry, staged, follow_symlinks = False)
+ os.replace(staged, dest)
+ except BaseException as exc:
+ _discard(staged)
+ if isinstance(exc, FileNotFoundError) and not os.path.lexists(entry):
+ return
+ if isinstance(exc, PermissionError):
+ raise _in_use_error(entry, exc) from exc
+ raise
+ try:
+ _unlink(entry)
+ except FileNotFoundError:
+ pass
+ except OSError as exc:
+ if not kept:
+ _discard(dest)
+ raise _in_use_error(entry, exc) from exc
+ log.moved.append((entry, dest, kept))
+
+
+_STAGING_SUFFIX = ".moving.tmp"
+_FLAGS_STORE = ".flags.json"
+
+
+def _staging_name(dest: Path) -> Path:
+ """Where a copy across drives is written before it takes `dest`'s name. A dotted `.tmp`, so
+ a listing hides it and a move passes it by as a save in progress."""
+ return dest.with_name(f".{dest.name}{_STAGING_SUFFIX}")
+
+
+def _clear_staging(folder: Path) -> None:
+ """Drop copies a crash cut short, before the move they belonged to starts again."""
+ try:
+ leftovers = list(folder.rglob(f".*{_STAGING_SUFFIX}"))
+ except OSError:
+ return
+ for leftover in leftovers:
+ _discard(leftover)
+
+
+def _same_bytes(a: Path, b: Path) -> bool:
+ try:
+ return a.is_file() and b.is_file() and filecmp.cmp(a, b, shallow = False)
+ except OSError:
+ return False
+
+
+def _move_entry(entry: Path, dest: Path, log: _MoveLog) -> None:
+ """Move `entry` to `dest`. A folder is renamed whole where it can be; across drives, or onto a
+ folder already there, it is merged in file by file, and the emptied original removed with
+ rmdir alone, which cannot take anything with it."""
+ if entry.name in _OS_CLUTTER or _in_progress(entry.name):
+ return
+ if not (entry.is_dir() and not entry.is_symlink()):
+ _move_file(entry, dest, log)
+ return
+ if not os.path.lexists(dest) and _renamed(entry, dest, log) is not False:
+ return
+ if os.path.lexists(dest) and not (dest.is_dir() and not dest.is_symlink()):
+ dest = _free_name(dest)
+ if not dest.is_dir():
+ dest.mkdir()
+ log.created.append(dest)
+ try:
+ children = list(entry.iterdir())
+ except FileNotFoundError:
+ return
+ for child in children:
+ _move_entry(child, dest / child.name, log)
+ try:
+ entry.rmdir()
+ except OSError:
+ pass # A save still writing in it, left for the next pass.
+
+
+def _move_entries(
+ source: Path,
+ target: Path,
+ log: _MoveLog,
+ only = None,
+) -> None:
+ """Move everything in `source` into `target`, noting each move in `log` as it lands so a
+ failure part way can be undone. Never an entry that holds `target` itself."""
+ for entry in list(source.iterdir()):
+ if (only is None or only(entry)) and not _inside(target, entry):
+ _move_entry(entry, target / entry.name, log)
+
+
+def _undo(log: _MoveLog) -> None:
+ """Put back everything `log` moved, then the folders it made, as long as they are empty."""
+ for source, dest, kept in reversed(log.moved):
+ try:
+ source.parent.mkdir(parents = True, exist_ok = True)
+ if not kept:
+ _move_entry(dest, source, _MoveLog())
+ elif not os.path.lexists(source):
+ shutil.copy2(dest, source, follow_symlinks = False)
+ except OSError:
+ logger.error("library.move_rollback_failed: %s", dest, exc_info = True)
+ for folder in reversed(log.created):
+ try:
+ folder.rmdir()
+ except OSError:
+ pass # Something was saved into it meanwhile; the stray pass takes that back.
+
+
+# How long a finished move waits for saves still writing to the old folder, and how recently a
+# save must have written to count as still writing (a crash's leftover does not hold a move up).
+_SETTLE_SECONDS = 30.0
+_WRITING_SECONDS = 10.0
+
+
+def _writing_in(folder: Path) -> bool:
+ now = time.time()
+ try:
+ entries = list(folder.iterdir())
+ except OSError:
+ return False
+ for entry in entries:
+ if entry.name.endswith(".tmp") and _in_progress(entry.name):
+ try:
+ if now - entry.stat().st_mtime < _WRITING_SECONDS:
+ return True
+ except OSError:
+ continue
+ return False
+
+
+def _settle(
+ source: Path,
+ target: Path,
+ wait: bool,
+ only = None,
+) -> None:
+ """Pick up what landed in `source` after the switch: saves that were already writing there.
+ Repeats until a pass finds nothing new and, with `wait`, nothing is still being written, for
+ at most _SETTLE_SECONDS."""
+ deadline = time.monotonic() + _SETTLE_SECONDS
+ while True:
+ log = _MoveLog()
+ try:
+ _move_entries(source, target, log, only)
+ except OSError:
+ logger.warning("library.move_straggler_failed: %s", source, exc_info = True)
+ return
+ writing = wait and _writing_in(source)
+ if not log.moved and not writing:
+ return
+ if time.monotonic() >= deadline:
+ if writing:
+ logger.warning("library.move_straggler_timeout: %s", source)
+ return
+ time.sleep(0.1)
+
+
+def move_location(key: str, path: Optional[str]) -> Optional[str]:
+ """Move one kind of file to another folder, files and all, and keep saving there. `path` None
+ moves it back to the default. Owner only; the caller checks.
+
+ The switch is recorded first, so a file saved during the move already lands in the new folder;
+ later passes then pick up saves that were writing to the old one. On a failure everything
+ moved so far goes back, with anything saved into the new folder meanwhile, and the old folder
+ stays in use. Returns the folder whose files were left where they are, for a Reset while its
+ drive is not there or a choice of the folder standing in for it, else None. Raises ValueError for a folder that cannot be used,
+ RuntimeError when the move itself fails."""
+ if key not in relocations.MOVABLE:
+ raise ValueError(
+ "These files stay where they are: training and chats remember them by path."
+ )
+ with _move_lock:
+ # A move cut short is finished first, now that its drives may be back: a new one started
+ # over it would forget the files still in the folder it was leaving.
+ if relocations.moving_from(key) is not None:
+ _resume_move(key)
+ current = _location_path(key).resolve()
+ if not relocations.is_available(key):
+ if path is not None:
+ raise ValueError(
+ f"{current} is not available, so its files cannot move. Reconnect its drive, "
+ "or reset the folder."
+ )
+ relocations.set_chosen(key, None)
+ return str(current)
+ target = _move_target(path) if path is not None else _location_default(key).resolve()
+ if _same_folder(target, current):
+ return _settle_waiting_move(key, current)
+ _refuse_while_waiting(key)
+ _refuse_overlap(target, key, final = False)
+ _refuse_short_space(current, target)
+ # Resolved again: the named subfolder can be a link to somewhere else entirely, or another
+ # kind's folder.
+ target = _prepare_target(target, key, current).resolve()
+ if _same_folder(target, current):
+ return _settle_waiting_move(key, current)
+ _refuse_overlap(target, key, final = True)
+ _refuse_short_space(current, target)
+ previous, previous_from = relocations.chosen(key), relocations.moving_from(key)
+ before = {entry.name for entry in target.iterdir()}
+ from core.inference import gallery_flags
+
+ # The pin/archive store is copied over first, under its lock: a flag set in the new folder
+ # before it arrived would start an empty store there, and Clear then deletes the archive.
+ # Only where a store is: the lock makes a lock file, which would then move as a file.
+ store = current / _FLAGS_STORE
+ with gallery_flags.exclusive(current) if store.is_file() else contextlib.nullcontext():
+ if store.is_file() and not os.path.lexists(target / _FLAGS_STORE):
+ shutil.copy2(store, target / _FLAGS_STORE)
+ # Recorded with the folder the files leave, so a crash part way is finished on restart.
+ relocations.set_chosen(key, target, moving_from = current)
+ log = _MoveLog()
+ try:
+ _move_entries(current, target, log)
+ except OSError as exc:
+ _undo(log)
+ relocations.set_chosen(key, previous, moving_from = previous_from)
+ _settle(target, current, wait = False, only = lambda entry: entry.name not in before)
+ raise RuntimeError(f"Could not move the files: {exc.strerror or exc}") from exc
+ _settle(current, target, wait = key != "uploads")
+ _finish_move(key, target)
+ return None
+
+
+def _refuse_while_waiting(key: str) -> None:
+ """ValueError while a move cut short still waits for a drive: files are on it, and a move from
+ here would leave them behind."""
+ if relocations.moving_from(key) is None:
+ return
+ missing = (
+ relocations.moving_from(key)
+ if relocations.chosen_available(key)
+ else relocations.chosen(key)
+ )
+ raise ValueError(
+ f"Some of these files are still in {missing}, which is not connected. Reconnect its "
+ "drive so their move can finish first."
+ )
+
+
+def _settle_waiting_move(key: str, current: Path) -> Optional[str]:
+ """The folder in use chosen again. While it stands in for a chosen folder whose drive is gone,
+ that is a choice to stay: the move waiting for the drive is dropped, and the folder whose files
+ are left on it returned."""
+ if relocations.moving_from(key) is None or relocations.chosen_available(key):
+ return None
+ waiting = relocations.chosen(key)
+ relocations.set_chosen(key, None if _same_folder(current, _location_default(key)) else current)
+ return str(waiting)
+
+
+def _finish_move(key: str, target: Path) -> None:
+ relocations.set_chosen(key, None if _same_folder(target, _location_default(key)) else target)
+
+
+def _resume_move(key: str) -> None:
+ """Finish a move a crash cut short: what is still in the folder it left goes on into the chosen
+ one, merged as the move merges. While either folder's drive is not there the move waits for
+ it, the old folder standing in for a missing chosen one. A failure is logged and tried again
+ on the next start."""
+ with _move_lock:
+ source = relocations.moving_from(key)
+ if source is None:
+ return
+ target = relocations.chosen(key)
+ if not relocations.chosen_available(key):
+ # What went there waits on that drive, so the move stays open: the folder the files
+ # were leaving takes new ones meanwhile, and the first start with the drive back
+ # finishes it.
+ logger.warning("library.move_resume_unavailable: %s", target)
+ relocations.wait_for_move(key)
+ return
+ if not relocations.moving_from_available(key):
+ # What is still on its drive waits for it: the move stays open, and is finished on the
+ # first start the drive is back. The chosen folder takes new files meanwhile.
+ logger.warning("library.move_resume_source_unavailable: %s", source)
+ return
+ try:
+ _clear_staging(target)
+ if source.is_dir():
+ _move_entries(source, target, _MoveLog())
+ except OSError:
+ logger.warning("library.move_resume_failed: %s", source, exc_info = True)
+ return
+ _finish_move(key, target)
+
+
+relocations.resume_move = _resume_move
def _delete_upload(upload_id: str, path: Path) -> bool:
@@ -1297,16 +1984,40 @@ class ItemChanged(RuntimeError):
"""Another file now has the path the item was listed at; nothing was deleted."""
+# Held by a delete and by an open's check and write, so an open cannot land between a delete's
+# removal of the item and of its row, and bring the row back.
+_overlay_lock = threading.Lock()
+
+
+def mark_opened(item_id: str) -> bool:
+ """Record that the item was just opened, kept for the file it is now. False when it is not
+ there, or is a path whose file is gone."""
+ with _overlay_lock:
+ found = fingerprint(item_id)
+ if found is None and (path_derived(item_id) or not item_exists(item_id)):
+ return False
+ library_db.mark_opened(item_id, fingerprint = found)
+ return True
+
+
def delete_item(item_id: str, fingerprint: Optional[str] = None) -> bool:
"""Delete an item from its source. Returns False when the source no longer has it. With the
`fingerprint` it was listed with, a path-derived item is only deleted while it is that file;
ItemChanged otherwise."""
+ with _overlay_lock:
+ return _delete_item(item_id, fingerprint)
+
+
+def _delete_item(item_id: str, fingerprint: Optional[str]) -> bool:
kind, _, ref = item_id.partition(":")
deleted = False
if kind == "upload":
- path = upload_path(ref)
- if path is not None:
- deleted = _delete_upload(ref, path)
+ # Under the move lock, as a note save: a move finishing between finding the file and
+ # setting it aside would leave it moved, and its row dropped as if it were gone.
+ with _move_lock:
+ path = upload_path(ref)
+ if path is not None:
+ deleted = _delete_upload(ref, path)
elif kind == "attachment":
from storage.studio_db import delete_chat_attachment
message_id, attachment_id = _attachment_ref(ref)
@@ -1327,7 +2038,10 @@ def delete_item(item_id: str, fingerprint: Optional[str] = None) -> bool:
elif kind == "sandbox":
deleted = _delete_sandbox_file(ref, fingerprint)
elif kind == "model":
- raise ValueError("Fine-tuned models are deleted from the model picker.")
+ _origin, _, path = ref.partition(":")
+ if not path or os.path.exists(path):
+ raise ValueError("Fine-tuned models are deleted from the model picker.")
+ deleted = True
else:
raise ValueError("Unknown library item")
invalidate_listing()
diff --git a/studio/backend/hub/storage/scan_folders.py b/studio/backend/hub/storage/scan_folders.py
index 17fbcc9b67b..55d61c5cf0d 100644
--- a/studio/backend/hub/storage/scan_folders.py
+++ b/studio/backend/hub/storage/scan_folders.py
@@ -17,6 +17,7 @@ from pathlib import Path
from storage.studio_db import get_connection
from hub.utils.paths import normalize_path
from utils.paths.external_media import is_linux_run_media_path, is_local_filesystem_root
+from utils.paths.path_utils import macos_volume_ignores_case
from utils.paths.scan_folder_health import is_readable_dir
from utils.paths.sensitive import (
contains_sensitive_path_component as _shared_contains_sensitive_path_component,
@@ -58,12 +59,57 @@ def is_denied_system_path(path: str) -> bool:
/run carve-out keeps Linux removable-media mounts browseable. Expects an
already-resolved (realpath) path so symlinks cannot escape into a denied subtree.
"""
- is_win = platform.system() == "Windows"
- check = os.path.normcase(path) if is_win else path
+ return _denied_prefix(path) is not None
+
+
+def _denied_prefix(path: str) -> str | None:
+ check = _comparable_path(path)
for prefix in _denied_path_prefixes():
- if check == prefix or check.startswith(prefix + os.sep):
- if prefix == "/run" and is_linux_run_media_path(check):
- continue
+ if is_within_any(path, [prefix]) and not (
+ prefix == "/run" and is_linux_run_media_path(check)
+ ):
+ return prefix
+ return None
+
+
+# Longest first: \\?\UNC\server\share is the share \\server\share. After normcase, so lower case.
+_EXTENDED_PREFIXES = (
+ ("\\\\?\\unc\\", "\\\\"),
+ ("\\\\.\\unc\\", "\\\\"),
+ ("\\\\?\\", ""),
+ ("\\\\.\\", ""),
+)
+
+
+def _comparable_path(path: str, fold: bool | None = None) -> str:
+ """``path`` spelled the way the filesystem compares it, for prefix checks. Windows ignores
+ case, and so does macOS unless the volume is case-sensitive (``fold`` says, else it is asked:
+ /LIBRARY is /Library on a default volume only). realpath() keeps a Windows extended-length
+ prefix (``\\\\?\\C:\\Windows``) that would otherwise hide the folder behind it."""
+ system = platform.system()
+ if system == "Windows":
+ check = os.path.normcase(path)
+ for extended, plain in _EXTENDED_PREFIXES:
+ if check.startswith(extended):
+ return plain + check[len(extended) :]
+ return check
+ if system == "Darwin":
+ if fold is None:
+ fold = macos_volume_ignores_case(path)
+ return path.casefold() if fold else path
+ return path
+
+
+def is_within_any(path: str, prefixes) -> bool:
+ """True if resolved ``path`` is, or is inside, one of ``prefixes``, compared the way the
+ filesystem holding ``path`` compares names (see ``_comparable_path``)."""
+ fold = platform.system() == "Darwin" and macos_volume_ignores_case(path)
+ check = _comparable_path(path, fold)
+ for prefix in prefixes:
+ prefix = _comparable_path(str(prefix), fold).rstrip(os.sep) or os.sep
+ if check == prefix or check.startswith(
+ prefix if prefix.endswith(os.sep) else prefix + os.sep
+ ):
return True
return False
@@ -112,12 +158,9 @@ def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:
raise ValueError("Path is outside this account's workspace")
is_win = platform.system() == "Windows"
- check = os.path.normcase(normalized) if is_win else normalized
- for prefix in _denied_path_prefixes():
- if check == prefix or check.startswith(prefix + os.sep):
- if prefix == "/run" and is_linux_run_media_path(check):
- continue
- raise ValueError(f"Path under {prefix} is not allowed")
+ denied = _denied_prefix(normalized)
+ if denied is not None:
+ raise ValueError(f"Path under {denied} is not allowed")
# Last, so a denied path is never opened. Mirrors studio_db.py.
if not is_readable_dir(normalized):
diff --git a/studio/backend/routes/library.py b/studio/backend/routes/library.py
index 236cb81d2a9..73208bae60d 100644
--- a/studio/backend/routes/library.py
+++ b/studio/backend/routes/library.py
@@ -158,8 +158,15 @@ async def get_library(
current_subject: str = Depends(get_current_subject),
via_api_key: bool = Depends(authenticated_via_api_key),
) -> dict:
+ from hub.utils.host_paths import redact_inventory_host_paths
+
items = await run_in_threadpool(library.list_items)
- return {"items": _items_for_caller(items, via_api_key), "folders": library_db.list_folders()}
+ disk = await run_in_threadpool(library.disk_usage)
+ return {
+ "items": _items_for_caller(items, via_api_key),
+ "folders": library_db.list_folders(),
+ "disk": redact_inventory_host_paths(disk, via_api_key = via_api_key),
+ }
@router.get("/favorites")
@@ -205,6 +212,15 @@ def patch_item(body: ItemPatch, current_subject: str = Depends(get_current_subje
return {"ok": True}
[email protected]("/items/opened")
+def mark_item_opened(body: ItemRef, current_subject: str = Depends(get_current_subject)) -> dict:
+ # Only an item that is there, and kept for the file it is now: an open landing after a delete
+ # must not leave a row that a file made at the same path later would take for its own.
+ if not library.mark_opened(body.id):
+ raise HTTPException(status_code = 404, detail = "Item not found")
+ return {"ok": True}
+
+
@router.post("/items/delete")
async def delete_item(
body: ItemDelete, current_subject: str = Depends(get_current_subject)
@@ -537,15 +553,48 @@ async def reveal_location(
account_access.require_installation_owner()
from pathlib import Path
- paths = {entry["key"]: entry["path"] for entry in await run_in_threadpool(library.locations)}
- if body.key not in paths:
+ entries = {entry["key"]: entry for entry in await run_in_threadpool(library.locations)}
+ if body.key not in entries:
raise HTTPException(status_code = 404, detail = "Unknown location")
- path = Path(paths[body.key])
+ path = Path(entries[body.key]["path"])
+ # A chosen folder that is gone is on a drive that is not there: making it would put the next
+ # saves beneath the mount point. Only a default is made.
+ if not entries[body.key]["available"]:
+ raise HTTPException(
+ status_code = 409,
+ detail = f"{path} is not available. Reconnect its drive, or reset the folder.",
+ )
await run_in_threadpool(lambda: path.mkdir(parents = True, exist_ok = True))
await run_in_threadpool(_reveal, path)
return {"ok": True}
+class LocationMove(BaseModel):
+ key: str = Field(max_length = 32)
+ path: Optional[str] = Field(default = None, max_length = 4096)
+
+
[email protected]("/locations/move")
+async def move_location(
+ body: LocationMove, current_subject: str = Depends(get_current_subject)
+) -> dict:
+ """Move one kind of file to another folder, files and all. Installation owner only, like the
+ other storage settings: other accounts keep their files in their own workspace. `leftBehind`
+ names the folder whose files stayed on an unplugged drive when a Reset let go of it."""
+ account_access.require_installation_owner()
+ try:
+ left_behind = await run_in_threadpool(library.move_location, body.key, body.path)
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc))
+ except RuntimeError as exc:
+ logger.warning("library.move_location_failed: %s", exc)
+ raise HTTPException(status_code = 500, detail = str(exc))
+ return {
+ "locations": await run_in_threadpool(library.locations),
+ "leftBehind": left_behind,
+ }
+
+
def _chunks(stream, name: str):
total = 0
while chunk := stream.read(_CHUNK_BYTES):
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index a1c37c9bde6..b1c35c4ed43 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -3049,6 +3049,22 @@ def _active_video_backend():
return None
+def _forget_gone_library_entries(source: str, folder: Path) -> None:
+ """Drop the Library's name, folder and star for models that were in `folder` and are gone now,
+ so they never land on a new model saved to the same path. A GGUF export is listed by one of
+ its files, so deleting that variant ends its entry. The files are gone already, so a failure
+ here only logs."""
+ try:
+ from storage import library_db
+ prefix = f"model:{source}:"
+ for item_id in library_db.list_entries():
+ path = item_id[len(prefix) :] if item_id.startswith(prefix) else ""
+ if path and not os.path.lexists(path) and _is_path_under(Path(path), folder):
+ library_db.delete_entry(item_id)
+ except Exception as e:
+ logger.warning("Could not clear the Library entries under %s: %s", folder, e)
+
+
def _prune_empty_parents(start: Path, stop_at: Path) -> None:
"""Remove empty ancestors of ``start`` up to (not including) ``stop_at``, so the enclosing run dir
does not linger as an empty entry in scan results."""
@@ -3383,6 +3399,7 @@ async def delete_finetuned_model(
_prune_empty_parents(target_path, allowed_root)
except OSError:
pass
+ _forget_gone_library_entries(source, target_path)
await _invalidate_local_scans()
logger.info(
"Deleted %s GGUF file(s) for exported model at %s variant %s (%0.1f MB freed)",
@@ -3409,6 +3426,7 @@ async def delete_finetuned_model(
)
_prune_empty_parents(target_path, allowed_root)
+ _forget_gone_library_entries(source, target_path)
await _invalidate_local_scans()
logger.info("Deleted fine-tuned model at %s", target_path)
diff --git a/studio/backend/storage/library_db.py b/studio/backend/storage/library_db.py
index d0e7d5c7ec3..2cf2582a9fd 100644
--- a/studio/backend/storage/library_db.py
+++ b/studio/backend/storage/library_db.py
@@ -46,10 +46,14 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
)
"""
)
- entry_columns = {row["name"] for row in conn.execute("PRAGMA table_info(library_entries)")}
- if "fingerprint" not in entry_columns:
+ # Added after the first release of the table, in place: a studio.db from before keeps its
+ # rows, fingerprinted on first sight.
+ entry_columns = {row[1] for row in conn.execute("PRAGMA table_info(library_entries)")}
+ for column, kind in (("opened_at", "INTEGER"), ("fingerprint", "TEXT")):
+ if column in entry_columns:
+ continue
try:
- conn.execute("ALTER TABLE library_entries ADD COLUMN fingerprint TEXT")
+ conn.execute(f"ALTER TABLE library_entries ADD COLUMN {column} {kind}")
except sqlite3.OperationalError as exc:
if "duplicate column" not in str(exc).lower():
raise
@@ -245,6 +249,7 @@ def list_entries() -> dict[str, dict]:
"favorite": bool(row["favorite"]),
"folderId": row["folder_id"],
"updatedAt": row["updated_at"],
+ "openedAt": row["opened_at"],
"fingerprint": row["fingerprint"],
}
for row in rows
@@ -307,6 +312,30 @@ def update_entry(
conn.close()
+def mark_opened(item_id: str, fingerprint: Optional[str] = None) -> None:
+ """Record that the item was just opened, for Suggested's Last activity. ``fingerprint`` is as
+ for ``update_entry``: a row kept for another file at the path is dropped, not carried over."""
+ conn = get_connection()
+ try:
+ _lock(conn)
+ now = _now_ms()
+ if fingerprint is not None:
+ conn.execute(
+ "DELETE FROM library_entries WHERE item_id = ? AND fingerprint IS NOT NULL AND fingerprint != ?",
+ (item_id, fingerprint),
+ )
+ conn.execute(
+ "INSERT INTO library_entries (item_id, updated_at, opened_at, fingerprint) "
+ "VALUES (?, ?, ?, ?) ON CONFLICT(item_id) DO UPDATE SET opened_at = "
+ "excluded.opened_at, fingerprint = COALESCE(library_entries.fingerprint, "
+ "excluded.fingerprint)",
+ (item_id, now, now, fingerprint),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+
def reconcile_entries(adopt: list[tuple[str, str]], stale: list[tuple[str, str]]) -> None:
"""Fingerprint legacy rows with the file found at their path (``adopt``), and drop rows kept
for a file since replaced (``stale``). Each only while the row still reads as the listing saw
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 3f42cfbaca9..120298c69a1 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -33,6 +33,7 @@ from utils.paths import (
studio_db_path,
)
from utils.paths.external_media import is_linux_run_media_path, is_local_filesystem_root
+from utils.paths.path_utils import macos_volume_ignores_case
from utils.paths.scan_folder_health import is_readable_dir
from utils.paths.sensitive import (
contains_sensitive_path_component as _shared_contains_sensitive_path_component,
@@ -82,9 +83,24 @@ def is_denied_system_path(path: str) -> bool:
keeps Linux removable-media mounts browseable. Expects an already-resolved (realpath) path so
symlinks cannot escape into a denied subtree.
"""
- is_win = platform.system() == "Windows"
- check = os.path.normcase(path) if is_win else path
+ system = platform.system()
+ fold = system == "Darwin" and macos_volume_ignores_case(path)
+ if system == "Windows":
+ check = os.path.normcase(path)
+ # realpath() keeps an extended-length prefix: \\?\C:\Windows is C:\Windows, and
+ # \\?\UNC\server\share is \\server\share. Self-contained: tests lift this function out.
+ for extended, plain in (("\\\\?\\unc\\", "\\\\"), ("\\\\?\\", "")):
+ if check.startswith(extended):
+ check = plain + check[len(extended) :]
+ break
+ elif fold:
+ # APFS and HFS+ ignore case unless formatted case-sensitive: /LIBRARY is /Library.
+ check = path.casefold()
+ else:
+ check = path
for prefix in _denied_path_prefixes():
+ if fold:
+ prefix = prefix.casefold()
if check == prefix or check.startswith(prefix + os.sep):
if prefix == "/run" and is_linux_run_media_path(check):
continue
diff --git a/studio/backend/tests/test_browse_denylist.py b/studio/backend/tests/test_browse_denylist.py
index e21dc5c5a83..be0dfa8703c 100644
--- a/studio/backend/tests/test_browse_denylist.py
+++ b/studio/backend/tests/test_browse_denylist.py
@@ -16,6 +16,7 @@ import ast
import ntpath
import os
import posixpath
+import sys
from pathlib import Path
from types import SimpleNamespace
from typing import Optional
@@ -37,6 +38,17 @@ class _HTTPException(Exception):
self.detail = detail
+_WIN_ENV_OS = SimpleNamespace(
+ sep = "\\",
+ environ = {
+ "SystemRoot": r"C:\Windows",
+ "ProgramFiles": r"C:\Program Files",
+ "ProgramFiles(x86)": r"C:\Program Files (x86)",
+ },
+ path = SimpleNamespace(normcase = ntpath.normcase),
+)
+
+
def _extract_is_denied_windows():
"""is_denied_system_path (+ _denied_path_prefixes) from studio_db.py under Windows semantics (ntpath) on a POSIX host."""
src = (_BACKEND_ROOT / "storage" / "studio_db.py").read_text(encoding = "utf-8")
@@ -50,17 +62,8 @@ def _extract_is_denied_windows():
module = ast.Module(body = funcs, type_ignores = [])
ast.fix_missing_locations(module)
- win_os = SimpleNamespace(
- sep = "\\",
- environ = {
- "SystemRoot": r"C:\Windows",
- "ProgramFiles": r"C:\Program Files",
- "ProgramFiles(x86)": r"C:\Program Files (x86)",
- },
- path = SimpleNamespace(normcase = ntpath.normcase),
- )
ns = {
- "os": win_os,
+ "os": _WIN_ENV_OS,
"platform": SimpleNamespace(system = lambda: "Windows"),
# /run has no Windows analog, so the carve-out is never reached.
"is_linux_run_media_path": lambda _p: False,
@@ -153,6 +156,64 @@ def test_is_denied_system_path_windows_allows_non_system(path):
assert is_denied(path) is False
+# A POSIX or macOS host simulated on Windows still joins with os.sep "\\", so these only run there.
+_POSIX_SEP = pytest.mark.skipif(sys.platform == "win32", reason = "simulates a POSIX host")
+
+
+ "system, path, denied",
+ [
+ ("Windows", r"\\?\C:\Windows\Temp\x", True),
+ ("Windows", r"\\?\c:\program files\y", True),
+ ("Windows", r"\\?\C:\WINDOWS", True),
+ ("Windows", r"\\?\D:\models", False),
+ ("Windows", r"\\?\UNC\server\share\Windows", False),
+ pytest.param("Darwin", "/LIBRARY/x", True, marks = _POSIX_SEP),
+ pytest.param("Darwin", "/library", True, marks = _POSIX_SEP),
+ pytest.param("Darwin", "/private/TMP/x", True, marks = _POSIX_SEP),
+ pytest.param("Darwin", "/SYSTEM/Volumes", True, marks = _POSIX_SEP),
+ pytest.param("Darwin", "/Users/me/Library-Backup", False, marks = _POSIX_SEP),
+ pytest.param("Darwin", "/Volumes/Drive/library", False, marks = _POSIX_SEP),
+ ],
+)
+def test_is_denied_system_path_sees_through_spelling(system, path, denied, monkeypatch):
+ legacy = studio_db.is_denied_system_path
+ if system == "Windows":
+ legacy = _extract_is_denied_windows()
+ monkeypatch.setattr(scan_folders, "os", _WIN_ENV_OS)
+ monkeypatch.setattr(scan_folders.platform, "system", lambda: system)
+ assert legacy(path) is denied
+ assert scan_folders.is_denied_system_path(path) is denied
+
+
+@_POSIX_SEP
+def test_is_within_any_compares_like_the_disk(monkeypatch):
+ monkeypatch.setattr(scan_folders.platform, "system", lambda: "Darwin")
+ assert scan_folders.is_within_any("/Users/Me/Library/CACHES/x", ["/Users/me/Library/Caches"])
+ assert not scan_folders.is_within_any("/Users/me/Library/Caches2", ["/Users/me/Library/Caches"])
+ monkeypatch.setattr(scan_folders.platform, "system", lambda: "Linux")
+ assert not scan_folders.is_within_any("/TMP/x", ["/tmp"])
+ assert scan_folders.is_within_any("/tmp", ["/tmp/"])
+
+
+@_POSIX_SEP
+def test_a_case_sensitive_macos_volume_keeps_case_apart(monkeypatch):
+ monkeypatch.setattr(scan_folders.platform, "system", lambda: "Darwin")
+ for module in (scan_folders, studio_db):
+ monkeypatch.setattr(module, "macos_volume_ignores_case", lambda path: False)
+ for check in (studio_db.is_denied_system_path, scan_folders.is_denied_system_path):
+ assert check("/Library/x") and not check("/library/models")
+ assert not scan_folders.is_within_any(
+ "/Users/Me/Library/CACHES/x", ["/Users/me/Library/Caches"]
+ )
+
+
[email protected](sys.platform != "darwin", reason = "asks the real macOS volume")
+def test_macos_volume_case_is_asked_of_the_nearest_existing_folder():
+ from utils.paths.path_utils import macos_volume_ignores_case
+ assert macos_volume_ignores_case("/no/such/folder/here") == macos_volume_ignores_case("/")
+
+
# _resolve_browse_target -- real-FS integration (legacy browser)
def _extract_resolver():
"""Extract the legacy browse resolver; its inline imports use the real storage.studio_db policy."""
diff --git a/studio/backend/tests/test_delete_finetuned_diffusion_guard.py b/studio/backend/tests/test_delete_finetuned_diffusion_guard.py
index 0bcaf68b4a7..bc30bc40459 100644
--- a/studio/backend/tests/test_delete_finetuned_diffusion_guard.py
+++ b/studio/backend/tests/test_delete_finetuned_diffusion_guard.py
@@ -21,6 +21,7 @@ from fastapi.testclient import TestClient
import routes.models as models_module
from auth.authentication import get_current_subject
from routes.models import router as models_router
+from storage import library_db
class _Backend:
@@ -51,11 +52,23 @@ class _Backend:
return self._loading
[email protected](autouse = True)
+def forgotten(monkeypatch):
+ """Library entries the route dropped: a model's name, folder and star are keyed by its path,
+ and left behind they would land on the next model saved there."""
+ ids: list[str] = []
+ monkeypatch.setattr(library_db, "delete_entry", ids.append)
+ return ids
+
+
@pytest.fixture()
def client(tmp_path, monkeypatch):
outputs = tmp_path / "outputs"
outputs.mkdir()
monkeypatch.setattr(models_module, "outputs_root", lambda: outputs)
+ monkeypatch.setattr(models_module, "exports_root", lambda: tmp_path / "exports")
+ entries = {f"model:training:{outputs / 'my-diffusion-model'}": {}, "upload:abc": {}}
+ monkeypatch.setattr(library_db, "list_entries", lambda: entries)
# No chat model is resident, so only the diffusion / video guards can refuse.
monkeypatch.setattr(models_module, "get_inference_backend", lambda: _NoChat())
@@ -85,7 +98,7 @@ def _delete(client, path):
)
-def test_refuses_to_delete_a_model_the_images_engine_has_loaded(client, monkeypatch):
+def test_refuses_to_delete_a_model_the_images_engine_has_loaded(client, forgotten, monkeypatch):
c, outputs = client
target = _model_dir(outputs)
monkeypatch.setattr(
@@ -97,6 +110,7 @@ def test_refuses_to_delete_a_model_the_images_engine_has_loaded(client, monkeypa
assert resp.status_code == 400
assert "Unload the model" in resp.json()["detail"]
assert target.exists()
+ assert forgotten == []
def test_refuses_the_companion_base_and_the_extra_repos_the_engine_reads(client, monkeypatch):
@@ -151,7 +165,7 @@ def test_allows_the_delete_when_no_diffusion_or_video_model_holds_it(client, mon
assert not target.exists()
-def test_a_chat_only_install_can_still_delete(client, monkeypatch):
+def test_a_chat_only_install_can_still_delete(client, forgotten, monkeypatch):
"""No diffusion stack installed: the guard must fail OPEN, not 503 every delete."""
c, outputs = client
target = _model_dir(outputs)
@@ -160,6 +174,7 @@ def test_a_chat_only_install_can_still_delete(client, monkeypatch):
assert _delete(c, target).status_code == 200
assert not target.exists()
+ assert forgotten == [f"model:training:{target}"]
def test_an_unreadable_engine_state_fails_closed(client, monkeypatch):
@@ -202,3 +217,25 @@ def test_refuses_the_delete_while_a_diffusion_training_run_is_active(client, mon
stub.get_diffusion_training_service = lambda: types.SimpleNamespace(is_active = lambda: False)
assert _delete(c, target).status_code == 200
assert not target.exists()
+
+
+def test_deleting_a_gguf_variant_drops_its_library_entry(client, forgotten, monkeypatch):
+ """A GGUF export is listed by one of its files; deleting that variant ends its entry, and the
+ other variants keep theirs."""
+ c, outputs = client
+ run = outputs.parent / "exports" / "my-export"
+ run.mkdir(parents = True)
+ q4, q8 = run / "model-Q4_K_M.gguf", run / "model-Q8_0.gguf"
+ q4.write_bytes(b"x")
+ q8.write_bytes(b"x")
+ monkeypatch.setattr(models_module, "_active_diffusion_backend", lambda: None)
+ monkeypatch.setattr(models_module, "_active_video_backend", lambda: None)
+ entries = {f"model:exported:{q4}": {}, f"model:exported:{q8}": {}, "upload:abc": {}}
+ monkeypatch.setattr(library_db, "list_entries", lambda: entries)
+ body = {"source": "exported", "export_type": "gguf", "gguf_variant": "Q4_K_M"}
+ response = c.request(
+ "DELETE", "/api/models/delete-finetuned", json = {"model_path": str(q4), **body}
+ )
+ assert response.status_code == 200, response.text
+ assert not q4.exists() and q8.exists()
+ assert forgotten == [f"model:exported:{q4}"]
diff --git a/studio/backend/tests/test_image_gallery.py b/studio/backend/tests/test_image_gallery.py
index e29f4132e91..c3062eaf0b3 100644
--- a/studio/backend/tests/test_image_gallery.py
+++ b/studio/backend/tests/test_image_gallery.py
@@ -523,3 +523,12 @@ def test_archiving_during_a_clear_never_leaves_a_deleted_image_reported_as_archi
# Either the archive won (reported success, file kept) or the clear won (reported gone, file
# deleted). "Reported success but deleted" is the outcome this must never produce.
assert said_ok == survived
+
+
+def test_save_looks_up_the_folder_after_encoding(tmp_path, monkeypatch):
+ order = []
+ encode = gallery._png_bytes
+ monkeypatch.setattr(gallery, "_png_bytes", lambda *a: order.append("encode") or encode(*a))
+ monkeypatch.setattr(gallery, "gallery_dir", lambda: order.append("dir") or tmp_path)
+ gallery.save(Image.new("RGB", (4, 4)), {"prompt": "p"})
+ assert order[:2] == ["encode", "dir"]
diff --git a/studio/backend/tests/test_library_routes.py b/studio/backend/tests/test_library_routes.py
index 2fc9a4d6304..3c35da09b55 100644
--- a/studio/backend/tests/test_library_routes.py
+++ b/studio/backend/tests/test_library_routes.py
@@ -3,6 +3,7 @@
import base64
import contextlib
+import errno
import io
import json
import os
@@ -27,9 +28,13 @@ from auth.authentication import ( # noqa: E402
from core import library # noqa: E402
from routes import library as library_routes # noqa: E402
from storage import library_db # noqa: E402
+import hub.storage.scan_folders as _scan_folders # noqa: E402
from .test_rag_native_drop_upload import SECRET, _sign # noqa: E402
+_REAL_DENIED = _scan_folders.is_denied_system_path
+_REAL_SCRATCH = library._scratch_and_system_folders
+
_CLIP = bytes(range(100))
_SANDBOX_ID = "sandbox:t-lib:report.txt"
_SANDBOX_A = "sandbox:t-lib:a.txt"
@@ -242,6 +247,13 @@ def test_rename_favorite_and_folders_are_an_overlay(client):
_patch(client, id = image, name = "photo.txt", favorite = True, folderId = folder)
item = _items(client)[0][image]
assert (item["name"], item["favorite"], item["folderId"]) == ("photo.txt", True, folder)
+ assert item["openedAt"] is None
+ assert _post(client, "items/opened", id = image).status_code == 200
+ item = _items(client)[0][image]
+ assert item["createdAt"] <= item["openedAt"] and item["favorite"] is True
+ for missing in ("upload:gone", "sandbox:t-lib:gone.txt"):
+ assert _post(client, "items/opened", id = missing).status_code == 404
+ assert "upload:gone" not in library_db.list_entries()
# The type follows the file's own name, so a binary renamed to .txt never opens as text.
assert item["fileName"] == "photo.png"
_patch(client, id = image, favorite = False)
@@ -388,6 +400,19 @@ def test_a_sandbox_file_written_twice_in_a_second_is_a_new_version(client, signe
assert versions == [1_700_000_000_100, 1_700_000_000_600]
+def test_a_clip_counts_its_recipe_toward_what_it_takes_on_disk(client, monkeypatch):
+ from core.inference import audio_gallery
+
+ monkeypatch.setattr(library, "_SOURCES", (library._audio_items, library._image_items))
+ audio, image = _gallery_audio("A recipe beside it"), _gallery_image("No recipe")
+ items = _items(client)[0]
+ wav = audio_gallery.audio_path(audio)
+ item = items[f"audio:{audio}"]
+ assert item["sizeBytes"] == wav.stat().st_size
+ assert item["storageBytes"] == wav.stat().st_size + wav.with_suffix(".json").stat().st_size
+ assert "storageBytes" not in items[f"image:{image}"]
+
+
def test_generated_audio_and_video_are_listed_and_deleted(client, monkeypatch):
import routes.video as video_routes
from core.inference import audio_gallery, video_gallery
@@ -418,6 +443,28 @@ def test_generated_audio_and_video_are_listed_and_deleted(client, monkeypatch):
assert forgotten == [video, video]
+def test_the_listing_reports_the_library_disk_and_the_sources_on_it(client, monkeypatch):
+ from utils.paths.storage_roots import exports_root
+
+ def sources():
+ response = client.get("/api/library")
+ assert response.status_code == 200
+ disk = response.json()["disk"]
+ assert 0 <= disk["freeBytes"] <= disk["totalBytes"] and disk["totalBytes"] > 0
+ return set(disk["sources"])
+
+ every = {"upload", "attachment", "image", "video", "audio", "sandbox"}
+ every |= {"model:training", "model:exported"}
+ assert sources() == every
+ real, exports, uploads = library._device, str(exports_root()), str(library.uploads_dir())
+ monkeypatch.setattr(library, "_device", lambda path: -1 if str(path) == exports else real(path))
+ assert sources() == every - {"model:exported"}
+ monkeypatch.setitem(library._SOURCE_ROOTS, "sandbox", _fail)
+ assert sources() == every - {"model:exported", "sandbox"}
+ monkeypatch.setattr(library, "_device", lambda path: 1 if str(path) == uploads else -1)
+ assert sources() == {"upload"}
+
+
def test_favorites_list_only_stars_the_source_still_has(client, monkeypatch):
from core.inference import image_gallery
@@ -464,25 +511,37 @@ def test_leftovers_of_a_crash_are_swept_from_the_uploads_folder(client):
def test_fine_tuned_models_are_listed_but_not_deleted_here(client, monkeypatch):
import shutil
- from utils.paths.storage_roots import outputs_root
+ from utils.paths.storage_roots import exports_root, outputs_root
monkeypatch.setattr(library, "_SOURCES", (library._model_items,))
outputs_root().mkdir(parents = True, exist_ok = True)
stamp = library._model_stamp()
- run = outputs_root() / "library-test-run"
+ run, gguf = outputs_root() / "library-test-run", exports_root() / "library-test-gguf"
run.mkdir()
(run / "adapter_config.json").write_text('{"base_model_name_or_path": "unsloth/base"}')
(run / "adapter_model.safetensors").write_bytes(b"x" * 10)
+ gguf.mkdir(parents = True)
+ (gguf / "model.Q4_K_M.gguf").write_bytes(b"x" * 10)
+ (gguf / "model.Q8_0.gguf").write_bytes(b"x" * 20)
try:
assert library._model_stamp() != stamp
- [item] = [item for item in _items(client)[0].values() if item["name"] == run.name]
+ items = {item["name"]: item for item in _items(client)[0].values()}
+ item, export = items[run.name], items[gguf.name]
assert item["contentType"] == library.MODEL_CONTENT_TYPE
assert (item["model"]["origin"], item["model"]["exportType"]) == ("training", "lora")
- assert item["sizeBytes"] >= 10
+ assert item["sizeBytes"] >= 10 and export["sizeBytes"] == 30
+ for starred in (item, export):
+ _patch(client, id = starred["id"], favorite = True)
+ assert _items(client)[0][export["id"]]["favorite"] is True
+ assert set(_favorites(client)) == {item["id"], export["id"]}
assert _delete(client, item["id"]) == 400
assert run.is_dir()
- finally:
shutil.rmtree(run)
+ assert _delete(client, item["id"]) == 200
+ assert _favorites(client) == [export["id"]]
+ finally:
+ shutil.rmtree(run, ignore_errors = True)
+ shutil.rmtree(gguf, ignore_errors = True)
def test_an_api_key_lists_fine_tunes_by_reference_and_can_still_act_on_them(client, monkeypatch):
@@ -633,6 +692,7 @@ def test_an_older_database_is_upgraded_and_checked_once(client, monkeypatch, tmp
"favorite": True,
"folderId": None,
"updatedAt": 1,
+ "openedAt": None,
"fingerprint": None,
}
runs = []
@@ -1049,6 +1109,807 @@ def test_a_projects_own_files_are_listed(client, monkeypatch, tmp_path):
assert "sandbox:project-p-lib:files/notes.txt" not in _items(client)[0]
[email protected](autouse = True)
+def _temp_folders_are_ordinary(monkeypatch):
+ # macOS keeps pytest's temp folders under /private/var, which the real checks refuse, and they
+ # are temporary folders, which Library moves refuse too.
+ monkeypatch.setattr(
+ _scan_folders,
+ "is_denied_system_path",
+ lambda path: path.startswith(("/etc", "/private/etc", "/usr")),
+ )
+ monkeypatch.setattr(
+ library,
+ "_scratch_and_system_folders",
+ lambda: [f for f in _REAL_SCRATCH() if f.startswith(("/usr", "/opt", "/Applications"))],
+ )
+
+
+def _move(client, key, path):
+ return client.post("/api/library/locations/move", json = {"key": key, "path": path})
+
+
+def _location(client, key = None):
+ locations = {e["key"]: e for e in client.get("/api/library/locations").json()["locations"]}
+ return locations[key] if key else [entry["path"] for entry in locations.values()]
+
+
+def _images():
+ from core.inference import image_gallery
+ return image_gallery.gallery_dir()
+
+
+def _videos():
+ from core.inference import video_gallery
+ return video_gallery.gallery_dir()
+
+
+def _fill(folder):
+ for i in range(3):
+ (folder / f"{i}.png").write_bytes(b"png%d" % i)
+
+
+def _files(folder):
+ return sorted(p.relative_to(folder).as_posix() for p in folder.rglob("*") if p.is_file())
+
+
+def _cross_device(_src, _dst):
+ raise OSError(errno.EXDEV, "Invalid cross-device link")
+
+
+def _save_during_move(monkeypatch, save):
+ """Calls `save(new_folder)` right after the move records the new folder."""
+ from utils.paths import relocations
+
+ real = relocations.set_chosen
+
+ def record(
+ key,
+ path,
+ moving_from = None,
+ ):
+ real(key, path, moving_from)
+ if moving_from is not None:
+ save(Path(path))
+
+ monkeypatch.setattr(relocations, "set_chosen", record)
+
+
+def _mounted(monkeypatch, mounts):
+ real = os.path.ismount
+ monkeypatch.setattr(os.path, "ismount", lambda path: str(path) in mounts or real(path))
+
+
+def test_images_move_to_a_new_folder_and_back(client, tmp_path):
+ old = _images()
+ (old / "a.png").write_bytes(b"png")
+ (old / "a.json").write_text("{}")
+ new = tmp_path / "Pictures" / "Unsloth"
+ new.parent.mkdir()
+
+ response = _move(client, "images", str(new))
+ assert response.status_code == 200, response.text
+ assert _files(new) == ["a.json", "a.png"] and _files(old) == []
+ assert _images() == new.resolve()
+ location = _location(client, "images")
+ assert [location[key] for key in ("path", "movable", "custom", "available")] == [
+ str(new.resolve()),
+ True,
+ True,
+ True,
+ ]
+ assert location["disk"]["freeBytes"] <= location["disk"]["totalBytes"]
+ fine_tunes = _location(client, "fineTunes")
+ assert location["device"] == fine_tunes["device"] and fine_tunes["movable"] is False
+
+ assert _move(client, "images", None).status_code == 200
+ assert _files(old) == ["a.json", "a.png"] and _images() == old
+ assert _location(client, "images")["custom"] is False
+
+ (new / "holiday.jpg").write_bytes(b"jpg")
+ assert _move(client, "images", str(new)).status_code == 200
+ assert _images() == (new / "Unsloth Images").resolve()
+ assert _files(new) == ["Unsloth Images/a.json", "Unsloth Images/a.png", "holiday.jpg"]
+ (old / "stray.txt").write_text("left behind")
+ for _ in range(2):
+ response = _move(client, "images", None)
+ assert response.status_code == 200, response.text
+ assert _images() == (old / "Unsloth Images").resolve()
+ assert _files(old) == ["Unsloth Images/a.json", "Unsloth Images/a.png", "stray.txt"]
+ assert _location(client, "images")["custom"] is True
+
+
+def _made(folder, file = None):
+ folder.mkdir(parents = True, exist_ok = True)
+ if file:
+ (folder / file).write_text("mine")
+ return folder
+
+
+def _named_folder(tmp_path, link_to = None):
+ """A folder holding a file of the user's, whose "Unsloth Images" links to `link_to`, or with
+ none, is the videos' folder."""
+ data = _made(tmp_path / "data", "notes.txt")
+ if link_to is None:
+ library.move_location("videos", str(data / "Unsloth Images"))
+ else:
+ (data / "Unsloth Images").symlink_to(link_to, target_is_directory = True)
+ return data
+
+
+def _sandbox():
+ from core.inference.tools import sandbox_root
+ return Path(sandbox_root())
+
+
+def _read_only(tmp_path):
+ if getattr(os, "geteuid", lambda: 0)() == 0:
+ pytest.skip("root writes anywhere, and Windows keeps no write bit on folders")
+ (tmp_path / "locked").mkdir(mode = 0o500)
+ return tmp_path / "locked" / "images"
+
+
+def _studio(sub = ""):
+ from utils.paths import studio_root
+ return studio_root() / sub
+
+
+ "key, target, detail",
+ [
+ ("images", lambda _: "relative/folder", "absolute"),
+ (
+ "images",
+ lambda _: os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "unsloth-images")
+ if os.name == "nt"
+ else "/etc/unsloth-images",
+ "System",
+ ),
+ ("images", lambda tmp: tmp / "missing" / "deeper", "parent folder"),
+ ("images", _read_only, "cannot write"),
+ (
+ "images",
+ lambda tmp: _made(tmp / "full" / "Unsloth Images", "keep").parent,
+ "holds files",
+ ),
+ ("images", lambda _: _videos() / "images", "inside another Unsloth folder"),
+ ("uploads", lambda _: _made(_sandbox() / "chat-1") / "uploads", "inside another Unsloth"),
+ ("images", lambda _: _sandbox(), "inside another Unsloth folder"),
+ ("images", lambda _: _images() / "sub", "inside another Unsloth folder"),
+ ("images", lambda _: _images() / "new", "inside another Unsloth folder"),
+ ("images", lambda _: _studio(), "Unsloth's own folder"),
+ ("images", lambda _: _studio("elsewhere"), "Unsloth's own folder"),
+ ("images", _named_folder, "inside another Unsloth folder"),
+ ("images", lambda tmp: _named_folder(tmp, _videos()), "inside another Unsloth folder"),
+ ("images", lambda tmp: _named_folder(tmp, _made(tmp / "home" / ".ssh")), "credential"),
+ ("fineTunes", lambda tmp: tmp / "fine-tunes", "stay where they are"),
+ ("exports", lambda tmp: tmp / "exports", "stay where they are"),
+ ("somewhere", lambda tmp: tmp / "somewhere", "stay where they are"),
+ ],
+)
+def test_a_folder_that_cannot_take_the_files_is_refused(client, tmp_path, key, target, detail):
+ def tree():
+ return {
+ str(path)
+ for root in (tmp_path, _studio())
+ for path in root.rglob("*")
+ if ".db" not in path.name
+ }
+
+ _fill(_images())
+ (_images() / "sub").mkdir()
+ target, folders = str(target(tmp_path)), _location(client)
+ before = tree()
+ response = _move(client, key, target)
+ assert response.status_code == 400
+ assert detail in response.json()["detail"]
+ assert (tree(), _location(client)) == (before, folders)
+
+
+def test_a_flag_set_during_a_move_keeps_the_ones_set_before(client, tmp_path, monkeypatch):
+ from core.inference import gallery_flags, image_gallery
+
+ kept = _gallery_image("archived long ago")
+ image_gallery.set_flags(kept, archived = True)
+ fresh = _gallery_image("archived during the move")
+
+ # The images first and the store last, the order that loses it (directory order is the OS's).
+ def store_last(
+ source,
+ target,
+ log,
+ only = None,
+ ):
+ for entry in sorted(source.iterdir(), key = lambda p: p.name.startswith(".")):
+ if (only is None or only(entry)) and not library._inside(target, entry):
+ if entry.name == ".flags.json":
+ assert image_gallery.set_flags(fresh, archived = True) is not None
+ library._move_entry(entry, target / entry.name, log)
+
+ monkeypatch.setattr(library, "_move_entries", store_last)
+ assert _move(client, "images", str(tmp_path / "Pics")).status_code == 200
+ flags = gallery_flags.read(_images())
+ assert gallery_flags.is_archived(flags, kept) and gallery_flags.is_archived(flags, fresh)
+ assert not list(_images().glob(".flags (*"))
+ image_gallery.clear()
+ assert {p.stem for p in _images().glob("*.png")} == {kept, fresh}
+
+
+def test_only_the_installation_owner_can_move(client, tmp_path, monkeypatch):
+ monkeypatch.setattr(library_routes.account_access, "managed_account", lambda: True)
+ assert _move(client, "images", str(tmp_path / "elsewhere")).status_code == 403
+ assert not (tmp_path / "elsewhere").exists()
+
+
[email protected]("mount_point", [False, True])
+def test_an_unplugged_folder_is_not_made_again_and_can_be_reset(
+ client, tmp_path, monkeypatch, mount_point
+):
+ import shutil
+
+ from utils.paths.relocations import LocationUnavailable
+
+ (_images() / "a.png").write_bytes(b"png")
+ drive = tmp_path / "Drive"
+ drive.mkdir()
+ mounts = {str(drive.resolve())} if mount_point else set()
+ _mounted(monkeypatch, mounts)
+ assert _move(client, "images", str(drive)).status_code == 200
+ assert _move(client, "uploads", str(tmp_path / "Uploads")).status_code == 200
+ folder = (drive / "Unsloth Images" if mount_point else drive).resolve()
+ assert _images() == folder
+
+ if mount_point:
+ mounts.clear()
+ else:
+ shutil.rmtree(drive)
+ shutil.rmtree(tmp_path / "Uploads")
+ with pytest.raises(LocationUnavailable):
+ _images()
+ assert drive.exists() is mount_point
+ logged = []
+ for level in ("debug", "info", "warning"):
+ monkeypatch.setattr(
+ library.logger, level, lambda message, *a, **_: logged.append(message % a)
+ )
+ for _ in range(3):
+ assert client.get("/api/library").json()["disk"]["totalBytes"] > 0
+ assert len(logged) == len(set(logged)) == 2
+ assert all("location_unavailable" in line for line in logged)
+ location = _location(client, "images")
+ assert (location["path"], location["available"], location["disk"]) == (str(folder), False, None)
+ assert _post(client, "locations/reveal", key = "images").status_code == 409
+ assert drive.exists() is mount_point
+ assert _move(client, "images", str(tmp_path / "elsewhere")).status_code == 400
+ response = _move(client, "images", None)
+ assert (response.status_code, response.json()["leftBehind"]) == (200, str(folder))
+ assert _location(client, "images")["custom"] is False and _images().is_dir()
+
+
+ "failure, detail",
+ [
+ ("full", "No space left"),
+ ("in use", "open.png is in use by another program. Close it and try again."),
+ ],
+)
+def test_a_failed_move_puts_everything_back(client, tmp_path, monkeypatch, failure, detail):
+ import shutil
+
+ old = _images()
+ _fill(old)
+ (old / "d").mkdir()
+ (old / "d" / "open.png").write_bytes(b"open")
+ real_copy, real_unlink = shutil.copy2, library._unlink
+ copies = []
+
+ def filling_copy(src, dst, **kwargs):
+ copies.append(src)
+ if len(copies) == 2:
+ Path(dst).write_bytes(b"par")
+ raise OSError(28, "No space left on device")
+ return real_copy(src, dst, **kwargs)
+
+ def locked(path):
+ if Path(path).name == "open.png":
+ exc = PermissionError(errno.EACCES, "The process cannot access the file")
+ exc.winerror = 32
+ raise exc
+ real_unlink(path)
+
+ monkeypatch.setattr(library, "_rename", _cross_device)
+ if failure == "full":
+ monkeypatch.setattr(library.shutil, "copy2", filling_copy)
+ else:
+ monkeypatch.setattr(library, "_unlink", locked)
+ _save_during_move(monkeypatch, lambda new: (new / "saved-meanwhile.png").write_bytes(b"new"))
+ target = tmp_path / "other-drive"
+ response = _move(client, "images", str(target))
+ assert response.status_code == 500 and detail in response.json()["detail"]
+ assert _files(old) == ["0.png", "1.png", "2.png", "d/open.png", "saved-meanwhile.png"]
+ assert (old / "1.png").read_bytes() == b"png1" and _files(target) == []
+ assert _images() == old and _location(client, "images")["custom"] is False
+
+
[email protected]("spelling", ["link", "case"])
+def test_another_spelling_of_a_folder_is_that_folder(client, tmp_path, monkeypatch, spelling):
+ images, videos = _images(), _videos()
+ _fill(images)
+ (videos / "v.mp4").write_bytes(b"v")
+ if spelling == "case" and not (images.parent / images.name.upper()).is_dir():
+ pytest.skip("this disk tells case apart")
+ if spelling == "link":
+ # resolve() keeps the spelling it is given: a case alias on a case-insensitive disk, or a
+ # bind mount, names a folder by a path that is not its own. A link that resolve() is kept
+ # from following stands in for either on any disk.
+ monkeypatch.setattr(library, "_move_target", lambda raw: Path(raw))
+
+ def alias(folder):
+ if spelling == "case":
+ return folder.parent / folder.name.upper()
+ (tmp_path / folder.name).symlink_to(folder, target_is_directory = True)
+ return tmp_path / folder.name
+
+ # The current folder under another name: nothing moves (a move onto itself would empty it).
+ assert _move(client, "images", str(alias(images))).status_code == 200
+ assert _move(client, "images", str(alias(videos))).status_code == 400
+ assert _files(images) == ["0.png", "1.png", "2.png"] and _files(videos) == ["v.mp4"]
+ assert _images() == images
+
+
+def test_a_move_never_moves_a_folder_into_itself(tmp_path):
+ _fill(tmp_path)
+ (tmp_path / "Unsloth Images").mkdir()
+ library._move_entries(tmp_path, tmp_path / "Unsloth Images", library._MoveLog())
+ assert _files(tmp_path) == [f"Unsloth Images/{i}.png" for i in range(3)]
+
+
+def test_a_move_across_drives_merges_skips_and_waits(client, tmp_path, monkeypatch):
+ import threading
+ import time
+
+ old = _videos()
+ (old / ".jobs").mkdir()
+ (old / ".jobs" / "old.json").write_text("old job")
+ (old / "same.txt").write_text("same")
+ (old / "clash.txt").write_text("from the old folder")
+ (old / "v.mp4").write_text("v")
+ (old / "gone.mp4").write_text("gone")
+ (old / ".late.mp4.tmp").write_text("late")
+
+ def save(new):
+ (new / ".jobs").mkdir()
+ (new / ".jobs" / "new.json").write_text("running job")
+ (new / "same.txt").write_text("same")
+ (new / "clash.txt").write_text("from the new folder")
+
+ def rename(src, dst):
+ if Path(src).name == "gone.mp4":
+ Path(src).unlink()
+ raise FileNotFoundError(2, "No such file or directory")
+ _cross_device(src, dst)
+
+ def finish():
+ time.sleep(0.5)
+ os.replace(old / ".late.mp4.tmp", old / "late.mp4")
+
+ monkeypatch.setattr(library, "_rename", rename)
+ _save_during_move(monkeypatch, save)
+ writer = threading.Thread(target = finish)
+ writer.start()
+ new = tmp_path / "videos"
+ assert _move(client, "videos", str(new)).status_code == 200
+ writer.join()
+ assert {name: (new / name).read_text() for name in _files(new)} == {
+ ".jobs/new.json": "running job",
+ ".jobs/old.json": "old job",
+ "same.txt": "same",
+ "clash.txt": "from the new folder",
+ "clash (2).txt": "from the old folder",
+ "v.mp4": "v",
+ "late.mp4": "late",
+ }
+ assert _files(old) == [] and _videos() == new.resolve()
+
+
+def test_an_upload_finishing_during_a_move_lands_in_the_new_folder(client, tmp_path):
+ [note] = _upload(client, ("plan.md", b"# plan", "text/markdown"))
+ new = tmp_path / "uploads"
+
+ def chunks():
+ yield b"first half, "
+ library.move_location("uploads", str(new))
+ yield b"second half"
+
+ slow = f"upload:{library.save_upload('slow.txt', 'text/plain', chunks())['id']}"
+ items = _items(client)[0]
+ served = [client.get(items[item_id]["fileUrl"]).content for item_id in (slow, note)]
+ assert served == [b"first half, second half", b"# plan"]
+ assert _files(new) == sorted(_ref(item_id) for item_id in (slow, note))
+ assert not [p for p in library._location_default("uploads").iterdir() if p.suffix == ".tmp"]
+
+
+def _move_after_lookup(monkeypatch, new):
+ """The first lookup of an upload's file starts a move of the uploads folder, and gives it a
+ moment to finish, before answering with where the file was."""
+ import threading
+
+ real = library.upload_path
+ movers = []
+
+ def lookup(upload_id):
+ path = real(upload_id)
+ if not movers:
+ movers.append(
+ threading.Thread(target = library.move_location, args = ("uploads", str(new)))
+ )
+ movers[0].start()
+ movers[0].join(0.5)
+ return path
+
+ monkeypatch.setattr(library, "upload_path", lookup)
+ return movers
+
+
+def test_an_upload_deleted_or_saved_as_a_move_finishes_is_not_left_behind(
+ client, tmp_path, monkeypatch
+):
+ gone, kept = _upload(
+ client, ("gone.txt", b"gone", "text/plain"), ("kept.txt", b"kept", "text/plain")
+ )
+ new = tmp_path / "uploads"
+ movers = _move_after_lookup(monkeypatch, new)
+ assert _delete(client, gone) == 200
+ movers[0].join()
+ assert _files(new) == [_ref(kept)]
+ assert set(_items(client)[0]) == {kept}
+
+ new = tmp_path / "uploads-again"
+ movers = _move_after_lookup(monkeypatch, new)
+ assert library.write_upload_text(kept.partition(":")[2], "edited", "utf-8")
+ movers[0].join()
+ assert (new / _ref(kept)).read_text() == "edited"
+
+
+def test_a_drive_without_room_for_the_files_is_refused_up_front(client, tmp_path, monkeypatch):
+ import shutil
+
+ (_images() / "big.png").write_bytes(b"x" * 1000)
+ target = tmp_path / "small-drive" / "images"
+ target.parent.mkdir()
+ real_device = library._device
+ monkeypatch.setattr(
+ library,
+ "_device",
+ lambda path: -1 if str(path).startswith(str(target.parent)) else real_device(path),
+ )
+ monkeypatch.setattr(
+ library.shutil, "disk_usage", lambda path: shutil._ntuple_diskusage(10**6, 10**6, 10)
+ )
+ response = _move(client, "images", str(target))
+ assert response.status_code == 400 and "free" in response.json()["detail"]
+ assert not target.exists()
+ assert (_images() / "big.png").stat().st_size == 1000
+
+
+def test_a_named_folder_linked_onto_a_full_drive_is_refused_up_front(client, tmp_path, monkeypatch):
+ import shutil
+
+ (_images() / "big.png").write_bytes(b"x" * 1000)
+ picked = tmp_path / "Pictures"
+ _made(picked, "holiday.jpg")
+ other = tmp_path / "small-drive"
+ _made(other / "images")
+ (picked / "Unsloth Images").symlink_to(other / "images", target_is_directory = True)
+ real_device = library._device
+ monkeypatch.setattr(
+ library,
+ "_device",
+ lambda path: -1 if str(path).startswith(str(other.resolve())) else real_device(path),
+ )
+ real_usage = shutil.disk_usage
+ monkeypatch.setattr(
+ library.shutil,
+ "disk_usage",
+ lambda path: shutil._ntuple_diskusage(10**6, 10**6, 10)
+ if str(path).startswith(str(other.resolve()))
+ else real_usage(path),
+ )
+ response = _move(client, "images", str(picked))
+ assert response.status_code == 400 and "free" in response.json()["detail"]
+ assert _files(other) == [] and (_images() / "big.png").stat().st_size == 1000
+
+
+def test_temporary_and_cache_folders_cannot_hold_library_files(monkeypatch):
+ import tempfile
+
+ monkeypatch.setattr(_scan_folders, "is_denied_system_path", _REAL_DENIED)
+ monkeypatch.setattr(
+ library, "_scratch_and_system_folders", lambda: [*_REAL_SCRATCH(), "/scratch-for-test"]
+ )
+ scratch = (
+ Path(os.environ.get("SystemRoot", r"C:\Windows")) / "Temp" / "images"
+ if os.name == "nt"
+ else Path("/var/tmp/images")
+ )
+ for folder in (Path(tempfile.gettempdir()) / "images", scratch):
+ with pytest.raises(ValueError, match = "cannot hold these files"):
+ library._refuse_denied(folder.resolve())
+ assert not _REAL_DENIED("/scratch-for-test/images")
+ with pytest.raises(ValueError, match = "Temporary"):
+ library._refuse_denied(Path("/scratch-for-test/images"))
+ library._refuse_denied(Path.home() / "Pictures" / "Unsloth")
+
+
+def test_a_folder_chosen_before_mount_points_learns_its_mount_once_present(
+ client, tmp_path, monkeypatch
+):
+ from storage.studio_db import get_app_setting, upsert_app_settings
+ from utils.paths.relocations import LocationUnavailable, forget_cache
+
+ drive = tmp_path / "mnt-usb"
+ folder, mount = drive / "Unsloth Images", str(drive.resolve())
+ mounts = set()
+ _mounted(monkeypatch, mounts)
+ upsert_app_settings({"library.locations": {"images": str(folder)}}, read_back = False)
+ forget_cache()
+ with pytest.raises(LocationUnavailable):
+ _images()
+ assert get_app_setting("library.locations", {})["images"] == str(folder)
+ folder.mkdir(parents = True)
+ mounts.add(mount)
+ forget_cache()
+ assert _images() == folder and _location(client, "images")["custom"] is True
+ assert get_app_setting("library.locations", {})["images"] == {
+ "path": str(folder),
+ "mount": mount,
+ }
+ mounts.clear()
+ forget_cache()
+ with pytest.raises(LocationUnavailable):
+ _images()
+
+
+def test_uploads_left_on_a_reset_drive_are_hidden_until_their_files_are_back(client, tmp_path):
+ [upload] = _upload(client, ("k.txt", b"k", "text/plain"))
+ drive = tmp_path / "Drive"
+ assert _move(client, "uploads", str(drive)).status_code == 200
+ drive.rename(tmp_path / "unplugged")
+ assert _move(client, "uploads", None).status_code == 200
+ assert _items(client)[0] == {}
+ (tmp_path / "unplugged" / _ref(upload)).rename(library.uploads_dir() / _ref(upload))
+ assert set(_items(client)[0]) == {upload}
+
+
+class _Crash(BaseException):
+ """The process dying: nothing the move does on a failure runs."""
+
+
+def _crash_moving(monkeypatch, key, path):
+ """Starts moving `key`'s files to `path` and crashes after the first."""
+ real = library._move_entry
+
+ def crash_after_one(entry, dest, log):
+ if log.moved:
+ raise _Crash
+ real(entry, dest, log)
+
+ monkeypatch.setattr(library, "_move_entry", crash_after_one)
+ with pytest.raises(_Crash):
+ library.move_location(key, str(path))
+ monkeypatch.setattr(library, "_move_entry", real)
+
+
+def test_a_move_cut_short_is_finished_on_the_next_start(client, tmp_path, monkeypatch):
+ from storage.studio_db import get_app_setting
+ from utils.paths.relocations import forget_cache
+
+ old, new = _images(), tmp_path / "Pictures"
+ _fill(old)
+ _crash_moving(monkeypatch, "images", new)
+ assert len(_files(new)) == 1 and len(_files(old)) == 2
+ forget_cache()
+ assert _images() == new.resolve() and len(_files(new)) == 3
+ assert "moving_from" not in str(get_app_setting("library.locations", {}))
+ assert _location(client, "images")["custom"] is True
+
+
+def test_a_move_cut_short_waits_for_the_drive_it_was_moving_onto(client, tmp_path, monkeypatch):
+ import shutil
+
+ from storage.studio_db import get_app_setting
+ from utils.paths.relocations import forget_cache
+
+ old, new = _images(), tmp_path / "Pictures"
+ _fill(old)
+ _crash_moving(monkeypatch, "images", new)
+ shutil.move(new, tmp_path / "unplugged")
+ forget_cache()
+ assert _images() == old and len(_files(old)) == 2
+ assert _location(client, "images")["available"] is True
+ assert "moving_from" in str(get_app_setting("library.locations", {}))
+ shutil.move(tmp_path / "unplugged", new)
+ assert _images() == old and len(_files(old)) == 2
+ forget_cache()
+ assert _images() == new.resolve() and len(_files(new)) == 3
+ assert "moving_from" not in str(get_app_setting("library.locations", {}))
+
+ _crash_moving(monkeypatch, "images", tmp_path / "Other")
+ shutil.move(tmp_path / "Other", tmp_path / "unplugged")
+ forget_cache()
+ response = _move(client, "images", str(new))
+ assert response.status_code == 200, response.text
+ assert response.json()["leftBehind"] == str((tmp_path / "Other").resolve())
+ assert _images() == new.resolve()
+ assert "moving_from" not in str(get_app_setting("library.locations", {}))
+
+
+def test_a_copy_across_drives_cut_short_leaves_no_partial_file_for_the_next_start(
+ client, tmp_path, monkeypatch
+):
+ import shutil
+
+ from utils.paths.relocations import forget_cache
+
+ old, new = _images(), tmp_path / "Pictures"
+ _fill(old)
+ monkeypatch.setattr(library, "_rename", _cross_device)
+ real_copy, real_discard = shutil.copy2, library._discard
+
+ def dying_copy(_src, dst, **_kwargs):
+ Path(dst).write_bytes(b"pn")
+ raise _Crash
+
+ monkeypatch.setattr(library.shutil, "copy2", dying_copy)
+ monkeypatch.setattr(library, "_discard", lambda _path: None)
+ with pytest.raises(_Crash):
+ library.move_location("images", str(new))
+ assert [name for name in os.listdir(new) if not name.startswith(".")] == []
+ monkeypatch.setattr(library.shutil, "copy2", real_copy)
+ monkeypatch.setattr(library, "_discard", real_discard)
+ forget_cache()
+ assert _images() == new.resolve()
+ assert _files(new) == ["0.png", "1.png", "2.png"]
+ assert (new / "0.png").read_bytes() == b"png0"
+
+
+def test_an_open_cannot_land_between_a_delete_and_its_row(client, monkeypatch):
+ import threading
+
+ [upload] = _upload(client, ("a.txt", b"a", "text/plain"))
+ _patch(client, id = upload, favorite = True)
+ real = library.item_exists
+
+ def a_delete_meanwhile(item_id, *args):
+ found = real(item_id, *args)
+ deleting = threading.Thread(target = library.delete_item, args = (upload,))
+ deleting.start()
+ deleting.join(0.3)
+ threads.append(deleting)
+ return found
+
+ threads = []
+ monkeypatch.setattr(library, "item_exists", a_delete_meanwhile)
+ assert _post(client, "items/opened", id = upload).status_code == 200
+ threads[0].join()
+ assert upload not in library_db.list_entries()
+
+
+def test_a_new_move_finishes_one_cut_short_first_or_waits_for_its_drive(
+ client, tmp_path, monkeypatch
+):
+ import shutil
+
+ from utils.paths.relocations import forget_cache
+
+ old, new, other = _images(), tmp_path / "Pictures", tmp_path / "Other"
+ _fill(old)
+ _crash_moving(monkeypatch, "images", new)
+ shutil.move(new, tmp_path / "unplugged")
+ forget_cache()
+ response = _move(client, "images", str(other))
+ assert response.status_code == 400 and str(new.resolve()) in response.json()["detail"]
+ shutil.move(tmp_path / "unplugged", new)
+ assert _move(client, "images", str(other)).status_code == 200
+ assert _images() == other.resolve() and len(_files(other)) == 3
+ assert _files(old) == [] and _files(new) == []
+
+
+def test_a_move_cut_short_waits_for_the_drive_it_was_leaving(client, tmp_path, monkeypatch):
+ import shutil
+
+ from storage.studio_db import get_app_setting
+ from utils.paths.relocations import forget_cache
+
+ drive = (tmp_path / "Drive").resolve()
+ drive.mkdir()
+ mounts = {str(drive)}
+ _mounted(monkeypatch, mounts)
+ source, target = drive / "Pictures", tmp_path / "Pictures"
+ assert _move(client, "images", str(source)).status_code == 200
+ _fill(_images())
+ _crash_moving(monkeypatch, "images", target)
+ shutil.move(source, tmp_path / "unplugged")
+ mounts.clear()
+ forget_cache()
+ assert _images() == target.resolve() and len(_files(target)) == 1
+ assert "moving_from" in str(get_app_setting("library.locations", {}))
+ shutil.move(tmp_path / "unplugged", source)
+ mounts.add(str(drive))
+ forget_cache()
+ assert _images() == target.resolve() and len(_files(target)) == 3
+ assert "moving_from" not in str(get_app_setting("library.locations", {}))
+
+
+def test_a_folder_choice_read_before_a_move_saved_does_not_replace_it(
+ client, tmp_path, monkeypatch
+):
+ import storage.studio_db as studio_db
+ from utils.paths import relocations
+
+ real = studio_db.get_app_setting
+ newer = (tmp_path / "Pictures").resolve()
+ newer.mkdir()
+ reads = []
+
+ def read_while_a_move_saves(*args, **kwargs):
+ value = real(*args, **kwargs)
+ reads.append(value)
+ if len(reads) == 1:
+ relocations.set_chosen("images", newer)
+ return value
+
+ relocations.forget_cache()
+ monkeypatch.setattr(studio_db, "get_app_setting", read_while_a_move_saves)
+ relocations.chosen("images")
+ assert relocations.chosen("images") == newer
+
+
+def test_a_folder_choice_that_cannot_be_read_fails_rather_than_saving_to_the_default(
+ client, tmp_path, monkeypatch
+):
+ import storage.studio_db as studio_db
+ from utils.paths.relocations import forget_cache
+
+ new = tmp_path / "Pictures"
+ assert _move(client, "images", str(new)).status_code == 200
+ real = studio_db.get_app_setting
+
+ def failing(message):
+ def read(*_args, **_kwargs):
+ raise sqlite3.OperationalError(message)
+
+ return read
+
+ monkeypatch.setattr(studio_db, "get_app_setting", failing("database is locked"))
+ forget_cache()
+ with pytest.raises(sqlite3.OperationalError):
+ _images()
+ monkeypatch.setattr(studio_db, "get_app_setting", failing("no such table: app_settings"))
+ forget_cache()
+ assert _images() == _studio("images")
+ monkeypatch.setattr(studio_db, "get_app_setting", real)
+ forget_cache()
+ assert _images() == new.resolve()
+
+
+def test_folders_on_a_disk_without_file_ids_compare_by_spelling(tmp_path, monkeypatch):
+ # FAT and some network shares report st_ino 0 for everything: equal ids must not make two
+ # different folders "the same", which would refuse every move onto such a drive.
+ a, b = tmp_path / "a", tmp_path / "b"
+ a.mkdir()
+ b.mkdir()
+ real_stat = os.stat
+
+ def no_ids(path, *args, **kwargs):
+ result = real_stat(path, *args, **kwargs)
+ return os.stat_result((result.st_mode, 0, *tuple(result)[2:]))
+
+ monkeypatch.setattr(library.os, "stat", no_ids)
+ assert not library._same_folder(a, b) and not library._inside(b / "x", a)
+ assert library._same_folder(a, tmp_path / "a") and library._inside(a / "x", a)
+
+
@pytest.fixture
def revealed(monkeypatch):
import utils.paths.file_manager as file_manager
diff --git a/studio/backend/utils/paths/path_utils.py b/studio/backend/utils/paths/path_utils.py
index 9ef905f4021..9a6a4956d1d 100644
--- a/studio/backend/utils/paths/path_utils.py
+++ b/studio/backend/utils/paths/path_utils.py
@@ -411,3 +411,26 @@ def reveal_in_file_manager(path: Path, expect_dir: bool = False) -> None:
elif not _wsl_reveal_in_explorer(path, is_file):
# No cross-desktop "select file" standard on Linux; open the directory.
subprocess.Popen(["xdg-open", str(path.parent) if is_file else target])
+
+
+# pathconf's _PC_CASE_SENSITIVE on macOS, which Python has no name for.
+_PC_CASE_SENSITIVE = 11
+
+
+def macos_volume_ignores_case(path: str) -> bool:
+ """Whether the macOS volume holding ``path`` (or its nearest folder that exists) ignores case,
+ as APFS and HFS+ do unless formatted case-sensitive. True off macOS, where only a test acting
+ as macOS asks."""
+ if sys.platform != "darwin":
+ return True
+ probe = path
+ while True:
+ try:
+ return os.pathconf(probe, _PC_CASE_SENSITIVE) == 0
+ except FileNotFoundError:
+ parent = os.path.dirname(probe)
+ if not parent or parent == probe:
+ return True
+ probe = parent
+ except (OSError, ValueError):
+ return True
diff --git a/studio/backend/utils/paths/relocations.py b/studio/backend/utils/paths/relocations.py
new file mode 100644
index 00000000000..0bc8d78bc6c
--- /dev/null
+++ b/studio/backend/utils/paths/relocations.py
@@ -0,0 +1,283 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Folders the installation owner moved a kind of file to (Settings > Library > Files on disk).
+
+Only the owner's folders move: a managed account keeps every file in its private workspace, so a
+choice is read in the owner context alone. Kept in the owner's app settings and cached, since the
+galleries resolve their folder on every file lookup.
+"""
+
+from __future__ import annotations
+
+import os
+import sqlite3
+import threading
+from pathlib import Path
+from typing import Callable, Optional
+
+from utils.account_context import is_owner_context
+
+# Fine-tunes and exports are not here: training history, chats and the model picker keep their
+# absolute paths, so moving them would strand those references.
+MOVABLE = ("uploads", "images", "videos", "audio")
+
+_SETTING = "library.locations"
+_lock = threading.Lock()
+# Keyed by the owner's database, so a test or a relaunch on another root never reads a stale map.
+# Each choice is {"path", "mount"}: `mount` is the drive or share the folder was on when picked.
+# One saved before mount points were recorded is its bare path, and is marked `bare` until its
+# folder is there to ask (while it is not, the drive is what it would name). A move under way also
+# keeps `moving_from`, the folder its files are leaving, until they have all left it, and
+# `moving_mount`, the drive or share that folder is on.
+_cache: dict[str, dict[str, dict]] = {}
+# Bumped by each write, so a load that read the database before one never caches what it read.
+_generation = 0
+# Resolving the database path walks the filesystem, and the galleries ask on every file lookup.
+# It only moves with the variables that place Studio's home (or a test swapping the function).
+_HOME_VARIABLES = ("UNSLOTH_STUDIO_HOME", "STUDIO_HOME", "UNSLOTH_HOME")
+_db_keys: dict[tuple, str] = {}
+# Set by core.library: finishes the move of a kind whose `moving_from` a crash left behind.
+resume_move: Optional[Callable[[str], None]] = None
+
+
+def _db_key() -> str:
+ from utils.paths import storage_roots
+
+ placed = (
+ *(os.environ.get(name) for name in _HOME_VARIABLES),
+ id(storage_roots.studio_db_path),
+ )
+ if placed not in _db_keys:
+ _db_keys.clear()
+ _db_keys[placed] = str(storage_roots.studio_db_path())
+ return _db_keys[placed]
+
+
+def _entry(value) -> Optional[dict]:
+ if isinstance(value, str) and value:
+ if not Path(value).is_dir():
+ return {"path": value, "mount": None, "bare": True}
+ return {"path": value, "mount": mount_point(Path(value))}
+ if isinstance(value, dict) and isinstance(value.get("path"), str) and value["path"]:
+ mount, source = value.get("mount"), value.get("moving_from")
+ entry = {
+ "path": value["path"],
+ "mount": mount if isinstance(mount, str) and mount else None,
+ }
+ if isinstance(source, str) and source:
+ entry["moving_from"] = source
+ source_mount = value.get("moving_mount")
+ entry["moving_mount"] = (
+ source_mount if isinstance(source_mount, str) and source_mount else None
+ )
+ return entry
+ return None
+
+
+def _save(chosen: dict[str, dict]) -> None:
+ from storage.studio_db import upsert_app_settings
+ stored = {
+ kind: entry["path"]
+ if entry.get("bare")
+ else {
+ key: entry[key]
+ for key in ("path", "mount", "moving_from", "moving_mount")
+ if key in entry
+ }
+ for kind, entry in chosen.items()
+ }
+ upsert_app_settings({_SETTING: stored}, read_back = False)
+
+
+def _load() -> dict[str, dict]:
+ key = _db_key()
+ with _lock:
+ if key in _cache:
+ return _cache[key]
+ generation = _generation
+ from storage.studio_db import get_app_setting
+
+ raw = get_app_setting(_SETTING, {})
+ raw = raw if isinstance(raw, dict) else {}
+ chosen = {kind: _entry(value) for kind, value in raw.items() if kind in MOVABLE}
+ chosen = {kind: entry for kind, entry in chosen.items() if entry is not None}
+ learned = any(
+ isinstance(raw[kind], str) and not entry.get("bare") for kind, entry in chosen.items()
+ )
+ with _lock:
+ # Written meanwhile: what was read is older than what that write cached.
+ if _generation != generation:
+ return _cache.get(key, chosen)
+ if learned:
+ try:
+ _save(chosen)
+ except (sqlite3.Error, OSError):
+ pass
+ _cache[key] = chosen
+ interrupted = [kind for kind, entry in chosen.items() if entry.get("moving_from")]
+ if interrupted and resume_move is not None:
+ for kind in interrupted:
+ resume_move(kind)
+ with _lock:
+ return _cache.get(key, chosen)
+ return chosen
+
+
+def _chosen_entry(key: str) -> Optional[dict]:
+ if not is_owner_context():
+ return None
+ try:
+ return _load().get(key)
+ except sqlite3.OperationalError as exc:
+ # No settings table (a database made without Studio's schema): nothing was ever moved.
+ # Any other failure, a lock held too long among them, is raised: falling back would save
+ # into the default folder, where the file vanishes once the chosen one is read again.
+ if "no such table" in str(exc):
+ return None
+ raise
+
+
+def chosen(key: str) -> Optional[Path]:
+ """The folder the owner picked for `key`, or None for the default."""
+ entry = _chosen_entry(key)
+ return Path(entry["path"]) if entry else None
+
+
+class LocationUnavailable(OSError):
+ """A chosen folder that is not there now, its drive unplugged or unmounted."""
+
+
+def mount_point(path: Path) -> Optional[str]:
+ """The mount point `path` is under when that is not the system disk's root: a drive or share
+ mounted at a fixed folder (/mnt/usb, /media/me/Drive, a Windows mounted folder). None for a
+ folder on the system disk, or on a drive with a letter or volume of its own, which goes away
+ whole when it is unplugged."""
+ for candidate in (path, *path.parents):
+ try:
+ if os.path.ismount(candidate):
+ return None if candidate.parent == candidate else str(candidate)
+ except (OSError, ValueError):
+ return None
+ return None
+
+
+def _unavailable(entry: dict) -> bool:
+ folder = Path(entry["path"])
+ if not folder.is_dir():
+ return True
+ # A fixed mount point stays behind as an empty folder once its drive is gone, and saves would
+ # land on the disk beneath it. The device number is not compared: it changes when a drive is
+ # plugged into another port, and the folder is still there then.
+ mount = entry.get("mount")
+ return bool(mount) and not os.path.ismount(mount)
+
+
+def _source_available(entry: dict) -> bool:
+ """Whether the drive of the folder a move is leaving is there."""
+ mount = entry.get("moving_mount")
+ if mount:
+ return os.path.ismount(mount)
+ anchor = Path(entry["moving_from"]).anchor
+ return not anchor or os.path.isdir(anchor)
+
+
+def _in_use(entry: dict) -> Optional[Path]:
+ """The folder `entry` saves into now: its own, or, while a move cut short waits for the drive
+ it was moving onto, the folder the files were leaving, where those not moved yet still are.
+ That stays in use until the move is taken up again, even once the drive is back: the chosen
+ folder alone would hide what the folder standing in holds. None while neither is there."""
+ source = entry.get("moving_from")
+ standing_in = bool(source) and _source_available(entry) and Path(source).is_dir()
+ if standing_in and entry.get("waiting"):
+ return Path(source)
+ if not _unavailable(entry):
+ return Path(entry["path"])
+ return Path(source) if standing_in else None
+
+
+def location_dir(key: str, default: Path) -> Path:
+ """`key`'s folder, ready to use. Only the default is created: a chosen folder that has gone is
+ not made again, or files would land on the disk beneath its mount point and vanish once the
+ drive is back."""
+ from utils.paths.storage_roots import ensure_dir
+
+ entry = _chosen_entry(key)
+ if entry is None:
+ return ensure_dir(default)
+ folder = _in_use(entry)
+ if folder is None:
+ raise LocationUnavailable(
+ f"{entry['path']} is not available. Reconnect its drive, or reset the folder in "
+ "Settings."
+ )
+ return folder
+
+
+def is_available(key: str) -> bool:
+ """False while the folder `key` saves into is on a drive that is not there."""
+ entry = _chosen_entry(key)
+ return entry is None or _in_use(entry) is not None
+
+
+def chosen_available(key: str) -> bool:
+ """False while `key`'s chosen folder itself is on a drive that is not there, even while the
+ folder a move was leaving stands in for it."""
+ entry = _chosen_entry(key)
+ return entry is None or not _unavailable(entry)
+
+
+def wait_for_move(key: str) -> None:
+ """Mark `key`'s move cut short as waiting for its chosen folder's drive, which keeps the folder
+ it was leaving in use until the move is taken up again. For this process only: the next load
+ tries the move again."""
+ with _lock:
+ entry = _cache.get(_db_key(), {}).get(key)
+ if entry is not None and entry.get("moving_from"):
+ entry["waiting"] = True
+
+
+def moving_from(key: str) -> Optional[Path]:
+ """The folder `key`'s files are still leaving, while a move is under way (or was cut short)."""
+ entry = _chosen_entry(key)
+ return Path(entry["moving_from"]) if entry and entry.get("moving_from") else None
+
+
+def moving_from_available(key: str) -> bool:
+ """False while the folder `key`'s files are leaving is on a drive that is not there: a folder
+ missing from it then is not one the move emptied."""
+ entry = _chosen_entry(key)
+ return not entry or not entry.get("moving_from") or _source_available(entry)
+
+
+def set_chosen(
+ key: str,
+ path: Optional[Path],
+ moving_from: Optional[Path] = None,
+) -> None:
+ """Record `path` for `key`; None goes back to the default. `moving_from` marks a move under
+ way, to be finished on the next load if it never is. Owner context only."""
+ if key not in MOVABLE:
+ raise ValueError(f"{key} files cannot move")
+ updated = dict(_load())
+ if path is None:
+ updated.pop(key, None)
+ else:
+ updated[key] = {"path": str(path), "mount": mount_point(path)}
+ if moving_from is not None:
+ updated[key]["moving_from"] = str(moving_from)
+ updated[key]["moving_mount"] = mount_point(moving_from)
+ global _generation
+ with _lock:
+ _save(updated)
+ _generation += 1
+ _cache[_db_key()] = updated
+
+
+def forget_cache() -> None:
+ """For tests that swap the database under a live process."""
+ global _generation
+ with _lock:
+ _generation += 1
+ _cache.clear()
+ _db_keys.clear()
diff --git a/studio/frontend/src/features/library/api.ts b/studio/frontend/src/features/library/api.ts
index ff436059b48..e5bf67b58c9 100644
--- a/studio/frontend/src/features/library/api.ts
+++ b/studio/frontend/src/features/library/api.ts
@@ -17,6 +17,7 @@ export interface LibraryItem {
source: LibrarySource;
contentType: string;
sizeBytes: number | null;
+ storageBytes?: number;
fingerprint?: string;
createdAt: number;
updatedAt: number;
@@ -26,6 +27,7 @@ export interface LibraryItem {
textOnly: boolean;
favorite: boolean;
folderId: string | null;
+ openedAt: number | null;
/** Set for fine-tuned models, which are directories: opened in chat, never downloaded. */
model: LibraryModel | null;
archived?: boolean;
@@ -46,9 +48,16 @@ export interface LibraryFolder {
updatedAt: number;
}
+export interface LibraryDisk {
+ totalBytes: number;
+ freeBytes: number;
+ sources?: string[];
+}
+
export interface LibrarySnapshot {
items: LibraryItem[];
folders: LibraryFolder[];
+ disk?: LibraryDisk | null;
}
export function errorMessage(error: unknown): string {
@@ -125,6 +134,10 @@ export function updateLibraryItem(
);
}
+export async function markLibraryItemOpened(id: string): Promise<void> {
+ await ensureOk(await sendWrite("/api/library/items/opened", jsonInit("POST", { id })));
+}
+
export async function addLibraryItemToProject(
id: string,
projectId: string,
@@ -139,6 +152,36 @@ export async function revealLibraryItem(id: string): Promise<void> {
await ensureOk(await sendWrite("/api/library/items/reveal", jsonInit("POST", { id })));
}
+export interface LibraryLocation {
+ key: "uploads" | "images" | "videos" | "audio" | "fineTunes" | "exports";
+ path: string;
+ movable?: boolean;
+ custom?: boolean;
+ available?: boolean;
+ disk?: LibraryDisk | null;
+ device?: string | null;
+}
+
+export async function getLibraryLocations(): Promise<LibraryLocation[]> {
+ const response = await ensureOk(await authFetch("/api/library/locations"));
+ return (await response.json()).locations;
+}
+
+export async function revealLibraryLocation(key: LibraryLocation["key"]): Promise<void> {
+ await ensureOk(await sendWrite("/api/library/locations/reveal", jsonInit("POST", { key })));
+}
+
+export async function moveLibraryLocation(
+ key: LibraryLocation["key"],
+ path: string | null,
+): Promise<{ locations: LibraryLocation[]; leftBehind: string | null }> {
+ const response = await ensureOk(
+ await sendWrite("/api/library/locations/move", jsonInit("POST", { key, path })),
+ );
+ const body = await response.json();
+ return { locations: body.locations, leftBehind: body.leftBehind ?? null };
+}
+
export async function deleteLibraryItem(id: string, fingerprint?: string): Promise<void> {
await ensureOk(
await sendWrite("/api/library/items/delete", jsonInit("POST", { id, fingerprint })),
diff --git a/studio/frontend/src/features/library/components/library-actions.tsx b/studio/frontend/src/features/library/components/library-actions.tsx
index 30bac77a55c..1bad807936a 100644
--- a/studio/frontend/src/features/library/components/library-actions.tsx
+++ b/studio/frontend/src/features/library/components/library-actions.tsx
@@ -26,7 +26,7 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { MessageCircleIcon, StarPointedIcon } from "@/lib/hugeicons-derived";
import { useMemo, useState } from "react";
import type { LibraryFolder } from "../api";
-import { isFileItem, isModelItem } from "../file-kind";
+import { isDeletable, isFileItem, isModelItem } from "../file-kind";
import { type LibraryTarget, useLibraryActions } from "../actions-context";
import { canReveal, revealInFolder, useRevealLabel } from "../reveal";
import { OVERLAY_CONTROL } from "../surface";
@@ -83,7 +83,6 @@ export function LibraryActionsMenu({
);
const inFolder = currentFolderId(target);
const item = target.kind === "item" ? target.item : null;
- const isFile = !item || isFileItem(item);
const revealLabel = useRevealLabel();
return (
@@ -127,7 +126,7 @@ export function LibraryActionsMenu({
{t(item.favorite ? "library.menu.removeFromFavorites" : "library.menu.addToFavorites")}
</DropdownMenuItem>
)}
- {item && isFile && (
+ {item && isFileItem(item) && (
<DropdownMenuItem onSelect={() => actions.download(item)}>
<HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className={ICON} />
{t("library.menu.download")}
@@ -173,7 +172,7 @@ export function LibraryActionsMenu({
))}
</DropdownMenuSubContent>
</DropdownMenuSub>
- {isFile && (
+ {(!item || isDeletable(item)) && (
<DropdownMenuItem variant="destructive" onSelect={() => actions.remove(target)}>
<HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className={ICON} />
{target.kind === "folder" ? t("library.menu.deleteFolder") : t("common.delete")}
diff --git a/studio/frontend/src/features/library/components/library-cards.tsx b/studio/frontend/src/features/library/components/library-cards.tsx
index 15c59cc22bb..2e244b56021 100644
--- a/studio/frontend/src/features/library/components/library-cards.tsx
+++ b/studio/frontend/src/features/library/components/library-cards.tsx
@@ -6,7 +6,7 @@ import { useLocale, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { Folder01Icon, PlayIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { type ReactNode, useContext, useRef, useState } from "react";
+import { type ReactNode, type RefObject, useContext, useRef, useState } from "react";
import type { LibraryFolder, LibraryItem } from "../api";
import {
KIND_ICONS,
@@ -17,7 +17,8 @@ import {
import { formatCardTime, formatItemCount } from "../format";
import { useColumnCount, useLibraryThumbnail, useSeen } from "../hooks";
import { useLibraryActions } from "../actions-context";
-import { GLASS_CONTROL, OVERLAY_CONTROL, RAISED_SURFACE } from "../surface";
+import { CARD_COLUMNS, useLibrarySettingsStore } from "../settings-store";
+import { GLASS_CONTROL, GLASS_SURFACE, OVERLAY_CONTROL, RAISED_SURFACE } from "../surface";
import { CardSelectionContext } from "./card-selection";
import { LibraryActionsMenu } from "./library-actions";
@@ -44,7 +45,15 @@ export function KindIcon({ item, className }: { item: LibraryItem; className?: s
const MIN_THUMB_RATIO = 2 / 3;
const MAX_THUMB_RATIO = 3 / 2;
-function ImageThumb({ item, className }: { item: LibraryItem; className?: string }) {
+function ImageThumb({
+ item,
+ className,
+ square = false,
+}: {
+ item: LibraryItem;
+ className?: string;
+ square?: boolean;
+}) {
const holder = useRef<HTMLDivElement>(null);
const { url, failed } = useLibraryThumbnail(item, useSeen(holder));
const [ratio, setRatio] = useState<number | null>(null);
@@ -60,9 +69,9 @@ function ImageThumb({ item, className }: { item: LibraryItem; className?: string
return (
<div
ref={holder}
- className={cn("relative overflow-hidden", className)}
+ className={cn("relative overflow-hidden", square && "aspect-square", className)}
style={
- loaded
+ loaded && !square
? { aspectRatio: 1 / Math.min(Math.max(ratio, MIN_THUMB_RATIO), MAX_THUMB_RATIO) }
: undefined
}
@@ -151,6 +160,8 @@ function CardFrame({
export function ItemCard({ item }: { item: LibraryItem }) {
const locale = useLocale();
const actions = useLibraryActions();
+ const showTime = useLibrarySettingsStore((s) => s.showCardDates);
+ const square = useLibrarySettingsStore((s) => s.imageLayout === "square");
const thumb = hasThumbnail(item);
return (
<CardFrame
@@ -165,10 +176,22 @@ export function ItemCard({ item }: { item: LibraryItem }) {
/>
}
glass={thumb}
- className={thumb ? cn("bg-muted", CARD_SHADOW) : CARD_SURFACE}
+ className={thumb ? cn("relative bg-muted", CARD_SHADOW) : CARD_SURFACE}
>
{thumb ? (
- <ImageThumb item={item} />
+ <>
+ <ImageThumb item={item} square={square && fileKind(item) === "image"} />
+ {showTime && (
+ <span
+ className={cn(
+ GLASS_SURFACE,
+ "pointer-events-none absolute bottom-2 left-2 rounded-full px-2 py-0.5 text-ui-12 opacity-0 transition-opacity group-hover/library-card:opacity-100 group-has-[:focus-visible]/library-card:opacity-100 pointer-coarse:opacity-100",
+ )}
+ >
+ {formatCardTime(item.updatedAt, locale)}
+ </span>
+ )}
+ </>
) : (
<div className="flex aspect-square flex-col px-5 pb-3.5 pt-5">
<p className="line-clamp-2 break-all pr-7 font-medium text-ui-14 leading-snug text-foreground">
@@ -178,7 +201,7 @@ export function ItemCard({ item }: { item: LibraryItem }) {
<KindIcon item={item} className="size-9" />
</div>
<p className="truncate pr-6 text-ui-13 text-muted-foreground">
- {formatCardTime(item.updatedAt, locale)}
+ {showTime && formatCardTime(item.updatedAt, locale)}
</p>
</div>
)}
@@ -220,6 +243,11 @@ function FolderCard({
);
}
+function useCardColumns(container: RefObject<HTMLDivElement | null>): number {
+ const { minWidth, max } = CARD_COLUMNS[useLibrarySettingsStore((s) => s.cardSize)];
+ return useColumnCount(container, minWidth, max);
+}
+
export function Masonry<T>({
items,
getKey,
@@ -230,7 +258,7 @@ export function Masonry<T>({
render: (item: T) => ReactNode;
}) {
const container = useRef<HTMLDivElement>(null);
- const columns = useColumnCount(container);
+ const columns = useCardColumns(container);
const buckets: T[][] = Array.from({ length: columns }, () => []);
items.forEach((item, index) => buckets[index % columns]!.push(item));
return (
@@ -254,7 +282,7 @@ export function FolderGrid({
counts: Map<string, number>;
}) {
const container = useRef<HTMLDivElement>(null);
- const columns = useColumnCount(container);
+ const columns = useCardColumns(container);
return (
<div
ref={container}
@@ -271,13 +299,13 @@ export function FolderGrid({
export function ItemTile({ item }: { item: LibraryItem }) {
if (hasThumbnail(item)) {
return (
- <div className="size-9 shrink-0 overflow-hidden rounded-xl border border-border/60 bg-muted [&_img]:size-9 [&_img]:object-cover [&_img]:object-top">
+ <div className="size-9 shrink-0 overflow-hidden rounded-[10px] border border-border/60 bg-muted [&_img]:size-9 [&_img]:object-cover [&_img]:object-top">
<ImageThumb item={item} />
</div>
);
}
return (
- <div className="flex size-9 shrink-0 items-center justify-center rounded-xl border border-border/60">
+ <div className="flex size-9 shrink-0 items-center justify-center rounded-[10px] border border-border/60">
<KindIcon item={item} className="size-5" />
</div>
);
diff --git a/studio/frontend/src/features/library/components/library-header.tsx b/studio/frontend/src/features/library/components/library-header.tsx
index 72d9dce2996..7d0d69c3de3 100644
--- a/studio/frontend/src/features/library/components/library-header.tsx
+++ b/studio/frontend/src/features/library/components/library-header.tsx
@@ -217,12 +217,14 @@ export function LibraryHeader({
className="sticky top-0 z-20 -mx-6 mt-2 bg-background px-6 py-4 sm:-mx-10 sm:px-10"
>
{tabs ? (
- <TabStrip
- tabs={tabs.items}
- active={tabs.active}
- onChange={tabs.onChange}
- reserve={covered ? controlsWidth + GAP_PX : 0}
- />
+ <div className="pl-3">
+ <TabStrip
+ tabs={tabs.items}
+ active={tabs.active}
+ onChange={tabs.onChange}
+ reserve={covered ? controlsWidth + GAP_PX : 0}
+ />
+ </div>
) : (
<div className="h-9" />
)}
diff --git a/studio/frontend/src/features/library/components/library-list.tsx b/studio/frontend/src/features/library/components/library-list.tsx
index c6e88924be9..aab56740dbd 100644
--- a/studio/frontend/src/features/library/components/library-list.tsx
+++ b/studio/frontend/src/features/library/components/library-list.tsx
@@ -2,7 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { Checkbox } from "@/components/ui/checkbox";
-import { useLocale, useT } from "@/i18n";
+import { type TranslationKey, useLocale, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { Folder01Icon } from "@hugeicons/core-free-icons";
import { StarPointedIcon } from "@/lib/hugeicons-derived";
@@ -10,7 +10,9 @@ import { HugeiconsIcon } from "@hugeicons/react";
import type { ReactNode } from "react";
import type { LibraryFolder, LibraryItem } from "../api";
import { modelLabelKey } from "../file-kind";
-import { formatActivityTime, formatItemCount } from "../format";
+import { formatActivityTime, formatCardTime, formatItemCount, formatSize } from "../format";
+import type { LibrarySortKey, LibrarySortState } from "../settings-store";
+import { ArrowDownIcon, ArrowUpIcon } from "lucide-react";
import { type LibraryTarget, useLibraryActions } from "../actions-context";
import { LibraryActionsMenu } from "./library-actions";
import { ItemTile } from "./library-cards";
@@ -19,7 +21,51 @@ function targetKey(target: LibraryTarget): string {
return target.kind === "item" ? `item:${target.item.id}` : `folder:${target.folder.id}`;
}
-const ROW_INSET = "pl-4 pr-3";
+const ROW_INSET = "pl-4 pr-6";
+
+const CELL = "hidden text-ui-13 text-muted-foreground sm:block";
+const ACTIVITY_COLUMN = "w-48 shrink-0";
+const MODIFIED_COLUMN = "w-40 shrink-0";
+const SIZE_COLUMN = "w-28 shrink-0";
+const ACTIVITY_COLUMNS: [LibrarySortKey, TranslationKey, string][] = [
+ ["modified", "library.list.lastActivity", ACTIVITY_COLUMN],
+];
+const COLUMNS: [LibrarySortKey, TranslationKey, string][] = [
+ ["modified", "library.list.modifiedColumn", MODIFIED_COLUMN],
+ ["size", "library.preview.size", SIZE_COLUMN],
+];
+
+function SortHeader({
+ column,
+ label,
+ sort,
+ onSortChange,
+ className,
+}: {
+ column: LibrarySortKey;
+ label: string;
+ sort: LibrarySortState;
+ onSortChange: (key: LibrarySortKey) => void;
+ className?: string;
+}) {
+ const active = sort.key === column;
+ const Arrow = sort.desc ? ArrowDownIcon : ArrowUpIcon;
+ return (
+ <button
+ type="button"
+ onClick={() => onSortChange(column)}
+ aria-sort={active ? (sort.desc ? "descending" : "ascending") : undefined}
+ className={cn(
+ "flex items-center gap-1 text-left transition-colors hover:text-foreground",
+ active && "text-foreground",
+ className,
+ )}
+ >
+ {label}
+ {active && <Arrow className="size-3.5" strokeWidth={2} />}
+ </button>
+ );
+}
function GutterCheckbox({
checked,
@@ -60,6 +106,9 @@ function Row({
onOpen,
tile,
name,
+ modified,
+ opened,
+ size,
activity,
}: {
target: LibraryTarget;
@@ -69,13 +118,17 @@ function Row({
onOpen: () => void;
tile: ReactNode;
name: ReactNode;
- activity: string;
+ modified: number;
+ opened?: number | null;
+ size?: number | null;
+ activity: boolean;
}) {
const t = useT();
+ const locale = useLocale();
return (
<div
className={cn(
- "group/library-row relative flex items-center gap-4 rounded-xl transition-colors hover:bg-muted dark:hover:bg-muted/60",
+ "group/library-row relative flex items-center gap-4 rounded-[14px] transition-colors hover:bg-muted dark:hover:bg-muted/60",
ROW_INSET,
selected && "bg-muted dark:bg-muted/60",
)}
@@ -96,9 +149,18 @@ function Row({
>
{tile}
<span className="flex min-w-0 items-center gap-2 text-ui-14 text-foreground">{name}</span>
- <span className="ml-auto hidden w-44 shrink-0 text-ui-13 text-muted-foreground sm:block">
- {activity}
- </span>
+ {activity ? (
+ <span className={cn(ACTIVITY_COLUMN, CELL, "ml-auto")}>
+ {(opened ?? 0) > modified
+ ? t("library.list.opened", { time: formatActivityTime(opened!, locale, t) })
+ : t("library.list.modified", { time: formatActivityTime(modified, locale, t) })}
+ </span>
+ ) : (
+ <>
+ <span className={cn(MODIFIED_COLUMN, CELL, "ml-auto")}>{formatCardTime(modified, locale)}</span>
+ <span className={cn(SIZE_COLUMN, CELL)}>{formatSize(size ?? null, locale, t)}</span>
+ </>
+ )}
</button>
<LibraryActionsMenu target={target} variant="row" />
</div>
@@ -111,18 +173,21 @@ export function LibraryList({
counts,
selection,
onSelectionChange,
+ sort,
+ onSortChange,
+ activity,
}: {
folders: LibraryFolder[];
items: LibraryItem[];
counts: Map<string, number>;
selection: Set<string>;
onSelectionChange: (next: Set<string>) => void;
+ sort: LibrarySortState;
+ onSortChange: (key: LibrarySortKey) => void;
+ activity: boolean;
}) {
const t = useT();
- const locale = useLocale();
const actions = useLibraryActions();
- const modified = (ts: number) =>
- t("library.list.modified", { time: formatActivityTime(ts, locale, t) });
const targets: LibraryTarget[] = [
...folders.map((folder) => ({ kind: "folder" as const, folder })),
...items.map((item) => ({ kind: "item" as const, item })),
@@ -140,7 +205,7 @@ export function LibraryList({
return (
<div>
{/* The padding sits outside the row, so the checkbox centers on the column titles. */}
- <div className="border-b border-border/60 pb-2">
+ <div className="pb-2">
<div
className={cn(
"group/library-head relative flex items-center gap-4 text-ui-13 text-muted-foreground",
@@ -157,8 +222,19 @@ export function LibraryList({
}
label={t("library.list.selectAll")}
/>
- <span className="flex-1">{t("library.list.name")}</span>
- <span className="hidden w-44 shrink-0 sm:block">{t("library.list.lastActivity")}</span>
+ <span className="flex-1">
+ <SortHeader column="name" label={t("library.list.name")} sort={sort} onSortChange={onSortChange} />
+ </span>
+ {(activity ? ACTIVITY_COLUMNS : COLUMNS).map(([column, label, width]) => (
+ <SortHeader
+ key={column}
+ column={column}
+ label={t(label)}
+ sort={sort}
+ onSortChange={onSortChange}
+ className={cn(width, "hidden sm:flex")}
+ />
+ ))}
<span className="w-8 shrink-0" />
</div>
</div>
@@ -172,7 +248,7 @@ export function LibraryList({
onSelectedChange={(selected) => setSelected({ kind: "folder", folder }, selected)}
onOpen={() => actions.openFolder(folder.id)}
tile={
- <div className="flex size-9 shrink-0 items-center justify-center rounded-xl border border-border/60">
+ <div className="flex size-9 shrink-0 items-center justify-center rounded-[10px] border border-border/60">
<HugeiconsIcon icon={Folder01Icon} strokeWidth={1.5} className="size-5" />
</div>
}
@@ -184,7 +260,8 @@ export function LibraryList({
</span>
</>
}
- activity={modified(folder.updatedAt)}
+ modified={folder.updatedAt}
+ activity={activity}
/>
))}
{items.map((item) => (
@@ -214,7 +291,10 @@ export function LibraryList({
)}
</>
}
- activity={modified(item.updatedAt)}
+ modified={item.updatedAt}
+ opened={item.openedAt}
+ size={item.sizeBytes}
+ activity={activity}
/>
))}
</div>
diff --git a/studio/frontend/src/features/library/components/library-preview.tsx b/studio/frontend/src/features/library/components/library-preview.tsx
index f18e20e2dd7..5e2a7aa812d 100644
--- a/studio/frontend/src/features/library/components/library-preview.tsx
+++ b/studio/frontend/src/features/library/components/library-preview.tsx
@@ -27,6 +27,7 @@ import {
import {
fileKind,
hasImagePreview,
+ isDeletable,
isFileItem,
isTextPreviewable,
modelLabelKey,
@@ -565,7 +566,7 @@ export function LibraryPreview({
return addLibraryItemToProject(item.id, projectId);
}
: undefined,
- onDelete: isFileItem(item) ? () => onDelete(item) : undefined,
+ onDelete: isDeletable(item) ? () => onDelete(item) : undefined,
}
: {}
}
diff --git a/studio/frontend/src/features/library/components/library-toolbar.tsx b/studio/frontend/src/features/library/components/library-toolbar.tsx
index 1b1c44aeea8..9933d4fcb17 100644
--- a/studio/frontend/src/features/library/components/library-toolbar.tsx
+++ b/studio/frontend/src/features/library/components/library-toolbar.tsx
@@ -35,7 +35,7 @@ import { ChevronDownIcon } from "lucide-react";
import type { LibrarySource } from "../api";
import type { LibraryTypeFilter } from "../file-kind";
import { EMPTY_FILTERS, type LibraryFilters, filtersActive } from "../filters";
-import type { LibraryView } from "../store";
+import type { LibraryView } from "../settings-store";
const ICON = "size-icon";
const ROUND_BUTTON =
diff --git a/studio/frontend/src/features/library/components/storage-bar.tsx b/studio/frontend/src/features/library/components/storage-bar.tsx
new file mode 100644
index 00000000000..ddd9b1c2171
--- /dev/null
+++ b/studio/frontend/src/features/library/components/storage-bar.tsx
@@ -0,0 +1,34 @@
+// 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 { useLocale, useT } from "@/i18n";
+import type { LibraryDisk } from "../api";
+import { formatSize } from "../format";
+
+export function LibraryStorageBar({
+ libraryBytes,
+ disk,
+}: {
+ libraryBytes: number;
+ disk: LibraryDisk | null;
+}) {
+ const t = useT();
+ const locale = useLocale();
+ if (!disk || disk.totalBytes <= 0) return null;
+ const otherBytes = Math.max(0, disk.totalBytes - disk.freeBytes - libraryBytes);
+ const share = (bytes: number) => `${(bytes / disk.totalBytes) * 100}%`;
+ return (
+ <>
+ <div className="flex h-2 overflow-hidden rounded-full bg-muted">
+ <div className="min-w-1 bg-foreground" style={{ width: share(libraryBytes) }} />
+ <div className="bg-muted-foreground/35" style={{ width: share(otherBytes) }} />
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t("settings.library.storageDisk", {
+ free: formatSize(disk.freeBytes, locale, t) ?? "",
+ total: formatSize(disk.totalBytes, locale, t) ?? "",
+ })}
+ </p>
+ </>
+ );
+}
diff --git a/studio/frontend/src/features/library/file-kind.ts b/studio/frontend/src/features/library/file-kind.ts
index 2ede8171c38..f21aaeea713 100644
--- a/studio/frontend/src/features/library/file-kind.ts
+++ b/studio/frontend/src/features/library/file-kind.ts
@@ -90,6 +90,10 @@ export function isFileItem(item: LibraryItem): boolean {
return !isModelItem(item);
}
+export function isDeletable(item: LibraryItem): boolean {
+ return item.model?.exportType !== "gguf";
+}
+
const MODEL_LABELS = {
"training:lora": "library.modelKind.lora",
"training:merged": "library.modelKind.fullFineTune",
diff --git a/studio/frontend/src/features/library/format.ts b/studio/frontend/src/features/library/format.ts
index dc1f996ef89..4ccebf88c2b 100644
--- a/studio/frontend/src/features/library/format.ts
+++ b/studio/frontend/src/features/library/format.ts
@@ -2,7 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import type { InterpolationValues, Locale, TranslationKey } from "@/i18n";
-import { formatRelativeTime } from "@/i18n/relative-time";
+import { formatRelativeTime } from "../../i18n/relative-time.ts";
type Translate = (key: TranslationKey, values?: InterpolationValues) => string;
@@ -17,23 +17,30 @@ function yesterday(locale: Locale): string {
return formatter.format(-1, "day");
}
+const DAY_MS = 86_400_000;
+
function startOfDay(date: Date): number {
return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
}
-export function formatCardTime(ts: number, locale: Locale): string {
+export function formatCardTime(ts: number, locale: Locale, now: number = Date.now()): string {
+ if (!Number.isFinite(ts)) return "";
const then = new Date(ts);
- const now = new Date();
- if (then.toDateString() === now.toDateString()) {
- return then.toLocaleTimeString(locale, {
- hour: "numeric",
- minute: "2-digit",
- });
+ const today = new Date(now);
+ // Rounded: a day with a daylight-saving change is 23 or 25 hours long.
+ const days = Math.round((startOfDay(today) - startOfDay(then)) / DAY_MS);
+ if (days === 0) {
+ return then.toLocaleTimeString(locale, { hour: "numeric", minute: "2-digit" });
+ }
+ if (days === 1) {
+ const word = yesterday(locale);
+ return word.charAt(0).toLocaleUpperCase(locale) + word.slice(1);
}
+ if (days > 1 && days < 7) return then.toLocaleDateString(locale, { weekday: "long" });
return then.toLocaleDateString(locale, {
month: "short",
day: "numeric",
- year: then.getFullYear() === now.getFullYear() ? undefined : "numeric",
+ year: then.getFullYear() === today.getFullYear() ? undefined : "numeric",
});
}
@@ -45,7 +52,7 @@ export function formatActivityTime(ts: number, locale: Locale, t: Translate): st
if (minutes < 60) return formatRelativeTime(locale, -minutes, "minute");
const hours = Math.floor(minutes / 60);
if (hours < 24) return formatRelativeTime(locale, -hours, "hour");
- const days = Math.round((startOfDay(new Date()) - startOfDay(new Date(ts))) / 86_400_000);
+ const days = Math.round((startOfDay(new Date()) - startOfDay(new Date(ts))) / DAY_MS);
if (days <= 1) return yesterday(locale);
if (days < 7) return formatRelativeTime(locale, -days, "day");
return formatCardTime(ts, locale);
@@ -55,6 +62,7 @@ const SIZE_UNITS = [
"library.size.kilobytes",
"library.size.megabytes",
"library.size.gigabytes",
+ "library.size.terabytes",
] as const satisfies readonly TranslationKey[];
export function formatSize(bytes: number | null, locale: Locale, t: Translate): string | null {
diff --git a/studio/frontend/src/features/library/index.ts b/studio/frontend/src/features/library/index.ts
index 33f7459a70c..2b6c871b4ed 100644
--- a/studio/frontend/src/features/library/index.ts
+++ b/studio/frontend/src/features/library/index.ts
@@ -3,4 +3,26 @@
export { useLibraryChatHandoffStore } from "./chat-handoff-store";
export { useLibraryFavorites } from "./favorites-store";
-export { validateLibrarySearch, type LibrarySearch, type LibraryTab } from "./search";
+export { LIBRARY_TABS, validateLibrarySearch, type LibrarySearch, type LibraryTab } from "./search";
+export {
+ LIBRARY_SETTINGS_STORAGE_KEY,
+ LIBRARY_VIEW_STORAGE_KEY,
+ SUGGESTED_LIMITS,
+ type LibrarySettings,
+ type LibraryTabVisibility,
+ useLibrarySettingsStore,
+ useLibraryViewStore,
+ useLibraryVisitStore,
+} from "./settings-store";
+export { STORAGE_LABELS, refreshLibraryStorage, useLibraryStorage } from "./storage";
+export { formatSize } from "./format";
+export { parentFolder } from "./paths";
+export { LibraryStorageBar } from "./components/storage-bar";
+export {
+ type LibraryLocation,
+ errorMessage,
+ getLibraryLocations,
+ moveLibraryLocation,
+ revealLibraryLocation,
+} from "./api";
+export { useRevealLabel } from "./reveal";
diff --git a/studio/frontend/src/features/library/library-page.tsx b/studio/frontend/src/features/library/library-page.tsx
index de1840243a8..1c215b638b5 100644
--- a/studio/frontend/src/features/library/library-page.tsx
+++ b/studio/frontend/src/features/library/library-page.tsx
@@ -47,7 +47,13 @@ import {
downloadLibraryItems,
} from "./actions";
import { type LibraryFolder, type LibraryItem, type LibraryUploadBatch, errorMessage } from "./api";
-import { fileKind, isFileItem, isModelItem } from "./file-kind";
+import {
+ type LibraryTypeFilter,
+ fileKind,
+ isDeletable,
+ isFileItem,
+ isModelItem,
+} from "./file-kind";
import {
type LibraryActions,
LibraryActionsProvider,
@@ -62,7 +68,18 @@ import { LibraryHeader } from "./components/library-header";
import { LibraryToolbar, type NewAction } from "./components/library-toolbar";
import { EMPTY_FILTERS, type LibraryFilters, filtersActive, matchesFilters } from "./filters";
import { LIBRARY_TABS, type LibrarySearch, type LibraryTab } from "./search";
-import { useLibraryStore, useLibraryViewStore } from "./store";
+import { useLibraryStore } from "./store";
+import {
+ SORT_STATES,
+ compareBySort,
+ includedBySettings,
+ lastActivity,
+ nextSort,
+ sortParam,
+ useLibrarySettingsStore,
+ useLibraryViewStore,
+ useLibraryVisitStore,
+} from "./settings-store";
const TAB_LABELS: Record<LibraryTab, TranslationKey> = {
suggested: "library.tabs.suggested",
@@ -100,8 +117,6 @@ const KIND_TABS: Partial<Record<LibraryTab, (item: LibraryItem) => boolean>> = {
models: isModelItem,
};
-const SUGGESTED_LIMIT = 40;
-
const DELETE_NOTES: Record<string, TranslationKey> = {
upload: "library.dialog.deleteUpload",
attachment: "library.dialog.deleteAttachment",
@@ -109,6 +124,7 @@ const DELETE_NOTES: Record<string, TranslationKey> = {
video: "library.dialog.deleteVideo",
audio: "library.dialog.deleteAudio",
sandbox: "library.dialog.deleteSandbox",
+ model: "library.dialog.deleteModel",
};
type NameDialogState =
@@ -124,8 +140,6 @@ const BAR_PILL =
const BAR_ROUND =
"flex size-9 items-center justify-center rounded-full outline-none transition-colors hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring";
-const KIND_ONLY_TABS = new Set<LibraryTab>(["images", "videos", "audio", "models"]);
-
function EmptyState({
icon,
title,
@@ -161,9 +175,12 @@ function LoadingGrid() {
);
}
+const FILE_TYPES: LibraryTypeFilter[] = ["documents", "spreadsheets", "presentations", "pdfs"];
+
export function LibraryPage() {
const search = useSearch({ from: "/library" });
const refresh = useLibraryStore((s) => s.refresh);
+ const visit = useLibraryVisitStore((s) => s.visit);
useEffect(() => {
void refresh();
@@ -172,26 +189,52 @@ export function LibraryPage() {
return () => window.removeEventListener("focus", onFocus);
}, [refresh]);
- return <LibraryView key={`${search.show ?? ""}:${search.folder ?? ""}`} search={search} />;
+ return (
+ <LibraryView
+ key={`${visit}:${search.show ?? ""}:${search.folder ?? ""}:${search.filter ?? ""}`}
+ search={search}
+ />
+ );
}
function LibraryView({ search }: { search: LibrarySearch }) {
const t = useT();
const navigate = useNavigate();
- const { items, folders, status, error, refresh, patchItem, removeItem, upload, addFolder, patchFolder, removeFolder } =
+ const { items: allItems, folders, status, error, refresh, patchItem, removeItem, upload, addFolder, patchFolder, removeFolder, markOpened } =
useLibraryStore();
+ const settings = useLibrarySettingsStore();
+ const items = useMemo(
+ () => allItems.filter((item) => includedBySettings(item.id, settings)),
+ [allItems, settings],
+ );
const view = useLibraryViewStore((s) => s.view);
const setView = useLibraryViewStore((s) => s.setView);
const openSettings = useSettingsDialogStore((s) => s.openDialog);
const [query, setQuery] = useState("");
- const [filters, setFilters] = useState<LibraryFilters>(EMPTY_FILTERS);
+ const [filters, setFilters] = useState<LibraryFilters>(() =>
+ search.filter === "files" ? { sources: new Set(), types: new Set(FILE_TYPES) } : EMPTY_FILTERS,
+ );
const [selection, setSelection] = useState<Set<string>>(new Set());
const [nameDialog, setNameDialog] = useState<NameDialogState | null>(null);
const [pendingDelete, setPendingDelete] = useState<LibraryTarget[] | null>(null);
const fileInput = useRef<HTMLInputElement>(null);
- const tab: LibraryTab = search.show ?? "suggested";
+ const loaded = status === "ready";
+ // "auto" tabs count as shown until the listing lands, so a start tab is not swapped mid-load.
+ const tabVisible = (entry: LibraryTab) => {
+ const visibility = settings.tabs[entry] ?? "always";
+ if (visibility === "hidden" || (entry === "models" && !settings.showFineTunes)) return false;
+ return visibility === "always" || !loaded || items.some(KIND_TABS[entry] ?? (() => true));
+ };
+ // Read once: changing Open on in settings must not move a Library that is already open.
+ const [preferred] = useState(() =>
+ settings.startTab === "last" ? settings.lastTab : settings.startTab,
+ );
+ const tab: LibraryTab =
+ search.show ??
+ (tabVisible(preferred) ? preferred : (LIBRARY_TABS.find(tabVisible) ?? "all"));
+ const sort = SORT_STATES[search.sort ?? settings.sort];
const folderId = search.folder ?? null;
const folderById = useMemo(() => new Map(folders.map((f) => [f.id, f])), [folders]);
const currentFolder = folderId ? (folderById.get(folderId) ?? null) : null;
@@ -226,14 +269,12 @@ function LibraryView({ search }: { search: LibrarySearch }) {
const kindFilter = folderId ? undefined : KIND_TABS[tab];
- const shownTabs = useMemo(
- () =>
- LIBRARY_TABS.filter(
- (entry) =>
- !KIND_ONLY_TABS.has(entry) || entry === tab || items.some(KIND_TABS[entry]!),
- ),
- [items, tab],
- );
+ const shownTabs = LIBRARY_TABS.filter((entry) => entry === tab || tabVisible(entry));
+
+ const setLibrarySettings = settings.set;
+ useEffect(() => {
+ if (!folderId) setLibrarySettings({ lastTab: tab });
+ }, [tab, folderId, setLibrarySettings]);
const visibleItems = useMemo(() => {
let pool = items;
if (folderId) pool = pool.filter((item) => item.folderId === folderId);
@@ -243,10 +284,13 @@ function LibraryView({ search }: { search: LibrarySearch }) {
pool = pool.filter(
(item) => nameMatches(item.name, needle) && matchesFilters(item, filters, !kindFilter),
);
- return tab === "suggested" && !folderId && !needle && !filtersActive(filters)
- ? pool.slice(0, SUGGESTED_LIMIT)
- : pool;
- }, [items, folderId, tab, needle, filters, kindFilter]);
+ if (tab === "suggested" && !folderId) {
+ const byActivity = [...pool].sort((a, b) => lastActivity(b) - lastActivity(a));
+ pool = needle || filtersActive(filters) ? byActivity : byActivity.slice(0, settings.suggestedLimit);
+ if (sort.key === "modified") return sort.desc ? pool : pool.reverse();
+ }
+ return [...pool].sort(compareBySort(sort));
+ }, [items, folderId, tab, needle, filters, kindFilter, settings.suggestedLimit, sort]);
const visibleFolders = useMemo(() => {
const showsFolders = folderId || tab === "folders" || tab === "all";
@@ -254,11 +298,11 @@ function LibraryView({ search }: { search: LibrarySearch }) {
return folders
.filter((folder) => folder.parentId === folderId)
.filter((folder) => nameMatches(folder.name, needle))
- .sort((a, b) => b.updatedAt - a.updatedAt);
- }, [folders, folderId, tab, needle, filters]);
+ .sort(compareBySort(sort.key === "size" ? { key: "name", desc: false } : sort));
+ }, [folders, folderId, tab, needle, filters, sort]);
- // A search or filter that hides a selected entry deselects it, so bulk actions only ever act on
- // what is on screen and clearing the filter never brings a selection back.
+ // A search, filter or Content setting that hides a selected entry deselects it, so bulk actions
+ // only ever act on what is on screen and clearing the filter never brings a selection back.
const visibleKeys = useMemo(
() =>
new Set([
@@ -272,6 +316,10 @@ function LibraryView({ search }: { search: LibrarySearch }) {
}
const previewItem = search.item ? (items.find((item) => item.id === search.item) ?? null) : null;
+ const previewId = previewItem?.id ?? null;
+ useEffect(() => {
+ if (previewId) markOpened(previewId);
+ }, [previewId, markOpened]);
const router = useRouter();
const pushedPreview = useRef<string | null>(null);
@@ -372,7 +420,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
moveTo: (target, destination) => void moveAll([target], destination),
moveToNewFolder: (target) =>
setNameDialog({ mode: "create", parentId: folderId, thenMove: target }),
- remove: (target) => setPendingDelete([target]),
+ remove: (target) => requestDelete([target]),
};
async function uploadBatch(batch: LibraryUploadBatch, count: number, label: string) {
@@ -474,6 +522,9 @@ function LibraryView({ search }: { search: LibrarySearch }) {
}
}
+ const requestDelete = (targets: LibraryTarget[]) =>
+ settings.confirmDelete ? setPendingDelete(targets) : void confirmDelete(targets);
+
async function confirmDelete(targets: LibraryTarget[]) {
setPendingDelete(null);
setSelection(new Set());
@@ -550,7 +601,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
}
const title = folderId ? (
- <nav className="flex min-w-0 items-center gap-2 text-ui-25 font-semibold tracking-[-0.028em]" aria-label={t("library.breadcrumb")}>
+ <nav className="flex min-w-0 items-center gap-2 text-[calc(1.6875rem*var(--ui-font-scale,1))] font-semibold tracking-[-0.028em]" aria-label={t("library.breadcrumb")}>
<button
type="button"
onClick={() => go({ show: "folders" })}
@@ -576,7 +627,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
))}
</nav>
) : (
- <h1 className="text-ui-25 font-semibold leading-[1.04] tracking-[-0.028em] text-foreground">
+ <h1 className="text-[calc(1.6875rem*var(--ui-font-scale,1))] font-semibold leading-[1.04] tracking-[-0.028em] text-foreground">
{t("shell.navigation.library")}
</h1>
);
@@ -709,6 +760,9 @@ function LibraryView({ search }: { search: LibrarySearch }) {
counts={counts}
selection={selection}
onSelectionChange={setSelection}
+ sort={sort}
+ onSortChange={(key) => go({ ...search, sort: sortParam(nextSort(sort, key)) }, true)}
+ activity={tab === "suggested" && !folderId}
/>
</div>
);
@@ -769,7 +823,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
setSelection(new Set());
};
const deletableSelection = () =>
- selectedTargets().filter((t) => t.kind === "folder" || isFileItem(t.item));
+ selectedTargets().filter((t) => t.kind === "folder" || isDeletable(t.item));
const deleteText = pendingDelete ? deleteCopy(pendingDelete) : null;
return (
@@ -802,7 +856,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
onSearchChange={setQuery}
searchPlaceholder={t(folderId ? "library.searchFolder" : "library.searchLibrary")}
onNew={handleNew}
- onSettings={() => openSettings("data")}
+ onSettings={() => openSettings("library")}
/>
}
tabs={
@@ -815,7 +869,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
}
}
/>
- {renderBody()}
+ <div className="pl-3">{renderBody()}</div>
{dragging && (
<div className="pointer-events-none fixed inset-0 z-40 flex items-center justify-center bg-background/70 backdrop-blur-sm">
@@ -859,7 +913,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
<button
type="button"
disabled={deletableSelection().length === 0}
- onClick={() => setPendingDelete(deletableSelection())}
+ onClick={() => requestDelete(deletableSelection())}
className={cn(
BAR_PILL,
"border border-red-500/70 text-red-600 transition-colors hover:bg-red-500/15 dark:text-red-400",
diff --git a/studio/frontend/src/features/library/paths.ts b/studio/frontend/src/features/library/paths.ts
new file mode 100644
index 00000000000..b32b61133c5
--- /dev/null
+++ b/studio/frontend/src/features/library/paths.ts
@@ -0,0 +1,17 @@
+// 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 folder above `path`, where the picker starts; undefined at a root. Drive and share roots
+ * keep their separator: `D:` alone is drive D's current folder, and `\\server` no folder at all. */
+export function parentFolder(path: string): string | undefined {
+ const trimmed = /^([A-Za-z]:)?[\\/]$/.test(path) ? path : path.replace(/[\\/]+$/, "");
+ const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
+ if (cut < 0 || cut === trimmed.length - 1) return undefined;
+ const separator = trimmed[cut]!;
+ const parent = trimmed.slice(0, cut);
+ if (parent === "") return separator === "/" ? "/" : undefined;
+ if (/^[A-Za-z]:$/.test(parent)) return parent + separator;
+ if (/^[\\/]{2}[^\\/]+$/.test(parent)) return undefined;
+ if (/^[\\/]{2}[^\\/]+[\\/][^\\/]+$/.test(parent)) return parent + separator;
+ return parent;
+}
diff --git a/studio/frontend/src/features/library/search.ts b/studio/frontend/src/features/library/search.ts
index 17922c37619..2e3ea96a0a2 100644
--- a/studio/frontend/src/features/library/search.ts
+++ b/studio/frontend/src/features/library/search.ts
@@ -1,6 +1,9 @@
// 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 { LIBRARY_URL_SORTS, type LibraryUrlSort } from "./settings-store";
+
+// Kept apart from the page so the route can validate its URL without loading the page chunk.
export const LIBRARY_TABS = [
"suggested",
"favorites",
@@ -17,6 +20,8 @@ export interface LibrarySearch {
show?: LibraryTab;
folder?: string;
item?: string;
+ sort?: LibraryUrlSort;
+ filter?: "files";
}
export function validateLibrarySearch(search: Record<string, unknown>): LibrarySearch {
@@ -25,5 +30,9 @@ export function validateLibrarySearch(search: Record<string, unknown>): LibraryS
...(show ? { show } : {}),
...(typeof search.folder === "string" ? { folder: search.folder } : {}),
...(typeof search.item === "string" ? { item: search.item } : {}),
+ ...(LIBRARY_URL_SORTS.includes(search.sort as LibraryUrlSort)
+ ? { sort: search.sort as LibraryUrlSort }
+ : {}),
+ ...(search.filter === "files" ? { filter: "files" as const } : {}),
};
}
diff --git a/studio/frontend/src/features/library/settings-store.ts b/studio/frontend/src/features/library/settings-store.ts
new file mode 100644
index 00000000000..5f6fd6d9fa9
--- /dev/null
+++ b/studio/frontend/src/features/library/settings-store.ts
@@ -0,0 +1,174 @@
+// 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 { create } from "zustand";
+import { persist } from "zustand/middleware";
+import type { LibraryTab } from "./search";
+
+export const LIBRARY_SETTINGS_STORAGE_KEY = "unsloth_library_settings";
+export const LIBRARY_VIEW_STORAGE_KEY = "unsloth_library_view";
+
+type LibrarySort = "recent" | "oldest" | "name" | "size";
+export type LibraryTabVisibility = "always" | "auto" | "hidden";
+
+export interface LibrarySettings {
+ cardSize: "small" | "medium" | "large";
+ imageLayout: "masonry" | "square";
+ showCardDates: boolean;
+ sort: LibrarySort;
+ startTab: "last" | "suggested" | "favorites" | "folders" | "all";
+ lastTab: LibraryTab;
+ tabs: Record<LibraryTab, LibraryTabVisibility>;
+ suggestedLimit: number;
+ showChatAttachments: boolean;
+ showChatToolFiles: boolean;
+ showGeneratedMedia: boolean;
+ showFineTunes: boolean;
+ confirmDelete: boolean;
+}
+
+export const DEFAULT_LIBRARY_SETTINGS: LibrarySettings = {
+ cardSize: "medium",
+ imageLayout: "masonry",
+ showCardDates: true,
+ sort: "recent",
+ startTab: "suggested",
+ lastTab: "suggested",
+ tabs: {
+ suggested: "always",
+ favorites: "always",
+ folders: "always",
+ images: "auto",
+ videos: "auto",
+ audio: "auto",
+ models: "auto",
+ all: "always",
+ },
+ suggestedLimit: 40,
+ showChatAttachments: true,
+ showChatToolFiles: true,
+ showGeneratedMedia: true,
+ showFineTunes: true,
+ confirmDelete: true,
+};
+
+export const SUGGESTED_LIMITS = [20, 40, 80] as const;
+
+export const CARD_COLUMNS: Record<LibrarySettings["cardSize"], { minWidth: number; max: number }> = {
+ small: { minWidth: 170, max: 6 },
+ medium: { minWidth: 200, max: 5 },
+ large: { minWidth: 240, max: 4 },
+};
+
+export type LibraryView = "grid" | "list";
+
+export const useLibraryViewStore = create<{
+ view: LibraryView;
+ setView: (view: LibraryView) => void;
+}>()(
+ persist(
+ (set) => ({
+ view: "grid",
+ setView: (view) => set({ view }),
+ }),
+ { name: LIBRARY_VIEW_STORAGE_KEY },
+ ),
+);
+
+interface LibrarySettingsState extends LibrarySettings {
+ set: (patch: Partial<LibrarySettings>) => void;
+ reset: () => void;
+}
+
+/** v1 had one mediaTabs switch for Images, Videos and Audio together; before v3, Fine-tunes
+ * always showed. */
+export function migrateLibrarySettings(persisted: unknown, version: number): Record<string, unknown> {
+ const state = { ...(persisted as Record<string, unknown>) };
+ if (version < 2) {
+ const media = state.mediaTabs === "always" ? "always" : "auto";
+ state.tabs = { ...DEFAULT_LIBRARY_SETTINGS.tabs, images: media, videos: media, audio: media };
+ delete state.mediaTabs;
+ }
+ if (version < 3) {
+ const tabs = state.tabs as Record<string, string> | undefined;
+ if (tabs?.models === "always") state.tabs = { ...tabs, models: "auto" };
+ }
+ return state;
+}
+
+export const useLibrarySettingsStore = create<LibrarySettingsState>()(
+ persist(
+ (set) => ({
+ ...DEFAULT_LIBRARY_SETTINGS,
+ set: (patch) => set(patch),
+ reset: () => set(DEFAULT_LIBRARY_SETTINGS),
+ }),
+ {
+ name: LIBRARY_SETTINGS_STORAGE_KEY,
+ version: 3,
+ migrate: (persisted, version) =>
+ migrateLibrarySettings(persisted, version) as unknown as LibrarySettingsState,
+ },
+ ),
+);
+
+const SOURCE_SETTING: Record<string, keyof LibrarySettings> = {
+ attachment: "showChatAttachments",
+ sandbox: "showChatToolFiles",
+ image: "showGeneratedMedia",
+ video: "showGeneratedMedia",
+ audio: "showGeneratedMedia",
+ model: "showFineTunes",
+};
+
+export function includedBySettings(itemId: string, settings: LibrarySettings): boolean {
+ const key = SOURCE_SETTING[itemId.slice(0, itemId.indexOf(":"))];
+ return !key || Boolean(settings[key]);
+}
+
+export type LibrarySortKey = "name" | "modified" | "size";
+export type LibrarySortState = { key: LibrarySortKey; desc: boolean };
+
+export type LibraryUrlSort = LibrarySort | "name-desc" | "size-asc";
+
+export const SORT_STATES: Record<LibraryUrlSort, LibrarySortState> = {
+ recent: { key: "modified", desc: true },
+ oldest: { key: "modified", desc: false },
+ name: { key: "name", desc: false },
+ "name-desc": { key: "name", desc: true },
+ size: { key: "size", desc: true },
+ "size-asc": { key: "size", desc: false },
+};
+
+export const LIBRARY_URL_SORTS = Object.keys(SORT_STATES) as LibraryUrlSort[];
+
+export function sortParam(state: LibrarySortState): LibraryUrlSort {
+ return LIBRARY_URL_SORTS.find(
+ (sort) => SORT_STATES[sort].key === state.key && SORT_STATES[sort].desc === state.desc,
+ )!;
+}
+
+export function nextSort(current: LibrarySortState, key: LibrarySortKey): LibrarySortState {
+ return current.key === key ? { key, desc: !current.desc } : { key, desc: key !== "name" };
+}
+
+type Sortable = { name: string; updatedAt: number; sizeBytes?: number | null };
+
+export function lastActivity(item: { updatedAt: number; openedAt?: number | null }): number {
+ return Math.max(item.updatedAt, item.openedAt ?? 0);
+}
+
+export function compareBySort({ key, desc }: LibrarySortState): (a: Sortable, b: Sortable) => number {
+ const ascending =
+ key === "name"
+ ? (a: Sortable, b: Sortable) => a.name.localeCompare(b.name, undefined, { numeric: true })
+ : key === "size"
+ ? (a: Sortable, b: Sortable) => (a.sizeBytes ?? -1) - (b.sizeBytes ?? -1)
+ : (a: Sortable, b: Sortable) => a.updatedAt - b.updatedAt;
+ return desc ? (a, b) => ascending(b, a) : ascending;
+}
+
+export const useLibraryVisitStore = create<{ visit: number; restart: () => void }>((set) => ({
+ visit: 0,
+ restart: () => set((state) => ({ visit: state.visit + 1 })),
+}));
diff --git a/studio/frontend/src/features/library/storage.ts b/studio/frontend/src/features/library/storage.ts
new file mode 100644
index 00000000000..785c17515d2
--- /dev/null
+++ b/studio/frontend/src/features/library/storage.ts
@@ -0,0 +1,121 @@
+// 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 { TranslationKey } from "@/i18n";
+import { useEffect, useMemo, useState } from "react";
+import { type LibraryDisk, type LibraryItem, type LibraryLocation, getLibrary } from "./api";
+import { fileKind } from "./file-kind";
+import type { LibrarySearch } from "./search";
+import { includedBySettings, useLibrarySettingsStore } from "./settings-store";
+
+type StorageCategory = "files" | "images" | "videos" | "audio" | "fineTunes";
+
+export const STORAGE_LABELS: Record<StorageCategory | LibraryLocation["key"], TranslationKey> = {
+ files: "settings.data.filesSection",
+ uploads: "settings.library.locationUploads",
+ images: "settings.library.categoryImages",
+ videos: "settings.library.categoryVideos",
+ audio: "library.tabs.audio",
+ fineTunes: "settings.library.categoryFineTunes",
+ exports: "settings.library.locationExports",
+};
+
+interface StorageUsage {
+ category: StorageCategory;
+ link: LibrarySearch;
+ bytes: number;
+ count: number;
+}
+
+interface LibraryStorage {
+ status: "loading" | "ready" | "error";
+ totalBytes: number;
+ hiddenBytes: number;
+ diskBytes: number;
+ categories: StorageUsage[];
+ disk: LibraryDisk | null;
+}
+
+const CATEGORY_LINKS: [StorageCategory, LibrarySearch][] = [
+ ["files", { show: "all", filter: "files", sort: "size" }],
+ ["images", { show: "images", sort: "size" }],
+ ["videos", { show: "videos", sort: "size" }],
+ ["audio", { show: "audio", sort: "size" }],
+ ["fineTunes", { show: "models", sort: "size" }],
+];
+
+const KIND_CATEGORIES: Partial<Record<string, StorageCategory>> = {
+ image: "images",
+ video: "videos",
+ audio: "audio",
+ model: "fineTunes",
+};
+
+function diskSource(id: string): string {
+ const [source, origin] = id.split(":", 2);
+ return source === "model" ? `${source}:${origin}` : source!;
+}
+
+const STALE_EVENT = "unsloth:library-storage-stale";
+
+export function refreshLibraryStorage(): void {
+ window.dispatchEvent(new Event(STALE_EVENT));
+}
+
+export function useLibraryStorage(): LibraryStorage {
+ const settings = useLibrarySettingsStore();
+ const [snapshot, setSnapshot] = useState<{
+ status: LibraryStorage["status"];
+ items: LibraryItem[];
+ disk: LibraryDisk | null;
+ }>({ status: "loading", items: [], disk: null });
+ const [version, setVersion] = useState(0);
+ useEffect(() => {
+ const stale = () => setVersion((current) => current + 1);
+ window.addEventListener(STALE_EVENT, stale);
+ return () => window.removeEventListener(STALE_EVENT, stale);
+ }, []);
+ useEffect(() => {
+ let cancelled = false;
+ getLibrary().then(
+ ({ items, disk }) => !cancelled && setSnapshot({ status: "ready", items, disk: disk ?? null }),
+ () => !cancelled && setSnapshot((current) => ({ ...current, status: "error" })),
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [version]);
+ return useMemo(() => {
+ const totals = new Map<StorageCategory, { bytes: number; count: number }>();
+ const onDisk = snapshot.disk?.sources ? new Set(snapshot.disk.sources) : null;
+ let diskBytes = 0;
+ let hiddenBytes = 0;
+ for (const item of snapshot.items) {
+ const bytes = item.storageBytes ?? item.sizeBytes ?? 0;
+ if (!onDisk || onDisk.has(diskSource(item.id))) {
+ diskBytes += bytes;
+ }
+ if (!includedBySettings(item.id, settings)) {
+ hiddenBytes += bytes;
+ continue;
+ }
+ const category = KIND_CATEGORIES[fileKind(item)] ?? "files";
+ const total = totals.get(category) ?? { bytes: 0, count: 0 };
+ total.bytes += bytes;
+ total.count += 1;
+ totals.set(category, total);
+ }
+ const categories = CATEGORY_LINKS.flatMap(([category, link]) => {
+ const total = totals.get(category);
+ return total ? [{ category, link, ...total }] : [];
+ }).sort((a, b) => b.bytes - a.bytes);
+ return {
+ status: snapshot.status,
+ totalBytes: categories.reduce((sum, entry) => sum + entry.bytes, hiddenBytes),
+ hiddenBytes,
+ diskBytes,
+ categories,
+ disk: snapshot.disk,
+ };
+ }, [snapshot, settings]);
+}
diff --git a/studio/frontend/src/features/library/store.ts b/studio/frontend/src/features/library/store.ts
index a707b184735..2cc2b28755c 100644
--- a/studio/frontend/src/features/library/store.ts
+++ b/studio/frontend/src/features/library/store.ts
@@ -2,9 +2,8 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { create } from "zustand";
-import { persist } from "zustand/middleware";
import { AUTH_SESSION_CLEARED_EVENT, getAuthSessionEpoch } from "@/features/auth";
-import { emitChatAttachmentDeleted } from "@/features/chat";
+import { deleteFineTunedModel, emitChatAttachmentDeleted } from "@/features/chat";
import { translate } from "@/i18n";
import { type GalleryKind, notifyGalleryChanged } from "@/lib/gallery-flags";
import {
@@ -16,6 +15,7 @@ import {
deleteLibraryItem,
errorMessage,
getLibrary,
+ markLibraryItemOpened,
updateLibraryFolder,
updateLibraryItem,
uploadLibraryFiles,
@@ -34,6 +34,7 @@ interface LibraryState {
refresh: () => Promise<void>;
patchItem: (id: string, patch: ItemPatch) => Promise<void>;
removeItem: (id: string, fingerprint: string | undefined) => Promise<void>;
+ markOpened: (id: string) => void;
upload: (batch: LibraryUploadBatch, folderId: string | null) => Promise<string[]>;
addFolder: (name: string, parentId: string | null) => Promise<LibraryFolder>;
patchFolder: (id: string, patch: FolderPatch) => Promise<void>;
@@ -181,11 +182,26 @@ export const useLibraryStore = create<LibraryState>((set, get) => {
},
// The fingerprint the confirmation was opened on: a refresh since may list a replacement file.
removeItem: (id, fingerprint) => {
+ const model = get().items.find((item) => item.id === id)?.model;
+ const star = useLibraryFavoritesStore.getState().mark(id, false);
return optimistic(
(state) => ({ items: state.items.filter((item) => item.id !== id) }),
async () => {
const epoch = getAuthSessionEpoch();
- await deleteLibraryItem(id, fingerprint);
+ try {
+ if (model) {
+ await deleteFineTunedModel({
+ modelPath: model.path,
+ source: model.origin,
+ exportType: model.exportType,
+ });
+ return;
+ }
+ await deleteLibraryItem(id, fingerprint);
+ } finally {
+ star.settle();
+ }
+ // Signed in as another account meanwhile: its chats can hold an attachment of this id.
if (getAuthSessionEpoch() !== epoch) return;
const [kind, messageId, ...rest] = id.split(":");
const gallery = GALLERIES[kind];
@@ -197,8 +213,16 @@ export const useLibraryStore = create<LibraryState>((set, get) => {
});
}
},
+ star.undo,
);
},
+ markOpened: (id) => {
+ const openedAt = Date.now();
+ set((state) => ({
+ items: state.items.map((item) => (item.id === id ? { ...item, openedAt } : item)),
+ }));
+ void markLibraryItemOpened(id).catch(() => undefined);
+ },
upload: async (batch, folderId) => {
try {
return await uploadLibraryFiles(batch, folderId);
@@ -263,17 +287,3 @@ if (typeof window !== "undefined") {
});
}
-export type LibraryView = "grid" | "list";
-
-export const useLibraryViewStore = create<{
- view: LibraryView;
- setView: (view: LibraryView) => void;
-}>()(
- persist(
- (set) => ({
- view: "grid",
- setView: (view) => set({ view }),
- }),
- { name: "unsloth_library_view" },
- ),
-);
diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsx
index 139749efd74..fe18ae88d9e 100644
--- a/studio/frontend/src/features/settings/settings-dialog.tsx
+++ b/studio/frontend/src/features/settings/settings-dialog.tsx
@@ -28,6 +28,7 @@ import {
Globe02Icon,
HelpCircleIcon,
HomeWifiIcon,
+ LibrariesIcon,
PaintBrush02Icon,
Search01Icon,
Settings02Icon,
@@ -83,6 +84,8 @@ const TAB_LOADERS = {
import("./tabs/connections-tab").then((m) => ({
default: m.ConnectionsTab,
})),
+ library: () =>
+ import("./tabs/library-tab").then((m) => ({ default: m.LibraryTab })),
data: () => import("./tabs/data-tab").then((m) => ({ default: m.DataTab })),
"keyboard-shortcuts": () =>
import("./tabs/keyboard-shortcuts-tab").then((m) => ({
@@ -224,7 +227,6 @@ const TABS: TabDef[] = [
id: "accounts",
labelKey: "settings.tabs.accounts",
icon: UserCircleIcon,
- badgeKey: "common.new",
},
{
id: "agents",
@@ -236,6 +238,12 @@ const TABS: TabDef[] = [
labelKey: "settings.tabs.voice",
iconComponent: MicIcon,
},
+ {
+ id: "library",
+ labelKey: "shell.navigation.library",
+ icon: LibrariesIcon,
+ badgeKey: "common.new",
+ },
{
id: "data",
labelKey: "settings.tabs.data",
@@ -427,6 +435,7 @@ export function SettingsDialog() {
voice: null,
connections: null,
"keyboard-shortcuts": null,
+ library: null,
data: null,
"api-keys": null,
"remote-lan": null,
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 89e2db11101..f04ae3ae68b 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -128,6 +128,24 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.chat.projectsSection",
"settings.chat.groups.menu.title",
],
+ library: [
+ "settings.library.storageSection",
+ "settings.library.locationsSection",
+ "settings.library.cardSize",
+ "settings.library.imageLayout",
+ "settings.library.showCardDates",
+ "settings.library.startTab",
+ "settings.library.sort",
+ "settings.library.suggestedLimit",
+ "settings.library.tabsSection",
+ "settings.library.contentSection",
+ "settings.library.showChatAttachments",
+ "settings.library.showChatToolFiles",
+ "settings.library.showGeneratedMedia",
+ "settings.library.categoryFineTunes",
+ "settings.library.confirmDelete",
+ "settings.library.reset",
+ ],
// Chat data management moved to the Data tab; keep these rows findable there.
data: [
"settings.data.fineTuneExport",
@@ -141,6 +159,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.data.archivedVideos",
"settings.data.archivedAudio",
"settings.data.uploadedFiles",
+ "settings.library.dataStorage",
"settings.chat.exportHistory",
"settings.chat.exportConversations",
"settings.chat.importChats",
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 6b56c87aa4e..99e2a50e579 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -16,6 +16,7 @@ export const SETTINGS_TABS = [
"chat",
"voice",
"connections",
+ "library",
"data",
"api-keys",
"remote-lan",
@@ -32,6 +33,7 @@ export type SettingsScrollTarget =
| "appearance-sidebar-nav"
| "chat-composer"
| "chat-canvas-network"
+ | "library-storage"
| "resources-caches";
/** Which archive the Data tab should open straight into. */
@@ -119,6 +121,7 @@ const SCROLL_TARGET_TAB: Record<SettingsScrollTarget, SettingsTab> = {
"about-updates": "about",
"appearance-sidebar-nav": "appearance",
"chat-canvas-network": "chat",
+ "library-storage": "library",
"resources-caches": "resources",
};
diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsx
index acec5b15d0c..e8a14929ee1 100644
--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx
@@ -52,12 +52,19 @@ import {
useChatRuntimeStore,
useChatSidebarItems,
} from "@/features/chat";
+import {
+ LibraryStorageBar,
+ STORAGE_LABELS,
+ formatSize,
+ refreshLibraryStorage,
+ useLibraryStorage,
+} from "@/features/library";
import {
LinkedFoldersManager,
listKnowledgeBases,
useRagAvailabilityStore,
} from "@/features/rag";
-import { useT } from "@/i18n";
+import { useLocale, useT } from "@/i18n";
import { isTauri } from "@/lib/api-base";
import {
@@ -102,6 +109,59 @@ import {
// display order, and the guard against a persisted action this build dropped.
const FINE_TUNE_ACTIONS: FineTuneAction[] = ["export", "train", "recipes"];
+function LibraryDataSection() {
+ const t = useT();
+ const locale = useLocale();
+ const openDialog = useSettingsDialogStore((s) => s.openDialog);
+ const storage = useLibraryStorage();
+ const count = storage.categories.reduce((sum, entry) => sum + entry.count, 0);
+ const size = (bytes: number) => formatSize(bytes, locale, t) ?? "";
+ const largest = storage.categories
+ .slice(0, 3)
+ .map((entry) => `${t(STORAGE_LABELS[entry.category])} ${size(entry.bytes)}`)
+ .join(" · ");
+
+ let summary: string;
+ if (storage.status === "loading") summary = "";
+ else if (storage.status === "error") summary = t("settings.library.storageError");
+ else if (storage.totalBytes === 0 && count === 0) summary = t("settings.library.storageEmpty");
+ else {
+ summary = [
+ t("settings.library.storageUsed", { size: size(storage.totalBytes) }),
+ count === 1
+ ? t("settings.library.itemCountOne")
+ : count > 0 && t("settings.library.itemCount", { count: count.toLocaleString() }),
+ storage.hiddenBytes > 0 && t("settings.library.storageHidden", { size: size(storage.hiddenBytes) }),
+ ]
+ .filter(Boolean)
+ .join(" · ");
+ }
+
+ return (
+ <SettingsSection title={t("shell.navigation.library")}>
+ <SettingsRow
+ label={t("settings.library.dataStorage")}
+ description={summary || "\u00a0"}
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => openDialog("library", { scrollTarget: "library-storage" })}
+ >
+ {t("settings.library.manageStorage")}
+ <HugeiconsIcon icon={ChevronRightStandardIcon} className="ml-1 size-3.5" />
+ </Button>
+ </SettingsRow>
+ {storage.status === "ready" && (count > 0 || storage.totalBytes > 0) && (
+ <div className="flex flex-col gap-2 pb-3">
+ <LibraryStorageBar libraryBytes={storage.diskBytes} disk={storage.disk} />
+ {largest && <p className="text-xs text-muted-foreground">{largest}</p>}
+ </div>
+ )}
+ </SettingsSection>
+ );
+}
+
// Which subpage an "open the archive" request lands on.
const SUBPAGE_FOR_SHELF = {
chats: "archived",
@@ -477,6 +537,7 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {
const result = await clearAllChats({
deleteFiles: deleteFilesOnClear,
});
+ refreshLibraryStorage();
const clearedCount = result.deletedThreadIds.length;
// A sandbox the backend could not remove, asked for or not.
// After a clear there is no row left to reach it from.
@@ -1038,6 +1099,8 @@ export function DataTab({ searchEntry }: { searchEntry?: string }) {
</div>
</SettingsSection>
+ <LibraryDataSection />
+
<SettingsSection title={t("settings.data.filesSection")}>
<SettingsRow
label={t("settings.data.uploadedFiles")}
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index 35c227f4196..c4fdae9d562 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -67,6 +67,10 @@ import {
import { loadCloseToTray, updateCloseToTray } from "../api/close-to-tray";
import { loadLaunchAtLogin, updateLaunchAtLogin } from "../api/launch-at-login";
import { useIsAccountOwner } from "@/features/auth";
+import {
+ LIBRARY_SETTINGS_STORAGE_KEY,
+ LIBRARY_VIEW_STORAGE_KEY,
+} from "@/features/library";
import { ChangePasswordDialog } from "../components/change-password-dialog";
import { DesktopRepairControl } from "../components/desktop-repair-control";
import {
@@ -101,6 +105,8 @@ const PREFS_KEYS: string[] = [
"sidebar_width",
"chat_settings_width",
"unsloth_sidebar_navigate_open",
+ LIBRARY_SETTINGS_STORAGE_KEY,
+ LIBRARY_VIEW_STORAGE_KEY,
// Grouping, sort and the manual row order.
SIDEBAR_ORGANIZATION_STORAGE_KEY,
"unsloth_settings_active_tab",
diff --git a/studio/frontend/src/features/settings/tabs/library-tab.tsx b/studio/frontend/src/features/settings/tabs/library-tab.tsx
new file mode 100644
index 00000000000..e3e9fcd0238
--- /dev/null
+++ b/studio/frontend/src/features/settings/tabs/library-tab.tsx
@@ -0,0 +1,511 @@
+// 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 {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { Spinner } from "@/components/ui/spinner";
+import {
+ LIBRARY_TABS,
+ type LibraryLocation,
+ type LibrarySearch,
+ LibraryStorageBar,
+ type LibrarySettings,
+ type LibraryTab as LibraryTabId,
+ type LibraryTabVisibility,
+ STORAGE_LABELS,
+ SUGGESTED_LIMITS,
+ errorMessage,
+ formatSize,
+ getLibraryLocations,
+ moveLibraryLocation,
+ parentFolder,
+ refreshLibraryStorage,
+ revealLibraryLocation,
+ useLibrarySettingsStore,
+ useLibraryStorage,
+ useLibraryViewStore,
+ useLibraryVisitStore,
+ useRevealLabel,
+} from "@/features/library";
+import { useIsAccountOwner } from "@/features/auth";
+import { FolderBrowser } from "@/features/model-picker";
+import { type TranslationKey, useLocale, useT } from "@/i18n";
+import { ChevronRightStandardIcon } from "@/lib/chevron-icons";
+import { notifyGalleryChanged } from "@/lib/gallery-flags";
+import { toast } from "@/lib/toast";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useNavigate } from "@tanstack/react-router";
+import { useEffect, useRef, useState } from "react";
+import { SettingsRow } from "../components/settings-row";
+import { SettingsSection } from "../components/settings-section";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+
+type ToggleKey = {
+ [K in keyof LibrarySettings]: LibrarySettings[K] extends boolean ? K : never;
+}[keyof LibrarySettings];
+
+const TAB_LABELS: Record<LibraryTabId, TranslationKey> = {
+ suggested: "settings.library.suggested",
+ favorites: "library.tabs.favorites",
+ folders: "library.tabs.folders",
+ images: STORAGE_LABELS.images,
+ videos: STORAGE_LABELS.videos,
+ audio: STORAGE_LABELS.audio,
+ models: STORAGE_LABELS.fineTunes,
+ all: "settings.library.all",
+};
+
+const CHOICES: {
+ [K in "cardSize" | "imageLayout" | "startTab" | "sort"]: [LibrarySettings[K], TranslationKey][];
+} = {
+ cardSize: [
+ ["small", "settings.library.small"],
+ ["medium", "settings.library.medium"],
+ ["large", "settings.library.large"],
+ ],
+ imageLayout: [
+ ["masonry", "settings.library.masonry"],
+ ["square", "settings.library.square"],
+ ],
+ startTab: [
+ ["last", "settings.library.lastVisited"],
+ ...(["suggested", "favorites", "folders", "all"] as const).map((tab): [typeof tab, TranslationKey] => [tab, TAB_LABELS[tab]]),
+ ],
+ sort: [
+ ["recent", "settings.library.recent"],
+ ["oldest", "settings.library.oldest"],
+ ["name", "settings.library.name"],
+ ["size", "library.preview.size"],
+ ],
+};
+
+const CONTENT_TABS = new Set<LibraryTabId>(["images", "videos", "audio", "models"]);
+
+const TAB_VISIBILITY: [LibraryTabVisibility, TranslationKey][] = [
+ ["auto", "settings.library.tabAuto"],
+ ["always", "settings.library.tabAlways"],
+ ["hidden", "settings.library.tabHidden"],
+];
+
+function ChoiceSelect({
+ label,
+ value,
+ options,
+ onChange,
+}: {
+ label: string;
+ value: string;
+ options: [string, string][];
+ onChange: (value: string) => void;
+}) {
+ return (
+ <Select value={value} onValueChange={onChange}>
+ <SelectTrigger size="sm" className="w-48" aria-label={label}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ {options.map(([option, text]) => (
+ <SelectItem key={option} value={option}>
+ {text}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+function StorageSection() {
+ const t = useT();
+ const locale = useLocale();
+ const navigate = useNavigate();
+ const closeDialog = useSettingsDialogStore((s) => s.closeDialog);
+ const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
+ const consumeScrollTarget = useSettingsDialogStore((s) => s.consumeScrollTarget);
+ const sectionRef = useRef<HTMLElement | null>(null);
+ const setView = useLibraryViewStore((s) => s.setView);
+ const restartLibrary = useLibraryVisitStore((s) => s.restart);
+ const storage = useLibraryStorage();
+ const size = (bytes: number) => formatSize(bytes, locale, t) ?? "";
+
+ useEffect(() => {
+ if (scrollTarget !== "library-storage") return;
+ const frame = window.requestAnimationFrame(() => {
+ sectionRef.current?.scrollIntoView({ block: "start", behavior: "smooth" });
+ consumeScrollTarget("library-storage");
+ });
+ return () => window.cancelAnimationFrame(frame);
+ }, [consumeScrollTarget, scrollTarget]);
+
+ const open = (link: LibrarySearch) => {
+ closeDialog();
+ setView("list");
+ // Already on that tab, the view would keep its search and filters and show less than counted.
+ restartLibrary();
+ void navigate({ to: "/library", search: link });
+ };
+
+ return (
+ <SettingsSection
+ ref={sectionRef}
+ title={t("settings.library.storageSection")}
+ description={t("settings.library.storageDescription")}
+ >
+ {storage.status === "loading" ? (
+ <Spinner className="my-4 size-5 text-muted-foreground" />
+ ) : storage.status === "error" ? (
+ <p className="py-3 text-sm text-muted-foreground">{t("settings.library.storageError")}</p>
+ ) : (
+ <>
+ <div className="flex flex-col gap-2 py-3">
+ <p className="text-sm font-medium text-foreground">
+ {t("settings.library.storageUsed", { size: size(storage.totalBytes) })}
+ </p>
+ <LibraryStorageBar libraryBytes={storage.diskBytes} disk={storage.disk} />
+ </div>
+ {storage.categories.length === 0 && storage.hiddenBytes === 0 && (
+ <p className="pb-3 text-sm text-muted-foreground">{t("settings.library.storageEmpty")}</p>
+ )}
+ {storage.categories.length > 0 && (
+ <div className="mb-3 flex flex-col overflow-hidden rounded-xl border border-border/60">
+ {storage.categories.map((entry) => (
+ <button
+ key={entry.category}
+ type="button"
+ onClick={() => open(entry.link)}
+ className="flex items-center gap-3 border-border/60 px-4 py-3 text-left transition-colors not-first:border-t hover:bg-muted/60"
+ >
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-sm font-medium text-foreground">
+ {t(STORAGE_LABELS[entry.category])}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {size(entry.bytes)}
+ {" · "}
+ {entry.count === 1
+ ? t("settings.library.itemCountOne")
+ : t("settings.library.itemCount", { count: entry.count.toLocaleString() })}
+ </span>
+ </span>
+ <HugeiconsIcon icon={ChevronRightStandardIcon} className="size-4 shrink-0 text-muted-foreground" />
+ </button>
+ ))}
+ </div>
+ )}
+ {storage.hiddenBytes > 0 && (
+ <p className="pb-3 text-xs text-muted-foreground">
+ {t("settings.library.storageHidden", { size: size(storage.hiddenBytes) })}
+ </p>
+ )}
+ </>
+ )}
+ </SettingsSection>
+ );
+}
+
+function LocationsSection() {
+ const t = useT();
+ const locale = useLocale();
+ const revealLabel = useRevealLabel();
+ const owner = useIsAccountOwner();
+ const [locations, setLocations] = useState<LibraryLocation[] | null>(null);
+ const [moving, setMoving] = useState(false);
+ const [picking, setPicking] = useState<LibraryLocation | null>(null);
+ const [resettingAway, setResettingAway] = useState<LibraryLocation | null>(null);
+ useEffect(() => {
+ let cancelled = false;
+ void getLibraryLocations()
+ .catch((): LibraryLocation[] => [])
+ .then((next) => !cancelled && setLocations(next));
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+ const nameOf = (location: LibraryLocation) => t(STORAGE_LABELS[location.key]);
+ const manyDisks = new Set(locations?.map((location) => location.device).filter(Boolean)).size > 1;
+
+ async function move(location: LibraryLocation, path: string | null) {
+ const name = nameOf(location);
+ setMoving(true);
+ const id = toast.loading(t("settings.library.locationMoving", { name }));
+ try {
+ const result = await moveLibraryLocation(location.key, path);
+ setLocations(result.locations);
+ refreshLibraryStorage();
+ if (location.key === "images" || location.key === "videos" || location.key === "audio") {
+ notifyGalleryChanged(location.key);
+ }
+ void import("@/features/library/store").then(({ useLibraryStore }) => {
+ const library = useLibraryStore.getState();
+ if (library.status !== "idle") void library.refresh();
+ });
+ toast.success(t("settings.library.locationMoved", { name }), {
+ id,
+ description: result.leftBehind
+ ? t("settings.library.locationLeftBehind", { path: result.leftBehind })
+ : undefined,
+ });
+ } catch (error) {
+ toast.error(t("settings.library.locationMoveFailed", { name }), { id, description: errorMessage(error) });
+ } finally {
+ setMoving(false);
+ }
+ }
+
+ return (
+ <SettingsSection
+ title={t("settings.library.locationsSection")}
+ description={t("settings.library.locationsDescription")}
+ >
+ {locations === null ? (
+ <Spinner className="my-4 size-5 text-muted-foreground" />
+ ) : (
+ locations.map((location) => (
+ <SettingsRow
+ key={location.key}
+ label={nameOf(location)}
+ description={
+ <>
+ <span className="block truncate font-mono text-ui-11" title={location.path}>
+ {location.path}
+ </span>
+ {location.available === false ? (
+ <span className="block text-xs text-destructive">
+ {t("settings.library.locationUnavailable")}
+ </span>
+ ) : (
+ manyDisks &&
+ location.disk && (
+ <span className="block text-xs">
+ {t("settings.library.locationFree", {
+ free: formatSize(location.disk.freeBytes, locale, t) ?? "",
+ })}
+ </span>
+ )
+ )}
+ </>
+ }
+ >
+ <div className="flex shrink-0 items-center gap-2">
+ {owner && location.movable && location.custom && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={moving}
+ onClick={() =>
+ location.available === false
+ ? setResettingAway(location)
+ : void move(location, null)
+ }
+ >
+ {t("settings.library.locationReset")}
+ </Button>
+ )}
+ {owner && location.movable && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={moving}
+ onClick={() => setPicking(location)}
+ >
+ {t("settings.resources.storage.changeAction")}
+ </Button>
+ )}
+ {revealLabel && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ void revealLibraryLocation(location.key).catch((error: unknown) =>
+ toast.error(t("settings.library.revealFailed"), { description: errorMessage(error) }),
+ )
+ }
+ >
+ {revealLabel}
+ </Button>
+ )}
+ </div>
+ </SettingsRow>
+ ))
+ )}
+ <FolderBrowser
+ open={picking !== null}
+ onOpenChange={(next) => !next && setPicking(null)}
+ onSelect={(path) => {
+ if (picking) void move(picking, path);
+ }}
+ initialPath={picking ? parentFolder(picking.path) : undefined}
+ title={picking ? t("settings.library.locationMoveTitle", { name: nameOf(picking) }) : ""}
+ description={t("settings.library.locationMoveDescription")}
+ confirmLabel={t("settings.library.locationMoveAction")}
+ showModelHints={false}
+ />
+ <AlertDialog
+ open={resettingAway !== null}
+ onOpenChange={(open) => !open && setResettingAway(null)}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle className="break-words">
+ {t("settings.library.locationResetUnavailableTitle", {
+ name: resettingAway ? nameOf(resettingAway) : "",
+ })}
+ </AlertDialogTitle>
+ <AlertDialogDescription className="break-words">
+ {t("settings.library.locationResetUnavailableDescription", {
+ path: resettingAway?.path ?? "",
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ if (resettingAway) void move(resettingAway, null);
+ setResettingAway(null);
+ }}
+ >
+ {t("settings.library.locationReset")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </SettingsSection>
+ );
+}
+
+export function LibraryTab() {
+ const t = useT();
+ const settings = useLibrarySettingsStore();
+
+ const choice = <K extends keyof typeof CHOICES>(key: K, labelKey: TranslationKey, descriptionKey: TranslationKey) => (
+ <SettingsRow label={t(labelKey)} description={t(descriptionKey)}>
+ <ChoiceSelect
+ label={t(labelKey)}
+ value={settings[key]}
+ options={CHOICES[key].map(([option, text]) => [option, t(text)])}
+ onChange={(value) => settings.set({ [key]: value } as Partial<LibrarySettings>)}
+ />
+ </SettingsRow>
+ );
+
+ const toggle = (key: ToggleKey, labelKey: TranslationKey, descriptionKey: TranslationKey) => (
+ <SettingsRow label={t(labelKey)} description={t(descriptionKey)}>
+ <Switch
+ aria-label={t(labelKey)}
+ checked={settings[key]}
+ onCheckedChange={(checked) => settings.set({ [key]: checked })}
+ />
+ </SettingsRow>
+ );
+
+ return (
+ <div className="flex flex-col gap-6">
+ <header className="flex flex-col gap-1">
+ <h1 className="text-xl font-semibold font-heading">{t("shell.navigation.library")}</h1>
+ </header>
+
+ <StorageSection />
+
+ <SettingsSection title={t("settings.library.layoutSection")}>
+ {choice("cardSize", "settings.library.cardSize", "settings.library.cardSizeDescription")}
+ {choice("imageLayout", "settings.library.imageLayout", "settings.library.imageLayoutDescription")}
+ {toggle("showCardDates", "settings.library.showCardDates", "settings.library.showCardDatesDescription")}
+ </SettingsSection>
+
+ <SettingsSection title={t("settings.library.browsingSection")}>
+ {choice("startTab", "settings.library.startTab", "settings.library.startTabDescription")}
+ {choice("sort", "settings.library.sort", "settings.library.sortDescription")}
+ <SettingsRow
+ label={t("settings.library.suggestedLimit")}
+ description={t("settings.library.suggestedLimitDescription")}
+ >
+ <ChoiceSelect
+ label={t("settings.library.suggestedLimit")}
+ value={String(settings.suggestedLimit)}
+ options={SUGGESTED_LIMITS.map((limit) => [String(limit), String(limit)])}
+ onChange={(value) => settings.set({ suggestedLimit: Number(value) })}
+ />
+ </SettingsRow>
+ </SettingsSection>
+
+ <SettingsSection
+ title={t("settings.library.tabsSection")}
+ description={t("settings.library.tabsDescription")}
+ >
+ {LIBRARY_TABS.map((tab) => {
+ const label = t(TAB_LABELS[tab]);
+ const visibility = settings.tabs[tab] ?? "always";
+ const setVisibility = (next: LibraryTabVisibility) =>
+ settings.set({ tabs: { ...settings.tabs, [tab]: next } });
+ return (
+ <SettingsRow key={tab} label={label}>
+ {CONTENT_TABS.has(tab) ? (
+ <ChoiceSelect
+ label={label}
+ value={visibility}
+ options={TAB_VISIBILITY.map(([option, text]) => [option, t(text)])}
+ onChange={(value) => setVisibility(value as LibraryTabVisibility)}
+ />
+ ) : (
+ <Switch
+ aria-label={label}
+ checked={visibility !== "hidden"}
+ onCheckedChange={(checked) => setVisibility(checked ? "always" : "hidden")}
+ />
+ )}
+ </SettingsRow>
+ );
+ })}
+ </SettingsSection>
+
+ <SettingsSection
+ title={t("settings.library.contentSection")}
+ description={t("settings.library.contentDescription")}
+ >
+ {toggle("showChatAttachments", "settings.library.showChatAttachments", "settings.library.showChatAttachmentsDescription")}
+ {toggle("showChatToolFiles", "settings.library.showChatToolFiles", "settings.library.showChatToolFilesDescription")}
+ {toggle("showGeneratedMedia", "settings.library.showGeneratedMedia", "settings.library.showGeneratedMediaDescription")}
+ {toggle("showFineTunes", "settings.library.categoryFineTunes", "settings.library.showFineTunesDescription")}
+ </SettingsSection>
+
+ <SettingsSection title={t("settings.library.deletingSection")}>
+ {toggle("confirmDelete", "settings.library.confirmDelete", "settings.library.confirmDeleteDescription")}
+ <SettingsRow
+ label={t("settings.library.reset")}
+ description={t("settings.library.resetDescription")}
+ destructive={true}
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ settings.reset();
+ toast.success(t("settings.library.resetDone"));
+ }}
+ >
+ {t("settings.library.resetButton")}
+ </Button>
+ </SettingsRow>
+ </SettingsSection>
+
+ <LocationsSection />
+ </div>
+ );
+}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 9ca2670fbbe..7736979853c 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -305,6 +305,85 @@ export const ar = {
panelFailed: "تعذر تحميل هذا القسم.",
panelReload: "إعادة التحميل",
},
+ library: {
+ layoutSection: "التخطيط",
+ cardSize: "حجم البطاقة",
+ cardSizeDescription: "عدد البطاقات في الصف الواحد.",
+ small: "صغير",
+ medium: "متوسط",
+ large: "كبير",
+ imageLayout: "بطاقات الصور",
+ imageLayoutDescription: "الاحتفاظ بشكل كل صورة أو قصها إلى مربعات متساوية.",
+ masonry: "الشكل الأصلي",
+ square: "مربع",
+ showCardDates: "إظهار التواريخ على البطاقات",
+ showCardDatesDescription: "إظهار آخر وقت تغيّر فيه كل ملف.",
+ browsingSection: "التصفح",
+ startTab: "الفتح على",
+ startTabDescription: "علامة التبويب التي تفتح عليها المكتبة.",
+ suggested: "المقترحة",
+ all: "الكل",
+ sort: "الترتيب حسب",
+ sortDescription: "ترتيب الملفات والمجلدات. تعرض المقترحة دائمًا الأحدث.",
+ recent: "الأحدث",
+ oldest: "الأقدم",
+ name: "الاسم",
+ suggestedLimit: "عناصر المقترحة",
+ suggestedLimitDescription: "عدد الملفات الحديثة التي تعرضها المقترحة.",
+ tabAuto: "عند وجود ملفات",
+ tabAlways: "دائمًا",
+ contentSection: "المحتوى",
+ contentDescription: "اختر ما تعرضه المكتبة. لا تُحذف الملفات المخفية.",
+ showChatAttachments: "مرفقات المحادثات",
+ showChatAttachmentsDescription: "الملفات التي أرفقتها بالمحادثات.",
+ showChatToolFiles: "ملفات أدوات المحادثة",
+ showChatToolFilesDescription: "الملفات التي أنشأتها الشيفرة والأدوات أثناء المحادثات.",
+ showGeneratedMedia: "الوسائط المولدة",
+ showGeneratedMediaDescription: "الصور والفيديو والصوت من صفحات الصور والفيديو والصوت.",
+ showFineTunesDescription: "النماذج التي درّبتها أو صدّرتها في Unsloth.",
+ deletingSection: "الحذف",
+ confirmDelete: "التأكيد قبل الحذف",
+ confirmDeleteDescription: "السؤال قبل حذف الملفات والمجلدات من المكتبة.",
+ reset: "إعادة ضبط إعدادات المكتبة",
+ resetDescription: "إرجاع كل خيار أعلاه إلى قيمته الافتراضية.",
+ resetButton: "إعادة ضبط",
+ resetDone: "تمت إعادة ضبط إعدادات المكتبة",
+ storageSection: "التخزين",
+ storageDescription: "افتح فئة لرؤية ملفاتها من الأكبر حجمًا، واحذف ما لم تعد تحتاجه.",
+ storageUsed: "تستخدم المكتبة {size}",
+ storageDisk: "{free} متاحة من {total} على هذا القرص",
+ storageEmpty: "لا يوجد شيء مخزّن في المكتبة بعد.",
+ storageHidden: "{size} مخفية في إعدادات المحتوى",
+ storageError: "تعذّرت قراءة تخزين المكتبة.",
+ locationsSection: "الملفات على القرص",
+ locationsDescription: "المكان الذي يحفظ فيه Unsloth كل نوع من الملفات. مجلدات المكتبة تسميات داخل Unsloth وليست مجلدات على القرص. تبقى النماذج المضبوطة والتصديرات في مكانها لأن التدريب والمحادثات تشير إليها بمسارها.",
+ locationUploads: "ملفات المكتبة المرفوعة",
+ locationExports: "التصديرات",
+ revealFailed: "تعذر فتح مدير الملفات",
+ locationReset: "إعادة التعيين",
+ locationMoveTitle: "نقل {name} إلى مجلد جديد",
+ locationMoveDescription: "اختر أي مجلد. إذا كان يحتوي على ملفات بالفعل، ينشئ Unsloth مجلدًا خاصًا به داخله. وسينتقل أيضًا كل ما هو موجود هنا.",
+ locationMoveAction: "النقل إلى هنا",
+ locationMoving: "جارٍ نقل {name}…",
+ locationMoved: "تم نقل {name}",
+ locationMoveFailed: "تعذر نقل {name}",
+ locationFree: "{free} متاحة على هذا القرص",
+ locationUnavailable: "غير متاح. أعد توصيل القرص أو أعد تعيين المجلد.",
+ locationResetUnavailableTitle: "إعادة تعيين {name}؟",
+ locationResetUnavailableDescription: "القرص غير متصل. ستبقى الملفات في {path} على ذلك القرص ولن تظهر في المكتبة حتى تنقلها مرة أخرى.",
+ locationLeftBehind: "تبقى الملفات في {path} على ذلك القرص.",
+ dataStorage: "مساحة تخزين المكتبة",
+ manageStorage: "إدارة التخزين",
+ categoryImages: "الصور",
+ categoryVideos: "الفيديو",
+ categoryFineTunes: "النماذج المضبوطة",
+ itemCountOne: "عنصر واحد",
+ itemCount: "{count} عناصر",
+ tabsSection: "علامات التبويب",
+ tabsDescription: "اختر علامات التبويب التي تعرضها المكتبة. تظل علامة التبويب المفتوحة من رابط ظاهرة.",
+ tabHidden: "مخفية",
+ lastVisited: "آخر ما تمت زيارته",
+ },
tabs: {
accounts: "الحسابات",
general: "عام",
@@ -2962,6 +3041,8 @@ export const ar = {
lastActivity: "آخر نشاط",
favorite: "مفضلة",
modified: "عُدّل {time}",
+ opened: "فُتح {time}",
+ modifiedColumn: "تاريخ التعديل",
justNow: "للتوّ",
},
size: {
@@ -2969,6 +3050,7 @@ export const ar = {
kilobytes: "{value} كيلوبايت",
megabytes: "{value} م.ب",
gigabytes: "{value} غ.ب",
+ terabytes: "{value} ت.ب",
},
modelKind: {
lora: "LoRA",
@@ -2993,6 +3075,7 @@ export const ar = {
deleteVideo: "ستتم إزالته أيضًا من معرض الفيديو.",
deleteAudio: "ستتم إزالته أيضًا من معرض الصوت.",
deleteSandbox: "ستتم إزالته أيضًا من المحادثة التي أنشأته.",
+ deleteModel: "سيؤدي هذا إلى حذف النموذج من القرص نهائيًا.",
unsavedTitle: "لم تُحفظ تغييراتك",
unsavedDescription: "{reason} أعد المحاولة، أو تجاهل تغييراتك لإغلاق الملف.",
keepEditing: "متابعة التحرير",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index bdf41b465e2..f88f15d86b2 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -309,6 +309,85 @@ export const de = {
panelFailed: "Dieser Bereich konnte nicht geladen werden.",
panelReload: "Neu laden",
},
+ library: {
+ layoutSection: "Layout",
+ cardSize: "Kartengröße",
+ cardSizeDescription: "Wie viele Karten in eine Reihe passen.",
+ small: "Klein",
+ medium: "Mittel",
+ large: "Groß",
+ imageLayout: "Bildkarten",
+ imageLayoutDescription: "Die Form jedes Bildes beibehalten oder gleichmäßig quadratisch zuschneiden.",
+ masonry: "Originalform",
+ square: "Quadratisch",
+ showCardDates: "Datum auf Karten anzeigen",
+ showCardDatesDescription: "Zeigt, wann jede Datei zuletzt geändert wurde.",
+ browsingSection: "Durchsuchen",
+ startTab: "Öffnen mit",
+ startTabDescription: "Der Tab, mit dem die Bibliothek öffnet.",
+ suggested: "Vorgeschlagen",
+ all: "Alle",
+ sort: "Sortieren nach",
+ sortDescription: "Reihenfolge von Dateien und Ordnern. Vorgeschlagen zeigt immer die neuesten.",
+ recent: "Neueste",
+ oldest: "Älteste",
+ name: "Name",
+ suggestedLimit: "Vorgeschlagene Einträge",
+ suggestedLimitDescription: "Wie viele aktuelle Dateien Vorgeschlagen zeigt.",
+ tabAuto: "Wenn Dateien vorhanden sind",
+ tabAlways: "Immer",
+ contentSection: "Inhalt",
+ contentDescription: "Wähle, was die Bibliothek zeigt. Ausgeblendete Dateien werden nicht gelöscht.",
+ showChatAttachments: "Chat-Anhänge",
+ showChatAttachmentsDescription: "Dateien, die du an Chats angehängt hast.",
+ showChatToolFiles: "Dateien aus Chat-Tools",
+ showChatToolFilesDescription: "Dateien, die Code und Tools in Chats erstellt haben.",
+ showGeneratedMedia: "Generierte Medien",
+ showGeneratedMediaDescription: "Bilder, Videos und Audio von den Seiten Bilder, Video und Audio.",
+ showFineTunesDescription: "Modelle, die du in Unsloth trainiert oder exportiert hast.",
+ deletingSection: "Löschen",
+ confirmDelete: "Vor dem Löschen bestätigen",
+ confirmDeleteDescription: "Vor dem Löschen von Dateien und Ordnern aus der Bibliothek nachfragen.",
+ reset: "Bibliothekseinstellungen zurücksetzen",
+ resetDescription: "Alle Optionen oben auf den Standard zurücksetzen.",
+ resetButton: "Zurücksetzen",
+ resetDone: "Bibliothekseinstellungen zurückgesetzt",
+ storageSection: "Speicher",
+ storageDescription: "Öffne eine Kategorie, um ihre Dateien nach Größe zu sehen, und lösche, was du nicht mehr brauchst.",
+ storageUsed: "{size} von der Bibliothek belegt",
+ storageDisk: "{free} frei von {total} auf diesem Laufwerk",
+ storageEmpty: "In der Bibliothek ist noch nichts gespeichert.",
+ storageHidden: "{size} in den Inhaltseinstellungen ausgeblendet",
+ storageError: "Der Speicher der Bibliothek konnte nicht gelesen werden.",
+ locationsSection: "Dateien auf dem Datenträger",
+ locationsDescription: "Wo Unsloth jede Dateiart speichert. Bibliotheksordner sind Beschriftungen in Unsloth, keine Ordner auf dem Datenträger. Feinabstimmungen und Exporte bleiben, wo sie sind, da Training und Chats sie über ihren Pfad finden.",
+ locationUploads: "Bibliotheks-Uploads",
+ locationExports: "Exporte",
+ revealFailed: "Dateimanager konnte nicht geöffnet werden",
+ locationReset: "Zurücksetzen",
+ locationMoveTitle: "{name} in einen neuen Ordner verschieben",
+ locationMoveDescription: "Wähle einen beliebigen Ordner. Enthält er schon Dateien, legt Unsloth darin einen eigenen Ordner an. Alles, was schon hier liegt, wird mit verschoben.",
+ locationMoveAction: "Hierher verschieben",
+ locationMoving: "{name} wird verschoben…",
+ locationMoved: "{name} verschoben",
+ locationMoveFailed: "{name} konnte nicht verschoben werden",
+ locationFree: "{free} frei auf diesem Laufwerk",
+ locationUnavailable: "Nicht verfügbar. Schließe das Laufwerk wieder an oder setze den Ordner zurück.",
+ locationResetUnavailableTitle: "{name} zurücksetzen?",
+ locationResetUnavailableDescription: "Das Laufwerk ist nicht verbunden. Die Dateien in {path} bleiben auf diesem Laufwerk und erscheinen erst wieder in der Bibliothek, wenn du sie zurückverschiebst.",
+ locationLeftBehind: "Die Dateien in {path} bleiben auf diesem Laufwerk.",
+ dataStorage: "Bibliotheksspeicher",
+ manageStorage: "Speicher verwalten",
+ categoryImages: "Bilder",
+ categoryVideos: "Videos",
+ categoryFineTunes: "Fine-Tunes",
+ itemCountOne: "1 Eintrag",
+ itemCount: "{count} Einträge",
+ tabsSection: "Tabs",
+ tabsDescription: "Wähle, welche Tabs die Bibliothek zeigt. Ein Tab, den du über einen Link öffnest, wird trotzdem angezeigt.",
+ tabHidden: "Ausgeblendet",
+ lastVisited: "Zuletzt besucht",
+ },
tabs: {
accounts: "Konten",
general: "Allgemein",
@@ -3031,6 +3110,8 @@ export const de = {
lastActivity: "Letzte Aktivität",
favorite: "Favorit",
modified: "Geändert {time}",
+ opened: "Geöffnet {time}",
+ modifiedColumn: "Geändert",
justNow: "gerade eben",
},
size: {
@@ -3038,6 +3119,7 @@ export const de = {
kilobytes: "{value} KB",
megabytes: "{value} MB",
gigabytes: "{value} GB",
+ terabytes: "{value} TB",
},
modelKind: {
lora: "LoRA",
@@ -3062,6 +3144,7 @@ export const de = {
deleteVideo: "Die Datei wird auch aus Ihrer Videogalerie entfernt.",
deleteAudio: "Die Datei wird auch aus Ihrer Audiogalerie entfernt.",
deleteSandbox: "Die Datei wird auch aus dem Chat entfernt, der sie erstellt hat.",
+ deleteModel: "Dadurch wird das Modell endgültig von der Festplatte gelöscht.",
unsavedTitle: "Ihre Änderungen wurden nicht gespeichert",
unsavedDescription: "{reason} Versuchen Sie es erneut oder verwerfen Sie Ihre Änderungen, um die Datei zu schließen.",
keepEditing: "Weiter bearbeiten",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 13b3fe45f70..c5f8c05d871 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -311,6 +311,85 @@ export const en = {
panelFailed: "This section could not be loaded.",
panelReload: "Reload",
},
+ library: {
+ layoutSection: "Layout",
+ cardSize: "Card size",
+ cardSizeDescription: "How many cards fit in a row.",
+ small: "Small",
+ medium: "Medium",
+ large: "Large",
+ imageLayout: "Image cards",
+ imageLayoutDescription: "Keep each image's shape, or crop them to even squares.",
+ masonry: "Original shape",
+ square: "Square",
+ showCardDates: "Show dates on cards",
+ showCardDatesDescription: "Show when each file last changed.",
+ browsingSection: "Browsing",
+ startTab: "Open on",
+ startTabDescription: "The tab the Library opens to.",
+ suggested: "Suggested",
+ all: "All",
+ sort: "Sort by",
+ sortDescription: "Order of files and folders. Suggested always shows the most recent.",
+ recent: "Most recent",
+ oldest: "Oldest",
+ name: "Name",
+ suggestedLimit: "Suggested items",
+ suggestedLimitDescription: "How many recent files Suggested shows.",
+ tabAuto: "When they have files",
+ tabAlways: "Always",
+ contentSection: "Content",
+ contentDescription: "Choose what the Library shows. Hidden files are not deleted.",
+ showChatAttachments: "Chat attachments",
+ showChatAttachmentsDescription: "Files you attached to chats.",
+ showChatToolFiles: "Files from chat tools",
+ showChatToolFilesDescription: "Files that code and tools created during chats.",
+ showGeneratedMedia: "Generated media",
+ showGeneratedMediaDescription: "Images, videos and audio from the Images, Video and Audio pages.",
+ showFineTunesDescription: "Models you trained or exported in Unsloth.",
+ deletingSection: "Deleting",
+ confirmDelete: "Confirm before deleting",
+ confirmDeleteDescription: "Ask before deleting files and folders from the Library.",
+ reset: "Reset Library settings",
+ resetDescription: "Restore every option above to its default.",
+ resetButton: "Reset",
+ resetDone: "Library settings reset",
+ storageSection: "Storage",
+ storageDescription: "Open a category to see its files largest first, and delete what you no longer need.",
+ storageUsed: "{size} used by the Library",
+ storageDisk: "{free} free of {total} on this disk",
+ storageEmpty: "Nothing is stored in the Library yet.",
+ storageHidden: "{size} hidden in Content settings",
+ storageError: "Could not read Library storage.",
+ locationsSection: "Files on disk",
+ locationsDescription: "Where Unsloth keeps each kind of file. Library folders are labels inside Unsloth, not folders on disk. Fine-tunes and exports stay where they are, since training and chats refer to them by path.",
+ locationUploads: "Library uploads",
+ locationExports: "Exports",
+ revealFailed: "Could not open the file manager",
+ locationReset: "Reset",
+ locationMoveTitle: "Move {name} to a new folder",
+ locationMoveDescription: "Pick any folder. If it already has files, Unsloth makes its own folder inside it. Everything already here moves too.",
+ locationMoveAction: "Move here",
+ locationMoving: "Moving {name}…",
+ locationMoved: "{name} moved",
+ locationMoveFailed: "Could not move {name}",
+ locationFree: "{free} free on this drive",
+ locationUnavailable: "Not available. Reconnect its drive, or reset the folder.",
+ locationResetUnavailableTitle: "Reset {name}?",
+ locationResetUnavailableDescription: "Its drive is not connected. The files in {path} stay on that drive and won't show in the Library until you move them back.",
+ locationLeftBehind: "The files in {path} stay on that drive.",
+ dataStorage: "Library storage",
+ manageStorage: "Manage storage",
+ categoryImages: "Images",
+ categoryVideos: "Videos",
+ categoryFineTunes: "Fine-tunes",
+ itemCountOne: "1 item",
+ itemCount: "{count} items",
+ tabsSection: "Tabs",
+ tabsDescription: "Choose which tabs the Library shows. A tab you open from a link still appears.",
+ tabHidden: "Hidden",
+ lastVisited: "Last visited",
+ },
tabs: {
accounts: "Accounts",
general: "General",
@@ -2953,6 +3032,8 @@ export const en = {
lastActivity: "Last activity",
favorite: "Favorite",
modified: "Modified {time}",
+ opened: "Opened {time}",
+ modifiedColumn: "Modified",
justNow: "just now",
},
// File sizes. {value} is already formatted for the locale.
@@ -2961,6 +3042,7 @@ export const en = {
kilobytes: "{value} KB",
megabytes: "{value} MB",
gigabytes: "{value} GB",
+ terabytes: "{value} TB",
},
// Fine-tuned models, by how they were made.
modelKind: {
@@ -2988,6 +3070,7 @@ export const en = {
deleteVideo: "It is also removed from your Video gallery.",
deleteAudio: "It is also removed from your Audio gallery.",
deleteSandbox: "It is also removed from the chat that created it.",
+ deleteModel: "This permanently deletes the model from disk.",
unsavedTitle: "Your changes weren't saved",
// {reason} is why the save failed, ending in a full stop.
unsavedDescription: "{reason} Try again, or discard your changes to close the file.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 2fa83f50230..ec07c867d03 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -308,6 +308,85 @@ export const es = {
panelFailed: "No se pudo cargar esta sección.",
panelReload: "Recargar",
},
+ library: {
+ layoutSection: "Diseño",
+ cardSize: "Tamaño de tarjeta",
+ cardSizeDescription: "Cuántas tarjetas caben en una fila.",
+ small: "Pequeño",
+ medium: "Mediano",
+ large: "Grande",
+ imageLayout: "Tarjetas de imagen",
+ imageLayoutDescription: "Mantener la forma de cada imagen o recortarlas en cuadrados iguales.",
+ masonry: "Forma original",
+ square: "Cuadrada",
+ showCardDates: "Mostrar fechas en las tarjetas",
+ showCardDatesDescription: "Muestra cuándo cambió cada archivo por última vez.",
+ browsingSection: "Navegación",
+ startTab: "Abrir en",
+ startTabDescription: "La pestaña con la que se abre la Biblioteca.",
+ suggested: "Sugeridos",
+ all: "Todo",
+ sort: "Ordenar por",
+ sortDescription: "Orden de archivos y carpetas. Sugeridos siempre muestra los más recientes.",
+ recent: "Más recientes",
+ oldest: "Más antiguos",
+ name: "Nombre",
+ suggestedLimit: "Elementos sugeridos",
+ suggestedLimitDescription: "Cuántos archivos recientes muestra Sugeridos.",
+ tabAuto: "Cuando tengan archivos",
+ tabAlways: "Siempre",
+ contentSection: "Contenido",
+ contentDescription: "Elige qué muestra la Biblioteca. Los archivos ocultos no se eliminan.",
+ showChatAttachments: "Adjuntos de chat",
+ showChatAttachmentsDescription: "Archivos que adjuntaste a los chats.",
+ showChatToolFiles: "Archivos de herramientas del chat",
+ showChatToolFilesDescription: "Archivos que el código y las herramientas crearon en los chats.",
+ showGeneratedMedia: "Contenido generado",
+ showGeneratedMediaDescription: "Imágenes, videos y audio de las páginas Imágenes, Video y Audio.",
+ showFineTunesDescription: "Modelos que entrenaste o exportaste en Unsloth.",
+ deletingSection: "Eliminación",
+ confirmDelete: "Confirmar antes de eliminar",
+ confirmDeleteDescription: "Preguntar antes de eliminar archivos y carpetas de la Biblioteca.",
+ reset: "Restablecer ajustes de la Biblioteca",
+ resetDescription: "Devuelve cada opción anterior a su valor predeterminado.",
+ resetButton: "Restablecer",
+ resetDone: "Ajustes de la Biblioteca restablecidos",
+ storageSection: "Almacenamiento",
+ storageDescription: "Abre una categoría para ver sus archivos de mayor a menor y elimina lo que ya no necesites.",
+ storageUsed: "{size} usados por la Biblioteca",
+ storageDisk: "{free} libres de {total} en este disco",
+ storageEmpty: "Todavía no hay nada guardado en la Biblioteca.",
+ storageHidden: "{size} ocultos en los ajustes de Contenido",
+ storageError: "No se pudo leer el almacenamiento de la Biblioteca.",
+ locationsSection: "Archivos en el disco",
+ locationsDescription: "Dónde guarda Unsloth cada tipo de archivo. Las carpetas de la biblioteca son etiquetas dentro de Unsloth, no carpetas en el disco. Los ajustes finos y las exportaciones se quedan donde están, porque el entrenamiento y los chats los encuentran por su ruta.",
+ locationUploads: "Archivos subidos a la biblioteca",
+ locationExports: "Exportaciones",
+ revealFailed: "No se pudo abrir el administrador de archivos",
+ locationReset: "Restablecer",
+ locationMoveTitle: "Mover {name} a una carpeta nueva",
+ locationMoveDescription: "Elige cualquier carpeta. Si ya tiene archivos, Unsloth crea su propia carpeta dentro. Todo lo que ya está aquí se mueve también.",
+ locationMoveAction: "Mover aquí",
+ locationMoving: "Moviendo {name}…",
+ locationMoved: "{name} movido",
+ locationMoveFailed: "No se pudo mover {name}",
+ locationFree: "{free} libres en esta unidad",
+ locationUnavailable: "No disponible. Vuelve a conectar su unidad o restablece la carpeta.",
+ locationResetUnavailableTitle: "¿Restablecer {name}?",
+ locationResetUnavailableDescription: "Su unidad no está conectada. Los archivos de {path} se quedan en esa unidad y no aparecerán en la Biblioteca hasta que los vuelvas a mover.",
+ locationLeftBehind: "Los archivos de {path} se quedan en esa unidad.",
+ dataStorage: "Almacenamiento de la biblioteca",
+ manageStorage: "Administrar almacenamiento",
+ categoryImages: "Imágenes",
+ categoryVideos: "Videos",
+ categoryFineTunes: "Ajustes finos",
+ itemCountOne: "1 elemento",
+ itemCount: "{count} elementos",
+ tabsSection: "Pestañas",
+ tabsDescription: "Elige qué pestañas muestra la Biblioteca. Una pestaña abierta desde un enlace sigue apareciendo.",
+ tabHidden: "Oculta",
+ lastVisited: "Última visitada",
+ },
tabs: {
accounts: "Cuentas",
general: "General",
@@ -3028,6 +3107,8 @@ export const es = {
lastActivity: "Última actividad",
favorite: "Favorito",
modified: "Modificado {time}",
+ opened: "Abierto {time}",
+ modifiedColumn: "Modificado",
justNow: "justo ahora",
},
size: {
@@ -3035,6 +3116,7 @@ export const es = {
kilobytes: "{value} KB",
megabytes: "{value} MB",
gigabytes: "{value} GB",
+ terabytes: "{value} TB",
},
modelKind: {
lora: "LoRA",
@@ -3059,6 +3141,7 @@ export const es = {
deleteVideo: "También se quitará de tu galería de Vídeo.",
deleteAudio: "También se quitará de tu galería de Audio.",
deleteSandbox: "También se quitará del chat que lo creó.",
+ deleteModel: "Esto elimina el modelo del disco de forma permanente.",
unsavedTitle: "Tus cambios no se guardaron",
unsavedDescription: "{reason} Vuelve a intentarlo o descarta los cambios para cerrar el archivo.",
keepEditing: "Seguir editando",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 5c6332a9344..4fd12dbcd22 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -309,6 +309,85 @@ export const fr = {
panelFailed: "Cette section n'a pas pu être chargée.",
panelReload: "Recharger",
},
+ library: {
+ layoutSection: "Disposition",
+ cardSize: "Taille des cartes",
+ cardSizeDescription: "Nombre de cartes par ligne.",
+ small: "Petite",
+ medium: "Moyenne",
+ large: "Grande",
+ imageLayout: "Cartes d'image",
+ imageLayoutDescription: "Conserver la forme de chaque image ou les recadrer en carrés réguliers.",
+ masonry: "Forme d'origine",
+ square: "Carrée",
+ showCardDates: "Afficher les dates sur les cartes",
+ showCardDatesDescription: "Indique quand chaque fichier a été modifié pour la dernière fois.",
+ browsingSection: "Navigation",
+ startTab: "Ouvrir sur",
+ startTabDescription: "L'onglet sur lequel la Bibliothèque s'ouvre.",
+ suggested: "Suggestions",
+ all: "Tout",
+ sort: "Trier par",
+ sortDescription: "Ordre des fichiers et dossiers. Suggestions affiche toujours les plus récents.",
+ recent: "Plus récents",
+ oldest: "Plus anciens",
+ name: "Nom",
+ suggestedLimit: "Éléments suggérés",
+ suggestedLimitDescription: "Nombre de fichiers récents affichés dans Suggestions.",
+ tabAuto: "Quand ils contiennent des fichiers",
+ tabAlways: "Toujours",
+ contentSection: "Contenu",
+ contentDescription: "Choisissez ce que la Bibliothèque affiche. Les fichiers masqués ne sont pas supprimés.",
+ showChatAttachments: "Pièces jointes des discussions",
+ showChatAttachmentsDescription: "Fichiers que vous avez joints aux discussions.",
+ showChatToolFiles: "Fichiers des outils de discussion",
+ showChatToolFilesDescription: "Fichiers créés par le code et les outils pendant les discussions.",
+ showGeneratedMedia: "Médias générés",
+ showGeneratedMediaDescription: "Images, vidéos et audio des pages Images, Vidéo et Audio.",
+ showFineTunesDescription: "Modèles que vous avez entraînés ou exportés dans Unsloth.",
+ deletingSection: "Suppression",
+ confirmDelete: "Confirmer avant de supprimer",
+ confirmDeleteDescription: "Demander avant de supprimer des fichiers et dossiers de la Bibliothèque.",
+ reset: "Réinitialiser les réglages de la Bibliothèque",
+ resetDescription: "Rétablir chaque option ci-dessus à sa valeur par défaut.",
+ resetButton: "Réinitialiser",
+ resetDone: "Réglages de la Bibliothèque réinitialisés",
+ storageSection: "Stockage",
+ storageDescription: "Ouvrez une catégorie pour voir ses fichiers du plus lourd au plus léger et supprimez ce dont vous n'avez plus besoin.",
+ storageUsed: "{size} utilisés par la Bibliothèque",
+ storageDisk: "{free} libres sur {total} sur ce disque",
+ storageEmpty: "Rien n'est encore stocké dans la Bibliothèque.",
+ storageHidden: "{size} masqués dans les réglages du contenu",
+ storageError: "Impossible de lire le stockage de la Bibliothèque.",
+ locationsSection: "Fichiers sur le disque",
+ locationsDescription: "Où Unsloth conserve chaque type de fichier. Les dossiers de la bibliothèque sont des étiquettes dans Unsloth, pas des dossiers sur le disque. Les affinages et les exports restent en place, car l'entraînement et les chats les retrouvent par leur chemin.",
+ locationUploads: "Fichiers importés dans la bibliothèque",
+ locationExports: "Exportations",
+ revealFailed: "Impossible d'ouvrir le gestionnaire de fichiers",
+ locationReset: "Réinitialiser",
+ locationMoveTitle: "Déplacer {name} vers un nouveau dossier",
+ locationMoveDescription: "Choisissez n'importe quel dossier. S'il contient déjà des fichiers, Unsloth y crée son propre dossier. Tout ce qui se trouve déjà ici est aussi déplacé.",
+ locationMoveAction: "Déplacer ici",
+ locationMoving: "Déplacement de {name}…",
+ locationMoved: "{name} déplacé",
+ locationMoveFailed: "Impossible de déplacer {name}",
+ locationFree: "{free} libres sur ce lecteur",
+ locationUnavailable: "Indisponible. Reconnectez son lecteur ou réinitialisez le dossier.",
+ locationResetUnavailableTitle: "Réinitialiser {name} ?",
+ locationResetUnavailableDescription: "Son lecteur n'est pas connecté. Les fichiers de {path} restent sur ce lecteur et n'apparaîtront pas dans la Bibliothèque tant que vous ne les aurez pas remis en place.",
+ locationLeftBehind: "Les fichiers de {path} restent sur ce lecteur.",
+ dataStorage: "Stockage de la bibliothèque",
+ manageStorage: "Gérer le stockage",
+ categoryImages: "Images",
+ categoryVideos: "Vidéos",
+ categoryFineTunes: "Fine-tunes",
+ itemCountOne: "1 élément",
+ itemCount: "{count} éléments",
+ tabsSection: "Onglets",
+ tabsDescription: "Choisissez les onglets affichés par la Bibliothèque. Un onglet ouvert depuis un lien reste visible.",
+ tabHidden: "Masqué",
+ lastVisited: "Dernier visité",
+ },
tabs: {
accounts: "Comptes",
general: "Général",
@@ -3042,6 +3121,8 @@ export const fr = {
lastActivity: "Dernière activité",
favorite: "Favori",
modified: "Modifié {time}",
+ opened: "Ouvert {time}",
+ modifiedColumn: "Modifié",
justNow: "à l'instant",
},
size: {
@@ -3049,6 +3130,7 @@ export const fr = {
kilobytes: "{value} Ko",
megabytes: "{value} Mo",
gigabytes: "{value} Go",
+ terabytes: "{value} To",
},
modelKind: {
lora: "LoRA",
@@ -3073,6 +3155,7 @@ export const fr = {
deleteVideo: "Il sera aussi retiré de votre galerie Vidéo.",
deleteAudio: "Il sera aussi retiré de votre galerie Audio.",
deleteSandbox: "Il sera aussi retiré de la discussion qui l'a créé.",
+ deleteModel: "Le modèle sera définitivement supprimé du disque.",
unsavedTitle: "Vos modifications n'ont pas été enregistrées",
unsavedDescription: "{reason} Réessayez, ou abandonnez vos modifications pour fermer le fichier.",
keepEditing: "Continuer la modification",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 545e0317827..89ccb655a78 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -308,6 +308,85 @@ export const hi = {
panelFailed: "यह अनुभाग लोड नहीं हो सका।",
panelReload: "फिर से लोड करें",
},
+ library: {
+ layoutSection: "लेआउट",
+ cardSize: "कार्ड का आकार",
+ cardSizeDescription: "एक पंक्ति में कितने कार्ड आएं।",
+ small: "छोटा",
+ medium: "मध्यम",
+ large: "बड़ा",
+ imageLayout: "इमेज कार्ड",
+ imageLayoutDescription: "हर इमेज का आकार बनाए रखें, या बराबर वर्गों में क्रॉप करें।",
+ masonry: "मूल आकार",
+ square: "वर्ग",
+ showCardDates: "कार्ड पर तारीख दिखाएं",
+ showCardDatesDescription: "दिखाएं कि हर फ़ाइल आखिरी बार कब बदली गई।",
+ browsingSection: "ब्राउज़िंग",
+ startTab: "इस टैब पर खोलें",
+ startTabDescription: "वह टैब जिस पर लाइब्रेरी खुलती है।",
+ suggested: "सुझाए गए",
+ all: "सभी",
+ sort: "इसके अनुसार क्रमबद्ध करें",
+ sortDescription: "फ़ाइलों और फ़ोल्डरों का क्रम। सुझाए गए में हमेशा सबसे नई फ़ाइलें दिखती हैं।",
+ recent: "सबसे नए",
+ oldest: "सबसे पुराने",
+ name: "नाम",
+ suggestedLimit: "सुझाए गए आइटम",
+ suggestedLimitDescription: "सुझाए गए में कितनी हाल की फ़ाइलें दिखें।",
+ tabAuto: "जब फ़ाइलें हों",
+ tabAlways: "हमेशा",
+ contentSection: "सामग्री",
+ contentDescription: "चुनें कि लाइब्रेरी क्या दिखाए। छिपी फ़ाइलें हटाई नहीं जातीं।",
+ showChatAttachments: "चैट अटैचमेंट",
+ showChatAttachmentsDescription: "वे फ़ाइलें जो आपने चैट में अटैच कीं।",
+ showChatToolFiles: "चैट टूल की फ़ाइलें",
+ showChatToolFilesDescription: "वे फ़ाइलें जो चैट के दौरान कोड और टूल ने बनाईं।",
+ showGeneratedMedia: "जनरेट किया गया मीडिया",
+ showGeneratedMediaDescription: "इमेज, वीडियो और ऑडियो पेज से बने इमेज, वीडियो और ऑडियो।",
+ showFineTunesDescription: "वे मॉडल जिन्हें आपने Unsloth में ट्रेन या एक्सपोर्ट किया।",
+ deletingSection: "हटाना",
+ confirmDelete: "हटाने से पहले पुष्टि करें",
+ confirmDeleteDescription: "लाइब्रेरी से फ़ाइलें और फ़ोल्डर हटाने से पहले पूछें।",
+ reset: "लाइब्रेरी सेटिंग्स रीसेट करें",
+ resetDescription: "ऊपर के सभी विकल्पों को डिफ़ॉल्ट पर लौटाएं।",
+ resetButton: "रीसेट",
+ resetDone: "लाइब्रेरी सेटिंग्स रीसेट हो गईं",
+ storageSection: "स्टोरेज",
+ storageDescription: "किसी श्रेणी को खोलकर उसकी फ़ाइलें सबसे बड़ी से देखें, और जो ज़रूरी नहीं है उसे हटाएं।",
+ storageUsed: "लाइब्रेरी {size} इस्तेमाल कर रही है",
+ storageDisk: "इस डिस्क पर {total} में से {free} खाली",
+ storageEmpty: "लाइब्रेरी में अभी कुछ भी सेव नहीं है।",
+ storageHidden: "{size} सामग्री सेटिंग्स में छिपा है",
+ storageError: "लाइब्रेरी का स्टोरेज नहीं पढ़ा जा सका।",
+ locationsSection: "डिस्क पर फ़ाइलें",
+ locationsDescription: "Unsloth हर तरह की फ़ाइल कहाँ रखता है। लाइब्रेरी फ़ोल्डर Unsloth के अंदर लेबल हैं, डिस्क पर फ़ोल्डर नहीं। फ़ाइन-ट्यून और एक्सपोर्ट अपनी जगह रहते हैं, क्योंकि ट्रेनिंग और चैट उन्हें पाथ से ढूँढते हैं।",
+ locationUploads: "लाइब्रेरी अपलोड",
+ locationExports: "एक्सपोर्ट",
+ revealFailed: "फ़ाइल मैनेजर नहीं खुल सका",
+ locationReset: "रीसेट करें",
+ locationMoveTitle: "{name} को नए फ़ोल्डर में ले जाएँ",
+ locationMoveDescription: "कोई भी फ़ोल्डर चुनें। अगर उसमें पहले से फ़ाइलें हैं, तो Unsloth उसके अंदर अपना फ़ोल्डर बनाता है। यहाँ पहले से मौजूद सब कुछ भी साथ जाएगा।",
+ locationMoveAction: "यहाँ ले जाएँ",
+ locationMoving: "{name} ले जाया जा रहा है…",
+ locationMoved: "{name} ले जाया गया",
+ locationMoveFailed: "{name} को नहीं ले जाया जा सका",
+ locationFree: "इस ड्राइव पर {free} खाली",
+ locationUnavailable: "उपलब्ध नहीं। इसकी ड्राइव फिर से जोड़ें, या फ़ोल्डर रीसेट करें।",
+ locationResetUnavailableTitle: "{name} रीसेट करें?",
+ locationResetUnavailableDescription: "इसकी ड्राइव जुड़ी नहीं है। {path} की फ़ाइलें उसी ड्राइव पर रहेंगी और जब तक आप उन्हें वापस नहीं ले जाते, लाइब्रेरी में नहीं दिखेंगी।",
+ locationLeftBehind: "{path} की फ़ाइलें उसी ड्राइव पर रहती हैं।",
+ dataStorage: "लाइब्रेरी स्टोरेज",
+ manageStorage: "स्टोरेज प्रबंधित करें",
+ categoryImages: "इमेज",
+ categoryVideos: "वीडियो",
+ categoryFineTunes: "फ़ाइन-ट्यून",
+ itemCountOne: "1 आइटम",
+ itemCount: "{count} आइटम",
+ tabsSection: "टैब",
+ tabsDescription: "चुनें कि लाइब्रेरी कौन से टैब दिखाए। लिंक से खोला गया टैब फिर भी दिखता है।",
+ tabHidden: "छिपा हुआ",
+ lastVisited: "पिछली बार देखा गया",
+ },
tabs: {
accounts: "खाते",
general: "सामान्य",
@@ -2969,6 +3048,8 @@ export const hi = {
lastActivity: "पिछली गतिविधि",
favorite: "पसंदीदा",
modified: "बदला गया: {time}",
+ opened: "खोला गया: {time}",
+ modifiedColumn: "बदला गया",
justNow: "अभी",
},
size: {
@@ -2976,6 +3057,7 @@ export const hi = {
kilobytes: "{value} KB",
megabytes: "{value} MB",
gigabytes: "{value} GB",
+ terabytes: "{value} TB",
},
modelKind: {
lora: "LoRA",
@@ -3000,6 +3082,7 @@ export const hi = {
deleteVideo: "इसे आपकी वीडियो गैलरी से भी हटा दिया जाएगा।",
deleteAudio: "इसे आपकी ऑडियो गैलरी से भी हटा दिया जाएगा।",
deleteSandbox: "इसे उस चैट से भी हटा दिया जाएगा जिसने इसे बनाया था।",
+ deleteModel: "इससे मॉडल डिस्क से हमेशा के लिए हट जाएगा।",
unsavedTitle: "आपके बदलाव सेव नहीं हुए",
unsavedDescription: "{reason} फिर कोशिश करें, या फ़ाइल बंद करने के लिए अपने बदलाव छोड़ दें।",
keepEditing: "एडिट करते रहें",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 5315203ec98..48a7cae70a0 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -273,6 +273,85 @@ export const it = {
panelFailed: "Non è stato possibile caricare questa sezione.",
panelReload: "Ricarica",
},
+ library: {
+ layoutSection: "Layout",
+ cardSize: "Dimensione schede",
+ cardSizeDescription: "Quante schede entrano in una riga.",
+ small: "Piccola",
+ medium: "Media",
+ large: "Grande",
+ imageLayout: "Schede immagine",
+ imageLayoutDescription: "Mantieni la forma di ogni immagine o ritagliale in quadrati uniformi.",
+ masonry: "Forma originale",
+ square: "Quadrata",
+ showCardDates: "Mostra date sulle schede",
+ showCardDatesDescription: "Mostra quando ogni file è stato modificato l'ultima volta.",
+ browsingSection: "Navigazione",
+ startTab: "Apri su",
+ startTabDescription: "La scheda con cui si apre la Libreria.",
+ suggested: "Suggeriti",
+ all: "Tutto",
+ sort: "Ordina per",
+ sortDescription: "Ordine di file e cartelle. Suggeriti mostra sempre i più recenti.",
+ recent: "Più recenti",
+ oldest: "Meno recenti",
+ name: "Nome",
+ suggestedLimit: "Elementi suggeriti",
+ suggestedLimitDescription: "Quanti file recenti mostra Suggeriti.",
+ tabAuto: "Quando contengono file",
+ tabAlways: "Sempre",
+ contentSection: "Contenuto",
+ contentDescription: "Scegli cosa mostra la Libreria. I file nascosti non vengono eliminati.",
+ showChatAttachments: "Allegati delle chat",
+ showChatAttachmentsDescription: "File che hai allegato alle chat.",
+ showChatToolFiles: "File degli strumenti della chat",
+ showChatToolFilesDescription: "File creati da codice e strumenti durante le chat.",
+ showGeneratedMedia: "Contenuti generati",
+ showGeneratedMediaDescription: "Immagini, video e audio dalle pagine Immagini, Video e Audio.",
+ showFineTunesDescription: "Modelli che hai addestrato o esportato in Unsloth.",
+ deletingSection: "Eliminazione",
+ confirmDelete: "Conferma prima di eliminare",
+ confirmDeleteDescription: "Chiedi prima di eliminare file e cartelle dalla Libreria.",
+ reset: "Reimposta impostazioni della Libreria",
+ resetDescription: "Riporta ogni opzione qui sopra al valore predefinito.",
+ resetButton: "Reimposta",
+ resetDone: "Impostazioni della Libreria reimpostate",
+ storageSection: "Spazio",
+ storageDescription: "Apri una categoria per vedere i file dal più grande e elimina ciò che non ti serve più.",
+ storageUsed: "{size} usati dalla Libreria",
+ storageDisk: "{free} liberi su {total} in questo disco",
+ storageEmpty: "Nella Libreria non c'è ancora nulla.",
+ storageHidden: "{size} nascosti nelle impostazioni Contenuti",
+ storageError: "Impossibile leggere lo spazio della Libreria.",
+ locationsSection: "File sul disco",
+ locationsDescription: "Dove Unsloth conserva ogni tipo di file. Le cartelle della libreria sono etichette dentro Unsloth, non cartelle sul disco. I fine-tuning e le esportazioni restano dove sono, perché addestramento e chat li trovano tramite il percorso.",
+ locationUploads: "Caricamenti della libreria",
+ locationExports: "Esportazioni",
+ revealFailed: "Impossibile aprire il gestore file",
+ locationReset: "Ripristina",
+ locationMoveTitle: "Sposta {name} in una nuova cartella",
+ locationMoveDescription: "Scegli una cartella qualsiasi. Se contiene già dei file, Unsloth crea al suo interno una propria cartella. Anche tutto ciò che è già qui viene spostato.",
+ locationMoveAction: "Sposta qui",
+ locationMoving: "Spostamento di {name}…",
+ locationMoved: "{name} spostato",
+ locationMoveFailed: "Impossibile spostare {name}",
+ locationFree: "{free} liberi su questa unità",
+ locationUnavailable: "Non disponibile. Ricollega la sua unità o reimposta la cartella.",
+ locationResetUnavailableTitle: "Reimpostare {name}?",
+ locationResetUnavailableDescription: "La sua unità non è collegata. I file in {path} restano su quell'unità e non compariranno nella Libreria finché non li sposti di nuovo.",
+ locationLeftBehind: "I file in {path} restano su quell'unità.",
+ dataStorage: "Spazio della libreria",
+ manageStorage: "Gestisci spazio",
+ categoryImages: "Immagini",
+ categoryVideos: "Video",
+ categoryFineTunes: "Fine-tune",
+ itemCountOne: "1 elemento",
+ itemCount: "{count} elementi",
+ tabsSection: "Schede",
+ tabsDescription: "Scegli quali schede mostra la Libreria. Una scheda aperta da un link resta visibile.",
+ tabHidden: "Nascosta",
+ lastVisited: "Ultima visitata",
+ },
tabs: {
accounts: "Account",
general: "Generali",
@@ -3029,6 +3108,8 @@ export const it = {
lastActivity: "Ultima attività",
favorite: "Preferito",
modified: "Modificato {time}",
+ opened: "Aperto {time}",
+ modifiedColumn: "Modificato",
justNow: "proprio ora",
},
size: {
@@ -3036,6 +3117,7 @@ export const it = {
kilobytes: "{value} KB",
megabytes: "{value} MB",
gigabytes: "{value} GB",
+ terabytes: "{value} TB",
},
modelKind: {
lora: "LoRA",
@@ -3060,6 +3142,7 @@ export const it = {
deleteVideo: "Verrà rimosso anche dalla tua galleria Video.",
deleteAudio: "Verrà rimosso anche dalla tua galleria Audio.",
deleteSandbox: "Verrà rimosso anche dalla chat che lo ha creato.",
+ deleteModel: "Il modello verrà eliminato definitivamente dal disco.",
unsavedTitle: "Le modifiche non sono state salvate",
unsavedDescription: "{reason} Riprova, oppure annulla le modifiche per chiudere il file.",
keepEditing: "Continua a modificare",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index b8578653d9a..c171dfdbc99 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -307,6 +307,85 @@ export const ja = {
panelFailed: "このセクションを読み込めませんでした。",
panelReload: "再読み込み",
},
+ library: {
+ layoutSection: "レイアウト",
+ cardSize: "カードのサイズ",
+ cardSizeDescription: "1行に並ぶカードの数。",
+ small: "小",
+ medium: "中",
+ large: "大",
+ imageLayout: "画像カード",
+ imageLayoutDescription: "各画像の形を保つか、均一な正方形に切り抜きます。",
+ masonry: "元の形",
+ square: "正方形",
+ showCardDates: "カードに日付を表示",
+ showCardDatesDescription: "各ファイルの最終更新日時を表示します。",
+ browsingSection: "閲覧",
+ startTab: "開くタブ",
+ startTabDescription: "ライブラリを開いたときに表示するタブ。",
+ suggested: "おすすめ",
+ all: "すべて",
+ sort: "並べ替え",
+ sortDescription: "ファイルとフォルダの順序。おすすめは常に新しい順です。",
+ recent: "新しい順",
+ oldest: "古い順",
+ name: "名前",
+ suggestedLimit: "おすすめの件数",
+ suggestedLimitDescription: "おすすめに表示する最近のファイル数。",
+ tabAuto: "ファイルがある場合",
+ tabAlways: "常に表示",
+ contentSection: "コンテンツ",
+ contentDescription: "ライブラリに表示するものを選びます。非表示のファイルは削除されません。",
+ showChatAttachments: "チャットの添付ファイル",
+ showChatAttachmentsDescription: "チャットに添付したファイル。",
+ showChatToolFiles: "チャットツールのファイル",
+ showChatToolFilesDescription: "チャット中にコードやツールが作成したファイル。",
+ showGeneratedMedia: "生成メディア",
+ showGeneratedMediaDescription: "画像・動画・音声ページで作成した画像、動画、音声。",
+ showFineTunesDescription: "Unsloth で学習またはエクスポートしたモデル。",
+ deletingSection: "削除",
+ confirmDelete: "削除前に確認",
+ confirmDeleteDescription: "ライブラリからファイルやフォルダを削除する前に確認します。",
+ reset: "ライブラリ設定をリセット",
+ resetDescription: "上記のすべてのオプションをデフォルトに戻します。",
+ resetButton: "リセット",
+ resetDone: "ライブラリ設定をリセットしました",
+ storageSection: "ストレージ",
+ storageDescription: "カテゴリを開くとファイルがサイズの大きい順に表示されます。不要なものを削除できます。",
+ storageUsed: "ライブラリの使用量 {size}",
+ storageDisk: "このディスクの空き容量 {free} / {total}",
+ storageEmpty: "ライブラリにはまだ何も保存されていません。",
+ storageHidden: "コンテンツ設定で非表示: {size}",
+ storageError: "ライブラリのストレージを読み込めませんでした。",
+ locationsSection: "ディスク上のファイル",
+ locationsDescription: "Unsloth が各種ファイルを保存している場所です。ライブラリのフォルダは Unsloth 内のラベルで、ディスク上のフォルダではありません。ファインチューニングとエクスポートは、学習とチャットがパスで参照するため移動できません。",
+ locationUploads: "ライブラリのアップロード",
+ locationExports: "エクスポート",
+ revealFailed: "ファイルマネージャーを開けませんでした",
+ locationReset: "リセット",
+ locationMoveTitle: "{name} を新しいフォルダに移動",
+ locationMoveDescription: "任意のフォルダを選んでください。すでにファイルがある場合は、Unsloth がその中に専用のフォルダを作成します。ここにあるファイルもすべて移動します。",
+ locationMoveAction: "ここに移動",
+ locationMoving: "{name} を移動しています…",
+ locationMoved: "{name} を移動しました",
+ locationMoveFailed: "{name} を移動できませんでした",
+ locationFree: "このドライブの空き容量 {free}",
+ locationUnavailable: "利用できません。ドライブを接続し直すか、フォルダをリセットしてください。",
+ locationResetUnavailableTitle: "{name} をリセットしますか?",
+ locationResetUnavailableDescription: "ドライブが接続されていません。{path} のファイルはそのドライブに残り、元に戻すまでライブラリには表示されません。",
+ locationLeftBehind: "{path} のファイルはそのドライブに残ります。",
+ dataStorage: "ライブラリのストレージ",
+ manageStorage: "ストレージを管理",
+ categoryImages: "画像",
+ categoryVideos: "動画",
+ categoryFineTunes: "ファインチューン",
+ itemCountOne: "1 件",
+ itemCount: "{count} 件",
+ tabsSection: "タブ",
+ tabsDescription: "ライブラリに表示するタブを選びます。リンクから開いたタブは表示されます。",
+ tabHidden: "非表示",
+ lastVisited: "前回開いたタブ",
+ },
tabs: {
accounts: "アカウント",
general: "一般",
@@ -2907,9 +2986,11 @@ export const ja = {
list: {
selectAll: "すべて選択",
name: "名前",
- lastActivity: "最終更新",
+ lastActivity: "最近のアクティビティ",
favorite: "お気に入り",
modified: "変更: {time}",
+ opened: "開いた日時: {time}",
+ modifiedColumn: "更新日時",
justNow: "たった今",
},
size: {
@@ -2917,6 +2998,7 @@ export const ja = {
kilobytes: "{value} KB",
megabytes: "{value} MB",
gigabytes: "{value} GB",
+ terabytes: "{value} TB",
},
modelKind: {
lora: "LoRA",
@@ -2941,6 +3023,7 @@ export const ja = {
deleteVideo: "動画ギャラリーからも削除されます。",
deleteAudio: "音声ギャラリーからも削除されます。",
deleteSandbox: "このファイルを作成したチャットからも削除されます。",
+ deleteModel: "モデルはディスクから完全に削除されます。",
unsavedTitle: "変更は保存されていません",
unsavedDescription: "{reason} もう一度試すか、変更を破棄してファイルを閉じてください。",
keepEditing: "編集を続ける",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 2d88f1682fb..e594724d9a9 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -305,6 +305,85 @@ export const ko = {
panelFailed: "이 섹션을 불러오지 못했습니다.",
panelReload: "새로고침",
},
+ library: {
+ layoutSection: "레이아웃",
+ cardSize: "카드 크기",
+ cardSizeDescription: "한 줄에 들어가는 카드 수입니다.",
+ small: "작게",
+ medium: "중간",
+ large: "크게",
+ imageLayout: "이미지 카드",
+ imageLayoutDescription: "각 이미지의 모양을 유지하거나 균일한 정사각형으로 자릅니다.",
+ masonry: "원래 모양",
+ square: "정사각형",
+ showCardDates: "카드에 날짜 표시",
+ showCardDatesDescription: "각 파일이 마지막으로 변경된 시간을 표시합니다.",
+ browsingSection: "탐색",
+ startTab: "시작 탭",
+ startTabDescription: "라이브러리를 열 때 표시할 탭입니다.",
+ suggested: "추천",
+ all: "전체",
+ sort: "정렬 기준",
+ sortDescription: "파일과 폴더의 순서입니다. 추천은 항상 최신 항목을 보여줍니다.",
+ recent: "최신순",
+ oldest: "오래된순",
+ name: "이름",
+ suggestedLimit: "추천 항목 수",
+ suggestedLimitDescription: "추천에 표시할 최근 파일 수입니다.",
+ tabAuto: "파일이 있을 때",
+ tabAlways: "항상",
+ contentSection: "콘텐츠",
+ contentDescription: "라이브러리에 표시할 항목을 선택합니다. 숨긴 파일은 삭제되지 않습니다.",
+ showChatAttachments: "채팅 첨부 파일",
+ showChatAttachmentsDescription: "채팅에 첨부한 파일입니다.",
+ showChatToolFiles: "채팅 도구 파일",
+ showChatToolFilesDescription: "채팅 중 코드와 도구가 만든 파일입니다.",
+ showGeneratedMedia: "생성된 미디어",
+ showGeneratedMediaDescription: "이미지, 동영상, 오디오 페이지에서 만든 이미지, 동영상, 오디오입니다.",
+ showFineTunesDescription: "Unsloth에서 학습하거나 내보낸 모델입니다.",
+ deletingSection: "삭제",
+ confirmDelete: "삭제 전 확인",
+ confirmDeleteDescription: "라이브러리에서 파일과 폴더를 삭제하기 전에 확인합니다.",
+ reset: "라이브러리 설정 초기화",
+ resetDescription: "위의 모든 옵션을 기본값으로 되돌립니다.",
+ resetButton: "초기화",
+ resetDone: "라이브러리 설정을 초기화했습니다",
+ storageSection: "저장 공간",
+ storageDescription: "카테고리를 열면 파일이 큰 순서로 표시되며, 필요 없는 파일을 삭제할 수 있습니다.",
+ storageUsed: "라이브러리 사용량 {size}",
+ storageDisk: "이 디스크의 여유 공간 {free} / {total}",
+ storageEmpty: "라이브러리에 아직 저장된 항목이 없습니다.",
+ storageHidden: "콘텐츠 설정에서 숨김: {size}",
+ storageError: "라이브러리 저장 공간을 읽지 못했습니다.",
+ locationsSection: "디스크의 파일",
+ locationsDescription: "Unsloth가 각 종류의 파일을 저장하는 위치입니다. 라이브러리 폴더는 Unsloth 안의 라벨이며 디스크의 폴더가 아닙니다. 파인튜닝 모델과 내보내기는 학습과 채팅이 경로로 참조하므로 그대로 유지됩니다.",
+ locationUploads: "라이브러리 업로드",
+ locationExports: "내보내기",
+ revealFailed: "파일 관리자를 열 수 없습니다",
+ locationReset: "초기화",
+ locationMoveTitle: "{name}을(를) 새 폴더로 이동",
+ locationMoveDescription: "아무 폴더나 선택하세요. 이미 파일이 있으면 Unsloth가 그 안에 전용 폴더를 만듭니다. 여기에 있는 파일도 모두 함께 이동합니다.",
+ locationMoveAction: "여기로 이동",
+ locationMoving: "{name} 이동 중…",
+ locationMoved: "{name} 이동됨",
+ locationMoveFailed: "{name}을(를) 이동할 수 없습니다",
+ locationFree: "이 드라이브의 여유 공간 {free}",
+ locationUnavailable: "사용할 수 없습니다. 드라이브를 다시 연결하거나 폴더를 재설정하세요.",
+ locationResetUnavailableTitle: "{name}을(를) 재설정할까요?",
+ locationResetUnavailableDescription: "드라이브가 연결되어 있지 않습니다. {path}의 파일은 그 드라이브에 남아 있으며, 다시 옮기기 전까지 라이브러리에 표시되지 않습니다.",
+ locationLeftBehind: "{path}의 파일은 그 드라이브에 남아 있습니다.",
+ dataStorage: "라이브러리 저장 공간",
+ manageStorage: "저장 공간 관리",
+ categoryImages: "이미지",
+ categoryVideos: "동영상",
+ categoryFineTunes: "파인튜닝",
+ itemCountOne: "1개 항목",
+ itemCount: "{count}개 항목",
+ tabsSection: "탭",
+ tabsDescription: "라이브러리에 표시할 탭을 선택합니다. 링크로 연 탭은 계속 표시됩니다.",
+ tabHidden: "숨김",
+ lastVisited: "마지막으로 본 탭",
+ },
tabs: {
accounts: "계정",
general: "일반",
@@ -2956,6 +3035,8 @@ export const ko = {
lastActivity: "최근 활동",
favorite: "즐겨찾기",
modified: "수정: {time}",
+ opened: "열람: {time}",
+ modifiedColumn: "수정한 날짜",
justNow: "방금",
},
size: {
@@ -2963,6 +3044,7 @@ export const ko = {
kilobytes: "{value} KB",
megabytes: "{value} MB",
gigabytes: "{value} GB",
+ terabytes: "{value} TB",
},
modelKind: {
lora: "LoRA",
@@ -2987,6 +3069,7 @@ export const ko = {
deleteVideo: "동영상 갤러리에서도 제거됩니다.",
deleteAudio: "오디오 갤러리에서도 제거됩니다.",
deleteSandbox: "이 파일을 만든 채팅에서도 제거됩니다.",
+ deleteModel: "모델이 디스크에서 영구적으로 삭제됩니다.",
unsavedTitle: "변경 사항이 저장되지 않았습니다",
unsavedDescription: "{reason} 다시 시도하거나 변경 사항을 버리고 파일을 닫으세요.",
keepEditing: "계속 편집",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index e92a8ee80f8..7991b8bba26 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -307,6 +307,85 @@ export const ptBR = {
panelFailed: "Não foi possível carregar esta seção.",
panelReload: "Recarregar",
},
+ library: {
+ layoutSection: "Layout",
+ cardSize: "Tamanho do cartão",
+ cardSizeDescription: "Quantos cartões cabem em uma linha.",
+ small: "Pequeno",
+ medium: "Médio",
+ large: "Grande",
+ imageLayout: "Cartões de imagem",
+ imageLayoutDescription: "Manter o formato de cada imagem ou cortá-las em quadrados iguais.",
+ masonry: "Formato original",
+ square: "Quadrado",
+ showCardDates: "Mostrar datas nos cartões",
+ showCardDatesDescription: "Mostra quando cada arquivo foi alterado pela última vez.",
+ browsingSection: "Navegação",
+ startTab: "Abrir em",
+ startTabDescription: "A aba em que a Biblioteca abre.",
+ suggested: "Sugeridos",
+ all: "Tudo",
+ sort: "Ordenar por",
+ sortDescription: "Ordem de arquivos e pastas. Sugeridos sempre mostra os mais recentes.",
+ recent: "Mais recentes",
+ oldest: "Mais antigos",
+ name: "Nome",
+ suggestedLimit: "Itens sugeridos",
+ suggestedLimitDescription: "Quantos arquivos recentes Sugeridos mostra.",
+ tabAuto: "Quando houver arquivos",
+ tabAlways: "Sempre",
+ contentSection: "Conteúdo",
+ contentDescription: "Escolha o que a Biblioteca mostra. Arquivos ocultos não são excluídos.",
+ showChatAttachments: "Anexos de chat",
+ showChatAttachmentsDescription: "Arquivos que você anexou aos chats.",
+ showChatToolFiles: "Arquivos de ferramentas do chat",
+ showChatToolFilesDescription: "Arquivos que o código e as ferramentas criaram nos chats.",
+ showGeneratedMedia: "Mídia gerada",
+ showGeneratedMediaDescription: "Imagens, vídeos e áudio das páginas Imagens, Vídeo e Áudio.",
+ showFineTunesDescription: "Modelos que você treinou ou exportou no Unsloth.",
+ deletingSection: "Exclusão",
+ confirmDelete: "Confirmar antes de excluir",
+ confirmDeleteDescription: "Perguntar antes de excluir arquivos e pastas da Biblioteca.",
+ reset: "Redefinir configurações da Biblioteca",
+ resetDescription: "Volta cada opção acima ao padrão.",
+ resetButton: "Redefinir",
+ resetDone: "Configurações da Biblioteca redefinidas",
+ storageSection: "Armazenamento",
+ storageDescription: "Abra uma categoria para ver os arquivos do maior para o menor e exclua o que não precisa mais.",
+ storageUsed: "{size} usados pela Biblioteca",
+ storageDisk: "{free} livres de {total} neste disco",
+ storageEmpty: "Ainda não há nada armazenado na Biblioteca.",
+ storageHidden: "{size} ocultos nas configurações de Conteúdo",
+ storageError: "Não foi possível ler o armazenamento da Biblioteca.",
+ locationsSection: "Arquivos no disco",
+ locationsDescription: "Onde o Unsloth guarda cada tipo de arquivo. As pastas da biblioteca são rótulos dentro do Unsloth, não pastas no disco. Ajustes finos e exportações ficam onde estão, pois o treinamento e os chats os encontram pelo caminho.",
+ locationUploads: "Envios da biblioteca",
+ locationExports: "Exportações",
+ revealFailed: "Não foi possível abrir o gerenciador de arquivos",
+ locationReset: "Redefinir",
+ locationMoveTitle: "Mover {name} para uma nova pasta",
+ locationMoveDescription: "Escolha qualquer pasta. Se ela já tiver arquivos, o Unsloth cria uma pasta própria dentro dela. Tudo o que já está aqui também é movido.",
+ locationMoveAction: "Mover para cá",
+ locationMoving: "Movendo {name}…",
+ locationMoved: "{name} movido",
+ locationMoveFailed: "Não foi possível mover {name}",
+ locationFree: "{free} livres nesta unidade",
+ locationUnavailable: "Indisponível. Reconecte a unidade ou redefina a pasta.",
+ locationResetUnavailableTitle: "Redefinir {name}?",
+ locationResetUnavailableDescription: "A unidade não está conectada. Os arquivos em {path} continuam nela e não aparecerão na Biblioteca até que você os mova de volta.",
+ locationLeftBehind: "Os arquivos em {path} continuam nessa unidade.",
+ dataStorage: "Armazenamento da biblioteca",
+ manageStorage: "Gerenciar armazenamento",
+ categoryImages: "Imagens",
+ categoryVideos: "Vídeos",
+ categoryFineTunes: "Fine-tunes",
+ itemCountOne: "1 item",
+ itemCount: "{count} itens",
+ tabsSection: "Abas",
+ tabsDescription: "Escolha quais abas a Biblioteca mostra. Uma aba aberta por um link continua aparecendo.",
+ tabHidden: "Oculta",
+ lastVisited: "Última visitada",
+ },
tabs: {
accounts: "Contas",
general: "Geral",
@@ -2990,6 +3069,8 @@ export const ptBR = {
lastActivity: "Última atividade",
favorite: "Favorito",
modified: "Modificado {time}",
+ opened: "Aberto {time}",
+ modifiedColumn: "Modificado",
justNow: "agora mesmo",
},
size: {
@@ -2997,6 +3078,7 @@ export const ptBR = {
kilobytes: "{value} KB",
megabytes: "{value} MB",
gigabytes: "{value} GB",
+ terabytes: "{value} TB",
},
modelKind: {
lora: "LoRA",
@@ -3021,6 +3103,7 @@ export const ptBR = {
deleteVideo: "Ele também é removido da sua galeria de Vídeo.",
deleteAudio: "Ele também é removido da sua galeria de Áudio.",
deleteSandbox: "Ele também é removido do chat que o criou.",
+ deleteModel: "Isso exclui o modelo do disco permanentemente.",
unsavedTitle: "Suas alterações não foram salvas",
unsavedDescription: "{reason} Tente novamente ou descarte suas alterações para fechar o arquivo.",
keepEditing: "Continuar editando",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index d867ae81662..ce446d2433f 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -307,6 +307,85 @@ export const ru = {
panelFailed: "Не удалось загрузить этот раздел.",
panelReload: "Перезагрузить",
},
+ library: {
+ layoutSection: "Вид",
+ cardSize: "Размер карточек",
+ cardSizeDescription: "Сколько карточек помещается в ряд.",
+ small: "Маленький",
+ medium: "Средний",
+ large: "Большой",
+ imageLayout: "Карточки изображений",
+ imageLayoutDescription: "Сохранять форму каждого изображения или обрезать до ровных квадратов.",
+ masonry: "Исходная форма",
+ square: "Квадрат",
+ showCardDates: "Показывать даты на карточках",
+ showCardDatesDescription: "Показывает, когда файл последний раз менялся.",
+ browsingSection: "Просмотр",
+ startTab: "Открывать на",
+ startTabDescription: "Вкладка, с которой открывается Библиотека.",
+ suggested: "Рекомендуемое",
+ all: "Все",
+ sort: "Сортировка",
+ sortDescription: "Порядок файлов и папок. Рекомендуемое всегда показывает самые новые.",
+ recent: "Сначала новые",
+ oldest: "Сначала старые",
+ name: "Имя",
+ suggestedLimit: "Элементы в рекомендуемом",
+ suggestedLimitDescription: "Сколько недавних файлов показывает Рекомендуемое.",
+ tabAuto: "Когда есть файлы",
+ tabAlways: "Всегда",
+ contentSection: "Содержимое",
+ contentDescription: "Выберите, что показывает Библиотека. Скрытые файлы не удаляются.",
+ showChatAttachments: "Вложения чатов",
+ showChatAttachmentsDescription: "Файлы, которые вы прикрепили к чатам.",
+ showChatToolFiles: "Файлы инструментов чата",
+ showChatToolFilesDescription: "Файлы, созданные кодом и инструментами в чатах.",
+ showGeneratedMedia: "Сгенерированные медиа",
+ showGeneratedMediaDescription: "Изображения, видео и аудио со страниц Изображения, Видео и Аудио.",
+ showFineTunesDescription: "Модели, которые вы обучили или экспортировали в Unsloth.",
+ deletingSection: "Удаление",
+ confirmDelete: "Подтверждать удаление",
+ confirmDeleteDescription: "Спрашивать перед удалением файлов и папок из Библиотеки.",
+ reset: "Сбросить настройки Библиотеки",
+ resetDescription: "Вернуть все параметры выше к значениям по умолчанию.",
+ resetButton: "Сбросить",
+ resetDone: "Настройки Библиотеки сброшены",
+ storageSection: "Хранилище",
+ storageDescription: "Откройте категорию, чтобы увидеть файлы от самых больших, и удалите ненужное.",
+ storageUsed: "Библиотека занимает {size}",
+ storageDisk: "Свободно {free} из {total} на этом диске",
+ storageEmpty: "В Библиотеке пока ничего нет.",
+ storageHidden: "{size} скрыто в настройках содержимого",
+ storageError: "Не удалось прочитать хранилище Библиотеки.",
+ locationsSection: "Файлы на диске",
+ locationsDescription: "Где Unsloth хранит файлы каждого типа. Папки библиотеки являются метками внутри Unsloth, а не папками на диске. Дообученные модели и экспорты остаются на месте: обучение и чаты находят их по пути.",
+ locationUploads: "Загрузки библиотеки",
+ locationExports: "Экспорт",
+ revealFailed: "Не удалось открыть файловый менеджер",
+ locationReset: "Сбросить",
+ locationMoveTitle: "Переместить {name} в новую папку",
+ locationMoveDescription: "Выберите любую папку. Если в ней уже есть файлы, Unsloth создаст внутри свою папку. Всё, что уже лежит здесь, тоже переместится.",
+ locationMoveAction: "Переместить сюда",
+ locationMoving: "Перемещение {name}…",
+ locationMoved: "{name}: перемещено",
+ locationMoveFailed: "Не удалось переместить {name}",
+ locationFree: "Свободно {free} на этом диске",
+ locationUnavailable: "Недоступно. Подключите диск снова или сбросьте папку.",
+ locationResetUnavailableTitle: "Сбросить {name}?",
+ locationResetUnavailableDescription: "Диск не подключен. Файлы в {path} останутся на нём и не появятся в библиотеке, пока вы не переместите их обратно.",
+ locationLeftBehind: "Файлы в {path} остаются на том диске.",
+ dataStorage: "Хранилище библиотеки",
+ manageStorage: "Управление хранилищем",
+ categoryImages: "Изображения",
+ categoryVideos: "Видео",
+ categoryFineTunes: "Файнтюны",
+ itemCountOne: "Элементов: 1",
+ itemCount: "Элементов: {count}",
+ tabsSection: "Вкладки",
+ tabsDescription: "Выберите, какие вкладки показывает Библиотека. Вкладка, открытая по ссылке, всё равно отображается.",
+ tabHidden: "Скрыта",
+ lastVisited: "Последняя открытая",
+ },
tabs: {
accounts: "Учётные записи",
general: "Общие",
@@ -2986,9 +3065,11 @@ export const ru = {
list: {
selectAll: "Выбрать все",
name: "Название",
- lastActivity: "Последнее изменение",
+ lastActivity: "Последняя активность",
favorite: "В избранном",
modified: "Изменено {time}",
+ opened: "Открыто {time}",
+ modifiedColumn: "Изменено",
justNow: "только что",
},
size: {
@@ -2996,6 +3077,7 @@ export const ru = {
kilobytes: "{value} КБ",
megabytes: "{value} МБ",
gigabytes: "{value} ГБ",
+ terabytes: "{value} ТБ",
},
modelKind: {
lora: "LoRA",
@@ -3020,6 +3102,7 @@ export const ru = {
deleteVideo: "Он также будет удалён из вашей галереи видео.",
deleteAudio: "Он также будет удалён из вашей галереи аудио.",
deleteSandbox: "Он также будет удалён из чата, в котором был создан.",
+ deleteModel: "Модель будет безвозвратно удалена с диска.",
unsavedTitle: "Изменения не сохранены",
unsavedDescription: "{reason} Повторите попытку или отмените изменения, чтобы закрыть файл.",
keepEditing: "Продолжить редактирование",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index c1c2297fdbf..b34d778460a 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -303,6 +303,85 @@ export const zhCN = {
panelFailed: "无法加载此部分。",
panelReload: "重新加载",
},
+ library: {
+ layoutSection: "布局",
+ cardSize: "卡片大小",
+ cardSizeDescription: "每行显示的卡片数量。",
+ small: "小",
+ medium: "中",
+ large: "大",
+ imageLayout: "图片卡片",
+ imageLayoutDescription: "保留每张图片的原始比例,或裁剪为统一的正方形。",
+ masonry: "原始比例",
+ square: "正方形",
+ showCardDates: "在卡片上显示日期",
+ showCardDatesDescription: "显示每个文件的最后修改时间。",
+ browsingSection: "浏览",
+ startTab: "默认打开",
+ startTabDescription: "打开资料库时显示的标签页。",
+ suggested: "推荐",
+ all: "全部",
+ sort: "排序方式",
+ sortDescription: "文件和文件夹的顺序。推荐始终显示最新内容。",
+ recent: "最新",
+ oldest: "最早",
+ name: "名称",
+ suggestedLimit: "推荐数量",
+ suggestedLimitDescription: "推荐中显示的最近文件数量。",
+ tabAuto: "有文件时",
+ tabAlways: "始终",
+ contentSection: "内容",
+ contentDescription: "选择资料库显示的内容。隐藏的文件不会被删除。",
+ showChatAttachments: "聊天附件",
+ showChatAttachmentsDescription: "你在聊天中附加的文件。",
+ showChatToolFiles: "聊天工具文件",
+ showChatToolFilesDescription: "聊天中代码和工具创建的文件。",
+ showGeneratedMedia: "生成的媒体",
+ showGeneratedMediaDescription: "来自图片、视频和音频页面的图片、视频和音频。",
+ showFineTunesDescription: "你在 Unsloth 中训练或导出的模型。",
+ deletingSection: "删除",
+ confirmDelete: "删除前确认",
+ confirmDeleteDescription: "从资料库删除文件和文件夹前进行确认。",
+ reset: "重置资料库设置",
+ resetDescription: "将以上所有选项恢复为默认值。",
+ resetButton: "重置",
+ resetDone: "资料库设置已重置",
+ storageSection: "存储空间",
+ storageDescription: "打开一个类别即可按大小从大到小查看文件,并删除不再需要的内容。",
+ storageUsed: "资料库已使用 {size}",
+ storageDisk: "此磁盘可用 {free},共 {total}",
+ storageEmpty: "资料库中还没有任何内容。",
+ storageHidden: "内容设置中已隐藏 {size}",
+ storageError: "无法读取资料库存储空间。",
+ locationsSection: "磁盘上的文件",
+ locationsDescription: "Unsloth 存放各类文件的位置。资料库文件夹只是 Unsloth 内的标签,不是磁盘上的文件夹。微调模型和导出文件保持原位,因为训练和对话会按路径引用它们。",
+ locationUploads: "资料库上传",
+ locationExports: "导出",
+ revealFailed: "无法打开文件管理器",
+ locationReset: "重置",
+ locationMoveTitle: "将{name}移到新文件夹",
+ locationMoveDescription: "可选择任意文件夹。如果其中已有文件,Unsloth 会在里面新建自己的文件夹。这里已有的文件也会一起移过去。",
+ locationMoveAction: "移到这里",
+ locationMoving: "正在移动{name}…",
+ locationMoved: "{name}已移动",
+ locationMoveFailed: "无法移动{name}",
+ locationFree: "此驱动器可用 {free}",
+ locationUnavailable: "不可用。请重新连接其驱动器,或重置该文件夹。",
+ locationResetUnavailableTitle: "要重置{name}吗?",
+ locationResetUnavailableDescription: "其驱动器未连接。{path} 中的文件会留在该驱动器上,在你将它们移回之前不会显示在资料库中。",
+ locationLeftBehind: "{path} 中的文件会留在该驱动器上。",
+ dataStorage: "资料库存储",
+ manageStorage: "管理存储",
+ categoryImages: "图片",
+ categoryVideos: "视频",
+ categoryFineTunes: "微调模型",
+ itemCountOne: "1 项",
+ itemCount: "{count} 项",
+ tabsSection: "标签页",
+ tabsDescription: "选择资料库显示哪些标签页。通过链接打开的标签页仍会显示。",
+ tabHidden: "隐藏",
+ lastVisited: "上次访问",
+ },
tabs: {
accounts: "账户",
general: "通用",
@@ -2869,6 +2948,8 @@ export const zhCN = {
lastActivity: "最近活动",
favorite: "已收藏",
modified: "修改于 {time}",
+ opened: "打开于 {time}",
+ modifiedColumn: "修改时间",
justNow: "刚刚",
},
size: {
@@ -2876,6 +2957,7 @@ export const zhCN = {
kilobytes: "{value} KB",
megabytes: "{value} MB",
gigabytes: "{value} GB",
+ terabytes: "{value} TB",
},
modelKind: {
lora: "LoRA",
@@ -2900,6 +2982,7 @@ export const zhCN = {
deleteVideo: "它也会从你的视频图库中移除。",
deleteAudio: "它也会从你的音频图库中移除。",
deleteSandbox: "它也会从创建它的聊天中移除。",
+ deleteModel: "这会将模型从磁盘中永久删除。",
unsavedTitle: "你的更改未保存",
unsavedDescription: "{reason} 请重试,或放弃更改以关闭文件。",
keepEditing: "继续编辑",
diff --git a/studio/frontend/tests/library-helpers.test.ts b/studio/frontend/tests/library-helpers.test.ts
index 736a6dd9a18..11fed5f3c7b 100644
--- a/studio/frontend/tests/library-helpers.test.ts
+++ b/studio/frontend/tests/library-helpers.test.ts
@@ -5,8 +5,6 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { readSrc } from "./helpers/kit.ts";
-
import {
embeddedBlobType,
itemVersion,
@@ -15,13 +13,27 @@ import {
streamsPreview,
uniqueFileNames,
} from "../src/features/library/file-name.ts";
+import { formatCardTime } from "../src/features/library/format.ts";
import { decodeNote, encodeNote } from "../src/features/library/note-text.ts";
import {
acquireObjectUrl,
cachedObjectUrlCount,
clearCachedObjectUrls,
} from "../src/features/library/object-url-cache.ts";
+import { parentFolder } from "../src/features/library/paths.ts";
import { isLoopbackHost, revealLabelFor } from "../src/features/library/reveal-label.ts";
+import {
+ DEFAULT_LIBRARY_SETTINGS,
+ type LibrarySortKey,
+ SORT_STATES,
+ compareBySort,
+ includedBySettings,
+ lastActivity,
+ migrateLibrarySettings,
+ nextSort,
+ sortParam,
+} from "../src/features/library/settings-store.ts";
+import { readSrc } from "./helpers/kit.ts";
function table<A extends unknown[], O>(name: string, run: (...args: A) => O, rows: [A, O][]) {
test(name, () => {
@@ -199,3 +211,117 @@ test("a hit is the same URL, and stays valid while anyone holds it", async () =>
assert.ok(!revoked.has(url));
second.release();
});
+
+// A Wednesday afternoon, local time. ICU may put a narrow no-break space before AM.
+const now = new Date(2026, 8, 23, 15, 0).getTime();
+const at = (month: number, day: number, year = 2026) => new Date(year, month, day, 10, 30).getTime();
+const cardTime = (ts: number, locale: Parameters<typeof formatCardTime>[1]) =>
+ formatCardTime(ts, locale, now).replace(/\s/g, " ");
+
+table("card times read in the app's language; a time ahead of this clock shows its date", cardTime, [
+ [[at(8, 22), "en"], "Yesterday"],
+ [[at(8, 22), "de"], "Gestern"],
+ [[at(8, 22), "fr"], "Hier"],
+ [[at(8, 22), "ja"], "昨日"],
+ [[at(8, 20), "en"], "Sunday"],
+ [[at(8, 20), "es"], "domingo"],
+ [[at(8, 23), "en"], "10:30 AM"],
+ [[at(7, 1), "en"], "Aug 1"],
+ [[at(7, 1, 2025), "en"], "Aug 1, 2025"],
+ [[at(8, 25), "en"], "Sep 25"],
+ [[at(0, 2, 2027), "en"], "Jan 2, 2027"],
+ [[Number.NaN, "en"], ""],
+]);
+
+table("the folder picker starts in the folder above, drive and share roots included", parentFolder, [
+ [["/Users/me/Pictures/Unsloth Images"], "/Users/me/Pictures"],
+ [["/Unsloth Images"], "/"],
+ [["/Users/me/Pictures/"], "/Users/me"],
+ [["D:\\Unsloth Images"], "D:\\"],
+ [["D:/Unsloth Images"], "D:/"],
+ [["C:\\Users\\me\\Unsloth"], "C:\\Users\\me"],
+ [["\\\\server\\share\\Unsloth Images"], "\\\\server\\share\\"],
+ [["\\\\server\\share\\a\\b"], "\\\\server\\share\\a"],
+ [["/"], undefined],
+ [["D:\\"], undefined],
+ [["\\\\server\\share"], undefined],
+ [["relative"], undefined],
+ [[""], undefined],
+]);
+
+const hidden = { ...DEFAULT_LIBRARY_SETTINGS, showChatAttachments: false, showFineTunes: false };
+const included = (id: string, more?: Partial<typeof hidden>) => includedBySettings(id, { ...hidden, ...more });
+
+table("sources hidden in settings drop out, Library uploads always stay", included, [
+ [["upload:abc"], true],
+ [["attachment:m:a"], false],
+ [["model:training:/runs/x"], false],
+ [["sandbox:t:out.csv"], true],
+ [["image:1", { showGeneratedMedia: false }], false],
+]);
+
+const sortable = [
+ { name: "b 10", updatedAt: 2, sizeBytes: 5 },
+ { name: "b 9", updatedAt: 3, sizeBytes: null },
+ { name: "a", updatedAt: 1, sizeBytes: 50 },
+];
+const sortedNames = (sort: keyof typeof SORT_STATES) =>
+ [...sortable].sort(compareBySort(SORT_STATES[sort])).map((item) => item.name);
+
+table("sort orders by recency, name and size", sortedNames, [
+ [["recent"], ["b 9", "b 10", "a"]],
+ [["oldest"], ["a", "b 10", "b 9"]],
+ [["name"], ["a", "b 9", "b 10"]],
+ [["size"], ["a", "b 10", "b 9"]],
+]);
+
+table("a column click flips its direction or starts a new column naturally", (key: LibrarySortKey) => nextSort(SORT_STATES.size, key), [
+ [["size"], { key: "size", desc: false }],
+ [["name"], { key: "name", desc: false }],
+ [["modified"], { key: "modified", desc: true }],
+]);
+
+table("last activity is the later of modified and opened", lastActivity, [
+ [[{ updatedAt: 5, openedAt: null }], 5],
+ [[{ updatedAt: 5, openedAt: 9 }], 9],
+ [[{ updatedAt: 9, openedAt: 5 }], 9],
+]);
+
+test("every column order has a ?sort value that reads back the same", () => {
+ for (const key of ["name", "modified", "size"] as const) {
+ for (const desc of [true, false]) assert.deepEqual(SORT_STATES[sortParam({ key, desc })], { key, desc });
+ }
+});
+
+test("the v1 media switch becomes one setting per tab", () => {
+ const migrated = migrateLibrarySettings({ mediaTabs: "always", sort: "name" }, 1);
+ assert.equal(migrated.mediaTabs, undefined);
+ assert.equal(migrated.sort, "name");
+ const media = { images: "always", videos: "always", audio: "always" };
+ assert.deepEqual(migrated.tabs, { ...DEFAULT_LIBRARY_SETTINGS.tabs, ...media });
+});
+
+test("an empty Fine-tunes tab hides by default, and for settings saved before that", () => {
+ assert.equal(DEFAULT_LIBRARY_SETTINGS.tabs.models, "auto");
+ const saved = { ...DEFAULT_LIBRARY_SETTINGS.tabs, models: "always" };
+ assert.equal((migrateLibrarySettings({ tabs: saved }, 2).tabs as typeof saved).models, "auto");
+ const hidden = { ...saved, models: "hidden" };
+ assert.equal((migrateLibrarySettings({ tabs: hidden }, 2).tabs as typeof saved).models, "hidden");
+});
+
+test("a card's date shows on hover, on keyboard focus and always on touch", () => {
+ const date = /"([^"]*)",\s*\)}\s*>\s*\{formatCardTime/.exec(readSrc("features/library/components/library-cards.tsx"))?.[1].split(" ");
+ for (const reveal of [
+ "group-hover/library-card:opacity-100",
+ "group-has-[:focus-visible]/library-card:opacity-100",
+ "pointer-coarse:opacity-100",
+ ]) {
+ assert.ok(date?.includes(reveal), reveal);
+ }
+});
+
+test("a moved folder's files are read again by the galleries and the Library", () => {
+ const move = /async function move\([\s\S]*?\n {2}\}\n/.exec(readSrc("features/settings/tabs/library-tab.tsx"))?.[0] ?? "";
+ assert.match(move, /notifyGalleryChanged\(location\.key\)/);
+ assert.match(move, /useLibraryStore\.getState\(\)[\s\S]*\.refresh\(\)/);
+});
diff --git a/studio/frontend/tests/library-state.test.ts b/studio/frontend/tests/library-state.test.ts
index 76879efcb01..edf8e01a0a3 100644
--- a/studio/frontend/tests/library-state.test.ts
+++ b/studio/frontend/tests/library-state.test.ts
@@ -203,6 +203,7 @@ function loadStore(
getAuthSessionEpoch: () => session.epoch,
},
"@/features/chat": {
+ deleteFineTunedModel: async () => {},
emitChatAttachmentDeleted: (event: unknown) => emitted.push(event),
},
"@/i18n": { translate: (key: string) => key },
diff --git a/studio/frontend/tests/settings-deep-open-requests.test.ts b/studio/frontend/tests/settings-deep-open-requests.test.ts
index 019aa1da18a..da934530805 100644
--- a/studio/frontend/tests/settings-deep-open-requests.test.ts
+++ b/studio/frontend/tests/settings-deep-open-requests.test.ts
@@ -133,13 +133,19 @@ test("consuming a scroll target clears it", () => {
assert.equal(store.getState().scrollTarget, null);
});
-test("the canvas network target lands on Chat and stays until Chat reads it", () => {
- reset();
- store.getState().openDialog("chat", { scrollTarget: "chat-canvas-network" });
- assert.equal(store.getState().activeTab, "chat");
- assert.equal(store.getState().scrollTarget, "chat-canvas-network");
- store.getState().setActiveTab("about");
- assert.equal(store.getState().scrollTarget, null);
+test("canvas network and Library storage land on their tab and stay until it reads them", () => {
+ for (const [tab, target, from] of [
+ ["chat", "chat-canvas-network", null],
+ ["library", "library-storage", "data"],
+ ] as const) {
+ reset();
+ if (from) store.getState().openDialog(from);
+ store.getState().openDialog(tab, { scrollTarget: target });
+ assert.equal(store.getState().activeTab, tab);
+ assert.equal(store.getState().scrollTarget, target);
+ store.getState().setActiveTab(from ?? "about");
+ assert.equal(store.getState().scrollTarget, null);
+ }
});
test("a deep link can provide a stable focus fallback", () => {
diff --git a/tests/studio/playwright_data_settings.py b/tests/studio/playwright_data_settings.py
index 40cd61fe495..ee7005fb15d 100644
--- a/tests/studio/playwright_data_settings.py
+++ b/tests/studio/playwright_data_settings.py
@@ -104,7 +104,8 @@ FIXTURE = """(() => {
} else if (url.pathname === '/api/chat/threads') {
if (fixture.listFail) { status = 503; body = { detail: 'Chat list unavailable' }; }
else body = { threads: fixture.rows };
- } else if (url.pathname === '/api/chat/projects') body = { projects: fixture.projects.filter(project => url.searchParams.get('include_archived') !== 'false' || !project.archived) };
+ } else if (url.pathname === '/api/library') body = { items: [], disk: null };
+ else if (url.pathname === '/api/chat/projects') body = { projects: fixture.projects.filter(project => url.searchParams.get('include_archived') !== 'false' || !project.archived) };
else if (url.pathname === '/api/chat/export') {
if (fixture.holdExport) await new Promise(resolve => { fixture.releaseExport = resolve; });
body = { threads: fixture.rows, messages: [], projects: [] };
diff --git a/tests/studio/playwright_settings_tabs.py b/tests/studio/playwright_settings_tabs.py
index d5ace07834d..2ba84dba308 100644
--- a/tests/studio/playwright_settings_tabs.py
+++ b/tests/studio/playwright_settings_tabs.py
@@ -38,6 +38,7 @@ TABS = [
"chat",
"voice",
"connections",
+ "library",
"data",
"api-keys",
"remote-lan",