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: upload files straight into a chat's folder (#13366)
Daniel Han658b75a681fc
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 869a68e15c4..66186d45dc7 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -8,6 +8,7 @@ import astimport codecsimport copyfrom collections import deque+from collections.abc import Iterableimport fnmatchimport functoolsimport hashlib@@ -21603,6 +21604,98 @@ def _install_attachment_copy(workdir: str, relative: str, source: Path) -> None:os.close(fd)+class SandboxUploadExists(Exception):+ """The upload's name is taken and the caller did not ask to replace it."""+++def sandbox_upload_name(name: "str | None") -> str:+ """The name an uploaded file is saved under at the sandbox root, one the download route serves back."""+ base = _UNSAFE_NAME_CHARS.sub("_", re.split(r"[\\/]", name or "")[-1]).strip(" .") or "upload"+ if _RESERVED_NAME.fullmatch(base.split(".", 1)[0].rstrip(" ")):+ base = "_" + base+ if len(base.encode()) > 255:+ stem, ext = os.path.splitext(base)+ ext = ext if len(ext.encode()) <= 16 else ""+ base = stem.encode()[: 255 - len(ext.encode())].decode("utf-8", "ignore").rstrip(" .") + ext+ return base if _servable_segment(base) else "upload"+++def save_sandbox_upload(+ session_id: "str | None",+ name: "str | None",+ chunks: "Iterable[bytes]",+ overwrite: bool = False,+) -> dict:+ """Write an uploaded file into the root of a chat's sandbox. Raises SandboxUploadExists when the+ name is taken, unless ``overwrite``."""+ name = sandbox_upload_name(name)+ with _session_in_flight(session_id):+ workdir = _get_workdir(session_id)+ # Registered as a call, so a tool call running meanwhile does not offer the upload as its own file.+ token = _call_started(workdir)+ try:+ replaced = _install_upload(workdir, name, chunks, overwrite)+ finally:+ _call_finished(token)+ return {"name": name, "path": os.path.join(workdir, name), "replaced": replaced}+++def _install_upload(workdir: str, name: str, chunks: "Iterable[bytes]", overwrite: bool) -> bool:+ """Stream into a fresh O_EXCL file, then link it in or, when replacing, rename onto the name. Through a+ directory descriptor where the platform has one, like the spill writer, so no link is followed."""+ dir_fd = (+ os.open(workdir, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) if _DIR_FD_WRITES else None+ )+ tmp, dest = f".tmp-{uuid.uuid4().hex[:12]}", name+ if dir_fd is None:+ tmp, dest = os.path.join(workdir, tmp), os.path.join(workdir, name)+ at = {} if dir_fd is None else {"dir_fd": dir_fd}+ pair = {} if dir_fd is None else {"src_dir_fd": dir_fd, "dst_dir_fd": dir_fd}+ flags = (+ os.O_WRONLY+ | os.O_CREAT+ | os.O_EXCL+ | getattr(os, "O_NOFOLLOW", 0)+ | getattr(os, "O_BINARY", 0)+ )+ try:+ with os.fdopen(os.open(tmp, flags, 0o600, **at), "wb") as out:+ for chunk in chunks:+ out.write(chunk)+ try:+ os.stat(dest, follow_symlinks = False, **at)+ existed = True+ except FileNotFoundError:+ existed = False+ if existed and not overwrite:+ raise SandboxUploadExists(name)+ if not existed:+ try:+ # link, not rename: it fails when a tool took the name since the check.+ os.link(tmp, dest, **pair)+ return False+ except FileExistsError:+ if not overwrite:+ raise SandboxUploadExists(name) from None+ except OSError:+ # A volume without hard links: claim the name exclusively, then rename onto the claim.+ try:+ os.close(os.open(dest, flags, 0o600, **at))+ except FileExistsError:+ if not overwrite:+ raise SandboxUploadExists(name) from None+ try:+ os.replace(tmp, dest, **pair)+ except (IsADirectoryError, NotADirectoryError, PermissionError) as exc:+ # A folder holds the name (Windows reports that as access denied).+ raise SandboxUploadExists(name) from exc+ return existed+ finally:+ _quiet_unlink(tmp, dir_fd = dir_fd)+ if dir_fd is not None:+ os.close(dir_fd)++def _is_attachment_copy(sandbox: str, parent: str, name: str) -> bool:prefix = os.path.basename(parent)path = os.path.join(parent, name)diff --git a/studio/backend/main.py b/studio/backend/main.pyindex ab2642ae9b7..28693d8949a 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1378,6 +1378,7 @@ from utils.upload_limits import ( # noqa: E402STT_AUDIO_JSON_MAX_BYTES,STT_AUDIO_RAW_MAX_BYTES,LIBRARY_UPLOAD_MAX_BYTES,+ SANDBOX_UPLOAD_MAX_BYTES,UNSTRUCTURED_RECIPE_UPLOAD_MAX_BYTES,VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES,VIDEO_INPUT_REFERENCE_MAX_BYTES,@@ -1434,6 +1435,11 @@ _LIBRARY_UPLOAD_PATH = "/api/library/uploads"_RAG_DOCUMENT_UPLOAD_RE = _re.compile(r"^/api/rag/(?:knowledge-bases|threads|projects)/[^/]+/documents/?$")+# One file into a chat's sandbox folder (multipart, capped by the route), on both mounts of the router.+_SANDBOX_UPLOAD_RE = _re.compile(r"^/(?:api/inference|v1)/sandbox/[^/]+/upload/?$")+_UPLOAD_PASSTHROUGH_RE = _re.compile(+ f"(?:{_RAG_DOCUMENT_UPLOAD_RE.pattern})|(?:{_SANDBOX_UPLOAD_RE.pattern})"+)# Streamed to disk and capped by the route itself; buffering here would hold 200 MiB in memory._AUDIO_INPUT_UPLOAD_PATHS = ("/api/inference/audio/inputs", "/v1/audio/inputs")_BODY_UPLOAD_PASSTHROUGH_PREFIXES = (@@ -1469,6 +1475,8 @@ def _get_upload_passthrough_request_max_bytes(path: str) -> int:return upload_request_limit_bytes(LIBRARY_UPLOAD_MAX_BYTES)if path.rstrip("/") in _AUDIO_INPUT_UPLOAD_PATHS:return AUDIO_INPUT_MAX_BYTES+ if _SANDBOX_UPLOAD_RE.match(path):+ return upload_request_limit_bytes(SANDBOX_UPLOAD_MAX_BYTES)if _RAG_DOCUMENT_UPLOAD_RE.match(path):from core.rag import config as _rag_config@@ -1685,7 +1693,7 @@ app.add_middleware(upload_passthrough_max_bytes_getter = _get_upload_passthrough_request_max_bytes,upload_passthrough_exact_paths = _BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS,chunked_upload_exact_paths = _CHUNKED_UPLOAD_EXACT_PATHS,- upload_passthrough_pattern = _RAG_DOCUMENT_UPLOAD_RE,+ upload_passthrough_pattern = _UPLOAD_PASSTHROUGH_RE,)# Tracks in-flight inference requests for idle auto-unload; off -> passthrough.diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 3b94abcdfed..d401c2e36e9 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -35552,6 +35552,44 @@ async def reveal_sandbox_dir(return {"status": "ok", "path": sandbox_dir}[email protected]("/sandbox/{session_id}/upload")+async def upload_sandbox_file(+ session_id: str,+ file: UploadFile = File(...),+ overwrite: bool = Form(False),+ session: Optional[str] = None,+ current_subject: str = Depends(get_current_subject),+):+ """Put one file into this chat's sandbox folder, where its tools read and write.++ Saved at the folder's root under the file's own name. A taken name is a 409 unless+ ``overwrite``, so a second upload never silently replaces what a tool wrote.+ """+ from starlette.concurrency import run_in_threadpool++ from core.inference.tools import SandboxUploadExists, save_sandbox_upload+ from utils.upload_limits import SANDBOX_UPLOAD_MAX_BYTES++ def _chunks():+ total = 0+ while chunk := file.file.read(1 << 20):+ total += len(chunk)+ if total > SANDBOX_UPLOAD_MAX_BYTES:+ raise HTTPException(status_code = 413, detail = f"{file.filename} is too large")+ yield chunk++ try:+ saved = await run_in_threadpool(+ save_sandbox_upload, session or session_id, file.filename, _chunks(), overwrite+ )+ except SandboxUploadExists as exc:+ raise HTTPException(status_code = 409, detail = f"{exc} already exists") from None+ except OSError:+ logger.error("Failed to save a sandbox upload", exc_info = True)+ raise HTTPException(status_code = 500, detail = "Could not save the file") from None+ return saved++@router.api_route("/sandbox/{session_id}/{filename:path}", methods = ["GET", "HEAD"])async def serve_sandbox_file(session_id: str,diff --git a/studio/backend/tests/multi_account/factories_media.py b/studio/backend/tests/multi_account/factories_media.pyindex bfa9a2306a3..8745b0da741 100644--- a/studio/backend/tests/multi_account/factories_media.py+++ b/studio/backend/tests/multi_account/factories_media.py@@ -466,6 +466,10 @@ SKIPPED = {"opens the backend host's file manager, so a success spawns xdg-open on a machine with ""no desktop session and the only in-process outcome is the 500 that failure maps to"),+ "routes.inference:POST:/sandbox/{session_id}/upload": (+ "needs a multipart body the JSON matrix client cannot send, so every actor stops at the "+ "same 422; the folder resolves inside the caller's own sandbox root (test_sandbox_upload)"+ ),"routes.inference:POST:/sandbox/{session_id}/open": ("launches the backend host's default app for the file and is owner-only ""(require_installation_owner), so no account other than the installation's own reaches it"diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.pyindex c50b3232a30..d87ba4ea73c 100644--- a/studio/backend/tests/test_middleware.py+++ b/studio/backend/tests/test_middleware.py@@ -1657,6 +1657,24 @@ def test_rag_document_uploads_pass_through_on_their_own_cap(main_module, monkeypassert not pattern.match(path), path+def test_sandbox_uploads_pass_through_on_their_own_cap(main_module):+ from utils.upload_limits import SANDBOX_UPLOAD_MAX_BYTES, upload_request_limit_bytes++ pattern = main_module._UPLOAD_PASSTHROUGH_RE+ for path in (+ "/api/inference/sandbox/thread-1/upload",+ "/api/inference/sandbox/_/upload/",+ "/v1/sandbox/thread-1/upload",+ ):+ assert pattern.match(path), path+ assert main_module._get_upload_passthrough_request_max_bytes(+ path+ ) == upload_request_limit_bytes(SANDBOX_UPLOAD_MAX_BYTES)+ for path in ("/api/inference/sandbox/thread-1/reveal", "/api/inference/sandbox/a/b/upload"):+ assert not pattern.match(path), path+ assert pattern.match("/api/rag/threads/t1/documents")++def test_pattern_passthrough_streams_and_refuses_oversized_declared_bodies(main_module):app = FastAPI()app.add_middleware(diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.pyindex 28464a5c4d3..0cee2052f75 100644--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py@@ -405,6 +405,7 @@ def test_sandbox_listing_route_exists():"/sandbox/{session_id}","/sandbox/{session_id}/open","/sandbox/{session_id}/reveal",+ "/sandbox/{session_id}/upload","/sandbox/{session_id}/{filename:path}",]diff --git a/studio/backend/tests/test_sandbox_upload.py b/studio/backend/tests/test_sandbox_upload.pynew file mode 100644index 00000000000..db6a4d51c77--- /dev/null+++ b/studio/backend/tests/test_sandbox_upload.py@@ -0,0 +1,181 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Uploading a file straight into a chat's sandbox folder (POST /sandbox/{session_id}/upload)."""++import asyncio+import io+import os+from pathlib import Path++import pytest+from fastapi import HTTPException+from starlette.datastructures import UploadFile+++def tools(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))+ from core.inference import tools++ tools._workdirs.clear()+ return tools++[email protected]("dir_fd_writes", [True, False])+def test_upload_lands_at_the_root_and_never_replaces_unless_asked(+ tools, monkeypatch, dir_fd_writes+):+ monkeypatch.setattr(tools, "_DIR_FD_WRITES", tools._DIR_FD_WRITES and dir_fd_writes)+ session = "__LOCALID_upload1"+ saved = tools.save_sandbox_upload(session, "report.xlsx", [b"PK\x03\x04", b"rest"])+ workdir = Path(tools.get_sandbox_workdir(session))+ assert saved == {"name": "report.xlsx", "path": str(workdir / "report.xlsx"), "replaced": False}+ assert (workdir / "report.xlsx").read_bytes() == b"PK\x03\x04rest"++ with pytest.raises(tools.SandboxUploadExists):+ tools.save_sandbox_upload(session, "report.xlsx", [b"second"])+ assert (workdir / "report.xlsx").read_bytes() == b"PK\x03\x04rest"++ # Replacing twice gives the same folder: the upload is idempotent.+ for _ in range(2):+ again = tools.save_sandbox_upload(session, "report.xlsx", [b"second"], overwrite = True)+ assert again["replaced"] is True+ assert (workdir / "report.xlsx").read_bytes() == b"second"++ (workdir / "out").mkdir()+ with pytest.raises(tools.SandboxUploadExists):+ tools.save_sandbox_upload(session, "out", [b"x"], overwrite = True)+ assert not [n for n in os.listdir(workdir) if n.startswith(".tmp-")], "temp file left behind"+++def test_a_failed_upload_leaves_nothing_behind(tools):+ session = "__LOCALID_upload2"++ def chunks():+ yield b"part"+ raise HTTPException(status_code = 413)++ with pytest.raises(HTTPException):+ tools.save_sandbox_upload(session, "big.bin", chunks())+ workdir = Path(tools.get_sandbox_workdir(session))+ assert [n for n in os.listdir(workdir) if not n.startswith(".unsloth")] == []+++def test_upload_names_stay_inside_the_folder(tools):+ assert tools.sandbox_upload_name("../../etc/passwd") == "passwd"+ assert tools.sandbox_upload_name("C:\\Users\\me\\report.xlsx") == "report.xlsx"+ assert tools.sandbox_upload_name("NUL.txt") == "_NUL.txt"+ assert tools.sandbox_upload_name("a:b?.csv") == "a_b_.csv"+ assert tools.sandbox_upload_name("..") == "upload"+ assert tools.sandbox_upload_name(None) == "upload"+ long_name = tools.sandbox_upload_name("季度" * 60 + ".xlsx")+ assert long_name.endswith(".xlsx") and len(long_name.encode()) <= 255+++def test_replacing_a_link_does_not_write_through_it(tools, tmp_path):+ session = "__LOCALID_upload3"+ workdir = Path(tools.get_sandbox_workdir(session))+ outside = tmp_path / "outside.txt"+ outside.write_bytes(b"keep")+ (workdir / "data.csv").symlink_to(outside)+ with pytest.raises(tools.SandboxUploadExists):+ tools.save_sandbox_upload(session, "data.csv", [b"new"])+ tools.save_sandbox_upload(session, "data.csv", [b"new"], overwrite = True)+ assert outside.read_bytes() == b"keep"+ assert not (workdir / "data.csv").is_symlink()+ assert (workdir / "data.csv").read_bytes() == b"new"+++def test_each_account_uploads_into_its_own_folder(tools):+ from utils.account_context import AccountContext, run_as++ alice, bob = AccountContext("alice-id", "alice"), AccountContext("bob-id", "bob")+ session = "__LOCALID_shared"+ run_as(alice, tools.save_sandbox_upload, session, "notes.txt", [b"alice"])+ run_as(bob, tools.save_sandbox_upload, session, "notes.txt", [b"bob"])+ alice_dir = Path(run_as(alice, tools.get_sandbox_workdir, session))+ bob_dir = Path(run_as(bob, tools.get_sandbox_workdir, session))+ assert alice_dir != bob_dir+ assert (alice_dir / "notes.txt").read_bytes() == b"alice"+ assert (bob_dir / "notes.txt").read_bytes() == b"bob"+++def _upload(+ inference,+ session_id,+ name,+ data,+ overwrite = False,+):+ upload = UploadFile(file = io.BytesIO(data), filename = name)+ return asyncio.run(+ inference.upload_sandbox_file(+ session_id, file = upload, overwrite = overwrite, session = None, current_subject = "u"+ )+ )+++def test_route_lists_the_upload_and_maps_conflicts_and_the_cap(tools, monkeypatch):+ from routes import inference+ from utils import upload_limits++ session = "thread-upload"+ saved = _upload(inference, session, "report.xlsx", b"xlsx-bytes")+ assert saved["name"] == "report.xlsx" and saved["replaced"] is False+ listed = [f["name"] for f in inference._sandbox_listing(inference._sandbox_dir_for(session))]+ assert "report.xlsx" in listed++ with pytest.raises(HTTPException) as conflict:+ _upload(inference, session, "report.xlsx", b"other")+ assert conflict.value.status_code == 409+ assert _upload(inference, session, "report.xlsx", b"other", overwrite = True)["replaced"]++ monkeypatch.setattr(upload_limits, "SANDBOX_UPLOAD_MAX_BYTES", 4)+ with pytest.raises(HTTPException) as too_large:+ _upload(inference, session, "big.bin", b"12345")+ assert too_large.value.status_code == 413+ assert not (Path(inference._sandbox_dir_for(session)) / "big.bin").exists()+++def test_a_sandbox_file_named_upload_is_still_served():+ from routes.inference import router++ scope = {+ "type": "http",+ "method": "GET",+ "path": "/sandbox/thread-1/upload",+ "headers": [],+ "root_path": "",+ }+ matched = [r for r in router.routes if r.matches(scope)[0].name == "FULL"]+ assert [r.endpoint.__name__ for r in matched] == ["serve_sandbox_file"]+ scope["method"] = "POST"+ matched = [r for r in router.routes if r.matches(scope)[0].name == "FULL"]+ assert [r.endpoint.__name__ for r in matched] == ["upload_sandbox_file"]++[email protected]("dir_fd_writes", [True, False])+def test_a_volume_without_hard_links_still_never_replaces_unless_asked(+ tools, monkeypatch, dir_fd_writes+):+ monkeypatch.setattr(tools, "_DIR_FD_WRITES", tools._DIR_FD_WRITES and dir_fd_writes)+ session = "__LOCALID_nolinks"+ workdir = Path(tools.get_sandbox_workdir(session))++ def link_refused(src, dst, **kwargs):+ # A tool takes the name between the check and the install, on a volume refusing links.+ (workdir / "report.xlsx").write_bytes(b"tool output")+ raise PermissionError("hard links not supported")++ monkeypatch.setattr(tools.os, "link", link_refused)+ with pytest.raises(tools.SandboxUploadExists):+ tools.save_sandbox_upload(session, "report.xlsx", [b"upload"])+ assert (workdir / "report.xlsx").read_bytes() == b"tool output"+ (workdir / "report.xlsx").unlink()+ monkeypatch.setattr(+ tools.os, "link", lambda *a, **k: (_ for _ in ()).throw(OSError("no links"))+ )+ assert tools.save_sandbox_upload(session, "report.xlsx", [b"upload"])["replaced"] is False+ assert (workdir / "report.xlsx").read_bytes() == b"upload"diff --git a/studio/backend/utils/upload_limits.py b/studio/backend/utils/upload_limits.pyindex 8c0d5dc9448..c09c333da97 100644--- a/studio/backend/utils/upload_limits.py+++ b/studio/backend/utils/upload_limits.py@@ -23,6 +23,8 @@ VIDEO_INPUT_REFERENCE_B64_MAX_CHARS = ((VIDEO_INPUT_REFERENCE_MAX_BYTES + 2) //VIDEO_INPUT_REFERENCE_JSON_MAX_BYTES = VIDEO_INPUT_REFERENCE_B64_MAX_CHARS + 64 * 1024LIBRARY_UPLOAD_MAX_BYTES = 512 * _BYTES_PER_MB+# One file into a chat's sandbox folder, the Library's per-file cap.+SANDBOX_UPLOAD_MAX_BYTES = LIBRARY_UPLOAD_MAX_BYTESLOCAL_SEED_UPLOAD_MAX_BYTES = 100 * _BYTES_PER_MBLOCAL_SEED_UPLOAD_MAX_LABEL = "100MB"diff --git a/studio/frontend/src/components/assistant-ui/sandbox-upload.ts b/studio/frontend/src/components/assistant-ui/sandbox-upload.tsnew file mode 100644index 00000000000..95fad7d43ed--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/sandbox-upload.ts@@ -0,0 +1,41 @@+// 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 { sandboxRoutePrefix } from "./sandbox-files";++/** Mirrors SANDBOX_UPLOAD_MAX_BYTES in backend/utils/upload_limits.py. */+export const MAX_SANDBOX_UPLOAD_BYTES = 512 * 1024 * 1024;++export type SandboxUploadResult = { name: string; path: string; replaced: boolean };++/**+ * Put one file into a chat's sandbox folder, at its root. A taken name is refused with a 409+ * unless `overwrite`, so a second upload never silently replaces what a tool wrote.+ */+export async function uploadToSandbox(+ sessionId: string,+ file: File,+ overwrite = false,+): Promise<SandboxUploadResult> {+ const { prefix, query } = sandboxRoutePrefix(sessionId);+ const form = new FormData();+ form.append("file", file, file.name);+ form.append("overwrite", overwrite ? "true" : "false");+ const response = await authFetch(`${prefix}/upload${query}`, { method: "POST", body: form });+ if (!response.ok) {+ let detail = "";+ try {+ const body: unknown = await response.json();+ const value = (body as { detail?: unknown } | null)?.detail;+ if (typeof value === "string") detail = value;+ } catch {+ // A non-JSON error body leaves the status as the only thing to report.+ }+ throw Object.assign(new Error(detail || `Request failed (${response.status})`), {+ status: response.status,+ });+ }+ return (await response.json()) as SandboxUploadResult;+}diff --git a/studio/frontend/src/features/chat/components/chat-header-menu.tsx b/studio/frontend/src/features/chat/components/chat-header-menu.tsxindex 5b64e59bc05..3e4f150a96a 100644--- a/studio/frontend/src/features/chat/components/chat-header-menu.tsx+++ b/studio/frontend/src/features/chat/components/chat-header-menu.tsx@@ -58,7 +58,7 @@ import {exportConversationByFormat,getSidebarItemThreadIds,} from "./chat-row-menu";-import { OpenChatFolderItem } from "./open-chat-folder-item";+import { OpenChatFolderItem, UploadToChatFolderItem } from "./open-chat-folder-item";const MENU = "library-actions-menu";const ICON = "size-icon";@@ -335,6 +335,7 @@ function ChatMenuItems({ menu }: { menu: ActiveChatMenu }) {</DropdownMenuSubContent></DropdownMenuSub><OpenChatFolderItem item={menu.item} />+ <UploadToChatFolderItem item={menu.item} /><DropdownMenuSeparator className="mx-3" /><Item icon={Archive03Icon} onSelect={menu.archive} shortcut="archiveChat">{t("settings.data.library.archive")}diff --git a/studio/frontend/src/features/chat/components/open-chat-folder-item.tsx b/studio/frontend/src/features/chat/components/open-chat-folder-item.tsxindex dcb5c9aef35..d08493c375c 100644--- a/studio/frontend/src/features/chat/components/open-chat-folder-item.tsx+++ b/studio/frontend/src/features/chat/components/open-chat-folder-item.tsx@@ -3,16 +3,21 @@import { sandboxSessionIdFor } from "@/components/assistant-ui/sandbox-files";import { revealSandbox } from "@/components/assistant-ui/sandbox-reveal";+import {+ MAX_SANDBOX_UPLOAD_BYTES,+ uploadToSandbox,+} from "@/components/assistant-ui/sandbox-upload";import { DropdownMenuItem } from "@/components/ui/dropdown-menu";import {Tooltip,TooltipContent,TooltipTrigger,} from "@/components/ui/tooltip";-import { FolderOpenIcon } from "@hugeicons/core-free-icons";+import { FolderOpenIcon, Upload01Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { useT } from "@/i18n";import { isTauri } from "@/lib/api-base";+import { openFilePicker } from "@/lib/open-file-picker";import { toast } from "@/lib/toast";import { useState, type ComponentProps, type ComponentType } from "react";import type { SidebarItem } from "../hooks/use-chat-sidebar-items";@@ -82,6 +87,82 @@ export function OpenChatFolderItem({);}+/**+ * "Upload to chat folder": files go to the folder the chat's next tool call runs in, without+ * entering the conversation. The bytes travel to the backend, so a browser session can use it too.+ */+export function UploadToChatFolderItem({+ item,+ Item = DropdownMenuItem,+}: {+ item: SidebarItem;+ Item?: ComponentType<ComponentProps<typeof DropdownMenuItem>>;+}) {+ const t = useT();+ const sandboxSessionId =+ item.type === "single" || item.projectId+ ? sandboxSessionIdFor(getSidebarItemThreadIds(item)[0] ?? item.id, item.projectId)+ : undefined;+ if (!sandboxSessionId) return null;+ return (+ <Item+ title={t("library.chats.folder.uploadTitle")}+ onSelect={() =>+ openFilePicker("*", (files) => void uploadToChatFolder(sandboxSessionId, files, t))+ }+ >+ <HugeiconsIcon icon={Upload01Icon} strokeWidth={1.75} className="size-icon" />+ <span>{t("library.chats.folder.upload")}</span>+ </Item>+ );+}++async function uploadToChatFolder(+ sessionId: string,+ files: File[],+ t: ReturnType<typeof useT>,+ overwrite = false,+): Promise<void> {+ const added: string[] = [];+ const taken: File[] = [];+ for (const file of files) {+ const failed = (description: string) =>+ toast.error(t("library.chats.folder.uploadFailed", { name: file.name }), { description });+ if (file.size > MAX_SANDBOX_UPLOAD_BYTES) {+ failed(t("library.toast.uploadTooLarge", { name: file.name }));+ continue;+ }+ try {+ added.push((await uploadToSandbox(sessionId, file, overwrite)).name);+ } catch (error) {+ // A 409 on a replace is a folder holding the name: offering Replace again would loop.+ if (!overwrite && (error as { status?: number } | null)?.status === 409) taken.push(file);+ else failed(error instanceof Error ? error.message : String(error));+ }+ }+ if (added.length > 0) {+ toast.success(+ added.length === 1+ ? t("library.chats.folder.uploaded", { name: added[0] })+ : t("library.chats.folder.uploadedMany", { count: added.length }),+ { description: t("library.chats.folder.uploadedDescription") },+ );+ }+ if (taken.length > 0) {+ toast.info(+ taken.length === 1+ ? t("library.chats.folder.uploadExists", { name: taken[0].name })+ : t("library.chats.folder.uploadExistsMany", { count: taken.length }),+ {+ action: {+ label: t("library.chats.folder.replace"),+ onClick: () => void uploadToChatFolder(sessionId, taken, t, true),+ },+ },+ );+ }+}+export function OpenProjectFolderItem({projectId,Item = DropdownMenuItem,diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex cc6d3958764..3f0ed542d06 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -3964,6 +3964,15 @@ export const ar = {chatMissing: "لا يوجد مجلد لهذه المحادثة بعد.",projectMissing: "لا يوجد مجلد لهذا المشروع بعد.",missingDescription: "يُنشأ عندما تكتب أداة ملفًا لأول مرة.",+ upload: "رفع إلى مجلد المحادثة",+ uploadTitle: "إضافة ملفات إلى المجلد الذي تقرأ منه أدوات هذه المحادثة وتكتب فيه",+ uploaded: "تمت إضافة {name} إلى مجلد المحادثة",+ uploadedMany: "تمت إضافة {count} ملفات إلى مجلد المحادثة",+ uploadedDescription: "يمكن لأدوات هذه المحادثة فتحها الآن. لا تتم إضافتها إلى المحادثة.",+ uploadExists: "{name} موجود بالفعل في مجلد المحادثة",+ uploadExistsMany: "{count} ملفات موجودة بالفعل في مجلد المحادثة",+ replace: "استبدال",+ uploadFailed: "تعذر رفع {name}",},},empty: {diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 4ff8743f1e7..b892f7b5ab8 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -4036,6 +4036,15 @@ export const de = {chatMissing: "Dieser Chat hat noch keinen Ordner.",projectMissing: "Dieses Projekt hat noch keinen Ordner.",missingDescription: "Er wird angelegt, sobald ein Tool zum ersten Mal eine Datei schreibt.",+ upload: "In Chat-Ordner hochladen",+ uploadTitle: "Dateien in den Ordner legen, den die Tool-Aufrufe dieses Chats lesen und schreiben",+ uploaded: "{name} wurde in den Chat-Ordner gelegt",+ uploadedMany: "{count} Dateien wurden in den Chat-Ordner gelegt",+ uploadedDescription: "Die Tools dieses Chats können sie jetzt öffnen. Sie werden nicht zur Unterhaltung hinzugefügt.",+ uploadExists: "{name} liegt bereits im Chat-Ordner",+ uploadExistsMany: "{count} Dateien liegen bereits im Chat-Ordner",+ replace: "Ersetzen",+ uploadFailed: "{name} konnte nicht hochgeladen werden",},},empty: {diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 329dc5bfc81..697e5fa8994 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -3991,6 +3991,15 @@ export const en = {chatMissing: "This chat has no folder yet.",projectMissing: "This project has no folder yet.",missingDescription: "It is created the first time a tool writes a file.",+ upload: "Upload to chat folder",+ uploadTitle: "Add files to the folder this chat's tool calls read and write",+ uploaded: "Added {name} to the chat folder",+ uploadedMany: "Added {count} files to the chat folder",+ uploadedDescription: "Tools in this chat can open them now. They are not added to the conversation.",+ uploadExists: "{name} is already in the chat folder",+ uploadExistsMany: "{count} files are already in the chat folder",+ replace: "Replace",+ uploadFailed: "Could not upload {name}",},},// One title and description per tab, shown when it has nothing yet.diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 1483ef3af6f..2c72af79f1e 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -4035,6 +4035,15 @@ export const es = {chatMissing: "Este chat aún no tiene carpeta.",projectMissing: "Este proyecto aún no tiene carpeta.",missingDescription: "Se crea la primera vez que una herramienta escribe un archivo.",+ upload: "Subir a la carpeta del chat",+ uploadTitle: "Añadir archivos a la carpeta que leen y escriben las herramientas de este chat",+ uploaded: "{name} se añadió a la carpeta del chat",+ uploadedMany: "Se añadieron {count} archivos a la carpeta del chat",+ uploadedDescription: "Las herramientas de este chat ya pueden abrirlos. No se añaden a la conversación.",+ uploadExists: "{name} ya está en la carpeta del chat",+ uploadExistsMany: "{count} archivos ya están en la carpeta del chat",+ replace: "Reemplazar",+ uploadFailed: "No se pudo subir {name}",},},empty: {diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex bcc1fcbb17f..4150777afcf 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -4047,6 +4047,15 @@ export const fr = {chatMissing: "Cette discussion n’a pas encore de dossier.",projectMissing: "Ce projet n’a pas encore de dossier.",missingDescription: "Il est créé la première fois qu’un outil écrit un fichier.",+ upload: "Téléverser dans le dossier de la discussion",+ uploadTitle: "Ajouter des fichiers au dossier que lisent et écrivent les outils de cette discussion",+ uploaded: "{name} a été ajouté au dossier de la discussion",+ uploadedMany: "{count} fichiers ont été ajoutés au dossier de la discussion",+ uploadedDescription: "Les outils de cette discussion peuvent maintenant les ouvrir. Ils ne sont pas ajoutés à la conversation.",+ uploadExists: "{name} est déjà dans le dossier de la discussion",+ uploadExistsMany: "{count} fichiers sont déjà dans le dossier de la discussion",+ replace: "Remplacer",+ uploadFailed: "Impossible de téléverser {name}",},},empty: {diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 27040038709..2ec7c8f0907 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -4077,6 +4077,15 @@ export const he = {chatMissing: "לצ'אט זה עדיין אין תיקייה.",projectMissing: "לפרויקט זה עדיין אין תיקייה.",missingDescription: "היא נוצרת בפעם הראשונה שכלי כותב קובץ.",+ upload: "העלה לתיקיית הצ'אט",+ uploadTitle: "הוסף קבצים לתיקייה שבה קוראות וכותבות קריאות הכלים של צ'אט זה",+ uploaded: "{name} נוסף לתיקיית הצ'אט",+ uploadedMany: "{count} קבצים נוספו לתיקיית הצ'אט",+ uploadedDescription: "הכלים של צ'אט זה יכולים לפתוח אותם עכשיו. הם לא נוספים לשיחה.",+ uploadExists: "{name} כבר נמצא בתיקיית הצ'אט",+ uploadExistsMany: "{count} קבצים כבר נמצאים בתיקיית הצ'אט",+ replace: "החלף",+ uploadFailed: "לא ניתן היה להעלות את {name}",},},empty: {diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 8809210d10d..2b7bccf10b9 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -3972,6 +3972,15 @@ export const hi = {chatMissing: "इस चैट का अभी कोई फ़ोल्डर नहीं है।",projectMissing: "इस प्रोजेक्ट का अभी कोई फ़ोल्डर नहीं है।",missingDescription: "यह तब बनता है जब कोई टूल पहली बार कोई फ़ाइल लिखता है।",+ upload: "चैट फ़ोल्डर में अपलोड करें",+ uploadTitle: "इस चैट के टूल कॉल जिस फ़ोल्डर को पढ़ते और लिखते हैं, उसमें फ़ाइलें जोड़ें",+ uploaded: "{name} चैट फ़ोल्डर में जोड़ी गई",+ uploadedMany: "{count} फ़ाइलें चैट फ़ोल्डर में जोड़ी गईं",+ uploadedDescription: "इस चैट के टूल अब इन्हें खोल सकते हैं। ये बातचीत में नहीं जोड़ी जातीं।",+ uploadExists: "{name} पहले से चैट फ़ोल्डर में है",+ uploadExistsMany: "{count} फ़ाइलें पहले से चैट फ़ोल्डर में हैं",+ replace: "बदलें",+ uploadFailed: "{name} अपलोड नहीं हो सकी",},},empty: {diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 52aa57df78a..775a56e2a70 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -4037,6 +4037,15 @@ export const it = {chatMissing: "Questa chat non ha ancora una cartella.",projectMissing: "Questo progetto non ha ancora una cartella.",missingDescription: "Viene creata la prima volta che uno strumento scrive un file.",+ upload: "Carica nella cartella della chat",+ uploadTitle: "Aggiungi file alla cartella che gli strumenti di questa chat leggono e scrivono",+ uploaded: "{name} aggiunto alla cartella della chat",+ uploadedMany: "{count} file aggiunti alla cartella della chat",+ uploadedDescription: "Gli strumenti di questa chat ora possono aprirli. Non vengono aggiunti alla conversazione.",+ uploadExists: "{name} è già nella cartella della chat",+ uploadExistsMany: "{count} file sono già nella cartella della chat",+ replace: "Sostituisci",+ uploadFailed: "Impossibile caricare {name}",},},empty: {diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 7db7c440098..e13e3d63e24 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -3912,6 +3912,15 @@ export const ja = {chatMissing: "このチャットにはまだフォルダがありません。",projectMissing: "このプロジェクトにはまだフォルダがありません。",missingDescription: "ツールが初めてファイルを書き込んだときに作成されます。",+ upload: "チャットフォルダにアップロード",+ uploadTitle: "このチャットのツール呼び出しが読み書きするフォルダにファイルを追加します",+ uploaded: "{name} をチャットフォルダに追加しました",+ uploadedMany: "{count} 個のファイルをチャットフォルダに追加しました",+ uploadedDescription: "このチャットのツールから開けるようになりました。会話には追加されません。",+ uploadExists: "{name} は既にチャットフォルダにあります",+ uploadExistsMany: "{count} 個のファイルは既にチャットフォルダにあります",+ replace: "置き換える",+ uploadFailed: "{name} をアップロードできませんでした",},},empty: {diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 66e17b788fd..09c8937c828 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -3955,6 +3955,15 @@ export const ko = {chatMissing: "이 채팅에는 아직 폴더가 없습니다.",projectMissing: "이 프로젝트에는 아직 폴더가 없습니다.",missingDescription: "도구가 처음 파일을 쓸 때 만들어집니다.",+ upload: "채팅 폴더에 업로드",+ uploadTitle: "이 채팅의 도구 호출이 읽고 쓰는 폴더에 파일을 추가합니다",+ uploaded: "{name}을(를) 채팅 폴더에 추가했습니다",+ uploadedMany: "파일 {count}개를 채팅 폴더에 추가했습니다",+ uploadedDescription: "이제 이 채팅의 도구가 열 수 있습니다. 대화에는 추가되지 않습니다.",+ uploadExists: "{name}은(는) 이미 채팅 폴더에 있습니다",+ uploadExistsMany: "파일 {count}개가 이미 채팅 폴더에 있습니다",+ replace: "바꾸기",+ uploadFailed: "{name}을(를) 업로드하지 못했습니다",},},empty: {diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 7aa91021a12..6158fd1a21b 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -3995,6 +3995,15 @@ export const ptBR = {chatMissing: "Este chat ainda não tem pasta.",projectMissing: "Este projeto ainda não tem pasta.",missingDescription: "Ela é criada na primeira vez que uma ferramenta escreve um arquivo.",+ upload: "Enviar para a pasta do chat",+ uploadTitle: "Adicionar arquivos à pasta que as ferramentas deste chat leem e escrevem",+ uploaded: "{name} foi adicionado à pasta do chat",+ uploadedMany: "{count} arquivos foram adicionados à pasta do chat",+ uploadedDescription: "As ferramentas deste chat já podem abri-los. Eles não são adicionados à conversa.",+ uploadExists: "{name} já está na pasta do chat",+ uploadExistsMany: "{count} arquivos já estão na pasta do chat",+ replace: "Substituir",+ uploadFailed: "Não foi possível enviar {name}",},},empty: {diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 8bcfa37c7df..3f115dbfd8b 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -3991,6 +3991,15 @@ export const ru = {chatMissing: "У этого чата пока нет папки.",projectMissing: "У этого проекта пока нет папки.",missingDescription: "Она создаётся, когда инструмент впервые записывает файл.",+ upload: "Загрузить в папку чата",+ uploadTitle: "Добавить файлы в папку, которую читают и пишут инструменты этого чата",+ uploaded: "{name} добавлен в папку чата",+ uploadedMany: "Файлов добавлено в папку чата: {count}",+ uploadedDescription: "Инструменты этого чата уже могут их открыть. В переписку они не добавляются.",+ uploadExists: "{name} уже есть в папке чата",+ uploadExistsMany: "Файлов уже в папке чата: {count}",+ replace: "Заменить",+ uploadFailed: "Не удалось загрузить {name}",},},empty: {diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 812ff03a22d..f6826f16b9d 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -4213,6 +4213,15 @@ export const sv = {projectMissing: "Det här projektet har ingen mapp än.",missingDescription:"Den skapas första gången ett verktyg skriver en fil.",+ upload: "Ladda upp till chattmapp",+ uploadTitle: "Lägg till filer i mappen som den här chattens verktygsanrop läser och skriver i",+ uploaded: "{name} lades till i chattmappen",+ uploadedMany: "{count} filer lades till i chattmappen",+ uploadedDescription: "Verktygen i den här chatten kan öppna dem nu. De läggs inte till i konversationen.",+ uploadExists: "{name} finns redan i chattmappen",+ uploadExistsMany: "{count} filer finns redan i chattmappen",+ replace: "Ersätt",+ uploadFailed: "Det gick inte att ladda upp {name}",},},empty: {diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 214ef905dbb..c90e2c5c321 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -3869,6 +3869,15 @@ export const zhCN = {chatMissing: "此聊天还没有文件夹。",projectMissing: "此项目还没有文件夹。",missingDescription: "工具首次写入文件时会创建它。",+ upload: "上传到聊天文件夹",+ uploadTitle: "将文件添加到此聊天的工具调用读写的文件夹",+ uploaded: "已将 {name} 添加到聊天文件夹",+ uploadedMany: "已将 {count} 个文件添加到聊天文件夹",+ uploadedDescription: "此聊天的工具现在可以打开它们。它们不会添加到对话中。",+ uploadExists: "{name} 已在聊天文件夹中",+ uploadExistsMany: "{count} 个文件已在聊天文件夹中",+ replace: "替换",+ uploadFailed: "无法上传 {name}",},},empty: {diff --git a/studio/frontend/tests/sandbox-upload.test.ts b/studio/frontend/tests/sandbox-upload.test.tsnew file mode 100644index 00000000000..48d8e2604e6--- /dev/null+++ b/studio/frontend/tests/sandbox-upload.test.ts@@ -0,0 +1,50 @@+// 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 { register } from "node:module";+import test from "node:test";++// sandbox-upload reaches authFetch through the auth barrel. See helpers/auth-stub.mjs.+register("./helpers/settings-api-resolver.mjs", import.meta.url);++const { uploadToSandbox } = await import("../src/components/assistant-ui/sandbox-upload.ts");++type Sent = { url: string; form: FormData };++function capture(status: number, body: unknown): Sent[] {+ const sent: Sent[] = [];+ globalThis.fetch = (async (url: string, init?: RequestInit) => {+ sent.push({ url, form: init?.body as FormData });+ return {+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+ } as unknown as Response;+ }) as typeof fetch;+ return sent;+}++test("a file goes to the session's upload route, refusing to replace by default", async () => {+ const sent = capture(200, { name: "report.xlsx", path: "/x/report.xlsx", replaced: false });+ const result = await uploadToSandbox("project-p1", new File(["x"], "report.xlsx"));+ assert.equal(result.name, "report.xlsx");+ assert.match(sent[0].url, /\/api\/inference\/sandbox\/project-p1\/upload$/);+ assert.equal(sent[0].form.get("overwrite"), "false");+ assert.equal((sent[0].form.get("file") as File).name, "report.xlsx");+});++test("an id the router cannot carry rides in the query, after the verb", async () => {+ const sent = capture(200, { name: "a.csv", path: "/x/a.csv", replaced: true });+ await uploadToSandbox("thread/with/slashes", new File(["x"], "a.csv"), true);+ assert.match(sent[0].url, /\/api\/inference\/sandbox\/_\/upload\?session=thread%2Fwith%2Fslashes$/);+ assert.equal(sent[0].form.get("overwrite"), "true");+});++test("a taken name rejects with its status, so the caller can offer to replace it", async () => {+ capture(409, { detail: "report.xlsx already exists" });+ await assert.rejects(uploadToSandbox("thread-1", new File(["x"], "report.xlsx")), {+ message: "report.xlsx already exists",+ status: 409,+ });+});