Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: Library page for files, media and fine-tunes (#11770)
Michael Hand75177373803
diff --git a/studio/backend/core/inference/gallery_projects.py b/studio/backend/core/inference/gallery_projects.pyindex e7efd1bc709..83d1bd0ee5c 100644--- a/studio/backend/core/inference/gallery_projects.py+++ b/studio/backend/core/inference/gallery_projects.py@@ -11,10 +11,12 @@ from __future__ import annotationsimport contextlibimport os+import reimport shutilimport statimport uuidfrom pathlib import Path+from typing import BinaryIO, Iterator, Unionfrom loggers import get_logger@@ -58,14 +60,41 @@ def _sandbox_dir(project_id: str) -> str:return sandbox_real+UNSAFE_NAME_CHARS = r"\\/:*?\"<>|\x00-\x1f\x7f"+_BAD_NAME_RE = re.compile(f"[{UNSAFE_NAME_CHARS}]")+RESERVED_NAMES = frozenset(+ {"CON", "PRN", "AUX", "NUL"}+ | {f"{device}{index}" for device in ("COM", "LPT") for index in range(1, 10)}+)+++def _bad_name(name: str) -> bool:+ return (+ not name+ or name.startswith(".")+ or name.endswith((".", " "))+ or bool(_BAD_NAME_RE.search(name))+ or name.split(".", 1)[0].rstrip(" ").upper() in RESERVED_NAMES+ )+++def _reading(source: Union[Path, BinaryIO]) -> Iterator[BinaryIO]:+ """The bytes to copy: an open file as it is, from where it stands, or a path opened here."""+ if hasattr(source, "read"):+ yield source # type: ignore[misc]+ return+ with open(source, "rb") as handle:+ yield handle++def _tmp_name(name: str) -> str:# Unique per call: two adds of one item can run at once in this process.return f".{name}.tmp-{uuid.uuid4().hex}"-def _copy_with_dir_fd(source: Path, sandbox: str, folder: str) -> bool:+def _copy_with_dir_fd(source: Union[Path, BinaryIO], sandbox: str, folder: str, name: str) -> bool:"""Copy into ``sandbox/folder`` by descriptor; returns whether it was already there."""- name = source.namesandbox_fd = os.open(sandbox, _DIR_FLAGS)try:try:@@ -92,7 +121,7 @@ def _copy_with_dir_fd(source: Path, sandbox: str, folder: str) -> bool:dir_fd = folder_fd,)try:- with os.fdopen(out, "wb") as dst, open(source, "rb") as src:+ with os.fdopen(out, "wb") as dst, _reading(source) as src:shutil.copyfileobj(src, dst)os.rename(tmp, name, src_dir_fd = folder_fd, dst_dir_fd = folder_fd)except BaseException:@@ -104,22 +133,26 @@ def _copy_with_dir_fd(source: Path, sandbox: str, folder: str) -> bool:return False-def _copy_by_path(source: Path, sandbox: str, folder: str) -> bool:+def _copy_by_path(source: Union[Path, BinaryIO], sandbox: str, folder: str, name: str) -> bool:"""Fallback without dir_fd support (Windows): resolve the folder and re-check containment."""target = Path(sandbox) / foldertarget.mkdir(exist_ok = True)real = os.path.realpath(target)if os.path.dirname(real) != sandbox:raise PermissionError(f"{target} resolves outside the project sandbox")- dest = Path(real) / source.name+ dest = Path(real) / nametry:if not dest.is_symlink() and dest.is_file():return Trueexcept OSError:pass- tmp = Path(real) / _tmp_name(source.name)+ tmp = Path(real) / _tmp_name(name)try:- shutil.copyfile(source, tmp)+ if isinstance(source, Path):+ shutil.copyfile(source, tmp)+ else:+ with open(tmp, "xb") as dst:+ shutil.copyfileobj(source, dst)# Without dir_fd the folder can be swapped after the check; check again before the rename.if os.path.realpath(tmp.parent) != real:raise PermissionError(f"{target} moved outside the project sandbox")@@ -131,13 +164,26 @@ def _copy_by_path(source: Path, sandbox: str, folder: str) -> bool:return False-def copy_into_project(source: Path, project_id: str, folder: str) -> dict[str, object]:+def copy_into_project(+ source: Union[Path, BinaryIO],+ project_id: str,+ folder: str,+ name: str | None = None,+) -> dict[str, object]:"""Copy ``source`` into the project's ``folder`` and return ``{"path", "already"}``.- Keyed by the gallery id, so a second add is a no-op. Written via a temp file so a failed copy- leaves nothing behind. Refuses a ``folder`` that leads outside the sandbox. Raises- ProjectNotFound or OSError."""+ ``source`` is a path, or a file already open (then ``name`` is required): a caller that checked+ the file it opened hands over that descriptor rather than a name that can be swapped since.+ Keyed by the file name (the gallery id unless ``name`` is given), so a second add is a no-op.+ Written via a temp file so a failed copy leaves nothing behind. Refuses a ``folder`` that leads+ outside the sandbox. Raises ProjectNotFound, ValueError for a bad ``name``, or OSError."""+ if name is None:+ if not isinstance(source, Path):+ raise ValueError("An open file needs a name to be copied as.")+ name = source.name+ if _bad_name(name):+ raise ValueError(f"Bad file name: {name!r}")sandbox = _sandbox_dir(project_id)copy = _copy_with_dir_fd if _USE_DIR_FD else _copy_by_path- already = copy(source, sandbox, folder)- return {"path": str(Path(sandbox) / folder / source.name), "already": already}+ already = copy(source, sandbox, folder, name)+ return {"path": str(Path(sandbox) / folder / name), "already": already}diff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.pyindex 0e5a56e5f7f..821411847d8 100644--- a/studio/backend/core/inference/image_gallery.py+++ b/studio/backend/core/inference/image_gallery.py@@ -136,7 +136,9 @@ def _read_meta(path: Path, *, strict_io: bool = False) -> Optional[dict[str, Anytry:with Image.open(path) as im:- raw = im.text.get(_META_KEY) # type: ignore[attr-defined]+ # _png_bytes writes the chunk before IDAT, so the header parse has it; im.text would+ # decode every pixel looking for chunks after IDAT.+ raw = im.info.get(_META_KEY) or im.text.get(_META_KEY) # type: ignore[attr-defined]except OSError as exc:if strict_io and exc.errno not in (None, errno.ENOENT):raisediff --git a/studio/backend/core/inference/video_gallery.py b/studio/backend/core/inference/video_gallery.pyindex 1deee09c208..741e18bb430 100644--- a/studio/backend/core/inference/video_gallery.py+++ b/studio/backend/core/inference/video_gallery.py@@ -17,7 +17,7 @@ import threadingimport uuidfrom collections.abc import Callablefrom pathlib import Path-from typing import Any, Optional+from typing import Any, BinaryIO, Optional, Unionfrom core.inference import gallery_flagsfrom loggers import get_logger@@ -198,26 +198,50 @@ def thumbnail(video_id: str) -> Optional[bytes]:path = owned_video_path(video_id)if path is None:return None- return _thumbnail_webp(path)+ return first_frame_webp(path)-def _thumbnail_webp(path: Path) -> bytes:+def first_frame_webp(+ source: Union[Path, BinaryIO],+ width: int = _THUMBNAIL_WIDTH,+ *,+ container: Optional[str] = None,+ max_pixels: Optional[int] = None,+ max_height: Optional[int] = None,+) -> bytes:+ """The first frame of a clip (a file or an open binary stream), at most `width` wide and+ `max_height` tall (four widths unless given), as WebP.++ ``container`` forces the demuxer instead of probing for one, and then nothing but the stream+ itself is read: a probed HLS or concat playlist names other files to open. ``max_pixels``+ refuses a frame larger than that before it is decoded."""import io+try:import avfrom PIL import Imageexcept Exception as exc: # noqa: BLE001 -- a missing decoder dependency makes thumbnails unavailableraise RuntimeError("Thumbnail generation needs the 'av' and 'Pillow' packages.") from exc+ if isinstance(source, Path):+ target, protocols = str(source), "file"+ else:+ target, protocols = source, "none"+ options = {"protocol_whitelist": protocols} if container else {}try:- with av.open(str(path)) as src:+ with av.open(target, format = container, options = options) as src:if not src.streams.video:raise RuntimeError("Thumbnail generation failed: the clip has no video stream.")- frame = next(src.decode(src.streams.video[0]), None)+ stream = src.streams.video[0]+ if max_pixels is not None:+ if stream.width * stream.height > max_pixels:+ raise RuntimeError(f"{stream.width}x{stream.height} is too large to thumbnail.")+ stream.codec_context.options = {"max_pixels": str(max_pixels)}+ frame = next(src.decode(stream), None)if frame is None:raise RuntimeError("Thumbnail generation failed: the clip has no decodable frames.")image = frame.to_image()- if image.width > _THUMBNAIL_WIDTH:- scale = _THUMBNAIL_WIDTH / image.width+ scale = min(1, width / image.width, (max_height or width * 4) / image.height)+ if scale < 1:image = image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))),Image.LANCZOS,diff --git a/studio/backend/core/library.py b/studio/backend/core/library.pynew file mode 100644index 00000000000..c1515111753--- /dev/null+++ b/studio/backend/core/library.py@@ -0,0 +1,1337 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""One listing over every place a Studio file can live.++Sources, each with its own id prefix so an item id says where its bytes are:++- ``upload:<id>`` a file uploaded straight into the Library+- ``attachment:<message_id>:<attachment_id>`` a file attached to a chat message+- ``image:<id>`` an image from the Images page gallery+- ``sandbox:<session_id>:<relative path>`` a file a chat tool wrote into its sandbox+- ``video:<id>`` a clip from the Video page gallery+- ``audio:<id>`` a clip from the Audio page's TTS gallery+- ``model:<training|exported>:<path>`` a fine-tuned model under outputs/ or exports/ (no bytes:+ a model is a directory, opened in chat instead)++The message and session ids are URL-encoded, since any string can be one and a colon would end it.++Bytes are always served by the source's own route (``fileUrl``); the Library only lists, deletes+and layers its overlay (name, favorite, folder) on top.+"""++from __future__ import annotations++import functools+import hashlib+import importlib+import io+import mimetypes+import os+import re+import stat+import threading+import time+import uuid+import zlib+from collections import OrderedDict+from datetime import datetime+from pathlib import Path+from types import ModuleType+from typing import BinaryIO, Callable, NamedTuple, Optional, Union+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.path_utils import is_path_within, same_path+from utils.paths.storage_roots import account_path++logger = get_logger(__name__)++_UPLOAD_ID_RE = re.compile(r"^[a-f0-9]{32}$")+_PROJECT_SESSION_PREFIX = "project-"+++def _to_ms(value: object) -> int:+ """Sources store seconds or milliseconds; the Library speaks milliseconds."""+ try:+ number = float(value) # type: ignore[arg-type]+ except (TypeError, ValueError):+ # Video and audio records keep ISO-8601 ("2026-09-25T10:00:00Z").+ try:+ return int(datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp() * 1000)+ except ValueError:+ return 0+ return int(number if number > 1e12 else number * 1000)+++def _named_for_type(name: str, content_type: str) -> str:+ """A pasted image or clip is named "Chat image"; the download needs its format's suffix."""+ if Path(name).suffix or not content_type.startswith(("image/", "audio/", "video/")):+ return name+ suffix = next(+ (ext for ext, known in content_types().items() if known == content_type), None+ ) or mimetypes.guess_extension(content_type)+ return f"{name}{suffix}" if suffix else name+++def _item(+ item_id: str,+ *,+ name: str,+ source: str,+ content_type: str,+ size_bytes: Optional[int],+ created_at: int,+ file_url: str,+ thread_id: Optional[str] = None,+ thread_title: Optional[str] = None,+ text_only: bool = False,+ model: Optional[dict] = None,+ archived: bool = False,+ fingerprint: Optional[str] = None,+) -> dict:+ return {+ "id": item_id,+ "name": name,+ # The source's own name, which a rename leaves alone, so the type never follows it.+ "fileName": name,+ "source": source,+ "contentType": content_type,+ "sizeBytes": size_bytes,+ "createdAt": created_at,+ "updatedAt": created_at,+ "fileUrl": file_url,+ "threadId": thread_id,+ "threadTitle": thread_title,+ "textOnly": text_only,+ "model": model,+ "archived": archived,+ "_fingerprint": fingerprint,+ }+++def _fingerprint(info: os.stat_result) -> str:+ """Which file a path-derived id (``sandbox:``, ``model:``) found: its inode (file id on Windows)+ and birth time where the OS keeps one, so an edit in place keeps it and a path made again does+ not. Not the device, which a remount changes. Linux keeps no birth time and ext4 reuses inodes,+ so there a file recreated at once can pass for the old one."""+ birth = getattr(info, "st_birthtime", None)+ if birth is None and os.name == "nt":+ birth = info.st_ctime+ return str(info.st_ino) if birth is None else f"{info.st_ino}:{birth!r}"+++def uploads_dir() -> Path:+ return ensure_dir(account_path("library"))+++def upload_path(upload_id: str) -> Optional[Path]:+ if not _UPLOAD_ID_RE.match(upload_id):+ return None+ return uploads_dir() / upload_id+++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"+ 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)+ return library_db.insert_upload(upload_id, name, content_type, size)+ except BaseException:+ tmp_path.unlink(missing_ok = True)+ final_path.unlink(missing_ok = True)+ raise+++def _verify_native(lease: str, *, consume: bool):+ from utils.native_path_leases import verify_native_path_lease++ grant = verify_native_path_lease(+ lease,+ operation = "attach",+ expected_kind = "attachment",+ expected_path_type = "file",+ consume = consume,+ )+ account_path(str(grant.canonical_path))+ return grant+++def check_native_upload(lease: str) -> tuple[str, int]:+ """(name, size) of a desktop drop, its grant checked but not spent, so a batch can check all."""+ grant = _verify_native(lease, consume = False)+ return grant.canonical_path.name, os.stat(grant.canonical_path).st_size+++def open_native_upload(lease: str):+ """(name, content type, binary handle) of a desktop drop: the app signs the path the OS handed+ it, never the webview, and the grant is spent here before a byte is read."""+ grant = _verify_native(lease, consume = True)+ name = grant.canonical_path.name+ # Opened once, and the file opened must be the one the grant checked: the name can be+ # swapped for a link to outside the account's workspace in between.+ try:+ handle = _open_regular(str(grant.canonical_path))+ except LookupError:+ raise ValueError("The dropped file changed after it was checked.") from None+ info = os.fstat(handle.fileno())+ identity = (grant.device_id, grant.file_id)+ if (None not in identity and (info.st_dev, info.st_ino) != identity) or (+ grant.size_bytes is not None and info.st_size != grant.size_bytes+ ):+ handle.close()+ raise ValueError("The dropped file changed after it was checked.")+ return name, _guess_type(name), handle+++_upload_lock = threading.Lock()+++def _swap_in(path: Path, data: bytes) -> None:+ """Replace the file whole: staged beside it and renamed over, so a failed write leaves it be."""+ tmp_path = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")+ try:+ tmp_path.write_bytes(data)+ os.replace(tmp_path, path)+ except BaseException:+ tmp_path.unlink(missing_ok = True)+ raise+++def write_upload_text(+ upload_id: str,+ text: str,+ encoding: str = "utf-8",+) -> 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:+ return False+ data = text.encode(encoding)+ with _upload_lock:+ 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+ # upload can be 512 MiB. Where links are not supported, it is held in memory as before.+ kept, previous = None, None+ if path.exists():+ kept = path.with_name(f".{upload_id}.{uuid.uuid4().hex}.tmp")+ try:+ os.link(path, kept)+ except OSError:+ kept, previous = None, path.read_bytes()+ try:+ _swap_in(path, data)+ library_db.touch_upload(upload_id, len(data))+ except BaseException:+ if kept is not None:+ os.replace(kept, path)+ elif previous is not None:+ _swap_in(path, previous)+ raise+ finally:+ if kept is not None:+ kept.unlink(missing_ok = True)+ return True+++_LEFTOVER_AGE_SECONDS = 3600+_swept_at: dict[str, float] = {}+++def _sweep_leftovers() -> None:+ """Clear what a crash left in the uploads folder, at most once an hour per account. A delete+ that stopped between setting its file aside and dropping the row put the file back instead:+ the row still lists it."""+ directory = uploads_dir()+ now = time.time()+ if now - _swept_at.get(str(directory), 0) < _LEFTOVER_AGE_SECONDS:+ return+ _swept_at[str(directory)] = now+ with _upload_lock:+ with os.scandir(directory) as entries:+ leftovers = [+ entry+ for entry in entries+ if entry.name.startswith(".") and entry.name.endswith((".tmp", ".deleting"))+ ]+ for entry in leftovers:+ try:+ info = entry.stat(follow_symlinks = False)+ if not stat.S_ISREG(info.st_mode) or now - info.st_mtime < _LEFTOVER_AGE_SECONDS:+ continue+ upload_id = entry.name[1 : -len(".deleting")]+ if (+ entry.name.endswith(".deleting")+ and _UPLOAD_ID_RE.match(upload_id)+ and library_db.get_upload(upload_id) is not None+ and not (directory / upload_id).exists()+ ):+ os.replace(entry.path, directory / upload_id)+ else:+ os.unlink(entry.path)+ except OSError:+ logger.debug("library.leftover_sweep_failed: %s", entry.name, exc_info = True)+++def _upload_items() -> list[dict]:+ try:+ _sweep_leftovers()+ except OSError:+ logger.debug("library.leftover_sweep_failed", exc_info = True)+ items = []+ for upload in library_db.list_uploads():+ item = _item(+ f"upload:{upload['id']}",+ name = upload["name"],+ source = "uploaded",+ content_type = upload["contentType"],+ size_bytes = upload["sizeBytes"],+ created_at = upload["createdAt"],+ file_url = f"/api/library/uploads/{upload['id']}/file",+ )+ item["updatedAt"] = upload["updatedAt"]+ items.append(item)+ return items+++def _attachment_id(message_id: str, attachment_id: str) -> str:+ """The item id of a chat attachment. A message id can be any string, so it is encoded: the+ attachment id is what follows its first colon."""+ return f"attachment:{quote(message_id, safe = '')}:{attachment_id}"+++def _attachment_ref(ref: str) -> tuple[str, str]:+ """The message and attachment ids an ``attachment:`` item id's ref names."""+ message, _, attachment = ref.partition(":")+ return unquote(message), attachment+++def _attachment_items() -> list[dict]:+ from storage.studio_db import list_chat_attachments++ items = []+ for attachment in list_chat_attachments():+ content_type = str(attachment.get("contentType") or "").split(";", 1)[0].strip().lower()+ has_bytes = attachment.get("type") in ("image", "audio") or content_type.startswith(+ ("image/", "audio/", "video/")+ )+ message_id, attachment_id = attachment["messageId"], attachment["id"]+ items.append(+ _item(+ _attachment_id(message_id, attachment_id),+ name = _named_for_type(attachment.get("name") or "Attachment", content_type),+ source = "uploaded",+ content_type = content_type or "application/octet-stream",+ size_bytes = attachment.get("sizeBytes"),+ created_at = _to_ms(attachment.get("createdAt")),+ file_url = f"/api/chat/attachments/{quote(message_id, safe = '')}/{quote(attachment_id, safe = '')}/file",+ thread_id = attachment.get("threadId"),+ thread_title = attachment.get("threadTitle"),+ text_only = not has_bytes,+ )+ )+ return items+++_NAME_BREAK_RE = re.compile(f"[{UNSAFE_NAME_CHARS}\\s]+")+++def _prompt_name(prompt: str, fallback: str, extension: str) -> str:+ cleaned = _NAME_BREAK_RE.sub(" ", prompt).strip()+ if len(cleaned) > 60:+ cleaned = cleaned[:60].rsplit(" ", 1)[0] or cleaned[:60]+ return f"{cleaned or fallback}.{extension}"+++class _Gallery(NamedTuple):+ module: ModuleType+ records: Callable+ resolve: Callable+ label: str # what an item with no prompt is called+ extension: str+ content_type: str+ folder: str # the project folder Add to project copies into+++_GALLERIES = {+ "image": ("image_gallery", "list_images", "image_path", "Image", "png", "image/png", "images"),+ "video": ("video_gallery", "list_videos", "video_path", "Video", "mp4", "video/mp4", "videos"),+ "audio": ("audio_gallery", "list_audio", "audio_path", "Audio", "wav", "audio/wav", "audio"),+}+++def _gallery(kind: str) -> _Gallery:+ module_name, records, resolve, *rest = _GALLERIES[kind]+ module = importlib.import_module(f"core.inference.{module_name}")+ return _Gallery(module, getattr(module, records), getattr(module, resolve), *rest)+++def _gallery_items(kind: str) -> list[dict]:+ gallery = _gallery(kind)+ items = []+ for archived in (False, True):+ for record in gallery.records(archived = archived):+ path = gallery.resolve(record["id"])+ try:+ size = path.stat().st_size if path is not None else None+ except OSError:+ size = None+ items.append(+ _item(+ f"{kind}:{record['id']}",+ name = _prompt_name(+ str(record.get("prompt") or ""), gallery.label, gallery.extension+ ),+ source = "generated",+ content_type = gallery.content_type,+ size_bytes = size,+ created_at = _to_ms(record.get("created_at")),+ file_url = record["url"],+ archived = archived,+ )+ )+ return items+++def _image_items() -> list[dict]:+ return _gallery_items("image")+++def _video_items() -> list[dict]:+ return _gallery_items("video")+++def _audio_items() -> list[dict]:+ return _gallery_items("audio")+++MODEL_CONTENT_TYPE = "application/x-unsloth-model"+++def _tree_stats(path: Path) -> tuple[int, float, os.stat_result]:+ """(total bytes, newest mtime, the path's own stat) of a model file or directory, symlinks+ not followed."""+ info = path.stat()+ if stat.S_ISREG(info.st_mode):+ return info.st_size, info.st_mtime, info+ total, newest = 0, info.st_mtime+ for root, _dirs, files in os.walk(path):+ for name in files:+ try:+ entry = os.lstat(os.path.join(root, name))+ except OSError:+ continue+ total += entry.st_size+ newest = max(newest, entry.st_mtime)+ return total, newest, info+++def _model_items() -> list[dict]:+ from utils.models.model_config import (+ get_base_model_from_checkpoint,+ scan_exported_models,+ scan_trained_models,+ )+ from utils.paths.storage_roots import exports_root, outputs_root++ found = [+ (name, path, "training", model_type, None)+ for name, path, model_type in scan_trained_models(str(outputs_root()))+ ]+ found.extend(+ (name, path, "exported", export_type, base_model)+ for name, path, export_type, base_model in scan_exported_models(str(exports_root()))+ )+ items = []+ for name, path, origin, model_type, base_model in found:+ try:+ size, modified, info = _tree_stats(Path(path))+ except OSError:+ continue+ if base_model is None and origin == "training":+ try:+ base_model = get_base_model_from_checkpoint(path)+ except Exception:+ base_model = None+ items.append(+ _item(+ f"model:{origin}:{path}",+ name = name,+ source = "generated",+ content_type = MODEL_CONTENT_TYPE,+ size_bytes = size,+ created_at = _to_ms(modified),+ file_url = "",+ model = {+ "path": path,+ "origin": origin,+ "exportType": model_type,+ "baseModel": base_model,+ },+ fingerprint = _fingerprint(info),+ )+ )+ return items+++def _sandbox_sessions() -> list[tuple[str, Optional[str], Optional[str]]]:+ """(session id, thread id, title) for every chat or project that can own a sandbox."""+ from storage.studio_db import get_connection++ conn = get_connection()+ try:+ threads = conn.execute(+ "SELECT id, title FROM chat_threads WHERE project_id IS NULL"+ ).fetchall()+ projects = conn.execute("SELECT id, name, root_path FROM chat_projects").fetchall()+ finally:+ conn.close()+ return [(row["id"], row["id"], row["title"]) for row in threads] + [+ (f"{_PROJECT_SESSION_PREFIX}{row['id']}", None, row["name"])+ for row in projects+ if _studio_project_root(row["root_path"])+ ]+++def _studio_project_root(root_path: Optional[str]) -> bool:+ """Whether a project works in Studio's own workspace (every project is given a folder there),+ not a folder of the user's own, whose files are not Studio's."""+ from utils.paths.storage_roots import project_workspaces_root++ if not root_path:+ return True+ return is_path_within(+ os.path.realpath(os.path.expanduser(root_path)),+ os.path.realpath(project_workspaces_root()),+ )+++def _sandbox_session_eligible(session_id: str) -> bool:+ """Whether one session id is among ``_sandbox_sessions``, asked of that row alone."""+ from storage.studio_db import get_connection++ conn = get_connection()+ try:+ if conn.execute(+ "SELECT 1 FROM chat_threads WHERE id = ? AND project_id IS NULL", (session_id,)+ ).fetchone():+ return True+ if not session_id.startswith(_PROJECT_SESSION_PREFIX):+ return False+ row = conn.execute(+ "SELECT root_path FROM chat_projects WHERE id = ?",+ (session_id[len(_PROJECT_SESSION_PREFIX) :],),+ ).fetchone()+ finally:+ conn.close()+ return row is not None and _studio_project_root(row["root_path"])+++def _sandbox_names(directory: str) -> frozenset:+ """The files one sandbox's listing holds, remembered with the listing, so a grid of cards walks+ a sandbox once rather than once a card."""+ from routes.inference import _sandbox_listing_names+ return _LISTING.get(+ ("names", directory),+ lambda: frozenset(_sandbox_listing_names(directory) if os.path.isdir(directory) else []),+ _SANDBOX_TTL_SECONDS,+ )+++def _sandbox_path(ref: str) -> str:+ """The file a ``sandbox:`` id names, by the listing walk's rules: an eligible session, servable+ segments, no dotfile, not too deep, no link on the way, and within the walk's cap. Checked for+ this one file, so a card never lists every chat. LookupError otherwise."""+ from core.inference.tools import (+ _MAX_SANDBOX_PATH_SEGMENTS,+ _servable_segment,+ _user_path_parts,+ resolve_sandbox_workdir,+ )++ session, _, relative = ref.partition(":")+ session_id = unquote(session)+ parts = relative.split("/")+ if not relative or any(part.startswith(".") or not _servable_segment(part) for part in parts):+ raise LookupError(ref)+ if not _sandbox_session_eligible(session_id):+ raise LookupError(ref)+ directory = os.path.realpath(resolve_sandbox_workdir(session_id))+ if len(_user_path_parts(parts, directory)) > _MAX_SANDBOX_PATH_SEGMENTS:+ raise LookupError(ref)+ path = os.path.join(directory, *parts)+ if not same_path(os.path.realpath(path), path) or not is_path_within(path, directory):+ raise LookupError(ref)+ # Past the listing's cap, or skipped by its walk: never listed, so not reachable by id either.+ if relative not in _sandbox_names(directory):+ raise LookupError(ref)+ return path+++def _open_regular(path: str) -> BinaryIO:+ """`path` opened once and checked by its descriptor; LookupError unless it is a regular file.++ Another process can swap a checked name for a link before it is opened again. O_NOFOLLOW where+ the OS has it, then the path must still resolve to itself and to this same file, which also+ refuses a parent swapped for a link (the only way in on Windows)."""+ # O_NONBLOCK: a FIFO swapped in for the file would otherwise hang here before the S_ISREG check.+ flags = (+ os.O_RDONLY+ | getattr(os, "O_NOFOLLOW", 0)+ | getattr(os, "O_BINARY", 0)+ | getattr(os, "O_NONBLOCK", 0)+ )+ try:+ fd = os.open(path, flags)+ except OSError:+ raise LookupError(path) from None+ try:+ info = os.fstat(fd)+ checked = os.stat(path, follow_symlinks = False)+ if (+ not stat.S_ISREG(info.st_mode)+ or not same_path(os.path.realpath(path), path)+ or (checked.st_dev, checked.st_ino) != (info.st_dev, info.st_ino)+ ):+ raise LookupError(path)+ except OSError:+ os.close(fd)+ raise LookupError(path) from None+ except BaseException:+ os.close(fd)+ raise+ return os.fdopen(fd, "rb")+++def _open_sandbox_file(ref: str) -> tuple[BinaryIO, str]:+ """(open file, path) for a ``sandbox:`` id, opened once and checked by its descriptor: tool+ code runs here."""+ path = _sandbox_path(ref)+ try:+ return _open_regular(path), path+ except LookupError:+ raise LookupError(ref) from None+++def _delete_sandbox_file(ref: str, expected: Optional[str] = None) -> bool:+ """Unlink the file an id names, only while its name is still the file checked, and with+ `expected`, only while it is the file listed with that fingerprint."""+ from core.inference.gallery_projects import _DIR_FLAGS, _USE_DIR_FD++ try:+ handle, path = _open_sandbox_file(ref)+ except LookupError:+ return False+ parent, name = os.path.split(path)+ with handle:+ info = os.fstat(handle.fileno())+ if expected is not None and _fingerprint(info) != expected:+ raise ItemChanged("This file changed since the Library listed it.")+ if _USE_DIR_FD:+ dir_fd = os.open(parent, _DIR_FLAGS)+ try:+ entry = os.stat(name, dir_fd = dir_fd, follow_symlinks = False)+ if (entry.st_dev, entry.st_ino) != (info.st_dev, info.st_ino):+ return False+ os.unlink(name, dir_fd = dir_fd)+ finally:+ os.close(dir_fd)+ return True+ os.unlink(path)+ return True+++def _sandbox_items() -> list[dict]:+ from core.inference.tools import resolve_sandbox_workdir+ from routes.inference import _sandbox_listing_names++ items = []+ generation = _LISTING.generation+ for session_id, thread_id, title in _sandbox_sessions():+ try:+ directory = os.path.realpath(resolve_sandbox_workdir(session_id))+ names = _sandbox_listing_names(directory) if os.path.isdir(directory) else []+ except Exception:+ logger.debug("library.sandbox_listing_failed", exc_info = True)+ continue+ _LISTING.put(("names", directory), frozenset(names), generation)+ for relative in names:+ if os.path.basename(relative).startswith("."):+ continue+ try:+ info = os.stat(os.path.join(directory, relative))+ except OSError:+ continue+ items.append(+ _item(+ f"sandbox:{quote(session_id, safe = '')}:{relative}",+ name = os.path.basename(relative),+ source = "generated",+ content_type = _guess_type(relative),+ size_bytes = info.st_size,+ created_at = info.st_mtime_ns // 1_000_000,+ file_url = f"/api/inference/sandbox/{quote(session_id, safe = '')}/{quote(relative)}",+ thread_id = thread_id,+ thread_title = title,+ fingerprint = _fingerprint(info),+ )+ )+ return items+++_CONTENT_TYPES = {+ f".{extension}": content_type+ for content_type, extensions in (+ ("image/svg+xml", "svg"),+ ("image/tiff", "tif tiff"),+ ("image/x-icon", "ico"),+ ("image/heic", "heic"),+ ("image/heif", "heif"),+ ("audio/mpeg", "mp3"),+ ("audio/wav", "wav"),+ ("audio/ogg", "ogg oga opus"),+ ("audio/flac", "flac"),+ ("audio/mp4", "m4a"),+ ("audio/aac", "aac"),+ ("audio/webm", "weba"),+ ("video/mp4", "mp4 m4v"),+ ("video/quicktime", "mov"),+ ("video/webm", "webm"),+ ("video/x-matroska", "mkv"),+ ("video/x-msvideo", "avi"),+ ("video/ogg", "ogv"),+ ("application/pdf", "pdf"),+ ("text/plain", "txt log toml ini sql"),+ ("text/markdown", "md markdown"),+ ("text/csv", "csv"),+ ("text/tab-separated-values", "tsv"),+ ("application/json", "json"),+ ("application/jsonl", "jsonl"),+ ("application/xml", "xml"),+ ("text/yaml", "yaml yml"),+ ("text/html", "html htm"),+ ("text/css", "css"),+ ("text/javascript", "js mjs cjs jsx"),+ ("text/typescript", "ts tsx mts cts"),+ ("text/x-python", "py"),+ ("application/x-ipynb+json", "ipynb"),+ ("text/x-shellscript", "sh"),+ ("application/rtf", "rtf"),+ ("application/msword", "doc"),+ ("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx"),+ ("application/vnd.ms-excel", "xls"),+ ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx"),+ ("application/vnd.ms-powerpoint", "ppt"),+ ("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx"),+ ("application/vnd.oasis.opendocument.text", "odt"),+ ("application/vnd.oasis.opendocument.spreadsheet", "ods"),+ ("application/vnd.oasis.opendocument.presentation", "odp"),+ ("application/epub+zip", "epub"),+ ("application/zip", "zip"),+ ("application/gzip", "gz"),+ ("application/x-tar", "tar"),+ ("application/vnd.apache.parquet", "parquet"),+ ("application/octet-stream", "safetensors gguf"),+ )+ for extension in extensions.split()+}++_MEDIA_TYPE_RE = re.compile(r"[a-z0-9][a-z0-9!#$&^_.+-]*/[a-z0-9][a-z0-9!#$&^_.+-]*")++_ACTIVE_TYPES = frozenset(+ "text/html application/xhtml+xml image/svg+xml application/pdf text/xml application/xml"+ " text/javascript application/javascript application/x-shockwave-flash".split()+)++[email protected]_cache(maxsize = None)+def content_types() -> dict[str, str]:+ from routes.inference import _SANDBOX_MEDIA_TYPES+ return {**_CONTENT_TYPES, **_SANDBOX_MEDIA_TYPES}+++def media_type(value: object) -> Optional[str]:+ """The one media type ``value`` names, lower case and without parameters; None when it names+ none, or several (``audio/x, text/html``)."""+ essence = str(value or "").split(";", 1)[0].strip().lower()+ return essence if _MEDIA_TYPE_RE.fullmatch(essence) else None+++def _guess_type(name: str) -> str:+ return content_types().get(os.path.splitext(name)[1].lower(), "application/octet-stream")+++def upload_content_type(name: str, declared: Optional[str]) -> str:+ """What an upload is stored as: its extension's type when the map knows it, else the type the+ client declared, as long as it is one type and nothing a browser would run."""+ known = content_types().get(os.path.splitext(name)[1].lower())+ if known:+ return known+ declared_type = media_type(declared)+ if declared_type is None or declared_type in _ACTIVE_TYPES:+ return "application/octet-stream"+ return declared_type+++def item_type(item_id: str) -> str:+ """The media type an item's bytes are, by the Library's fixed map; "" for an item it has none+ for. LookupError for an upload the account does not have."""+ kind, _, ref = item_id.partition(":")+ if kind in _GALLERIES:+ return _gallery(kind).content_type+ if kind == "upload":+ record = library_db.get_upload(ref)+ if record is None:+ raise LookupError(item_id)+ return media_type(record["contentType"]) or ""+ return _guess_type(ref) if kind == "sandbox" else ""+++def _account_key() -> str:+ """Which account's stores a cached answer came from: each has a studio.db of its own."""+ from utils.paths import studio_db_path+ return str(studio_db_path())+++class _Memo:+ """Answers kept per account and key, each for ``ttl`` seconds while its ``stamp`` agrees, and+ only the ``size`` most recent when that is set. ``forget`` drops them all, and an answer worked+ out across a forget is not kept: it can predate the write that forgot."""++ def __init__(self, size: int = 0):+ self.size = size+ self.generation = 0+ self._entries: OrderedDict[tuple, tuple[float, object, object]] = OrderedDict()+ self._lock = threading.Lock()++ def forget(self) -> None:+ with self._lock:+ self.generation += 1+ self._entries.clear()++ def get(+ self,+ key: tuple,+ compute: Callable,+ ttl: float = float("inf"),+ stamp = None,+ ):+ full, now = (_account_key(), *key), time.monotonic()+ with self._lock:+ generation, hit = self.generation, self._entries.get(full)+ if hit is not None and now - hit[0] < ttl and hit[1] == stamp:+ self._entries.move_to_end(full)+ return hit[2]+ value = compute()+ self.put(key, value, generation, stamp)+ return value++ def put(+ self,+ key: tuple,+ value: object,+ generation: int,+ stamp = None,+ ) -> None:+ with self._lock:+ if generation == self.generation:+ self._entries[(_account_key(), *key)] = (time.monotonic(), stamp, value)+ while self.size and len(self._entries) > self.size:+ self._entries.popitem(last = False)+++_SANDBOX_TTL_SECONDS = 5.0+_MODEL_TTL_SECONDS = 60.0+# Bounded: sandboxes of chats and accounts nobody lists again would otherwise stay forever.+_LISTING = _Memo(size = 1024)+invalidate_listing = _LISTING.forget+++def _model_stamp() -> tuple:+ """The mtimes of the fine-tune roots and the folders in them: a run added, removed or renamed+ changes one."""+ from utils.paths.storage_roots import exports_root, outputs_root++ stamp = []+ for root in (outputs_root(), exports_root()):+ try:+ with os.scandir(root) as entries:+ stamp.append((str(root), os.stat(root).st_mtime_ns))+ stamp.extend(+ (entry.name, entry.stat(follow_symlinks = False).st_mtime_ns)+ for entry in entries+ if entry.is_dir(follow_symlinks = False)+ )+ except OSError:+ stamp.append((str(root), None))+ return tuple(sorted(stamp, key = repr))+++def _remembered(+ name: str,+ ttl: float,+ stamp: Optional[Callable] = None,+) -> Callable:+ """The source ``name``, remembered. Found by name, so a test that swaps the source swaps it."""++ def remembered() -> list[dict]:+ items = _LISTING.get((name,), globals()[name], ttl, stamp() if stamp else None)+ return [dict(item) for item in items]++ remembered.__name__ = name+ return remembered+++_SOURCES = (+ _upload_items,+ _attachment_items,+ _image_items,+ _video_items,+ _audio_items,+ _remembered("_model_items", _MODEL_TTL_SECONDS, _model_stamp),+ _remembered("_sandbox_items", _SANDBOX_TTL_SECONDS),+)+++def list_items() -> list[dict]:+ """Every item with its overlay applied, newest activity first. A failing source is skipped so+ one broken store cannot empty the whole Library."""+ overlay = library_db.list_entries()+ items: list[dict] = []+ for source in _SOURCES:+ try:+ items.extend(source())+ except Exception:+ logger.warning("library.source_failed: %s", source.__name__, exc_info = True)+ adopt: list[tuple[str, str]] = []+ stale: list[tuple[str, str]] = []+ for item in items:+ entry = overlay.get(item["id"])+ fingerprint = item.pop("_fingerprint", None)+ if fingerprint is not None:+ # Sent back with a delete, so a stale card never deletes a file made at its path since.+ item["fingerprint"] = fingerprint+ if entry and fingerprint is not None and entry["fingerprint"] != fingerprint:+ if entry["fingerprint"] is None:+ adopt.append((item["id"], fingerprint))+ else:+ stale.append((item["id"], entry["fingerprint"]))+ entry = None+ item["favorite"] = bool(entry and entry["favorite"])+ item["folderId"] = entry["folderId"] if entry else None+ if entry and entry["name"]:+ item["name"] = entry["name"]+ try:+ library_db.reconcile_entries(adopt, stale)+ except Exception:+ logger.warning("library.overlay_reconcile_failed", exc_info = True)+ items.sort(key = lambda item: item["updatedAt"], reverse = True)+ return items+++def path_derived(item_id: str) -> bool:+ """Whether the id names a path, which another file can take later."""+ return item_id.partition(":")[0] in ("sandbox", "model")+++def fingerprint(item_id: str) -> Optional[str]:+ """The fingerprint of the file a path-derived id names now, for its overlay row; None for other+ ids (never given to another file) and for a file that is gone."""+ kind, _, ref = item_id.partition(":")+ if kind not in ("sandbox", "model"):+ return None+ try:+ path = _sandbox_path(ref) if kind == "sandbox" else local_path(item_id)+ return _fingerprint(os.stat(path))+ except (LookupError, ValueError, OSError):+ return None+++def safe_file_name(+ name: str,+ fallback: str = "file",+ item_id: Optional[str] = None,+) -> str:+ """``name`` as a file name every OS can hold: its last path segment, nothing Windows refuses, no+ leading dot (hidden), no trailing dot or space (Windows drops them), never a device name such as+ ``CON``. With ``item_id``, a hash of it keeps each item's project copy apart, so adding one+ twice is a no-op."""+ stem, ext = os.path.splitext(re.split(r"[\\/]", name or "")[-1])+ if not ext and stem.startswith("."):+ stem, ext = os.path.splitext(stem.lstrip("."))+ stem = _NAME_BREAK_RE.sub(" ", stem).strip(" .") or fallback+ ext = _utf8_prefix(re.sub(f"[{UNSAFE_NAME_CHARS}]", "", ext).rstrip(" ."), 16)+ ext = ext if len(ext) > 1 else ""+ stem = _utf8_prefix(stem, 160 if item_id else 200).rstrip(" .") or fallback+ if _bad_name(stem):+ stem = f"_{stem}"+ if item_id:+ return f"{stem}-{hashlib.sha1(item_id.encode()).hexdigest()[:8]}{ext}"+ return f"{stem}{ext}"+++def _utf8_prefix(text: str, limit: int) -> str:+ """The longest start of ``text`` at most ``limit`` bytes long in UTF-8, never half a character."""+ return text.encode("utf-8", "ignore")[:limit].decode("utf-8", "ignore")+++class ItemFile:+ """An item's file, open. Every consumer reads this one descriptor, so what was checked is what+ is read, and nothing reopens the name."""++ def __init__(self, handle: BinaryIO, name: str, folder: str, project_name: str):+ self.handle = handle+ info = os.fstat(handle.fileno())+ self.size = info.st_size+ self.modified_ns = info.st_mtime_ns+ self.name = name+ self.folder = folder+ self.project_name = project_name++ def close(self) -> None:+ self.handle.close()++ def __enter__(self) -> "ItemFile":+ return self++ def __exit__(self, *_exc) -> None:+ self.close()+++def _gallery_file(kind: str, ref: str) -> tuple[Path, str]:+ """(path, prompt) of a gallery item Studio made, by the gallery's own ownership test (a file+ with a readable recipe); LookupError otherwise. An image's recipe sits in its PNG, which Pillow+ decodes whole."""+ gallery = _gallery(kind)+ path = gallery.resolve(ref)+ if path is not None:+ meta = gallery.module._read_meta(+ path if kind == "image" else gallery.module._sidecar_path(ref)+ )+ if path is None or meta is None:+ raise LookupError(f"{kind}:{ref}")+ return path, str(meta.get("prompt") or "")+++def _open_owned(path: Path, item_id: str) -> BinaryIO:+ try:+ return open(path, "rb")+ except (FileNotFoundError, IsADirectoryError, NotADirectoryError):+ raise LookupError(item_id) from None+++def open_item(item_id: str) -> ItemFile:+ """An item's file, opened, with the names it downloads and copies into a project as.++ Raises LookupError when the item is gone and ValueError for items with no file of their own+ (chat attachments live inside messages, fine-tunes are folders)."""+ kind, _, ref = item_id.partition(":")+ if kind == "upload":+ record = library_db.get_upload(ref)+ path = upload_path(ref)+ if record is None or path is None:+ raise LookupError(item_id)+ return ItemFile(+ _open_owned(path, item_id),+ safe_file_name(record["name"]),+ "files",+ safe_file_name(record["name"], item_id = item_id),+ )+ if kind in _GALLERIES:+ path, prompt = _gallery_file(kind, ref)+ name = safe_file_name(_prompt_name(prompt, ref, path.suffix.lstrip(".")), ref)+ return ItemFile(_open_owned(path, item_id), name, _gallery(kind).folder, path.name)+ if kind == "sandbox":+ handle, path = _open_sandbox_file(ref)+ name = os.path.basename(path)+ return ItemFile(+ handle, safe_file_name(name), "files", safe_file_name(name, item_id = item_id)+ )+ raise ValueError("This item cannot be added to a project.")+++def local_path(item_id: str) -> Path:+ """The file, or model folder, behind an item, for Reveal in Finder.++ Same errors as ``open_item``. A model path comes from the id, so it must sit inside the+ outputs or exports root."""+ kind, _, ref = item_id.partition(":")+ if kind == "upload":+ path = upload_path(ref)+ if library_db.get_upload(ref) is None or path is None or not path.is_file():+ raise LookupError(item_id)+ return path+ if kind in _GALLERIES:+ return _gallery_file(kind, ref)[0]+ if kind == "sandbox":+ path = Path(_sandbox_path(ref))+ if not path.is_file():+ raise LookupError(item_id)+ return path+ if kind != "model":+ raise ValueError("This item cannot be added to a project.")+ from utils.paths.storage_roots import exports_root, outputs_root++ _origin, _, path = ref.partition(":")+ resolved = os.path.realpath(path) if path else ""+ roots = [os.path.realpath(root) for root in (outputs_root(), exports_root())]+ if (+ not resolved+ or not any(is_path_within(resolved, root) for root in roots)+ or not os.path.exists(resolved)+ ):+ raise LookupError(item_id)+ return Path(resolved)+++_THUMBNAIL_WIDTH = 640+# The grid crops a picture past these heights (as a share of its width), so the rest is never sent.+_THUMBNAIL_MIN_RATIO = 2 / 3+_THUMBNAIL_MAX_RATIO = 3 / 2+_THUMBNAIL_MAX_PIXELS = 64_000_000+_THUMBNAIL_IMAGE_FORMATS = ("PNG", "JPEG", "WEBP", "GIF", "BMP", "TIFF", "AVIF")+_THUMBNAIL_VIDEO_CONTAINERS = {+ "video/mp4": "mp4",+ "video/quicktime": "mov",+ "video/webm": "webm",+ "video/x-matroska": "matroska",+ "video/ogg": "ogg",+ "video/x-msvideo": "avi",+}+_THUMBNAIL_DECODES = threading.BoundedSemaphore(2)+_THUMBNAILS = _Memo(size = 256)+++def _attachment_media(ref: str) -> tuple[str, bytes]:+ """The image or clip stored in a chat attachment, with its type. LookupError when it holds none.++ An image is stored as a data URL (``{"type": "image", "image": "data:image/png;base64,..."}``),+ a clip as raw base64 (``{"type": "file", "data", "mimeType"}``), as the attachment route reads+ them."""+ import urllib.parse++ from fastapi import HTTPException++ from routes.chat_history import _decode_attachment_base64+ from storage.studio_db import get_chat_attachment++ message_id, attachment_id = _attachment_ref(ref)+ attachment = get_chat_attachment(message_id, attachment_id) or {}+ try:+ for part in attachment.get("content") or []:+ if not isinstance(part, dict):+ continue+ image = part.get("image")+ if isinstance(image, str) and image[:5].lower() == "data:":+ header, _, payload = image.partition(",")+ mime_type = media_type(header[5:].split(";", 1)[0]) or ""+ if not mime_type.startswith("image/"):+ continue+ if "base64" not in header.lower():+ return mime_type, urllib.parse.unquote_to_bytes(payload)+ return mime_type, _decode_attachment_base64(payload)+ if part.get("type") != "file":+ continue+ data = part.get("data")+ mime_type = media_type(part.get("mimeType") or attachment.get("contentType")) or ""+ if isinstance(data, str) and data and mime_type.startswith(("image/", "video/")):+ return mime_type, _decode_attachment_base64(data)+ except HTTPException as exc:+ raise RuntimeError("The attachment's data is corrupt.") from exc+ raise LookupError(ref)+++def _image_thumbnail(source: Union[Path, BinaryIO]) -> bytes:+ """The picture cropped as a card shows it and at most `_THUMBNAIL_WIDTH` wide, as WebP."""+ try:+ from PIL import Image, ImageOps+ except Exception as exc: # noqa: BLE001 -- a missing dependency makes thumbnails unavailable+ raise RuntimeError("Thumbnail generation needs the 'Pillow' package.") from exc+ Image.init()+ formats = [name for name in _THUMBNAIL_IMAGE_FORMATS if name in Image.OPEN]+ try:+ with Image.open(source, formats = formats) as opened:+ if opened.width * opened.height > _THUMBNAIL_MAX_PIXELS:+ raise RuntimeError(f"{opened.width}x{opened.height} is too large to thumbnail.")+ opened.draft("RGB", (_THUMBNAIL_WIDTH, _THUMBNAIL_WIDTH))+ image = ImageOps.exif_transpose(opened)+ width, height = image.size+ if height > width * _THUMBNAIL_MAX_RATIO:+ image = image.crop((0, 0, width, round(width * _THUMBNAIL_MAX_RATIO)))+ elif height < width * _THUMBNAIL_MIN_RATIO:+ keep = round(height / _THUMBNAIL_MIN_RATIO)+ left = (width - keep) // 2+ image = image.crop((left, 0, left + keep, height))+ image.thumbnail(+ (_THUMBNAIL_WIDTH, round(_THUMBNAIL_WIDTH * _THUMBNAIL_MAX_RATIO)), Image.LANCZOS+ )+ if image.mode not in ("RGB", "RGBA"):+ transparent = "A" in image.getbands() or "transparency" in image.info+ image = image.convert("RGBA" if transparent else "RGB")+ buf = io.BytesIO()+ image.save(buf, format = "WEBP", quality = 85, method = 4)+ return buf.getvalue()+ except Exception as exc: # noqa: BLE001 -- surface decoder / WebP encoder failures+ raise RuntimeError(f"Thumbnail generation failed to decode the image: {exc}") from exc+++def _decode(mime_type: str, source: BinaryIO) -> bytes:+ """The thumbnail; the caller holds one of `_THUMBNAIL_DECODES`."""+ from core.inference import video_gallery++ if mime_type.startswith("video/") and mime_type in _THUMBNAIL_VIDEO_CONTAINERS:+ return video_gallery.first_frame_webp(+ source,+ width = _THUMBNAIL_WIDTH,+ container = _THUMBNAIL_VIDEO_CONTAINERS[mime_type],+ max_pixels = _THUMBNAIL_MAX_PIXELS,+ max_height = round(_THUMBNAIL_WIDTH * _THUMBNAIL_MAX_RATIO),+ )+ if mime_type.startswith("image/") and mime_type != "image/svg+xml":+ return _image_thumbnail(source)+ raise LookupError(mime_type)+++def _decoded(mime_type: str, source: BinaryIO) -> bytes:+ with _THUMBNAIL_DECODES:+ return _decode(mime_type, source)+++def thumbnail(item_id: str) -> bytes:+ """A card's picture: an image cropped and scaled down, or a video's first frame, as WebP.+ Remembered by the file's version, so an edit makes a new one.++ LookupError when the item is gone or has no picture; RuntimeError when it cannot be decoded."""+ kind, _, ref = item_id.partition(":")+ if kind == "attachment":+ with _THUMBNAIL_DECODES:+ mime_type, data = _attachment_media(ref)+ version = (item_id, len(data), zlib.crc32(data))+ return _THUMBNAILS.get(version, lambda: _decode(mime_type, io.BytesIO(data)))+ mime_type = item_type(item_id)+ if not mime_type.startswith(("image/", "video/")):+ raise LookupError(item_id)+ with open_item(item_id) as item:+ version = (item_id, item.size, item.modified_ns)+ return _THUMBNAILS.get(version, lambda: _decoded(mime_type, item.handle))+++def item_exists(item_id: str, recorded: Optional[str] = None) -> bool:+ """Whether the source still has the item, without listing the source. Errors other than its+ absence propagate, so a store that cannot be read is never taken for an empty one. With the+ fingerprint an overlay row recorded, a new file at the item's path is not the item."""+ kind, _, ref = item_id.partition(":")+ try:+ if kind == "attachment":+ from storage.studio_db import get_chat_attachment+ message_id, attachment_id = _attachment_ref(ref)+ return get_chat_attachment(message_id, attachment_id) is not None+ if kind in _GALLERIES:+ return _gallery(kind).resolve(ref) is not None+ path = local_path(item_id)+ except (LookupError, ValueError):+ return False+ if recorded is None or kind not in ("sandbox", "model"):+ return True+ try:+ return _fingerprint(os.stat(path)) == recorded+ except OSError:+ return False+++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++ 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),+ )+ ]+++def _delete_upload(upload_id: str, path: Path) -> bool:+ """Set the file aside before dropping its row, so a failure at either step leaves both."""+ staged = path.with_name(f".{upload_id}.deleting")+ with _upload_lock:+ try:+ os.replace(path, staged)+ except FileNotFoundError:+ return library_db.delete_upload(upload_id)+ try:+ deleted = library_db.delete_upload(upload_id)+ except BaseException:+ os.replace(staged, path)+ raise+ if deleted:+ staged.unlink(missing_ok = True)+ else:+ os.replace(staged, path)+ return deleted+++class DeleteIncomplete(RuntimeError):+ """A delete that stopped part way; the item is still there to delete again."""+++class ItemChanged(RuntimeError):+ """Another file now has the path the item was listed at; nothing was deleted."""+++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."""+ kind, _, ref = item_id.partition(":")+ deleted = False+ if kind == "upload":+ 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)+ deleted = delete_chat_attachment(message_id, attachment_id)+ elif kind == "video":+ from core.inference import video_gallery+ from routes.video import _forget_openai_job, _forget_terminal_video+ if video_gallery.get_record(ref) is not None:+ # The job goes first, as the Video page's cleanup, so /v1/videos never keeps a ghost+ # of the clip. Failing there leaves the clip listed, and deleting it again finishes.+ if not _forget_openai_job(ref):+ raise DeleteIncomplete("Could not delete the video job; try again.")+ deleted = video_gallery.delete(ref)+ if deleted:+ _forget_terminal_video(ref)+ elif kind in _GALLERIES:+ deleted = _gallery(kind).module.delete(ref)+ elif kind == "sandbox":+ deleted = _delete_sandbox_file(ref, fingerprint)+ elif kind == "model":+ raise ValueError("Fine-tuned models are deleted from the model picker.")+ else:+ raise ValueError("Unknown library item")+ invalidate_listing()+ if not deleted and kind in _GALLERIES and item_exists(item_id):+ raise DeleteIncomplete("Could not delete the file. Close any app using it and try again.")+ library_db.delete_entry(item_id)+ return deleteddiff --git a/studio/backend/main.py b/studio/backend/main.pyindex d864c804401..9de3aa5a49d 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -368,6 +368,7 @@ from hub.utils.download_registry import (from routes.settings import router as settings_routerfrom routes.systemone import router as systemone_routerfrom routes.prompts import router as prompts_router+from routes.library import router as library_routerfrom routes.profile_stats import router as profile_stats_routerfrom auth import policy as auth_policy, storagefrom auth.authentication import authenticated_via_api_key, get_current_subject@@ -1256,6 +1257,7 @@ import json as _json_for_413 # noqa: E402from utils.upload_limits import ( # noqa: E402STT_AUDIO_JSON_MAX_BYTES,STT_AUDIO_RAW_MAX_BYTES,+ LIBRARY_UPLOAD_MAX_BYTES,UNSTRUCTURED_RECIPE_UPLOAD_MAX_BYTES,VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,VIDEO_INPUT_REFERENCE_MAX_BYTES,@@ -1277,6 +1279,7 @@ _BODY_PROTECTED_PREFIXES = ("/api/settings","/api/train","/api/export",+ "/api/library","/mcp",)_DATASET_UPLOAD_PASSTHROUGH_PREFIXES = (@@ -1297,6 +1300,7 @@ _VIDEO_MULTIPART_UPLOAD_PATHS = ("/v1/videos","/api/inference/videos",)+_LIBRARY_UPLOAD_PATH = "/api/library/uploads"_BODY_UPLOAD_PASSTHROUGH_PREFIXES = (*_DATASET_UPLOAD_PASSTHROUGH_PREFIXES,_DATA_RECIPE_UNSTRUCTURED_UPLOAD_PASSTHROUGH_PREFIX,@@ -1306,6 +1310,7 @@ _BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS = (_DIFFUSION_DATASET_UPLOAD_PATH,*_STT_MULTIPART_UPLOAD_PATHS,*_VIDEO_MULTIPART_UPLOAD_PATHS,+ _LIBRARY_UPLOAD_PATH,)# Which of those may arrive with no Content-Length and be counted instead of refused. Deliberately NOT the# whole set above: this middleware runs before authentication, and a counted body is a held body, so the dataset@@ -1324,6 +1329,8 @@ def _get_upload_passthrough_request_max_bytes(path: str) -> int:upload_request_limit_bytes(VIDEO_INPUT_REFERENCE_MAX_BYTES),VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,)+ if path.rstrip("/") == _LIBRARY_UPLOAD_PATH:+ return upload_request_limit_bytes(LIBRARY_UPLOAD_MAX_BYTES)# The trailing-slash variant reaches this middleware BEFORE the router's redirect_slashes# 307, so it must resolve to the same cap. JSON sub-routes keep extra path components.if (@@ -1629,6 +1636,7 @@ app.include_router(settings_router, prefix = "/api/settings", tags = ["settings"app.include_router(mcp_servers_router, prefix = "/api/mcp/servers", tags = ["mcp"])app.include_router(skills_router, prefix = "/api/skills", tags = ["skills"])app.include_router(prompts_router, prefix = "/api/prompts", tags = ["prompts"])+app.include_router(library_router, prefix = "/api/library", tags = ["library"])app.include_router(profile_stats_router, prefix = "/api/profile", tags = ["profile"])app.include_router(datasets_router, prefix = "/api/datasets", tags = ["datasets"])app.include_router(data_recipe_router, prefix = "/api/data-recipe", tags = ["data-recipe"])@@ -1989,6 +1997,9 @@ async def health_check(request: Request):authed["chat_only_detail"] = snapshot[2]authed["device_type"] = device_typeauthed["apple_silicon"] = is_apple_silicon()+ from utils.paths.file_manager import file_manager_kind++ authed["file_manager"] = file_manager_kind()# base predates the bearer await; never ship "detecting" beside a measurement.authed.pop("hardware_detecting", None)# Same for the deferred marker: the client reads it first and would keep the old reason.diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex dc776b59c88..2c015b926a3 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -8,6 +8,7 @@ handlers explicitly send their database transaction through Starlette's threadpo"""import asyncio+import reimport sqlite3from typing import Annotated, Any, Literal, Optional, Union@@ -966,6 +967,9 @@ def _decode_attachment_base64(payload: str) -> bytes:corrupted bytes, so raise 422."""import base64+ # An imported file part can keep its data URL; base64 has no ':', so this never cuts a payload.+ if payload[:5].lower() == "data:" and "," in payload:+ payload = payload.split(",", 1)[1]normalized = "".join(payload.split())altchars = b"-_" if ("-" in normalized or "_" in normalized) else Nonenormalized += "=" * (-len(normalized) % 4)@@ -1000,7 +1004,7 @@ def get_attachment_file(attachment_id: str,current_subject: str = Depends(get_current_subject),):- """Serve one attachment's stored content: image or audio bytes, or+ """Serve one attachment's stored content: image, audio or video bytes, orextracted text."""import urllib.parse@@ -1048,6 +1052,16 @@ def get_attachment_file())return Response(content = data, media_type = media_type)+ file_data = part.get("data")+ mime_type = str(part.get("mimeType") or attachment_content_type or "")+ mime_type = mime_type.split(";", 1)[0].strip().lower()+ if (+ part.get("type") == "file"+ and isinstance(file_data, str)+ and file_data+ and re.fullmatch(r"video/[a-z0-9.+-]+", mime_type)+ ):+ return Response(content = _decode_attachment_base64(file_data), media_type = mime_type)text = part.get("text")if isinstance(text, str) and text:texts.append(text)diff --git a/studio/backend/routes/library.py b/studio/backend/routes/library.pynew file mode 100644index 00000000000..236cb81d2a9--- /dev/null+++ b/studio/backend/routes/library.py@@ -0,0 +1,710 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Library API: one view over uploads, chat attachments, generated images and audio, fine-tuned+models and sandbox files, plus folders, favorites and renames. See ``core.library`` for the sources."""++import hashlib+import hmac+import os+import re+import secrets+import time+from typing import Literal, Optional+from urllib.parse import quote, urlencode++from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile+from fastapi.responses import FileResponse, Response, StreamingResponse+from pydantic import BaseModel, Field, field_validator+from starlette.background import BackgroundTask+from starlette.concurrency import run_in_threadpool++from auth.authentication import (+ authenticated_via_api_key,+ get_current_subject,+ request_admitted_without_credential,+ subject_for_header_or_query_token,+)+from core import library+from hub.services.models import account_access+from loggers import get_logger+from storage import library_db+from storage.studio_db import ChatMessageProtectedError+from utils.account_context import run_as+from utils.upload_limits import LIBRARY_UPLOAD_MAX_BYTES+from utils.utils import log_and_http_error, safe_curated_detail++logger = get_logger(__name__)++router = APIRouter()++_MAX_UPLOAD_BYTES = LIBRARY_UPLOAD_MAX_BYTES+_CHUNK_BYTES = 1024 * 1024+# Raster images, audio and video render inline; anything else (svg and html included) downloads as+# opaque bytes, as the sandbox route does, so a crafted upload cannot run script on the app origin.+# Exact types, never a prefix: a stored "audio/x, text/html" is not audio.+_INLINE_IMAGE_TYPES = frozenset(+ {"image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"}+)+_NOSNIFF = {"X-Content-Type-Options": "nosniff"}+++def _playable(content_type: Optional[str]) -> Optional[str]:+ """The exact audio or video type the Library's fixed map has, else None."""+ value = library.media_type(content_type)+ known = library.content_types().values()+ return value if value in known and value.startswith(("audio/", "video/")) else None+++def _inline_type(content_type: str) -> Optional[str]:+ value = library.media_type(content_type)+ return value if value in _INLINE_IMAGE_TYPES else _playable(value)+++def _model_ref(item_id: str) -> Optional[tuple[str, str]]:+ kind, _, rest = item_id.partition(":")+ origin, sep, path = rest.partition(":")+ return (origin, path) if kind == "model" and sep and path else None+++def _for_caller(item_id: str, via_api_key: bool) -> str:+ """A fine-tune's id names its folder; an API key gets a reference in its place, as the Hub+ inventory routes give it, which ``_from_caller`` turns back."""+ from hub.utils.host_paths import cache_reference, host_paths_visible++ ref = _model_ref(item_id)+ if ref is None or host_paths_visible(via_api_key):+ return item_id+ return f"model:{ref[0]}:{cache_reference(ref[1])}"+++def _from_caller(item_id: str) -> str:+ from hub.utils.host_paths import resolve_host_path_reference++ ref = _model_ref(item_id)+ path = resolve_host_path_reference(ref[1]) if ref else None+ return f"model:{ref[0]}:{path}" if path else item_id+++def _items_for_caller(items: list[dict], via_api_key: bool) -> list[dict]:+ from hub.utils.host_paths import (+ cache_reference,+ host_paths_visible,+ redact_inventory_host_paths,+ )++ if host_paths_visible(via_api_key):+ return items+ shown = []+ for item in items:+ item = {**item, "id": _for_caller(item["id"], via_api_key)}+ base = (item.get("model") or {}).get("baseModel")+ # A fine-tune of a local model names that folder; a Hub repo id is kept.+ if isinstance(base, str) and os.path.isabs(base):+ item["model"] = {**item["model"], "baseModel": cache_reference(base)}+ shown.append(item)+ return redact_inventory_host_paths(shown, via_api_key = via_api_key)+++class _ItemIdModel(BaseModel):+ @field_validator("id", check_fields = False)+ @classmethod+ def _resolve_id(cls, value: str) -> str:+ return _from_caller(value)+++class ItemPatch(_ItemIdModel):+ id: str = Field(max_length = 4096)+ name: Optional[str] = Field(default = None, min_length = 1, max_length = 255)+ favorite: Optional[bool] = None+ folderId: Optional[str] = Field(default = None, min_length = 1, max_length = 64)+++class ItemRef(_ItemIdModel):+ id: str = Field(max_length = 4096)+++class ItemDelete(ItemRef):+ # The file a sandbox item was listed as, so a delete never takes one made at its path since.+ fingerprint: Optional[str] = Field(default = None, max_length = 256)+++class LocationRef(BaseModel):+ key: str = Field(max_length = 32)+++class ProjectCopy(_ItemIdModel):+ id: str = Field(max_length = 4096)+ projectId: str = Field(max_length = 256)+++class FolderCreate(BaseModel):+ name: str = Field(min_length = 1, max_length = 255)+ parentId: Optional[str] = Field(default = None, min_length = 1, max_length = 64)+++class FolderPatch(BaseModel):+ name: Optional[str] = Field(default = None, min_length = 1, max_length = 255)+ parentId: Optional[str] = Field(default = None, min_length = 1, max_length = 64)+++class TextContent(BaseModel):+ text: str = Field(max_length = 5_000_000)+ encoding: Literal["utf-8", "utf-16le", "utf-16be"] = "utf-8"+++async def get_library(+ current_subject: str = Depends(get_current_subject),+ via_api_key: bool = Depends(authenticated_via_api_key),+) -> dict:+ items = await run_in_threadpool(library.list_items)+ return {"items": _items_for_caller(items, via_api_key), "folders": library_db.list_folders()}++[email protected]("/favorites")+def get_favorites(+ current_subject: str = Depends(get_current_subject),+ via_api_key: bool = Depends(authenticated_via_api_key),+) -> dict:+ """Favorite item ids alone, for pages that mark favorites without listing every source. Only+ those the source still has: a gallery or chat can delete one without the Library."""+ return {+ "ids": [+ _for_caller(item_id, via_api_key)+ for item_id, entry in library_db.list_entries().items()+ if entry["favorite"] and _still_there(item_id, entry["fingerprint"])+ ]+ }+++def _still_there(item_id: str, fingerprint: Optional[str]) -> bool:+ try:+ return library.item_exists(item_id, fingerprint)+ except Exception:+ logger.debug("library.favorite_check_failed: %s", item_id, exc_info = True)+ return True++[email protected]("/items")+def patch_item(body: ItemPatch, current_subject: str = Depends(get_current_subject)) -> dict:+ fingerprint = library.fingerprint(body.id)+ if fingerprint is None and library.path_derived(body.id):+ raise HTTPException(status_code = 404, detail = "Item not found")+ try:+ library_db.update_entry(+ body.id,+ name = body.name.strip() if body.name else None,+ favorite = body.favorite,+ folder_id = body.folderId,+ move = "folderId" in body.model_fields_set,+ fingerprint = fingerprint,+ )+ except KeyError:+ raise HTTPException(status_code = 404, detail = "Folder not found")+ return {"ok": True}++[email protected]("/items/delete")+async def delete_item(+ body: ItemDelete, current_subject: str = Depends(get_current_subject)+) -> dict:+ try:+ deleted = await run_in_threadpool(library.delete_item, body.id, body.fingerprint)+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc))+ except library.DeleteIncomplete as exc:+ raise HTTPException(status_code = 500, detail = str(exc))+ except library.ItemChanged as exc:+ raise HTTPException(status_code = 409, detail = str(exc))+ except ChatMessageProtectedError as exc:+ raise log_and_http_error(+ exc,+ 409,+ safe_curated_detail(exc),+ event = "library.delete_protected",+ log = logger,+ ) from exc+ except OSError as exc:+ raise _file_error(exc, "library.delete_failed", "Could not delete the file.") from exc+ if not deleted:+ raise HTTPException(status_code = 404, detail = "Item not found")+ return {"ok": True}+++def _file_error(exc: OSError, event: str, detail: str) -> HTTPException:+ """Windows refuses to replace or delete a file another program holds open, so that one says+ what to do; anything else is logged and answered without the path."""+ if isinstance(exc, PermissionError):+ logger.info("%s: %s", event, exc)+ return HTTPException(status_code = 409, detail = "The file is in use. Close it and try again.")+ logger.warning("%s: %s", event, exc, exc_info = True)+ return HTTPException(status_code = 500, detail = detail)++[email protected]("/items/project")+async def add_item_to_project(+ body: ProjectCopy, current_subject: str = Depends(get_current_subject)+) -> dict:+ """Copy an item's file into a chat project's folder. The Library keeps its item."""+ from core.inference.gallery_projects import ProjectNotFound, copy_into_project++ def _copy() -> dict:+ with library.open_item(body.id) as item:+ copied = copy_into_project(item.handle, body.projectId, item.folder, item.project_name)+ library.invalidate_listing()+ return copied++ try:+ result = await run_in_threadpool(_copy)+ except ProjectNotFound:+ raise HTTPException(status_code = 404, detail = "Project not found")+ except LookupError:+ raise HTTPException(status_code = 404, detail = "Item not found")+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc))+ except OSError as exc:+ logger.warning("library.add_to_project_failed: %s", exc)+ raise HTTPException(status_code = 500, detail = "Could not copy the file into the project.")+ return {"already": result["already"]}+++def _reveal(path) -> None:+ from utils.paths.file_manager import file_manager_kind+ from utils.paths.path_utils import reveal_in_file_manager++ # The UI hides Reveal on such a host; a direct call must not open a window nobody sees.+ if file_manager_kind() is None:+ raise HTTPException(status_code = 503, detail = "No file manager is available on this machine")+ try:+ reveal_in_file_manager(path)+ except FileNotFoundError:+ if os.path.exists(path):+ logger.error("library.reveal_failed: %s", path, exc_info = True)+ raise HTTPException(+ status_code = 503, detail = "No file manager is available on this machine"+ )+ raise HTTPException(status_code = 404, detail = "File not found")+ except Exception:+ logger.error("library.reveal_failed: %s", path, exc_info = True)+ raise HTTPException(status_code = 500, detail = "Failed to open file manager")++[email protected]("/items/reveal")+async def reveal_item(body: ItemRef, current_subject: str = Depends(get_current_subject)) -> dict:+ """Show the item's file in the OS file manager. The backend host's, so the desktop app's."""+ account_access.require_installation_owner()+ try:+ path = await run_in_threadpool(library.local_path, body.id)+ except LookupError:+ raise HTTPException(status_code = 404, detail = "Item not found")+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc))+ await run_in_threadpool(_reveal, path)+ return {"ok": True}++[email protected]("/items/thumbnail")+def get_item_thumbnail(+ id: str = Query(max_length = 4096), current_subject: str = Depends(get_current_subject)+):+ """An image or video item's card picture. The client adds the item's version to the URL, so it+ can cache."""+ id = _from_caller(id)+ try:+ data = library.thumbnail(id)+ except LookupError:+ raise HTTPException(status_code = 404, detail = "Item not found")+ except (RuntimeError, OSError) as exc:+ logger.info("library.thumbnail_unavailable: %s", exc)+ raise HTTPException(status_code = 501, detail = "No thumbnail for this item")+ return Response(+ content = data,+ media_type = "image/webp",+ headers = {+ "Cache-Control": "private, max-age=31536000, immutable",+ "Vary": "Authorization",+ **_NOSNIFF,+ },+ )++[email protected]_route("/items/download", methods = ["GET", "HEAD"])+async def download_item(+ request: Request,+ id: str = Query(max_length = 4096),+ token: Optional[str] = Query(default = None, max_length = 8192),+):+ """An item's file as an attachment. Takes ``?token=`` as well: the desktop app streams it+ straight to disk, and its native save sends no header."""+ id = _from_caller(id)+ await subject_for_header_or_query_token(request, token)+ try:+ item = await run_in_threadpool(library.open_item, id)+ except LookupError:+ raise HTTPException(status_code = 404, detail = "Item not found")+ except ValueError:+ raise HTTPException(status_code = 400, detail = "This item has no file to download")+ ascii_name = item.name.encode("ascii", "replace").decode("ascii").replace('"', "_")+ disposition = f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(item.name)}"+ headers = {"Content-Disposition": disposition, "Cache-Control": "private, no-store", **_NOSNIFF}+ return _send(request, item, "application/octet-stream", headers)+++def _send(+ request: Request,+ item,+ media_type: str,+ headers: dict,+ span = None,+) -> Response:+ """The open file, or its (first, last) ``span`` as a 206, never past Content-Length even if the+ file grows meanwhile, as the sandbox route streams; the headers alone for a HEAD."""+ start, end = span or (0, item.size - 1)+ headers["Content-Length"] = str(end - start + 1)+ status_code = 206 if span else 200+ if request.method.upper() == "HEAD":+ item.close()+ return Response(status_code = status_code, media_type = media_type, headers = headers)++ def read():+ with item:+ item.handle.seek(start)+ remaining = end - start + 1+ while remaining > 0 and (chunk := item.handle.read(min(_CHUNK_BYTES, remaining))):+ remaining -= len(chunk)+ yield chunk++ return StreamingResponse(+ read(),+ status_code = status_code,+ media_type = media_type,+ headers = headers,+ background = BackgroundTask(item.close),+ )+++# An audio or video preview plays from a link the element fetches itself, with range requests, so+# a long file is never buffered whole and can seek. The bearer mints the link; the link alone then+# serves that one item, in that one account, until it expires. A secret and domain of its own, so+# a gallery's media link never works here, nor one of these there.+_STREAM_LINK_TTL = 6 * 3600+_STREAM_LINK_SECRET = secrets.token_bytes(32)+_STREAM_LINK_DOMAIN = b"unsloth-library-stream\0"+++def _stream_signature(payload: str) -> str:+ return hmac.new(+ _STREAM_LINK_SECRET, _STREAM_LINK_DOMAIN + payload.encode(), hashlib.sha256+ ).hexdigest()+++def _sign_stream_id(item_id: str) -> str:+ """A link token for ``item_id`` in the calling account."""+ payload = f"{account_access.media_link_target(item_id)}.{int(time.time()) + _STREAM_LINK_TTL}"+ return f"{payload}.{_stream_signature(payload)}"+++def _stream_link_account(token: str, item_id: str):+ """The account a valid, unexpired token for ``item_id`` was minted in, else None."""+ parts = token.rsplit(".", 2)+ if len(parts) != 3:+ return None+ target, expires, signature = parts+ # Bytes: compare_digest raises TypeError on a non-ASCII str.+ if not hmac.compare_digest(+ signature.encode(), _stream_signature(f"{target}.{expires}").encode()+ ):+ return None+ if not expires.isdigit() or int(expires) < time.time():+ return None+ return account_access.media_link_account(target, item_id)+++def _stream_type(item_id: str) -> Optional[str]:+ """The exact audio or video type an item plays as, None for anything this route never serves.+ Read in the item's own account; LookupError for an upload it does not have."""+ return _playable(library.item_type(item_id))+++class _Unsatisfiable(Exception):+ pass+++_RANGE_RE = re.compile(r"\s*bytes\s*=\s*([0-9]*)-([0-9]*)\s*", re.IGNORECASE)+++def _byte_range(request: Request, size: int) -> Optional[tuple[int, int]]:+ """The one ``bytes=`` range asked for, as (first, last) inclusive; None for the whole file.++ What RFC 9110 lets a server ignore is ignored (another unit, several ranges, a malformed one,+ an ``If-Range`` this route has no validator to match); a range past the end is unsatisfiable."""+ match = _RANGE_RE.fullmatch(request.headers.get("range") or "")+ if not match or request.headers.get("if-range") or match.groups() == ("", ""):+ return None+ first, last = match.groups()+ if not first:+ if int(last) == 0 or size == 0:+ raise _Unsatisfiable+ return max(0, size - int(last)), size - 1+ start = int(first)+ if last and int(last) < start:+ return None+ if start >= size:+ raise _Unsatisfiable+ return start, min(int(last) if last else size - 1, size - 1)++[email protected]("/items/stream-url")+async def get_item_stream_url(+ id: str = Query(max_length = 4096),+ current_subject: str = Depends(get_current_subject),+ no_credential: bool = Depends(request_admitted_without_credential),+) -> dict:+ """A short-lived link an ``<audio>`` or ``<video>`` element plays an item from, with range+ requests. Relative, so it works behind any proxy the page is served through."""+ id = _from_caller(id)+ if no_credential:+ raise HTTPException(+ status_code = 403,+ detail = "Media links can only be created from the Unsloth UI or with an API key.",+ )+ try:+ content_type = await run_in_threadpool(_stream_type, id)+ except LookupError:+ raise HTTPException(status_code = 404, detail = "Item not found")+ if content_type is None:+ raise HTTPException(status_code = 400, detail = "Only audio and video items can be streamed")+ if not await run_in_threadpool(library.item_exists, id):+ raise HTTPException(status_code = 404, detail = "Item not found")+ query = urlencode({"id": id, "token": _sign_stream_id(id)})+ return {"url": f"/api/library/items/stream?{query}"}++[email protected]_route("/items/stream", methods = ["GET", "HEAD"])+async def stream_item(+ request: Request,+ id: str = Query(max_length = 4096),+ token: str = Query(max_length = 8192),+):+ """An audio or video item, gated by its link rather than the bearer so it can be a plain+ ``src``, and range-capable so it seeks. Opened once in the link's account and read from that+ descriptor, so a sandbox name swapped for a link after the check is never followed."""+ account = _stream_link_account(token, id)+ if account is None:+ raise HTTPException(status_code = 401, detail = "Invalid or expired media link.")++ def _open():+ content_type = _stream_type(id)+ if content_type is None:+ raise LookupError(id)+ return content_type, library.open_item(id)++ try:+ content_type, item = await run_in_threadpool(run_as, account, _open)+ except (LookupError, ValueError):+ raise HTTPException(status_code = 404, detail = "Item not found")+ headers = {"Accept-Ranges": "bytes", "Cache-Control": "private", **_NOSNIFF}+ try:+ requested = _byte_range(request, item.size)+ except _Unsatisfiable:+ item.close()+ return Response(+ status_code = 416, headers = {"Content-Range": f"bytes */{item.size}", **headers}+ )+ if requested is not None:+ headers["Content-Range"] = f"bytes {requested[0]}-{requested[1]}/{item.size}"+ return _send(request, item, content_type, headers, requested)++[email protected]("/locations")+async def get_locations(+ 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++ # Settings > Library shows these to a signed-in user; an API key gets references, as the Hub+ # inventory routes give it.+ locations = await run_in_threadpool(library.locations)+ return redact_inventory_host_paths({"locations": locations}, via_api_key = via_api_key)++[email protected]("/locations/reveal")+async def reveal_location(+ body: LocationRef, current_subject: str = Depends(get_current_subject)+) -> dict:+ 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:+ raise HTTPException(status_code = 404, detail = "Unknown location")+ path = Path(paths[body.key])+ await run_in_threadpool(lambda: path.mkdir(parents = True, exist_ok = True))+ await run_in_threadpool(_reveal, path)+ return {"ok": True}+++def _chunks(stream, name: str):+ total = 0+ while chunk := stream.read(_CHUNK_BYTES):+ total += len(chunk)+ if total > _MAX_UPLOAD_BYTES:+ raise HTTPException(status_code = 413, detail = f"{name} is too large")+ yield chunk+++def _base_name(name: Optional[str]) -> str:+ return re.split(r"[\\/]", name or "")[-1][:255] or "Untitled"++[email protected]("/uploads")+async def upload_files(+ files: Optional[list[UploadFile]] = File(None),+ nativePathLeases: Optional[list[str]] = Form(None),+ folderId: Optional[str] = Form(None),+ current_subject: str = Depends(get_current_subject),+) -> dict:+ if not files and not nativePathLeases:+ raise HTTPException(status_code = 400, detail = "No files were provided.")+ if folderId and library_db.get_folder(folderId) is None:+ raise HTTPException(status_code = 404, detail = "Folder not found")++ def _native(read, lease: str):+ try:+ return read(lease)+ except (ValueError, OSError) as exc:+ logger.info("library.native_drop_refused: %s", exc)+ raise HTTPException(+ status_code = 400, detail = "The dropped file could not be read. Drop it again."+ ) from exc++ def _check_native(lease: str) -> None:+ name, size = _native(library.check_native_upload, lease)+ if size > _MAX_UPLOAD_BYTES:+ raise HTTPException(status_code = 413, detail = f"{name} is too large")++ consumed: list[str] = []++ def _save_native(lease: str) -> dict:+ name, content_type, handle = _native(library.open_native_upload, lease)+ consumed.append(lease)+ with handle:+ if os.fstat(handle.fileno()).st_size > _MAX_UPLOAD_BYTES:+ raise HTTPException(status_code = 413, detail = f"{name} is too large")+ return library.save_upload(name, content_type, _chunks(handle, name))++ for lease in nativePathLeases or []:+ await run_in_threadpool(_check_native, lease)++ records = []+ try:+ for upload in files or []:+ name = _base_name(upload.filename)+ records.append(+ await run_in_threadpool(+ library.save_upload,+ name,+ library.upload_content_type(name, upload.content_type),+ _chunks(upload.file, name),+ )+ )+ for lease in nativePathLeases or []:+ records.append(await run_in_threadpool(_save_native, lease))+ ids = [f"upload:{record['id']}" for record in records]+ if folderId:+ for item_id in ids:+ library_db.update_entry(item_id, folder_id = folderId, move = True)+ except BaseException as exc:+ # All or nothing, so a retry never duplicates the files that did make it, and the grants+ # this batch spent are given back, or its retry would be refused as a replay.+ for record in records:+ await run_in_threadpool(library.delete_item, f"upload:{record['id']}")+ _release_leases(consumed)+ if isinstance(exc, KeyError):+ raise HTTPException(status_code = 404, detail = "Folder not found") from exc+ raise+ return {"ids": ids}+++def _release_leases(leases: list[str]) -> None:+ from utils.native_path_leases import release_native_path_lease+ for lease in leases:+ try:+ release_native_path_lease(lease)+ except ValueError:+ logger.debug("library.native_lease_release_failed", exc_info = True)++[email protected]("/uploads/{upload_id}/file")+def get_upload_file(upload_id: str, current_subject: str = Depends(get_current_subject)):+ record = library_db.get_upload(upload_id)+ path = library.upload_path(upload_id)+ if record is None or path is None or not path.is_file():+ raise HTTPException(status_code = 404, detail = "File not found")+ content_type = _inline_type(record["contentType"])+ # A note is saved through another URL, so the browser must ask again rather than reuse this.+ headers = {"Cache-Control": "private, no-cache", **_NOSNIFF}+ if content_type:+ return FileResponse(path, media_type = content_type, headers = headers)+ return FileResponse(+ path,+ media_type = "application/octet-stream",+ filename = library.safe_file_name(record["name"]),+ headers = headers,+ )++[email protected]("/uploads/{upload_id}/text")+def put_upload_text(+ upload_id: str,+ body: TextContent,+ current_subject: str = Depends(get_current_subject),+) -> dict:+ try:+ written = library.write_upload_text(upload_id, body.text, body.encoding)+ except UnicodeEncodeError:+ raise HTTPException(status_code = 400, detail = "The note has characters it cannot hold.")+ except OSError as exc:+ raise _file_error(exc, "library.note_save_failed", "Could not save the note.") from exc+ if not written:+ raise HTTPException(status_code = 404, detail = "File not found")+ return {"ok": True}++[email protected]("/folders")+def create_folder(body: FolderCreate, current_subject: str = Depends(get_current_subject)) -> dict:+ try:+ return library_db.create_folder(body.name.strip(), body.parentId)+ except KeyError:+ raise HTTPException(status_code = 404, detail = "Parent folder not found")++[email protected]("/folders/{folder_id}")+def patch_folder(+ folder_id: str,+ body: FolderPatch,+ current_subject: str = Depends(get_current_subject),+) -> dict:+ try:+ folder = library_db.update_folder(+ folder_id,+ name = body.name.strip() if body.name else None,+ parent_id = body.parentId,+ move = "parentId" in body.model_fields_set,+ )+ except KeyError:+ raise HTTPException(status_code = 404, detail = "Parent folder not found")+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc))+ if folder is None:+ raise HTTPException(status_code = 404, detail = "Folder not found")+ return folder++[email protected]("/folders/{folder_id}")+def delete_folder(folder_id: str, current_subject: str = Depends(get_current_subject)) -> dict:+ if not library_db.delete_folder(folder_id):+ raise HTTPException(status_code = 404, detail = "Folder not found")+ return {"ok": True}diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex bd1a56e670c..0a76460fbbd 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -3756,8 +3756,9 @@ SIDEBAR_MENU_ITEM_DEFAULTS = {SIDEBAR_NAV_ITEM_DEFAULTS = {"hub": True,"projects": True,+ "library": True,"images": True,- "video": True,+ "video": False,"audio": False,"train": True,"recipes": False,@@ -3797,6 +3798,7 @@ def _default_sidebar_menu() -> "list[PersonalizationSidebarMenuItem]":SidebarNavItemId = Literal["hub","projects",+ "library","images","video","audio",diff --git a/studio/backend/storage/library_db.py b/studio/backend/storage/library_db.pynew file mode 100644index 00000000000..d0e7d5c7ec3--- /dev/null+++ b/studio/backend/storage/library_db.py@@ -0,0 +1,409 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Library state in studio.db.++The Library lists files that already live elsewhere (chat uploads, generated images, sandbox+files), so it only stores what those sources cannot: folders, and a per-item overlay of display+name, favorite flag and folder. Files uploaded straight into the Library are the one source it+owns; their bytes sit under ``account_path("library")``.+"""++import sqlite3+import threading+import time+import uuid+from pathlib import Path+from typing import Optional++from utils.paths import ensure_dir, studio_db_path++_schema_lock = threading.Lock()+_schema_ready: set[Path] = set()+++def _ensure_schema(conn: sqlite3.Connection) -> None:+ conn.execute("PRAGMA journal_mode=WAL")+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS library_folders (+ id TEXT NOT NULL PRIMARY KEY,+ name TEXT NOT NULL,+ parent_id TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ )+ """+ )+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS library_entries (+ item_id TEXT NOT NULL PRIMARY KEY,+ name TEXT,+ favorite INTEGER NOT NULL DEFAULT 0,+ folder_id TEXT,+ updated_at INTEGER NOT NULL+ )+ """+ )+ entry_columns = {row["name"] for row in conn.execute("PRAGMA table_info(library_entries)")}+ if "fingerprint" not in entry_columns:+ try:+ conn.execute("ALTER TABLE library_entries ADD COLUMN fingerprint TEXT")+ except sqlite3.OperationalError as exc:+ if "duplicate column" not in str(exc).lower():+ raise+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS library_uploads (+ id TEXT NOT NULL PRIMARY KEY,+ name TEXT NOT NULL,+ content_type TEXT NOT NULL,+ size_bytes INTEGER NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ )+ """+ )+++def reset_schema_state_for_tests() -> None:+ with _schema_lock:+ _schema_ready.clear()+++def get_connection() -> sqlite3.Connection:+ db_path = studio_db_path()+ ensure_dir(db_path.parent)+ # One key for the check and the add, or a home reached through a link never finds its entry+ # and runs the schema again on every connection.+ schema_path = db_path.resolve()+ conn = sqlite3.connect(str(db_path))+ conn.row_factory = sqlite3.Row+ if schema_path not in _schema_ready:+ with _schema_lock:+ if schema_path not in _schema_ready:+ try:+ _ensure_schema(conn)+ _schema_ready.add(schema_path)+ except Exception:+ conn.close()+ raise+ return conn+++def _lock(conn: sqlite3.Connection) -> None:+ """Take the write lock before the checks, so nothing they read can change before the write."""+ conn.execute("BEGIN IMMEDIATE")+++def _now_ms() -> int:+ return int(time.time() * 1000)+++def _folder(row: sqlite3.Row) -> dict:+ return {+ "id": row["id"],+ "name": row["name"],+ "parentId": row["parent_id"],+ "createdAt": row["created_at"],+ "updatedAt": row["updated_at"],+ }+++def list_folders() -> list[dict]:+ conn = get_connection()+ try:+ rows = conn.execute("SELECT * FROM library_folders ORDER BY updated_at DESC").fetchall()+ return [_folder(row) for row in rows]+ finally:+ conn.close()+++def get_folder(folder_id: str) -> Optional[dict]:+ conn = get_connection()+ try:+ row = conn.execute("SELECT * FROM library_folders WHERE id = ?", (folder_id,)).fetchone()+ return _folder(row) if row else None+ finally:+ conn.close()+++def _is_descendant(conn: sqlite3.Connection, folder_id: str, ancestor_id: str) -> bool:+ """Whether ``folder_id`` sits anywhere under ``ancestor_id`` (or is it)."""+ current: Optional[str] = folder_id+ seen: set[str] = set()+ while current and current not in seen:+ if current == ancestor_id:+ return True+ seen.add(current)+ row = conn.execute(+ "SELECT parent_id FROM library_folders WHERE id = ?", (current,)+ ).fetchone()+ current = row["parent_id"] if row else None+ return False+++def create_folder(name: str, parent_id: Optional[str] = None) -> dict:+ now = _now_ms()+ folder_id = uuid.uuid4().hex+ conn = get_connection()+ try:+ _lock(conn)+ if (+ parent_id+ and not conn.execute(+ "SELECT 1 FROM library_folders WHERE id = ?", (parent_id,)+ ).fetchone()+ ):+ raise KeyError(parent_id)+ conn.execute(+ "INSERT INTO library_folders (id, name, parent_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",+ (folder_id, name, parent_id, now, now),+ )+ conn.commit()+ finally:+ conn.close()+ return {+ "id": folder_id,+ "name": name,+ "parentId": parent_id,+ "createdAt": now,+ "updatedAt": now,+ }+++def update_folder(+ folder_id: str,+ *,+ name: Optional[str] = None,+ parent_id: Optional[str] = None,+ move: bool = False,+) -> Optional[dict]:+ """Rename and/or move a folder. ``move`` distinguishes "move to the root" from "leave it"."""+ conn = get_connection()+ try:+ _lock(conn)+ if not conn.execute("SELECT 1 FROM library_folders WHERE id = ?", (folder_id,)).fetchone():+ return None+ if move and parent_id:+ if not conn.execute(+ "SELECT 1 FROM library_folders WHERE id = ?", (parent_id,)+ ).fetchone():+ raise KeyError(parent_id)+ if _is_descendant(conn, parent_id, folder_id):+ raise ValueError("A folder cannot be moved into itself")+ now = _now_ms()+ if name is not None:+ conn.execute(+ "UPDATE library_folders SET name = ?, updated_at = ? WHERE id = ?",+ (name, now, folder_id),+ )+ if move:+ conn.execute(+ "UPDATE library_folders SET parent_id = ?, updated_at = ? WHERE id = ?",+ (parent_id, now, folder_id),+ )+ conn.commit()+ row = conn.execute("SELECT * FROM library_folders WHERE id = ?", (folder_id,)).fetchone()+ return _folder(row)+ finally:+ conn.close()+++def delete_folder(folder_id: str) -> bool:+ """Delete a folder; what it held moves up to its parent rather than disappearing."""+ conn = get_connection()+ try:+ _lock(conn)+ row = conn.execute(+ "SELECT parent_id FROM library_folders WHERE id = ?", (folder_id,)+ ).fetchone()+ if row is None:+ return False+ parent_id = row["parent_id"]+ conn.execute(+ "UPDATE library_folders SET parent_id = ? WHERE parent_id = ?", (parent_id, folder_id)+ )+ conn.execute(+ "UPDATE library_entries SET folder_id = ? WHERE folder_id = ?", (parent_id, folder_id)+ )+ conn.execute("DELETE FROM library_folders WHERE id = ?", (folder_id,))+ conn.commit()+ return True+ finally:+ conn.close()+++def list_entries() -> dict[str, dict]:+ conn = get_connection()+ try:+ rows = conn.execute("SELECT * FROM library_entries").fetchall()+ return {+ row["item_id"]: {+ "name": row["name"],+ "favorite": bool(row["favorite"]),+ "folderId": row["folder_id"],+ "updatedAt": row["updated_at"],+ "fingerprint": row["fingerprint"],+ }+ for row in rows+ }+ finally:+ conn.close()+++def update_entry(+ item_id: str,+ *,+ name: Optional[str] = None,+ favorite: Optional[bool] = None,+ folder_id: Optional[str] = None,+ move: bool = False,+ fingerprint: Optional[str] = None,+) -> None:+ """Write an item's overlay. ``fingerprint`` is the file a path-derived id names right now: a+ row kept for another file at that path is dropped before the write, not carried over."""+ conn = get_connection()+ try:+ _lock(conn)+ if (+ move+ and folder_id+ and not conn.execute(+ "SELECT 1 FROM library_folders WHERE id = ?", (folder_id,)+ ).fetchone()+ ):+ raise KeyError(folder_id)+ 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 OR IGNORE INTO library_entries (item_id, updated_at) VALUES (?, ?)",+ (item_id, now),+ )+ if fingerprint is not None:+ conn.execute(+ "UPDATE library_entries SET fingerprint = ? WHERE item_id = ?",+ (fingerprint, item_id),+ )+ if name is not None:+ conn.execute("UPDATE library_entries SET name = ? WHERE item_id = ?", (name, item_id))+ if favorite is not None:+ conn.execute(+ "UPDATE library_entries SET favorite = ? WHERE item_id = ?",+ (int(favorite), item_id),+ )+ if move:+ conn.execute(+ "UPDATE library_entries SET folder_id = ? WHERE item_id = ?", (folder_id, item_id)+ )+ conn.execute("UPDATE library_entries SET updated_at = ? WHERE item_id = ?", (now, item_id))+ 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+ it, so a write that landed in between is kept."""+ if not adopt and not stale:+ return+ conn = get_connection()+ try:+ conn.executemany(+ "UPDATE library_entries SET fingerprint = ? WHERE item_id = ? AND fingerprint IS NULL",+ [(fingerprint, item_id) for item_id, fingerprint in adopt],+ )+ conn.executemany(+ "DELETE FROM library_entries WHERE item_id = ? AND fingerprint = ?",+ stale,+ )+ conn.commit()+ finally:+ conn.close()+++def delete_entry(item_id: str) -> None:+ conn = get_connection()+ try:+ conn.execute("DELETE FROM library_entries WHERE item_id = ?", (item_id,))+ conn.commit()+ finally:+ conn.close()+++def _upload(row: sqlite3.Row) -> dict:+ return {+ "id": row["id"],+ "name": row["name"],+ "contentType": row["content_type"],+ "sizeBytes": row["size_bytes"],+ "createdAt": row["created_at"],+ "updatedAt": row["updated_at"],+ }+++def list_uploads() -> list[dict]:+ conn = get_connection()+ try:+ rows = conn.execute("SELECT * FROM library_uploads").fetchall()+ return [_upload(row) for row in rows]+ finally:+ conn.close()+++def get_upload(upload_id: str) -> Optional[dict]:+ conn = get_connection()+ try:+ row = conn.execute("SELECT * FROM library_uploads WHERE id = ?", (upload_id,)).fetchone()+ return _upload(row) if row else None+ finally:+ conn.close()+++def insert_upload(upload_id: str, name: str, content_type: str, size_bytes: int) -> dict:+ now = _now_ms()+ conn = get_connection()+ try:+ conn.execute(+ "INSERT INTO library_uploads (id, name, content_type, size_bytes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",+ (upload_id, name, content_type, size_bytes, now, now),+ )+ conn.commit()+ finally:+ conn.close()+ return {+ "id": upload_id,+ "name": name,+ "contentType": content_type,+ "sizeBytes": size_bytes,+ "createdAt": now,+ "updatedAt": now,+ }+++def touch_upload(upload_id: str, size_bytes: int) -> None:+ conn = get_connection()+ try:+ conn.execute(+ "UPDATE library_uploads SET size_bytes = ?, updated_at = ? WHERE id = ?",+ (size_bytes, _now_ms(), upload_id),+ )+ conn.commit()+ finally:+ conn.close()+++def delete_upload(upload_id: str) -> bool:+ conn = get_connection()+ try:+ cursor = conn.execute("DELETE FROM library_uploads WHERE id = ?", (upload_id,))+ conn.commit()+ return cursor.rowcount > 0+ finally:+ conn.close()diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex e8c81e95fbe..3f42cfbaca9 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -7,6 +7,8 @@ Like auth/storage.py (module-level functions, raw sqlite3, per-function connectiand PRAGMA foreign_keys = ON for CASCADE deletes."""+import base64+import binasciiimport hashlibimport jsonimport logging@@ -102,7 +104,7 @@ _schema_lock = threading.Lock()_schema_ready: set[Path] = set()_SQLITE_IN_CHUNK_SIZE = 900_PROJECT_WORKSPACE_SUBDIRS = ("sandbox",)-_CHAT_ATTACHMENT_INVENTORY_VERSION = 1+_CHAT_ATTACHMENT_INVENTORY_VERSION = 3def _project_slug(name: str) -> str:@@ -4326,6 +4328,9 @@ def _blob_part_base64_len(part: dict) -> int:data = audio.get("data")if isinstance(data, str) and _is_locally_stored_blob(data):return len(data)+ data = part.get("data")+ if part.get("type") == "file" and isinstance(data, str) and _is_locally_stored_blob(data):+ return len(data.rsplit(",", 1)[-1])return 0@@ -4337,9 +4342,9 @@ def _attachment_content_parts(attachment: dict) -> list[dict]:def _chat_attachment_size_bytes(attachment: dict) -> Optional[int]:- """Approximate stored size of one attachment's content parts. Image and audio parts hold base64- payloads (decoded bytes ~= 3/4 of the encoded length); text parts count their character length.- None when there is no sizable content."""+ """Approximate stored size of one attachment's content parts. Image, audio and file (video)+ parts hold base64 payloads (decoded bytes ~= 3/4 of the encoded length); text parts count their+ character length. None when there is no sizable content."""total = 0found = Falsefor part in _attachment_content_parts(attachment):@@ -4355,6 +4360,46 @@ def _chat_attachment_size_bytes(attachment: dict) -> Optional[int]:return total if found else None+_AUDIO_FORMAT_TYPES = {+ "mp3": "audio/mpeg",+ "wav": "audio/wav",+ "ogg": "audio/ogg",+ "flac": "audio/flac",+}+++def _content_part_audio_type(audio: Any) -> Optional[str]:+ """An audio part's type: its data URL's, its format's, or else its bytes' own header, since a+ compare chat stores bare base64 with neither."""+ data = audio+ if isinstance(audio, dict):+ known = _AUDIO_FORMAT_TYPES.get(str(audio.get("format") or "").lower())+ if known:+ return known+ data = audio.get("data")+ if not isinstance(data, str):+ return None+ data = data.strip()+ if data[:5].lower() == "data:":+ header, _, data = data.partition(",")+ declared = header[5:].split(";", 1)[0].strip().lower()+ if declared.startswith("audio/"):+ return declared+ try:+ head = base64.b64decode(data[:16])+ except (binascii.Error, ValueError):+ return None+ if head.startswith(b"RIFF") and head[8:12] == b"WAVE":+ return "audio/wav"+ if head.startswith(b"ID3") or (len(head) > 1 and head[0] == 0xFF and head[1] & 0xE0 == 0xE0):+ return "audio/mpeg"+ if head.startswith(b"OggS"):+ return "audio/ogg"+ if head.startswith(b"fLaC"):+ return "audio/flac"+ return None++def _content_part_attachments(content_json: Optional[str]) -> list[dict]:"""Managed local blobs stored in content_json, with stable payload ids. Exact duplicate blobsintentionally share one inventory id: deleting it removes every identical copy, avoiding@@ -4375,7 +4420,9 @@ def _content_part_attachments(content_json: Optional[str]) -> list[dict]:kind, value = payloadcontent_type = Nonepart_name = part.get("name")- if isinstance(value, str) and value[:5].lower() == "data:":+ if kind == "audio":+ content_type = _content_part_audio_type(value)+ elif isinstance(value, str) and value[:5].lower() == "data:":content_type = value[5:].split(";", 1)[0].split(",", 1)[0] or Noneout.append({diff --git a/studio/backend/tests/multi_account/factories.py b/studio/backend/tests/multi_account/factories.pyindex b409b0ec9e4..0aa96b59a27 100644--- a/studio/backend/tests/multi_account/factories.py+++ b/studio/backend/tests/multi_account/factories.py@@ -161,6 +161,7 @@ CORE_FACTORIES = {from . import ( # noqa: E402 domain tables import Factory and register their seeders firstfactories_chat,+ factories_library,factories_media,factories_providers,factories_rag,@@ -170,6 +171,7 @@ from . import ( # noqa: E402 domain tables import Factory and register their sDOMAINS = (factories_chat,+ factories_library,factories_media,factories_providers,factories_rag,diff --git a/studio/backend/tests/multi_account/factories_library.py b/studio/backend/tests/multi_account/factories_library.pynew file mode 100644index 00000000000..99277fc3e06--- /dev/null+++ b/studio/backend/tests/multi_account/factories_library.py@@ -0,0 +1,43 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from .factory_base import Factory, seeder++FOLDER_NAME = "library-matrix-folder"+EDITED = "library-matrix-edited"+NOTE = "library-matrix-note.md"+CONTENT = b"library matrix sentinel note\n"+++@seeder("library-folder")+def seed_library_folder(account) -> dict[str, str]:+ from storage import library_db+ from utils.account_context import run_as++ folder = run_as(account, library_db.create_folder, FOLDER_NAME)+ return {"folder_id": folder["id"]}+++@seeder("library-upload")+def seed_library_upload(account) -> dict[str, str]:+ from core import library+ from utils.account_context import run_as++ record = run_as(account, library.save_upload, NOTE, "text/markdown", iter([CONTENT]))+ return {"upload_id": record["id"]}+++FACTORIES = {+ "routes.library:PATCH:/folders/{folder_id}": Factory(+ "library-folder", {"name": EDITED}, fragment = EDITED+ ),+ "routes.library:DELETE:/folders/{folder_id}": Factory("library-folder", fragment = '"ok":true'),+ "routes.library:GET:/uploads/{upload_id}/file": Factory(+ "library-upload", fragment = CONTENT.decode().strip()+ ),+ "routes.library:PUT:/uploads/{upload_id}/text": Factory(+ "library-upload", {"text": EDITED}, fragment = '"ok":true'+ ),+}++SKIPPED: dict[str, str] = {}diff --git a/studio/backend/tests/multi_account/legacy_probe.py b/studio/backend/tests/multi_account/legacy_probe.pyindex 57046dd6755..e1a933e3cf8 100644--- a/studio/backend/tests/multi_account/legacy_probe.py+++ b/studio/backend/tests/multi_account/legacy_probe.py@@ -74,9 +74,13 @@ def main() -> None:if name not in ("auth/auth.db", "studio.db"):assert (home / name).read_bytes() == payload, f"Owner read changed {name}"assert old_auth_row(home / "auth" / "auth.db") == auth_row- assert (- legacy_studio_rows(home / "studio.db") == studio_rows- ), "Owner read changed legacy studio.db rows"+ # The attachment inventory is a versioned derived cache: a newer build rebuilds it on first+ # read, so its bookkeeping row moves by design. Every user-written row must not.+ derived = "chat_attachment_inventory_state"+ after = legacy_studio_rows(home / "studio.db")+ assert {t: r for t, r in after.items() if t != derived} == {+ t: r for t, r in studio_rows.items() if t != derived+ }, "Owner read changed legacy studio.db rows"assert not (home / "accounts").exists()print(json.dumps({"preserved_files": len(original), "owner_login": True}))diff --git a/studio/backend/tests/test_chat_attachments.py b/studio/backend/tests/test_chat_attachments.pyindex 482ece1b6ef..7e3fff74d81 100644--- a/studio/backend/tests/test_chat_attachments.py+++ b/studio/backend/tests/test_chat_attachments.py@@ -462,6 +462,35 @@ def test_audio_attachment_file_serves_bytes(tmp_path, monkeypatch):assert response.media_type == "audio/wav"+ "mime_type, served", [("video/mp4", "video/mp4"), ("video/webm;codecs=vp9", "video/webm")]+)+def test_video_attachment_file_serves_bytes_and_lists_with_size(+ tmp_path, monkeypatch, mime_type, served+):+ clip = b"\0\0\0\x18ftypmp42" * 100+ attachment = {+ "id": "att-video",+ "type": "file",+ "name": "clip",+ "contentType": mime_type,+ "content": [+ {+ "type": "file",+ "filename": "clip",+ "data": base64.b64encode(clip).decode("ascii"),+ "mimeType": mime_type,+ }+ ],+ "status": {"type": "complete"},+ }+ _seed(tmp_path, monkeypatch, [attachment])+ response = chat_history.get_attachment_file("msg-1", "att-video", current_subject = "unsloth")+ assert response.body == clip+ assert response.media_type == served+ assert abs(studio_db.list_chat_attachments()[0]["sizeBytes"] - len(clip)) <= 2++def test_audio_attachment_media_type_from_format(tmp_path, monkeypatch):attachment = _audio_attachment()attachment["contentType"] = Nonediff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.pyindex 89346f37a2b..c4d750d6d50 100644--- a/studio/backend/tests/test_desktop_auth.py+++ b/studio/backend/tests/test_desktop_auth.py@@ -825,6 +825,8 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):profile_stats_module.router = APIRouter()accounts_module = ModuleType("routes.accounts")accounts_module.router = APIRouter()+ library_module = ModuleType("routes.library")+ library_module.router = APIRouter()systemone_module = ModuleType("routes.systemone")systemone_module.router = APIRouter()@@ -851,6 +853,7 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):monkeypatch.setitem(sys.modules, "routes.npu", npu_module)monkeypatch.setitem(sys.modules, "routes.profile_stats", profile_stats_module)monkeypatch.setitem(sys.modules, "routes.accounts", accounts_module)+ monkeypatch.setitem(sys.modules, "routes.library", library_module)monkeypatch.setitem(sys.modules, "routes.systemone", systemone_module)import studio.backend.main as backend_maindiff --git a/studio/backend/tests/test_image_gallery.py b/studio/backend/tests/test_image_gallery.pyindex 7cb4d157262..e29f4132e91 100644--- a/studio/backend/tests/test_image_gallery.py+++ b/studio/backend/tests/test_image_gallery.py@@ -63,6 +63,22 @@ def test_save_embeds_recipe_and_round_trips():assert listed[0]["prompt"] == "a sloth" and listed[0]["seed"] == 7+def test_listing_reads_the_recipe_without_decoding_pixels(monkeypatch):+ from PIL import PngImagePlugin++ for i in range(3):+ gallery.save(_img(), _meta(seed = i))+ loads = []+ real_load = PngImagePlugin.PngImageFile.load+ monkeypatch.setattr(+ PngImagePlugin.PngImageFile,+ "load",+ lambda self, *a, **k: loads.append(1) or real_load(self, *a, **k),+ )+ assert sorted(r["seed"] for r in gallery.list_images()) == [0, 1, 2]+ assert loads == []++def _save_with_mtime(prompt: str, t: float) -> dict:record = gallery.save(_img(), _meta(prompt = prompt, created_at = t))# Listing orders by mtime; set it explicitly so a tight test loop can't tie it.diff --git a/studio/backend/tests/test_library_routes.py b/studio/backend/tests/test_library_routes.pynew file mode 100644index 00000000000..2fc9a4d6304--- /dev/null+++ b/studio/backend/tests/test_library_routes.py@@ -0,0 +1,1524 @@+# 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 base64+import contextlib+import io+import json+import os+import sqlite3+import sys+from pathlib import Path+from urllib.parse import quote++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++_BACKEND = Path(__file__).resolve().parents[1]+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++from auth.authentication import ( # noqa: E402+ authenticated_via_api_key,+ get_current_subject,+ request_admitted_without_credential,+)+from core import library # noqa: E402+from routes import library as library_routes # noqa: E402+from storage import library_db # noqa: E402++from .test_rag_native_drop_upload import SECRET, _sign # noqa: E402++_CLIP = bytes(range(100))+_SANDBOX_ID = "sandbox:t-lib:report.txt"+_SANDBOX_A = "sandbox:t-lib:a.txt"+++def _app(subject) -> TestClient:+ """The router alone; with a ``subject``, as a caller signed in with the UI or a key."""+ app = FastAPI()+ if subject is not None:+ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[request_admitted_without_credential] = lambda: False+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ app.include_router(library_routes.router, prefix = "/api/library")+ return TestClient(app)+++def client(monkeypatch):+ monkeypatch.setattr(library, "_SOURCES", (library._upload_items,))+ library.invalidate_listing()+ library._THUMBNAILS.forget()+ return _app(lambda: "unsloth")+++async def _signed_in_subject(_request, _token):+ return "unsloth"+++def signed_in(monkeypatch):+ monkeypatch.setattr(library_routes, "subject_for_header_or_query_token", _signed_in_subject)+++def _send(client, files, **form):+ return client.post("/api/library/uploads", files = [("files", f) for f in files], data = form)+++def _upload(client, *files):+ response = _send(client, files)+ assert response.status_code == 200, response.text+ return response.json()["ids"]+++def _items(client):+ body = client.get("/api/library").json()+ return {item["id"]: item for item in body["items"]}, body["folders"]+++def _post(client, path, **body):+ return client.post(f"/api/library/{path}", json = body)+++def _patch(client, **body):+ assert client.patch("/api/library/items", json = body).status_code == 200+++def _favorites(client):+ return client.get("/api/library/favorites").json()["ids"]+++def _delete(client, item_id) -> int:+ return _post(client, "items/delete", id = item_id).status_code+++def _download(client, item_id):+ return client.get("/api/library/items/download", params = {"id": item_id})+++def _thumbnail(client, item_id):+ return client.get("/api/library/items/thumbnail", params = {"id": item_id})+++def _folder(client, name, parent_id) -> str:+ return _post(client, "folders", name = name, parentId = parent_id).json()["id"]+++def _ref(item_id: str) -> str:+ return item_id.split(":", 1)[1]+++def _fail(*_args, **_kwargs):+ raise sqlite3.OperationalError("database is locked")+++def _file(path: Path, body: str) -> Path:+ path.write_text(body)+ return path+++def _gallery_image(prompt: str) -> str:+ from PIL import Image++ from core.inference import image_gallery++ meta = {"prompt": prompt, "width": 4, "height": 4, "steps": 1, "guidance": 1, "seed": 1}+ return image_gallery.save(Image.new("RGB", (4, 4)), {**meta, "created_at": 1})["id"]+++def _gallery_video(prompt: str) -> str:+ from core.inference import video_gallery++ keys = ("width", "height", "num_frames", "fps", "duration_s", "steps", "guidance", "seed")+ meta = {key: 1 for key in keys}+ return video_gallery.save(+ b"\0\0\0\x18ftypmp42", {**meta, "prompt": prompt, "created_at": 1_700_000_000}+ )["id"]+++def _gallery_audio(prompt: str) -> str:+ from core.inference import audio_gallery+ meta = {"model": "sample-tts", "audio_type": "snac", "sample_rate": 24000, "duration_s": 1.0}+ return audio_gallery.save(+ b"RIFF0000WAVE", {**meta, "prompt": prompt, "created_at": 1_700_000_000}+ )["id"]+++def _sandbox_chat(+ name,+ body,+ thread = "t-lib",+):+ """A file ``name`` in the chat's sandbox: (sandbox directory, its path)."""+ from core.inference.tools import resolve_sandbox_workdir+ from storage import studio_db++ studio_db.upsert_chat_thread(+ {"id": thread, "title": "T", "modelType": "base", "modelId": "m", "createdAt": 1}+ )+ directory = resolve_sandbox_workdir(thread)+ path = os.path.join(directory, name)+ os.makedirs(os.path.dirname(path), exist_ok = True)+ Path(path).write_bytes(body)+ return directory, path+++def _png(width, height, mode) -> bytes:+ from PIL import Image++ buf = io.BytesIO()+ color = (200, 40, 40, 128) if mode == "RGBA" else (200, 40, 40)+ Image.new(mode, (width, height), color).save(buf, format = "PNG")+ return buf.getvalue()+++def _thumbnail_size(client, item_id):+ from PIL import Image++ response = _thumbnail(client, item_id)+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "image/webp"+ return Image.open(io.BytesIO(response.content)).size+++def test_uploads_are_listed_and_typed_by_their_extension_not_the_client(client, monkeypatch):+ import mimetypes++ uploads = [+ (("note.md", b"# hi", "text/markdown"), "note.md", "text/markdown"),+ (("C:\\Users\\me\\notes.txt", b"<script>", "text/html"), "notes.txt", "text/plain"),+ (("report.pdf", b"%PDF-1.7", "text/html"), "report.pdf", "application/pdf"),+ (("track.xyz", b"x", "audio/x, text/html"), "track.xyz", "application/octet-stream"),+ (("data.bin2", b"x", "application/xhtml+xml"), "data.bin2", "application/octet-stream"),+ ]+ ids = _upload(client, *(sent for sent, _, _ in uploads))+ items, folders = _items(client)+ assert folders == []+ assert [(items[i]["name"], items[i]["contentType"]) for i in ids] == [+ (name, stored) for _, name, stored in uploads+ ]+ note = items[ids[0]]+ assert note["source"] == "uploaded" and note["sizeBytes"] == 4+ assert note["favorite"] is False and note["folderId"] is None+ monkeypatch.setattr(mimetypes, "guess_type", lambda *_a, **_k: ("video/mp2t", None))+ types = ("app.ts", "view.tsx", "mod.mts", "photo.JPG", "mystery.xyz")+ assert [library._guess_type(name) for name in types] == [+ *["text/typescript"] * 3,+ "image/jpeg",+ "application/octet-stream",+ ]+++ "stored, inline",+ [+ ("image/png", True),+ ("audio/mpeg", True),+ ("image/png; charset=binary", True),+ # Served on the app origin, so markup never comes back as something a browser renders.+ ("text/html", False),+ ("image/svg+xml", False),+ ("audio/x, text/html", False),+ ],+)+def test_only_an_exact_raster_or_media_type_is_served_inline(client, stored, inline):+ [item] = _upload(client, ("page.xyz", b"<script>1</script>", "application/octet-stream"))+ conn = library_db.get_connection()+ conn.execute("UPDATE library_uploads SET content_type = ? WHERE id = ?", (stored, _ref(item)))+ conn.commit()+ conn.close()+ response = client.get(_items(client)[0][item]["fileUrl"])+ assert response.headers["x-content-type-options"] == "nosniff"+ assert ("attachment" not in response.headers.get("content-disposition", "")) is inline+ expected = library.media_type(stored) if inline else "application/octet-stream"+ assert response.headers["content-type"] == expected+++def test_rename_favorite_and_folders_are_an_overlay(client):+ [image] = _upload(client, ("photo.png", b"", "image/png"))+ folder = _folder(client, "Work", None)+ _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)+ # 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)+ assert _items(client)[0][image]["folderId"] == folder+ _patch(client, id = image, folderId = None)+ assert _items(client)[0][image]["folderId"] is None+ response = client.patch("/api/library/items", json = {"id": image, "folderId": "nope"})+ assert response.status_code == 404+ # Folders nest; a folder never moves under itself, and a deleted one hands its contents up.+ inner = _folder(client, "Inner", folder)+ child = _folder(client, "Child", inner)+ for parent in (inner, folder):+ response = client.patch(f"/api/library/folders/{folder}", json = {"parentId": parent})+ assert response.status_code == 400+ assert response.json()["detail"] == "A folder cannot be moved into itself"+ [note] = _send(client, [("note.md", b"", "text/markdown")], folderId = inner).json()["ids"]+ assert client.delete(f"/api/library/folders/{inner}").status_code == 200+ items, folders = _items(client)+ assert items[note]["folderId"] == folder+ assert {f["id"]: f["parentId"] for f in folders} == {folder: None, child: folder}+++def test_notes_are_saved_in_their_own_encoding_and_deletable(client):+ [note] = _upload(client, ("log.txt", "\ufeffold\r\n".encode("utf-16le"), "text/plain"))+ url = f"/api/library/uploads/{_ref(note)}/text"+ response = client.put(url, json = {"text": "\ufeffnew\r\n", "encoding": "utf-16le"})+ assert response.status_code == 200+ item = _items(client)[0][note]+ assert client.get(item["fileUrl"]).content == b"\xff\xfen\x00e\x00w\x00\r\x00\n\x00"+ assert client.put(url, json = {"text": "x", "encoding": "latin-1"}).status_code == 422+ assert client.put(url, json = {"text": "hello"}).status_code == 200+ assert _items(client)[0][note]["sizeBytes"] == 5+ assert _delete(client, note) == 200+ assert note not in _items(client)[0]+ assert client.get(item["fileUrl"]).status_code == 404+ assert _delete(client, note) == 404+ assert client.put(url, json = {"text": "x"}).status_code == 404+++def test_chat_attachments_holding_bytes_are_known_by_their_type_in_any_case(client, monkeypatch):+ import storage.studio_db as studio_db++ def attachment(attachment_id, content_type):+ return {"messageId": "m", "id": attachment_id, "type": "file", "contentType": content_type}++ voice = {"messageId": "m:1", "id": "voice", "type": "audio", "contentType": None}+ monkeypatch.setattr(library, "_SOURCES", (library._attachment_items,))+ monkeypatch.setattr(+ studio_db,+ "list_chat_attachments",+ lambda: [+ attachment("clip", "Video/WebM; codecs=vp9"),+ attachment("words", "Text/Plain"),+ voice,+ ],+ )+ items = _items(client)[0]+ clip, words = items["attachment:m:clip"], items["attachment:m:words"]+ assert (clip["contentType"], clip["textOnly"]) == ("video/webm", False)+ assert (words["contentType"], words["textOnly"]) == ("text/plain", True)+ assert items["attachment:m%3A1:voice"]["textOnly"] is False+ deleted = []+ monkeypatch.setattr(studio_db, "delete_chat_attachment", lambda *ids: deleted.append(ids) or 1)+ assert _delete(client, "attachment:m%3A1:voice") == 200+ assert deleted == [("m:1", "voice")]+++def test_a_chat_audio_part_is_typed_by_its_format_or_its_bytes():+ from storage.studio_db import _content_part_attachments++ def typed(audio):+ [part] = _content_part_attachments(json.dumps([{"type": "audio", "audio": audio}]))+ return part["contentType"]++ wav = base64.b64encode(b"RIFF\0\0\0\0WAVEfmt ").decode()+ assert typed(wav) == "audio/wav"+ assert typed(base64.b64encode(b"ID3\3\0\0\0\0\0\0\0\0").decode()) == "audio/mpeg"+ assert typed({"data": wav, "format": "flac"}) == "audio/flac"+ assert typed(f"data:audio/ogg;base64,{wav}") == "audio/ogg"+ assert typed(base64.b64encode(b"not a sound at all").decode()) is None+++def test_a_gallery_file_that_cannot_be_deleted_keeps_its_name_star_and_folder(client, monkeypatch):+ from core.inference import audio_gallery++ monkeypatch.setattr(library, "_SOURCES", (library._audio_items,))+ item_id = f"audio:{_gallery_audio('Kept')}"+ _patch(client, id = item_id, name = "Renamed", favorite = True)+ monkeypatch.setattr(audio_gallery, "delete", lambda _ref: False)+ assert _delete(client, item_id) == 500+ item = _items(client)[0][item_id]+ assert (item["name"], item["favorite"]) == ("Renamed", True)+++def test_a_sandbox_file_that_is_gone_takes_no_rename_a_later_file_would_inherit(+ client, signed_in, monkeypatch+):+ monkeypatch.setattr(library, "_SOURCES", (library._sandbox_items,))+ _directory, path = _sandbox_chat("a.txt", b"first")+ os.unlink(path)+ response = client.patch("/api/library/items", json = {"id": _SANDBOX_A, "name": "Old"})+ assert response.status_code == 404+ _sandbox_chat("a.txt", b"another file at the same path")+ assert _items(client)[0][_SANDBOX_A]["name"] == "a.txt"+++def test_a_sandbox_delete_takes_only_the_file_it_was_listed_as(client, signed_in, monkeypatch):+ monkeypatch.setattr(library, "_SOURCES", (library._sandbox_items,))+ _directory, path = _sandbox_chat("a.txt", b"listed")+ listed = _items(client)[0][_SANDBOX_A]["fingerprint"]+ # Held open so ext4 cannot hand the new file the same inode; Windows refuses to unlink an+ # open file and never reuses a file id, so nothing is held there.+ with open(path, "rb") if os.name != "nt" else contextlib.nullcontext():+ os.unlink(path)+ _sandbox_chat("a.txt", b"made since")+ response = _post(client, "items/delete", id = _SANDBOX_A, fingerprint = listed)+ assert response.status_code == 409+ assert Path(path).read_bytes() == b"made since"+ library.invalidate_listing()+ current = _items(client)[0][_SANDBOX_A]["fingerprint"]+ assert current != listed+ assert _post(client, "items/delete", id = _SANDBOX_A, fingerprint = current).status_code == 200+ assert not os.path.exists(path)+++def test_a_sandbox_file_of_a_chat_whose_id_has_a_colon_is_reachable(client, signed_in, monkeypatch):+ monkeypatch.setattr(library, "_SOURCES", (library._sandbox_items,))+ _sandbox_chat("a.txt", b"mine", thread = "imported:1")+ [item_id] = _items(client)[0]+ assert item_id == "sandbox:imported%3A1:a.txt"+ assert _download(client, item_id).content == b"mine"+ assert _delete(client, item_id) == 200+ assert _items(client)[0] == {}+++def test_a_sandbox_file_written_twice_in_a_second_is_a_new_version(client, signed_in, monkeypatch):+ monkeypatch.setattr(library, "_SOURCES", (library._sandbox_items,))+ _directory, path = _sandbox_chat("frame.png", b"one")+ versions = []+ for ns in (1_700_000_000_100_000_000, 1_700_000_000_600_000_000):+ os.utime(path, ns = (ns, ns))+ library.invalidate_listing()+ versions.append(_items(client)[0]["sandbox:t-lib:frame.png"]["updatedAt"])+ assert versions == [1_700_000_000_100, 1_700_000_000_600]+++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++ monkeypatch.setattr(library, "_SOURCES", (library._audio_items, library._video_items))+ audio = _gallery_audio("Hello from the Library")+ video, shelved = _gallery_video("A calm sea"), _gallery_video("Archived")+ video_gallery.set_flags(shelved, archived = True)+ items = _items(client)[0]+ item = items[f"audio:{audio}"]+ assert (item["name"], item["contentType"]) == ("Hello from the Library.wav", "audio/wav")+ assert (item["source"], item["createdAt"]) == ("generated", 1_700_000_000_000)+ item = items[f"video:{video}"]+ assert (item["name"], item["contentType"]) == ("A calm sea.mp4", "video/mp4")+ assert (item["archived"], items[f"video:{shelved}"]["archived"]) == (False, True)+ assert _delete(client, f"audio:{audio}") == 200+ assert audio_gallery.audio_path(audio) is None++ forgotten = []+ monkeypatch.setattr(video_routes, "_forget_terminal_video", forgotten.append)+ monkeypatch.setattr(video_routes, "_forget_openai_job", lambda ref: False)+ response = _post(client, "items/delete", id = f"video:{video}")+ assert response.status_code == 500 and "video job" in response.json()["detail"]+ assert video_gallery.video_path(video) is not None+ monkeypatch.setattr(video_routes, "_forget_openai_job", lambda ref: forgotten.append(ref) or 1)+ assert _delete(client, f"video:{video}") == 200+ assert video_gallery.video_path(video) is None+ assert forgotten == [video, video]+++def test_favorites_list_only_stars_the_source_still_has(client, monkeypatch):+ from core.inference import image_gallery++ [starred, plain] = _upload(client, ("a.txt", b"a", "text/plain"), ("b.txt", b"b", "text/plain"))+ image = f"image:{_gallery_image('A star')}"+ for item_id, favorite in ((starred, True), (plain, False), (image, True), ("image:gone", True)):+ _patch(client, id = item_id, favorite = favorite)+ reads = []+ real = image_gallery._read_meta+ monkeypatch.setattr(image_gallery, "_read_meta", lambda path: reads.append(path) or real(path))+ assert set(_favorites(client)) == {starred, image}+ assert reads == []+ image_gallery.image_path(_ref(image)).unlink()+ assert _favorites(client) == [starred]+ assert (_delete(client, starred), _delete(client, "image:gone")) == (200, 404)+ assert set(library_db.list_entries()) == {plain, image}+ assert _delete(client, "elsewhere:x") == 400+++def test_leftovers_of_a_crash_are_swept_from_the_uploads_folder(client):+ import time++ [kept, interrupted] = _upload(+ client, ("k.txt", b"k", "text/plain"), ("i.txt", b"i", "text/plain")+ )+ directory = library.uploads_dir()+ aside = directory / f".{_ref(interrupted)}.deleting"+ os.replace(directory / _ref(interrupted), aside)+ stale = [directory / ".0123.tmp", directory / f".{'a' * 32}.deleting"]+ fresh = directory / ".4567.tmp"+ for path in (*stale, fresh):+ path.write_bytes(b"x")+ old = time.time() - 2 * library._LEFTOVER_AGE_SECONDS+ for path in (*stale, aside):+ os.utime(path, (old, old))+ library._swept_at.clear()+ items = _items(client)[0]+ assert {kept, interrupted} <= set(items)+ names = {path.name for path in directory.iterdir()}+ assert names == {_ref(kept), _ref(interrupted), fresh.name}+ assert client.get(items[interrupted]["fileUrl"]).content == b"i"+++def test_fine_tuned_models_are_listed_but_not_deleted_here(client, monkeypatch):+ import shutil++ from utils.paths.storage_roots import 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.mkdir()+ (run / "adapter_config.json").write_text('{"base_model_name_or_path": "unsloth/base"}')+ (run / "adapter_model.safetensors").write_bytes(b"x" * 10)+ try:+ assert library._model_stamp() != stamp+ [item] = [item for item in _items(client)[0].values() if item["name"] == run.name]+ assert item["contentType"] == library.MODEL_CONTENT_TYPE+ assert (item["model"]["origin"], item["model"]["exportType"]) == ("training", "lora")+ assert item["sizeBytes"] >= 10+ assert _delete(client, item["id"]) == 400+ assert run.is_dir()+ finally:+ shutil.rmtree(run)+++def test_an_api_key_lists_fine_tunes_by_reference_and_can_still_act_on_them(client, monkeypatch):+ import shutil++ from utils.paths.storage_roots import outputs_root++ monkeypatch.setattr(library, "_SOURCES", (library._model_items,))+ outputs_root().mkdir(parents = True, exist_ok = True)+ run = outputs_root() / "library-key-run"+ run.mkdir()+ local_base = str(outputs_root() / "my-local-base")+ (run / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": local_base}))+ (run / "adapter_model.safetensors").write_bytes(b"x" * 10)+ try:+ library.invalidate_listing()+ client.app.dependency_overrides[library_routes.authenticated_via_api_key] = lambda: True+ body = client.get("/api/library").text+ assert str(run) not in body and local_base not in body+ [item] = [i for i in json.loads(body)["items"] if i["name"] == run.name]+ _patch(client, id = item["id"], favorite = True)+ assert str(run) not in json.dumps(_favorites(client))+ client.app.dependency_overrides[library_routes.authenticated_via_api_key] = lambda: False+ assert f"model:training:{run}" in _favorites(client)+ finally:+ shutil.rmtree(run)+++def test_a_file_part_kept_as_a_data_url_decodes():+ import base64++ from routes.chat_history import _decode_attachment_base64++ clip = base64.b64encode(_CLIP).decode()+ assert _decode_attachment_base64(f"data:video/mp4;base64,{clip}") == _CLIP+ assert _decode_attachment_base64(clip) == _CLIP+++def test_gallery_iso_dates_and_suffixless_chat_media_names():+ assert library._to_ms("2026-09-25T10:00:00Z") == 1790330400000+ assert library._to_ms(1790330400) == 1790330400000+ assert library._to_ms("not a date") == 0+ assert library._named_for_type("Chat image", "image/png") == "Chat image.png"+ assert library._named_for_type("Chat audio", "audio/wav") == "Chat audio.wav"+ assert library._named_for_type("photo.jpg", "image/jpeg") == "photo.jpg"+ assert library._named_for_type("notes", "application/pdf") == "notes"+++def test_an_empty_parent_or_folder_id_is_refused(client):+ assert _post(client, "folders", name = "x", parentId = "").status_code == 422+ assert (+ client.patch("/api/library/items", json = {"id": "upload:x", "folderId": ""}).status_code+ == 422+ )+++def test_an_upload_file_is_revalidated_after_a_note_save(client):+ [note] = _upload(client, ("plan.md", b"# plan", "text/markdown"))+ response = client.get(_items(client)[0][note]["fileUrl"])+ assert "no-cache" in response.headers["cache-control"]+++def test_the_listing_memo_is_bounded():+ assert library._LISTING.size > 0+++def test_the_slow_sources_are_remembered_briefly_and_forgotten_on_a_write(client, monkeypatch):+ calls = []++ def walked():+ calls.append(1)+ fields = {"source": "generated", "content_type": "text/plain", "file_url": ""}+ return [+ library._item("sandbox:t:a.txt", name = "a.txt", size_bytes = 1, created_at = 1, **fields)+ ]++ def broken():+ raise RuntimeError("gallery unreadable")++ monkeypatch.setattr(library, "_sandbox_items", walked)+ monkeypatch.setattr(library, "_SOURCES", (library._remembered("_sandbox_items", 60), broken))+ # Listed only, never written: the star is kept for the file it would find.+ monkeypatch.setattr(library, "fingerprint", lambda _item_id: "1:1")+ _patch(client, id = "sandbox:t:a.txt", favorite = True)+ for _ in range(2):+ assert _items(client)[0]["sandbox:t:a.txt"]["favorite"] is True+ assert len(calls) == 1+ # Another account's listing is never this one's.+ monkeypatch.setattr(library, "_account_key", lambda: "other")+ _items(client)+ _items(client)+ assert len(calls) == 2+ library.invalidate_listing()+ _items(client)+ assert len(calls) == 3+++def test_an_overlay_row_stays_with_the_file_it_was_made_for(client, monkeypatch, tmp_path):+ monkeypatch.setattr(library, "_SOURCES", (library._sandbox_items,))+ _directory, path = _sandbox_chat("report.txt", b"v1")++ def make_again():+ os.replace(path, tmp_path / f"old-{len(os.listdir(tmp_path))}")+ Path(path).write_bytes(b"new")+ library.invalidate_listing()++ library_db.update_entry(_SANDBOX_ID, favorite = True)+ assert library_db.list_entries()[_SANDBOX_ID]["fingerprint"] is None+ item = _items(client)[0][_SANDBOX_ID]+ assert item["favorite"] is True and "_fingerprint" not in item+ assert library_db.list_entries()[_SANDBOX_ID]["fingerprint"] == library.fingerprint(_SANDBOX_ID)++ _patch(client, id = _SANDBOX_ID, name = "Q3")+ with open(path, "ab") as handle:+ handle.write(b" and v2")+ library.invalidate_listing()+ item = _items(client)[0][_SANDBOX_ID]+ assert (item["favorite"], item["name"]) == (True, "Q3")+ assert _favorites(client) == [_SANDBOX_ID]++ make_again()+ assert _favorites(client) == []+ _patch(client, id = _SANDBOX_ID, folderId = None)+ entry = library_db.list_entries()[_SANDBOX_ID]+ assert (entry["name"], entry["favorite"]) == (None, False)++ _patch(client, id = _SANDBOX_ID, favorite = True, name = "Old")+ make_again()+ item = _items(client)[0][_SANDBOX_ID]+ assert (item["favorite"], item["name"]) == (False, "report.txt")+ assert _SANDBOX_ID not in library_db.list_entries()+++def test_an_older_database_is_upgraded_and_checked_once(client, monkeypatch, tmp_path):+ (tmp_path / "real").mkdir()+ conn = sqlite3.connect(tmp_path / "real" / "studio.db")+ conn.execute(+ "CREATE TABLE library_entries (item_id TEXT NOT NULL PRIMARY KEY, name TEXT, "+ "favorite INTEGER NOT NULL DEFAULT 0, folder_id TEXT, updated_at INTEGER NOT NULL)"+ )+ conn.execute("INSERT INTO library_entries (item_id, favorite, updated_at) VALUES ('x', 1, 1)")+ conn.commit()+ conn.close()+ (tmp_path / "link").symlink_to(tmp_path / "real", target_is_directory = True)+ monkeypatch.setattr(library_db, "studio_db_path", lambda: tmp_path / "link" / "studio.db")+ assert library_db.list_entries()["x"] == {+ "name": None,+ "favorite": True,+ "folderId": None,+ "updatedAt": 1,+ "fingerprint": None,+ }+ runs = []+ monkeypatch.setattr(library_db, "_ensure_schema", runs.append)+ for _ in range(3):+ library_db.get_connection().close()+ assert runs == []+++def test_a_failed_write_leaves_the_uploads_as_they_were(client, monkeypatch):+ [note] = _upload(client, ("n.md", b"old", "text/markdown"))+ for name, call in (+ ("touch_upload", lambda: library.write_upload_text(_ref(note), "new")),+ ("delete_upload", lambda: library.delete_item(note)),+ ("insert_upload", lambda: library.save_upload("a.txt", "text/plain", [b"hi"])),+ ):+ with monkeypatch.context() as patched:+ patched.setattr(library_db, name, _fail)+ with pytest.raises(sqlite3.OperationalError):+ call()+ assert library.upload_path(_ref(note)).read_bytes() == b"old"+ assert [path.name for path in library.uploads_dir().iterdir()] == [_ref(note)]+ assert note in _items(client)[0]+++def test_a_note_save_keeps_the_old_file_on_disk_not_in_memory(client, monkeypatch):+ from pathlib import Path++ [note] = _upload(client, ("n.md", b"old", "text/markdown"))+ path = library.upload_path(_ref(note))+ read = Path.read_bytes+ with monkeypatch.context() as patched:+ patched.setattr(+ Path, "read_bytes", lambda self: pytest.fail("read") if self == path else read(self)+ )+ patched.setattr(library_db, "touch_upload", _fail)+ with pytest.raises(sqlite3.OperationalError):+ library.write_upload_text(_ref(note), "new")+ assert path.read_bytes() == b"old"+ assert library.write_upload_text(_ref(note), "new")+ assert path.read_bytes() == b"new"+ assert [p.name for p in library.uploads_dir().iterdir()] == [_ref(note)]+++def test_a_file_held_open_on_windows_answers_409(client, monkeypatch):+ [note] = _upload(client, ("n.md", b"old", "text/markdown"))+ url = f"/api/library/uploads/{_ref(note)}/text"++ def held(*_args):+ raise PermissionError(13, "The process cannot access the file")++ monkeypatch.setattr(library.os, "replace", held)+ response = client.put(url, json = {"text": "new"})+ assert response.status_code == 409+ assert response.json()["detail"] == "The file is in use. Close it and try again."+ assert _delete(client, note) == 409++ def broken(*_args):+ raise OSError(5, "I/O error", "/secret/path")++ monkeypatch.setattr(library.os, "replace", broken)+ for response in (client.put(url, json = {"text": "new"}), _post(client, "items/delete", id = note)):+ assert response.status_code == 500 and "/secret" not in response.text+ assert [path.name for path in library.uploads_dir().iterdir()] == [_ref(note)]+ assert library.upload_path(_ref(note)).read_bytes() == b"old"+++def test_concurrent_deletes_and_note_saves_leave_nothing_behind(client):+ from concurrent.futures import ThreadPoolExecutor++ [upload, note] = _upload(+ client, ("twice.txt", b"hi", "text/plain"), ("n.md", b"old", "text/markdown")+ )+ with ThreadPoolExecutor(8) as pool:+ deletes = [pool.submit(library.delete_item, upload) for _ in range(4)]+ saves = [pool.submit(library.write_upload_text, _ref(note), f"v{i}") for i in range(6)]+ saves.append(pool.submit(library.delete_item, note))+ [job.result() for job in saves]+ assert [job.result() for job in deletes].count(True) == 1+ assert not any(library.uploads_dir().iterdir())+ assert _items(client)[0] == {}+++def lease_secret(monkeypatch):+ import utils.native_path_leases as leases++ secret = base64.urlsafe_b64encode(SECRET).decode("ascii").rstrip("=")+ monkeypatch.setenv(leases.LEASE_SECRET_ENV, secret)+ monkeypatch.setattr(leases, "_CACHED_LEASE_SECRET", None, raising = False)+ yield+ monkeypatch.setattr(leases, "_CACHED_LEASE_SECRET", None, raising = False)++[email protected]("swap", ["link", "file"])+def test_a_desktop_drop_swapped_after_its_check_is_refused(+ client, lease_secret, tmp_path, monkeypatch, swap+):+ path = _file(tmp_path / "notes.txt", "mine")+ outside = _file(tmp_path / "outside.txt", "your")+ lease = _sign(path)+ real = library._verify_native++ def swapped_after_the_check(*args, **kwargs):+ grant = real(*args, **kwargs)+ if kwargs.get("consume"):+ path.unlink()+ if swap == "link":+ path.symlink_to(outside)+ else:+ os.replace(outside, path)+ return grant++ monkeypatch.setattr(library, "_verify_native", swapped_after_the_check)+ assert _send(client, [], nativePathLeases = [lease]).status_code == 400+ assert _items(client)[0] == {}+++def test_a_desktop_drop_is_read_from_its_signed_path_once_the_whole_batch_checks(+ client, lease_secret, tmp_path+):+ lease = _sign(_file(tmp_path / "Quarterly report.pdf", "%PDF-1.7 report"))+ forged = _sign(_file(tmp_path / "other.txt", "hi"), secret = b"x" * 32)+ response = _send(+ client, [("kept.md", b"# hi", "text/markdown")], nativePathLeases = [lease, forged]+ )+ assert response.status_code == 400+ assert response.json()["detail"] == "The dropped file could not be read. Drop it again."+ assert _items(client)[0] == {} and list(library.uploads_dir().iterdir()) == []+ folder = _folder(client, "Work", None)+ response = _send(client, [], nativePathLeases = [lease], folderId = folder)+ assert response.status_code == 200, response.text+ [item_id] = response.json()["ids"]+ item = _items(client)[0][item_id]+ assert (item["name"], item["contentType"]) == ("Quarterly report.pdf", "application/pdf")+ assert item["folderId"] == folder+ assert client.get(item["fileUrl"]).content == b"%PDF-1.7 report"+ assert _send(client, []).status_code == 400+++def test_a_failed_batch_keeps_nothing_and_gives_its_grants_back(+ client, lease_secret, tmp_path, monkeypatch+):+ leases = [_sign(_file(tmp_path / "a.txt", "a")), _sign(_file(tmp_path / "b.txt", "b"))]+ original = library.save_upload+ calls = []++ def fail_second(*args):+ calls.append(args[0])+ if len(calls) == 2:+ raise OSError("disk full")+ return original(*args)++ def gone(*_args, **_kwargs):+ raise KeyError("folder")++ with monkeypatch.context() as patched:+ patched.setattr(library, "save_upload", fail_second)+ with pytest.raises(OSError):+ _send(client, [], nativePathLeases = leases)+ assert _items(client)[0] == {}+ folder = _folder(client, "Work", None)+ with monkeypatch.context() as patched:+ patched.setattr(library_db, "update_entry", gone)+ plan = ("plan.md", b"# plan", "text/markdown")+ response = _send(client, [plan], nativePathLeases = leases, folderId = folder)+ assert response.status_code == 404+ assert _items(client)[0] == {}+ response = _send(client, [], nativePathLeases = leases)+ assert response.status_code == 200 and len(response.json()["ids"]) == 2+ assert _send(client, [], nativePathLeases = leases[:1]).status_code == 400+++def test_an_oversized_desktop_drop_is_refused_before_copying(client, monkeypatch, tmp_path):+ big = _file(tmp_path / "big.bin", "x" * 10)+ monkeypatch.setattr(library_routes, "_MAX_UPLOAD_BYTES", 4)+ opened = lambda lease: ("big.bin", "application/octet-stream", open(big, "rb")) # noqa: E731+ monkeypatch.setattr(library, "open_native_upload", opened)++ def copied(*_args):+ raise AssertionError("copied an oversized drop")++ monkeypatch.setattr(library, "save_upload", copied)+ for size in (10, 1):+ monkeypatch.setattr(+ library, "check_native_upload", lambda lease, size = size: ("big.bin", size)+ )+ assert _send(client, [], nativePathLeases = ["lease"]).status_code == 413+++def project(tmp_path, monkeypatch):+ import storage.studio_db as studio_db++ root = tmp_path / "Projects" / "demo"+ (root / "sandbox").mkdir(parents = True)+ record = {"id": "p1", "rootPath": str(root), "sandboxPath": str(root / "sandbox")}+ monkeypatch.setattr(+ studio_db, "ensure_chat_project_workspace", lambda pid: record if pid == "p1" else None+ )+ return root / "sandbox"+++def test_an_upload_is_copied_into_a_project_under_its_own_name(client, project, tmp_path):+ from core.inference import gallery_projects++ [note] = _upload(client, ("plan.md", b"# plan", "text/markdown"))+ add = lambda item_id, project_id: _post( # noqa: E731+ client, "items/project", id = item_id, projectId = project_id+ )+ assert add(note, "p1").json() == {"already": False}+ [copied] = (project / "files").iterdir()+ assert copied.name.startswith("plan-") and copied.suffix == ".md"+ assert copied.read_bytes() == b"# plan"+ assert add(note, "p1").json() == {"already": True}+ assert add(note, "missing").status_code == 404+ assert add("upload:0123456789abcdef0123456789abcdef", "p1").status_code == 404+ assert add("attachment:m:a", "p1").status_code == 400+ assert add("model:training:/tmp/run", "p1").status_code == 400+ source = _file(tmp_path / "x.txt", "x")+ for bad in ("a:b.txt", "CON.txt", "trailing.", "tab\there.txt"):+ with pytest.raises(ValueError):+ gallery_projects.copy_into_project(source, "p1", "files", bad)+ with open(source, "rb") as handle:+ result = gallery_projects.copy_into_project(handle, "p1", "files", "x-1.txt")+ assert Path(result["path"]).read_text() == "x"+++ "name, safe",+ [+ ("report.csv", "report.csv"),+ ("a<b>c:d|e?.txt", "a b c d e.txt"),+ ("CON.txt", "_CON.txt"),+ ("lpt1", "_lpt1"),+ ("notes. . .", "notes"),+ (".env", "env"),+ ("line\nbreak\ttab.md", "line break tab.md"),+ ("...", "file"),+ ("C:\\Users\\me\\x.txt", "x.txt"),+ pytest.param("\U0001f9a5" * 80 + ".txt", "\U0001f9a5" * 50 + ".txt", id = "sloths"),+ ],+)+def test_names_written_to_disk_are_valid_on_windows(name, safe):+ from core.inference.gallery_projects import _bad_name, _tmp_name++ assert library.safe_file_name(name) == safe+ project_name = library.safe_file_name(name, item_id = "upload:x")+ assert not _bad_name(project_name), project_name+ assert len(_tmp_name(project_name).encode()) <= 255+++def test_items_download_as_attachments_under_the_name_they_were_given(client, monkeypatch):+ [upload] = _upload(client, ("re:port*q3?.html", b"<script>1</script>", "text/html"))+ assert _download(client, upload).status_code == 401+ monkeypatch.setattr(library_routes, "subject_for_header_or_query_token", _signed_in_subject)+ response = _download(client, upload)+ assert (response.status_code, response.content) == (200, b"<script>1</script>")+ assert response.headers["content-type"] == "application/octet-stream"+ disposition = response.headers["content-disposition"]+ assert disposition.startswith('attachment; filename="re port q3.html"')+ assert response.headers["content-length"] == "18"+ assert response.headers["x-content-type-options"] == "nosniff"+ head = client.head("/api/library/items/download", params = {"id": upload})+ assert (head.status_code, head.content) == (200, b"")+ assert _download(client, "upload:" + "0" * 32).status_code == 404+ assert _download(client, "attachment:m:a").status_code == 400+++def test_generated_media_download_under_their_prompt(client, signed_in, project):+ from core.inference import gallery_projects, image_gallery++ def disposition(item_id):+ response = _download(client, item_id)+ assert response.status_code == 200+ return response.headers["content-disposition"]++ image = _gallery_image('A red fox: "at dawn"')+ assert disposition(f"image:{image}").startswith('attachment; filename="A red fox at dawn.png"')+ image = _gallery_image("Café ☕ at noon")+ assert f"filename*=UTF-8''{quote('Café ☕ at noon.png')}" in disposition(f"image:{image}")+ # No prompt: the id, never an empty name.+ image = _gallery_image(" ")+ assert f'filename="{image}.png"' in disposition(f"image:{image}")+ assert 'filename="Hello there.wav"' in disposition(f"audio:{_gallery_audio('Hello there')}")++ first, second = _gallery_image("Same prompt"), _gallery_image("Same prompt")+ for image in (first, second):+ response = _post(client, "items/project", id = f"image:{image}", projectId = "p1")+ assert response.json() == {"already": False}+ names = sorted(path.name for path in (project / "images").iterdir())+ assert names == sorted(f"{image}.png" for image in (first, second))+ path = image_gallery.owned_image_path(first)+ assert gallery_projects.copy_into_project(path, "p1", "images")["already"] is True+++def test_a_sandbox_file_is_reachable_by_id_only_as_the_listing_walks_it(+ client, signed_in, monkeypatch+):+ import routes.inference as inference++ monkeypatch.setattr(library, "_SOURCES", (library._sandbox_items,))+ monkeypatch.setattr(inference, "_MAX_SNAPSHOT_FILES", 3)+ directory, _path = _sandbox_chat("a.txt", b"mine")+ for name in ("b.txt", "c.txt", ".env", "d1/d2/d3/d4/deep.txt"):+ _sandbox_chat(name, b"x")+ walks = []+ real = inference._sandbox_listing_names+ monkeypatch.setattr(+ inference, "_sandbox_listing_names", lambda path: walks.append(path) or real(path)+ )+ status = lambda name: _download(client, f"sandbox:t-lib:{name}").status_code # noqa: E731++ def listed(*_args):+ raise AssertionError("a per-item route listed the sandboxes")++ with monkeypatch.context() as patched:+ # A card's file never lists every chat, and its sandbox is walked once for every card.+ patched.setattr(library, "_sandbox_sessions", listed)+ response = _download(client, "sandbox:t-lib:a.txt")+ assert response.content == b"mine"+ assert 'filename="a.txt"' in response.headers["content-disposition"]+ assert status("b.txt") == 200 and len(walks) == 1+ for name in ("c.txt", ".env", "d1/d2/d3/d4/deep.txt", "../x", ".hidden"):+ assert status(name) == 404, name+ assert _download(client, "sandbox:nope:a.txt").status_code == 404+ assert set(_items(client)[0]) == {"sandbox:t-lib:a.txt", "sandbox:t-lib:b.txt"}+ library.invalidate_listing()+ _items(client)+ walks.clear()+ assert (status("a.txt"), status("c.txt"), walks) == (200, 404, [])+ for item_id in ("sandbox:t-lib:.env", "sandbox:t-lib:c.txt", "sandbox:not-a-chat:a.txt"):+ assert _delete(client, item_id) == 404, item_id+ assert os.path.exists(os.path.join(directory, ".env"))+ assert os.path.exists(os.path.join(directory, "c.txt"))+ assert _delete(client, "sandbox:t-lib:a.txt") == 200+ assert not os.path.exists(os.path.join(directory, "a.txt"))++[email protected](not hasattr(os, "mkfifo"), reason = "no FIFOs on this OS")+def test_a_file_swapped_for_a_fifo_is_refused_without_waiting_for_a_writer(tmp_path):+ import threading++ fifo = tmp_path / "out.png"+ os.mkfifo(fifo)+ outcome = []++ def open_it():+ try:+ library._open_regular(str(fifo)).close()+ outcome.append("opened")+ except LookupError:+ outcome.append("refused")++ worker = threading.Thread(target = open_it, daemon = True)+ worker.start()+ worker.join(5)+ if worker.is_alive():+ # Unblock the stuck open so the thread ends, then fail.+ os.close(os.open(fifo, os.O_WRONLY | os.O_NONBLOCK))+ assert outcome == ["refused"]++[email protected]("route", ["download", "stream"])+def test_a_sandbox_file_swapped_for_a_link_after_the_check_is_not_read(+ client, signed_in, monkeypatch, tmp_path, route+):+ secret = _file(tmp_path / "secret.mp3", "secret")+ _directory, path = _sandbox_chat("song.mp3", b"mine")+ item_id = "sandbox:t-lib:song.mp3"+ if route == "stream":+ url = _stream_url(client, item_id)+ assert _app(None).get(url).content == b"mine"+ real = library._sandbox_path+ swapped = []++ def swap_after_check(ref):+ checked = real(ref)+ if not swapped:+ os.unlink(path)+ os.symlink(secret, path)+ swapped.append(ref)+ return checked++ monkeypatch.setattr(library, "_sandbox_path", swap_after_check)+ response = _app(None).get(url) if route == "stream" else _download(client, item_id)+ assert response.status_code == 404+ assert b"secret" not in response.content+++def test_a_projects_own_files_are_listed(client, monkeypatch, tmp_path):+ from core.inference.tools import resolve_sandbox_workdir+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects home"))+ monkeypatch.setattr(library, "_SOURCES", (library._sandbox_items,))+ project = studio_db.upsert_chat_project(+ {"id": "p-lib", "name": "Research", "createdAt": 1, "updatedAt": 1}+ )+ # Studio gives every project a folder of its own, so the column is never empty.+ assert project["rootPath"]+ directory = resolve_sandbox_workdir("project-p-lib")+ os.makedirs(os.path.join(directory, "files"), exist_ok = True)+ Path(directory, "files", "notes.txt").write_text("x")+ item = _items(client)[0]["sandbox:project-p-lib:files/notes.txt"]+ assert item["threadTitle"] == "Research"++ own = tmp_path / "My code"+ conn = studio_db.get_connection()+ conn.execute("UPDATE chat_projects SET root_path = ? WHERE id = 'p-lib'", (str(own),))+ conn.commit()+ conn.close()+ assert not library._studio_project_root(str(own))+ assert "sandbox:project-p-lib:files/notes.txt" not in _items(client)[0]+++def revealed(monkeypatch):+ import utils.paths.file_manager as file_manager+ import utils.paths.path_utils as path_utils++ calls = []+ monkeypatch.setattr(file_manager, "file_manager_kind", lambda: "files")+ monkeypatch.setattr(path_utils, "reveal_in_file_manager", lambda path: calls.append(str(path)))+ return calls+++def test_reveal_opens_an_items_own_file_or_a_location_by_key(client, revealed):+ reveal = lambda item_id: _post(client, "items/reveal", id = item_id).status_code # noqa: E731+ [note] = _upload(client, ("plan.md", b"# plan", "text/markdown"))+ assert reveal("attachment:m:a") == 400+ assert reveal("upload:0123456789abcdef0123456789abcdef") == 404+ assert reveal("model:training:/etc") == 404+ assert _post(client, "locations/reveal", key = "/etc").status_code == 404+ assert revealed == []+ assert reveal(note) == 200+ locations = client.get("/api/library/locations").json()["locations"]+ paths = {entry["key"]: entry["path"] for entry in locations}+ assert set(paths) == {"uploads", "images", "videos", "audio", "fineTunes", "exports"}+ assert _post(client, "locations/reveal", key = "images").status_code == 200+ assert revealed == [str(library.upload_path(_ref(note))), paths["images"]]+++def test_locations_hide_host_paths_from_an_api_key(client):+ signed_in = client.get("/api/library/locations").json()["locations"]+ assert all(os.path.isabs(entry["path"]) for entry in signed_in)+ client.app.dependency_overrides[authenticated_via_api_key] = lambda: True+ keyed = client.get("/api/library/locations").json()["locations"]+ assert [entry["key"] for entry in keyed] == [entry["key"] for entry in signed_in]+ for entry, shown in zip(keyed, signed_in):+ assert entry["path"] != shown["path"]+ assert shown["path"] not in json.dumps(entry)+++def test_reveal_is_refused_to_a_managed_account_and_where_no_file_manager_is(+ client, revealed, monkeypatch+):+ import utils.paths.file_manager as file_manager+ import utils.paths.path_utils as path_utils++ [note] = _upload(client, ("plan.md", b"# plan", "text/markdown"))+ reveal = lambda: ( # noqa: E731+ _post(client, "items/reveal", id = note).status_code,+ _post(client, "locations/reveal", key = "images").status_code,+ )+ with monkeypatch.context() as managed:+ managed.setattr(library_routes.account_access, "managed_account", lambda: True)+ assert reveal() == (403, 403)+ monkeypatch.setattr(file_manager, "file_manager_kind", lambda: None)+ assert reveal() == (503, 503)+ assert revealed == []++ def no_launcher(path):+ raise FileNotFoundError(2, "No such file or directory: 'xdg-open'")++ monkeypatch.setattr(file_manager, "file_manager_kind", lambda: "files")+ monkeypatch.setattr(path_utils, "reveal_in_file_manager", no_launcher)+ response = _post(client, "items/reveal", id = note)+ assert response.status_code == 503+ assert response.json()["detail"] == "No file manager is available on this machine"+++def _os_named(name):+ # A copy of os for one module: setting the real os.name to "nt" breaks pathlib in pytest itself.+ import types++ fake = types.ModuleType("os")+ fake.__dict__.update(os.__dict__)+ fake.name = name+ return fake+++ "platform, os_name, wsl, container, display, expected",+ [+ ("darwin", "posix", False, False, None, "finder"),+ ("win32", "nt", False, False, None, "explorer"),+ ("linux", "posix", True, False, None, "explorer"),+ ("linux", "posix", False, False, None, None),+ ("linux", "posix", False, False, "WAYLAND_DISPLAY", "files"),+ # Never in a container, even with a display.+ ("linux", "posix", False, True, "DISPLAY", None),+ ],+)+def test_file_manager_is_named_only_where_a_window_can_appear(+ monkeypatch, platform, os_name, wsl, container, display, expected+):+ from utils.paths import file_manager, path_utils++ monkeypatch.setattr(file_manager.sys, "platform", platform)+ monkeypatch.setattr(file_manager, "os", _os_named(os_name))+ monkeypatch.setattr(path_utils, "_IS_WSL", wsl)+ monkeypatch.setattr(file_manager, "_in_container", lambda: container)+ for name in ("DISPLAY", "WAYLAND_DISPLAY"):+ monkeypatch.delenv(name, raising = False)+ if display:+ monkeypatch.setenv(display, ":0")+ assert file_manager.file_manager_kind() == expected+++def test_explorer_gets_the_documented_select_command(tmp_path, monkeypatch):+ import subprocess+ from types import SimpleNamespace++ import utils.paths.path_utils as path_utils++ target = tmp_path / "a b" / "c.txt"+ target.parent.mkdir()+ target.write_text("x")+ calls = []+ monkeypatch.setattr(subprocess, "Popen", lambda command, *args, **kwargs: calls.append(command))+ with monkeypatch.context() as windows:+ windows.setattr(path_utils.sys, "platform", "win32")+ windows.setattr(path_utils, "os", _os_named("nt"))+ path_utils.reveal_in_file_manager(target)+ assert calls.pop() == f'explorer /select,"{target}"'+ windows_path = "C:\\Users\\me\\a b\\c.txt"+ monkeypatch.setattr(path_utils, "_IS_WSL", True)+ monkeypatch.setattr(+ subprocess, "run", lambda *_a, **_k: SimpleNamespace(stdout = f"{windows_path}\n")+ )+ assert path_utils._wsl_reveal_in_explorer(target, is_file = True)+ assert calls == [["explorer.exe", "/select,", windows_path]]+++ "path, root, inside",+ [+ (r"\\?\C:\Users\me\Studio\library\x", r"C:\Users\me\Studio", True),+ (r"C:\Users\me\Studio\library\x", r"\\?\c:\users\ME\studio", True),+ (r"\\?\UNC\server\share\Studio\x", r"\\server\share\Studio", True),+ (r"C:\Users\me\Studio2\x", r"C:\Users\me\Studio", False),+ (r"D:\Studio\x", r"C:\Studio", False),+ (r"C:\Studio", r"C:\Studio", False),+ ("C:\\x", "C:\\", True),+ ],+)+def test_containment_ignores_the_windows_long_path_prefix(path, root, inside):+ import ntpath++ from utils.paths.path_utils import is_path_within+ assert is_path_within(path, root, pathmod = ntpath) is inside+++ "size, mode, thumbnail",+ [+ ((3000, 2000), "RGB", (640, 427)),+ ((1000, 5000), "RGBA", (640, 960)),+ ((4000, 500), "RGB", (640, 427)),+ # Never scaled up.+ ((100, 80), "RGB", (100, 80)),+ ],+)+def test_image_thumbnail_is_bounded_and_cropped_as_the_card_shows_it(client, size, mode, thumbnail):+ [image] = _upload(client, ("pic.png", _png(*size, mode), "application/octet-stream"))+ assert _thumbnail_size(client, image) == thumbnail+++def _clip(width, height) -> bytes:+ av = pytest.importorskip("av")+ np = pytest.importorskip("numpy")+ buf = io.BytesIO()+ with av.open(buf, mode = "w", format = "mp4") as out:+ stream = out.add_stream("libx264", rate = 4)+ stream.width, stream.height, stream.pix_fmt = width, height, "yuv420p"+ pixels = np.full((height, width, 3), 80, dtype = np.uint8)+ out.mux(stream.encode(av.VideoFrame.from_ndarray(pixels, format = "rgb24")))+ out.mux(stream.encode())+ return buf.getvalue()+++def test_a_tall_clip_thumbnail_is_bounded_in_height_too(client):+ [clip] = _upload(client, ("tall.mp4", _clip(32, 4000), "video/mp4"))+ assert _thumbnail_size(client, clip) == (8, 960)+++def test_video_upload_thumbnail_is_its_first_frame(client):+ av = pytest.importorskip("av")+ np = pytest.importorskip("numpy")+ buf = io.BytesIO()+ with av.open(buf, mode = "w", format = "mp4") as out:+ stream = out.add_stream("libx264", rate = 4)+ stream.width, stream.height, stream.pix_fmt = 64, 48, "yuv420p"+ for index in range(4):+ pixels = np.full((48, 64, 3), index * 40, dtype = np.uint8)+ out.mux(stream.encode(av.VideoFrame.from_ndarray(pixels, format = "rgb24")))+ out.mux(stream.encode())+ [clip] = _upload(client, ("clip.mp4", buf.getvalue(), "video/mp4"))+ assert _thumbnail_size(client, clip) == (64, 48)+++def test_what_is_not_a_small_raster_or_clip_has_no_thumbnail(client, monkeypatch):+ from PIL import Image++ monkeypatch.setattr(library, "_THUMBNAIL_MAX_PIXELS", 100 * 100)+ ppm = io.BytesIO()+ Image.new("RGB", (8, 8)).save(ppm, format = "PPM")+ eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 8 8\nshowpage\n"+ undecodable = _upload(+ client,+ ("huge.png", _png(101, 100, "RGB"), "image/png"),+ ("broken.png", b"not a png", "image/png"),+ # A format Pillow knows but a card does not need is never handed to its decoder.+ ("pic.png", ppm.getvalue(), "image/png"),+ ("pic.jpg", eps, "image/jpeg"),+ ("broken.mp4", b"not a video", "video/mp4"),+ )+ for item_id in undecodable:+ assert _thumbnail(client, item_id).status_code == 501, item_id+ no_picture = _upload(+ client, ("note.md", b"# hi", "text/markdown"), ("icon.svg", b"<svg/>", "image/svg+xml")+ )+ for item_id in (*no_picture, "upload:" + "0" * 32, "model:training:/tmp/x", "image:missing"):+ assert _thumbnail(client, item_id).status_code == 404, item_id+++def test_a_video_thumbnail_reads_its_container_by_type(client, monkeypatch):+ from core.inference import video_gallery++ seen = []+ monkeypatch.setattr(+ video_gallery,+ "first_frame_webp",+ lambda source, **kwargs: seen.append((hasattr(source, "read"), kwargs)) or b"webp",+ )+ [clip, playlist, flv] = _upload(+ client,+ ("clip.webm", b"x", "video/webm"),+ ("clip.m3u8", b"#EXTM3U", "video/mp4"),+ ("clip.flv", b"x", "video/x-flv"),+ )+ assert [_thumbnail(client, item_id).status_code for item_id in (clip, playlist)] == [200, 200]+ # A descriptor, never a name to reopen, and a demuxer forced rather than probed, so a playlist+ # sent as mp4 is read as mp4 and never followed as HLS.+ assert [(is_stream, kwargs["container"]) for is_stream, kwargs in seen] == [+ (True, "webm"),+ (True, "mp4"),+ ]+ assert seen[0][1]["max_pixels"] == library._THUMBNAIL_MAX_PIXELS+ assert _thumbnail(client, flv).status_code == 404+++def test_an_attachment_is_read_for_its_thumbnail_only_within_the_decodes_count(client, monkeypatch):+ free = []++ def media(_ref):+ free.append(library._THUMBNAIL_DECODES._value)+ return "image/png", _png(8, 8, "RGB")++ monkeypatch.setattr(library, "_attachment_media", media)+ assert _thumbnail(client, "attachment:m:a").status_code == 200+ assert free == [1]+++def test_thumbnails_are_cached_by_version_and_attachments_have_them_too(client, monkeypatch):+ import storage.studio_db as studio_db++ calls = []+ real = library._decode+ monkeypatch.setattr(+ library, "_decode", lambda mime, source: calls.append(mime) or real(mime, source)+ )+ [image] = _upload(client, ("a.png", _png(40, 30, "RGB"), "image/png"))+ for _ in range(3):+ assert _thumbnail_size(client, image) == (40, 30)+ assert calls == ["image/png"]+ assert _thumbnail(client, image).headers["vary"] == "Authorization"+ library.upload_path(_ref(image)).write_bytes(_png(30, 20, "RGB"))+ assert _thumbnail_size(client, image) == (30, 20)+ assert len(calls) == 2++ data = base64.b64encode(_png(120, 90, "RGB")).decode("ascii")+ attachment = {+ "type": "image",+ "contentType": "image/png",+ "content": [{"type": "image", "image": f"data:image/png;base64,{data}"}],+ }+ monkeypatch.setattr(studio_db, "get_chat_attachment", lambda *_ids: attachment)+ for _ in range(2):+ assert _thumbnail_size(client, "attachment:m:a") == (120, 90)+ assert len(calls) == 3+ attachment["content"] = [{"type": "text", "text": "just words"}]+ assert _thumbnail(client, "attachment:m:a").status_code == 404+++def _mint(client, item_id):+ return client.get("/api/library/items/stream-url", params = {"id": item_id})+++def _stream_url(client, item_id):+ response = _mint(client, item_id)+ assert response.status_code == 200, response.text+ url = response.json()["url"]+ assert url.startswith("/api/library/items/stream?")+ return url+++def _stream(item_id, token):+ # The real dependencies: the stream route must not need the bearer the mint does.+ return _app(None).get("/api/library/items/stream", params = {"id": item_id, "token": token})+++def test_audio_and_video_stream_from_a_signed_link_with_ranges(client):+ [clip, song] = _upload(+ client, ("clip.mp4", _CLIP, "video/mp4"), ("song.mp3", b"ID3" + b"x" * 7, "audio/mpeg")+ )+ url = _stream_url(client, clip)+ stream = _app(None)+ whole = stream.get(url)+ assert (whole.status_code, whole.content) == (200, _CLIP)+ for header, value in (+ ("content-type", "video/mp4"),+ ("x-content-type-options", "nosniff"),+ ("cache-control", "private"),+ ("accept-ranges", "bytes"),+ ("content-length", "100"),+ ):+ assert whole.headers[header] == value, header+ for header, body, content_range in (+ ("bytes=10-19", _CLIP[10:20], "bytes 10-19/100"),+ ("bytes=95-", _CLIP[95:], "bytes 95-99/100"),+ ("bytes=90-500", _CLIP[90:], "bytes 90-99/100"),+ ("bytes=-5", _CLIP[-5:], "bytes 95-99/100"),+ ("bytes=-500", _CLIP, "bytes 0-99/100"),+ ):+ response = stream.get(url, headers = {"Range": header})+ assert (response.status_code, response.content) == (206, body), header+ assert response.headers["content-range"] == content_range, header+ assert response.headers["content-length"] == str(len(body)), header+ for headers in (+ {"Range": "bytes=0-1,5-6"},+ {"Range": "bytes=5-1"},+ {"Range": "items=0-1"},+ {"Range": "bytes=a-b"},+ {"Range": "bytes=0-1", "If-Range": '"etag"'},+ ):+ response = stream.get(url, headers = headers)+ assert (response.status_code, response.content) == (200, _CLIP), headers+ for header in ("bytes=100-", "bytes=-0"):+ response = stream.get(url, headers = {"Range": header})+ assert response.status_code == 416, header+ assert response.headers["content-range"] == "bytes */100"+ head = stream.head(url, headers = {"Range": "bytes=0-9"})+ assert (head.status_code, head.content, head.headers["content-length"]) == (206, b"", "10")+ for item_id, content_type, body in (+ (song, "audio/mpeg", b"ID3" + b"x" * 7),+ (f"video:{_gallery_video('A calm sea')}", "video/mp4", b"\0\0\0\x18ftypmp42"),+ (f"audio:{_gallery_audio('Hello')}", "audio/wav", b"RIFF0000WAVE"),+ ):+ response = stream.get(_stream_url(client, item_id))+ assert (response.status_code, response.headers["content-type"]) == (200, content_type)+ assert response.content == body+++def test_only_audio_and_video_items_get_a_stream_link(client):+ [note, image, unknown] = _upload(+ client,+ ("note.md", b"# hi", "text/markdown"),+ ("pic.png", b"\x89PNG", "image/png"),+ # A declared type the extension map does not know is stored, but never streamed.+ ("clip.xyz", b"x", "video/x-custom"),+ )+ _sandbox_chat("notes.txt", b"text")+ mint = lambda item_id: _mint(client, item_id).status_code # noqa: E731+ for item_id in (note, image, unknown, "sandbox:t-lib:notes.txt", "attachment:m:a"):+ assert mint(item_id) == 400, item_id+ for item_id in ("model:training:/x", "elsewhere:x"):+ assert mint(item_id) == 400, item_id+ assert (mint("upload:" + "0" * 32), mint("video:nope")) == (404, 404)+ # A link can never be made for one, so the stream refuses it even with a valid signature.+ response = _stream(note, library_routes._sign_stream_id(note))+ assert response.status_code == 404 and b"# hi" not in response.content+ assert _mint(_app(None), note).status_code in (401, 403)+ client.app.dependency_overrides[request_admitted_without_credential] = lambda: True+ assert mint(note) == 403+++def test_a_tampered_expired_foreign_or_other_kind_of_link_is_refused(client, monkeypatch):+ import routes.video as video_routes++ [clip, other] = _upload(+ client, ("clip.mp4", _CLIP, "video/mp4"), ("other.mp4", b"other", "video/mp4")+ )+ token = library_routes._sign_stream_id(clip)+ assert _stream(clip, token).status_code == 200+ target, expires, signature = token.rsplit(".", 2)+ for bad in (+ f"{target}.{expires}.{'0' * len(signature)}",+ f"{target}.{expires}." + "\u00e9" * len(signature),+ f"{target}.{int(expires) + 60}.{signature}",+ f"{library_routes._sign_stream_id(other).rsplit('.', 2)[0]}.{expires}.{signature}",+ "nonsense",+ "",+ ):+ assert _stream(clip, bad).status_code in (401, 422), bad+ response = _stream(other, token)+ assert response.status_code == 401 and b"other" not in response.content++ # A Video page link never opens this route, nor one of these the Video page's.+ video = _gallery_video("A calm sea")+ app = FastAPI()+ app.include_router(video_routes.router, prefix = "/api/inference")+ video_page = TestClient(app).get+ video_token = video_routes._sign_video_id(video)+ signed_url = f"/api/inference/video/gallery/{video}/file-signed"+ assert _stream(f"video:{video}", video_token).status_code == 401+ library_token = library_routes._sign_stream_id(video)+ assert video_page(signed_url, params = {"token": library_token}).status_code == 401+ assert video_page(signed_url, params = {"token": video_token}).status_code == 200++ monkeypatch.setattr(library_routes, "_STREAM_LINK_TTL", -1)+ assert _stream(clip, library_routes._sign_stream_id(clip)).status_code == 401+++def two_accounts(monkeypatch, tmp_path):+ from auth import policy, storage as auth_storage+ from utils.account_context import AccountContext++ alice = AccountContext("a" * 32, "alice")+ bob = AccountContext("b" * 32, "bob")+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(auth_storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(auth_storage, "_bootstrap_password", None)+ policy.invalidate_account_cache()+ connection = auth_storage.get_connection()+ with connection:+ for account in (alice, bob):+ connection.execute(+ "INSERT INTO auth_user (username, password_salt, password_hash, jwt_secret,"+ " account_id, role, is_active) VALUES (?, 'salt', 'hash', 'secret', ?, 'user', 1)",+ (account.username, account.account_id),+ )+ connection.close()+ yield alice, bob+ policy.invalidate_account_cache()+++def _account_client(account):+ from utils.account_context import bind_account, reset_account+ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ return _app(subject)+++def test_a_stream_link_reads_only_its_own_accounts_item(client, two_accounts):+ from utils.account_context import OWNER, run_as++ alice, bob = two_accounts+ mine = run_as(alice, library.save_upload, "clip.mp4", "video/mp4", iter([b"alice"]))+ theirs = run_as(bob, library.save_upload, "clip.mp4", "video/mp4", iter([b"bob"]))+ mine_id, theirs_id = f"upload:{mine['id']}", f"upload:{theirs['id']}"+ sign = lambda account, item_id: run_as(account, library_routes._sign_stream_id, item_id) # noqa: E731+ with _account_client(alice) as as_alice, _account_client(bob) as as_bob:+ url = _stream_url(as_alice, mine_id)+ assert _mint(as_bob, mine_id).status_code == 404+ response = _app(None).get(url)+ assert (response.status_code, response.content) == (200, b"alice")+ response = _stream(theirs_id, sign(alice, theirs_id))+ assert response.status_code == 404 and b"bob" not in response.content+ assert _stream(theirs_id, sign(alice, mine_id)).status_code == 401+ assert _stream(mine_id, sign(OWNER, mine_id)).status_code == 404diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.pyindex 91b41e75791..15c543167f9 100644--- a/studio/backend/tests/test_middleware.py+++ b/studio/backend/tests/test_middleware.py@@ -266,6 +266,24 @@ class TestMaxBodyMiddleware:assert cap == upload_request_limit_bytes() # DB-aware cap + multipart overheadassert cap > default_request_body_limit_bytes() # not the plain default body cap+ def test_library_uploads_are_capped_before_parsing(self, main_module):+ from utils.upload_limits import (+ LIBRARY_UPLOAD_MAX_BYTES,+ default_request_body_limit_bytes,+ upload_request_limit_bytes,+ )++ assert "/api/library" in main_module._BODY_PROTECTED_PREFIXES+ for path in ("/api/library/uploads", "/api/library/uploads/"):+ assert main_module._get_upload_passthrough_request_max_bytes(path) == (+ upload_request_limit_bytes(LIBRARY_UPLOAD_MAX_BYTES)+ ), path+ path = "/api/library/uploads/abc/text"+ assert path not in main_module._BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS+ assert main_module._get_upload_passthrough_request_max_bytes(path) == (+ default_request_body_limit_bytes()+ )+def test_diffusion_dataset_json_subroutes_keep_default_cap(self, main_module):# The exact-path passthrough must NOT sweep in the JSON sub-routes under the same prefix: a prefix match would let a large# caption/import body bypass the default JSON cap and be buffered up to the far larger upload limit.diff --git a/studio/backend/tests/test_personalization_settings.py b/studio/backend/tests/test_personalization_settings.pyindex b0aa1c110d0..301e8618d59 100644--- a/studio/backend/tests/test_personalization_settings.py+++ b/studio/backend/tests/test_personalization_settings.py@@ -187,8 +187,9 @@ def _sidebar_nav(items):FRONTEND_SHIPPED_SIDEBAR_NAV = [("hub", True),("projects", True),+ ("library", True),("images", True),- ("video", True),+ ("video", False),("audio", False),("train", True),("recipes", False),@@ -228,6 +229,7 @@ def test_customization_sidebar_nav_preserves_order_and_normalizes():("video", True),("hub", False),("projects", True),+ ("library", True),("images", True),("audio", False),("train", True),@@ -526,6 +528,7 @@ def test_personalization_route_roundtrip_real_shape(monkeypatch):{"id": "hub", "pinned": True},{"id": "train", "pinned": True},{"id": "projects", "pinned": False},+ {"id": "library", "pinned": True},{"id": "recipes", "pinned": False},{"id": "export", "pinned": False},{"id": "api", "pinned": False},diff --git a/studio/backend/tests/test_video_gallery.py b/studio/backend/tests/test_video_gallery.pyindex 6586e525113..7b29a02478c 100644--- a/studio/backend/tests/test_video_gallery.py+++ b/studio/backend/tests/test_video_gallery.py@@ -503,6 +503,26 @@ def test_thumbnail_scales_large_frames_to_gallery_width():assert image.size == (192, 341)+def test_thumbnail_refuses_frames_past_max_pixels_even_when_the_header_understates_them():+ import io++ av = pytest.importorskip("av")+ clip = _real_mp4_bytes(frames = 2, size = 256)+ lying = io.BytesIO()+ with av.open(io.BytesIO(clip)) as src, av.open(lying, "w", format = "mp4") as out:+ stream = out.add_stream("mpeg4", rate = 8)+ stream.width = stream.height = 16+ stream.pix_fmt = "yuv420p"+ for packet in src.demux(src.streams.video[0]):+ if packet.dts is not None:+ packet.stream = stream+ out.mux(packet)+ assert gallery.first_frame_webp(io.BytesIO(clip), container = "mp4", max_pixels = 2 * 256 * 256)+ for data in (clip, lying.getvalue()):+ with pytest.raises(RuntimeError):+ gallery.first_frame_webp(io.BytesIO(data), container = "mp4", max_pixels = 128 * 128)++def test_thumbnail_rejects_unowned_and_invalid_videos():assert gallery.thumbnail("does-not-exist") is Nonerecord = gallery.save(_mp4(), _meta())diff --git a/studio/backend/utils/native_path_leases.py b/studio/backend/utils/native_path_leases.pyindex 0b8f6e645c0..c28bcae32db 100644--- a/studio/backend/utils/native_path_leases.py+++ b/studio/backend/utils/native_path_leases.py@@ -195,7 +195,10 @@ def verify_native_path_lease(expected_kind: str | None = None,expected_path_type: str | None = None,allowed_suffixes: Iterable[str] | None = None,+ consume: bool = True,) -> NativePathGrant:+ """Check a grant and use it up. ``consume = False`` only checks it, for a caller that verifies+ a whole batch before reading any of it, and verifies each again (consuming) when it reads."""if not lease:raise NativePathLeaseError("Native path grant is required.")@@ -254,11 +257,21 @@ def verify_native_path_lease(current_identity = _validate_current_stat(grant, identity_options)if current_identity is not None:grant = replace(grant, device_id = current_identity[0], file_id = current_identity[1])- _consume_nonce(str(payload["nonce"]), grant.expires_at_ms)+ if consume:+ _consume_nonce(str(payload["nonce"]), grant.expires_at_ms)_remember_native_path_for_redaction(str(resolved), grant.display_label)return grant+def release_native_path_lease(lease: str) -> None:+ """Make a grant this caller consumed usable again, once it has undone everything it read with+ it: a batch that failed part way and kept nothing, so its retry is not refused as a replay.+ Only for a lease the caller verified itself; the grant still expires as signed."""+ payload = _decode_payload(_split_lease(lease)[0])+ with _REPLAY_LOCK:+ _USED_NONCES.pop(str(payload.get("nonce")), None)++def display_label_for_native_path(value: str | None) -> str | None:if not value:return valuediff --git a/studio/backend/utils/paths/file_manager.py b/studio/backend/utils/paths/file_manager.pynew file mode 100644index 00000000000..bfaf9a30b8a--- /dev/null+++ b/studio/backend/utils/paths/file_manager.py@@ -0,0 +1,45 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Which file manager ``reveal_in_file_manager`` would open on this host, if any.++Reported by ``/api/health`` so the UI offers Reveal only where it can show something to the person+at the machine, and names it the way the platform does. A loopback URL is not enough on its own: an+SSH port-forward, a container or a headless server all look like localhost to the browser.+"""++from __future__ import annotations++import os+import sys+from typing import Literal, Optional++FileManager = Literal["finder", "explorer", "files"]+++def _in_container() -> bool:+ return (+ os.path.exists("/.dockerenv")+ or os.path.exists("/run/.containerenv")+ or bool(os.environ.get("container"))+ or bool(os.environ.get("KUBERNETES_SERVICE_HOST"))+ )+++def file_manager_kind() -> Optional[FileManager]:+ """``finder`` on macOS, ``explorer`` on Windows and WSL (which reveals in the Windows host's+ Explorer), ``files`` on a Linux desktop session, else None: a container, or Linux with no+ display to open a window on."""+ if sys.platform == "darwin":+ return "finder"+ if os.name == "nt":+ return "explorer"+ from utils.paths.path_utils import _IS_WSL++ if _IS_WSL:+ return "explorer"+ if _in_container():+ return None+ if os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"):+ return "files"+ return Nonediff --git a/studio/backend/utils/paths/path_utils.py b/studio/backend/utils/paths/path_utils.pyindex f6425f1c436..9ef905f4021 100644--- a/studio/backend/utils/paths/path_utils.py+++ b/studio/backend/utils/paths/path_utils.py@@ -303,6 +303,47 @@ def reset_cache_case_resolution_state() -> None:_CACHE_CASE_RESOLUTION_STATS[key] = 0+def _comparable_path(path, pathmod) -> str:+ """*path* spelled the way two paths are compared: on Windows without the extended-length+ prefix, which realpath keeps on one side only for a long path, and case folded."""+ text = os.fspath(path)+ if pathmod.sep == "\\":+ if text[:8].upper() == "\\\\?\\UNC\\":+ text = "\\\\" + text[8:]+ elif text[:4] == "\\\\?\\":+ text = text[4:]+ return pathmod.normcase(pathmod.normpath(text))+++def is_path_within(+ path,+ root,+ *,+ allow_root: bool = False,+ pathmod = os.path,+) -> bool:+ """Whether resolved *path* sits inside resolved *root*.++ commonpath rather than a prefix test: a drive root already ends in a separator, and ``C:\\a``+ must not contain ``C:\\ab``. Paths on different drives are simply not inside."""+ candidate, base = _comparable_path(path, pathmod), _comparable_path(root, pathmod)+ try:+ common = pathmod.commonpath([candidate, base])+ except ValueError:+ return False+ return common == base and (allow_root or candidate != base)+++def same_path(+ left,+ right,+ *,+ pathmod = os.path,+) -> bool:+ """Whether two resolved paths are one, compared as ``is_path_within`` compares them."""+ return _comparable_path(left, pathmod) == _comparable_path(right, pathmod)++def _wsl_reveal_in_explorer(path: Path, is_file: bool) -> bool:import subprocessif not _IS_WSL:@@ -319,8 +360,11 @@ def _wsl_reveal_in_explorer(path: Path, is_file: bool) -> bool:).stdout.strip()if not windows_path:return False- argument = f"/select,{windows_path}" if is_file else windows_path- subprocess.Popen(["explorer.exe", argument])+ subprocess.Popen(+ ["explorer.exe", "/select,", windows_path]+ if is_file+ else ["explorer.exe", windows_path]+ )return Trueexcept (OSError, subprocess.SubprocessError):return False@@ -358,8 +402,10 @@ def reveal_in_file_manager(path: Path, expect_dir: bool = False) -> None:cmd = ["open", "-R", target] if is_file else ["open", target]subprocess.Popen(cmd)elif os.name == "nt":- if is_file:- subprocess.Popen(["explorer", f"/select,{target}"])+ if is_file and '"' not in target:+ subprocess.Popen(f'explorer /select,"{target}"')+ elif is_file:+ os.startfile(str(path.parent)) # noqa: S606 - local user's own file managerelse:os.startfile(target) # noqa: S606 - local user's own file managerelif not _wsl_reveal_in_explorer(path, is_file):diff --git a/studio/backend/utils/upload_limits.py b/studio/backend/utils/upload_limits.pyindex 5344ac398b0..a849f31c70a 100644--- a/studio/backend/utils/upload_limits.py+++ b/studio/backend/utils/upload_limits.py@@ -21,6 +21,8 @@ STT_AUDIO_JSON_MAX_BYTES = STT_AUDIO_B64_MAX_CHARS + 64 * 1024VIDEO_INPUT_REFERENCE_B64_MAX_CHARS = ((VIDEO_INPUT_REFERENCE_MAX_BYTES + 2) // 3) * 4VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES = VIDEO_INPUT_REFERENCE_B64_MAX_CHARS + 64 * 1024+LIBRARY_UPLOAD_MAX_BYTES = 512 * _BYTES_PER_MB+LOCAL_SEED_UPLOAD_MAX_BYTES = 100 * _BYTES_PER_MBLOCAL_SEED_UPLOAD_MAX_LABEL = "100MB"UNSTRUCTURED_RECIPE_UPLOAD_MAX_BYTES = 500 * _BYTES_PER_MBdiff --git a/studio/frontend/src/app/router.tsx b/studio/frontend/src/app/router.tsxindex 9fafbe7f1a8..85ee5f04d74 100644--- a/studio/frontend/src/app/router.tsx+++ b/studio/frontend/src/app/router.tsx@@ -18,6 +18,7 @@ import { Route as indexRoute } from "./routes/index";import { Route as loginRoute } from "./routes/login";import { Route as hubRoute } from "./routes/hub";import { Route as projectsRoute } from "./routes/projects";+import { Route as libraryRoute } from "./routes/library";import { Route as changePasswordRoute } from "./routes/change-password";import { Route as settingsRoute } from "./routes/settings";import { Route as studioRoute } from "./routes/studio";@@ -31,6 +32,7 @@ const routeTree = rootRoute.addChildren([studioRoute,chatRoute,projectsRoute,+ libraryRoute,exportRoute,imagesRoute,videoRoute,diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 92a3c2db5aa..79c746692b5 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -247,6 +247,7 @@ const CHAT_ONLY_ALLOWED = new Set(["/","/chat","/projects",+ "/library","/hub","/login","/signup",@@ -399,6 +400,7 @@ function RootLayout() {// Same persistent mount for /audio so generation UI state survives leaving the tab.const isAudioRoute = pathname === "/audio";+ const isLibraryRoute = pathname === "/library";const [audioMounted, setAudioMounted] = useState(isAudioRoute);if (isAudioRoute && !audioMounted) {setAudioMounted(true);@@ -636,7 +638,14 @@ function RootLayout() {<AppSidebar /><SidebarEdgeTrigger /><SidebarInset- className={isChatLike ? "overflow-hidden" : "overflow-y-auto"}+ className={+ isChatLike+ ? "overflow-hidden"+ : // Reserve the scrollbar so the Library does not shift when it appears.+ isLibraryRoute+ ? "overflow-y-auto [scrollbar-gutter:stable]"+ : "overflow-y-auto"+ }><Navbar /><divdiff --git a/studio/frontend/src/app/routes/audio.tsx b/studio/frontend/src/app/routes/audio.tsxindex 9a358be88fc..01b8c8e0251 100644--- a/studio/frontend/src/app/routes/audio.tsx+++ b/studio/frontend/src/app/routes/audio.tsx@@ -28,6 +28,7 @@ export const Route = createRoute({task?: string;audioType?: string;loadId?: string;+ item?: string;} => ({...(typeof search.model === "string" ? { model: search.model } : {}),...(typeof search.quant === "string" ? { quant: search.quant } : {}),@@ -45,6 +46,7 @@ export const Route = createRoute({...(typeof search.loadId === "string" && search.loadId.trim()? { loadId: search.loadId }: {}),+ ...(typeof search.item === "string" ? { item: search.item } : {}),}),beforeLoad: () => requireAuth(),component: () => null,diff --git a/studio/frontend/src/app/routes/images.tsx b/studio/frontend/src/app/routes/images.tsxindex 5608fd64e24..2435c10665e 100644--- a/studio/frontend/src/app/routes/images.tsx+++ b/studio/frontend/src/app/routes/images.tsx@@ -14,12 +14,13 @@ export const Route = createRoute({// which the page loads and then clears.validateSearch: (search: Record<string, unknown>,- ): { model?: string; quant?: string; ggufQuant?: string } => ({+ ): { model?: string; quant?: string; ggufQuant?: string; item?: string } => ({...(typeof search.model === "string" ? { model: search.model } : {}),...(typeof search.quant === "string" ? { quant: search.quant } : {}),...(typeof search.ggufQuant === "string"? { ggufQuant: search.ggufQuant }: {}),+ ...(typeof search.item === "string" ? { item: search.item } : {}),}),beforeLoad: () => requireAuth(),component: () => null,diff --git a/studio/frontend/src/app/routes/library.tsx b/studio/frontend/src/app/routes/library.tsxnew file mode 100644index 00000000000..a0442021ef3--- /dev/null+++ b/studio/frontend/src/app/routes/library.tsx@@ -0,0 +1,21 @@+// 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 { createRoute, lazyRouteComponent } from "@tanstack/react-router";+import { validateLibrarySearch } from "@/features/library";+import { requireAuth } from "../auth-guards";+import { Route as rootRoute } from "./__root";++const LibraryPage = lazyRouteComponent(+ () => import("@/features/library/library-page"),+ "LibraryPage",+);++export const Route = createRoute({+ getParentRoute: () => rootRoute,+ path: "/library",+ staticData: { title: "Library" },+ validateSearch: validateLibrarySearch,+ beforeLoad: () => requireAuth(),+ component: LibraryPage,+});diff --git a/studio/frontend/src/app/routes/video.tsx b/studio/frontend/src/app/routes/video.tsxindex 4a91b8118c1..6c64f574b7e 100644--- a/studio/frontend/src/app/routes/video.tsx+++ b/studio/frontend/src/app/routes/video.tsx@@ -14,12 +14,13 @@ export const Route = createRoute({// which the page loads and then clears.validateSearch: (search: Record<string, unknown>,- ): { model?: string; quant?: string; ggufQuant?: string } => ({+ ): { model?: string; quant?: string; ggufQuant?: string; item?: string } => ({...(typeof search.model === "string" ? { model: search.model } : {}),...(typeof search.quant === "string" ? { quant: search.quant } : {}),...(typeof search.ggufQuant === "string"? { ggufQuant: search.ggufQuant }: {}),+ ...(typeof search.item === "string" ? { item: search.item } : {}),}),beforeLoad: () => requireAuth(),component: () => null,diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex 3254acc1e19..1b013a5af6c 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -98,6 +98,7 @@ import {Globe02Icon,HelpCircleIcon,Image03Icon,+ LibrariesIcon,Logout05Icon,MoreHorizontalIcon,MoreVerticalIcon,@@ -2227,6 +2228,18 @@ export function AppSidebar() {</button>),},+ library: {+ icon: LibrariesIcon,+ label: t("shell.navigation.library"),+ active: pathname === "/library",+ onClick: () => {+ navigate({ to: "/library" });+ closeMobileIfOpen();+ },+ onIntent: () => {+ preloadSilently(router.preloadRoute({ to: "/library" }));+ },+ },hub: {icon: DashboardCircleIcon,label: t("shell.navigation.hub"),diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 0bd339e168b..223e781317d 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -142,6 +142,10 @@ import {useNativeIntentStore,} from "@/features/native-intents";import { nativeAttachmentIntentToFile } from "@/features/native-intents/native-attachment-file";+import {+ attachLibraryChatFiles,+ useLibraryChatHandoffStore,+} from "@/features/library/chat-handoff-store";import { cancelResearchRun } from "@/features/chat/api/research-api";import {ingestResearchUpdate,@@ -185,7 +189,7 @@ import {isMacPlatform,} from "@/features/settings";import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page";-import { useT } from "@/i18n";+import { translate, useT } from "@/i18n";import {clampReasoningEffortToLevels,getExternalReasoningCapabilities,@@ -2983,6 +2987,57 @@ const Composer: FC<{const nativeAttachmentTargetKey = useNativeAttachmentTargetKey();const nativeAttachmentTargetKeyRef = useRef(nativeAttachmentTargetKey);nativeAttachmentTargetKeyRef.current = nativeAttachmentTargetKey;++ useEffect(() => {+ if (!nativeAttachmentTargetKey) return;+ const targetKey = nativeAttachmentTargetKey;+ let disposed = false;+ // aui.composer() is whichever chat is open now: a switch mid-batch must not take the rest.+ const add = async (file: File) => {+ if (disposed || nativeAttachmentTargetKeyRef.current !== targetKey) {+ throw new Error("The chat changed before this file was attached.");+ }+ await aui.composer().addAttachment(file);+ };+ const drain = async () => {+ const held = await attachLibraryChatFiles(targetKey, add);+ if (held > 0) toast(translate("library.toast.chatFilesWaiting", { count: held }));+ };+ void drain();+ const offers = useLibraryChatHandoffStore.subscribe((state) => {+ if (state.pending?.targetKey === targetKey) void drain();+ });+ let retrying = false;+ let again = false;+ const retry = async () => {+ if (retrying) {+ again = true;+ return;+ }+ retrying = true;+ do {+ again = false;+ await attachLibraryChatFiles(targetKey, add, true);+ } while (again);+ retrying = false;+ };+ const loads = useChatRuntimeStore.subscribe((state, prev) => {+ if (state.modelLoading) return;+ if (+ prev.modelLoading ||+ state.params.checkpoint !== prev.params.checkpoint ||+ state.residentCheckpoint !== prev.residentCheckpoint ||+ state.loadedIsMultimodal !== prev.loadedIsMultimodal+ ) {+ void retry();+ }+ });+ return () => {+ disposed = true;+ offers();+ loads();+ };+ }, [nativeAttachmentTargetKey, aui]);const hasPendingImageAttachments = useNativeIntentStore((s) =>Boolean(nativeAttachmentTargetKey &&diff --git a/studio/frontend/src/components/code-source-view.tsx b/studio/frontend/src/components/code-source-view.tsxnew file mode 100644index 00000000000..0374f490c9f--- /dev/null+++ b/studio/frontend/src/components/code-source-view.tsx@@ -0,0 +1,85 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useMemo } from "react";+import { Streamdown } from "streamdown";++import { createCodePlugin } from "@/components/assistant-ui/code-plugin";+import { unslothDarkTheme, unslothLightTheme } from "@/components/assistant-ui/code-themes";+import { cn } from "@/lib/utils";++const sourceCodePlugin = createCodePlugin({+ themes: [unslothLightTheme, unslothDarkTheme],+});++const MAX_HIGHLIGHT_CHARS = 200_000;+const MAX_HIGHLIGHT_LINES = 5_000;++function lineCount(source: string): number {+ let lines = 1;+ for (let index = source.indexOf("\n"); index !== -1; index = source.indexOf("\n", index + 1)) {+ lines += 1;+ }+ return lines;+}++function PlainSource({ code, lines, className }: { code: string; lines: number; className?: string }) {+ const numbers = useMemo(+ () => Array.from({ length: lines }, (_, index) => index + 1).join("\n"),+ [lines],+ );+ return (+ <div className={cn("h-full overflow-auto font-mono text-xs leading-relaxed", className)}>+ <div className="flex min-w-max">+ <pre aria-hidden="true" className="m-0 select-none pr-4 text-right text-muted-foreground/60">+ {numbers}+ </pre>+ <pre className="m-0 flex-1">{code}</pre>+ </div>+ </div>+ );+}++function buildFence(source: string, language: string): string {+ const longestBacktickRun = Math.max(+ 2,+ ...(source.match(/`+/g) ?? []).map((match) => match.length),+ );+ const fence = "`".repeat(longestBacktickRun + 1);+ return `${fence}${language}\n${source}\n${fence}`;+}++export function CodeSourceView({+ code,+ language,+ className,+}: {+ code: string;+ language: string;+ className?: string;+}) {+ const lines = useMemo(() => lineCount(code), [code]);+ const plain = code.length > MAX_HIGHLIGHT_CHARS || lines > MAX_HIGHLIGHT_LINES;+ const markdown = useMemo(+ () => (plain ? "" : buildFence(code, language)),+ [plain, code, language],+ );+ if (plain) return <PlainSource code={code} lines={lines} className={className} />;+ return (+ <div+ className={cn(+ "h-full overflow-auto text-xs leading-relaxed [&_[data-streamdown=code-block]]:!my-0 [&_[data-streamdown=code-block]]:!gap-0 [&_[data-streamdown=code-block]]:!rounded-none [&_[data-streamdown=code-block]]:!border-0 [&_[data-streamdown=code-block]]:!bg-transparent [&_[data-streamdown=code-block]]:!p-0 [&_[data-streamdown=code-block-body]]:!border-0 [&_[data-streamdown=code-block-body]]:!bg-transparent [&_[data-streamdown=code-block-body]]:!p-0 [&_pre]:!m-0 [&_pre]:!bg-transparent [&_pre]:!p-0 [&_pre]:text-xs [&_pre]:leading-relaxed [&_code]:text-xs",+ className,+ )}+ >+ <Streamdown+ mode="static"+ plugins={{ code: sourceCodePlugin }}+ controls={{ code: false }}+ shikiTheme={[unslothLightTheme, unslothDarkTheme]}+ >+ {markdown}+ </Streamdown>+ </div>+ );+}diff --git a/studio/frontend/src/components/gallery-item-menu.tsx b/studio/frontend/src/components/gallery-item-menu.tsxindex 21d5180886c..28b5c527a8c 100644--- a/studio/frontend/src/components/gallery-item-menu.tsx+++ b/studio/frontend/src/components/gallery-item-menu.tsx@@ -6,9 +6,6 @@ import {ArchiveRestoreIcon,Delete02Icon,Download01Icon,- Folder01Icon,- FolderAddIcon,- FolderExportIcon,MoreVerticalIcon,PinIcon,PinOffIcon,@@ -22,15 +19,13 @@ import {DropdownMenuContent,DropdownMenuItem,DropdownMenuSeparator,- DropdownMenuSub,- DropdownMenuSubContent,- DropdownMenuSubTrigger,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { NewProjectDialog, useChatProjects } from "@/features/chat";-import { toast } from "@/lib/toast";+import { useT } from "@/i18n";+import { StarPointedIcon } from "@/lib/hugeicons-derived";import { cn } from "@/lib/utils";+import { type MediaNoun, useProjectSubmenu } from "./project-submenu";/*** Actions for one gallery item, shared by the Images, Video and Audio pages. Matches a chat row's menu.@@ -45,6 +40,8 @@ export type GalleryItemMenuVariant = "toolbar" | "overlay" | "row";export function GalleryItemMenu({pinned,archived,+ favorite,+ onToggleFavorite,onTogglePin,onToggleArchive,onDelete,@@ -58,6 +55,8 @@ export function GalleryItemMenu({}: {pinned: boolean;archived: boolean;+ favorite?: boolean;+ onToggleFavorite?: () => void;onTogglePin: () => void;onToggleArchive: () => void;onDelete: () => void;@@ -69,34 +68,23 @@ export function GalleryItemMenu({leadingItems?: ReactNode;variant?: GalleryItemMenuVariant;/** Used in the aria-label and messages, e.g. "image" or "video". */- noun: string;+ noun: MediaNoun;/** False while the page is off-tab; forces the menu shut so a portalled popup cannot outlive it. */active?: boolean;className?: string;}) {// Controlled like RecipePopover: DropdownMenuContent portals to body, so the inert page wrapper// cannot contain it when the tab goes away.+ const t = useT();const [open, setOpen] = useState(false);- const [creatingProject, setCreatingProject] = useState(false);+ const project = useProjectSubmenu({ noun, onAddToProject });+ const closeProject = project.close;useEffect(() => {if (!active) {setOpen(false);- setCreatingProject(false);- }- }, [active]);- const { projects } = useChatProjects();-- async function addToProject(projectId: string, projectName: string) {- if (!onAddToProject) return;- try {- const { already } = await onAddToProject(projectId);- toast.success(already ? `Already in ${projectName}` : `Added to ${projectName}`);- } catch (err) {- toast.error(`Failed to add ${noun} to project`, {- description: err instanceof Error ? err.message : undefined,- });+ closeProject();}- }+ }, [active, closeProject]);const overlay = variant === "overlay";const row = variant === "row";@@ -110,9 +98,8 @@ export function GalleryItemMenu({className={cn(// Circular hover, no border: focus returning on close would draw one. Keyboard focus tints instead."rounded-full border-0 focus-visible:bg-muted dark:focus-visible:bg-muted/50",- // Reads over any thumbnail, whatever its colours.overlay &&- "bg-background/80 text-foreground shadow-sm backdrop-blur hover:bg-background focus-visible:bg-background dark:focus-visible:bg-background",+ "bg-background/80 text-foreground shadow-sm backdrop-blur hover:bg-background focus-visible:bg-background aria-expanded:bg-background dark:focus-visible:bg-background",row && "text-muted-foreground hover:text-foreground",className,)}@@ -138,45 +125,23 @@ export function GalleryItemMenu({<HugeiconsIcon icon={pinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />{pinned ? "Unpin" : "Pin"}</DropdownMenuItem>+ {onToggleFavorite && (+ <DropdownMenuItem onClick={onToggleFavorite}>+ <HugeiconsIcon+ icon={StarPointedIcon}+ strokeWidth={1.75}+ className={cn("size-icon", favorite && "[&_path]:fill-current")}+ />+ {t(favorite ? "library.menu.removeFromFavorites" : "library.menu.addToFavorites")}+ </DropdownMenuItem>+ )}{onDownload ? (<DropdownMenuItem onClick={onDownload}><HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-icon" />Download</DropdownMenuItem>) : null}- {onAddToProject ? (- <DropdownMenuSub>- <DropdownMenuSubTrigger>- <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />- <span>Project</span>- </DropdownMenuSubTrigger>- <DropdownMenuSubContent- sideOffset={0}- alignOffset={-4}- className="unsloth-plus-menu sidebar-row-menu w-48"- >- {/* Actions above the rule, destinations below, as in a chat's Project menu. */}- <DropdownMenuItem onClick={() => setCreatingProject(true)}>- <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />- <span>New project</span>- </DropdownMenuItem>- <DropdownMenuSeparator />- {projects.length === 0 ? (- <DropdownMenuItem disabled={true}>No projects yet</DropdownMenuItem>- ) : (- projects.map((project) => (- <DropdownMenuItem- key={project.id}- onClick={() => void addToProject(project.id, project.name)}- >- <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />- <span className="truncate">{project.name}</span>- </DropdownMenuItem>- ))- )}- </DropdownMenuSubContent>- </DropdownMenuSub>- ) : null}+ {project.submenu}<DropdownMenuItem onClick={onToggleArchive}><HugeiconsIcon icon={archived ? ArchiveRestoreIcon : Archive03Icon} strokeWidth={1.75} className="size-icon" />{archived ? "Restore from archive" : "Archive"}@@ -190,16 +155,7 @@ export function GalleryItemMenu({</DropdownMenu>);- // Mounted only while open, since the overlay renders once per tile.- const newProjectDialog = creatingProject ? (- <NewProjectDialog- open={true}- onOpenChange={setCreatingProject}- title={`Add ${noun} to new project`}- submitLabel="Create and add"- onCreated={(project) => addToProject(project.id, project.name)}- />- ) : null;+ const newProjectDialog = project.dialog;if (!overlay && !row) {return (diff --git a/studio/frontend/src/components/media-page-link.tsx b/studio/frontend/src/components/media-page-link.tsxindex 6fe23368236..67b5c9e6fef 100644--- a/studio/frontend/src/components/media-page-link.tsx+++ b/studio/frontend/src/components/media-page-link.tsx@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { LibrariesIcon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import type { IconSvgElement } from "@hugeicons/react";import { useNavigate } from "@tanstack/react-router";@@ -10,15 +11,18 @@ import {TooltipContent,TooltipTrigger,} from "@/components/ui/tooltip";+import type { LibraryTab } from "@/features/library";+import { useT } from "@/i18n";import { cn } from "@/lib/utils";import {ArrowRightIcon,} from "lucide-react";-/** The link out to another page's workspace (Images, Video, Audio, image training).+/** The link out to another page's workspace (Images, Video, Audio, the Library).* Kept out of the mode strip and parked past a divider so it reads as leaving. */export function MediaPageLink({to,+ libraryTab,label,icon,tooltip,@@ -26,7 +30,8 @@ export function MediaPageLink({labelClassName,arrowClassName,}: {- to: "/images" | "/video" | "/audio";+ to: "/images" | "/video" | "/audio" | "/library";+ libraryTab?: LibraryTab;label: string;icon: IconSvgElement;/** Needed on a translated page: the default prefix below is English. */@@ -54,7 +59,11 @@ export function MediaPageLink({aria-label={label}onClick={() => {onNavigate?.();- navigate({ to });+ if (to === "/library") {+ void navigate({ to, search: libraryTab ? { show: libraryTab } : {} });+ } else {+ void navigate({ to });+ }}}className="flex h-[calc(34px*var(--ui-space-scale,1))] min-w-0 items-center gap-1.5 rounded-full pl-2.5 pr-2 text-ui-13 font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">@@ -72,3 +81,26 @@ export function MediaPageLink({</>);}++export function LibraryPageLink({+ tab,+ labelClassName,+ arrowClassName,+}: {+ tab: LibraryTab;+ labelClassName?: string;+ arrowClassName?: string;+}) {+ const t = useT();+ return (+ <MediaPageLink+ to="/library"+ libraryTab={tab}+ label={t("shell.navigation.library")}+ tooltip={t("studio.goToLibrary")}+ icon={LibrariesIcon}+ labelClassName={labelClassName}+ arrowClassName={arrowClassName}+ />+ );+}diff --git a/studio/frontend/src/components/media-viewer.tsx b/studio/frontend/src/components/media-viewer.tsxnew file mode 100644index 00000000000..08ca74924ae--- /dev/null+++ b/studio/frontend/src/components/media-viewer.tsx@@ -0,0 +1,268 @@+// 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 {+ ArrowTurnBackwardIcon,+ Cancel01Icon,+ Delete02Icon,+ Download01Icon,+ Folder01Icon,+ MoreHorizontalIcon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";+import { type KeyboardEventHandler, type ReactNode, useRef, useState } from "react";++import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { type TranslationKey, useLocale, useT } from "@/i18n";+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";+import { StarPointedIcon } from "@/lib/hugeicons-derived";+import { cn } from "@/lib/utils";+import { type MediaZoom, MediaZoomStage } from "./media-zoom";+import { type MediaNoun, useProjectSubmenu } from "./project-submenu";++export interface MediaViewerActions {+ primary?: { label: string; icon: IconSvgElement; onClick: () => void; disabled?: boolean };+ onDownload?: () => void;+ viewOriginal?: { label: string; onClick: () => void };+ reveal?: { label: string; onClick: () => void };+ favorite?: boolean;+ onToggleFavorite?: () => void;+ onAddToProject?: (projectId: string) => Promise<{ already: boolean }>;+ onDelete?: () => void;+}++const MEDIA_ZOOMS = [0.25, 0.5, 0.75, 1, 1.25, 1.5] as const;++const MORE_ACTIONS: Record<MediaNoun, TranslationKey> = {+ image: "library.viewer.moreActionsImage",+ video: "library.viewer.moreActionsVideo",+ clip: "library.viewer.moreActionsClip",+ file: "library.viewer.moreActionsFile",+};++function percent(scale: number, locale: string): string {+ return new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 0 }).format(+ scale,+ );+}++export function ScaleMenu({+ value,+ scales,+ fitScale,+ onChange,+}: {+ value: MediaZoom;+ scales: readonly number[];+ fitScale?: number;+ onChange: (value: MediaZoom) => void;+}) {+ const t = useT();+ const locale = useLocale();+ const options = scales.map((scale) => ({ value: String(scale), label: percent(scale, locale) }));+ if (fitScale !== undefined) options.unshift({ value: "fit", label: t("library.viewer.fit") });+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild={true}>+ <button+ type="button"+ aria-label={t("library.viewer.scale")}+ className="mr-1 flex h-9 shrink-0 items-center gap-1 rounded-full bg-muted px-3.5 text-sm tabular-nums outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"+ >+ {percent(value === "fit" ? (fitScale ?? 1) : value, locale)}+ <HugeiconsIcon icon={ChevronDownStandardIcon} strokeWidth={1.75} className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-40">+ <DropdownMenuRadioGroup+ value={String(value)}+ onValueChange={(next) => onChange(next === "fit" ? "fit" : Number(next))}+ >+ {options.map((option) => (+ <DropdownMenuRadioItem key={option.value} value={option.value}>+ {option.label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++export function MediaViewer({+ open,+ onOpenChange,+ title,+ meta,+ media,+ noun,+ actions,+ extra,+ onKeyDown,+ children,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ title: string;+ meta?: ReactNode;+ media: boolean;+ noun: MediaNoun;+ actions: MediaViewerActions;+ extra?: ReactNode;+ onKeyDown?: KeyboardEventHandler<HTMLDivElement>;+ children: ReactNode;+}) {+ const t = useT();+ const [menuOpen, setMenuOpen] = useState(false);+ const [zoom, setZoom] = useState<MediaZoom>("fit");+ const [fitScale, setFitScale] = useState<number | null>(null);+ const [wasOpen, setWasOpen] = useState(open);+ if (open !== wasOpen) {+ setWasOpen(open);+ if (open) setZoom("fit");+ }+ const returnFocus = useRef<HTMLElement | null>(null);+ const project = useProjectSubmenu({ noun, onAddToProject: actions.onAddToProject });+ const iconButton =+ "flex size-9 shrink-0 items-center justify-center rounded-full outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring aria-expanded:bg-muted";+ const hasMenu = Boolean(+ actions.viewOriginal ||+ actions.reveal ||+ actions.onToggleFavorite ||+ actions.onAddToProject ||+ actions.onDelete,+ );++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ showCloseButton={false}+ onKeyDown={onKeyDown}+ onOpenAutoFocus={() => {+ const active = document.activeElement;+ returnFocus.current = active instanceof HTMLElement && active !== document.body ? active : null;+ }}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ const target = returnFocus.current;+ returnFocus.current = null;+ if (target?.isConnected) target.focus({ preventScroll: true });+ }}+ className="flex h-[calc(100dvh-var(--studio-window-chrome-top,0px)-2rem)] w-[min(92vw,1200px)] max-w-none flex-col gap-0 overflow-hidden p-0 sm:max-w-none"+ >+ <div className="flex items-center gap-2 py-3 pl-6 pr-4">+ <div className="min-w-0 flex-1">+ <DialogTitle className="truncate text-ui-15 font-medium">{title}</DialogTitle>+ <DialogDescription className="mt-0.5 truncate text-ui-13">+ {meta}+ </DialogDescription>+ </div>+ {extra}+ {media && fitScale !== null && (+ <ScaleMenu value={zoom} scales={MEDIA_ZOOMS} fitScale={fitScale} onChange={setZoom} />+ )}+ {actions.primary && (+ <button+ type="button"+ disabled={actions.primary.disabled}+ onClick={actions.primary.onClick}+ className="mr-1 flex h-9 shrink-0 items-center gap-2 rounded-full bg-foreground px-4 text-sm font-medium text-background outline-none transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"+ >+ <HugeiconsIcon icon={actions.primary.icon} strokeWidth={1.75} className="size-4" />+ {actions.primary.label}+ </button>+ )}+ {actions.onDownload && (+ <button+ type="button"+ aria-label={t("library.menu.download")}+ title={t("library.menu.download")}+ onClick={actions.onDownload}+ className={iconButton}+ >+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-5" />+ </button>+ )}+ {hasMenu && (+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>+ <DropdownMenuTrigger asChild={true}>+ <button type="button" aria-label={t(MORE_ACTIONS[noun])} className={iconButton}>+ <HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="unsloth-plus-menu sidebar-row-menu menu-flat-destructive w-56"+ >+ {actions.viewOriginal && (+ <DropdownMenuItem onClick={actions.viewOriginal.onClick}>+ <HugeiconsIcon icon={ArrowTurnBackwardIcon} strokeWidth={1.75} className="size-icon" />+ {actions.viewOriginal.label}+ </DropdownMenuItem>+ )}+ {actions.reveal && (+ <DropdownMenuItem onClick={actions.reveal.onClick}>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ {actions.reveal.label}+ </DropdownMenuItem>+ )}+ {(actions.viewOriginal || actions.reveal) && <DropdownMenuSeparator />}+ {actions.onToggleFavorite && (+ <DropdownMenuItem onClick={actions.onToggleFavorite}>+ <HugeiconsIcon+ icon={StarPointedIcon}+ strokeWidth={1.75}+ className={cn("size-icon", actions.favorite && "[&_path]:fill-current")}+ />+ {t(+ actions.favorite+ ? "library.menu.removeFromFavorites"+ : "library.menu.addToFavorites",+ )}+ </DropdownMenuItem>+ )}+ {project.submenu}+ {actions.onDelete && (+ <DropdownMenuItem variant="destructive" onClick={actions.onDelete}>+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />+ {t("common.delete")}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ <DialogClose asChild={true}>+ <button type="button" aria-label={t("common.close")} className={iconButton}>+ <HugeiconsIcon icon={Cancel01Icon} strokeWidth={1.75} className="size-5" />+ </button>+ </DialogClose>+ </div>+ <div className={cn("flex min-h-0 flex-1", media ? "px-4 pb-4" : "px-6 pb-6")}>+ {media ? (+ <MediaZoomStage zoom={zoom} onFitScale={setFitScale}>+ {children}+ </MediaZoomStage>+ ) : (+ children+ )}+ </div>+ {project.dialog}+ </DialogContent>+ </Dialog>+ );+}diff --git a/studio/frontend/src/components/media-zoom.tsx b/studio/frontend/src/components/media-zoom.tsxnew file mode 100644index 00000000000..2fbb9829f3f--- /dev/null+++ b/studio/frontend/src/components/media-zoom.tsx@@ -0,0 +1,220 @@+// 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 PointerEvent as ReactPointerEvent,+ type ReactNode,+ type SyntheticEvent,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+} from "react";++import { cn } from "@/lib/utils";++export type MediaZoom = "fit" | number;++// A video's own controls sit along its bottom edge; a drag never starts there.+const VIDEO_CONTROLS_PX = 56;+const DRAG_SLOP_PX = 4;++type Size = { width: number; height: number };++function translate({ x, y }: { x: number; y: number }): string {+ return `translate3d(${x}px, ${y}px, 0)`;+}++function clamp(value: number, limit: number): number {+ return Math.max(-limit, Math.min(limit, value));+}++export function MediaZoomStage({+ zoom,+ onFitScale,+ children,+}: {+ zoom: MediaZoom;+ onFitScale: (scale: number | null) => void;+ children: ReactNode;+}) {+ const stageRef = useRef<HTMLDivElement>(null);+ const layerRef = useRef<HTMLDivElement>(null);+ const [stage, setStage] = useState<Size | null>(null);+ const [natural, setNatural] = useState<(Size & { src: string }) | null>(null);+ const [offset, setOffset] = useState({ x: 0, y: 0 });+ const drag = useRef<{+ id: number;+ x: number;+ y: number;+ ox: number;+ oy: number;+ moved: boolean;+ next: { x: number; y: number };+ frame: number;+ } | null>(null);+ const dragged = useRef(false);+ const [grabbing, setGrabbing] = useState(false);++ useLayoutEffect(() => {+ const node = stageRef.current;+ if (!node) return;+ const observer = new ResizeObserver(([entry]) =>+ setStage({+ width: entry.contentRect.width,+ height: entry.contentRect.height,+ }),+ );+ observer.observe(node);+ return () => observer.disconnect();+ }, []);++ const fit =+ stage && natural+ ? Math.min(stage.width / natural.width, stage.height / natural.height)+ : null;+ useEffect(() => onFitScale(fit), [fit, onFitScale]);++ const scale = zoom === "fit" ? fit : zoom;+ const box =+ natural && scale+ ? { width: natural.width * scale, height: natural.height * scale }+ : null;+ const slack =+ box && stage+ ? {+ x: Math.max(0, (box.width - stage.width) / 2),+ y: Math.max(0, (box.height - stage.height) / 2),+ }+ : { x: 0, y: 0 };+ const pan = { x: clamp(offset.x, slack.x), y: clamp(offset.y, slack.y) };+ const pannable = slack.x > 0 || slack.y > 0;++ function measure(event: SyntheticEvent) {+ const target = event.target;+ const size =+ target instanceof HTMLImageElement+ ? {+ width: target.naturalWidth,+ height: target.naturalHeight,+ src: target.currentSrc,+ }+ : target instanceof HTMLVideoElement+ ? {+ width: target.videoWidth,+ height: target.videoHeight,+ src: target.currentSrc,+ }+ : null;+ if (!size || !size.width || !size.height) return;+ if (size.src !== natural?.src) setOffset({ x: 0, y: 0 });+ setNatural(size);+ }++ function onPointerDown(event: ReactPointerEvent<HTMLDivElement>) {+ dragged.current = false;+ if (!pannable || event.button !== 0) return;+ const target = event.target;+ if (+ target instanceof HTMLVideoElement &&+ event.clientY > target.getBoundingClientRect().bottom - VIDEO_CONTROLS_PX+ ) {+ return;+ }+ drag.current = {+ id: event.pointerId,+ x: event.clientX,+ y: event.clientY,+ ox: pan.x,+ oy: pan.y,+ moved: false,+ next: pan,+ frame: 0,+ };+ }++ function onPointerMove(event: ReactPointerEvent<HTMLDivElement>) {+ const current = drag.current;+ if (!current || current.id !== event.pointerId) return;+ if ((event.buttons & 1) === 0) {+ endDrag(current);+ return;+ }+ const dx = event.clientX - current.x;+ const dy = event.clientY - current.y;+ if (!current.moved) {+ if (Math.hypot(dx, dy) < DRAG_SLOP_PX) return;+ current.moved = true;+ setGrabbing(true);+ event.currentTarget.setPointerCapture(event.pointerId);+ }+ current.next = {+ x: clamp(current.ox + dx, slack.x),+ y: clamp(current.oy + dy, slack.y),+ };+ if (current.frame) return;+ current.frame = requestAnimationFrame(() => {+ current.frame = 0;+ const layer = layerRef.current;+ if (layer) layer.style.transform = translate(current.next);+ });+ }++ function onPointerEnd(event: ReactPointerEvent<HTMLDivElement>) {+ const current = drag.current;+ if (current?.id !== event.pointerId) return;+ endDrag(current);+ }++ function endDrag(current: NonNullable<typeof drag.current>) {+ cancelAnimationFrame(current.frame);+ dragged.current = current.moved;+ drag.current = null;+ setGrabbing(false);+ if (current.moved) setOffset(current.next);+ }++ return (+ <div+ ref={stageRef}+ onLoadCapture={measure}+ onLoadedMetadataCapture={measure}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerEnd}+ onPointerCancel={onPointerEnd}+ onLostPointerCapture={onPointerEnd}+ // The click that ends a drag must not also play or pause a video.+ onClickCapture={(event) => {+ if (!dragged.current) return;+ dragged.current = false;+ event.preventDefault();+ event.stopPropagation();+ }}+ onDragStart={(event) => pannable && event.preventDefault()}+ className={cn(+ "relative min-h-0 flex-1 select-none overflow-hidden",+ pannable && "touch-none",+ pannable && (grabbing ? "cursor-grabbing" : "cursor-grab"),+ )}+ >+ <div+ ref={layerRef}+ className="absolute flex will-change-transform"+ style={+ box && stage+ ? {+ width: box.width,+ height: box.height,+ left: (stage.width - box.width) / 2,+ top: (stage.height - box.height) / 2,+ transform: translate(pan),+ }+ : { inset: 0 }+ }+ >+ {children}+ </div>+ </div>+ );+}diff --git a/studio/frontend/src/components/project-submenu.tsx b/studio/frontend/src/components/project-submenu.tsxnew file mode 100644index 00000000000..aa925d3287a--- /dev/null+++ b/studio/frontend/src/components/project-submenu.tsx@@ -0,0 +1,108 @@+// 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 { Folder01Icon, FolderAddIcon, FolderExportIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { useCallback, useState } from "react";++import {+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from "@/components/ui/dropdown-menu";+import { NewProjectDialog, useChatProjects } from "@/features/chat";+import { type TranslationKey, useT } from "@/i18n";+import { toast } from "@/lib/toast";++export type MediaNoun = "image" | "video" | "clip" | "file";++const ADD_FAILED: Record<MediaNoun, TranslationKey> = {+ image: "library.project.addFailedImage",+ video: "library.project.addFailedVideo",+ clip: "library.project.addFailedClip",+ file: "library.project.addFailedFile",+};++const NEW_PROJECT_TITLE: Record<MediaNoun, TranslationKey> = {+ image: "library.project.newProjectImage",+ video: "library.project.newProjectVideo",+ clip: "library.project.newProjectClip",+ file: "library.project.newProjectFile",+};++export function useProjectSubmenu({+ noun,+ onAddToProject,+}: {+ noun: MediaNoun;+ onAddToProject?: (projectId: string) => Promise<{ already: boolean }>;+}) {+ const t = useT();+ const [creatingProject, setCreatingProject] = useState(false);+ const { projects } = useChatProjects();++ async function addToProject(projectId: string, projectName: string) {+ if (!onAddToProject) return;+ try {+ const { already } = await onAddToProject(projectId);+ toast.success(+ t(already ? "library.project.alreadyIn" : "library.project.addedTo", {+ project: projectName,+ }),+ );+ } catch (err) {+ toast.error(t(ADD_FAILED[noun]), {+ description: err instanceof Error ? err.message : undefined,+ });+ }+ }++ const submenu = onAddToProject ? (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />+ <span>{t("library.project.label")}</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent+ sideOffset={0}+ alignOffset={-4}+ className="unsloth-plus-menu sidebar-row-menu w-48"+ >+ {/* Actions above the rule, destinations below, as in a chat's Project menu. */}+ <DropdownMenuItem onClick={() => setCreatingProject(true)}>+ <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className="size-icon" />+ <span>{t("library.project.newProject")}</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ {projects.length === 0 ? (+ <DropdownMenuItem disabled={true}>{t("library.project.noProjects")}</DropdownMenuItem>+ ) : (+ projects.map((project) => (+ <DropdownMenuItem+ key={project.id}+ onClick={() => void addToProject(project.id, project.name)}+ >+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ <span className="truncate">{project.name}</span>+ </DropdownMenuItem>+ ))+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ ) : null;++ const dialog = creatingProject ? (+ <NewProjectDialog+ open={true}+ onOpenChange={setCreatingProject}+ title={t(NEW_PROJECT_TITLE[noun])}+ submitLabel={t("library.project.createAndAdd")}+ onCreated={(project) => addToProject(project.id, project.name)}+ />+ ) : null;++ const close = useCallback(() => setCreatingProject(false), []);+ return { submenu, dialog, close };+}diff --git a/studio/frontend/src/config/env.ts b/studio/frontend/src/config/env.tsindex efb79670233..b506144661e 100644--- a/studio/frontend/src/config/env.ts+++ b/studio/frontend/src/config/env.ts@@ -21,6 +21,8 @@ export const env = {export type DeviceType = "mac" | "windows" | "linux" | string;+export type FileManager = "finder" | "explorer" | "files" | null;+interface PlatformState {deviceType: DeviceType;// Unified memory: GPU and system draw on one pool, so an over-committed load has@@ -28,6 +30,7 @@ interface PlatformState {// deviceType === "mac", which includes Intel Macs with a discrete GPU, where spilling// to system RAM is exactly what happens. Mirrors the backend's is_apple_silicon gate.appleSilicon: boolean;+ fileManager: FileManager | undefined;chatOnly: boolean;// Why chatOnly is set (null when training is enabled), from /api/health.// e.g. "mlx_unavailable" on Apple Silicon -> the UI explains the greyed-out@@ -69,6 +72,7 @@ const localDeviceType = detectLocalPlatform();export const usePlatformStore = create<PlatformState>()((_, get) => ({deviceType: localDeviceType,appleSilicon: false,+ fileManager: undefined,// A guess from the user agent, kept only as the pre-measurement fallback for the redirects// that must decide something before /api/health answers. Capability gating must read// capabilitiesUnknown() first and hold, not gray a tab out on this.@@ -160,6 +164,7 @@ export async function fetchDeviceType(options?: {const data = (await res.json()) as {device_type?: string;apple_silicon?: boolean;+ file_manager?: FileManager;chat_only?: boolean;chat_only_reason?: string | null;hardware_detecting?: boolean;@@ -194,6 +199,12 @@ export async function fetchDeviceType(options?: {// on an Intel Mac, and on a Mac browser pointed at a Linux host.const appleSilicon =data.apple_silicon ?? (keepPlatform ? previous.appleSilicon : false);+ const fileManager =+ data.device_type !== undefined+ ? data.file_manager+ : keepPlatform+ ? previous.fileManager+ : undefined;// A still-provisional reply keeps the stored verdict: see resolveVerdict.const { chatOnly, chatOnlyReason, chatOnlyDetail } = resolveVerdict(data,@@ -205,6 +216,7 @@ export async function fetchDeviceType(options?: {usePlatformStore.setState({deviceType,appleSilicon,+ fileManager,chatOnly,chatOnlyReason,chatOnlyDetail,diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsxindex d696807dd90..657a99c2974 100644--- a/studio/frontend/src/features/audio/audio-page.tsx+++ b/studio/frontend/src/features/audio/audio-page.tsx@@ -16,6 +16,8 @@ import {StopIcon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";+import { LibraryPageLink } from "@/components/media-page-link";+import { translate } from "@/i18n";import {type ReactNode,useCallback,@@ -110,6 +112,7 @@ import {} from "@/lib/gallery-flags";import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";import { toast } from "@/lib/toast";+import { loadGalleryUntil } from "@/lib/gallery-deep-link";import { readLastPrompt, saveLastPrompt } from "@/lib/last-prompt";import { cn } from "@/lib/utils";import { useIsMobileShell } from "@/hooks/use-mobile";@@ -1726,6 +1729,7 @@ export function AudioPage({task?: string;audioType?: string;loadId?: string;+ item?: string;};const handledRouteModel = useRef<string | null>(null);useEffect(() => {@@ -1781,6 +1785,41 @@ export function AudioPage({transitionMode,]);+ // A Library "View in Audio" link arrives as ?task=text-to-speech&item=: the task switches to Speak+ // (and clears its part of the query), this selects the clip, paging back until it loads. A+ // counter, not effect cleanup, retires a lookup: clearing the query must not cancel its own.+ const routedItem = active ? routeSearch.item : undefined;+ const routedLookup = useRef(0);+ useEffect(() => {+ if (!active) routedLookup.current += 1;+ }, [active]);+ useEffect(() => {+ if (!routedItem) return;+ const lookup = ++routedLookup.current;+ void navigateSelf({+ to: "/audio",+ search: (prev) => ({ ...prev, item: undefined }),+ replace: true,+ });+ void loadGalleryUntil({+ has: () => galleryCache.clips.some((clip) => clip.id === routedItem),+ count: () => galleryCache.clips.length,+ hasMore: () => galleryCache.hasMore,+ refresh: () => refreshGallery(undefined, galleryCache.clips.length),+ loadMore,+ busy: () => loadingMoreRef.current,+ cancelled: () => lookup !== routedLookup.current,+ }).then((found) => {+ if (lookup !== routedLookup.current) return;+ if (found) selectClip(routedItem);+ else {+ toast(translate("library.toast.clipNotFound"), {+ description: translate("library.toast.notFoundDescription"),+ });+ }+ });+ }, [routedItem, navigateSelf, refreshGallery, loadMore, selectClip]);+const ttsLoaded = Boolean(status?.active_model &&@@ -2663,8 +2702,8 @@ export function AudioPage({/></div></div>- <div className="grid h-full min-w-0 grid-cols-[1fr_auto] @[50rem]:grid-cols-[1fr_auto_1fr]">- <div className="pointer-events-auto col-start-2 justify-self-end pr-3 pt-[var(--studio-chat-header-padding-top,11px)] @[50rem]:justify-self-center @[50rem]:pr-0">+ <div className="grid h-full min-w-0 grid-cols-[1fr_auto_auto] gap-2 @[50rem]:grid-cols-[1fr_auto_1fr] @[50rem]:gap-0">+ <div className="pointer-events-auto col-start-2 justify-self-end pt-[var(--studio-chat-header-padding-top,11px)] @[50rem]:justify-self-center"><PillTabsariaLabel="Page mode"// Always "create": Train navigates away, so the pill never latches.@@ -2700,6 +2739,15 @@ export function AudioPage({]}/></div>+ <div className="pointer-events-none col-start-3 flex min-w-0 items-start justify-end pr-2 pt-[var(--studio-chat-header-padding-top,11px)]">+ <div className="pointer-events-auto flex min-w-0 items-center gap-2">+ <LibraryPageLink+ tab="audio"+ labelClassName="hidden @[50rem]:inline"+ arrowClassName="hidden @[50rem]:block"+ />+ </div>+ </div></div></div>{/* Below 50rem the panes stack and the page scrolls as one column, matching Images and Video:diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex b3cc4dd3f47..e62f0066705 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -362,6 +362,7 @@ export {resolveOpen,} from "./utils/display-visibility";export { ArtifactCard } from "./artifacts/artifact-card";+export { ArtifactHtmlFrame } from "./artifacts/html-frame";export { ResearchMessage } from "./components/research-message";export {ResearchActivityPanel,diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex cac249e9f97..6d414a6d44b 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -17,7 +17,6 @@ import {ArrowReloadHorizontalIcon,Delete02Icon,Download01Icon,- FlimSlateIcon,Image03Icon,ImageAdd02Icon,InformationCircleIcon,@@ -87,7 +86,9 @@ import { MediaRailResizeHandle } from "@/components/media-rail-resize-handle";import { MEDIA_RAIL_ROOT_ATTR, useMediaRailWidth } from "@/hooks/use-media-rail-width";import { StripDropLine } from "@/components/gallery-strip-reorder";import { useStripReorder } from "@/hooks/use-strip-reorder";-import { MediaPageLink } from "@/components/media-page-link";+import { LibraryPageLink } from "@/components/media-page-link";+import { translate } from "@/i18n";+import { useLibraryFavorites } from "@/features/library";import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";import {type NewRecordProbeBaseline,@@ -156,6 +157,7 @@ import {routedGgufLabel,} from "@/lib/diffusion-route-search";import { toast } from "@/lib/toast";+import { loadGalleryUntil } from "@/lib/gallery-deep-link";import { subscribeModelEjected } from "@/lib/model-lifecycle-events";import { DEFAULT_GEN, defaultsFor, resolutionFor } from "./image-generation-defaults";import {@@ -2011,6 +2013,7 @@ export function ImagesPage({// The pin state each id was last CLICKED into, so a failing request can tell whether it is// still the current intent; without it a slow failure rolls back a later success.+ const { isFavorite, toggleFavorite } = useLibraryFavorites();const pinAttempt = useRef(new Map<string, number>());const pinSeq = useRef(0);@@ -3263,6 +3266,37 @@ export function ImagesPage({revertPick,]);+ // A Library "View in" link arrives as ?item=: select that image, paging back until it loads. A+ // counter, not effect cleanup, retires a lookup: clearing the query must not cancel its own.+ const routedItem = active ? routeSearch?.item : undefined;+ const routedLookup = useRef(0);+ useEffect(() => {+ if (!active) routedLookup.current += 1;+ }, [active]);+ useEffect(() => {+ if (!routedItem) return;+ const lookup = ++routedLookup.current;+ void navigateSelf({ to: "/images", search: {}, replace: true });+ void loadGalleryUntil({+ has: () => galleryCache.images.some((entry) => entry.id === routedItem),+ count: () => galleryCache.images.length,+ hasMore: () => galleryCache.hasMore,+ refresh: loadGallery,+ loadMore,+ busy: () => loadingMore.current,+ cancelled: () => lookup !== routedLookup.current,+ }).then((found) => {+ if (lookup !== routedLookup.current) return;+ if (found) {+ setSelectedId(routedItem);+ } else {+ toast(translate("library.toast.imageNotFound"), {+ description: translate("library.toast.notFoundDescription"),+ });+ }+ });+ }, [routedItem, navigateSelf, loadGallery, loadMore]);+// Reload the current model with the current advanced options.const handleReapply = useCallback(() => {const l = lastLoad.current;@@ -4570,10 +4604,8 @@ export function ImagesPage({</div><div className="pointer-events-none col-start-3 flex min-w-0 items-start justify-end pr-2 pt-[var(--studio-chat-header-padding-top,11px)]"><div className="pointer-events-auto flex min-w-0 items-center gap-2">- <MediaPageLink- to="/video"- label="Video"- icon={FlimSlateIcon}+ <LibraryPageLink+ tab="images"labelClassName="hidden @[50rem]:inline"arrowClassName="hidden @[50rem]:block"/>@@ -5327,6 +5359,8 @@ export function ImagesPage({active={active}pinned={Boolean(selected.pinned)}archived={Boolean(selected.archived)}+ favorite={isFavorite(`image:${selected.id}`)}+ onToggleFavorite={() => toggleFavorite(`image:${selected.id}`)}onTogglePin={() =>void handleTogglePin(selected.id, !selected.pinned)}@@ -5454,6 +5488,8 @@ export function ImagesPage({active={active}pinned={Boolean(image.pinned)}archived={Boolean(image.archived)}+ favorite={isFavorite(`image:${image.id}`)}+ onToggleFavorite={() => toggleFavorite(`image:${image.id}`)}onTogglePin={() => void handleTogglePin(image.id, !image.pinned)}onToggleArchive={() => void handleArchive(image.id)}onDelete={() => void handleDelete(image.id)}diff --git a/studio/frontend/src/features/library/actions-context.ts b/studio/frontend/src/features/library/actions-context.tsnew file mode 100644index 00000000000..e3d0c080929--- /dev/null+++ b/studio/frontend/src/features/library/actions-context.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { createContext, useContext } from "react";+import type { LibraryFolder, LibraryItem } from "./api";++export type LibraryTarget =+ | { kind: "item"; item: LibraryItem }+ | { kind: "folder"; folder: LibraryFolder };++export interface LibraryActions {+ folders: LibraryFolder[];+ openItem: (item: LibraryItem) => void;+ openFolder: (folderId: string) => void;+ chatAbout: (target: LibraryTarget) => void;+ toggleFavorite: (item: LibraryItem) => void;+ download: (item: LibraryItem) => void;+ rename: (target: LibraryTarget) => void;+ moveTo: (target: LibraryTarget, folderId: string | null) => void;+ moveToNewFolder: (target: LibraryTarget) => void;+ remove: (target: LibraryTarget) => void;+}++const LibraryActionsContext = createContext<LibraryActions | null>(null);++export const LibraryActionsProvider = LibraryActionsContext.Provider;++export function useLibraryActions(): LibraryActions {+ const actions = useContext(LibraryActionsContext);+ if (!actions) throw new Error("useLibraryActions outside LibraryActionsProvider");+ return actions;+}diff --git a/studio/frontend/src/features/library/actions.ts b/studio/frontend/src/features/library/actions.tsnew file mode 100644index 00000000000..64750621083--- /dev/null+++ b/studio/frontend/src/features/library/actions.ts@@ -0,0 +1,246 @@+// 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 { useNavigate } from "@tanstack/react-router";+import { zipSync } from "fflate";+import { getAuthSessionEpoch } from "@/features/auth";+import { clearNewChatDraft, listLoras, useChatRuntimeStore } from "@/features/chat";+import {+ clearModelConfigHandoff,+ createModelConfigHandoffRequestId,+ requestModelConfigHandoff,+} from "@/features/model-picker";+import { translate } from "@/i18n";+import { MAX_AUDIO_SIZE } from "@/lib/audio-utils";+import { isTauri } from "@/lib/api-base";+import { downloadFile, downloadUrlStreaming, isDownloadCancelled } from "@/lib/native-files";+import { toast } from "@/lib/toast";+import { MAX_VIDEO_SIZE } from "@/lib/video-utils";+import {+ LibraryFileTooLarge,+ type LibraryItem,+ errorMessage,+ libraryDownloadUrl,+ libraryItemFile,+} from "./api";+import { fileKind } from "./file-kind";+import { hasOwnFile, libraryFileName, uniqueFileNames } from "./file-name";+import {+ type LibraryChatHandoff,+ useLibraryChatHandoffStore,+} from "./chat-handoff-store";++type Navigate = ReturnType<typeof useNavigate>;++export const MAX_CHAT_FILES = 10;++const MAX_IMAGE_OR_TEXT_BYTES = 20 * 1024 * 1024;+const MAX_DOCUMENT_BYTES = 50 * 1024 * 1024;++function chatSizeLimit(item: LibraryItem): number {+ const kind = fileKind(item);+ if (kind === "audio") return MAX_AUDIO_SIZE;+ if (kind === "video") return MAX_VIDEO_SIZE;+ if (kind === "image" || kind === "code" || kind === "web" || item.textOnly) {+ return MAX_IMAGE_OR_TEXT_BYTES;+ }+ return item.contentType.startsWith("text/") ? MAX_IMAGE_OR_TEXT_BYTES : MAX_DOCUMENT_BYTES;+}++function fitsInChat(item: LibraryItem): boolean {+ return item.sizeBytes === null || item.sizeBytes <= chatSizeLimit(item);+}++export async function downloadLibraryItem(+ item: LibraryItem,+ epoch = getAuthSessionEpoch(),+): Promise<void> {+ if (getAuthSessionEpoch() !== epoch) return;+ try {+ if (isTauri && !item.textOnly && hasOwnFile(item.id)) {+ const url = await libraryDownloadUrl(item);+ if (getAuthSessionEpoch() !== epoch) return;+ await downloadUrlStreaming(url, libraryFileName(item));+ return;+ }+ const file = await libraryItemFile(item);+ if (getAuthSessionEpoch() !== epoch) return;+ await downloadFile(file, file.name, file.type);+ } catch (error) {+ if (isDownloadCancelled(error)) return;+ toast.error(translate("library.toast.downloadFailed", { name: item.name }), {+ description: errorMessage(error),+ });+ }+}++const MAX_ZIP_BYTES = 256 * 1024 * 1024;++export async function downloadLibraryItems(items: LibraryItem[]): Promise<void> {+ const epoch = getAuthSessionEpoch();+ if (items.length <= 1 || isTauri) {+ for (const item of items) await downloadLibraryItem(item, epoch);+ return;+ }+ // A file of unknown size could be any size, so it never goes into a zip held in memory.+ const bytes = items.reduce((sum, item) => sum + (item.sizeBytes ?? Infinity), 0);+ if (bytes > MAX_ZIP_BYTES) {+ toast(translate("library.toast.downloadingMany", { count: items.length }), {+ description: translate("library.toast.downloadingManyDescription"),+ });+ for (const item of items) await downloadLibraryItem(item, epoch);+ return;+ }+ const progress = toast.loading(translate("library.toast.preparingMany", { count: items.length }));+ try {+ const files: File[] = [];+ let budget = MAX_ZIP_BYTES;+ for (const item of items) {+ let file: File;+ try {+ file = await libraryItemFile(item, budget);+ } catch (error) {+ if (!(error instanceof LibraryFileTooLarge)) throw error;+ // Grown past what the listing said: one download at a time instead of one zip in memory.+ toast.dismiss(progress);+ for (const each of items) await downloadLibraryItem(each, epoch);+ return;+ }+ budget -= file.size;+ files.push(file);+ if (getAuthSessionEpoch() !== epoch) return;+ }+ const names = uniqueFileNames(["__proto__", ...files.map((file) => file.name)]).slice(1);+ const entries: Record<string, Uint8Array> = {};+ for (const [index, file] of files.entries()) {+ entries[names[index]!] = new Uint8Array(await file.arrayBuffer());+ }+ const archive = zipSync(entries, { level: 0 });+ if (getAuthSessionEpoch() !== epoch) return;+ await downloadFile(+ new Blob([archive], { type: "application/zip" }),+ `${translate("library.toast.zipFileName")}.zip`,+ );+ } catch (error) {+ toast.error(translate("library.toast.downloadManyFailed"), { description: errorMessage(error) });+ } finally {+ toast.dismiss(progress);+ }+}++function resetToNewChat(): void {+ clearNewChatDraft();+ const runtime = useChatRuntimeStore.getState();+ runtime.setActiveThreadId(null);+ runtime.setActiveProjectId(null);+ runtime.setIncognito(false);+}++function startLibraryChat(+ navigate: Navigate,+ handoff: LibraryChatHandoff,+): void {+ const nonce = createModelConfigHandoffRequestId();+ resetToNewChat();+ useLibraryChatHandoffStore.getState().offer(`single:${nonce}`, handoff);+ void navigate({ to: "/chat", search: { new: nonce } });+}++export async function chatAboutItems(+ navigate: Navigate,+ items: LibraryItem[],+): Promise<void> {+ if (items.length === 0) {+ toast(translate("library.toast.nothingToChat"), {+ description: translate("library.toast.emptyFolder"),+ });+ return;+ }+ const fitting = items.filter(fitsInChat);+ let tooLarge = items.length - fitting.length;+ if (fitting.length === 0) {+ toast.error(+ items.length === 1+ ? translate("library.toast.tooLargeOne", { name: items[0].name })+ : translate("library.toast.tooLargeMany"),+ );+ return;+ }+ const chosen = fitting.slice(0, MAX_CHAT_FILES);+ const epoch = getAuthSessionEpoch();+ try {+ // One at a time, so a folder never holds ten downloads in flight at once.+ const files: File[] = [];+ // Bounded as it reads: a size the listing did not know, or a file grown since, is only found here.+ for (const item of chosen) {+ try {+ files.push(await libraryItemFile(item, chatSizeLimit(item)));+ } catch (error) {+ if (!(error instanceof LibraryFileTooLarge)) throw error;+ tooLarge += 1;+ }+ if (getAuthSessionEpoch() !== epoch) return;+ }+ if (files.length === 0) {+ toast.error(+ chosen.length === 1+ ? translate("library.toast.tooLargeOne", { name: chosen[0].name })+ : translate("library.toast.tooLargeMany"),+ );+ return;+ }+ const leftOut = fitting.length - chosen.length;+ if (tooLarge > 0 || leftOut > 0) {+ const attached =+ files.length === 1 ? "library.toast.attachedOne" : "library.toast.attachedMany";+ toast(translate(attached, { count: files.length }), {+ description: [+ tooLarge > 0 && translate("library.toast.skippedTooLarge", { count: tooLarge }),+ leftOut > 0 &&+ translate("library.toast.skippedOverLimit", { count: leftOut, limit: MAX_CHAT_FILES }),+ ]+ .filter(Boolean)+ .join(" "),+ });+ }+ startLibraryChat(navigate, { files });+ } catch (error) {+ toast.error(translate("library.toast.openFilesFailed"), { description: errorMessage(error) });+ }+}++export async function chatWithModel(+ navigate: Navigate,+ item: LibraryItem,+): Promise<void> {+ const model = item.model;+ if (!model) return;+ const epoch = getAuthSessionEpoch();+ const scanned = await listLoras()+ .then(({ loras }) => loras.find((lora) => lora.adapter_path === model.path))+ .catch(() => undefined);+ if (getAuthSessionEpoch() !== epoch) return;+ if (scanned?.audio_type) {+ toast(translate("library.toast.speechModel", { name: item.name }), {+ description: translate("library.toast.speechModelDescription"),+ });+ void navigate({ to: "/audio" });+ return;+ }+ const requestId = createModelConfigHandoffRequestId();+ resetToNewChat();+ requestModelConfigHandoff({+ requestId,+ id: model.path,+ displayName: item.name,+ meta: {+ source: model.origin === "exported" ? "exported" : "lora",+ isLora: model.exportType === "lora",+ isDownloaded: true,+ isGguf: model.exportType === "gguf",+ },+ });+ void navigate({ to: "/chat", search: { new: requestId } }).catch(() =>+ clearModelConfigHandoff(requestId),+ );+}diff --git a/studio/frontend/src/features/library/api.ts b/studio/frontend/src/features/library/api.tsnew file mode 100644index 00000000000..ff436059b48--- /dev/null+++ b/studio/frontend/src/features/library/api.ts@@ -0,0 +1,346 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch, getAuthSessionEpoch, getAuthToken } from "@/features/auth";+import { type TranslationKey, translate } from "@/i18n";+import { apiUrl } from "@/lib/api-base";+import { readFastApiError } from "@/lib/format-fastapi-error";+import { itemVersion, libraryFileName, libraryFileType } from "./file-name";+import { type DecodedNote, type NoteEncoding, decodeNote } from "./note-text";++export type LibrarySource = "uploaded" | "generated";++export interface LibraryItem {+ id: string;+ name: string;+ fileName?: string;+ source: LibrarySource;+ contentType: string;+ sizeBytes: number | null;+ fingerprint?: string;+ createdAt: number;+ updatedAt: number;+ fileUrl: string;+ threadId: string | null;+ threadTitle: string | null;+ textOnly: boolean;+ favorite: boolean;+ folderId: string | null;+ /** Set for fine-tuned models, which are directories: opened in chat, never downloaded. */+ model: LibraryModel | null;+ archived?: boolean;+}++export interface LibraryModel {+ path: string;+ origin: "training" | "exported";+ exportType: "lora" | "merged" | "gguf";+ baseModel: string | null;+}++export interface LibraryFolder {+ id: string;+ name: string;+ parentId: string | null;+ createdAt: number;+ updatedAt: number;+}++export interface LibrarySnapshot {+ items: LibraryItem[];+ folders: LibraryFolder[];+}++export function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++async function ensureOk(response: Response): Promise<Response> {+ if (!response.ok) throw new Error(await readFastApiError(response));+ return response;+}++function jsonInit(method: string, body: unknown): RequestInit {+ return {+ method,+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ };+}++export async function getLibrary(): Promise<LibrarySnapshot> {+ const response = await ensureOk(await authFetch("/api/library"));+ return response.json();+}++export async function getLibraryFavorites(): Promise<string[]> {+ const response = await ensureOk(await authFetch("/api/library/favorites"));+ return ((await response.json()) as { ids: string[] }).ids;+}++const writeQueues = new Map<string, Promise<void>>();++function sameSession(epoch: number, message: TranslationKey): () => void {+ return () => {+ if (getAuthSessionEpoch() !== epoch) throw new Error(translate(message));+ };+}++/** A write: a retry never goes out under an account other than the one that sent it. */+function sendWrite(input: string, init: RequestInit): Promise<Response> {+ return authFetch(input, init, {+ beforeRetry: sameSession(getAuthSessionEpoch(), "library.toast.signedOutBeforeSave"),+ });+}++/**+ * Sends one write for `target` after the ones before it, so a quick second change never lands+ * first. Per session too: another account can have an item or folder of this id, and must not+ * wait on a write of the account that left, which a sign-out does not cut short.+ */+function inOrder(target: string, send: (check: () => void) => Promise<Response>): Promise<void> {+ const epoch = getAuthSessionEpoch();+ const key = `${epoch}:${target}`;+ const request = (writeQueues.get(key) ?? Promise.resolve())+ .catch(() => {})+ .then(async () => {+ const check = sameSession(epoch, "library.toast.signedOutBeforeSave");+ check();+ await ensureOk(await send(check));+ });+ writeQueues.set(key, request);+ const settle = () => {+ if (writeQueues.get(key) === request) writeQueues.delete(key);+ };+ request.then(settle, settle);+ return request;+}++export function updateLibraryItem(+ id: string,+ patch: { name?: string; favorite?: boolean; folderId?: string | null },+): Promise<void> {+ return inOrder(`item:${id}`, (check) =>+ authFetch("/api/library/items", jsonInit("PATCH", { id, ...patch }), { beforeRetry: check }),+ );+}++export async function addLibraryItemToProject(+ id: string,+ projectId: string,+): Promise<{ already: boolean }> {+ const response = await ensureOk(+ await sendWrite("/api/library/items/project", jsonInit("POST", { id, projectId })),+ );+ return response.json();+}++export async function revealLibraryItem(id: string): Promise<void> {+ await ensureOk(await sendWrite("/api/library/items/reveal", jsonInit("POST", { id })));+}++export async function deleteLibraryItem(id: string, fingerprint?: string): Promise<void> {+ await ensureOk(+ await sendWrite("/api/library/items/delete", jsonInit("POST", { id, fingerprint })),+ );+}++export interface LibraryUploadBatch {+ files?: File[];+ nativePathLeases?: string[];+ sessionEpoch?: number;+}++export const MAX_LIBRARY_UPLOAD_BYTES = 512 * 1024 * 1024;+// Starlette's form parser refuses more than 1000 files in one request (Request.form max_files).+const MAX_LIBRARY_UPLOAD_FILES = 1000;+// And more than 1000 other fields (max_fields): the leases, with room for folderId.+const MAX_LEASES_PER_REQUEST = 999;++function uploadGroups(files: File[]): File[][] {+ const groups: File[][] = [];+ let bytes = Infinity;+ for (const file of files) {+ if (+ bytes + file.size > MAX_LIBRARY_UPLOAD_BYTES ||+ (groups.at(-1)?.length ?? 0) >= MAX_LIBRARY_UPLOAD_FILES+ ) {+ groups.push([]);+ bytes = 0;+ }+ groups[groups.length - 1]!.push(file);+ bytes += file.size;+ }+ return groups;+}++export async function uploadLibraryFiles(+ batch: LibraryUploadBatch,+ folderId: string | null,+): Promise<string[]> {+ const files = batch.files ?? [];+ const tooLarge = files.find((file) => file.size > MAX_LIBRARY_UPLOAD_BYTES);+ if (tooLarge) throw new Error(translate("library.toast.uploadTooLarge", { name: tooLarge.name }));+ const leases = batch.nativePathLeases ?? [];+ const requests: FormData[] = uploadGroups(files).map((group) => {+ const form = new FormData();+ for (const file of group) form.append("files", file, file.name);+ return form;+ });+ for (let start = 0; start < leases.length; start += MAX_LEASES_PER_REQUEST) {+ const form = new FormData();+ for (const lease of leases.slice(start, start + MAX_LEASES_PER_REQUEST)) {+ form.append("nativePathLeases", lease);+ }+ requests.push(form);+ }+ if (requests.length === 0) requests.push(new FormData());+ const check = sameSession(+ batch.sessionEpoch ?? getAuthSessionEpoch(),+ "library.toast.signedOutBeforeUpload",+ );+ const ids: string[] = [];+ for (const form of requests) {+ check();+ if (folderId) form.append("folderId", folderId);+ const response = await ensureOk(+ await authFetch("/api/library/uploads", { method: "POST", body: form }, { beforeRetry: check }),+ );+ ids.push(...((await response.json()) as { ids: string[] }).ids);+ }+ return ids;+}++export async function writeLibraryText(+ itemId: string,+ text: string,+ encoding: NoteEncoding,+): Promise<void> {+ const uploadId = itemId.replace(/^upload:/, "");+ await ensureOk(+ await sendWrite(+ `/api/library/uploads/${encodeURIComponent(uploadId)}/text`,+ jsonInit("PUT", { text, encoding }),+ ),+ );+}++export async function createLibraryFolder(+ name: string,+ parentId: string | null,+): Promise<LibraryFolder> {+ const response = await ensureOk(+ await sendWrite("/api/library/folders", jsonInit("POST", { name, parentId })),+ );+ return response.json();+}++export function updateLibraryFolder(+ id: string,+ patch: { name?: string; parentId?: string | null },+): Promise<void> {+ return inOrder(`folder:${id}`, (check) =>+ authFetch(`/api/library/folders/${encodeURIComponent(id)}`, jsonInit("PATCH", patch), {+ beforeRetry: check,+ }),+ );+}++export function deleteLibraryFolder(id: string): Promise<void> {+ return inOrder(`folder:${id}`, (check) =>+ authFetch(`/api/library/folders/${encodeURIComponent(id)}`, { method: "DELETE" }, {+ beforeRetry: check,+ }),+ );+}++export class LibraryFileTooLarge extends Error {}++export async function fetchLibraryBlob(+ item: LibraryItem,+ type: string,+ maxBytes = Infinity,+): Promise<Blob> {+ const response = await ensureOk(await authFetch(item.fileUrl));+ if (Number(response.headers.get("content-length")) > maxBytes) {+ void response.body?.cancel();+ throw new LibraryFileTooLarge(item.name);+ }+ const reader = maxBytes === Infinity ? undefined : response.body?.getReader();+ if (!reader) {+ const blob = await response.blob();+ if (blob.size > maxBytes) throw new LibraryFileTooLarge(item.name);+ return blob.type === type ? blob : new Blob([blob], { type });+ }+ const chunks: Uint8Array<ArrayBuffer>[] = [];+ let read = 0;+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ read += value.length;+ if (read > maxBytes) {+ void reader.cancel();+ throw new LibraryFileTooLarge(item.name);+ }+ chunks.push(value);+ }+ return new Blob(chunks, { type });+}++export async function fetchLibraryStreamUrl(item: LibraryItem): Promise<string> {+ const params = new URLSearchParams({ id: item.id });+ const response = await ensureOk(await authFetch(`/api/library/items/stream-url?${params}`));+ const { url } = (await response.json()) as { url?: string };+ if (!url) throw new Error(translate("library.toast.noMediaLink"));+ return apiUrl(url);+}++export async function fetchLibraryThumbnail(item: LibraryItem): Promise<Blob> {+ const params = new URLSearchParams({ id: item.id, v: itemVersion(item) });+ const response = await ensureOk(await authFetch(`/api/library/items/thumbnail?${params}`));+ return response.blob();+}++/** Up to `maxBytes` of the item, decoded as its BOM (or UTF-8) says; the rest is never read. */+export async function fetchLibraryText(+ item: LibraryItem,+ maxBytes: number,+): Promise<DecodedNote & { truncated: boolean }> {+ const response = await ensureOk(await authFetch(item.fileUrl));+ const reader = response.body?.getReader();+ if (!reader) {+ const bytes = new Uint8Array(await response.arrayBuffer());+ const truncated = bytes.length > maxBytes;+ return { ...decodeNote(bytes.subarray(0, maxBytes), truncated), truncated };+ }+ const chunks: Uint8Array<ArrayBuffer>[] = [];+ let read = 0;+ let truncated = false;+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ if (read + value.length > maxBytes) {+ chunks.push(value.subarray(0, maxBytes - read));+ truncated = true;+ void reader.cancel();+ break;+ }+ chunks.push(value);+ read += value.length;+ }+ const bytes = new Uint8Array(await new Blob(chunks).arrayBuffer());+ return { ...decodeNote(bytes, truncated), truncated };+}++export async function libraryDownloadUrl(item: LibraryItem): Promise<string> {+ const path = `/api/library/items/download?${new URLSearchParams({ id: item.id })}`;+ await ensureOk(await authFetch(path, { method: "HEAD" }));+ const token = getAuthToken();+ return apiUrl(token ? `${path}&token=${encodeURIComponent(token)}` : path);+}++export async function libraryItemFile(item: LibraryItem, maxBytes = Infinity): Promise<File> {+ const name = libraryFileName(item);+ const type = libraryFileType(name, item.textOnly ? "text/plain" : item.contentType);+ return new File([await fetchLibraryBlob(item, type, maxBytes)], name, { type });+}diff --git a/studio/frontend/src/features/library/chat-handoff-store.ts b/studio/frontend/src/features/library/chat-handoff-store.tsnew file mode 100644index 00000000000..ef80387954e--- /dev/null+++ b/studio/frontend/src/features/library/chat-handoff-store.ts@@ -0,0 +1,79 @@+// 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 { AUTH_SESSION_CLEARED_EVENT } from "../auth/session-events.ts";++// "Chat about this" hands files to a composer that may not be mounted yet (the chat page mounts+// on navigation) or already is (it stays mounted off-route). Keyed by the composer's attachment+// target, so only the fresh chat that was opened for the files picks them up. Kept free of other+// imports but an event name: the chat thread reads it, and must not pull the Library in.+export interface LibraryChatHandoff {+ files: File[];+}++interface LibraryChatHandoffState {+ pending: { targetKey: string; handoff: LibraryChatHandoff } | null;+ held: { targetKey: string; files: File[] } | null;+ offer: (targetKey: string, handoff: LibraryChatHandoff) => void;+ take: (targetKey: string) => LibraryChatHandoff | null;+}++let session = 0;++export const useLibraryChatHandoffStore = create<LibraryChatHandoffState>(+ (set, get) => ({+ pending: null,+ held: null,+ offer: (targetKey, handoff) => set({ pending: { targetKey, handoff }, held: null }),+ take: (targetKey) => {+ const pending = get().pending;+ if (!pending || pending.targetKey !== targetKey) return null;+ set({ pending: null });+ return pending.handoff;+ },+ }),+);++export async function attachLibraryChatFiles(+ targetKey: string,+ add: (file: File) => Promise<unknown>,+ retryHeld = false,+): Promise<number> {+ const store = useLibraryChatHandoffStore;+ const started = session;+ const held = store.getState().held;+ let files: File[];+ if (retryHeld) {+ if (held?.targetKey !== targetKey) return 0;+ store.setState({ held: null });+ files = held.files;+ } else {+ files = store.getState().take(targetKey)?.files ?? [];+ }+ const refused: File[] = [];+ for (const file of files) {+ if (session !== started) return 0;+ try {+ await add(file);+ } catch {+ refused.push(file);+ }+ }+ if (refused.length === 0 || session !== started) return 0;+ store.setState(({ held: now }) => ({+ held: {+ targetKey,+ files: [...(now?.targetKey === targetKey ? now.files : []), ...refused],+ },+ }));+ return refused.length;+}++// Module state outlives a sign-out; the next account must not be handed these files.+if (typeof window !== "undefined") {+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, () => {+ session += 1;+ useLibraryChatHandoffStore.setState({ pending: null, held: null });+ });+}diff --git a/studio/frontend/src/features/library/components/card-selection.ts b/studio/frontend/src/features/library/components/card-selection.tsnew file mode 100644index 00000000000..aae8b3f5e66--- /dev/null+++ b/studio/frontend/src/features/library/components/card-selection.ts@@ -0,0 +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 { createContext } from "react";++export const CardSelectionContext = createContext<{+ selection: ReadonlySet<string>;+ toggle: (key: string) => void;+} | null>(null);diff --git a/studio/frontend/src/features/library/components/library-actions.tsx b/studio/frontend/src/features/library/components/library-actions.tsxnew file mode 100644index 00000000000..30bac77a55c--- /dev/null+++ b/studio/frontend/src/features/library/components/library-actions.tsx@@ -0,0 +1,185 @@+// 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 {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import {+ Delete02Icon,+ Download01Icon,+ Edit03Icon,+ Folder01Icon,+ FolderAddIcon,+ FolderExportIcon,+ MoreHorizontalIcon,+} from "@hugeicons/core-free-icons";+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 { type LibraryTarget, useLibraryActions } from "../actions-context";+import { canReveal, revealInFolder, useRevealLabel } from "../reveal";+import { OVERLAY_CONTROL } from "../surface";++const ICON = "size-icon";++/** Folders a target can move into, depth-first with their nesting depth. A folder is never offered+ * itself or anything under it. */+function moveDestinations(+ folders: LibraryFolder[],+ target: LibraryTarget,+): { folder: LibraryFolder; depth: number }[] {+ const excluded = target.kind === "folder" ? target.folder.id : null;+ const byParent = new Map<string | null, LibraryFolder[]>();+ for (const folder of folders) {+ const siblings = byParent.get(folder.parentId) ?? [];+ siblings.push(folder);+ byParent.set(folder.parentId, siblings);+ }+ const out: { folder: LibraryFolder; depth: number }[] = [];+ const walk = (parentId: string | null, depth: number) => {+ const children = [...(byParent.get(parentId) ?? [])].sort((a, b) =>+ a.name.localeCompare(b.name),+ );+ for (const folder of children) {+ if (folder.id === excluded) continue;+ out.push({ folder, depth });+ walk(folder.id, depth + 1);+ }+ };+ walk(null, 0);+ return out;+}++function currentFolderId(target: LibraryTarget): string | null {+ return target.kind === "item" ? target.item.folderId : target.folder.parentId;+}++export function LibraryActionsMenu({+ target,+ variant,+ className,+}: {+ target: LibraryTarget;+ variant: "overlay" | "row";+ className?: string;+}) {+ const t = useT();+ const actions = useLibraryActions();+ const [open, setOpen] = useState(false);+ const destinations = useMemo(+ () => (open ? moveDestinations(actions.folders, target) : []),+ [open, actions.folders, target],+ );+ const inFolder = currentFolderId(target);+ const item = target.kind === "item" ? target.item : null;+ const isFile = !item || isFileItem(item);+ const revealLabel = useRevealLabel();++ return (+ <DropdownMenu open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={t("library.menu.moreActions")}+ data-open={open || undefined}+ onClick={(event) => event.stopPropagation()}+ className={cn(+ "flex shrink-0 items-center justify-center rounded-full outline-none transition-opacity focus-visible:opacity-100 data-open:opacity-100",+ variant === "overlay"+ ? cn(+ OVERLAY_CONTROL,+ "size-8 text-muted-foreground opacity-0 hover:text-foreground group-hover/library-card:opacity-100 dark:text-white dark:hover:bg-neutral-600",+ )+ : "size-8 text-muted-foreground opacity-0 hover:bg-accent hover:text-foreground group-hover/library-row:opacity-100",+ className,+ )}+ >+ <HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="w-60"+ onClick={(event) => event.stopPropagation()}+ >+ <DropdownMenuItem onSelect={() => actions.chatAbout(target)}>+ <HugeiconsIcon icon={MessageCircleIcon} strokeWidth={1.75} className={ICON} />+ {t(item && isModelItem(item) ? "library.menu.chatWithModel" : "library.menu.chatAboutThis")}+ </DropdownMenuItem>+ {item && (+ <DropdownMenuItem onSelect={() => actions.toggleFavorite(item)}>+ <HugeiconsIcon+ icon={StarPointedIcon}+ strokeWidth={1.75}+ className={cn(ICON, item.favorite && "[&_path]:fill-current")}+ />+ {t(item.favorite ? "library.menu.removeFromFavorites" : "library.menu.addToFavorites")}+ </DropdownMenuItem>+ )}+ {item && isFile && (+ <DropdownMenuItem onSelect={() => actions.download(item)}>+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className={ICON} />+ {t("library.menu.download")}+ </DropdownMenuItem>+ )}+ {item && revealLabel && canReveal(item) && (+ <DropdownMenuItem onSelect={() => revealInFolder(item.id)}>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className={ICON} />+ {revealLabel}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem onSelect={() => actions.rename(target)}>+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className={ICON} />+ {t("common.rename")}+ </DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-2.5">+ <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className={ICON} />+ {t("library.menu.addToFolder")}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-[min(--spacing(80),var(--radix-dropdown-menu-content-available-height))] w-56">+ <DropdownMenuItem onSelect={() => actions.moveToNewFolder(target)}>+ <HugeiconsIcon icon={FolderAddIcon} strokeWidth={1.75} className={ICON} />+ {t("library.menu.newFolder")}+ </DropdownMenuItem>+ {inFolder && (+ <DropdownMenuItem onSelect={() => actions.moveTo(target, null)}>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className={ICON} />+ {t("library.menu.noFolder")}+ </DropdownMenuItem>+ )}+ {destinations.length > 0 && <DropdownMenuSeparator />}+ {destinations.map(({ folder, depth }) => (+ <DropdownMenuItem+ key={folder.id}+ disabled={folder.id === inFolder}+ onSelect={() => actions.moveTo(target, folder.id)}+ style={{ paddingLeft: `${12 + depth * 14}px` }}+ >+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className={ICON} />+ <span className="truncate">{folder.name}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ {isFile && (+ <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")}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/studio/frontend/src/features/library/components/library-cards.tsx b/studio/frontend/src/features/library/components/library-cards.tsxnew file mode 100644index 00000000000..15c59cc22bb--- /dev/null+++ b/studio/frontend/src/features/library/components/library-cards.tsx@@ -0,0 +1,284 @@+// 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 { Checkbox } from "@/components/ui/checkbox";+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 { LibraryFolder, LibraryItem } from "../api";+import {+ KIND_ICONS,+ KIND_ICON_CLASS,+ fileKind,+ hasThumbnail,+} from "../file-kind";+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 { CardSelectionContext } from "./card-selection";+import { LibraryActionsMenu } from "./library-actions";++const CARD_SHADOW =+ "shadow-[0_1px_2px_rgba(0,0,0,0.04),0_4px_16px_rgba(0,0,0,0.06)] dark:shadow-none";++const CARD_SURFACE = cn(+ RAISED_SURFACE,+ CARD_SHADOW,+ "group-hover/library-card:bg-neutral-100 group-hover/library-card:shadow-none dark:group-hover/library-card:bg-accent/60",+);++export function KindIcon({ item, className }: { item: LibraryItem; className?: string }) {+ const kind = fileKind(item);+ return (+ <HugeiconsIcon+ icon={KIND_ICONS[kind]}+ strokeWidth={1.5}+ className={cn(KIND_ICON_CLASS[kind], className, kind === "model" && "scale-95")}+ />+ );+}++const MIN_THUMB_RATIO = 2 / 3;+const MAX_THUMB_RATIO = 3 / 2;++function ImageThumb({ item, className }: { item: LibraryItem; className?: string }) {+ const holder = useRef<HTMLDivElement>(null);+ const { url, failed } = useLibraryThumbnail(item, useSeen(holder));+ const [ratio, setRatio] = useState<number | null>(null);+ const loaded = ratio !== null;+ const [brokenUrl, setBrokenUrl] = useState<string | null>(null);+ if (failed || (url !== null && url === brokenUrl)) {+ return (+ <div className={cn("flex aspect-square items-center justify-center", className)}>+ <KindIcon item={item} className="h-auto w-1/4 max-w-9" />+ </div>+ );+ }+ return (+ <div+ ref={holder}+ className={cn("relative overflow-hidden", className)}+ style={+ loaded+ ? { aspectRatio: 1 / Math.min(Math.max(ratio, MIN_THUMB_RATIO), MAX_THUMB_RATIO) }+ : undefined+ }+ >+ {!loaded && <div className="aspect-square w-full animate-pulse bg-muted" />}+ {url && (+ <img+ src={url}+ alt={item.name}+ draggable={false}+ onLoad={(event) => {+ const { naturalWidth, naturalHeight } = event.currentTarget;+ setRatio(naturalWidth > 0 ? naturalHeight / naturalWidth : 1);+ }}+ onError={() => setBrokenUrl(url)}+ className={cn(+ "absolute inset-0 block size-full object-cover",+ !loaded && "opacity-0",+ loaded && ratio > MAX_THUMB_RATIO && "object-top",+ )}+ />+ )}+ {loaded && fileKind(item) === "video" && (+ <span className="pointer-events-none absolute inset-0 m-auto flex aspect-square w-1/4 max-w-10 items-center justify-center rounded-full bg-white/30 text-white backdrop-blur-md dark:bg-black/40">+ <HugeiconsIcon icon={PlayIcon} strokeWidth={2} className="size-1/2 [&_path]:fill-current" />+ </span>+ )}+ </div>+ );+}++function CardFrame({+ selectKey,+ onOpen,+ menu,+ children,+ className,+ label,+ glass = false,+}: {+ selectKey: string;+ onOpen: () => void;+ menu: ReactNode;+ children: ReactNode;+ className?: string;+ label: string;+ glass?: boolean;+}) {+ const t = useT();+ const select = useContext(CardSelectionContext);+ const selected = select?.selection.has(selectKey) ?? false;+ const selecting = (select?.selection.size ?? 0) > 0;+ return (+ <div className="group/library-card relative">+ <button+ type="button"+ aria-label={label}+ aria-pressed={select && selecting ? selected : undefined}+ onClick={select && selecting ? () => select.toggle(selectKey) : onOpen}+ className={cn(+ "block w-full overflow-hidden rounded-xl text-left outline-none transition focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",+ selected && "ring-3 ring-foreground",+ className,+ )}+ >+ {children}+ </button>+ {select && (+ <Checkbox+ checked={selected}+ onCheckedChange={() => select.toggle(selectKey)}+ aria-label={t("library.selectItem", { name: label })}+ className={cn(+ OVERLAY_CONTROL,+ "absolute bottom-4 right-4 size-5 rounded-full border-0 opacity-0 transition-opacity group-hover/library-card:opacity-100 focus-visible:opacity-100 data-checked:bg-white data-checked:text-foreground dark:data-checked:bg-neutral-200 dark:data-checked:text-neutral-900 [&_svg]:size-3.5",+ glass && GLASS_CONTROL,+ selected && "opacity-100",+ )}+ />+ )}+ <div className="absolute right-2 top-2">{menu}</div>+ </div>+ );+}++export function ItemCard({ item }: { item: LibraryItem }) {+ const locale = useLocale();+ const actions = useLibraryActions();+ const thumb = hasThumbnail(item);+ return (+ <CardFrame+ selectKey={`item:${item.id}`}+ label={item.name}+ onOpen={() => actions.openItem(item)}+ menu={+ <LibraryActionsMenu+ target={{ kind: "item", item }}+ variant="overlay"+ className={thumb ? GLASS_CONTROL : undefined}+ />+ }+ glass={thumb}+ className={thumb ? cn("bg-muted", CARD_SHADOW) : CARD_SURFACE}+ >+ {thumb ? (+ <ImageThumb item={item} />+ ) : (+ <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">+ {item.name}+ </p>+ <div className="flex flex-1 items-center justify-center">+ <KindIcon item={item} className="size-9" />+ </div>+ <p className="truncate pr-6 text-ui-13 text-muted-foreground">+ {formatCardTime(item.updatedAt, locale)}+ </p>+ </div>+ )}+ </CardFrame>+ );+}++function FolderCard({+ folder,+ itemCount,+}: {+ folder: LibraryFolder;+ itemCount: number;+}) {+ const t = useT();+ const actions = useLibraryActions();+ return (+ <div>+ <CardFrame+ selectKey={`folder:${folder.id}`}+ label={folder.name}+ onOpen={() => actions.openFolder(folder.id)}+ menu={<LibraryActionsMenu target={{ kind: "folder", folder }} variant="overlay" />}+ className={CARD_SURFACE}+ >+ <div className="flex aspect-square items-center justify-center">+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.5} className="size-9" />+ </div>+ </CardFrame>+ <button+ type="button"+ onClick={() => actions.openFolder(folder.id)}+ className="mt-2 block w-full px-1 text-left"+ >+ <p className="truncate font-medium text-ui-14 text-foreground">{folder.name}</p>+ <p className="text-ui-13 text-muted-foreground">{formatItemCount(itemCount, t)}</p>+ </button>+ </div>+ );+}++export function Masonry<T>({+ items,+ getKey,+ render,+}: {+ items: T[];+ getKey: (item: T) => string;+ render: (item: T) => ReactNode;+}) {+ const container = useRef<HTMLDivElement>(null);+ const columns = useColumnCount(container);+ const buckets: T[][] = Array.from({ length: columns }, () => []);+ items.forEach((item, index) => buckets[index % columns]!.push(item));+ return (+ <div ref={container} className="flex items-start gap-5">+ {buckets.map((bucket, column) => (+ <div key={column} className="flex min-w-0 flex-1 flex-col gap-5">+ {bucket.map((item) => (+ <div key={getKey(item)}>{render(item)}</div>+ ))}+ </div>+ ))}+ </div>+ );+}++export function FolderGrid({+ folders,+ counts,+}: {+ folders: LibraryFolder[];+ counts: Map<string, number>;+}) {+ const container = useRef<HTMLDivElement>(null);+ const columns = useColumnCount(container);+ return (+ <div+ ref={container}+ className="grid gap-5"+ style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}+ >+ {folders.map((folder) => (+ <FolderCard key={folder.id} folder={folder} itemCount={counts.get(folder.id) ?? 0} />+ ))}+ </div>+ );+}++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">+ <ImageThumb item={item} />+ </div>+ );+ }+ return (+ <div className="flex size-9 shrink-0 items-center justify-center rounded-xl border border-border/60">+ <KindIcon item={item} className="size-5" />+ </div>+ );+}diff --git a/studio/frontend/src/features/library/components/library-dialogs.tsx b/studio/frontend/src/features/library/components/library-dialogs.tsxnew file mode 100644index 00000000000..29126282273--- /dev/null+++ b/studio/frontend/src/features/library/components/library-dialogs.tsx@@ -0,0 +1,181 @@+// 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 {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { useT } from "@/i18n";+import { useEffect, useRef, useState } from "react";++interface NameDialogProps {+ open: boolean;+ title: string;+ submitLabel: string;+ initialValue: string;+ onSubmit: (name: string) => Promise<void>;+ onOpenChange: (open: boolean) => void;+}++export function NameDialog({ open, title, onOpenChange, ...form }: NameDialogProps) {+ const [busy, setBusy] = useState(false);+ return (+ <Dialog open={open} onOpenChange={(next) => !busy && onOpenChange(next)}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{title}</DialogTitle>+ </DialogHeader>+ {/* Content unmounts on close, so every open starts from initialValue. */}+ <NameForm {...form} busy={busy} setBusy={setBusy} onClose={() => onOpenChange(false)} />+ </DialogContent>+ </Dialog>+ );+}++function NameForm({+ submitLabel,+ initialValue,+ onSubmit,+ busy,+ setBusy,+ onClose,+}: Pick<NameDialogProps, "submitLabel" | "initialValue" | "onSubmit"> & {+ busy: boolean;+ setBusy: (busy: boolean) => void;+ onClose: () => void;+}) {+ const t = useT();+ const [value, setValue] = useState(initialValue);+ const input = useRef<HTMLInputElement>(null);++ useEffect(() => {+ const dot = initialValue.lastIndexOf(".");+ const frame = requestAnimationFrame(() =>+ input.current?.setSelectionRange(0, dot > 0 ? dot : initialValue.length),+ );+ return () => cancelAnimationFrame(frame);+ }, [initialValue]);++ const trimmed = value.trim();+ async function submit() {+ if (!trimmed || busy) return;+ setBusy(true);+ try {+ await onSubmit(trimmed);+ onClose();+ } catch {+ // The caller toasted; keep the dialog open so the name can be fixed.+ } finally {+ setBusy(false);+ }+ }++ return (+ <form+ onSubmit={(event) => {+ event.preventDefault();+ void submit();+ }}+ >+ <Input+ ref={input}+ autoFocus+ value={value}+ maxLength={255}+ onChange={(event) => setValue(event.target.value)}+ aria-label={t("library.list.name")}+ />+ <DialogFooter className="mt-5">+ <Button type="button" variant="ghost" onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <Button type="submit" disabled={!trimmed || busy}>+ {submitLabel}+ </Button>+ </DialogFooter>+ </form>+ );+}++export function ConfirmDeleteDialog({+ open,+ title,+ description,+ confirmLabel,+ onConfirm,+ onOpenChange,+}: {+ open: boolean;+ title: string;+ description: string;+ confirmLabel: string;+ onConfirm: () => void;+ onOpenChange: (open: boolean) => void;+}) {+ const t = useT();+ return (+ <AlertDialog open={open} onOpenChange={onOpenChange}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{title}</AlertDialogTitle>+ <AlertDialogDescription>{description}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>+ <AlertDialogAction variant="destructive" onClick={onConfirm}>+ {confirmLabel}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}++export function UnsavedChangesDialog({+ error,+ onRetry,+ onDiscard,+ onKeepEditing,+}: {+ error: string | null;+ onRetry: () => void;+ onDiscard: () => void;+ onKeepEditing: () => void;+}) {+ const t = useT();+ const reason = error && !/[.!?。!?؟।]$/.test(error) ? `${error}.` : error;+ return (+ <AlertDialog open={error !== null} onOpenChange={(open) => !open && onKeepEditing()}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("library.dialog.unsavedTitle")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t("library.dialog.unsavedDescription", { reason })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t("library.dialog.keepEditing")}</AlertDialogCancel>+ <AlertDialogAction variant="destructive" onClick={onDiscard}>+ {t("library.dialog.discardChanges")}+ </AlertDialogAction>+ <AlertDialogAction onClick={onRetry}>{t("library.empty.tryAgain")}</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/studio/frontend/src/features/library/components/library-header.tsx b/studio/frontend/src/features/library/components/library-header.tsxnew file mode 100644index 00000000000..72d9dce2996--- /dev/null+++ b/studio/frontend/src/features/library/components/library-header.tsx@@ -0,0 +1,232 @@+// 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 { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import {+ type MouseEvent as ReactMouseEvent,+ type PointerEvent as ReactPointerEvent,+ type ReactNode,+ useEffect,+ useRef,+ useState,+} from "react";+import { RAISED_SURFACE } from "../surface";++const GAP_PX = 16;+const FADE_PX = 48;+const DRAG_SLOP_PX = 4;++export interface HeaderTab {+ key: string;+ label: string;+}++function fadeMask(left: boolean, right: boolean): string | undefined {+ if (!left && !right) return undefined;+ const start = left ? `transparent 0, black ${FADE_PX}px` : "black 0";+ const end = right ? `black calc(100% - ${FADE_PX}px), transparent 100%` : "black 100%";+ return `linear-gradient(to right, ${start}, ${end})`;+}++function TabStrip({+ tabs,+ active,+ onChange,+ reserve,+}: {+ tabs: HeaderTab[];+ active: string;+ onChange: (key: string) => void;+ reserve: number;+}) {+ const t = useT();+ const scrollerRef = useRef<HTMLDivElement>(null);+ const listRef = useRef<HTMLDivElement>(null);+ const [edges, setEdges] = useState({ left: false, right: false });+ const drag = useRef<{ id: number; x: number; left: number; moved: boolean } | null>(null);+ const dragged = useRef(false);++ useEffect(() => {+ const scroller = scrollerRef.current;+ const list = listRef.current;+ if (!scroller || !list) return;+ const measure = () =>+ setEdges({+ left: scroller.scrollLeft > 1,+ right: scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth - 1,+ });+ const observer = new ResizeObserver(measure);+ observer.observe(scroller);+ observer.observe(list);+ scroller.addEventListener("scroll", measure, { passive: true });+ return () => {+ observer.disconnect();+ scroller.removeEventListener("scroll", measure);+ };+ }, []);++ useEffect(() => {+ const scroller = scrollerRef.current;+ const tab = scroller?.querySelector<HTMLElement>('[aria-current="page"]');+ if (!scroller || !tab) return;+ const left = tab.offsetLeft - scroller.offsetLeft;+ const right = left + tab.offsetWidth;+ if (left < scroller.scrollLeft) scroller.scrollLeft = left - FADE_PX;+ else if (right > scroller.scrollLeft + scroller.clientWidth) {+ scroller.scrollLeft = right - scroller.clientWidth + FADE_PX;+ }+ }, [active, reserve]);++ function onPointerDown(event: ReactPointerEvent<HTMLDivElement>) {+ dragged.current = false;+ if (event.pointerType !== "mouse" || event.button !== 0 || !(edges.left || edges.right)) {+ return;+ }+ drag.current = {+ id: event.pointerId,+ x: event.clientX,+ left: event.currentTarget.scrollLeft,+ moved: false,+ };+ }++ function onPointerMove(event: ReactPointerEvent<HTMLDivElement>) {+ const current = drag.current;+ if (!current || current.id !== event.pointerId) return;+ // Released off the strip before a drag captured the pointer: the strip never saw the release,+ // and a hover must not scroll it.+ if ((event.buttons & 1) === 0) {+ drag.current = null;+ return;+ }+ const dx = event.clientX - current.x;+ if (!current.moved) {+ if (Math.abs(dx) < DRAG_SLOP_PX) return;+ current.moved = true;+ event.currentTarget.setPointerCapture(event.pointerId);+ }+ event.currentTarget.scrollLeft = current.left - dx;+ }++ function onPointerEnd(event: ReactPointerEvent<HTMLDivElement>) {+ if (drag.current?.id !== event.pointerId) return;+ dragged.current = drag.current.moved;+ drag.current = null;+ }++ // The click that ends a drag must not also switch tab.+ function onClickCapture(event: ReactMouseEvent) {+ if (!dragged.current) return;+ dragged.current = false;+ event.preventDefault();+ event.stopPropagation();+ }++ const mask = fadeMask(edges.left, edges.right);+ return (+ <div+ ref={scrollerRef}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerEnd}+ onPointerCancel={onPointerEnd}+ onLostPointerCapture={onPointerEnd}+ onClickCapture={onClickCapture}+ // Important: index.css's unlayered `* { scrollbar-width: thin }` outranks any utility.+ className="-mx-2 -mb-3 -mt-1 overflow-x-auto px-2 pb-3 pt-1 [scrollbar-width:none]! [&::-webkit-scrollbar]:hidden!"+ style={{ marginRight: reserve || undefined, maskImage: mask, WebkitMaskImage: mask }}+ >+ <nav ref={listRef} className="flex w-max gap-1" aria-label={t("library.tabs.ariaLabel")}>+ {tabs.map((tab) => (+ <button+ key={tab.key}+ type="button"+ aria-current={tab.key === active ? "page" : undefined}+ onClick={() => onChange(tab.key)}+ className={cn(+ "flex h-9 shrink-0 items-center rounded-full px-3.5 text-ui-15 text-foreground/80 transition-colors hover:text-foreground",+ tab.key === active && cn(RAISED_SURFACE, "font-medium text-foreground"),+ )}+ >+ {tab.label}+ </button>+ ))}+ </nav>+ </div>+ );+}++export function LibraryHeader({+ title,+ controls,+ tabs,+}: {+ title: ReactNode;+ controls: ReactNode;+ tabs: { items: HeaderTab[]; active: string; onChange: (key: string) => void } | null;+}) {+ const controlsRef = useRef<HTMLDivElement>(null);+ const rowRef = useRef<HTMLDivElement>(null);+ const [controlsWidth, setControlsWidth] = useState(0);+ const [covered, setCovered] = useState(false);++ useEffect(() => {+ const controlsNode = controlsRef.current;+ const row = rowRef.current;+ if (!controlsNode || !row) return;+ let frame = 0;+ const update = () => {+ frame = 0;+ setControlsWidth(controlsNode.getBoundingClientRect().width);+ setCovered(row.getBoundingClientRect().top < controlsNode.getBoundingClientRect().bottom);+ };+ const schedule = () => {+ if (!frame) frame = requestAnimationFrame(update);+ };+ const observer = new ResizeObserver(schedule);+ observer.observe(controlsNode);+ document.addEventListener("scroll", schedule, { capture: true, passive: true });+ window.addEventListener("resize", schedule);+ schedule();+ return () => {+ cancelAnimationFrame(frame);+ observer.disconnect();+ document.removeEventListener("scroll", schedule, { capture: true });+ window.removeEventListener("resize", schedule);+ };+ }, []);++ return (+ <>+ {/* No height of its own: the controls hang from it over the title row, then stick level with+ the tabs, whose row is as tall as they are plus its padding. */}+ <div className="pointer-events-none sticky top-4 z-30 flex h-0 justify-end">+ <div ref={controlsRef} className="pointer-events-auto">+ {controls}+ </div>+ </div>+ <div+ className="flex h-9 min-w-0 items-center"+ style={{ paddingRight: controlsWidth + GAP_PX }}+ >+ {title}+ </div>+ <div+ ref={rowRef}+ 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="h-9" />+ )}+ </div>+ </>+ );+}diff --git a/studio/frontend/src/features/library/components/library-list.tsx b/studio/frontend/src/features/library/components/library-list.tsxnew file mode 100644index 00000000000..c6e88924be9--- /dev/null+++ b/studio/frontend/src/features/library/components/library-list.tsx@@ -0,0 +1,223 @@+// 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 { Checkbox } from "@/components/ui/checkbox";+import { useLocale, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { Folder01Icon } from "@hugeicons/core-free-icons";+import { StarPointedIcon } from "@/lib/hugeicons-derived";+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 { type LibraryTarget, useLibraryActions } from "../actions-context";+import { LibraryActionsMenu } from "./library-actions";+import { ItemTile } from "./library-cards";++function targetKey(target: LibraryTarget): string {+ return target.kind === "item" ? `item:${target.item.id}` : `folder:${target.folder.id}`;+}++const ROW_INSET = "pl-4 pr-3";++function GutterCheckbox({+ checked,+ visible,+ group,+ onCheckedChange,+ label,+}: {+ checked: boolean;+ visible: boolean;+ group: "row" | "head";+ onCheckedChange: () => void;+ label: string;+}) {+ return (+ <div className="absolute right-full top-1/2 mr-3 flex -translate-y-1/2">+ <Checkbox+ checked={checked}+ onCheckedChange={onCheckedChange}+ aria-label={label}+ className={cn(+ "rounded-full border-neutral-300 opacity-0 transition-opacity focus-visible:opacity-100 dark:border-input",+ group === "row"+ ? "group-hover/library-row:opacity-100"+ : "group-hover/library-head:opacity-100",+ visible && "opacity-100",+ )}+ />+ </div>+ );+}++function Row({+ target,+ selected,+ selecting,+ onSelectedChange,+ onOpen,+ tile,+ name,+ activity,+}: {+ target: LibraryTarget;+ selected: boolean;+ selecting: boolean;+ onSelectedChange: (selected: boolean) => void;+ onOpen: () => void;+ tile: ReactNode;+ name: ReactNode;+ activity: string;+}) {+ const t = useT();+ 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",+ ROW_INSET,+ selected && "bg-muted dark:bg-muted/60",+ )}+ >+ <GutterCheckbox+ checked={selected}+ visible={selecting}+ group="row"+ onCheckedChange={() => onSelectedChange(!selected)}+ label={t("library.selectItem", {+ name: target.kind === "item" ? target.item.name : target.folder.name,+ })}+ />+ <button+ type="button"+ onClick={onOpen}+ className="flex min-w-0 flex-1 items-center gap-4 rounded-lg py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {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>+ </button>+ <LibraryActionsMenu target={target} variant="row" />+ </div>+ );+}++export function LibraryList({+ folders,+ items,+ counts,+ selection,+ onSelectionChange,+}: {+ folders: LibraryFolder[];+ items: LibraryItem[];+ counts: Map<string, number>;+ selection: Set<string>;+ onSelectionChange: (next: Set<string>) => void;+}) {+ 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 })),+ ];+ const allSelected = targets.length > 0 && targets.every((t) => selection.has(targetKey(t)));+ const selecting = selection.size > 0;++ const setSelected = (target: LibraryTarget, selected: boolean) => {+ const next = new Set(selection);+ if (selected) next.add(targetKey(target));+ else next.delete(targetKey(target));+ onSelectionChange(next);+ };++ 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={cn(+ "group/library-head relative flex items-center gap-4 text-ui-13 text-muted-foreground",+ ROW_INSET,+ )}+ >+ {/* Ticked only once everything is: a partial tick read as every row being selected. */}+ <GutterCheckbox+ checked={allSelected}+ visible={selecting}+ group="head"+ onCheckedChange={() =>+ onSelectionChange(allSelected ? new Set() : new Set(targets.map(targetKey)))+ }+ 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="w-8 shrink-0" />+ </div>+ </div>+ <div className="mt-1 flex flex-col">+ {folders.map((folder) => (+ <Row+ key={folder.id}+ target={{ kind: "folder", folder }}+ selected={selection.has(`folder:${folder.id}`)}+ selecting={selecting}+ 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">+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.5} className="size-5" />+ </div>+ }+ name={+ <>+ <span className="truncate">{folder.name}</span>+ <span className="shrink-0 text-muted-foreground text-sm">+ {formatItemCount(counts.get(folder.id) ?? 0, t)}+ </span>+ </>+ }+ activity={modified(folder.updatedAt)}+ />+ ))}+ {items.map((item) => (+ <Row+ key={item.id}+ target={{ kind: "item", item }}+ selected={selection.has(`item:${item.id}`)}+ selecting={selecting}+ onSelectedChange={(selected) => setSelected({ kind: "item", item }, selected)}+ onOpen={() => actions.openItem(item)}+ tile={<ItemTile item={item} />}+ name={+ <>+ <span className="truncate">{item.name}</span>+ {item.model && (+ <span className="shrink-0 text-muted-foreground text-sm">+ {t(modelLabelKey(item)!)}+ </span>+ )}+ {item.favorite && (+ <HugeiconsIcon+ icon={StarPointedIcon}+ aria-label={t("library.list.favorite")}+ strokeWidth={1.75}+ className="size-3.5 shrink-0 text-muted-foreground [&_path]:fill-current"+ />+ )}+ </>+ }+ activity={modified(item.updatedAt)}+ />+ ))}+ </div>+ </div>+ );+}diff --git a/studio/frontend/src/features/library/components/library-preview.tsx b/studio/frontend/src/features/library/components/library-preview.tsxnew file mode 100644index 00000000000..f18e20e2dd7--- /dev/null+++ b/studio/frontend/src/features/library/components/library-preview.tsx@@ -0,0 +1,598 @@+// 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 { CodeToggleIcon } from "@/components/assistant-ui/code-toggle-icon";+import { CodeSourceView } from "@/components/code-source-view";+import { Button } from "@/components/ui/button";+import { MediaViewer, ScaleMenu } from "@/components/media-viewer";+import { Spinner } from "@/components/ui/spinner";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { ArtifactHtmlFrame } from "@/features/chat";+import { type TranslationKey, useLocale, useT } from "@/i18n";+import { isTauri } from "@/lib/api-base";+import { MessageCircleIcon } from "@/lib/hugeicons-derived";+import { toast } from "@/lib/toast";+import { useBlocker, useNavigate } from "@tanstack/react-router";+import { cn } from "@/lib/utils";+import { PlayIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { type ReactNode, useEffect, useRef, useState } from "react";+import {+ type LibraryItem,+ addLibraryItemToProject,+ errorMessage,+ fetchLibraryText,+ writeLibraryText,+} from "../api";+import {+ fileKind,+ hasImagePreview,+ isFileItem,+ isTextPreviewable,+ modelLabelKey,+} from "../file-kind";+import { formatCardTime, formatSize } from "../format";+import { type EmbeddedBody, hasOwnFile, itemVersion } from "../file-name";+import { useLibraryPreviewUrl } from "../hooks";+import { type NoteFormat, type NoteReadOnlyReason, encodeNote } from "../note-text";+import { canReveal, revealInFolder, useRevealLabel } from "../reveal";+import { KindIcon } from "./library-cards";+import { UnsavedChangesDialog } from "./library-dialogs";++const PAGE_SCALES = [0.5, 0.75, 1, 1.25, 1.5, 2];++const MAX_TEXT_PREVIEW_BYTES = 1024 * 1024;++type Body = "image" | "web" | "text" | "pdf" | "audio" | "video" | "model" | "none";++function bodyFor(item: LibraryItem): Body {+ if (item.model) return "model";+ if (hasImagePreview(item)) return "image";+ if (item.textOnly) return "text";+ const kind = fileKind(item);+ if (kind === "web") return "web";+ if (kind === "pdf") return isTauri || navigator.pdfViewerEnabled === false ? "none" : "pdf";+ if (kind === "audio" || kind === "video") return kind;+ return isTextPreviewable(item) ? "text" : "none";+}++function generatedOn(item: LibraryItem) {+ if (item.archived) return null;+ const [kind, ...rest] = item.id.split(":");+ const search = { item: rest.join(":") };+ if (kind === "image") return { label: "library.preview.viewInImages", to: "/images", search } as const;+ if (kind === "video") return { label: "library.preview.viewInVideo", to: "/video", search } as const;+ const speak = { ...search, task: "text-to-speech" } as const;+ if (kind === "audio") return { label: "library.preview.viewInAudio", to: "/audio", search: speak } as const;+ return null;+}++function isEditable(item: LibraryItem): boolean {+ return item.id.startsWith("upload:") && bodyFor(item) === "text";+}++interface LoadedText {+ key: string;+ itemId: string;+ text?: string;+ truncated?: boolean;+ format?: NoteFormat;+ readOnlyReason?: NoteReadOnlyReason | null;+ error?: string;+}++/**+ * The item's text, or null while it first loads. A newer version of the same item keeps showing+ * the last one until it arrives (`loadedKey` says which is on screen), so an editor is never+ * swapped for a spinner, and never loses focus, when its own save bumps the version.+ */+function useItemText(item: LibraryItem | null, enabled: boolean) {+ const key = item ? itemVersion(item) : "";+ const [state, setState] = useState<LoadedText | null>(null);+ if (!item && state) setState(null);+ useEffect(() => {+ if (!enabled || !item) return;+ let cancelled = false;+ const itemId = item.id;+ fetchLibraryText(item, MAX_TEXT_PREVIEW_BYTES).then(+ ({ text, truncated, format, readOnlyReason }) =>+ !cancelled && setState({ key, itemId, text, truncated, format, readOnlyReason }),+ (err: unknown) => !cancelled && setState({ key, itemId, error: errorMessage(err) }),+ );+ return () => {+ cancelled = true;+ };+ // `key` carries the item's identity and version; the object itself changes on every refresh.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key, enabled]);+ const current = item && state?.itemId === item.id ? state : null;+ return {+ text: current?.text ?? null,+ truncated: current?.truncated ?? false,+ format: current?.format ?? null,+ readOnlyReason: current?.readOnlyReason ?? null,+ error: current?.error ?? null,+ loadedKey: current?.key ?? null,+ };+}++type ItemText = ReturnType<typeof useItemText>;++const READ_ONLY_REASONS: Record<NoteReadOnlyReason, TranslationKey> = {+ utf16: "library.preview.readOnlyUtf16",+ notUtf8: "library.preview.readOnlyNotUtf8",+};++function ModelDetails({ item }: { item: LibraryItem }) {+ const t = useT();+ const locale = useLocale();+ const unknown = t("library.preview.unknown");+ const rows: [string, string][] = [+ [t("library.preview.type"), t(modelLabelKey(item) ?? "library.modelKind.model")],+ [t("library.preview.baseModel"), item.model?.baseModel ?? unknown],+ [t("library.preview.size"), formatSize(item.sizeBytes, locale, t) || unknown],+ [t("library.preview.location"), item.model?.path ?? ""],+ ];+ return (+ <div className="m-auto flex w-full max-w-xl flex-col items-center gap-8">+ <KindIcon item={item} className="size-16" />+ <dl className="grid w-full grid-cols-[auto_1fr] gap-x-8 gap-y-3 text-sm">+ {rows.map(([label, value]) => (+ <div key={label} className="contents">+ <dt className="text-muted-foreground">{label}</dt>+ <dd className="select-text break-all text-foreground">{value}</dd>+ </div>+ ))}+ </dl>+ </div>+ );+}++function TextPrefix({ text, className }: { text: string; className?: string }) {+ return (+ <pre+ className={cn(+ "size-full overflow-auto whitespace-pre-wrap break-words font-mono text-sm leading-relaxed",+ className,+ )}+ >+ {text}+ </pre>+ );+}++/** What shows when a file cannot be previewed here, by type or because it failed to load. */+function NoPreview({+ item,+ message,+ onDownload,+}: {+ item: LibraryItem;+ message: string;+ onDownload?: () => void;+}) {+ const t = useT();+ return (+ <div className="m-auto flex max-w-md flex-col items-center gap-3 text-center text-muted-foreground">+ <KindIcon item={item} className="size-16" />+ <p className="text-sm">{message}</p>+ {onDownload && (+ <Button variant="muted" size="sm" className="rounded-full px-4" onClick={onDownload}>+ {t("library.menu.download")}+ </Button>+ )}+ </div>+ );+}++function ViewButton({+ label,+ active,+ onClick,+ children,+}: {+ label: string;+ active: boolean;+ onClick: () => void;+ children: ReactNode;+}) {+ return (+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ aria-label={label}+ aria-pressed={active}+ onClick={onClick}+ className={cn(+ "flex size-9 shrink-0 items-center justify-center rounded-full outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring",+ active && "bg-muted",+ )}+ >+ {children}+ </button>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ );+}++function PreviewBody({+ item,+ itemText,+ draft,+ onDraftChange,+ showCode,+ pageScale,+ mediaFailed,+ onMediaError,+ onDownload,+}: {+ item: LibraryItem;+ itemText: ItemText;+ draft: string | null;+ onDraftChange: (value: string) => void;+ showCode: boolean;+ pageScale: number;+ mediaFailed: boolean;+ onMediaError: () => void;+ onDownload?: () => void;+}) {+ const t = useT();+ const body = bodyFor(item);+ const embedded: EmbeddedBody | null =+ !mediaFailed && (body === "image" || body === "pdf" || body === "audio" || body === "video")+ ? body+ : null;+ const { url, error: urlError, retry } = useLibraryPreviewUrl(item, embedded);+ const handleMediaError = () => {+ if (!retry()) onMediaError();+ };+ const { text, truncated, readOnlyReason, error: textError } = itemText;+ const noPreview = (message: string) => (+ <NoPreview item={item} message={message} onDownload={onDownload} />+ );++ if (mediaFailed) return noPreview(t("library.preview.cannotPreview"));+ if (urlError) return noPreview(urlError);+ if (textError) return <p className="m-auto text-sm text-muted-foreground">{textError}</p>;+ if ((embedded && !url) || ((body === "text" || body === "web") && text === null)) {+ return <Spinner className="m-auto size-6" />;+ }+ const prefix = truncated ? `${text}\n\n…` : text!;+ switch (body) {+ case "model":+ return <ModelDetails item={item} />;+ case "image":+ return (+ <img src={url!} alt={item.name} onError={handleMediaError} className="size-full object-contain" />+ );+ case "pdf":+ return <iframe title={item.name} src={url!} className="size-full rounded-xl bg-white" />;+ case "audio":+ return (+ <audio src={url!} controls onError={handleMediaError} className="m-auto w-full max-w-lg" />+ );+ case "video":+ return (+ <video+ src={url!}+ controls+ autoPlay+ onError={handleMediaError}+ className="size-full object-contain"+ />+ );+ case "web":+ if (showCode) {+ return (+ <CodeSourceView+ code={truncated ? `${text!}\n…` : text!}+ language="html"+ className="rounded-xl"+ />+ );+ }+ if (truncated) return <TextPrefix text={prefix} />;+ return (+ <div className="size-full overflow-hidden rounded-xl">+ <div+ className="origin-top-left"+ style={{+ width: `${100 / pageScale}%`,+ height: `${100 / pageScale}%`,+ transform: `scale(${pageScale})`,+ }}+ >+ <ArtifactHtmlFrame code={text!} title={item.name} fill />+ </div>+ </div>+ );+ case "text":+ if (isEditable(item) && !truncated && !readOnlyReason) {+ return (+ <textarea+ value={draft ?? text!}+ onChange={(event) => onDraftChange(event.target.value)}+ spellCheck={false}+ placeholder={t("library.preview.startWriting")}+ className="size-full resize-none bg-transparent font-mono text-sm leading-relaxed outline-none"+ />+ );+ }+ // A note the editor would write back wrongly says why it cannot be edited.+ return isEditable(item) && readOnlyReason ? (+ <div className="flex size-full min-h-0 flex-col gap-3">+ <p className="text-ui-13 text-muted-foreground">+ {t(READ_ONLY_REASONS[readOnlyReason])}+ </p>+ <TextPrefix text={prefix} className="min-h-0 flex-1" />+ </div>+ ) : (+ <TextPrefix text={prefix} />+ );+ default:+ return noPreview(t("library.preview.noPreview"));+ }+}++export function LibraryPreview({+ item,+ onOpenChange,+ onChat,+ onDownload,+ onOpenThread,+ onToggleFavorite,+ onDelete,+ onSaved,+}: {+ item: LibraryItem | null;+ onOpenChange: (open: boolean) => void;+ onChat: (item: LibraryItem) => void;+ onDownload: (item: LibraryItem) => void;+ onOpenThread: (threadId: string) => void;+ onToggleFavorite: (item: LibraryItem) => void;+ onDelete: (item: LibraryItem) => void;+ onSaved: () => void;+}) {+ const t = useT();+ const locale = useLocale();+ const body = item ? bodyFor(item) : "none";+ const itemText = useItemText(item, body === "text" || body === "web");+ const version = item && itemVersion(item);+ // Tagged with its item, so a draft never follows the preview to another file.+ // `savedAt` marks text already written: the item version it was saved over, shown until the+ // refreshed item's text has loaded, so the editor never falls back to the old text.+ const [edit, setEdit] = useState<{ itemId: string; text: string; savedAt?: number } | null>(+ null,+ );+ // The same draft, readable after an await: a save must not return while typing moved past it.+ const latestEdit = useRef(edit);+ const lastSaved = useRef<{ itemId: string; text: string } | null>(null);+ const current = item && edit?.itemId === item.id ? edit : null;+ if (+ current?.savedAt !== undefined &&+ item!.updatedAt !== current.savedAt &&+ itemText.loadedKey === version+ ) {+ setEdit(null);+ }+ const draft = current ? current.text : null;+ const unsaved = current !== null && current.savedAt === undefined;+ const setDraft = (text: string | null) => {+ const next = item && text !== null ? { itemId: item.id, text } : null;+ latestEdit.current = next;+ setEdit(next);+ };+ const [saving, setSaving] = useState(false);+ const [closeError, setCloseError] = useState<string | null>(null);+ const [brokenMedia, setBrokenMedia] = useState<string | null>(null);+ const mediaFailed = version !== null && brokenMedia === version;+ const [codeFor, setCodeFor] = useState<string | null>(null);+ const [zoom, setZoom] = useState<{ itemId: string; scale: number } | null>(null);+ if (item === null && (codeFor !== null || zoom !== null)) {+ setCodeFor(null);+ setZoom(null);+ }+ const showCode = item !== null && codeFor === item.id;+ const pageScale = item !== null && zoom?.itemId === item.id ? zoom.scale : 1;+ const revealLabel = useRevealLabel();+ const navigate = useNavigate();+ const origin = item ? generatedOn(item) : null;++ async function trySave(): Promise<string | null> {+ if (!item || draft === null || !unsaved) return null;+ const format = itemText.format ?? { encoding: "utf-8", bom: false, eol: "\n" };+ setSaving(true);+ try {+ let sent = draft;+ for (;;) {+ await writeLibraryText(item.id, encodeNote(sent, format), format.encoding);+ const latest = latestEdit.current;+ if (latest?.itemId !== item.id || latest.text === sent) break;+ sent = latest.text;+ }+ const savedAt = item.updatedAt;+ lastSaved.current = { itemId: item.id, text: sent };+ setEdit((latest) =>+ latest?.itemId === item.id && latest.text === sent ? { ...latest, savedAt } : latest,+ );+ onSaved();+ return null;+ } catch (error) {+ return errorMessage(error);+ } finally {+ setSaving(false);+ }+ }++ async function save(): Promise<boolean> {+ const error = await trySave();+ if (error !== null) toast.error(t("library.toast.saveFailed"), { description: error });+ return error === null;+ }++ async function saveThen(action: () => void) {+ if (await save()) action();+ }++ // Closing a note saves it, so an edit is never lost to a stray Escape. A save that fails asks+ // what to do instead, so the preview can always be closed.+ async function handleOpenChange(open: boolean) {+ if (!open) {+ const error = await trySave();+ if (error !== null) {+ setCloseError(error);+ return;+ }+ }+ onOpenChange(open);+ }++ // Back, or any link, closes the preview without handleOpenChange: save first, as closing does.+ // Refs, not `unsaved`: a discard or a save just made has not rendered yet when it navigates.+ useBlocker({+ shouldBlockFn: async () => {+ const latest = latestEdit.current;+ const saved = lastSaved.current;+ if (!latest || (saved?.itemId === latest.itemId && saved.text === latest.text)) return false;+ return !(await save());+ },+ enableBeforeUnload: () => unsaved,+ });++ function discardAndClose() {+ setCloseError(null);+ setDraft(null);+ onOpenChange(false);+ }++ const meta = item+ ? [+ t(+ modelLabelKey(item) ??+ (item.source === "generated" ? "library.toolbar.generated" : "library.toolbar.uploaded"),+ ),+ formatSize(item.sizeBytes, locale, t),+ formatCardTime(item.updatedAt, locale),+ ].filter(Boolean)+ : [];+ const download = item && isFileItem(item) ? () => void saveThen(() => onDownload(item)) : undefined;+ const media = (body === "image" || body === "video") && !mediaFailed;++ return (+ <MediaViewer+ open={item !== null}+ onOpenChange={(open) => void handleOpenChange(open)}+ title={item?.name ?? ""}+ meta={meta.join(" · ")}+ media={media}+ noun={media ? body : "file"}+ onKeyDown={(event) => {+ const saveKey = event.code === "KeyS" || event.key.toLowerCase() === "s";+ if ((event.metaKey || event.ctrlKey) && saveKey) {+ event.preventDefault();+ void save();+ }+ }}+ extra={+ <>+ {body === "web" && item && !showCode && (+ <ScaleMenu+ value={pageScale}+ scales={PAGE_SCALES}+ onChange={(value) => setZoom({ itemId: item.id, scale: Number(value) })}+ />+ )}+ {body === "web" && item && (+ <div className="mr-1 flex items-center gap-1">+ <ViewButton+ label={t("library.preview.code")}+ active={showCode}+ onClick={() => setCodeFor(item.id)}+ >+ <CodeToggleIcon className="size-4.5" />+ </ViewButton>+ <ViewButton+ label={t("library.preview.preview")}+ active={!showCode}+ onClick={() => setCodeFor(null)}+ >+ <HugeiconsIcon icon={PlayIcon} strokeWidth={1.75} className="size-5" />+ </ViewButton>+ </div>+ )}+ {unsaved && (+ <Button variant="dark" size="sm" className="mr-1" disabled={saving} onClick={() => void save()}>+ {t("common.save")}+ </Button>+ )}+ </>+ }+ actions={+ item+ ? {+ primary: {+ label: t(item.model ? "library.menu.chatWithModel" : "library.menu.chatAboutThis"),+ icon: MessageCircleIcon,+ disabled: saving,+ onClick: () => void saveThen(() => onChat(item)),+ },+ onDownload: download,+ viewOriginal: item.threadId+ ? {+ label: t("library.preview.viewOriginalChat"),+ onClick: () => void saveThen(() => onOpenThread(item.threadId!)),+ }+ : origin+ ? {+ label: t(origin.label),+ onClick: () => void navigate({ to: origin.to, search: origin.search }),+ }+ : undefined,+ reveal:+ revealLabel && canReveal(item)+ ? {+ label: revealLabel,+ onClick: () => void saveThen(() => revealInFolder(item.id)),+ }+ : undefined,+ favorite: item.favorite,+ onToggleFavorite: () => onToggleFavorite(item),+ onAddToProject: hasOwnFile(item.id)+ ? async (projectId) => {+ if (!(await save())) throw new Error(t("library.toast.saveNoteFirst"));+ return addLibraryItemToProject(item.id, projectId);+ }+ : undefined,+ onDelete: isFileItem(item) ? () => onDelete(item) : undefined,+ }+ : {}+ }+ >+ {item && (+ <PreviewBody+ item={item}+ itemText={itemText}+ draft={draft}+ onDraftChange={setDraft}+ showCode={showCode}+ pageScale={pageScale}+ mediaFailed={mediaFailed}+ onMediaError={() => setBrokenMedia(version)}+ onDownload={download}+ />+ )}+ {/* Portalled, so it sits over the preview whatever the body is. */}+ <UnsavedChangesDialog+ error={closeError}+ onRetry={() => {+ setCloseError(null);+ void handleOpenChange(false);+ }}+ onDiscard={discardAndClose}+ onKeepEditing={() => setCloseError(null)}+ />+ </MediaViewer>+ );+}diff --git a/studio/frontend/src/features/library/components/library-toolbar.tsx b/studio/frontend/src/features/library/components/library-toolbar.tsxnew file mode 100644index 00000000000..1b1c44aeea8--- /dev/null+++ b/studio/frontend/src/features/library/components/library-toolbar.tsx@@ -0,0 +1,277 @@+// 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 {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import {+ AiEditingIcon,+ AudioWave01Icon,+ File02Icon,+ FilterMailIcon,+ FlimSlateIcon,+ Folder01Icon,+ GridViewIcon,+ Image02Icon,+ LeftToRightListBulletIcon,+ Note01Icon,+ Pdf01Icon,+ Presentation01Icon,+ Search01Icon,+ Settings02Icon,+ Tick02Icon,+ Upload01Icon,+} from "@hugeicons/core-free-icons";+import { type TranslationKey, useT } from "@/i18n";+import { SheetIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";+import { cn } from "@/lib/utils";+import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";+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";++const ICON = "size-icon";+const ROUND_BUTTON =+ "flex size-9 shrink-0 items-center justify-center rounded-full text-foreground outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring data-[active=true]:bg-white data-[active=true]:shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:data-[active=true]:bg-card dark:data-[active=true]:shadow-none data-open:bg-muted";++interface MenuOption<T extends string> {+ value: T;+ label: TranslationKey;+ icon: IconSvgElement;+}++const SOURCE_OPTIONS: MenuOption<LibrarySource>[] = [+ { value: "uploaded", label: "library.toolbar.uploaded", icon: Upload01Icon },+ { value: "generated", label: "library.toolbar.generated", icon: AiEditingIcon },+];++const TYPE_OPTIONS: MenuOption<LibraryTypeFilter>[] = [+ { value: "images", label: "library.tabs.images", icon: Image02Icon },+ { value: "videos", label: "library.tabs.videos", icon: FlimSlateIcon },+ { value: "audio", label: "library.tabs.audio", icon: AudioWave01Icon },+ { value: "documents", label: "library.toolbar.documents", icon: File02Icon },+ { value: "spreadsheets", label: "library.toolbar.spreadsheets", icon: SheetIcon },+ { value: "presentations", label: "library.toolbar.presentations", icon: Presentation01Icon },+ { value: "pdfs", label: "library.toolbar.pdfs", icon: Pdf01Icon },+];++const VIEW_OPTIONS = [+ { value: "grid", label: "library.toolbar.gridView", icon: GridViewIcon },+ { value: "list", label: "library.toolbar.listView", icon: LeftToRightListBulletIcon },+] satisfies MenuOption<LibraryView>[];++function toggled<T>(set: Set<T>, value: T): Set<T> {+ const next = new Set(set);+ if (next.has(value)) next.delete(value);+ else next.add(value);+ return next;+}++function FilterMenu({+ filters,+ onChange,+ showTypes,+}: {+ filters: LibraryFilters;+ onChange: (next: LibraryFilters) => void;+ showTypes: boolean;+}) {+ const t = useT();+ const option = (+ { value, label, icon }: MenuOption<string>,+ checked: boolean,+ toggle: () => void,+ ) => (+ <DropdownMenuItem+ key={value}+ onSelect={(event) => {+ event.preventDefault();+ toggle();+ }}+ >+ <HugeiconsIcon icon={icon} strokeWidth={1.75} className={ICON} />+ <span className="flex-1">{t(label)}</span>+ {checked && <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="size-4" />}+ </DropdownMenuItem>+ );++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={t("library.toolbar.filter")}+ data-active={filtersActive(filters)}+ className={ROUND_BUTTON}+ >+ <HugeiconsIcon icon={FilterMailIcon} strokeWidth={1.75} className="size-5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuLabel className="px-3 pb-1 pt-2 text-muted-foreground font-normal">+ {t("library.toolbar.source")}+ </DropdownMenuLabel>+ {SOURCE_OPTIONS.map((entry) =>+ option(entry, filters.sources.has(entry.value), () =>+ onChange({ ...filters, sources: toggled(filters.sources, entry.value) }),+ ),+ )}+ {showTypes && (+ <>+ <DropdownMenuSeparator className="mx-3" />+ <DropdownMenuLabel className="px-3 pb-1 pt-2 text-muted-foreground font-normal">+ {t("library.toolbar.fileType")}+ </DropdownMenuLabel>+ {TYPE_OPTIONS.map((entry) =>+ option(entry, filters.types.has(entry.value), () =>+ onChange({ ...filters, types: toggled(filters.types, entry.value) }),+ ),+ )}+ </>+ )}+ {filtersActive(filters) && (+ <>+ <DropdownMenuSeparator className="mx-3" />+ <DropdownMenuItem onSelect={() => onChange(EMPTY_FILTERS)}>+ <span className="pl-[calc(26px*var(--ui-space-scale,1))] text-muted-foreground">+ {t("library.toolbar.clearFilters")}+ </span>+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++export type NewAction =+ | "note"+ | "image"+ | "video"+ | "audio"+ | "model"+ | "folder"+ | "upload";++const NEW_OPTIONS: MenuOption<NewAction>[] = [+ { value: "note", label: "library.create.note", icon: Note01Icon },+ { value: "image", label: "library.create.image", icon: Image02Icon },+ { value: "video", label: "library.create.video", icon: FlimSlateIcon },+ { value: "audio", label: "library.create.audio", icon: AudioWave01Icon },+ { value: "model", label: "library.create.model", icon: TestTubeOutlineIcon },+ { value: "folder", label: "library.create.folder", icon: Folder01Icon },+];++function NewMenu({ onSelect }: { onSelect: (action: NewAction) => void }) {+ const t = useT();+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ className="flex h-9 shrink-0 items-center gap-1.5 rounded-full bg-foreground pl-4 pr-3 font-medium text-ui-14 text-background outline-none transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("common.new")}+ <ChevronDownIcon className="size-4" strokeWidth={2} />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-44">+ {NEW_OPTIONS.map(({ value, label, icon }) => (+ <DropdownMenuItem key={value} onSelect={() => onSelect(value)}>+ <HugeiconsIcon icon={icon} strokeWidth={1.75} className={ICON} />+ {t(label)}+ </DropdownMenuItem>+ ))}+ <DropdownMenuSeparator className="mx-3" />+ <DropdownMenuItem onSelect={() => onSelect("upload")}>+ <HugeiconsIcon icon={Upload01Icon} strokeWidth={1.75} className={ICON} />+ {t("library.empty.uploadFiles")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++export function LibraryToolbar({+ filters,+ onFiltersChange,+ filterMode,+ view,+ onViewChange,+ search,+ onSearchChange,+ searchPlaceholder,+ onNew,+ onSettings,+}: {+ filters: LibraryFilters;+ onFiltersChange: (next: LibraryFilters) => void;+ filterMode: "none" | "source" | "all";+ view: LibraryView;+ onViewChange: (view: LibraryView) => void;+ search: string;+ onSearchChange: (value: string) => void;+ searchPlaceholder: string;+ onNew: (action: NewAction) => void;+ onSettings: () => void;+}) {+ const t = useT();+ return (+ <div className="flex min-w-0 items-center gap-2">+ {filterMode !== "none" && (+ <>+ <FilterMenu+ filters={filters}+ onChange={onFiltersChange}+ showTypes={filterMode === "all"}+ />+ <span className="mx-1.5 h-6 w-px shrink-0 bg-border" aria-hidden="true" />+ </>+ )}+ {VIEW_OPTIONS.map(({ value, label, icon }) => (+ <button+ key={value}+ type="button"+ aria-label={t(label)}+ data-active={view === value}+ aria-pressed={view === value}+ onClick={() => onViewChange(value)}+ className={ROUND_BUTTON}+ >+ <HugeiconsIcon icon={icon} strokeWidth={1.75} className="size-5" />+ </button>+ ))}+ {/* Outlined on light; a lighter fill than the page on dark, where an outline reads as a hole. */}+ <label className="relative ml-2 flex h-9 w-[min(18rem,28vw)] min-w-40 items-center rounded-full border border-border px-4 focus-within:border-ring dark:border-transparent dark:bg-card dark:focus-within:border-ring">+ <HugeiconsIcon+ icon={Search01Icon}+ strokeWidth={1.75}+ className="size-[calc(18px*var(--ui-space-scale,1))] shrink-0 text-muted-foreground dark:text-foreground/70"+ />+ <input+ type="search"+ value={search}+ onChange={(event) => onSearchChange(event.target.value)}+ placeholder={searchPlaceholder}+ className="ml-2.5 min-w-0 flex-1 bg-transparent text-ui-14 outline-none placeholder:text-muted-foreground dark:placeholder:text-foreground/55 [&::-webkit-search-cancel-button]:hidden"+ />+ </label>+ <NewMenu onSelect={onNew} />+ <button+ type="button"+ aria-label={t("library.toolbar.settings")}+ onClick={onSettings}+ className={cn(ROUND_BUTTON, "text-muted-foreground hover:text-foreground dark:text-foreground")}+ >+ <HugeiconsIcon icon={Settings02Icon} strokeWidth={1.75} className="size-5" />+ </button>+ </div>+ );+}diff --git a/studio/frontend/src/features/library/favorites-store.ts b/studio/frontend/src/features/library/favorites-store.tsnew file mode 100644index 00000000000..819730a3174--- /dev/null+++ b/studio/frontend/src/features/library/favorites-store.ts@@ -0,0 +1,136 @@+// 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 { useEffect } from "react";+import { create } from "zustand";+import { AUTH_SESSION_CLEARED_EVENT } from "@/features/auth";+import { translate } from "@/i18n";+import { toast } from "@/lib/toast";+import { errorMessage, getLibraryFavorites, updateLibraryItem } from "./api";++export interface FavoritesSnapshotStart {+ attempts: ReadonlyMap<string, number>;+ pending: ReadonlySet<string>;+ session: number;+}++interface FavoritesState {+ ids: ReadonlySet<string>;+ load: () => Promise<void>;+ begin: () => FavoritesSnapshotStart;+ adopt: (start: FavoritesSnapshotStart, loaded: ReadonlySet<string>) => ReadonlySet<string>;+ mark: (id: string, favorite: boolean) => { settle: () => void; undo: () => void };+ setFavorite: (id: string, favorite: boolean) => Promise<void>;+}++const latestAttempt = new Map<string, number>();+const pending = new Map<string, number>();+// Bumped on sign-out, so a load started for the last account never lands for the next one.+let session = 0;++export const useLibraryFavoritesStore = create<FavoritesState>((set, get) => {+ function track(id: string): () => void {+ const trackedSession = session;+ pending.set(id, (pending.get(id) ?? 0) + 1);+ let settled = false;+ return () => {+ if (settled || trackedSession !== session) return;+ settled = true;+ const left = (pending.get(id) ?? 1) - 1;+ if (left > 0) pending.set(id, left);+ else pending.delete(id);+ };+ }++ function apply(id: string, favorite: boolean): void {+ const ids = new Set(get().ids);+ if (favorite) ids.add(id);+ else ids.delete(id);+ set({ ids });+ }++ return {+ ids: new Set(),+ load: async () => {+ const start = get().begin();+ try {+ get().adopt(start, new Set(await getLibraryFavorites()));+ } catch {+ // Favorites are a convenience here; the page works without them.+ }+ },+ begin: () => ({ attempts: new Map(latestAttempt), pending: new Set(pending.keys()), session }),+ adopt: (start, loaded) => {+ if (start.session !== session) return get().ids;+ const ids = get().ids;+ const next = new Set(loaded);+ for (const [id, attempt] of latestAttempt) {+ const settledBefore = !start.pending.has(id) && !pending.has(id);+ if (start.attempts.get(id) === attempt && settledBefore) continue;+ if (ids.has(id)) next.add(id);+ else next.delete(id);+ }+ set({ ids: next });+ return next;+ },+ mark: (id, favorite) => {+ const attempt = (latestAttempt.get(id) ?? 0) + 1;+ latestAttempt.set(id, attempt);+ const was = get().ids.has(id);+ const markedSession = session;+ apply(id, favorite);+ return {+ settle: track(id),+ undo: () => {+ if (markedSession === session && latestAttempt.get(id) === attempt) apply(id, was);+ },+ };+ },+ setFavorite: async (id, favorite) => {+ const attempt = (latestAttempt.get(id) ?? 0) + 1;+ latestAttempt.set(id, attempt);+ apply(id, favorite);+ const settle = track(id);+ try {+ await updateLibraryItem(id, { favorite });+ settle();+ if (latestAttempt.get(id) !== attempt) return;+ toast.success(+ translate(+ favorite ? "library.toast.addedToFavorites" : "library.toast.removedFromFavorites",+ ),+ );+ } catch (error) {+ settle();+ if (latestAttempt.get(id) !== attempt) return;+ apply(id, !favorite);+ toast.error(translate("library.toast.favoritesFailed"), {+ description: errorMessage(error),+ });+ }+ },+ };+});++// Module state, so a sign-out must drop it here: Images and Video load this without the Library.+if (typeof window !== "undefined") {+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, () => {+ session += 1;+ latestAttempt.clear();+ pending.clear();+ useLibraryFavoritesStore.setState({ ids: new Set() });+ });+}++export function useLibraryFavorites() {+ const ids = useLibraryFavoritesStore((s) => s.ids);+ const load = useLibraryFavoritesStore((s) => s.load);+ const setFavorite = useLibraryFavoritesStore((s) => s.setFavorite);+ useEffect(() => {+ void load();+ }, [load]);+ return {+ isFavorite: (id: string) => ids.has(id),+ toggleFavorite: (id: string) => void setFavorite(id, !ids.has(id)),+ };+}diff --git a/studio/frontend/src/features/library/file-kind.ts b/studio/frontend/src/features/library/file-kind.tsnew file mode 100644index 00000000000..2ede8171c38--- /dev/null+++ b/studio/frontend/src/features/library/file-kind.ts@@ -0,0 +1,185 @@+// 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 {+ AudioWave01Icon,+ File02Icon,+ FlimSlateIcon,+ Image02Icon,+ InternetIcon,+ Pdf01Icon,+ Presentation01Icon,+ SourceCodeIcon,+} from "@hugeicons/core-free-icons";+import { SheetIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";+import type { IconSvgElement } from "@hugeicons/react";+import type { LibraryItem } from "./api";+import { fileExtension } from "./file-name";++export type LibraryFileKind =+ | "image"+ | "web"+ | "document"+ | "spreadsheet"+ | "presentation"+ | "pdf"+ | "code"+ | "audio"+ | "video"+ | "model";++export type LibraryTypeFilter =+ | "images"+ | "videos"+ | "audio"+ | "documents"+ | "spreadsheets"+ | "presentations"+ | "pdfs";++const MODEL_CONTENT_TYPE = "application/x-unsloth-model";++const EXTENSION_KINDS: Record<string, LibraryFileKind> = {+ png: "image",+ jpg: "image",+ jpeg: "image",+ gif: "image",+ webp: "image",+ avif: "image",+ bmp: "image",+ svg: "image",+ html: "web",+ htm: "web",+ csv: "spreadsheet",+ tsv: "spreadsheet",+ xls: "spreadsheet",+ xlsx: "spreadsheet",+ ods: "spreadsheet",+ ppt: "presentation",+ pptx: "presentation",+ odp: "presentation",+ key: "presentation",+ pdf: "pdf",+ py: "code",+ js: "code",+ ts: "code",+ tsx: "code",+ jsx: "code",+ json: "code",+ sh: "code",+ css: "code",+ sql: "code",+ yaml: "code",+ yml: "code",+ mp3: "audio",+ wav: "audio",+ ogg: "audio",+ flac: "audio",+ m4a: "audio",+ mp4: "video",+ mov: "video",+ webm: "video",+ mkv: "video",+};++export function isModelItem(item: LibraryItem): boolean {+ return item.model != null;+}++export function isFileItem(item: LibraryItem): boolean {+ return !isModelItem(item);+}++const MODEL_LABELS = {+ "training:lora": "library.modelKind.lora",+ "training:merged": "library.modelKind.fullFineTune",+ "exported:lora": "library.modelKind.loraExport",+ "exported:merged": "library.modelKind.mergedExport",+ "exported:gguf": "library.modelKind.ggufExport",+} as const;++export type ModelLabelKey =+ | (typeof MODEL_LABELS)[keyof typeof MODEL_LABELS]+ | "library.modelKind.model";++export function modelLabelKey(item: LibraryItem): ModelLabelKey | null {+ const model = item.model;+ if (!model) return null;+ const key = `${model.origin}:${model.exportType}`;+ return key in MODEL_LABELS+ ? MODEL_LABELS[key as keyof typeof MODEL_LABELS]+ : "library.modelKind.model";+}++/** The extension the file itself has. A rename changes only the name shown, never what it is. */+function ownExtension(item: Pick<LibraryItem, "name" | "fileName">): string {+ return fileExtension(item.fileName ?? item.name);+}++export function fileKind(+ item: Pick<LibraryItem, "name" | "fileName" | "contentType">,+): LibraryFileKind {+ if (item.contentType === MODEL_CONTENT_TYPE) return "model";+ const byExtension = EXTENSION_KINDS[ownExtension(item)];+ if (byExtension) return byExtension;+ const type = item.contentType.toLowerCase();+ if (type.startsWith("image/")) return "image";+ if (type.startsWith("audio/")) return "audio";+ if (type.startsWith("video/")) return "video";+ if (type === "application/pdf") return "pdf";+ if (type === "text/html") return "web";+ return "document";+}++/** Raster images only: an svg is served as an opaque download and never rendered inline. */+export function hasImagePreview(item: LibraryItem): boolean {+ return (+ !item.textOnly &&+ fileKind(item) === "image" &&+ ownExtension(item) !== "svg"+ );+}++export function hasThumbnail(item: LibraryItem): boolean {+ return hasImagePreview(item) || (!item.textOnly && fileKind(item) === "video");+}++export const TYPE_FILTER_KINDS: Record<LibraryTypeFilter, LibraryFileKind[]> = {+ images: ["image"],+ videos: ["video"],+ audio: ["audio"],+ documents: ["document", "web", "code"],+ spreadsheets: ["spreadsheet"],+ presentations: ["presentation"],+ pdfs: ["pdf"],+};++export const KIND_ICONS: Record<LibraryFileKind, IconSvgElement> = {+ image: Image02Icon,+ web: InternetIcon,+ document: File02Icon,+ spreadsheet: SheetIcon,+ presentation: Presentation01Icon,+ pdf: Pdf01Icon,+ code: SourceCodeIcon,+ audio: AudioWave01Icon,+ video: FlimSlateIcon,+ model: TestTubeOutlineIcon,+};++export const KIND_ICON_CLASS: Partial<Record<LibraryFileKind, string>> = {+ spreadsheet: "text-emerald-500",+ pdf: "text-red-500",+ presentation: "text-orange-500",+};++export function isTextPreviewable(item: LibraryItem): boolean {+ if (item.textOnly) return true;+ const kind = fileKind(item);+ if (kind === "code" || kind === "web") return true;+ const ext = ownExtension(item);+ return (+ item.contentType.startsWith("text/") ||+ ["md", "txt", "csv", "tsv", "log", "xml"].includes(ext)+ );+}diff --git a/studio/frontend/src/features/library/file-name.ts b/studio/frontend/src/features/library/file-name.tsnew file mode 100644index 00000000000..04b1886e437--- /dev/null+++ b/studio/frontend/src/features/library/file-name.ts@@ -0,0 +1,143 @@+// 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 { isTextAttachmentName } from "../chat/text-attachment-accept.ts";++const INVALID_CHARS = new Set('<>:"/\\|?*');+const RESERVED_STEM = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$)$/i;+const MAX_NAME_BYTES = 200;+const utf8 = new TextEncoder();+const FALLBACK_STEM = "file";+const OPAQUE_TYPE = "application/octet-stream";++export function fileExtension(name: string): string {+ const dot = name.lastIndexOf(".");+ return dot > 0 ? name.slice(dot + 1).toLowerCase() : "";+}++function splitName(name: string): [stem: string, suffix: string] {+ const dot = name.lastIndexOf(".");+ return dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""];+}++function clean(name: string): string {+ let out = "";+ for (const char of name) {+ const code = char.codePointAt(0)!;+ out += INVALID_CHARS.has(char) || code < 0x20 || code === 0x7f ? "_" : char;+ }+ return out.replace(/[. ]+$/, "").trim();+}++export function libraryFileName(item: {+ name: string;+ fileName?: string;+ textOnly?: boolean;+}): string {+ const extension = clean(item.textOnly ? "txt" : fileExtension(item.fileName ?? item.name));+ let name = clean(item.name) || FALLBACK_STEM;+ if (extension && fileExtension(name) !== extension) name = `${name}.${extension}`;+ const [base, suffix] = splitName(name);+ let stem = base.trim() ? base : FALLBACK_STEM;+ if (RESERVED_STEM.test(stem.split(".", 1)[0]!.trim())) stem = `_${stem}`;+ const budget = MAX_NAME_BYTES - utf8.encode(suffix).length;+ if (utf8.encode(stem).length > budget) {+ let cut = "";+ let bytes = 0;+ for (const char of stem) {+ bytes += utf8.encode(char).length;+ if (bytes > budget && cut) break;+ cut += char;+ }+ stem = clean(cut) || FALLBACK_STEM;+ }+ return `${stem}${suffix}`;+}++export function uniqueFileNames(names: string[]): string[] {+ const taken = new Set<string>();+ return names.map((name) => {+ const [stem, suffix] = splitName(name);+ let candidate = name;+ for (let n = 2; taken.has(candidate.toLowerCase()); n++) candidate = `${stem} (${n})${suffix}`;+ taken.add(candidate.toLowerCase());+ return candidate;+ });+}++const EXTENSION_TYPES: Record<string, string> = {+ png: "image/png",+ jpg: "image/jpeg",+ jpeg: "image/jpeg",+ gif: "image/gif",+ webp: "image/webp",+ avif: "image/avif",+ bmp: "image/bmp",+ svg: "image/svg+xml",+ heic: "image/heic",+ tif: "image/tiff",+ tiff: "image/tiff",+ pdf: "application/pdf",+ html: "text/html",+ htm: "text/html",+ md: "text/markdown",+ csv: "text/csv",+ tsv: "text/tab-separated-values",+ json: "application/json",+ mp3: "audio/mpeg",+ wav: "audio/wav",+ ogg: "audio/ogg",+ flac: "audio/flac",+ m4a: "audio/mp4",+ mp4: "video/mp4",+ mov: "video/quicktime",+ webm: "video/webm",+ mkv: "video/x-matroska",+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",+};++function baseType(type: string): string {+ return type.split(";", 1)[0]!.trim().toLowerCase();+}++export function libraryFileType(fileName: string, serverType: string): string {+ const type = baseType(serverType);+ if (type && type !== OPAQUE_TYPE) return type;+ const byExtension = EXTENSION_TYPES[fileExtension(fileName)];+ if (byExtension) return byExtension;+ return isTextAttachmentName(fileName) ? "text/plain" : OPAQUE_TYPE;+}++const SCRIPTABLE_TYPES = new Set([+ "text/html",+ "application/xhtml+xml",+ "image/svg+xml",+ "text/xml",+ "application/xml",+]);++export type EmbeddedBody = "image" | "pdf" | "audio" | "video";++export function embeddedBlobType(body: EmbeddedBody, serverType: string): string {+ if (body === "pdf") return "application/pdf";+ const type = baseType(serverType);+ return type.startsWith(`${body}/`) && !SCRIPTABLE_TYPES.has(type) ? type : OPAQUE_TYPE;+}++export function itemVersion(item: { id: string; updatedAt: number; sizeBytes: number | null }): string {+ return `${item.id}@${item.updatedAt}.${item.sizeBytes ?? ""}`;+}++export function hasOwnFile(itemId: string): boolean {+ return /^(upload|image|video|audio|sandbox):/.test(itemId);+}++const STREAMED_SOURCES = new Set(["upload", "audio", "video", "sandbox"]);++export function streamsPreview(itemId: string, body: string | null): boolean {+ if (body !== "audio" && body !== "video") return false;+ const colon = itemId.indexOf(":");+ return colon > 0 && STREAMED_SOURCES.has(itemId.slice(0, colon));+}diff --git a/studio/frontend/src/features/library/filters.ts b/studio/frontend/src/features/library/filters.tsnew file mode 100644index 00000000000..46d5ec079dd--- /dev/null+++ b/studio/frontend/src/features/library/filters.ts@@ -0,0 +1,27 @@+// 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 { LibraryItem, LibrarySource } from "./api";+import { type LibraryTypeFilter, TYPE_FILTER_KINDS, fileKind } from "./file-kind";++export interface LibraryFilters {+ sources: Set<LibrarySource>;+ types: Set<LibraryTypeFilter>;+}++export const EMPTY_FILTERS: LibraryFilters = { sources: new Set(), types: new Set() };++export function filtersActive(filters: LibraryFilters): boolean {+ return filters.sources.size > 0 || filters.types.size > 0;+}++export function matchesFilters(+ item: LibraryItem,+ filters: LibraryFilters,+ typesApply: boolean,+): boolean {+ if (filters.sources.size > 0 && !filters.sources.has(item.source)) return false;+ if (!typesApply || filters.types.size === 0) return true;+ const kind = fileKind(item);+ return [...filters.types].some((type) => TYPE_FILTER_KINDS[type].includes(kind));+}diff --git a/studio/frontend/src/features/library/format.ts b/studio/frontend/src/features/library/format.tsnew file mode 100644index 00000000000..dc1f996ef89--- /dev/null+++ b/studio/frontend/src/features/library/format.ts@@ -0,0 +1,82 @@+// 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 { InterpolationValues, Locale, TranslationKey } from "@/i18n";+import { formatRelativeTime } from "@/i18n/relative-time";++type Translate = (key: TranslationKey, values?: InterpolationValues) => string;++const yesterdayFormatters = new Map<Locale, Intl.RelativeTimeFormat>();++function yesterday(locale: Locale): string {+ let formatter = yesterdayFormatters.get(locale);+ if (!formatter) {+ formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });+ yesterdayFormatters.set(locale, formatter);+ }+ return formatter.format(-1, "day");+}++function startOfDay(date: Date): number {+ return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();+}++export function formatCardTime(ts: number, locale: Locale): string {+ const then = new Date(ts);+ const now = new Date();+ if (then.toDateString() === now.toDateString()) {+ return then.toLocaleTimeString(locale, {+ hour: "numeric",+ minute: "2-digit",+ });+ }+ return then.toLocaleDateString(locale, {+ month: "short",+ day: "numeric",+ year: then.getFullYear() === now.getFullYear() ? undefined : "numeric",+ });+}++export function formatActivityTime(ts: number, locale: Locale, t: Translate): string {+ const elapsed = Date.now() - ts;+ if (elapsed < -60_000) return formatCardTime(ts, locale);+ const minutes = Math.floor(elapsed / 60_000);+ if (minutes < 1) return t("library.list.justNow");+ 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);+ if (days <= 1) return yesterday(locale);+ if (days < 7) return formatRelativeTime(locale, -days, "day");+ return formatCardTime(ts, locale);+}++const SIZE_UNITS = [+ "library.size.kilobytes",+ "library.size.megabytes",+ "library.size.gigabytes",+] as const satisfies readonly TranslationKey[];++export function formatSize(bytes: number | null, locale: Locale, t: Translate): string | null {+ if (bytes === null) return null;+ if (bytes < 1024) {+ return t("library.size.bytes", { value: bytes.toLocaleString(locale, { useGrouping: false }) });+ }+ let value = bytes / 1024;+ let unit: (typeof SIZE_UNITS)[number] = SIZE_UNITS[0];+ for (const next of SIZE_UNITS.slice(1)) {+ if (value < 1024) break;+ value /= 1024;+ unit = next;+ }+ const digits = value >= 10 ? 0 : 1;+ const formatted = value.toLocaleString(locale, {+ minimumFractionDigits: digits,+ maximumFractionDigits: digits,+ });+ return t(unit, { value: formatted });+}++export function formatItemCount(count: number, t: Translate): string {+ return t(count === 1 ? "library.itemCountOne" : "library.itemCount", { count });+}diff --git a/studio/frontend/src/features/library/hooks.ts b/studio/frontend/src/features/library/hooks.tsnew file mode 100644index 00000000000..c7cd5fa7124--- /dev/null+++ b/studio/frontend/src/features/library/hooks.ts@@ -0,0 +1,146 @@+// 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 { translate } from "@/i18n";+import { type RefObject, useEffect, useState } from "react";+import {+ LibraryFileTooLarge,+ type LibraryItem,+ errorMessage,+ fetchLibraryBlob,+ fetchLibraryStreamUrl,+ fetchLibraryThumbnail,+} from "./api";+import { type EmbeddedBody, embeddedBlobType, itemVersion, streamsPreview } from "./file-name";+import { acquireObjectUrl } from "./object-url-cache";++const MAX_BUFFERED_PREVIEW_BYTES = 256 * 1024 * 1024;++async function previewSource(+ item: LibraryItem,+ body: EmbeddedBody,+): Promise<{ url: string; streamed: boolean }> {+ if (streamsPreview(item.id, body)) {+ try {+ return { url: await fetchLibraryStreamUrl(item), streamed: true };+ } catch {+ // An older server without the route: the blob below still plays it.+ }+ }+ const tooLarge = () => new Error(translate("library.preview.tooLargeToPreview"));+ if (item.sizeBytes !== null && item.sizeBytes > MAX_BUFFERED_PREVIEW_BYTES) throw tooLarge();+ const type = embeddedBlobType(body, item.contentType);+ const blob = await fetchLibraryBlob(item, type, MAX_BUFFERED_PREVIEW_BYTES).catch((error) => {+ throw error instanceof LibraryFileTooLarge ? tooLarge() : error;+ });+ return { url: URL.createObjectURL(blob), streamed: false };+}++export function useLibraryPreviewUrl(+ item: LibraryItem,+ body: EmbeddedBody | null,+): { url: string | null; error: string | null; retry: () => boolean } {+ const baseKey = `${itemVersion(item)}:${body ?? ""}`;+ const [reminted, setReminted] = useState<string | null>(null);+ const key = `${baseKey}#${reminted === baseKey ? 1 : 0}`;+ const [state, setState] = useState<{+ key: string;+ url: string | null;+ streamed?: boolean;+ error?: string;+ } | null>(null);+ useEffect(() => {+ if (!body) return;+ let cancelled = false;+ const next = previewSource(item, body);+ next.then(+ ({ url, streamed }) => !cancelled && setState({ key, url, streamed }),+ (err: unknown) => !cancelled && setState({ key, url: null, error: errorMessage(err) }),+ );+ return () => {+ cancelled = true;+ void next.then(({ url, streamed }) => !streamed && URL.revokeObjectURL(url), () => {});+ };+ // `key` carries the item's identity and version; the object itself changes on every refresh.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key]);+ const current = body && state?.key === key ? state : null;+ const retry = () => {+ if (!current?.url || !current.streamed || reminted === baseKey) return false;+ setReminted(baseKey);+ return true;+ };+ return { url: current?.url ?? null, error: current?.error ?? null, retry };+}++/** A card's picture once `enabled`: a bounded thumbnail of the image, or a video's first frame,+ * never the original, whose decoded size has no limit. Cached, and held while the card shows it;+ * `failed` once it cannot load, so the card can fall back to the type icon. */+export function useLibraryThumbnail(+ item: LibraryItem,+ enabled: boolean,+): { url: string | null; failed: boolean } {+ const key = itemVersion(item);+ const [state, setState] = useState<{ key: string; url: string | null } | null>(null);+ useEffect(() => {+ if (!enabled) return;+ let cancelled = false;+ const { url: next, release } = acquireObjectUrl(key, () => fetchLibraryThumbnail(item));+ next.then(+ (url) => !cancelled && setState({ key, url }),+ () => !cancelled && setState({ key, url: null }),+ );+ return () => {+ cancelled = true;+ release();+ };+ // `key` carries the item's identity and version; the object itself changes on every refresh.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key, enabled]);+ const current = enabled && state?.key === key ? state : null;+ return { url: current?.url ?? null, failed: current !== null && current.url === null };+}++/** True once the element has come within a screen of the viewport; never flips back. */+export function useSeen(ref: RefObject<Element | null>): boolean {+ const [seen, setSeen] = useState(() => typeof IntersectionObserver === "undefined");+ useEffect(() => {+ const element = ref.current;+ if (!element || seen) return;+ const observer = new IntersectionObserver(+ (entries) => {+ if (entries.some((entry) => entry.isIntersecting)) {+ setSeen(true);+ observer.disconnect();+ }+ },+ { rootMargin: "400px" },+ );+ observer.observe(element);+ return () => observer.disconnect();+ }, [ref, seen]);+ return seen;+}++export function useColumnCount(+ ref: RefObject<HTMLElement | null>,+ minColumnWidth = 200,+ maxColumns = 5,+): number {+ const [columns, setColumns] = useState(4);+ useEffect(() => {+ const element = ref.current;+ if (!element) return;+ const measure = () => {+ const width = element.clientWidth;+ setColumns(+ Math.max(2, Math.min(maxColumns, Math.floor(width / minColumnWidth))),+ );+ };+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(element);+ return () => observer.disconnect();+ }, [ref, minColumnWidth, maxColumns]);+ return columns;+}diff --git a/studio/frontend/src/features/library/index.ts b/studio/frontend/src/features/library/index.tsnew file mode 100644index 00000000000..33f7459a70c--- /dev/null+++ b/studio/frontend/src/features/library/index.ts@@ -0,0 +1,6 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export { useLibraryChatHandoffStore } from "./chat-handoff-store";+export { useLibraryFavorites } from "./favorites-store";+export { validateLibrarySearch, type LibrarySearch, type LibraryTab } from "./search";diff --git a/studio/frontend/src/features/library/library-page.tsx b/studio/frontend/src/features/library/library-page.tsxnew file mode 100644index 00000000000..de1840243a8--- /dev/null+++ b/studio/frontend/src/features/library/library-page.tsx@@ -0,0 +1,940 @@+// 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 { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Skeleton } from "@/components/ui/skeleton";+import {+ type NativeIntent,+ consumeNativePathToken,+ useNativeFileDrop,+} from "@/features/native-intents";+import { getAuthSessionEpoch } from "@/features/auth";+import { useSettingsDialogStore } from "@/features/settings";+import { type TranslationKey, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { toast } from "@/lib/toast";+import {+ AudioWave01Icon,+ Cancel01Icon,+ FlimSlateIcon,+ Delete02Icon,+ Download01Icon,+ Folder01Icon,+ FolderExportIcon,+ Image02Icon,+ MoreHorizontalIcon,+ PencilEdit02Icon,+ Upload01Icon,+} from "@hugeicons/core-free-icons";+import { ChevronRightStandardIcon } from "@/lib/chevron-icons";+import { StarPointedIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";+import { HugeiconsIcon } from "@hugeicons/react";+import { useNavigate, useRouter, useSearch } from "@tanstack/react-router";+import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ chatAboutItems,+ chatWithModel,+ downloadLibraryItem,+ downloadLibraryItems,+} from "./actions";+import { type LibraryFolder, type LibraryItem, type LibraryUploadBatch, errorMessage } from "./api";+import { fileKind, isFileItem, isModelItem } from "./file-kind";+import {+ type LibraryActions,+ LibraryActionsProvider,+ type LibraryTarget,+} from "./actions-context";+import { CardSelectionContext } from "./components/card-selection";+import { FolderGrid, ItemCard, Masonry } from "./components/library-cards";+import { ConfirmDeleteDialog, NameDialog } from "./components/library-dialogs";+import { LibraryList } from "./components/library-list";+import { LibraryPreview } from "./components/library-preview";+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";++const TAB_LABELS: Record<LibraryTab, TranslationKey> = {+ suggested: "library.tabs.suggested",+ favorites: "library.tabs.favorites",+ folders: "library.tabs.folders",+ images: "library.tabs.images",+ videos: "library.tabs.videos",+ audio: "library.tabs.audio",+ models: "library.tabs.models",+ all: "library.tabs.all",+};++type EmptyCopy = [icon: typeof Folder01Icon, title: TranslationKey, description: TranslationKey];+const EMPTY_COPY: Record<LibraryTab, EmptyCopy> = {+ suggested: [Upload01Icon, "library.empty.suggestedTitle", "library.empty.suggestedDescription"],+ favorites: [StarPointedIcon, "library.empty.favoritesTitle", "library.empty.favoritesDescription"],+ folders: [Folder01Icon, "library.empty.foldersTitle", "library.empty.foldersDescription"],+ images: [Image02Icon, "library.empty.imagesTitle", "library.empty.imagesDescription"],+ videos: [FlimSlateIcon, "library.empty.videosTitle", "library.empty.videosDescription"],+ audio: [AudioWave01Icon, "library.empty.audioTitle", "library.empty.audioDescription"],+ models: [TestTubeOutlineIcon, "library.empty.modelsTitle", "library.empty.modelsDescription"],+ all: [Upload01Icon, "library.empty.suggestedTitle", "library.empty.suggestedDescription"],+};++const EMPTY_LINKS = {+ videos: ["/video", "library.empty.generateVideo"],+ audio: ["/audio", "library.empty.generateAudio"],+ models: ["/studio", "library.empty.trainModel"],+} as const;++const KIND_TABS: Partial<Record<LibraryTab, (item: LibraryItem) => boolean>> = {+ images: (item) => fileKind(item) === "image",+ videos: (item) => fileKind(item) === "video",+ audio: (item) => fileKind(item) === "audio",+ models: isModelItem,+};++const SUGGESTED_LIMIT = 40;++const DELETE_NOTES: Record<string, TranslationKey> = {+ upload: "library.dialog.deleteUpload",+ attachment: "library.dialog.deleteAttachment",+ image: "library.dialog.deleteImage",+ video: "library.dialog.deleteVideo",+ audio: "library.dialog.deleteAudio",+ sandbox: "library.dialog.deleteSandbox",+};++type NameDialogState =+ | { mode: "create"; parentId: string | null; thenMove?: LibraryTarget }+ | { mode: "rename"; target: LibraryTarget };++function nameMatches(name: string, needle: string): boolean {+ return !needle || name.toLowerCase().includes(needle);+}++const BAR_PILL =+ "flex h-9 items-center gap-2 rounded-full px-4 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50";+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,+ description,+ action,+}: {+ icon: typeof Folder01Icon;+ title: string;+ description: string;+ action?: ReactNode;+}) {+ return (+ <div className="mx-auto mt-16 flex max-w-md flex-col items-center gap-2 text-center">+ <HugeiconsIcon icon={icon} strokeWidth={1.5} className="mb-2 size-7" />+ <h2 className="font-medium text-ui-21 text-foreground">{title}</h2>+ <p className="text-ui-15 text-muted-foreground">{description}</p>+ {action && <div className="mt-3">{action}</div>}+ </div>+ );+}++function SectionHeading({ children }: { children: ReactNode }) {+ return <h2 className="mb-4 mt-8 font-medium text-ui-18 text-foreground">{children}</h2>;+}++function LoadingGrid() {+ return (+ <div className="mt-6 grid grid-cols-2 gap-5 sm:grid-cols-3 lg:grid-cols-5">+ {Array.from({ length: 10 }, (_, index) => (+ <Skeleton key={index} className="aspect-square rounded-xl" />+ ))}+ </div>+ );+}++export function LibraryPage() {+ const search = useSearch({ from: "/library" });+ const refresh = useLibraryStore((s) => s.refresh);++ useEffect(() => {+ void refresh();+ const onFocus = () => void refresh();+ window.addEventListener("focus", onFocus);+ return () => window.removeEventListener("focus", onFocus);+ }, [refresh]);++ return <LibraryView key={`${search.show ?? ""}:${search.folder ?? ""}`} 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 } =+ useLibraryStore();+ 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 [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 folderId = search.folder ?? null;+ const folderById = useMemo(() => new Map(folders.map((f) => [f.id, f])), [folders]);+ const currentFolder = folderId ? (folderById.get(folderId) ?? null) : null;++ const go = useCallback(+ (next: LibrarySearch, replace = false) =>+ void navigate({ to: "/library", search: next, replace }),+ [navigate],+ );++ const [parentOfOpen, setParentOfOpen] = useState<string | null>(null);+ if (currentFolder && currentFolder.parentId !== parentOfOpen) {+ setParentOfOpen(currentFolder.parentId);+ }+ const folderGone = status === "ready" && folderId !== null && currentFolder === null;+ useEffect(() => {+ if (!folderGone) return;+ const parent = parentOfOpen && folderById.has(parentOfOpen) ? parentOfOpen : undefined;+ go({ folder: parent, show: "folders" }, true);+ }, [folderGone, parentOfOpen, folderById, go]);+++ const counts = useMemo(() => {+ const map = new Map<string, number>();+ const bump = (id: string | null) => id && map.set(id, (map.get(id) ?? 0) + 1);+ for (const item of items) bump(item.folderId);+ for (const folder of folders) bump(folder.parentId);+ return map;+ }, [items, folders]);++ const needle = query.trim().toLowerCase();++ 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 visibleItems = useMemo(() => {+ let pool = items;+ if (folderId) pool = pool.filter((item) => item.folderId === folderId);+ else if (tab === "favorites") pool = pool.filter((item) => item.favorite);+ else if (kindFilter) pool = pool.filter(kindFilter);+ else if (tab === "folders") pool = [];+ 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]);++ const visibleFolders = useMemo(() => {+ const showsFolders = folderId || tab === "folders" || tab === "all";+ if (!showsFolders || (filtersActive(filters) && tab !== "folders")) return [];+ 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]);++ // 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.+ const visibleKeys = useMemo(+ () =>+ new Set([+ ...visibleFolders.map((folder) => `folder:${folder.id}`),+ ...visibleItems.map((item) => `item:${item.id}`),+ ]),+ [visibleFolders, visibleItems],+ );+ if ([...selection].some((key) => !visibleKeys.has(key))) {+ setSelection(new Set([...selection].filter((key) => visibleKeys.has(key))));+ }++ const previewItem = search.item ? (items.find((item) => item.id === search.item) ?? null) : null;++ const router = useRouter();+ const pushedPreview = useRef<string | null>(null);+ const [closingPreview, setClosingPreview] = useState<string | null>(null);+ if (!search.item && closingPreview !== null) setClosingPreview(null);+ useEffect(() => {+ if (!search.item) pushedPreview.current = null;+ }, [search.item]);+ const openPreview = (id: string) => {+ pushedPreview.current = id;+ go({ ...search, item: id });+ };+ const closePreview = () => {+ if (!search.item) return;+ setClosingPreview(search.item);+ if (pushedPreview.current === search.item) {+ pushedPreview.current = null;+ router.history.back();+ } else {+ go({ ...search, item: undefined }, true);+ }+ };++ const missingItem =+ search.item && status === "ready" && !previewItem && closingPreview !== search.item+ ? search.item+ : null;+ useEffect(() => {+ if (!missingItem) return;+ let cancelled = false;+ void refresh().then(() => {+ if (cancelled) return;+ if (useLibraryStore.getState().items.some((item) => item.id === missingItem)) return;+ toast(t("library.toast.missingItem"));+ void navigate({+ to: "/library",+ search: (prev) => ({ ...prev, item: undefined }),+ replace: true,+ });+ });+ return () => {+ cancelled = true;+ };+ }, [missingItem, refresh, navigate, t]);+++ const fail = (message: string) => (err: unknown) =>+ toast.error(message, { description: errorMessage(err) });++ const filesInFolder = (id: string) => {+ const inside = new Set([id]);+ for (let grew = true; grew; ) {+ grew = false;+ for (const folder of folders) {+ if (folder.parentId && inside.has(folder.parentId) && !inside.has(folder.id)) {+ inside.add(folder.id);+ grew = true;+ }+ }+ }+ return items.filter(+ (item) => item.folderId !== null && inside.has(item.folderId) && isFileItem(item),+ );+ };++ const chatAbout = (item: LibraryItem) =>+ void (item.model ? chatWithModel(navigate, item) : chatAboutItems(navigate, [item]));++ const moveAll = async (targets: LibraryTarget[], destination: string | null) => {+ const folder = destination+ ? (folderById.get(destination)?.name ?? t("library.toast.folderFallback"))+ : null;+ const results = await Promise.allSettled(+ targets.map((target) =>+ target.kind === "item"+ ? patchItem(target.item.id, { folderId: destination })+ : patchFolder(target.folder.id, { parentId: destination }),+ ),+ );+ const failed = results.find((result) => result.status === "rejected");+ if (failed) fail(t("library.toast.moveFailed"))(failed.reason);+ else if (folder === null) toast.success(t("library.toast.movedToLibrary"));+ else toast.success(t("library.toast.movedToFolder", { folder }));+ };++ const actions: LibraryActions = {+ folders,+ openItem: (item) => openPreview(item.id),+ openFolder: (id) => go({ folder: id }),+ chatAbout: (target) =>+ target.kind === "item"+ ? chatAbout(target.item)+ : void chatAboutItems(navigate, filesInFolder(target.folder.id)),+ toggleFavorite: (item) =>+ void patchItem(item.id, { favorite: !item.favorite }).catch(fail(t("library.toast.favoritesFailed"))),+ download: (item) => void downloadLibraryItem(item),+ rename: (target) => setNameDialog({ mode: "rename", target }),+ moveTo: (target, destination) => void moveAll([target], destination),+ moveToNewFolder: (target) =>+ setNameDialog({ mode: "create", parentId: folderId, thenMove: target }),+ remove: (target) => setPendingDelete([target]),+ };++ async function uploadBatch(batch: LibraryUploadBatch, count: number, label: string) {+ if (count === 0) return;+ const id = toast.loading(+ count === 1+ ? t("library.toast.uploadingOne", { name: label })+ : t("library.toast.uploadingMany", { count }),+ );+ try {+ await upload(batch, folderId);+ toast.success(+ count === 1 ? t("library.toast.uploadedOne") : t("library.toast.uploadedMany", { count }),+ { id },+ );+ } catch (err) {+ toast.error(t("library.toast.uploadFailed"), { id, description: errorMessage(err) });+ }+ }++ const uploadFiles = (files: File[]) =>+ uploadBatch({ files }, files.length, files[0]?.name ?? "");++ async function uploadNativeDrops(intents: NativeIntent[]) {+ // The grants are the signed-in account's: one who signs in meanwhile must not upload them.+ const sessionEpoch = getAuthSessionEpoch();+ try {+ const leases = await Promise.all(+ intents.map((intent) => consumeNativePathToken(intent.path.token, "attach")),+ );+ await uploadBatch(+ { nativePathLeases: leases.map((lease) => lease.nativePathLease), sessionEpoch },+ leases.length,+ leases[0]?.displayLabel ?? "",+ );+ } catch (err) {+ fail(t("library.toast.readDropsFailed"))(err);+ }+ }++ const { ref: dropRef, dragging, dragHandlers } = useNativeFileDrop({+ onFiles: uploadFiles,+ onNativeIntents: uploadNativeDrops,+ });++ async function createNote() {+ try {+ const note = new File([""], `${t("library.create.untitledNote")}.md`, {+ type: "text/markdown",+ });+ const [id] = await upload({ files: [note] }, folderId);+ if (id) openPreview(id);+ } catch (err) {+ fail(t("library.toast.createNoteFailed"))(err);+ }+ }++ function handleNew(action: NewAction) {+ switch (action) {+ case "note":+ void createNote();+ break;+ case "image":+ void navigate({ to: "/images" });+ break;+ case "video":+ void navigate({ to: "/video" });+ break;+ case "audio":+ void navigate({ to: "/audio", search: { task: "text-to-speech" } });+ break;+ case "model":+ void navigate({ to: "/studio" });+ break;+ case "folder":+ setNameDialog({ mode: "create", parentId: folderId });+ break;+ case "upload":+ fileInput.current?.click();+ break;+ }+ }++ async function submitName(name: string) {+ if (!nameDialog) return;+ try {+ if (nameDialog.mode === "rename") {+ const { target } = nameDialog;+ if (target.kind === "item") await patchItem(target.item.id, { name });+ else await patchFolder(target.folder.id, { name });+ return;+ }+ const folder = await addFolder(name, nameDialog.parentId);+ if (nameDialog.thenMove) await moveAll([nameDialog.thenMove], folder.id);+ } catch (err) {+ const renaming = nameDialog.mode === "rename";+ fail(t(renaming ? "library.toast.renameFailed" : "library.toast.createFolderFailed"))(err);+ throw err;+ }+ }++ async function confirmDelete(targets: LibraryTarget[]) {+ setPendingDelete(null);+ setSelection(new Set());+ if (targets.some((t) => t.kind === "item" && t.item.id === search.item)) closePreview();+ const results = await Promise.allSettled(+ targets.map((target) =>+ target.kind === "item"+ ? removeItem(target.item.id, target.item.fingerprint)+ : removeFolder(target.folder.id),+ ),+ );+ const failed = results.find((result) => result.status === "rejected");+ if (failed) fail(t("library.toast.deleteFailed"))(failed.reason);+ if (folderId && targets.some((t) => t.kind === "folder" && t.folder.id === folderId)) {+ go({ folder: currentFolder?.parentId ?? undefined, show: "folders" }, true);+ }+ }++ const deleteCopy = (targets: LibraryTarget[]) => {+ if (targets.length > 1) {+ return {+ title: t("library.dialog.deleteManyTitle", { count: targets.length }),+ description: t("library.dialog.deleteManyDescription"),+ };+ }+ const target = targets[0]!;+ if (target.kind === "folder") {+ const parent = target.folder.parentId ? folderById.get(target.folder.parentId) : null;+ return {+ title: t("library.dialog.deleteTitle", { name: target.folder.name }),+ description: parent+ ? t("library.dialog.deleteFolderIntoParent", { folder: parent.name })+ : t("library.dialog.deleteFolderIntoLibrary"),+ };+ }+ const source = target.item.id.split(":", 1)[0]!;+ return {+ title: t("library.dialog.deleteTitle", { name: target.item.name }),+ description: t(DELETE_NOTES[source] ?? "library.dialog.deleteUpload"),+ };+ };++ const cardSelection = {+ selection,+ toggle: (key: string) =>+ setSelection((current) => {+ const next = new Set(current);+ if (!next.delete(key)) next.add(key);+ return next;+ }),+ };++ const selectedTargets = (): LibraryTarget[] => {+ const out: LibraryTarget[] = [];+ for (const folder of visibleFolders)+ if (selection.has(`folder:${folder.id}`)) out.push({ kind: "folder", folder });+ for (const item of visibleItems)+ if (selection.has(`item:${item.id}`)) out.push({ kind: "item", item });+ return out;+ };++ const bulkDestinations = () =>+ folders.filter((folder) => {+ for (let at: LibraryFolder | undefined = folder; at; at = at.parentId ? folderById.get(at.parentId) : undefined)+ if (selection.has(`folder:${at.id}`)) return false;+ return true;+ });+++ const breadcrumb: LibraryFolder[] = [];+ for (let at = currentFolder; at; at = at.parentId ? (folderById.get(at.parentId) ?? null) : null) {+ breadcrumb.unshift(at);+ if (breadcrumb.length > 32) break;+ }++ 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")}>+ <button+ type="button"+ onClick={() => go({ show: "folders" })}+ className="shrink-0 text-muted-foreground transition-colors hover:text-foreground"+ >+ {t("shell.navigation.library")}+ </button>+ {breadcrumb.map((folder, index) => (+ <span key={folder.id} className="flex min-w-0 items-center gap-2">+ <HugeiconsIcon icon={ChevronRightStandardIcon} strokeWidth={2} className="size-5 shrink-0 text-muted-foreground" />+ {index === breadcrumb.length - 1 ? (+ <span className="truncate text-foreground">{folder.name}</span>+ ) : (+ <button+ type="button"+ onClick={() => go({ folder: folder.id })}+ className="truncate text-muted-foreground transition-colors hover:text-foreground"+ >+ {folder.name}+ </button>+ )}+ </span>+ ))}+ </nav>+ ) : (+ <h1 className="text-ui-25 font-semibold leading-[1.04] tracking-[-0.028em] text-foreground">+ {t("shell.navigation.library")}+ </h1>+ );+++ const uploadButton = (+ <Button variant="muted" className="rounded-full px-5" onClick={() => fileInput.current?.click()}>+ {t("library.empty.uploadFiles")}+ </Button>+ );++ function renderCards() {+ const itemsGrid = visibleItems.length > 0 && (+ <Masonry+ items={visibleItems}+ getKey={(item) => item.id}+ render={(item) => <ItemCard item={item} />}+ />+ );+ if (folderId || tab === "all") {+ const sectioned = !folderId;+ return (+ <>+ {visibleFolders.length > 0 && (+ <>+ {sectioned && <SectionHeading>{t("library.tabs.folders")}</SectionHeading>}+ <div className={cn(!sectioned && "mt-6")}>+ <FolderGrid folders={visibleFolders} counts={counts} />+ </div>+ </>+ )}+ {visibleItems.length > 0 && (+ <>+ {sectioned ? (+ <SectionHeading>{t("library.sections.items")}</SectionHeading>+ ) : (+ <div className="mt-6" />+ )}+ {itemsGrid}+ </>+ )}+ </>+ );+ }+ if (tab === "folders") {+ return (+ <div className="mt-6">+ <FolderGrid folders={visibleFolders} counts={counts} />+ </div>+ );+ }+ return <div className="mt-6">{itemsGrid}</div>;+ }++ function emptyAction(): ReactNode {+ if (tab === "favorites") return undefined;+ if (tab === "folders") {+ return (+ <Button+ variant="dark"+ className="rounded-full px-5"+ onClick={() => setNameDialog({ mode: "create", parentId: null })}+ >+ {t("library.empty.createFolder")}+ </Button>+ );+ }+ if (!(tab in EMPTY_LINKS)) return uploadButton;+ const [to, label] = EMPTY_LINKS[tab as keyof typeof EMPTY_LINKS];+ return (+ <Button variant="muted" className="rounded-full px-5" onClick={() => void navigate({ to })}>+ {t(label)}+ </Button>+ );+ }++ function renderBody() {+ if (status === "loading" || status === "idle") return <LoadingGrid />;+ if (status === "error") {+ return (+ <EmptyState+ icon={Folder01Icon}+ title={t("library.empty.loadErrorTitle")}+ description={error ?? t("library.empty.loadErrorFallback")}+ action={+ <Button variant="muted" className="rounded-full" onClick={() => void refresh()}>+ {t("library.empty.tryAgain")}+ </Button>+ }+ />+ );+ }+ const empty = visibleItems.length === 0 && visibleFolders.length === 0;+ const narrowed = Boolean(needle) || filtersActive(filters);+ if (empty && narrowed) {+ return (+ <EmptyState+ icon={Folder01Icon}+ title={t("library.empty.noMatchesTitle")}+ description={t("library.empty.noMatchesDescription")}+ />+ );+ }+ if (empty && folderId) {+ return (+ <div className="mt-6 flex min-h-[calc(420px*var(--ui-space-scale,1))] flex-col items-center justify-center gap-5 rounded-xl border border-dashed border-border bg-muted/50">+ <HugeiconsIcon icon={Upload01Icon} strokeWidth={1.5} className="size-8" />+ {uploadButton}+ <p className="text-sm text-muted-foreground">{t("library.empty.dropHere")}</p>+ </div>+ );+ }+ if (empty) {+ const [emptyIcon, emptyTitle, emptyDescription] = EMPTY_COPY[tab];+ return (+ <EmptyState+ icon={emptyIcon}+ title={t(emptyTitle)}+ description={t(emptyDescription)}+ action={emptyAction()}+ />+ );+ }+ if (view === "list") {+ return (+ <div className="mt-6">+ <LibraryList+ folders={visibleFolders}+ items={visibleItems}+ counts={counts}+ selection={selection}+ onSelectionChange={setSelection}+ />+ </div>+ );+ }+ return (+ <CardSelectionContext.Provider value={cardSelection}>{renderCards()}</CardSelectionContext.Provider>+ );+ }++ const nameDialogProps =+ nameDialog?.mode === "rename"+ ? {+ title: t(+ nameDialog.target.kind === "folder"+ ? "library.dialog.renameFolder"+ : "library.dialog.renameFile",+ ),+ submitLabel: t("common.rename"),+ initialValue:+ nameDialog.target.kind === "item" ? nameDialog.target.item.name : nameDialog.target.folder.name,+ }+ : {+ title: t("library.menu.newFolder"),+ submitLabel: t("library.dialog.create"),+ initialValue: "",+ };++ const selectedCount = selection.size;+ const selectedFiles = () => {+ const out = new Map<string, LibraryItem>();+ for (const target of selectedTargets()) {+ const files =+ target.kind === "item"+ ? [target.item].filter(isFileItem)+ : filesInFolder(target.folder.id);+ for (const file of files) out.set(file.id, file);+ }+ return [...out.values()];+ };+ const selectedModel = () => {+ const targets = selectedTargets();+ const only = targets.length === 1 ? targets[0] : undefined;+ return only?.kind === "item" && isModelItem(only.item) ? only.item : null;+ };+ const bulkChat = () => {+ const model = selectedModel();+ if (model) chatAbout(model);+ else void chatAboutItems(navigate, selectedFiles());+ setSelection(new Set());+ };+ const bulkDownload = () => {+ const files = selectedFiles();+ setSelection(new Set());+ void downloadLibraryItems(files);+ };+ const bulkMove = (destination: string | null) => {+ void moveAll(selectedTargets(), destination);+ setSelection(new Set());+ };+ const deletableSelection = () =>+ selectedTargets().filter((t) => t.kind === "folder" || isFileItem(t.item));+ const deleteText = pendingDelete ? deleteCopy(pendingDelete) : null;++ return (+ <LibraryActionsProvider value={actions}>+ <main+ ref={dropRef}+ {...dragHandlers}+ className="relative mx-auto w-full max-w-[calc(1560px*var(--ui-space-scale,1))] px-6 pb-24 pt-8 font-heading sm:px-10"+ >+ <input+ ref={fileInput}+ type="file"+ multiple+ hidden+ onChange={(event) => {+ void uploadFiles([...(event.target.files ?? [])]);+ event.target.value = "";+ }}+ />+ <LibraryHeader+ title={title}+ controls={+ <LibraryToolbar+ filters={filters}+ onFiltersChange={setFilters}+ filterMode={!folderId && tab === "folders" ? "none" : kindFilter ? "source" : "all"}+ view={view}+ onViewChange={setView}+ search={query}+ onSearchChange={setQuery}+ searchPlaceholder={t(folderId ? "library.searchFolder" : "library.searchLibrary")}+ onNew={handleNew}+ onSettings={() => openSettings("data")}+ />+ }+ tabs={+ folderId+ ? null+ : {+ items: shownTabs.map((key) => ({ key, label: t(TAB_LABELS[key]) })),+ active: tab,+ onChange: (next) => go({ show: next as LibraryTab }),+ }+ }+ />+ {renderBody()}++ {dragging && (+ <div className="pointer-events-none fixed inset-0 z-40 flex items-center justify-center bg-background/70 backdrop-blur-sm">+ <div className="flex flex-col items-center gap-3 rounded-xl border-2 border-dashed border-muted-foreground px-16 py-12">+ <HugeiconsIcon icon={Upload01Icon} strokeWidth={1.5} className="size-8" />+ <p className="font-medium text-lg">+ {currentFolder+ ? t("library.dropToUploadInto", { folder: currentFolder.name })+ : t("library.dropToUpload")}+ </p>+ </div>+ </div>+ )}++ {selectedCount > 0 && (+ <div className="fixed bottom-8 left-1/2 z-30 flex -translate-x-1/2 items-center gap-2 rounded-full bg-sidebar py-2 pl-6 pr-2 text-sidebar-foreground shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:shadow-[0_8px_28px_-6px_var(--background)]">+ <span className="mr-4 whitespace-nowrap text-sm font-medium">+ {t("shell.selection.countSelected", { count: selectedCount })}+ </span>+ <button+ type="button"+ disabled={selectedModel() === null && selectedFiles().length === 0}+ onClick={bulkChat}+ className={cn(BAR_PILL, "bg-foreground text-background transition-opacity hover:opacity-85")}+ >+ <HugeiconsIcon icon={PencilEdit02Icon} strokeWidth={1.75} className="size-4" />+ {t("library.selection.startChat")}+ </button>+ <button+ type="button"+ disabled={selectedFiles().length === 0}+ onClick={bulkDownload}+ className={cn(+ BAR_PILL,+ "border border-border transition-colors hover:bg-sidebar-accent dark:border-transparent dark:bg-accent/60 dark:hover:bg-accent",+ )}+ >+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-4" />+ {t("library.menu.download")}+ </button>+ <button+ type="button"+ disabled={deletableSelection().length === 0}+ onClick={() => setPendingDelete(deletableSelection())}+ className={cn(+ BAR_PILL,+ "border border-red-500/70 text-red-600 transition-colors hover:bg-red-500/15 dark:text-red-400",+ )}+ >+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-4" />+ {t("common.delete")}+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={t("library.menu.moreActions")}+ className={cn(BAR_ROUND, "data-[state=open]:bg-sidebar-accent")}+ >+ <HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="center" side="top" className="w-48">+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-2.5">+ <HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />+ {t("library.selection.move")}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-[min(--spacing(80),var(--radix-dropdown-menu-content-available-height))] w-56">+ <DropdownMenuItem onSelect={() => bulkMove(null)}>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ {t("library.menu.noFolder")}+ </DropdownMenuItem>+ {bulkDestinations().map((folder) => (+ <DropdownMenuItem key={folder.id} onSelect={() => bulkMove(folder.id)}>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-icon" />+ <span className="truncate">{folder.name}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuContent>+ </DropdownMenu>+ <button+ type="button"+ aria-label={t("library.selection.clear")}+ onClick={() => setSelection(new Set())}+ className={BAR_ROUND}+ >+ <HugeiconsIcon icon={Cancel01Icon} strokeWidth={1.75} className="size-5" />+ </button>+ </div>+ )}+ </main>++ <NameDialog+ open={nameDialog !== null}+ {...nameDialogProps}+ onSubmit={submitName}+ onOpenChange={(open) => !open && setNameDialog(null)}+ />+ <ConfirmDeleteDialog+ open={pendingDelete !== null}+ title={deleteText?.title ?? ""}+ description={deleteText?.description ?? ""}+ confirmLabel={t("common.delete")}+ onConfirm={() => pendingDelete && void confirmDelete(pendingDelete)}+ onOpenChange={(open) => !open && setPendingDelete(null)}+ />+ <LibraryPreview+ item={previewItem}+ onOpenChange={(open) => !open && closePreview()}+ onChat={chatAbout}+ onDownload={(item) => void downloadLibraryItem(item)}+ onOpenThread={(threadId) => void navigate({ to: "/chat", search: { thread: threadId } })}+ onToggleFavorite={actions.toggleFavorite}+ onDelete={(item) => actions.remove({ kind: "item", item })}+ onSaved={() => void refresh()}+ />+ </LibraryActionsProvider>+ );+}diff --git a/studio/frontend/src/features/library/note-text.ts b/studio/frontend/src/features/library/note-text.tsnew file mode 100644index 00000000000..30c625e64f5--- /dev/null+++ b/studio/frontend/src/features/library/note-text.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++export type NoteEncoding = "utf-8" | "utf-16le" | "utf-16be";++export interface NoteFormat {+ encoding: NoteEncoding;+ /** The file started with a byte order mark, which a save must keep. */+ bom: boolean;+ eol: "\n" | "\r\n";+}++export type NoteReadOnlyReason = "utf16" | "notUtf8";++export interface DecodedNote {+ text: string;+ format: NoteFormat;+ readOnlyReason: NoteReadOnlyReason | null;+}++function detectEncoding(bytes: Uint8Array): { encoding: NoteEncoding; bom: boolean } {+ if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {+ return { encoding: "utf-8", bom: true };+ }+ if (bytes[0] === 0xff && bytes[1] === 0xfe) return { encoding: "utf-16le", bom: true };+ if (bytes[0] === 0xfe && bytes[1] === 0xff) return { encoding: "utf-16be", bom: true };+ return { encoding: "utf-8", bom: false };+}++/**+ * Decode a file's bytes, or the first of them when `truncated`, where a character cut at the end is+ * dropped rather than read as corrupt. The BOM decides the encoding; with none the file must be+ * valid UTF-8 to be editable, since saving a legacy code page as UTF-8 would rewrite every accented+ * letter in it.+ */+export function decodeNote(bytes: Uint8Array, truncated = false): DecodedNote {+ const { encoding, bom } = detectEncoding(bytes);+ let raw: string;+ let readOnlyReason: NoteReadOnlyReason | null = null;+ try {+ raw = new TextDecoder(encoding, { fatal: true }).decode(bytes, { stream: truncated });+ } catch {+ raw = new TextDecoder(encoding).decode(bytes, { stream: truncated });+ readOnlyReason = encoding === "utf-8" ? "notUtf8" : "utf16";+ }+ const crlf = raw.match(/\r\n/g)?.length ?? 0;+ const lf = (raw.match(/\n/g)?.length ?? 0) - crlf;+ return {+ text: raw.replace(/\r\n/g, "\n"),+ format: { encoding, bom, eol: crlf > lf ? "\r\n" : "\n" },+ readOnlyReason,+ };+}++export function encodeNote(text: string, format: NoteFormat): string {+ const lines = text.replace(/\r\n/g, "\n");+ const body = format.eol === "\r\n" ? lines.replace(/\n/g, "\r\n") : lines;+ return format.bom ? `\uFEFF${body}` : body;+}diff --git a/studio/frontend/src/features/library/object-url-cache.ts b/studio/frontend/src/features/library/object-url-cache.tsnew file mode 100644index 00000000000..70e711d93d4--- /dev/null+++ b/studio/frontend/src/features/library/object-url-cache.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Thumbnails are auth-fetched blobs, so the browser cache cannot hold them. The most recent stay as+// object URLs within a count and a byte budget, so a revisit paints at once. An entry a card still+// shows (or waits on) is never evicted, since its URL would be revoked under it.++const MAX_CACHED_URLS = 300;+const MAX_CACHED_BYTES = 128 * 1024 * 1024;++interface Entry {+ url: Promise<string>;+ bytes: number;+ users: number;+}++const objectUrls = new Map<string, Entry>();+let cachedBytes = 0;++function revoke(entry: Entry): void {+ void entry.url.then((url) => URL.revokeObjectURL(url), () => {});+}++export function clearCachedObjectUrls(): void {+ objectUrls.forEach(revoke);+ objectUrls.clear();+ cachedBytes = 0;+}++function evict(key: string): void {+ const entry = objectUrls.get(key);+ if (!entry) return;+ objectUrls.delete(key);+ cachedBytes -= entry.bytes;+ revoke(entry);+}++function trim(): void {+ for (const [key, entry] of objectUrls) {+ if (objectUrls.size <= MAX_CACHED_URLS && cachedBytes <= MAX_CACHED_BYTES) return;+ if (entry.users === 0) evict(key);+ }+}++export function acquireObjectUrl(+ key: string,+ load: () => Promise<Blob>,+): { url: Promise<string>; release: () => void } {+ let entry = objectUrls.get(key);+ if (entry) {+ objectUrls.delete(key);+ } else {+ const created: Entry = { url: Promise.resolve(""), bytes: 0, users: 0 };+ created.url = load().then((blob) => {+ if (objectUrls.get(key) === created) {+ created.bytes = blob.size;+ cachedBytes += blob.size;+ }+ return URL.createObjectURL(blob);+ });+ created.url.then(trim, () => objectUrls.get(key) === created && evict(key));+ entry = created;+ }+ objectUrls.set(key, entry);+ const held = entry;+ held.users += 1;+ trim();+ let released = false;+ return {+ url: held.url,+ release: () => {+ if (released) return;+ released = true;+ held.users -= 1;+ if (held.users === 0) trim();+ },+ };+}++export function cachedObjectUrlCount(): number {+ return objectUrls.size;+}diff --git a/studio/frontend/src/features/library/reveal-label.ts b/studio/frontend/src/features/library/reveal-label.tsnew file mode 100644index 00000000000..5b2b8812b1c--- /dev/null+++ b/studio/frontend/src/features/library/reveal-label.ts@@ -0,0 +1,27 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++const LABELS = {+ finder: "library.reveal.finder",+ explorer: "library.reveal.explorer",+ files: "library.reveal.files",+} as const;++export function isLoopbackHost(hostname: string): boolean {+ const host = hostname.toLowerCase().replace(/^\[(.*)\]$/, "$1").replace(/\.$/, "");+ if (host === "localhost" || host.endsWith(".localhost")) return true;+ if (/^127(\.\d{1,3}){3}$/.test(host) || host === "0.0.0.0") return true;+ if (host === "::1" || host === "::" || host === "0:0:0:0:0:0:0:1") return true;+ return /^::ffff:(127(\.\d{1,3}){3}|7f[0-9a-f]{2}:[0-9a-f]{1,4})$/.test(host);+}++export function revealLabelFor(+ fileManager: keyof typeof LABELS | null | undefined,+ deviceType: string,+): (typeof LABELS)[keyof typeof LABELS] | null {+ if (fileManager === null) return null;+ if (fileManager) return LABELS[fileManager];+ if (deviceType === "mac") return LABELS.finder;+ return deviceType === "windows" ? LABELS.explorer : LABELS.files;+}diff --git a/studio/frontend/src/features/library/reveal.ts b/studio/frontend/src/features/library/reveal.tsnew file mode 100644index 00000000000..f0682306242--- /dev/null+++ b/studio/frontend/src/features/library/reveal.ts@@ -0,0 +1,33 @@+// 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 { usePlatformStore } from "@/config/env";+import { useIsAccountOwner } from "@/features/auth";+import { isTauri } from "@/lib/api-base";+import { translate, useT } from "@/i18n";+import { toast } from "@/lib/toast";+import { type LibraryItem, errorMessage, revealLibraryItem } from "./api";+import { isLoopbackHost, revealLabelFor } from "./reveal-label";++export function useRevealLabel(): string | null {+ const t = useT();+ const owner = useIsAccountOwner();+ const deviceType = usePlatformStore((s) => s.deviceType);+ const fileManager = usePlatformStore((s) => s.fileManager);+ const local = isTauri || isLoopbackHost(window.location.hostname);+ if (!owner || !local) return null;+ const key = revealLabelFor(fileManager, deviceType);+ return key && t(key);+}++export function canReveal(item: LibraryItem): boolean {+ return !item.id.startsWith("attachment:");+}++export function revealInFolder(id: string): void {+ revealLibraryItem(id).catch((error: unknown) =>+ toast.error(translate("library.toast.revealFailed"), {+ description: errorMessage(error),+ }),+ );+}diff --git a/studio/frontend/src/features/library/search.ts b/studio/frontend/src/features/library/search.tsnew file mode 100644index 00000000000..17922c37619--- /dev/null+++ b/studio/frontend/src/features/library/search.ts@@ -0,0 +1,29 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export const LIBRARY_TABS = [+ "suggested",+ "favorites",+ "folders",+ "images",+ "videos",+ "audio",+ "models",+ "all",+] as const;+export type LibraryTab = (typeof LIBRARY_TABS)[number];++export interface LibrarySearch {+ show?: LibraryTab;+ folder?: string;+ item?: string;+}++export function validateLibrarySearch(search: Record<string, unknown>): LibrarySearch {+ const show = LIBRARY_TABS.find((entry) => entry === search.show);+ return {+ ...(show ? { show } : {}),+ ...(typeof search.folder === "string" ? { folder: search.folder } : {}),+ ...(typeof search.item === "string" ? { item: search.item } : {}),+ };+}diff --git a/studio/frontend/src/features/library/store.ts b/studio/frontend/src/features/library/store.tsnew file mode 100644index 00000000000..a707b184735--- /dev/null+++ b/studio/frontend/src/features/library/store.ts@@ -0,0 +1,279 @@+// 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 { AUTH_SESSION_CLEARED_EVENT, getAuthSessionEpoch } from "@/features/auth";+import { emitChatAttachmentDeleted } from "@/features/chat";+import { translate } from "@/i18n";+import { type GalleryKind, notifyGalleryChanged } from "@/lib/gallery-flags";+import {+ type LibraryFolder,+ type LibraryItem,+ type LibraryUploadBatch,+ createLibraryFolder,+ deleteLibraryFolder,+ deleteLibraryItem,+ errorMessage,+ getLibrary,+ updateLibraryFolder,+ updateLibraryItem,+ uploadLibraryFiles,+} from "./api";+import { useLibraryFavoritesStore } from "./favorites-store";+import { clearCachedObjectUrls } from "./object-url-cache";++type ItemPatch = { name?: string; favorite?: boolean; folderId?: string | null };+type FolderPatch = { name?: string; parentId?: string | null };++interface LibraryState {+ items: LibraryItem[];+ folders: LibraryFolder[];+ status: "idle" | "loading" | "ready" | "error";+ error: string | null;+ refresh: () => Promise<void>;+ patchItem: (id: string, patch: ItemPatch) => Promise<void>;+ removeItem: (id: string, fingerprint: string | undefined) => Promise<void>;+ upload: (batch: LibraryUploadBatch, folderId: string | null) => Promise<string[]>;+ addFolder: (name: string, parentId: string | null) => Promise<LibraryFolder>;+ patchFolder: (id: string, patch: FolderPatch) => Promise<void>;+ removeFolder: (id: string) => Promise<void>;+}++const GALLERIES: Record<string, GalleryKind> = { image: "images", video: "videos", audio: "audio" };++let refreshGeneration = 0;+let snapshots = 0;++function undoEdit<T extends { id: string }>(now: T[], before: T[], after: T[] | undefined): T[] {+ if (!after) return now;+ const edited = new Map(after.map((entry) => [entry.id, entry]));+ const prior = new Map(+ before.filter((entry) => edited.get(entry.id) !== entry).map((entry) => [entry.id, entry]),+ );+ const restored = now.map((entry) => {+ const was = prior.get(entry.id);+ const made = edited.get(entry.id);+ if (!was || !made) return entry;+ let undone = entry;+ for (const key of new Set([...Object.keys(was), ...Object.keys(made)]) as Set<keyof T>) {+ if (made[key] !== was[key] && entry[key] === made[key]) {+ undone = { ...undone, [key]: was[key] };+ }+ }+ return undone;+ });+ const present = new Set(now.map((entry) => entry.id));+ for (const entry of prior.values()) {+ if (!edited.has(entry.id) && !present.has(entry.id)) {+ restored.splice(Math.min(before.indexOf(entry), restored.length), 0, entry);+ }+ }+ return restored;+}++// Edits apply here before the server has them, so a snapshot fetched while one is in flight, or+// started before one, can predate it and would undo it on screen. Such a snapshot is dropped and+// fetched again once every edit has settled; a failed edit rolls back the same way. A sign-out+// starts the count again: an edit of the account that left must not hold back the next one's.+let session = 0;+let inFlight = 0;+let edits = 0;+let stale = false;+let undos: (() => void)[] = [];++export const useLibraryStore = create<LibraryState>((set, get) => {+ async function optimistic(+ apply: (state: LibraryState) => Partial<LibraryState>,+ request: () => Promise<void>,+ undoElsewhere?: () => void,+ ): Promise<void> {+ const before = get();+ const after = apply(before);+ const epoch = getAuthSessionEpoch();+ const started = session;+ set(after);+ edits += 1;+ inFlight += 1;+ try {+ await request();+ } catch (error) {+ if (started === session) {+ stale = true;+ undos.push(() => {+ if (getAuthSessionEpoch() !== epoch) return;+ set((state) => ({+ items: undoEdit(state.items, before.items, after.items),+ folders: undoEdit(state.folders, before.folders, after.folders),+ }));+ undoElsewhere?.();+ });+ }+ throw error;+ } finally {+ if (started === session) inFlight -= 1;+ if (started === session && inFlight === 0 && stale) {+ stale = false;+ const pending = undos;+ undos = [];+ const landed = snapshots;+ await get().refresh();+ if (snapshots === landed) for (const undo of pending.reverse()) undo();+ }+ }+ }++ return {+ items: [],+ folders: [],+ status: "idle",+ error: null,+ refresh: async () => {+ const generation = ++refreshGeneration;+ const editsBefore = edits;+ const favoritesStart = useLibraryFavoritesStore.getState().begin();+ if (get().status === "idle") set({ status: "loading" });+ try {+ const { items, folders } = await getLibrary();+ if (generation !== refreshGeneration) return;+ if (inFlight > 0) {+ stale = true;+ return;+ }+ if (edits !== editsBefore) return get().refresh();+ const favorites = useLibraryFavoritesStore.getState().adopt(+ favoritesStart,+ new Set(items.filter((item) => item.favorite).map((item) => item.id)),+ );+ snapshots += 1;+ set({+ items: items.map((item) =>+ favorites.has(item.id) === item.favorite+ ? item+ : { ...item, favorite: !item.favorite },+ ),+ folders,+ status: "ready",+ error: null,+ });+ } catch (error) {+ if (generation !== refreshGeneration) return;+ set({+ status: get().status === "ready" ? "ready" : "error",+ error: errorMessage(error),+ });+ }+ },+ patchItem: (id, patch) => {+ const star =+ patch.favorite !== undefined+ ? useLibraryFavoritesStore.getState().mark(id, patch.favorite)+ : undefined;+ return optimistic(+ (state) => ({+ items: state.items.map((item) =>+ item.id === id ? { ...item, ...patch } : item,+ ),+ }),+ () => updateLibraryItem(id, patch).finally(star?.settle),+ star?.undo,+ );+ },+ // The fingerprint the confirmation was opened on: a refresh since may list a replacement file.+ removeItem: (id, fingerprint) => {+ return optimistic(+ (state) => ({ items: state.items.filter((item) => item.id !== id) }),+ async () => {+ const epoch = getAuthSessionEpoch();+ await deleteLibraryItem(id, fingerprint);+ if (getAuthSessionEpoch() !== epoch) return;+ const [kind, messageId, ...rest] = id.split(":");+ const gallery = GALLERIES[kind];+ if (gallery) notifyGalleryChanged(gallery);+ if (kind === "attachment" && messageId && rest.length > 0) {+ emitChatAttachmentDeleted({+ messageId: decodeURIComponent(messageId),+ attachmentId: rest.join(":"),+ });+ }+ },+ );+ },+ upload: async (batch, folderId) => {+ try {+ return await uploadLibraryFiles(batch, folderId);+ } finally {+ await get().refresh();+ }+ },+ addFolder: async (name, parentId) => {+ const epoch = getAuthSessionEpoch();+ const folder = await createLibraryFolder(name, parentId);+ if (getAuthSessionEpoch() !== epoch) {+ throw new Error(translate("library.toast.signedOutBeforeFolder"));+ }+ edits += 1;+ set((state) => ({+ folders: [folder, ...state.folders.filter((f) => f.id !== folder.id)],+ }));+ return folder;+ },+ patchFolder: (id, patch) =>+ optimistic(+ (state) => ({+ folders: state.folders.map((folder) =>+ folder.id === id+ ? { ...folder, ...patch, updatedAt: Date.now() }+ : folder,+ ),+ }),+ () => updateLibraryFolder(id, patch),+ ),+ removeFolder: (id) =>+ optimistic(+ (state) => {+ const parentId =+ state.folders.find((folder) => folder.id === id)?.parentId ?? null;+ return {+ folders: state.folders+ .filter((folder) => folder.id !== id)+ .map((folder) =>+ folder.parentId === id ? { ...folder, parentId } : folder,+ ),+ items: state.items.map((item) =>+ item.folderId === id ? { ...item, folderId: parentId } : item,+ ),+ };+ },+ () => deleteLibraryFolder(id),+ ),+ };+});++// The store is module state, so a sign-out must drop it or the next account sees these files.+if (typeof window !== "undefined") {+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, () => {+ refreshGeneration += 1;+ session += 1;+ inFlight = 0;+ stale = false;+ undos = [];+ useLibraryStore.setState({ items: [], folders: [], status: "idle", error: null });+ clearCachedObjectUrls();+ });+}++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/library/surface.ts b/studio/frontend/src/features/library/surface.tsnew file mode 100644index 00000000000..ffebf04bb82--- /dev/null+++ b/studio/frontend/src/features/library/surface.ts@@ -0,0 +1,13 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export const RAISED_SURFACE =+ "bg-white shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:bg-card dark:shadow-none";++export const OVERLAY_CONTROL =+ "bg-white shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:bg-neutral-700 dark:shadow-none";++export const GLASS_SURFACE =+ "bg-white/60 text-neutral-900 shadow-none ring-1 ring-white/50 backdrop-blur-md dark:bg-black/40 dark:text-white dark:ring-white/20";++export const GLASS_CONTROL = `${GLASS_SURFACE} hover:bg-white/80 hover:text-neutral-900 dark:hover:bg-black/55 dark:hover:text-white`;diff --git a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts b/studio/frontend/src/features/profile/hooks/use-personalization-sync.tsindex ed781d0bc8c..d8ebed64786 100644--- a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts+++ b/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts@@ -38,9 +38,7 @@ const PUSH_DEBOUNCE_MS = 800;// Version 2 payloads store the language preference ("auto" or a pinned locale). Version 1 always// serialized the resolved locale, so its "en" is usually the old default rather than an explicit// pick. Version 3 migrates untouched sidebar layouts to keep Video under More. Version 4 pins Video-// under Images. Without this bump a synced profile rehydrates its stored layout over the local-// migration.-const PERSONALIZATION_VERSION = 4;+const PERSONALIZATION_VERSION = 5;type ProfileSnapshot = {displayName: string;diff --git a/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx b/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsxindex fea428ffc4d..c45d37fbec1 100644--- a/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx+++ b/studio/frontend/src/features/settings/components/sidebar-nav-customizer.tsx@@ -11,6 +11,7 @@ import {Folder01Icon,Globe02Icon,Image03Icon,+ LibrariesIcon,MoreHorizontalIcon,PencilEdit02Icon,} from "@hugeicons/core-free-icons";@@ -35,6 +36,7 @@ const ITEM_META: Record<{ icon: IconSvgElement; labelKey: TranslationKey }> = {projects: { icon: Folder01Icon, labelKey: "shell.navigation.projects" },+ library: { icon: LibrariesIcon, labelKey: "shell.navigation.library" },hub: { icon: DashboardCircleIcon, labelKey: "shell.navigation.hub" },images: { icon: Image03Icon, labelKey: "shell.navigation.images" },train: { icon: TestTubeOutlineIcon, labelKey: "shell.navigation.train" },diff --git a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts b/studio/frontend/src/features/settings/stores/appearance-custom-store.tsindex b2cdd713cd6..ebc95a0f091 100644--- a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts+++ b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts@@ -92,6 +92,7 @@ export const SIDEBAR_NAV_ITEM_IDS = [// Model hub leads: picking a model comes before the work that uses one."hub","projects",+ "library","images",// Video and Audio sit directly under Images: the media tabs read as one group."video",@@ -140,9 +141,9 @@ export function sidebarNavAutoAfterChoice(export const SIDEBAR_NAV_DEFAULT_PINNED: Record<SidebarNavItemId, boolean> = {hub: true,projects: true,+ library: true,images: true,- video: true,- // Under "More" until a user pins it.+ video: false,audio: false,train: true,recipes: false,@@ -153,7 +154,7 @@ export const SIDEBAR_NAV_DEFAULT_PINNED: Record<SidebarNavItemId, boolean> = {/** Every previously shipped layout, so a migration can tell an untouched install from one the* user arranged themselves. v3 pinned Video under Images; v4 moved Model hub above Projects;* v5 put Video back under "More" and later added API before Audio shipped; v6 added Audio;- * v7 pins Video under Images again. */+ * v7 pins Video under Images again; v8 adds Library under Projects and moves Video to "More". */const SHIPPED_SIDEBAR_NAV_DEFAULTS: SidebarNavItemPref[][] = [[{ id: "projects", pinned: true },@@ -203,6 +204,17 @@ const SHIPPED_SIDEBAR_NAV_DEFAULTS: SidebarNavItemPref[][] = [{ id: "export", pinned: false },{ id: "api", pinned: false },],+ [+ { id: "hub", pinned: true },+ { id: "projects", pinned: true },+ { id: "images", pinned: true },+ { id: "video", pinned: true },+ { id: "audio", pinned: false },+ { id: "train", pinned: true },+ { id: "recipes", pinned: false },+ { id: "export", pinned: false },+ { id: "api", pinned: false },+ ],];export const MAX_IMPORTED_FONTS = 3;@@ -589,14 +601,14 @@ export const useAppearanceCustomStore = create<AppearanceCustomState>()(}),{name: "unsloth_appearance_customization",- version: 7,+ version: 8,storage: createJSONStorage(() => guardedLocalStorage),migrate: (persisted, version) => {const state = (persisted ?? {}) as Partial<AppearanceCustomState>;const customization = migrateShippedSidebarNavDefault(sanitizeCustomization(state.customization),version,- 7,+ 8,);return { customization } as AppearanceCustomState;},diff --git a/studio/frontend/src/features/studio/studio-page.tsx b/studio/frontend/src/features/studio/studio-page.tsxindex 49821d0c271..1d2601703b8 100644--- a/studio/frontend/src/features/studio/studio-page.tsx+++ b/studio/frontend/src/features/studio/studio-page.tsx@@ -16,9 +16,8 @@ import {} from "@/features/training";import { useT } from "@/i18n";import { MediaPageLink } from "@/components/media-page-link";-import { useImageWorkflowStore } from "@/features/images/stores/image-workflow-store";import {- Image03Icon,+ LibrariesIcon,} from "@hugeicons/core-free-icons";import {ChevronLeftIcon,@@ -215,17 +214,14 @@ export function StudioPage(): ReactElement {trainingRunActive={trainingRunActive}showTrainingView={showTrainingView}/>- {/* Image training is a mode of the Images page, not a route, so it sits- beside the sub-nav rather than in it. */}+ {/* Finished runs land in the Library's Fine-tunes tab. */}<div className="ml-auto flex items-center gap-2 pb-2"><MediaPageLink- to="/images"- label={t("studio.imageTraining")}- tooltip={t("studio.goToImageTraining")}- icon={Image03Icon}- onNavigate={() =>- useImageWorkflowStore.getState().setPageMode("train")- }+ to="/library"+ libraryTab="models"+ label={t("shell.navigation.library")}+ tooltip={t("studio.goToLibrary")}+ icon={LibrariesIcon}/></div></div>diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex ad68872b877..a7ca4e49337 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -8,7 +8,6 @@ import {Download01Icon,FlimSlateIcon,ImageCropIcon,- Image03Icon,InformationCircleIcon,} from "@hugeicons/core-free-icons";import { Volume02Icon } from "@/lib/volume-icons";@@ -21,7 +20,9 @@ import { MEDIA_RAIL_ROOT_ATTR, useMediaRailWidth } from "@/hooks/use-media-rail-import { StripDropLine } from "@/components/gallery-strip-reorder";import { useStripReorder } from "@/hooks/use-strip-reorder";import { ImageDropzone } from "@/components/image-dropzone";-import { MediaPageLink } from "@/components/media-page-link";+import { LibraryPageLink } from "@/components/media-page-link";+import { translate } from "@/i18n";+import { useLibraryFavorites } from "@/features/library";import { GuidedTour, useGuidedTourController } from "@/features/tour";import { videoTourSteps } from "./tour";import { useSettingsDialogStore } from "@/features/settings/stores/settings-dialog-store";@@ -153,6 +154,7 @@ import {isDownloadCancelled,} from "@/lib/native-files";import { toast } from "@/lib/toast";+import { loadGalleryUntil } from "@/lib/gallery-deep-link";import { subscribeModelEjected } from "@/lib/model-lifecycle-events";import { BlobUrlCache } from "@/lib/blob-url-cache";@@ -1926,6 +1928,7 @@ function VideoGenerator({// The pin state each id was last CLICKED into, so a failing request can tell whether it is// still the current intent; without it a slow failure rolls back a later success.+ const { isFavorite, toggleFavorite } = useLibraryFavorites();const pinAttempt = useRef(new Map<string, number>());const pinSeq = useRef(0);@@ -2940,6 +2943,37 @@ function VideoGenerator({videoPresets.hydrated,]);+ // A Library "View in" link arrives as ?item=: select that clip, paging back until it loads. A+ // counter, not effect cleanup, retires a lookup: clearing the query must not cancel its own.+ const routedItem = active ? routeSearch?.item : undefined;+ const routedLookup = useRef(0);+ useEffect(() => {+ if (!active) routedLookup.current += 1;+ }, [active]);+ useEffect(() => {+ if (!routedItem) return;+ const lookup = ++routedLookup.current;+ void navigateSelf({ to: "/video", search: {}, replace: true });+ void loadGalleryUntil({+ has: () => galleryCache.videos.some((entry) => entry.id === routedItem),+ count: () => galleryCache.videos.length,+ hasMore: () => galleryCache.hasMore,+ refresh: loadGallery,+ loadMore,+ busy: () => loadingMore.current,+ cancelled: () => lookup !== routedLookup.current,+ }).then((found) => {+ if (lookup !== routedLookup.current) return;+ if (found) {+ setSelectedId(routedItem);+ } else {+ toast(translate("library.toast.clipNotFound"), {+ description: translate("library.toast.notFoundDescription"),+ });+ }+ });+ }, [routedItem, navigateSelf, loadGallery, loadMore]);+// The task dialog defers the load out of the branch that snapshotted the rollback, so the two// ways out carry that branch's two endings: choosing runs the load and reverts if it never@@ -3638,11 +3672,9 @@ function VideoGenerator({)}</div><div className="pointer-events-auto flex shrink-0 items-center gap-2">- {/* Images is a separate page, so it sits out here, not in this page's controls. */}- <MediaPageLink- to="/images"- label="Images"- icon={Image03Icon}+ {/* A separate page, so it sits outside this page's controls. */}+ <LibraryPageLink+ tab="videos"labelClassName="@max-[30rem]:hidden"arrowClassName="@max-[30rem]:hidden"/>@@ -4279,6 +4311,8 @@ function VideoGenerator({active={active}pinned={Boolean(selected.pinned)}archived={Boolean(selected.archived)}+ favorite={isFavorite(`video:${selected.id}`)}+ onToggleFavorite={() => toggleFavorite(`video:${selected.id}`)}onTogglePin={() =>void handleTogglePin(selected.id, !selected.pinned)}@@ -4431,6 +4465,8 @@ function VideoGenerator({active={active}pinned={Boolean(video.pinned)}archived={Boolean(video.archived)}+ favorite={isFavorite(`video:${video.id}`)}+ onToggleFavorite={() => toggleFavorite(`video:${video.id}`)}onTogglePin={() => void handleTogglePin(video.id, !video.pinned)}onToggleArchive={() => void handleArchive(video.id)}onDelete={() => void handleDelete(video.id)}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex caead82dbb9..9ca2670fbbe 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -156,6 +156,7 @@ export const ar = {search: "بحث",hub: "مركز النماذج",projects: "المشاريع",+ library: "المكتبة",train: "تدريب",recipes: "الوصفات",images: "الصور",@@ -2140,8 +2141,7 @@ export const ar = {},},studio: {- imageTraining: "تدريب الصور",- goToImageTraining: "الانتقال إلى تدريب الصور",+ goToLibrary: "الانتقال إلى المكتبة",routeTitle: "تدريب",wizard: {modelTitle: "النموذج",@@ -2860,4 +2860,235 @@ export const ar = {updateError: "تعذّر تحديث المهارة",mentions: "المهارات",},+ library: {+ tabs: {+ ariaLabel: "أقسام المكتبة",+ suggested: "مقترحة",+ favorites: "المفضلة",+ folders: "المجلدات",+ images: "الصور",+ videos: "الفيديوهات",+ audio: "الصوت",+ models: "النماذج المضبوطة",+ all: "الكل",+ },+ empty: {+ suggestedTitle: "مكتبتك فارغة",+ suggestedDescription: "تظهر هنا الملفات التي ترفعها أو تنشئها في المحادثات.",+ favoritesTitle: "لا توجد عناصر مفضلة بعد",+ favoritesDescription: "أضف الملفات إلى المفضلة للعثور عليها هنا بسرعة.",+ foldersTitle: "أنشئ أول مجلد لك",+ foldersDescription: "أنشئ مجلدات لتنظيم العناصر في مكتبتك.",+ imagesTitle: "لا توجد صور بعد",+ imagesDescription: "تظهر هنا الصور التي ترفعها أو تنشئها.",+ videosTitle: "لا توجد فيديوهات بعد",+ videosDescription: "تظهر هنا الفيديوهات التي ترفعها أو تنشئها.",+ audioTitle: "لا يوجد صوت بعد",+ audioDescription: "يظهر هنا الكلام الذي تنشئه في صفحة الصوت.",+ modelsTitle: "لا توجد نماذج مضبوطة بعد",+ modelsDescription: "تظهر هنا النماذج التي تدربها أو تصدّرها في Unsloth.",+ createFolder: "إنشاء مجلد",+ generateVideo: "إنشاء فيديو",+ generateAudio: "إنشاء صوت",+ trainModel: "تدريب نموذج",+ uploadFiles: "رفع ملفات",+ dropHere: "أو أفلت الملفات هنا",+ noMatchesTitle: "لا توجد نتائج مطابقة",+ noMatchesDescription: "جرّب بحثًا مختلفًا أو امسح عوامل التصفية.",+ loadErrorTitle: "تعذّر تحميل مكتبتك",+ loadErrorFallback: "حدث خطأ ما.",+ tryAgain: "إعادة المحاولة",+ },+ sections: {+ items: "العناصر",+ },+ breadcrumb: "مسار التنقل",+ searchLibrary: "البحث في المكتبة",+ searchFolder: "البحث في المجلد",+ dropToUpload: "أفلت للرفع",+ dropToUploadInto: 'أفلت للرفع إلى "{folder}"',+ itemCountOne: "عدد العناصر: {count}",+ itemCount: "عدد العناصر: {count}",+ selectItem: "تحديد {name}",+ selection: {+ startChat: "بدء محادثة",+ move: "نقل",+ clear: "مسح التحديد",+ },+ menu: {+ moreActions: "إجراءات أخرى",+ chatAboutThis: "الدردشة حول هذا",+ chatWithModel: "الدردشة مع هذا النموذج",+ addToFavorites: "إضافة إلى المفضلة",+ removeFromFavorites: "إزالة من المفضلة",+ download: "تنزيل",+ addToFolder: "إضافة إلى مجلد",+ newFolder: "مجلد جديد",+ noFolder: "المكتبة (بدون مجلد)",+ deleteFolder: "حذف المجلد",+ },+ reveal: {+ finder: "الإظهار في Finder",+ explorer: "الإظهار في Explorer",+ files: "الإظهار في المجلد",+ },+ toolbar: {+ filter: "تصفية",+ source: "المصدر",+ fileType: "نوع الملف",+ clearFilters: "مسح عوامل التصفية",+ uploaded: "مرفوعة",+ generated: "منشأة",+ documents: "المستندات",+ spreadsheets: "جداول البيانات",+ presentations: "العروض التقديمية",+ pdfs: "ملفات PDF",+ gridView: "عرض الشبكة",+ listView: "عرض القائمة",+ settings: "إعدادات المكتبة",+ },+ create: {+ note: "ملاحظة",+ image: "صورة",+ video: "فيديو",+ audio: "صوت",+ model: "نموذج",+ folder: "مجلد",+ untitledNote: "ملاحظة بلا عنوان",+ },+ list: {+ selectAll: "تحديد الكل",+ name: "الاسم",+ lastActivity: "آخر نشاط",+ favorite: "مفضلة",+ modified: "عُدّل {time}",+ justNow: "للتوّ",+ },+ size: {+ bytes: "{value} بايت",+ kilobytes: "{value} كيلوبايت",+ megabytes: "{value} م.ب",+ gigabytes: "{value} غ.ب",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "ضبط دقيق كامل",+ loraExport: "تصدير LoRA",+ mergedExport: "تصدير مدمج",+ ggufExport: "تصدير GGUF",+ model: "نموذج",+ },+ dialog: {+ create: "إنشاء",+ renameFolder: "إعادة تسمية المجلد",+ renameFile: "إعادة تسمية الملف",+ deleteTitle: 'حذف "{name}"؟',+ deleteManyTitle: "حذف {count} من العناصر؟",+ deleteManyDescription: "تُحذف الملفات من أماكن حفظها. وينتقل ما بداخل المجلد المحذوف مستوى واحدًا إلى الأعلى.",+ deleteFolderIntoParent: 'ينتقل كل ما بداخله إلى "{folder}". لن يُحذف أي ملف.',+ deleteFolderIntoLibrary: "ينتقل كل ما بداخله إلى مكتبتك. لن يُحذف أي ملف.",+ deleteUpload: "سيؤدي هذا إلى حذف الملف نهائيًا.",+ deleteAttachment: "ستتم إزالته أيضًا من المحادثة التي كان مرفقًا بها.",+ deleteImage: "ستتم إزالته أيضًا من معرض الصور.",+ deleteVideo: "ستتم إزالته أيضًا من معرض الفيديو.",+ deleteAudio: "ستتم إزالته أيضًا من معرض الصوت.",+ deleteSandbox: "ستتم إزالته أيضًا من المحادثة التي أنشأته.",+ unsavedTitle: "لم تُحفظ تغييراتك",+ unsavedDescription: "{reason} أعد المحاولة، أو تجاهل تغييراتك لإغلاق الملف.",+ keepEditing: "متابعة التحرير",+ discardChanges: "تجاهل التغييرات",+ },+ preview: {+ code: "الكود",+ preview: "معاينة",+ viewOriginalChat: "عرض المحادثة الأصلية",+ viewInImages: "العرض في الصور",+ viewInVideo: "العرض في الفيديو",+ viewInAudio: "العرض في الصوت",+ cannotPreview: "تتعذّر معاينة هذا الملف هنا. نزّله لفتحه.",+ noPreview: "لا تتوفر معاينة لهذا النوع من الملفات.",+ tooLargeToPreview: "هذا الملف أكبر من أن تتم معاينته هنا. نزّله لفتحه.",+ startWriting: "ابدأ الكتابة…",+ type: "النوع",+ baseModel: "النموذج الأساسي",+ size: "الحجم",+ location: "الموقع",+ unknown: "غير معروف",+ readOnlyUtf16: "هذا الملف ليس نصًا صالحًا بترميز UTF-16، لذا يُفتح هنا للقراءة فقط.",+ readOnlyNotUtf8: "هذا الملف ليس نصًا بترميز UTF-8، لذا يُفتح هنا للقراءة فقط. قد لا تظهر بعض الأحرف بشكل صحيح.",+ },+ viewer: {+ scale: "التكبير",+ fit: "ملاءمة",+ moreActionsImage: "إجراءات أخرى لهذه الصورة",+ moreActionsVideo: "إجراءات أخرى لهذا الفيديو",+ moreActionsClip: "إجراءات أخرى لهذا المقطع",+ moreActionsFile: "إجراءات أخرى لهذا الملف",+ },+ project: {+ label: "المشروع",+ newProject: "مشروع جديد",+ noProjects: "لا توجد مشاريع بعد",+ alreadyIn: "موجود بالفعل في {project}",+ addedTo: "تمت الإضافة إلى {project}",+ createAndAdd: "إنشاء وإضافة",+ addFailedImage: "تعذّرت إضافة الصورة إلى المشروع",+ addFailedVideo: "تعذّرت إضافة الفيديو إلى المشروع",+ addFailedClip: "تعذّرت إضافة المقطع إلى المشروع",+ addFailedFile: "تعذّرت إضافة الملف إلى المشروع",+ newProjectImage: "إضافة الصورة إلى مشروع جديد",+ newProjectVideo: "إضافة الفيديو إلى مشروع جديد",+ newProjectClip: "إضافة المقطع إلى مشروع جديد",+ newProjectFile: "إضافة الملف إلى مشروع جديد",+ },+ toast: {+ missingItem: "لم يعد هذا الملف موجودًا في المكتبة",+ moveFailed: "تعذّر النقل",+ movedToFolder: "تم النقل إلى {folder}",+ movedToLibrary: "تم النقل إلى المكتبة",+ folderFallback: "المجلد",+ favoritesFailed: "تعذّر تحديث المفضلة",+ addedToFavorites: "تمت الإضافة إلى المفضلة",+ removedFromFavorites: "تمت الإزالة من المفضلة",+ uploadingOne: "جارٍ رفع {name}…",+ uploadingMany: "جارٍ رفع الملفات ({count})…",+ uploadedOne: "تم رفع الملف",+ uploadedMany: "تم رفع الملفات ({count})",+ uploadFailed: "فشل الرفع",+ uploadTooLarge: "حجم {name} أكبر من 512 م.ب.",+ readDropsFailed: "تعذّرت قراءة الملفات المُفلتة",+ createNoteFailed: "تعذّر إنشاء الملاحظة",+ renameFailed: "تعذّرت إعادة التسمية",+ createFolderFailed: "تعذّر إنشاء المجلد",+ signedOutBeforeFolder: "تم تسجيل الخروج قبل إنشاء المجلد.",+ signedOutBeforeSave: "تم تسجيل الخروج قبل حفظ التغيير.",+ signedOutBeforeUpload: "تم تسجيل الخروج قبل اكتمال الرفع.",+ deleteFailed: "تعذّر حذف بعض العناصر",+ saveFailed: "تعذّر الحفظ",+ saveNoteFirst: "احفظ الملاحظة أولًا.",+ revealFailed: "تعذّر فتح مدير الملفات",+ downloadFailed: "تعذّر تنزيل {name}",+ downloadManyFailed: "تعذّر تنزيل الملفات",+ downloadingMany: "جارٍ تنزيل الملفات ({count})",+ downloadingManyDescription: "إذا طلب متصفحك ذلك، فاسمح لهذا الموقع بتنزيل ملفات متعددة.",+ preparingMany: "جارٍ تجهيز الملفات ({count})…",+ zipFileName: "ملفات المكتبة",+ nothingToChat: "لا يوجد ما يمكن الدردشة حوله بعد",+ emptyFolder: "لا يحتوي هذا المجلد على ملفات.",+ tooLargeOne: "حجم {name} أكبر من أن يُرفق",+ tooLargeMany: "هذه الملفات أكبر من أن تُرفق",+ attachedOne: "تم إرفاق {count} ملف",+ attachedMany: "تم إرفاق الملفات ({count})",+ skippedTooLarge: "ملفات أكبر من أن تُرفق: {count}.",+ skippedOverLimit: "ملفات إضافية تتجاوز حد {limit} ملفات: {count}.",+ chatFilesWaiting: "ستُرفق عند تحميل نموذج يمكنه قراءتها: {count}.",+ openFilesFailed: "تعذّر فتح الملفات",+ speechModel: "{name} نموذج كلام",+ speechModelDescription: "اختره من قائمة النماذج في صفحة الصوت.",+ noMediaLink: "لم يُرجع الخادم أي رابط لتشغيل هذا الملف.",+ imageNotFound: "تعذّر العثور على هذه الصورة",+ clipNotFound: "تعذّر العثور على هذا المقطع",+ notFoundDescription: "ربما تمت أرشفته أو حذفه.",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 3c245b803df..bdf41b465e2 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -159,6 +159,7 @@ export const de = {search: "Suchen",hub: "Modell-Hub",projects: "Projekte",+ library: "Bibliothek",train: "Trainieren",recipes: "Rezepte",images: "Bilder",@@ -2187,8 +2188,7 @@ export const de = {},},studio: {- imageTraining: "Bildtraining",- goToImageTraining: "Zum Bildtraining",+ goToLibrary: "Zur Bibliothek",routeTitle: "Trainieren",wizard: {modelTitle: "Modell",@@ -2929,4 +2929,235 @@ export const de = {updateError: "Fähigkeit konnte nicht aktualisiert werden",mentions: "Fähigkeiten",},+ library: {+ tabs: {+ ariaLabel: "Bereiche der Bibliothek",+ suggested: "Vorschläge",+ favorites: "Favoriten",+ folders: "Ordner",+ images: "Bilder",+ videos: "Videos",+ audio: "Audio",+ models: "Fine-Tunes",+ all: "Alle",+ },+ empty: {+ suggestedTitle: "Ihre Bibliothek ist leer",+ suggestedDescription: "Dateien, die Sie hochladen oder in Chats erstellen, erscheinen hier.",+ favoritesTitle: "Noch keine Favoriten",+ favoritesDescription: "Fügen Sie Dateien zu Ihren Favoriten hinzu, um sie hier schnell wiederzufinden.",+ foldersTitle: "Erstellen Sie Ihren ersten Ordner",+ foldersDescription: "Erstellen Sie Ordner, um die Einträge in Ihrer Bibliothek zu organisieren.",+ imagesTitle: "Noch keine Bilder",+ imagesDescription: "Bilder, die Sie hochladen oder generieren, erscheinen hier.",+ videosTitle: "Noch keine Videos",+ videosDescription: "Videos, die Sie hochladen oder generieren, erscheinen hier.",+ audioTitle: "Noch kein Audio",+ audioDescription: "Sprache, die Sie auf der Audio-Seite generieren, erscheint hier.",+ modelsTitle: "Noch keine feinabgestimmten Modelle",+ modelsDescription: "Modelle, die Sie in Unsloth trainieren oder exportieren, erscheinen hier.",+ createFolder: "Ordner erstellen",+ generateVideo: "Video generieren",+ generateAudio: "Audio generieren",+ trainModel: "Modell trainieren",+ uploadFiles: "Dateien hochladen",+ dropHere: "oder Dateien hier ablegen",+ noMatchesTitle: "Keine Treffer",+ noMatchesDescription: "Versuchen Sie eine andere Suche oder setzen Sie die Filter zurück.",+ loadErrorTitle: "Ihre Bibliothek konnte nicht geladen werden",+ loadErrorFallback: "Etwas ist schiefgelaufen.",+ tryAgain: "Erneut versuchen",+ },+ sections: {+ items: "Einträge",+ },+ breadcrumb: "Navigationspfad",+ searchLibrary: "Bibliothek durchsuchen",+ searchFolder: "Ordner durchsuchen",+ dropToUpload: "Zum Hochladen ablegen",+ dropToUploadInto: "Zum Hochladen in „{folder}“ ablegen",+ itemCountOne: "{count} Eintrag",+ itemCount: "{count} Einträge",+ selectItem: "{name} auswählen",+ selection: {+ startChat: "Chat starten",+ move: "Verschieben",+ clear: "Auswahl aufheben",+ },+ menu: {+ moreActions: "Weitere Aktionen",+ chatAboutThis: "Darüber chatten",+ chatWithModel: "Mit diesem Modell chatten",+ addToFavorites: "Zu Favoriten hinzufügen",+ removeFromFavorites: "Aus Favoriten entfernen",+ download: "Herunterladen",+ addToFolder: "Zu Ordner hinzufügen",+ newFolder: "Neuer Ordner",+ noFolder: "Bibliothek (kein Ordner)",+ deleteFolder: "Ordner löschen",+ },+ reveal: {+ finder: "Im Finder zeigen",+ explorer: "Im Explorer anzeigen",+ files: "Im Ordner anzeigen",+ },+ toolbar: {+ filter: "Filter",+ source: "Quelle",+ fileType: "Dateityp",+ clearFilters: "Filter zurücksetzen",+ uploaded: "Hochgeladen",+ generated: "Generiert",+ documents: "Dokumente",+ spreadsheets: "Tabellen",+ presentations: "Präsentationen",+ pdfs: "PDFs",+ gridView: "Rasteransicht",+ listView: "Listenansicht",+ settings: "Bibliothekseinstellungen",+ },+ create: {+ note: "Notiz",+ image: "Bild",+ video: "Video",+ audio: "Audio",+ model: "Modell",+ folder: "Ordner",+ untitledNote: "Unbenannte Notiz",+ },+ list: {+ selectAll: "Alle auswählen",+ name: "Name",+ lastActivity: "Letzte Aktivität",+ favorite: "Favorit",+ modified: "Geändert {time}",+ justNow: "gerade eben",+ },+ size: {+ bytes: "{value} B",+ kilobytes: "{value} KB",+ megabytes: "{value} MB",+ gigabytes: "{value} GB",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "Vollständiges Fine-Tuning",+ loraExport: "LoRA-Export",+ mergedExport: "Zusammengeführter Export",+ ggufExport: "GGUF-Export",+ model: "Modell",+ },+ dialog: {+ create: "Erstellen",+ renameFolder: "Ordner umbenennen",+ renameFile: "Datei umbenennen",+ deleteTitle: "„{name}“ löschen?",+ deleteManyTitle: "{count} Einträge löschen?",+ deleteManyDescription: "Dateien werden dort gelöscht, wo sie liegen. Inhalte eines gelöschten Ordners rücken eine Ebene nach oben.",+ deleteFolderIntoParent: "Der gesamte Inhalt wird nach „{folder}“ verschoben. Es werden keine Dateien gelöscht.",+ deleteFolderIntoLibrary: "Der gesamte Inhalt wird in Ihre Bibliothek verschoben. Es werden keine Dateien gelöscht.",+ deleteUpload: "Dadurch wird die Datei dauerhaft gelöscht.",+ deleteAttachment: "Die Datei wird auch aus dem Chat entfernt, an den sie angehängt war.",+ deleteImage: "Die Datei wird auch aus Ihrer Bildergalerie entfernt.",+ 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.",+ 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",+ discardChanges: "Änderungen verwerfen",+ },+ preview: {+ code: "Code",+ preview: "Vorschau",+ viewOriginalChat: "Ursprünglichen Chat anzeigen",+ viewInImages: "In Bilder anzeigen",+ viewInVideo: "In Video anzeigen",+ viewInAudio: "In Audio anzeigen",+ cannotPreview: "Für diese Datei ist hier keine Vorschau möglich. Laden Sie sie herunter, um sie zu öffnen.",+ noPreview: "Keine Vorschau für diesen Dateityp.",+ tooLargeToPreview: "Diese Datei ist zu groß für eine Vorschau. Laden Sie sie herunter, um sie zu öffnen.",+ startWriting: "Mit dem Schreiben beginnen…",+ type: "Typ",+ baseModel: "Basismodell",+ size: "Größe",+ location: "Speicherort",+ unknown: "Unbekannt",+ readOnlyUtf16: "Diese Datei ist kein gültiger UTF-16-Text und wird hier daher schreibgeschützt geöffnet.",+ readOnlyNotUtf8: "Diese Datei ist kein UTF-8-Text und wird hier daher schreibgeschützt geöffnet. Manche Zeichen werden eventuell nicht richtig angezeigt.",+ },+ viewer: {+ scale: "Skalierung",+ fit: "Einpassen",+ moreActionsImage: "Weitere Aktionen für dieses Bild",+ moreActionsVideo: "Weitere Aktionen für dieses Video",+ moreActionsClip: "Weitere Aktionen für diesen Clip",+ moreActionsFile: "Weitere Aktionen für diese Datei",+ },+ project: {+ label: "Projekt",+ newProject: "Neues Projekt",+ noProjects: "Noch keine Projekte",+ alreadyIn: "Bereits in {project}",+ addedTo: "Zu {project} hinzugefügt",+ createAndAdd: "Erstellen und hinzufügen",+ addFailedImage: "Bild konnte nicht zum Projekt hinzugefügt werden",+ addFailedVideo: "Video konnte nicht zum Projekt hinzugefügt werden",+ addFailedClip: "Clip konnte nicht zum Projekt hinzugefügt werden",+ addFailedFile: "Datei konnte nicht zum Projekt hinzugefügt werden",+ newProjectImage: "Bild zu neuem Projekt hinzufügen",+ newProjectVideo: "Video zu neuem Projekt hinzufügen",+ newProjectClip: "Clip zu neuem Projekt hinzufügen",+ newProjectFile: "Datei zu neuem Projekt hinzufügen",+ },+ toast: {+ missingItem: "Diese Datei ist nicht mehr in der Bibliothek",+ moveFailed: "Verschieben fehlgeschlagen",+ movedToFolder: "Nach {folder} verschoben",+ movedToLibrary: "In die Bibliothek verschoben",+ folderFallback: "Ordner",+ favoritesFailed: "Favoriten konnten nicht aktualisiert werden",+ addedToFavorites: "Zu Favoriten hinzugefügt",+ removedFromFavorites: "Aus Favoriten entfernt",+ uploadingOne: "{name} wird hochgeladen…",+ uploadingMany: "{count} Dateien werden hochgeladen…",+ uploadedOne: "Datei hochgeladen",+ uploadedMany: "{count} Dateien hochgeladen",+ uploadFailed: "Hochladen fehlgeschlagen",+ uploadTooLarge: "{name} ist größer als 512 MB.",+ readDropsFailed: "Die abgelegten Dateien konnten nicht gelesen werden",+ createNoteFailed: "Die Notiz konnte nicht erstellt werden",+ renameFailed: "Umbenennen fehlgeschlagen",+ createFolderFailed: "Der Ordner konnte nicht erstellt werden",+ signedOutBeforeFolder: "Abgemeldet, bevor der Ordner erstellt wurde.",+ signedOutBeforeSave: "Abgemeldet, bevor die Änderung gespeichert wurde.",+ signedOutBeforeUpload: "Abgemeldet, bevor das Hochladen abgeschlossen war.",+ deleteFailed: "Einige Einträge konnten nicht gelöscht werden",+ saveFailed: "Speichern fehlgeschlagen",+ saveNoteFirst: "Speichern Sie zuerst die Notiz.",+ revealFailed: "Der Dateimanager konnte nicht geöffnet werden",+ downloadFailed: "{name} konnte nicht heruntergeladen werden",+ downloadManyFailed: "Die Dateien konnten nicht heruntergeladen werden",+ downloadingMany: "{count} Dateien werden heruntergeladen",+ downloadingManyDescription: "Wenn Ihr Browser nachfragt, erlauben Sie dieser Website, mehrere Dateien herunterzuladen.",+ preparingMany: "{count} Dateien werden vorbereitet…",+ zipFileName: "Bibliotheksdateien",+ nothingToChat: "Noch nichts, worüber sich chatten ließe",+ emptyFolder: "Dieser Ordner enthält keine Dateien.",+ tooLargeOne: "{name} ist zu groß zum Anhängen",+ tooLargeMany: "Diese Dateien sind zu groß zum Anhängen",+ attachedOne: "{count} Datei angehängt",+ attachedMany: "{count} Dateien angehängt",+ skippedTooLarge: "{count} zu groß zum Anhängen.",+ skippedOverLimit: "{count} weitere über dem Limit von {limit} Dateien.",+ chatFilesWaiting: "{count} werden angehängt, sobald ein Modell geladen ist, das sie lesen kann.",+ openFilesFailed: "Die Dateien konnten nicht geöffnet werden",+ speechModel: "{name} ist ein Sprachmodell",+ speechModelDescription: "Wählen Sie es im Modellmenü auf der Audio-Seite aus.",+ noMediaLink: "Der Server hat keinen Link zum Abspielen dieser Datei zurückgegeben.",+ imageNotFound: "Dieses Bild wurde nicht gefunden",+ clipNotFound: "Dieser Clip wurde nicht gefunden",+ notFoundDescription: "Möglicherweise archiviert oder gelöscht.",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 239d6f38934..13b3fe45f70 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -156,6 +156,7 @@ export const en = {compare: "Compare",search: "Search",projects: "Projects",+ library: "Library",hub: "Model hub",train: "Train",recipes: "Recipes",@@ -2315,8 +2316,7 @@ export const en = {currentRun: "Current Run",history: "History",},- imageTraining: "Image training",- goToImageTraining: "Go to image training",+ goToLibrary: "Go to Library",loadingRuntime: "Loading training runtime...",checkingSupport: "Checking this machine for training support...",backToHistory: "Back to history",@@ -2844,4 +2844,253 @@ export const en = {updateError: "Could not update skill",mentions: "Skills",},+ // The Library page, its file viewer, and the menus and toasts that act on its files.+ library: {+ tabs: {+ ariaLabel: "Library sections",+ suggested: "Suggested",+ favorites: "Favorites",+ folders: "Folders",+ images: "Images",+ videos: "Videos",+ audio: "Audio",+ models: "Fine-tunes",+ all: "All",+ },+ // One title and description per tab, shown when it has nothing yet.+ empty: {+ suggestedTitle: "Your library is empty",+ suggestedDescription: "Files you upload or create in chats show up here.",+ favoritesTitle: "No favorites yet",+ favoritesDescription: "Add files to your favorites to find them here quickly.",+ foldersTitle: "Create your first folder",+ foldersDescription: "Create folders to organize items in your library.",+ imagesTitle: "No images yet",+ imagesDescription: "Images you upload or generate show up here.",+ videosTitle: "No videos yet",+ videosDescription: "Videos you upload or generate show up here.",+ audioTitle: "No audio yet",+ audioDescription: "Speech you generate on the Audio page shows up here.",+ modelsTitle: "No fine-tuned models yet",+ modelsDescription: "Models you train or export in Unsloth show up here.",+ createFolder: "Create folder",+ generateVideo: "Generate a video",+ generateAudio: "Generate audio",+ trainModel: "Train a model",+ uploadFiles: "Upload files",+ dropHere: "or drop files here",+ noMatchesTitle: "No matches",+ noMatchesDescription: "Try a different search or clear the filters.",+ loadErrorTitle: "Could not load your Library",+ loadErrorFallback: "Something went wrong.",+ tryAgain: "Try again",+ },+ sections: {+ items: "Items",+ },+ breadcrumb: "Breadcrumb",+ searchLibrary: "Search library",+ searchFolder: "Search folder",+ dropToUpload: "Drop to upload",+ dropToUploadInto: 'Drop to upload to "{folder}"',+ // Folder cards and list rows. The singular form is used when count is 1.+ itemCountOne: "{count} item",+ itemCount: "{count} items",+ selectItem: "Select {name}",+ // The bar that floats over the page while anything is selected.+ selection: {+ startChat: "Start chat",+ move: "Move",+ clear: "Clear selection",+ },+ menu: {+ moreActions: "More actions",+ chatAboutThis: "Chat about this",+ chatWithModel: "Chat with this model",+ addToFavorites: "Add to Favorites",+ removeFromFavorites: "Remove from Favorites",+ download: "Download",+ addToFolder: "Add to folder",+ newFolder: "New folder",+ noFolder: "Library (no folder)",+ deleteFolder: "Delete folder",+ },+ // Each platform's own name for opening the file manager at a file.+ reveal: {+ finder: "Reveal in Finder",+ explorer: "Show in Explorer",+ files: "Show in Folder",+ },+ toolbar: {+ filter: "Filter",+ source: "Source",+ fileType: "File type",+ clearFilters: "Clear filters",+ uploaded: "Uploaded",+ generated: "Generated",+ documents: "Documents",+ spreadsheets: "Spreadsheets",+ presentations: "Presentations",+ pdfs: "PDFs",+ gridView: "Grid view",+ listView: "List view",+ settings: "Library settings",+ },+ // Entries of the New menu.+ create: {+ note: "Note",+ image: "Image",+ video: "Video",+ audio: "Audio",+ model: "Model",+ folder: "Folder",+ // File name of a new note, before its .md extension.+ untitledNote: "Untitled note",+ },+ list: {+ selectAll: "Select all",+ name: "Name",+ lastActivity: "Last activity",+ favorite: "Favorite",+ modified: "Modified {time}",+ justNow: "just now",+ },+ // File sizes. {value} is already formatted for the locale.+ size: {+ bytes: "{value} B",+ kilobytes: "{value} KB",+ megabytes: "{value} MB",+ gigabytes: "{value} GB",+ },+ // Fine-tuned models, by how they were made.+ modelKind: {+ lora: "LoRA",+ fullFineTune: "Full fine-tune",+ loraExport: "LoRA export",+ mergedExport: "Merged export",+ ggufExport: "GGUF export",+ model: "Model",+ },+ dialog: {+ create: "Create",+ renameFolder: "Rename folder",+ renameFile: "Rename file",+ deleteTitle: 'Delete "{name}"?',+ deleteManyTitle: "Delete {count} items?",+ deleteManyDescription:+ "Files are deleted from where they live. Anything inside a deleted folder moves up a level.",+ deleteFolderIntoParent: 'Everything inside moves to "{folder}". No files are deleted.',+ deleteFolderIntoLibrary: "Everything inside moves to your Library. No files are deleted.",+ // What else deleting a file removes, by where it came from.+ deleteUpload: "This permanently deletes the file.",+ deleteAttachment: "It is also removed from the chat it was attached to.",+ deleteImage: "It is also removed from your Images gallery.",+ 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.",+ 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.",+ keepEditing: "Keep editing",+ discardChanges: "Discard changes",+ },+ preview: {+ code: "Code",+ preview: "Preview",+ viewOriginalChat: "View original chat",+ viewInImages: "View in Images",+ viewInVideo: "View in Video",+ viewInAudio: "View in Audio",+ cannotPreview: "This file can't be previewed here. Download it to open it.",+ noPreview: "No preview for this file type.",+ tooLargeToPreview: "This file is too large to preview here. Download it to open it.",+ startWriting: "Start writing…",+ type: "Type",+ baseModel: "Base model",+ size: "Size",+ location: "Location",+ unknown: "Unknown",+ readOnlyUtf16: "This file is not valid UTF-16 text, so it opens read-only here.",+ readOnlyNotUtf8:+ "This file is not UTF-8 text, so it opens read-only here. Some characters may not show correctly.",+ },+ // The full-window file viewer, shared with the Images, Video and Audio pages.+ viewer: {+ scale: "Scale",+ fit: "Fit",+ moreActionsImage: "More actions for this image",+ moreActionsVideo: "More actions for this video",+ moreActionsClip: "More actions for this clip",+ moreActionsFile: "More actions for this file",+ },+ // The Project submenu that copies a file into a project.+ project: {+ label: "Project",+ newProject: "New project",+ noProjects: "No projects yet",+ alreadyIn: "Already in {project}",+ addedTo: "Added to {project}",+ createAndAdd: "Create and add",+ addFailedImage: "Failed to add image to project",+ addFailedVideo: "Failed to add video to project",+ addFailedClip: "Failed to add clip to project",+ addFailedFile: "Failed to add file to project",+ newProjectImage: "Add image to new project",+ newProjectVideo: "Add video to new project",+ newProjectClip: "Add clip to new project",+ newProjectFile: "Add file to new project",+ },+ toast: {+ missingItem: "That file is no longer in the Library",+ moveFailed: "Could not move",+ movedToFolder: "Moved to {folder}",+ movedToLibrary: "Moved to Library",+ // Stands in for a destination folder whose name is not known.+ folderFallback: "folder",+ favoritesFailed: "Could not update favorites",+ addedToFavorites: "Added to Favorites",+ removedFromFavorites: "Removed from Favorites",+ uploadingOne: "Uploading {name}…",+ uploadingMany: "Uploading {count} files…",+ uploadedOne: "File uploaded",+ uploadedMany: "{count} files uploaded",+ uploadFailed: "Upload failed",+ uploadTooLarge: "{name} is larger than 512 MB.",+ readDropsFailed: "Could not read the dropped files",+ createNoteFailed: "Could not create the note",+ renameFailed: "Could not rename",+ createFolderFailed: "Could not create the folder",+ signedOutBeforeFolder: "Signed out before the folder was made.",+ signedOutBeforeSave: "Signed out before the change was saved.",+ signedOutBeforeUpload: "Signed out before the upload finished.",+ deleteFailed: "Some items could not be deleted",+ saveFailed: "Could not save",+ saveNoteFirst: "Save the note first.",+ revealFailed: "Could not open the file manager",+ downloadFailed: "Could not download {name}",+ downloadManyFailed: "Could not download the files",+ downloadingMany: "Downloading {count} files",+ downloadingManyDescription: "If your browser asks, allow this site to download multiple files.",+ preparingMany: "Preparing {count} files…",+ // Name of the zip a browser downloads several files in.+ zipFileName: "Library files",+ nothingToChat: "Nothing to chat about yet",+ emptyFolder: "This folder has no files.",+ tooLargeOne: "{name} is too large to attach",+ tooLargeMany: "These files are too large to attach",+ attachedOne: "Attached {count} file",+ attachedMany: "Attached {count} files",+ skippedTooLarge: "{count} too large to attach.",+ skippedOverLimit: "{count} more past the {limit} file limit.",+ chatFilesWaiting: "{count} will be attached once a model that reads them is loaded.",+ openFilesFailed: "Could not open the files",+ speechModel: "{name} is a speech model",+ speechModelDescription: "Pick it from the model menu on the Audio page.",+ noMediaLink: "The server returned no link to play this file.",+ // A Library "View in" link to a gallery entry that is no longer listed.+ imageNotFound: "Could not find this image",+ clipNotFound: "Could not find this clip",+ notFoundDescription: "It may be archived or deleted.",+ },+ },} as const;diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 412dcf7242b..2fa83f50230 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -158,6 +158,7 @@ export const es = {search: "Buscar",hub: "Centro de modelos",projects: "Proyectos",+ library: "Biblioteca",train: "Entrenar",recipes: "Recetas",images: "Imágenes",@@ -2179,8 +2180,7 @@ export const es = {},},studio: {- imageTraining: "Entrenamiento de imágenes",- goToImageTraining: "Ir al entrenamiento de imágenes",+ goToLibrary: "Ir a la Biblioteca",routeTitle: "Entrenar",wizard: {modelTitle: "Modelo",@@ -2926,4 +2926,235 @@ export const es = {updateError: "No se pudo actualizar la habilidad",mentions: "Habilidades",},+ library: {+ tabs: {+ ariaLabel: "Secciones de la Biblioteca",+ suggested: "Sugerencias",+ favorites: "Favoritos",+ folders: "Carpetas",+ images: "Imágenes",+ videos: "Vídeos",+ audio: "Audio",+ models: "Fine-tunes",+ all: "Todo",+ },+ empty: {+ suggestedTitle: "Tu biblioteca está vacía",+ suggestedDescription: "Los archivos que subas o crees en los chats aparecen aquí.",+ favoritesTitle: "Aún no hay favoritos",+ favoritesDescription: "Añade archivos a tus favoritos para encontrarlos aquí rápidamente.",+ foldersTitle: "Crea tu primera carpeta",+ foldersDescription: "Crea carpetas para organizar los elementos de tu biblioteca.",+ imagesTitle: "Aún no hay imágenes",+ imagesDescription: "Las imágenes que subas o generes aparecen aquí.",+ videosTitle: "Aún no hay vídeos",+ videosDescription: "Los vídeos que subas o generes aparecen aquí.",+ audioTitle: "Aún no hay audio",+ audioDescription: "La voz que generes en la página Audio aparece aquí.",+ modelsTitle: "Aún no hay modelos ajustados",+ modelsDescription: "Los modelos que entrenes o exportes en Unsloth aparecen aquí.",+ createFolder: "Crear carpeta",+ generateVideo: "Generar un vídeo",+ generateAudio: "Generar audio",+ trainModel: "Entrenar un modelo",+ uploadFiles: "Subir archivos",+ dropHere: "o suelta archivos aquí",+ noMatchesTitle: "Sin resultados",+ noMatchesDescription: "Prueba con otra búsqueda o borra los filtros.",+ loadErrorTitle: "No se pudo cargar tu Biblioteca",+ loadErrorFallback: "Algo salió mal.",+ tryAgain: "Volver a intentar",+ },+ sections: {+ items: "Elementos",+ },+ breadcrumb: "Ruta de navegación",+ searchLibrary: "Buscar en la biblioteca",+ searchFolder: "Buscar en la carpeta",+ dropToUpload: "Suelta para subir",+ dropToUploadInto: "Suelta para subir a «{folder}»",+ itemCountOne: "{count} elemento",+ itemCount: "{count} elementos",+ selectItem: "Seleccionar {name}",+ selection: {+ startChat: "Iniciar chat",+ move: "Mover",+ clear: "Borrar selección",+ },+ menu: {+ moreActions: "Más acciones",+ chatAboutThis: "Chatear sobre esto",+ chatWithModel: "Chatear con este modelo",+ addToFavorites: "Añadir a Favoritos",+ removeFromFavorites: "Quitar de Favoritos",+ download: "Descargar",+ addToFolder: "Añadir a carpeta",+ newFolder: "Nueva carpeta",+ noFolder: "Biblioteca (sin carpeta)",+ deleteFolder: "Eliminar carpeta",+ },+ reveal: {+ finder: "Mostrar en el Finder",+ explorer: "Mostrar en el Explorador",+ files: "Mostrar en la carpeta",+ },+ toolbar: {+ filter: "Filtrar",+ source: "Origen",+ fileType: "Tipo de archivo",+ clearFilters: "Borrar filtros",+ uploaded: "Subidos",+ generated: "Generados",+ documents: "Documentos",+ spreadsheets: "Hojas de cálculo",+ presentations: "Presentaciones",+ pdfs: "PDF",+ gridView: "Vista de cuadrícula",+ listView: "Vista de lista",+ settings: "Ajustes de la Biblioteca",+ },+ create: {+ note: "Nota",+ image: "Imagen",+ video: "Vídeo",+ audio: "Audio",+ model: "Modelo",+ folder: "Carpeta",+ untitledNote: "Nota sin título",+ },+ list: {+ selectAll: "Seleccionar todo",+ name: "Nombre",+ lastActivity: "Última actividad",+ favorite: "Favorito",+ modified: "Modificado {time}",+ justNow: "justo ahora",+ },+ size: {+ bytes: "{value} B",+ kilobytes: "{value} KB",+ megabytes: "{value} MB",+ gigabytes: "{value} GB",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "Fine-tuning completo",+ loraExport: "Exportación LoRA",+ mergedExport: "Exportación fusionada",+ ggufExport: "Exportación GGUF",+ model: "Modelo",+ },+ dialog: {+ create: "Crear",+ renameFolder: "Renombrar carpeta",+ renameFile: "Renombrar archivo",+ deleteTitle: "¿Eliminar «{name}»?",+ deleteManyTitle: "¿Eliminar {count} elementos?",+ deleteManyDescription: "Los archivos se eliminan de donde estén guardados. Lo que haya dentro de una carpeta eliminada sube un nivel.",+ deleteFolderIntoParent: "Todo su contenido se mueve a «{folder}». No se elimina ningún archivo.",+ deleteFolderIntoLibrary: "Todo su contenido se mueve a tu Biblioteca. No se elimina ningún archivo.",+ deleteUpload: "Esto elimina el archivo de forma permanente.",+ deleteAttachment: "También se quitará del chat al que estaba adjunto.",+ deleteImage: "También se quitará de tu galería de Imágenes.",+ 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ó.",+ unsavedTitle: "Tus cambios no se guardaron",+ unsavedDescription: "{reason} Vuelve a intentarlo o descarta los cambios para cerrar el archivo.",+ keepEditing: "Seguir editando",+ discardChanges: "Descartar cambios",+ },+ preview: {+ code: "Código",+ preview: "Vista previa",+ viewOriginalChat: "Ver el chat original",+ viewInImages: "Ver en Imágenes",+ viewInVideo: "Ver en Vídeo",+ viewInAudio: "Ver en Audio",+ cannotPreview: "No se puede previsualizar este archivo aquí. Descárgalo para abrirlo.",+ noPreview: "No hay vista previa para este tipo de archivo.",+ tooLargeToPreview: "Este archivo es demasiado grande para previsualizarlo aquí. Descárgalo para abrirlo.",+ startWriting: "Empieza a escribir…",+ type: "Tipo",+ baseModel: "Modelo base",+ size: "Tamaño",+ location: "Ubicación",+ unknown: "Desconocido",+ readOnlyUtf16: "Este archivo no es texto UTF-16 válido, así que aquí se abre en modo de solo lectura.",+ readOnlyNotUtf8: "Este archivo no es texto UTF-8, así que aquí se abre en modo de solo lectura. Es posible que algunos caracteres no se muestren correctamente.",+ },+ viewer: {+ scale: "Escala",+ fit: "Ajustar",+ moreActionsImage: "Más acciones para esta imagen",+ moreActionsVideo: "Más acciones para este vídeo",+ moreActionsClip: "Más acciones para este clip",+ moreActionsFile: "Más acciones para este archivo",+ },+ project: {+ label: "Proyecto",+ newProject: "Nuevo proyecto",+ noProjects: "Aún no hay proyectos",+ alreadyIn: "Ya está en {project}",+ addedTo: "Añadido a {project}",+ createAndAdd: "Crear y añadir",+ addFailedImage: "No se pudo añadir la imagen al proyecto",+ addFailedVideo: "No se pudo añadir el vídeo al proyecto",+ addFailedClip: "No se pudo añadir el clip al proyecto",+ addFailedFile: "No se pudo añadir el archivo al proyecto",+ newProjectImage: "Añadir imagen a un nuevo proyecto",+ newProjectVideo: "Añadir vídeo a un nuevo proyecto",+ newProjectClip: "Añadir clip a un nuevo proyecto",+ newProjectFile: "Añadir archivo a un nuevo proyecto",+ },+ toast: {+ missingItem: "Ese archivo ya no está en la Biblioteca",+ moveFailed: "No se pudo mover",+ movedToFolder: "Movido a {folder}",+ movedToLibrary: "Movido a la Biblioteca",+ folderFallback: "carpeta",+ favoritesFailed: "No se pudieron actualizar los favoritos",+ addedToFavorites: "Añadido a Favoritos",+ removedFromFavorites: "Quitado de Favoritos",+ uploadingOne: "Subiendo {name}…",+ uploadingMany: "Subiendo {count} archivos…",+ uploadedOne: "Archivo subido",+ uploadedMany: "{count} archivos subidos",+ uploadFailed: "Error al subir",+ uploadTooLarge: "{name} supera los 512 MB.",+ readDropsFailed: "No se pudieron leer los archivos soltados",+ createNoteFailed: "No se pudo crear la nota",+ renameFailed: "No se pudo renombrar",+ createFolderFailed: "No se pudo crear la carpeta",+ signedOutBeforeFolder: "Se cerró la sesión antes de crear la carpeta.",+ signedOutBeforeSave: "Se cerró la sesión antes de guardar el cambio.",+ signedOutBeforeUpload: "Se cerró la sesión antes de terminar la subida.",+ deleteFailed: "No se pudieron eliminar algunos elementos",+ saveFailed: "No se pudo guardar",+ saveNoteFirst: "Guarda primero la nota.",+ revealFailed: "No se pudo abrir el gestor de archivos",+ downloadFailed: "No se pudo descargar {name}",+ downloadManyFailed: "No se pudieron descargar los archivos",+ downloadingMany: "Descargando {count} archivos",+ downloadingManyDescription: "Si tu navegador lo pide, permite que este sitio descargue varios archivos.",+ preparingMany: "Preparando {count} archivos…",+ zipFileName: "Archivos de la Biblioteca",+ nothingToChat: "Todavía no hay nada sobre lo que chatear",+ emptyFolder: "Esta carpeta no tiene archivos.",+ tooLargeOne: "{name} es demasiado grande para adjuntarlo",+ tooLargeMany: "Estos archivos son demasiado grandes para adjuntarlos",+ attachedOne: "{count} archivo adjuntado",+ attachedMany: "{count} archivos adjuntados",+ skippedTooLarge: "{count} demasiado grandes para adjuntar.",+ skippedOverLimit: "{count} más por encima del límite de {limit} archivos.",+ chatFilesWaiting: "{count} se adjuntarán cuando se cargue un modelo que pueda leerlos.",+ openFilesFailed: "No se pudieron abrir los archivos",+ speechModel: "{name} es un modelo de voz",+ speechModelDescription: "Selecciónalo en el menú de modelos de la página Audio.",+ noMediaLink: "El servidor no devolvió ningún enlace para reproducir este archivo.",+ imageNotFound: "No se encontró esta imagen",+ clipNotFound: "No se encontró este clip",+ notFoundDescription: "Puede que se haya archivado o eliminado.",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 929ab782ae1..5c6332a9344 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -159,6 +159,7 @@ export const fr = {search: "Rechercher",hub: "Hub de modèles",projects: "Projets",+ library: "Bibliothèque",train: "Entraîner",recipes: "Recettes",images: "Images",@@ -2190,8 +2191,7 @@ export const fr = {},},studio: {- imageTraining: "Entraînement d'images",- goToImageTraining: "Aller à l'entraînement d'images",+ goToLibrary: "Aller à la Bibliothèque",routeTitle: "Entraîner",wizard: {modelTitle: "Modèle",@@ -2940,4 +2940,235 @@ export const fr = {updateError: "Impossible de mettre à jour la compétence",mentions: "Compétences",},+ library: {+ tabs: {+ ariaLabel: "Sections de la Bibliothèque",+ suggested: "Suggestions",+ favorites: "Favoris",+ folders: "Dossiers",+ images: "Images",+ videos: "Vidéos",+ audio: "Audio",+ models: "Fine-tunes",+ all: "Tout",+ },+ empty: {+ suggestedTitle: "Votre bibliothèque est vide",+ suggestedDescription: "Les fichiers que vous importez ou créez dans les discussions apparaissent ici.",+ favoritesTitle: "Aucun favori pour l'instant",+ favoritesDescription: "Ajoutez des fichiers à vos favoris pour les retrouver rapidement ici.",+ foldersTitle: "Créez votre premier dossier",+ foldersDescription: "Créez des dossiers pour organiser les éléments de votre bibliothèque.",+ imagesTitle: "Aucune image pour l'instant",+ imagesDescription: "Les images que vous importez ou générez apparaissent ici.",+ videosTitle: "Aucune vidéo pour l'instant",+ videosDescription: "Les vidéos que vous importez ou générez apparaissent ici.",+ audioTitle: "Aucun audio pour l'instant",+ audioDescription: "La voix que vous générez sur la page Audio apparaît ici.",+ modelsTitle: "Aucun modèle affiné pour l'instant",+ modelsDescription: "Les modèles que vous entraînez ou exportez dans Unsloth apparaissent ici.",+ createFolder: "Créer un dossier",+ generateVideo: "Générer une vidéo",+ generateAudio: "Générer de l'audio",+ trainModel: "Entraîner un modèle",+ uploadFiles: "Importer des fichiers",+ dropHere: "ou déposez des fichiers ici",+ noMatchesTitle: "Aucun résultat",+ noMatchesDescription: "Essayez une autre recherche ou effacez les filtres.",+ loadErrorTitle: "Impossible de charger votre Bibliothèque",+ loadErrorFallback: "Une erreur s'est produite.",+ tryAgain: "Réessayer",+ },+ sections: {+ items: "Éléments",+ },+ breadcrumb: "Fil d'Ariane",+ searchLibrary: "Rechercher dans la bibliothèque",+ searchFolder: "Rechercher dans le dossier",+ dropToUpload: "Déposez pour importer",+ dropToUploadInto: "Déposez pour importer dans « {folder} »",+ itemCountOne: "{count} élément",+ itemCount: "{count} éléments",+ selectItem: "Sélectionner {name}",+ selection: {+ startChat: "Démarrer une discussion",+ move: "Déplacer",+ clear: "Effacer la sélection",+ },+ menu: {+ moreActions: "Plus d'actions",+ chatAboutThis: "Discuter de ce fichier",+ chatWithModel: "Discuter avec ce modèle",+ addToFavorites: "Ajouter aux favoris",+ removeFromFavorites: "Retirer des favoris",+ download: "Télécharger",+ addToFolder: "Ajouter à un dossier",+ newFolder: "Nouveau dossier",+ noFolder: "Bibliothèque (aucun dossier)",+ deleteFolder: "Supprimer le dossier",+ },+ reveal: {+ finder: "Afficher dans le Finder",+ explorer: "Afficher dans l'Explorateur",+ files: "Afficher dans le dossier",+ },+ toolbar: {+ filter: "Filtrer",+ source: "Source",+ fileType: "Type de fichier",+ clearFilters: "Effacer les filtres",+ uploaded: "Importés",+ generated: "Générés",+ documents: "Documents",+ spreadsheets: "Feuilles de calcul",+ presentations: "Présentations",+ pdfs: "PDF",+ gridView: "Vue en grille",+ listView: "Vue en liste",+ settings: "Paramètres de la Bibliothèque",+ },+ create: {+ note: "Note",+ image: "Image",+ video: "Vidéo",+ audio: "Audio",+ model: "Modèle",+ folder: "Dossier",+ untitledNote: "Note sans titre",+ },+ list: {+ selectAll: "Tout sélectionner",+ name: "Nom",+ lastActivity: "Dernière activité",+ favorite: "Favori",+ modified: "Modifié {time}",+ justNow: "à l'instant",+ },+ size: {+ bytes: "{value} o",+ kilobytes: "{value} Ko",+ megabytes: "{value} Mo",+ gigabytes: "{value} Go",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "Fine-tuning complet",+ loraExport: "Export LoRA",+ mergedExport: "Export fusionné",+ ggufExport: "Export GGUF",+ model: "Modèle",+ },+ dialog: {+ create: "Créer",+ renameFolder: "Renommer le dossier",+ renameFile: "Renommer le fichier",+ deleteTitle: "Supprimer « {name} » ?",+ deleteManyTitle: "Supprimer {count} éléments ?",+ deleteManyDescription: "Les fichiers sont supprimés de leur emplacement d'origine. Le contenu d'un dossier supprimé remonte d'un niveau.",+ deleteFolderIntoParent: "Tout son contenu est déplacé vers « {folder} ». Aucun fichier n'est supprimé.",+ deleteFolderIntoLibrary: "Tout son contenu est déplacé vers votre Bibliothèque. Aucun fichier n'est supprimé.",+ deleteUpload: "Le fichier sera définitivement supprimé.",+ deleteAttachment: "Il sera aussi retiré de la discussion à laquelle il était joint.",+ deleteImage: "Il sera aussi retiré de votre galerie Images.",+ 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éé.",+ 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",+ discardChanges: "Abandonner les modifications",+ },+ preview: {+ code: "Code",+ preview: "Aperçu",+ viewOriginalChat: "Voir la discussion d'origine",+ viewInImages: "Voir dans Images",+ viewInVideo: "Voir dans Vidéo",+ viewInAudio: "Voir dans Audio",+ cannotPreview: "Impossible d'afficher un aperçu de ce fichier ici. Téléchargez-le pour l'ouvrir.",+ noPreview: "Aucun aperçu pour ce type de fichier.",+ tooLargeToPreview: "Ce fichier est trop volumineux pour être prévisualisé ici. Téléchargez-le pour l'ouvrir.",+ startWriting: "Commencez à écrire…",+ type: "Type",+ baseModel: "Modèle de base",+ size: "Taille",+ location: "Emplacement",+ unknown: "Inconnu",+ readOnlyUtf16: "Ce fichier n'est pas un texte UTF-16 valide : il s'ouvre donc ici en lecture seule.",+ readOnlyNotUtf8: "Ce fichier n'est pas un texte UTF-8 : il s'ouvre donc ici en lecture seule. Certains caractères peuvent s'afficher incorrectement.",+ },+ viewer: {+ scale: "Échelle",+ fit: "Ajuster",+ moreActionsImage: "Plus d'actions pour cette image",+ moreActionsVideo: "Plus d'actions pour cette vidéo",+ moreActionsClip: "Plus d'actions pour cet extrait",+ moreActionsFile: "Plus d'actions pour ce fichier",+ },+ project: {+ label: "Projet",+ newProject: "Nouveau projet",+ noProjects: "Aucun projet pour l'instant",+ alreadyIn: "Déjà dans {project}",+ addedTo: "Ajouté à {project}",+ createAndAdd: "Créer et ajouter",+ addFailedImage: "Impossible d'ajouter l'image au projet",+ addFailedVideo: "Impossible d'ajouter la vidéo au projet",+ addFailedClip: "Impossible d'ajouter l'extrait au projet",+ addFailedFile: "Impossible d'ajouter le fichier au projet",+ newProjectImage: "Ajouter l'image à un nouveau projet",+ newProjectVideo: "Ajouter la vidéo à un nouveau projet",+ newProjectClip: "Ajouter l'extrait à un nouveau projet",+ newProjectFile: "Ajouter le fichier à un nouveau projet",+ },+ toast: {+ missingItem: "Ce fichier n'est plus dans la Bibliothèque",+ moveFailed: "Impossible de déplacer",+ movedToFolder: "Déplacé vers {folder}",+ movedToLibrary: "Déplacé vers la Bibliothèque",+ folderFallback: "dossier",+ favoritesFailed: "Impossible de mettre à jour les favoris",+ addedToFavorites: "Ajouté aux favoris",+ removedFromFavorites: "Retiré des favoris",+ uploadingOne: "Importation de {name}…",+ uploadingMany: "Importation de {count} fichiers…",+ uploadedOne: "Fichier importé",+ uploadedMany: "{count} fichiers importés",+ uploadFailed: "Échec de l'importation",+ uploadTooLarge: "{name} dépasse 512 Mo.",+ readDropsFailed: "Impossible de lire les fichiers déposés",+ createNoteFailed: "Impossible de créer la note",+ renameFailed: "Impossible de renommer",+ createFolderFailed: "Impossible de créer le dossier",+ signedOutBeforeFolder: "Déconnecté avant la création du dossier.",+ signedOutBeforeSave: "Déconnecté avant l'enregistrement de la modification.",+ signedOutBeforeUpload: "Déconnecté avant la fin de l'importation.",+ deleteFailed: "Certains éléments n'ont pas pu être supprimés",+ saveFailed: "Impossible d'enregistrer",+ saveNoteFirst: "Enregistrez d'abord la note.",+ revealFailed: "Impossible d'ouvrir le gestionnaire de fichiers",+ downloadFailed: "Impossible de télécharger {name}",+ downloadManyFailed: "Impossible de télécharger les fichiers",+ downloadingMany: "Téléchargement de {count} fichiers",+ downloadingManyDescription: "Si votre navigateur le demande, autorisez ce site à télécharger plusieurs fichiers.",+ preparingMany: "Préparation de {count} fichiers…",+ zipFileName: "Fichiers de la Bibliothèque",+ nothingToChat: "Rien à discuter pour l'instant",+ emptyFolder: "Ce dossier ne contient aucun fichier.",+ tooLargeOne: "{name} est trop volumineux pour être joint",+ tooLargeMany: "Ces fichiers sont trop volumineux pour être joints",+ attachedOne: "{count} fichier joint",+ attachedMany: "{count} fichiers joints",+ skippedTooLarge: "{count} trop volumineux pour être joints.",+ skippedOverLimit: "{count} de plus au-delà de la limite de {limit} fichiers.",+ chatFilesWaiting: "{count} seront joints dès qu'un modèle capable de les lire sera chargé.",+ openFilesFailed: "Impossible d'ouvrir les fichiers",+ speechModel: "{name} est un modèle vocal",+ speechModelDescription: "Sélectionnez-le dans le menu des modèles de la page Audio.",+ noMediaLink: "Le serveur n'a renvoyé aucun lien pour lire ce fichier.",+ imageNotFound: "Impossible de trouver cette image",+ clipNotFound: "Impossible de trouver cet extrait",+ notFoundDescription: "Cet élément a peut-être été archivé ou supprimé.",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 8571978a11c..545e0317827 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -159,6 +159,7 @@ export const hi = {search: "खोजें",hub: "मॉडल हब",projects: "प्रोजेक्ट",+ library: "लाइब्रेरी",train: "ट्रेनिंग",recipes: "रेसिपी",images: "इमेज",@@ -2148,8 +2149,7 @@ export const hi = {},},studio: {- imageTraining: "इमेज ट्रेनिंग",- goToImageTraining: "इमेज ट्रेनिंग पर जाएं",+ goToLibrary: "लाइब्रेरी पर जाएं",routeTitle: "ट्रेनिंग",wizard: {modelTitle: "मॉडल",@@ -2867,4 +2867,235 @@ export const hi = {updateError: "कौशल अपडेट नहीं हो सका",mentions: "कौशल",},+ library: {+ tabs: {+ ariaLabel: "लाइब्रेरी के सेक्शन",+ suggested: "सुझाए गए",+ favorites: "पसंदीदा",+ folders: "फ़ोल्डर",+ images: "इमेज",+ videos: "वीडियो",+ audio: "ऑडियो",+ models: "फ़ाइन-ट्यून",+ all: "सभी",+ },+ empty: {+ suggestedTitle: "आपकी लाइब्रेरी खाली है",+ suggestedDescription: "आप जो फ़ाइलें अपलोड करते हैं या चैट में बनाते हैं, वे यहाँ दिखती हैं।",+ favoritesTitle: "अभी कोई पसंदीदा नहीं",+ favoritesDescription: "फ़ाइलों को पसंदीदा में जोड़ें ताकि वे यहाँ जल्दी मिल सकें।",+ foldersTitle: "अपना पहला फ़ोल्डर बनाएँ",+ foldersDescription: "अपनी लाइब्रेरी के आइटम व्यवस्थित करने के लिए फ़ोल्डर बनाएँ।",+ imagesTitle: "अभी कोई इमेज नहीं",+ imagesDescription: "आप जो इमेज अपलोड या जनरेट करते हैं, वे यहाँ दिखती हैं।",+ videosTitle: "अभी कोई वीडियो नहीं",+ videosDescription: "आप जो वीडियो अपलोड या जनरेट करते हैं, वे यहाँ दिखते हैं।",+ audioTitle: "अभी कोई ऑडियो नहीं",+ audioDescription: "ऑडियो पेज पर जनरेट की गई स्पीच यहाँ दिखती है।",+ modelsTitle: "अभी कोई फ़ाइन-ट्यून किया गया मॉडल नहीं",+ modelsDescription: "Unsloth में आप जो मॉडल ट्रेन या एक्सपोर्ट करते हैं, वे यहाँ दिखते हैं।",+ createFolder: "फ़ोल्डर बनाएँ",+ generateVideo: "वीडियो जनरेट करें",+ generateAudio: "ऑडियो जनरेट करें",+ trainModel: "मॉडल ट्रेन करें",+ uploadFiles: "फ़ाइलें अपलोड करें",+ dropHere: "या फ़ाइलें यहाँ छोड़ें",+ noMatchesTitle: "कोई मिलान नहीं",+ noMatchesDescription: "कोई दूसरी खोज आज़माएँ या फ़िल्टर हटाएँ।",+ loadErrorTitle: "आपकी लाइब्रेरी लोड नहीं हो सकी",+ loadErrorFallback: "कुछ गलत हो गया।",+ tryAgain: "फिर कोशिश करें",+ },+ sections: {+ items: "आइटम",+ },+ breadcrumb: "ब्रेडक्रंब",+ searchLibrary: "लाइब्रेरी में खोजें",+ searchFolder: "फ़ोल्डर में खोजें",+ dropToUpload: "अपलोड करने के लिए छोड़ें",+ dropToUploadInto: '"{folder}" में अपलोड करने के लिए छोड़ें',+ itemCountOne: "{count} आइटम",+ itemCount: "{count} आइटम",+ selectItem: "{name} चुनें",+ selection: {+ startChat: "चैट शुरू करें",+ move: "ले जाएँ",+ clear: "चयन हटाएँ",+ },+ menu: {+ moreActions: "और कार्रवाइयाँ",+ chatAboutThis: "इसके बारे में चैट करें",+ chatWithModel: "इस मॉडल से चैट करें",+ addToFavorites: "पसंदीदा में जोड़ें",+ removeFromFavorites: "पसंदीदा से हटाएँ",+ download: "डाउनलोड करें",+ addToFolder: "फ़ोल्डर में जोड़ें",+ newFolder: "नया फ़ोल्डर",+ noFolder: "लाइब्रेरी (कोई फ़ोल्डर नहीं)",+ deleteFolder: "फ़ोल्डर हटाएँ",+ },+ reveal: {+ finder: "Finder में दिखाएँ",+ explorer: "Explorer में दिखाएँ",+ files: "फ़ोल्डर में दिखाएँ",+ },+ toolbar: {+ filter: "फ़िल्टर",+ source: "स्रोत",+ fileType: "फ़ाइल का प्रकार",+ clearFilters: "फ़िल्टर हटाएँ",+ uploaded: "अपलोड की गई",+ generated: "जनरेट की गई",+ documents: "दस्तावेज़",+ spreadsheets: "स्प्रेडशीट",+ presentations: "प्रेज़ेंटेशन",+ pdfs: "PDF",+ gridView: "ग्रिड व्यू",+ listView: "सूची व्यू",+ settings: "लाइब्रेरी सेटिंग्स",+ },+ create: {+ note: "नोट",+ image: "इमेज",+ video: "वीडियो",+ audio: "ऑडियो",+ model: "मॉडल",+ folder: "फ़ोल्डर",+ untitledNote: "बिना शीर्षक का नोट",+ },+ list: {+ selectAll: "सभी चुनें",+ name: "नाम",+ lastActivity: "पिछली गतिविधि",+ favorite: "पसंदीदा",+ modified: "बदला गया: {time}",+ justNow: "अभी",+ },+ size: {+ bytes: "{value} B",+ kilobytes: "{value} KB",+ megabytes: "{value} MB",+ gigabytes: "{value} GB",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "फुल फ़ाइन-ट्यून",+ loraExport: "LoRA एक्सपोर्ट",+ mergedExport: "मर्ज किया गया एक्सपोर्ट",+ ggufExport: "GGUF एक्सपोर्ट",+ model: "मॉडल",+ },+ dialog: {+ create: "बनाएँ",+ renameFolder: "फ़ोल्डर का नाम बदलें",+ renameFile: "फ़ाइल का नाम बदलें",+ deleteTitle: '"{name}" हटाएँ?',+ deleteManyTitle: "{count} आइटम हटाएँ?",+ deleteManyDescription: "फ़ाइलें अपनी मूल जगह से हटा दी जाती हैं। हटाए गए फ़ोल्डर के अंदर की चीज़ें एक स्तर ऊपर चली जाती हैं।",+ deleteFolderIntoParent: 'अंदर की सारी चीज़ें "{folder}" में चली जाएँगी। कोई फ़ाइल नहीं हटेगी।',+ deleteFolderIntoLibrary: "अंदर की सारी चीज़ें आपकी लाइब्रेरी में चली जाएँगी। कोई फ़ाइल नहीं हटेगी।",+ deleteUpload: "इससे फ़ाइल स्थायी रूप से हट जाएगी।",+ deleteAttachment: "इसे उस चैट से भी हटा दिया जाएगा जिसमें यह अटैच थी।",+ deleteImage: "इसे आपकी इमेज गैलरी से भी हटा दिया जाएगा।",+ deleteVideo: "इसे आपकी वीडियो गैलरी से भी हटा दिया जाएगा।",+ deleteAudio: "इसे आपकी ऑडियो गैलरी से भी हटा दिया जाएगा।",+ deleteSandbox: "इसे उस चैट से भी हटा दिया जाएगा जिसने इसे बनाया था।",+ unsavedTitle: "आपके बदलाव सेव नहीं हुए",+ unsavedDescription: "{reason} फिर कोशिश करें, या फ़ाइल बंद करने के लिए अपने बदलाव छोड़ दें।",+ keepEditing: "एडिट करते रहें",+ discardChanges: "बदलाव छोड़ें",+ },+ preview: {+ code: "कोड",+ preview: "प्रीव्यू",+ viewOriginalChat: "मूल चैट देखें",+ viewInImages: "इमेज पेज में देखें",+ viewInVideo: "वीडियो पेज में देखें",+ viewInAudio: "ऑडियो पेज में देखें",+ cannotPreview: "इस फ़ाइल का प्रीव्यू यहाँ नहीं दिखाया जा सकता। इसे खोलने के लिए डाउनलोड करें।",+ noPreview: "इस प्रकार की फ़ाइल का कोई प्रीव्यू नहीं है।",+ tooLargeToPreview: "यह फ़ाइल यहाँ प्रीव्यू के लिए बहुत बड़ी है। इसे खोलने के लिए डाउनलोड करें।",+ startWriting: "लिखना शुरू करें…",+ type: "प्रकार",+ baseModel: "बेस मॉडल",+ size: "आकार",+ location: "स्थान",+ unknown: "अज्ञात",+ readOnlyUtf16: "यह फ़ाइल मान्य UTF-16 टेक्स्ट नहीं है, इसलिए यहाँ सिर्फ़ पढ़ने के लिए खुलती है।",+ readOnlyNotUtf8: "यह फ़ाइल UTF-8 टेक्स्ट नहीं है, इसलिए यहाँ सिर्फ़ पढ़ने के लिए खुलती है। कुछ अक्षर सही से न दिखें, ऐसा हो सकता है।",+ },+ viewer: {+ scale: "स्केल",+ fit: "फ़िट",+ moreActionsImage: "इस इमेज के लिए और कार्रवाइयाँ",+ moreActionsVideo: "इस वीडियो के लिए और कार्रवाइयाँ",+ moreActionsClip: "इस क्लिप के लिए और कार्रवाइयाँ",+ moreActionsFile: "इस फ़ाइल के लिए और कार्रवाइयाँ",+ },+ project: {+ label: "प्रोजेक्ट",+ newProject: "नया प्रोजेक्ट",+ noProjects: "अभी कोई प्रोजेक्ट नहीं",+ alreadyIn: "पहले से {project} में है",+ addedTo: "{project} में जोड़ा गया",+ createAndAdd: "बनाएँ और जोड़ें",+ addFailedImage: "इमेज को प्रोजेक्ट में नहीं जोड़ा जा सका",+ addFailedVideo: "वीडियो को प्रोजेक्ट में नहीं जोड़ा जा सका",+ addFailedClip: "क्लिप को प्रोजेक्ट में नहीं जोड़ा जा सका",+ addFailedFile: "फ़ाइल को प्रोजेक्ट में नहीं जोड़ा जा सका",+ newProjectImage: "इमेज को नए प्रोजेक्ट में जोड़ें",+ newProjectVideo: "वीडियो को नए प्रोजेक्ट में जोड़ें",+ newProjectClip: "क्लिप को नए प्रोजेक्ट में जोड़ें",+ newProjectFile: "फ़ाइल को नए प्रोजेक्ट में जोड़ें",+ },+ toast: {+ missingItem: "वह फ़ाइल अब लाइब्रेरी में नहीं है",+ moveFailed: "ले जाया नहीं जा सका",+ movedToFolder: "{folder} में ले जाया गया",+ movedToLibrary: "लाइब्रेरी में ले जाया गया",+ folderFallback: "फ़ोल्डर",+ favoritesFailed: "पसंदीदा अपडेट नहीं हो सके",+ addedToFavorites: "पसंदीदा में जोड़ा गया",+ removedFromFavorites: "पसंदीदा से हटाया गया",+ uploadingOne: "{name} अपलोड हो रही है…",+ uploadingMany: "{count} फ़ाइलें अपलोड हो रही हैं…",+ uploadedOne: "फ़ाइल अपलोड हो गई",+ uploadedMany: "{count} फ़ाइलें अपलोड हो गईं",+ uploadFailed: "अपलोड विफल रहा",+ uploadTooLarge: "{name} 512 MB से बड़ी है।",+ readDropsFailed: "छोड़ी गई फ़ाइलें पढ़ी नहीं जा सकीं",+ createNoteFailed: "नोट नहीं बनाया जा सका",+ renameFailed: "नाम नहीं बदला जा सका",+ createFolderFailed: "फ़ोल्डर नहीं बनाया जा सका",+ signedOutBeforeFolder: "फ़ोल्डर बनने से पहले ही साइन आउट हो गया।",+ signedOutBeforeSave: "बदलाव सेव होने से पहले ही साइन आउट हो गया।",+ signedOutBeforeUpload: "अपलोड पूरा होने से पहले ही साइन आउट हो गया।",+ deleteFailed: "कुछ आइटम हटाए नहीं जा सके",+ saveFailed: "सेव नहीं हो सका",+ saveNoteFirst: "पहले नोट सेव करें।",+ revealFailed: "फ़ाइल मैनेजर नहीं खोला जा सका",+ downloadFailed: "{name} डाउनलोड नहीं हो सकी",+ downloadManyFailed: "फ़ाइलें डाउनलोड नहीं हो सकीं",+ downloadingMany: "{count} फ़ाइलें डाउनलोड हो रही हैं",+ downloadingManyDescription: "अगर आपका ब्राउज़र पूछे, तो इस साइट को कई फ़ाइलें डाउनलोड करने की अनुमति दें।",+ preparingMany: "{count} फ़ाइलें तैयार की जा रही हैं…",+ zipFileName: "लाइब्रेरी फ़ाइलें",+ nothingToChat: "अभी चैट करने के लिए कुछ नहीं है",+ emptyFolder: "इस फ़ोल्डर में कोई फ़ाइल नहीं है।",+ tooLargeOne: "{name} अटैच करने के लिए बहुत बड़ी है",+ tooLargeMany: "ये फ़ाइलें अटैच करने के लिए बहुत बड़ी हैं",+ attachedOne: "{count} फ़ाइल अटैच की गई",+ attachedMany: "{count} फ़ाइलें अटैच की गईं",+ skippedTooLarge: "{count} अटैच करने के लिए बहुत बड़ी हैं।",+ skippedOverLimit: "{limit} फ़ाइलों की सीमा से {count} और ज़्यादा हैं।",+ chatFilesWaiting: "{count} फ़ाइलें तब अटैच होंगी जब उन्हें पढ़ सकने वाला मॉडल लोड हो जाएगा।",+ openFilesFailed: "फ़ाइलें खोली नहीं जा सकीं",+ speechModel: "{name} एक स्पीच मॉडल है",+ speechModelDescription: "इसे ऑडियो पेज के मॉडल मेनू से चुनें।",+ noMediaLink: "सर्वर ने इस फ़ाइल को चलाने के लिए कोई लिंक नहीं लौटाया।",+ imageNotFound: "यह इमेज नहीं मिली",+ clipNotFound: "यह क्लिप नहीं मिली",+ notFoundDescription: "हो सकता है इसे संग्रहीत या हटा दिया गया हो।",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 1e406cdead7..5315203ec98 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -123,6 +123,7 @@ export const it = {search: "Cerca",hub: "Hub dei modelli",projects: "Progetti",+ library: "Libreria",train: "Addestra",recipes: "Ricette",images: "Immagini",@@ -2186,8 +2187,7 @@ export const it = {},},studio: {- imageTraining: "Addestramento immagini",- goToImageTraining: "Vai all'addestramento immagini",+ goToLibrary: "Vai alla Libreria",routeTitle: "Addestra",wizard: {modelTitle: "Modello",@@ -2927,4 +2927,235 @@ export const it = {updateError: "Impossibile aggiornare la competenza",mentions: "Competenze",},+ library: {+ tabs: {+ ariaLabel: "Sezioni della Libreria",+ suggested: "Suggeriti",+ favorites: "Preferiti",+ folders: "Cartelle",+ images: "Immagini",+ videos: "Video",+ audio: "Audio",+ models: "Fine-tune",+ all: "Tutti",+ },+ empty: {+ suggestedTitle: "La tua libreria è vuota",+ suggestedDescription: "I file che carichi o crei nelle chat compaiono qui.",+ favoritesTitle: "Ancora nessun preferito",+ favoritesDescription: "Aggiungi file ai preferiti per ritrovarli qui velocemente.",+ foldersTitle: "Crea la tua prima cartella",+ foldersDescription: "Crea cartelle per organizzare gli elementi della tua libreria.",+ imagesTitle: "Ancora nessuna immagine",+ imagesDescription: "Le immagini che carichi o generi compaiono qui.",+ videosTitle: "Ancora nessun video",+ videosDescription: "I video che carichi o generi compaiono qui.",+ audioTitle: "Ancora nessun audio",+ audioDescription: "Il parlato che generi nella pagina Audio compare qui.",+ modelsTitle: "Ancora nessun modello con fine-tuning",+ modelsDescription: "I modelli che addestri o esporti in Unsloth compaiono qui.",+ createFolder: "Crea cartella",+ generateVideo: "Genera un video",+ generateAudio: "Genera audio",+ trainModel: "Addestra un modello",+ uploadFiles: "Carica file",+ dropHere: "oppure trascina qui i file",+ noMatchesTitle: "Nessun risultato",+ noMatchesDescription: "Prova un'altra ricerca o rimuovi i filtri.",+ loadErrorTitle: "Impossibile caricare la tua Libreria",+ loadErrorFallback: "Qualcosa è andato storto.",+ tryAgain: "Riprova",+ },+ sections: {+ items: "Elementi",+ },+ breadcrumb: "Percorso di navigazione",+ searchLibrary: "Cerca nella libreria",+ searchFolder: "Cerca nella cartella",+ dropToUpload: "Rilascia per caricare",+ dropToUploadInto: "Rilascia per caricare in «{folder}»",+ itemCountOne: "{count} elemento",+ itemCount: "{count} elementi",+ selectItem: "Seleziona {name}",+ selection: {+ startChat: "Avvia chat",+ move: "Sposta",+ clear: "Annulla selezione",+ },+ menu: {+ moreActions: "Altre azioni",+ chatAboutThis: "Chatta su questo",+ chatWithModel: "Chatta con questo modello",+ addToFavorites: "Aggiungi ai preferiti",+ removeFromFavorites: "Rimuovi dai preferiti",+ download: "Scarica",+ addToFolder: "Aggiungi a cartella",+ newFolder: "Nuova cartella",+ noFolder: "Libreria (nessuna cartella)",+ deleteFolder: "Elimina cartella",+ },+ reveal: {+ finder: "Mostra nel Finder",+ explorer: "Mostra in Esplora risorse",+ files: "Mostra nella cartella",+ },+ toolbar: {+ filter: "Filtra",+ source: "Origine",+ fileType: "Tipo di file",+ clearFilters: "Rimuovi filtri",+ uploaded: "Caricati",+ generated: "Generati",+ documents: "Documenti",+ spreadsheets: "Fogli di calcolo",+ presentations: "Presentazioni",+ pdfs: "PDF",+ gridView: "Vista a griglia",+ listView: "Vista a elenco",+ settings: "Impostazioni della Libreria",+ },+ create: {+ note: "Nota",+ image: "Immagine",+ video: "Video",+ audio: "Audio",+ model: "Modello",+ folder: "Cartella",+ untitledNote: "Nota senza titolo",+ },+ list: {+ selectAll: "Seleziona tutto",+ name: "Nome",+ lastActivity: "Ultima attività",+ favorite: "Preferito",+ modified: "Modificato {time}",+ justNow: "proprio ora",+ },+ size: {+ bytes: "{value} B",+ kilobytes: "{value} KB",+ megabytes: "{value} MB",+ gigabytes: "{value} GB",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "Fine-tuning completo",+ loraExport: "Esportazione LoRA",+ mergedExport: "Esportazione unita",+ ggufExport: "Esportazione GGUF",+ model: "Modello",+ },+ dialog: {+ create: "Crea",+ renameFolder: "Rinomina cartella",+ renameFile: "Rinomina file",+ deleteTitle: "Eliminare «{name}»?",+ deleteManyTitle: "Eliminare {count} elementi?",+ deleteManyDescription: "I file vengono eliminati dalla loro posizione. Il contenuto di una cartella eliminata sale di un livello.",+ deleteFolderIntoParent: "Tutto il contenuto viene spostato in «{folder}». Nessun file viene eliminato.",+ deleteFolderIntoLibrary: "Tutto il contenuto viene spostato nella tua Libreria. Nessun file viene eliminato.",+ deleteUpload: "Il file verrà eliminato definitivamente.",+ deleteAttachment: "Verrà rimosso anche dalla chat a cui era allegato.",+ deleteImage: "Verrà rimosso anche dalla tua galleria Immagini.",+ 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.",+ unsavedTitle: "Le modifiche non sono state salvate",+ unsavedDescription: "{reason} Riprova, oppure annulla le modifiche per chiudere il file.",+ keepEditing: "Continua a modificare",+ discardChanges: "Annulla modifiche",+ },+ preview: {+ code: "Codice",+ preview: "Anteprima",+ viewOriginalChat: "Vai alla chat originale",+ viewInImages: "Vedi in Immagini",+ viewInVideo: "Vedi in Video",+ viewInAudio: "Vedi in Audio",+ cannotPreview: "Impossibile visualizzare l'anteprima di questo file qui. Scaricalo per aprirlo.",+ noPreview: "Nessuna anteprima per questo tipo di file.",+ tooLargeToPreview: "Questo file è troppo grande per l'anteprima. Scaricalo per aprirlo.",+ startWriting: "Inizia a scrivere…",+ type: "Tipo",+ baseModel: "Modello base",+ size: "Dimensione",+ location: "Posizione",+ unknown: "Sconosciuto",+ readOnlyUtf16: "Questo file non è testo UTF-16 valido, quindi qui si apre in sola lettura.",+ readOnlyNotUtf8: "Questo file non è testo UTF-8, quindi qui si apre in sola lettura. Alcuni caratteri potrebbero non essere visualizzati correttamente.",+ },+ viewer: {+ scale: "Scala",+ fit: "Adatta",+ moreActionsImage: "Altre azioni per questa immagine",+ moreActionsVideo: "Altre azioni per questo video",+ moreActionsClip: "Altre azioni per questa clip",+ moreActionsFile: "Altre azioni per questo file",+ },+ project: {+ label: "Progetto",+ newProject: "Nuovo progetto",+ noProjects: "Ancora nessun progetto",+ alreadyIn: "Già in {project}",+ addedTo: "Aggiunto a {project}",+ createAndAdd: "Crea e aggiungi",+ addFailedImage: "Impossibile aggiungere l'immagine al progetto",+ addFailedVideo: "Impossibile aggiungere il video al progetto",+ addFailedClip: "Impossibile aggiungere la clip al progetto",+ addFailedFile: "Impossibile aggiungere il file al progetto",+ newProjectImage: "Aggiungi l'immagine a un nuovo progetto",+ newProjectVideo: "Aggiungi il video a un nuovo progetto",+ newProjectClip: "Aggiungi la clip a un nuovo progetto",+ newProjectFile: "Aggiungi il file a un nuovo progetto",+ },+ toast: {+ missingItem: "Quel file non è più nella Libreria",+ moveFailed: "Impossibile spostare",+ movedToFolder: "Spostato in {folder}",+ movedToLibrary: "Spostato nella Libreria",+ folderFallback: "cartella",+ favoritesFailed: "Impossibile aggiornare i preferiti",+ addedToFavorites: "Aggiunto ai preferiti",+ removedFromFavorites: "Rimosso dai preferiti",+ uploadingOne: "Caricamento di {name}…",+ uploadingMany: "Caricamento di {count} file…",+ uploadedOne: "File caricato",+ uploadedMany: "{count} file caricati",+ uploadFailed: "Caricamento non riuscito",+ uploadTooLarge: "{name} supera i 512 MB.",+ readDropsFailed: "Impossibile leggere i file rilasciati",+ createNoteFailed: "Impossibile creare la nota",+ renameFailed: "Impossibile rinominare",+ createFolderFailed: "Impossibile creare la cartella",+ signedOutBeforeFolder: "Disconnesso prima che la cartella venisse creata.",+ signedOutBeforeSave: "Disconnesso prima che la modifica venisse salvata.",+ signedOutBeforeUpload: "Disconnesso prima che il caricamento terminasse.",+ deleteFailed: "Non è stato possibile eliminare alcuni elementi",+ saveFailed: "Impossibile salvare",+ saveNoteFirst: "Salva prima la nota.",+ revealFailed: "Impossibile aprire il gestore file",+ downloadFailed: "Impossibile scaricare {name}",+ downloadManyFailed: "Impossibile scaricare i file",+ downloadingMany: "Download di {count} file",+ downloadingManyDescription: "Se il browser lo chiede, consenti a questo sito di scaricare più file.",+ preparingMany: "Preparazione di {count} file…",+ zipFileName: "File della Libreria",+ nothingToChat: "Ancora niente di cui chattare",+ emptyFolder: "Questa cartella non contiene file.",+ tooLargeOne: "{name} è troppo grande per essere allegato",+ tooLargeMany: "Questi file sono troppo grandi per essere allegati",+ attachedOne: "{count} file allegato",+ attachedMany: "{count} file allegati",+ skippedTooLarge: "{count} troppo grandi per essere allegati.",+ skippedOverLimit: "Altri {count} oltre il limite di {limit} file.",+ chatFilesWaiting: "{count} verranno allegati appena sarà caricato un modello in grado di leggerli.",+ openFilesFailed: "Impossibile aprire i file",+ speechModel: "{name} è un modello vocale",+ speechModelDescription: "Sceglilo dal menu dei modelli nella pagina Audio.",+ noMediaLink: "Il server non ha restituito alcun link per riprodurre questo file.",+ imageNotFound: "Impossibile trovare questa immagine",+ clipNotFound: "Impossibile trovare questa clip",+ notFoundDescription: "L'elemento potrebbe essere stato archiviato o eliminato.",+ },+ },} as const;diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 0a0a7dc1a20..b8578653d9a 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -158,6 +158,7 @@ export const ja = {search: "検索",hub: "モデルハブ",projects: "プロジェクト",+ library: "ライブラリ",train: "トレーニング",recipes: "レシピ",images: "画像",@@ -2107,8 +2108,7 @@ export const ja = {},},studio: {- imageTraining: "画像トレーニング",- goToImageTraining: "画像トレーニングへ移動",+ goToLibrary: "ライブラリへ移動",routeTitle: "トレーニング",wizard: {modelTitle: "モデル",@@ -2808,4 +2808,235 @@ export const ja = {updateError: "スキルを更新できませんでした",mentions: "スキル",},+ library: {+ tabs: {+ ariaLabel: "ライブラリのセクション",+ suggested: "おすすめ",+ favorites: "お気に入り",+ folders: "フォルダ",+ images: "画像",+ videos: "動画",+ audio: "音声",+ models: "ファインチューン",+ all: "すべて",+ },+ empty: {+ suggestedTitle: "ライブラリは空です",+ suggestedDescription: "アップロードしたファイルやチャットで作成したファイルがここに表示されます。",+ favoritesTitle: "お気に入りはまだありません",+ favoritesDescription: "ファイルをお気に入りに追加すると、ここですぐに見つけられます。",+ foldersTitle: "最初のフォルダを作成しましょう",+ foldersDescription: "フォルダを作成して、ライブラリの項目を整理できます。",+ imagesTitle: "画像はまだありません",+ imagesDescription: "アップロードまたは生成した画像がここに表示されます。",+ videosTitle: "動画はまだありません",+ videosDescription: "アップロードまたは生成した動画がここに表示されます。",+ audioTitle: "音声はまだありません",+ audioDescription: "音声ページで生成した音声がここに表示されます。",+ modelsTitle: "ファインチューニング済みモデルはまだありません",+ modelsDescription: "Unsloth でトレーニングまたはエクスポートしたモデルがここに表示されます。",+ createFolder: "フォルダを作成",+ generateVideo: "動画を生成",+ generateAudio: "音声を生成",+ trainModel: "モデルをトレーニング",+ uploadFiles: "ファイルをアップロード",+ dropHere: "またはここにファイルをドロップ",+ noMatchesTitle: "一致する項目はありません",+ noMatchesDescription: "検索条件を変えるか、フィルタをクリアしてください。",+ loadErrorTitle: "ライブラリを読み込めませんでした",+ loadErrorFallback: "問題が発生しました。",+ tryAgain: "再試行",+ },+ sections: {+ items: "項目",+ },+ breadcrumb: "パンくずリスト",+ searchLibrary: "ライブラリを検索",+ searchFolder: "フォルダ内を検索",+ dropToUpload: "ドロップしてアップロード",+ dropToUploadInto: "ドロップして「{folder}」にアップロード",+ itemCountOne: "{count} 件",+ itemCount: "{count} 件",+ selectItem: "{name} を選択",+ selection: {+ startChat: "チャットを開始",+ move: "移動",+ clear: "選択を解除",+ },+ menu: {+ moreActions: "その他の操作",+ chatAboutThis: "これについてチャット",+ chatWithModel: "このモデルとチャット",+ addToFavorites: "お気に入りに追加",+ removeFromFavorites: "お気に入りから削除",+ download: "ダウンロード",+ addToFolder: "フォルダに追加",+ newFolder: "新規フォルダ",+ noFolder: "ライブラリ(フォルダなし)",+ deleteFolder: "フォルダを削除",+ },+ reveal: {+ finder: "Finder で表示",+ explorer: "エクスプローラーで表示",+ files: "フォルダで表示",+ },+ toolbar: {+ filter: "フィルタ",+ source: "ソース",+ fileType: "ファイルの種類",+ clearFilters: "フィルタをクリア",+ uploaded: "アップロード済み",+ generated: "生成済み",+ documents: "ドキュメント",+ spreadsheets: "スプレッドシート",+ presentations: "プレゼンテーション",+ pdfs: "PDF",+ gridView: "グリッド表示",+ listView: "リスト表示",+ settings: "ライブラリの設定",+ },+ create: {+ note: "メモ",+ image: "画像",+ video: "動画",+ audio: "音声",+ model: "モデル",+ folder: "フォルダ",+ untitledNote: "無題のメモ",+ },+ list: {+ selectAll: "すべて選択",+ name: "名前",+ lastActivity: "最終更新",+ favorite: "お気に入り",+ modified: "変更: {time}",+ justNow: "たった今",+ },+ size: {+ bytes: "{value} B",+ kilobytes: "{value} KB",+ megabytes: "{value} MB",+ gigabytes: "{value} GB",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "フルファインチューニング",+ loraExport: "LoRA エクスポート",+ mergedExport: "マージ済みエクスポート",+ ggufExport: "GGUF エクスポート",+ model: "モデル",+ },+ dialog: {+ create: "作成",+ renameFolder: "フォルダ名を変更",+ renameFile: "ファイル名を変更",+ deleteTitle: "「{name}」を削除しますか?",+ deleteManyTitle: "{count} 件の項目を削除しますか?",+ deleteManyDescription: "ファイルは保存場所から削除されます。削除したフォルダ内の項目は 1 つ上の階層に移動します。",+ deleteFolderIntoParent: "中身はすべて「{folder}」に移動します。ファイルは削除されません。",+ deleteFolderIntoLibrary: "中身はすべてライブラリに移動します。ファイルは削除されません。",+ deleteUpload: "このファイルは完全に削除されます。",+ deleteAttachment: "添付されていたチャットからも削除されます。",+ deleteImage: "画像ギャラリーからも削除されます。",+ deleteVideo: "動画ギャラリーからも削除されます。",+ deleteAudio: "音声ギャラリーからも削除されます。",+ deleteSandbox: "このファイルを作成したチャットからも削除されます。",+ unsavedTitle: "変更は保存されていません",+ unsavedDescription: "{reason} もう一度試すか、変更を破棄してファイルを閉じてください。",+ keepEditing: "編集を続ける",+ discardChanges: "変更を破棄",+ },+ preview: {+ code: "コード",+ preview: "プレビュー",+ viewOriginalChat: "元のチャットを表示",+ viewInImages: "画像ページで表示",+ viewInVideo: "動画ページで表示",+ viewInAudio: "音声ページで表示",+ cannotPreview: "このファイルはここではプレビューできません。ダウンロードして開いてください。",+ noPreview: "この種類のファイルはプレビューできません。",+ tooLargeToPreview: "このファイルは大きすぎるため、ここではプレビューできません。ダウンロードして開いてください。",+ startWriting: "書き始めましょう…",+ type: "種類",+ baseModel: "ベースモデル",+ size: "サイズ",+ location: "場所",+ unknown: "不明",+ readOnlyUtf16: "このファイルは有効な UTF-16 テキストではないため、ここでは読み取り専用で開きます。",+ readOnlyNotUtf8: "このファイルは UTF-8 テキストではないため、ここでは読み取り専用で開きます。一部の文字が正しく表示されない場合があります。",+ },+ viewer: {+ scale: "拡大率",+ fit: "フィット",+ moreActionsImage: "この画像のその他の操作",+ moreActionsVideo: "この動画のその他の操作",+ moreActionsClip: "このクリップのその他の操作",+ moreActionsFile: "このファイルのその他の操作",+ },+ project: {+ label: "プロジェクト",+ newProject: "新規プロジェクト",+ noProjects: "プロジェクトはまだありません",+ alreadyIn: "すでに {project} にあります",+ addedTo: "{project} に追加しました",+ createAndAdd: "作成して追加",+ addFailedImage: "画像をプロジェクトに追加できませんでした",+ addFailedVideo: "動画をプロジェクトに追加できませんでした",+ addFailedClip: "クリップをプロジェクトに追加できませんでした",+ addFailedFile: "ファイルをプロジェクトに追加できませんでした",+ newProjectImage: "画像を新規プロジェクトに追加",+ newProjectVideo: "動画を新規プロジェクトに追加",+ newProjectClip: "クリップを新規プロジェクトに追加",+ newProjectFile: "ファイルを新規プロジェクトに追加",+ },+ toast: {+ missingItem: "このファイルはライブラリにありません",+ moveFailed: "移動できませんでした",+ movedToFolder: "{folder} に移動しました",+ movedToLibrary: "ライブラリに移動しました",+ folderFallback: "フォルダ",+ favoritesFailed: "お気に入りを更新できませんでした",+ addedToFavorites: "お気に入りに追加しました",+ removedFromFavorites: "お気に入りから削除しました",+ uploadingOne: "{name} をアップロードしています…",+ uploadingMany: "{count} 個のファイルをアップロードしています…",+ uploadedOne: "ファイルをアップロードしました",+ uploadedMany: "{count} 個のファイルをアップロードしました",+ uploadFailed: "アップロードに失敗しました",+ uploadTooLarge: "{name} は 512 MB を超えています。",+ readDropsFailed: "ドロップされたファイルを読み取れませんでした",+ createNoteFailed: "メモを作成できませんでした",+ renameFailed: "名前を変更できませんでした",+ createFolderFailed: "フォルダを作成できませんでした",+ signedOutBeforeFolder: "フォルダの作成前にサインアウトされました。",+ signedOutBeforeSave: "変更の保存前にサインアウトされました。",+ signedOutBeforeUpload: "アップロードの完了前にサインアウトされました。",+ deleteFailed: "一部の項目を削除できませんでした",+ saveFailed: "保存できませんでした",+ saveNoteFirst: "先にメモを保存してください。",+ revealFailed: "ファイルマネージャーを開けませんでした",+ downloadFailed: "{name} をダウンロードできませんでした",+ downloadManyFailed: "ファイルをダウンロードできませんでした",+ downloadingMany: "{count} 個のファイルをダウンロードしています",+ downloadingManyDescription: "ブラウザで確認が表示されたら、このサイトに複数ファイルのダウンロードを許可してください。",+ preparingMany: "{count} 個のファイルを準備しています…",+ zipFileName: "ライブラリのファイル",+ nothingToChat: "チャットで扱えるものがまだありません",+ emptyFolder: "このフォルダにはファイルがありません。",+ tooLargeOne: "{name} は大きすぎるため添付できません",+ tooLargeMany: "これらのファイルは大きすぎるため添付できません",+ attachedOne: "{count} 個のファイルを添付しました",+ attachedMany: "{count} 個のファイルを添付しました",+ skippedTooLarge: "{count} 個は大きすぎるため添付できません。",+ skippedOverLimit: "{limit} ファイルの上限を超えた {count} 個は添付されていません。",+ chatFilesWaiting: "{count} 個は、読み取れるモデルが読み込まれると添付されます。",+ openFilesFailed: "ファイルを開けませんでした",+ speechModel: "{name} は音声モデルです",+ speechModelDescription: "音声ページのモデルメニューから選択してください。",+ noMediaLink: "サーバーからこのファイルを再生するためのリンクが返されませんでした。",+ imageNotFound: "この画像が見つかりませんでした",+ clipNotFound: "このクリップが見つかりませんでした",+ notFoundDescription: "アーカイブまたは削除された可能性があります。",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex be348d1976b..2d88f1682fb 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -156,6 +156,7 @@ export const ko = {search: "검색",hub: "모델 허브",projects: "프로젝트",+ library: "라이브러리",train: "학습",recipes: "레시피",images: "이미지",@@ -2134,8 +2135,7 @@ export const ko = {},},studio: {- imageTraining: "이미지 학습",- goToImageTraining: "이미지 학습으로 이동",+ goToLibrary: "라이브러리로 이동",routeTitle: "학습",wizard: {modelTitle: "모델",@@ -2854,4 +2854,235 @@ export const ko = {updateError: "스킬을 업데이트할 수 없습니다",mentions: "스킬",},+ library: {+ tabs: {+ ariaLabel: "라이브러리 섹션",+ suggested: "추천",+ favorites: "즐겨찾기",+ folders: "폴더",+ images: "이미지",+ videos: "동영상",+ audio: "오디오",+ models: "파인튜닝",+ all: "전체",+ },+ empty: {+ suggestedTitle: "라이브러리가 비어 있습니다",+ suggestedDescription: "업로드하거나 채팅에서 만든 파일이 여기에 표시됩니다.",+ favoritesTitle: "아직 즐겨찾기가 없습니다",+ favoritesDescription: "파일을 즐겨찾기에 추가하면 여기에서 빠르게 찾을 수 있습니다.",+ foldersTitle: "첫 폴더를 만들어 보세요",+ foldersDescription: "폴더를 만들어 라이브러리의 항목을 정리하세요.",+ imagesTitle: "아직 이미지가 없습니다",+ imagesDescription: "업로드하거나 생성한 이미지가 여기에 표시됩니다.",+ videosTitle: "아직 동영상이 없습니다",+ videosDescription: "업로드하거나 생성한 동영상이 여기에 표시됩니다.",+ audioTitle: "아직 오디오가 없습니다",+ audioDescription: "오디오 페이지에서 생성한 음성이 여기에 표시됩니다.",+ modelsTitle: "아직 파인튜닝된 모델이 없습니다",+ modelsDescription: "Unsloth에서 학습하거나 내보낸 모델이 여기에 표시됩니다.",+ createFolder: "폴더 만들기",+ generateVideo: "동영상 생성",+ generateAudio: "오디오 생성",+ trainModel: "모델 학습",+ uploadFiles: "파일 업로드",+ dropHere: "또는 여기에 파일을 끌어다 놓으세요",+ noMatchesTitle: "일치하는 항목 없음",+ noMatchesDescription: "다른 검색어를 입력하거나 필터를 지우세요.",+ loadErrorTitle: "라이브러리를 불러오지 못했습니다",+ loadErrorFallback: "문제가 발생했습니다.",+ tryAgain: "다시 시도",+ },+ sections: {+ items: "항목",+ },+ breadcrumb: "이동 경로",+ searchLibrary: "라이브러리 검색",+ searchFolder: "폴더 검색",+ dropToUpload: "놓아서 업로드",+ dropToUploadInto: '놓아서 "{folder}"에 업로드',+ itemCountOne: "항목 {count}개",+ itemCount: "항목 {count}개",+ selectItem: "{name} 선택",+ selection: {+ startChat: "채팅 시작",+ move: "이동",+ clear: "선택 해제",+ },+ menu: {+ moreActions: "추가 작업",+ chatAboutThis: "이 파일로 채팅",+ chatWithModel: "이 모델과 채팅",+ addToFavorites: "즐겨찾기에 추가",+ removeFromFavorites: "즐겨찾기에서 제거",+ download: "다운로드",+ addToFolder: "폴더에 추가",+ newFolder: "새 폴더",+ noFolder: "라이브러리(폴더 없음)",+ deleteFolder: "폴더 삭제",+ },+ reveal: {+ finder: "Finder에서 보기",+ explorer: "탐색기에서 보기",+ files: "폴더에서 보기",+ },+ toolbar: {+ filter: "필터",+ source: "출처",+ fileType: "파일 형식",+ clearFilters: "필터 지우기",+ uploaded: "업로드됨",+ generated: "생성됨",+ documents: "문서",+ spreadsheets: "스프레드시트",+ presentations: "프레젠테이션",+ pdfs: "PDF",+ gridView: "그리드 보기",+ listView: "목록 보기",+ settings: "라이브러리 설정",+ },+ create: {+ note: "메모",+ image: "이미지",+ video: "동영상",+ audio: "오디오",+ model: "모델",+ folder: "폴더",+ untitledNote: "제목 없는 메모",+ },+ list: {+ selectAll: "모두 선택",+ name: "이름",+ lastActivity: "최근 활동",+ favorite: "즐겨찾기",+ modified: "수정: {time}",+ justNow: "방금",+ },+ size: {+ bytes: "{value} B",+ kilobytes: "{value} KB",+ megabytes: "{value} MB",+ gigabytes: "{value} GB",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "전체 파인튜닝",+ loraExport: "LoRA 내보내기",+ mergedExport: "병합 내보내기",+ ggufExport: "GGUF 내보내기",+ model: "모델",+ },+ dialog: {+ create: "만들기",+ renameFolder: "폴더 이름 변경",+ renameFile: "파일 이름 변경",+ deleteTitle: '"{name}"을(를) 삭제할까요?',+ deleteManyTitle: "항목 {count}개를 삭제할까요?",+ deleteManyDescription: "파일은 저장된 위치에서 삭제됩니다. 삭제한 폴더 안의 항목은 한 단계 위로 이동합니다.",+ deleteFolderIntoParent: '안의 모든 항목이 "{folder}"(으)로 이동합니다. 파일은 삭제되지 않습니다.',+ deleteFolderIntoLibrary: "안의 모든 항목이 라이브러리로 이동합니다. 파일은 삭제되지 않습니다.",+ deleteUpload: "파일이 영구적으로 삭제됩니다.",+ deleteAttachment: "첨부되어 있던 채팅에서도 제거됩니다.",+ deleteImage: "이미지 갤러리에서도 제거됩니다.",+ deleteVideo: "동영상 갤러리에서도 제거됩니다.",+ deleteAudio: "오디오 갤러리에서도 제거됩니다.",+ deleteSandbox: "이 파일을 만든 채팅에서도 제거됩니다.",+ unsavedTitle: "변경 사항이 저장되지 않았습니다",+ unsavedDescription: "{reason} 다시 시도하거나 변경 사항을 버리고 파일을 닫으세요.",+ keepEditing: "계속 편집",+ discardChanges: "변경 사항 버리기",+ },+ preview: {+ code: "코드",+ preview: "미리보기",+ viewOriginalChat: "원래 채팅 보기",+ viewInImages: "이미지에서 보기",+ viewInVideo: "동영상에서 보기",+ viewInAudio: "오디오에서 보기",+ cannotPreview: "이 파일은 여기에서 미리 볼 수 없습니다. 다운로드해서 여세요.",+ noPreview: "이 파일 형식은 미리보기를 지원하지 않습니다.",+ tooLargeToPreview: "파일이 너무 커서 여기에서 미리 볼 수 없습니다. 다운로드해서 여세요.",+ startWriting: "작성을 시작하세요…",+ type: "유형",+ baseModel: "기본 모델",+ size: "크기",+ location: "위치",+ unknown: "알 수 없음",+ readOnlyUtf16: "이 파일은 올바른 UTF-16 텍스트가 아니므로 여기에서는 읽기 전용으로 열립니다.",+ readOnlyNotUtf8: "이 파일은 UTF-8 텍스트가 아니므로 여기에서는 읽기 전용으로 열립니다. 일부 문자가 올바르게 표시되지 않을 수 있습니다.",+ },+ viewer: {+ scale: "배율",+ fit: "맞춤",+ moreActionsImage: "이 이미지에 대한 추가 작업",+ moreActionsVideo: "이 동영상에 대한 추가 작업",+ moreActionsClip: "이 클립에 대한 추가 작업",+ moreActionsFile: "이 파일에 대한 추가 작업",+ },+ project: {+ label: "프로젝트",+ newProject: "새 프로젝트",+ noProjects: "아직 프로젝트가 없습니다",+ alreadyIn: "이미 {project}에 있습니다",+ addedTo: "{project}에 추가됨",+ createAndAdd: "만들고 추가",+ addFailedImage: "이미지를 프로젝트에 추가하지 못했습니다",+ addFailedVideo: "동영상을 프로젝트에 추가하지 못했습니다",+ addFailedClip: "클립을 프로젝트에 추가하지 못했습니다",+ addFailedFile: "파일을 프로젝트에 추가하지 못했습니다",+ newProjectImage: "새 프로젝트에 이미지 추가",+ newProjectVideo: "새 프로젝트에 동영상 추가",+ newProjectClip: "새 프로젝트에 클립 추가",+ newProjectFile: "새 프로젝트에 파일 추가",+ },+ toast: {+ missingItem: "이 파일은 더 이상 라이브러리에 없습니다",+ moveFailed: "이동하지 못했습니다",+ movedToFolder: "{folder}(으)로 이동됨",+ movedToLibrary: "라이브러리로 이동됨",+ folderFallback: "폴더",+ favoritesFailed: "즐겨찾기를 업데이트하지 못했습니다",+ addedToFavorites: "즐겨찾기에 추가됨",+ removedFromFavorites: "즐겨찾기에서 제거됨",+ uploadingOne: "{name} 업로드 중…",+ uploadingMany: "파일 {count}개 업로드 중…",+ uploadedOne: "파일 업로드됨",+ uploadedMany: "파일 {count}개 업로드됨",+ uploadFailed: "업로드 실패",+ uploadTooLarge: "{name}이(가) 512MB를 초과합니다.",+ readDropsFailed: "끌어다 놓은 파일을 읽지 못했습니다",+ createNoteFailed: "메모를 만들지 못했습니다",+ renameFailed: "이름을 변경하지 못했습니다",+ createFolderFailed: "폴더를 만들지 못했습니다",+ signedOutBeforeFolder: "폴더가 만들어지기 전에 로그아웃되었습니다.",+ signedOutBeforeSave: "변경 사항이 저장되기 전에 로그아웃되었습니다.",+ signedOutBeforeUpload: "업로드가 끝나기 전에 로그아웃되었습니다.",+ deleteFailed: "일부 항목을 삭제하지 못했습니다",+ saveFailed: "저장하지 못했습니다",+ saveNoteFirst: "먼저 메모를 저장하세요.",+ revealFailed: "파일 관리자를 열지 못했습니다",+ downloadFailed: "{name}을(를) 다운로드하지 못했습니다",+ downloadManyFailed: "파일을 다운로드하지 못했습니다",+ downloadingMany: "파일 {count}개 다운로드 중",+ downloadingManyDescription: "브라우저에서 묻는 경우 이 사이트가 여러 파일을 다운로드하도록 허용하세요.",+ preparingMany: "파일 {count}개 준비 중…",+ zipFileName: "라이브러리 파일",+ nothingToChat: "아직 채팅할 내용이 없습니다",+ emptyFolder: "이 폴더에는 파일이 없습니다.",+ tooLargeOne: "{name}은(는) 너무 커서 첨부할 수 없습니다",+ tooLargeMany: "이 파일들은 너무 커서 첨부할 수 없습니다",+ attachedOne: "파일 {count}개 첨부됨",+ attachedMany: "파일 {count}개 첨부됨",+ skippedTooLarge: "{count}개는 너무 커서 첨부할 수 없습니다.",+ skippedOverLimit: "{limit}개 파일 한도를 넘는 {count}개는 제외되었습니다.",+ chatFilesWaiting: "{count}개는 이를 읽을 수 있는 모델이 로드되면 첨부됩니다.",+ openFilesFailed: "파일을 열지 못했습니다",+ speechModel: "{name}은(는) 음성 모델입니다",+ speechModelDescription: "오디오 페이지의 모델 메뉴에서 선택하세요.",+ noMediaLink: "서버가 이 파일을 재생할 링크를 반환하지 않았습니다.",+ imageNotFound: "이 이미지를 찾을 수 없습니다",+ clipNotFound: "이 클립을 찾을 수 없습니다",+ notFoundDescription: "보관되었거나 삭제되었을 수 있습니다.",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex ca401d84521..e92a8ee80f8 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -158,6 +158,7 @@ export const ptBR = {search: "Buscar",hub: "Hub de modelos",projects: "Projetos",+ library: "Biblioteca",train: "Treinar",recipes: "Receitas",images: "Imagens",@@ -2161,8 +2162,7 @@ export const ptBR = {},},studio: {- imageTraining: "Treinamento de imagens",- goToImageTraining: "Ir para o treinamento de imagens",+ goToLibrary: "Ir para a Biblioteca",routeTitle: "Treinar",wizard: {modelTitle: "Modelo",@@ -2888,4 +2888,235 @@ export const ptBR = {updateError: "Não foi possível atualizar a habilidade",mentions: "Habilidades",},+ library: {+ tabs: {+ ariaLabel: "Seções da Biblioteca",+ suggested: "Sugestões",+ favorites: "Favoritos",+ folders: "Pastas",+ images: "Imagens",+ videos: "Vídeos",+ audio: "Áudio",+ models: "Fine-tunes",+ all: "Tudo",+ },+ empty: {+ suggestedTitle: "Sua biblioteca está vazia",+ suggestedDescription: "Os arquivos que você envia ou cria nos chats aparecem aqui.",+ favoritesTitle: "Nenhum favorito ainda",+ favoritesDescription: "Adicione arquivos aos favoritos para encontrá-los aqui rapidamente.",+ foldersTitle: "Crie sua primeira pasta",+ foldersDescription: "Crie pastas para organizar os itens da sua biblioteca.",+ imagesTitle: "Nenhuma imagem ainda",+ imagesDescription: "As imagens que você envia ou gera aparecem aqui.",+ videosTitle: "Nenhum vídeo ainda",+ videosDescription: "Os vídeos que você envia ou gera aparecem aqui.",+ audioTitle: "Nenhum áudio ainda",+ audioDescription: "A fala que você gera na página Áudio aparece aqui.",+ modelsTitle: "Nenhum modelo ajustado ainda",+ modelsDescription: "Os modelos que você treina ou exporta no Unsloth aparecem aqui.",+ createFolder: "Criar pasta",+ generateVideo: "Gerar um vídeo",+ generateAudio: "Gerar áudio",+ trainModel: "Treinar um modelo",+ uploadFiles: "Enviar arquivos",+ dropHere: "ou solte arquivos aqui",+ noMatchesTitle: "Nenhum resultado",+ noMatchesDescription: "Tente outra busca ou limpe os filtros.",+ loadErrorTitle: "Não foi possível carregar sua Biblioteca",+ loadErrorFallback: "Algo deu errado.",+ tryAgain: "Tentar novamente",+ },+ sections: {+ items: "Itens",+ },+ breadcrumb: "Trilha de navegação",+ searchLibrary: "Buscar na biblioteca",+ searchFolder: "Buscar na pasta",+ dropToUpload: "Solte para enviar",+ dropToUploadInto: 'Solte para enviar para "{folder}"',+ itemCountOne: "{count} item",+ itemCount: "{count} itens",+ selectItem: "Selecionar {name}",+ selection: {+ startChat: "Iniciar chat",+ move: "Mover",+ clear: "Limpar seleção",+ },+ menu: {+ moreActions: "Mais ações",+ chatAboutThis: "Conversar sobre isto",+ chatWithModel: "Conversar com este modelo",+ addToFavorites: "Adicionar aos Favoritos",+ removeFromFavorites: "Remover dos Favoritos",+ download: "Baixar",+ addToFolder: "Adicionar à pasta",+ newFolder: "Nova pasta",+ noFolder: "Biblioteca (sem pasta)",+ deleteFolder: "Excluir pasta",+ },+ reveal: {+ finder: "Mostrar no Finder",+ explorer: "Mostrar no Explorer",+ files: "Mostrar na pasta",+ },+ toolbar: {+ filter: "Filtrar",+ source: "Origem",+ fileType: "Tipo de arquivo",+ clearFilters: "Limpar filtros",+ uploaded: "Enviados",+ generated: "Gerados",+ documents: "Documentos",+ spreadsheets: "Planilhas",+ presentations: "Apresentações",+ pdfs: "PDFs",+ gridView: "Visualização em grade",+ listView: "Visualização em lista",+ settings: "Configurações da Biblioteca",+ },+ create: {+ note: "Nota",+ image: "Imagem",+ video: "Vídeo",+ audio: "Áudio",+ model: "Modelo",+ folder: "Pasta",+ untitledNote: "Nota sem título",+ },+ list: {+ selectAll: "Selecionar tudo",+ name: "Nome",+ lastActivity: "Última atividade",+ favorite: "Favorito",+ modified: "Modificado {time}",+ justNow: "agora mesmo",+ },+ size: {+ bytes: "{value} B",+ kilobytes: "{value} KB",+ megabytes: "{value} MB",+ gigabytes: "{value} GB",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "Fine-tuning completo",+ loraExport: "Exportação LoRA",+ mergedExport: "Exportação mesclada",+ ggufExport: "Exportação GGUF",+ model: "Modelo",+ },+ dialog: {+ create: "Criar",+ renameFolder: "Renomear pasta",+ renameFile: "Renomear arquivo",+ deleteTitle: 'Excluir "{name}"?',+ deleteManyTitle: "Excluir {count} itens?",+ deleteManyDescription: "Os arquivos são excluídos de onde estão armazenados. O conteúdo de uma pasta excluída sobe um nível.",+ deleteFolderIntoParent: 'Todo o conteúdo é movido para "{folder}". Nenhum arquivo é excluído.',+ deleteFolderIntoLibrary: "Todo o conteúdo é movido para sua Biblioteca. Nenhum arquivo é excluído.",+ deleteUpload: "Isso exclui o arquivo permanentemente.",+ deleteAttachment: "Ele também é removido do chat ao qual estava anexado.",+ deleteImage: "Ele também é removido da sua galeria de Imagens.",+ 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.",+ unsavedTitle: "Suas alterações não foram salvas",+ unsavedDescription: "{reason} Tente novamente ou descarte suas alterações para fechar o arquivo.",+ keepEditing: "Continuar editando",+ discardChanges: "Descartar alterações",+ },+ preview: {+ code: "Código",+ preview: "Prévia",+ viewOriginalChat: "Ver chat original",+ viewInImages: "Ver em Imagens",+ viewInVideo: "Ver em Vídeo",+ viewInAudio: "Ver em Áudio",+ cannotPreview: "Não é possível visualizar este arquivo aqui. Baixe-o para abri-lo.",+ noPreview: "Não há prévia para este tipo de arquivo.",+ tooLargeToPreview: "Este arquivo é grande demais para ser visualizado aqui. Baixe-o para abri-lo.",+ startWriting: "Comece a escrever…",+ type: "Tipo",+ baseModel: "Modelo base",+ size: "Tamanho",+ location: "Local",+ unknown: "Desconhecido",+ readOnlyUtf16: "Este arquivo não é um texto UTF-16 válido, por isso abre aqui somente para leitura.",+ readOnlyNotUtf8: "Este arquivo não é texto UTF-8, por isso abre aqui somente para leitura. Alguns caracteres podem não aparecer corretamente.",+ },+ viewer: {+ scale: "Escala",+ fit: "Ajustar",+ moreActionsImage: "Mais ações para esta imagem",+ moreActionsVideo: "Mais ações para este vídeo",+ moreActionsClip: "Mais ações para este clipe",+ moreActionsFile: "Mais ações para este arquivo",+ },+ project: {+ label: "Projeto",+ newProject: "Novo projeto",+ noProjects: "Nenhum projeto ainda",+ alreadyIn: "Já está em {project}",+ addedTo: "Adicionado a {project}",+ createAndAdd: "Criar e adicionar",+ addFailedImage: "Falha ao adicionar a imagem ao projeto",+ addFailedVideo: "Falha ao adicionar o vídeo ao projeto",+ addFailedClip: "Falha ao adicionar o clipe ao projeto",+ addFailedFile: "Falha ao adicionar o arquivo ao projeto",+ newProjectImage: "Adicionar imagem a um novo projeto",+ newProjectVideo: "Adicionar vídeo a um novo projeto",+ newProjectClip: "Adicionar clipe a um novo projeto",+ newProjectFile: "Adicionar arquivo a um novo projeto",+ },+ toast: {+ missingItem: "Esse arquivo não está mais na Biblioteca",+ moveFailed: "Não foi possível mover",+ movedToFolder: "Movido para {folder}",+ movedToLibrary: "Movido para a Biblioteca",+ folderFallback: "pasta",+ favoritesFailed: "Não foi possível atualizar os favoritos",+ addedToFavorites: "Adicionado aos Favoritos",+ removedFromFavorites: "Removido dos Favoritos",+ uploadingOne: "Enviando {name}…",+ uploadingMany: "Enviando {count} arquivos…",+ uploadedOne: "Arquivo enviado",+ uploadedMany: "{count} arquivos enviados",+ uploadFailed: "Falha no envio",+ uploadTooLarge: "{name} tem mais de 512 MB.",+ readDropsFailed: "Não foi possível ler os arquivos soltos",+ createNoteFailed: "Não foi possível criar a nota",+ renameFailed: "Não foi possível renomear",+ createFolderFailed: "Não foi possível criar a pasta",+ signedOutBeforeFolder: "A sessão foi encerrada antes de a pasta ser criada.",+ signedOutBeforeSave: "A sessão foi encerrada antes de a alteração ser salva.",+ signedOutBeforeUpload: "A sessão foi encerrada antes de o envio terminar.",+ deleteFailed: "Não foi possível excluir alguns itens",+ saveFailed: "Não foi possível salvar",+ saveNoteFirst: "Salve a nota primeiro.",+ revealFailed: "Não foi possível abrir o gerenciador de arquivos",+ downloadFailed: "Não foi possível baixar {name}",+ downloadManyFailed: "Não foi possível baixar os arquivos",+ downloadingMany: "Baixando {count} arquivos",+ downloadingManyDescription: "Se o navegador perguntar, permita que este site baixe vários arquivos.",+ preparingMany: "Preparando {count} arquivos…",+ zipFileName: "Arquivos da Biblioteca",+ nothingToChat: "Ainda não há nada para conversar",+ emptyFolder: "Esta pasta não tem arquivos.",+ tooLargeOne: "{name} é grande demais para ser anexado",+ tooLargeMany: "Estes arquivos são grandes demais para serem anexados",+ attachedOne: "{count} arquivo anexado",+ attachedMany: "{count} arquivos anexados",+ skippedTooLarge: "{count} grandes demais para anexar.",+ skippedOverLimit: "Mais {count} além do limite de {limit} arquivos.",+ chatFilesWaiting: "{count} serão anexados assim que um modelo capaz de lê-los for carregado.",+ openFilesFailed: "Não foi possível abrir os arquivos",+ speechModel: "{name} é um modelo de fala",+ speechModelDescription: "Escolha-o no menu de modelos da página Áudio.",+ noMediaLink: "O servidor não retornou nenhum link para reproduzir este arquivo.",+ imageNotFound: "Não foi possível encontrar esta imagem",+ clipNotFound: "Não foi possível encontrar este clipe",+ notFoundDescription: "O item pode ter sido arquivado ou excluído.",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 3084e6dbb1f..d867ae81662 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -158,6 +158,7 @@ export const ru = {search: "Поиск",hub: "Хаб моделей",projects: "Проекты",+ library: "Библиотека",train: "Обучение",recipes: "Рецепты",images: "Изображения",@@ -2158,8 +2159,7 @@ export const ru = {},},studio: {- imageTraining: "Обучение изображений",- goToImageTraining: "Перейти к обучению изображений",+ goToLibrary: "Перейти в Библиотеку",routeTitle: "Обучение",wizard: {modelTitle: "Модель",@@ -2887,4 +2887,235 @@ export const ru = {updateError: "Не удалось обновить навык",mentions: "Навыки",},+ library: {+ tabs: {+ ariaLabel: "Разделы библиотеки",+ suggested: "Рекомендуемое",+ favorites: "Избранное",+ folders: "Папки",+ images: "Изображения",+ videos: "Видео",+ audio: "Аудио",+ models: "Дообученные",+ all: "Все",+ },+ empty: {+ suggestedTitle: "Ваша библиотека пуста",+ suggestedDescription: "Здесь появляются файлы, которые вы загружаете или создаёте в чатах.",+ favoritesTitle: "В избранном пока пусто",+ favoritesDescription: "Добавляйте файлы в избранное, чтобы быстро находить их здесь.",+ foldersTitle: "Создайте первую папку",+ foldersDescription: "Создавайте папки, чтобы упорядочить содержимое библиотеки.",+ imagesTitle: "Изображений пока нет",+ imagesDescription: "Здесь появляются изображения, которые вы загружаете или генерируете.",+ videosTitle: "Видео пока нет",+ videosDescription: "Здесь появляются видео, которые вы загружаете или генерируете.",+ audioTitle: "Аудио пока нет",+ audioDescription: "Здесь появляется речь, которую вы генерируете на странице «Аудио».",+ modelsTitle: "Дообученных моделей пока нет",+ modelsDescription: "Здесь появляются модели, которые вы обучаете или экспортируете в Unsloth.",+ createFolder: "Создать папку",+ generateVideo: "Сгенерировать видео",+ generateAudio: "Сгенерировать аудио",+ trainModel: "Обучить модель",+ uploadFiles: "Загрузить файлы",+ dropHere: "или перетащите файлы сюда",+ noMatchesTitle: "Ничего не найдено",+ noMatchesDescription: "Измените запрос или сбросьте фильтры.",+ loadErrorTitle: "Не удалось загрузить библиотеку",+ loadErrorFallback: "Что-то пошло не так.",+ tryAgain: "Повторить",+ },+ sections: {+ items: "Элементы",+ },+ breadcrumb: "Путь навигации",+ searchLibrary: "Поиск в библиотеке",+ searchFolder: "Поиск в папке",+ dropToUpload: "Отпустите, чтобы загрузить",+ dropToUploadInto: "Отпустите, чтобы загрузить в «{folder}»",+ itemCountOne: "Элементов: {count}",+ itemCount: "Элементов: {count}",+ selectItem: "Выбрать «{name}»",+ selection: {+ startChat: "Начать чат",+ move: "Переместить",+ clear: "Снять выделение",+ },+ menu: {+ moreActions: "Другие действия",+ chatAboutThis: "Обсудить в чате",+ chatWithModel: "Чат с этой моделью",+ addToFavorites: "Добавить в избранное",+ removeFromFavorites: "Удалить из избранного",+ download: "Скачать",+ addToFolder: "Добавить в папку",+ newFolder: "Новая папка",+ noFolder: "Библиотека (без папки)",+ deleteFolder: "Удалить папку",+ },+ reveal: {+ finder: "Показать в Finder",+ explorer: "Показать в Проводнике",+ files: "Показать в папке",+ },+ toolbar: {+ filter: "Фильтр",+ source: "Источник",+ fileType: "Тип файла",+ clearFilters: "Сбросить фильтры",+ uploaded: "Загруженные",+ generated: "Сгенерированные",+ documents: "Документы",+ spreadsheets: "Таблицы",+ presentations: "Презентации",+ pdfs: "PDF",+ gridView: "Сетка",+ listView: "Список",+ settings: "Настройки библиотеки",+ },+ create: {+ note: "Заметка",+ image: "Изображение",+ video: "Видео",+ audio: "Аудио",+ model: "Модель",+ folder: "Папка",+ untitledNote: "Заметка без названия",+ },+ list: {+ selectAll: "Выбрать все",+ name: "Название",+ lastActivity: "Последнее изменение",+ favorite: "В избранном",+ modified: "Изменено {time}",+ justNow: "только что",+ },+ size: {+ bytes: "{value} Б",+ kilobytes: "{value} КБ",+ megabytes: "{value} МБ",+ gigabytes: "{value} ГБ",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "Полное дообучение",+ loraExport: "Экспорт LoRA",+ mergedExport: "Объединённый экспорт",+ ggufExport: "Экспорт GGUF",+ model: "Модель",+ },+ dialog: {+ create: "Создать",+ renameFolder: "Переименовать папку",+ renameFile: "Переименовать файл",+ deleteTitle: "Удалить «{name}»?",+ deleteManyTitle: "Удалить элементы ({count})?",+ deleteManyDescription: "Файлы удаляются из места хранения. Содержимое удалённой папки переносится на уровень выше.",+ deleteFolderIntoParent: "Всё содержимое будет перемещено в «{folder}». Файлы не удаляются.",+ deleteFolderIntoLibrary: "Всё содержимое будет перемещено в вашу библиотеку. Файлы не удаляются.",+ deleteUpload: "Файл будет удалён без возможности восстановления.",+ deleteAttachment: "Он также будет удалён из чата, к которому был прикреплён.",+ deleteImage: "Он также будет удалён из вашей галереи изображений.",+ deleteVideo: "Он также будет удалён из вашей галереи видео.",+ deleteAudio: "Он также будет удалён из вашей галереи аудио.",+ deleteSandbox: "Он также будет удалён из чата, в котором был создан.",+ unsavedTitle: "Изменения не сохранены",+ unsavedDescription: "{reason} Повторите попытку или отмените изменения, чтобы закрыть файл.",+ keepEditing: "Продолжить редактирование",+ discardChanges: "Отменить изменения",+ },+ preview: {+ code: "Код",+ preview: "Просмотр",+ viewOriginalChat: "Открыть исходный чат",+ viewInImages: "Открыть в «Изображениях»",+ viewInVideo: "Открыть в «Видео»",+ viewInAudio: "Открыть в «Аудио»",+ cannotPreview: "Этот файл нельзя просмотреть здесь. Скачайте его, чтобы открыть.",+ noPreview: "Для этого типа файлов просмотр недоступен.",+ tooLargeToPreview: "Файл слишком большой для просмотра здесь. Скачайте его, чтобы открыть.",+ startWriting: "Начните писать…",+ type: "Тип",+ baseModel: "Базовая модель",+ size: "Размер",+ location: "Расположение",+ unknown: "Неизвестно",+ readOnlyUtf16: "Этот файл не является корректным текстом в кодировке UTF-16, поэтому здесь он открывается только для чтения.",+ readOnlyNotUtf8: "Этот файл не в кодировке UTF-8, поэтому здесь он открывается только для чтения. Некоторые символы могут отображаться неправильно.",+ },+ viewer: {+ scale: "Масштаб",+ fit: "По размеру",+ moreActionsImage: "Другие действия с изображением",+ moreActionsVideo: "Другие действия с видео",+ moreActionsClip: "Другие действия с клипом",+ moreActionsFile: "Другие действия с файлом",+ },+ project: {+ label: "Проект",+ newProject: "Новый проект",+ noProjects: "Проектов пока нет",+ alreadyIn: "Уже в проекте {project}",+ addedTo: "Добавлено в {project}",+ createAndAdd: "Создать и добавить",+ addFailedImage: "Не удалось добавить изображение в проект",+ addFailedVideo: "Не удалось добавить видео в проект",+ addFailedClip: "Не удалось добавить клип в проект",+ addFailedFile: "Не удалось добавить файл в проект",+ newProjectImage: "Добавить изображение в новый проект",+ newProjectVideo: "Добавить видео в новый проект",+ newProjectClip: "Добавить клип в новый проект",+ newProjectFile: "Добавить файл в новый проект",+ },+ toast: {+ missingItem: "Этого файла больше нет в библиотеке",+ moveFailed: "Не удалось переместить",+ movedToFolder: "Перемещено в {folder}",+ movedToLibrary: "Перемещено в библиотеку",+ folderFallback: "папку",+ favoritesFailed: "Не удалось обновить избранное",+ addedToFavorites: "Добавлено в избранное",+ removedFromFavorites: "Удалено из избранного",+ uploadingOne: "Загрузка {name}…",+ uploadingMany: "Загрузка файлов ({count})…",+ uploadedOne: "Файл загружен",+ uploadedMany: "Загружено файлов: {count}",+ uploadFailed: "Не удалось загрузить",+ uploadTooLarge: "Файл {name} больше 512 МБ.",+ readDropsFailed: "Не удалось прочитать перетащенные файлы",+ createNoteFailed: "Не удалось создать заметку",+ renameFailed: "Не удалось переименовать",+ createFolderFailed: "Не удалось создать папку",+ signedOutBeforeFolder: "Вы вышли из аккаунта до создания папки.",+ signedOutBeforeSave: "Вы вышли из аккаунта до сохранения изменения.",+ signedOutBeforeUpload: "Вы вышли из аккаунта до завершения загрузки.",+ deleteFailed: "Не удалось удалить некоторые элементы",+ saveFailed: "Не удалось сохранить",+ saveNoteFirst: "Сначала сохраните заметку.",+ revealFailed: "Не удалось открыть файловый менеджер",+ downloadFailed: "Не удалось скачать {name}",+ downloadManyFailed: "Не удалось скачать файлы",+ downloadingMany: "Скачивание файлов ({count})",+ downloadingManyDescription: "Если браузер спросит, разрешите этому сайту скачивать несколько файлов.",+ preparingMany: "Подготовка файлов ({count})…",+ zipFileName: "Файлы библиотеки",+ nothingToChat: "Пока нечего обсуждать",+ emptyFolder: "В этой папке нет файлов.",+ tooLargeOne: "Файл {name} слишком большой для прикрепления",+ tooLargeMany: "Эти файлы слишком большие для прикрепления",+ attachedOne: "Прикреплено файлов: {count}",+ attachedMany: "Прикреплено файлов: {count}",+ skippedTooLarge: "Слишком большие для прикрепления: {count}.",+ skippedOverLimit: "Сверх лимита в {limit} файлов: ещё {count}.",+ chatFilesWaiting: "Будут прикреплены после загрузки модели, которая может их прочитать: {count}.",+ openFilesFailed: "Не удалось открыть файлы",+ speechModel: "{name} — модель синтеза речи",+ speechModelDescription: "Выберите её в меню моделей на странице «Аудио».",+ noMediaLink: "Сервер не вернул ссылку для воспроизведения этого файла.",+ imageNotFound: "Не удалось найти это изображение",+ clipNotFound: "Не удалось найти этот клип",+ notFoundDescription: "Возможно, элемент архивирован или удалён.",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 44a2fc64160..c1c2297fdbf 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -154,6 +154,7 @@ export const zhCN = {search: "搜索",hub: "模型中心",projects: "项目",+ library: "资料库",train: "训练",recipes: "配方",images: "图像",@@ -2084,8 +2085,7 @@ export const zhCN = {},},studio: {- imageTraining: "图像训练",- goToImageTraining: "前往图像训练",+ goToLibrary: "前往资料库",routeTitle: "训练",wizard: {modelTitle: "模型",@@ -2767,4 +2767,235 @@ export const zhCN = {updateError: "无法更新技能",mentions: "技能",},+ library: {+ tabs: {+ ariaLabel: "资料库分区",+ suggested: "推荐",+ favorites: "收藏",+ folders: "文件夹",+ images: "图像",+ videos: "视频",+ audio: "音频",+ models: "微调模型",+ all: "全部",+ },+ empty: {+ suggestedTitle: "资料库为空",+ suggestedDescription: "你上传的文件或在聊天中创建的文件会显示在这里。",+ favoritesTitle: "还没有收藏",+ favoritesDescription: "将文件加入收藏,即可在这里快速找到。",+ foldersTitle: "创建你的第一个文件夹",+ foldersDescription: "创建文件夹来整理资料库中的内容。",+ imagesTitle: "还没有图像",+ imagesDescription: "你上传或生成的图像会显示在这里。",+ videosTitle: "还没有视频",+ videosDescription: "你上传或生成的视频会显示在这里。",+ audioTitle: "还没有音频",+ audioDescription: "你在音频页面生成的语音会显示在这里。",+ modelsTitle: "还没有微调模型",+ modelsDescription: "你在 Unsloth 中训练或导出的模型会显示在这里。",+ createFolder: "创建文件夹",+ generateVideo: "生成视频",+ generateAudio: "生成音频",+ trainModel: "训练模型",+ uploadFiles: "上传文件",+ dropHere: "或将文件拖放到这里",+ noMatchesTitle: "没有匹配项",+ noMatchesDescription: "请尝试其他搜索词或清除筛选条件。",+ loadErrorTitle: "无法加载资料库",+ loadErrorFallback: "出了点问题。",+ tryAgain: "重试",+ },+ sections: {+ items: "项目",+ },+ breadcrumb: "路径导航",+ searchLibrary: "搜索资料库",+ searchFolder: "搜索文件夹",+ dropToUpload: "松开即可上传",+ dropToUploadInto: "松开即可上传到“{folder}”",+ itemCountOne: "{count} 项",+ itemCount: "{count} 项",+ selectItem: "选择 {name}",+ selection: {+ startChat: "开始聊天",+ move: "移动",+ clear: "清除选择",+ },+ menu: {+ moreActions: "更多操作",+ chatAboutThis: "就此聊天",+ chatWithModel: "与此模型聊天",+ addToFavorites: "加入收藏",+ removeFromFavorites: "取消收藏",+ download: "下载",+ addToFolder: "添加到文件夹",+ newFolder: "新建文件夹",+ noFolder: "资料库(无文件夹)",+ deleteFolder: "删除文件夹",+ },+ reveal: {+ finder: "在 Finder 中显示",+ explorer: "在资源管理器中显示",+ files: "在文件夹中显示",+ },+ toolbar: {+ filter: "筛选",+ source: "来源",+ fileType: "文件类型",+ clearFilters: "清除筛选",+ uploaded: "已上传",+ generated: "已生成",+ documents: "文档",+ spreadsheets: "电子表格",+ presentations: "演示文稿",+ pdfs: "PDF",+ gridView: "网格视图",+ listView: "列表视图",+ settings: "资料库设置",+ },+ create: {+ note: "笔记",+ image: "图像",+ video: "视频",+ audio: "音频",+ model: "模型",+ folder: "文件夹",+ untitledNote: "未命名笔记",+ },+ list: {+ selectAll: "全选",+ name: "名称",+ lastActivity: "最近活动",+ favorite: "已收藏",+ modified: "修改于 {time}",+ justNow: "刚刚",+ },+ size: {+ bytes: "{value} B",+ kilobytes: "{value} KB",+ megabytes: "{value} MB",+ gigabytes: "{value} GB",+ },+ modelKind: {+ lora: "LoRA",+ fullFineTune: "全量微调",+ loraExport: "LoRA 导出",+ mergedExport: "合并导出",+ ggufExport: "GGUF 导出",+ model: "模型",+ },+ dialog: {+ create: "创建",+ renameFolder: "重命名文件夹",+ renameFile: "重命名文件",+ deleteTitle: "删除“{name}”?",+ deleteManyTitle: "删除 {count} 个项目?",+ deleteManyDescription: "文件会从其存储位置删除。已删除文件夹中的内容会上移一级。",+ deleteFolderIntoParent: "其中的所有内容都会移到“{folder}”。不会删除任何文件。",+ deleteFolderIntoLibrary: "其中的所有内容都会移到你的资料库。不会删除任何文件。",+ deleteUpload: "此操作会永久删除该文件。",+ deleteAttachment: "它也会从所附加的聊天中移除。",+ deleteImage: "它也会从你的图像图库中移除。",+ deleteVideo: "它也会从你的视频图库中移除。",+ deleteAudio: "它也会从你的音频图库中移除。",+ deleteSandbox: "它也会从创建它的聊天中移除。",+ unsavedTitle: "你的更改未保存",+ unsavedDescription: "{reason} 请重试,或放弃更改以关闭文件。",+ keepEditing: "继续编辑",+ discardChanges: "放弃更改",+ },+ preview: {+ code: "代码",+ preview: "预览",+ viewOriginalChat: "查看原始聊天",+ viewInImages: "在图像中查看",+ viewInVideo: "在视频中查看",+ viewInAudio: "在音频中查看",+ cannotPreview: "无法在此预览该文件。请下载后打开。",+ noPreview: "此文件类型不支持预览。",+ tooLargeToPreview: "文件过大,无法在此预览。请下载后打开。",+ startWriting: "开始写作…",+ type: "类型",+ baseModel: "基础模型",+ size: "大小",+ location: "位置",+ unknown: "未知",+ readOnlyUtf16: "此文件不是有效的 UTF-16 文本,因此在这里以只读方式打开。",+ readOnlyNotUtf8: "此文件不是 UTF-8 文本,因此在这里以只读方式打开。部分字符可能无法正确显示。",+ },+ viewer: {+ scale: "缩放",+ fit: "适应",+ moreActionsImage: "此图像的更多操作",+ moreActionsVideo: "此视频的更多操作",+ moreActionsClip: "此片段的更多操作",+ moreActionsFile: "此文件的更多操作",+ },+ project: {+ label: "项目",+ newProject: "新建项目",+ noProjects: "还没有项目",+ alreadyIn: "已在 {project} 中",+ addedTo: "已添加到 {project}",+ createAndAdd: "创建并添加",+ addFailedImage: "无法将图像添加到项目",+ addFailedVideo: "无法将视频添加到项目",+ addFailedClip: "无法将片段添加到项目",+ addFailedFile: "无法将文件添加到项目",+ newProjectImage: "将图像添加到新项目",+ newProjectVideo: "将视频添加到新项目",+ newProjectClip: "将片段添加到新项目",+ newProjectFile: "将文件添加到新项目",+ },+ toast: {+ missingItem: "该文件已不在资料库中",+ moveFailed: "无法移动",+ movedToFolder: "已移到 {folder}",+ movedToLibrary: "已移到资料库",+ folderFallback: "文件夹",+ favoritesFailed: "无法更新收藏",+ addedToFavorites: "已加入收藏",+ removedFromFavorites: "已取消收藏",+ uploadingOne: "正在上传 {name}…",+ uploadingMany: "正在上传 {count} 个文件…",+ uploadedOne: "文件已上传",+ uploadedMany: "已上传 {count} 个文件",+ uploadFailed: "上传失败",+ uploadTooLarge: "{name} 超过 512 MB。",+ readDropsFailed: "无法读取拖放的文件",+ createNoteFailed: "无法创建笔记",+ renameFailed: "无法重命名",+ createFolderFailed: "无法创建文件夹",+ signedOutBeforeFolder: "文件夹创建完成前已退出登录。",+ signedOutBeforeSave: "更改保存完成前已退出登录。",+ signedOutBeforeUpload: "上传完成前已退出登录。",+ deleteFailed: "部分项目无法删除",+ saveFailed: "无法保存",+ saveNoteFirst: "请先保存笔记。",+ revealFailed: "无法打开文件管理器",+ downloadFailed: "无法下载 {name}",+ downloadManyFailed: "无法下载这些文件",+ downloadingMany: "正在下载 {count} 个文件",+ downloadingManyDescription: "如果浏览器询问,请允许此网站下载多个文件。",+ preparingMany: "正在准备 {count} 个文件…",+ zipFileName: "资料库文件",+ nothingToChat: "还没有可以聊的内容",+ emptyFolder: "此文件夹中没有文件。",+ tooLargeOne: "{name} 过大,无法附加",+ tooLargeMany: "这些文件过大,无法附加",+ attachedOne: "已附加 {count} 个文件",+ attachedMany: "已附加 {count} 个文件",+ skippedTooLarge: "{count} 个文件过大,无法附加。",+ skippedOverLimit: "另有 {count} 个超出 {limit} 个文件的上限。",+ chatFilesWaiting: "{count} 个文件将在加载可读取它们的模型后附加。",+ openFilesFailed: "无法打开这些文件",+ speechModel: "{name} 是语音模型",+ speechModelDescription: "请在音频页面的模型菜单中选择它。",+ noMediaLink: "服务器未返回用于播放此文件的链接。",+ imageNotFound: "找不到此图像",+ clipNotFound: "找不到此片段",+ notFoundDescription: "它可能已被归档或删除。",+ },+ },} satisfies DeepPartialMessageTree<typeof en>;diff --git a/studio/frontend/src/lib/gallery-deep-link.ts b/studio/frontend/src/lib/gallery-deep-link.tsnew file mode 100644index 00000000000..d70d7b03256--- /dev/null+++ b/studio/frontend/src/lib/gallery-deep-link.ts@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++const MAX_PAGES = 100;+const BUSY_WAIT_MS = 200;+const MAX_FRUITLESS = 3;++export async function loadGalleryUntil({+ has,+ count,+ hasMore,+ refresh,+ loadMore,+ busy,+ cancelled,+}: {+ has: () => boolean;+ count: () => number;+ hasMore: () => boolean;+ refresh: () => Promise<unknown>;+ loadMore: () => Promise<unknown>;+ busy: () => boolean;+ cancelled: () => boolean;+}): Promise<boolean> {+ await refresh();+ let fruitless = 0;+ for (let page = 0; page < MAX_PAGES; page++) {+ if (cancelled()) return false;+ if (has()) return true;+ if (!hasMore()) return false;+ const before = count();+ const waited = busy();+ await loadMore();+ if (count() !== before) {+ fruitless = 0;+ continue;+ }+ if (!waited && ++fruitless >= MAX_FRUITLESS) return false;+ await new Promise((resolve) => setTimeout(resolve, BUSY_WAIT_MS));+ }+ return !cancelled() && has();+}diff --git a/studio/frontend/src/lib/hugeicons-derived.ts b/studio/frontend/src/lib/hugeicons-derived.tsindex bd90456744c..859473263cb 100644--- a/studio/frontend/src/lib/hugeicons-derived.ts+++ b/studio/frontend/src/lib/hugeicons-derived.ts@@ -3,6 +3,7 @@// Derived HugeIcons shared between the sidebar and page tabs, so the same visual language appears everywhere.+import type { IconSvgElement } from "@hugeicons/react";import { BubbleChatIcon, TestTube01Icon } from "@hugeicons/core-free-icons";// TestTube01Icon's last 2 paths are interior bubbles; slice to the first 3 (outline + cap + liquid line). Original export untouched.@@ -18,3 +19,33 @@ export const MessageCircleIcon = BubbleChatIcon.slice(0,1,) as typeof BubbleChatIcon;++export const SheetIcon: IconSvgElement = [+ ["path", { d: "M2.49219 9.5H21.4922", stroke: "currentColor", strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: "1.5", key: "0" }],+ ["path", { d: "M2.99219 15.5H20.9922", stroke: "currentColor", strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: "1.5", key: "1" }],+ ["path", { d: "M8.49219 21L8.49219 9.5", stroke: "currentColor", strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: "1.5", key: "2" }],+ ["path", { d: "M15.4922 21L15.4922 9.5", stroke: "currentColor", strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: "1.5", key: "3" }],+ [+ "path",+ {+ d: "M2.49219 12C2.49219 7.52166 2.49219 5.28249 3.88343 3.89124C5.27467 2.5 7.51384 2.5 11.9922 2.5C16.4705 2.5 18.7097 2.5 20.1009 3.89124C21.4922 5.28249 21.4922 7.52166 21.4922 12C21.4922 16.4783 21.4922 18.7175 20.1009 20.1088C18.7097 21.5 16.4705 21.5 11.9922 21.5C7.51384 21.5 5.27467 21.5 3.88343 20.1088C2.49219 18.7175 2.49219 16.4783 2.49219 12Z",+ stroke: "currentColor",+ strokeWidth: "1.5",+ key: "4",+ },+ ],+];++export const StarPointedIcon: IconSvgElement = [+ [+ "path",+ {+ d: "M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",+ stroke: "currentColor",+ strokeLinecap: "round",+ strokeLinejoin: "round",+ strokeWidth: "1.5",+ key: "0",+ },+ ],+];diff --git a/studio/frontend/tests/gallery-deep-link.test.ts b/studio/frontend/tests/gallery-deep-link.test.tsnew file mode 100644index 00000000000..cc86569c954--- /dev/null+++ b/studio/frontend/tests/gallery-deep-link.test.ts@@ -0,0 +1,46 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A Library link into a gallery pages back until its item loads. A failing gallery must end the+// search after a few tries, not one request per remaining page.++import assert from "node:assert/strict";+import test from "node:test";++import { loadGalleryUntil } from "../src/lib/gallery-deep-link.ts";++test("a gallery that keeps failing ends the lookup after a few tries", async () => {+ let requests = 0;+ const found = await loadGalleryUntil({+ has: () => false,+ count: () => 50,+ hasMore: () => true,+ refresh: async () => {},+ loadMore: async () => {+ requests += 1;+ },+ busy: () => false,+ cancelled: () => false,+ });+ assert.equal(found, false);+ assert.equal(requests, 3);+});++test("pages keep loading until the item arrives", async () => {+ let loaded = 0;+ const found = await loadGalleryUntil({+ has: () => loaded >= 150,+ count: () => loaded,+ hasMore: () => true,+ refresh: async () => {+ loaded = 50;+ },+ loadMore: async () => {+ loaded += 50;+ },+ busy: () => false,+ cancelled: () => false,+ });+ assert.equal(found, true);+ assert.equal(loaded, 150);+});diff --git a/studio/frontend/tests/library-helpers.test.ts b/studio/frontend/tests/library-helpers.test.tsnew file mode 100644index 00000000000..736a6dd9a18--- /dev/null+++ b/studio/frontend/tests/library-helpers.test.ts@@ -0,0 +1,201 @@+// 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 assert from "node:assert/strict";+import test from "node:test";++import { readSrc } from "./helpers/kit.ts";++import {+ embeddedBlobType,+ itemVersion,+ libraryFileName,+ libraryFileType,+ streamsPreview,+ uniqueFileNames,+} from "../src/features/library/file-name.ts";+import { decodeNote, encodeNote } from "../src/features/library/note-text.ts";+import {+ acquireObjectUrl,+ cachedObjectUrlCount,+ clearCachedObjectUrls,+} from "../src/features/library/object-url-cache.ts";+import { isLoopbackHost, revealLabelFor } from "../src/features/library/reveal-label.ts";++function table<A extends unknown[], O>(name: string, run: (...args: A) => O, rows: [A, O][]) {+ test(name, () => {+ for (const [args, expected] of rows) assert.deepEqual(run(...args), expected, String(args));+ });+}++const fileName = (name: string, file?: string, textOnly?: boolean) =>+ libraryFileName({ name, fileName: file, textOnly });++table("a renamed item saves under a name every OS takes, with its file's extension", fileName, [+ [["Q3 report", "report.pdf"], "Q3 report.pdf"],+ [["notes.v2", "notes.md"], "notes.v2.md"],+ [["script.PY", "script.py"], "script.PY"],+ [['a<b>c:d"e/f\\g|h?i*j', "x.txt"], "a_b_c_d_e_f_g_h_i_j.txt"],+ [["tab\there\u0007", "x.md"], "tab_here_.md"],+ [["draft. . .", "draft.md"], "draft.md"],+ [["../../etc/passwd", "a.txt"], ".._.._etc_passwd.txt"],+ [["CON", "con.txt"], "_CON.txt"],+ [["nul.backup", "x.txt"], "_nul.backup.txt"],+ [["com1", "a.py"], "_com1.py"],+ [["console", "a.py"], "console.py"],+ [["", "image.png"], "file.png"],+ [["...", "image.png"], "file.png"],+ [[".env", ".env"], ".env"],+ [["paper.pdf", undefined, true], "paper.pdf.txt"],+ [["notes.txt", undefined, true], "notes.txt"],+ [["x".repeat(400), "a.jsonl"], `${"x".repeat(194)}.jsonl`],+ [["字".repeat(200), "a.txt"], `${"字".repeat(65)}.txt`],+ [["😀".repeat(100), "a.png"], `${"😀".repeat(49)}.png`],+]);++test("an item's version changes with its size, as an attachment rewritten in place keeps its time", () => {+ const item = { id: "attachment:m:a", updatedAt: 5, sizeBytes: 10 };+ assert.notEqual(itemVersion(item), itemVersion({ ...item, sizeBytes: 11 }));+ assert.notEqual(itemVersion(item), itemVersion({ ...item, updatedAt: 6 }));+ assert.equal(itemVersion({ ...item, sizeBytes: null }), "attachment:m:a@5.");+});++test("a folder that is gone sends its view back to where it was, or to Folders", () => {+ const page = readSrc("features/library/library-page.tsx");+ const start = page.indexOf("const folderGone =");+ const effect = page.slice(start, page.indexOf("}, [folderGone", start));+ for (const line of [+ 'status === "ready" && folderId !== null && currentFolder === null',+ "parentOfOpen && folderById.has(parentOfOpen) ? parentOfOpen : undefined",+ 'go({ folder: parent, show: "folders" }, true);',+ ]) {+ assert.ok(effect.includes(line), line);+ }+});++test("names in one download are made unique, ignoring case", () => {+ assert.deepEqual(+ uniqueFileNames(["a.txt", "A.txt", "a.txt", "b", "b", "a (2).txt"]),+ ["a.txt", "A (2).txt", "a (3).txt", "b", "b (2)", "a (2) (2).txt"],+ );+});++table("a file the server types opaquely gets a type from its extension", libraryFileType, [+ [["run.py", ""], "text/plain"],+ [["run.py", "application/octet-stream"], "text/plain"],+ [["photo.JPG", ""], "image/jpeg"],+ [["blob.bin", ""], "application/octet-stream"],+ [["run.py", "text/x-python; charset=utf-8"], "text/x-python"],+]);++table("nothing embedded directly is typed as a scriptable document", embeddedBlobType, [+ [["pdf", "text/html"], "application/pdf"],+ [["pdf", "application/octet-stream"], "application/pdf"],+ [["image", "image/svg+xml"], "application/octet-stream"],+ [["image", "text/html"], "application/octet-stream"],+ [["image", "image/png"], "image/png"],+ [["video", "video/mp4"], "video/mp4"],+ [["audio", "video/mp4"], "application/octet-stream"],+]);++test("audio and video with a file of their own stream; the rest keep a blob", () => {+ for (const id of ["upload:abc", "audio:a1", "video:v1", "sandbox:t-1:out/song.mp3"]) {+ assert.ok(streamsPreview(id, "audio") && streamsPreview(id, "video"), id);+ }+ for (const [id, body] of [+ ["attachment:m:a", "video"], ["upload:abc", "image"], ["upload:abc", "pdf"], ["upload:abc", null],+ ["model:training:/x", "video"], ["upload", "video"], [":upload", "video"],+ ] as const) {+ assert.equal(streamsPreview(id, body), false, `${id} ${body}`);+ }+});++const utf8 = (text: string) => new TextEncoder().encode(text);+const bytes = (...values: number[]) => new Uint8Array(values);+const utf16le = (text: string) =>+ bytes(0xff, 0xfe, ...[...text].flatMap((c) => [c.charCodeAt(0) & 0xff, c.charCodeAt(0) >> 8]));++test("notes decode by their BOM and save back in the same shape", () => {+ const cases: [Uint8Array, string, string, boolean, string, string, string][] = [+ [utf8("héllo\nworld\n"), "héllo\nworld\n", "utf-8", false, "\n", "héllo\n", "héllo\n"],+ [utf8("a\r\nb\r\nc"), "a\nb\nc", "utf-8", false, "\r\n", "a\nb\r\nc", "a\r\nb\r\nc"],+ [bytes(0xef, 0xbb, 0xbf, ...utf8("hi")), "hi", "utf-8", true, "\n", "hi!", "\uFEFFhi!"],+ [utf16le("Write-Host\r\n"), "Write-Host\n", "utf-16le", true, "\r\n", "x\n", "\uFEFFx\r\n"],+ [bytes(0xfe, 0xff, 0x00, 0x41, 0x00, 0x42), "AB", "utf-16be", true, "\n", "AB", "\uFEFFAB"],+ ];+ for (const [input, text, encoding, bom, eol, edit, saved] of cases) {+ const note = decodeNote(input);+ assert.deepEqual(note, { text, format: { encoding, bom, eol }, readOnlyReason: null });+ assert.equal(encodeNote(edit, note.format), saved);+ }+});++test("a note that would not save back as it was opens read-only", () => {+ assert.equal(decodeNote(bytes(0xff, 0xfe, 0x00, 0xd8)).readOnlyReason, "utf16");+ const legacy = decodeNote(bytes(0x63, 0x61, 0x66, 0xe9));+ assert.ok(legacy.readOnlyReason === "notUtf8" && legacy.text.startsWith("caf"));+ const cut = decodeNote(utf8("ab€").subarray(0, 4), true);+ assert.deepEqual([cut.text, cut.readOnlyReason], ["ab", null]);+});++test("every spelling of this machine counts as local, and nothing else does", () => {+ const local = "localhost LOCALHOST studio.localhost 127.0.0.1 127.1.2.3 [::1] ::1 0.0.0.0 [::]";+ const remote = "192.168.1.20 studio.example.com localhost.example.com 128.0.0.1 [::2]";+ for (const host of [...local.split(" "), "[::ffff:127.0.0.1]", "[::ffff:7f00:1]"]) {+ assert.equal(isLoopbackHost(host), true, host);+ }+ for (const host of remote.split(" ")) assert.equal(isLoopbackHost(host), false, host);+});++table("Reveal is named by the server's file manager, else by its platform", revealLabelFor, [+ [["finder", "mac"], "library.reveal.finder"],+ [["explorer", "windows"], "library.reveal.explorer"],+ [["explorer", "linux"], "library.reveal.explorer"],+ [["files", "linux"], "library.reveal.files"],+ [[null, "linux"], null],+ [[undefined, "mac"], "library.reveal.finder"],+ [[undefined, "windows"], "library.reveal.explorer"],+ [[undefined, "linux"], "library.reveal.files"],+]);++// Thumbnail URLs: one a card still loads or shows is never revoked under it.+const revoked = new Set<string>();+const realRevoke = URL.revokeObjectURL.bind(URL);+URL.revokeObjectURL = (url: string) => {+ revoked.add(url);+ realRevoke(url);+};+const blob = () => Promise.resolve(new Blob(["x"]));+async function fill(prefix: string, count: number) {+ for (let i = 0; i < count; i++) {+ const held = acquireObjectUrl(`${prefix}-${i}`, blob);+ await held.url;+ held.release();+ }+}++test("a held URL survives the count cap, and goes once released", async () => {+ clearCachedObjectUrls();+ let finish!: (value: Blob) => void;+ const pending = acquireObjectUrl("pending", () => new Promise((resolve) => (finish = resolve)));+ await fill("item", 310);+ finish(new Blob(["late"]));+ const url = await pending.url;+ assert.ok(!revoked.has(url) && cachedObjectUrlCount() <= 300);+ pending.release();+ await fill("one-more", 1);+ assert.ok(revoked.has(url));+});++test("a hit is the same URL, and stays valid while anyone holds it", async () => {+ clearCachedObjectUrls();+ const first = acquireObjectUrl("same", blob);+ const second = acquireObjectUrl("same", () => Promise.reject(new Error("not refetched")));+ const url = await first.url;+ assert.equal(await second.url, url);+ first.release();+ await fill("filler", 305);+ assert.ok(!revoked.has(url));+ second.release();+});diff --git a/studio/frontend/tests/library-state.test.ts b/studio/frontend/tests/library-state.test.tsnew file mode 100644index 00000000000..76879efcb01--- /dev/null+++ b/studio/frontend/tests/library-state.test.ts@@ -0,0 +1,482 @@+// 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 assert from "node:assert/strict";+import test from "node:test";+import * as fflate from "fflate";+import * as zustand from "zustand";+import * as zustandMiddleware from "zustand/middleware";++import { installLocalStorageFake } from "./helpers/kit.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++const { fireWindowEvent } = installLocalStorageFake();+const SIGNED_OUT = "unsloth:auth-session-cleared";+const { uniqueFileNames } = await import("../src/features/library/file-name.ts");+const { attachLibraryChatFiles, useLibraryChatHandoffStore } = await import(+ "../src/features/library/chat-handoff-store.ts"+);++const file = (name: string) => new File(["x"], name);+const names = (files: File[] | undefined) => files?.map((f) => f.name);++test("files the composer refuses wait for a model instead of being lost", async () => {+ const handoff = useLibraryChatHandoffStore.getState();+ handoff.offer("single:1", { files: [file("a.png"), file("notes.md")] });+ const added: string[] = [];+ let modelLoaded = false;+ const add = async (f: File) => {+ if (f.name.endsWith(".png") && !modelLoaded) throw new Error("Load a model first");+ added.push(f.name);+ };+ assert.equal(await attachLibraryChatFiles("single:2", add), 0);+ assert.equal(await attachLibraryChatFiles("single:1", add), 1);+ assert.deepEqual(added, ["notes.md"]);+ assert.deepEqual(names(useLibraryChatHandoffStore.getState().held?.files), ["a.png"]);+ assert.equal(await attachLibraryChatFiles("single:2", add, true), 0);+ assert.equal(await attachLibraryChatFiles("single:1", add, true), 1);+ modelLoaded = true;+ assert.equal(await attachLibraryChatFiles("single:1", add, true), 0);+ assert.deepEqual(added, ["notes.md", "a.png"]);+ assert.equal(useLibraryChatHandoffStore.getState().held, null);+});++test("a sign-out drops files handed to a chat that has not taken them", async () => {+ const handoff = useLibraryChatHandoffStore.getState();+ handoff.offer("single:3", { files: [file("a.png")] });+ useLibraryChatHandoffStore.setState({ held: { targetKey: "single:3", files: [file("b.png")] } });+ fireWindowEvent(SIGNED_OUT, {});+ assert.equal(handoff.take("single:3"), null);+ assert.equal(useLibraryChatHandoffStore.getState().held, null);+});++test("a sign-out mid-handoff stops it, and keeps nothing for the next account", async () => {+ useLibraryChatHandoffStore+ .getState()+ .offer("single:4", { files: [file("a.png"), file("b.png"), file("c.png")] });+ const added: string[] = [];+ const add = async (f: File) => {+ added.push(f.name);+ if (f.name === "a.png") fireWindowEvent(SIGNED_OUT, {});+ throw new Error("Load a model first");+ };+ assert.equal(await attachLibraryChatFiles("single:4", add), 0);+ assert.deepEqual(added, ["a.png"]);+ assert.equal(useLibraryChatHandoffStore.getState().held, null);+});++function loadApi(session: { epoch: number }, authFetch: (url: string, init?: RequestInit) => unknown) {+ return loadWithStubs<{+ uploadLibraryFiles: (batch: object, folderId: string | null) => Promise<string[]>;+ updateLibraryItem: (id: string, patch: { name?: string }) => Promise<void>;+ updateLibraryFolder: (id: string, patch: { name?: string }) => Promise<void>;+ fetchLibraryBlob: (item: object, type: string, maxBytes?: number) => Promise<Blob>;+ LibraryFileTooLarge: new () => Error;+ }>(new URL("../src/features/library/api.ts", import.meta.url), {+ "@/features/auth": {+ authFetch,+ getAuthSessionEpoch: () => session.epoch,+ getAuthToken: () => null,+ },+ "@/i18n": { translate: (key: string) => key },+ "@/lib/api-base": {},+ "@/lib/format-fastapi-error": {},+ "./file-name": {},+ "./note-text": {},+ });+}++test("two quick changes to one folder reach the server in the order they were made", async () => {+ const sent: string[] = [];+ let answerFirst = () => {};+ const { updateLibraryFolder } = loadApi({ epoch: 1 }, (_url, init) => {+ const { name } = JSON.parse(String(init?.body)) as { name: string };+ sent.push(name);+ if (name !== "first") return Promise.resolve(new Response("{}"));+ return new Promise((resolve) => (answerFirst = () => resolve(new Response("{}"))));+ });+ const first = updateLibraryFolder("f1", { name: "first" });+ const second = updateLibraryFolder("f1", { name: "second" });+ await new Promise((resolve) => setTimeout(resolve, 10));+ assert.deepEqual(sent, ["first"]);+ answerFirst();+ await Promise.all([first, second]);+ assert.deepEqual(sent, ["first", "second"]);+});++test("a preview stops reading at its cap, whatever size the listing said", async () => {+ const bytes = (n: number) =>+ new ReadableStream({+ start(controller) {+ for (let i = 0; i < n; i++) controller.enqueue(new Uint8Array(4));+ controller.close();+ },+ });+ const answer = { body: (): BodyInit => bytes(1), headers: {} as Record<string, string> };+ const api = loadApi({ epoch: 1 }, async () => new Response(answer.body(), { headers: answer.headers }));+ const item = { name: "grew.png", fileUrl: "/f", sizeBytes: 4 };+ assert.equal((await api.fetchLibraryBlob(item, "image/png", 10)).size, 4);+ answer.body = () => bytes(4);+ await assert.rejects(api.fetchLibraryBlob(item, "image/png", 10), api.LibraryFileTooLarge);+ answer.body = () => "x".repeat(40);+ answer.headers = { "content-length": "40" };+ await assert.rejects(api.fetchLibraryBlob(item, "image/png", 10), api.LibraryFileTooLarge);+});++test("an upload's grants from before a sign-in are not sent under it", async () => {+ const session = { epoch: 1 };+ let requests = 0;+ const { uploadLibraryFiles } = loadApi(session, async () => {+ requests += 1;+ return new Response(JSON.stringify({ ids: ["upload:x"] }));+ });+ const batch = { nativePathLeases: ["lease"], sessionEpoch: session.epoch };+ session.epoch += 1;+ await assert.rejects(uploadLibraryFiles(batch, null), /signedOutBeforeUpload/);+ assert.equal(requests, 0);+ const now = { ...batch, sessionEpoch: session.epoch };+ assert.deepEqual(await uploadLibraryFiles(now, null), ["upload:x"]);+});++test("a batch of more than 1000 files goes as several requests", async () => {+ const perRequest: number[] = [];+ const { uploadLibraryFiles } = loadApi({ epoch: 1 }, async (_url, init) => {+ const files = (init?.body as FormData).getAll("files");+ perRequest.push(files.length);+ return new Response(JSON.stringify({ ids: files.map((_, i) => `upload:${i}`) }));+ });+ const files = Array.from({ length: 2500 }, (_, i) => new File(["x"], `${i}.txt`));+ assert.equal((await uploadLibraryFiles({ files, sessionEpoch: 1 }, null)).length, 2500);+ assert.deepEqual(perRequest, [1000, 1000, 500]);+});++test("a desktop drop of more than 999 files keeps each request under the field limit", async () => {+ const fields: number[] = [];+ const { uploadLibraryFiles } = loadApi({ epoch: 1 }, async (_url, init) => {+ const form = init?.body as FormData;+ fields.push(form.getAll("nativePathLeases").length + form.getAll("folderId").length);+ return new Response(JSON.stringify({ ids: ["upload:x"] }));+ });+ const nativePathLeases = Array.from({ length: 1500 }, (_, i) => `lease${i}`);+ await uploadLibraryFiles({ nativePathLeases, sessionEpoch: 1 }, "folder1");+ assert.deepEqual(fields, [1000, 502]);+});++test("the next account's edit does not wait behind one the account that left never finished", { timeout: 2000 }, async () => {+ const session = { epoch: 1 };+ const sent: string[] = [];+ const { updateLibraryItem } = loadApi(session, (_url, init) => {+ const { name } = JSON.parse(String(init?.body)) as { name: string };+ sent.push(name);+ return name === "A's" ? new Promise(() => {}) : Promise.resolve(new Response("{}"));+ });+ void updateLibraryItem("attachment:m:a", { name: "A's" });+ await new Promise((resolve) => setTimeout(resolve, 0));+ session.epoch += 1;+ await updateLibraryItem("attachment:m:a", { name: "B's" });+ assert.deepEqual(sent, ["A's", "B's"]);+});++type Item = { id: string; name: string; favorite: boolean; folderId: string | null };++function loadStore(+ api: Record<string, unknown>,+ emitted: unknown[] = [],+ session: { epoch: number } = { epoch: 0 },+ starsUndone: string[] = [],+) {+ return loadWithStubs<{+ useLibraryStore: zustand.UseBoundStore<+ zustand.StoreApi<{+ items: Item[];+ refresh: () => Promise<void>;+ removeItem: (id: string, fingerprint?: string) => Promise<void>;+ patchItem: (id: string, patch: Partial<Item>) => Promise<void>;+ }>+ >;+ }>(new URL("../src/features/library/store.ts", import.meta.url), {+ zustand,+ "zustand/middleware": zustandMiddleware,+ "@/features/auth": {+ AUTH_SESSION_CLEARED_EVENT: SIGNED_OUT,+ getAuthSessionEpoch: () => session.epoch,+ },+ "@/features/chat": {+ emitChatAttachmentDeleted: (event: unknown) => emitted.push(event),+ },+ "@/i18n": { translate: (key: string) => key },+ "@/lib/gallery-flags": { notifyGalleryChanged: () => {} },+ "./api": { errorMessage: String, ...api },+ "./favorites-store": {+ useLibraryFavoritesStore: {+ getState: () => ({+ begin: () => ({}),+ adopt: (_: unknown, ids: unknown) => ids,+ mark: (id: string) => ({ settle: () => {}, undo: () => starsUndone.push(id) }),+ }),+ },+ },+ "./object-url-cache": { clearCachedObjectUrls: () => {} },+ }).useLibraryStore;+}++const item = (id: string, name = id): Item => ({ id, name, favorite: false, folderId: null });++test("a failed edit is undone locally when the refresh meant to undo it fails too", async () => {+ let online = true;+ const store = loadStore({+ getLibrary: async () => {+ if (!online) throw new Error("offline");+ return { items: [item("upload:a"), item("upload:b")], folders: [] };+ },+ deleteLibraryItem: async () => {+ throw new Error("offline");+ },+ updateLibraryItem: async () => {+ throw new Error("offline");+ },+ });+ await store.getState().refresh();+ online = false;+ await assert.rejects(store.getState().removeItem("upload:a"));+ await Promise.all([+ assert.rejects(store.getState().patchItem("upload:b", { name: "one" })),+ assert.rejects(store.getState().patchItem("upload:b", { name: "two" })),+ ]);+ assert.deepEqual(store.getState().items, [item("upload:a"), item("upload:b")]);+});++test("undoing a failed edit keeps what a later edit to the same item saved", async () => {+ let online = true;+ const store = loadStore({+ getLibrary: async () => {+ if (!online) throw new Error("offline");+ return { items: [item("upload:a")], folders: [] };+ },+ updateLibraryItem: async (_id: string, patch: Partial<Item>) => {+ if (patch.name) throw new Error("offline");+ },+ });+ await store.getState().refresh();+ online = false;+ await Promise.allSettled([+ store.getState().patchItem("upload:a", { name: "renamed" }),+ store.getState().patchItem("upload:a", { favorite: true }),+ ]);+ assert.deepEqual(store.getState().items, [{ ...item("upload:a"), favorite: true }]);+});++test("an edit still pending at sign-out does not hold back the next account's Library", async () => {+ const store = loadStore({+ getLibrary: async () => ({ items: [item("upload:b")], folders: [] }),+ updateLibraryItem: () => new Promise(() => {}),+ });+ void store.getState().patchItem("upload:a", { name: "never answered" });+ fireWindowEvent(SIGNED_OUT, {});+ await store.getState().refresh();+ assert.deepEqual(store.getState().items, [item("upload:b")]);+});++test("a star that fails offline is undone where Images and Video read it too", async () => {+ const starsUndone: string[] = [];+ let online = true;+ const store = loadStore(+ {+ getLibrary: async () => {+ if (!online) throw new Error("offline");+ return { items: [item("image:a")], folders: [] };+ },+ updateLibraryItem: async () => {+ throw new Error("offline");+ },+ },+ [],+ { epoch: 0 },+ starsUndone,+ );+ await store.getState().refresh();+ online = false;+ await assert.rejects(store.getState().patchItem("image:a", { favorite: true }));+ assert.deepEqual(starsUndone, ["image:a"]);+ assert.equal(store.getState().items[0]!.favorite, false);+});++test("undoing a mirrored star leaves a newer toggle of it alone", () => {+ const { useLibraryFavoritesStore } = loadWithStubs<{+ useLibraryFavoritesStore: zustand.StoreApi<{+ ids: ReadonlySet<string>;+ mark: (id: string, favorite: boolean) => { settle: () => void; undo: () => void };+ }>;+ }>(new URL("../src/features/library/favorites-store.ts", import.meta.url), {+ react: { useEffect: () => {} },+ zustand,+ "@/features/auth": { AUTH_SESSION_CLEARED_EVENT: SIGNED_OUT },+ "@/i18n": { translate: (key: string) => key },+ "@/lib/toast": { toast: {} },+ "./api": {},+ });+ const stars = useLibraryFavoritesStore.getState();+ const failed = stars.mark("image:a", true);+ failed.undo();+ assert.equal(useLibraryFavoritesStore.getState().ids.has("image:a"), false);+ const first = stars.mark("image:b", true);+ stars.mark("image:b", false);+ first.undo();+ assert.equal(useLibraryFavoritesStore.getState().ids.has("image:b"), false);+ stars.mark("image:b", true).settle();+ first.undo();+ assert.equal(useLibraryFavoritesStore.getState().ids.has("image:b"), true);+});++test("a sandbox file is deleted as the file it was listed as", async () => {+ const deleted: unknown[] = [];+ let fingerprint = "7:1.5";+ const store = loadStore({+ getLibrary: async () => ({+ items: [{ ...item("sandbox:t:a.png"), fingerprint }],+ folders: [],+ }),+ deleteLibraryItem: async (...args: unknown[]) => void deleted.push(args),+ });+ await store.getState().refresh();+ const shown = store.getState().items[0] as Item & { fingerprint: string };+ // Replaced while the confirmation was open: the refresh must not lend the delete its fingerprint.+ fingerprint = "9:2.5";+ await store.getState().refresh();+ await store.getState().removeItem(shown.id, shown.fingerprint);+ assert.deepEqual(deleted, [["sandbox:t:a.png", "7:1.5"]]);+});++test("deleting a chat attachment tells an open chat to drop it", async () => {+ const emitted: unknown[] = [];+ const store = loadStore(+ {+ getLibrary: async () => ({ items: [item("attachment:m%3A1:content-part-x")], folders: [] }),+ deleteLibraryItem: async () => {},+ },+ emitted,+ );+ await store.getState().refresh();+ await store.getState().removeItem("attachment:m%3A1:content-part-x");+ await store.getState().removeItem("upload:a");+ assert.deepEqual(emitted, [{ messageId: "m:1", attachmentId: "content-part-x" }]);+});++function loadDownloads(+ fflate: object,+ saved: (File | Blob)[],+ fileNames: object,+ session: { epoch: number } = { epoch: 0 },+ fetched: (name: string) => void = () => {},+) {+ const toast = Object.assign(() => {}, { loading: () => 0, dismiss: () => {}, error: () => {} });+ return loadWithStubs<{+ downloadLibraryItems: (items: { name: string; sizeBytes: number | null }[]) => Promise<void>;+ }>(new URL("../src/features/library/actions.ts", import.meta.url), {+ fflate,+ "@/features/auth": { getAuthSessionEpoch: () => session.epoch },+ "@/features/chat": {},+ "@/features/model-picker": {},+ "@/i18n": { translate: (key: string) => key },+ "@/lib/audio-utils": {},+ "@/lib/api-base": { isTauri: false },+ "@/lib/native-files": {+ downloadFile: async (f: File | Blob) => saved.push(f),+ isDownloadCancelled: () => false,+ },+ "@/lib/toast": { toast },+ "@/lib/video-utils": {},+ "./api": {+ errorMessage: String,+ libraryItemFile: async (i: { name: string }) => {+ fetched(i.name);+ return file(i.name);+ },+ },+ "./file-kind": {},+ "./file-name": { hasOwnFile: () => true, ...fileNames },+ "./chat-handoff-store": {},+ }).downloadLibraryItems;+}++test("an attachment deleted as another account signs in is not dropped from its chats", async () => {+ const emitted: unknown[] = [];+ const session = { epoch: 1 };+ const store = loadStore(+ {+ getLibrary: async () => ({ items: [item("attachment:m:a")], folders: [] }),+ deleteLibraryItem: async () => {+ session.epoch += 1;+ },+ },+ emitted,+ session,+ );+ await store.getState().refresh();+ await store.getState().removeItem("attachment:m:a");+ assert.deepEqual(emitted, []);+});++test("a browser download with a file of unknown size goes one by one, never as a zip", async () => {+ const saved: File[] = [];+ const zipSync = () => {+ throw new Error("zipped in memory");+ };+ const downloadLibraryItems = loadDownloads({ zipSync }, saved, {+ uniqueFileNames: (n: string[]) => n,+ });+ await downloadLibraryItems([+ { name: "a.txt", sizeBytes: 10 },+ { name: "clip.webm", sizeBytes: null },+ ]);+ assert.deepEqual(names(saved), ["a.txt", "clip.webm"]);+});++test("a download started before a sign-in saves nothing of the next account's", async () => {+ const saved: File[] = [];+ const session = { epoch: 1 };+ const fetched: string[] = [];+ const signInDuring = (name: string) => {+ fetched.push(name);+ if (name === "a.txt") session.epoch += 1;+ };+ const downloadLibraryItems = loadDownloads({}, saved, { uniqueFileNames }, session, signInDuring);+ await downloadLibraryItems([+ { name: "a.txt", sizeBytes: null },+ { name: "b.txt", sizeBytes: null },+ ]);+ assert.deepEqual(names(saved), []);+ assert.deepEqual(fetched, ["a.txt"]);+});++test("a zip whose last file is read as another account signs in is not saved", async () => {+ const saved: Blob[] = [];+ const session = { epoch: 1 };+ const download = loadDownloads(fflate, saved, { uniqueFileNames }, session);+ const read = File.prototype.arrayBuffer;+ File.prototype.arrayBuffer = function (this: File) {+ session.epoch += 1;+ return read.call(this);+ };+ try {+ await download([+ { name: "a.txt", sizeBytes: 1 },+ { name: "b.txt", sizeBytes: 1 },+ ]);+ } finally {+ File.prototype.arrayBuffer = read;+ }+ assert.deepEqual(saved, []);+});++test("a file named __proto__ is kept in a zipped download", async () => {+ const saved: Blob[] = [];+ const downloadLibraryItems = loadDownloads(fflate, saved, { uniqueFileNames });+ await downloadLibraryItems([+ { name: "__proto__", sizeBytes: 1 },+ { name: "a.txt", sizeBytes: 1 },+ ]);+ const archive = fflate.unzipSync(new Uint8Array(await saved[0]!.arrayBuffer()));+ assert.deepEqual(Object.keys(archive), ["__proto__ (2)", "a.txt"]);+});diff --git a/studio/frontend/tests/personalization-locale-hydration.test.ts b/studio/frontend/tests/personalization-locale-hydration.test.tsindex 1e0cf2b4ee1..9a65559b5eb 100644--- a/studio/frontend/tests/personalization-locale-hydration.test.ts+++ b/studio/frontend/tests/personalization-locale-hydration.test.ts@@ -365,7 +365,7 @@ function widthRemote(chatWidthSaved?: boolean, chatWidth?: string) {const remote = remotePersonalization("auto");return {...remote,- version: 4,+ version: 5,chatWidthSaved,appearance: {...remote.appearance,diff --git a/studio/frontend/tests/sidebar-nav-migration.test.ts b/studio/frontend/tests/sidebar-nav-migration.test.tsindex 6a30cef0e99..77bc57863d9 100644--- a/studio/frontend/tests/sidebar-nav-migration.test.ts+++ b/studio/frontend/tests/sidebar-nav-migration.test.ts@@ -61,13 +61,24 @@ const shippedLayouts: SidebarNavItemPref[][] = [{ id: "export", pinned: false },{ id: "api", pinned: false },],+ [+ { id: "hub", pinned: true },+ { id: "projects", pinned: true },+ { id: "images", pinned: true },+ { id: "video", pinned: true },+ { id: "audio", pinned: false },+ { id: "train", pinned: true },+ { id: "recipes", pinned: false },+ { id: "export", pinned: false },+ { id: "api", pinned: false },+ ],];test("every previously shipped sidebar adopts the current default", () => {for (const sidebarNav of shippedLayouts) {const customization = sanitizeCustomization({ sidebarNav });assert.deepEqual(- migrateShippedSidebarNavDefault(customization, 4, 7).sidebarNav,+ migrateShippedSidebarNavDefault(customization, 4, 8).sidebarNav,DEFAULT_CUSTOMIZATION.sidebarNav,);}@@ -78,12 +89,12 @@ test("the untouched pre-Audio version-5 sidebar adopts the Audio-aware default",sidebarNav: shippedLayouts[3],});assert.deepEqual(- migrateShippedSidebarNavDefault(customization, 5, 7).sidebarNav,+ migrateShippedSidebarNavDefault(customization, 5, 8).sidebarNav,DEFAULT_CUSTOMIZATION.sidebarNav,);});-test("a customized version-5 sidebar keeps its order and only gains Audio", () => {+test("a customized version-5 sidebar keeps its order and only gains the rows added since", () => {const customizedV5: SidebarNavItemPref[] = [{ id: "projects", pinned: true },{ id: "hub", pinned: true },@@ -97,12 +108,12 @@ test("a customized version-5 sidebar keeps its order and only gains Audio", () =const customization = sanitizeCustomization({ sidebarNav: customizedV5 });assert.strictEqual(- migrateShippedSidebarNavDefault(customization, 5, 7),+ migrateShippedSidebarNavDefault(customization, 5, 8),customization,);assert.deepEqual(customization.sidebarNav.map((item) => item.id),- [...customizedV5.map((item) => item.id), "audio"],+ [...customizedV5.map((item) => item.id), "library", "audio"],);assert.equal(customization.sidebarNav.at(-1)?.pinned, false);});@@ -114,19 +125,28 @@ test("a user-arranged sidebar survives the migration", () => {),});assert.strictEqual(- migrateShippedSidebarNavDefault(customization, 4, 7),+ migrateShippedSidebarNavDefault(customization, 4, 8),customization,);});-test("an install sitting on the version-6 default picks Video up", () => {- // The layout this change replaces. Untouched, so it adopts the new default- // rather than being read as a deliberate choice to keep Video under More.+test("an install sitting on the version-6 default adopts the current layout", () => {const customization = sanitizeCustomization({ sidebarNav: shippedLayouts[4] });- const migrated = migrateShippedSidebarNavDefault(customization, 6, 7);+ const migrated = migrateShippedSidebarNavDefault(customization, 6, 8);assert.deepEqual(migrated.sidebarNav, DEFAULT_CUSTOMIZATION.sidebarNav);const ids = migrated.sidebarNav.filter((item) => item.pinned).map((i) => i.id);- assert.deepEqual(ids, ["hub", "projects", "images", "video", "train"]);+ assert.deepEqual(ids, ["hub", "projects", "library", "images", "train"]);+});++test("an install sitting on the version-7 default gains Library and moves Video to More", () => {+ const customization = sanitizeCustomization({ sidebarNav: shippedLayouts[5] });+ const migrated = migrateShippedSidebarNavDefault(customization, 7, 8);+ assert.deepEqual(migrated.sidebarNav, DEFAULT_CUSTOMIZATION.sidebarNav);+ assert.deepEqual(+ migrated.sidebarNav.slice(0, 3).map((item) => item.id),+ ["hub", "projects", "library"],+ );+ assert.equal(migrated.sidebarNav.find((item) => item.id === "video")?.pinned, false);});test("a shipped-looking layout chosen after migration is preserved", () => {@@ -134,7 +154,7 @@ test("a shipped-looking layout chosen after migration is preserved", () => {sidebarNav: shippedLayouts[2],});assert.strictEqual(- migrateShippedSidebarNavDefault(customization, 7, 7),+ migrateShippedSidebarNavDefault(customization, 8, 8),customization,);});@@ -152,10 +172,10 @@ test("a synced profile picks the layout change up too", async () => {// only migrates locally is overwritten by the stored layout on every login.// PERSONALIZATION_VERSION has to move with the layout for that migration to// run against the remote record.- const stored = sanitizeCustomization({ sidebarNav: shippedLayouts[4] });+ const stored = sanitizeCustomization({ sidebarNav: shippedLayouts[5] });const migrated = migrateShippedSidebarNavDefault(stored,- 3,+ 4,await personalizationVersion(),);assert.deepEqual(migrated.sidebarNav, DEFAULT_CUSTOMIZATION.sidebarNav);diff --git a/tests/studio/playwright_mac_tab_capabilities.py b/tests/studio/playwright_mac_tab_capabilities.pyindex 5b5b6862fc8..1d53e6170f2 100644--- a/tests/studio/playwright_mac_tab_capabilities.py+++ b/tests/studio/playwright_mac_tab_capabilities.py@@ -125,6 +125,7 @@ PROBE_PATHS = (LIVENESS_PATH, HEALTH_PATH)TABS = [("/chat", "projects", "Chat"),("/hub", "hub", "Hub"),+ ("/library", "library", "Library"),("/images", "images", "Images"),("/studio", "train", "Train"),("/video", "video", "Video"),@@ -148,7 +149,7 @@ _SIGNED_OUT_PATHS = ("/login", "/change-password")# once more. test_inline_row_ids_match_the_frontends_default_pinned_set holds this tuple to# the store's pinned set, in both directions, so neither a pin nor an unpin can leave an# assertion here silently observing nothing.-INLINE_ROW_IDS = ("hub", "projects", "images", "video", "train")+INLINE_ROW_IDS = ("hub", "projects", "library", "images", "train")# The row every pending-state assertion below is pinned to.GATED_ROW_ID = "train"# Intercept pattern for the browser's health reads.diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex 0641293d5f5..5b8799c97ee 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -2405,10 +2405,11 @@ def test_audio_page_matches_the_image_rail_header_and_action_footer():'@[68rem]:gap-2 @[68rem]:pl-4 @[68rem]:pr-2"' in header)assert 'triggerLabelClassName="text-ui-14 @[68rem]:text-ui-16"' in header- assert "grid h-full min-w-0 grid-cols-[1fr_auto]" in header+ assert "grid h-full min-w-0 grid-cols-[1fr_auto_auto] gap-2" in headerassert "@[50rem]:grid-cols-[1fr_auto_1fr]" in header- assert "col-start-2 justify-self-end pr-3" in header- assert "@[50rem]:justify-self-center @[50rem]:pr-0" in header+ assert "col-start-2 justify-self-end pt-" in header+ assert "@[50rem]:justify-self-center" in header+ assert "col-start-3" in header and "<LibraryPageLink" in headerassert "absolute" not in header.split("<PillTabs", 1)[0]assert "@[50rem]:flex-row @[50rem]:overflow-hidden" in layoutdiff --git a/tests/studio/test_reveal_file_manager.py b/tests/studio/test_reveal_file_manager.pyindex 16a7e6f316a..76860fed0ba 100644--- a/tests/studio/test_reveal_file_manager.py+++ b/tests/studio/test_reveal_file_manager.py@@ -87,7 +87,7 @@ def test_wsl_file_is_selected_in_explorer(linux_host, spawned, monkeypatch, tmp_target.write_bytes(b"gguf")path_utils.reveal_in_file_manager(target)assert spawned.run == [["wslpath", "-w", str(target)]]- assert spawned.popen == [["explorer.exe", f"/select,{_WINDOWS_PATH}"]]+ assert spawned.popen == [["explorer.exe", "/select,", _WINDOWS_PATH]]def test_wsl_directory_opens_in_explorer(linux_host, spawned, monkeypatch, tmp_path):diff --git a/tests/studio/test_reveal_file_manager_matrix.py b/tests/studio/test_reveal_file_manager_matrix.pyindex c6c6f1e0654..914096a4cd4 100644--- a/tests/studio/test_reveal_file_manager_matrix.py+++ b/tests/studio/test_reveal_file_manager_matrix.py@@ -74,7 +74,7 @@ def spawned(monkeypatch):def fake_popen(cmd, **kwargs):if calls.popen_error is not None:raise calls.popen_error- calls.popen.append(list(cmd))+ calls.popen.append(cmd if isinstance(cmd, str) else list(cmd))return types.SimpleNamespace()monkeypatch.setattr(subprocess, "run", fake_run)@@ -132,7 +132,7 @@ def test_windows_selects_a_file_in_explorer(windows, spawned, tmp_path):target = tmp_path / "report.csv"target.write_text("a,b\n")path_utils.reveal_in_file_manager(target)- assert spawned.popen == [["explorer", f"/select,{target}"]]+ assert spawned.popen == [f'explorer /select,"{target}"']assert spawned.startfile == []@@ -150,18 +150,16 @@ def test_windows_never_waits_on_explorer_or_reads_its_exit_code(windows, spawnedtarget.write_text("a,b\n")path_utils.reveal_in_file_manager(target)assert spawned.run == [], "explorer must not be run and waited on"- assert spawned.popen and spawned.popen[0][0] == "explorer"+ assert spawned.popen and spawned.popen[0].startswith("explorer /select,")def test_windows_keeps_a_comma_in_the_path_out_of_the_select_flag(windows, spawned, tmp_path):- """``/select,`` is comma-delimited and a filename may contain one. Recorded,- not asserted-correct: it is one argv element, so parsing is Explorer's- problem, not the shell's."""+ """``/select,`` is comma-delimited and a filename may contain one: the path is+ passed quoted after the flag, the documented form, so Explorer reads it whole."""target = tmp_path / "q3, final.csv"target.write_text("a,b\n")path_utils.reveal_in_file_manager(target)- assert spawned.popen == [["explorer", f"/select,{target}"]]- assert len(spawned.popen[0]) == 2+ assert spawned.popen == [f'explorer /select,"{target}"']# ---------------------------------------------------------------------------