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: document viewer for PDF, Word, Excel and PowerPoint, with origin links in Library (#12001)
Michael Han23a87c036351
diff --git a/studio/backend/core/chat_originals.py b/studio/backend/core/chat_originals.pynew file mode 100644index 00000000000..ee85e50ce20--- /dev/null+++ b/studio/backend/core/chat_originals.py@@ -0,0 +1,192 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The original files of documents sent in chat.++A chat keeps a document's extracted text for the model; the file itself (a PDF, a Word document, a+workbook or a deck) is kept here so it can be opened as it looked. Each is stored once under its+SHA-256, which the attachment records as ``{"original": {"sha256", "sizeBytes"}}``: a fork or an+import copies the reference, never the bytes, and a retried send stores nothing new.++A file no attachment references any more is removed by ``sweep``, once it is older than an hour, so+one uploaded moments before its message is saved is never taken. A sweep that leaves such a file for+being too new schedules another for when it is not.+"""++from __future__ import annotations++import contextvars+import hashlib+import os+import re+import threading+import time+import uuid+from pathlib import Path+from typing import Iterable, Optional++from loggers import get_logger+from utils.paths.storage_roots import account_path, ensure_account_dir++logger = get_logger(__name__)++EXTENSIONS = frozenset({".pdf", ".docx", ".xlsx", ".xlsm", ".pptx"})+MAX_BYTES = 50 * 1024 * 1024+_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")+_SWEEP_GRACE_SECONDS = 3600+_SWEEP_INTERVAL_SECONDS = 600+_sweep_lock = threading.Lock()+# Held across save-publish and sweep check-and-remove, so a sweep never removes a just-refreshed file.+_file_lock = threading.Lock()+# Per originals folder: each account has its own, and one account's sweep must not delay another's.+_last_sweep: dict[Path, float] = {}+_due: dict[Path, tuple[float, contextvars.Context]] = {}+_due_changed = threading.Condition()+_worker: Optional[threading.Thread] = None+++class TooLarge(Exception):+ pass+++def originals_dir() -> Path:+ """This account's originals folder. Only save() creates it, so a late sweep cannot recreate a+ deleted account's workspace."""+ return account_path("chat-originals")+++def attachment_sha256(attachment: object) -> Optional[str]:+ if not isinstance(attachment, dict):+ return None+ original = attachment.get("original")+ sha256 = original.get("sha256") if isinstance(original, dict) else None+ return sha256 if isinstance(sha256, str) and _SHA256_RE.match(sha256) else None+++def attachment_size(attachment: object) -> Optional[int]:+ original = attachment.get("original") if isinstance(attachment, dict) else None+ size = original.get("sizeBytes") if isinstance(original, dict) else None+ return size if isinstance(size, int) and size >= 0 and attachment_sha256(attachment) else None+++def path_for(attachment: object) -> Optional[Path]:+ sha256 = attachment_sha256(attachment)+ if sha256 is None:+ return None+ path = originals_dir() / sha256+ return path if path.is_file() else None+++def save(chunks: Iterable[bytes]) -> tuple[str, int]:+ """Store streamed bytes under their hash: (sha256, size). Raises TooLarge past MAX_BYTES."""+ directory = ensure_account_dir(originals_dir())+ tmp_path = directory / f".{uuid.uuid4().hex}.tmp"+ digest = hashlib.sha256()+ size = 0+ try:+ with open(tmp_path, "wb") as handle:+ for chunk in chunks:+ size += len(chunk)+ if size > MAX_BYTES:+ raise TooLarge()+ digest.update(chunk)+ handle.write(chunk)+ sha256 = digest.hexdigest()+ final_path = directory / sha256+ with _file_lock:+ if final_path.exists():+ os.utime(final_path)+ else:+ os.replace(tmp_path, final_path)+ return sha256, size+ finally:+ tmp_path.unlink(missing_ok = True)+++def sweep(force: bool = False) -> int:+ """Remove unreferenced originals past the grace period, at most every few minutes unless ``force``."""+ from storage.studio_db import chat_original_unreferenced, referenced_chat_original_hashes++ now = time.time()+ try:+ directory = originals_dir()+ if not directory.is_dir():+ return 0+ except (OSError, ValueError):+ return 0+ with _sweep_lock:+ throttled = not force and now - _last_sweep.get(directory, 0.0) < _SWEEP_INTERVAL_SECONDS+ if not throttled:+ _last_sweep[directory] = now+ if throttled:+ _schedule(directory)+ return 0+ try:+ referenced = referenced_chat_original_hashes()+ removed = 0+ waiting = False+ with os.scandir(directory) as entries:+ for entry in entries:+ is_original = _SHA256_RE.match(entry.name) is not None+ if (is_original and entry.name in referenced) or not entry.is_file():+ continue+ if not (is_original or entry.name.endswith(".tmp")):+ continue+ with _file_lock:+ try:+ mtime = os.stat(entry.path).st_mtime+ except FileNotFoundError:+ continue+ if now - mtime < _SWEEP_GRACE_SECONDS:+ waiting = True+ continue+ if not is_original:+ os.unlink(entry.path)+ else:+ # The scan may be stale (fork/import); recheck, blocking new references until removed.+ with chat_original_unreferenced(entry.name) as unreferenced:+ if not unreferenced:+ continue+ os.unlink(entry.path)+ removed += 1+ if waiting:+ _schedule(directory)+ return removed+ except Exception:+ logger.debug("chat_originals.sweep_failed", exc_info = True)+ return 0+++def _schedule(directory: Path) -> None:+ """Sweep ``directory`` again once the grace period has passed, in this account's context."""+ global _worker+ with _due_changed:+ if directory in _due:+ return+ _due[directory] = (time.monotonic() + _SWEEP_GRACE_SECONDS + 60, contextvars.copy_context())+ if _worker is None:+ _worker = threading.Thread(target = _run_due, name = "chat-originals-sweep", daemon = True)+ _worker.start()+ _due_changed.notify()+++def _run_due() -> None:+ """Runs each due sweep, sleeping until the next; ends once none is left."""+ global _worker+ while True:+ with _due_changed:+ while True:+ if not _due:+ _worker = None+ return+ now = time.monotonic()+ ready = [directory for directory, (at, _) in _due.items() if at <= now]+ if ready:+ break+ _due_changed.wait(min(at for at, _ in _due.values()) - now)+ jobs = [(directory, _due.pop(directory)[1]) for directory in ready]+ for _directory, context in jobs:+ try:+ context.run(sweep, True)+ except Exception:+ logger.debug("chat_originals.scheduled_sweep_failed", exc_info = True)diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.pyindex 4c779f7eb27..74d9a819921 100644--- a/studio/backend/core/export/export.py+++ b/studio/backend/core/export/export.py@@ -891,7 +891,13 @@ class ExportBackend:if self.current_checkpointelse None)- metadata = {"base_model": base_model}+ source = self.current_checkpoint+ metadata = {+ "base_model": base_model,+ "source_checkpoint": str(Path(source).resolve())+ if source and Path(source).exists()+ else None,+ }metadata_path = os.path.join(save_directory, "export_metadata.json")with open(metadata_path, "w", encoding = "utf-8") as f:json.dump(metadata, f, indent = 2)@@ -1707,6 +1713,7 @@ class ExportBackend:else:self.current_model.save_pretrained(save_directory)self.current_tokenizer.save_pretrained(save_directory)+ self._write_export_metadata(save_directory)logger.info(f"Adapter saved successfully to {save_directory}")output_path = str(Path(save_directory).resolve())diff --git a/studio/backend/core/library.py b/studio/backend/core/library.pyindex 3a9f3159c7a..6fdb0573b55 100644--- a/studio/backend/core/library.py+++ b/studio/backend/core/library.py@@ -29,6 +29,7 @@ import functoolsimport hashlibimport importlibimport io+import jsonimport mimetypesimport osimport platform@@ -98,6 +99,9 @@ def _item(model: Optional[dict] = None,archived: bool = False,fingerprint: Optional[str] = None,+ pair_id: Optional[str] = None,+ project_id: Optional[str] = None,+ run_id: Optional[str] = None,) -> dict:return {"id": item_id,@@ -112,6 +116,9 @@ def _item("fileUrl": file_url,"threadId": thread_id,"threadTitle": thread_title,+ "pairId": pair_id,+ "projectId": project_id,+ "runId": run_id,"textOnly": text_only,"model": model,"archived": archived,@@ -416,10 +423,13 @@ def _attachment_items() -> list[dict]:from storage.studio_db import list_chat_attachmentsitems = []+ counted: set[str] = set()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/")+ has_bytes = (+ attachment.get("type") in ("image", "audio")+ or content_type.startswith(("image/", "audio/", "video/"))+ or bool(attachment.get("hasOriginal")))message_id, attachment_id = attachment["messageId"], attachment["id"]items.append(@@ -434,8 +444,17 @@ def _attachment_items() -> list[dict]:thread_id = attachment.get("threadId"),thread_title = attachment.get("threadTitle"),text_only = not has_bytes,+ pair_id = attachment.get("pairId"),))+ sha256 = attachment.get("originalSha256")+ if sha256:+ text_bytes = attachment.get("textBytes") or 0+ first = attachment.get("hasOriginal") and sha256 not in counted+ items[-1]["storageBytes"] = text_bytes + (+ (attachment.get("sizeBytes") or 0) if first else 0+ )+ counted.add(sha256)return items@@ -559,6 +578,93 @@ def _tree_stats(path: Path) -> tuple[int, float, os.stat_result]:return total, newest, info+_EXPORT_SUFFIX_RE = re.compile(r"[-_](gguf|adapter|merged|finetune)$", re.IGNORECASE)+++def _training_runs_by_dir() -> dict[str, str]:+ """Folder name under outputs/ to the id of the newest training run that wrote it. A run that wrote+ anywhere else is left out, so an external folder of the same name never claims a managed model.+ A finished run outranks a running or failed one reusing the folder, which may have written nothing."""+ from storage.studio_db import get_connection+ from utils.paths.storage_roots import outputs_root, resolve_output_dir++ conn = get_connection()+ try:+ rows = conn.execute(+ "SELECT id, output_dir FROM training_runs WHERE output_dir IS NOT NULL"+ " ORDER BY status IN ('completed', 'stopped'), started_at"+ ).fetchall()+ except Exception:+ logger.debug("library.training_runs_unavailable", exc_info = True)+ return {}+ finally:+ conn.close()+ root = Path(outputs_root()).resolve()+ runs: dict[str, str] = {}+ for row in rows:+ try:+ path = Path(resolve_output_dir(row["output_dir"])).resolve()+ except (ValueError, OSError):+ continue+ if path.parent == root:+ runs[path.name] = row["id"]+ return runs+++_MAX_EXPORT_METADATA_BYTES = 1024 * 1024+++def _export_metadata(path: str, root: Path) -> Optional[dict]:+ """The export_metadata.json Studio writes beside an export, from the model up to its top folder."""+ here = Path(path)+ if not here.is_dir():+ here = here.parent+ while True:+ meta = here / "export_metadata.json"+ if meta.is_file():+ try:+ with open(meta, "rb") as handle:+ raw = handle.read(_MAX_EXPORT_METADATA_BYTES + 1)+ if len(raw) > _MAX_EXPORT_METADATA_BYTES:+ return None+ data = json.loads(raw.decode("utf-8-sig"))+ except (OSError, ValueError):+ return None+ return data if isinstance(data, dict) else None+ if here.parent == root or here == root or here.parent == here:+ return None+ here = here.parent+++def _model_run_id(path: str, origin: str, runs: dict[str, str]) -> Optional[str]:+ """The training run a model came out of: its own folder under outputs/, or for an export the+ checkpoint its metadata records. An older Studio export, with metadata but no checkpoint, falls+ back to its folder name (``{run}/{checkpoint}``, ``{run}-GGUF``); a folder with no metadata+ has no known origin."""+ from utils.paths.storage_roots import exports_root, outputs_root++ try:+ outputs = Path(outputs_root()).resolve()+ if origin == "training":+ return runs.get(Path(path).resolve().relative_to(outputs).parts[0])+ root = Path(exports_root()).resolve()+ top = Path(path).resolve().relative_to(root).parts[0]+ meta = _export_metadata(path, root)+ if meta is None:+ return None+ source = meta.get("source_checkpoint")+ if isinstance(source, str) and source:+ return runs.get(Path(source).resolve().relative_to(outputs).parts[0])+ except (ValueError, IndexError, OSError):+ return None+ while top and top not in runs:+ stripped = _EXPORT_SUFFIX_RE.sub("", top)+ if stripped == top:+ break+ top = stripped+ return runs.get(top)++def _model_items() -> list[dict]:from utils.models.model_config import (get_base_model_from_checkpoint,@@ -575,6 +681,7 @@ def _model_items() -> list[dict]:(name, path, "exported", export_type, base_model)for name, path, export_type, base_model in scan_exported_models(str(exports_root())))+ runs = _training_runs_by_dir() if found else {}items = []for name, path, origin, model_type, base_model in found:stats_path = Path(path)@@ -607,25 +714,38 @@ def _model_items() -> list[dict]:"baseModel": base_model,},fingerprint = _fingerprint(info),+ run_id = _model_run_id(path, origin, runs),))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."""+class _SandboxSession(NamedTuple):+ session_id: str+ thread_id: Optional[str]+ title: Optional[str]+ pair_id: Optional[str] = None+ project_id: Optional[str] = None+++def _sandbox_sessions() -> list[_SandboxSession]:from storage.studio_db import get_connectionconn = get_connection()try:threads = conn.execute(- "SELECT id, title FROM chat_threads WHERE project_id IS NULL"+ "SELECT id, title, pair_id 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"])+ return [+ _SandboxSession(row["id"], row["id"], row["title"], pair_id = row["pair_id"])+ for row in threads+ ] + [+ _SandboxSession(+ f"{_PROJECT_SESSION_PREFIX}{row['id']}", None, row["name"], project_id = row["id"]+ )for row in projectsif _studio_project_root(row["root_path"])]@@ -785,7 +905,7 @@ def _sandbox_items() -> list[dict]:items = []generation = _LISTING.generation- for session_id, thread_id, title in _sandbox_sessions():+ for session_id, thread_id, title, pair_id, project_id in _sandbox_sessions():try:directory = os.path.realpath(resolve_sandbox_workdir(session_id))names = _sandbox_listing_names(directory) if os.path.isdir(directory) else []@@ -812,6 +932,8 @@ def _sandbox_items() -> list[dict]:thread_id = thread_id,thread_title = title,fingerprint = _fingerprint(info),+ pair_id = pair_id,+ project_id = project_id,))return items@@ -2024,7 +2146,12 @@ def delete_item(item_id: str, fingerprint: Optional[str] = None) -> bool:`fingerprint` it was listed with, a path-derived item is only deleted while it is that file;ItemChanged otherwise."""with _overlay_lock:- return _delete_item(item_id, fingerprint)+ deleted = _delete_item(item_id, fingerprint)+ if deleted and item_id.startswith("attachment:"):+ # May have held the last reference to an original. Swept outside the lock.+ from core import chat_originals+ chat_originals.sweep()+ return deleteddef _delete_item(item_id: str, fingerprint: Optional[str]) -> bool:diff --git a/studio/backend/main.py b/studio/backend/main.pyindex b41c105be94..e1b17d5e86e 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -663,6 +663,18 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:return_start_linked_folder_auto_sync(generation)+ try:+ from core import chat_originals+ from core.training.account_jobs import startup_reconciliation_accounts+ from utils.account_context import run_as++ for account in startup_reconciliation_accounts():+ if _post_warm_retired(generation):+ return+ run_as(account, chat_originals.sweep, True)+ except Exception: # noqa: BLE001+ pass+# Last, and deliberately so: it is the only item here that is pure latency work rather than# correctness, so everything above keeps its place in the queue. Roughly 5.3s of diffusers# import that the first image load would otherwise pay, moved onto this thread, and only ondiff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 2c015b926a3..6c73367e45b 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -12,7 +12,7 @@ import reimport sqlite3from typing import Annotated, Any, Literal, Optional, Union-from fastapi import APIRouter, Depends, HTTPException, Query, Request+from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFilefrom pydantic import (BaseModel,BeforeValidator,@@ -24,6 +24,7 @@ from pydantic import ()from auth.authentication import get_current_subject+from core import chat_originalsfrom auth import policyfrom routes.chat_generation_runs import cancel_account_runfrom core.inference.llama_server_args import (@@ -831,6 +832,7 @@ async def delete_threads(# Archived turns and uploaded documents are keyed by thread id and unreferenced once the thread# is gone, so drop them rather than leaking scopes per deleted chat.await run_in_threadpool(_remove_thread_rag_data, payload.ids, cutoff = cutoff)+ await run_in_threadpool(chat_originals.sweep)return {"status": "deleted", "sandboxes_removed": removed, "sandboxes_kept": kept}@@ -979,6 +981,19 @@ def _decode_attachment_base64(payload: str) -> bytes:raise HTTPException(status_code = 422, detail = "Attachment data is corrupt") from exc+_ATTACHMENT_TAG_RE = re.compile(r"<attachment name=[^\n]*>\n(.*)\n</attachment>", re.DOTALL)+_ATTACHMENT_LABEL_RE = re.compile(r"\[(?:PDF|DOCX|HTML|ODS|ODT|XLSX|PPTX): [^\n]*\]\n")+++def _attachment_body_text(text: str) -> str:+ """An attachment's text without its chat wrapper, as the file itself reads."""+ tagged = _ATTACHMENT_TAG_RE.fullmatch(text)+ if tagged:+ return tagged.group(1)+ labelled = _ATTACHMENT_LABEL_RE.match(text)+ return text[labelled.end() :] if labelled else text++_AUDIO_FORMAT_MEDIA_TYPES = {"mp3": "audio/mpeg","wav": "audio/wav",@@ -998,22 +1013,48 @@ def _safe_image_media_type(media_type: str) -> str:return "application/octet-stream"[email protected]("/attachment-originals")+def upload_attachment_original(+ file: UploadFile = File(...), current_subject: str = Depends(get_current_subject)+) -> dict:+ """Store a chat document's original file; the message records the returned hash. Sync, so+ disk writes run in the threadpool."""+ from pathlib import PurePath++ if PurePath(file.filename or "").suffix.lower() not in chat_originals.EXTENSIONS:+ raise HTTPException(status_code = 415, detail = "Only documents keep their original file")+ try:+ sha256, size = chat_originals.save(iter(lambda: file.file.read(1024 * 1024), b""))+ except chat_originals.TooLarge:+ raise HTTPException(status_code = 413, detail = f"{file.filename} is too large")+ chat_originals.sweep()+ return {"sha256": sha256, "sizeBytes": size}++@router.get("/attachments/{message_id}/{attachment_id}/file")def get_attachment_file(message_id: str,attachment_id: str,current_subject: str = Depends(get_current_subject),):- """Serve one attachment's stored content: image, audio or video bytes, or- extracted text."""+ """Serve one attachment's stored content: a document's original file, image, audio or video+ bytes, or extracted text."""import urllib.parse- from fastapi.responses import Response+ from fastapi.responses import FileResponse, Responseattachment = get_chat_attachment(message_id, attachment_id)if attachment is None:raise HTTPException(status_code = 404, detail = "Attachment not found")+ original = chat_originals.path_for(attachment)+ if original is not None:+ return FileResponse(+ original,+ media_type = "application/octet-stream",+ headers = {"X-Content-Type-Options": "nosniff"},+ )+attachment_content_type = attachment.get("contentType")texts: list[str] = []for part in attachment.get("content") or []:@@ -1064,7 +1105,7 @@ def get_attachment_file(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)+ texts.append(_attachment_body_text(text))if texts:return Response(content = "\n".join(texts), media_type = "text/plain; charset=utf-8")raise HTTPException(status_code = 404, detail = "Attachment has no stored content")@@ -1090,6 +1131,7 @@ def delete_attachment() from excif not deleted:raise HTTPException(status_code = 404, detail = "Attachment not found")+ chat_originals.sweep()return {"ok": True}@@ -1228,6 +1270,7 @@ async def delete_project(logger.warning("failed to delete RAG sources for project %s", project_id, exc_info = True)# The project's chats go with it, so their archives and documents have to as well.await run_in_threadpool(_remove_thread_rag_data, member_ids, cutoff = cutoff)+ await run_in_threadpool(chat_originals.sweep)if project.get("sandboxPath"):from core.inference.tools import (finish_workspace_delete_when_idle,@@ -1389,8 +1432,8 @@ def save_thread_message(if get_chat_thread(thread_id) is None:raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")try:- return ChatMessage(- **upsert_chat_message(payload.model_dump(), allow_generation_edit = allow_generation_edit)+ saved = upsert_chat_message(+ payload.model_dump(), allow_generation_edit = allow_generation_edit)except sqlite3.IntegrityError as exc:if get_chat_thread(thread_id) is None:@@ -1405,6 +1448,8 @@ def save_thread_message(log = logger,headers = _conflict_headers(exc),) from exc+ chat_originals.sweep()+ return ChatMessage(**saved)@router.put("/threads/{thread_id}/messages", response_model = ChatMessageListResponse)@@ -1425,16 +1470,11 @@ def replace_thread_messages(raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")messages = [message.model_dump() for message in payload.messages]try:- return ChatMessageListResponse(- messages = [- ChatMessage(**m)- for m in sync_chat_messages(- thread_id,- messages,- prune_missing = payload.pruneMissing,- deleted_message_ids = payload.deletedMessageIds,- )- ]+ synced = sync_chat_messages(+ thread_id,+ messages,+ prune_missing = payload.pruneMissing,+ deleted_message_ids = payload.deletedMessageIds,)except sqlite3.IntegrityError as exc:if get_chat_thread(thread_id) is None:@@ -1449,6 +1489,8 @@ def replace_thread_messages(log = logger,headers = _conflict_headers(exc),) from exc+ chat_originals.sweep()+ return ChatMessageListResponse(messages = [ChatMessage(**m) for m in synced])@router.get("/count", response_model = ChatCountResponse)@@ -1570,6 +1612,7 @@ async def clear_history(await run_in_threadpool(_remove_thread_rag_data, list(dict.fromkeys(thread_ids + cleared)), cutoff = cutoff)+ await run_in_threadpool(chat_originals.sweep)# "Clear all chats" is the common bulk delete.# delete_files matches DELETE /threads: off by default, since the files are the user's.removed, kept = await _remove_sandboxes(list(dict.fromkeys(thread_ids + cleared)), delete_files)diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 474bfe5202b..3bd41d56b82 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -18,13 +18,15 @@ import reimport shutilimport sqlite3import threading+from contextlib import contextmanagerfrom datetime import datetime, timezonefrom pathlib import Pathlogger = logging.getLogger(__name__)-from typing import Any, Callable, Iterable, Mapping, Optional+from typing import Any, Callable, Iterable, Iterator, Mapping, Optional+from core import chat_originalsfrom utils.account_context import is_owner_contextfrom utils.paths import (ensure_account_dir,@@ -120,7 +122,7 @@ _schema_lock = threading.Lock()_schema_ready: set[Path] = set()_SQLITE_IN_CHUNK_SIZE = 900_PROJECT_WORKSPACE_SUBDIRS = ("sandbox",)-_CHAT_ATTACHMENT_INVENTORY_VERSION = 3+_CHAT_ATTACHMENT_INVENTORY_VERSION = 5def _project_slug(name: str) -> str:@@ -619,10 +621,19 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:type TEXT,content_type TEXT,size_bytes INTEGER,+ original_sha256 TEXT,+ text_bytes INTEGER,PRIMARY KEY(message_id, attachment_id)) WITHOUT ROWID""")+ inventory_columns = {+ row[1] for row in conn.execute("PRAGMA table_info(chat_attachment_inventory)")+ }+ if "original_sha256" not in inventory_columns:+ conn.execute("ALTER TABLE chat_attachment_inventory ADD COLUMN original_sha256 TEXT")+ if "text_bytes" not in inventory_columns:+ conn.execute("ALTER TABLE chat_attachment_inventory ADD COLUMN text_bytes INTEGER")conn.execute("""CREATE TABLE IF NOT EXISTS chat_attachment_inventory_state (@@ -3518,6 +3529,8 @@ def _chat_attachment_inventory_entries("type": _chat_attachment_metadata_text(attachment.get("type")),"contentType": _chat_attachment_metadata_text(attachment.get("contentType")),"sizeBytes": _chat_attachment_size_bytes(attachment),+ "originalSha256": chat_originals.attachment_sha256(attachment),+ "textBytes": _chat_attachment_text_bytes(attachment),})return entries@@ -3545,8 +3558,9 @@ def _replace_chat_attachment_inventory(conn.executemany("""INSERT INTO chat_attachment_inventory- (message_id, attachment_id, name, type, content_type, size_bytes)- VALUES (?, ?, ?, ?, ?, ?)+ (message_id, attachment_id, name, type, content_type, size_bytes, original_sha256,+ text_bytes)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",[(@@ -3556,6 +3570,8 @@ def _replace_chat_attachment_inventory(entry["type"],entry["contentType"],entry["sizeBytes"],+ entry["originalSha256"],+ entry["textBytes"],)for entry in entries],@@ -4405,10 +4421,26 @@ def _attachment_content_parts(attachment: dict) -> list[dict]:return [part for part in content if isinstance(part, dict)]+def _chat_attachment_text_bytes(attachment: dict) -> Optional[int]:+ """UTF-8 size of a kept original's extracted text, which the database stores as well. None+ without an original, whose size already counts its text."""+ if chat_originals.attachment_sha256(attachment) is None:+ return None+ return sum(+ len(part["text"].encode("utf-8", errors = "ignore"))+ for part in _attachment_content_parts(attachment)+ if isinstance(part.get("text"), str)+ )++def _chat_attachment_size_bytes(attachment: dict) -> Optional[int]:"""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."""+ character length. None when there is no sizable content. A document whose original file is kept+ counts that file instead of its extracted text."""+ original_size = chat_originals.attachment_size(attachment)+ if original_size is not None:+ return original_sizetotal = 0found = Falsefor part in _attachment_content_parts(attachment):@@ -4516,7 +4548,7 @@ def list_chat_attachments_page(rows = conn.execute("""SELECT i.attachment_id, i.name, i.type, i.content_type,- i.size_bytes, m.id AS message_id, m.thread_id,+ i.size_bytes, i.original_sha256, i.text_bytes, m.id AS message_id, m.thread_id,m.created_at, t.title AS thread_title, t.pair_idFROM chat_attachment_inventory iJOIN chat_messages m ON m.id = i.message_id@@ -4531,6 +4563,7 @@ def list_chat_attachments_page(has_more = len(rows) > limitpage_rows = rows[:limit]+ originals = chat_originals.originals_dir()attachments = [{"id": row["attachment_id"],@@ -4542,6 +4575,10 @@ def list_chat_attachments_page("type": row["type"],"contentType": row["content_type"],"sizeBytes": row["size_bytes"],+ "originalSha256": row["original_sha256"],+ "textBytes": row["text_bytes"],+ "hasOriginal": bool(row["original_sha256"])+ and (originals / row["original_sha256"]).is_file(),"createdAt": row["created_at"],}for row in page_rows@@ -4549,6 +4586,40 @@ def list_chat_attachments_page(return attachments, offset + limit if has_more else None+def referenced_chat_original_hashes() -> set[str]:+ """Every stored original a chat attachment still points at."""+ conn = get_connection()+ try:+ _ensure_chat_attachment_inventory_current(conn)+ rows = conn.execute(+ "SELECT DISTINCT original_sha256 FROM chat_attachment_inventory"+ " WHERE original_sha256 IS NOT NULL"+ ).fetchall()+ finally:+ conn.close()+ return {row[0] for row in rows}+++@contextmanager+def chat_original_unreferenced(sha256: str) -> Iterator[bool]:+ """Whether no attachment references ``sha256``, with the write lock held until the block+ ends: a message that would reference it waits, so it cannot do so while the file is removed."""+ conn = get_connection()+ try:+ conn.execute("BEGIN IMMEDIATE")+ _ensure_chat_attachment_inventory_current(conn)+ row = conn.execute(+ "SELECT 1 FROM chat_attachment_inventory WHERE original_sha256 = ? LIMIT 1", (sha256,)+ ).fetchone()+ yield row is None+ conn.commit()+ except BaseException:+ conn.rollback()+ raise+ finally:+ conn.close()++def list_chat_attachments() -> list[dict]:"""Compatibility helper returning the full normalized inventory."""attachments: list[dict] = []diff --git a/studio/backend/tests/test_chat_attachments.py b/studio/backend/tests/test_chat_attachments.pyindex 7e3fff74d81..027e3057c07 100644--- a/studio/backend/tests/test_chat_attachments.py+++ b/studio/backend/tests/test_chat_attachments.py@@ -364,13 +364,14 @@ def test_attachment_file_serves_text_parts(tmp_path, monkeypatch):"type": "document","name": "notes.txt","content": [- {"type": "text", "text": "first"},- {"type": "text", "text": "second"},+ {"type": "text", "text": "<attachment name=notes.txt>\nfirst\n</attachment>"},+ {"type": "text", "text": "[PDF: notes.pdf]\nsecond"},+ {"type": "text", "text": "third"},],}_seed(tmp_path, monkeypatch, [attachment])response = chat_history.get_attachment_file("msg-1", "att-txt", current_subject = "unsloth")- assert response.body.decode("utf-8") == "first\nsecond"+ assert response.body.decode("utf-8") == "first\nsecond\nthird"assert response.media_type.startswith("text/plain")@@ -661,3 +662,36 @@ def test_png_data_url_keeps_its_media_type(tmp_path, monkeypatch):image_id = _content_part_id_for("msg-cmp", "image")response = chat_history.get_attachment_file("msg-cmp", image_id, current_subject = "unsloth")assert response.media_type == "image/png"+++def test_a_sweep_never_creates_the_originals_folder(tmp_path, monkeypatch):+ from core import chat_originals++ _reset_studio_db(tmp_path, monkeypatch)+ assert chat_originals.sweep(force = True) == 0+ assert not chat_originals.originals_dir().exists()+++def test_a_sweep_rechecks_a_stale_snapshot_before_removing(tmp_path, monkeypatch):+ from core import chat_originals++ _reset_studio_db(tmp_path, monkeypatch)+ sha256, size = chat_originals.save([b"%PDF-1.4 kept"])+ path = chat_originals.originals_dir() / sha256+ os.utime(path, (0, 0))+ studio_db.upsert_chat_thread(_thread())+ attachment = {+ "id": "att-1",+ "type": "document",+ "name": "a.pdf",+ "contentType": "application/pdf",+ "content": [{"type": "text", "text": "x"}],+ "original": {"sha256": sha256, "sizeBytes": size},+ }+ studio_db.upsert_chat_message(_message("msg-1", attachments = [attachment]))+ monkeypatch.setattr(studio_db, "referenced_chat_original_hashes", lambda: set())+ assert chat_originals.sweep(force = True) == 0+ assert path.is_file()+ studio_db.delete_chat_threads(["thread-1"])+ assert chat_originals.sweep(force = True) == 1+ assert not path.exists()diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.pyindex f49f5441f1d..42171f520b5 100644--- a/studio/backend/tests/test_chat_history_routes.py+++ b/studio/backend/tests/test_chat_history_routes.py@@ -49,6 +49,39 @@ def test_async_delete_handlers_dispatch_sqlite_to_the_threadpool():assert "run_in_threadpool" in inspect.getsource(handler)+def test_message_removal_paths_sweep_chat_originals(monkeypatch):+ """A removed or rewritten message can drop the last reference to a kept original, so every+ path sweeps."""+ for handler in (+ chat_history.clear_history,+ chat_history.delete_project,+ chat_history.delete_threads,+ ):+ assert "chat_originals.sweep" in inspect.getsource(handler)++ sweeps = []+ monkeypatch.setattr(chat_history, "get_chat_thread", lambda thread_id: {"id": thread_id})+ monkeypatch.setattr(chat_history, "sync_chat_messages", lambda *args, **kwargs: [])+ monkeypatch.setattr(+ chat_history.chat_originals, "sweep", lambda force = False: sweeps.append(force)+ )+ for prune, deleted in ((False, []), (True, []), (False, ["msg-2"])):+ chat_history.replace_thread_messages(+ "thread-1",+ chat_history.ChatMessageSyncRequest(+ messages = [_message("msg-1", "thread-1")],+ pruneMissing = prune,+ deletedMessageIds = deleted,+ ),+ current_subject = "test-user",+ )+ monkeypatch.setattr(chat_history, "upsert_chat_message", lambda message, **kwargs: message)+ chat_history.save_thread_message(+ "thread-1", "msg-1", _message("msg-1", "thread-1"), current_subject = "test-user"+ )+ assert sweeps == [False] * 4++def test_replace_thread_messages_rejects_body_thread_mismatch(monkeypatch):called = Falsediff --git a/studio/backend/tests/test_library_routes.py b/studio/backend/tests/test_library_routes.pyindex c6db62152eb..63b4dc525c5 100644--- a/studio/backend/tests/test_library_routes.py+++ b/studio/backend/tests/test_library_routes.py@@ -321,6 +321,54 @@ def test_chat_attachments_holding_bytes_are_known_by_their_type_in_any_case(clieassert deleted == [("m:1", "voice")]+def test_deleting_a_chat_attachment_from_the_library_sweeps_its_original(client, monkeypatch):+ import storage.studio_db as studio_db+ from core import chat_originals++ sweeps = []+ monkeypatch.setattr(chat_originals, "sweep", lambda force = False: sweeps.append(force))+ monkeypatch.setattr(studio_db, "delete_chat_attachment", lambda *ids: True)+ assert _delete(client, "attachment:m:doc") == 200+ assert sweeps == [False]+++def test_an_original_sent_many_times_counts_once_toward_disk_usage(client, monkeypatch):+ import storage.studio_db as studio_db++ def sent(+ attachment_id,+ sha256,+ has_original = True,+ ):+ return {+ "messageId": "m",+ "id": attachment_id,+ "type": "document",+ "contentType": "application/pdf",+ "sizeBytes": 1000,+ "originalSha256": sha256,+ "textBytes": 50,+ "hasOriginal": has_original,+ }++ monkeypatch.setattr(library, "_SOURCES", (library._attachment_items,))+ monkeypatch.setattr(+ studio_db,+ "list_chat_attachments",+ lambda: [+ sent("a", "1" * 64),+ sent("b", "1" * 64),+ sent("c", "2" * 64),+ sent("d", "1" * 64),+ sent("e", "3" * 64, has_original = False),+ ],+ )+ items = _items(client)[0]+ usage = [items[f"attachment:m:{name}"]["storageBytes"] for name in "abcde"]+ assert usage == [1050, 50, 1050, 50, 50]+ assert all(items[f"attachment:m:{name}"]["sizeBytes"] == 1000 for name in "abcde")++def test_a_chat_audio_part_is_typed_by_its_format_or_its_bytes():from storage.studio_db import _content_part_attachments@@ -592,6 +640,55 @@ def test_fine_tuned_models_are_listed_but_not_deleted_here(client, monkeypatch):shutil.rmtree(gguf, ignore_errors = True)+def test_training_runs_map_only_folders_directly_under_outputs(monkeypatch):+ """A newer run in an external folder of the same name, or a newer failed one in the same+ folder, must not claim the managed model."""+ import sqlite3++ from storage import studio_db+ from utils.paths.storage_roots import outputs_root++ conn = sqlite3.connect(":memory:")+ conn.row_factory = sqlite3.Row+ conn.execute(+ "CREATE TABLE training_runs (id TEXT, output_dir TEXT, started_at TEXT, status TEXT)"+ )+ conn.executemany(+ "INSERT INTO training_runs VALUES (?, ?, ?, ?)",+ [+ ("managed", str(outputs_root() / "my-run"), "2026-01-01", "completed"),+ ("external", "/tmp/elsewhere/my-run", "2026-02-01", "completed"),+ ("nested", str(outputs_root() / "group" / "other"), "2026-03-01", "completed"),+ ("failed", str(outputs_root() / "my-run"), "2026-04-01", "error"),+ ],+ )+ monkeypatch.setattr(studio_db, "get_connection", lambda: conn)+ assert library._training_runs_by_dir() == {"my-run": "managed"}+++def test_an_export_links_to_its_run_only_through_studio_metadata(tmp_path, monkeypatch):+ from utils.paths import storage_roots++ outputs, exports = tmp_path / "outputs", tmp_path / "exports"+ monkeypatch.setattr(storage_roots, "outputs_root", lambda: outputs)+ monkeypatch.setattr(storage_roots, "exports_root", lambda: exports)+ runs = {"foo": "run-foo", "bar": "run-bar"}+ for name, meta in [+ ("foo-GGUF", None),+ ("foo-merged", '{"base_model": null}'),+ ("renamed", json.dumps({"source_checkpoint": str(outputs / "bar" / "checkpoint-10")})),+ ]:+ (exports / name).mkdir(parents = True)+ (exports / name / "model.gguf").write_bytes(b"x")+ if meta:+ (exports / name / "export_metadata.json").write_text(meta)+ run_id = lambda name: library._model_run_id(+ str(exports / name / "model.gguf"), "exported", runs+ )+ assert run_id("foo-GGUF") is None+ assert (run_id("foo-merged"), run_id("renamed")) == ("run-foo", "run-bar")++def test_an_api_key_lists_fine_tunes_by_reference_and_can_still_act_on_them(client, monkeypatch):import shutildiff --git a/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsx b/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsxnew file mode 100644index 00000000000..d57dc067b0c--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsx@@ -0,0 +1,204 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"use client";++import type { AttachmentSource } from "@/components/assistant-ui/use-attachment-source";+import { DocumentView, documentKind, isMarkdown } from "@/components/file-viewer";+import { MarkdownPreview } from "@/components/markdown/markdown-preview";+import { MediaViewer, ScaleMenu } from "@/components/media-viewer";+import { Spinner } from "@/components/ui/spinner";+import {+ attachmentBodyText,+ fetchChatAttachmentBlob,+ readAttachmentText,+ truncateAttachmentPreviewText,+} from "@/features/chat";+import { formatBytes } from "@/features/hub";+import { useT } from "@/i18n";+import { downloadFile } from "@/lib/native-files";+import { useAuiState } from "@assistant-ui/react";+import { Slot } from "radix-ui";+import { type FC, type PropsWithChildren, useEffect, useRef, useState } from "react";++const SCALES = [0.5, 0.75, 1, 1.25, 1.5, 2];++type Loaded = { blob?: Blob; text?: string; plain?: string; truncated?: boolean; error?: boolean };++const DocumentBody: FC<{ name: string; contentType?: string; loaded: Loaded; scale: number }> = ({+ name,+ contentType,+ loaded,+ scale,+}) => {+ const t = useT();+ if (loaded.error) {+ return <p className="m-auto text-sm text-muted-foreground">{t("library.preview.cannotPreview")}</p>;+ }+ if (loaded.plain !== undefined) {+ return (+ <pre className="size-full overflow-auto whitespace-pre-wrap px-6 py-4 font-sans text-ui-14 select-text">+ {loaded.plain}+ </pre>+ );+ }+ if (loaded.text !== undefined) {+ return (+ <div className="size-full overflow-auto px-6">+ <div className="mx-auto max-w-3xl" style={{ zoom: scale }}>+ <MarkdownPreview+ markdown={loaded.text}+ defer={true}+ className="max-h-none select-text overflow-visible border-0 bg-transparent px-2 py-4 text-ui-15p5"+ />+ </div>+ </div>+ );+ }+ const kind = documentKind(name, contentType);+ if (!loaded.blob || !kind) return <Spinner className="m-auto size-6" />;+ return <DocumentView file={loaded.blob} kind={kind} name={name} contentType={contentType} scale={scale} />;+};++const DocumentDialog: FC<+ PropsWithChildren<{+ source: AttachmentSource;+ load: () => Promise<Blob>;+ redactFromReload: boolean;+ textFallback?: boolean;+ }>+> = ({ children, source, load, redactFromReload, textFallback = false }) => {+ const [open, setOpen] = useState(false);+ const [scale, setScale] = useState(1);+ const [loaded, setLoaded] = useState<Loaded | null>(null);+ const markdown = isMarkdown(source.name, source.contentType ?? "");+ const loadRef = useRef(load);+ useEffect(() => {+ loadRef.current = load;+ });++ useEffect(() => {+ if (!open || loaded) return;+ let cancelled = false;+ loadRef+ .current()+ .then(async (blob) => {+ let next: Loaded = { blob };+ if (markdown) {+ // A composer File decodes as its adapter read it (BOM, UTF-16); Blob.text() is UTF-8 only.+ const { text, truncated } =+ blob instanceof File+ ? await readAttachmentText(blob, source.name, source.contentType)+ : truncateAttachmentPreviewText(await blob.text());+ next = { blob, text, truncated };+ } else if (textFallback && blob.type.startsWith("text/")) {+ const { text, truncated } = truncateAttachmentPreviewText(await blob.text());+ next = { blob, plain: text, truncated };+ }+ if (!cancelled) setLoaded(next);+ })+ .catch(() => !cancelled && setLoaded({ error: true }));+ return () => {+ cancelled = true;+ };+ }, [open, loaded, markdown, textFallback, source.name, source.contentType]);++ const blob = loaded?.blob;+ const meta = [+ source.name.split(".").pop()?.toUpperCase(),+ blob ? formatBytes(blob.size) : null,+ loaded?.truncated ? "preview truncated" : null,+ ]+ .filter(Boolean)+ .join(" · ");++ return (+ <>+ <Slot.Root+ onClick={() => setOpen(true)}+ className="aui-attachment-preview-trigger cursor-pointer transition-colors hover:bg-accent/50"+ >+ {children}+ </Slot.Root>+ <MediaViewer+ open={open}+ onOpenChange={(next) => {+ setOpen(next);+ if (!next) setLoaded(null);+ }}+ title={source.name}+ meta={meta}+ media={false}+ noun="file"+ flush={true}+ redactFromReload={redactFromReload}+ extra={+ <ScaleMenu value={scale} scales={SCALES} onChange={(value) => setScale(Number(value))} />+ }+ actions={{+ onDownload: blob+ ? () =>+ void (loaded?.plain !== undefined+ ? downloadFile(blob, `${source.name.replace(/\.[^.]+$/, "")}.txt`, "text/plain")+ : downloadFile(blob, source.name, source.contentType || undefined))+ : undefined,+ }}+ >+ {open && (+ <DocumentBody+ name={source.name}+ contentType={source.contentType}+ loaded={loaded ?? {}}+ scale={scale}+ />+ )}+ </MediaViewer>+ </>+ );+};++const SentOriginalDialog: FC<+ PropsWithChildren<{ source: AttachmentSource; redactFromReload: boolean }>+> = ({ children, source, redactFromReload }) => {+ const messageId = useAuiState(({ message }) => message.id);+ const attachmentId = useAuiState(({ attachment }) => attachment.id);+ return (+ <DocumentDialog+ source={source}+ load={() => fetchChatAttachmentBlob(messageId, attachmentId)}+ redactFromReload={redactFromReload}+ textFallback={true}+ >+ {children}+ </DocumentDialog>+ );+};++export const AttachmentDocumentDialog: FC<+ PropsWithChildren<{ source: AttachmentSource; redactFromReload: boolean }>+> = ({ children, source, redactFromReload }) => {+ const { file, text } = source;+ if (file) {+ return (+ <DocumentDialog source={source} load={() => Promise.resolve(file)} redactFromReload={redactFromReload}>+ {children}+ </DocumentDialog>+ );+ }+ if (!source.hasOriginal && text !== undefined) {+ return (+ <DocumentDialog+ source={source}+ load={() => Promise.resolve(new Blob([attachmentBodyText(text)]))}+ redactFromReload={redactFromReload}+ >+ {children}+ </DocumentDialog>+ );+ }+ return (+ <SentOriginalDialog source={source} redactFromReload={redactFromReload}>+ {children}+ </SentOriginalDialog>+ );+};diff --git a/studio/frontend/src/components/assistant-ui/attachment-preview.tsx b/studio/frontend/src/components/assistant-ui/attachment-preview.tsxindex ec1bf1020ab..fdcf6cd4123 100644--- a/studio/frontend/src/components/assistant-ui/attachment-preview.tsx+++ b/studio/frontend/src/components/assistant-ui/attachment-preview.tsx@@ -3,6 +3,7 @@"use client";+import { AttachmentDocumentDialog } from "@/components/assistant-ui/attachment-document-dialog";import { AudioPlayer } from "@/components/assistant-ui/audio-player";import {type AttachmentSource,@@ -361,6 +362,14 @@ export const AttachmentPreviewDialog: FC<);}+ if (source.kind === "document") {+ return (+ <AttachmentDocumentDialog source={source} redactFromReload={redactFromReload}>+ {children}+ </AttachmentDocumentDialog>+ );+ }+if (!(source.file || source.text)) {return children;}diff --git a/studio/frontend/src/components/assistant-ui/attachment-selection.ts b/studio/frontend/src/components/assistant-ui/attachment-selection.tsindex 4645ba1c0ea..982ae585809 100644--- a/studio/frontend/src/components/assistant-ui/attachment-selection.ts+++ b/studio/frontend/src/components/assistant-ui/attachment-selection.ts@@ -1,9 +1,10 @@// 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 { documentKind, isMarkdown, sheetDelimiter } from "@/components/file-viewer/kind";import { isAudioAttachment } from "@/features/chat/attachment-content";-export type AttachmentPreviewKind = "image" | "audio" | "text";+export type AttachmentPreviewKind = "image" | "audio" | "text" | "document";export type AttachmentAudioPart = { data: string; format: string };@@ -22,8 +23,21 @@ export type AttachmentSelection = {image: string | undefined;audio: AttachmentAudioPart | undefined;text: string | undefined;+ hasOriginal: boolean;};+function isViewableDocument(+ name: string,+ contentType: string | undefined,+ file: File | undefined,+ hasOriginal: boolean,+ hasText: boolean,+): boolean {+ if (isMarkdown(name, contentType)) return Boolean(file) || hasText;+ if (!documentKind(name, contentType)) return false;+ return Boolean(file) || hasOriginal || (sheetDelimiter(name, contentType) !== null && hasText);+}+/*** Picks the parts a preview can show out of the attachment in scope.*@@ -43,7 +57,8 @@ export const selectAttachmentSource = ({};}): AttachmentSelection => {const parts = attachment.content ?? [];- const file = (attachment as { file?: File }).file;+ const held = (attachment as { file?: unknown }).file;+ const file = held instanceof File ? held : undefined;const contentType =file?.type ||(attachment as { contentType?: string }).contentType ||@@ -56,9 +71,14 @@ export const selectAttachmentSource = ({.filter((part) => part.type === "text").map((part) => part.text).join("\n");+ const hasOriginal = Boolean((attachment as { original?: unknown }).original);+ const isDocument =+ !isImage &&+ !isAudio &&+ isViewableDocument(attachment.name, contentType, file, hasOriginal, Boolean(text));return {- kind: isImage ? "image" : isAudio ? "audio" : "text",+ kind: isImage ? "image" : isAudio ? "audio" : isDocument ? "document" : "text",name: attachment.name,contentType,file,@@ -67,5 +87,6 @@ export const selectAttachmentSource = ({: undefined,audio: isImage ? undefined : audio,text: text || undefined,+ hasOriginal,};};diff --git a/studio/frontend/src/components/assistant-ui/use-attachment-source.ts b/studio/frontend/src/components/assistant-ui/use-attachment-source.tsindex 2ca1b540201..9f7603ea922 100644--- a/studio/frontend/src/components/assistant-ui/use-attachment-source.ts+++ b/studio/frontend/src/components/assistant-ui/use-attachment-source.ts@@ -22,6 +22,7 @@ export type AttachmentSource = {src: string | undefined;audio: AttachmentAudioPart | undefined;text: string | undefined;+ hasOriginal: boolean;};const useFileSrc = (file: File | undefined): string | undefined => {@@ -45,7 +46,9 @@ const useFileSrc = (file: File | undefined): string | undefined => {export const useAttachmentSource = (): AttachmentSource => {const source = useAuiState(useShallow(selectAttachmentSource));- const fileSrc = useFileSrc(source.kind === "text" ? undefined : source.file);+ const fileSrc = useFileSrc(+ source.kind === "text" || source.kind === "document" ? undefined : source.file,+ );// audio passes through unjoined: the payload is MAX_AUDIO_SIZE of base64 and every tile mounts this hookreturn {@@ -56,6 +59,7 @@ export const useAttachmentSource = (): AttachmentSource => {src: fileSrc ?? source.image,audio: source.audio,text: source.text,+ hasOriginal: source.hasOriginal,};};diff --git a/studio/frontend/src/components/file-viewer/document-view.tsx b/studio/frontend/src/components/file-viewer/document-view.tsxnew file mode 100644index 00000000000..b43e73f88d8--- /dev/null+++ b/studio/frontend/src/components/file-viewer/document-view.tsx@@ -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 { Spinner } from "@/components/ui/spinner";+import { Suspense, lazy } from "react";+import type { DocumentKind } from "./kind";++const PdfView = lazy(() => import("./pdf-view"));+const OfficeView = lazy(() => import("./office-view"));++export function DocumentView({+ file,+ kind,+ name,+ contentType = "",+ scale = 1,+}: {+ file: Blob;+ kind: DocumentKind;+ name: string;+ contentType?: string;+ scale?: number;+}) {+ return (+ <Suspense fallback={<Spinner className="m-auto size-6" />}>+ {kind === "pdf" ? (+ <PdfView file={file} scale={scale} />+ ) : (+ <OfficeView file={file} kind={kind} name={name} contentType={contentType} scale={scale} />+ )}+ </Suspense>+ );+}diff --git a/studio/frontend/src/components/file-viewer/index.ts b/studio/frontend/src/components/file-viewer/index.tsnew file mode 100644index 00000000000..ef2adcaf240--- /dev/null+++ b/studio/frontend/src/components/file-viewer/index.ts@@ -0,0 +1,5 @@+// 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 { DocumentView } from "./document-view";+export { type DocumentKind, MAX_DOCUMENT_PREVIEW_BYTES, documentKind, isMarkdown, sheetDelimiter } from "./kind";diff --git a/studio/frontend/src/components/file-viewer/kind.ts b/studio/frontend/src/components/file-viewer/kind.tsnew file mode 100644index 00000000000..b19c64edf28--- /dev/null+++ b/studio/frontend/src/components/file-viewer/kind.ts@@ -0,0 +1,64 @@+// 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 DocumentKind = "pdf" | "docx" | "sheet" | "slides";++const EXTENSION_KINDS: Record<string, DocumentKind> = {+ pdf: "pdf",+ docx: "docx",+ xlsx: "sheet",+ xlsm: "sheet",+ csv: "sheet",+ tsv: "sheet",+ pptx: "slides",+};++const TYPE_KINDS: Record<string, DocumentKind> = {+ "application/pdf": "pdf",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "sheet",+ "application/vnd.ms-excel.sheet.macroenabled.12": "sheet",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "slides",+ "text/csv": "sheet",+ "text/tab-separated-values": "sheet",+};++// Own keys only: a name ending ".constructor" must not find Object.prototype's.+function lookUp(table: Record<string, DocumentKind>, key: string): DocumentKind | undefined {+ return Object.hasOwn(table, key) ? table[key] : undefined;+}++function extensionOf(name: string): string {+ const dot = name.lastIndexOf(".");+ return dot > 0 ? name.slice(dot + 1).toLowerCase() : "";+}++function mimeOf(contentType: string): string {+ return contentType.split(";", 1)[0]!.trim().toLowerCase();+}++export function documentKind(name: string, contentType = ""): DocumentKind | null {+ return lookUp(EXTENSION_KINDS, extensionOf(name)) ?? lookUp(TYPE_KINDS, mimeOf(contentType)) ?? null;+}++const DELIMITERS: Record<string, "," | "\t"> = {+ csv: ",",+ tsv: "\t",+ "text/csv": ",",+ "text/tab-separated-values": "\t",+};++export function sheetDelimiter(name: string, contentType = ""): "," | "\t" | null {+ const extension = extensionOf(name);+ const key = lookUp(EXTENSION_KINDS, extension) ? extension : mimeOf(contentType);+ return Object.hasOwn(DELIMITERS, key) ? DELIMITERS[key]! : null;+}++const MARKDOWN_EXTENSIONS = new Set(["md", "markdown", "mdx"]);+const MARKDOWN_TYPES = new Set(["text/markdown", "text/x-markdown"]);++export function isMarkdown(name: string, contentType = ""): boolean {+ return MARKDOWN_EXTENSIONS.has(extensionOf(name)) || MARKDOWN_TYPES.has(mimeOf(contentType));+}++export const MAX_DOCUMENT_PREVIEW_BYTES = 50 * 1024 * 1024;diff --git a/studio/frontend/src/components/file-viewer/office-view.tsx b/studio/frontend/src/components/file-viewer/office-view.tsxnew file mode 100644index 00000000000..b04cc69b89a--- /dev/null+++ b/studio/frontend/src/components/file-viewer/office-view.tsx@@ -0,0 +1,542 @@+// 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 { Spinner } from "@/components/ui/spinner";+import { repackDocxPreviewArchive } from "@/features/chat";+import { useT } from "@/i18n";+import { openLink } from "@/lib/open-link";+import { useUiSpaceScale } from "@/hooks/use-ui-space-scale";+import { cn } from "@/lib/utils";+import { useVirtualizer } from "@tanstack/react-virtual";+import { type CSSProperties, type MouseEvent, memo, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { type DocumentKind, sheetDelimiter } from "./kind";+import { useWidth } from "./use-width";+import {+ type Deck,+ type Sheet,+ type SheetCell,+ type Slide,+ type SlideBox,+ columnName,+ picturePixels,+ readDelimited,+ readPptx,+ readXlsx,+} from "./office";++type Parsed =+ | { kind: "docx"; html: string; truncated: boolean }+ | { kind: "sheet"; sheets: Sheet[] }+ | { kind: "slides"; deck: Deck };++async function parse(file: Blob, kind: DocumentKind, name: string, contentType: string): Promise<Parsed> {+ const bytes = new Uint8Array(await file.arrayBuffer());+ if (kind === "docx") {+ const { default: mammoth } = await import("mammoth");+ const repacked = repackDocxPreviewArchive(name, bytes, MAX_DOCX_PARAGRAPHS);+ let dropped = false;+ let pixelsLeft = MAX_DOCX_PIXELS;+ const convertImage = mammoth.images.imgElement(async (image) => {+ const pixels = picturePixels(new Uint8Array(await image.readAsArrayBuffer()));+ if (pixels !== undefined && pixels <= pixelsLeft) {+ pixelsLeft -= pixels;+ return { src: `data:${image.contentType};base64,${await image.readAsBase64String()}` };+ }+ dropped = true;+ return { src: "" };+ });+ const { value } = await mammoth.convertToHtml({ arrayBuffer: repacked.archive.buffer as ArrayBuffer }, { convertImage, idPrefix: "docx-" });+ const { html, truncated } = sanitizeDocxHtml(value);+ return { kind, html, truncated: truncated || repacked.truncated || dropped };+ }+ if (kind === "slides") return { kind, deck: readPptx(bytes) };+ const delimiter = sheetDelimiter(name, contentType);+ if (delimiter) {+ const encoding =+ bytes[0] === 0xff && bytes[1] === 0xfe+ ? "utf-16le"+ : bytes[0] === 0xfe && bytes[1] === 0xff+ ? "utf-16be"+ : "utf-8";+ const text = new TextDecoder(encoding).decode(bytes);+ return { kind: "sheet", sheets: [readDelimited(text, delimiter, name)] };+ }+ return { kind: "sheet", sheets: readXlsx(bytes) };+}++const DOCX_TAGS = new Set(+ "p h1 h2 h3 h4 h5 h6 strong b em i u s sup sub a img br ul ol li table thead tbody tr td th blockquote pre code span div hr".split(" "),+);+const DOCX_ATTRIBUTES = new Set(["href", "src", "alt", "id", "colspan", "rowspan"]);++const MAX_DOCX_PARAGRAPHS = 20_000;+const MAX_DOCX_ELEMENTS = 50_000;+const MAX_DOCX_PIXELS = 128 * 1024 * 1024;++function sanitizeDocxHtml(html: string): { html: string; truncated: boolean } {+ // Cut before parsing: mammoth escapes each < in text, so every one left is a tag.+ const opening = /<[a-z]/gi;+ let cut = -1;+ for (let count = 0; opening.exec(html); count++) {+ if (count === MAX_DOCX_ELEMENTS) {+ cut = opening.lastIndex - 2;+ break;+ }+ }+ const kept = cut === -1 ? html : html.slice(0, cut);+ const doc = new DOMParser().parseFromString(`<body>${kept}</body>`, "text/html");+ for (const element of Array.from(doc.body.querySelectorAll("*"))) {+ if (!DOCX_TAGS.has(element.localName)) {+ element.replaceWith(...Array.from(element.childNodes));+ continue;+ }+ for (const attr of Array.from(element.attributes)) {+ const value = attr.value.trim().toLowerCase();+ const unsafe =+ !DOCX_ATTRIBUTES.has(attr.name) ||+ (attr.name === "href" && !/^(https?:|mailto:|#)/.test(value)) ||+ (attr.name === "src" && !value.startsWith("data:image/"));+ if (unsafe) element.removeAttribute(attr.name);+ }+ }+ return { html: doc.body.innerHTML, truncated: cut !== -1 };+}++const DOCX_PAGE_WIDTH = 816;++function DocxView({ html, truncated, scale }: { html: string; truncated: boolean; scale: number }) {+ const t = useT();+ const [container, setContainer] = useState<HTMLDivElement | null>(null);+ const pageWidth = Math.max(+ 200,+ Math.min(useWidth(container), DOCX_PAGE_WIDTH * useUiSpaceScale()),+ );+ const onClick = (event: MouseEvent<HTMLDivElement>) => {+ const link = (event.target as Element).closest("a");+ const href = link?.getAttribute("href");+ if (!href) return;+ event.preventDefault();+ if (href.startsWith("#")) {+ event.currentTarget.querySelector(`[id="${CSS.escape(href.slice(1))}"]`)?.scrollIntoView();+ } else {+ openLink(href);+ }+ };+ return (+ <div ref={setContainer} className="size-full overflow-auto bg-muted/60 py-6">+ <article+ onClick={onClick}+ style={{ zoom: scale, width: pageWidth }}+ className="mx-auto min-h-full select-text bg-white px-[clamp(24px,8%,80px)] py-16 text-ui-15 leading-relaxed text-neutral-900 shadow-sm ring-1 ring-black/5 [&_a]:text-blue-700 [&_a]:underline [&_h1]:mb-3 [&_h1]:text-2xl [&_h1]:font-semibold [&_h2]:mt-5 [&_h2]:mb-2 [&_h2]:text-xl [&_h2]:font-semibold [&_h3]:mt-4 [&_h3]:mb-2 [&_h3]:text-lg [&_h3]:font-semibold [&_img]:inline-block [&_img]:max-w-full [&_li]:my-1 [&_ol]:mb-3 [&_ol]:list-decimal [&_ol]:pl-7 [&_p]:mb-2.5 [&_table]:my-3 [&_table]:border-collapse [&_td]:border [&_td]:border-neutral-300 [&_td]:px-2 [&_td]:py-1 [&_td]:align-top [&_th]:border [&_th]:border-neutral-300 [&_th]:px-2 [&_th]:py-1 [&_ul]:mb-3 [&_ul]:list-disc [&_ul]:pl-7"+ dangerouslySetInnerHTML={{ __html: html }}+ />+ {truncated && (+ <p className="mt-4 text-center text-ui-12 text-muted-foreground">{t("library.preview.documentTruncated")}</p>+ )}+ </div>+ );+}++const ROW_HEIGHT = 28;+const DEFAULT_COLUMN_WIDTH = 100;+const ROW_HEADER_WIDTH = 48;++const CELL = "h-7 border-r border-b border-border px-2 whitespace-nowrap overflow-hidden text-ellipsis";+const HEADER = `${CELL} sticky bg-muted font-normal text-muted-foreground text-center`;++const SheetRow = memo(function SheetRow({+ r,+ row,+ columns,+ start,+ end,+ left,+ right,+}: {+ r: number;+ row: (SheetCell | undefined)[] | undefined;+ columns: number[];+ start: number;+ end: number;+ left: boolean;+ right: boolean;+}) {+ const cells = [];+ for (let i = start; i < end; i++) {+ const index = columns[i]!;+ const value = row?.[index];+ let className = CELL;+ if (value?.numeric) className += " text-right";+ if (value?.bold) className += " font-semibold";+ if (value?.italic) className += " italic";+ cells.push(+ <td key={index} title={value && value.text.length > 12 ? value.text : undefined} className={className}>+ {value?.text}+ </td>,+ );+ }+ return (+ <tr>+ <th className={`${HEADER} left-0 z-10`}>{r + 1}</th>+ {left && <td className="p-0" />}+ {cells}+ {right && <td className="p-0" />}+ </tr>+ );+});++function SheetGrid({+ sheet,+ scale,+ uiScale,+}: {+ sheet: Sheet;+ scale: number;+ uiScale: number;+}) {+ const scrollRef = useRef<HTMLDivElement>(null);+ const rowHeight = ROW_HEIGHT * uiScale * scale;+ const headerWidth = ROW_HEADER_WIDTH * uiScale;+ const { visibleColumns, visibleRows, widths, rowCount } = useMemo(() => {+ const columns = Math.max(+ 1,+ sheet.rows.reduce((max, row) => Math.max(max, row?.length ?? 0), sheet.widths.length),+ );+ const rowCount = Math.max(sheet.rows.length, 1);+ const visibleColumns = Array.from({ length: columns }, (_, index) => index).filter(+ (index) => !sheet.hidden?.columns.has(index),+ );+ const visibleRows = sheet.hidden?.rows.size+ ? Array.from({ length: rowCount }, (_, index) => index).filter((index) => !sheet.hidden!.rows.has(index))+ : null;+ const widths = visibleColumns.map((index) => (sheet.widths[index] ?? DEFAULT_COLUMN_WIDTH) * uiScale);+ return { visibleColumns, visibleRows, widths, rowCount };+ }, [sheet, uiScale]);+ const tableWidth = useMemo(() => widths.reduce((sum, width) => sum + width, headerWidth), [widths, headerWidth]);+ // eslint-disable-next-line react-hooks/incompatible-library+ const virtualizer = useVirtualizer({+ count: visibleRows?.length ?? rowCount,+ getScrollElement: () => scrollRef.current,+ estimateSize: () => rowHeight,+ paddingStart: rowHeight,+ overscan: 6,+ });+ const columnVirtualizer = useVirtualizer({+ horizontal: true,+ count: visibleColumns.length,+ getScrollElement: () => scrollRef.current,+ estimateSize: (index) => widths[index]! * scale,+ paddingStart: headerWidth * scale,+ overscan: 4,+ });+ const items = virtualizer.getVirtualItems();+ const before = ((items[0]?.start ?? 0) - rowHeight) / scale;+ const after = (virtualizer.getTotalSize() - (items.at(-1)?.end ?? 0)) / scale;+ const columnItems = columnVirtualizer.getVirtualItems();+ const left = ((columnItems[0]?.start ?? headerWidth * scale) - headerWidth * scale) / scale;+ const right = (columnVirtualizer.getTotalSize() - (columnItems.at(-1)?.end ?? headerWidth * scale)) / scale;+ const start = columnItems[0]?.index ?? 0;+ const end = (columnItems.at(-1)?.index ?? -1) + 1;+ return (+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-auto">+ <table+ className="border-separate border-spacing-0 text-ui-13 tabular-nums"+ style={{ zoom: scale, tableLayout: "fixed", width: tableWidth } as CSSProperties}+ >+ <colgroup>+ <col style={{ width: headerWidth }} />+ {left > 0 && <col style={{ width: left }} />}+ {columnItems.map((item) => (+ <col key={item.index} style={{ width: widths[item.index] }} />+ ))}+ {right > 0 && <col style={{ width: right }} />}+ </colgroup>+ <thead>+ <tr>+ <th className={`${HEADER} top-0 left-0 z-20`} />+ {left > 0 && <th className="p-0" />}+ {columnItems.map((item) => {+ const index = visibleColumns[item.index]!;+ return (+ <th key={index} className={`${HEADER} top-0 z-10`}>+ {columnName(index)}+ </th>+ );+ })}+ {right > 0 && <th className="p-0" />}+ </tr>+ </thead>+ <tbody>+ {before > 0 && <tr style={{ height: before }} />}+ {items.map((item) => {+ const r = visibleRows?.[item.index] ?? item.index;+ return (+ <SheetRow+ key={r}+ r={r}+ row={sheet.rows[r]}+ columns={visibleColumns}+ start={start}+ end={end}+ left={left > 0}+ right={right > 0}+ />+ );+ })}+ {after > 0 && <tr style={{ height: after }} />}+ </tbody>+ </table>+ </div>+ );+}++function SheetView({ sheets, tabs, scale }: { sheets: Sheet[]; tabs: boolean; scale: number }) {+ const t = useT();+ const uiScale = useUiSpaceScale();+ const [active, setActive] = useState(0);+ const sheet = sheets[active] ?? sheets[0];+ if (!sheet) return <p className="m-auto text-sm text-muted-foreground">{t("library.preview.emptyDocument")}</p>;+ return (+ <div className="flex size-full min-h-0 flex-col overflow-hidden border-t border-border">+ <SheetGrid key={`${active}:${scale}:${uiScale}`} sheet={sheet} scale={scale} uiScale={uiScale} />+ {(tabs || sheet.truncated) && (+ <div className="flex shrink-0 items-center gap-1 overflow-x-auto border-t border-border px-2 py-1.5">+ {tabs &&+ sheets.map((item, index) => (+ <button+ key={index}+ type="button"+ onClick={() => setActive(index)}+ className={cn(+ "shrink-0 rounded-md px-3 py-1 text-ui-13 transition-colors hover:bg-muted",+ index === active ? "bg-muted font-medium text-foreground" : "text-muted-foreground",+ )}+ >+ {item.name}+ </button>+ ))}+ {sheet.truncated && (+ <span className="ml-auto shrink-0 px-2 text-ui-12 text-muted-foreground">+ {t("library.preview.sheetTruncated")}+ </span>+ )}+ </div>+ )}+ </div>+ );+}++const TITLE_FRAME = { x: 0.06, y: 0.05, w: 0.88, h: 0.18 };+const BODY_FRAME = { x: 0.06, y: 0.26, w: 0.88, h: 0.68 };+const CENTER_TITLE_FRAME = { x: 0.1, y: 0.26, w: 0.8, h: 0.24 };+const SUBTITLE_FRAME = { x: 0.15, y: 0.53, w: 0.7, h: 0.2 };+const TITLES = new Set(["title", "ctrTitle"]);++function frameStyle(frame: NonNullable<SlideBox["frame"]>, mirror = false): CSSProperties {+ const turn = (frame.rot ?? 0) + (!mirror && frame.flipV ? 180 : 0);+ const flip = mirror && (frame.flipH || frame.flipV) ? `scale(${frame.flipH ? -1 : 1}, ${frame.flipV ? -1 : 1})` : "";+ return {+ left: `${frame.x * 100}%`,+ top: `${frame.y * 100}%`,+ width: `${frame.w * 100}%`,+ height: `${frame.h * 100}%`,+ transform: [turn ? `rotate(${turn}deg)` : "", flip].filter(Boolean).join(" ") || undefined,+ };+}++function SlideText({ box, widthPt }: { box: SlideBox; widthPt: number }) {+ const title = TITLES.has(box.placeholder ?? "");+ return (+ <>+ {box.paragraphs?.map((p, index) => (+ <p+ key={index}+ className={cn("leading-tight whitespace-pre-line", (title || p.bold) && "font-semibold", p.bullet && "pl-[1.1em] -indent-[1.1em]")}+ style={{+ fontSize: `${((p.size ?? (title ? 36 : 18)) / widthPt) * 100}cqw`,+ textAlign: p.align === "ctr" ? "center" : p.align === "r" ? "right" : undefined,+ marginBottom: "0.3em",+ }}+ >+ {p.bullet && "• "}+ {p.text}+ </p>+ ))}+ </>+ );+}++function SlideTable({ rows, caption, widthPt }: { rows: string[][]; caption?: string; widthPt: number }) {+ return (+ <table className="size-full table-fixed border-collapse" style={{ fontSize: `${(14 / widthPt) * 100}cqw` }}>+ {caption && <caption className="pb-[0.4em] text-left font-semibold">{caption}</caption>}+ <tbody>+ {rows.map((row, r) => (+ <tr key={r} className={cn(r === 0 && "font-semibold")}>+ {row.map((cell, c) => (+ <td key={c} className="border border-neutral-300 px-[0.4em] py-[0.2em] align-top whitespace-pre-wrap">+ {cell}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ );+}++function SlideImage({ image, crop }: { image: Blob; crop?: SlideBox["crop"] }) {+ const attach = useCallback(+ (element: HTMLImageElement | null) => {+ if (!element) return;+ const url = URL.createObjectURL(image);+ element.src = url;+ return () => URL.revokeObjectURL(url);+ },+ [image],+ );+ const w = crop ? 1 - crop.l - crop.r : 1;+ const h = crop ? 1 - crop.t - crop.b : 1;+ return (+ <img+ ref={attach}+ alt=""+ decoding="async"+ className="absolute max-w-none"+ style={{+ left: `${(-(crop?.l ?? 0) / w) * 100}%`,+ top: `${(-(crop?.t ?? 0) / h) * 100}%`,+ width: `${100 / w}%`,+ height: `${100 / h}%`,+ }}+ />+ );+}++const SlideFace = memo(function SlideFace({ slide, index, deck }: { slide: Slide; index: number; deck: Deck }) {+ const flow = slide.boxes.filter((box) => !box.frame && box.paragraphs);+ const titles = flow.filter((box) => TITLES.has(box.placeholder ?? ""));+ const body = flow.filter((box) => !TITLES.has(box.placeholder ?? ""));+ const titleSlide = titles.some((box) => box.placeholder === "ctrTitle");+ return (+ <div className="flex flex-col gap-1.5">+ <div+ className="relative w-full overflow-hidden bg-white text-neutral-900 shadow-sm ring-1 ring-black/5 select-text"+ style={{ aspectRatio: `1 / ${deck.aspect}`, containerType: "inline-size" }}+ >+ {slide.boxes.map((box, boxIndex) =>+ box.frame ? (+ <div key={boxIndex} className="absolute overflow-hidden" style={frameStyle(box.frame, Boolean(box.image))}>+ {box.image ? (+ <SlideImage image={box.image} crop={box.crop} />+ ) : box.table ? (+ <SlideTable rows={box.table} caption={box.caption} widthPt={deck.widthPt} />+ ) : (+ <SlideText box={box} widthPt={deck.widthPt} />+ )}+ </div>+ ) : null,+ )}+ {titles.length > 0 && (+ <div+ className={cn("absolute flex flex-col justify-end overflow-hidden", titleSlide && "text-center")}+ style={frameStyle(titleSlide ? CENTER_TITLE_FRAME : TITLE_FRAME)}+ >+ {titles.map((box, i) => <SlideText key={i} box={box} widthPt={deck.widthPt} />)}+ </div>+ )}+ {body.length > 0 && (+ <div+ className={cn("absolute overflow-hidden", titleSlide && "text-center")}+ style={frameStyle(titleSlide ? SUBTITLE_FRAME : BODY_FRAME)}+ >+ {body.map((box, i) => <SlideText key={i} box={box} widthPt={deck.widthPt} />)}+ </div>+ )}+ </div>+ <span className="text-center text-ui-12 text-muted-foreground tabular-nums">{index + 1}</span>+ </div>+ );+});++const SLIDE_GAP = 24;+const SLIDE_LABEL = 26;++function SlidesView({ deck, scale }: { deck: Deck; scale: number }) {+ const t = useT();+ const [container, setContainer] = useState<HTMLDivElement | null>(null);+ const width = Math.max(200, useWidth(container)) * scale;+ if (!deck.slides.length) {+ return <p className="m-auto text-sm text-muted-foreground">{t("library.preview.emptyDocument")}</p>;+ }+ return (+ <div ref={setContainer} className="size-full overflow-auto bg-muted/60">+ <SlideList key={width} deck={deck} width={width} scrollElement={container} />+ {deck.truncated && (+ <p className="pb-6 text-center text-ui-12 text-muted-foreground">{t("library.preview.documentTruncated")}</p>+ )}+ </div>+ );+}++function SlideList({ deck, width, scrollElement }: { deck: Deck; width: number; scrollElement: HTMLElement | null }) {+ // eslint-disable-next-line react-hooks/incompatible-library+ const virtualizer = useVirtualizer({+ count: deck.slides.length,+ getScrollElement: () => scrollElement,+ estimateSize: () => width * deck.aspect + SLIDE_LABEL + SLIDE_GAP,+ paddingStart: SLIDE_GAP,+ overscan: 2,+ });+ return (+ <div className="relative mx-auto" style={{ width, height: virtualizer.getTotalSize() }}>+ {virtualizer.getVirtualItems().map((item) => (+ <div+ key={item.key}+ data-index={item.index}+ ref={virtualizer.measureElement}+ className="absolute top-0 left-0 w-full"+ style={{ transform: `translateY(${item.start}px)`, paddingBottom: SLIDE_GAP }}+ >+ <SlideFace slide={deck.slides[item.index]!} index={item.index} deck={deck} />+ </div>+ ))}+ </div>+ );+}++export default function OfficeView({+ file,+ kind,+ name,+ contentType,+ scale,+}: {+ file: Blob;+ kind: DocumentKind;+ name: string;+ contentType: string;+ scale: number;+}) {+ const t = useT();+ const [state, setState] = useState<{ file: Blob; parsed?: Parsed; error?: boolean } | null>(null);+ useEffect(() => {+ let cancelled = false;+ parse(file, kind, name, contentType).then(+ (parsed) => !cancelled && setState({ file, parsed }),+ () => !cancelled && setState({ file, error: true }),+ );+ return () => {+ cancelled = true;+ };+ }, [file, kind, name, contentType]);+ const current = state?.file === file ? state : null;+ if (current?.error) {+ return <p className="m-auto text-sm text-muted-foreground">{t("library.preview.cannotPreview")}</p>;+ }+ const parsed = current?.parsed;+ if (!parsed) return <Spinner className="m-auto size-6" />;+ if (parsed.kind === "docx") return <DocxView html={parsed.html} truncated={parsed.truncated} scale={scale} />;+ if (parsed.kind === "slides") return <SlidesView deck={parsed.deck} scale={scale} />;+ return <SheetView sheets={parsed.sheets} tabs={!sheetDelimiter(name, contentType)} scale={scale} />;+}diff --git a/studio/frontend/src/components/file-viewer/office.ts b/studio/frontend/src/components/file-viewer/office.tsnew file mode 100644index 00000000000..65acd0670de--- /dev/null+++ b/studio/frontend/src/components/file-viewer/office.ts@@ -0,0 +1,1662 @@+// 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 { Inflate, type Unzipped, inflateSync, strFromU8, unzipSync } from "fflate";+++const MAX_UNPACKED_BYTES = 200 * 1024 * 1024;+const MAX_XML_PART_BYTES = 10 * 1024 * 1024;+const MAX_ZIP_ENTRIES = 100_000;+export const MAX_SHEET_ROWS = 5000;+export const MAX_SHEET_COLUMNS = 200;+const MAX_WORKBOOK_CELLS = MAX_SHEET_ROWS * (MAX_SHEET_COLUMNS + 1);+const MAX_SHEETS = 100;++export interface SheetCell {+ text: string;+ numeric?: boolean;+ bold?: boolean;+ italic?: boolean;+}++export interface Sheet {+ name: string;+ rows: (SheetCell | undefined)[][];+ widths: (number | undefined)[];+ truncated: boolean;+ hidden?: { rows: Set<number>; columns: Set<number> };+}++interface ZipEntry {+ offset: number;+ size: number;+ originalSize: number;+ method: number;+}++function zipIndex(bytes: Uint8Array, view: DataView): Map<string, ZipEntry> | null {+ let end = bytes.length - 22;+ const stop = Math.max(0, end - 0xffff);+ while (end >= stop && view.getUint32(end, true) !== 0x06054b50) end--;+ if (end < stop) return null;+ let count = view.getUint16(end + 10, true);+ let at = view.getUint32(end + 16, true);+ const u64 = (offset: number) => (offset + 8 <= bytes.length ? Number(view.getBigUint64(offset, true)) : Number.NaN);+ if (count === 0xffff || at === 0xffffffff) {+ // ZIP64: the real count and directory offset are in the record its locator points at.+ const locator = end - 20;+ if (locator < 0 || view.getUint32(locator, true) !== 0x07064b50) return null;+ const record = u64(locator + 8);+ if (!(record + 56 <= bytes.length) || view.getUint32(record, true) !== 0x06064b50) return null;+ count = u64(record + 32);+ at = u64(record + 48);+ if (!Number.isSafeInteger(count) || !Number.isSafeInteger(at)) return null;+ }+ if (count > MAX_ZIP_ENTRIES) throw new Error("File is too large to preview.");+ const utf8 = new TextDecoder();+ const index = new Map<string, ZipEntry>();+ for (let i = 0; i < count; i++) {+ if (at + 46 > bytes.length || view.getUint32(at, true) !== 0x02014b50) return null;+ let size = view.getUint32(at + 20, true);+ let originalSize = view.getUint32(at + 24, true);+ let offset = view.getUint32(at + 42, true);+ const nameEnd = at + 46 + view.getUint16(at + 28, true);+ const extraEnd = nameEnd + view.getUint16(at + 30, true);+ if (size === 0xffffffff || originalSize === 0xffffffff || offset === 0xffffffff) {+ // The ZIP64 extra field (0x0001) holds, in order, the 64-bit values that did not fit.+ let field = -1;+ for (let extra = nameEnd; extra + 4 <= extraEnd; extra += 4 + view.getUint16(extra + 2, true)) {+ if (view.getUint16(extra, true) === 1) {+ field = extra + 4;+ break;+ }+ }+ if (field === -1) return null;+ const next = () => {+ const value = field + 8 <= extraEnd ? u64(field) : Number.NaN;+ field += 8;+ return value;+ };+ if (originalSize === 0xffffffff) originalSize = next();+ if (size === 0xffffffff) size = next();+ if (offset === 0xffffffff) offset = next();+ if (![size, originalSize, offset].every(Number.isSafeInteger)) return null;+ }+ const raw = bytes.subarray(at + 46, nameEnd);+ // Bit 11 marks a UTF-8 name; otherwise one byte a character, as unzipSync reads it.+ const name = view.getUint16(at + 8, true) & 0x800 ? utf8.decode(raw) : String.fromCharCode(...raw);+ index.set(name, { offset, size, originalSize, method: view.getUint16(at + 10, true) });+ at = extraEnd + view.getUint16(at + 32, true);+ }+ return index;+}++function inflateEntry(bytes: Uint8Array, view: DataView, entry: ZipEntry): Uint8Array<ArrayBuffer> {+ const at = entry.offset;+ if (view.getUint32(at, true) !== 0x04034b50) throw new Error("Not a valid ZIP archive.");+ const start = at + 30 + view.getUint16(at + 26, true) + view.getUint16(at + 28, true);+ const data = bytes.subarray(start, start + entry.size);+ if (entry.method === 0) return data.slice();+ if (entry.method === 8) return inflateSync(data, { out: new Uint8Array(entry.originalSize) });+ throw new Error(`Unsupported ZIP compression method ${entry.method}.`);+}++type Reader = ((names: Iterable<string>, limit?: number) => Unzipped) & {+ size: (name: string) => number | undefined;+ head: (name: string, max: number) => Uint8Array | undefined;+ open: (name: string, max: number) => Growing | undefined;+};++function archive(bytes: Uint8Array): Reader {+ let total = 0;+ const charge = (size: number) => {+ total += size;+ if (total > MAX_UNPACKED_BYTES) throw new Error("File is too large to preview.");+ };+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const index = zipIndex(bytes, view);+ if (!index) {+ const read = (names: Iterable<string>, limit = Infinity) => {+ const wanted = new Set(names);+ return unzipSync(bytes, {+ filter: (entry) => wanted.has(entry.name) && entry.originalSize <= limit && (charge(entry.originalSize), true),+ });+ };+ let sizes: Map<string, number> | undefined;+ const size = (name: string) => {+ if (!sizes) {+ const found = new Map<string, number>();+ unzipSync(bytes, { filter: (entry) => (found.set(entry.name, entry.originalSize), false) });+ sizes = found;+ }+ return sizes.get(name);+ };+ const head = (name: string, max: number) => {+ if ((size(name) ?? 0) > max) throw new Error("File is too large to preview.");+ return read([name])[name];+ };+ const open = (name: string, max: number): Growing | undefined => {+ const data = head(name, max);+ return data && { data, done: true, grow() {} };+ };+ return Object.assign(read, { size, head, open });+ }+ const read = (names: Iterable<string>, limit = Infinity) => {+ const files: Unzipped = {};+ for (const name of new Set(names)) {+ const entry = index.get(name);+ if (!entry || entry.originalSize > limit) continue;+ charge(entry.originalSize);+ files[name] = inflateEntry(bytes, view, entry);+ }+ return files;+ };+ const open = (name: string, max: number) => {+ const entry = index.get(name);+ return entry && growing(bytes, view, entry, max, charge);+ };+ const head = (name: string, max: number) => {+ const entry = index.get(name);+ if (!entry || entry.originalSize <= max) return read([name])[name];+ const part = growing(bytes, view, entry, max, charge);+ while (!part.done) part.grow();+ return part.data;+ };+ return Object.assign(read, { size: (name: string) => index.get(name)?.originalSize, head, open });+}++export interface Growing {+ data: Uint8Array;+ done: boolean;+ cut?: boolean;+ grow(): void;+}++function growing(bytes: Uint8Array, view: DataView, entry: ZipEntry, max: number, charge: (size: number) => void): Growing {+ const at = entry.offset;+ if (view.getUint32(at, true) !== 0x04034b50) throw new Error("Not a valid ZIP archive.");+ const start = at + 30 + view.getUint16(at + 26, true) + view.getUint16(at + 28, true);+ const data = bytes.subarray(start, start + entry.size);+ if (entry.method === 0) {+ const whole = data.slice(0, max);+ charge(whole.length);+ return { data: whole, done: true, cut: data.length > max, grow() {} };+ }+ if (entry.method !== 8) throw new Error(`Unsupported ZIP compression method ${entry.method}.`);+ let buffer = new Uint8Array(Math.min(max, 1 << 20));+ let length = 0;+ let from = 0;+ const inflater = new Inflate((chunk) => {+ const room = Math.min(chunk.length, max - length);+ if (room < chunk.length) part.cut = true;+ if (length + room > buffer.length) {+ const next = new Uint8Array(Math.min(max, Math.max(buffer.length * 2, length + room)));+ next.set(buffer.subarray(0, length));+ buffer = next;+ }+ buffer.set(chunk.subarray(0, room), length);+ length += room;+ });+ const part: Growing = {+ data: buffer.subarray(0, 0),+ done: false,+ grow() {+ const before = length;+ while (!part.done && length < before + (1 << 20)) {+ inflater.push(data.subarray(from, from + 16384), from + 16384 >= data.length);+ from += 16384;+ if (from >= data.length || length >= max) part.done = true;+ }+ charge(length - before);+ part.data = buffer.subarray(0, length);+ },+ };+ return part;+}++function xml(files: Unzipped, path: string): Document | null {+ const bytes = files[path];+ return bytes ? parseXml(strFromU8(bytes)) : null;+}++function parseXml(text: string): Document | null {+ const doc = new DOMParser().parseFromString(text, "application/xml");+ return doc.getElementsByTagName("parsererror").length ? null : doc;+}++function all(node: Document | Element, name: string): Element[] {+ return Array.from(node.getElementsByTagNameNS("*", name));+}++function first(node: Document | Element, name: string): Element | undefined {+ return node.getElementsByTagNameNS("*", name)[0];+}++function children(node: Element, name: string): Element[] {+ return Array.from(node.children).filter((child) => child.localName === name);+}++function relationshipList(files: Unzipped, part: string): { id: string; type: string; path: string }[] {+ const slash = part.lastIndexOf("/");+ const dir = part.slice(0, slash + 1);+ const doc = xml(files, relsPath(part));+ const out: { id: string; type: string; path: string }[] = [];+ for (const rel of doc ? all(doc, "Relationship") : []) {+ const id = rel.getAttribute("Id");+ if (!id || rel.getAttribute("TargetMode") === "External") continue;+ out.push({ id, type: rel.getAttribute("Type") ?? "", path: resolvePath(dir, rel.getAttribute("Target") ?? "") });+ }+ return out;+}++function relationships(files: Unzipped, part: string): Map<string, string> {+ return new Map(relationshipList(files, part).map((rel) => [rel.id, rel.path]));+}++function mainPart(read: Reader, fallback: string): string {+ const root = read(["_rels/.rels"], MAX_XML_PART_BYTES);+ const path = relationshipList(root, "").find((rel) => rel.type.endsWith("/officeDocument"))?.path;+ return path && read.size(path) !== undefined ? path : fallback;+}++function relsPath(part: string): string {+ const slash = part.lastIndexOf("/");+ return `${part.slice(0, slash + 1)}_rels/${part.slice(slash + 1)}.rels`;+}++function resolvePath(dir: string, target: string): string {+ const parts = (target.startsWith("/") ? target.slice(1) : dir + target).split("/");+ const out: string[] = [];+ for (const part of parts) {+ if (part === "..") out.pop();+ else if (part !== "." && part !== "") out.push(part);+ }+ return out.join("/");+}++function relId(node: Element, name: string): string | null {+ for (const attr of Array.from(node.attributes)) {+ if (attr.localName === name && attr.namespaceURI?.endsWith("/relationships")) return attr.value;+ }+ return null;+}+++const BUILTIN_FORMATS: Record<number, string> = {+ 5: '"$"#,##0_);("$"#,##0)',+ 6: '"$"#,##0_);[Red]("$"#,##0)',+ 7: '"$"#,##0.00_);("$"#,##0.00)',+ 8: '"$"#,##0.00_);[Red]("$"#,##0.00)',+ 1: "0",+ 2: "0.00",+ 3: "#,##0",+ 4: "#,##0.00",+ 9: "0%",+ 10: "0.00%",+ 11: "0.00E+00",+ 12: "# ?/?",+ 13: "# ??/??",+ 14: "m/d/yyyy",+ 15: "d-mmm-yy",+ 16: "d-mmm",+ 17: "mmm-yy",+ 18: "h:mm AM/PM",+ 19: "h:mm:ss AM/PM",+ 20: "h:mm",+ 21: "h:mm:ss",+ 22: "m/d/yyyy h:mm",+ 37: "#,##0 ;(#,##0)",+ 38: "#,##0 ;[Red](#,##0)",+ 39: "#,##0.00;(#,##0.00)",+ 40: "#,##0.00;[Red](#,##0.00)",+ 41: '_(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)',+ 42: '_("$"* #,##0_);_("$"* (#,##0);_("$"* "-"_);_(@_)',+ 43: '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)',+ 44: '_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)',+ 45: "mm:ss",+ 46: "[h]:mm:ss",+ 47: "mm:ss.0",+ 48: "##0.0E+0",+ 49: "@",+};++const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];+const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];+const DATE_TOKEN = /"[^"]*"|\\.|y+|m+|d+|h+|s+|am\/pm|a\/p|\.0+|./gi;++function memo<T>(compute: (code: string) => T): (code: string) => T {+ const cache = new Map<string, T>();+ return (code) => {+ let value = cache.get(code);+ if (value === undefined) {+ if (cache.size >= 8192) cache.clear();+ value = compute(code);+ cache.set(code, value);+ }+ return value;+ };+}++const dateTokens = memo((code) => {+ const tokens = code.match(DATE_TOKEN) ?? [];+ return {+ tokens,+ kinds: tokens.map((token) => (/^[ymdhs]/i.test(token) && !token.startsWith("\\") ? token[0]!.toLowerCase() : "")),+ twelve: tokens.some((token) => /^(am\/pm|a\/p)$/i.test(token)),+ fraction: /s\.(0+)/i.exec(code)?.[1]?.length ?? 0,+ };+});++/** `m` is minutes after an hour or before a second, otherwise the month. */+function formatDate(serial: number, code: string): string | null {+ const { tokens, kinds, twelve, fraction } = dateTokens(code);+ const unit = 1000 / 10 ** fraction;+ // The 1900 system counts a 29 February 1900 that never was (serial 60), so earlier serials run a day ahead.+ const whole = Math.floor(serial);+ const shifted = serial < 60 ? serial + 1 : serial;+ const date = new Date(Math.round(((shifted - 25569) * 86400000) / unit) * unit);+ if (!Number.isFinite(date.getTime())) return null;+ const pad = (n: number, width = 2) => String(n).padStart(width, "0");+ const hours = date.getUTCHours();+ return tokens+ .map((token, index) => {+ const n = token.length;+ switch (kinds[index]) {+ case "y":+ return n <= 2 ? pad(date.getUTCFullYear() % 100) : String(date.getUTCFullYear());+ case "d": {+ const weekday = DAYS[(((whole + 6) % 7) + 7) % 7]!;+ const day = whole === 60 ? 29 : date.getUTCDate();+ if (n >= 4) return weekday;+ if (n === 3) return weekday.slice(0, 3);+ return n === 2 ? pad(day) : String(day);+ }+ case "h": {+ const h = twelve ? hours % 12 || 12 : hours;+ return n >= 2 ? pad(h) : String(h);+ }+ case "s":+ return n >= 2 ? pad(date.getUTCSeconds()) : String(date.getUTCSeconds());+ case "m": {+ const previous = kinds.slice(0, index).reverse().find(Boolean);+ const next = kinds.slice(index + 1).find(Boolean);+ if (n <= 2 && (previous === "h" || next === "s")) {+ return n === 2 ? pad(date.getUTCMinutes()) : String(date.getUTCMinutes());+ }+ const month = date.getUTCMonth();+ if (n >= 5) return MONTHS[month]![0]!;+ if (n === 4) return MONTHS[month]!;+ if (n === 3) return MONTHS[month]!.slice(0, 3);+ return n === 2 ? pad(month + 1) : String(month + 1);+ }+ }+ if (/^am\/pm$/i.test(token)) return hours < 12 ? "AM" : "PM";+ if (/^a\/p$/i.test(token)) return hours < 12 ? "A" : "P";+ if (/^\.0+$/.test(token)) return `.${pad(date.getUTCMilliseconds(), 3).slice(0, n - 1)}`;+ if (token.startsWith('"')) return token.slice(1, -1);+ return token.startsWith("\\") ? token.slice(1) : token;+ })+ .join("");+}++const fractionShape = memo((format) =>+ /(?:([0#?]+)\s+)?[0#?]+\s*\/\s*([1-9]\d*|[0#?]+)/.exec(format.replace(/"[^"]*"|\\./g, (text) => "\u0001".repeat(text.length))),+);++const unquote = (format: string) => format.replace(/"([^"]*)"/g, "$1").replace(/\\(.)/g, "$1");++function closestFraction(x: number, maxDen: number): [number, number] {+ let [p0, q0, p1, q1] = [0, 1, 1, 0];+ let v = x;+ for (let i = 0; i < 64; i++) {+ const a = Math.floor(v);+ const q2 = q0 + a * q1;+ if (q2 > maxDen) break;+ [p0, q0, p1, q1] = [p1, q1, p0 + a * p1, q2];+ if (v - a < 1e-12) break;+ v = 1 / (v - a);+ }+ const k = Math.floor((maxDen - q0) / q1);+ const [ps, qs] = [p0 + k * p1, q0 + k * q1];+ return Math.abs(x - ps / qs) < Math.abs(x - p1 / q1) - 1e-12 ? [ps, qs] : [p1, q1];+}++function formatFraction(value: number, format: string): string | null {+ const match = fractionShape(format);+ if (!match) return null;+ const text = match[0];+ const wholeCode = match[1];+ const denominatorCode = match[2] ?? "";+ const abs = Math.abs(value);+ let whole = wholeCode ? Math.floor(abs) : 0;+ const rest = abs - whole;+ let numerator = Math.round(rest);+ let denominator = 1;+ if (/^[1-9]/.test(denominatorCode)) {+ denominator = Number(denominatorCode);+ numerator = Math.round(rest * denominator);+ } else {+ [numerator, denominator] = closestFraction(rest, 10 ** denominatorCode.length - 1);+ }+ if (wholeCode && numerator === denominator) {+ whole += 1;+ numerator = 0;+ }+ const fraction = numerator ? `${numerator}/${denominator}` : "";+ let body = `${numerator}/${denominator}`;+ if (wholeCode) body = whole || fraction ? [whole ? String(whole) : "", fraction].filter(Boolean).join(" ") : "0";+ const at = match.index;+ return `${value < 0 ? "-" : ""}${unquote(format.slice(0, at))}${body}${unquote(format.slice(at + text.length))}`.trim();+}++function formatElapsed(value: number, format: string): string {+ const tokens: string[] = format.match(/"[^"]*"|\\.|\[[hms]+\]|h+|m+|s+|\.0+|[\s\S]/gi) ?? [];+ const digits = tokens.find((token) => /^\.0+$/.test(token))?.length ?? 1;+ const scale = 10 ** (digits - 1);+ const ticks = Math.round(Math.abs(value) * 86400 * scale);+ const total = Math.floor(ticks / scale);+ const pad = (n: number, width: number) => String(n).padStart(Math.min(width, 2), "0");+ const out = tokens+ .map((token) => {+ const unit = token.toLowerCase();+ if (unit.startsWith("[")) {+ const per = unit[1] === "h" ? 3600 : unit[1] === "m" ? 60 : 1;+ return pad(Math.floor(total / per), unit.length - 2);+ }+ if (unit[0] === "h") return pad(Math.floor(total / 3600) % 24, unit.length);+ if (unit[0] === "m") return pad(Math.floor((total % 3600) / 60), unit.length);+ if (unit[0] === "s") return pad(total % 60, unit.length);+ if (/^\.0+$/.test(token)) return `.${String(ticks % scale).padStart(digits - 1, "0")}`;+ if (token.startsWith('"')) return token.slice(1, -1);+ return token.startsWith("\\") ? token.slice(1) : token;+ })+ .join("");+ return value < 0 ? `-${out}` : out;+}++function generalText(value: number): string {+ return String(Number.isInteger(value) ? value : Number(value.toPrecision(15)));+}++const isPlaceholder = (token: string) => token === "0" || token === "#" || token === "?";+const emptyPlaceholder = (token: string) => (token === "0" ? "0" : token === "?" ? " " : "");++function literalText(token: string): string {+ if (token.startsWith('"')) return token.slice(1, -1);+ if (token.startsWith("\\")) return token.slice(1);+ return token === "," ? "" : token;+}++const digitLayout = memo((format) => {+ const tokens: string[] = format.match(/"[^"]*"|\\.|[0#?.,]|[^"\\0#?.,]+/g) ?? [];+ const dot = tokens.indexOf(".");+ const whole = dot === -1 ? tokens : tokens.slice(0, dot);+ const part = dot === -1 ? [] : tokens.slice(dot + 1);+ const first = whole.findIndex(isPlaceholder);+ const last = whole.length - 1 - [...whole].reverse().findIndex(isPlaceholder);+ return {+ dot,+ whole,+ part,+ first,+ places: part.filter(isPlaceholder),+ grouped: whole.some((token, i) => token === "," && i > first && i < last),+ zeros: whole.filter((token) => token === "0").length,+ before: whole.slice(0, first).map(literalText).join(""),+ after: whole.slice(last + 1).map(literalText).join(""),+ };+});++function placeDigits(number: number, format: string): string {+ const { dot, whole, part, first, places, grouped, zeros, before, after } = digitLayout(format);+ const shown = number ? 14 - Math.floor(Math.log10(Math.abs(number))) : 100;+ const [intDigits = "", fracDigits = ""] = number+ .toFixed(Math.max(0, Math.min(places.length, shown, 100)))+ .split(".");+ if (/e/i.test(intDigits)) return generalText(number);+ const significant = intDigits === "0" ? "" : intDigits;+ let integer: string;+ // No whole-number placeholders (".00"): Excel still shows the integer, just left of the point.+ if (first === -1) {+ integer = `${whole.map(literalText).join("")}${significant}`;+ } else if (grouped) {+ integer = `${before}${significant.padStart(zeros, "0").replace(/\B(?=(\d{3})+$)/g, ",")}${after}`;+ } else {+ let left = significant;+ const out = whole.map(() => "");+ for (let i = whole.length - 1; i >= 0; i--) {+ const token = whole[i]!;+ if (!isPlaceholder(token)) out[i] = literalText(token);+ else if (i === first) out[i] = left || emptyPlaceholder(token);+ else out[i] = left.slice(-1) || emptyPlaceholder(token);+ if (isPlaceholder(token)) left = i === first ? "" : left.slice(0, -1);+ }+ integer = out.join("");+ }+ if (dot === -1) return integer;+ const digits = fracDigits.padEnd(places.length, "0").split("");+ for (let i = places.length - 1; i >= 0 && digits[i] === "0" && places[i] !== "0"; i--) {+ digits[i] = emptyPlaceholder(places[i]!);+ }+ let next = 0;+ return `${integer}.${part.map((token) => (isPlaceholder(token) ? digits[next++] : literalText(token))).join("")}`;+}++const CONDITION = /\[(<=|>=|<>|<|>|=)\s*(-?\d+(?:\.\d+)?)\]/;++const conditionOf = memo((section) => CONDITION.exec(section));++function meets(value: number, section: string | undefined): boolean | null {+ const match = section ? conditionOf(section) : null;+ if (!match) return null;+ const limit = Number(match[2]);+ switch (match[1]) {+ case "<":+ return value < limit;+ case ">":+ return value > limit;+ case "<=":+ return value <= limit;+ case ">=":+ return value >= limit;+ case "=":+ return value === limit;+ default:+ return value !== limit;+ }+}++function pickSection(value: number, sections: string[]): { index: number; sign: string } {+ const first = meets(value, sections[0]);+ const second = meets(value, sections[1]);+ if (first === null && second === null) {+ const index = value < 0 && sections.length > 1 ? 1 : value === 0 && sections.length > 2 ? 2 : 0;+ return { index, sign: value < 0 && index === 0 ? "-" : "" };+ }+ const sign = value < 0 ? "-" : "";+ if (first) return { index: 0, sign };+ if (second || (second === null && sections.length > 1)) return { index: 1, sign };+ return { index: Math.min(2, sections.length - 1), sign };+}++/** `date1904`: dates count from 1904, 1,462 days after the 1900 system. */+const splitSections = memo((code) => {+ const sections: string[] = [];+ let start = 0;+ for (let i = 0; i < code.length; i++) {+ const char = code[i];+ if (char === '"') {+ const close = code.indexOf('"', i + 1);+ i = close === -1 ? code.length : close;+ } else if (char === "\\") i++;+ else if (char === ";") {+ sections.push(code.slice(start, i));+ start = i + 1;+ }+ }+ sections.push(code.slice(start));+ return sections;+});++type SectionKind = "elapsed" | "date" | "literal" | "scientific" | "number";++const SCALE_COMMAS = /([0#?])(,+)(?=\.|[^0#?]*$)/;++const readSection = memo((section) => {+ const tagged = (section.match(/"[^"]*"|\\[\s\S]|\[[^\]]*\]|[_*][\s\S]?|[\s\S]/g) ?? [])+ .map((token) => {+ if (token[0] === "_" || token[0] === "*") return "";+ if (token[0] !== "[" || /^\[[hms]+\]$/i.test(token)) return token;+ const symbol = /^\[\$([^\]-]*)/.exec(token)?.[1];+ return symbol ? `"${symbol}"` : "";+ })+ .join("");+ const code = tagged.replace(/"([^"]*)"/g, "$1").replace(/\\(.)/g, "$1");+ const bare = tagged.replace(/"[^"]*"|\\./g, "");+ const dateLike = !/[0#?]/.test(bare.replace(/s\]?\.0+/gi, "s"));+ const kind: SectionKind =+ dateLike && /\[[hms]+\]/i.test(bare)+ ? "elapsed"+ : dateLike && /[dmyhs]/i.test(bare.replace(/general/gi, ""))+ ? "date"+ : !/[0#?]/.test(bare)+ ? "literal"+ : /E[+-]/i.test(bare)+ ? "scientific"+ : "number";+ const scale = 1000 ** (bare.match(SCALE_COMMAS)?.[2]?.length ?? 0);+ return { tagged, code, kind, percents: bare.split("%").length - 1, scale };+});++function exponentAt(format: string): number {+ for (let i = 0; i < format.length; i++) {+ const char = format[i];+ if (char === '"') {+ const close = format.indexOf('"', i + 1);+ i = close === -1 ? format.length : close;+ } else if (char === "\\") i++;+ else if ((char === "E" || char === "e") && (format[i + 1] === "+" || format[i + 1] === "-")) return i;+ }+ return -1;+}++function formatScientific(value: number, format: string): string {+ const at = exponentAt(format);+ const mantissaFormat = format.slice(0, at);+ const exponentFormat = format.slice(at + 2);+ const tokens: string[] = mantissaFormat.match(/"[^"]*"|\\.|[0#?.]|[^"\\0#?.]+/g) ?? [];+ const dot = tokens.indexOf(".");+ const places = Math.min(dot === -1 ? 0 : tokens.slice(dot + 1).filter(isPlaceholder).length, 100);+ const step = Math.max(1, (dot === -1 ? tokens : tokens.slice(0, dot)).filter(isPlaceholder).length);+ const [normalized = "0", exponentText = "0"] = value.toExponential(places).split("e");+ let mantissa = normalized;+ let exponent = Number(exponentText);+ if (step > 1 && value !== 0) {+ exponent = Math.floor(Math.log10(value) / step) * step;+ mantissa = (value / 10 ** exponent).toFixed(places);+ if (Number(mantissa) >= 10 ** step) {+ exponent += step;+ mantissa = (value / 10 ** exponent).toFixed(places);+ }+ }+ const expSign = exponent < 0 ? "-" : format[at + 1] === "+" ? "+" : "";+ return `${placeDigits(Number(mantissa), mantissaFormat)}E${expSign}${placeDigits(Math.abs(exponent), exponentFormat)}`;+}++export function formatNumber(value: number, rawCode: string | undefined, date1904 = false): string {+ if (!rawCode || rawCode === "General" || rawCode === "@") return generalText(value);+ const sections = splitSections(rawCode);+ const { index, sign } = pickSection(value, sections);+ const { tagged, code, kind, percents, scale } = readSection(sections[index] ?? rawCode);+ if (kind === "elapsed") return `${sign}${formatElapsed(Math.abs(value), tagged)}`;+ if (kind === "date") return formatDate(date1904 ? value + 1462 : value, tagged) ?? generalText(value);+ if (kind === "literal") return `${sign}${code.replace(/general/i, generalText(Math.abs(value)))}`.trim();+ const number = (Math.abs(value) * 100 ** percents) / scale;+ const unscaled = (format: string) => (scale === 1 ? format : format.replace(SCALE_COMMAS, "$1"));+ if (kind === "scientific") return `${sign}${formatScientific(number, unscaled(tagged)).trim()}`;+ const fraction = formatFraction(number, unscaled(tagged));+ if (fraction !== null) return `${sign}${fraction}`;+ return `${sign}${placeDigits(number, tagged).trim()}`;+}++function formatText(text: string, rawCode: string | undefined): string {+ if (!rawCode || rawCode === "@" || rawCode === "General") return text;+ const sections = splitSections(rawCode);+ const tokens: string[] = readSection(sections[3] ?? sections[0]!).tagged.match(/"[^"]*"|\\.|[\s\S]/g) ?? [];+ if (sections.length < 4 && (sections.length > 1 || !tokens.includes("@"))) return text;+ return tokens+ .map((token) => (token === "@" ? text : token.startsWith('"') ? token.slice(1, -1) : token.startsWith("\\") ? token.slice(1) : token))+ .join("");+}++function columnIndex(ref: string): number {+ let index = 0;+ for (const char of ref) {+ const code = char.charCodeAt(0) & ~32;+ if (code < 65 || code > 90) break;+ index = index * 26 + (code - 64);+ }+ return index - 1;+}++export function columnName(index: number): string {+ let name = "";+ for (let n = index + 1; n > 0; n = Math.floor((n - 1) / 26)) {+ name = String.fromCharCode(65 + ((n - 1) % 26)) + name;+ }+ return name;+}++interface CellStyle {+ format?: string;+ bold?: boolean;+ italic?: boolean;+}++function localeFormat(id: number): string | undefined {+ if (id === 32) return "h:mm";+ if (id === 33) return "h:mm:ss";+ return (id >= 27 && id <= 36) || (id >= 50 && id <= 58) ? "m/d/yyyy" : undefined;+}++const isOn = (flag: Element) => !["0", "false", "off"].includes(flag.getAttribute("val") ?? "");++const MAX_FORMAT_CODE = 1024;+const MAX_NUM_FMTS = 1000;++function readStyles(doc: Document | null): { styles: CellStyle[]; cut: boolean } {+ if (!doc) return { styles: [], cut: false };+ const formats = new Map<number, string>();+ let cut = false;+ for (const [index, fmt] of all(doc, "numFmt").entries()) {+ const code = fmt.getAttribute("formatCode") ?? "";+ // Past Excel's own limits a format is read as General: the formatters cache by code, across files.+ const kept = index < MAX_NUM_FMTS && code.length <= MAX_FORMAT_CODE;+ cut ||= !kept;+ formats.set(Number(fmt.getAttribute("numFmtId")), kept ? code : "General");+ }+ const fontsNode = first(doc, "fonts");+ const fonts = fontsNode+ ? children(fontsNode, "font").map((font) => ({+ bold: children(font, "b").some(isOn),+ italic: children(font, "i").some(isOn),+ }))+ : [];+ const xfs = first(doc, "cellXfs");+ const styles = (xfs ? children(xfs, "xf") : []).map((xf) => {+ const id = Number(xf.getAttribute("numFmtId") ?? 0);+ const font = fonts[Number(xf.getAttribute("fontId") ?? 0)];+ return { format: formats.get(id) ?? BUILTIN_FORMATS[id] ?? localeFormat(id), ...font };+ });+ return { styles, cut };+}++const REFERENCE =+ /(^|[^A-Za-z0-9_.$])(?:(\$?)([A-Za-z]{1,3})(\$?)(\d+)(?![\d(A-Za-z_!])|(\$?)([A-Za-z]{1,3}):(\$?)([A-Za-z]{1,3})(?![\w(!.])|(\$?)(\d+):(\$?)(\d+)(?![\d.]))/g;++function shiftFormula(formula: string, rows: number, columns: number): string {+ const column = (abs: string, name: string) =>+ abs + (abs ? name.toUpperCase() : columnName(columnIndex(name.toUpperCase()) + columns));+ const row = (abs: string, n: string) => abs + (abs ? n : String(Number(n) + rows));+ return formula+ .split(/("(?:[^"]|"")*"|'(?:[^']|'')*'|\[(?:[^[\]']|'.|\[(?:[^[\]']|'.)*\])*\])/)+ .map((part, index) =>+ index % 2+ ? part+ : part.replace(REFERENCE, (...m: string[]) => {+ const [, lead, ca, c, ra, r, c1a, c1, c2a, c2, r1a, r1, r2a, r2] = m;+ if (c !== undefined) return `${lead}${column(ca!, c)}${row(ra!, r!)}`;+ if (c1 !== undefined) return `${lead}${column(c1a!, c1)}:${column(c2a!, c2!)}`;+ return `${lead}${row(r1a!, r1!)}:${row(r2a!, r2!)}`;+ }),+ )+ .join("");+}+++const NAMED_ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };+const ENTITY = /&(?:#x([0-9a-f]+)|#(\d+)|(amp|lt|gt|quot|apos));|<!\[CDATA\[([\s\S]*?)\]\]>/gi;++function decodeXml(text: string): string {+ if (!text.includes("&") && !text.includes("<!")) return text;+ return text.replace(ENTITY, (match, hex?: string, dec?: string, name?: string, cdata?: string) => {+ if (cdata !== undefined) return cdata;+ if (name) return NAMED_ENTITIES[name.toLowerCase()]!;+ const code = hex ? parseInt(hex, 16) : Number(dec);+ return code <= 0x10ffff ? String.fromCodePoint(code) : match;+ });+}++const attributePatterns = new Map<string, RegExp>();++function attribute(attributes: string, name: string): string | null {+ let pattern = attributePatterns.get(name);+ if (!pattern) {+ pattern = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`);+ attributePatterns.set(name, pattern);+ }+ const match = pattern.exec(attributes);+ return match ? decodeXml(match[1] ?? match[2] ?? "") : null;+}++const openTag = (name: string) => new RegExp(`<(?:[\\w.-]+:)?${name}(?=[\\s/>])([^>]*?)(/)?>`, "g");+const closeTag = (name: string) => new RegExp(`</(?:[\\w.-]+:)?${name}\\s*>`, "g");++function* elements(text: string, open: RegExp, close: RegExp): Generator<[string, string]> {+ open.lastIndex = 0;+ for (let match = open.exec(text); match; match = open.exec(text)) {+ if (match[2]) {+ yield [match[1]!, ""];+ continue;+ }+ close.lastIndex = open.lastIndex;+ const end = close.exec(text);+ if (!end) return;+ const inner = text.slice(open.lastIndex, end.index);+ open.lastIndex = close.lastIndex;+ yield [match[1]!, inner];+ }+}++const ROW_OPEN = openTag("row");+const ROW_CLOSE = closeTag("row");+const CELL_OPEN = openTag("c");+const CELL_CLOSE = closeTag("c");+const COL_OPEN = openTag("col");+const COL_CLOSE = closeTag("col");+const VALUE = /<(?:[\w.-]+:)?v(?=[\s/>])[^>]*?(?:\/>|>([\s\S]*?)<\/(?:[\w.-]+:)?v\s*>)/;+const FORMULA = /<(?:[\w.-]+:)?f(?=[\s/>])([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:[\w.-]+:)?f\s*>)/;+const PHONETIC = /<(?:[\w.-]+:)?rPh(?=[\s/>])[^>]*?(?:\/>|>[\s\S]*?<\/(?:[\w.-]+:)?rPh\s*>)/g;+const TEXT_RUN = /<(?:[\w.-]+:)?t(?:\s[^>]*)?>([\s\S]*?)(?:<\/(?:[\w.-]+:)?t\s*>|$)/g;+const SHEET_DATA = /<(?:[\w.-]+:)?sheetData[\s/>]/;++const MARKUP = /<!\[CDATA\[([\s\S]*?)\]\]>|<!--[\s\S]*?-->/g;++function flattenMarkup(text: string): string {+ if (!text.includes("<!")) return text;+ return text.replace(MARKUP, (_, cdata?: string) =>+ cdata === undefined ? "" : cdata.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"),+ );+}++function stringText(xmlText: string): string {+ let out = "";+ for (const match of flattenMarkup(xmlText).replace(PHONETIC, "").matchAll(TEXT_RUN)) {+ out += decodeXml(match[1]!.slice(0, MAX_CELL_BYTES));+ if (out.length >= MAX_CELL_TEXT) return out.slice(0, MAX_CELL_TEXT);+ }+ return out;+}++const isTrue = (value: string | null) => value === "1" || value === "true";++const MAX_CELL_TEXT = 32_767;+const MAX_CELL_BYTES = MAX_CELL_TEXT * 10;++function readSheet(+ text: string,+ name: string,+ string: (index: number) => string,+ style: (index: number) => CellStyle | undefined,+ date1904: boolean,+ budget: { cells: number },+): Sheet {+ const rows: (SheetCell | undefined)[][] = [];+ const widths: (number | undefined)[] = [];+ const hidden = { rows: new Set<number>(), columns: new Set<number>() };+ text = flattenMarkup(text);+ const dataAt = text.search(SHEET_DATA);+ const head = dataAt === -1 ? text : text.slice(0, dataAt);+ for (const [attrs] of elements(head, COL_OPEN, COL_CLOSE)) {+ const min = Number(attribute(attrs, "min") ?? 1);+ const max = Math.min(Number(attribute(attrs, "max") ?? min), MAX_SHEET_COLUMNS);+ const width = Number(attribute(attrs, "width"));+ const hide = isTrue(attribute(attrs, "hidden"));+ for (let i = min; i <= max; i++) {+ if (hide) hidden.columns.add(i - 1);+ else if (width) widths[i - 1] = Math.round(width * 7 + 5);+ }+ }+ if (dataAt === -1) return { name, rows, widths, truncated: false, hidden };+ const data = text.slice(dataAt);+ // Shared formulas: the master cell holds the text and comes before the cells sharing it.+ const shared = new Map<string, { formula: string; row: number; col: number }>();+ let truncated = false;+ let nextRow = 0;+ for (const [rowAttrs, rowBody] of elements(data, ROW_OPEN, ROW_CLOSE)) {+ const r = Number(attribute(rowAttrs, "r") ?? nextRow + 1) - 1;+ nextRow = r + 1;+ if (r >= MAX_SHEET_ROWS || budget.cells <= 0) {+ truncated = true;+ break;+ }+ budget.cells--;+ const rowHidden = isTrue(attribute(rowAttrs, "hidden"));+ if (rowHidden) hidden.rows.add(r);+ if (rowHidden && !rowBody.includes("shared")) continue;+ const cells: (SheetCell | undefined)[] = [];+ let nextColumn = 0;+ for (const [attrs, body] of elements(rowBody, CELL_OPEN, CELL_CLOSE)) {+ const ref = attribute(attrs, "r");+ const col = ref ? columnIndex(ref) : nextColumn;+ nextColumn = col + 1;+ if (col >= MAX_SHEET_COLUMNS) {+ truncated ||= !rowHidden;+ continue;+ }+ const f = body.includes("f") ? FORMULA.exec(body) : null;+ const fAttrs = f?.[1] ?? "";+ const fText = decodeXml((f?.[2] ?? "").slice(0, MAX_CELL_BYTES));+ const sharedId = f && attribute(fAttrs, "t") === "shared" ? (attribute(fAttrs, "si") ?? "") : null;+ if (sharedId !== null && fText && ref) {+ shared.set(sharedId, { formula: fText, row: r, col });+ }+ if (rowHidden || hidden.columns.has(col)) continue;+ const type = attribute(attrs, "t");+ const cached = VALUE.exec(body);+ const raw = decodeXml((cached?.[1] ?? "").slice(0, MAX_CELL_BYTES));+ const master = sharedId !== null ? shared.get(sharedId) : undefined;+ const formula = fText || (master ? shiftFormula(master.formula, r - master.row, col - master.col) : "");+ const cellStyle = style(Number(attribute(attrs, "s") ?? 0)) ?? {};+ let value = raw;+ let numeric = false;+ if (raw === "" && formula && !(type === "str" && cached)) value = `=${formula}`;+ else if (type === "s" || type === "inlineStr" || type === "str") {+ value = formatText(type === "s" ? string(Number(raw)) : type === "inlineStr" ? stringText(body) : raw, cellStyle.format);+ } else if (type === "b") value = isTrue(raw) ? "TRUE" : "FALSE";+ else if (type !== "str" && type !== "e" && raw !== "" && Number.isFinite(Number(raw))) {+ value = formatNumber(Number(raw), cellStyle.format, date1904);+ numeric = true;+ }+ if (value === "" && !cellStyle.bold) continue;+ cells[col] = { text: value.slice(0, MAX_CELL_TEXT), numeric, bold: cellStyle.bold, italic: cellStyle.italic };+ budget.cells--;+ }+ if (!rowHidden) rows[r] = cells;+ }+ return { name, rows, widths, truncated, hidden };+}++const SHEET_CUT_BYTES = 1024 * 1024;+const MAX_SHEET_XML_BYTES = 64 * 1024 * 1024;++const SHEET_DATA_CLOSE = Array.from("sheetData>", (char) => char.charCodeAt(0));++function rowsEnd(bytes: Uint8Array, rows: number): { end: number; capped: boolean; closed?: number } {+ let count = 0;+ let last = -1;+ for (let i = bytes.indexOf(0x3c); i !== -1; i = bytes.indexOf(0x3c, i + 1)) {+ if (i > MAX_SHEET_XML_BYTES) return { end: last, capped: true };+ const skipped = skipMarkup(bytes, i);+ if (skipped === -1) break;+ if (skipped !== i) {+ i = skipped;+ continue;+ }+ if (bytes[i + 1] !== 0x2f) continue;+ let name = i + 2;+ for (let j = name; j < i + 40 && bytes[j] !== 0x3e; j++) {+ if (bytes[j] === 0x3a) {+ name = j + 1;+ break;+ }+ }+ if (bytes[name] === 0x72 && bytes[name + 1] === 0x6f && bytes[name + 2] === 0x77 && bytes[name + 3] === 0x3e) {+ last = name + 4;+ if (++count === rows) return { end: last, capped: false };+ } else if (SHEET_DATA_CLOSE.every((byte, n) => bytes[name + n] === byte)) {+ return { end: -1, capped: false, closed: name + SHEET_DATA_CLOSE.length };+ }+ }+ return { end: -1, capped: false };+}++function sheetText(bytes: Uint8Array, rows: number, whole = true): { text: string; cut: boolean } {+ if (bytes.length <= SHEET_CUT_BYTES) return { text: strFromU8(bytes), cut: false };+ const { end, capped, closed } = rowsEnd(bytes, rows);+ if (closed !== undefined) return { text: strFromU8(bytes.subarray(0, closed)), cut: false };+ if (end === -1) {+ return bytes.length > MAX_SHEET_XML_BYTES || capped+ ? { text: strFromU8(bytes.subarray(0, MAX_SHEET_XML_BYTES)), cut: true }+ : { text: strFromU8(bytes), cut: false };+ }+ const next = rowsEnd(bytes.subarray(end), 1);+ const more = capped || next.end !== -1 || (!whole && next.closed === undefined);+ return { text: strFromU8(bytes.subarray(0, end)), cut: more };+}++const CDATA_END = [0x5d, 0x5d, 0x3e]; // ]]>+const COMMENT_END = [0x2d, 0x2d, 0x3e]; // -->++function indexOfBytes(bytes: Uint8Array, seq: number[], from: number): number {+ for (let i = bytes.indexOf(seq[0]!, from); i !== -1; i = bytes.indexOf(seq[0]!, i + 1)) {+ if (seq.every((byte, n) => bytes[i + n] === byte)) return i;+ }+ return -1;+}++function skipMarkup(bytes: Uint8Array, i: number): number {+ if (bytes[i + 1] !== 0x21) return i;+ const close = bytes[i + 2] === 0x5b ? CDATA_END : bytes[i + 2] === 0x2d ? COMMENT_END : null;+ if (!close) return i;+ const at = indexOfBytes(bytes, close, i + 3);+ return at === -1 ? -1 : at + 2;+}++function findTag(bytes: Uint8Array, from: number, name: string, closing: boolean) {+ for (let i = bytes.indexOf(0x3c, from); i !== -1; i = bytes.indexOf(0x3c, i + 1)) {+ const skipped = skipMarkup(bytes, i);+ if (skipped === -1) return null;+ if (skipped !== i) {+ i = skipped;+ continue;+ }+ let j = i + 1;+ if ((bytes[j] === 0x2f) !== closing) continue;+ if (closing) j++;+ let k = j;+ while (k < bytes.length && bytes[k]! > 0x20 && bytes[k] !== 0x3e && bytes[k] !== 0x2f) {+ if (bytes[k] === 0x3a) j = k + 1;+ k++;+ }+ if (k - j !== name.length) continue;+ let same = true;+ for (let n = 0; n < name.length && same; n++) same = bytes[j + n] === name.charCodeAt(n);+ if (!same) continue;+ const end = bytes.indexOf(0x3e, k);+ if (end === -1) return null;+ return { start: i, end: end + 1, empty: bytes[end - 1] === 0x2f };+ }+ return null;+}++const MAX_SHARED_STRINGS = 2_000_000;++function sharedStrings(part: Growing | undefined): (index: number) => string | undefined {+ let starts = new Uint32Array(1024);+ let ends = new Uint32Array(1024);+ let count = 0;+ const texts = new Map<number, string>();+ let at = part ? 0 : -1;+ return (index) => {+ while (part && at !== -1 && count <= index && count < MAX_SHARED_STRINGS) {+ const open = findTag(part.data, at, "si", false);+ const close = open && !open.empty ? findTag(part.data, open.end, "si", true) : null;+ if (!open || (!open.empty && !close)) {+ if (part.done) at = -1;+ else part.grow();+ continue;+ }+ if (count === starts.length) {+ starts = grow(starts);+ ends = grow(ends);+ }+ starts[count] = open.end;+ ends[count] = close ? close.start : open.end;+ count++;+ at = close ? close.end : open.end;+ }+ if ((part?.cut || count >= MAX_SHARED_STRINGS) && index >= count) return undefined;+ if (!part || !Number.isInteger(index) || index < 0 || index >= count) return "";+ let text = texts.get(index);+ if (text === undefined) {+ const start = starts[index]!;+ text = stringText(strFromU8(part.data.subarray(start, Math.min(ends[index]!, start + MAX_CELL_BYTES))));+ texts.set(index, text);+ }+ return text;+ };+}++function grow(array: Uint32Array): Uint32Array<ArrayBuffer> {+ const next = new Uint32Array(array.length * 2);+ next.set(array);+ return next;+}++const MAX_STYLE_SECTION_BYTES = 16 * 1024 * 1024;+const MAX_STYLE_SECTION_TAGS = 200_000;+const MAX_STYLES_BYTES = 3 * MAX_STYLE_SECTION_BYTES;++function styleSections(bytes: Uint8Array | undefined): { doc: Document | null; cut: boolean } {+ const root = bytes && findTag(bytes, 0, "styleSheet", false);+ if (!bytes || !root || root.empty) return { doc: null, cut: false };+ const open = strFromU8(bytes.subarray(root.start, root.end));+ let cut = false;+ const parts = ["numFmts", "fonts", "cellXfs"].map((name) => {+ const start = findTag(bytes, root.end, name, false);+ const end = start && !start.empty ? findTag(bytes, start.end, name, true) : null;+ if (!start || !end) return "";+ if (end.end - start.start > MAX_STYLE_SECTION_BYTES) return ((cut = true), "");+ // Counted before it is parsed: tiny elements would build a DOM far larger than the bytes.+ let tags = 0;+ for (let at = start.start; at < end.end && tags <= MAX_STYLE_SECTION_TAGS; at++) {+ if (bytes[at] === 0x3c) tags++;+ }+ if (tags > MAX_STYLE_SECTION_TAGS) return ((cut = true), "");+ return strFromU8(bytes.subarray(start.start, end.end));+ });+ const prefix = /^<([\w.-]+:)?/.exec(open)?.[1] ?? "";+ return { doc: parseXml(`${open}${parts.join("")}</${prefix}styleSheet>`), cut };+}++export function readXlsx(bytes: Uint8Array): Sheet[] {+ const read = archive(bytes);+ const main = mainPart(read, "xl/workbook.xml");+ if ((read.size(main) ?? 0) > MAX_XML_PART_BYTES) throw new Error("File is too large to preview.");+ const head = read([main, relsPath(main)], MAX_XML_PART_BYTES);+ const workbook = xml(head, main);+ if (!workbook) throw new Error("Not a valid XLSX workbook.");+ const rels = relationshipList(head, main);+ const partOf = (type: string, fallback: string) => rels.find((rel) => rel.type.endsWith(`/${type}`))?.path ?? fallback;+ const stringsPath = partOf("sharedStrings", "xl/sharedStrings.xml");+ const stylesPath = partOf("styles", "xl/styles.xml");+ let strings: ((index: number) => string | undefined) | undefined;+ let missed = false;+ const string = (index: number) => {+ const text = (strings ??= sharedStrings(read.open(stringsPath, MAX_SHEET_XML_BYTES)))(index);+ missed ||= text === undefined;+ return text ?? "";+ };+ let styles: CellStyle[] | undefined;+ let stylesCut = false;+ const style = (index: number) => {+ if (!styles) {+ const sections = styleSections(read([stylesPath], MAX_STYLES_BYTES)[stylesPath]);+ const table = readStyles(sections.doc);+ stylesCut = sections.cut || table.cut || (read.size(stylesPath) ?? 0) > MAX_STYLES_BYTES;+ styles = table.styles;+ }+ missed ||= stylesCut;+ return styles[index];+ };+ const date1904 = ["1", "true"].includes(first(workbook, "workbookPr")?.getAttribute("date1904") ?? "");+ const paths = new Map(rels.map((rel) => [rel.id, rel.path]));+ const sheets: Sheet[] = [];+ const budget = { cells: MAX_WORKBOOK_CELLS };+ for (const sheet of all(workbook, "sheet")) {+ if (sheet.getAttribute("state") === "hidden" || sheet.getAttribute("state") === "veryHidden") continue;+ if (budget.cells <= 0 || sheets.length >= MAX_SHEETS) {+ const last = sheets.at(-1);+ if (last) last.truncated = true;+ break;+ }+ const path = paths.get(relId(sheet, "id") ?? "");+ const part = path ? read.head(path, MAX_SHEET_XML_BYTES + 1) : undefined;+ if (!part) continue;+ const whole = part.length <= MAX_SHEET_XML_BYTES;+ const { text, cut } = sheetText(part, Math.min(MAX_SHEET_ROWS, budget.cells), whole);+ missed = false;+ const parsed = readSheet(text, sheet.getAttribute("name") ?? "Sheet", string, style, date1904, budget);+ if (cut || missed) parsed.truncated = true;+ sheets.push(parsed);+ }+ return sheets;+}++export function readDelimited(text: string, delimiter: string, name: string): Sheet {+ const rows: (SheetCell | undefined)[][] = [];+ let row: (SheetCell | undefined)[] = [];+ let field = "";+ let quoted = false;+ let truncated = false;+ const push = () => {+ if (row.length < MAX_SHEET_COLUMNS) {+ const numeric = field.trim() !== "" && Number.isFinite(Number(field.replace(/[$,%]/g, "")));+ row.push(field === "" ? undefined : { text: field, numeric });+ } else truncated = true;+ field = "";+ };+ const append = (char: string) => {+ if (field.length < MAX_CELL_TEXT) field += char;+ else truncated = true;+ };+ for (let i = 0; i < text.length; i++) {+ const char = text[i]!;+ if (quoted) {+ if (char === '"' && text[i + 1] === '"') {+ append('"');+ i++;+ } else if (char === '"') quoted = false;+ else append(char);+ } else if (char === '"' && field === "") quoted = true;+ else if (char === delimiter) push();+ else if (char === "\n" || char === "\r") {+ if (char === "\r" && text[i + 1] === "\n") i++;+ push();+ rows.push(row);+ row = [];+ if (rows.length >= MAX_SHEET_ROWS) {+ truncated = i < text.length - 1;+ break;+ }+ } else append(char);+ }+ if (field !== "" || row.length) {+ push();+ rows.push(row);+ }+ return { name, rows, widths: [], truncated };+}+++export interface SlideBox {+ frame?: {+ x: number;+ y: number;+ w: number;+ h: number;+ rot?: number;+ flipH?: boolean;+ flipV?: boolean;+ };+ placeholder?: string;+ paragraphs?: { text: string; size?: number; bold?: boolean; align?: string; bullet?: boolean }[];+ image?: Blob;+ crop?: { l: number; t: number; r: number; b: number };+ table?: string[][];+ caption?: string;+}++export interface Slide {+ boxes: SlideBox[];+}++export interface Deck {+ aspect: number;+ widthPt: number;+ slides: Slide[];+ truncated?: boolean;+}++const IMAGE_TYPES: Record<string, string> = {+ png: "image/png",+ jpg: "image/jpeg",+ jpeg: "image/jpeg",+ gif: "image/gif",+ svg: "image/svg+xml",+ webp: "image/webp",+ bmp: "image/bmp",+};++const imageType = (path: string) => {+ const extension = path.split(".").pop()!.toLowerCase();+ return Object.hasOwn(IMAGE_TYPES, extension) ? IMAGE_TYPES[extension] : undefined;+};++function packageImageTypes(read: Reader): (path: string) => string | undefined {+ const name = "[Content_Types].xml";+ const doc = xml(read([name], MAX_XML_PART_BYTES), name);+ const declared = (tag: string, key: string, trim: RegExp) =>+ new Map(+ (doc ? all(doc, tag) : []).map((el) => [+ (el.getAttribute(key) ?? "").replace(trim, "").toLowerCase(),+ (el.getAttribute("ContentType") ?? "").toLowerCase(),+ ]),+ );+ const defaults = declared("Default", "Extension", /^$/);+ const overrides = declared("Override", "PartName", /^\//);+ const shown = new Set(Object.values(IMAGE_TYPES));+ return (path) => {+ const dot = path.lastIndexOf(".");+ const type = overrides.get(path.toLowerCase()) ?? (dot === -1 ? undefined : defaults.get(path.slice(dot + 1).toLowerCase()));+ return type && shown.has(type) ? type : undefined;+ };+}++const MAX_CHART_SERIES = 100;+const MAX_CHART_CELLS = 5000;++const MAX_SLIDES = 500;+const MAX_DECK_TEXT = 8 * 1024 * 1024;+const MAX_DECK_IMAGE_BYTES = 64 * 1024 * 1024;+const MAX_PICTURE_PIXELS = 64 * 1024 * 1024;+const MAX_SLIDE_PIXELS = 128 * 1024 * 1024;++function imagePixels(b: Uint8Array): number | undefined {+ const view = new DataView(b.buffer, b.byteOffset, b.byteLength);+ const ascii = (at: number, text: string) => [...text].every((c, i) => b[at + i] === c.charCodeAt(0));+ if (b.length >= 24 && ascii(1, "PNG")) return view.getUint32(16) * view.getUint32(20);+ if (b.length >= 10 && ascii(0, "GIF8")) return view.getUint16(6, true) * view.getUint16(8, true);+ if (b.length >= 26 && ascii(0, "BM")) {+ if (view.getUint32(14, true) === 12) return view.getUint16(18, true) * view.getUint16(20, true);+ return Math.abs(view.getInt32(18, true)) * Math.abs(view.getInt32(22, true));+ }+ if (b.length >= 30 && ascii(0, "RIFF") && ascii(8, "WEBP")) {+ if (ascii(12, "VP8 ")) return (view.getUint16(26, true) & 0x3fff) * (view.getUint16(28, true) & 0x3fff);+ if (ascii(12, "VP8L")) {+ const bits = view.getUint32(21, true);+ return ((bits & 0x3fff) + 1) * (((bits >>> 14) & 0x3fff) + 1);+ }+ if (ascii(12, "VP8X")) return ((view.getUint32(24, true) & 0xffffff) + 1) * ((view.getUint32(27, true) & 0xffffff) + 1);+ return undefined;+ }+ if (b[0] === 0xff && b[1] === 0xd8) {+ for (let at = 2; at + 9 <= b.length; ) {+ if (b[at] !== 0xff) return undefined;+ const marker = b[at + 1]!;+ if (marker === 0xff) at++;+ else if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) at += 2;+ else if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {+ return view.getUint16(at + 5) * view.getUint16(at + 7);+ } else at += 2 + view.getUint16(at + 2);+ }+ }+ return undefined;+}++/** Decoded pixels of a raster within MAX_PICTURE_PIXELS, else undefined; never SVG (unbounded cost, Office keeps a PNG). */+export function picturePixels(bytes: Uint8Array): number | undefined {+ const pixels = imagePixels(bytes);+ return pixels !== undefined && pixels <= MAX_PICTURE_PIXELS ? pixels : undefined;+}++function boxText(box: SlideBox): number {+ let n = box.caption?.length ?? 0;+ for (const p of box.paragraphs ?? []) n += p.text.length;+ for (const row of box.table ?? []) for (const cell of row) n += cell.length;+ return n;+}+const HIDDEN_SLIDE = /<(?:[\w.-]+:)?sld\b[^>]*\sshow\s*=\s*["'](?:0|false)["']/;++const MAX_SLIDE_ITEMS = 10_000;++function readTable(tbl: Element, limit: number): string[][] {+ const table: string[][] = [];+ let cells = 0;+ let cut = false;+ for (const tr of children(tbl, "tr")) {+ const tcs = children(tr, "tc");+ if (tcs.length > MAX_CHART_SERIES) cut = true;+ const row = tcs.slice(0, MAX_CHART_SERIES);+ if (cells + row.length > Math.min(limit, MAX_CHART_CELLS)) {+ cut = true;+ break;+ }+ cells += row.length;+ table.push(row.map((tc) => clip(all(tc, "p").map(paragraphText).join("\n"))));+ }+ if (cut) table.push(["…"]);+ return table;+}++const MAX_DIAGRAM_NODES = 500;++function readDiagram(doc: Document, limit: number): NonNullable<SlideBox["paragraphs"]> {+ const paragraphs: NonNullable<SlideBox["paragraphs"]> = [];+ for (const pt of all(doc, "pt")) {+ const type = pt.getAttribute("type");+ if (type && type !== "node") continue;+ const text = clip(all(pt, "p").map(paragraphText).join("\n"));+ if (!text.trim()) continue;+ if (paragraphs.length >= Math.min(limit, MAX_DIAGRAM_NODES)) {+ paragraphs.push({ text: "…" });+ break;+ }+ paragraphs.push({ text, bullet: true });+ }+ return paragraphs;+}++function readChart(doc: Document, budget: number): { caption?: string; table: string[][] } | null {+ const serNodes = all(doc, "ser");+ const width = Math.min(serNodes.length, MAX_CHART_SERIES) + 1;+ if (serNodes.length && width > Math.min(budget, MAX_CHART_CELLS)) return { table: [["…"]] };+ const limit = Math.floor(Math.min(budget, MAX_CHART_CELLS) / width) - 1;+ let cut = serNodes.length > MAX_CHART_SERIES;+ const cache = (node: Element | undefined) => {+ const out: string[] = [];+ for (const pt of node ? all(node, "pt") : []) {+ const idx = Number(pt.getAttribute("idx") ?? out.length);+ if (idx >= limit) cut = true;+ else if (idx >= 0) out[idx] = clip(first(pt, "v")?.textContent ?? "");+ }+ return out;+ };+ const series = serNodes.slice(0, MAX_CHART_SERIES).map((ser) => {+ const tx = children(ser, "tx")[0];+ return {+ name: clip((tx && (cache(tx)[0] ?? first(tx, "v")?.textContent)) ?? ""),+ categories: cache(children(ser, "cat")[0] ?? children(ser, "xVal")[0]),+ values: cache(children(ser, "val")[0] ?? children(ser, "yVal")[0]),+ };+ });+ if (!series.length) return null;+ const categories = series.find((s) => s.categories.length)?.categories ?? [];+ const count = series.reduce((n, s) => Math.max(n, s.values.length), categories.length);+ const table = [["", ...series.map((s) => s.name)]];+ for (let i = 0; i < count; i++) table.push([categories[i] ?? String(i + 1), ...series.map((s) => s.values[i] ?? "")]);+ if (cut) table.push(["…"]);+ const title = first(doc, "title");+ const caption = title ? clip(all(title, "t").map((t) => t.textContent ?? "").join("")) : "";+ return { caption: caption || undefined, table };+}++const clip = (text: string) => (text.length > MAX_CELL_TEXT ? text.slice(0, MAX_CELL_TEXT) : text);++function paragraphText(p: Element): string {+ return clip(Array.from(p.children)+ .map((child) =>+ child.localName === "br"+ ? "\n"+ : child.localName === "r" || child.localName === "fld"+ ? all(child, "t").map((t) => t.textContent ?? "").join("")+ : "",+ )+ .join(""));+}++function point(xfrm: Element | undefined, name: string, a: string, b: string): [number, number] | undefined {+ const node = xfrm && children(xfrm, name)[0];+ return node ? [Number(node.getAttribute(a)) || 0, Number(node.getAttribute(b)) || 0] : undefined;+}++function readCrop(pic: Element): SlideBox["crop"] {+ const rect = first(pic, "srcRect");+ const side = (name: string) => {+ const value = Number(rect?.getAttribute(name)) / 100_000;+ return Number.isFinite(value) ? value : 0;+ };+ const [l, t, r, b] = ["l", "t", "r", "b"].map(side) as [number, number, number, number];+ if (!(l || t || r || b) || l + r >= 1 || t + b >= 1) return undefined;+ return { l, t, r, b };+}++function readFrame(shape: Element, cx: number, cy: number): SlideBox["frame"] {+ const xfrm = first(shape, "xfrm");+ const off = point(xfrm, "off", "x", "y");+ const ext = point(xfrm, "ext", "cx", "cy");+ if (!off || !ext) return undefined;+ let [x, y] = off;+ let [w, h] = ext;+ let rot = degrees(xfrm);+ let flipH = isTrue(xfrm?.getAttribute("flipH") ?? null);+ let flipV = isTrue(xfrm?.getAttribute("flipV") ?? null);+ for (let group = shape.parentElement; group; group = group.parentElement) {+ if (group.localName !== "grpSp") continue;+ const box = children(group, "grpSpPr").flatMap((props) => children(props, "xfrm"))[0];+ const [gx, gy] = point(box, "off", "x", "y") ?? [0, 0];+ const [gw, gh] = point(box, "ext", "cx", "cy") ?? [0, 0];+ const [ox, oy] = point(box, "chOff", "x", "y") ?? [0, 0];+ const [ow, oh] = point(box, "chExt", "cx", "cy") ?? [0, 0];+ const sx = gw && ow ? gw / ow : 1;+ const sy = gh && oh ? gh / oh : 1;+ x = gx + (x - ox) * sx;+ y = gy + (y - oy) * sy;+ w *= sx;+ h *= sy;+ if (isTrue(box?.getAttribute("flipH") ?? null)) {+ x = 2 * gx + gw - x - w;+ rot = -rot;+ flipH = !flipH;+ }+ if (isTrue(box?.getAttribute("flipV") ?? null)) {+ y = 2 * gy + gh - y - h;+ rot = -rot;+ flipV = !flipV;+ }+ const turn = degrees(box);+ if (turn) {+ const angle = (turn * Math.PI) / 180;+ const dx = x + w / 2 - (gx + gw / 2);+ const dy = y + h / 2 - (gy + gh / 2);+ x = gx + gw / 2 + dx * Math.cos(angle) - dy * Math.sin(angle) - w / 2;+ y = gy + gh / 2 + dx * Math.sin(angle) + dy * Math.cos(angle) - h / 2;+ rot += turn;+ }+ }+ rot %= 360;+ return {+ x: x / cx,+ y: y / cy,+ w: w / cx,+ h: h / cy,+ ...(rot ? { rot } : {}),+ ...(flipH ? { flipH } : {}),+ ...(flipV ? { flipV } : {}),+ };+}++function degrees(xfrm: Element | undefined): number {+ return Number(xfrm?.getAttribute("rot")) / 60000 || 0;+}++export function readPptx(bytes: Uint8Array, { images = true } = {}): Deck {+ const read = archive(bytes);+ const main = mainPart(read, "ppt/presentation.xml");+ if ((read.size(main) ?? 0) > MAX_XML_PART_BYTES) throw new Error("File is too large to preview.");+ const head = read([main, relsPath(main)], MAX_XML_PART_BYTES);+ const presentation = xml(head, main);+ if (!presentation) throw new Error("Not a valid PPTX presentation.");+ const size = first(presentation, "sldSz");+ const cx = Number(size?.getAttribute("cx")) || 12192000;+ const cy = Number(size?.getAttribute("cy")) || 6858000;+ const rels = relationships(head, main);+ const slidePaths = all(presentation, "sldId").map((id) => rels.get(relId(id, "id") ?? ""));+ const slides: Slide[] = [];+ const pictures = new Map<string, { image: Blob; pixels: number }>();+ let pictureBytes = 0;+ let declared: ((path: string) => string | undefined) | undefined;+ const pictureType = (path: string) => imageType(path) ?? (declared ??= packageImageTypes(read))(path);+ let truncated = false;+ let textLeft = MAX_DECK_TEXT;+ for (const [index, path] of slidePaths.entries()) {+ if (!path) continue;+ if ((read.size(path) ?? 0) > MAX_XML_PART_BYTES) {+ if (slides.length === MAX_SLIDES) {+ truncated = true;+ break;+ }+ slides.push({ boxes: [{ paragraphs: [{ text: "…" }] }] });+ continue;+ }+ const part = read([path, relsPath(path)], MAX_XML_PART_BYTES);+ const slideXml = part[path];+ if (!slideXml || HIDDEN_SLIDE.test(strFromU8(slideXml.subarray(0, 16384)))) continue;+ if (slides.length === MAX_SLIDES) {+ truncated = true;+ break;+ }+ const doc = xml(part, path);+ if (!doc || ["0", "false"].includes(doc.documentElement.getAttribute("show")?.trim() ?? "")) continue;+ const slideRelList = relationshipList(part, path);+ const partDoc = (partPath: string) => {+ if ((read.size(partPath) ?? 0) > MAX_XML_PART_BYTES) {+ cut = true;+ return null;+ }+ return xml(read([partPath], MAX_XML_PART_BYTES), partPath);+ };+ const slideRels = new Map(slideRelList.map((rel) => [rel.id, rel.path]));+ const boxes: SlideBox[] = [];+ let left = MAX_SLIDE_ITEMS;+ let pixelsLeft = MAX_SLIDE_PIXELS;+ let cut = false;+ const keep = (box: SlideBox): boolean => {+ boxes.push(box);+ textLeft -= boxText(box);+ return textLeft <= 0 && (cut = true);+ };+ const addShape = (shape: Element): boolean => {+ const body = first(shape, "txBody");+ if (!body) return false;+ if (left <= 0) return (cut = true);+ const paragraphs: NonNullable<SlideBox["paragraphs"]> = [];+ const list = body.getElementsByTagNameNS("*", "p");+ for (let i = 0, p = list.item(0); p; p = list.item(++i)) {+ const text = paragraphText(p);+ if (!text.trim()) continue;+ if (paragraphs.length === left) {+ cut = true;+ break;+ }+ const runs = all(p, "r");+ const rPr = runs[0] && first(runs[0], "rPr");+ const pPr = first(p, "pPr");+ const sz = Number(rPr?.getAttribute("sz"));+ paragraphs.push({+ text,+ size: sz ? sz / 100 : undefined,+ bold: isTrue(rPr?.getAttribute("b") ?? null),+ align: pPr?.getAttribute("algn") ?? undefined,+ bullet: Boolean(pPr && (first(pPr, "buChar") || first(pPr, "buAutoNum"))),+ });+ }+ if (!paragraphs.length) return false;+ left -= paragraphs.length;+ return keep({+ frame: readFrame(shape, cx, cy),+ placeholder: first(shape, "ph")?.getAttribute("type") ?? (first(shape, "ph") ? "body" : undefined),+ paragraphs,+ });+ };+ const addFrame = (frame: Element): boolean => {+ if (left <= 0) return (cut = true);+ const place = () => readFrame(frame, cx, cy) ?? { x: 0.05, y: 0.25, w: 0.9, h: 0.65 };+ const chartRef = first(frame, "chart");+ const chartPath = chartRef && slideRels.get(relId(chartRef, "id") ?? "");+ const chartDoc = chartPath ? partDoc(chartPath) : null;+ const chart = chartDoc && readChart(chartDoc, left);+ if (chart) {+ left -= chart.table.reduce((n, row) => n + row.length, 0);+ if (keep({ frame: place(), ...chart })) return true;+ }+ const diagramRef = first(frame, "relIds");+ const diagramPath = diagramRef && slideRels.get(relId(diagramRef, "dm") ?? "");+ const diagramDoc = diagramPath ? partDoc(diagramPath) : null;+ const diagram = diagramDoc && left > 0 ? readDiagram(diagramDoc, left) : [];+ if (diagram.length) {+ left -= diagram.length;+ if (keep({ frame: place(), paragraphs: diagram })) return true;+ }+ const tbl = first(frame, "tbl");+ if (!tbl || left <= 0) return false;+ const table = readTable(tbl, left);+ if (!table.some((row) => row.some((cell) => cell.trim()))) return false;+ left -= table.reduce((n, row) => n + row.length, 0);+ return keep({ frame: place(), table });+ };+ const addPicture = (pic: Element): boolean => {+ const blip = first(pic, "blip");+ const target = blip && slideRels.get(relId(blip, "embed") ?? "");+ const type = target && pictureType(target);+ if (!target || !type) return false;+ if (left <= 0) return (cut = true);+ let picture = pictures.get(target);+ if (!picture) {+ if (pictureBytes + (read.size(target) ?? 0) > MAX_DECK_IMAGE_BYTES) {+ cut = true;+ return false;+ }+ const data = read([target])[target];+ if (!data) return false;+ const pixels = picturePixels(data);+ if (pixels === undefined) {+ cut = true;+ return false;+ }+ pictureBytes += data.length;+ picture = { image: new Blob([data as Uint8Array<ArrayBuffer>], { type }), pixels };+ pictures.set(target, picture);+ }+ if (picture.pixels > pixelsLeft) {+ cut = true;+ return false;+ }+ pixelsLeft -= picture.pixels;+ left--;+ boxes.push({ frame: readFrame(pic, cx, cy), image: picture.image, crop: readCrop(pic) });+ return false;+ };+ const walk = (parent: Element): boolean => {+ for (let node = parent.firstElementChild; node; node = node.nextElementSibling) {+ const name = node.localName;+ const branch =+ name === "AlternateContent" ? (children(node, "Fallback")[0] ?? children(node, "Choice")[0]) : undefined;+ const stop =+ name === "grpSp"+ ? walk(node)+ : branch+ ? walk(branch)+ : name === "sp"+ ? addShape(node)+ : name === "graphicFrame"+ ? addFrame(node)+ : name === "pic" && images+ ? addPicture(node)+ : false;+ if (stop) return true;+ }+ return false;+ };+ const tree = first(doc, "spTree");+ if (tree) walk(tree);+ if (cut) boxes.push({ paragraphs: [{ text: "…" }] });+ slides.push({ boxes });+ if (textLeft <= 0) {+ truncated = index < slidePaths.length - 1;+ break;+ }+ }+ return { aspect: cy / cx, widthPt: cx / 12700, slides, truncated };+}diff --git a/studio/frontend/src/components/file-viewer/pdf-view.tsx b/studio/frontend/src/components/file-viewer/pdf-view.tsxnew file mode 100644index 00000000000..b475d2b0bf9--- /dev/null+++ b/studio/frontend/src/components/file-viewer/pdf-view.tsx@@ -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 { Spinner } from "@/components/ui/spinner";+import { useT } from "@/i18n";+import { useVirtualizer } from "@tanstack/react-virtual";+import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";+import { Document, Page, pdfjs, usePageContext } from "react-pdf";+import "react-pdf/dist/Page/TextLayer.css";+import { useWidth } from "./use-width";++pdfjs.GlobalWorkerOptions.workerSrc = new URL(+ "pdfjs-dist/build/pdf.worker.min.mjs",+ import.meta.url,+).toString();++const MAX_PAGE_WIDTH = 880;+const PAGE_GAP = 16;+const EDGE = 24;+const MAX_CANVAS_PIXELS = 32 * 1024 * 1024;+const MAX_CANVAS_SIDE = 16384;+// PDF.js skips larger images before decoding; a 600dpi letter/A4 scan still fits.+const PDF_OPTIONS = { maxImageSize: 64 * 1024 * 1024 };+const MIN_PIXEL_RATIO = 0.1;+const MAX_TEXT_ITEMS = 20_000;+const MAX_PAGE_OPERATIONS = 1_000_000;+const MAX_PDF_PAGES = 10_000;+const clampAspect = (aspect: number) => Math.min(Math.max(aspect, 0.05), 20);++type PdfDocument = {+ getPage(page: number): Promise<{+ getViewport(options: { scale: number }): { width: number; height: number };+ streamTextContent(): ReadableStream<{ items: unknown[] }>;+ }>;+};++const overflowed = new WeakMap<object, Set<number>>();+const PageOverflow = createContext<() => void>(() => {});++function PdfCanvas() {+ const context = usePageContext();+ const onOverflow = useContext(PageOverflow);+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const page = context?.page;+ const scale = context?.scale ?? 1;+ const rotate = context?.rotate ?? 0;+ const ratio = context?.devicePixelRatio ?? 1;+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!page || !canvas) return;+ const viewport = page.getViewport({ scale: scale * ratio, rotation: rotate });+ const shown = page.getViewport({ scale, rotation: rotate });+ canvas.width = viewport.width;+ canvas.height = viewport.height;+ canvas.style.width = `${Math.floor(shown.width)}px`;+ canvas.style.height = `${Math.floor(shown.height)}px`;+ let over = false;+ const task = page.render({+ canvas,+ canvasContext: canvas.getContext("2d", { alpha: false })!,+ viewport,+ annotationMode: pdfjs.AnnotationMode.ENABLE,+ operationsFilter: (index) => {+ if (index < MAX_PAGE_OPERATIONS) return true;+ if (!over) {+ over = true;+ queueMicrotask(() => task.cancel());+ }+ return false;+ },+ });+ task.promise.catch(() => {+ if (!over) return;+ page.cleanup();+ onOverflow();+ });+ return () => {+ task.cancel();+ page.cleanup();+ canvas.width = 0;+ canvas.height = 0;+ };+ }, [page, scale, rotate, ratio, onOverflow]);+ return <canvas ref={canvasRef} className="block select-none" />;+}++function PdfPage({ pdf, index, width, aspect }: { pdf: PdfDocument; index: number; width: number; aspect: number }) {+ const t = useT();+ const [own, setOwn] = useState<{ index: number; aspect: number } | null>(null);+ useEffect(() => {+ let live = true;+ pdf.getPage(index + 1).then(+ (page) => {+ const viewport = page.getViewport({ scale: 1 });+ if (live) setOwn({ index, aspect: viewport.height / viewport.width });+ },+ () => live && setOwn({ index, aspect: Number.NaN }),+ );+ return () => {+ live = false;+ };+ }, [pdf, index]);+ const [selectable, setSelectable] = useState<number | null>(null);+ useEffect(() => {+ let live = true;+ let reader: ReadableStreamDefaultReader<{ items: unknown[] }> | undefined;+ void (async () => {+ reader = (await pdf.getPage(index + 1)).streamTextContent().getReader();+ let items = 0;+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {+ items += chunk.value.items.length;+ if (!live || items > MAX_TEXT_ITEMS) return;+ }+ if (live) setSelectable(index);+ })()+ .catch(() => {})+ .finally(() => void reader?.cancel().catch(() => {}));+ return () => {+ live = false;+ };+ }, [pdf, index]);+ const [tooLong, setTooLong] = useState<number | null>(null);+ const markOverflow = useCallback(() => {+ const pages = overflowed.get(pdf) ?? new Set<number>();+ overflowed.set(pdf, pages.add(index));+ setTooLong(index);+ }, [pdf, index]);+ const pageAspect = own?.index === index ? own.aspect : null;+ if (pageAspect === null) return <div style={{ height: width * aspect }} />;+ const height = width * pageAspect;+ const ratio = Math.min(+ window.devicePixelRatio || 1,+ Math.sqrt(MAX_CANVAS_PIXELS / (width * height)),+ MAX_CANVAS_SIDE / width,+ MAX_CANVAS_SIDE / height,+ );+ if (!(ratio >= MIN_PIXEL_RATIO) || tooLong === index || overflowed.get(pdf)?.has(index)) {+ return (+ <p className="flex items-center justify-center text-sm text-muted-foreground" style={{ height: width * clampAspect(pageAspect) }}>+ {t("library.preview.cannotPreview")}+ </p>+ );+ }+ return (+ <PageOverflow.Provider value={markOverflow}>+ <Page+ pageNumber={index + 1}+ width={width}+ devicePixelRatio={ratio}+ renderMode="custom"+ customRenderer={PdfCanvas}+ renderAnnotationLayer={false}+ renderTextLayer={selectable === index}+ loading={<div style={{ height }} />}+ />+ </PageOverflow.Provider>+ );+}++function PdfPages({+ pdf,+ pages,+ width,+ aspect,+ scrollElement,+}: {+ pdf: PdfDocument;+ pages: number;+ width: number;+ aspect: number;+ scrollElement: HTMLElement | null;+}) {+ // eslint-disable-next-line react-hooks/incompatible-library+ const virtualizer = useVirtualizer({+ count: pages,+ getScrollElement: () => scrollElement,+ estimateSize: () => width * aspect + PAGE_GAP,+ paddingStart: EDGE,+ paddingEnd: EDGE - PAGE_GAP,+ overscan: 2,+ });+ return (+ <div className="relative mx-auto" style={{ width, height: virtualizer.getTotalSize() }}>+ {virtualizer.getVirtualItems().map((item) => (+ <div+ key={item.key}+ data-index={item.index}+ ref={virtualizer.measureElement}+ className="absolute top-0 left-0 w-full"+ style={{ transform: `translateY(${item.start}px)`, paddingBottom: PAGE_GAP }}+ >+ <div className="bg-white shadow-sm ring-1 ring-black/5" style={{ minHeight: width * aspect }}>+ <PdfPage pdf={pdf} index={item.index} width={width} aspect={aspect} />+ </div>+ </div>+ ))}+ </div>+ );+}++export default function PdfView({ file, scale }: { file: Blob; scale: number }) {+ const t = useT();+ const [container, setContainer] = useState<HTMLDivElement | null>(null);+ const available = useWidth(container);+ const [pdf, setPdf] = useState<PdfDocument | null>(null);+ const [pages, setPages] = useState(0);+ const [aspect, setAspect] = useState(1.294);+ const [failed, setFailed] = useState<Blob | null>(null);+ const width = Math.max(200, Math.min(available, MAX_PAGE_WIDTH)) * scale;++ if (failed === file) {+ return <p className="m-auto text-sm text-muted-foreground">{t("library.preview.cannotPreview")}</p>;+ }+ return (+ <div ref={setContainer} className="size-full overflow-auto bg-muted/60">+ <Document+ file={file}+ options={PDF_OPTIONS}+ onLoadSuccess={(document) => {+ setPdf(document);+ setPages(document.numPages);+ void document.getPage(1).then((page) => {+ const viewport = page.getViewport({ scale: 1 });+ setAspect(clampAspect(viewport.height / viewport.width));+ });+ }}+ onLoadError={() => setFailed(file)}+ loading={<Spinner className="mx-auto mt-24 size-6" />}+ >+ {available > 0 && pdf && (+ <PdfPages+ key={`${width}:${aspect}`}+ pdf={pdf}+ pages={Math.min(pages, MAX_PDF_PAGES)}+ width={width}+ aspect={aspect}+ scrollElement={container}+ />+ )}+ {available > 0 && pdf && pages > MAX_PDF_PAGES && (+ <p className="pb-6 text-center text-ui-12 text-muted-foreground">{t("library.preview.documentTruncated")}</p>+ )}+ </Document>+ </div>+ );+}diff --git a/studio/frontend/src/components/file-viewer/use-width.ts b/studio/frontend/src/components/file-viewer/use-width.tsnew file mode 100644index 00000000000..fe8b9496376--- /dev/null+++ b/studio/frontend/src/components/file-viewer/use-width.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useLayoutEffect, useState } from "react";++export function useWidth(element: HTMLElement | null): number {+ const [width, setWidth] = useState(0);+ useLayoutEffect(() => {+ if (!element) return;+ const measure = () => setWidth(element.clientWidth);+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(element);+ return () => observer.disconnect();+ }, [element]);+ return width;+}diff --git a/studio/frontend/src/components/media-viewer.tsx b/studio/frontend/src/components/media-viewer.tsxindex 161c1d284da..631fa2e1bd1 100644--- a/studio/frontend/src/components/media-viewer.tsx+++ b/studio/frontend/src/components/media-viewer.tsx@@ -119,6 +119,8 @@ export function MediaViewer({actions,extra,onKeyDown,+ flush = false,+ redactFromReload = false,children,}: {open: boolean;@@ -130,6 +132,8 @@ export function MediaViewer({actions: MediaViewerActions;extra?: ReactNode;onKeyDown?: KeyboardEventHandler<HTMLDivElement>;+ flush?: boolean;+ redactFromReload?: boolean;children: ReactNode;}) {const t = useT();@@ -157,6 +161,7 @@ export function MediaViewer({<Dialog open={open} onOpenChange={onOpenChange}><DialogContentshowCloseButton={false}+ data-reload-snapshot-sensitive={redactFromReload ? "" : undefined}onKeyDown={onKeyDown}onOpenAutoFocus={() => {const active = document.activeElement;@@ -168,7 +173,7 @@ export function MediaViewer({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"+ 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 rounded-[1.5rem] 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">@@ -257,7 +262,7 @@ export function MediaViewer({</button></DialogClose></div>- <div className={cn("flex min-h-0 flex-1", media ? "px-4 pb-4" : "px-6 pb-6")}>+ <div className={cn("flex min-h-0 flex-1", !flush && (media ? "px-4 pb-4" : "px-6 pb-6"))}>{media ? (<MediaZoomStage zoom={zoom} onFitScale={setFitScale}>{children}diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 66794c55e4b..1e3aef0abab 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -1,7 +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 { authFetch } from "@/features/auth";+import { authFetch, getAuthSessionEpoch } from "@/features/auth";import { prepareHfTokenForUse } from "@/features/hf-auth";// These helpers are deliberately API-layer-only, not part of their features' public barrels.// eslint-disable-next-line no-restricted-imports@@ -855,7 +855,25 @@ export async function listChatAttachments(};}-/** Stored attachment content (image bytes or extracted text) as a Blob. */+export async function uploadChatAttachmentOriginal(+ file: File,+ epoch = getAuthSessionEpoch(),+): Promise<{ sha256: string; sizeBytes: number }> {+ const sameAccount = () => {+ if (getAuthSessionEpoch() !== epoch) throw new Error("The account changed during the upload.");+ };+ sameAccount();+ const form = new FormData();+ form.append("file", file, file.name);+ const response = await authFetch(+ "/api/chat/attachment-originals",+ { method: "POST", body: form },+ { beforeRetry: sameAccount },+ );+ sameAccount();+ return parseJsonOrThrow<{ sha256: string; sizeBytes: number }>(response);+}+export async function fetchChatAttachmentBlob(messageId: string,attachmentId: string,diff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.tsindex 0d52dcf16a8..ffb93e6fad1 100644--- a/studio/frontend/src/features/chat/attachment-content.ts+++ b/studio/frontend/src/features/chat/attachment-content.ts@@ -1,8 +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 { type Unzipped, strFromU8, unzipSync, zipSync } from "fflate";+import { type Unzipped, strFromU8, strToU8, unzipSync, zipSync } from "fflate";import {+ MAX_TEXT_ATTACHMENT_BYTES,TEXT_ATTACHMENT_ACCEPT,decodeTextAttachmentBytes,isTextAttachmentName,@@ -18,7 +19,14 @@ import {OPEN_DOCUMENT_TEXT_MIME,} from "./open-document-accept";-export type AttachmentTextLabel = "PDF" | "DOCX" | "HTML" | "ODS" | "ODT";+export type AttachmentTextLabel =+ | "PDF"+ | "DOCX"+ | "HTML"+ | "ODS"+ | "ODT"+ | "XLSX"+ | "PPTX";export { TEXT_ATTACHMENT_ACCEPT };@@ -37,7 +45,7 @@ const PDF_ATTACHMENT_RE = /\.pdf$/i;const DOCX_ATTACHMENT_RE = /\.docx$/i;const HTML_ATTACHMENT_RE = /\.x?html?$/i;const OPEN_DOCUMENT_ATTACHMENT_RE = /\.(ods|odt)$/i;-const LABELLED_ATTACHMENT_TEXT_RE = /^\[(PDF|DOCX|HTML|ODS|ODT): [^\n]*\]\n/;+const LABELLED_ATTACHMENT_TEXT_RE = /^\[(PDF|DOCX|HTML|ODS|ODT|XLSX|PPTX): [^\n]*\]\n/;const ATTACHMENT_TAG_OPEN_RE = /^<attachment name=[^\n]*>\n/;const ATTACHMENT_TAG_CLOSE = "\n</attachment>";// Both wrappers start on the first line, so only a prefix is matched against.@@ -91,6 +99,7 @@ const XML_NAMED_ENTITIES: Record<string, string> = {* the webview. fflate allocates at the declared size and stops, so mammoth is handed a* repack of fflate's output. */const MAX_DOCX_UNPACKED_BYTES = 2 * MAX_OPEN_DOCUMENT_ARCHIVE_BYTES;+const MAX_DOCX_ENTRIES = 100_000;const AUDIO_EXTENSION_MIMES: Record<string, string> = {wav: "audio/wav",mp3: "audio/mpeg",@@ -498,7 +507,7 @@ function isTextAttachment(// loses the typed message along with the file.export function getDocumentAttachmentSizeError(file: File,- label: "PDF" | "DOCX",+ label: "PDF" | "DOCX" | "XLSX" | "PPTX",): string | null {return file.size > MAX_OPEN_DOCUMENT_ARCHIVE_BYTES? `${label} file is too large: ${file.name}`@@ -507,7 +516,7 @@ export function getDocumentAttachmentSizeError(export function assertDocumentAttachmentSize(file: File,- label: "PDF" | "DOCX",+ label: "PDF" | "DOCX" | "XLSX" | "PPTX",): void {const error = getDocumentAttachmentSizeError(file, label);if (error) {@@ -593,18 +602,73 @@ type DocxArchive = {/** Inflates the archive under fflate's declared-size allocation. An entry past the XML ceiling* is left out rather than refused: mammoth opens the package parts and whatever the* relationships point at, so a large unreferenced part must still preview.- * `assertDocxPartSizes` refuses the ones mammoth would have parsed. */-function unpackDocxEntries(filename: string, bytes: Uint8Array): DocxArchive {+ * `assertDocxPartSizes` refuses the ones mammoth would have parsed. `keepLarge` keeps them+ * (still marked oversized) for the viewer, which needs large images as well as text. */+const DOCX_IMAGE_PART = /\.(png|jpe?g|gif|bmp|tiff?|emf|wmf|svg|webp)$/i;++function docxPreviewImages(bytes: Uint8Array): { isImage: (name: string) => boolean; used: Set<string> } {+ const names = new Set<string>();+ const read = (name: string) =>+ unzipSync(bytes, {+ filter: (entry) => {+ names.add(entry.name);+ return entry.name === name && entry.originalSize <= MAX_OPEN_DOCUMENT_XML_BYTES;+ },+ })[name];+ const types = read(DOCX_CONTENT_TYPES_PART);+ const defaults = new Map<string, string>();+ const overrides = new Map<string, string>();+ const markup = types ? strFromU8(types).replace(XML_NON_ELEMENT_RE, "") : "";+ for (const [, tag, attributes] of markup.matchAll(/<(?:[\w.-]+:)?(Default|Override)\b([^>]*)>/g)) {+ const values = new Map<string, string>();+ for (const [, key, double, single] of attributes!.matchAll(XML_ATTRIBUTE_RE)) {+ values.set(key!, double ?? single ?? "");+ }+ const type = (values.get("ContentType") ?? "").toLowerCase();+ if (tag === "Default") defaults.set((values.get("Extension") ?? "").toLowerCase(), type);+ else overrides.set((values.get("PartName") ?? "").replace(/^\//, "").toLowerCase(), type);+ }+ const isImage = (name: string) => {+ const dot = name.lastIndexOf(".");+ const type =+ overrides.get(name.toLowerCase()) ?? (dot === -1 ? undefined : defaults.get(name.slice(dot + 1).toLowerCase()));+ return type ? type.startsWith("image/") : DOCX_IMAGE_PART.test(name);+ };+ const targetsOf = (path: string) =>+ readDocxXmlTargets(read(docxRelationshipsPath(path)), path.slice(0, Math.max(0, path.lastIndexOf("/"))));+ const resolve = (targets: string[] | undefined, fallback: string) =>+ targets?.find((path) => names.has(path)) ?? fallback;+ const main = resolve(targetsOf("").get(DOCX_MAIN_DOCUMENT_TYPE), DOCX_MAIN_DOCUMENT_FALLBACK);+ const mainTargets = targetsOf(main);+ const used = new Set([...mainTargets.values()].flat());+ for (const name of DOCX_BODY_PART_NAMES) {+ const path = resolve(mainTargets.get(`${DOCX_RELATIONSHIP_NAMESPACE}${name}`), `word/${name}.xml`);+ for (const target of [...targetsOf(path).values()].flat()) used.add(target);+ }+ return { isImage, used };+}++function unpackDocxEntries(filename: string, bytes: Uint8Array, keepLarge = false): DocxArchive {const names = new Set<string>();const oversized = new Set<string>();+ let count = 0;+ unzipSync(bytes, {+ filter: () => {+ if (++count > MAX_DOCX_ENTRIES) throw new Error(`DOCX file is too large: ${filename}`);+ return false;+ },+ });+ const images = keepLarge ? docxPreviewImages(bytes) : null;let unpacked = 0;const entries = unzipSync(bytes, {filter: (entry) => {names.add(entry.name);+ const image = images?.isImage(entry.name) ?? false;+ if (image && !images!.used.has(entry.name)) return false;if (entry.originalSize > MAX_OPEN_DOCUMENT_XML_BYTES) {oversized.add(entry.name);- return false;+ if (!image) return false;}unpacked += entry.originalSize;if (unpacked > MAX_DOCX_UNPACKED_BYTES) {@@ -620,7 +684,7 @@ function unpackDocxEntries(filename: string, bytes: Uint8Array): DocxArchive {/** Refuses the parts mammoth goes on to parse when they exceed the XML ceiling. mammoth takes* no entry filter, so the set is resolved as findPartPaths resolves it, each falling back* to a fixed name when no target resolves. Both sides read the same bytes. */-function assertDocxPartSizes(filename: string, archive: DocxArchive): void {+function assertDocxPartSizes(filename: string, archive: DocxArchive): string {const { entries, names, oversized } = archive;const bound = (path: string) => {if (oversized.has(path)) {@@ -658,6 +722,7 @@ function assertDocxPartSizes(filename: string, archive: DocxArchive): void {bound(docxRelationshipsPath(path));}}+ return mainDocument;}/** The archive mammoth is given: fflate's own output, so a part that lies about its size@@ -671,6 +736,44 @@ export function repackDocxAttachmentArchive(return zipSync(archive.entries, { level: 0 });}+const XML_TOKEN_RE =+ /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<[?!][\s\S]*?>|<(\/?)([^\s/>]+)(?:\s+[^\s=/>]+\s*=\s*(?:"[^"]*"|'[^']*'))*\s*(\/?)>/g;+const PARAGRAPH_RE = /<(?:[\w.-]+:)?p[\s/>]/;++function cutDocxParagraphs(xml: string, max: number): string | null {+ const open: string[] = [];+ let count = 0;+ XML_TOKEN_RE.lastIndex = 0;+ for (let match = XML_TOKEN_RE.exec(xml); match; match = XML_TOKEN_RE.exec(xml)) {+ const [, closing, name, empty] = match;+ if (!name) continue;+ if (!closing && !empty) {+ open.push(name);+ continue;+ }+ if (closing) open.pop();+ if (/(?:^|:)p$/.test(name) && ++count === max) {+ const end = XML_TOKEN_RE.lastIndex;+ if (!PARAGRAPH_RE.test(xml.slice(end))) return null;+ return `${xml.slice(0, end)}${open.reverse().map((tag) => `</${tag}>`).join("")}`;+ }+ }+ return null;+}++export function repackDocxPreviewArchive(+ filename: string,+ bytes: Uint8Array,+ maxParagraphs: number,+): { archive: Uint8Array; truncated: boolean } {+ const archive = unpackDocxEntries(filename, bytes, true);+ const mainDocument = assertDocxPartSizes(filename, archive);+ const main = archive.entries[mainDocument];+ const cut = main ? cutDocxParagraphs(strFromU8(main), maxParagraphs) : null;+ if (cut !== null) archive.entries[mainDocument] = strToU8(cut);+ return { archive: zipSync(archive.entries, { level: 0 }), truncated: cut !== null };+}+/** The bytes of a view, as an ArrayBuffer, without copying when it owns one. jszip reads the* whole buffer and looks for the end-of-directory record at its tail, so a view that does* not span its buffer would arrive as a corrupt archive. */@@ -729,6 +832,92 @@ export async function extractPdfAttachmentText(file: File): Promise<string> {}}+// A text attachment's limit, in UTF-8 bytes. Cells are not capped, so the total must be.+const MAX_OFFICE_TEXT_BYTES = MAX_TEXT_ATTACHMENT_BYTES;++function utf8Within(text: string, limit: number): { bytes: number; end: number } {+ let bytes = 0;+ for (let i = 0; i < text.length; i++) {+ const code = text.charCodeAt(i);+ const pair = code >= 0xd800 && code < 0xdc00 && i + 1 < text.length;+ const size = code < 0x80 ? 1 : code < 0x800 ? 2 : pair ? 4 : 3;+ if (bytes + size > limit) return { bytes, end: i };+ bytes += size;+ if (pair) i++;+ }+ return { bytes, end: text.length };+}++function textBudget(limit: number) {+ let left = limit;+ let cut = false;+ return {+ take(text: string): string {+ if (cut) return "";+ const { bytes, end } = utf8Within(text, Math.max(0, left - 1));+ if (end < text.length) cut = true;+ left -= bytes + 1;+ return text.slice(0, end);+ },+ get cut() {+ return cut;+ },+ };+}++export async function extractOfficeAttachmentText(+ file: File,+ label: "XLSX" | "PPTX",+): Promise<string> {+ assertDocumentAttachmentSize(file, label);+ const [{ MAX_SHEET_COLUMNS, MAX_SHEET_ROWS, readPptx, readXlsx }, buffer] = await Promise.all([+ import("@/components/file-viewer/office"),+ file.arrayBuffer(),+ ]);+ const bytes = new Uint8Array(buffer);+ const budget = textBudget(MAX_OFFICE_TEXT_BYTES);+ const parts: string[] = [];+ if (label === "PPTX") {+ const deck = readPptx(bytes, { images: false });+ for (const [index, slide] of deck.slides.entries()) {+ if (budget.cut) break;+ const lines = [budget.take(`Slide ${index + 1}`)];+ for (const box of slide.boxes) {+ for (const p of box.paragraphs ?? []) lines.push(budget.take(p.text));+ if (box.caption) lines.push(budget.take(box.caption));+ for (const row of box.table ?? []) lines.push(row.map((cell) => budget.take(cell)).join("\t"));+ }+ parts.push(lines.join("\n"));+ }+ if (deck.truncated && !budget.cut) {+ parts.push(`[Truncated: only the first ${deck.slides.length} slides are included.]`);+ }+ } else {+ for (const sheet of readXlsx(bytes)) {+ if (budget.cut) break;+ const lines = [budget.take(`Sheet: ${sheet.name}`)];+ for (const row of sheet.rows) {+ if (!row || budget.cut) continue;+ const line = Array.from(row, (cell) => budget.take(cell?.text ?? ""))+ .filter((_, index) => !sheet.hidden?.columns.has(index))+ .join("\t")+ .trimEnd();+ if (line) lines.push(line);+ }+ if (sheet.truncated) {+ lines.push(+ `[Truncated: only part of the workbook is included, at most ${MAX_SHEET_ROWS} rows and ${MAX_SHEET_COLUMNS} columns per sheet.]`,+ );+ }+ parts.push(lines.join("\n"));+ }+ }+ if (budget.cut) {+ parts.push(`[Truncated: the text stops after ${MAX_OFFICE_TEXT_BYTES.toLocaleString("en-US")} bytes.]`);+ }+ return parts.join("\n\n");+}+export async function extractDocxAttachmentText(file: File): Promise<string> {assertDocumentAttachmentSize(file, "DOCX");const [{ default: mammoth }, buffer] = await Promise.all([@@ -861,13 +1050,28 @@ async function readBoundedText(// adapter's header rather than showing it. The stored payload has no size limit, so the// wrapper is matched on a prefix and only the capped body is copied out.export function parseAttachmentText(raw: string): AttachmentText {+ const { label, start, end } = attachmentBodyRange(raw);+ return { label, ...sliceAttachmentBody(raw, start, end) };+}++export function attachmentBodyText(raw: string): string {+ const { start, end } = attachmentBodyRange(raw);+ return raw.slice(start, Math.max(start, end));+}++function attachmentBodyRange(raw: string): {+ label: AttachmentTextLabel | null;+ start: number;+ end: number;+} {const head = raw.slice(0, MAX_ATTACHMENT_WRAPPER_LENGTH);const labelled = head.match(LABELLED_ATTACHMENT_TEXT_RE);if (labelled) {return {label: labelled[1] as AttachmentTextLabel,- ...sliceAttachmentBody(raw, labelled[0].length, raw.length),+ start: labelled[0].length,+ end: raw.length,};}@@ -875,15 +1079,12 @@ export function parseAttachmentText(raw: string): AttachmentText {if (tagOpen && raw.endsWith(ATTACHMENT_TAG_CLOSE)) {return {label: null,- ...sliceAttachmentBody(- raw,- tagOpen[0].length,- raw.length - ATTACHMENT_TAG_CLOSE.length,- ),+ start: tagOpen[0].length,+ end: raw.length - ATTACHMENT_TAG_CLOSE.length,};}- return { label: null, ...sliceAttachmentBody(raw, 0, raw.length) };+ return { label: null, start: 0, end: raw.length };}function sliceAttachmentBody(diff --git a/studio/frontend/src/features/chat/attachment-originals.ts b/studio/frontend/src/features/chat/attachment-originals.tsnew file mode 100644index 00000000000..bd6bf776979--- /dev/null+++ b/studio/frontend/src/features/chat/attachment-originals.ts@@ -0,0 +1,70 @@+// 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 { CompleteAttachment, PendingAttachment } from "@assistant-ui/react";+import { uploadChatAttachmentOriginal } from "./api/chat-api";++export interface ChatAttachmentOriginal {+ sha256: string;+ sizeBytes: number;+}++const ORIGINAL_EXTENSIONS = /\.(pdf|docx|xlsx|xlsm|pptx)$/i;+const ORIGINAL_TYPES: Record<string, string> = {+ "application/pdf": "pdf",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",+ "application/vnd.ms-excel.sheet.macroenabled.12": "xlsm",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",+};++function originalUpload(file: File): File | null {+ if (ORIGINAL_EXTENSIONS.test(file.name)) return file;+ const type = file.type.split(";", 1)[0]!.trim().toLowerCase();+ const extension = Object.hasOwn(ORIGINAL_TYPES, type) ? ORIGINAL_TYPES[type] : undefined;+ return extension ? new File([file], `${file.name || "document"}.${extension}`, { type: file.type }) : null;+}++export function attachmentOriginal(attachment: unknown): ChatAttachmentOriginal | null {+ const original = (attachment as { original?: unknown } | null)?.original;+ if (!original || typeof original !== "object") return null;+ const { sha256, sizeBytes } = original as Partial<ChatAttachmentOriginal>;+ return typeof sha256 === "string" && typeof sizeBytes === "number" ? { sha256, sizeBytes } : null;+}++export async function withAttachmentOriginal(+ pending: PendingAttachment,+ complete: CompleteAttachment,+ temporary: boolean,+ epoch: number,+): Promise<CompleteAttachment> {+ const upload = complete.type === "document" ? originalUpload(pending.file) : null;+ if (!upload) return complete;+ if (temporary) return { ...complete, file: pending.file } as CompleteAttachment;+ try {+ const original: ChatAttachmentOriginal = await uploadChatAttachmentOriginal(upload, epoch);+ return { ...complete, original } as CompleteAttachment;+ } catch {+ return complete;+ }+}++export async function persistAttachmentOriginals(+ attachments: readonly CompleteAttachment[] | undefined,+ epoch: number,+): Promise<CompleteAttachment[]> {+ return Promise.all(+ (attachments ?? []).map(async (attachment) => {+ const { file, ...rest } = attachment as CompleteAttachment & { file?: unknown };+ if (file === undefined) return attachment;+ const upload = file instanceof File && !attachmentOriginal(rest) ? originalUpload(file) : null;+ if (!upload) return rest as CompleteAttachment;+ try {+ const original: ChatAttachmentOriginal = await uploadChatAttachmentOriginal(upload, epoch);+ return { ...rest, original } as CompleteAttachment;+ } catch {+ return rest as CompleteAttachment;+ }+ }),+ );+}diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 1270e0e270a..da0241d6d95 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -285,8 +285,11 @@ export {attachmentTextLanguage,countAttachmentTextLines,isAudioAttachment,+ attachmentBodyText,parseAttachmentText,readAttachmentText,+ repackDocxAttachmentArchive,+ repackDocxPreviewArchive,truncateAttachmentPreviewText,} from "./attachment-content";export { ApiProviderLogo } from "./api-provider-logo";@@ -505,3 +508,4 @@ export {type ComposerFollowUpBehavior,type ComposerSubmitIntent,} from "./utils/composer-preferences";+export { isTextAttachmentName } from "./text-attachment-accept";diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 0f948e2a00f..94a6330d6c5 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -2,7 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { useAppShellReadySignal } from "@/components/app-readiness";-import { authFetch } from "@/features/auth";+import { authFetch, getAuthSessionEpoch } from "@/features/auth";import {classifiedAttachmentFile,needsAttachmentTrackInspection,@@ -60,10 +60,12 @@ import {TEXT_ATTACHMENT_ACCEPT,extractDocxAttachmentText,extractHtmlAttachmentText,+ extractOfficeAttachmentText,extractPdfAttachmentText,getDocumentAttachmentSizeError,getDocxAttachmentError,} from "./attachment-content";+import { persistAttachmentOriginals, withAttachmentOriginal } from "./attachment-originals";import { AudioAttachmentAdapter } from "./audio-attachment-adapter";import {isBinaryPropertyList,@@ -265,8 +267,10 @@ class PreStreamAwareAttachmentAdapter implements AttachmentAdapter {async send(attachment: PendingAttachment): Promise<CompleteAttachment> {const threadIds = this.getThreadIds();const reservationToken = findPreStreamRunReservation(threadIds);+ const { incognito } = useChatRuntimeStore.getState();+ const epoch = getAuthSessionEpoch();try {- return await this.delegate.send(attachment);+ return await withAttachmentOriginal(attachment, await this.delegate.send(attachment), incognito, epoch);} catch (error) {if (reservationToken &&@@ -570,6 +574,76 @@ class DocxAttachmentAdapter implements AttachmentAdapter {}}+const OFFICE_LABELS: Record<string, "XLSX" | "PPTX"> = {+ xlsx: "XLSX",+ xlsm: "XLSX",+ pptx: "PPTX",+};++class OfficeAttachmentAdapter implements AttachmentAdapter {+ accept = [+ ".xlsx,.xlsm,.pptx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ "application/vnd.ms-excel.sheet.macroEnabled.12",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ ].join(",");++ private label(name: string, type: string): "XLSX" | "PPTX" {+ const extension = name.split(".").pop()?.toLowerCase() ?? "";+ const byName = Object.hasOwn(OFFICE_LABELS, extension) ? OFFICE_LABELS[extension] : undefined;+ return byName ?? (type.includes("presentationml") ? "PPTX" : "XLSX");+ }++ // Read at add: the composer drops the typed message before send(), so refuse unreadable files here.+ private readonly texts = new Map<string, string>();++ async add({ file }: { file: File }): Promise<PendingAttachment> {+ const label = this.label(file.name, file.type);+ let text: string;+ try {+ text = await extractOfficeAttachmentText(file, label);+ } catch (cause) {+ const message = (cause as Error | undefined)?.message;+ const tooLarge = `${label} file is too large: ${file.name}`;+ const error =+ message === tooLarge || message === "File is too large to preview."+ ? tooLarge+ : `${label} file could not be read: ${file.name}`;+ toast.error(error);+ throw new Error(error);+ }+ const id = crypto.randomUUID();+ this.texts.set(id, text);+ return {+ id,+ type: "document",+ name: file.name,+ contentType: file.type,+ file,+ status: { type: "requires-action", reason: "composer-send" },+ };+ }++ async send(attachment: PendingAttachment): Promise<CompleteAttachment> {+ const label = this.label(attachment.name, attachment.contentType ?? "");+ const text = this.texts.get(attachment.id) ?? (await extractOfficeAttachmentText(attachment.file, label));+ this.texts.delete(attachment.id);+ return {+ id: attachment.id,+ type: "document",+ name: attachment.name,+ contentType: attachment.contentType,+ content: [{ type: "text", text: `[${label}: ${attachment.name}]\n${text}` }],+ status: { type: "complete" },+ };+ }++ remove(attachment: Attachment): Promise<void> {+ this.texts.delete(attachment.id);+ return Promise.resolve();+ }+}+class OpenDocumentAttachmentAdapter implements AttachmentAdapter {private readonly active = new Set<string>();private readonly sending = new Set<string>();@@ -774,7 +848,7 @@ function cloneAttachments(if (!Array.isArray(attachments)) {return [];}- return JSON.parse(JSON.stringify(attachments));+ return JSON.parse(JSON.stringify(attachments.map((attachment) => ({ ...attachment, file: undefined }))));}function toThreadMessage(m: MessageRecord): ThreadMessage {@@ -1398,9 +1472,13 @@ export async function persistTemporaryThread({createdAt:creation?.createdAt ?? (times.length > 0 ? Math.min(...times) : Date.now()),});- const records: MessageRecord[] = parentsFirst(messages).map(({ parentId, message }) => {+ const epoch = getAuthSessionEpoch();+ const records: MessageRecord[] = await Promise.all(parentsFirst(messages).map(async ({ parentId, message }) => {+ // Documents kept in memory are uploaded now, before the File is lost to JSON.const attachments =- message.role === "user" ? cloneAttachments(message.attachments) : [];+ message.role === "user"+ ? cloneAttachments(await persistAttachmentOriginals(message.attachments, epoch))+ : [];const metadata = message.metadata?.custom as| Record<string, unknown>| undefined;@@ -1414,7 +1492,7 @@ export async function persistTemporaryThread({...(metadata && { metadata }),createdAt: message.createdAt?.getTime?.() ?? Date.now(),};- });+ }));await syncStoredChatMessages(threadId, records, { pruneMissing: false });temporaryThreadCreation.delete(threadId);} catch (error) {@@ -2415,6 +2493,7 @@ function useStudioRuntimeAdapters(new HtmlAttachmentAdapter(),new PDFAttachmentAdapter(),new DocxAttachmentAdapter(),+ new OfficeAttachmentAdapter(),new OpenDocumentAttachmentAdapter(),]),() => {diff --git a/studio/frontend/src/features/library/api.ts b/studio/frontend/src/features/library/api.tsindex e5bf67b58c9..7886430f460 100644--- a/studio/frontend/src/features/library/api.ts+++ b/studio/frontend/src/features/library/api.ts@@ -24,6 +24,9 @@ export interface LibraryItem {fileUrl: string;threadId: string | null;threadTitle: string | null;+ pairId?: string | null;+ projectId?: string | null;+ runId?: string | null;textOnly: boolean;favorite: boolean;folderId: string | null;diff --git a/studio/frontend/src/features/library/components/library-actions.tsx b/studio/frontend/src/features/library/components/library-actions.tsxindex 4252cc5302f..474b75b089a 100644--- a/studio/frontend/src/features/library/components/library-actions.tsx+++ b/studio/frontend/src/features/library/components/library-actions.tsx@@ -14,6 +14,7 @@ import {import { useT } from "@/i18n";import { cn } from "@/lib/utils";import {+ ArrowTurnBackwardIcon,Delete02Icon,Download01Icon,Edit03Icon,@@ -28,6 +29,7 @@ import { useMemo, useState } from "react";import type { LibraryFolder } from "../api";import { isDeletable, isFileItem, isModelItem } from "../file-kind";import { type LibraryTarget, useLibraryActions } from "../actions-context";+import { useLibraryOrigin } from "../origin";import { canReveal, revealInFolder, useRevealLabel } from "../reveal";import { OVERLAY_CONTROL } from "../surface";@@ -84,6 +86,8 @@ export function LibraryActionsMenu({const inFolder = currentFolderId(target);const item = target.kind === "item" ? target.item : null;const revealLabel = useRevealLabel();+ const originOf = useLibraryOrigin();+ const origin = item ? originOf(item) : null;return (<DropdownMenu open={open} onOpenChange={setOpen}>@@ -116,6 +120,12 @@ export function LibraryActionsMenu({<HugeiconsIcon icon={MessageCircleIcon} strokeWidth={1.75} className={ICON} />{t(item && isModelItem(item) ? "library.menu.chatWithModel" : "library.menu.chatAboutThis")}</DropdownMenuItem>+ {origin && (+ <DropdownMenuItem onSelect={origin.open}>+ <HugeiconsIcon icon={ArrowTurnBackwardIcon} strokeWidth={1.75} className={ICON} />+ {t(origin.label)}+ </DropdownMenuItem>+ )}{item && (<DropdownMenuItem onSelect={() => actions.toggleFavorite(item)}><HugeiconsIcondiff --git a/studio/frontend/src/features/library/components/library-cards.tsx b/studio/frontend/src/features/library/components/library-cards.tsxindex 50fbdec5015..8f2965ead25 100644--- a/studio/frontend/src/features/library/components/library-cards.tsx+++ b/studio/frontend/src/features/library/components/library-cards.tsx@@ -142,7 +142,7 @@ function CardFrame({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",+ selected && "ring-2 ring-foreground",className,)}>diff --git a/studio/frontend/src/features/library/components/library-preview.tsx b/studio/frontend/src/features/library/components/library-preview.tsxindex 5e2a7aa812d..2f1066df9ef 100644--- a/studio/frontend/src/features/library/components/library-preview.tsx+++ b/studio/frontend/src/features/library/components/library-preview.tsx@@ -3,20 +3,21 @@import { CodeToggleIcon } from "@/components/assistant-ui/code-toggle-icon";import { CodeSourceView } from "@/components/code-source-view";+import { DocumentView, documentKind, isMarkdown, sheetDelimiter } from "@/components/file-viewer";+import { MarkdownPreview } from "@/components/markdown/markdown-preview";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 { useBlocker } 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 ReactNode, useEffect, useMemo, useRef, useState } from "react";import {type LibraryItem,addLibraryItemToProject,@@ -33,8 +34,9 @@ import {modelLabelKey,} from "../file-kind";import { formatCardTime, formatSize } from "../format";-import { type EmbeddedBody, hasOwnFile, itemVersion } from "../file-name";-import { useLibraryPreviewUrl } from "../hooks";+import { type EmbeddedBody, fileExtension, hasOwnFile, itemVersion } from "../file-name";+import { useLibraryDocument, useLibraryPreviewUrl } from "../hooks";+import { useLibraryOrigin } from "../origin";import { type NoteFormat, type NoteReadOnlyReason, encodeNote } from "../note-text";import { canReveal, revealInFolder, useRevealLabel } from "../reveal";import { KindIcon } from "./library-cards";@@ -44,32 +46,64 @@ 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";+type Body =+ | "image"+ | "web"+ | "text"+ | "markdown"+ | "document"+ | "audio"+ | "video"+ | "model"+ | "none";++const CODE_LANGUAGES: Record<string, string> = {+ py: "python",+ js: "javascript",+ jsx: "jsx",+ ts: "typescript",+ tsx: "tsx",+ json: "json",+ sh: "bash",+ css: "css",+ sql: "sql",+ yaml: "yaml",+ yml: "yaml",+ xml: "xml",+};++function ownName(item: LibraryItem): string {+ return item.fileName ?? item.name;+}function bodyFor(item: LibraryItem): Body {if (item.model) return "model";if (hasImagePreview(item)) return "image";- if (item.textOnly) return "text";+ if (item.textOnly) {+ if (isMarkdown(ownName(item), item.contentType)) return "markdown";+ return sheetDelimiter(ownName(item), item.contentType) ? "document" : "text";+ }+ if (documentKind(ownName(item), item.contentType)) return "document";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;+ if (isMarkdown(ownName(item), item.contentType)) return "markdown";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 hasSource(item: LibraryItem, body: Body): boolean {+ if (body === "web" || body === "markdown") return true;+ return body === "document" && sheetDelimiter(ownName(item), item.contentType) !== null;+}++function viewFor(item: LibraryItem, showCode: boolean): Body {+ const body = bodyFor(item);+ return showCode && body !== "web" && hasSource(item, body) ? "text" : body;}function isEditable(item: LibraryItem): boolean {- return item.id.startsWith("upload:") && bodyFor(item) === "text";+ const body = bodyFor(item);+ return item.id.startsWith("upload:") && (body === "text" || (body !== "web" && hasSource(item, body)));}interface LoadedText {@@ -149,11 +183,30 @@ function ModelDetails({ item }: { item: LibraryItem }) {);}+const ZOOMABLE: ReadonlySet<Body> = new Set(["web", "document", "markdown", "text"]);++function Zoomed({ scale, children }: { scale: number; children: ReactNode }) {+ return (+ <div className="size-full overflow-hidden">+ <div+ className="origin-top-left"+ style={{+ width: `${100 / scale}%`,+ height: `${100 / scale}%`,+ transform: `scale(${scale})`,+ }}+ >+ {children}+ </div>+ </div>+ );+}+function TextPrefix({ text, className }: { text: string; className?: string }) {return (<preclassName={cn(- "size-full overflow-auto whitespace-pre-wrap break-words font-mono text-sm leading-relaxed",+ "size-full overflow-auto whitespace-pre-wrap break-words px-6 pb-6 font-mono text-sm leading-relaxed",className,)}>@@ -240,12 +293,12 @@ function PreviewBody({onDownload?: () => void;}) {const t = useT();- const body = bodyFor(item);+ const body = viewFor(item, showCode);const embedded: EmbeddedBody | null =- !mediaFailed && (body === "image" || body === "pdf" || body === "audio" || body === "video")- ? body- : null;+ !mediaFailed && (body === "image" || body === "audio" || body === "video") ? body : null;const { url, error: urlError, retry } = useLibraryPreviewUrl(item, embedded);+ const doc = useLibraryDocument(item, body === "document");+ const draftFile = useMemo(() => (draft === null ? null : new Blob([draft])), [draft]);const handleMediaError = () => {if (!retry()) onMediaError();};@@ -256,11 +309,17 @@ function PreviewBody({if (mediaFailed) return noPreview(t("library.preview.cannotPreview"));if (urlError) return noPreview(urlError);+ if (doc.error) return noPreview(doc.error);if (textError) return <p className="m-auto text-sm text-muted-foreground">{textError}</p>;- if ((embedded && !url) || ((body === "text" || body === "web") && text === null)) {+ if (+ (embedded && !url) ||+ (body === "document" && !(draftFile ?? doc.file)) ||+ ((body === "text" || body === "web" || body === "markdown") && text === null)+ ) {return <Spinner className="m-auto size-6" />;}const prefix = truncated ? `${text}\n\n…` : text!;+ const language = !item.textOnly && CODE_LANGUAGES[fileExtension(ownName(item))];switch (body) {case "model":return <ModelDetails item={item} />;@@ -268,11 +327,33 @@ function PreviewBody({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 "document":+ return (+ <DocumentView+ file={draftFile ?? doc.file!}+ kind={documentKind(ownName(item), item.contentType)!}+ name={ownName(item)}+ contentType={item.contentType}+ scale={pageScale}+ />+ );+ case "markdown":+ return (+ <Zoomed scale={pageScale}>+ <div className="size-full overflow-auto px-6">+ <MarkdownPreview+ markdown={draft ?? prefix}+ defer={true}+ className="mx-auto max-h-none max-w-3xl select-text overflow-visible border-0 bg-transparent px-2 py-4 text-ui-15p5"+ />+ </div>+ </Zoomed>+ );case "audio":return (- <audio src={url!} controls onError={handleMediaError} className="m-auto w-full max-w-lg" />+ <div className="m-auto w-full max-w-lg px-6">+ <audio src={url!} controls onError={handleMediaError} className="w-full" />+ </div>);case "video":return (@@ -287,50 +368,62 @@ function PreviewBody({case "web":if (showCode) {return (- <CodeSourceView- code={truncated ? `${text!}\n…` : text!}- language="html"- className="rounded-xl"- />+ <Zoomed scale={pageScale}>+ <CodeSourceView+ code={truncated ? `${text!}\n…` : text!}+ language="html"+ className="px-6 pb-6"+ />+ </Zoomed>+ );+ }+ if (truncated) {+ return (+ <Zoomed scale={pageScale}>+ <TextPrefix text={prefix} />+ </Zoomed>);}- 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>+ <Zoomed scale={pageScale}>+ <ArtifactHtmlFrame code={text!} title={item.name} fill />+ </Zoomed>);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"- />+ <Zoomed scale={pageScale}>+ <textarea+ value={draft ?? text!}+ onChange={(event) => onDraftChange(event.target.value)}+ spellCheck={false}+ placeholder={t("library.preview.startWriting")}+ className="size-full resize-none bg-transparent px-6 pb-6 font-mono text-sm leading-relaxed outline-none"+ />+ </Zoomed>);}// 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} />+ if (isEditable(item) && readOnlyReason) {+ return (+ <Zoomed scale={pageScale}>+ <div className="flex size-full min-h-0 flex-col gap-3">+ <p className="px-6 text-ui-13 text-muted-foreground">+ {t(READ_ONLY_REASONS[readOnlyReason])}+ </p>+ <TextPrefix text={prefix} className="min-h-0 flex-1" />+ </div>+ </Zoomed>+ );+ }+ return (+ <Zoomed scale={pageScale}>+ {language ? (+ <CodeSourceView code={prefix} language={language} className="px-6 pb-6" />+ ) : (+ <TextPrefix text={prefix} />+ )}+ </Zoomed>);default:return noPreview(t("library.preview.noPreview"));@@ -342,7 +435,6 @@ export function LibraryPreview({onOpenChange,onChat,onDownload,- onOpenThread,onToggleFavorite,onDelete,onSaved,@@ -351,15 +443,17 @@ export function LibraryPreview({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 [codeFor, setCodeFor] = useState<string | null>(null);+ const showCode = item !== null && codeFor === item.id;const body = item ? bodyFor(item) : "none";- const itemText = useItemText(item, body === "text" || body === "web");+ const view = item ? viewFor(item, showCode) : "none";+ const itemText = useItemText(item, view === "text" || view === "web" || view === "markdown");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@@ -389,17 +483,15 @@ export function LibraryPreview({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;+ const originOf = useLibraryOrigin();+ const origin = item ? originOf(item) : null;async function trySave(): Promise<string | null> {if (!item || draft === null || !unsaved) return null;@@ -470,10 +562,13 @@ export function LibraryPreview({const meta = item? [- t(- modelLabelKey(item) ??- (item.source === "generated" ? "library.toolbar.generated" : "library.toolbar.uploaded"),- ),+ item.threadId+ ? t("library.preview.fromChat")+ : t(+ modelLabelKey(item) ??+ (item.source === "generated" ? "library.toolbar.generated" : "library.toolbar.uploaded"),+ ),+ item.threadId ? item.threadTitle : null,formatSize(item.sizeBytes, locale, t),formatCardTime(item.updatedAt, locale),].filter(Boolean)@@ -488,6 +583,7 @@ export function LibraryPreview({title={item?.name ?? ""}meta={meta.join(" · ")}media={media}+ flush={true}noun={media ? body : "file"}onKeyDown={(event) => {const saveKey = event.code === "KeyS" || event.key.toLowerCase() === "s";@@ -498,14 +594,14 @@ export function LibraryPreview({}}extra={<>- {body === "web" && item && !showCode && (+ {item && ZOOMABLE.has(body) && (<ScaleMenuvalue={pageScale}scales={PAGE_SCALES}onChange={(value) => setZoom({ itemId: item.id, scale: Number(value) })}/>)}- {body === "web" && item && (+ {item && hasSource(item, body) && (<div className="mr-1 flex items-center gap-1"><ViewButtonlabel={t("library.preview.code")}@@ -540,17 +636,9 @@ export function LibraryPreview({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,+ viewOriginal: origin+ ? { label: t(origin.label), onClick: () => void saveThen(origin.open) }+ : undefined,reveal:revealLabel && canReveal(item)? {diff --git a/studio/frontend/src/features/library/components/library-toolbar.tsx b/studio/frontend/src/features/library/components/library-toolbar.tsxindex 820d0d1f1c8..2c2001d1ffc 100644--- a/studio/frontend/src/features/library/components/library-toolbar.tsx+++ b/studio/frontend/src/features/library/components/library-toolbar.tsx@@ -76,6 +76,8 @@ export interface LibrarySortMenuProps {activity?: boolean;/** False where only folders show, which have no size. */showSize?: boolean;+ desc?: boolean;+ onDirectionChange?: (desc: boolean) => void;}const SORT_OPTIONS: { value: LibrarySortChoice; label: TranslationKey }[] = [@@ -174,11 +176,38 @@ function FilterMenu({);}+function SortRadio({+ label,+ checked,+ onSelect,+}: {+ label: string;+ checked: boolean;+ onSelect: () => void;+}) {+ return (+ <DropdownMenuItem role="menuitemradio" aria-checked={checked} onSelect={onSelect}>+ <span className="flex-1">{label}</span>+ <span+ aria-hidden="true"+ className={cn(+ "ml-2 flex size-3.5 shrink-0 items-center justify-center rounded-full border-[1.5px]",+ checked ? "border-foreground bg-foreground" : "border-muted-foreground/60",+ )}+ >+ {checked && <span className="size-1.25 rounded-full bg-background" />}+ </span>+ </DropdownMenuItem>+ );+}+function SortMenu({value,onChange,activity = false,showSize = true,+ desc = true,+ onDirectionChange,}: LibrarySortMenuProps) {const t = useT();// Suggested orders "Modified" by last activity, as its list view header says.@@ -201,28 +230,29 @@ function SortMenu({</button></DropdownMenuTrigger><DropdownMenuContent align="start" sideOffset={4} className="w-max min-w-36">- {options.map(({ value: option, label }) => {- const checked = option === value;- return (- <DropdownMenuItem- key={option}- role="menuitemradio"- aria-checked={checked}- onSelect={() => onChange(option)}- >- <span className="flex-1">{t(label)}</span>- <span- aria-hidden="true"- className={cn(- "ml-2 flex size-4 shrink-0 items-center justify-center rounded-full border-[1.5px]",- checked ? "border-foreground bg-foreground" : "border-muted-foreground/60",- )}- >- {checked && <span className="size-1.5 rounded-full bg-background" />}- </span>- </DropdownMenuItem>- );- })}+ {options.map(({ value: option, label }) => (+ <SortRadio+ key={option}+ label={t(label)}+ checked={option === value}+ onSelect={() => onChange(option)}+ />+ ))}+ {value === "modified" && onDirectionChange && (+ <>+ <DropdownMenuSeparator className="mx-3" />+ <SortRadio+ label={t("library.toolbar.sortAscending")}+ checked={!desc}+ onSelect={() => onDirectionChange(false)}+ />+ <SortRadio+ label={t("library.toolbar.sortDescending")}+ checked={desc}+ onSelect={() => onDirectionChange(true)}+ />+ </>+ )}</DropdownMenuContent></DropdownMenu>);@@ -327,7 +357,7 @@ export function LibraryToolbar({</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">+ <label className="relative ml-2 flex h-9 w-[min(15rem,24vw)] 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"><HugeiconsIconicon={Search01Icon}strokeWidth={1.75}diff --git a/studio/frontend/src/features/library/file-kind.ts b/studio/frontend/src/features/library/file-kind.tsindex f21aaeea713..a8ec285171e 100644--- a/studio/frontend/src/features/library/file-kind.ts+++ b/studio/frontend/src/features/library/file-kind.ts@@ -13,6 +13,7 @@ import {} from "@hugeicons/core-free-icons";import { SheetIcon, TestTubeOutlineIcon } from "@/lib/hugeicons-derived";import type { IconSvgElement } from "@hugeicons/react";+import { documentKind } from "@/components/file-viewer/kind";import type { LibraryItem } from "./api";import { fileExtension } from "./file-name";@@ -54,6 +55,7 @@ const EXTENSION_KINDS: Record<string, LibraryFileKind> = {tsv: "spreadsheet",xls: "spreadsheet",xlsx: "spreadsheet",+ xlsm: "spreadsheet",ods: "spreadsheet",ppt: "presentation",pptx: "presentation",@@ -132,6 +134,9 @@ export function fileKind(if (type.startsWith("video/")) return "video";if (type === "application/pdf") return "pdf";if (type === "text/html") return "web";+ const viewed = documentKind("", type);+ if (viewed === "sheet") return "spreadsheet";+ if (viewed === "slides") return "presentation";return "document";}diff --git a/studio/frontend/src/features/library/file-name.ts b/studio/frontend/src/features/library/file-name.tsindex 04b1886e437..e974b2f3709 100644--- a/studio/frontend/src/features/library/file-name.ts+++ b/studio/frontend/src/features/library/file-name.ts@@ -34,7 +34,8 @@ export function libraryFileName(item: {fileName?: string;textOnly?: boolean;}): string {- const extension = clean(item.textOnly ? "txt" : fileExtension(item.fileName ?? item.name));+ const own = item.fileName ?? item.name;+ const extension = clean(item.textOnly && !isTextAttachmentName(own) ? "txt" : fileExtension(own));let name = clean(item.name) || FALLBACK_STEM;if (extension && fileExtension(name) !== extension) name = `${name}.${extension}`;const [base, suffix] = splitName(name);@@ -118,10 +119,9 @@ const SCRIPTABLE_TYPES = new Set(["application/xml",]);-export type EmbeddedBody = "image" | "pdf" | "audio" | "video";+export type EmbeddedBody = "image" | "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;}diff --git a/studio/frontend/src/features/library/hooks.ts b/studio/frontend/src/features/library/hooks.tsindex c7cd5fa7124..ef3e56fa9f8 100644--- a/studio/frontend/src/features/library/hooks.ts+++ b/studio/frontend/src/features/library/hooks.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { MAX_DOCUMENT_PREVIEW_BYTES } from "@/components/file-viewer";import { translate } from "@/i18n";import { type RefObject, useEffect, useState } from "react";import {@@ -73,6 +74,38 @@ export function useLibraryPreviewUrl(return { url: current?.url ?? null, error: current?.error ?? null, retry };}+export function useLibraryDocument(+ item: LibraryItem,+ enabled: boolean,+): { file: Blob | null; error: string | null } {+ const key = itemVersion(item);+ const [state, setState] = useState<{ key: string; file?: Blob; error?: string } | null>(null);+ const tooLarge = item.sizeBytes !== null && item.sizeBytes > MAX_DOCUMENT_PREVIEW_BYTES;+ useEffect(() => {+ if (!enabled || tooLarge) return;+ let cancelled = false;+ fetchLibraryBlob(item, item.contentType, MAX_DOCUMENT_PREVIEW_BYTES).then(+ (file) => !cancelled && setState({ key, file }),+ (err: unknown) =>+ !cancelled &&+ setState({+ key,+ error:+ err instanceof LibraryFileTooLarge+ ? translate("library.preview.tooLargeToPreview")+ : errorMessage(err),+ }),+ );+ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key, enabled]);+ if (enabled && tooLarge) return { file: null, error: translate("library.preview.tooLargeToPreview") };+ const current = enabled && state?.key === key ? state : null;+ return { file: current?.file ?? null, error: current?.error ?? null };+}+/** 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. */@@ -132,10 +165,9 @@ export function useColumnCount(const element = ref.current;if (!element) return;const measure = () => {- const width = element.clientWidth;- setColumns(- Math.max(2, Math.min(maxColumns, Math.floor(width / minColumnWidth))),- );+ const gap = parseFloat(getComputedStyle(element).columnGap) || 0;+ const fit = Math.floor((element.clientWidth + gap) / (minColumnWidth + gap));+ setColumns(Math.max(2, Math.min(maxColumns, fit)));};measure();const observer = new ResizeObserver(measure);diff --git a/studio/frontend/src/features/library/library-page.tsx b/studio/frontend/src/features/library/library-page.tsxindex aca324da2a0..e4e19ad8c10 100644--- a/studio/frontend/src/features/library/library-page.tsx+++ b/studio/frontend/src/features/library/library-page.tsx@@ -255,6 +255,9 @@ function LibraryView({ search }: { search: LibrarySearch }) {value: gridSortValue,activity: tab === "suggested" && !folderId,showSize: Boolean(folderId) || tab !== "folders",+ desc: sort.desc,+ onDirectionChange: (desc: boolean) =>+ desc !== sort.desc && go({ ...search, sort: sortParam({ key: sort.key, desc }) }, true),// Reselecting the checked key keeps its direction, which list view may have flipped.onChange: (choice: LibrarySortChoice) =>choice !== gridSortValue &&@@ -1013,7 +1016,6 @@ function LibraryView({ search }: { search: LibrarySearch }) {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()}diff --git a/studio/frontend/src/features/library/origin.ts b/studio/frontend/src/features/library/origin.tsnew file mode 100644index 00000000000..05a0e5cd377--- /dev/null+++ b/studio/frontend/src/features/library/origin.ts@@ -0,0 +1,68 @@+// 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 { useTrainingRuntimeStore } from "@/features/training";+import type { TranslationKey } from "@/i18n";+import { useNavigate } from "@tanstack/react-router";+import type { LibraryItem } from "./api";++export interface LibraryOrigin {+ label: TranslationKey;+ open: () => void;+}++export function useLibraryOrigin(): (item: LibraryItem) => LibraryOrigin | null {+ const navigate = useNavigate();+ return (item) => {+ if (item.threadId) {+ const { threadId, pairId } = item;+ return {+ label: "library.preview.viewOriginalChat",+ open: () =>+ void navigate({+ to: "/chat",+ search: pairId ? { compare: pairId } : { thread: threadId },+ }),+ };+ }+ if (item.projectId) {+ const project = item.projectId;+ return {+ label: "library.preview.viewOriginalProject",+ open: () => void navigate({ to: "/chat", search: { project } }),+ };+ }+ if (item.runId) {+ const runId = item.runId;+ return {+ label: "library.preview.viewTrainingRun",+ open: () => {+ useTrainingRuntimeStore.getState().setSelectedHistoryRunId(runId);+ void navigate({ to: "/studio" });+ },+ };+ }+ if (item.archived) return null;+ const [kind, ...rest] = item.id.split(":");+ const search = { item: rest.join(":") };+ if (kind === "image") {+ return {+ label: "library.preview.viewInImages",+ open: () => void navigate({ to: "/images", search }),+ };+ }+ if (kind === "video") {+ return {+ label: "library.preview.viewInVideo",+ open: () => void navigate({ to: "/video", search }),+ };+ }+ if (kind === "audio") {+ return {+ label: "library.preview.viewInAudio",+ open: () => void navigate({ to: "/audio", search: { ...search, task: "text-to-speech" } }),+ };+ }+ return null;+ };+}diff --git a/studio/frontend/src/features/library/settings-store.ts b/studio/frontend/src/features/library/settings-store.tsindex 5f6fd6d9fa9..ecb21b4e562 100644--- a/studio/frontend/src/features/library/settings-store.ts+++ b/studio/frontend/src/features/library/settings-store.ts@@ -55,9 +55,9 @@ export const DEFAULT_LIBRARY_SETTINGS: LibrarySettings = {export const SUGGESTED_LIMITS = [20, 40, 80] as const;export const CARD_COLUMNS: Record<LibrarySettings["cardSize"], { minWidth: number; max: number }> = {- small: { minWidth: 170, max: 6 },- medium: { minWidth: 200, max: 5 },- large: { minWidth: 240, max: 4 },+ small: { minWidth: 140, max: 6 },+ medium: { minWidth: 170, max: 5 },+ large: { minWidth: 210, max: 4 },};export type LibraryView = "grid" | "list";diff --git a/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsx b/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsxindex 6a0b4bc6b49..55826d1487c 100644--- a/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsx+++ b/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsx@@ -17,6 +17,7 @@ import {deleteChatAttachment,emitChatAttachmentDeleted,fetchChatAttachmentBlob,+ isTextAttachmentName,listChatAttachments,} from "@/features/chat";import {@@ -258,8 +259,6 @@ const EXT_BY_MIME: Record<string, string> = {};// Name the save after the bytes the route actually returns. Uploaded documents come back as-// extracted text (TextAttachmentAdapter also wraps it in <attachment name=...>), so text/plain is-// .txt whatever the upload was called. Managed content parts arrive named "Chat image"/"Chat audio"// with no extension at all, which the OS cannot recognise. A dot at index 0 is a dotfile (.env),// not an extension: treating it as one would strip the whole name and save a bare ".txt".function extensionStart(name: string): number {@@ -271,7 +270,7 @@ function savedAttachmentName(name: string, blobType: string): string {const mime = blobType.split(";")[0].trim().toLowerCase();const dot = extensionStart(name);if (mime === "text/plain") {- if (name.toLowerCase().endsWith(".txt")) return name;+ if (name.toLowerCase().endsWith(".txt") || isTextAttachmentName(name)) return name;return `${dot === -1 ? name : name.slice(0, dot)}.txt`;}if (dot !== -1) return name;diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 71cec55a0f5..6b1e3d75aa0 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -3072,6 +3072,8 @@ export const ar = {fileType: "نوع الملف",clearFilters: "مسح عوامل التصفية",uploaded: "مرفوعة",+ sortAscending: "تصاعدي",+ sortDescending: "تنازلي",generated: "منشأة",documents: "المستندات",spreadsheets: "جداول البيانات",@@ -3144,10 +3146,16 @@ export const ar = {preview: {code: "الكود",preview: "معاينة",+ fromChat: "من المحادثة",viewOriginalChat: "عرض المحادثة الأصلية",viewInImages: "العرض في الصور",viewInVideo: "العرض في الفيديو",viewInAudio: "العرض في الصوت",+ viewOriginalProject: "عرض المشروع الأصلي",+ viewTrainingRun: "عرض جولة التدريب",+ sheetTruncated: "عرض جزء من هذه الورقة",+ documentTruncated: "عرض بداية هذا المستند",+ emptyDocument: "هذا الملف فارغ.",cannotPreview: "تتعذّر معاينة هذا الملف هنا. نزّله لفتحه.",noPreview: "لا تتوفر معاينة لهذا النوع من الملفات.",tooLargeToPreview: "هذا الملف أكبر من أن تتم معاينته هنا. نزّله لفتحه.",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex d8fdc374d6a..4175e620884 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -3141,6 +3141,8 @@ export const de = {fileType: "Dateityp",clearFilters: "Filter zurücksetzen",uploaded: "Hochgeladen",+ sortAscending: "Aufsteigend",+ sortDescending: "Absteigend",generated: "Generiert",documents: "Dokumente",spreadsheets: "Tabellen",@@ -3213,10 +3215,16 @@ export const de = {preview: {code: "Code",preview: "Vorschau",+ fromChat: "Aus Chat",viewOriginalChat: "Ursprünglichen Chat anzeigen",viewInImages: "In Bilder anzeigen",viewInVideo: "In Video anzeigen",viewInAudio: "In Audio anzeigen",+ viewOriginalProject: "Ursprüngliches Projekt anzeigen",+ viewTrainingRun: "Trainingslauf anzeigen",+ sheetTruncated: "Nur ein Teil dieses Tabellenblatts wird angezeigt",+ documentTruncated: "Nur der Anfang dieses Dokuments wird angezeigt",+ emptyDocument: "Diese Datei ist leer.",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.",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex f41bd9b53a4..6a2192318d1 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -3075,6 +3075,8 @@ export const en = {sortName: "Name",sortModified: "Modified",sortSize: "Size",+ sortAscending: "Ascending",+ sortDescending: "Descending",},// Entries of the New menu.create: {@@ -3141,10 +3143,16 @@ export const en = {preview: {code: "Code",preview: "Preview",+ fromChat: "From chat",viewOriginalChat: "View original chat",viewInImages: "View in Images",viewInVideo: "View in Video",viewInAudio: "View in Audio",+ viewOriginalProject: "View original project",+ viewTrainingRun: "View training run",+ sheetTruncated: "Showing part of this sheet",+ documentTruncated: "Showing the start of this document",+ emptyDocument: "This file is empty.",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.",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 949330995f0..30c71439231 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -3138,6 +3138,8 @@ export const es = {fileType: "Tipo de archivo",clearFilters: "Borrar filtros",uploaded: "Subidos",+ sortAscending: "Ascendente",+ sortDescending: "Descendente",generated: "Generados",documents: "Documentos",spreadsheets: "Hojas de cálculo",@@ -3210,10 +3212,16 @@ export const es = {preview: {code: "Código",preview: "Vista previa",+ fromChat: "Del chat",viewOriginalChat: "Ver el chat original",viewInImages: "Ver en Imágenes",viewInVideo: "Ver en Vídeo",viewInAudio: "Ver en Audio",+ viewOriginalProject: "Ver proyecto original",+ viewTrainingRun: "Ver ejecución de entrenamiento",+ sheetTruncated: "Mostrando parte de esta hoja",+ documentTruncated: "Mostrando el principio de este documento",+ emptyDocument: "Este archivo está vacío.",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.",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 3ef1946d9b0..8ad40c02acb 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -3152,6 +3152,8 @@ export const fr = {fileType: "Type de fichier",clearFilters: "Effacer les filtres",uploaded: "Importés",+ sortAscending: "Croissant",+ sortDescending: "Décroissant",generated: "Générés",documents: "Documents",spreadsheets: "Feuilles de calcul",@@ -3224,10 +3226,16 @@ export const fr = {preview: {code: "Code",preview: "Aperçu",+ fromChat: "Depuis la discussion",viewOriginalChat: "Voir la discussion d'origine",viewInImages: "Voir dans Images",viewInVideo: "Voir dans Vidéo",viewInAudio: "Voir dans Audio",+ viewOriginalProject: "Voir le projet d'origine",+ viewTrainingRun: "Voir l'entraînement",+ sheetTruncated: "Affichage d'une partie de cette feuille",+ documentTruncated: "Affichage du début de ce document",+ emptyDocument: "Ce fichier est vide.",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.",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 10251aac18e..bae630548e1 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -3079,6 +3079,8 @@ export const hi = {fileType: "फ़ाइल का प्रकार",clearFilters: "फ़िल्टर हटाएँ",uploaded: "अपलोड की गई",+ sortAscending: "आरोही",+ sortDescending: "अवरोही",generated: "जनरेट की गई",documents: "दस्तावेज़",spreadsheets: "स्प्रेडशीट",@@ -3151,10 +3153,16 @@ export const hi = {preview: {code: "कोड",preview: "प्रीव्यू",+ fromChat: "चैट से",viewOriginalChat: "मूल चैट देखें",viewInImages: "इमेज पेज में देखें",viewInVideo: "वीडियो पेज में देखें",viewInAudio: "ऑडियो पेज में देखें",+ viewOriginalProject: "मूल प्रोजेक्ट देखें",+ viewTrainingRun: "ट्रेनिंग रन देखें",+ sheetTruncated: "इस शीट का केवल एक भाग दिखाया जा रहा है",+ documentTruncated: "इस दस्तावेज़ का केवल आरंभिक भाग दिखाया जा रहा है",+ emptyDocument: "यह फ़ाइल खाली है।",cannotPreview: "इस फ़ाइल का प्रीव्यू यहाँ नहीं दिखाया जा सकता। इसे खोलने के लिए डाउनलोड करें।",noPreview: "इस प्रकार की फ़ाइल का कोई प्रीव्यू नहीं है।",tooLargeToPreview: "यह फ़ाइल यहाँ प्रीव्यू के लिए बहुत बड़ी है। इसे खोलने के लिए डाउनलोड करें।",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex bedefd0029d..57e9fb0dd07 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -3139,6 +3139,8 @@ export const it = {fileType: "Tipo di file",clearFilters: "Rimuovi filtri",uploaded: "Caricati",+ sortAscending: "Crescente",+ sortDescending: "Decrescente",generated: "Generati",documents: "Documenti",spreadsheets: "Fogli di calcolo",@@ -3211,10 +3213,16 @@ export const it = {preview: {code: "Codice",preview: "Anteprima",+ fromChat: "Dalla chat",viewOriginalChat: "Vai alla chat originale",viewInImages: "Vedi in Immagini",viewInVideo: "Vedi in Video",viewInAudio: "Vedi in Audio",+ viewOriginalProject: "Vai al progetto originale",+ viewTrainingRun: "Vedi l'addestramento",+ sheetTruncated: "Visualizzata solo una parte del foglio",+ documentTruncated: "Visualizzato solo l'inizio del documento",+ emptyDocument: "Questo file è vuoto.",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.",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 96879fdcb17..e295671aa38 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -3020,6 +3020,8 @@ export const ja = {fileType: "ファイルの種類",clearFilters: "フィルタをクリア",uploaded: "アップロード済み",+ sortAscending: "昇順",+ sortDescending: "降順",generated: "生成済み",documents: "ドキュメント",spreadsheets: "スプレッドシート",@@ -3092,10 +3094,16 @@ export const ja = {preview: {code: "コード",preview: "プレビュー",+ fromChat: "チャットから",viewOriginalChat: "元のチャットを表示",viewInImages: "画像ページで表示",viewInVideo: "動画ページで表示",viewInAudio: "音声ページで表示",+ viewOriginalProject: "元のプロジェクトを表示",+ viewTrainingRun: "トレーニング実行を表示",+ sheetTruncated: "このシートの一部のみを表示中",+ documentTruncated: "この文書の冒頭のみを表示中",+ emptyDocument: "このファイルは空です。",cannotPreview: "このファイルはここではプレビューできません。ダウンロードして開いてください。",noPreview: "この種類のファイルはプレビューできません。",tooLargeToPreview: "このファイルは大きすぎるため、ここではプレビューできません。ダウンロードして開いてください。",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex bbcd0d0ea82..96bdb5563f6 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -3066,6 +3066,8 @@ export const ko = {fileType: "파일 형식",clearFilters: "필터 지우기",uploaded: "업로드됨",+ sortAscending: "오름차순",+ sortDescending: "내림차순",generated: "생성됨",documents: "문서",spreadsheets: "스프레드시트",@@ -3138,10 +3140,16 @@ export const ko = {preview: {code: "코드",preview: "미리보기",+ fromChat: "채팅에서",viewOriginalChat: "원래 채팅 보기",viewInImages: "이미지에서 보기",viewInVideo: "동영상에서 보기",viewInAudio: "오디오에서 보기",+ viewOriginalProject: "원본 프로젝트 보기",+ viewTrainingRun: "학습 실행 보기",+ sheetTruncated: "이 시트의 일부만 표시 중",+ documentTruncated: "이 문서의 앞부분만 표시 중",+ emptyDocument: "이 파일은 비어 있습니다.",cannotPreview: "이 파일은 여기에서 미리 볼 수 없습니다. 다운로드해서 여세요.",noPreview: "이 파일 형식은 미리보기를 지원하지 않습니다.",tooLargeToPreview: "파일이 너무 커서 여기에서 미리 볼 수 없습니다. 다운로드해서 여세요.",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 793be152728..d980a59bf8c 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -3100,6 +3100,8 @@ export const ptBR = {fileType: "Tipo de arquivo",clearFilters: "Limpar filtros",uploaded: "Enviados",+ sortAscending: "Crescente",+ sortDescending: "Decrescente",generated: "Gerados",documents: "Documentos",spreadsheets: "Planilhas",@@ -3172,10 +3174,16 @@ export const ptBR = {preview: {code: "Código",preview: "Prévia",+ fromChat: "Do chat",viewOriginalChat: "Ver chat original",viewInImages: "Ver em Imagens",viewInVideo: "Ver em Vídeo",viewInAudio: "Ver em Áudio",+ viewOriginalProject: "Ver projeto original",+ viewTrainingRun: "Ver execução de treinamento",+ sheetTruncated: "Mostrando parte desta planilha",+ documentTruncated: "Mostrando o início deste documento",+ emptyDocument: "Este arquivo está vazio.",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.",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 3780aced766..b87625275dd 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -3099,6 +3099,8 @@ export const ru = {fileType: "Тип файла",clearFilters: "Сбросить фильтры",uploaded: "Загруженные",+ sortAscending: "По возрастанию",+ sortDescending: "По убыванию",generated: "Сгенерированные",documents: "Документы",spreadsheets: "Таблицы",@@ -3171,10 +3173,16 @@ export const ru = {preview: {code: "Код",preview: "Просмотр",+ fromChat: "Из чата",viewOriginalChat: "Открыть исходный чат",viewInImages: "Открыть в «Изображениях»",viewInVideo: "Открыть в «Видео»",viewInAudio: "Открыть в «Аудио»",+ viewOriginalProject: "Открыть исходный проект",+ viewTrainingRun: "Открыть запуск обучения",+ sheetTruncated: "Показана только часть листа",+ documentTruncated: "Показано только начало документа",+ emptyDocument: "Файл пуст.",cannotPreview: "Этот файл нельзя просмотреть здесь. Скачайте его, чтобы открыть.",noPreview: "Для этого типа файлов просмотр недоступен.",tooLargeToPreview: "Файл слишком большой для просмотра здесь. Скачайте его, чтобы открыть.",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 853a6f3c744..ae9c88d041d 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -2979,6 +2979,8 @@ export const zhCN = {fileType: "文件类型",clearFilters: "清除筛选",uploaded: "已上传",+ sortAscending: "升序",+ sortDescending: "降序",generated: "已生成",documents: "文档",spreadsheets: "电子表格",@@ -3051,10 +3053,16 @@ export const zhCN = {preview: {code: "代码",preview: "预览",+ fromChat: "来自聊天",viewOriginalChat: "查看原始聊天",viewInImages: "在图像中查看",viewInVideo: "在视频中查看",viewInAudio: "在音频中查看",+ viewOriginalProject: "查看原始项目",+ viewTrainingRun: "查看训练运行",+ sheetTruncated: "仅显示此工作表的一部分",+ documentTruncated: "仅显示此文档的开头部分",+ emptyDocument: "此文件为空。",cannotPreview: "无法在此预览该文件。请下载后打开。",noPreview: "此文件类型不支持预览。",tooLargeToPreview: "文件过大,无法在此预览。请下载后打开。",diff --git a/studio/frontend/tests/attachment-preview-text.test.ts b/studio/frontend/tests/attachment-preview-text.test.tsindex ccb6adb9ebd..ae64af17423 100644--- a/studio/frontend/tests/attachment-preview-text.test.ts+++ b/studio/frontend/tests/attachment-preview-text.test.ts@@ -988,3 +988,13 @@ test("a preview is never stricter than the adapter that took the file", async ()(error: Error) => error instanceof UndecodableTextError,);});++test("a UTF-16 Markdown file previews as its text in the document viewer", async () => {+ const utf16 = new Uint8Array([0xff, 0xfe, ...Array.from("# Notes", (c) => [c.charCodeAt(0), 0]).flat()]);+ const file = new File([utf16], "notes.md", { type: "text/markdown" });+ assert.equal((await readAttachmentText(file, file.name, file.type)).text, "# Notes");+ assert.notEqual(await file.text(), "# Notes");+ const { readFile } = await import("node:fs/promises");+ const dialog = await readFile(new URL("../src/components/assistant-ui/attachment-document-dialog.tsx", import.meta.url), "utf8");+ assert.match(dialog, /blob instanceof File\s*\?\s*await readAttachmentText\(blob, source\.name, source\.contentType\)/);+});diff --git a/studio/frontend/tests/file-viewer-office.test.ts b/studio/frontend/tests/file-viewer-office.test.tsnew file mode 100644index 00000000000..73bec7efe21--- /dev/null+++ b/studio/frontend/tests/file-viewer-office.test.ts@@ -0,0 +1,216 @@+// 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 { DOMParser } from "@xmldom/xmldom";+import { strToU8, zipSync } from "fflate";++import { formatNumber, readPptx, readXlsx } from "../src/components/file-viewer/office.ts";++{+ const proto = Object.getPrototypeOf(new DOMParser().parseFromString("<a/>", "application/xml").documentElement);+ const element = (node: Node | null): Element | null => {+ while (node && node.nodeType !== 1) node = node.nextSibling;+ return node as Element | null;+ };+ Object.defineProperties(proto, {+ firstElementChild: { get: function (this: Element) { return element(this.firstChild); } },+ nextElementSibling: { get: function (this: Element) { return element(this.nextSibling); } },+ parentElement: { get: function (this: Element) { return this.parentNode?.nodeType === 1 ? this.parentNode : null; } },+ children: {+ get: function (this: Element) {+ const out: Element[] = [];+ for (let node = this.firstElementChild; node; node = node.nextElementSibling) out.push(node);+ return out;+ },+ },+ });+ (globalThis as { DOMParser?: unknown }).DOMParser = DOMParser;+}++const MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";+const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";+const PKG = "http://schemas.openxmlformats.org/package/2006/relationships";+const rels = (items: string) => strToU8(`<Relationships xmlns="${PKG}">${items}</Relationships>`);++function workbook(sheet: string, extra: Record<string, Uint8Array> = {}): Uint8Array {+ return zipSync({+ "xl/workbook.xml": strToU8(+ `<workbook xmlns="${MAIN}" xmlns:r="${REL}"><sheets><sheet name="One" sheetId="1" r:id="rId1"/></sheets></workbook>`,+ ),+ "xl/_rels/workbook.xml.rels": rels(`<Relationship Id="rId1" Type="${REL}/worksheet" Target="worksheets/sheet1.xml"/>`),+ "xl/worksheets/sheet1.xml": strToU8(sheet),+ ...extra,+ });+}++function declareHuge(zip: Uint8Array, name: string): Uint8Array {+ const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);+ for (let i = 0; i < zip.length - 46; i++) {+ if (view.getUint32(i, true) !== 0x02014b50) continue;+ if (new TextDecoder().decode(zip.subarray(i + 46, i + 46 + view.getUint16(i + 28, true))) === name) {+ view.setUint32(i + 24, 0xfffffff0, true);+ return zip;+ }+ }+ throw new Error(`no entry ${name}`);+}++test("number formats", () => {+ const cases: [number, string, string][] = [+ [1234567.891, "#,##0.00", "1,234,567.89"],+ [-5, "#,##0.00;(#,##0.00)", "(5.00)"],+ [1.5, "# ?/?", "1 1/2"],+ [-1.5, "# ?/?;(# ?/?)", "(1 1/2)"],+ [45000, "yyyy-mm-dd", "2023-03-15"],+ [12.5, '0.00 "kg; net"', "12.50 kg; net"],+ [1, '"A_B"0', "A_B1"],+ [1234, '0.00E+00 "kg"', "1.23E+03 kg"],+ [-1234, "0.00E+00;(0.00E+00)", "(1.23E+03)"],+ [0.0123, "0.00E+00%", "1.23E+00%"],+ [1.5 / 86400, "[h]:mm:ss.00", "0:00:01.50"],+ [1 / 24, '[h]:mm "hours"', "1:00 hours"],+ [1 / 24, "[h]:m:s", "1:0:0"],+ [0.125, "# ?/?%", "12 1/2%"],+ [125000, "# ?/?,", "125"],+ [1.5, '0 "0/0"', "2 0/0"],+ [0.01, "0%%", "100%%"],+ [12345, "##0.0E+0", "12.3E+3"],+ [0.00123, "##0.0E+0", "1.2E-3"],+ [12.345, ".00", "12.35"],+ [0.5, ".00", ".50"],+ [3.5, '"$".00', "$3.50"],+ ];+ for (const [value, format, expected] of cases) assert.equal(formatNumber(value, format), expected, format);+});++test("xlsx: reads only the parts and rows it keeps", () => {+ let rows = "";+ for (let r = 1; r <= 5200; r++) {+ rows += `<x:row r="${r}"><x:c r="A${r}"><x:v>${r}</x:v></x:c><x:c r="B${r}" t="inlineStr"><x:is><x:t>${"x".repeat(200)}</x:t></x:is></x:c></x:row>`;+ }+ const zip = workbook(`<x:worksheet xmlns:x="${MAIN}"><x:sheetData>${rows}</x:sheetData></x:worksheet>`, {+ "customXml/item1.xml": strToU8("<x/>"),+ });+ const [sheet] = readXlsx(declareHuge(zip, "customXml/item1.xml"));+ assert.equal(sheet?.rows.length, 5000);+ assert.equal(sheet?.truncated, true);+});++test("xlsx: sheet XML read as text", () => {+ const [sheet] = readXlsx(+ workbook(`<worksheet xmlns="${MAIN}"><cols><col min='2' max='2' hidden='1'/></cols><sheetData>+<row r="1"><c r="A1" t="inlineStr"><is><r><t>a & B</t></r><r><t><![CDATA[<c></row>]]></t></r><rPh><t>ruby</t></rPh></is></c><c r="B1"><v>9</v></c></row>+<row r="2"><c r="A2"><f t="shared" ref="A2:A3" si="0">SUM(b2,C:C,2:2)*2+$C$1+'A1'!A1+T[[#This Row],[Q1]]</f><v>7</v></c></row>+<row r="3"><c r="A3"><f t="shared" si="0"/></c></row>+</sheetData></worksheet>`),+ );+ assert.deepEqual(+ sheet?.rows.map((row) => row.map((cell) => cell?.text)),+ [["a & B<c></row>"], ["7"], ["=SUM(B3,C:C,3:3)*2+$C$1+'A1'!A2+T[[#This Row],[Q1]]"]],+ );+});++test("xlsx: lowercase cell references land in their columns", () => {+ const [sheet] = readXlsx(+ workbook(`<worksheet xmlns="${MAIN}"><sheetData><row r="1"><c r="a1"><v>1</v></c><c r="c1"><v>3</v></c></row></sheetData></worksheet>`),+ );+ assert.deepEqual(sheet?.rows.map((row) => Array.from(row, (cell) => cell?.text)), [["1", undefined, "3"]]);+});++test("pptx: tables capped, SmartArt read, pictures as Blobs", () => {+ const P = "http://schemas.openxmlformats.org/presentationml/2006/main";+ const A = "http://schemas.openxmlformats.org/drawingml/2006/main";+ const DGM = "http://schemas.openxmlformats.org/drawingml/2006/diagram";+ const tc = "<a:tc><a:txBody><a:p><a:r><a:t>v</a:t></a:r></a:p></a:txBody></a:tc>";+ const text = (t: string) => `<dgm:t><a:p><a:r><a:t>${t}</a:t></a:r></a:p></dgm:t>`;+ const zip = zipSync({+ "ppt/presentation.xml": strToU8(+ `<p:presentation xmlns:p="${P}" xmlns:r="${REL}"><p:sldIdLst><p:sldId id="256" r:id="rId1"/></p:sldIdLst></p:presentation>`,+ ),+ "ppt/_rels/presentation.xml.rels": rels(`<Relationship Id="rId1" Type="${REL}/slide" Target="slides/slide1.xml"/>`),+ "ppt/slides/slide1.xml": strToU8(+ `<p:sld xmlns:p="${P}" xmlns:a="${A}" xmlns:r="${REL}" xmlns:dgm="${DGM}"><p:cSld><p:spTree>` ++ `<p:graphicFrame><a:graphic><a:graphicData><a:tbl>${`<a:tr>${tc.repeat(10)}</a:tr>`.repeat(1000)}</a:tbl></a:graphicData></a:graphic></p:graphicFrame>` ++ `<p:graphicFrame><a:graphic><a:graphicData><dgm:relIds r:dm="rId2"/></a:graphicData></a:graphic></p:graphicFrame>` ++ `<p:pic><p:blipFill><a:blip r:embed="rId3"/><a:srcRect l="25000" b="-10000"/></p:blipFill></p:pic>` ++ `</p:spTree></p:cSld></p:sld>`,+ ),+ "ppt/slides/_rels/slide1.xml.rels": rels(+ `<Relationship Id="rId2" Type="${REL}/diagramData" Target="../diagrams/data1.xml"/><Relationship Id="rId3" Type="${REL}/image" Target="../media/image1.png"/>`,+ ),+ "ppt/diagrams/data1.xml": strToU8(+ `<dgm:dataModel xmlns:dgm="${DGM}" xmlns:a="${A}"><dgm:ptLst><dgm:pt type="doc">${text("Doc")}</dgm:pt><dgm:pt>${text("Plan")}</dgm:pt></dgm:ptLst></dgm:dataModel>`,+ ),+ "ppt/media/image1.png": new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1]),+ "ppt/media/clip.mp4": new Uint8Array(8),+ });+ const [table, diagram, image] = readPptx(declareHuge(zip, "ppt/media/clip.mp4")).slides[0]!.boxes;+ assert.equal(image?.image?.type, "image/png");+ assert.deepEqual(image?.crop, { l: 0.25, t: 0, r: 0, b: -0.1 });+ assert.equal(table?.table?.length, 501);+ assert.deepEqual(table?.table?.at(-1), ["…"]);+ assert.deepEqual(diagram?.paragraphs?.map((p) => p.text), ["Plan"]);+});++for (const cache of ["<v></v>", "<v/>", "<s:v xmlns:s=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" />"]) {+ test(`xlsx: preserves a cached empty string formula result (${cache})`, () => {+ const [sheet] = readXlsx(workbook(+ `<worksheet xmlns="${MAIN}"><sheetData><row r="1">+ <c r="A1" t="str"><f>IF(1=1,"",42)</f>${cache}</c>+ <c r="B1" t="str"><f>IF(1=1,"ready",42)</f><v>ready</v></c>+ <c r="C1"><f>1-1</f><v>0</v></c>+ </row></sheetData></worksheet>`,+ ));+ assert.equal(sheet?.rows[0]?.[0]?.text ?? "", "");+ assert.equal(sheet?.rows[0]?.[1]?.text, "ready");+ assert.equal(sheet?.rows[0]?.[2]?.text, "0");+ });+}++test("xlsx: preserves formula fallback for uncalculated cells and shared followers", () => {+ const [sheet] = readXlsx(workbook(+ `<worksheet xmlns="${MAIN}"><sheetData><row r="1">+ <c r="A1"><f>SUM(1,2)</f><v></v></c>+ <c r="B1" t="n"><f>SUM(1,2)</f><v/></c>+ <c r="C1"><f>SUM(1,2)</f></c>+ <c r="D1" t="str"><f>IF(1=1,"",42)</f></c>+ <c r="E1" t="str"><f t="shared" si="0" ref="E1:G1">IF(A1=0,"",A1)</f><v/></c>+ <c r="F1" t="str"><f t="shared" si="0"/><v/></c>+ <c r="G1"><f t="shared" si="0"/><v/></c>+ </row></sheetData></worksheet>`,+ ));+ const row = sheet?.rows[0];+ for (const col of [0, 1, 2]) assert.equal(row?.[col]?.text, "=SUM(1,2)");+ assert.equal(row?.[3]?.text, '=IF(1=1,"",42)');+ assert.equal(row?.[4]?.text ?? "", "");+ assert.equal(row?.[5]?.text ?? "", "");+ assert.equal(row?.[6]?.text, '=IF(C1=0,"",C1)');+});+++test("xlsx: out-of-range date values do not prevent reading the workbook", () => {+ for (const date1904 of [false, true]) {+ for (const value of [1700000000, -1700000000]) {+ assert.equal(formatNumber(value, "mmm-yy", date1904), String(value));+ assert.equal(formatNumber(value, "mmmmm", date1904), String(value));+ }+ }+ assert.equal(formatNumber(45000, "mmm-yy"), "Mar-23");+ const [sheet] = readXlsx(workbook(+ `<worksheet xmlns="${MAIN}"><sheetData><row r="1">+ <c r="A1" s="1"><v>1700000000</v></c>+ <c r="B1" s="1"><v>45000</v></c>+ <c r="C1"><v>42</v></c>+ </row></sheetData></worksheet>`,+ {+ "xl/styles.xml": strToU8(`<styleSheet xmlns="${MAIN}">+ <numFmts count="1"><numFmt numFmtId="164" formatCode="mmm-yy"/></numFmts>+ <cellXfs count="2"><xf numFmtId="0"/><xf numFmtId="164"/></cellXfs>+ </styleSheet>`),+ },+ ));+ assert.deepEqual(sheet?.rows[0]?.map((cell) => cell?.text), ["1700000000", "Mar-23", "42"]);+});diff --git a/studio/frontend/tests/library-helpers.test.ts b/studio/frontend/tests/library-helpers.test.tsindex 11fed5f3c7b..942007903bd 100644--- a/studio/frontend/tests/library-helpers.test.ts+++ b/studio/frontend/tests/library-helpers.test.ts@@ -102,8 +102,6 @@ table("a file the server types opaquely gets a type from its extension", library]);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"],