Skip to content

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

Studio: show the files a tool call creates, and keep them in one place (#8256)

Daniel Hanba4f7274a170
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index feedae58742..b03c3dcb84a 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -138,7 +138,7 @@ class ToolCallCompletion:
if not self.executed:
return {"role": "user", "content": self.result}
- content = strip_result_for_model(self.result)
+ content = strip_result_for_model(self.result, self.decision.tool_name)
if self.is_error:
content = content + TOOL_ERROR_NUDGE
message: dict[str, Any] = {
@@ -278,10 +278,52 @@ def _strip_mcp_image_suffix(result: str) -> str:
return head.rstrip()
-def strip_result_for_model(result: str) -> str:
+def _strip_files_sentinel(result: str) -> str:
+ """Drop a trailing ``__FILES__`` envelope, and only that.
+
+ Validated rather than split on sight: a tool whose own output contains the
+ literal text would otherwise lose everything after it.
+ """
+ marker = "\n__FILES__:"
+ start = result.rfind(marker)
+ if start == -1:
+ return result
+ payload_start = start + len(marker)
+ end = result.find("\n__", payload_start)
+ if end == -1:
+ end = len(result)
+ try:
+ entries = json.loads(result[payload_start:end])
+ except (ValueError, TypeError, RecursionError):
+ return result
+ # Every entry, not just the list: the executor emits {"name": str, "size":
+ # int | None}, and anything else is a tool that happened to print the marker.
+ if not isinstance(entries, list) or not all(_is_file_entry(e) for e in entries):
+ return result
+ return result[:start] + result[end:]
+
+
+def _is_file_entry(entry: object) -> bool:
+ return (
+ isinstance(entry, dict)
+ and isinstance(entry.get("name"), str)
+ and bool(entry.get("name"))
+ and (entry.get("size") is None or isinstance(entry.get("size"), int))
+ )
+
+
+# Only these emit the file envelope, and only their output is defused first. An
+# MCP tool or a fetched page ending in a well-formed __FILES__ line is content,
+# not an envelope, and stripping it would take that line away from the model.
+_SANDBOX_TOOLS = frozenset({"python", "terminal"})
+
+
+def strip_result_for_model(result: str, tool_name: "str | None" = None) -> str:
"""Remove frontend-only sentinels (image paths, RAG source map) before
feeding the result back to the model."""
result = _strip_mcp_image_suffix(result)
+ if tool_name is None or tool_name in _SANDBOX_TOOLS:
+ result = _strip_files_sentinel(result)
for sentinel in ("__IMAGES__:", "__RAG_SOURCES__:"):
if sentinel in result:
result = result.split(sentinel, 1)[0].rstrip()
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index f0d19211d4d..01b7b747fb3 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -8,6 +8,8 @@ import ast
import codecs
import fnmatch
import functools
+import hashlib
+import json
import http.client
import os
import signal
@@ -21,10 +23,13 @@ import re
import shlex
import shutil
import ssl
+from stat import S_ISREG
import subprocess
import sys
import tempfile
+import contextlib
import threading
+import uuid
import time
import urllib.parse
import urllib.request
@@ -7120,18 +7125,472 @@ def _get_shell_cmd(command: str) -> list[str]:
# Per-session working directories so each chat thread gets its own sandbox.
# Falls back to ~/studio_sandbox/_default for callers without a session_id.
_workdirs: dict[str, str] = {}
+# Sessions with a tool call in flight. Deleting a chat unlinks its workdir, and
+# a process whose cwd has been removed fails every relative write with ENOENT.
+_active_sessions: "dict[str, int]" = {}
+# Deletions that arrived mid-call: the thread has gone from history, so nothing
+# would ask for the folder again. Keyed like the above and holding every exact
+# id that folded onto the key, since each can be its own directory.
+_pending_removals: "dict[str, dict[str, bool]]" = {}
+_active_sessions_lock = threading.Lock()
+# Sessions whose sandbox is being removed right now. A start for one of these
+# waits on the condition rather than on the lock, so only that chat is held up.
+_removing_sessions: "set[str]" = set()
+_sessions_free = threading.Condition(_active_sessions_lock)
+
+
+def _session_key(session_id: "str | None") -> str:
+ """Lifecycle key for a session id.
+
+ Case-folded: two ids differing only in case are one directory on Windows and
+ on a default macOS volume, and keying them apart let a delete land while the
+ other chat was running a tool in there.
+ """
+ return (session_id or _ANON_KEY).casefold()
+
+
+def _session_in_flight(session_id: "str | None"):
+ key = _session_key(session_id)
+ with _sessions_free:
+ # A removal for this session runs with the lock released, so a call
+ # starting in that window would be handed the directory it is about to
+ # rename away. Only this session waits; every other chat is untouched.
+ while key in _removing_sessions:
+ _sessions_free.wait()
+ first = _active_sessions.get(key, 0) == 0
+ _active_sessions[key] = _active_sessions.get(key, 0) + 1
+ try:
+ yield
+ finally:
+ pending: "dict[str, bool]" = {}
+ with _sessions_free:
+ if _active_sessions.get(key, 0) <= 1:
+ _active_sessions.pop(key, None)
+ pending = _pending_removals.pop(key, {})
+ if pending:
+ _removing_sessions.add(key)
+ else:
+ _active_sessions[key] -= 1
+ if not pending:
+ return
+ # Outside the lock: deciding whether the tree holds files can take
+ # seconds, and no other chat could start a call meanwhile. This session
+ # stays closed, so nothing starts in the directory being removed.
+ try:
+ for pending_id, pending_files in pending.items():
+ if _thread_exists(pending_id, unknown = True):
+ # Recreated while that call ran: this delete belongs to the
+ # chat that went, and the folder is the new one's now.
+ continue
+ _remove_session_sandbox_locked(pending_id, pending_files)
+ finally:
+ with _sessions_free:
+ _removing_sessions.discard(key)
+ _sessions_free.notify_all()
# Non-matching session_ids collapse to ``_invalid`` to block cross-session escapes.
_SESSION_ID_RE = re.compile(r"\A[A-Za-z0-9_\-]{1,64}\Z")
+# Reserved on Windows even as a directory name, and an API caller picks this id.
+_WINDOWS_DEVICE_NAMES = frozenset(
+ ["con", "prn", "aux", "nul"]
+ + [f"com{i}" for i in range(1, 10)]
+ + [f"lpt{i}" for i in range(1, 10)]
+)
_PROJECT_SESSION_PREFIX = "project-"
+def _usable_session_id(session_id: str) -> bool:
+ """Matches the id charset and is a name every OS can hold as a directory."""
+ if not _SESSION_ID_RE.match(session_id):
+ return False
+ return session_id.split(".")[0].lower() not in _WINDOWS_DEVICE_NAMES
+
+
+def _orphan_records_dir() -> str:
+ """Where a preserved project workspace's path is written down.
+
+ One small file per project, named by its id: the row that knew the path is
+ gone, and a workspace the user pointed somewhere custom cannot be derived
+ from anything else.
+ """
+ try:
+ from utils.paths.storage_roots import studio_root
+ return os.path.join(str(studio_root()), "orphaned-projects")
+ except Exception:
+ # Only if the studio home cannot be resolved at all: beside the sandbox
+ # root, whose parent an administrator may have made read-only.
+ return os.path.join(
+ os.path.dirname(os.path.realpath(sandbox_root())),
+ "orphaned-projects",
+ )
+
+
+# One record per kept folder, named by kind and a digest of the id, with the
+# exact id inside: chats and projects are different tables and can carry the
+# same client-supplied id, which is not always one a filename can hold.
+_ORPHAN_CHAT = "chat"
+_ORPHAN_PROJECT = "project"
+# A pass reads every record: they are a few hundred bytes each, one per deleted
+# folder still kept, and a cap here would strand everything past it for good.
+_MAX_ORPHAN_RECORDS = 10_000
+
+
+def _orphan_record_name(kind: str, record_id: str) -> str:
+ """The filename a record is kept under."""
+ digest = hashlib.sha256(record_id.encode("utf-8", "surrogatepass")).hexdigest()[:32]
+ return f"{kind}-{digest}"
+
+
+def _read_orphan_record(kind: str, record_id: str) -> "dict | None":
+ """One record by key, without listing the directory."""
+ import json as _json
+
+ path = os.path.join(_orphan_records_dir(), _orphan_record_name(kind, record_id))
+ try:
+ with open(path, encoding = "utf-8") as fh:
+ record = _json.loads(fh.read(4096).strip())
+ except (OSError, ValueError, TypeError):
+ return None
+ return record if isinstance(record, dict) and record.get("path") else None
+
+
+def record_orphaned_project(
+ project_id: str,
+ workspace: str,
+ pending_delete: bool = False,
+ root_path: "str | None" = None,
+) -> None:
+ """Remember where a deleted project's kept workspace lives.
+
+ Written whether or not files were to be deleted: the row that knew the path
+ has gone either way, and a chat forked out of the project still shows cards
+ for it. ``pending_delete`` is what separates "keep this, just make it
+ reachable" from "the user asked for it, finish when nothing is using it".
+ """
+ if not project_id or not workspace:
+ return
+ _write_orphan_record(
+ _ORPHAN_PROJECT,
+ project_id,
+ {
+ "path": os.path.realpath(workspace),
+ # The whole workspace is what the delete dialog offers, and the sandbox
+ # is one directory inside it.
+ "rootPath": os.path.realpath(root_path) if root_path else None,
+ "pendingDelete": bool(pending_delete),
+ },
+ )
+
+
+def _write_orphan_record(kind: str, record_id: str, record: dict) -> None:
+ """One small JSON file per kept folder, under its kind and id."""
+ import json as _json
+
+ record = {**record, "id": record_id, "chat": kind == _ORPHAN_CHAT}
+ try:
+ os.makedirs(_orphan_records_dir(), exist_ok = True)
+ name = _orphan_record_name(kind, record_id)
+ with open(os.path.join(_orphan_records_dir(), name), "w", encoding = "utf-8") as fh:
+ fh.write(_json.dumps(record))
+ except OSError:
+ logger.warning("Could not record kept folder for %s", record_id)
+
+
+def record_kept_sandbox(session_id: str) -> None:
+ """Remember a chat sandbox kept because a fork still shows its files.
+
+ The user asked for those files and the chat is gone, so nothing would come
+ back to that folder: the fork's own delete finishes the job instead.
+ """
+ if not session_id:
+ return
+ try:
+ workdir = os.path.realpath(resolve_sandbox_workdir(session_id))
+ except OSError:
+ return
+ if not os.path.isdir(workdir):
+ return
+ _write_orphan_record(
+ _ORPHAN_CHAT,
+ session_id,
+ {"path": workdir, "rootPath": None, "pendingDelete": True},
+ )
+
+
+def forget_orphaned_project(project_id: str, is_chat: bool = False) -> None:
+ """Drop the record once the folder has gone."""
+ if not project_id:
+ return
+ kind = _ORPHAN_CHAT if is_chat else _ORPHAN_PROJECT
+ try:
+ os.unlink(os.path.join(_orphan_records_dir(), _orphan_record_name(kind, project_id)))
+ except OSError:
+ pass
+
+
+def list_orphaned_projects() -> "list[tuple[str, str, str | None, bool, bool]]":
+ """Every recorded (id, folder, project root, pending, is a chat) still there."""
+ import json as _json
+
+ records = []
+ try:
+ names = sorted(os.listdir(_orphan_records_dir()))
+ except OSError:
+ return records
+ if len(names) > _MAX_ORPHAN_RECORDS:
+ logger.warning(
+ "%d kept-folder records; reading the first %d", len(names), _MAX_ORPHAN_RECORDS
+ )
+ names = names[:_MAX_ORPHAN_RECORDS]
+ for name in names:
+ try:
+ with open(os.path.join(_orphan_records_dir(), name), encoding = "utf-8") as fh:
+ raw = fh.read(4096).strip()
+ except OSError:
+ continue
+ try:
+ record = _json.loads(raw)
+ path, pending = record["path"], bool(record.get("pendingDelete"))
+ root = record.get("rootPath") or None
+ is_chat = bool(record.get("chat"))
+ record_id = record["id"]
+ except (ValueError, TypeError, KeyError):
+ continue
+ if _recorded_workspace_remains(path, root):
+ records.append((record_id, path, root, pending, is_chat))
+ else:
+ forget_orphaned_project(record_id, is_chat)
+ return records
+
+
+def _recorded_workspace_remains(workspace: str, root: "str | None") -> bool:
+ """Whether anything a record names is still on disk.
+
+ The project root as well as its sandbox: a delete that removed the sandbox
+ and stopped at a locked file elsewhere leaves the rest of the workspace,
+ and dropping the record here loses both the path and the user's request.
+ """
+ for path in (workspace, root):
+ if path and os.path.isdir(path) and not os.path.islink(path):
+ return True
+ return False
+
+
+def forget_orphaned_project_if_gone(
+ project_id: str,
+ workspace: str,
+ root: "str | None",
+ is_chat: bool = False,
+) -> None:
+ """Drop the record only once the folder has gone."""
+ if _recorded_workspace_remains(workspace, root):
+ logger.warning("Workspace for %s is still there; left pending", project_id)
+ return
+ forget_orphaned_project(project_id, is_chat)
+
+
+def _delete_recorded_workspace(project_id: str, workspace: str, root: "str | None") -> None:
+ """Remove a recorded workspace the way the immediate delete would.
+
+ Always through the storage helper, whose folder-name and denied-path checks
+ decide what may go: a record is a file on disk, and a stale or edited one
+ naming an unrelated directory must not become an rmtree of it. Without a
+ recorded root the workspace's own parent is offered, which is what the
+ default layout puts the sandbox in; anything else it refuses, and the
+ record stays pending rather than being deleted on our own authority.
+ """
+ from storage.studio_db import delete_project_workspace
+
+ target = root or os.path.dirname(os.path.realpath(workspace))
+ delete_project_workspace({"id": project_id, "rootPath": target})
+
+
+def collect_orphaned_project_workspaces() -> None:
+ """Finish the workspace deletes the user asked for.
+
+ Only records marked pending: one kept merely so a fork's cards resolve is
+ not something anybody asked to remove. Skipped while a tool call is still
+ running in there, or while a chat still shows its files.
+ """
+ from storage.studio_db import sandbox_is_referenced_elsewhere
+ for record_id, workspace, root, pending, is_chat in list_orphaned_projects():
+ if not pending:
+ continue
+ try:
+ session = record_id if is_chat else project_session_id(record_id)
+ # This runs minutes after the row went, and the id is the client's
+ # to reuse: a chat or a project created since owns that folder, and
+ # a card of its own may not be stored yet.
+ recreated = (
+ _thread_exists(record_id, unknown = True)
+ if is_chat
+ else live_project_owns(record_id, workspace, root)
+ )
+ if recreated:
+ logger.info("Kept %s: it was created again", record_id)
+ continue
+ if not wait_for_sessions_idle([session], timeout = 0.0):
+ continue
+ if sandbox_is_referenced_elsewhere(session):
+ continue
+ if is_chat:
+ # Its own ownership checks decide whether that directory is
+ # ours to take, exactly as the chat's own delete would.
+ remove_session_sandbox(session, delete_files = True)
+ else:
+ _delete_recorded_workspace(record_id, workspace, root)
+ # A locked file on Windows, or a network volume having a bad
+ # moment: the record stays so the next launch tries again.
+ forget_orphaned_project_if_gone(record_id, workspace, root, is_chat)
+ except Exception: # noqa: BLE001 - a stuck record must not break a delete
+ logger.warning("Could not collect workspace for %s", record_id, exc_info = True)
+
+
+def finish_workspace_delete_when_idle(
+ project_id: str, timeout: float = 600.0
+) -> "threading.Thread":
+ """Wait out the tool call still using a workspace, then delete it.
+
+ The delete dialog promised those files would go, and nothing else would
+ come back to them: the collection otherwise runs only on the next delete.
+ """
+
+ def _wait_and_collect() -> None:
+ session = project_session_id(project_id)
+ wait_for_sessions_idle([session], timeout = timeout)
+ collect_orphaned_project_workspaces()
+
+ thread = threading.Thread(
+ target = _wait_and_collect,
+ name = "workspace-delete",
+ daemon = True,
+ )
+ thread.start()
+ return thread
+
+
+def _recorded_project_workdir(project_id: str) -> "str | None":
+ """The kept workspace of a deleted project, wherever the user put it.
+
+ By key: a resolve happens on every tool call for such a project, and no
+ number of other records may keep it from finding its own.
+ """
+ record = _read_orphan_record(_ORPHAN_PROJECT, project_id)
+ if not record:
+ return None
+ path = record["path"]
+ # Only a sandbox still there: a record kept alive by the rest of its
+ # workspace names a directory nothing can be served from.
+ return path if os.path.isdir(path) else None
+
+
+def _orphaned_project_workdir(project_id: str) -> "str | None":
+ """A deleted project's workspace, when its files were kept.
+
+ The record answers for any id, since it is keyed by a digest. Only the
+ guess below builds a directory name, so only that needs an id a filename
+ can hold.
+ """
+ recorded = _recorded_project_workdir(project_id)
+ if recorded:
+ return recorded
+ if not _usable_session_id(project_id):
+ return None
+ suffix = re.sub(r"[^A-Za-z0-9_-]+", "-", project_id)[:8].strip("-_") or "project"
+ try:
+ from utils.paths import project_workspaces_root
+ root = str(project_workspaces_root())
+ names = sorted(os.listdir(root))[:_MAX_SNAPSHOT_DIRS]
+ except Exception:
+ return None
+ for entry in names:
+ if not entry.endswith(f"-{suffix}"):
+ continue
+ candidate = os.path.join(root, entry, "sandbox")
+ if os.path.isdir(candidate) and not os.path.islink(candidate):
+ return os.path.realpath(candidate)
+ return None
+
+
+def _thread_exists(thread_id: str, unknown: bool = False) -> bool:
+ """Whether a chat of the user's is stored under this exact id.
+
+ ``unknown`` is what a check that could not be made returns: a caller about
+ to delete files passes True, so a database hiccup keeps them, while one
+ merely routing a call passes False and treats the id as a project's.
+ """
+ try:
+ from storage.studio_db import get_chat_thread
+ return get_chat_thread(thread_id) is not None
+ except Exception: # noqa: BLE001 - see `unknown`
+ return unknown
+
+
+def live_project_owns(
+ project_id: str,
+ workspace: str,
+ root: "str | None" = None,
+) -> bool:
+ """Whether a project with this id is the one those folders belong to.
+
+ A reused id is not the same workspace: the default root carries the
+ project's name, and renaming a project leaves its root where it was. A
+ folder the live row does not own is still the deleted project's, and still
+ the one the user asked to remove.
+ """
+ try:
+ from storage.studio_db import get_chat_project
+ project = get_chat_project(project_id)
+ except Exception: # noqa: BLE001 - an unanswerable check keeps the files
+ return True
+ if not project:
+ return False
+ live = [project.get("rootPath"), project.get("sandboxPath")]
+ theirs = {os.path.realpath(path) for path in live if path}
+ for path in (workspace, root):
+ if not path:
+ continue
+ resolved = os.path.realpath(path)
+ if any(resolved == one or resolved.startswith(one + os.sep) for one in theirs):
+ return True
+ return False
+
+
+def _project_exists(project_id: str) -> bool:
+ """Whether a project of the user's is stored under this exact id."""
+ try:
+ from storage.studio_db import get_chat_project
+ return get_chat_project(project_id) is not None
+ except Exception: # noqa: BLE001 - a storage hiccup must not delete files
+ return True
+
+
+def _project_workdir_for(session_id: "str | None") -> "str | None":
+ """The project workspace a session id names, if it names one.
+
+ The prefixed id can be longer than a directory name may be, or carry a
+ character one may not: it is the project part that has to be usable, and
+ the workspace path comes from the row rather than from the id.
+ """
+ if not session_id:
+ return None
+ if not _usable_session_id(session_id) and not session_id.startswith(_PROJECT_SESSION_PREFIX):
+ return None
+ return _get_project_workdir(session_id)
+
+
def _get_project_workdir(session_id: str) -> str | None:
if not session_id.startswith(_PROJECT_SESSION_PREFIX):
return None
project_id = session_id[len(_PROJECT_SESSION_PREFIX) :]
- if not project_id or not _SESSION_ID_RE.match(project_id):
+ if not project_id:
+ return None
+ if _thread_exists(session_id):
+ # An API client picks its own thread ids, and a chat called this is a
+ # chat: sharing the project's workspace would run its tool calls in
+ # there and leave its delete refusing to remove anything.
return None
try:
from storage.studio_db import ensure_chat_project_workspace
@@ -7140,7 +7599,10 @@ def _get_project_workdir(session_id: str) -> str | None:
logger.warning("Failed to resolve project sandbox for %s", session_id, exc_info = True)
return None
if not project:
- return None
+ # The project is gone but a chat forked out of it still shows cards for
+ # this sandbox, and the workspace was kept for exactly that: the record
+ # answers for any id, and the folder-name guess needs a usable one.
+ return _orphaned_project_workdir(project_id)
root_path = project.get("rootPath")
sandbox_path = project.get("sandboxPath")
if not root_path or not sandbox_path:
@@ -7152,37 +7614,763 @@ def _get_project_workdir(session_id: str) -> str | None:
return sandbox_real
+# Dropped in every session directory we create. The root can be an existing
+# shared folder the user pointed us at, and a chat id can name something already
+# in there; this is the only evidence the directory is ours to delete.
+_SANDBOX_MARKER = ".unsloth_sandbox"
+
+# Reserved: a directory named this way belongs to the id that hashes to it, and
+# never to a chat that happens to be called the same thing.
+_DERIVED_PREFIX = "_id-"
+
+# The directories a call with no usable session id runs in. A chat whose id is
+# one of these gets a derived name instead of sharing that folder, and with it
+# every session-less call's files and the delete that takes them.
+_FALLBACK_NAMES = frozenset({"_default", "_invalid"})
+
+# The cache and lifecycle key for a call with no session id. Holds a character
+# the id charset forbids, so a chat cannot key onto the same entry and be handed
+# the session-less sandbox out of the cache.
+_ANON_KEY = "\x00_default"
+
+
+def _sandbox_name(session_id: str) -> str:
+ """The directory name for an id.
+
+ An id the filesystem cannot hold gets a name derived from it rather than a
+ shared bucket: those ids come from API clients, and one bucket meant every
+ such chat could read and delete every other one's files.
+ """
+ if (
+ _usable_session_id(session_id)
+ and not session_id.startswith(_DERIVED_PREFIX)
+ and session_id not in _FALLBACK_NAMES
+ ):
+ return session_id
+ # An id that already looks derived is derived too, or it would land on the
+ # directory of whichever unusable id hashes to it. surrogatepass because a
+ # lone surrogate reaches here from JSON and from surrogateescape alike.
+ encoded = session_id.encode("utf-8", "surrogatepass")
+ return _DERIVED_PREFIX + hashlib.sha256(encoded).hexdigest()[:16]
+
+
+def _preserve_foreign_marker(workdir: str, name: "str | None" = None) -> None:
+ """Move aside a marker-named entry that this migration did not write.
+
+ This name was not reserved before the change, so a chat that wrote its own
+ .unsloth_sandbox has a real file there, and a short note like "notes" reads
+ as a perfectly good session name. Only the exact marker this move is about
+ to write is left alone; everything else is renamed, not removed.
+ """
+ marker = os.path.join(workdir, _SANDBOX_MARKER)
+ if not os.path.lexists(marker):
+ return
+ if name is not None and _marker_owner(workdir) == _sandbox_name(name):
+ return # already ours, from a move that ran before
+ for n in range(1, 100):
+ kept = f"{marker}.saved" if n == 1 else f"{marker}.saved-{n}"
+ if not os.path.lexists(kept):
+ try:
+ os.rename(marker, kept)
+ except OSError:
+ logger.warning("Could not preserve %s", marker)
+ return
+
+
+def _mark_sandbox(workdir: str, session_id: str) -> None:
+ """(Re)write the marker. Never through a link.
+
+ The file sits where tool code runs, so one replaced by a symlink would send
+ this write to whatever it points at and truncate it.
+ """
+ marker = os.path.join(workdir, _SANDBOX_MARKER)
+ try:
+ if os.path.islink(marker):
+ os.unlink(marker)
+ flags = os.O_CREAT | os.O_WRONLY | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
+ fd = os.open(marker, flags, 0o600)
+ try:
+ os.write(fd, _sandbox_name(session_id).encode("utf-8"))
+ finally:
+ os.close(fd)
+ except OSError:
+ pass
+
+
+def _marker_owner(workdir: str) -> "str | None":
+ """The id this directory was created for, when it says.
+
+ Anything that is not an id reads as no owner rather than as somebody else's:
+ a tool writing over this file would otherwise send its own chat to a fresh
+ directory on the next launch, leaving its files behind.
+ """
+ marker = os.path.join(workdir, _SANDBOX_MARKER)
+ if os.path.islink(marker):
+ return None # not a marker we wrote, and not one to follow
+ try:
+ with open(marker, encoding = "utf-8") as fh:
+ owner = fh.read(256).strip()
+ except (OSError, UnicodeDecodeError):
+ return None
+ return owner if owner and _usable_session_id(owner) else None
+
+
+def _session_dir(root: str, session_id: str) -> str:
+ """The directory for this exact id.
+
+ Two ids differing only in case are one name on Windows and on a default
+ macOS volume. The marker says which id made the directory, and anyone else
+ gets one of their own rather than sharing files that either chat's deletion
+ would then remove. A directory already sitting in a root the user pointed
+ us at is nobody's sandbox: it is stepped around rather than run in, so no
+ tool can write a marker into it and make it look like ours.
+ """
+ name = _sandbox_name(session_id)
+ plain = os.path.join(root, name)
+ # A link is never ours, whatever it points at: claiming through one writes
+ # the marker into a directory somebody else made, inside the root or not.
+ if not os.path.islink(plain):
+ owner = _marker_owner(plain)
+ if owner == name:
+ return plain
+ if owner is None and not (os.path.isdir(plain) and not _root_is_ours()):
+ return plain
+ # Taken by something that is not ours, so this chat gets a name of its own.
+ return os.path.join(root, f"{name}-{_name_suffix(session_id)}")
+
+
+def _name_suffix(session_id: str) -> str:
+ """A short stable tail, so the same chat lands in the same directory.
+
+ surrogatepass for the same reason _sandbox_name uses it: an id with a lone
+ surrogate reaches here on the collision path, and a strict encode would
+ raise rather than step aside.
+ """
+ encoded = session_id.encode("utf-8", "surrogatepass")
+ return hashlib.sha256(encoded).hexdigest()[:8]
+
+
+# Serialises the pick-then-create below. Two case-variant ids racing on a
+# case-insensitive volume could otherwise both see an unowned name and take it.
+_assign_lock = threading.Lock()
+
+
+# Directories this run created and claimed. Not a record of ownership beyond
+# this process: it is what lets a marker a tool removed be written again.
+_claimed_here: "set[str]" = set()
+
+
+def _claim_sandbox(workdir: str, session_id: str) -> bool:
+ """Write the marker if nobody has, and report whether this id owns it.
+
+ O_EXCL, so of two processes creating the same directory exactly one claims
+ it and the other is told to go elsewhere.
+ """
+ marker = os.path.join(workdir, _SANDBOX_MARKER)
+ name = _sandbox_name(session_id)
+ try:
+ fd = os.open(marker, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ except FileExistsError:
+ return _marker_owner(workdir) == name
+ except OSError:
+ return False
+ try:
+ os.write(fd, name.encode("utf-8"))
+ finally:
+ os.close(fd)
+ _claimed_here.add(workdir)
+ return True
+
+
+def _ensure_session_dir(root: str, session_id: str) -> str:
+ """Create this id's sandbox and claim it, stepping aside on a collision."""
+ with _assign_lock:
+ workdir = _session_dir(root, session_id)
+ if not _contained_in_root(workdir, root):
+ return _sandbox_fallback(root, "_invalid")
+ # Before creating anything: _session_dir can hand back the fallback
+ # name, which in a root the user pointed us at can be a directory of
+ # theirs, and claiming it would run this chat inside their files.
+ if not os.path.exists(workdir):
+ # A tree an interrupted migration left marked but not moved in is
+ # this chat's, at any root: starting fresh beside it would leave
+ # those files unreachable for good.
+ stranded = _marked_sandbox_in(root, session_id)
+ if stranded:
+ try:
+ os.rename(stranded, workdir)
+ except OSError:
+ return stranded
+ return workdir
+ if not _free_for(workdir, _sandbox_name(session_id)) and not _root_is_ours():
+ workdir = _free_fallback_dir(root, session_id)
+ if workdir is None or not _contained_in_root(workdir, root):
+ return _sandbox_fallback(root, "_invalid")
+ os.makedirs(workdir, exist_ok = True)
+ if _claim_sandbox(workdir, session_id):
+ return workdir
+ # A marker naming nobody is one a tool wrote over, and at our own root
+ # nothing else could have put this directory here.
+ if _root_is_ours() and _marker_owner(workdir) is None:
+ _mark_sandbox(workdir, session_id)
+ return workdir
+ # Somebody else's, so take a name of our own rather than run inside it.
+ # The fallback is in the same user-controlled root, so it gets the same
+ # test: an unowned directory already sitting there is theirs too.
+ workdir = _free_fallback_dir(root, session_id)
+ if workdir is None or not _contained_in_root(workdir, root):
+ return _sandbox_fallback(root, "_invalid")
+ os.makedirs(workdir, exist_ok = True)
+ _claim_sandbox(workdir, session_id)
+ return workdir
+
+
+def _marked_sandbox_in(root: str, session_id: str) -> "str | None":
+ """A directory in *root* whose marker names this chat, if there is one.
+
+ A fresh fallback has a name nothing can recompute, so this is what finds it
+ again on a later launch, on a read and on a delete. Bounded: a root the
+ user pointed us at can hold a lot of their own folders.
+ """
+ name = _sandbox_name(session_id)
+ # Only names derived from this id, the plain name a half-finished migration
+ # staged beside, and their staging names: tool code can write any owner into
+ # the marker, so "whoever claims to be me" would hand over another's files.
+ candidates = [os.path.join(root, name), *_fallback_candidates(root, session_id)]
+ # Listed once: there are 33 candidate names, and a scan each would be 33
+ # walks of a root that can hold a folder per chat, on a first call.
+ try:
+ entries = sorted(os.listdir(root))
+ except OSError:
+ entries = []
+ for candidate in candidates:
+ base = os.path.basename(candidate)
+ prefix = f"{base}{_STAGING_SUFFIX}"
+ staged = [os.path.join(root, e) for e in entries if e.startswith(prefix)]
+ for path in [candidate, *staged]:
+ if os.path.islink(path) or not os.path.isdir(path):
+ continue
+ if _marker_owner(path) == name:
+ return path
+ return None
+
+
+def _free_fallback_dir(root: str, session_id: str) -> "str | None":
+ """A name in *root* this chat may take, or None when they are all spoken for.
+
+ The deterministic one first, so the same chat comes back to the same folder,
+ then a fresh one rather than running inside anything already there.
+ """
+ # One we already made wins, wherever it is: a fresh name every launch would
+ # scatter this chat's files.
+ ours = _marked_sandbox_in(root, session_id)
+ if ours:
+ return ours
+ for candidate in _fallback_candidates(root, session_id):
+ if _free_for(candidate, _sandbox_name(session_id)):
+ return candidate
+ return None
+
+
+# How many derived names a chat may try in a root the user pointed us at. Each
+# is recomputable, so a later launch finds the folder by name; a random name
+# needed a scan, which a big enough root pushes past its bound.
+_MAX_FALLBACK_NAMES = 32
+
+
+def _fallback_candidates(root: str, session_id: str) -> "list[str]":
+ """The names this chat may take, in the order it takes them."""
+ name = _sandbox_name(session_id)
+ stem = f"{name}-{_name_suffix(session_id)}"
+ return [os.path.join(root, stem)] + [
+ os.path.join(root, f"{stem}-{n}") for n in range(2, _MAX_FALLBACK_NAMES + 1)
+ ]
+
+
+def _free_for(path: str, name: str) -> bool:
+ """Whether we may run in *path*: ours already, or not there at all."""
+ if os.path.islink(path):
+ return False
+ if not os.path.exists(path):
+ return True
+ return _marker_owner(path) == name
+
+
+def _root_is_ours() -> bool:
+ """True unless the root is a directory the user pointed us at.
+
+ A link is theirs as well: `<studio home>/sandbox` pointing somewhere else
+ means the directories under it are the user's, and "ours by construction"
+ is what lets a delete rename and remove one of them.
+ """
+ if (os.environ.get("UNSLOTH_STUDIO_SANDBOX_HOME") or "").strip():
+ return False
+ try:
+ return not os.path.islink(sandbox_root())
+ except OSError:
+ return False
+
+
+def _sandbox_is_ours(target: str) -> bool:
+ """Ours by construction at our own root, otherwise only with the marker.
+
+ A real file: isfile() follows a link, so a marker symlinked at any existing
+ file would make an unrelated directory in a shared root deletable.
+ """
+ if _root_is_ours():
+ return True
+ marker = os.path.join(target, _SANDBOX_MARKER)
+ return os.path.isfile(marker) and not os.path.islink(marker)
+
+
+def _legacy_sandbox_root() -> str:
+ """Where the sandbox used to live: a third folder in the user's home."""
+ return os.path.join(os.path.expanduser("~"), "studio_sandbox")
+
+
+def sandbox_root() -> str:
+ """Root of the per-session tool sandboxes.
+
+ Under the studio home, so UNSLOTH_STUDIO_HOME keeps everything in one place
+ instead of leaving a stray ~/studio_sandbox. Falls back to the legacy path
+ only if the studio root cannot be resolved.
+ """
+ override = (os.environ.get("UNSLOTH_STUDIO_SANDBOX_HOME") or "").strip()
+ if override:
+ return os.path.expanduser(override)
+ try:
+ from utils.paths.storage_roots import studio_root
+ return os.path.join(str(studio_root()), "sandbox")
+ except Exception:
+ return _legacy_sandbox_root()
+
+
+_legacy_sandbox_migrated = False
+_legacy_sandbox_lock = threading.Lock()
+
+
+# Where a cross-filesystem move is assembled. Not a session name, so nothing
+# resolves to it while it is being filled.
+_STAGING_SUFFIX = ".arriving-"
+
+
+def _free_move_target(root: str, name: str) -> "str | None":
+ """A name in *root* nothing occupies, for a legacy move to land on.
+
+ The resolver's own answer first, so an untouched root keeps the plain name.
+ Both derived names can be the user's in a root they pointed us at, and
+ returning nothing there stranded the files at the legacy root for good: the
+ marker the move writes is what finds this one again.
+ """
+ candidate = _session_dir(root, name)
+ if not os.path.exists(candidate):
+ return candidate
+ if _marker_owner(candidate) == _sandbox_name(name):
+ # This session's folder is already at the destination from an earlier
+ # move. A duplicate legacy copy is left alone rather than overwritten,
+ # or moved somewhere the user could no longer find it.
+ return None
+ if _root_is_ours():
+ return None # ours and occupied is a real collision, not a borrowed name
+ # The same derived names the request path takes, so whichever runs first the
+ # other one resolves to the folder that ended up holding the files.
+ for candidate in _fallback_candidates(root, name):
+ if not os.path.exists(candidate):
+ return candidate
+ return None
+
+
+def _staged_move(source: str, target: str, name: str) -> None:
+ """Move one session in, so an interruption cannot look like a collision.
+
+ Across filesystems shutil.move copies as it goes, and a run killed part way
+ leaves a partial destination with the original still in place. The next
+ launch would read that as a session the new root already has and strand the
+ files. Filled under a name nothing resolves to, then renamed, which on one
+ filesystem is atomic.
+ """
+ staging = f"{target}{_STAGING_SUFFIX}{uuid.uuid4().hex[:8]}"
+ try:
+ shutil.move(source, staging)
+ except OSError:
+ # Half filled and ours, and the source is still where it was.
+ shutil.rmtree(staging, ignore_errors = True)
+ raise
+ # Marked here, not after the rename: across filesystems the move has already
+ # removed the legacy copy, so from this instant the staging tree is the only
+ # one there is and a kill before the marker would leave it unfindable.
+ _preserve_foreign_marker(staging, name)
+ _mark_sandbox(staging, name)
+ try:
+ os.rename(staging, target)
+ except OSError:
+ # The move already took the legacy copy, so this tree is the only one
+ # and deleting it would lose the files. It is marked, so
+ # _marked_sandbox_in finds it; put it back and let the next pass retry.
+ try:
+ os.rename(staging, source)
+ except OSError:
+ logger.warning("Sandbox %s left at %s: could not be moved in", name, staging)
+ raise
+ _mark_sandbox(target, name)
+
+
+# Bookkeeping only, never held across a move: starting the background pass and
+# the sweep. Anything that copies a tree takes that session's own lock below.
+_legacy_one_lock = threading.Lock()
+
+# One lock per session being moved: a single lock made a first tool call wait
+# out another chat's multi-gigabyte copy, which is what the background pass
+# exists to avoid. Bounded by the chats that had a legacy folder.
+_legacy_session_locks: "dict[str, threading.Lock]" = {}
+_legacy_locks_guard = threading.Lock()
+
+
+def _legacy_lock_for(name: str) -> threading.Lock:
+ """The lock covering this one session's move."""
+ with _legacy_locks_guard:
+ return _legacy_session_locks.setdefault(name, threading.Lock())
+
+
+# Where every id the old code could not use as a directory name went. One
+# bucket for all of them, which is what this change stops doing, so it is never
+# moved up as though it were a chat: several chats' files are in there.
+_LEGACY_SHARED_BUCKET = "_invalid"
+
+
+def _legacy_session_dir(session_id: str) -> "str | None":
+ """This session's directory at the legacy root, while one is still there.
+
+ Both names, like the migration itself: a chat from before the upgrade whose
+ id starts with the derived prefix kept its folder under the literal id.
+ """
+ legacy_root = _legacy_sandbox_root()
+ names = [_sandbox_name(session_id)]
+ if not _usable_session_id(session_id):
+ # Before this change an id the filesystem could not hold shared one
+ # bucket with every other such chat: read where they are, never moved or
+ # deleted, and only for such an id, or a chat reads somebody else's.
+ names.append(_LEGACY_SHARED_BUCKET)
+ elif session_id not in names and session_id not in _FALLBACK_NAMES:
+ # Only the derived-prefix case: an id the old code could hold kept its
+ # folder under the literal name while _sandbox_name now hashes it. A
+ # fallback name is nobody's chat: every session-less call ran in there.
+ names.append(session_id)
+ for name in names:
+ candidate = os.path.join(legacy_root, name)
+ if not os.path.isdir(candidate) or os.path.islink(candidate):
+ continue
+ # Under this session's move lock, and checked again inside it: the move
+ # is a rename, so a path handed back mid-move lists nothing and 404s
+ # every card. One that already ran sends the caller to the destination.
+ with _legacy_lock_for(name):
+ if os.path.isdir(candidate) and not os.path.islink(candidate):
+ return candidate
+ return None
+
+
+def _migrate_one_legacy_session(root: str, name: str) -> None:
+ """Bring one session up from the legacy root, without waiting for the rest."""
+ if _legacy_sandbox_migrated:
+ return
+ source = os.path.join(_legacy_sandbox_root(), name)
+ if os.path.islink(source) or not os.path.isdir(source):
+ return
+ with _legacy_lock_for(name):
+ if not os.path.isdir(source):
+ return # the background pass got there first
+ # Through the resolver, like the whole-tree pass: at a shared root the
+ # plain name can be the user's own, and stopping here would leave this
+ # chat with an empty sandbox and its files stranded at the old root.
+ target = _free_move_target(root, name)
+ if target is None or not _contained_in_root(target, root):
+ return # nowhere free to land, left for the whole-tree pass
+ try:
+ os.makedirs(root, exist_ok = True)
+ _staged_move(source, target, name)
+ except OSError as error:
+ logger.warning("Could not move sandbox %s: %s", name, error)
+
+
+_legacy_background: "threading.Thread | None" = None
+
+
+def _start_legacy_migration() -> "threading.Thread | None":
+ """Carry the rest of the tree up, one pass at a time, off this request."""
+ global _legacy_background
+ if _legacy_sandbox_migrated:
+ return None
+ with _legacy_one_lock:
+ if _legacy_background is not None and _legacy_background.is_alive():
+ return _legacy_background
+ _legacy_background = migrate_legacy_sandbox_in_background()
+ return _legacy_background
+
+
+def _migrate_legacy_sandbox(root: str) -> None:
+ """Move sessions from ~/studio_sandbox into the studio home, once.
+
+ Those files are the user's, so they move rather than being dropped. A
+ session already present at the new root wins and its legacy copy is left
+ alone, so nothing is silently overwritten.
+ """
+ global _legacy_sandbox_migrated
+ if _legacy_sandbox_migrated:
+ return
+ # Flagged only once the move is done: setting it first let a concurrent
+ # call create the destination, which then read as a collision.
+ with _legacy_sandbox_lock:
+ if _legacy_sandbox_migrated:
+ return
+ # Only when nothing movable is left: a file locked on Windows is
+ # retryable, and one attempt strands it once the destination exists.
+ if _migrate_legacy_sandbox_locked(root):
+ _legacy_sandbox_migrated = True
+
+
+def _migrate_legacy_sandbox_locked(root: str) -> bool:
+ """True when the legacy root holds nothing that could still be moved.
+
+ A collision is not a failure: the new root already has that session, and the
+ legacy copy is deliberately left for the user to find.
+ """
+ legacy = _legacy_sandbox_root()
+ try:
+ if os.path.realpath(legacy) == os.path.realpath(root) or not os.path.isdir(legacy):
+ return True
+ os.makedirs(root, exist_ok = True)
+ moved = 0
+ complete = True
+ for name in os.listdir(legacy):
+ source = os.path.join(legacy, name)
+ # A link is not a sandbox of ours: the move preserves it, and the
+ # marker would then be written inside whatever it points at, which
+ # is a directory outside both roots.
+ if os.path.islink(source) or not os.path.isdir(source):
+ continue
+ if name == _LEGACY_SHARED_BUCKET:
+ continue # several chats' files, not one chat's
+ # The same choice the request path makes: at a shared root both
+ # derived names can be the user's, and skipping here while still
+ # reporting the pass complete stranded that chat's files for good.
+ target = _free_move_target(root, name)
+ if target is None or not _contained_in_root(target, root):
+ continue
+ try:
+ with _legacy_lock_for(name):
+ if not os.path.isdir(source) or os.path.exists(target):
+ continue # a request path moved it while we waited
+ _staged_move(source, target, name)
+ moved += 1
+ except OSError as error:
+ # A file locked on Windows is retryable, so this run reports
+ # itself unfinished and the next launch tries again.
+ complete = False
+ logger.warning("Could not move sandbox %s: %s", name, error)
+ if moved:
+ logger.info("Moved %d chat sandbox folder(s) from %s to %s", moved, legacy, root)
+ # Empty only: a leftover is a collision the user should still find.
+ try:
+ os.rmdir(legacy)
+ except OSError:
+ pass
+ return complete
+ except Exception as error: # noqa: BLE001 - startup must survive this
+ logger.warning("Sandbox migration skipped: %s", error)
+ return False
+
+
+def _sandbox_fallback(
+ root: str,
+ name: str,
+ create: bool = False,
+) -> str:
+ """``_default`` / ``_invalid`` under the root, contained like any session.
+
+ They are ordinary directories in a writable sandbox, so one replaced by a
+ symlink would otherwise become the root every unchecked request reads from.
+ Dropping that link is only ours to do at our own root; in a directory the
+ user pointed us at, the entry is theirs and a fresh one is used instead.
+ """
+ owner = _sandbox_name(name) # reserved, so it is never a chat's own name
+ path = os.path.join(root, name)
+ if os.path.islink(path):
+ if _root_is_ours():
+ try:
+ os.unlink(path)
+ return path
+ except OSError:
+ pass
+ elif _root_is_ours() or not os.path.exists(path) or _marker_owner(path) == owner:
+ return path
+ # In a root the user pointed us at, a directory already sitting under this
+ # name is theirs: a call with no session id would otherwise run in it. The
+ # one we made instead is remembered, so it is not a new one every call.
+ stem = f"{name}_{_name_suffix(name)}"
+ candidates = [os.path.join(root, stem)] + [
+ os.path.join(root, f"{stem}-{n}") for n in range(2, _MAX_FALLBACK_NAMES + 1)
+ ]
+ if not create:
+ for made in candidates:
+ if not os.path.islink(made) and _marker_owner(made) == owner:
+ return made
+ return _nothing_to_serve(name)
+ for made in candidates:
+ # exist_ok alone would take a directory of theirs that happens to carry
+ # this name, and follow a link out of the root to run wherever it
+ # points, so the entry has to be free and the claim has to succeed.
+ if not _free_for(made, owner):
+ continue
+ try:
+ os.makedirs(made, exist_ok = True)
+ except OSError:
+ continue
+ if _claim_sandbox(made, name):
+ return made
+ return _nothing_to_serve(name)
+
+
+# Where a read is sent when the chat owns nothing. Outside every sandbox root
+# and inside a directory this process makes and empties, so a listing is empty
+# and a download is a 404 rather than whatever the user keeps at that name.
+_NOTHING_ROOT = None
+_nothing_lock = threading.Lock()
+
+
+def _nothing_to_serve(name: str) -> str:
+ """A path that exists nowhere the user keeps files.
+
+ The name is derived first: callers pass the id straight from the request,
+ and an absolute one like ``/etc`` would make os.path.join drop the root it
+ was given and hand back a directory of the system's.
+ """
+ global _NOTHING_ROOT
+ leaf = _sandbox_name(name)
+ with _nothing_lock:
+ if _NOTHING_ROOT is None or not os.path.isdir(_NOTHING_ROOT):
+ try:
+ _NOTHING_ROOT = tempfile.mkdtemp(prefix = "unsloth-unowned-")
+ except OSError:
+ _NOTHING_ROOT = os.path.join(tempfile.gettempdir(), "unsloth-unowned")
+ root = _NOTHING_ROOT
+ resolved = os.path.join(root, leaf)
+ # Belt and braces: a derived name cannot escape, and neither may anything
+ # else that reaches here.
+ return resolved if _contained_in_root(resolved, root) else root
+
+
+def _contained_in_root(workdir: str, root: str) -> bool:
+ """Whether a resolved session path is still inside the sandbox root.
+
+ Applied to cached paths too: a directory replaced by a symlink after it was
+ cached would otherwise keep serving from wherever it now points.
+ """
+ try:
+ resolved, base = os.path.realpath(workdir), os.path.realpath(root)
+ # commonpath, not a prefix test: a filesystem root already ends in a
+ # separator, and appending another failed every real session path.
+ return resolved != base and os.path.commonpath([resolved, base]) == base
+ except (OSError, ValueError):
+ return False
+
+
+def _owned_by_session(workdir: str, session_id: str) -> bool:
+ """Whether this session may read *workdir*, for a caller that creates nothing.
+
+ ``_ensure_session_dir`` claims or steps aside; a read has to decide on what
+ is already there, and the name it was given can be somebody else's too.
+ """
+ owner = _marker_owner(workdir)
+ if owner is not None:
+ return owner == _sandbox_name(session_id)
+ # No marker, so the name is the only evidence, and `Foo` and `foo` are one
+ # directory on Windows and on a default macOS volume. The delete path has
+ # always asked this; a read that did not let the other chat's files through.
+ return _root_is_ours() and os.path.basename(workdir) == _sandbox_name(session_id)
+
+
def _get_workdir(session_id: str | None = None) -> str:
"""Return a per-session sandbox dir at mode 0o700."""
global _workdirs
- key = session_id or "_default"
- if key not in _workdirs or not os.path.isdir(_workdirs[key]):
- home = os.path.expanduser("~")
- sandbox_root = os.path.join(home, "studio_sandbox")
- project_workdir = (
- _get_project_workdir(session_id)
- if session_id and _SESSION_ID_RE.match(session_id)
- else None
- )
+ key = session_id or _ANON_KEY
+ cached = _workdirs.get(key)
+ if cached is not None and not os.path.isdir(cached):
+ cached = None
+ if cached is not None and not _get_project_workdir(session_id or ""):
+ # The same checks a fresh resolve makes: the entry can have been
+ # renamed and replaced with a link to another chat's directory since,
+ # and containment alone accepts that.
+ root_now = sandbox_root()
+ # Tool code runs in here and can delete the marker. For a directory
+ # this run claimed it is written again, rather than read as somebody
+ # else's, which would strand the files in it and start the chat anew.
+ if (
+ session_id
+ and cached in _claimed_here
+ and not os.path.islink(cached)
+ and _contained_in_root(cached, root_now)
+ and os.path.isdir(cached)
+ and _marker_owner(cached) != _sandbox_name(session_id)
+ ):
+ # Whatever it says now, this process made this directory for this
+ # chat. A tool writing another id into the marker would otherwise
+ # send the chat to a new folder and strand what it just wrote.
+ _preserve_foreign_marker(cached, session_id)
+ _mark_sandbox(cached, session_id)
+ if (
+ os.path.islink(cached)
+ or not _contained_in_root(cached, root_now)
+ or (session_id and not _owned_by_session(cached, session_id))
+ ):
+ cached = None
+ if cached is None:
+ _workdirs.pop(key, None)
+ sandbox_root_path = sandbox_root()
+ root_existed = os.path.isdir(sandbox_root_path)
+ # The folder may still be at the legacy root right after an upgrade.
+ # Only this chat's, so a first tool call never waits on the whole tree:
+ # across filesystems that is a copy of every session.
+ if session_id:
+ # A pre-upgrade chat whose id already starts with the derived
+ # prefix kept its folder under the literal id, so that name is
+ # tried too. Only a usable one: the rest never named a directory.
+ derived = _sandbox_name(session_id)
+ if (
+ derived != session_id
+ and _usable_session_id(session_id)
+ and session_id not in _FALLBACK_NAMES
+ ):
+ _migrate_one_legacy_session(sandbox_root_path, session_id)
+ _migrate_one_legacy_session(sandbox_root_path, derived)
+ _start_legacy_migration()
+ _start_detached_sweep()
+ project_workdir = _project_workdir_for(session_id)
if project_workdir:
workdir = project_workdir
- elif session_id and _SESSION_ID_RE.match(session_id):
- workdir = os.path.join(sandbox_root, session_id)
- if not os.path.realpath(workdir).startswith(os.path.realpath(sandbox_root) + os.sep):
- workdir = os.path.join(sandbox_root, "_invalid")
elif session_id:
- workdir = os.path.join(sandbox_root, "_invalid")
+ workdir = _ensure_session_dir(sandbox_root_path, session_id)
else:
- workdir = os.path.join(sandbox_root, "_default")
+ workdir = _sandbox_fallback(sandbox_root_path, "_default", create = True)
+ created = not os.path.isdir(workdir)
os.makedirs(workdir, exist_ok = True)
- try:
- os.chmod(sandbox_root, 0o700)
- except OSError:
- pass
- try:
- os.chmod(workdir, 0o700)
- except OSError:
- pass
+ if not project_workdir and not session_id:
+ # The fallbacks are directories like any other: claimed, so the next
+ # run knows this one is the one we made.
+ _claim_sandbox(workdir, "_default")
+ # Only a root we just created: the override can name a shared
+ # directory, and locking that down would cut off everything else.
+ if not root_existed or not (os.environ.get("UNSLOTH_STUDIO_SANDBOX_HOME") or "").strip():
+ try:
+ os.chmod(sandbox_root_path, 0o700)
+ except OSError:
+ pass
+ # Only ours: a shared root can already hold a directory with this name,
+ # and tightening it would cut off whoever else uses it.
+ if created or _sandbox_is_ours(workdir):
+ try:
+ os.chmod(workdir, 0o700)
+ except OSError:
+ pass
_workdirs[key] = workdir
return _workdirs[key]
@@ -7191,6 +8379,432 @@ def get_sandbox_workdir(session_id: str | None = None) -> str:
return _get_workdir(session_id)
+def resolve_sandbox_workdir(session_id: str | None = None) -> str:
+ """Where a session's sandbox would be, without creating it.
+
+ For read-only callers: serving a file must not materialise a directory for
+ every id someone asks about.
+ """
+ if session_id:
+ project = _project_workdir_for(session_id)
+ if project:
+ return project
+ root = sandbox_root()
+ cached = _workdirs.get(session_id or _ANON_KEY)
+ if (
+ cached
+ and not os.path.islink(cached)
+ and _contained_in_root(cached, root)
+ and (not session_id or _owned_by_session(cached, session_id))
+ ):
+ return cached
+ if not session_id:
+ return _sandbox_fallback(root, "_default")
+ # A directory this process made for this chat is this chat's, whatever a
+ # tool wrote into the marker since: the check above trusts that file, and
+ # without this the files it holds are served from nowhere.
+ claimed = _claimed_by_this_run(session_id, os.path.realpath(root))
+ if claimed:
+ return claimed
+ workdir = _session_dir(root, session_id)
+ # Same containment _get_workdir applies: a session entry symlinked out of
+ # the root would otherwise serve whatever it points at.
+ if not _contained_in_root(workdir, root):
+ return _sandbox_fallback(root, "_invalid")
+ if not os.path.isdir(workdir):
+ # A migration that moved the tree but could not rename it into place
+ # leaves the only copy under a marked name, at any root.
+ ours = _marked_sandbox_in(root, session_id)
+ if ours:
+ return ours
+ # Right after an upgrade the files can still be at the legacy root: the
+ # move runs in the background and can take minutes. Read where they are
+ # rather than 404 every card in the transcript until it finishes.
+ legacy = _legacy_session_dir(session_id)
+ if legacy:
+ return legacy
+ if not _root_is_ours() and not _owned_by_session(workdir, session_id):
+ # In a root the user pointed us at this chat can be in a fallback whose
+ # name nothing recomputes, and a read that stops here shows an empty
+ # sandbox and 404s the file cards already in the transcript.
+ ours = _marked_sandbox_in(root, session_id)
+ if ours:
+ return ours
+ if os.path.isdir(workdir) and not _owned_by_session(workdir, session_id):
+ # Somebody else's, so this session has nothing here to serve.
+ return _nothing_to_serve(session_id)
+ return workdir
+
+
+def migrate_legacy_sandbox_in_background() -> "threading.Thread":
+ """Move the legacy sandbox up at startup, off every request.
+
+ Across filesystems this copies every session, which is not something a
+ listing or a download can wait on: those run on the event loop.
+ """
+
+ def _run() -> None:
+ try:
+ _migrate_legacy_sandbox(sandbox_root())
+ except Exception: # noqa: BLE001 - best effort, like the rest of this
+ logger.debug("legacy sandbox migration failed", exc_info = True)
+
+ thread = threading.Thread(target = _run, name = "sandbox-migrate", daemon = True)
+ thread.start()
+ return thread
+
+
+# A name no session resolves to, so a detached tree is inert until it is gone.
+_DETACHED_SUFFIX = ".deleting-"
+# The exact shape the rename produces. A substring test would also have matched
+# a backup of the user's own named report.deleting-old.
+_DETACHED_RE = re.compile(r"\A.+\.deleting-[0-9a-f]{8}\Z")
+
+
+# One worker for every detached tree, rather than a thread per chat: clearing a
+# thousand chats would otherwise start a thousand recursive deletes at once.
+_delete_queue: "queue.Queue[tuple[str, int]]" = queue.Queue()
+# Attempts at one tree, and how long the first wait is (doubled each time).
+_MAX_DETACHED_DELETE_TRIES = 5
+_DETACHED_RETRY_DELAY = 1.0
+_delete_worker: "threading.Thread | None" = None
+_delete_worker_lock = threading.Lock()
+
+
+def _drain_detached_deletes() -> None:
+ while True:
+ target, tries = _delete_queue.get()
+ try:
+ shutil.rmtree(target, ignore_errors = True)
+ if os.path.exists(target):
+ _retry_detached_delete(target, tries)
+ finally:
+ _delete_queue.task_done()
+
+
+def _retry_detached_delete(target: str, tries: int) -> None:
+ """Queue another attempt at a tree ignore_errors left behind.
+
+ A file held open by a scanner or a process still exiting is transient, and
+ on Windows routine. The route has already told the user those files went,
+ so waiting for the next launch's sweep is not an answer.
+ """
+ if tries + 1 >= _MAX_DETACHED_DELETE_TRIES:
+ logger.warning("Could not delete %s; the next sweep retries it", target)
+ return
+ try:
+ timer = threading.Timer(
+ min(_DETACHED_RETRY_DELAY * 2**tries, 30.0),
+ _delete_queue.put,
+ [(target, tries + 1)],
+ )
+ timer.daemon = True
+ timer.start()
+ except RuntimeError:
+ logger.warning("Could not delete %s; the next sweep retries it", target)
+
+
+def _queue_detached_delete(target: str) -> None:
+ """Hand a renamed tree to the sweeper, or delete it here if none can run."""
+ global _delete_worker
+ with _delete_worker_lock:
+ if _delete_worker is None or not _delete_worker.is_alive():
+ try:
+ _delete_worker = threading.Thread(
+ target = _drain_detached_deletes,
+ name = "sandbox-delete",
+ daemon = True,
+ )
+ _delete_worker.start()
+ except RuntimeError:
+ # No thread to be had: better a slow call than a tree under a
+ # name nothing resolves to and nothing deletes.
+ _delete_worker = None
+ shutil.rmtree(target, ignore_errors = True)
+ return
+ _delete_queue.put((target, 0))
+
+
+def sweep_detached_sandboxes(root: "str | None" = None) -> None:
+ """Finish deletes a previous run was killed part way through.
+
+ The rename is what puts the tree out of reach, so a kill between it and the
+ rmtree leaves a full copy of the files nothing resolves to.
+
+ At our own root the name is enough: nothing but this code puts a
+ ``.deleting-<hex>`` directory there, and a tool that had removed the marker
+ before the delete would otherwise leave the tree unreachable for good. In a
+ root the user pointed us at, the marker is still required, since a folder of
+ theirs can carry any name.
+ """
+ base = os.path.realpath(root or sandbox_root())
+ try:
+ names = [name for name in os.listdir(base) if _DETACHED_RE.match(name)]
+ except OSError:
+ return
+ for name in names:
+ target = os.path.join(base, name)
+ if os.path.islink(target) or not os.path.isdir(target):
+ continue
+ if _marker_owner(target) is None and not _root_is_ours():
+ continue
+ shutil.rmtree(target, ignore_errors = True)
+
+
+_swept_detached = False
+
+
+def start_sandbox_recovery() -> "threading.Thread | None":
+ """Finish what an interrupted run left: renamed trees and pending deletes."""
+ return _start_detached_sweep()
+
+
+def _start_detached_sweep() -> "threading.Thread | None":
+ """Run the sweep once per process, off the call that noticed."""
+ global _swept_detached
+ with _legacy_one_lock:
+ if _swept_detached:
+ return None
+ _swept_detached = True
+
+ def _sweep() -> None:
+ sweep_detached_sandboxes()
+ # A workspace the user asked to delete, left pending because a tool was
+ # still running in it when the app went away.
+ collect_orphaned_project_workspaces()
+
+ thread = threading.Thread(target = _sweep, name = "sandbox-sweep", daemon = True)
+ thread.start()
+ return thread
+
+
+def remove_session_sandbox(session_id: str, delete_files: bool = False) -> bool:
+ """Drop a deleted chat's sandbox. True when something was removed.
+
+ The chat was the only handle on that directory, so leaving it behind means
+ one unreachable folder per chat forever. Empty folders always go; files
+ need ``delete_files``, since they are the user's and are downloadable from
+ the chat. Project workspaces are shared and have their own delete flow.
+ """
+ if not session_id:
+ return False
+ # Only a session that really resolves to a project workspace: an imported
+ # chat whose id merely starts with the prefix gets an ordinary directory
+ # from _get_workdir, and would otherwise never be cleaned up.
+ if session_id.startswith(_PROJECT_SESSION_PREFIX) and _get_project_workdir(session_id):
+ # Unless this id has a sandbox of its own: a chat named like a project
+ # session had one while its row existed, and the row goes first, so the
+ # project would inherit the question and those files stay behind.
+ root_here = os.path.realpath(sandbox_root())
+ if not _claimed_by_this_run(session_id, root_here) and not _marked_sandbox_in(
+ root_here,
+ session_id,
+ ):
+ return False
+ # The folder may still be at the legacy root right after an upgrade. This
+ # session only, or a delete would sit behind a copy of every chat, and
+ # outside the lock below, since it moves a tree and takes its own.
+ root_now = sandbox_root()
+ _migrate_one_legacy_session(root_now, _sandbox_name(session_id))
+ if _usable_session_id(session_id) and _sandbox_name(session_id) != session_id:
+ _migrate_one_legacy_session(root_now, session_id)
+ _start_legacy_migration()
+ # Held across the decision AND the unlink: otherwise a tool can start in
+ # between and run in a directory this call then removes.
+ key = _session_key(session_id)
+ with _sessions_free:
+ while key in _removing_sessions:
+ _sessions_free.wait() # another delete for this chat is finishing
+ if _active_sessions.get(key, 0) > 0:
+ # Queued rather than dropped: the chat is already gone from history,
+ # so no later delete or clear would ever name this session again.
+ queued = _pending_removals.setdefault(key, {})
+ queued[session_id] = delete_files or queued.get(session_id, False)
+ return False # see sandbox_removal_deferred
+ # Closed for this chat, then released: deciding whether the sandbox is
+ # empty walks the tree, and holding the global lock for that stops tool
+ # calls starting in every unrelated chat.
+ _removing_sessions.add(key)
+ try:
+ return _remove_session_sandbox_locked(session_id, delete_files)
+ finally:
+ with _sessions_free:
+ _removing_sessions.discard(key)
+ _sessions_free.notify_all()
+
+
+def session_sandbox_has_files(session_id: str) -> bool:
+ """Whether this chat's sandbox still holds files of the user's.
+
+ For a delete that was not offered the choice: the chat was the only way to
+ those files, so the caller can offer it afterwards rather than leave a
+ folder nothing can reach.
+ """
+ if not session_id:
+ return False
+ try:
+ target = os.path.realpath(resolve_sandbox_workdir(session_id))
+ if not os.path.isdir(target) or not _sandbox_is_ours(target):
+ claimed = _claimed_by_this_run(session_id, os.path.realpath(sandbox_root()))
+ if not claimed:
+ return False
+ target = os.path.realpath(claimed)
+ return not _holds_no_user_files(target, _sandbox_name(session_id))
+ except OSError:
+ return False
+
+
+def _holds_no_user_files(target: str, owner: "str | None" = None) -> bool:
+ """Whether a sandbox holds nothing but (possibly empty) directories.
+
+ Our own marker does not count, and only while it is still ours: tool code
+ runs in there and can write its own content over that file, which is then
+ the only copy of it. Bounded like every other walk here, and a tree too big
+ to check is not one to remove without being asked.
+ """
+ budget = _MAX_SNAPSHOT_DIRS
+ for parent, dirs, files in os.walk(target):
+ # A link to a directory is listed here, not in files, and a tool made
+ # it: a sandbox holding one is not empty.
+ if any(os.path.islink(os.path.join(parent, name)) for name in dirs):
+ return False
+ for name in files:
+ if parent == target and name in _INTERNAL_SANDBOX_FILES:
+ if name != _SANDBOX_MARKER:
+ continue
+ marker = _marker_owner(target)
+ if marker is not None and owner in (None, marker):
+ continue
+ return False
+ budget -= 1
+ if budget <= 0:
+ return False
+ return True
+
+
+def _claimed_by_this_run(session_id: str, root: str) -> "str | None":
+ """The directory this process made for this chat, whatever the marker says.
+
+ Tool code runs in there and can empty that file or write another id into
+ it, and neither makes the directory somebody else's: this process wrote the
+ marker with O_EXCL and remembers doing it. Put back here, so the ordinary
+ routes find it too rather than leaving the files stranded until some later
+ call happens to repair it.
+ """
+ cached = _workdirs.get(session_id)
+ if not cached or cached not in _claimed_here:
+ return None
+ if os.path.islink(cached) or not os.path.isdir(cached):
+ return None
+ if not _contained_in_root(cached, root):
+ return None
+ if _marker_owner(cached) != _sandbox_name(session_id):
+ _preserve_foreign_marker(cached, session_id)
+ _mark_sandbox(cached, session_id)
+ return cached
+
+
+def project_session_id(project_id: str) -> str:
+ """The sandbox session a project's chats share."""
+ return f"{_PROJECT_SESSION_PREFIX}{project_id}"
+
+
+def wait_for_sessions_idle(session_ids, timeout: float = 10.0) -> bool:
+ """Wait until no tool call is running for these sessions. True if none is.
+
+ Cancelling a generation only sets its event, so the call inside the executor
+ is still using its working directory for a moment after.
+ """
+ keys = {_session_key(session_id) for session_id in session_ids or []}
+ if not keys:
+ return True
+ deadline = time.monotonic() + max(0.0, timeout)
+ while True:
+ with _active_sessions_lock:
+ busy = any(_active_sessions.get(key, 0) > 0 for key in keys)
+ if not busy:
+ return True
+ if time.monotonic() >= deadline:
+ return False
+ time.sleep(0.05)
+
+
+def sandbox_removal_deferred(session_id: str) -> bool:
+ """Whether this session's removal is queued behind a running tool call.
+
+ The caller reports what it kept, and the answer is not known yet: the call
+ still in flight can write a file after the sandbox looked empty, and the
+ deferred removal would then keep it with nobody left to say so.
+ """
+ if not session_id:
+ return False
+ with _active_sessions_lock:
+ return session_id in _pending_removals.get(_session_key(session_id), {})
+
+
+def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:
+ root = os.path.realpath(sandbox_root())
+ claimed = _claimed_by_this_run(session_id, root)
+ entry = os.path.join(root, _sandbox_name(session_id))
+ if not os.path.islink(entry):
+ entry = _session_dir(root, session_id)
+ # Neither computed name is ours, so this chat may be in a fallback, or
+ # in a directory whose marker a tool removed since we made it.
+ if not _owned_by_session(entry, session_id):
+ entry = _marked_sandbox_in(root, session_id) or claimed or entry
+ # The entry itself, not what it resolves to: a symlink to a sibling passes
+ # the check below and would take that chat's files. Drop the link, but only
+ # at our own root: in a shared one it is the user's entry, not a sandbox.
+ if os.path.islink(entry):
+ if not _root_is_ours():
+ return False
+ try:
+ os.unlink(entry)
+ return True
+ except OSError:
+ return False
+ target = os.path.realpath(entry)
+ if os.path.dirname(target) != root or not os.path.isdir(target): # contained
+ return False
+ # Ours by the marker, or because this process is the one that made it.
+ ours_here = bool(claimed) and target == os.path.realpath(claimed)
+ if not ours_here and not _sandbox_is_ours(target):
+ return False
+ # Made for a different id: the same directory on a case-insensitive volume,
+ # and those files are the other chat's.
+ owner = _marker_owner(target)
+ if owner is not None and owner != _sandbox_name(session_id):
+ return False
+ if owner is None and not ours_here and os.path.basename(target) != _sandbox_name(session_id):
+ # Nothing says whose this is, and on a case-insensitive volume `foo`
+ # and `Foo` are one directory: without the marker the name is the only
+ # evidence, and it names the other chat.
+ return False
+ _workdirs.pop(session_id, None)
+ try:
+ if delete_files:
+ # Renamed while locked, deleted after: every tool start takes this
+ # lock, so an rmtree of a large tree in here stops calls in every
+ # other chat for as long as it runs.
+ detached = f"{target}{_DETACHED_SUFFIX}{uuid.uuid4().hex[:8]}"
+ try:
+ os.rename(target, detached)
+ except OSError:
+ shutil.rmtree(target, ignore_errors = True)
+ return not os.path.isdir(target)
+ _queue_detached_delete(detached)
+ return True
+ # Empty means no files of the user's: a tool that only ran mkdir, or
+ # deleted what it wrote, leaves directories behind, and the chat record
+ # is already gone by the time this runs.
+ if not _holds_no_user_files(target, _sandbox_name(session_id)):
+ return False
+ shutil.rmtree(target, ignore_errors = True)
+ return not os.path.isdir(target)
+ except OSError:
+ return False
+
+
WEB_SEARCH_TOOL = {
"type": "function",
"function": {
@@ -7227,16 +8841,23 @@ def _build_sandbox_paths_note() -> str:
instead: without it a model assumes the pipe is its only output and declines
to open a window it believes nobody can see.
"""
+ # Without this a model assumes its output vanished into a scratch dir and
+ # says so, which reads as "the file was not really created".
+ created = (
+ " Any file you create here is kept and shown to the user with a download "
+ "link, so name the files you created in your reply -- by file name only, "
+ "since you do not know their absolute path."
+ )
if sys.platform != "win32":
return (
" Read and write files using relative paths in the current working "
"directory, which persists for this conversation; absolute paths like "
- "/mnt/data or /tmp/outputs do not exist."
+ "/mnt/data or /tmp/outputs do not exist." + created
)
return (
" You are on Windows, and this runs on the user's own machine. Read and "
"write files using relative paths in the current working directory, which "
- "persists for this conversation."
+ "persists for this conversation." + created
)
@@ -7624,24 +9245,28 @@ def execute_tool(
cancel_event = cancel_event,
website_policy = website_policy,
)
+ # Both run with the session's sandbox as cwd, so a chat deleted mid-call
+ # must not unlink it from under them.
if name == "python":
- return _python_exec(
- arguments.get("code", ""),
- cancel_event,
- effective_timeout,
- session_id,
- disable_sandbox = disable_sandbox,
- output_callback = output_callback,
- )
+ with _session_in_flight(session_id):
+ return _python_exec(
+ arguments.get("code", ""),
+ cancel_event,
+ effective_timeout,
+ session_id,
+ disable_sandbox = disable_sandbox,
+ output_callback = output_callback,
+ )
if name == "terminal":
- return _bash_exec(
- arguments.get("command", ""),
- cancel_event,
- effective_timeout,
- session_id,
- disable_sandbox = disable_sandbox,
- output_callback = output_callback,
- )
+ with _session_in_flight(session_id):
+ return _bash_exec(
+ arguments.get("command", ""),
+ cancel_event,
+ effective_timeout,
+ session_id,
+ disable_sandbox = disable_sandbox,
+ output_callback = output_callback,
+ )
return f"Unknown tool: {name}"
@@ -10221,9 +11846,9 @@ _MISSING_PATH_PREFIXES = (
_QUOTED_ABS_PATH_RE = re.compile(r"""['"](/[^'"\n]+)['"]""")
_BASH_ABS_PATH_RE = re.compile(r"(/[^\s:'\"]+):\s*No such file or directory")
-# The sandbox CWD is a per-thread dir under ~/studio_sandbox; an absolute path
+# The sandbox CWD is a per-session dir under the studio home; an absolute path
# under it is a genuine local miss, not a hallucinated out-of-sandbox write.
-_SANDBOX_ROOT = os.path.join(os.path.expanduser("~"), "studio_sandbox")
+# Resolved through the same helper as _get_workdir so the two cannot drift.
def _missing_error_lines(output: str) -> list[str]:
@@ -10260,7 +11885,7 @@ def _is_outside_workdir(abs_path: str, workdir: str | None = None) -> bool:
or it is wrongly classed as an external habit path.
"""
try:
- root = os.path.realpath(workdir or _SANDBOX_ROOT)
+ root = os.path.realpath(workdir or sandbox_root())
rp = os.path.realpath(abs_path)
except (OSError, ValueError):
return True
@@ -10386,6 +12011,289 @@ def _drain_process_output(
return "".join(chunks), timed_out
+_MAX_REPORTED_FILES = 25
+# Bounded so an unpacked archive cannot turn a tool call into a filesystem
+# crawl. In path segments, the unit the download route enforces, so a card can
+# never advertise a file that route would refuse.
+_MAX_SANDBOX_PATH_SEGMENTS = 4
+_MAX_SNAPSHOT_FILES = 2000 # a shard-writing script must not blow up the result
+_MAX_SNAPSHOT_DIRS = 2000 # nor a directory-writing one stall the next call
+
+
+# The same allowlist the download route applies per segment, so a name that
+# route would refuse never reaches a file chip.
+_SERVABLE_SEGMENT_RE = re.compile(r"\A[^/\\\x00-\x1f]{1,255}\Z")
+
+
+def _servable_segment(name: str) -> bool:
+ if name in (".", "..") or not _SERVABLE_SEGMENT_RE.match(name):
+ return False
+ # Non-UTF-8 bytes in a POSIX filename surface as lone surrogates, which
+ # encodeURIComponent throws on, so the chip could never issue its download.
+ return not any("\ud800" <= ch <= "\udfff" for ch in name)
+
+
+# Studio's own bookkeeping, written by the sandbox sitecustomize. One exact
+# name we write ourselves, not a pattern reserved over names a tool may pick.
+_INTERNAL_SANDBOX_FILES = frozenset({".unsloth_sandbox_remap.json", _SANDBOX_MARKER})
+
+
+# Above this a file is identified by mtime and size alone. Rewriting a large
+# artifact byte for byte inside one filesystem tick is not worth reading every
+# artifact twice per tool call.
+_MAX_HASHED_SNAPSHOT_BYTES = 4 * 1024 * 1024
+
+
+def _content_key(path: str, size: int) -> "str | None":
+ """A digest for a file small enough to read, else None.
+
+ On FAT/exFAT and some network volumes the timestamp granularity is a second
+ or two, so an overwrite with different content of the same length inside one
+ tick is invisible to mtime and size, and the call reported no file at all.
+ """
+ if size > _MAX_HASHED_SNAPSHOT_BYTES:
+ return None
+ try:
+ digest = hashlib.blake2b(digest_size = 16)
+ with open(path, "rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+ except OSError:
+ return None
+
+
+# Volumes already known to timestamp finely, by device id. Only the positive is
+# kept: a negative costs one stat to redo and hashing to get wrong.
+_fine_mtime_devices: "set[int]" = set()
+
+
+def _volume_timestamps_finely(workdir: str) -> bool:
+ """Whether this volume records sub-second times, so digests can be skipped.
+
+ That is the only thing the digest buys: at sub-second resolution a program
+ cannot overwrite a file inside the tick of its own previous write, and
+ reading every artifact twice per call was ~90% of a snapshot's cost.
+
+ Read off the directory rather than probed with a file of our own: several
+ chats can share a workdir, and a probe file appearing mid-walk is reported
+ as a file the other call created. Three stamps because one whole-second
+ reading on a fine volume is chance; three is not. Anything unreadable
+ answers False, which hashes exactly as before.
+ """
+ try:
+ stat = os.stat(workdir)
+ except OSError:
+ return False
+ if stat.st_dev in _fine_mtime_devices:
+ return True
+ if not any(
+ stamp % 1_000_000_000
+ for stamp in (stat.st_mtime_ns, stat.st_ctime_ns, stat.st_atime_ns)
+ ):
+ return False
+ _fine_mtime_devices.add(stat.st_dev)
+ return True
+
+
+def _defuse_sentinels(text: str) -> str:
+ """Break a marker line the executed program printed itself.
+
+ Both readers take the last one, so a call that created nothing and printed
+ `__FILES__:[{"name": "report.csv", "size": 1}]` had that read as the
+ envelope: the line was hidden from the model and the UI offered a download
+ for a file nobody wrote. One space is enough, since both anchor on the line
+ start, and it leaves the text otherwise as the program wrote it.
+ """
+ for marker in ("\n__FILES__:", "\n__IMAGES__:"):
+ text = text.replace(marker, "\n " + marker[1:])
+ return text
+
+
+# What one snapshot may read to tell a same-size overwrite apart. The file cap
+# alone allowed 2,000 x 4 MiB per walk, twice per call, which on a directory of
+# artifacts made a trivial command look hung.
+_MAX_SNAPSHOT_HASH_BYTES = 64 * 1024 * 1024
+
+
+def _snapshot_workdir_files(workdir: str | None) -> "dict[str, tuple]":
+ """relative path -> change key for every regular file, for the post-run diff.
+
+ All files, not just images: a .csv the model wrote used to be invisible.
+ Size rides along with mtime because FAT/exFAT and some network volumes have
+ coarse timestamps, where an overwrite inside one tick would look unchanged,
+ and on those volumes alone a digest rides along too, since a same-length
+ rewrite inside one tick matches on all of it otherwise.
+ """
+ snapshot: "dict[str, tuple]" = {}
+ if not workdir or not os.path.isdir(workdir):
+ return snapshot
+ # Directories are budgeted separately from files: thousands of empty output
+ # folders never reach the file cap, and this walk runs twice per tool call.
+ visited = 0
+ hash_budget = 0 if _volume_timestamps_finely(workdir) else _MAX_SNAPSHOT_HASH_BYTES
+ # Walked, not listed: a script writing outputs/report.csv is ordinary, and a
+ # top-level listing saw only the directory and dropped it.
+ for base, dirs, names in os.walk(workdir):
+ visited += 1
+ if visited > _MAX_SNAPSHOT_DIRS:
+ return snapshot
+ # depth 0 is the workdir itself, whose files are one segment.
+ depth = base[len(workdir) :].count(os.sep)
+ # Dot-directories stay out: .git, .cache and friends are where the noise
+ # lives. Dot-FILES are reported, since .gitignore is a real artifact.
+ dirs[:] = (
+ []
+ if depth >= _MAX_SANDBOX_PATH_SEGMENTS - 1
+ else [d for d in dirs if not d.startswith(".") and _servable_segment(d)]
+ )
+ for name in names:
+ # Only at the top: a tool that wrote archive/.unsloth_sandbox made an
+ # ordinary file, and dropping it hid it from every listing while
+ # still counting it as a reason to keep the sandbox.
+ if base == workdir and name in _INTERNAL_SANDBOX_FILES:
+ continue
+ if not _servable_segment(name):
+ continue
+ path = os.path.join(base, name)
+ try:
+ # One lstat where isfile + islink + stat were three, on every
+ # file of every walk. A link is not a regular file to lstat, so
+ # this drops the same entries the pair did.
+ stat = os.lstat(path)
+ if not S_ISREG(stat.st_mode):
+ continue
+ relative = os.path.relpath(path, workdir).replace(os.sep, "/")
+ content = None
+ if hash_budget and hash_budget >= stat.st_size:
+ content = _content_key(path, stat.st_size)
+ if content is not None:
+ hash_budget -= stat.st_size
+ snapshot[relative] = (stat.st_mtime_ns, stat.st_size, content)
+ except OSError:
+ continue
+ if len(snapshot) >= _MAX_SNAPSHOT_FILES:
+ return snapshot
+ return snapshot
+
+
+# Scratch scripts of calls running right now. Chats in one project share a
+# workdir and each snapshots all of it, so without this the other call's
+# studio_exec_*.py is offered as this call's file and 404s once it is gone.
+_active_scratch: "set[str]" = set()
+_scratch_lock = threading.Lock()
+
+# Tool calls running in each workdir. Chats in one project share one and each
+# call diffs the whole tree, so the other call's file would land on this card.
+# A call ever alongside another claims nothing, and no clock is involved.
+_workdir_calls: "dict[str, list]" = {}
+_calls_lock = threading.Lock()
+
+
+def _call_started(workdir: "str | None") -> dict:
+ """Register a call in *workdir* and hand back its token."""
+ token = {"workdir": workdir, "shared": False}
+ if not workdir:
+ return token
+ with _calls_lock:
+ running = _workdir_calls.setdefault(workdir, [])
+ if running:
+ token["shared"] = True
+ for other in running:
+ other["shared"] = True
+ running.append(token)
+ return token
+
+
+def _call_finished(token: "dict | None") -> None:
+ """Drop a call's registration. Its token keeps whatever it learned."""
+ if not token or not token.get("workdir"):
+ return
+ with _calls_lock:
+ running = _workdir_calls.get(token["workdir"])
+ if running is None:
+ return
+ try:
+ running.remove(token)
+ except ValueError:
+ pass
+ if not running:
+ _workdir_calls.pop(token["workdir"], None)
+
+
+def _snapshot_differs(before: tuple, after: tuple) -> bool:
+ """Whether a file changed between two snapshots of its directory.
+
+ The digest only when both snapshots have one: hashing stops at a byte
+ budget, so a file added or removed earlier in the walk can push an
+ untouched later file in or out of it, and comparing the tuples whole would
+ then report that file as one this call wrote.
+ """
+ if before[:2] != after[:2]:
+ return True
+ return before[2] is not None and after[2] is not None and before[2] != after[2]
+
+
+def _created_file_sentinels(
+ workdir: str | None,
+ before: "dict[str, tuple]",
+ exclude: "str | None" = None,
+ token: "dict | None" = None,
+) -> str:
+ """Sentinels naming the files this call created or overwrote.
+
+ ``__IMAGES__`` renders inline as before; ``__FILES__`` carries every file
+ with its size so the UI can offer a download. Both are stripped before the
+ model sees the result.
+ """
+ if token is not None and token.get("shared"):
+ # Another call ran in this directory while this one did, so nothing here
+ # can be said to be ours. A missing card beats one that names, and
+ # downloads, another chat's file.
+ return ""
+ after = _snapshot_workdir_files(workdir)
+ if token is not None and token.get("shared"):
+ # A call that started while that walk was running. What it wrote is in
+ # `after` and cannot be told apart from ours, so the same rule applies:
+ # the check above only saves the walk when the sharing was already known.
+ return ""
+ # ``exclude`` is this call's own scratch script by exact name, not a pattern
+ # reserved over names a tool might pick.
+ with _scratch_lock:
+ scratch = set(_active_scratch)
+ scratch.discard(exclude) # this call's own is named below anyway
+ changed = sorted(
+ name
+ for name, key in after.items()
+ if name != exclude
+ and name not in scratch
+ and (name not in before or _snapshot_differs(before[name], key))
+ )
+ if not changed:
+ return ""
+
+ import json as _json
+
+ # Same cap on both: a script writing a frame per step would otherwise put
+ # every name in the result and the stored chat, and the UI would render them all.
+ images = [n for n in changed if os.path.splitext(n)[1].lower() in _IMAGE_EXTS]
+ images = images[:_MAX_REPORTED_FILES]
+ entries = []
+ for name in changed[:_MAX_REPORTED_FILES]:
+ try:
+ size = os.stat(os.path.join(workdir, name)).st_size
+ except OSError:
+ size = None
+ entries.append({"name": name, "size": size})
+
+ # __IMAGES__ stays LAST: older clients slice from it to the end of the
+ # string, so anything after would land inside their JSON.
+ out = f"\n__FILES__:{_json.dumps(entries)}"
+ if images:
+ out += f"\n__IMAGES__:{_json.dumps(images)}"
+ return out
+
+
def _python_exec(
code: str,
cancel_event = None,
@@ -10423,22 +12331,20 @@ def _python_exec(
)
tmp_path = None
+ _scratch_name = None
workdir = _get_workdir(session_id)
- # Snapshot image mtimes to detect new and overwritten files.
- _before: dict[str, int] = {}
- if os.path.isdir(workdir):
- for _name in os.listdir(workdir):
- if os.path.splitext(_name)[1].lower() in _IMAGE_EXTS:
- _p = os.path.join(workdir, _name)
- if os.path.isfile(_p):
- try:
- _before[_name] = os.stat(_p).st_mtime_ns
- except OSError:
- pass
+ call_token = _call_started(workdir)
+ # Snapshot mtimes to detect new and overwritten files.
+ _before = _snapshot_workdir_files(workdir)
try:
+ # In the workdir: Python puts it on sys.path[0], so an earlier call's
+ # helper.py stays importable and __file__ resolves inside the sandbox.
fd, tmp_path = tempfile.mkstemp(suffix = ".py", prefix = "studio_exec_", dir = workdir)
# utf-8 so non-ASCII in model-written code survives the OS default codec
# (Windows cp1252 would otherwise raise UnicodeEncodeError).
+ _scratch_name = os.path.basename(tmp_path)
+ with _scratch_lock:
+ _active_scratch.add(_scratch_name)
with os.fdopen(fd, "w", encoding = "utf-8") as f:
f.write(code)
@@ -10489,11 +12395,22 @@ def _python_exec(
output, timed_out = _drain_process_output(
proc, timeout, output_callback, cancel_event, pgid = pgid
)
+ # A run that wrote its file and then hung still produced that file, so
+ # report it: `printf data > report.csv; sleep 999` is downloadable.
if timed_out:
- return _truncate(f"Execution timed out after {timeout} seconds.")
+ ended = _truncate(f"Execution timed out after {timeout} seconds.")
+ return ended + (
+ _created_file_sentinels(workdir, _before, _scratch_name, call_token)
+ if session_id
+ else ""
+ )
if cancel_event is not None and cancel_event.is_set():
- return "Execution cancelled."
+ return "Execution cancelled." + (
+ _created_file_sentinels(workdir, _before, _scratch_name, call_token)
+ if session_id
+ else ""
+ )
result = output or ""
if proc.returncode != 0:
@@ -10505,31 +12422,25 @@ def _python_exec(
hint = _missing_path_hint(result, workdir)
result = _truncate(result) if result.strip() else "(no output)"
result += hint
+ # Before ours is appended, and whether or not one is: a program's own
+ # marker line is not an envelope.
+ result = _defuse_sentinels(result)
- # Detect new/overwritten images and append sentinel for the frontend
- if session_id and os.path.isdir(workdir):
- new_images = []
- for _name in os.listdir(workdir):
- if os.path.splitext(_name)[1].lower() not in _IMAGE_EXTS:
- continue
- _p = os.path.join(workdir, _name)
- if not os.path.isfile(_p):
- continue
- try:
- _mtime = os.stat(_p).st_mtime_ns
- except OSError:
- continue
- if _name not in _before or _mtime != _before[_name]:
- new_images.append(_name)
- if new_images:
- import json as _json
- result += f"\n__IMAGES__:{_json.dumps(sorted(new_images))}"
+ # Only for a chat that has an id: without one every first turn shares
+ # the _default workdir, so a card pinned to it would later download
+ # whatever the next new chat wrote there.
+ if session_id:
+ result += _created_file_sentinels(workdir, _before, _scratch_name, call_token)
return result
except Exception as e:
return f"Execution error: {e}"
finally:
+ _call_finished(call_token)
+ if _scratch_name:
+ with _scratch_lock:
+ _active_scratch.discard(_scratch_name)
_forget_tool_pid(locals().get("proc"))
if tmp_path and os.path.exists(tmp_path):
try:
@@ -10574,8 +12485,14 @@ def _bash_exec(
"/proc environment reads; refusing bypass execution."
)
+ workdir = None
+ call_token = None
try:
workdir = _get_workdir(session_id)
+ call_token = _call_started(workdir)
+ # Same pre-run snapshot as _python_exec. A command that writes a file used
+ # to produce "(no output)" and no other trace anywhere in the product.
+ _before = _snapshot_workdir_files(workdir)
safe_env = _build_bypass_env(workdir) if disable_sandbox else _build_safe_env(workdir)
popen_kwargs = dict(
stdout = subprocess.PIPE,
@@ -10615,11 +12532,18 @@ def _bash_exec(
output, timed_out = _drain_process_output(
proc, timeout, output_callback, cancel_event, pgid = pgid
)
+ # A run that wrote its file and then hung still produced that file, so
+ # report it: `printf data > report.csv; sleep 999` is downloadable.
if timed_out:
- return _truncate(f"Execution timed out after {timeout} seconds.")
+ ended = _truncate(f"Execution timed out after {timeout} seconds.")
+ return ended + (
+ _created_file_sentinels(workdir, _before, None, call_token) if session_id else ""
+ )
if cancel_event is not None and cancel_event.is_set():
- return "Execution cancelled."
+ return "Execution cancelled." + (
+ _created_file_sentinels(workdir, _before, None, call_token) if session_id else ""
+ )
result = output or ""
if proc.returncode != 0:
@@ -10627,9 +12551,15 @@ def _bash_exec(
# Same missing-path healing as _python_exec.
hint = _missing_path_hint(result, workdir)
result = _truncate(result) if result.strip() else "(no output)"
- return result + hint
+ result += hint
+ result = _defuse_sentinels(result) # see _python_exec
+ # Only for a chat that has an id (see _python_exec).
+ if session_id:
+ result += _created_file_sentinels(workdir, _before, None, call_token)
+ return result
except Exception as e:
return f"Execution error: {e}"
finally:
+ _call_finished(call_token)
_forget_tool_pid(locals().get("proc"))
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.py
index 3c968f93d97..f4bc1a2d6b6 100644
--- a/studio/backend/core/research_runs.py
+++ b/studio/backend/core/research_runs.py
@@ -864,7 +864,7 @@ class ResearchSupervisor:
for source, result in zip(targets, results):
if isinstance(result, BaseException) or not isinstance(result, str):
continue
- body = strip_result_for_model(result)
+ body = strip_result_for_model(result, "web_search")
if is_tool_error(body):
continue
body = _clean_scraped_text(body)
@@ -2054,7 +2054,7 @@ class ResearchSupervisor:
f"### {action['title']} ({action['action']})\n"
f"Input: {argument}\nResult:\n{result[:12000]}"
)
- clean_result = strip_result_for_model(result)
+ clean_result = strip_result_for_model(result, "web_search")
step_result = {
"action": action["action"],
"input": argument,
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 4a13504a71f..4ef7da2afe7 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -201,6 +201,16 @@ import _platform_compat # noqa: F401
# unsloth-zoo import below, whose LLAMA_CPP_DEFAULT_DIR binding is import-time.
from utils.paths.storage_roots import studio_root as _studio_root
+# Same reason, same deadline: unsloth_zoo.compiler reads UNSLOTH_COMPILE_LOCATION
+# at import time, and without this a direct start falls back to a CWD-relative
+# unsloth_compiled_cache (on Windows that is the user profile).
+from utils.paths.storage_roots import setup_cache_env as _setup_cache_env
+
+try:
+ _setup_cache_env()
+except Exception: # noqa: BLE001
+ pass
+
try:
_LEGACY_STUDIO_ROOT = (_Path.home() / ".unsloth" / "studio").resolve()
except (OSError, ValueError):
@@ -604,6 +614,21 @@ async def lifespan(app: FastAPI):
_lifespan_log = _structlog.get_logger(__name__)
clear_unsloth_compiled_cache()
+ # Move the legacy sandbox up here rather than from the first request: the
+ # copy can be minutes when the studio home is on another filesystem.
+ try:
+ from core.inference.tools import (
+ migrate_legacy_sandbox_in_background,
+ start_sandbox_recovery,
+ )
+ migrate_legacy_sandbox_in_background()
+ # A tree renamed for deletion by a run that was killed, and the
+ # workspace deletes it left pending: both waited for the next Python or
+ # terminal call, which ordinary chat never makes.
+ start_sandbox_recovery()
+ except Exception: # noqa: BLE001
+ pass
+
# Remove stale .venv_overlay from old versions; switching now uses .venv_t5/.
overlay_dir = Path(__file__).resolve().parent.parent.parent / ".venv_overlay"
if overlay_dir.is_dir():
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 48b0e6102c4..d4b9134e2f9 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -108,6 +108,12 @@ class ChatProject(BaseModel):
updatedAt: int
+class ChatProjectDeleted(ChatProject):
+ """The deleted project, plus the member sandboxes that still hold files."""
+
+ sandboxes_kept: list[str] = []
+
+
class ChatProjectPatch(BaseModel):
name: Optional[str] = None
instructions: Optional[str] = None
@@ -135,6 +141,9 @@ class ChatMessageSyncRequest(BaseModel):
class ChatDeleteRequest(BaseModel):
ids: list[str]
+ # Files a tool call wrote. Off by default: they are the user's and the chat
+ # card offers them as downloads. An empty sandbox is removed either way.
+ delete_files: bool = False
class ChatCountResponse(BaseModel):
@@ -354,6 +363,51 @@ def _cancel_active_research(request: Request, thread_ids: list[str]) -> None:
)
+def _cancel_research_runs(request: Request, run_ids: list[str]) -> None:
+ """Stop these research runs by id. Best effort, like every cleanup here."""
+ if not run_ids:
+ return
+ try:
+ from storage import research_runs_db
+ except Exception: # noqa: BLE001 - research storage optional/unavailable
+ return
+ supervisor = getattr(request.app.state, "research_supervisor", None)
+ for run_id in run_ids:
+ # The row is usually already gone here, which makes request_cancel raise:
+ # the supervisor is what actually stops the worker, so it is told first
+ # and the status update is the best-effort half.
+ if supervisor is not None:
+ try:
+ supervisor.cancel(run_id)
+ except Exception: # noqa: BLE001
+ logger.warning("Could not signal research run %s", run_id, exc_info = True)
+ try:
+ research_runs_db.request_cancel(run_id)
+ except Exception: # noqa: BLE001
+ pass # no row to update, which is the ordinary case after a delete
+
+
+def _cancel_active_generations(thread_ids: list[str]) -> None:
+ """Stop any generation still running for these threads.
+
+ The sandbox goes with the thread, but a request that has not reached the
+ executor yet would dispatch its tool call afterwards, recreate the folder,
+ and write files no chat can reach. The in-flight guard only covers calls
+ already inside the executor. Best effort: this must never break a delete.
+ """
+ if not thread_ids:
+ return
+ try:
+ from state import active_generations
+ except Exception: # noqa: BLE001 - never block a delete on this
+ return
+ for thread_id in thread_ids:
+ try:
+ active_generations.cancel_thread(thread_id)
+ except Exception: # noqa: BLE001
+ continue
+
+
@router.delete("/threads")
async def delete_threads(
payload: ChatDeleteRequest,
@@ -361,8 +415,76 @@ async def delete_threads(
current_subject: str = Depends(get_current_subject),
):
_cancel_active_research(request, payload.ids)
+ _cancel_active_generations(payload.ids)
delete_chat_threads(payload.ids)
- return {"status": "deleted"}
+ # Keyed by thread id, so nothing can reference the folder once the thread
+ # is gone. Clean it up rather than leaking one per chat.
+ # In a worker: right after an upgrade this also runs the legacy move, and a
+ # cross-filesystem copy on the event loop stops every other request.
+ removed, kept = await _remove_sandboxes(payload.ids, payload.delete_files)
+ return {"status": "deleted", "sandboxes_removed": removed, "sandboxes_kept": kept}
+
+
+async def _remove_sandboxes(thread_ids, delete_files: bool) -> "tuple[int, list[str]]":
+ """Drop each thread's sandbox off the event loop. Never raises.
+
+ Returns how many went and which ids still have files. The chat is the only
+ way to those files, so a caller that never offered the choice can offer it
+ once it knows there was something to keep.
+ """
+ from starlette.concurrency import run_in_threadpool
+
+ def _remove() -> "tuple[int, list[str]]":
+ from core.inference.tools import (
+ record_kept_sandbox,
+ remove_session_sandbox,
+ sandbox_removal_deferred,
+ session_sandbox_has_files,
+ )
+ from storage.studio_db import sandbox_is_referenced_elsewhere
+
+ removed, kept = 0, []
+ for thread_id in thread_ids:
+ # The row went first, and another tab can upsert the same id in the
+ # meantime. That chat is alive, with a tool call possibly running in
+ # here, so its folder is not this delete's to take.
+ if get_chat_thread(thread_id) is not None:
+ continue
+ # A fork clones the message content, cards and all, so the source
+ # chat's files are still on screen in a chat the user kept.
+ if delete_files and sandbox_is_referenced_elsewhere(thread_id):
+ if session_sandbox_has_files(thread_id):
+ kept.append(thread_id)
+ # The user asked for these files and the chat is gone, so
+ # nothing comes back to that folder: written down, and the
+ # collection below takes it once the last fork goes too.
+ record_kept_sandbox(thread_id)
+ continue
+ # Again, next to the removal: the reference scan above reads
+ # every message, and another tab can recreate the chat while it runs.
+ if get_chat_thread(thread_id) is not None:
+ continue
+ if remove_session_sandbox(thread_id, delete_files = delete_files):
+ removed += 1
+ # A removal that had to wait for a running tool call is reported as
+ # kept: that call can still write a file, and this is the only
+ # answer the caller gets.
+ elif sandbox_removal_deferred(thread_id) or session_sandbox_has_files(thread_id):
+ kept.append(thread_id)
+ return removed, kept
+
+ try:
+ result = await run_in_threadpool(_remove)
+ except Exception:
+ logger.warning("chat_history.sandbox_cleanup_failed", exc_info = True)
+ return 0, []
+ # Whatever this delete asked for: the last chat referencing a workspace the
+ # user already asked to delete can go through the plain path, and only the
+ # records marked pending are ever collected.
+ from core.inference.tools import collect_orphaned_project_workspaces
+
+ await run_in_threadpool(collect_orphaned_project_workspaces)
+ return result
@router.get("/attachments")
@@ -549,22 +671,146 @@ async def patch_project(
return ChatProject(**project)
[email protected]("/projects/{project_id}", response_model = ChatProject)
[email protected]("/projects/{project_id}", response_model = ChatProjectDeleted)
async def delete_project(
project_id: str,
request: Request,
delete_files: bool = Query(False),
current_subject: str = Depends(get_current_subject),
):
- _cancel_active_research(
- request, [thread["id"] for thread in list_chat_threads(project_id = project_id)]
- )
- project = delete_chat_project(project_id, delete_files = delete_files)
+ # Rows first, files last: a member chat can still be running a tool in the
+ # workspace, and its cwd disappearing mid-call either kills the call or
+ # leaves what it writes next in a directory no project owns.
+ project = delete_chat_project(project_id, delete_files = False)
if project is None:
raise HTTPException(
status_code = 404,
detail = f"Project {project_id} not found",
)
+ # The transaction is the only authority on membership and it runs first, so
+ # a chat moved in just before is deleted and one moved out survives. An
+ # earlier listing would stop a chat that is still there.
+ member_ids = list(project.get("memberIds") or [])
+ # By run id: the rows are gone by now, so there is nothing left to look up.
+ _cancel_research_runs(request, list(project.get("activeResearchRunIds") or []))
+ _cancel_active_generations(member_ids)
+ if project.get("sandboxPath"):
+ from starlette.concurrency import run_in_threadpool
+
+ from core.inference.tools import (
+ finish_workspace_delete_when_idle,
+ forget_orphaned_project,
+ forget_orphaned_project_if_gone,
+ live_project_owns,
+ project_session_id,
+ record_orphaned_project,
+ wait_for_sessions_idle,
+ )
+ from storage.studio_db import (
+ delete_project_workspace,
+ sandbox_is_referenced_elsewhere,
+ )
+
+ # Cancelling only asks: a call already in the executor still has its
+ # cwd in there, and removing it strands what it writes next. The shared
+ # id first, since a call in a project runs as `project-<id>`.
+ shared = project_session_id(project_id)
+ idle = (
+ await run_in_threadpool(wait_for_sessions_idle, [shared, *member_ids])
+ if delete_files
+ else True
+ )
+ # A chat forked out of the project still shows cards for the shared
+ # workspace, and the fork is not one of the ids deleted here.
+ referenced = await run_in_threadpool(sandbox_is_referenced_elsewhere, shared, None)
+ # The row went first, so another client can create a project with this
+ # id in the window. It resolves to the same default path, and a tool
+ # call of its own may be writing in there right now.
+ recreated = await run_in_threadpool(get_chat_project, project_id) is not None
+ if not delete_files:
+ # The files stay, so the only job here is making them reachable: the
+ # row that held a custom path is gone, and a fork's cards still name
+ # this session.
+ await run_in_threadpool(
+ record_orphaned_project,
+ project_id,
+ project["sandboxPath"],
+ False,
+ project.get("rootPath"),
+ )
+ elif recreated:
+ logger.warning(
+ "Kept project workspace %s: a project was created with that id",
+ project_id,
+ )
+ elif not idle:
+ # Still running after the wait. Removing a live tool call's working
+ # directory is worse than keeping files the user asked to delete,
+ # and the record below means the next delete can still collect them.
+ logger.warning(
+ "Kept project workspace %s: a tool call was still running in it",
+ project_id,
+ )
+ elif referenced:
+ logger.info(
+ "Kept project workspace %s: a surviving chat still shows its files",
+ project_id,
+ )
+ if delete_files and idle and not referenced and not recreated:
+ # Written down first: the delete can decline an unexpected path or
+ # stop at a locked file, and the row that knew where this workspace
+ # lives has already gone. The record is the only way back to it.
+ await run_in_threadpool(
+ record_orphaned_project,
+ project_id,
+ project["sandboxPath"],
+ True,
+ project.get("rootPath"),
+ )
+ # Once more, next to the delete itself: the record write above is
+ # an await, and a project created in that window resolves to this
+ # same path.
+ if await run_in_threadpool(get_chat_project, project_id) is not None:
+ logger.warning(
+ "Kept project workspace %s: a project was created with that id",
+ project_id,
+ )
+ # Only when the new row is about these folders: the default
+ # root carries the project's name, so a project remade under
+ # this id can sit elsewhere and the old one would be stranded.
+ if await run_in_threadpool(
+ live_project_owns,
+ project_id,
+ project["sandboxPath"],
+ project.get("rootPath"),
+ ):
+ await run_in_threadpool(forget_orphaned_project, project_id)
+ else:
+ await run_in_threadpool(delete_project_workspace, project)
+ await run_in_threadpool(
+ forget_orphaned_project_if_gone,
+ project_id,
+ project["sandboxPath"],
+ project.get("rootPath"),
+ )
+ elif delete_files and not recreated:
+ # Written down so it can be resolved and later collected: the row
+ # that knew where it lives is gone. The root too, since the deferred
+ # delete removes what the immediate one would; not for a live id.
+ await run_in_threadpool(
+ record_orphaned_project,
+ project_id,
+ project["sandboxPath"],
+ True,
+ project.get("rootPath"),
+ )
+ if not idle:
+ # Nothing else would come back to it: the collection otherwise
+ # waits for some later delete that may never happen.
+ finish_workspace_delete_when_idle(project_id)
+ # Each member chat had its own sandbox for anything it wrote before joining
+ # the project, and deleting the project removes the only records of them.
+ _, sandboxes_kept = await _remove_sandboxes(member_ids, delete_files)
# Best-effort: drop the project's RAG sources (lazy import keeps RAG optional).
try:
import os
@@ -594,7 +840,9 @@ async def delete_project(
conn.close()
except Exception: # noqa: BLE001 - source cleanup must not block project deletion
logger.warning("failed to delete RAG sources for project %s", project_id, exc_info = True)
- return ChatProject(**project)
+ # Those folders are reachable from nothing now, so the caller is told which
+ # ones survived and can offer the delete once.
+ return ChatProjectDeleted(**project, sandboxes_kept = sandboxes_kept)
@router.get("/threads/{thread_id}/messages", response_model = ChatMessageListResponse)
@@ -718,10 +966,33 @@ async def record_import_ledger(
@router.delete("")
-async def clear_history(request: Request, current_subject: str = Depends(get_current_subject)):
- _cancel_active_research(request, [thread["id"] for thread in list_chat_threads()])
- clear_chat_history()
- return {"status": "deleted"}
+async def clear_history(
+ request: Request,
+ delete_files: bool = False,
+ current_subject: str = Depends(get_current_subject),
+):
+ thread_ids = [thread["id"] for thread in list_chat_threads()]
+ _cancel_active_research(request, thread_ids)
+ _cancel_active_generations(thread_ids)
+ # The clear reports what it deleted, which is what gets cleaned up: a thread
+ # added between the listing above and the delete is gone too, and its
+ # sandbox would otherwise be stranded.
+ cleared, cleared_runs = clear_chat_history()
+ # A chat started between the listing and the transaction is in `cleared`
+ # but was never cancelled, and a generation still running would dispatch a
+ # tool and rebuild the sandbox this call is about to remove.
+ listed = set(thread_ids)
+ late = [thread_id for thread_id in cleared if thread_id not in listed]
+ if late:
+ _cancel_active_generations(late)
+ # By id: the rows went with the threads, so nothing can look them up now.
+ _cancel_research_runs(request, cleared_runs)
+ # "Clear all chats" is the common bulk delete, so it has to clean up the
+ # same folders DELETE /threads does; otherwise every sandbox is stranded.
+ # delete_files matches DELETE /threads: off by default, since the files are
+ # the user's, but a caller clearing everything can ask for them too.
+ removed, kept = await _remove_sandboxes(list(dict.fromkeys(thread_ids + cleared)), delete_files)
+ return {"status": "deleted", "sandboxes_removed": removed, "sandboxes_kept": kept}
@router.get("/settings", response_model = ChatSettingsResponse)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 7d26e5a3d42..abed1a7d405 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -31,6 +31,7 @@ from dataclasses import replace
import re as _re
+from urllib.parse import quote as _urlquote
# Model size extraction (shared with core/inference/llama_cpp.py)
from utils.models import extract_model_size_b as _extract_model_size_b
@@ -13548,64 +13549,254 @@ _SANDBOX_MEDIA_TYPES = {
}
[email protected]("/sandbox/{session_id}/{filename}")
+def _sandbox_dir_for(session_id: str, create: bool = True) -> str:
+ """The session's sandbox directory.
+
+ ``create=False`` resolves the path without materialising it, so a read-only
+ request cannot leave a directory behind for every id it is asked about.
+ """
+ from core.inference.tools import get_sandbox_workdir, resolve_sandbox_workdir
+
+ resolver = get_sandbox_workdir if create else resolve_sandbox_workdir
+ return os.path.realpath(resolver(session_id))
+
+
+# A tool may write into a subdirectory, so a single segment is not enough. Taken
+# from the snapshot walk rather than restated, so the card can never advertise a
+# file this route would then refuse.
+from core.inference.tools import (
+ _INTERNAL_SANDBOX_FILES,
+ _MAX_SANDBOX_PATH_SEGMENTS,
+ _MAX_SNAPSHOT_DIRS,
+ _MAX_SNAPSHOT_FILES,
+ _servable_segment,
+)
+
+
+def _contained_sandbox_path(session_id: str, filename: str) -> tuple[str, str]:
+ """(sandbox_dir, absolute path) for a user-supplied relative path.
+
+ Character allowlist per segment and realpath containment as the image route
+ has always done, factored out so the two callers cannot drift. Containment
+ is decided by the resolved path, never by the string, so a symlink pointing
+ out of the sandbox is refused like any other escape.
+ """
+ parts = [part for part in filename.replace("\\", "/").split("/") if part not in ("", ".")]
+ if not parts or len(parts) > _MAX_SANDBOX_PATH_SEGMENTS:
+ raise HTTPException(status_code = 404, detail = "Not found")
+ for part in parts:
+ # os.path.join would let an absolute segment (or a Windows drive) throw
+ # the prefix away; realpath containment catches it, this is the guard in front.
+ if part == ".." or os.path.isabs(part) or os.path.splitdrive(part)[0]:
+ raise HTTPException(status_code = 404, detail = "Not found")
+ if not _re.fullmatch(r"[^/\\\x00-\x1f]{1,255}", part):
+ raise HTTPException(status_code = 404, detail = "Not found")
+ sandbox_dir = _sandbox_dir_for(session_id, create = False)
+ file_path = os.path.realpath(os.path.join(sandbox_dir, *parts))
+ if file_path != sandbox_dir and not file_path.startswith(sandbox_dir + os.sep):
+ raise HTTPException(
+ status_code = status.HTTP_403_FORBIDDEN,
+ detail = "Access denied",
+ )
+ return sandbox_dir, file_path
+
+
+def _sandbox_listing_names(sandbox_dir: str) -> "list[str]":
+ """Relative paths of the files in a sandbox, subdirectories included.
+
+ Bounded the same way the snapshot walk is, so a chat that unpacked an
+ archive cannot turn a listing into a filesystem crawl.
+ """
+ names: "list[str]" = []
+ visited = 0
+ for base, dirs, entries in os.walk(sandbox_dir):
+ visited += 1
+ if visited > _MAX_SNAPSHOT_DIRS:
+ return names
+ depth = base[len(sandbox_dir) :].count(os.sep)
+ # depth 0 is the sandbox itself, whose files are one segment.
+ # Segments the route would refuse are dropped here too, so the two walks agree.
+ dirs[:] = (
+ []
+ if depth >= _MAX_SANDBOX_PATH_SEGMENTS - 1
+ else [d for d in sorted(dirs) if not d.startswith(".") and _servable_segment(d)]
+ )
+ for entry in sorted(entries):
+ # Mirrors the snapshot, dotfiles included, and like it hides the
+ # bookkeeping only where we write it.
+ if base == sandbox_dir and entry in _INTERNAL_SANDBOX_FILES:
+ continue
+ if not _servable_segment(entry):
+ continue
+ path = os.path.join(base, entry)
+ try:
+ if not os.path.isfile(path) or os.path.islink(path):
+ continue
+ except OSError:
+ continue
+ names.append(os.path.relpath(path, sandbox_dir).replace(os.sep, "/"))
+ if len(names) >= _MAX_SNAPSHOT_FILES:
+ return names
+ return names
+
+
+def _sandbox_listing(sandbox_dir: str) -> "list[dict]":
+ """Name, size and mtime for everything this chat's tools left behind."""
+ files = []
+ if not os.path.isdir(sandbox_dir):
+ return files
+ for name in _sandbox_listing_names(sandbox_dir):
+ path = os.path.join(sandbox_dir, name)
+ try:
+ stat = os.stat(path)
+ except OSError:
+ continue
+ files.append(
+ {
+ "name": name,
+ "size": stat.st_size,
+ "modified": int(stat.st_mtime),
+ "inline": os.path.splitext(name)[1].lower() in _SANDBOX_MEDIA_TYPES,
+ }
+ )
+ return files
+
+
[email protected]("/sandbox/{session_id}")
+async def list_sandbox_files(
+ session_id: str,
+ request: Request,
+ token: Optional[str] = None,
+ session: Optional[str] = None,
+):
+ """Where this chat's files are, and what is in there.
+
+ The path answers "where did my file go"; before this the only way to find
+ one was to search the filesystem by hand.
+ """
+ await _authenticate_header_or_query(request, token)
+
+ from starlette.concurrency import run_in_threadpool
+
+ def _resolve_and_list() -> "tuple[str, list[dict]]":
+ # The query form carries an id a path segment cannot: an API client can
+ # use one with a slash in it, and ASGI decodes %2F before route matching.
+ sandbox_dir = _sandbox_dir_for(session or session_id, create = False)
+ if not os.path.isdir(sandbox_dir):
+ # Right after an upgrade the background move can rename the legacy
+ # tree into place between resolving and walking it. One more resolve
+ # finds it at the destination rather than showing an empty chat.
+ sandbox_dir = _sandbox_dir_for(session or session_id, create = False)
+ return sandbox_dir, _sandbox_listing(sandbox_dir)
+
+ # Resolving scans the root for a marked directory and may read the legacy
+ # root too, so it belongs in the worker with the walk: on a slow or network
+ # filesystem either one would hold the event loop for every other request.
+ sandbox_dir, files = await run_in_threadpool(_resolve_and_list)
+ return {"path": sandbox_dir, "files": files}
+
+
[email protected]_route("/sandbox/{session_id}/{filename:path}", methods = ["GET", "HEAD"])
async def serve_sandbox_file(
session_id: str,
filename: str,
request: Request,
token: Optional[str] = None,
+ session: Optional[str] = None,
):
"""
- Serve image files created by Python tool execution.
+ Serve a file a tool call created in this chat's sandbox.
+
+ Images keep their real media type and render inline. Everything else is an
+ opaque attachment: the model picks these filenames, so an inline text/html
+ or image/svg+xml would be same-origin script execution. nosniff plus a
+ Content-Disposition filename is what makes serving them safe.
Accepts auth via an Authorization header or a query token. Studio uses an
authenticated fetch and object URL; query auth remains for older clients.
"""
- from fastapi.responses import FileResponse
-
# ── Authentication (header or query param) ──────────────────
await _authenticate_header_or_query(request, token)
- # ── Filename sanitization ───────────────────────────────────
+ # ── Filename sanitization + path containment ────────────────
+ import stat as _stat
+
+ from starlette.concurrency import run_in_threadpool
+
safe_filename = os.path.basename(filename)
- if not safe_filename or safe_filename in (".", ".."):
- raise HTTPException(status_code = 404, detail = "Not found")
- # Defense-in-depth allowlist (clears CodeQL py/path-injection), still allowing
- # names like "loss curve.png"; basename + extension + realpath below are the guards.
- if not _re.fullmatch(r"[^/\\\x00-\x1f]{1,255}", safe_filename):
- raise HTTPException(status_code = 404, detail = "Not found")
- # ── Extension allowlist ─────────────────────────────────────
- ext = os.path.splitext(safe_filename)[1].lower()
- media_type = _SANDBOX_MEDIA_TYPES.get(ext)
- if not media_type:
- raise HTTPException(
- status_code = status.HTTP_403_FORBIDDEN,
- detail = "File type not allowed",
- )
+ # In a worker like the listing: resolving the sandbox touches the
+ # filesystem, and so does the open below.
+ def _open_checked() -> "tuple[int, int]":
+ _dir, path = _contained_sandbox_path(session or session_id, filename)
+ if not os.path.isfile(path):
+ # As in the listing: the legacy move can rename the tree out from
+ # under a path resolved a moment ago, and the file is at the new one.
+ _dir, path = _contained_sandbox_path(session or session_id, filename)
+ try:
+ # O_NOFOLLOW: tool code runs in this directory and can put a link
+ # here between the check and the open.
+ handle = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
+ except OSError:
+ raise HTTPException(status_code = 404, detail = "Not found") from None
+ try:
+ info = os.fstat(handle)
+ # The descriptor is what gets read, so it is what the containment
+ # check has to be about: resolved again, and the same file, or a
+ # parent swapped for a link would be served from outside the root.
+ _dir, again = _contained_sandbox_path(session or session_id, filename)
+ checked = os.stat(again)
+ if not _stat.S_ISREG(info.st_mode) or (checked.st_dev, checked.st_ino) != (
+ info.st_dev,
+ info.st_ino,
+ ):
+ raise HTTPException(status_code = 404, detail = "Not found")
+ except BaseException:
+ os.close(handle)
+ raise
+ return handle, info.st_size
- # ── Path containment check ──────────────────────────────────
- from core.inference.tools import get_sandbox_workdir
+ handle, size = await run_in_threadpool(_open_checked)
+ head_only = getattr(request, "method", "GET").upper() == "HEAD"
+ if head_only:
+ # FastAPI does not add HEAD to a GET route, and the client asks with one
+ # to refresh the session and settle whether the file is still there.
+ # Nothing is read: the artifact can be gigabytes.
+ os.close(handle)
- sandbox_dir = os.path.realpath(get_sandbox_workdir(session_id))
- file_path = os.path.realpath(os.path.join(sandbox_dir, safe_filename))
- if file_path != sandbox_dir and not file_path.startswith(sandbox_dir + os.sep):
- raise HTTPException(
- status_code = status.HTTP_403_FORBIDDEN,
- detail = "Access denied",
+ ext = os.path.splitext(safe_filename)[1].lower()
+ media_type = _SANDBOX_MEDIA_TYPES.get(ext)
+ headers = {
+ "Cache-Control": "private, no-store",
+ "X-Content-Type-Options": "nosniff",
+ }
+ if media_type is None:
+ media_type = "application/octet-stream"
+ # RFC 5987: ASCII fallback plus UTF-8 form, so "ventas año.csv" saves.
+ ascii_name = safe_filename.encode("ascii", "replace").decode("ascii").replace('"', "_")
+ quoted = _urlquote(safe_filename)
+ headers["Content-Disposition"] = (
+ f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{quoted}"
)
- if not os.path.isfile(file_path):
- raise HTTPException(status_code = 404, detail = "Not found")
+ headers["Content-Length"] = str(size)
+ if head_only:
+ return Response(status_code = 200, media_type = media_type, headers = headers)
+
+ def _read():
+ # Exactly the length in the header: another call can still append to
+ # this file, and a body longer than Content-Length is cut off or
+ # refused by the client rather than simply carrying the extra.
+ remaining = size
+ with os.fdopen(handle, "rb") as opened:
+ while remaining > 0:
+ chunk = opened.read(min(64 * 1024, remaining))
+ if not chunk:
+ return
+ remaining -= len(chunk)
+ yield chunk
- return FileResponse(
- path = file_path,
- media_type = media_type,
- headers = {
- "Cache-Control": "private, no-store",
- "X-Content-Type-Options": "nosniff",
- },
- )
+ return StreamingResponse(_read(), media_type = media_type, headers = headers)
# =====================================================================
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 8682b1ee82b..830452627ec 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -124,6 +124,78 @@ def _ensure_project_workspace(root_path: str) -> str:
return str(root_resolved)
+def sandbox_is_referenced_elsewhere(
+ session_id: str, exclude_thread_id: "str | None" = None
+) -> bool:
+ """Whether a surviving chat still shows file cards for this sandbox.
+
+ Forking clones the message content verbatim, so the fork's cards keep the
+ source chat's session id. Deleting the source's files would leave those
+ cards downloading nothing, in a chat the user did not delete.
+ """
+ if not session_id:
+ return False
+ conn = get_connection()
+ try:
+ # The LIKE only narrows, on the id as JSON writes it, so a quote or a
+ # backslash is still found. Every hit is parsed and the id has to be a
+ # sessionId value: a short one is a substring of ordinary prose.
+ escaped = json.dumps(session_id)[1:-1]
+ rows = conn.execute(
+ """
+ SELECT content_json FROM chat_messages
+ WHERE (? IS NULL OR thread_id != ?) AND content_json LIKE ? ESCAPE '\\'
+ """,
+ (exclude_thread_id, exclude_thread_id, f"%{_like_escape(escaped)}%"),
+ )
+ for row in rows:
+ if _mentions_session(row["content_json"], session_id):
+ return True
+ return False
+ except sqlite3.Error:
+ # A locked database is not an answer, and every caller reads False as
+ # "nothing shows these files any more" before deleting them. Kept, so
+ # the worst case is a folder collected on the next delete.
+ logger.warning("Could not check references for sandbox %s; keeping it", session_id)
+ return True
+ finally:
+ conn.close()
+
+
+def _mentions_session(content_json: str, session_id: str) -> bool:
+ """Whether this message's content names *session_id* as a sandbox."""
+ try:
+ content = json.loads(content_json)
+ except (TypeError, ValueError):
+ return False
+ stack = [content]
+ while stack:
+ node = stack.pop()
+ if isinstance(node, dict):
+ if node.get("sessionId") == session_id:
+ return True
+ stack.extend(node.values())
+ elif isinstance(node, list):
+ stack.extend(node)
+ return False
+
+
+def _like_escape(value: str) -> str:
+ for char in ("\\", "%", "_"):
+ value = value.replace(char, "\\" + char)
+ return value
+
+
+def delete_project_workspace(project: dict) -> None:
+ """Remove a deleted project's workspace directory.
+
+ Separate from the row delete so the caller can stop the tool calls running
+ in there first: pulling the working directory out from under a live
+ subprocess is how a half-written file ends up outside any project.
+ """
+ _delete_project_workspace(project)
+
+
def _delete_project_workspace(project: dict) -> None:
root_path = project.get("rootPath")
if not root_path:
@@ -1755,15 +1827,30 @@ def delete_chat_threads(ids: list[str]) -> None:
conn.close()
-def clear_chat_history() -> None:
+def clear_chat_history() -> "tuple[list[str], list[str]]":
+ """Delete every chat thread. Returns (thread ids removed, research runs cascaded).
+
+ Both taken inside the same transaction: another process can add a thread
+ between a listing and this call, its sandbox has to be cleaned up too, and
+ after the cascade nothing can tell the supervisor which runs to stop.
+ """
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
_ensure_chat_attachment_inventory_current(conn)
+ removed = [str(row[0]) for row in conn.execute("SELECT id FROM chat_threads")]
+ active_runs = [
+ str(row[0])
+ for row in conn.execute(
+ "SELECT id FROM research_runs "
+ "WHERE status NOT IN ('cancelled', 'completed', 'failed')"
+ )
+ ]
conn.execute("DELETE FROM chat_attachment_tombstones")
conn.execute("DELETE FROM chat_threads")
_mark_chat_attachment_inventory_clean(conn)
conn.commit()
+ return removed, active_runs
finally:
conn.close()
@@ -1901,6 +1988,23 @@ def delete_chat_project(id: str, delete_files: bool = False) -> Optional[dict]:
(id,),
)
}
+ # Read before the cascade removes them: afterwards nothing can tell the
+ # supervisor which runs to stop, and a worker keeps doing model, web and
+ # RAG work for a project that is gone.
+ active_runs = (
+ [
+ row["id"]
+ for row in conn.execute(
+ "SELECT id FROM research_runs WHERE thread_id IN ({}) "
+ "AND status NOT IN ('cancelled', 'completed', 'failed')".format(
+ ",".join("?" for _ in thread_ids) or "NULL"
+ ),
+ tuple(thread_ids),
+ )
+ ]
+ if thread_ids
+ else []
+ )
_reparent_surviving_forks(conn, thread_ids)
conn.execute("DELETE FROM chat_threads WHERE project_id = ?", (id,))
conn.execute("DELETE FROM chat_projects WHERE id = ?", (id,))
@@ -1908,6 +2012,11 @@ def delete_chat_project(id: str, delete_files: bool = False) -> Optional[dict]:
conn.commit()
if delete_files:
_delete_project_workspace(project)
+ # The membership this transaction actually deleted, which is not the
+ # caller's earlier listing when a chat was moved in between the two.
+ project = dict(project)
+ project["memberIds"] = sorted(thread_ids)
+ project["activeResearchRunIds"] = active_runs
return project
except Exception:
conn.rollback()
diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
new file mode 100644
index 00000000000..e0a0d6ad5be
--- /dev/null
+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
@@ -0,0 +1,5838 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Where a chat's files live, and how a user gets them back.
+
+Every assertion here failed before: the sandbox ignored UNSLOTH_STUDIO_HOME, only
+images could be fetched, nothing listed a chat's files, bash reported none, the
+compiled cache landed in the launcher's CWD, and a deleted chat left its folder
+behind. Verified on Windows, macOS and Linux.
+"""
+
+import hashlib
+import json
+import os
+import shutil
+import sys
+import tempfile
+import threading
+import time
+import platform
+from pathlib import Path
+
+import pytest
+
+
+# ---------------------------------------------------------------------------
+# 1. Sandbox location
+# ---------------------------------------------------------------------------
+def test_sandbox_lives_under_the_studio_home(tmp_path, monkeypatch):
+ fake_home = tmp_path / "userprofile"
+ studio_home = tmp_path / "custom_studio_home"
+ fake_home.mkdir()
+ studio_home.mkdir()
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(studio_home))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ wd = Path(tools.get_sandbox_workdir("__LOCALID_aB3xY7q"))
+ print(f"\n[{platform.system()}] sandbox workdir = {wd}")
+
+ # It follows UNSLOTH_STUDIO_HOME instead of dropping a third folder in the
+ # user's home next to .unsloth.
+ assert str(wd).startswith(str(studio_home)), wd
+ assert not str(wd).startswith(str(fake_home / "studio_sandbox")), wd
+ assert wd.parent.name == "sandbox"
+ assert wd.name.startswith("__LOCALID_")
+
+
+def test_sandbox_home_override(tmp_path, monkeypatch):
+ """A user who wants the sandbox on another volume can say so."""
+ elsewhere = tmp_path / "other volume" / "sandboxes"
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(elsewhere))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ wd = Path(tools.get_sandbox_workdir("__LOCALID_aB3xY7q"))
+ assert wd == elsewhere / "__LOCALID_aB3xY7q"
+
+
+def test_legacy_sandbox_is_migrated(tmp_path, monkeypatch):
+ """Files created before the move are carried over, not abandoned."""
+ fake_home = tmp_path / "userprofile"
+ studio_home = tmp_path / "studio_home"
+ legacy = fake_home / "studio_sandbox" / "__LOCALID_old1234"
+ legacy.mkdir(parents = True)
+ (legacy / "results.csv").write_text("a,b\n1,2\n")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(studio_home))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ wd = Path(tools.get_sandbox_workdir("__LOCALID_new5678"))
+ # Another chat's folder rides the background pass, so a first call never
+ # waits on the whole tree.
+ for thread in threading.enumerate():
+ if thread.name == "sandbox-migrate":
+ thread.join(30)
+ moved = wd.parent / "__LOCALID_old1234" / "results.csv"
+ print(f"\nmigrated to {moved}")
+ assert moved.is_file()
+ assert moved.read_text() == "a,b\n1,2\n"
+
+
+# ---------------------------------------------------------------------------
+# 2. Getting files back out
+# ---------------------------------------------------------------------------
+def test_images_stay_inline_and_everything_else_downloads():
+ """Images keep a real media type; the rest are opaque attachments.
+
+ The allowlist is deliberately NOT just widened: the model picks these
+ filenames, so an inline text/html would be same-origin script execution.
+ """
+ from routes.inference import _SANDBOX_MEDIA_TYPES
+
+ for ext in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"):
+ assert ext in _SANDBOX_MEDIA_TYPES
+ for ext in (".csv", ".txt", ".py", ".json", ".pdf", ".zip", ".html", ".svg"):
+ assert ext not in _SANDBOX_MEDIA_TYPES, ext
+
+ import inspect
+ from routes import inference
+
+ src = inspect.getsource(inference.serve_sandbox_file)
+ assert "application/octet-stream" in src
+ assert "Content-Disposition" in src
+ assert "attachment" in src
+ assert "File type not allowed" not in src, "non-images are no longer rejected"
+
+
+def test_sandbox_listing_route_exists():
+ """The UI can enumerate a chat's files, and learn where they live."""
+ from routes.inference import router
+
+ sandbox_routes = sorted(r.path for r in router.routes if "sandbox" in r.path)
+ print(f"\nsandbox routes = {sandbox_routes}")
+ # :path so a file written into a subdirectory is reachable.
+ assert sandbox_routes == ["/sandbox/{session_id}", "/sandbox/{session_id}/{filename:path}"]
+
+ import inspect
+ from routes import inference
+
+ src = inspect.getsource(inference.list_sandbox_files)
+ assert '"path"' in src, "the listing must answer 'where did my file go'"
+
+
+# ---------------------------------------------------------------------------
+# 3. Reporting what a call created
+# ---------------------------------------------------------------------------
+def test_both_executors_report_created_files(tmp_path, monkeypatch):
+ """A file is reported whether it came from python or from bash."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ session = "__LOCALID_exec123"
+ workdir = tools.get_sandbox_workdir(session)
+
+ for name, run in (
+ (
+ "py.csv",
+ lambda: tools._python_exec("open('py.csv','w').write('a,b\\n')", session_id = session),
+ ),
+ ("sh.csv", lambda: tools._bash_exec("printf 'a,b\\n' > sh.csv", session_id = session)),
+ ):
+ result = run()
+ print(f"\n{name} -> {result!r}")
+ assert "__FILES__:" in result, result
+ assert name in result
+ assert os.path.isfile(os.path.join(workdir, name))
+
+ # The sentinel never reaches the model.
+ from core.inference.tool_loop_controller import strip_result_for_model
+
+ stripped = strip_result_for_model('done\n__FILES__:[{"name": "x.csv"}]')
+ assert "__FILES__" not in stripped
+ assert stripped.strip() == "done"
+
+
+def test_internal_temp_files_are_not_reported(tmp_path, monkeypatch):
+ """The executor's own scratch script is not a user-facing artifact."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ result = tools._python_exec("print('hi')", session_id = "__LOCALID_tmp999")
+ assert "studio_exec_" not in result
+ assert "__FILES__" not in result
+
+
+def test_tool_description_says_files_are_kept():
+ from core.inference import tools
+
+ note = tools._SANDBOX_PATHS_NOTE
+ print(f"\nsandbox note = {note!r}")
+ assert "download link" in note
+ assert "name the files you created" in note
+ assert "absolute path" in note
+
+
+# ---------------------------------------------------------------------------
+# 4. Compiled cache
+# ---------------------------------------------------------------------------
+def test_compiled_cache_is_pinned_under_the_studio_home(tmp_path, monkeypatch):
+ """Not left CWD-relative, which put it in %USERPROFILE% on Windows."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio_home"))
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+
+ import importlib
+ from utils.paths import storage_roots
+
+ importlib.reload(storage_roots)
+ storage_roots.ensure_studio_directories()
+
+ location = Path(os.environ["UNSLOTH_COMPILE_LOCATION"])
+ print(f"\n[{platform.system()}] compiled cache pinned to {location}")
+ assert location.is_absolute()
+ assert str(tmp_path / "studio_home") in str(location)
+
+
+def test_cache_cleanup_finds_the_configured_and_cwd_caches(tmp_path, monkeypatch):
+ """Cleanup can now see a cache created outside the source tree.
+
+ Both cases matter: the pinned location for new installs, and the launcher's
+ CWD for a machine that already has one sitting in the user profile.
+ """
+ from utils import cache_cleanup
+
+ monkeypatch.chdir(tmp_path)
+ configured = tmp_path / "studio_home" / "compiled_cache"
+ configured.mkdir(parents = True)
+ (tmp_path / "unsloth_compiled_cache").mkdir()
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(configured))
+
+ found = {str(Path(d).resolve()) for d in cache_cleanup.get_existing_cache_dirs()}
+ print("\nfound cache dirs:")
+ for d in sorted(found):
+ print(" ", d)
+ assert str(configured.resolve()) in found
+ assert str((tmp_path / "unsloth_compiled_cache").resolve()) in found
+
+
+# ---------------------------------------------------------------------------
+# 5. Cleanup on chat delete
+# ---------------------------------------------------------------------------
+def test_deleting_a_chat_cleans_up_its_sandbox(tmp_path, monkeypatch):
+ """An empty sandbox always goes; files need an explicit opt-in."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ empty = Path(tools.get_sandbox_workdir("__LOCALID_empty11"))
+ assert tools.remove_session_sandbox("__LOCALID_empty11") is True
+ assert not empty.exists()
+
+ tools._workdirs.clear()
+ withfile = Path(tools.get_sandbox_workdir("__LOCALID_files22"))
+ (withfile / "keep.csv").write_text("a\n")
+ # Not deleted implicitly: those files are the user's.
+ assert tools.remove_session_sandbox("__LOCALID_files22") is False
+ assert (withfile / "keep.csv").is_file()
+ assert tools.remove_session_sandbox("__LOCALID_files22", delete_files = True) is True
+ assert not withfile.exists()
+
+
+def test_sandbox_removal_cannot_escape_the_root(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ outside = tmp_path / "precious"
+ outside.mkdir()
+ for bad in ("..", "../precious", "/etc", "project-abc", ""):
+ assert tools.remove_session_sandbox(bad, delete_files = True) is False
+ assert outside.is_dir()
+
+
+def test_a_windows_device_name_never_becomes_a_directory(tmp_path, monkeypatch):
+ """CON, NUL and friends are reserved on Windows even as folder names, and
+ the session id comes from the caller."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ seen = set()
+ for reserved in ("con", "NUL", "aux", "COM1", "lpt9", "nul.txt"):
+ workdir = Path(tools.get_sandbox_workdir(reserved))
+ assert workdir.name.startswith("_id-"), reserved
+ seen.add(workdir.name)
+ assert tools.remove_session_sandbox(reserved, delete_files = True) is True
+ assert len(seen) == 6, "reserved names shared a directory"
+
+
+def test_reading_a_sandbox_never_creates_it(tmp_path, monkeypatch):
+ """A GET must not leave a folder behind for every id it is asked about."""
+ root = tmp_path / "sb"
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ resolved = Path(tools.resolve_sandbox_workdir("__LOCALID_ghost"))
+ assert resolved == root / "__LOCALID_ghost"
+ assert not resolved.exists()
+ assert not root.exists()
+ # The creating resolver still agrees on the path.
+ assert Path(tools.get_sandbox_workdir("__LOCALID_ghost")) == resolved
+ assert resolved.is_dir()
+
+
+def test_clearing_the_compiled_cache_covers_the_configured_location(tmp_path, monkeypatch):
+ """The cleanup must follow UNSLOTH_COMPILE_LOCATION, not just the defaults."""
+ pinned = tmp_path / "home" / "compiled_cache"
+ pinned.mkdir(parents = True)
+ (pinned / "unsloth_compiled_module_gemma3.py").write_text("x = 1\n")
+ (pinned / "UnslothSFTTrainer.py").write_text("x = 1\n")
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(pinned))
+
+ from utils import cache_cleanup
+
+ assert pinned in cache_cleanup.get_existing_cache_dirs()
+ cache_cleanup.clear_unsloth_compiled_cache(preserve_patterns = ["Unsloth*Trainer.py"])
+ assert not (pinned / "unsloth_compiled_module_gemma3.py").exists()
+ assert (pinned / "UnslothSFTTrainer.py").is_file()
+
+
+def test_a_file_in_a_subdirectory_is_reported_and_servable(tmp_path, monkeypatch):
+ """`df.to_csv("outputs/report.csv")` is ordinary; a top-level listing saw
+ only the directory and dropped it, so no chip and no download."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_nested1"))
+ before = tools._snapshot_workdir_files(str(workdir))
+ (workdir / "outputs").mkdir()
+ (workdir / "outputs" / "report.csv").write_text("a,b\n")
+ (workdir / "top.txt").write_text("x")
+
+ sentinels = tools._created_file_sentinels(str(workdir), before)
+ assert "outputs/report.csv" in sentinels
+ assert "top.txt" in sentinels
+
+
+def test_the_walk_is_bounded(tmp_path, monkeypatch):
+ """A chat that unpacked an archive must not turn a tool call into a crawl."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_deep111"))
+ deep = workdir
+ for level in range(8):
+ deep = deep / f"level{level}"
+ deep.mkdir()
+ (deep / "f.txt").write_text("x")
+ found = tools._snapshot_workdir_files(str(workdir))
+ assert found, "nothing was found at all"
+ assert max(name.count("/") + 1 for name in found) <= tools._MAX_SANDBOX_PATH_SEGMENTS
+
+
+def test_files_written_before_a_timeout_are_still_reported(tmp_path, monkeypatch):
+ """`printf data > report.csv; sleep 999` produced that file."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ result = tools._bash_exec(
+ "printf data > report.csv; sleep 30",
+ timeout = 3,
+ session_id = "__LOCALID_slowrun",
+ )
+ assert "timed out" in result
+ assert "__FILES__:" in result, result
+ assert "report.csv" in result
+
+
+def test_the_image_list_is_capped_like_the_file_list(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_manyimg"))
+ before = tools._snapshot_workdir_files(str(workdir))
+ for i in range(80):
+ (workdir / f"frame{i:03d}.png").write_bytes(b"\x89PNG")
+ sentinels = tools._created_file_sentinels(str(workdir), before)
+ images = json.loads(sentinels.split("__IMAGES__:")[1])
+ files = json.loads(sentinels.split("__FILES__:")[1].split("\n")[0])
+ assert len(images) == tools._MAX_REPORTED_FILES
+ assert len(files) == tools._MAX_REPORTED_FILES
+
+
+def test_a_tool_printing_the_files_marker_keeps_its_output():
+ """Only a structurally valid trailing envelope is stripped."""
+ from core.inference.tool_loop_controller import strip_result_for_model
+
+ printed = "here is the doc:\n__FILES__:see the manual\nand the answer is 42"
+ assert strip_result_for_model(printed) == printed
+
+ real = 'output\n__FILES__:[{"name": "a.csv", "size": 3}]'
+ assert strip_result_for_model(real) == "output"
+
+
+def test_clearing_all_chats_cleans_up_their_sandboxes(tmp_path, monkeypatch):
+ """The UI's "Clear all chats" is the common bulk delete."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ empty = Path(tools.get_sandbox_workdir("__LOCALID_bulk111"))
+ assert empty.is_dir()
+
+ import routes.chat_history as chat_history
+
+ monkeypatch.setattr(chat_history, "list_chat_threads", lambda: [{"id": "__LOCALID_bulk111"}])
+ monkeypatch.setattr(chat_history, "clear_chat_history", lambda: ([], []))
+ monkeypatch.setattr(chat_history, "_cancel_active_research", lambda request, ids: None)
+
+ import asyncio
+
+ body = asyncio.run(chat_history.clear_history(request = None, current_subject = "tester"))
+ assert body["sandboxes_removed"] == 1
+ assert not empty.exists()
+
+
+def test_the_legacy_migration_is_startup_work(tmp_path, monkeypatch):
+ """Across filesystems it copies every session, which is not something a
+ listing or a download can wait on: those run on the event loop."""
+ home = tmp_path / "home"
+ fake_home = tmp_path / "userprofile"
+ fake_home.mkdir()
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ legacy = fake_home / "studio_sandbox" / "__LOCALID_upgrade"
+ legacy.mkdir(parents = True)
+ (legacy / "sales.csv").write_text("a,b\n")
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ # A read does not move anything.
+ Path(tools.resolve_sandbox_workdir("__LOCALID_upgrade"))
+ assert (legacy / "sales.csv").is_file()
+
+ tools.migrate_legacy_sandbox_in_background()
+ for _ in range(50):
+ if not legacy.exists():
+ break
+ time.sleep(0.05)
+ resolved = Path(tools.resolve_sandbox_workdir("__LOCALID_upgrade"))
+ assert (resolved / "sales.csv").is_file(), "the file did not follow the migration"
+
+
+def test_the_migration_is_serialised(tmp_path, monkeypatch):
+ """Two chats running their first tool call at once must not strand files."""
+ import threading
+
+ fake_home = tmp_path / "userprofile"
+ fake_home.mkdir()
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ for index in range(6):
+ session = fake_home / "studio_sandbox" / f"__LOCALID_race{index}"
+ session.mkdir(parents = True)
+ (session / "data.csv").write_text("a\n")
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ results = []
+
+ def first_tool_call(index):
+ results.append(Path(tools.get_sandbox_workdir(f"__LOCALID_race{index}")))
+
+ threads = [threading.Thread(target = first_tool_call, args = (i,)) for i in range(6)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+
+ assert len(results) == 6
+ for workdir in results:
+ assert (workdir / "data.csv").is_file(), f"{workdir} lost its files"
+
+
+def test_every_reported_file_is_downloadable(tmp_path, monkeypatch):
+ """The walk and the download route must agree, or the card advertises a
+ file that always 404s."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from fastapi import HTTPException
+
+ from core.inference import tools
+ from routes.inference import _contained_sandbox_path
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_agree11"))
+ before = tools._snapshot_workdir_files(str(workdir))
+ deep = workdir
+ for level in range(6):
+ deep = deep / f"d{level}"
+ deep.mkdir()
+ (deep / f"f{level}.csv").write_text("x")
+
+ reported = json.loads(
+ tools._created_file_sentinels(str(workdir), before).split("__FILES__:")[1].split("\n")[0]
+ )
+ assert reported, "nothing was reported at all"
+ for entry in reported:
+ # Must not raise: whatever the snapshot names, the route must serve.
+ try:
+ _sandbox_dir, resolved = _contained_sandbox_path("__LOCALID_agree11", entry["name"])
+ except HTTPException as refused:
+ raise AssertionError(f"{entry['name']} reported but refused ({refused.status_code})")
+ assert os.path.isfile(resolved), entry["name"]
+
+
+def test_a_same_timestamp_overwrite_is_still_reported(tmp_path, monkeypatch):
+ """Coarse-resolution volumes (FAT/exFAT) can repeat mtime_ns."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_coarse1"))
+ target = workdir / "report.csv"
+ target.write_text("a")
+ before = tools._snapshot_workdir_files(str(workdir))
+ target.write_text("a,b,c,d")
+ os.utime(target, ns = (before["report.csv"][0], before["report.csv"][0])) # same tick
+ assert "report.csv" in tools._created_file_sentinels(str(workdir), before)
+
+
+ "payload",
+ [
+ "[null]",
+ "[1, 2]",
+ '["a.csv"]',
+ '[{"size": 3}]',
+ '[{"name": ""}]',
+ '[{"name": 5}]',
+ '[{"name": "a.csv", "size": "big"}]',
+ ],
+)
+def test_a_malformed_files_envelope_is_left_as_text(payload):
+ """Only the executor's own envelope is protocol; anything else is output."""
+ from core.inference.tool_loop_controller import strip_result_for_model
+
+ printed = f"tool output\n__FILES__:{payload}"
+ assert strip_result_for_model(printed) == printed
+
+
+def test_a_dotfile_a_tool_creates_is_reported(tmp_path, monkeypatch):
+ """.gitignore is a real artifact and the route serves it; only the noisy
+ dot-DIRECTORIES stay out."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_dotfile"))
+ before = tools._snapshot_workdir_files(str(workdir))
+ (workdir / ".gitignore").write_text("*.pyc\n")
+ (workdir / ".env.example").write_text("KEY=\n")
+ noise = workdir / ".cache"
+ noise.mkdir()
+ (noise / "junk.bin").write_bytes(b"x")
+
+ reported = tools._snapshot_workdir_files(str(workdir))
+ assert ".gitignore" in reported and ".env.example" in reported
+ assert not any(name.startswith(".cache/") for name in reported), reported
+ assert ".gitignore" in tools._created_file_sentinels(str(workdir), before)
+
+
+def test_a_name_the_route_would_refuse_is_never_reported(tmp_path, monkeypatch):
+ """A backslash or control character is legal in a POSIX filename but the
+ download route rejects it, so the card must not offer it."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_badname"))
+ before = tools._snapshot_workdir_files(str(workdir))
+ for name in ("back\\slash.csv", "bell\x07.csv", "ok.csv"):
+ try:
+ (workdir / name).write_text("x")
+ except OSError:
+ continue
+
+ reported = tools._snapshot_workdir_files(str(workdir))
+ assert "ok.csv" in reported
+ assert not any("\\" in name or any(ord(c) < 32 for c in name) for name in reported), reported
+ del before
+
+
+def test_deleting_a_chat_right_after_an_upgrade_finds_its_legacy_sandbox(tmp_path, monkeypatch):
+ """The first thing a user does may be a delete, before any tool has run."""
+ fake_home = tmp_path / "userprofile"
+ fake_home.mkdir()
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ legacy = fake_home / "studio_sandbox" / "__LOCALID_oldchat"
+ legacy.mkdir(parents = True)
+ (legacy / "sales.csv").write_text("a,b\n")
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ assert tools.remove_session_sandbox("__LOCALID_oldchat", delete_files = True) is True
+ assert not legacy.exists()
+ assert not (Path(tools.sandbox_root()) / "__LOCALID_oldchat").exists()
+
+
+def test_a_configured_cache_that_holds_other_files_is_never_deleted(tmp_path, monkeypatch):
+ """UNSLOTH_COMPILE_LOCATION is user-set. Pointed at a shared directory it
+ would otherwise be rmtree'd at startup, taking whatever else lives there."""
+ shared = tmp_path / "shared"
+ (shared / "important").mkdir(parents = True)
+ (shared / "important" / "notes.txt").write_text("user data")
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(shared))
+
+ from utils import cache_cleanup
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert (shared / "important" / "notes.txt").read_text() == "user data"
+
+ cache_cleanup.clear_unsloth_compiled_cache(preserve_patterns = ["Unsloth*Trainer.py"])
+ assert (shared / "important" / "notes.txt").read_text() == "user data"
+
+
+def test_an_unmarked_configured_cache_keeps_what_studio_did_not_write(tmp_path, monkeypatch):
+ cache = tmp_path / "compiled_cache"
+ cache.mkdir()
+ (cache / "unsloth_compiled_module_gemma3.py").write_text("x = 1\n")
+ (cache / "__pycache__").mkdir()
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(cache))
+
+ from utils import cache_cleanup
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert not (cache / "unsloth_compiled_module_gemma3.py").exists()
+ assert (cache / "__pycache__").is_dir()
+
+
+def test_a_symlinked_session_cannot_serve_files_outside_the_sandbox(tmp_path, monkeypatch):
+ """A legacy session entry that is a symlink used to become the sandbox root
+ for reads, so anything under its target was downloadable."""
+ fake_home = tmp_path / "userprofile"
+ fake_home.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "secret.txt").write_text("TOPSECRET")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ legacy = fake_home / "studio_sandbox"
+ legacy.mkdir(parents = True)
+ (legacy / "__LOCALID_evil").symlink_to(outside)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ tools._migrate_legacy_sandbox(tools.sandbox_root())
+ resolved = tools.resolve_sandbox_workdir("__LOCALID_evil")
+ # The link is left at the legacy root rather than carried across, so the
+ # name inside the sandbox root is a plain path with nothing behind it.
+ assert not (Path(tools.sandbox_root()) / "__LOCALID_evil").is_symlink()
+ assert (legacy / "__LOCALID_evil").is_symlink(), "moved a link into the root"
+ assert not Path(resolved).is_symlink()
+ assert not str(Path(resolved).resolve()).startswith(str(outside.resolve()))
+ assert not (Path(resolved) / "secret.txt").exists()
+
+
+def test_the_executor_leaves_nothing_in_the_sandbox(tmp_path, monkeypatch):
+ """Its scratch script lives outside the sandbox, so a chat whose tools only
+ printed is still an empty folder and removable without the opt-in."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_scratch"))
+ tools._python_exec("print('hi')", session_id = "__LOCALID_scratch")
+ assert [p.name for p in workdir.iterdir()] == [tools._SANDBOX_MARKER]
+
+ assert tools.remove_session_sandbox("__LOCALID_scratch") is True
+ assert not workdir.exists()
+
+
+def test_a_real_file_still_blocks_removal(tmp_path, monkeypatch):
+ """Only scratch is ignored; the user's own files still need the opt-in."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_keepit"))
+ (workdir / "studio_exec_abc123.py").write_text("print(1)")
+ (workdir / "sales.csv").write_text("a,b\n")
+
+ assert tools.remove_session_sandbox("__LOCALID_keepit") is False
+ assert (workdir / "sales.csv").is_file()
+
+
+def test_the_listing_drops_a_directory_the_route_would_refuse(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+ from routes.inference import _sandbox_listing_names
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_baddir"))
+ try:
+ bad = workdir / "back\\slash"
+ bad.mkdir()
+ (bad / "report.csv").write_text("x")
+ except OSError:
+ pytest.skip("filesystem rejects the name")
+ (workdir / "ok.csv").write_text("x")
+
+ names = _sandbox_listing_names(str(workdir))
+ assert "ok.csv" in names
+ assert not any("\\" in name for name in names), names
+
+
+def test_a_user_file_named_like_scratch_is_kept(tmp_path, monkeypatch):
+ """No filename is reserved: everything in the sandbox is the user's."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_prefix1"))
+ (workdir / "studio_exec_results.csv").write_text("a,b\n")
+ (workdir / "studio_exec_ab12cd.py").write_text("print(1)")
+
+ snapshot = tools._snapshot_workdir_files(str(workdir))
+ assert "studio_exec_results.csv" in snapshot
+ assert "studio_exec_ab12cd.py" in snapshot
+ # Both block removal without the opt-in.
+ assert tools.remove_session_sandbox("__LOCALID_prefix1") is False
+ assert (workdir / "studio_exec_results.csv").is_file()
+ assert (workdir / "studio_exec_ab12cd.py").is_file()
+
+
+def test_an_existing_sandbox_override_keeps_its_permissions(tmp_path, monkeypatch):
+ """UNSLOTH_STUDIO_SANDBOX_HOME can name a shared directory; locking it down
+ to 0o700 would cut off everything else using it."""
+ shared = tmp_path / "shared"
+ shared.mkdir(mode = 0o755)
+ before = shared.stat().st_mode & 0o777
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(shared))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_shared1"))
+ assert (shared.stat().st_mode & 0o777) == before, "the shared root was re-permissioned"
+ # The session directory is ours, so it is still locked down.
+ assert (workdir.stat().st_mode & 0o777) == 0o700
+
+
+def test_a_sandbox_root_studio_creates_is_still_locked_down(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "fresh"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools.get_sandbox_workdir("__LOCALID_fresh11")
+ assert ((tmp_path / "fresh").stat().st_mode & 0o777) == 0o700
+
+
+def test_a_directory_of_plain_python_files_is_not_a_cache(tmp_path, monkeypatch):
+ """A package or scripts directory is only .py files too, so shape alone
+ cannot decide what gets deleted."""
+ scripts = tmp_path / "scripts"
+ scripts.mkdir()
+ (scripts / "helper.py").write_text("print(1)\n")
+ (scripts / "__pycache__").mkdir()
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(scripts))
+
+ from utils import cache_cleanup
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert (scripts / "helper.py").read_text() == "print(1)\n"
+
+
+def test_a_marked_directory_is_cleared(tmp_path, monkeypatch):
+ """Studio writes the marker when it creates the location."""
+ cache = tmp_path / "compiled_cache"
+ cache.mkdir()
+ (cache / "helper.py").write_text("print(1)\n")
+
+ from utils import cache_cleanup
+
+ (cache / cache_cleanup.CACHE_MARKER).touch()
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(cache))
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert not (cache / "helper.py").exists()
+ # Emptied, not unmade: the marker is what keeps it ours next time.
+ assert list(cache.iterdir()) == [cache / cache_cleanup.CACHE_MARKER]
+
+
+def test_generated_modules_identify_a_cache_without_a_marker(tmp_path, monkeypatch):
+ """An install that predates the marker is still cleaned, file by file."""
+ cache = tmp_path / "old_cache"
+ cache.mkdir()
+ (cache / "unsloth_compiled_module_gemma3.py").write_text("x = 1\n", encoding = "utf-8")
+ # Their own file, and Unsloth*Trainer.py is a name a user's subclass can
+ # carry: without the marker there is nothing to say we wrote it.
+ (cache / "UnslothCustomTrainer.py").write_text("class X: pass\n", encoding = "utf-8")
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(cache))
+
+ from utils import cache_cleanup
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert not (cache / "unsloth_compiled_module_gemma3.py").exists()
+ assert (cache / "UnslothCustomTrainer.py").is_file()
+
+
+def test_studio_writes_the_marker_when_it_creates_the_location(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+
+ from utils import cache_cleanup
+ from utils.paths import storage_roots
+
+ storage_roots.setup_cache_env()
+ pinned = Path(os.environ["UNSLOTH_COMPILE_LOCATION"])
+ assert (pinned / cache_cleanup.CACHE_MARKER).is_file()
+
+
+def test_a_cached_sandbox_path_is_re_checked(tmp_path, monkeypatch):
+ """A session directory swapped for a symlink after it was cached would
+ otherwise keep serving from wherever it now points."""
+ root = tmp_path / "sb"
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "secret.txt").write_text("TOPSECRET")
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_swapped"))
+ assert workdir.is_dir()
+
+ # Swap it, leaving the resolver's cache pointing at the same string.
+ shutil.rmtree(workdir)
+ workdir.symlink_to(outside)
+
+ resolved = Path(tools.resolve_sandbox_workdir("__LOCALID_swapped"))
+ assert resolved.name != "__LOCALID_swapped", resolved
+ assert not (resolved / "secret.txt").exists()
+
+ executing = Path(tools.get_sandbox_workdir("__LOCALID_swapped"))
+ assert executing.name != "__LOCALID_swapped", executing
+ assert not executing.is_symlink() and executing.is_dir()
+ assert not (executing / "secret.txt").exists()
+
+
+def test_a_shared_compile_location_loses_only_generated_files(tmp_path, monkeypatch):
+ """UNSLOTH_COMPILE_LOCATION=$HOME/.cache after one compile made the whole
+ directory look like ours; only the compiler's own output is."""
+ shared = tmp_path / "dot_cache"
+ (shared / "pip").mkdir(parents = True)
+ (shared / "pip" / "wheel.whl").write_text("wheel")
+ (shared / "notes.txt").write_text("keep me")
+ (shared / "unsloth_compiled_module_gemma3.py").write_text("x = 1\n")
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(shared))
+
+ from utils import cache_cleanup
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert shared.is_dir()
+ assert (shared / "pip" / "wheel.whl").read_text() == "wheel"
+ assert (shared / "notes.txt").read_text() == "keep me"
+ assert not (shared / "unsloth_compiled_module_gemma3.py").exists()
+
+
+def test_a_shared_compile_location_keeps_preserved_patterns(tmp_path, monkeypatch):
+ shared = tmp_path / "dot_cache2"
+ shared.mkdir()
+ (shared / "UnslothSFTTrainer.py").write_text("trainer")
+ (shared / "unsloth_compiled_module_llama.py").write_text("x = 1\n")
+ (shared / "__pycache__").mkdir()
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(shared))
+
+ from utils import cache_cleanup
+
+ cache_cleanup.clear_unsloth_compiled_cache(preserve_patterns = ["Unsloth*Trainer.py"])
+ assert (shared / "UnslothSFTTrainer.py").is_file()
+ assert not (shared / "unsloth_compiled_module_llama.py").exists()
+ # Not ours to remove in a directory we do not own.
+ assert (shared / "__pycache__").is_dir()
+
+
+def test_a_marked_shared_directory_is_still_cleared_whole(tmp_path, monkeypatch):
+ """The marker means Studio made the directory, so the old behaviour stands."""
+ cache = tmp_path / "marked"
+ cache.mkdir()
+
+ from utils import cache_cleanup
+
+ (cache / cache_cleanup.CACHE_MARKER).touch()
+ (cache / "leftover.txt").write_text("x")
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(cache))
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert not (cache / "leftover.txt").exists()
+ assert list(cache.iterdir()) == [cache / cache_cleanup.CACHE_MARKER]
+
+
+def test_many_empty_directories_do_not_stall_the_snapshot(tmp_path, monkeypatch):
+ """Directories never hit the file cap, so the walk needs its own budget."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_manydirs"))
+ monkeypatch.setattr(tools, "_MAX_SNAPSHOT_DIRS", 5)
+ for i in range(40):
+ (workdir / f"out{i}").mkdir()
+
+ visited = []
+ real_walk = os.walk
+
+ def counting_walk(top, *a, **kw):
+ for entry in real_walk(top, *a, **kw):
+ visited.append(entry[0])
+ yield entry
+
+ monkeypatch.setattr(tools.os, "walk", counting_walk)
+ tools._snapshot_workdir_files(str(workdir))
+ # The budget is checked on entry, so the one that trips it is visited too.
+ assert len(visited) <= 6, len(visited)
+
+
+def test_a_files_marker_with_absurd_nesting_does_not_abort_the_turn(tmp_path):
+ """json.loads raises RecursionError, which is not a ValueError."""
+ from core.inference import tool_loop_controller
+
+ payload = "[" * 200000 + "]" * 200000
+ text = "tool output\n__FILES__:" + payload
+ assert tool_loop_controller.strip_result_for_model(text) == text
+
+
+def test_the_listing_walk_is_bounded_like_the_snapshot(tmp_path, monkeypatch):
+ """Same directory budget: a listing request must not crawl a filesystem
+ either, and it runs on a server worker."""
+ from core.inference import tools
+ from routes import inference
+
+ sandbox = tmp_path / "sb"
+ sandbox.mkdir()
+ for i in range(40):
+ (sandbox / f"out{i}").mkdir()
+
+ visited = []
+ real_walk = os.walk
+
+ def counting_walk(top, *a, **kw):
+ for entry in real_walk(top, *a, **kw):
+ visited.append(entry[0])
+ yield entry
+
+ monkeypatch.setattr(inference, "_MAX_SNAPSHOT_DIRS", 5)
+ monkeypatch.setattr(inference.os, "walk", counting_walk)
+ inference._sandbox_listing_names(str(sandbox))
+ assert len(visited) <= 6, len(visited)
+ assert inference._MAX_SNAPSHOT_FILES == tools._MAX_SNAPSHOT_FILES
+
+
+def test_the_listing_shows_a_user_file_named_like_scratch(tmp_path):
+ """Nothing in the sandbox belongs to the executor, so nothing is hidden."""
+ from routes import inference
+
+ sandbox = tmp_path / "sb"
+ sandbox.mkdir()
+ (sandbox / "studio_exec_results.csv").write_text("a,b\n")
+ (sandbox / "studio_exec_ab12cd.py").write_text("print(1)")
+
+ names = inference._sandbox_listing_names(str(sandbox))
+ assert names == ["studio_exec_ab12cd.py", "studio_exec_results.csv"], names
+
+
+def test_clear_all_chats_can_take_the_files_too(tmp_path, monkeypatch):
+ """DELETE /threads has the opt-in; without it here a bulk clear could only
+ ever leave a nonempty sandbox behind, with no thread left to reach it."""
+ import inspect
+
+ from routes import chat_history
+
+ signature = inspect.signature(chat_history.clear_history)
+ assert "delete_files" in signature.parameters
+ assert signature.parameters["delete_files"].default is False
+
+ source = inspect.getsource(chat_history.clear_history)
+ assert "_remove_sandboxes(" in source
+ assert "delete_files" in source.split("_remove_sandboxes(", 1)[1]
+
+
+def test_a_failed_legacy_move_is_retried(tmp_path, monkeypatch):
+ """A file locked by another process on Windows is retryable; giving up after
+ one attempt strands it once the destination directory exists."""
+ fake_home = tmp_path / "userprofile"
+ legacy = fake_home / "studio_sandbox" / "__LOCALID_locked1"
+ legacy.mkdir(parents = True)
+ (legacy / "results.csv").write_text("a,b\n")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio_home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+
+ attempts = []
+ real_move = tools.shutil.move
+
+ def failing_move(source, target):
+ attempts.append(source)
+ if len(attempts) == 1:
+ raise OSError(13, "in use by another process")
+ return real_move(source, target)
+
+ monkeypatch.setattr(tools.shutil, "move", failing_move)
+ root = tools.sandbox_root()
+ tools._migrate_legacy_sandbox(root)
+ assert tools._legacy_sandbox_migrated is False, "gave up on a retryable failure"
+
+ tools._migrate_legacy_sandbox(root)
+ assert tools._legacy_sandbox_migrated is True
+ assert (Path(root) / "__LOCALID_locked1" / "results.csv").read_text() == "a,b\n"
+
+
+def test_a_collision_is_not_a_retryable_failure(tmp_path, monkeypatch):
+ """The new root already has that session, so the legacy copy stays for the
+ user to find and the migration is still done."""
+ fake_home = tmp_path / "userprofile"
+ legacy = fake_home / "studio_sandbox" / "__LOCALID_dupe123"
+ legacy.mkdir(parents = True)
+ (legacy / "old.csv").write_text("old\n")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio_home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ root = Path(tools.sandbox_root())
+ existing = root / "__LOCALID_dupe123"
+ existing.mkdir(parents = True)
+ # Claimed, which is what a session directory the new root made looks like.
+ (existing / tools._SANDBOX_MARKER).write_text("__LOCALID_dupe123", encoding = "utf-8")
+
+ tools._migrate_legacy_sandbox(str(root))
+ assert tools._legacy_sandbox_migrated is True
+ assert (legacy / "old.csv").is_file(), "the legacy copy was not left behind"
+
+
+def test_deleting_a_symlinked_session_spares_the_chat_it_points_at(tmp_path, monkeypatch):
+ """realpath containment passes for a sibling, so a link left in the sandbox
+ could take another chat's files."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ victim = Path(tools.get_sandbox_workdir("__LOCALID_victim1"))
+ (victim / "report.csv").write_text("a,b\n")
+ link = victim.parent / "__LOCALID_link111"
+ link.symlink_to(victim)
+
+ assert tools.remove_session_sandbox("__LOCALID_link111", delete_files = True) is True
+ assert not link.exists(), "the stale link stayed behind"
+ assert (victim / "report.csv").read_text() == "a,b\n", "the other chat lost its files"
+ assert victim.is_dir()
+
+
+def test_the_marker_survives_a_cache_clear(tmp_path, monkeypatch):
+ """Startup clears the cache it just created, and nothing else rewrites the
+ marker, so without this our own cache is demoted to 'shared'."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+
+ from utils import cache_cleanup
+ from utils.paths import storage_roots
+
+ storage_roots.setup_cache_env()
+ pinned = Path(os.environ["UNSLOTH_COMPILE_LOCATION"])
+ (pinned / "unsloth_compiled_module_gemma3.py").write_text("x = 1\n", encoding = "utf-8")
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert (pinned / cache_cleanup.CACHE_MARKER).is_file()
+ assert not (pinned / "unsloth_compiled_module_gemma3.py").exists()
+
+ # Still ours on the next pass, so a __pycache__ left by the compiler goes too.
+ (pinned / "__pycache__").mkdir()
+ (pinned / "UnslothSFTTrainer.py").write_text("trainer\n", encoding = "utf-8")
+ cache_cleanup.clear_unsloth_compiled_cache(preserve_patterns = ["Unsloth*Trainer.py"])
+ assert not (pinned / "__pycache__").exists()
+ assert (pinned / "UnslothSFTTrainer.py").is_file()
+ assert (pinned / cache_cleanup.CACHE_MARKER).is_file()
+
+
+def test_an_unrelated_cache_named_folder_in_the_cwd_is_not_ours(tmp_path, monkeypatch):
+ """Studio is launched from wherever the shell happens to be, so the name
+ alone cannot license an rmtree."""
+ launch_dir = tmp_path / "someproject"
+ cache = launch_dir / "unsloth_compiled_cache"
+ cache.mkdir(parents = True)
+ (cache / "notes.txt").write_text("keep me")
+ monkeypatch.chdir(launch_dir)
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+
+ from utils import cache_cleanup
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert (cache / "notes.txt").read_text() == "keep me"
+
+
+def test_a_marked_cwd_cache_is_still_cleared(tmp_path, monkeypatch):
+ launch_dir = tmp_path / "studioproject"
+ cache = launch_dir / "unsloth_compiled_cache"
+ cache.mkdir(parents = True)
+ monkeypatch.chdir(launch_dir)
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+
+ from utils import cache_cleanup
+
+ (cache / cache_cleanup.CACHE_MARKER).touch()
+ (cache / "unsloth_compiled_module_gemma3.py").write_text("x = 1\n")
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert not (cache / "unsloth_compiled_module_gemma3.py").exists()
+
+
+def test_a_user_python_file_is_never_executor_scratch(tmp_path, monkeypatch):
+ """The executor's own file no longer lives in the sandbox, so no filename
+ is reserved and studio_exec_results.py is just a file."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+ from routes import inference
+
+ tools._workdirs.clear()
+ session = "__LOCALID_userpy1"
+ result = tools._python_exec(
+ "open('studio_exec_results.py','w').write('x = 1\\n')", session_id = session
+ )
+ assert "studio_exec_results.py" in result, result
+
+ workdir = Path(tools.get_sandbox_workdir(session))
+ # The executor left nothing of its own behind.
+ assert sorted(
+ p.name for p in workdir.iterdir() if p.name not in tools._INTERNAL_SANDBOX_FILES
+ ) == ["studio_exec_results.py"]
+ assert inference._sandbox_listing_names(str(workdir)) == ["studio_exec_results.py"]
+ # And a delete without the opt-in will not quietly take it.
+ assert tools.remove_session_sandbox(session) is False
+ assert (workdir / "studio_exec_results.py").is_file()
+
+
+def test_a_sandbox_root_at_a_filesystem_root_still_isolates_chats(tmp_path, monkeypatch):
+ """A root already ending in a separator made every session path fail
+ containment, so every chat collapsed into _invalid together."""
+ from core.inference import tools
+
+ assert tools._contained_in_root("/srv/chat", "/") is True
+ assert tools._contained_in_root("/", "/") is False
+ assert tools._contained_in_root("/etc/passwd", str(tmp_path)) is False
+
+ root = tmp_path / "sb"
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+ tools._workdirs.clear()
+ first = Path(tools.get_sandbox_workdir("__LOCALID_alpha1"))
+ second = Path(tools.get_sandbox_workdir("__LOCALID_beta22"))
+ assert first != second
+ assert first.name != "_invalid" and second.name != "_invalid"
+
+
+def test_containment_is_not_fooled_by_a_shared_name_prefix(tmp_path):
+ """The old prefix test would also have accepted a sibling like sb-evil."""
+ from core.inference import tools
+
+ (tmp_path / "sb").mkdir()
+ (tmp_path / "sb-evil").mkdir()
+ assert tools._contained_in_root(str(tmp_path / "sb-evil"), str(tmp_path / "sb")) is False
+ assert tools._contained_in_root(str(tmp_path / "sb" / "chat"), str(tmp_path / "sb")) is True
+
+
+def test_studios_own_sandbox_bookkeeping_is_not_a_user_file(tmp_path, monkeypatch):
+ """The remap sidecar the sandbox sitecustomize writes is ours, and reporting
+ it also made a streamed result differ from a non-streamed one."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+ from routes import inference
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_remap01"))
+ (workdir / ".unsloth_sandbox_remap.json").write_text("{}")
+ (workdir / ".gitignore").write_text("*.pyc\n")
+
+ snapshot = tools._snapshot_workdir_files(str(workdir))
+ assert ".unsloth_sandbox_remap.json" not in snapshot
+ # Other dotfiles are still the user's.
+ assert ".gitignore" in snapshot
+ assert inference._sandbox_listing_names(str(workdir)) == [".gitignore"]
+
+
+def test_a_module_written_by_an_earlier_call_is_importable(tmp_path, monkeypatch):
+ """The scratch script is what Python puts on sys.path[0], so moving it out
+ of the sandbox broke `import helper` and sent __file__ outside."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ session = "__LOCALID_import1"
+ tools._python_exec('open("helper.py", "w").write("VALUE = 42")', session_id = session)
+ result = tools._python_exec("import helper; print(helper.VALUE)", session_id = session)
+ assert "42" in result, result
+
+ where = tools._python_exec("print(__file__)", session_id = session)
+ workdir = tools.get_sandbox_workdir(session)
+ assert workdir in where, where
+
+
+def test_the_scratch_script_is_never_reported_as_a_file(tmp_path, monkeypatch):
+ """Excluded by its exact name for this one call, so a tool writing
+ studio_exec_results.py still keeps it."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ session = "__LOCALID_scratch2"
+ result = tools._python_exec(
+ 'open("studio_exec_results.py", "w").write("x = 1")', session_id = session
+ )
+ files = result.split("__FILES__:")[1]
+ assert "studio_exec_results.py" in files
+ workdir = Path(tools.get_sandbox_workdir(session))
+ # Only the user's file is left; the executor cleaned up after itself.
+ assert sorted(
+ p.name for p in workdir.iterdir() if p.name not in tools._INTERNAL_SANDBOX_FILES
+ ) == ["studio_exec_results.py"]
+ assert json.loads(files) == [{"name": "studio_exec_results.py", "size": 5}]
+
+
+def test_a_turn_without_a_chat_id_reports_no_files(tmp_path, monkeypatch):
+ """Every such turn shares the _default workdir, so a card pinned to it
+ would later download whatever the next new chat wrote there."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ result = tools._python_exec('open("first.csv", "w").write("a")')
+ assert "__FILES__" not in result, result
+ assert "__IMAGES__" not in result
+ bash_result = tools._bash_exec("printf a > second.csv")
+ assert "__FILES__" not in bash_result, bash_result
+
+
+def test_an_unowned_cwd_cache_is_not_put_on_the_import_path(tmp_path, monkeypatch):
+ """Registering it would shadow real dependencies for every spawned worker."""
+ launch_dir = tmp_path / "someproject"
+ cache = launch_dir / "unsloth_compiled_cache"
+ cache.mkdir(parents = True)
+ (cache / "numpy.py").write_text("raise SystemExit('shadowed')\n")
+ monkeypatch.chdir(launch_dir)
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+ monkeypatch.setenv("PYTHONPATH", "")
+
+ from utils import cache_cleanup
+
+ before = list(sys.path)
+ try:
+ cache_cleanup.register_compiled_cache_on_path()
+ assert str(cache.resolve()) not in sys.path
+ assert str(cache.resolve()) not in os.environ.get("PYTHONPATH", "")
+ finally:
+ sys.path[:] = before
+
+
+def test_a_marked_cwd_cache_is_still_registered(tmp_path, monkeypatch):
+ launch_dir = tmp_path / "studioproject"
+ cache = launch_dir / "unsloth_compiled_cache"
+ cache.mkdir(parents = True)
+ monkeypatch.chdir(launch_dir)
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+
+ from utils import cache_cleanup
+
+ (cache / cache_cleanup.CACHE_MARKER).touch()
+ before = list(sys.path)
+ try:
+ cache_cleanup.register_compiled_cache_on_path()
+ assert str(cache.resolve()) in sys.path
+ finally:
+ sys.path[:] = before
+
+
+def test_a_chat_deleted_mid_call_keeps_its_sandbox(tmp_path, monkeypatch):
+ """The running tool has this directory as its cwd, and a process whose cwd
+ was unlinked fails every relative write with ENOENT."""
+ import threading
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ session = "__LOCALID_busy111"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ started, may_finish = threading.Event(), threading.Event()
+ removed = {}
+
+ def run_tool():
+ with tools._session_in_flight(session):
+ started.set()
+ may_finish.wait(timeout = 10)
+
+ worker = threading.Thread(target = run_tool)
+ worker.start()
+ try:
+ assert started.wait(timeout = 10)
+ removed["during"] = tools.remove_session_sandbox(session)
+ assert removed["during"] is False, "the sandbox went out from under a running tool"
+ assert workdir.is_dir()
+ finally:
+ may_finish.set()
+ worker.join(timeout = 10)
+
+ # The refused request was queued, so leaving the call performs it.
+ assert not workdir.exists()
+
+
+def test_the_executor_marks_its_session_busy():
+ """The guard has to sit on the dispatch both executors go through."""
+ import inspect
+
+ from core.inference import tools
+
+ source = inspect.getsource(tools.execute_tool)
+ for call in ("_python_exec(", "_bash_exec("):
+ before = source.split(call)[0]
+ assert "_session_in_flight" in before.rsplit("if name ==", 1)[-1], call
+
+
+def test_a_pre_existing_compile_directory_is_never_marked_as_ours(tmp_path, monkeypatch):
+ """mkdir(exist_ok=True) does not mean we created it, and the marker is
+ permission to rmtree."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+
+ from utils import cache_cleanup
+ from utils.paths import storage_roots
+
+ # Where Studio would pin it, already there and holding someone else's files.
+ pinned = Path(storage_roots.cache_root()).parent / "compiled_cache"
+ pinned.mkdir(parents = True)
+ (pinned / "someones_notes.txt").write_text("keep me")
+
+ storage_roots.setup_cache_env()
+ assert Path(os.environ["UNSLOTH_COMPILE_LOCATION"]) == pinned
+ assert not (pinned / cache_cleanup.CACHE_MARKER).exists(), "claimed a directory it found"
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert (pinned / "someones_notes.txt").read_text() == "keep me"
+
+
+def test_a_directory_studio_creates_is_marked(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "fresh"))
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+
+ from utils import cache_cleanup
+ from utils.paths import storage_roots
+
+ storage_roots.setup_cache_env()
+ pinned = Path(os.environ["UNSLOTH_COMPILE_LOCATION"])
+ assert (pinned / cache_cleanup.CACHE_MARKER).is_file()
+
+
+def test_removal_and_the_busy_check_are_one_decision(tmp_path, monkeypatch):
+ """Checking first and deleting after leaves a window for a tool to start in
+ between, and it would then be running in a directory this call removes."""
+ import threading
+ import time
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ session = "__LOCALID_race111"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ started = threading.Event()
+ entered = threading.Event()
+
+ real_rmtree = tools.shutil.rmtree
+
+ def slow_rmtree(path, **kwargs):
+ # Stand in for the window between deciding and unlinking.
+ entered.set()
+ time.sleep(0.3)
+ return real_rmtree(path, **kwargs)
+
+ monkeypatch.setattr(tools.shutil, "rmtree", slow_rmtree)
+ result = {}
+
+ def remover():
+ result["removed"] = tools.remove_session_sandbox(session)
+
+ def tool():
+ entered.wait(timeout = 5)
+ with tools._session_in_flight(session):
+ started.set()
+ time.sleep(0.05)
+
+ threads = [threading.Thread(target = remover), threading.Thread(target = tool)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout = 10)
+
+ # The tool could only take the lock after the removal finished, so it never
+ # ran inside a directory that was being deleted.
+ assert started.is_set()
+ assert result["removed"] is True
+ assert tools._active_sessions == {}
+
+
+def test_the_delete_dialog_offers_the_same_choice_for_a_chat():
+ """Without it every deleted chat that wrote a file leaves its sandbox
+ behind with nothing left to reach it."""
+ root = Path(__file__).resolve().parents[2] / "frontend" / "src"
+ sidebar = (root / "components" / "app-sidebar.tsx").read_text(encoding = "utf-8")
+ assert "shouldDeleteChatFiles" in sidebar
+ assert "deleteChatWithCleanup(target.item, {" in sidebar
+
+ api = (root / "features" / "chat" / "api" / "chat-api.ts").read_text(encoding = "utf-8")
+ assert "delete_files: !!args.deleteFiles" in api
+
+
+def test_a_delete_during_a_call_happens_once_the_call_ends(tmp_path, monkeypatch):
+ """The thread is gone from history by then, so a dropped request would
+ strand the folder for good."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._pending_removals.clear()
+ session = "__LOCALID_defer11"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "report.csv").write_text("a,b\n")
+
+ with tools._session_in_flight(session):
+ assert tools.remove_session_sandbox(session, delete_files = True) is False
+ assert workdir.is_dir(), "removed under a running tool"
+ # Queued, so leaving the call performs it.
+ assert not workdir.exists()
+ assert tools._pending_removals == {}
+
+
+def test_a_queued_delete_keeps_the_strongest_request(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._pending_removals.clear()
+ session = "__LOCALID_defer22"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "report.csv").write_text("a,b\n")
+
+ with tools._session_in_flight(session):
+ tools.remove_session_sandbox(session, delete_files = False)
+ tools.remove_session_sandbox(session, delete_files = True)
+ assert not workdir.exists()
+
+
+def test_a_symlinked_cache_location_is_still_cleared(tmp_path, monkeypatch):
+ """rmtree refuses a symlink, and ignore_errors made that silent."""
+ real = tmp_path / "real_cache"
+ real.mkdir()
+ link = tmp_path / "link_cache"
+ link.symlink_to(real, target_is_directory = True)
+
+ from utils import cache_cleanup
+
+ (real / cache_cleanup.CACHE_MARKER).touch()
+ (real / "unsloth_compiled_module_gemma3.py").write_text("x = 1\n")
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(link))
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert not (real / "unsloth_compiled_module_gemma3.py").exists()
+ assert (real / cache_cleanup.CACHE_MARKER).is_file(), "still ours next time"
+
+
+def test_the_delete_switch_only_appears_where_it_works():
+ """A training run has no sandbox of its own; a chat always does."""
+ sidebar = (
+ Path(__file__).resolve().parents[2] / "frontend" / "src" / "components" / "app-sidebar.tsx"
+ ).read_text(encoding = "utf-8")
+ assert "function deleteTargetHasFiles" in sidebar
+ assert '"training"' not in sidebar.split("function deleteTargetHasFiles")[1][:400]
+ assert "{deleteTargetHasFiles(confirmingDelete) ? (" in sidebar
+ # And every opener clears the switch, so it can never arrive preselected.
+ assert "function openDeleteDialog" in sidebar
+ assert "setConfirmingDelete({ kind:" not in sidebar
+
+
+def test_a_symlinked_builtin_cache_is_not_deleted_through(tmp_path, monkeypatch):
+ """Being at a built-in path proves ownership of the directory, not of
+ whatever a link there points at."""
+ victim = tmp_path / "someones_files"
+ victim.mkdir()
+ (victim / "thesis.txt").write_text("years of work")
+
+ from utils import cache_cleanup
+
+ link = tmp_path / "unsloth_compiled_cache"
+ link.symlink_to(victim, target_is_directory = True)
+ monkeypatch.setattr(cache_cleanup, "_CACHE_DIRS", [link])
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+ monkeypatch.chdir(tmp_path / "..")
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert (victim / "thesis.txt").read_text() == "years of work"
+
+
+def test_a_symlinked_builtin_cache_with_the_marker_is_cleared(tmp_path, monkeypatch):
+ real = tmp_path / "real_cache"
+ real.mkdir()
+
+ from utils import cache_cleanup
+
+ (real / cache_cleanup.CACHE_MARKER).touch()
+ (real / "unsloth_compiled_module_gemma3.py").write_text("x = 1\n")
+ link = tmp_path / "unsloth_compiled_cache"
+ link.symlink_to(real, target_is_directory = True)
+ monkeypatch.setattr(cache_cleanup, "_CACHE_DIRS", [link])
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert not (real / "unsloth_compiled_module_gemma3.py").exists()
+
+
+def test_the_invalid_fallback_cannot_be_pointed_out_of_the_sandbox(tmp_path, monkeypatch):
+ """Tool code runs inside the sandbox, so it can plant this link; every
+ unchecked request would then read from wherever it points."""
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "id_rsa").write_text("PRIVATE KEY")
+ root = tmp_path / "sb"
+ root.mkdir()
+ (root / "_invalid").symlink_to(outside, target_is_directory = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ resolved = Path(tools.resolve_sandbox_workdir("../escape"))
+ assert not (resolved / "id_rsa").exists(), resolved
+ assert outside.is_dir() and (outside / "id_rsa").is_file(), "the target was touched"
+
+ executing = Path(tools.get_sandbox_workdir("../escape"))
+ assert not (executing / "id_rsa").exists(), executing
+
+
+def test_the_default_fallback_is_contained_too(tmp_path, monkeypatch):
+ outside = tmp_path / "elsewhere"
+ outside.mkdir()
+ (outside / "secret.txt").write_text("TOPSECRET")
+ root = tmp_path / "sb"
+ root.mkdir()
+ (root / "_default").symlink_to(outside, target_is_directory = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ resolved = Path(tools.resolve_sandbox_workdir(None))
+ assert not (resolved / "secret.txt").exists(), resolved
+
+
+def test_deleting_a_big_sandbox_does_not_hold_the_tool_lock(tmp_path, monkeypatch):
+ """rmtree of a large tree would otherwise block every tool start, and the
+ event loop of the route that called it."""
+ import threading
+ import time
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ session = "__LOCALID_bigdel1"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "data.bin").write_bytes(b"x" * 1024)
+
+ slow = threading.Event()
+ real_rmtree = tools.shutil.rmtree
+
+ def slow_rmtree(path, **kw):
+ slow.set()
+ time.sleep(0.5)
+ return real_rmtree(path, **kw)
+
+ monkeypatch.setattr(tools.shutil, "rmtree", slow_rmtree)
+ assert tools.remove_session_sandbox(session, delete_files = True) is True
+ assert not workdir.exists(), "the session directory is gone immediately"
+
+ # The lock is free while the tree is still being removed.
+ assert slow.wait(timeout = 5)
+ started = time.monotonic()
+ with tools._session_in_flight("__LOCALID_other12"):
+ pass
+ assert time.monotonic() - started < 0.3, "a tool start waited for the delete"
+
+
+def test_a_chat_whose_id_looks_like_a_project_is_still_cleaned(tmp_path, monkeypatch):
+ """An imported chat can carry that prefix without a project behind it, and
+ _get_workdir gives it an ordinary directory."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ monkeypatch.setattr(tools, "_get_project_workdir", lambda session_id: None)
+ session = f"{tools._PROJECT_SESSION_PREFIX}notreal123"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ assert workdir.is_dir()
+
+ assert tools.remove_session_sandbox(session) is True
+ assert not workdir.exists()
+
+
+def test_a_real_project_workspace_is_still_left_alone(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ shared = tmp_path / "project_workspace"
+ shared.mkdir()
+ monkeypatch.setattr(tools, "_get_project_workdir", lambda session_id: str(shared))
+ session = f"{tools._PROJECT_SESSION_PREFIX}real123"
+ assert tools.remove_session_sandbox(session, delete_files = True) is False
+ assert shared.is_dir(), "a shared project workspace was removed"
+
+
+def test_a_foreign_tool_result_keeps_its_own_fields():
+ """Studio's wrapper always carries images; anything else with text and
+ sessionId is someone else's result and must not be reduced to its text."""
+ adapter = (
+ Path(__file__).resolve().parents[2]
+ / "frontend"
+ / "src"
+ / "features"
+ / "chat"
+ / "api"
+ / "chat-adapter.ts"
+ ).read_text(encoding = "utf-8")
+ predicate = adapter.split("export function isSandboxToolResult(", 1)[1].split("\n}", 1)[0]
+ assert "Array.isArray(v.images)" in predicate, predicate
+
+
+def test_a_shared_roots_own_folder_is_never_deleted(tmp_path, monkeypatch):
+ """An id can name something already in a shared root, and that folder was
+ not created by us."""
+ root = tmp_path / "shared"
+ root.mkdir()
+ theirs = root / "invoices"
+ theirs.mkdir()
+ (theirs / "2026.pdf").write_text("money", encoding = "utf-8")
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ assert tools.remove_session_sandbox("invoices", delete_files = True) is False
+ assert (theirs / "2026.pdf").is_file()
+
+ # Empty ones are not ours to reclaim either.
+ (root / "empty").mkdir()
+ assert tools.remove_session_sandbox("empty") is False
+ assert (root / "empty").is_dir()
+
+
+def test_a_sandbox_we_created_in_a_shared_root_is_still_removable(tmp_path, monkeypatch):
+ root = tmp_path / "shared"
+ root.mkdir()
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_mine11"))
+ assert (workdir / tools._SANDBOX_MARKER).is_file()
+ # Nothing but our marker in it, so it counts as empty.
+ assert tools.remove_session_sandbox("__LOCALID_mine11") is True
+ assert not workdir.exists()
+
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_mine22"))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ assert tools.remove_session_sandbox("__LOCALID_mine22", delete_files = True) is True
+
+
+def test_two_ids_differing_only_in_case_share_the_busy_check(tmp_path, monkeypatch):
+ """They are one directory on Windows and on a default macOS volume, so a
+ delete of one must not land while the other is running a tool in it."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._pending_removals.clear()
+ workdir = Path(tools.get_sandbox_workdir("ChatCase"))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ with tools._session_in_flight("chatcase"):
+ assert tools.remove_session_sandbox("ChatCase", delete_files = True) is False
+ assert workdir.is_dir(), "removed under a running tool"
+ # And the queued delete names the id that was asked for, not the folded key.
+ assert not workdir.exists()
+ assert tools._pending_removals == {}
+
+
+def test_an_existing_folder_in_a_shared_root_is_never_claimed(tmp_path, monkeypatch):
+ """A chat id can name something already in there, and running a tool in it
+ must not make it ours to delete."""
+ root = tmp_path / "shared"
+ root.mkdir()
+ theirs = root / "taxes"
+ theirs.mkdir()
+ (theirs / "2026.pdf").write_text("money", encoding = "utf-8")
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("taxes"))
+ assert workdir != theirs, "ran the tool inside a folder we did not create"
+ assert workdir.name.startswith("taxes-")
+ assert not (theirs / tools._SANDBOX_MARKER).exists(), "claimed a folder we did not create"
+ # Deleting the chat takes our directory and leaves theirs alone.
+ assert tools.remove_session_sandbox("taxes", delete_files = True) is True
+ assert (theirs / "2026.pdf").is_file()
+
+
+def test_both_case_variants_are_removed_when_their_calls_end(tmp_path, monkeypatch):
+ """They fold onto one key, and on a case-sensitive filesystem they are two
+ directories, so neither may be dropped."""
+ import time
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._pending_removals.clear()
+ lower = Path(tools.get_sandbox_workdir("casepair"))
+ upper = Path(tools.get_sandbox_workdir("CasePair"))
+ if lower == upper:
+ pytest.skip("case-insensitive filesystem: one directory, nothing to strand")
+ (lower / "a.csv").write_text("a\n", encoding = "utf-8")
+ (upper / "b.csv").write_text("b\n", encoding = "utf-8")
+
+ with tools._session_in_flight("casepair"), tools._session_in_flight("CasePair"):
+ assert tools.remove_session_sandbox("casepair", delete_files = True) is False
+ assert tools.remove_session_sandbox("CasePair", delete_files = True) is False
+ for _ in range(50):
+ if not lower.exists() and not upper.exists():
+ break
+ time.sleep(0.05)
+ assert not lower.exists() and not upper.exists()
+ assert tools._pending_removals == {}
+
+
+def test_a_foreign_fallback_link_is_left_where_it_stands(tmp_path, monkeypatch):
+ """At a root the user pointed us at, _default is their entry: it must not be
+ followed, and it is not ours to unlink either."""
+ root = tmp_path / "shared"
+ root.mkdir()
+ outside = tmp_path / "elsewhere"
+ outside.mkdir()
+ (outside / "secret.txt").write_text("TOPSECRET", encoding = "utf-8")
+ (root / "_default").symlink_to(outside, target_is_directory = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ resolved = Path(tools.resolve_sandbox_workdir(None))
+ assert not (resolved / "secret.txt").exists(), resolved
+ assert (root / "_default").is_symlink(), "an entry we do not own was unlinked"
+
+ workdir = Path(tools.get_sandbox_workdir(None))
+ assert not (workdir / "secret.txt").exists(), workdir
+ assert (root / "_default").is_symlink()
+
+
+def test_our_own_fallback_link_is_still_dropped(tmp_path, monkeypatch):
+ """At our own root nothing else put it there, so the link goes and the
+ fallback keeps its name."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ root = Path(tools.sandbox_root())
+ root.mkdir(parents = True, exist_ok = True)
+ outside = tmp_path / "elsewhere"
+ outside.mkdir()
+ (root / "_default").symlink_to(outside, target_is_directory = True)
+
+ workdir = Path(tools.get_sandbox_workdir(None))
+ assert workdir == root / "_default"
+ assert workdir.is_dir() and not workdir.is_symlink()
+
+
+def test_a_pre_existing_folder_keeps_its_permissions(tmp_path, monkeypatch):
+ """Running a tool in a shared root must not re-permission someone's folder."""
+ if os.name == "nt":
+ pytest.skip("POSIX permission bits")
+ root = tmp_path / "shared"
+ root.mkdir()
+ theirs = root / "team"
+ theirs.mkdir()
+ os.chmod(theirs, 0o755)
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ assert Path(tools.get_sandbox_workdir("team")) != theirs
+ assert oct(theirs.stat().st_mode)[-3:] == "755", "an unowned folder was locked down"
+
+ # Ours is still tightened.
+ mine = Path(tools.get_sandbox_workdir("__LOCALID_mine33"))
+ assert oct(mine.stat().st_mode)[-3:] == "700"
+
+
+def test_a_link_in_a_shared_root_is_left_alone_by_a_delete(tmp_path, monkeypatch):
+ """A chat id can name an entry the user put there, and a delete is not a
+ licence to remove it."""
+ root = tmp_path / "shared"
+ root.mkdir()
+ elsewhere = tmp_path / "elsewhere"
+ elsewhere.mkdir()
+ (root / "notes").symlink_to(elsewhere, target_is_directory = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ assert tools.remove_session_sandbox("notes", delete_files = True) is False
+ assert (root / "notes").is_symlink(), "an entry we did not create was unlinked"
+ assert elsewhere.is_dir()
+
+
+def test_a_case_variant_chat_gets_its_own_directory(tmp_path, monkeypatch):
+ """One name on Windows and on a default macOS volume: sharing it means
+ either chat's delete takes the other's files."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ first = Path(tools.get_sandbox_workdir("CaseOwn"))
+ (first / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ assert (first / tools._SANDBOX_MARKER).read_text(encoding = "utf-8") == "CaseOwn"
+
+ # What the other id sees on a case-insensitive volume: this directory, made
+ # by someone else. On a case-sensitive one it is a separate name already.
+ root = first.parent
+ collision = root / "caseown"
+ if not collision.exists():
+ collision.mkdir()
+ (collision / tools._SANDBOX_MARKER).write_text("CaseOwn", encoding = "utf-8")
+ (collision / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ second = Path(tools._session_dir(str(root), "caseown"))
+ assert second.name == "caseown-" + hashlib.sha256(b"caseown").hexdigest()[:8]
+
+ # And that id cannot delete the other chat's files.
+ assert tools.remove_session_sandbox("caseown", delete_files = True) is False
+ assert (collision / "report.csv").is_file()
+ assert tools.remove_session_sandbox("CaseOwn", delete_files = True) is True
+
+
+def test_the_delete_switch_does_not_promise_project_files():
+ """A chat moved back to Recents wrote its earlier files into the project
+ workspace, which chat deletion does not touch."""
+ sidebar = (
+ Path(__file__).resolve().parents[2] / "frontend" / "src" / "components" / "app-sidebar.tsx"
+ ).read_text(encoding = "utf-8")
+ assert "This chat's own sandbox folder is removed from disk." in sidebar
+ assert "Anything this chat's tools wrote is removed from disk." not in sidebar
+
+
+def test_a_tool_cannot_forge_its_way_into_owning_a_folder(tmp_path, monkeypatch):
+ """The marker is writable by whatever runs in the sandbox, so the answer is
+ to never run in a folder that was already there."""
+ root = tmp_path / "shared"
+ import time
+
+ root.mkdir()
+ theirs = root / "photos"
+ theirs.mkdir()
+ (theirs / "wedding.jpg").write_text("jpeg", encoding = "utf-8")
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("photos"))
+ assert workdir != theirs, "ran the tool inside a folder we did not create"
+ assert not (theirs / tools._SANDBOX_MARKER).exists()
+ # What the tool writes lands in ours, and deleting the chat takes ours.
+ (workdir / "plot.png").write_text("png", encoding = "utf-8")
+ assert tools.remove_session_sandbox("photos", delete_files = True) is True
+ for _ in range(50):
+ if not workdir.exists():
+ break
+ time.sleep(0.05)
+ assert not workdir.exists()
+ assert (theirs / "wedding.jpg").is_file()
+
+
+def test_two_ids_racing_for_one_name_do_not_share_it(tmp_path, monkeypatch):
+ """Both can see an unowned name before either writes its marker."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ root = tools.sandbox_root()
+ os.makedirs(root, exist_ok = True)
+ first = Path(tools._ensure_session_dir(root, "RaceId"))
+ # The other id, resolving the same plain name (what a case-insensitive
+ # volume produces): the claim is already taken, so it steps aside.
+ plain = Path(root) / "raceid"
+ if not plain.exists():
+ plain.mkdir()
+ (plain / tools._SANDBOX_MARKER).write_text("RaceId", encoding = "utf-8")
+ second = Path(tools._ensure_session_dir(root, "raceid"))
+ assert second != first and second != plain
+ assert (second / tools._SANDBOX_MARKER).read_text(encoding = "utf-8") == "raceid"
+
+
+def test_a_migrated_sandbox_stays_deletable_in_an_overridden_root(tmp_path, monkeypatch):
+ """It came from our own folder, so the move has to say so or the chat can
+ never remove it again."""
+ home = tmp_path / "userhome"
+ home.mkdir()
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ legacy = home / "studio_sandbox" / "__LOCALID_moved11"
+ legacy.mkdir(parents = True)
+ (legacy / "notes.txt").write_text("mine", encoding = "utf-8")
+ root = tmp_path / "shared"
+ root.mkdir()
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ tools._migrate_legacy_sandbox(str(root))
+
+ moved = root / "__LOCALID_moved11"
+ assert (moved / "notes.txt").is_file()
+ assert (moved / tools._SANDBOX_MARKER).is_file(), "the migrated sandbox lost its claim"
+ assert tools.remove_session_sandbox("__LOCALID_moved11", delete_files = True) is True
+
+
+def test_a_name_the_download_url_cannot_carry_is_not_advertised():
+ """A non-UTF-8 byte in a POSIX filename arrives as a lone surrogate, and
+ encodeURIComponent throws on it, so the chip could never download."""
+ from core.inference import tools
+
+ assert tools._servable_segment("report.csv")
+ assert not tools._servable_segment("bad\udcffname.csv")
+ assert not tools._servable_segment("\ud800.txt")
+
+
+def test_a_tool_writing_over_the_marker_does_not_lose_its_files(tmp_path, monkeypatch):
+ """The file sits in a directory the tool can write, so a restart must not
+ send that chat somewhere else and strand what it made."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_clob11"))
+ (workdir / "results.csv").write_text("a,b\n", encoding = "utf-8")
+ (workdir / tools._SANDBOX_MARKER).write_text("Traceback: not an id\n", encoding = "utf-8")
+
+ # What the next launch sees.
+ tools._workdirs.clear()
+ again = Path(tools.get_sandbox_workdir("__LOCALID_clob11"))
+ assert again == workdir, "the chat was sent to a new directory"
+ assert (again / "results.csv").is_file()
+ # And the claim is back, so deletion still works.
+ assert (again / tools._SANDBOX_MARKER).read_text(encoding = "utf-8") == "__LOCALID_clob11"
+ assert Path(tools.resolve_sandbox_workdir("__LOCALID_clob11")) == workdir
+
+
+def test_a_legacy_name_taken_in_a_shared_root_moves_beside_it(tmp_path, monkeypatch):
+ """The name is somebody's own folder, so the session moves to the name it
+ will resolve to instead of merging into theirs."""
+ fake_home = tmp_path / "userprofile"
+ legacy = fake_home / "studio_sandbox" / "notes"
+ legacy.mkdir(parents = True)
+ (legacy / "mine.csv").write_text("mine", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ root = tmp_path / "shared"
+ root.mkdir()
+ theirs = root / "notes"
+ theirs.mkdir()
+ (theirs / "theirs.txt").write_text("theirs", encoding = "utf-8")
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ tools._migrate_legacy_sandbox(str(root))
+
+ assert (theirs / "theirs.txt").is_file()
+ assert not (theirs / "mine.csv").exists(), "merged into a folder we do not own"
+ moved = Path(tools.get_sandbox_workdir("notes"))
+ assert moved != theirs
+ assert (moved / "mine.csv").read_text(encoding = "utf-8") == "mine"
+
+
+def test_an_empty_compile_location_is_not_an_override(tmp_path, monkeypatch):
+ """An inherited KEY= would pin the cache to "", which puts an empty entry on
+ sys.path and sends the compiler to the system temp directory."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", "")
+
+ from utils.paths import storage_roots
+
+ storage_roots.setup_cache_env()
+ pinned = os.environ["UNSLOTH_COMPILE_LOCATION"]
+ assert pinned.strip(), "the cache was left unpinned"
+ assert Path(pinned).is_dir()
+
+
+def test_an_id_the_filesystem_cannot_hold_still_gets_its_own_directory(tmp_path, monkeypatch):
+ """These come from API clients. One shared bucket meant every such chat
+ could read, and delete, every other one's files."""
+ 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()
+ first = Path(tools.get_sandbox_workdir("chat.one"))
+ second = Path(tools.get_sandbox_workdir("chat.two"))
+ assert first != second
+ assert first.name.startswith("_id-") and second.name.startswith("_id-")
+ (first / "mine.csv").write_text("mine", encoding = "utf-8")
+
+ # Stable across a restart, so a download chip still resolves.
+ tools._workdirs.clear()
+ assert Path(tools.resolve_sandbox_workdir("chat.one")) == first
+ # And nothing traverses: the name is derived, not the id.
+ escape = Path(tools.get_sandbox_workdir("../../etc"))
+ assert escape.parent == Path(tools.sandbox_root())
+
+
+def test_a_foreign_folder_is_not_taken_for_an_interrupted_move(tmp_path, monkeypatch):
+ """Entry names overlapping is not provenance: only the record written
+ before a move says the directory was ours to fill."""
+ fake_home = tmp_path / "userprofile"
+ legacy = fake_home / "studio_sandbox" / "shared_name"
+ legacy.mkdir(parents = True)
+ (legacy / "notes.txt").write_text("mine", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ root = tmp_path / "shared"
+ root.mkdir()
+ theirs = root / "shared_name"
+ theirs.mkdir()
+ # A subset of the legacy names, which used to be enough to look partial.
+ (theirs / "notes.txt").write_text("theirs", encoding = "utf-8")
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ tools._migrate_legacy_sandbox(str(root))
+
+ assert not (theirs / tools._SANDBOX_MARKER).exists(), "claimed a folder we never made"
+ assert (theirs / "notes.txt").read_text(encoding = "utf-8") == "theirs"
+
+
+def test_a_literal_id_cannot_take_a_derived_name(tmp_path, monkeypatch):
+ """_id-<hash> is the name an unusable id resolves to, so a chat called that
+ must not land on the same directory."""
+ 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()
+ derived = tools._sandbox_name("chat.one")
+ assert derived.startswith(tools._DERIVED_PREFIX)
+ assert tools._sandbox_name(derived) != derived, "a literal id took a derived name"
+
+ first = Path(tools.get_sandbox_workdir("chat.one"))
+ (first / "mine.csv").write_text("mine", encoding = "utf-8")
+ second = Path(tools.get_sandbox_workdir(derived))
+ assert second != first
+ assert not (second / "mine.csv").exists()
+
+
+def test_a_link_inside_the_root_is_stepped_around(tmp_path, monkeypatch):
+ """Its target is contained, so containment alone accepts it, and claiming
+ through it writes our marker into a directory we never made."""
+ root = tmp_path / "shared"
+ root.mkdir()
+ foreign = root / "foreign"
+ foreign.mkdir()
+ (foreign / "theirs.txt").write_text("theirs", encoding = "utf-8")
+ (root / "chat").symlink_to(foreign, target_is_directory = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("chat"))
+ assert workdir.resolve() != foreign.resolve(), workdir
+ assert not (foreign / tools._SANDBOX_MARKER).exists(), "claimed through a link"
+ assert (foreign / "theirs.txt").is_file()
+
+
+def test_an_unowned_cache_of_trainers_is_not_put_on_sys_path(tmp_path, monkeypatch):
+ """Unsloth*Trainer.py is a name a user's own subclass carries, and anything
+ else in that directory would then shadow real modules for every worker."""
+ import sys as _sys
+
+ theirs = tmp_path / "unsloth_compiled_cache"
+ theirs.mkdir()
+ (theirs / "UnslothCustomTrainer.py").write_text("class X: pass\n", encoding = "utf-8")
+ (theirs / "numpy.py").write_text("raise SystemExit('shadowed')\n", encoding = "utf-8")
+ # In the launch directory, which is the case that is not ours.
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("PYTHONPATH", "")
+
+ from utils import cache_cleanup
+
+ before = list(_sys.path)
+ cache_cleanup.register_compiled_cache_on_path()
+ assert str(theirs.resolve()) not in _sys.path, "an unowned directory went on sys.path"
+ assert str(theirs.resolve()) not in os.environ.get("PYTHONPATH", "")
+ _sys.path[:] = before
+
+ # One the compiler has actually written into is still registered.
+ (theirs / "unsloth_compiled_module_gemma3.py").write_text("x = 1\n", encoding = "utf-8")
+ cache_cleanup.register_compiled_cache_on_path()
+ assert str(theirs.resolve()) in _sys.path
+ _sys.path[:] = before
+
+
+def test_the_delete_switch_reaches_a_chat_moved_into_a_project():
+ """Anything it wrote before the move is in its own folder, and the backend
+ never touches the project workspace."""
+ sidebar = (
+ Path(__file__).resolve().parents[2] / "frontend" / "src" / "components" / "app-sidebar.tsx"
+ ).read_text(encoding = "utf-8")
+ assert 'return target.kind === "project" || target.kind === "chat";' in sidebar
+ assert "!target.item.projectId" not in sidebar
+
+
+def test_a_persisted_files_value_that_is_not_a_list_is_not_a_wrapper():
+ """The cards map over it, so anything else takes the chat view down."""
+ root = Path(__file__).resolve().parents[2] / "frontend" / "src"
+ adapter = (root / "features" / "chat" / "api" / "chat-adapter.ts").read_text(encoding = "utf-8")
+ python_card = (root / "components" / "assistant-ui" / "tool-ui-python.tsx").read_text(
+ encoding = "utf-8"
+ )
+ assert "export function isSandboxFileList" in adapter
+ # Every entry, not just the array: the rows read name off each one.
+ assert 'typeof (entry as { name?: unknown }).name === "string"' in adapter
+ for source in (adapter, python_card):
+ assert "isSandboxFileList(v.files)" in source
+
+
+def test_a_sandbox_of_empty_directories_is_still_reclaimed(tmp_path, monkeypatch):
+ """A tool that only ran mkdir, or deleted what it wrote, leaves a folder no
+ chat can reach once its record is gone."""
+ 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()
+ session = "__LOCALID_dirs111"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "outputs" / "runs").mkdir(parents = True)
+
+ assert tools.remove_session_sandbox(session) is True
+ assert not workdir.exists()
+
+ # One with a file in it still needs the opt-in.
+ other = Path(tools.get_sandbox_workdir("__LOCALID_dirs222"))
+ (other / "outputs").mkdir()
+ (other / "outputs" / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ assert tools.remove_session_sandbox("__LOCALID_dirs222") is False
+ assert (other / "outputs" / "report.csv").is_file()
+
+
+def test_a_symlinked_builtin_cache_is_left_usable(tmp_path, monkeypatch):
+ """Clearing resolves the link and removes the target, so without this the
+ link dangles and the next compile cannot write through it."""
+ real = tmp_path / "real_cache"
+ real.mkdir()
+
+ from utils import cache_cleanup
+
+ (real / cache_cleanup.CACHE_MARKER).touch()
+ (real / "unsloth_compiled_module_gemma3.py").write_text("x = 1\n", encoding = "utf-8")
+ link = tmp_path / "unsloth_compiled_cache"
+ link.symlink_to(real, target_is_directory = True)
+ monkeypatch.setattr(cache_cleanup, "_CACHE_DIRS", [link])
+ monkeypatch.delenv("UNSLOTH_COMPILE_LOCATION", raising = False)
+
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert real.is_dir(), "the link was left dangling"
+ assert (real / cache_cleanup.CACHE_MARKER).is_file()
+ assert not (real / "unsloth_compiled_module_gemma3.py").exists()
+ # Writable through the link, which is what the compiler does next.
+ os.makedirs(link, exist_ok = True)
+
+
+def test_the_sandbox_listing_runs_in_a_worker():
+ """It walks up to a couple of thousand entries and stats each one."""
+ import inspect
+
+ from routes import inference as inference_routes
+
+ source = inspect.getsource(inference_routes.list_sandbox_files)
+ # Resolution goes with it: that scans the root for a marked directory.
+ assert "_sandbox_listing(sandbox_dir)" in source
+ assert "run_in_threadpool(_resolve_and_list)" in source
+ assert "os.stat" not in source
+
+
+def test_a_marker_replaced_by_a_link_is_not_written_through(tmp_path, monkeypatch):
+ """The file sits where tool code runs, so a link there would send our write
+ to whatever it points at."""
+ 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()
+ session = "__LOCALID_link911"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ victim = tmp_path / "notes.txt"
+ victim.write_text("years of notes", encoding = "utf-8")
+
+ marker = workdir / tools._SANDBOX_MARKER
+ marker.unlink()
+ marker.symlink_to(victim)
+ assert tools._marker_owner(str(workdir)) is None, "followed a link to read"
+
+ tools._mark_sandbox(str(workdir), session)
+ assert victim.read_text(encoding = "utf-8") == "years of notes", "wrote through the link"
+ assert not marker.is_symlink()
+ assert marker.read_text(encoding = "utf-8") == session
+
+
+def test_a_cached_path_swapped_for_another_chats_directory_is_dropped(tmp_path, monkeypatch):
+ """cd .., mv, ln -s is all a tool needs, and containment accepts a link to
+ a sibling."""
+ 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()
+ victim = Path(tools.get_sandbox_workdir("__LOCALID_victim2"))
+ (victim / "private.csv").write_text("theirs", encoding = "utf-8")
+ attacker = Path(tools.get_sandbox_workdir("__LOCALID_attack2"))
+
+ shutil.rmtree(attacker)
+ attacker.symlink_to(victim, target_is_directory = True)
+
+ again = Path(tools.get_sandbox_workdir("__LOCALID_attack2"))
+ assert again.resolve() != victim.resolve(), again
+ assert not (again / "private.csv").exists()
+ resolved = Path(tools.resolve_sandbox_workdir("__LOCALID_attack2"))
+ assert not (resolved / "private.csv").exists(), resolved
+
+
+def test_a_default_folder_that_was_already_there_is_not_run_in(tmp_path, monkeypatch):
+ """A call with no session id lands on the fallback, which in a shared root
+ can be a directory of the user's own."""
+ root = tmp_path / "shared"
+ root.mkdir()
+ theirs = root / "_default"
+ theirs.mkdir()
+ (theirs / "notes.txt").write_text("theirs", encoding = "utf-8")
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir(None))
+ assert workdir != theirs, workdir
+ assert not (workdir / "notes.txt").exists()
+ assert (theirs / "notes.txt").read_text(encoding = "utf-8") == "theirs"
+ assert not (theirs / tools._SANDBOX_MARKER).exists()
+
+ # Ours is claimed, so the next run recognises it rather than making another.
+ tools._workdirs.clear()
+ assert Path(tools.get_sandbox_workdir(None)) == workdir
+
+
+def test_an_id_a_path_segment_cannot_carry_rides_in_the_query():
+ """ASGI decodes %2F before it matches a route, so an id with a slash in it
+ would arrive as a different id and a different filename."""
+ root = Path(__file__).resolve().parents[2] / "frontend" / "src"
+ helper = (root / "components" / "assistant-ui" / "sandbox-files.ts").read_text(encoding = "utf-8")
+ assert "export function sandboxRoutePrefix" in helper
+ assert "?session=${encodeURIComponent(sessionId)}" in helper
+
+ from routes import inference as inference_routes
+ import inspect
+
+ for route in (inference_routes.list_sandbox_files, inference_routes.serve_sandbox_file):
+ source = inspect.getsource(route)
+ assert "session: Optional[str] = None" in source
+ assert "session or session_id" in source
+
+
+def test_clearing_every_chat_reports_what_it_deleted(tmp_path, monkeypatch):
+ """A thread added between the listing and the delete is gone too, and its
+ sandbox has to be cleaned up with the rest."""
+ import inspect
+
+ from routes import chat_history
+ from storage import studio_db
+
+ source = inspect.getsource(studio_db.clear_chat_history)
+ assert "SELECT id FROM chat_threads" in source
+ assert source.index("SELECT id FROM chat_threads") < source.index("DELETE FROM chat_threads")
+ assert "return removed, active_runs" in source
+
+ route = inspect.getsource(chat_history.clear_history)
+ assert "cleared, cleared_runs = clear_chat_history()" in route
+ assert "cleared" in route.split("_remove_sandboxes(", 1)[1].split(")", 1)[0]
+
+
+def test_a_symlinked_cache_marker_does_not_license_a_delete(tmp_path, monkeypatch):
+ """exists() follows a link, so a marker pointing at any existing path would
+ have the cleanup rmtree a directory of the user's own."""
+ from utils import cache_cleanup
+
+ theirs = tmp_path / "unsloth_compiled_cache"
+ theirs.mkdir()
+ (theirs / "notes.txt").write_text("years of notes", encoding = "utf-8")
+ (theirs / cache_cleanup.CACHE_MARKER).symlink_to(tmp_path / "anything")
+ (tmp_path / "anything").write_text("x", encoding = "utf-8")
+
+ assert cache_cleanup._is_dedicated_cache(theirs) is False
+
+ monkeypatch.setenv("UNSLOTH_COMPILE_LOCATION", str(theirs))
+ monkeypatch.chdir(tmp_path)
+ cache_cleanup.clear_unsloth_compiled_cache()
+ assert (theirs / "notes.txt").is_file(), "deleted a directory it does not own"
+
+
+def test_a_real_cache_marker_still_counts(tmp_path):
+ """The other half: a directory Studio made is still cleaned out."""
+ from utils import cache_cleanup
+
+ ours = tmp_path / "unsloth_compiled_cache"
+ ours.mkdir()
+ (ours / cache_cleanup.CACHE_MARKER).touch()
+ assert cache_cleanup._is_dedicated_cache(ours) is True
+
+
+def test_an_id_with_a_lone_surrogate_still_gets_a_directory(tmp_path, monkeypatch):
+ """An API client can send one in JSON, and a POSIX name decoded with
+ surrogateescape carries them too; a strict encode raises instead."""
+ 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()
+ odd = "chat-\ud800-one"
+ name = tools._sandbox_name(odd)
+ assert name.startswith(tools._DERIVED_PREFIX)
+ # Distinct ids stay distinct: surrogatepass keeps the code point, where a
+ # replacing policy would fold every bad id onto one directory.
+ assert name != tools._sandbox_name("chat-\ud801-one")
+
+ workdir = Path(tools.get_sandbox_workdir(odd))
+ assert workdir.is_dir()
+ assert Path(tools.resolve_sandbox_workdir(odd)) == workdir
+
+
+def test_a_legacy_entry_that_is_a_symlink_is_left_alone(tmp_path, monkeypatch):
+ """move() keeps the link, and the marker would then be written inside
+ whatever it points at, which is outside both roots."""
+ fake_home = tmp_path / "userprofile"
+ legacy = fake_home / "studio_sandbox"
+ legacy.mkdir(parents = True)
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "theirs.txt").write_text("mine", encoding = "utf-8")
+ (legacy / "__LOCALID_link111").symlink_to(outside, target_is_directory = True)
+ (legacy / "__LOCALID_real111").mkdir()
+ (legacy / "__LOCALID_real111" / "results.csv").write_text("a,b\n", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ root = Path(tools.sandbox_root())
+ tools._migrate_legacy_sandbox(str(root))
+
+ assert not (outside / tools._SANDBOX_MARKER).exists(), "wrote outside both roots"
+ assert (outside / "theirs.txt").is_file()
+ assert not (root / "__LOCALID_link111").exists()
+ # The rest of the pass still runs.
+ assert (root / "__LOCALID_real111" / "results.csv").is_file()
+
+
+def test_a_first_tool_call_does_not_wait_for_the_whole_legacy_tree(tmp_path, monkeypatch):
+ """Across filesystems the migration copies every session, which is minutes;
+ a call that only needs its own folder must not queue behind it."""
+ fake_home = tmp_path / "userprofile"
+ legacy = fake_home / "studio_sandbox"
+ (legacy / "__LOCALID_mine111").mkdir(parents = True)
+ (legacy / "__LOCALID_mine111" / "results.csv").write_text("a,b\n", encoding = "utf-8")
+ (legacy / "__LOCALID_huge111").mkdir()
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ held = threading.Event()
+ monkeypatch.setattr(
+ tools,
+ "migrate_legacy_sandbox_in_background",
+ lambda: threading.Thread(target = held.wait),
+ )
+
+ class _Blocked:
+ def __enter__(self):
+ assert held.wait(0), "the request path took the whole-tree lock"
+
+ def __exit__(self, *exc):
+ return False
+
+ monkeypatch.setattr(tools, "_legacy_sandbox_lock", _Blocked())
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_mine111"))
+ held.set()
+
+ assert (workdir / "results.csv").is_file(), "this chat's own files were left behind"
+
+
+def test_deleting_a_chat_stops_a_generation_that_would_recreate_it(monkeypatch):
+ """A request that has not reached the executor yet would dispatch its tool
+ call after the delete and write files no chat can reach."""
+ import routes.chat_history as chat_history
+
+ cancelled = []
+ monkeypatch.setattr(chat_history, "delete_chat_threads", lambda ids: None)
+ monkeypatch.setattr(chat_history, "_cancel_active_research", lambda request, ids: None)
+
+ from state import active_generations
+
+ monkeypatch.setattr(active_generations, "cancel_thread", lambda tid: cancelled.append(tid) or 1)
+
+ chat_history._cancel_active_generations(["__LOCALID_gone111", "__LOCALID_gone222"])
+ assert cancelled == ["__LOCALID_gone111", "__LOCALID_gone222"]
+
+ import inspect
+
+ for route in (chat_history.delete_threads, chat_history.clear_history):
+ source = inspect.getsource(route)
+ assert "_cancel_active_generations" in source, route.__name__
+ assert source.index("_cancel_active_generations") < source.index("_remove_sandboxes")
+
+
+def test_a_large_file_is_streamed_rather_than_buffered():
+ """A tool can write a multi-gigabyte artifact, and a Blob plus the IPC copy
+ of it would be two more of it in the renderer."""
+ view = (
+ Path(__file__).resolve().parents[2]
+ / "frontend/src/components/assistant-ui/sandbox-files-view.tsx"
+ ).read_text(encoding = "utf-8")
+
+ assert "downloadUrlStreaming" in view
+ assert "response.blob()" not in view
+ # The route takes the bearer as a query parameter, since the streaming path
+ # sends no headers of its own.
+ assert "token=" in view
+
+
+def test_a_same_size_overwrite_is_still_reported(tmp_path, monkeypatch):
+ """On a coarse-timestamp volume a rewrite of the same length inside one tick
+ matches on mtime and size, and the call reported no file at all."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_same111"))
+ # The premise: where mtime alone separates the writes there is no digest.
+ monkeypatch.setattr(tools, "_volume_timestamps_finely", lambda _: False)
+ report = workdir / "report.csv"
+ report.write_text("a,b\n1,2\n", encoding = "utf-8")
+
+ before = tools._snapshot_workdir_files(str(workdir))
+ report.write_text("a,b\n3,4\n", encoding = "utf-8") # same length
+ os.utime(report, ns = (before["report.csv"][0], before["report.csv"][0]))
+
+ after = tools._snapshot_workdir_files(str(workdir))
+ assert after["report.csv"][:2] == before["report.csv"][:2], "the test lost its premise"
+ assert after["report.csv"] != before["report.csv"], "a same-size rewrite looked unchanged"
+
+ sentinel = tools._created_file_sentinels(str(workdir), before)
+ assert "report.csv" in (sentinel or ""), sentinel
+
+
+def test_a_file_too_big_to_read_is_still_snapshotted(tmp_path, monkeypatch):
+ """The digest is bounded: reading every artifact twice per call is not the
+ price for a case that needs a coarse clock and an exact length match."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_big1111"))
+ big = workdir / "model.bin"
+ big.write_bytes(b"0" * (tools._MAX_HASHED_SNAPSHOT_BYTES + 1))
+
+ entry = tools._snapshot_workdir_files(str(workdir))["model.bin"]
+ assert entry[1] == tools._MAX_HASHED_SNAPSHOT_BYTES + 1
+ assert entry[2] is None, "hashed a file past the cap"
+
+
+def test_deleting_a_big_sandbox_does_not_hold_up_other_chats(tmp_path, monkeypatch):
+ """Every tool start takes this lock, so an rmtree in here stops calls in
+ every unrelated chat for as long as it runs."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ session = "__LOCALID_big2222"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "data.csv").write_text("a,b\n", encoding = "utf-8")
+
+ started = threading.Event()
+ release = threading.Event()
+ real_rmtree = tools.shutil.rmtree
+
+ def slow_rmtree(path, **kwargs):
+ started.set()
+ release.wait(10)
+ return real_rmtree(path, **kwargs)
+
+ monkeypatch.setattr(tools.shutil, "rmtree", slow_rmtree)
+ outcome = []
+ deleter = threading.Thread(
+ target = lambda: outcome.append(tools.remove_session_sandbox(session, delete_files = True)),
+ )
+ try:
+ deleter.start()
+ assert started.wait(5), "the delete never started"
+ # Observed while the tree is still going: this is the lock every tool
+ # start takes, so holding it here stops calls in every other chat.
+ assert tools._active_sessions_lock.acquire(timeout = 2), "held the tool lock"
+ tools._active_sessions_lock.release()
+ assert not workdir.exists(), "the name is still there"
+ finally:
+ release.set()
+ deleter.join(15)
+ monkeypatch.setattr(tools.shutil, "rmtree", real_rmtree)
+ assert outcome == [True], outcome
+ for _ in range(100):
+ leftovers = [n for n in os.listdir(tools.sandbox_root()) if tools._DETACHED_SUFFIX in n]
+ if not leftovers:
+ break
+ time.sleep(0.05)
+ assert leftovers == [], leftovers
+
+
+def test_an_interrupted_move_is_not_read_as_a_collision(tmp_path, monkeypatch):
+ """Across filesystems the copy fills the destination as it goes, so a run
+ killed part way leaves a partial directory with the source still there."""
+ fake_home = tmp_path / "userprofile"
+ legacy = fake_home / "studio_sandbox" / "__LOCALID_part111"
+ legacy.mkdir(parents = True)
+ (legacy / "results.csv").write_text("a,b\n", encoding = "utf-8")
+ (legacy / "second.csv").write_text("c,d\n", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ root = Path(tools.sandbox_root())
+ root.mkdir(parents = True, exist_ok = True)
+
+ real_move = tools.shutil.move
+
+ def half_copied(source, target):
+ os.makedirs(target, exist_ok = True)
+ shutil.copy2(os.path.join(source, "results.csv"), os.path.join(target, "results.csv"))
+ raise OSError(5, "interrupted")
+
+ monkeypatch.setattr(tools.shutil, "move", half_copied)
+ tools._migrate_legacy_sandbox(str(root))
+ monkeypatch.setattr(tools.shutil, "move", real_move)
+
+ # Nothing at the session's name, so the next launch does not read the half
+ # copy as a session the new root already has.
+ assert not (root / "__LOCALID_part111").exists(), "left a partial copy at the real name"
+ assert [n for n in os.listdir(root) if tools._STAGING_SUFFIX in n] == []
+ assert (legacy / "second.csv").is_file(), "lost the source"
+
+ tools._legacy_sandbox_migrated = False
+ tools._migrate_legacy_sandbox(str(root))
+ assert (root / "__LOCALID_part111" / "second.csv").is_file(), "the retry never happened"
+
+
+def test_a_delete_without_the_switch_says_what_it_kept(tmp_path, monkeypatch):
+ """Surfaces other than the sidebar never offer the choice, and after the
+ delete the folder is unreachable, so the route reports it."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ kept = "__LOCALID_keeps11"
+ empty = "__LOCALID_empty11"
+ workdir = Path(tools.get_sandbox_workdir(kept))
+ (workdir / "results.csv").write_text("a,b\n", encoding = "utf-8")
+ Path(tools.get_sandbox_workdir(empty))
+
+ assert tools.session_sandbox_has_files(kept) is True
+ assert tools.session_sandbox_has_files(empty) is False
+ assert tools.session_sandbox_has_files("__LOCALID_never11") is False
+
+ import asyncio
+
+ import routes.chat_history as chat_history
+
+ removed, still_there = (
+ asyncio.get_event_loop_policy()
+ .new_event_loop()
+ .run_until_complete(chat_history._remove_sandboxes([kept, empty], False))
+ )
+ assert removed == 1, removed # the empty one
+ assert still_there == [kept], still_there
+ assert (workdir / "results.csv").is_file()
+
+
+def test_every_delete_surface_can_still_reach_the_files():
+ """The offer is made where every surface goes through, not only the one
+ dialog that has the switch."""
+ src = Path(__file__).resolve().parents[2] / "frontend/src"
+ hook = (src / "features/chat/hooks/use-chat-sidebar-items.ts").read_text(
+ encoding = "utf-8",
+ )
+ offer = (src / "features/chat/utils/offer-kept-sandbox-files.ts").read_text(
+ encoding = "utf-8",
+ )
+
+ body = hook[hook.index("export async function deleteChatItem") :]
+ assert "offerToDeleteKeptSandboxes(kept)" in body
+ assert "toast(" in offer, "nothing tells the user the files are still there"
+ assert "deleteFiles: true" in offer
+
+
+def test_a_fallback_name_already_in_a_shared_root_is_not_taken(tmp_path, monkeypatch):
+ """Both names can be the user's, and claiming the second one puts the chat
+ inside their files, which a delete with the switch would then remove."""
+ root = tmp_path / "shared"
+ root.mkdir()
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ session = "__LOCALID_both111"
+ name = tools._sandbox_name(session)
+ theirs = root / name
+ theirs.mkdir()
+ (theirs / "plain.txt").write_text("mine", encoding = "utf-8")
+ fallback = root / f"{name}-{tools._name_suffix(session)}"
+ fallback.mkdir()
+ (fallback / "also-mine.txt").write_text("mine", encoding = "utf-8")
+
+ workdir = Path(tools.get_sandbox_workdir(session))
+ assert workdir not in (theirs, fallback), workdir
+ assert not (theirs / tools._SANDBOX_MARKER).exists()
+ assert not (fallback / tools._SANDBOX_MARKER).exists()
+ assert tools._marker_owner(str(workdir)) == name
+
+ # And a delete takes only what we made.
+ tools.remove_session_sandbox(session, delete_files = True)
+ assert (theirs / "plain.txt").is_file()
+ assert (fallback / "also-mine.txt").is_file()
+
+
+def test_a_symlinked_sandbox_marker_does_not_make_a_directory_ours(tmp_path, monkeypatch):
+ """isfile() follows the link, so a marker pointing at any existing file
+ would let a delete remove an unrelated directory in a shared root."""
+ root = tmp_path / "shared"
+ root.mkdir()
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ session = "__LOCALID_fake111"
+ theirs = root / tools._sandbox_name(session)
+ theirs.mkdir()
+ (theirs / "notes.txt").write_text("years of notes", encoding = "utf-8")
+ (root / "anything").write_text("x", encoding = "utf-8")
+ (theirs / tools._SANDBOX_MARKER).symlink_to(root / "anything")
+
+ assert tools._sandbox_is_ours(str(theirs)) is False
+ assert tools.remove_session_sandbox(session, delete_files = True) is False
+ assert (theirs / "notes.txt").is_file(), "deleted a directory it does not own"
+
+
+def test_a_chat_that_owns_nothing_never_reads_from_the_shared_root(tmp_path, monkeypatch):
+ """The reserved-looking path was inside the user's own root, so a folder
+ they happen to keep at that name would have been listed and served."""
+ root = tmp_path / "shared"
+ root.mkdir()
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ session = "__LOCALID_none111"
+ theirs = root / tools._sandbox_name(session)
+ theirs.mkdir()
+ (theirs / "private.csv").write_text("theirs", encoding = "utf-8")
+ # What the old sentinel pointed at, filled by the user.
+ planted = root / "_unowned" / tools._sandbox_name(session)
+ planted.mkdir(parents = True)
+ (planted / "also-theirs.csv").write_text("theirs", encoding = "utf-8")
+
+ # The fallback name is theirs too, so the resolver has nothing of ours to
+ # answer with and must not point at anything in here.
+ fallback = root / f"{tools._sandbox_name(session)}-{tools._name_suffix(session)}"
+ fallback.mkdir()
+ (fallback / "third.csv").write_text("theirs", encoding = "utf-8")
+
+ resolved = Path(tools.resolve_sandbox_workdir(session))
+ assert not str(resolved).startswith(str(root)), resolved
+ assert not (resolved / "also-theirs.csv").exists()
+ assert not (resolved / "private.csv").exists()
+ assert not (resolved / "third.csv").exists()
+
+
+def test_a_request_path_move_lands_where_the_resolver_says(tmp_path, monkeypatch):
+ """Stopping at the plain-name collision left the chat with an empty sandbox
+ and its files at the old root, with the whole-tree pass then agreeing."""
+ fake_home = tmp_path / "userprofile"
+ legacy = fake_home / "studio_sandbox" / "__LOCALID_taken11"
+ legacy.mkdir(parents = True)
+ (legacy / "results.csv").write_text("a,b\n", encoding = "utf-8")
+
+ root = tmp_path / "shared"
+ root.mkdir()
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tools._legacy_sandbox_migrated = False
+ theirs = root / "__LOCALID_taken11"
+ theirs.mkdir()
+ (theirs / "plain.txt").write_text("mine", encoding = "utf-8")
+
+ tools._migrate_one_legacy_session(str(root), "__LOCALID_taken11")
+
+ assert (theirs / "plain.txt").is_file(), "moved into the user's own folder"
+ landed = Path(tools.get_sandbox_workdir("__LOCALID_taken11"))
+ assert (landed / "results.csv").is_file(), f"the chat's files were stranded: {landed}"
+
+
+def test_deleting_a_project_takes_its_chats_sandboxes(tmp_path, monkeypatch):
+ """A chat can write files before it joins a project, and deleting the
+ project removes the only records of those chats."""
+ import inspect
+
+ from routes import chat_history
+
+ source = inspect.getsource(chat_history.delete_project)
+ assert "_remove_sandboxes(member_ids" in source
+ assert "_cancel_active_generations(member_ids)" in source
+ assert source.index("delete_chat_project(") < source.index(
+ "_cancel_active_generations(member_ids)"
+ )
+
+
+def test_a_native_download_gets_an_absolute_url():
+ """The native command parses the URL and rejects a relative one, so a bare
+ /api path failed before the request was made."""
+ view = (
+ Path(__file__).resolve().parents[2]
+ / "frontend/src/components/assistant-ui/sandbox-files-view.tsx"
+ ).read_text(encoding = "utf-8")
+
+ assert "apiUrl(" in view
+ body = view[view.index("const save = useCallback") :]
+ assert body.index("apiUrl(") < body.index("downloadUrlStreaming(")
+
+
+def _forget_sandbox_state(tools):
+ """Everything a fresh process would not remember."""
+ tools._workdirs.clear()
+ getattr(tools, "_claimed_here", set()).clear()
+
+
+def _shared_root(tmp_path, monkeypatch):
+ root = tmp_path / "shared"
+ root.mkdir()
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(root))
+ return root
+
+
+def test_a_fallback_with_a_random_name_is_found_again(tmp_path, monkeypatch):
+ """Nothing can recompute that name, so without the marker the chat gets a
+ new folder every launch and a delete never reaches the old ones."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_rand111"
+ name = tools._sandbox_name(session)
+ for taken in (root / name, root / f"{name}-{tools._name_suffix(session)}"):
+ taken.mkdir()
+
+ first = Path(tools.get_sandbox_workdir(session))
+ (first / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ assert tools._marker_owner(str(first)) == name
+
+ # A later launch: nothing cached, and the name is not derivable.
+ _forget_sandbox_state(tools)
+ assert Path(tools.get_sandbox_workdir(session)) == first
+ assert Path(tools.resolve_sandbox_workdir(session)) == first
+
+ assert tools.remove_session_sandbox(session, delete_files = True) is True
+ assert not first.exists(), "the delete could not reach the fallback"
+
+
+def test_a_marker_a_tool_deleted_is_written_again(tmp_path, monkeypatch):
+ """Tool code runs in this directory. Reading the missing marker as somebody
+ else's strands the files already written and restarts the chat elsewhere."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_clob111"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "plot.png").write_bytes(b"x")
+ (workdir / tools._SANDBOX_MARKER).unlink()
+
+ again = Path(tools.get_sandbox_workdir(session))
+ assert again == workdir, "the chat walked away from its own files"
+ assert tools._marker_owner(str(workdir)) == tools._sandbox_name(session)
+ assert (again / "plot.png").is_file()
+
+ # A directory this run never claimed is still left alone.
+ theirs = root / "not-ours"
+ theirs.mkdir()
+ tools._workdirs[("__LOCALID_other11", None)] = str(theirs)
+ assert Path(tools.get_sandbox_workdir("__LOCALID_other11")) != theirs
+ assert not (theirs / tools._SANDBOX_MARKER).exists()
+
+
+def test_an_interrupted_delete_is_finished_on_the_next_launch(tmp_path, monkeypatch):
+ """The rename is what puts the tree out of reach, so a kill before the
+ rmtree leaves a full copy of the files nothing resolves to."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ tombstone = root / f"__LOCALID_gone111{tools._DETACHED_SUFFIX}0123abcd"
+ tombstone.mkdir()
+ (tombstone / "secret.csv").write_text("rows", encoding = "utf-8")
+ (tombstone / tools._SANDBOX_MARKER).write_text(
+ "__LOCALID_gone111",
+ encoding = "utf-8",
+ )
+ # The user's own, named similarly and never marked.
+ theirs = root / "report.deleting-old"
+ theirs.mkdir()
+ (theirs / "keep.txt").write_text("mine", encoding = "utf-8")
+
+ tools.sweep_detached_sandboxes(str(root))
+
+ assert not tombstone.exists(), "an interrupted delete left the files behind"
+ assert (theirs / "keep.txt").is_file(), "swept a folder it does not own"
+
+
+def test_a_legacy_chat_named_like_a_derived_id_is_migrated(tmp_path, monkeypatch):
+ """Its folder is under the literal id, but the name is now hashed, so
+ looking only at the hash leaves those files at the old root."""
+ fake_home = tmp_path / "userprofile"
+ session = tools_derived_id = "_id-0123456789abcdef"
+ legacy = fake_home / "studio_sandbox" / session
+ legacy.mkdir(parents = True)
+ (legacy / "old.csv").write_text("a,b\n", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ assert tools_derived_id.startswith(tools._DERIVED_PREFIX)
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+
+ landed = Path(tools.get_sandbox_workdir(session))
+ assert (landed / "old.csv").is_file(), f"files stranded at the legacy root: {landed}"
+
+
+def test_clearing_every_chat_reports_the_files_it_kept():
+ """Without the switch the folders survive the clear, and afterwards there
+ is no card left to reach them from."""
+ src = Path(__file__).resolve().parents[2] / "frontend/src"
+
+ api = (src / "features/chat/api/chat-api.ts").read_text(encoding = "utf-8")
+ clear = api[api.index("export async function clearBackendChats") :]
+ clear = clear[: clear.index("\nexport ")]
+ assert "Promise<string[]>" in clear
+ assert "sandboxes_kept" in clear
+
+ storage = (src / "features/chat/utils/chat-history-storage.ts").read_text(
+ encoding = "utf-8",
+ )
+ assert "sandboxesKept" in storage
+ assert "result.sandboxesKept = await clearBackendChats" in storage
+
+ tab = (src / "features/settings/tabs/data-tab.tsx").read_text(encoding = "utf-8")
+ assert "offerToDeleteKeptSandboxes(result.sandboxesKept)" in tab
+
+ offer = (src / "features/chat/utils/offer-kept-sandbox-files.ts").read_text(
+ encoding = "utf-8",
+ )
+ assert "deleteFiles: true" in offer
+ # And the per-chat surfaces go through the same offer.
+ hook = (src / "features/chat/hooks/use-chat-sidebar-items.ts").read_text(
+ encoding = "utf-8",
+ )
+ assert "offerToDeleteKeptSandboxes(kept)" in hook
+
+
+def test_a_lone_surrogate_id_can_still_step_aside(tmp_path, monkeypatch):
+ """The collision path encodes the id a second time, and a strict encode
+ there raises before the chat can be given a name of its own."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "chat-\udce2-1" # what an API client can send, and what os.listdir returns
+ theirs = root / tools._sandbox_name(session)
+ theirs.mkdir()
+ (theirs / "theirs.txt").write_text("mine", encoding = "utf-8")
+
+ workdir = Path(tools.get_sandbox_workdir(session))
+ assert workdir != theirs
+ assert tools._marker_owner(str(workdir)) == tools._sandbox_name(session)
+
+
+def test_a_legacy_move_lands_when_both_names_are_taken(tmp_path, monkeypatch):
+ """Both derived names can be the user's, and returning there left the files
+ at the legacy root with nothing that would ever move them."""
+ fake_home = tmp_path / "userprofile"
+ session = "__LOCALID_both222"
+ legacy = fake_home / "studio_sandbox" / session
+ legacy.mkdir(parents = True)
+ (legacy / "results.csv").write_text("a,b\n", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+ taken = [root / session, root / f"{session}-{tools._name_suffix(session)}"]
+ for directory in taken:
+ directory.mkdir()
+ (directory / "theirs.txt").write_text("mine", encoding = "utf-8")
+
+ tools._migrate_one_legacy_session(str(root), session)
+
+ landed = Path(tools.get_sandbox_workdir(session))
+ assert (landed / "results.csv").is_file(), f"files stranded at the legacy root: {landed}"
+ for directory in taken:
+ assert (directory / "theirs.txt").is_file(), "moved into the user's own folder"
+
+
+def test_a_read_finds_the_marked_fallback_after_a_restart(tmp_path, monkeypatch):
+ """Only creation and deletion scanned for the marker, so every file card in
+ the transcript 404s until some later tool call refills the cache."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_read111"
+ name = tools._sandbox_name(session)
+ for taken in (root / name, root / f"{name}-{tools._name_suffix(session)}"):
+ taken.mkdir()
+
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ _forget_sandbox_state(tools) # a restart: nothing cached
+ served = Path(tools.resolve_sandbox_workdir(session))
+ assert served == workdir, f"the read could not find the fallback: {served}"
+ assert (served / "report.csv").is_file()
+
+
+def test_a_chat_started_during_the_clear_is_cancelled_too():
+ """Its id is in the transaction's result and its sandbox is removed, but a
+ generation still running would dispatch a tool and rebuild it."""
+ import inspect
+
+ from routes import chat_history
+
+ source = inspect.getsource(chat_history.clear_history)
+ assert "late" in source
+ assert source.index("cleared, cleared_runs = clear_chat_history()") < source.index(
+ "_cancel_active_generations(late)"
+ )
+ assert source.index("_cancel_active_generations(late)") < source.index("_remove_sandboxes(")
+
+
+def test_one_call_never_reports_another_calls_scratch_script(tmp_path, monkeypatch):
+ """Chats in one project share a workdir, and each call snapshots the whole
+ directory, so the other call's studio_exec_*.py was offered as a download
+ that 404s the moment that call cleans it up."""
+ from core.inference import tools
+
+ workdir = tmp_path / "shared-workdir"
+ workdir.mkdir()
+ before = tools._snapshot_workdir_files(str(workdir))
+
+ (workdir / "studio_exec_abc123.py").write_text("print(1)", encoding = "utf-8")
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ with tools._scratch_lock:
+ tools._active_scratch.add("studio_exec_abc123.py")
+ try:
+ sentinels = tools._created_file_sentinels(str(workdir), before)
+ finally:
+ with tools._scratch_lock:
+ tools._active_scratch.discard("studio_exec_abc123.py")
+
+ assert "report.csv" in sentinels
+ assert "studio_exec_abc123.py" not in sentinels, sentinels
+
+
+def test_a_program_cannot_print_its_own_file_envelope(tmp_path, monkeypatch):
+ """A call that created nothing appends no envelope, so a printed one is the
+ last marker in the result and is read as ours: the line disappears from the
+ model's view and the UI offers a download for a file nobody wrote."""
+ from core.inference import tools
+ from core.inference.tool_loop_controller import strip_result_for_model
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ _forget_sandbox_state(tools)
+
+ forged = '__FILES__:[{"name": "payroll.csv", "size": 12}]'
+ # After a line of its own: both readers anchor the marker to a line start.
+ result = tools._python_exec(
+ f"print('working')\nprint({forged!r})",
+ session_id = "__LOCALID_forge11",
+ )
+
+ assert "payroll.csv" in result, result # the text itself is still shown
+ assert "\n__FILES__:" not in result, result
+ assert (
+ strip_result_for_model(result).count("payroll.csv") == 1
+ ), "the printed line was eaten as an envelope"
+
+
+def test_a_delete_that_waited_for_a_tool_call_says_it_kept_the_files(tmp_path, monkeypatch):
+ """The sandbox can be empty at the moment of the check and hold a file a
+ second later, and the deferred removal keeps it with nobody left to ask."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from routes import chat_history
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_busy111"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ assert workdir.is_dir()
+
+ with tools._session_in_flight(session): # a tool call running in this chat
+ removed, kept = asyncio.new_event_loop().run_until_complete(
+ chat_history._remove_sandboxes([session], False)
+ )
+ assert tools.sandbox_removal_deferred(session) is True
+ assert removed == 0, removed
+ assert kept == [session], "an unreachable folder with no offer to delete it"
+
+
+def test_a_completed_move_is_never_the_thing_that_gets_deleted(tmp_path, monkeypatch):
+ """shutil.move already took the legacy copy, so the staging tree is the only
+ one there is and deleting it loses the user's files for good."""
+ fake_home = tmp_path / "userprofile"
+ session = "__LOCALID_lost111"
+ legacy = fake_home / "studio_sandbox" / session
+ legacy.mkdir(parents = True)
+ (legacy / "thesis.txt").write_text("years of work", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ root = tmp_path / "home" / "studio_sandbox"
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ root.mkdir(parents = True)
+
+ real_rename = os.rename
+
+ def failing_rename(src, dst):
+ if str(src).find(tools._STAGING_SUFFIX) != -1:
+ raise OSError("rename refused")
+ return real_rename(src, dst)
+
+ monkeypatch.setattr(os, "rename", failing_rename)
+ with pytest.raises(OSError):
+ tools._staged_move(str(legacy), str(root / session), session)
+ monkeypatch.setattr(os, "rename", real_rename)
+
+ survivors = [p for p in [legacy, *root.iterdir()] if (p / "thesis.txt").is_file()]
+ assert survivors, "the only copy of the user's files was deleted"
+
+
+def test_a_symlinked_directory_counts_as_a_file_of_the_users(tmp_path, monkeypatch):
+ """os.walk lists it in dirs, and a check that reads only files called the
+ sandbox empty and removed the link the tool made."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_link111"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ elsewhere = tmp_path / "data"
+ elsewhere.mkdir()
+ (workdir / "dataset").symlink_to(elsewhere, target_is_directory = True)
+
+ assert tools._holds_no_user_files(str(workdir)) is False
+ assert tools.remove_session_sandbox(session, delete_files = False) is False
+ assert (workdir / "dataset").is_symlink(), "removed something the tool made"
+ assert tools.session_sandbox_has_files(session) is True
+
+
+def test_a_project_delete_uses_the_membership_it_really_deleted():
+ """A chat moved in after the listing is deleted by the transaction, and its
+ generation would keep running and rebuild a sandbox nothing can reach."""
+ import inspect
+
+ from routes import chat_history
+ from storage import studio_db
+
+ storage = inspect.getsource(studio_db.delete_chat_project)
+ assert 'project["memberIds"] = sorted(thread_ids)' in storage
+
+ route = inspect.getsource(chat_history.delete_project)
+ # Only the transaction's membership: a chat moved out just before it
+ # survives the delete, and cancelling or deleting from an earlier listing
+ # would stop it and remove the files it wrote.
+ assert 'member_ids = list(project.get("memberIds") or [])' in route
+ assert "list_chat_threads(project_id" not in route
+ assert route.index("_cancel_active_generations(member_ids)") < route.index("_remove_sandboxes(")
+ # And what survived is reported, or the folders are reachable from nothing.
+ assert "sandboxes_kept = await _remove_sandboxes(member_ids" in route
+ assert "ChatProjectDeleted(**project, sandboxes_kept = sandboxes_kept)" in route
+
+
+def test_closing_an_incognito_chat_cleans_up_its_sandbox():
+ """Its id is what the tool call sent as the sandbox session, so a folder
+ exists on disk even though no history row does."""
+ src = Path(__file__).resolve().parents[2] / "frontend/src"
+
+ storage = (src / "features/chat/utils/chat-history-storage.ts").read_text(
+ encoding = "utf-8",
+ )
+ body = storage[storage.index("export async function deleteStoredChatThreads") :]
+ body = body[: body.index("\nexport ")]
+ assert "deleteChatThreads(idsToDelete" in body, "incognito ids never reach the backend"
+ assert "isThreadIncognito" in body # the Dexie work still skips them
+
+ projects = (src / "features/chat/hooks/use-chat-projects.ts").read_text(
+ encoding = "utf-8",
+ )
+ assert "offerToDeleteKeptSandboxes(kept)" in projects
+
+
+def test_a_snapshot_stops_hashing_once_it_has_read_enough(tmp_path, monkeypatch):
+ """The file cap alone allowed thousands of files under the per-file bound to
+ be read in full, twice per call, on a directory of experiment artifacts."""
+ from core.inference import tools
+
+ workdir = tmp_path / "artifacts"
+ workdir.mkdir()
+ chunk = b"x" * (1024 * 1024)
+ for i in range(8):
+ (workdir / f"run{i}.bin").write_bytes(chunk)
+
+ monkeypatch.setattr(tools, "_MAX_SNAPSHOT_HASH_BYTES", 3 * 1024 * 1024)
+ read = []
+ real_content_key = tools._content_key
+
+ def counting_content_key(path, size):
+ read.append(size)
+ return real_content_key(path, size)
+
+ monkeypatch.setattr(tools, "_content_key", counting_content_key)
+ snapshot = tools._snapshot_workdir_files(str(workdir))
+
+ assert len(snapshot) == 8, snapshot # every file is still reported
+ assert sum(read) <= 3 * 1024 * 1024 + 1024 * 1024, sum(read)
+ assert any(key[2] is None for key in snapshot.values()), "nothing fell back"
+
+
+def test_a_call_that_shared_its_workdir_claims_nothing(tmp_path):
+ """Chats in one project share a workdir. Each call diffs the whole tree, so
+ the other call's output was advertised on this card and its download served
+ that content. No timestamps: a coarse or remote clock is exactly what this
+ cannot depend on."""
+ from core.inference import tools
+
+ workdir = tmp_path / "project-workspace"
+ workdir.mkdir()
+
+ theirs = tools._call_started(str(workdir)) # the other chat's call
+ try:
+ before = tools._snapshot_workdir_files(str(workdir))
+ ours = tools._call_started(str(workdir)) # ours starts while theirs runs
+ try:
+ (workdir / "theirs.csv").write_text("a,b\n", encoding = "utf-8")
+ sentinels = tools._created_file_sentinels(str(workdir), before, None, ours)
+ finally:
+ tools._call_finished(ours)
+ assert ours["shared"] is True
+ assert theirs["shared"] is True, "the call already running was not told"
+ finally:
+ tools._call_finished(theirs)
+
+ assert sentinels == "", sentinels
+
+ # Alone in the workdir, the same write is reported as before.
+ alone = tools._call_started(str(workdir))
+ try:
+ before = tools._snapshot_workdir_files(str(workdir))
+ (workdir / "ours.csv").write_text("a,b\n", encoding = "utf-8")
+ sentinels = tools._created_file_sentinels(str(workdir), before, None, alone)
+ finally:
+ tools._call_finished(alone)
+ assert "ours.csv" in sentinels, sentinels
+
+
+def test_a_read_serves_the_legacy_files_while_the_move_is_still_running(tmp_path, monkeypatch):
+ """The move runs in the background and across filesystems takes minutes, and
+ a pass that fails leaves the files there for the rest of the process."""
+ fake_home = tmp_path / "userprofile"
+ session = "__LOCALID_slow111"
+ legacy = fake_home / "studio_sandbox" / session
+ legacy.mkdir(parents = True)
+ (legacy / "plot.png").write_bytes(b"png")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+
+ served = Path(tools.resolve_sandbox_workdir(session))
+ assert (served / "plot.png").is_file(), f"the card 404s until a later tool call: {served}"
+ # And nothing was created at the new root by the read.
+ assert not (Path(tools.sandbox_root()) / session).exists()
+
+
+def test_a_case_variant_id_cannot_delete_a_markerless_sandbox(tmp_path, monkeypatch):
+ """On Windows and a default macOS volume `Foo` and `foo` are one directory,
+ and with the marker gone the default root said yes to either."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ workdir = Path(tools.get_sandbox_workdir("Foo_chat1"))
+ (workdir / "notes.txt").write_text("theirs", encoding = "utf-8")
+ (workdir / tools._SANDBOX_MARKER).unlink() # a tool wrote over it
+ _forget_sandbox_state(tools)
+
+ # This host is case-sensitive, so the volume that folds the two names is
+ # modelled where the folding happens: both ids resolve to the one directory.
+ real_session_dir = tools._session_dir
+ monkeypatch.setattr(
+ tools,
+ "_session_dir",
+ lambda root, session_id: (
+ str(workdir)
+ if session_id.casefold() == "foo_chat1"
+ else real_session_dir(root, session_id)
+ ),
+ )
+
+ assert tools.remove_session_sandbox("foo_chat1", delete_files = True) is False
+ assert (workdir / "notes.txt").is_file(), "deleted another chat's files"
+ # Its own id still reaches it.
+ assert tools.remove_session_sandbox("Foo_chat1", delete_files = True) is True
+
+
+def test_a_delete_moves_only_its_own_session_up(tmp_path, monkeypatch):
+ """The whole-tree pass is a cross-filesystem copy of every chat, and the
+ delete used to sit behind it before its response could go out."""
+ fake_home = tmp_path / "userprofile"
+ legacy_root = fake_home / "studio_sandbox"
+ session = "__LOCALID_quick11"
+ (legacy_root / session).mkdir(parents = True)
+ (legacy_root / session / "mine.txt").write_text("x", encoding = "utf-8")
+ for other in range(3):
+ (legacy_root / f"__LOCALID_other{other}").mkdir()
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+ monkeypatch.setattr(tools, "_start_legacy_migration", lambda: None)
+ whole_tree = []
+ monkeypatch.setattr(tools, "_migrate_legacy_sandbox", lambda root: whole_tree.append(root))
+
+ tools.remove_session_sandbox(session, delete_files = True)
+
+ assert whole_tree == [], "the delete waited for every other chat to move"
+ assert not (legacy_root / session).exists(), "its own files were left behind"
+ for other in range(3):
+ assert (legacy_root / f"__LOCALID_other{other}").is_dir()
+
+
+def test_a_deferred_removal_runs_outside_the_global_lock(tmp_path, monkeypatch):
+ """It walks the tree to decide whether to keep the files, and every tool
+ call in every other chat waits on that lock to start."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_defer11"
+ tools.get_sandbox_workdir(session)
+
+ held = []
+
+ def slow_remove(session_id, delete_files):
+ held.append(tools._active_sessions_lock.acquire(blocking = False))
+ if held[-1]:
+ tools._active_sessions_lock.release()
+ return True
+
+ monkeypatch.setattr(tools, "_remove_session_sandbox_locked", slow_remove)
+ with tools._session_in_flight(session):
+ tools.remove_session_sandbox(session, delete_files = True)
+
+ assert held == [True], "the removal ran while holding the global lock"
+
+
+def test_only_the_sandbox_tools_have_their_file_line_read(tmp_path):
+ """An MCP tool or a fetched page can legitimately end in a well-formed
+ __FILES__ line, and stripping it takes that content from the model."""
+ from core.inference.tool_loop_controller import strip_result_for_model
+
+ printed = 'here is the manifest\n__FILES__:[{"name": "report.csv", "size": 1}]'
+
+ assert "__FILES__" not in strip_result_for_model(printed, "python")
+ assert "__FILES__" not in strip_result_for_model(printed, "terminal")
+ assert strip_result_for_model(printed, "mcp__files__list") == printed
+ assert strip_result_for_model(printed, "web_search") == printed
+
+
+def test_a_migration_that_could_not_move_in_is_adopted(tmp_path, monkeypatch):
+ """The rename failed after the tree had already moved, so the marked
+ staging directory is the only copy of the user's files there is."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_stage11"
+ root = Path(tools.sandbox_root())
+ root.mkdir(parents = True, exist_ok = True)
+ stranded = root / f"{session}{tools._STAGING_SUFFIX}0123abcd"
+ stranded.mkdir()
+ (stranded / "thesis.txt").write_text("years of work", encoding = "utf-8")
+ tools._mark_sandbox(str(stranded), session)
+
+ served = Path(tools.resolve_sandbox_workdir(session))
+ assert (served / "thesis.txt").is_file(), f"the only copy was unreachable: {served}"
+
+ workdir = Path(tools.get_sandbox_workdir(session))
+ assert (workdir / "thesis.txt").is_file(), "the next tool call started in an empty folder"
+
+
+def test_bulk_deletes_share_one_sweeper(tmp_path, monkeypatch):
+ """A clear-all can hand over every chat at once, and a thread with a
+ recursive walk per chat is what exhausts the process."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ started = []
+ real_thread = threading.Thread
+
+ class CountingThread(real_thread):
+ def start(self):
+ started.append(self.name)
+ super().start()
+
+ monkeypatch.setattr(threading, "Thread", CountingThread)
+ monkeypatch.setattr(tools.threading, "Thread", CountingThread)
+ tools._delete_worker = None
+
+ for i in range(12):
+ session = f"__LOCALID_bulk{i:03d}"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "out.csv").write_text("a,b\n", encoding = "utf-8")
+ assert tools.remove_session_sandbox(session, delete_files = True) is True
+
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ if not any(name.startswith(f"__LOCALID_bulk") for name in os.listdir(tools.sandbox_root())):
+ break
+ time.sleep(0.05)
+
+ assert started.count("sandbox-delete") == 1, started
+ for i in range(12):
+ assert not (Path(tools.sandbox_root()) / f"__LOCALID_bulk{i:03d}").exists()
+
+
+def test_one_chats_legacy_copy_does_not_hold_up_another(tmp_path, monkeypatch):
+ """A single lock around every move meant a first tool call in one chat sat
+ behind a multi-gigabyte copy belonging to a different one."""
+ fake_home = tmp_path / "userprofile"
+ legacy_root = fake_home / "studio_sandbox"
+ for name in ("__LOCALID_huge111", "__LOCALID_tiny111"):
+ (legacy_root / name).mkdir(parents = True)
+ (legacy_root / name / "data.bin").write_bytes(b"x")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+ getattr(tools, "_legacy_session_locks", {}).clear()
+
+ started = threading.Event()
+ release = threading.Event()
+ real_move = tools._staged_move
+
+ def slow_move(source, target, name):
+ if "huge" in name:
+ started.set()
+ assert release.wait(timeout = 5)
+ return real_move(source, target, name)
+
+ monkeypatch.setattr(tools, "_staged_move", slow_move)
+
+ big = threading.Thread(
+ target = tools._migrate_one_legacy_session,
+ args = (tools.sandbox_root(), "__LOCALID_huge111"),
+ )
+ big.start()
+ try:
+ assert started.wait(timeout = 5)
+ small = threading.Thread(
+ target = tools._migrate_one_legacy_session,
+ args = (tools.sandbox_root(), "__LOCALID_tiny111"),
+ )
+ small.start()
+ small.join(timeout = 5)
+ assert not small.is_alive(), "the small chat waited on the big chat's copy"
+ assert (Path(tools.sandbox_root()) / "__LOCALID_tiny111" / "data.bin").is_file()
+ finally:
+ release.set()
+ big.join(timeout = 5)
+
+
+def test_an_absolute_session_id_cannot_reach_outside_the_sentinel(tmp_path, monkeypatch):
+ """The id comes straight from the query, and os.path.join drops the root it
+ is given when the second half is absolute."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._NOTHING_ROOT = None
+
+ for hostile in ("/etc", "/", os.path.join("..", "..", "etc")):
+ resolved = Path(tools._nothing_to_serve(hostile))
+ assert not (resolved / "passwd").exists(), resolved
+ assert str(resolved).startswith(tempfile.gettempdir()), resolved
+
+ # And through the resolver, which is what the download route asks.
+ session = "/etc"
+ theirs = root / tools._sandbox_name(session)
+ theirs.mkdir()
+ served = Path(tools.resolve_sandbox_workdir(session))
+ assert not str(served).startswith("/etc"), served
+ assert str(served) != "/", served
+
+
+def test_a_legacy_copy_of_a_folder_we_already_moved_is_left_alone(tmp_path, monkeypatch):
+ """The destination already carries this chat's marker from an earlier move,
+ so a second one would take the old copy somewhere nothing resolves to."""
+ fake_home = tmp_path / "userprofile"
+ session = "__LOCALID_twice11"
+ legacy = fake_home / "studio_sandbox" / session
+ legacy.mkdir(parents = True)
+ (legacy / "old.csv").write_text("old", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+ getattr(tools, "_legacy_session_locks", {}).clear()
+ # What an earlier move left: the destination, marked, already in place.
+ moved = root / session
+ moved.mkdir()
+ (moved / "new.csv").write_text("new", encoding = "utf-8")
+ tools._mark_sandbox(str(moved), session)
+
+ tools._migrate_one_legacy_session(str(root), session)
+
+ assert (legacy / "old.csv").is_file(), "the legacy copy went somewhere unreachable"
+ assert Path(tools.resolve_sandbox_workdir(session)) == moved
+ assert len(list(root.iterdir())) == 1, list(root.iterdir())
+
+
+def test_an_interrupted_delete_is_swept_even_without_its_marker(tmp_path, monkeypatch):
+ """A tool can remove the marker before the delete, and nothing but this code
+ names a directory that way in our own root."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ root = Path(tools.sandbox_root())
+ root.mkdir(parents = True, exist_ok = True)
+ tombstone = root / f"__LOCALID_gone222{tools._DETACHED_SUFFIX}0123abcd"
+ tombstone.mkdir()
+ (tombstone / "big.bin").write_bytes(b"x" * 16)
+
+ tools.sweep_detached_sandboxes(str(root))
+ assert not tombstone.exists(), "an unreachable tree was left on disk for good"
+
+
+def test_the_startup_pass_lands_a_chat_whose_names_are_taken(tmp_path, monkeypatch):
+ """It skipped the collision and still reported itself complete, which turns
+ off both legacy reads and the per-session retry: those files are gone."""
+ fake_home = tmp_path / "userprofile"
+ session = "__LOCALID_startup1"
+ legacy = fake_home / "studio_sandbox" / session
+ legacy.mkdir(parents = True)
+ (legacy / "notes.csv").write_text("a,b\n", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+ for taken in (root / session, root / f"{session}-{tools._name_suffix(session)}"):
+ taken.mkdir()
+ (taken / "theirs.txt").write_text("mine", encoding = "utf-8")
+
+ tools._migrate_legacy_sandbox(str(root))
+
+ assert tools._legacy_sandbox_migrated is True
+ landed = Path(tools.resolve_sandbox_workdir(session))
+ assert (landed / "notes.csv").is_file(), f"the chat's files were stranded: {landed}"
+
+
+def test_a_fallback_is_found_in_a_root_full_of_other_folders(tmp_path, monkeypatch):
+ """The scan is bounded and sorted, so a big enough root hid the fallback and
+ the next launch made another one beside it."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "zz_LOCALID_late11"
+ name = tools._sandbox_name(session)
+ for taken in (root / name, root / f"{name}-{tools._name_suffix(session)}"):
+ taken.mkdir()
+
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ # Everything the scan would reach before this chat's own folder.
+ monkeypatch.setattr(tools, "_MAX_SNAPSHOT_DIRS", 4)
+ for i in range(40):
+ (root / f"aaa{i:03d}").mkdir()
+
+ _forget_sandbox_state(tools)
+ assert Path(tools.resolve_sandbox_workdir(session)) == workdir
+ assert Path(tools.get_sandbox_workdir(session)) == workdir
+ assert tools.remove_session_sandbox(session, delete_files = True) is True
+
+
+def test_a_staged_move_is_marked_before_the_rename(tmp_path, monkeypatch):
+ """Across filesystems the move has already removed the legacy copy, so a
+ kill before the marker leaves the only copy unfindable."""
+ fake_home = tmp_path / "userprofile"
+ session = "__LOCALID_kill111"
+ legacy = fake_home / "studio_sandbox" / session
+ legacy.mkdir(parents = True)
+ (legacy / "thesis.txt").write_text("years of work", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ root = Path(tools.sandbox_root())
+ root.mkdir(parents = True, exist_ok = True)
+
+ class Killed(RuntimeError):
+ pass
+
+ real_rename = os.rename
+
+ def killed_rename(src, dst):
+ # Only the staging-to-target step: shutil.move uses rename to get there.
+ if tools._STAGING_SUFFIX in str(dst):
+ return real_rename(src, dst)
+ raise Killed("the process went away here")
+
+ monkeypatch.setattr(os, "rename", killed_rename)
+ with pytest.raises(Killed):
+ tools._staged_move(str(legacy), str(root / session), session)
+ monkeypatch.undo()
+
+ staged = [p for p in root.iterdir() if tools._STAGING_SUFFIX in p.name]
+ assert staged, "the tree vanished"
+ assert tools._marker_owner(str(staged[0])) == tools._sandbox_name(session)
+
+
+def test_a_delete_finds_the_folder_this_run_made(tmp_path, monkeypatch):
+ """A tool can remove the marker, and after that neither name resolves to the
+ directory: the delete left it behind without even saying it kept anything."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_cache11"
+ (root / tools._sandbox_name(session)).mkdir() # the user's, so we fall back
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ (workdir / tools._SANDBOX_MARKER).unlink()
+
+ assert tools.session_sandbox_has_files(session) is True # this run made it
+ assert tools.remove_session_sandbox(session, delete_files = True) is True
+ assert not workdir.exists(), "the folder was left behind with nobody able to reach it"
+
+
+def test_a_chat_moved_out_of_a_project_survives_its_deletion():
+ """The transaction decides membership, and an earlier listing would have
+ stopped that chat's generation and deleted the files it wrote."""
+ import inspect
+
+ from routes import chat_history
+
+ route = inspect.getsource(chat_history.delete_project)
+ assert "list_chat_threads(project_id" not in route
+ assert 'member_ids = list(project.get("memberIds") or [])' in route
+ assert route.index("delete_chat_project(") < route.index("member_ids = list(")
+
+
+def test_the_client_reads_the_file_line_only_from_the_sandbox_tools():
+ """An MCP tool or a fetched page ending in that line is content, and the
+ card it produced pointed at a file nobody wrote."""
+ src = Path(__file__).resolve().parents[2] / "frontend/src"
+
+ files = (src / "components/assistant-ui/sandbox-files.ts").read_text(encoding = "utf-8")
+ assert "SANDBOX_FILE_TOOLS" in files
+ assert '"python", "terminal"' in files
+
+ adapter = (src / "features/chat/api/chat-adapter.ts").read_text(encoding = "utf-8")
+ guarded = adapter[adapter.index("const rawEvent = (toolEvent.result as string)") :]
+ guarded = guarded[: guarded.index("const imgMarker")]
+ assert "SANDBOX_FILE_TOOLS.has(" in guarded
+ assert guarded.index("SANDBOX_FILE_TOOLS.has(") < guarded.index("extractCreatedFiles(")
+
+
+def test_the_old_shared_bucket_is_read_but_never_moved(tmp_path, monkeypatch):
+ """Before this change every id the filesystem could not hold shared one
+ directory, so it belongs to no single chat and must not travel as one."""
+ fake_home = tmp_path / "userprofile"
+ bucket = fake_home / "studio_sandbox" / "_invalid"
+ bucket.mkdir(parents = True)
+ (bucket / "old.csv").write_text("a,b\n", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+ session = "client.v1" # what the old regex rejected
+ assert tools._usable_session_id(session) is False
+
+ served = Path(tools.resolve_sandbox_workdir(session))
+ assert (served / "old.csv").is_file(), f"the chat lost its files: {served}"
+
+ tools._migrate_legacy_sandbox(tools.sandbox_root())
+ assert (bucket / "old.csv").is_file(), "a shared bucket was moved as one chat's"
+ assert not (Path(tools.sandbox_root()) / "_invalid").exists()
+ # And still readable once the pass has run.
+ assert (Path(tools.resolve_sandbox_workdir(session)) / "old.csv").is_file()
+
+
+def test_a_chat_cannot_claim_another_chats_directory(tmp_path, monkeypatch):
+ """Tool code runs inside the sandbox and can write anything into the marker,
+ so adopting on the marker alone hands one chat another chat's files."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ attacker, victim = "__LOCALID_aaa1111", "__LOCALID_bbb2222"
+ theirs = Path(tools.get_sandbox_workdir(attacker))
+ (theirs / "private.csv").write_text("the attacker's own", encoding = "utf-8")
+ # What a tool running in there can do.
+ (theirs / tools._SANDBOX_MARKER).write_text(
+ tools._sandbox_name(victim),
+ encoding = "utf-8",
+ )
+
+ _forget_sandbox_state(tools)
+ landed = Path(tools.get_sandbox_workdir(victim))
+ assert landed != theirs, "one chat was handed another chat's directory"
+ assert not (landed / "private.csv").exists()
+ assert theirs.is_dir(), "and the other chat's folder was taken from it"
+
+
+def test_a_users_own_marker_file_survives_the_migration(tmp_path, monkeypatch):
+ """The name was not reserved before this change, so a chat that wrote its
+ own .unsloth_sandbox has a real file there."""
+ fake_home = tmp_path / "userprofile"
+ session = "__LOCALID_marker1"
+ legacy = fake_home / "studio_sandbox" / session
+ legacy.mkdir(parents = True)
+ (legacy / ".unsloth_sandbox").write_text("notes the user wrote", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+
+ landed = Path(tools.get_sandbox_workdir(session))
+ saved = list(landed.glob(".unsloth_sandbox.saved*"))
+ assert saved, sorted(p.name for p in landed.iterdir())
+ assert saved[0].read_text(encoding = "utf-8") == "notes the user wrote"
+ assert tools._marker_owner(str(landed)) == tools._sandbox_name(session)
+
+
+def test_a_project_workspace_goes_after_its_tools_are_stopped():
+ """The member chats' calls run with their cwd in there, and pulling it out
+ from under a live subprocess strands whatever it writes next."""
+ import inspect
+
+ from routes import chat_history
+
+ route = inspect.getsource(chat_history.delete_project)
+ assert "delete_chat_project(project_id, delete_files = False)" in route
+ assert route.index("_cancel_active_generations(member_ids)") < route.index(
+ "delete_project_workspace"
+ )
+
+
+def test_a_forked_chat_keeps_the_files_its_cards_point_at(tmp_path, monkeypatch):
+ """Forking clones the message content verbatim, so the fork's cards still
+ name the source chat's sandbox."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from routes import chat_history
+
+ _forget_sandbox_state(tools)
+ source = "__LOCALID_source1"
+ workdir = Path(tools.get_sandbox_workdir(source))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ import storage.studio_db as studio_db
+
+ monkeypatch.setattr(
+ studio_db, "sandbox_is_referenced_elsewhere", lambda session_id: session_id == source
+ )
+
+ removed, kept = asyncio.new_event_loop().run_until_complete(
+ chat_history._remove_sandboxes([source], True)
+ )
+
+ assert removed == 0, removed
+ assert kept == [source], kept
+ assert (workdir / "report.csv").is_file(), "a surviving fork's cards now 404"
+
+
+def test_the_research_loop_keeps_a_pages_file_line():
+ """The persisted excerpt is what a resumed run reads back, and a fetched
+ page ending in that line is content, not an envelope."""
+ import inspect
+
+ from core import research_runs
+
+ source = inspect.getsource(research_runs)
+ assert "strip_result_for_model(result)" not in source
+ assert source.count('strip_result_for_model(result, "web_search")') == 2
+
+
+def test_a_workspace_delete_waits_for_the_tool_calls_in_it(tmp_path, monkeypatch):
+ """Cancelling only asks. A call already in the executor still has its cwd
+ in there, and removing it underneath strands whatever it writes next."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "project-abc123"
+ assert tools.project_session_id("abc123") == session
+
+ with tools._session_in_flight(session):
+ assert tools.wait_for_sessions_idle([session], timeout = 0.2) is False
+ assert tools.wait_for_sessions_idle([session], timeout = 0.2) is True
+
+ import inspect
+
+ from routes import chat_history
+
+ route = inspect.getsource(chat_history.delete_project)
+ assert route.index("run_in_threadpool(wait_for_sessions_idle") < route.index(
+ "run_in_threadpool(delete_project_workspace, project)"
+ )
+
+
+def test_a_reference_is_a_session_id_not_a_piece_of_prose(tmp_path, monkeypatch):
+ """A short id matches ordinary text, and an id JSON has to escape does not
+ match itself: one keeps a sandbox for ever, the other deletes a live one."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from storage import studio_db
+
+ studio_db.upsert_chat_thread(
+ {
+ "id": "keeper",
+ "title": "t",
+ "modelType": "local",
+ "modelId": "m",
+ "createdAt": 1,
+ "updatedAt": 1,
+ }
+ )
+ quoted = 'client"v1'
+ studio_db.upsert_chat_message(
+ {
+ "id": "m1",
+ "threadId": "keeper",
+ "role": "assistant",
+ "content": [{"type": "text", "sessionId": quoted}],
+ "createdAt": 1,
+ }
+ )
+ studio_db.upsert_chat_message(
+ {
+ "id": "m2",
+ "threadId": "keeper",
+ "role": "assistant",
+ "content": [{"type": "text", "text": "the report is in chat abc"}],
+ "createdAt": 2,
+ }
+ )
+
+ # The escaped id is found ...
+ assert studio_db.sandbox_is_referenced_elsewhere(quoted) is True
+ # ... and a short id that only appears inside prose is not.
+ assert studio_db.sandbox_is_referenced_elsewhere("abc") is False
+
+
+def test_a_project_workspace_a_fork_still_shows_is_kept():
+ """A chat forked out of the project keeps cards for the shared workspace,
+ and it is not one of the ids the project delete removes."""
+ import inspect
+
+ from routes import chat_history
+
+ route = inspect.getsource(chat_history.delete_project)
+ assert "project_session_id(project_id)" in route
+ assert "sandbox_is_referenced_elsewhere, shared" in route
+ assert route.index("sandbox_is_referenced_elsewhere, shared") < route.index(
+ "run_in_threadpool(delete_project_workspace, project)"
+ )
+
+
+def test_a_project_delete_cancels_the_research_it_removed():
+ """The rows cascade with the threads, so after the transaction there is
+ nothing left to look the runs up by."""
+ import inspect
+
+ from routes import chat_history
+ from storage import studio_db
+
+ storage = inspect.getsource(studio_db.delete_chat_project)
+ assert 'project["activeResearchRunIds"] = active_runs' in storage
+ assert storage.index("SELECT id FROM research_runs") < storage.index("DELETE FROM chat_threads")
+
+ route = inspect.getsource(chat_history.delete_project)
+ assert '_cancel_research_runs(request, list(project.get("activeResearchRunIds")' in route
+ assert "_cancel_active_research(request, member_ids)" not in route
+
+
+def test_the_wait_covers_the_session_a_project_tool_runs_as():
+ """A tool call in a project runs as project-<id>, not as the chat, so
+ waiting on the member ids returned at once and the cwd went underneath."""
+ import inspect
+
+ from routes import chat_history
+
+ route = inspect.getsource(chat_history.delete_project)
+ assert "wait_for_sessions_idle, [shared, *member_ids]" in route
+ assert route.index("shared = project_session_id(project_id)") < route.index(
+ "run_in_threadpool(wait_for_sessions_idle"
+ )
+
+
+def test_a_new_call_cannot_start_in_a_sandbox_being_removed(tmp_path, monkeypatch):
+ """The deferred removal runs with the lock released, and a call starting in
+ that window was handed the directory the removal then renamed away."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_race111"
+ tools.get_sandbox_workdir(session)
+
+ queued, proceed = threading.Event(), threading.Event()
+ removing, release, started = threading.Event(), threading.Event(), threading.Event()
+ real_remove = tools._remove_session_sandbox_locked
+
+ def slow_remove(session_id, delete_files):
+ removing.set()
+ assert release.wait(timeout = 5)
+ return real_remove(session_id, delete_files)
+
+ monkeypatch.setattr(tools, "_remove_session_sandbox_locked", slow_remove)
+
+ def first_call():
+ with tools._session_in_flight(session):
+ queued.set()
+ assert proceed.wait(timeout = 5)
+ # The queued removal runs as this call leaves.
+
+ def second_call():
+ with tools._session_in_flight(session):
+ started.set()
+
+ first = threading.Thread(target = first_call)
+ first.start()
+ try:
+ assert queued.wait(timeout = 5)
+ assert tools.remove_session_sandbox(session, delete_files = True) is False
+ proceed.set()
+ assert removing.wait(timeout = 5), "the deferred removal never ran"
+
+ second = threading.Thread(target = second_call)
+ second.start()
+ assert not started.wait(timeout = 0.5), "a call started in the folder being removed"
+ release.set()
+ second.join(timeout = 5)
+ assert started.is_set(), "and it never got to start afterwards"
+ finally:
+ release.set()
+ proceed.set()
+ first.join(timeout = 5)
+
+
+def test_a_note_named_like_the_marker_is_kept(tmp_path, monkeypatch):
+ """A short note reads as a perfectly good session name, and the migration
+ was treating anything that parses as its own metadata."""
+ fake_home = tmp_path / "userprofile"
+ session = "__LOCALID_notes11"
+ legacy = fake_home / "studio_sandbox" / session
+ legacy.mkdir(parents = True)
+ (legacy / ".unsloth_sandbox").write_text("notes", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+
+ landed = Path(tools.get_sandbox_workdir(session))
+ saved = list(landed.glob(".unsloth_sandbox.saved*"))
+ assert saved, sorted(p.name for p in landed.iterdir())
+ assert saved[0].read_text(encoding = "utf-8") == "notes"
+ assert tools._marker_owner(str(landed)) == tools._sandbox_name(session)
+
+
+def test_a_kept_project_workspace_still_resolves(tmp_path, monkeypatch):
+ """It is kept because a chat forked out of the project still shows its
+ cards, and those cards resolve through the project row that is now gone."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))
+
+ from core.inference import tools
+ from utils.paths import project_workspaces_root
+
+ _forget_sandbox_state(tools)
+ project_id = "proj12345"
+ suffix = project_id[:8]
+ workspace = Path(project_workspaces_root()) / f"My Notes-{suffix}" / "sandbox"
+ workspace.mkdir(parents = True)
+ (workspace / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ # No project row: the delete removed it and kept the files.
+ served = Path(tools.resolve_sandbox_workdir(tools.project_session_id(project_id)))
+ assert served == workspace.resolve(), served
+ assert (served / "report.csv").is_file()
+
+
+def test_clearing_every_chat_cancels_the_research_it_removed():
+ """The runs cascade with the threads, so afterwards there is nothing left
+ to look them up by and the worker keeps going."""
+ import inspect
+
+ from routes import chat_history
+ from storage import studio_db
+
+ storage = inspect.getsource(studio_db.clear_chat_history)
+ assert "SELECT id FROM research_runs" in storage
+ assert storage.index("SELECT id FROM research_runs") < storage.index("DELETE FROM chat_threads")
+
+ route = inspect.getsource(chat_history.clear_history)
+ assert "_cancel_research_runs(request, cleared_runs)" in route
+
+
+def test_the_supervisor_is_told_even_with_no_row_left():
+ """request_cancel raises KeyError once the row has cascaded, and that used
+ to skip the one call that actually stops the worker."""
+ import inspect
+
+ from routes import chat_history
+
+ source = inspect.getsource(chat_history._cancel_research_runs)
+ assert source.index("supervisor.cancel(run_id)") < source.index(
+ "research_runs_db.request_cancel(run_id)"
+ )
+
+
+def test_a_workspace_is_kept_when_the_wait_ran_out():
+ """The bound exists so the request cannot hang, and past it the tool call
+ is still there: removing its working directory is the worse outcome."""
+ import inspect
+
+ from routes import chat_history
+
+ route = inspect.getsource(chat_history.delete_project)
+ assert "run_in_threadpool(wait_for_sessions_idle, [shared, *member_ids])" in route
+ assert "if delete_files and idle and not referenced and not recreated:" in route
+ assert route.index(
+ "if delete_files and idle and not referenced and not recreated:"
+ ) < route.index("run_in_threadpool(delete_project_workspace, project)")
+ # And a wait that ran out queues the finish rather than dropping it.
+ assert "finish_workspace_delete_when_idle(project_id)" in route
+
+
+def test_a_kept_workspace_the_user_moved_still_resolves(tmp_path, monkeypatch):
+ """A custom rootPath is not derivable from the id, and the row that knew it
+ is what the delete just removed."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ project_id = "proj98765"
+ custom = tmp_path / "somewhere" / "of the user's" / "sandbox"
+ custom.mkdir(parents = True)
+ (custom / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ tools.record_orphaned_project(project_id, str(custom))
+ served = Path(tools.resolve_sandbox_workdir(tools.project_session_id(project_id)))
+ assert served == custom.resolve(), served
+ assert (served / "report.csv").is_file()
+
+ # And the record goes when the folder does.
+ shutil.rmtree(custom)
+ assert tools.list_orphaned_projects() == []
+
+
+def test_the_last_fork_going_takes_the_kept_workspace(tmp_path, monkeypatch):
+ """The user asked for the files on both surfaces, and nothing else would
+ ever come back to that workspace."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from routes import chat_history
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ project_id = "proj55555"
+ workspace = tmp_path / "Notes-proj5555"
+ (workspace / "sandbox").mkdir(parents = True)
+ (workspace / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ tools.record_orphaned_project(
+ project_id,
+ str(workspace / "sandbox"),
+ True,
+ str(workspace),
+ )
+
+ # While a fork still shows it, the collection leaves it alone.
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: True)
+ asyncio.new_event_loop().run_until_complete(chat_history._remove_sandboxes([], True))
+ assert (workspace / "report.csv").is_file()
+
+ # Once that fork is deleted too, it goes.
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+ asyncio.new_event_loop().run_until_complete(chat_history._remove_sandboxes([], True))
+ assert not workspace.exists(), "the workspace was orphaned for good"
+ assert tools.list_orphaned_projects() == []
+
+
+def test_a_tool_renaming_the_marker_does_not_move_the_chat(tmp_path, monkeypatch):
+ """A valid-looking id in that file is still something a tool wrote, and the
+ chat abandoning its own directory strands what the same call just made."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_owned11"
+ (root / tools._sandbox_name(session)).mkdir() # the user's, so we fall back
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "plot.png").write_bytes(b"x")
+ (workdir / tools._SANDBOX_MARKER).write_text("notes", encoding = "utf-8")
+
+ again = Path(tools.get_sandbox_workdir(session))
+ assert again == workdir, "the chat walked away from the files it just wrote"
+ assert tools._marker_owner(str(workdir)) == tools._sandbox_name(session)
+ saved = list(workdir.glob(".unsloth_sandbox.saved*"))
+ assert saved and saved[0].read_text(encoding = "utf-8") == "notes"
+
+
+def test_an_empty_sandbox_scan_does_not_hold_the_global_lock(tmp_path, monkeypatch):
+ """It walks up to 2,000 directories to decide, and every unrelated chat
+ waits on that lock to start a tool call."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_scan111"
+ tools.get_sandbox_workdir(session)
+
+ held = []
+
+ def slow_scan(target, owner = None):
+ held.append(tools._active_sessions_lock.acquire(blocking = False))
+ if held[-1]:
+ tools._active_sessions_lock.release()
+ return True
+
+ monkeypatch.setattr(tools, "_holds_no_user_files", slow_scan)
+ tools.remove_session_sandbox(session, delete_files = False)
+
+ assert held == [True], "the scan ran while holding the global lock"
+
+
+def test_a_cache_directory_needs_a_generated_file_not_a_name(tmp_path, monkeypatch):
+ """The directory is prepended to sys.path for every worker, so a folder
+ that merely carries the name lets anything beside it shadow a real module."""
+ from utils import cache_cleanup
+
+ candidate = tmp_path / "unsloth_compiled_cache"
+ (candidate / "unsloth_compiled_module_fake.py").mkdir(parents = True)
+ (candidate / "numpy.py").write_text("raise SystemExit", encoding = "utf-8")
+
+ assert cache_cleanup._holds_generated_modules(candidate) is False
+
+ (candidate / "unsloth_compiled_module_real.py").write_text("x = 1", encoding = "utf-8")
+ assert cache_cleanup._holds_generated_modules(candidate) is True
+
+
+def test_a_kept_workspace_is_recorded_even_when_nothing_was_deleted():
+ """The row that held a custom path is gone either way, and a fork's cards
+ still name that session."""
+ import inspect
+
+ from routes import chat_history
+
+ route = inspect.getsource(chat_history.delete_project)
+ assert 'if project.get("sandboxPath"):' in route
+ assert "if not delete_files:" in route
+ body = route[route.index("if not delete_files:") :]
+ assert "record_orphaned_project," in body[:400]
+ assert "False," in body[:400], "a keep must not be recorded as pending deletion"
+
+
+def test_only_a_pending_record_is_ever_collected(tmp_path, monkeypatch):
+ """One written down so a fork's cards resolve is not something anybody
+ asked to delete."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+
+ keep, go = tmp_path / "Keep-projkeep", tmp_path / "Go-projgone"
+ (keep / "sandbox").mkdir(parents = True)
+ (go / "sandbox").mkdir(parents = True)
+ tools.record_orphaned_project("projkeep1", str(keep / "sandbox"), False, str(keep))
+ tools.record_orphaned_project("projgone1", str(go / "sandbox"), True, str(go))
+
+ tools.collect_orphaned_project_workspaces()
+
+ assert keep.is_dir(), "deleted a workspace the user kept"
+ assert not go.exists(), "left one the user asked to delete"
+
+
+def test_a_workspace_delete_finishes_once_the_tool_call_ends(tmp_path, monkeypatch):
+ """Past the wait the delete dialog's promise is still outstanding, and
+ nothing else would come back to it."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+
+ project_id = "projbusy1"
+ workspace = tmp_path / "Busy-projbusy"
+ (workspace / "sandbox").mkdir(parents = True)
+ (workspace / "out.csv").write_text("a,b\n", encoding = "utf-8")
+ tools.record_orphaned_project(
+ project_id,
+ str(workspace / "sandbox"),
+ True,
+ str(workspace),
+ )
+
+ with tools._session_in_flight(tools.project_session_id(project_id)):
+ # Still running: the collection must leave it alone ...
+ tools.collect_orphaned_project_workspaces()
+ assert workspace.is_dir()
+ finisher = tools.finish_workspace_delete_when_idle(project_id, timeout = 5.0)
+ time.sleep(0.2)
+ assert workspace.is_dir(), "removed a workspace a tool call was using"
+
+ finisher.join(timeout = 5)
+ assert not workspace.exists(), "the promise was never finished"
+ assert tools.list_orphaned_projects() == []
+
+
+def test_a_pending_workspace_is_collected_by_a_plain_delete(tmp_path, monkeypatch):
+ """The last chat referencing it can be deleted without the switch, and the
+ workspace the user already asked to delete would wait for ever."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from routes import chat_history
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+
+ workspace = tmp_path / "Promised-projplai"
+ (workspace / "sandbox").mkdir(parents = True)
+ (workspace / "out.csv").write_text("a,b\n", encoding = "utf-8")
+ tools.record_orphaned_project(
+ "projplain",
+ str(workspace / "sandbox"),
+ True,
+ str(workspace),
+ )
+
+ # The plain path, no switch.
+ asyncio.new_event_loop().run_until_complete(chat_history._remove_sandboxes([], False))
+
+ assert not workspace.exists(), "the promised delete never happened"
+
+
+def test_a_nested_file_named_like_the_marker_is_a_file(tmp_path, monkeypatch):
+ """Only the sandbox's own bookkeeping is hidden: a tool that wrote
+ archive/.unsloth_sandbox made an ordinary file."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "__LOCALID_nested1"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ before = tools._snapshot_workdir_files(str(workdir))
+ (workdir / "archive").mkdir()
+ (workdir / "archive" / tools._SANDBOX_MARKER).write_text("theirs", encoding = "utf-8")
+
+ sentinels = tools._created_file_sentinels(str(workdir), before)
+ assert "archive/.unsloth_sandbox" in sentinels, sentinels
+ # And the marker at the top is still hidden.
+ assert tools._SANDBOX_MARKER not in sentinels.replace("archive/.unsloth_sandbox", "")
+
+ listing = tools._snapshot_workdir_files(str(workdir))
+ assert "archive/.unsloth_sandbox" in listing
+ assert tools._SANDBOX_MARKER not in listing
+
+
+def test_the_listing_route_hides_the_same_names_as_the_snapshot():
+ """The two walks have to agree, or a card names a file the download route
+ refuses, or the other way round."""
+ import inspect
+
+ from routes import inference
+
+ source = inspect.getsource(inference._sandbox_listing_names)
+ assert "base == sandbox_dir and entry in _INTERNAL_SANDBOX_FILES" in source
+
+
+def test_the_orphan_records_live_under_the_studio_home(tmp_path, monkeypatch):
+ """A sandbox root an administrator created can sit in a directory nothing
+ else may write to, and the record would never be written."""
+ home = tmp_path / "home"
+ readonly_parent = tmp_path / "readonly"
+ sandbox = readonly_parent / "sandboxes"
+ sandbox.mkdir(parents = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(sandbox))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ records = Path(tools._orphan_records_dir())
+ assert str(records).startswith(str(home)), records
+
+ workspace = tmp_path / "workspace"
+ workspace.mkdir()
+ readonly_parent.chmod(0o500)
+ try:
+ tools.record_orphaned_project("projro123", str(workspace), True)
+ assert [name for name, *_rest in tools.list_orphaned_projects()] == ["projro123"]
+ finally:
+ readonly_parent.chmod(0o700)
+
+
+def test_an_image_below_a_subdirectory_keeps_its_separators():
+ """An encoded slash is refused by proxies before the route sees it, and the
+ file card for the same file uses a real one."""
+ view = (
+ Path(__file__).resolve().parents[2]
+ / "frontend/src/components/assistant-ui/python-tool-image-path.ts"
+ ).read_text(encoding = "utf-8")
+
+ assert "sandboxFilePath(sessionId, filename)" in view
+ assert "encodeURIComponent(filename)" not in view
+
+
+def test_an_ordinary_chat_never_reads_the_old_shared_bucket(tmp_path, monkeypatch):
+ """That bucket holds every rejected id's files, and an ordinary chat with
+ no legacy folder of its own was being handed all of them."""
+ fake_home = tmp_path / "userprofile"
+ bucket = fake_home / "studio_sandbox" / "_invalid"
+ bucket.mkdir(parents = True)
+ (bucket / "someone-elses.csv").write_text("private", encoding = "utf-8")
+
+ monkeypatch.setenv("HOME", str(fake_home))
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._legacy_sandbox_migrated = False
+
+ ordinary = "__LOCALID_plain11"
+ assert tools._usable_session_id(ordinary) is True
+ served = Path(tools.resolve_sandbox_workdir(ordinary))
+ assert not (served / "someone-elses.csv").exists(), served
+
+ # The chats that really did share it still see it.
+ rejected = "client.v1"
+ assert tools._usable_session_id(rejected) is False
+ served = Path(tools.resolve_sandbox_workdir(rejected))
+ assert (served / "someone-elses.csv").is_file()
+
+
+def test_a_case_variant_cannot_read_a_markerless_sandbox(tmp_path, monkeypatch):
+ """With the marker gone the name is the only evidence, and `Foo` and `foo`
+ are one directory on Windows and on a default macOS volume."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ workdir = Path(tools.get_sandbox_workdir("Bar_chat1"))
+ (workdir / "notes.txt").write_text("theirs", encoding = "utf-8")
+ (workdir / tools._SANDBOX_MARKER).unlink()
+
+ assert tools._owned_by_session(str(workdir), "Bar_chat1") is True
+ assert tools._owned_by_session(str(workdir), "bar_chat1") is False
+
+
+def test_a_failed_workspace_delete_stays_pending(tmp_path, monkeypatch):
+ """A locked file on Windows must not lose both the path and the fact that
+ the user asked for it."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+
+ workspace = tmp_path / "Stuck-projstuc"
+ (workspace / "sandbox").mkdir(parents = True)
+ (workspace / "locked.bin").write_bytes(b"x")
+ tools.record_orphaned_project(
+ "projstuck",
+ str(workspace / "sandbox"),
+ True,
+ str(workspace),
+ )
+
+ monkeypatch.setattr(studio_db.shutil, "rmtree", lambda *a, **k: None)
+ tools.collect_orphaned_project_workspaces()
+
+ assert workspace.is_dir()
+ assert [name for name, _p, _r, pending, _c in tools.list_orphaned_projects() if pending] == [
+ "projstuck"
+ ], "the record was forgotten with the workspace still there"
+
+ monkeypatch.undo()
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ tools.collect_orphaned_project_workspaces()
+ assert not workspace.exists(), "the retry never happened"
+
+
+def test_a_deferred_delete_removes_the_whole_workspace(tmp_path, monkeypatch):
+ """The dialog offers the project workspace, and the sandbox is one folder
+ inside it: the immediate path removes the root, so this one must too."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+
+ project_id = "projwhole"
+ root = Path(tmp_path / "projects" / f"My Notes-{project_id[:8]}")
+ sandbox = root / "sandbox"
+ sandbox.mkdir(parents = True)
+ (sandbox / "out.csv").write_text("a,b\n", encoding = "utf-8")
+ (root / "notes.md").write_text("beside the sandbox", encoding = "utf-8")
+
+ tools.record_orphaned_project(project_id, str(sandbox), True, str(root))
+ tools.collect_orphaned_project_workspaces()
+
+ assert not root.exists(), sorted(p.name for p in root.iterdir()) if root.exists() else None
+
+
+def _deleted_project(tmp_path, monkeypatch, project_id, workspace):
+ """Drive delete_project for a project whose only member is itself."""
+ import asyncio
+
+ from routes import chat_history
+
+ project = {
+ "id": project_id,
+ "name": "Notes",
+ "createdAt": 1,
+ "updatedAt": 1,
+ "sandboxPath": str(workspace / "sandbox"),
+ "rootPath": str(workspace),
+ "memberIds": [],
+ "activeResearchRunIds": [],
+ }
+ monkeypatch.setattr(
+ chat_history, "delete_chat_project", lambda pid, delete_files: dict(project)
+ )
+ monkeypatch.setattr(chat_history, "_cancel_research_runs", lambda request, ids: None)
+ monkeypatch.setattr(chat_history, "_cancel_active_generations", lambda ids: None)
+ return asyncio.new_event_loop().run_until_complete(
+ chat_history.delete_project(
+ project_id,
+ request = None,
+ delete_files = True,
+ current_subject = "test",
+ )
+ )
+
+
+def test_a_workspace_delete_that_declined_can_still_be_retried(tmp_path, monkeypatch):
+ """The rows have gone by then, so a delete that stops at a locked file
+ leaves a workspace nothing names and no way to ask for it again."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ project_id = "proj31415"
+ workspace = tmp_path / "Notes-proj3141"
+ (workspace / "sandbox").mkdir(parents = True)
+ (workspace / "sandbox" / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ # The storage helper refuses anything it does not recognise, and a locked
+ # file leaves the tree behind the same way.
+ monkeypatch.setattr(studio_db, "delete_project_workspace", lambda project: None)
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+ _deleted_project(tmp_path, monkeypatch, project_id, workspace)
+
+ records = tools.list_orphaned_projects()
+ assert records == [
+ (
+ project_id,
+ str((workspace / "sandbox").resolve()),
+ str(workspace.resolve()),
+ True,
+ False,
+ )
+ ], records
+
+ # And the next collection finishes the job the user asked for.
+ monkeypatch.undo()
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+ tools.collect_orphaned_project_workspaces()
+ assert not workspace.exists()
+
+
+def test_a_half_deleted_workspace_keeps_its_record(tmp_path, monkeypatch):
+ """The sandbox went and something else in the workspace did not: dropping
+ the record here loses the path and the user's request with it."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ project_id = "proj27182"
+ workspace = tmp_path / "Notes-proj2718"
+ sandbox = workspace / "sandbox"
+ sandbox.mkdir(parents = True)
+ tools.record_orphaned_project(project_id, str(sandbox), True, str(workspace))
+
+ shutil.rmtree(sandbox)
+ (workspace / "datasets").mkdir()
+ records = tools.list_orphaned_projects()
+ assert [(r[0], r[3]) for r in records] == [(project_id, True)], records
+ # Nothing is served from a sandbox that is not there.
+ assert tools._recorded_project_workdir(project_id) is None
+
+ shutil.rmtree(workspace)
+ assert tools.list_orphaned_projects() == []
+
+
+def test_a_database_that_will_not_answer_keeps_the_files(monkeypatch):
+ """False reads as "no other chat shows these files" and the caller then
+ deletes them; a locked database is not that answer."""
+ import sqlite3
+
+ from storage import studio_db
+
+ class _Broken:
+ def execute(self, *args, **kwargs):
+ raise sqlite3.OperationalError("database is locked")
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(studio_db, "get_connection", lambda: _Broken())
+ assert studio_db.sandbox_is_referenced_elsewhere("thread-1") is True
+
+
+def test_the_default_sandbox_never_lands_in_a_directory_of_theirs(tmp_path, monkeypatch):
+ """A session-less call falls back to _default, and in a shared root both
+ that name and the derived one can already be the user's."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ (root / "_default").mkdir()
+ theirs = root / f"_default_{tools._name_suffix('_default')}"
+ theirs.mkdir()
+ (theirs / "thesis.tex").write_text("x", encoding = "utf-8")
+
+ workdir = Path(tools._sandbox_fallback(str(root), "_default", create = True))
+ assert workdir != theirs, "a tool call would have run in the user's directory"
+ assert tools._marker_owner(str(workdir)) == tools._sandbox_name("_default")
+ assert not (workdir / "thesis.tex").exists()
+ # And the read path finds the same one.
+ assert Path(tools._sandbox_fallback(str(root), "_default")) == workdir
+
+
+def test_the_default_sandbox_is_not_created_through_a_link(tmp_path, monkeypatch):
+ """makedirs(exist_ok) follows a directory symlink, and the marker and the
+ tool call would both land in whatever it points at."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ (root / "_default").mkdir()
+ outside = tmp_path / "elsewhere"
+ outside.mkdir()
+ (root / f"_default_{tools._name_suffix('_default')}").symlink_to(outside)
+
+ workdir = Path(tools._sandbox_fallback(str(root), "_default", create = True))
+ assert workdir.resolve() != outside.resolve(), "the call ran through the link"
+ assert not (outside / tools._SANDBOX_MARKER).exists()
+
+
+def test_a_sandbox_listing_does_not_resolve_on_the_event_loop(tmp_path, monkeypatch):
+ """Resolving scans the root and may read the legacy one: on a slow or
+ network filesystem that holds every other request."""
+ import asyncio
+ import threading
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from routes import inference
+
+ ran_on = []
+
+ def slow_resolve(session_id, create = False):
+ ran_on.append(threading.get_ident())
+ return str(tmp_path / "nowhere")
+
+ monkeypatch.setattr(inference, "_sandbox_dir_for", slow_resolve)
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+
+ loop_thread = threading.get_ident()
+ asyncio.new_event_loop().run_until_complete(
+ inference.list_sandbox_files("thread-1", request = None, token = None, session = None)
+ )
+ assert ran_on and loop_thread not in ran_on, "resolution ran on the event loop"
+
+
+def test_a_kept_sandbox_is_offered_even_when_deletion_was_asked_for():
+ """A sandbox the backend could not remove comes back as kept, and by then
+ the chat has gone: this offer is the only notice and the only retry."""
+ src = Path(__file__).resolve().parents[2] / "frontend/src"
+ for hook in (
+ "features/chat/hooks/use-chat-sidebar-items.ts",
+ "features/chat/hooks/use-chat-projects.ts",
+ ):
+ text = (src / hook).read_text(encoding = "utf-8")
+ assert "offerToDeleteKeptSandboxes(kept)" in text, hook
+ assert "!args.deleteFiles) offerToDeleteKeptSandboxes" not in text, hook
+
+
+async def _noop_async(*args, **kwargs):
+ return None
+
+
+def test_a_read_waits_for_the_move_of_the_tree_it_would_return(tmp_path, monkeypatch):
+ """Within one filesystem the move is a rename, so a legacy path handed back
+ while it runs lists nothing and 404s every card in the transcript."""
+ import threading
+
+ monkeypatch.setenv("HOME", str(tmp_path / "userprofile"))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "userprofile"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "chat-moving-1"
+ legacy = Path(tools._legacy_sandbox_root()) / session
+ legacy.mkdir(parents = True)
+ (legacy / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ started = threading.Event()
+ resolved = []
+
+ def mover():
+ with tools._legacy_lock_for(session):
+ started.set()
+ time.sleep(0.3) # the rename, from the reader's point of view
+ shutil.rmtree(legacy)
+
+ thread = threading.Thread(target = mover)
+ thread.start()
+ started.wait(5)
+
+ def reader():
+ resolved.append(tools._legacy_session_dir(session))
+
+ reading = threading.Thread(target = reader)
+ reading.start()
+ reading.join(10)
+ thread.join(10)
+
+ assert resolved == [None], f"a path in the middle of its move was served: {resolved}"
+
+
+def test_a_detached_tree_that_would_not_delete_is_retried(tmp_path, monkeypatch):
+ """ignore_errors leaves a locked file's tree behind, and the route has
+ already told the user those files went."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ monkeypatch.setattr(tools, "_DETACHED_RETRY_DELAY", 0.02)
+
+ target = tmp_path / "chat-1.deleting-abcdef12"
+ target.mkdir()
+ (target / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ real_rmtree = shutil.rmtree
+ attempts = []
+
+ def flaky(path, **kwargs):
+ attempts.append(str(path))
+ if len(attempts) == 1:
+ return # a file held open by a scanner, which ignore_errors swallows
+ real_rmtree(path, **kwargs)
+
+ monkeypatch.setattr(tools.shutil, "rmtree", flaky)
+ tools._queue_detached_delete(str(target))
+
+ deadline = time.time() + 10
+ while time.time() < deadline and target.exists():
+ time.sleep(0.05)
+ assert not target.exists(), f"the tree was left behind after {len(attempts)} attempt(s)"
+ assert len(attempts) >= 2
+
+
+def test_a_marker_a_tool_wrote_over_counts_as_the_user_s_file(tmp_path, monkeypatch):
+ """The name is not reserved on an old install, so that file can hold the
+ only copy of what a tool wrote, and this decides whether the tree goes."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "chat-marker-1"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ assert tools._holds_no_user_files(str(workdir), tools._sandbox_name(session)) is True
+
+ # A tool call writes its own content over the marker.
+ (workdir / tools._SANDBOX_MARKER).write_text("my notes", encoding = "utf-8")
+ assert tools._holds_no_user_files(str(workdir), tools._sandbox_name(session)) is False
+
+ # And a delete that was not asked to remove files keeps them. The delete
+ # repairs the marker on the way, so what the tool wrote is beside it.
+ assert tools.remove_session_sandbox(session, delete_files = False) is False
+ saved = list(workdir.glob(".unsloth_sandbox.saved*"))
+ assert saved and saved[0].read_text(encoding = "utf-8") == "my notes"
+ assert tools._holds_no_user_files(str(workdir), tools._sandbox_name(session)) is False
+
+
+def test_clearing_every_chat_builds_the_listed_set_once():
+ """It is event-loop code, and rebuilding the set per chat makes a clear of
+ a few thousand threads quadratic."""
+ import inspect
+
+ from routes import chat_history
+
+ route = inspect.getsource(chat_history.clear_history)
+ assert "listed = set(thread_ids)" in route
+ assert "not in set(thread_ids)" not in route
+
+
+def test_a_call_that_starts_during_the_snapshot_costs_the_card(tmp_path, monkeypatch):
+ """The walk takes as long as the directory is big, and a call starting
+ inside it writes files this one would then name and offer for download."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ workdir = str(tmp_path / "shared")
+ os.makedirs(workdir)
+ token = tools._call_started(workdir)
+ before = tools._snapshot_workdir_files(workdir)
+
+ real_snapshot = tools._snapshot_workdir_files
+
+ def snapshot_with_a_late_arrival(target):
+ # The other chat in this project starts its call while we walk.
+ tools._call_started(target)
+ Path(target, "theirs.csv").write_text("a,b\n", encoding = "utf-8")
+ return real_snapshot(target)
+
+ monkeypatch.setattr(tools, "_snapshot_workdir_files", snapshot_with_a_late_arrival)
+ sentinels = tools._created_file_sentinels(workdir, before, token = token)
+ assert sentinels == "", f"another call's file was put on this card: {sentinels}"
+
+
+def test_a_chat_called_default_does_not_take_the_anonymous_sandbox(tmp_path, monkeypatch):
+ """An API client picks its own thread ids, and that folder holds every
+ session-less call's files, which this chat's delete would take."""
+ monkeypatch.setenv("HOME", str(tmp_path / "userprofile"))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "userprofile"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ anonymous = Path(tools.get_sandbox_workdir(None))
+ (anonymous / "scratch.csv").write_text("a,b\n", encoding = "utf-8")
+
+ chat = Path(tools.get_sandbox_workdir("_default"))
+ assert chat != anonymous, "the chat is running in the session-less sandbox"
+ assert not (chat / "scratch.csv").exists()
+
+ # And deleting the chat leaves the session-less files alone.
+ tools.remove_session_sandbox("_default", delete_files = True)
+ assert (anonymous / "scratch.csv").is_file()
+
+
+def test_a_chat_called_default_is_not_served_the_old_shared_folder(tmp_path, monkeypatch):
+ """Before the upgrade every call with no session id ran in that directory."""
+ monkeypatch.setenv("HOME", str(tmp_path / "userprofile"))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path / "userprofile"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ for name in ("_default", "_invalid"):
+ legacy = Path(tools._legacy_sandbox_root()) / name
+ legacy.mkdir(parents = True, exist_ok = True)
+ (legacy / "somebody-elses.csv").write_text("a,b\n", encoding = "utf-8")
+ assert tools._legacy_session_dir(name) is None, name
+
+
+def test_a_chat_recreated_under_the_same_id_keeps_its_sandbox(tmp_path, monkeypatch):
+ """The row goes first, so another tab can upsert the same id before the
+ cleanup runs, and that chat may have a tool call in there right now."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from routes import chat_history
+
+ _forget_sandbox_state(tools)
+ thread_id = "chat-recreated-1"
+ workdir = Path(tools.get_sandbox_workdir(thread_id))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ monkeypatch.setattr(chat_history, "get_chat_thread", lambda tid: {"id": tid})
+ removed, kept = asyncio.new_event_loop().run_until_complete(
+ chat_history._remove_sandboxes([thread_id], True)
+ )
+ assert removed == 0, "the recreated chat's sandbox was deleted"
+ assert (workdir / "report.csv").is_file()
+
+
+def test_a_listing_follows_a_tree_moved_out_from_under_it(tmp_path, monkeypatch):
+ """The legacy move renames the tree between resolving and walking it, and
+ the chat's own files would show as an empty sandbox."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from routes import inference
+
+ moved = tmp_path / "moved-in"
+ moved.mkdir()
+ (moved / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ answers = [str(tmp_path / "gone"), str(moved)]
+
+ monkeypatch.setattr(
+ inference,
+ "_sandbox_dir_for",
+ lambda session_id, create = False: answers.pop(0),
+ )
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+
+ result = asyncio.new_event_loop().run_until_complete(
+ inference.list_sandbox_files("thread-1", request = None, token = None, session = None)
+ )
+ assert [f["name"] for f in result["files"]] == ["report.csv"], result
+
+
+def test_a_record_never_deletes_what_the_helper_refused(tmp_path, monkeypatch):
+ """A record is a file on disk: a stale or edited one naming an unrelated
+ directory must not turn into an rmtree of it."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ project_id = "proj16180"
+ innocent = tmp_path / "Documents"
+ innocent.mkdir()
+ (innocent / "thesis.tex").write_text("x", encoding = "utf-8")
+ tools.record_orphaned_project(project_id, str(innocent), True, str(innocent))
+
+ refused = []
+ real_delete = studio_db.delete_project_workspace
+ monkeypatch.setattr(
+ studio_db,
+ "delete_project_workspace",
+ lambda project: refused.append(project) or real_delete({"id": "x", "rootPath": None}),
+ )
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+ tools.collect_orphaned_project_workspaces()
+
+ assert refused, "the validated helper was not consulted"
+ assert (innocent / "thesis.tex").is_file(), "a refused delete was done anyway"
+
+
+def test_the_last_fork_going_takes_the_source_chat_s_files(tmp_path, monkeypatch):
+ """The source's delete asked for its files and kept them for the fork, and
+ nothing else ever comes back to that folder."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from routes import chat_history
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ source, fork = "chat-source-1", "chat-fork-1"
+ workdir = Path(tools.get_sandbox_workdir(source))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ monkeypatch.setattr(chat_history, "get_chat_thread", lambda tid: None)
+ # The fork still shows the source's cards, so its files are kept.
+ monkeypatch.setattr(
+ studio_db,
+ "sandbox_is_referenced_elsewhere",
+ lambda s, e = None: s == source,
+ )
+ _removed, kept = asyncio.new_event_loop().run_until_complete(
+ chat_history._remove_sandboxes([source], True)
+ )
+ assert kept == [source]
+ assert (workdir / "report.csv").is_file()
+
+ # Now the fork is deleted too, and nothing references the source any more.
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+ asyncio.new_event_loop().run_until_complete(chat_history._remove_sandboxes([fork], True))
+ assert not workdir.exists(), "the source's files were orphaned for good"
+
+
+def test_a_chat_called_like_a_project_session_keeps_its_own_sandbox(tmp_path, monkeypatch):
+ """An API client picks its own thread ids, and one shaped like the
+ synthetic project session would run in that project's workspace."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ workspace = tmp_path / "Notes-proj7777"
+ (workspace / "sandbox").mkdir(parents = True)
+ monkeypatch.setattr(
+ studio_db,
+ "ensure_chat_project_workspace",
+ lambda pid: {
+ "id": pid,
+ "rootPath": str(workspace),
+ "sandboxPath": str(workspace / "sandbox"),
+ },
+ )
+ session = tools.project_session_id("proj7777")
+ assert Path(tools.get_sandbox_workdir(session)) == (workspace / "sandbox").resolve()
+
+ # The same id, but a chat of the user's is stored under it.
+ _forget_sandbox_state(tools)
+ monkeypatch.setattr(studio_db, "get_chat_thread", lambda tid: {"id": tid})
+ workdir = Path(tools.get_sandbox_workdir(session))
+ assert workdir != (workspace / "sandbox").resolve(), "the chat took the project workspace"
+ assert tools.remove_session_sandbox(session, delete_files = True) is True
+
+
+def test_a_long_project_id_still_reaches_its_workspace(tmp_path, monkeypatch):
+ """`project-` plus the id can be longer than a directory name may be, and
+ the workspace comes from the row, not from the id."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ project_id = "p" * 60
+ workspace = tmp_path / "Long-pppppppp"
+ (workspace / "sandbox").mkdir(parents = True)
+ monkeypatch.setattr(
+ studio_db,
+ "ensure_chat_project_workspace",
+ lambda pid: {
+ "id": pid,
+ "rootPath": str(workspace),
+ "sandboxPath": str(workspace / "sandbox"),
+ },
+ )
+ session = tools.project_session_id(project_id)
+ assert not tools._usable_session_id(session), "the prefixed id fits after all"
+ assert Path(tools.get_sandbox_workdir(session)) == (workspace / "sandbox").resolve()
+
+
+def test_a_project_recreated_under_the_same_id_keeps_its_workspace(tmp_path, monkeypatch):
+ """The row goes first, so another client can create a project with that id
+ before the files are removed, and its own tool call may be writing there."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from routes import chat_history
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ project_id = "proj24242"
+ workspace = tmp_path / "Notes-proj2424"
+ (workspace / "sandbox").mkdir(parents = True)
+ (workspace / "sandbox" / "fresh.csv").write_text("a,b\n", encoding = "utf-8")
+
+ monkeypatch.setattr(chat_history, "get_chat_project", lambda pid: {"id": pid})
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+ _deleted_project(tmp_path, monkeypatch, project_id, workspace)
+
+ assert (workspace / "sandbox" / "fresh.csv").is_file(), "the new project's files went"
+ assert tools.list_orphaned_projects() == [], "a live project was recorded as orphaned"
+
+
+def test_a_download_serves_the_file_it_checked(tmp_path, monkeypatch):
+ """Tool code runs in that directory: between the containment check and the
+ open it can put a link there, and the response would follow it."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from routes import inference
+
+ sandbox = tmp_path / "sandbox"
+ sandbox.mkdir()
+ (sandbox / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ secret = tmp_path / "secret.txt"
+ secret.write_text("passwords", encoding = "utf-8")
+
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ monkeypatch.setattr(
+ inference,
+ "_sandbox_dir_for",
+ lambda session_id, create = False: str(sandbox),
+ )
+
+ loop = asyncio.new_event_loop()
+ response = loop.run_until_complete(
+ inference.serve_sandbox_file(
+ "thread-1",
+ "report.csv",
+ request = None,
+ token = None,
+ session = None,
+ )
+ )
+ # The swap happens after the check, before anything is read.
+ (sandbox / "report.csv").unlink()
+ (sandbox / "report.csv").symlink_to(secret)
+
+ body = b""
+
+ async def drain():
+ nonlocal body
+ async for chunk in response.body_iterator:
+ body += chunk
+
+ loop.run_until_complete(drain())
+ assert body == b"a,b\n", f"the response followed the link: {body!r}"
+
+
+def test_a_download_refuses_a_file_swapped_for_a_link(tmp_path, monkeypatch):
+ """The same swap, made before the open rather than after it."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from fastapi import HTTPException
+ from routes import inference
+
+ sandbox = tmp_path / "sandbox"
+ sandbox.mkdir()
+ secret = tmp_path / "secret.txt"
+ secret.write_text("passwords", encoding = "utf-8")
+ (sandbox / "report.csv").symlink_to(secret)
+
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ monkeypatch.setattr(
+ inference,
+ "_sandbox_dir_for",
+ lambda session_id, create = False: str(sandbox),
+ )
+
+ with pytest.raises(HTTPException) as raised:
+ asyncio.new_event_loop().run_until_complete(
+ inference.serve_sandbox_file(
+ "thread-1",
+ "report.csv",
+ request = None,
+ token = None,
+ session = None,
+ )
+ )
+ assert raised.value.status_code in (403, 404)
+
+
+def test_a_linked_sandbox_root_is_not_ours_to_delete_from(tmp_path, monkeypatch):
+ """`<studio home>/sandbox` pointing into the user's own folder makes every
+ directory under it theirs, whatever the environment says."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ theirs = tmp_path / "Documents"
+ (theirs / "chat-linked-1").mkdir(parents = True)
+ (theirs / "chat-linked-1" / "thesis.tex").write_text("x", encoding = "utf-8")
+ root = Path(tools.sandbox_root())
+ if root.exists():
+ shutil.rmtree(root)
+ root.parent.mkdir(parents = True, exist_ok = True)
+ root.symlink_to(theirs)
+
+ assert tools._root_is_ours() is False
+ workdir = Path(tools.get_sandbox_workdir("chat-linked-1"))
+ assert not (workdir / "thesis.tex").exists(), "the chat ran in the user's directory"
+ tools.remove_session_sandbox("chat-linked-1", delete_files = True)
+ assert (theirs / "chat-linked-1" / "thesis.tex").is_file(), "deleted the user's files"
+
+
+def test_a_collection_failure_names_the_record_it_was_on(tmp_path, monkeypatch):
+ """The handler runs before the loop's own name is bound, and an
+ UnboundLocalError there turns a finished delete into a 500."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ workspace = tmp_path / "Notes-projfail"
+ (workspace / "sandbox").mkdir(parents = True)
+ tools.record_orphaned_project("projfail1", str(workspace / "sandbox"), True, str(workspace))
+
+ def boom(*args, **kwargs):
+ raise RuntimeError("database is away")
+
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", boom)
+ tools.collect_orphaned_project_workspaces() # must not raise
+ assert workspace.is_dir()
+
+
+def test_a_project_created_again_keeps_the_recorded_workspace(tmp_path, monkeypatch):
+ """The collection runs minutes later, and the id is the client's to reuse."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ project_id = "projagain"
+ workspace = tmp_path / "Notes-projagai"
+ (workspace / "sandbox").mkdir(parents = True)
+ (workspace / "fresh.csv").write_text("a,b\n", encoding = "utf-8")
+ tools.record_orphaned_project(project_id, str(workspace / "sandbox"), True, str(workspace))
+
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+ # The same id and the same folder: this is the project those files belong to.
+ monkeypatch.setattr(
+ studio_db,
+ "get_chat_project",
+ lambda pid: {
+ "id": pid,
+ "rootPath": str(workspace),
+ "sandboxPath": str(workspace / "sandbox"),
+ },
+ )
+ tools.collect_orphaned_project_workspaces()
+ assert (workspace / "fresh.csv").is_file(), "the new project's files went"
+
+ # Gone again, and the collection finishes what was asked for.
+ monkeypatch.setattr(studio_db, "get_chat_project", lambda pid: None)
+ tools.collect_orphaned_project_workspaces()
+ assert not workspace.exists()
+
+
+def test_a_chat_recreated_while_its_tool_ran_keeps_its_files(tmp_path, monkeypatch):
+ """The delete was queued behind a running call, and by the time it fires
+ the id can belong to a chat the user did not delete."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ session = "chat-requeued-1"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ monkeypatch.setattr(studio_db, "get_chat_thread", lambda tid: None)
+ with tools._session_in_flight(session):
+ assert tools.remove_session_sandbox(session, delete_files = True) is False
+ assert tools.sandbox_removal_deferred(session)
+ # The user starts a new chat and the id comes round again.
+ monkeypatch.setattr(studio_db, "get_chat_thread", lambda tid: {"id": tid})
+
+ assert (workdir / "report.csv").is_file(), "the recreated chat's files went"
+
+
+def test_a_file_outside_the_hash_budget_is_not_reported_as_written(tmp_path, monkeypatch):
+ """Hashing stops at a byte budget, so a file written earlier in the walk
+ pushes an untouched later one out of it."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ monkeypatch.setattr(tools, "_volume_timestamps_finely", lambda _: False)
+ workdir = tmp_path / "sandbox"
+ workdir.mkdir()
+ untouched = workdir / "z-report.csv"
+ untouched.write_bytes(b"x" * 32)
+
+ before = tools._snapshot_workdir_files(str(workdir))
+ assert before["z-report.csv"][2] is not None, "the file was not hashed to begin with"
+
+ # The call writes its own file, and the budget the untouched one had is
+ # taken by whatever the walk reaches first.
+ (workdir / "a-new.bin").write_bytes(b"y" * 64)
+ monkeypatch.setattr(tools, "_MAX_SNAPSHOT_HASH_BYTES", 0)
+ sentinels = tools._created_file_sentinels(str(workdir), before)
+ assert "a-new.bin" in sentinels
+ assert "z-report.csv" not in sentinels, sentinels
+
+
+def test_the_file_download_button_refreshes_the_session_first():
+ """The bearer rides in the URL, so an access token that expired during the
+ session would save a 401 body under the file's name."""
+ src = Path(__file__).resolve().parents[2] / "frontend/src"
+ view = (src / "components/assistant-ui/sandbox-files-view.tsx").read_text(encoding = "utf-8")
+ assert 'authFetch(apiUrl(path), { method: "HEAD" })' in view
+ assert view.index("authFetch(apiUrl(path)") < view.index("const token = getAuthToken()")
+
+
+def test_the_download_route_answers_the_probe_the_button_sends(tmp_path, monkeypatch):
+ """FastAPI does not add HEAD to a GET route, so the probe would 405 and no
+ sandbox file could be saved at all."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from routes import inference
+
+ methods = {
+ frozenset(r.methods)
+ for r in inference.router.routes
+ if getattr(r, "path", "") == "/sandbox/{session_id}/{filename:path}"
+ }
+ assert methods == {frozenset({"GET", "HEAD"})}, methods
+
+ sandbox = tmp_path / "sandbox"
+ sandbox.mkdir()
+ (sandbox / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ monkeypatch.setattr(
+ inference,
+ "_sandbox_dir_for",
+ lambda session_id, create = False: str(sandbox),
+ )
+
+ class _Head:
+ method = "HEAD"
+
+ response = asyncio.new_event_loop().run_until_complete(
+ inference.serve_sandbox_file(
+ "thread-1",
+ "report.csv",
+ request = _Head(),
+ token = None,
+ session = None,
+ )
+ )
+ assert response.status_code == 200
+ assert response.headers["content-length"] == "4"
+ assert response.body == b"", "the file was read to answer a HEAD"
+
+
+def test_a_project_id_a_filename_cannot_hold_is_still_recorded(tmp_path, monkeypatch):
+ """Project ids are the client's, and a record refused here loses both the
+ deferred delete and the cards of a fork that kept the files."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ project_id = "Ünsloth/Notes " + "x" * 80
+ workspace = tmp_path / "Notes-project"
+ (workspace / "sandbox").mkdir(parents = True)
+ tools.record_orphaned_project(project_id, str(workspace / "sandbox"), True, str(workspace))
+
+ records = tools.list_orphaned_projects()
+ assert [(r[0], r[3]) for r in records] == [(project_id, True)], records
+ assert tools._recorded_project_workdir(project_id) == str((workspace / "sandbox").resolve())
+
+ tools.forget_orphaned_project(project_id)
+ assert tools.list_orphaned_projects() == []
+
+
+def test_a_chat_and_a_project_with_one_id_keep_their_own_records(tmp_path, monkeypatch):
+ """They are different tables, so the same client-supplied id can name both,
+ and one record overwriting the other stranded a folder."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ shared_id = "notes1234"
+ workspace = tmp_path / "Notes-notes123"
+ (workspace / "sandbox").mkdir(parents = True)
+ chat_dir = Path(tools.get_sandbox_workdir(shared_id))
+ (chat_dir / "chat.csv").write_text("a,b\n", encoding = "utf-8")
+
+ tools.record_orphaned_project(shared_id, str(workspace / "sandbox"), True, str(workspace))
+ tools.record_kept_sandbox(shared_id)
+
+ records = sorted(tools.list_orphaned_projects(), key = lambda r: r[4])
+ assert [r[0] for r in records] == [shared_id, shared_id]
+ assert [r[4] for r in records] == [False, True], "one record overwrote the other"
+ assert records[0][1] == str((workspace / "sandbox").resolve())
+ assert records[1][1] == str(chat_dir.resolve())
+ # And the project's own resolve is unaffected by the chat's record.
+ assert tools._recorded_project_workdir(shared_id) == str((workspace / "sandbox").resolve())
+
+
+def test_a_kept_workspace_is_found_past_a_crowd_of_records(tmp_path, monkeypatch):
+ """A bounded listing meant a busy install could never see the newest
+ records, so their folders were unreachable and their deletes never ran."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ crowd = tmp_path / "crowd"
+ crowd.mkdir()
+ for n in range(50):
+ tools.record_orphaned_project(f"aaaa{n:04d}", str(crowd), False, None)
+
+ project_id = "zzzz9999"
+ workspace = tmp_path / "Notes-zzzz9999"
+ (workspace / "sandbox").mkdir(parents = True)
+ tools.record_orphaned_project(project_id, str(workspace / "sandbox"), True, str(workspace))
+
+ monkeypatch.setattr(tools, "_MAX_ORPHAN_RECORDS", 4)
+ assert tools._recorded_project_workdir(project_id) == str((workspace / "sandbox").resolve())
+
+
+def test_a_project_created_during_the_record_write_keeps_its_files(tmp_path, monkeypatch):
+ """The record write is an await, and a project created in that window
+ resolves to the same default workspace path."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from routes import chat_history
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ project_id = "proj13131"
+ workspace = tmp_path / "Notes-proj1313"
+ (workspace / "sandbox").mkdir(parents = True)
+ (workspace / "sandbox" / "fresh.csv").write_text("a,b\n", encoding = "utf-8")
+
+ answers = [None, {"id": project_id}]
+ monkeypatch.setattr(
+ chat_history,
+ "get_chat_project",
+ lambda pid: answers.pop(0) if answers else None,
+ )
+ monkeypatch.setattr(
+ studio_db,
+ "get_chat_project",
+ lambda pid: {
+ "id": pid,
+ "rootPath": str(workspace),
+ "sandboxPath": str(workspace / "sandbox"),
+ },
+ )
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+ _deleted_project(tmp_path, monkeypatch, project_id, workspace)
+
+ assert (workspace / "sandbox" / "fresh.csv").is_file(), "the new project's files went"
+ assert tools.list_orphaned_projects() == [], "a live project was left recorded"
+
+
+def test_a_kept_workspace_resolves_for_any_project_id(tmp_path, monkeypatch):
+ """The record is keyed by a digest, so the id it holds needs to be nothing
+ in particular; only the guessed directory name does."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ project_id = "Ünsloth/Notes " + "y" * 80
+ workspace = tmp_path / "Notes-kept"
+ (workspace / "sandbox").mkdir(parents = True)
+ (workspace / "sandbox" / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ tools.record_orphaned_project(project_id, str(workspace / "sandbox"), False, str(workspace))
+
+ monkeypatch.setattr(studio_db, "ensure_chat_project_workspace", lambda pid: None)
+ served = Path(tools.resolve_sandbox_workdir(tools.project_session_id(project_id)))
+ assert served == (workspace / "sandbox").resolve(), served
+ assert (served / "report.csv").is_file()
+
+
+def test_a_marker_rewritten_with_another_name_keeps_the_chat_s_files(tmp_path, monkeypatch):
+ """That file is tool-writable, and a valid-looking name in it made the
+ directory unreachable: no download, and a delete that reported nothing."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ session = "chat-marker-2"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ # A tool call writes a perfectly good session name over the marker.
+ (workdir / tools._SANDBOX_MARKER).write_text("someone-else", encoding = "utf-8")
+
+ assert Path(tools.resolve_sandbox_workdir(session)) == workdir, "the files were stranded"
+ assert tools.session_sandbox_has_files(session) is True
+ assert tools.remove_session_sandbox(session, delete_files = True) is True
+ assert not workdir.exists()
+
+
+def test_a_sandbox_lookup_lists_the_root_once(tmp_path, monkeypatch):
+ """There are 33 candidate names, and a scan each turned one first call into
+ 33 walks of a root that holds a folder per chat."""
+ root = _shared_root(tmp_path, monkeypatch)
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ scans = []
+ real_listdir = os.listdir
+
+ def counting_listdir(path):
+ scans.append(str(path))
+ return real_listdir(path)
+
+ monkeypatch.setattr(tools.os, "listdir", counting_listdir)
+ assert tools._marked_sandbox_in(str(root), "chat-scan-1") is None
+ assert len([s for s in scans if s == str(root)]) == 1, scans
+
+
+def test_a_deferred_delete_keeps_the_files_when_the_check_cannot_be_made(tmp_path, monkeypatch):
+ """The queued delete fires with no request around it, and the row check is
+ the only thing standing between it and a recreated chat's files."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ session = "chat-unknown-1"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ def broken(thread_id):
+ raise RuntimeError("database is away")
+
+ monkeypatch.setattr(studio_db, "get_chat_thread", broken)
+ with tools._session_in_flight(session):
+ assert tools.remove_session_sandbox(session, delete_files = True) is False
+
+ assert (workdir / "report.csv").is_file(), "files went on an unanswerable check"
+
+
+def test_only_a_sandbox_tool_s_result_is_unwrapped_for_replay():
+ """A custom tool answering with text, sessionId and images is someone
+ else's result, and replaying only its text drops the rest."""
+ src = Path(__file__).resolve().parents[2] / "frontend/src"
+ adapter = (src / "features/chat/api/chat-adapter.ts").read_text(encoding = "utf-8")
+ assert "function isSandboxWrapper(" in adapter
+ assert "): result is { text: string; sessionId: string } {" in adapter
+ assert "SANDBOX_FILE_TOOLS.has(toolName)" in adapter
+ assert 'isSandboxWrapper(result, tc.toolName ?? "")' in adapter
+ # The export paths pass the name too, so a wrapper is stripped in one place.
+ dialog = (src / "features/chat/prompt-storage/prompt-storage-dialog.tsx").read_text(
+ encoding = "utf-8"
+ )
+ assert 'typeof p.toolName === "string" ? p.toolName : undefined,' in dialog
+ assert "toolResultModelText(p.result, name)" in dialog
+
+
+def test_a_project_remade_somewhere_else_does_not_strand_the_old_workspace(tmp_path, monkeypatch):
+ """The default root carries the project's name, so a project remade under
+ that id can sit somewhere else entirely."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ project_id = "projmoved"
+ old = tmp_path / "Notes-projmove"
+ (old / "sandbox").mkdir(parents = True)
+ (old / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ new = tmp_path / "Renamed-projmove"
+ (new / "sandbox").mkdir(parents = True)
+ tools.record_orphaned_project(project_id, str(old / "sandbox"), True, str(old))
+
+ monkeypatch.setattr(studio_db, "sandbox_is_referenced_elsewhere", lambda s, e = None: False)
+ monkeypatch.setattr(
+ studio_db,
+ "get_chat_project",
+ lambda pid: {"id": pid, "rootPath": str(new), "sandboxPath": str(new / "sandbox")},
+ )
+ assert tools.live_project_owns(project_id, str(old / "sandbox"), str(old)) is False
+ assert tools.live_project_owns(project_id, str(new / "sandbox"), str(new)) is True
+
+ tools.collect_orphaned_project_workspaces()
+ assert not old.exists(), "the old workspace was stranded"
+ assert new.is_dir(), "the live project's workspace went"
+
+
+def test_a_chat_named_like_a_project_session_still_loses_its_files(tmp_path, monkeypatch):
+ """Its row is deleted before the cleanup runs, so the id reads as the
+ project's from then on and its own folder was left behind."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+ from storage import studio_db
+
+ _forget_sandbox_state(tools)
+ workspace = tmp_path / "Shared-foo12345"
+ (workspace / "sandbox").mkdir(parents = True)
+ (workspace / "sandbox" / "shared.csv").write_text("a,b\n", encoding = "utf-8")
+ monkeypatch.setattr(
+ studio_db,
+ "ensure_chat_project_workspace",
+ lambda pid: {
+ "id": pid,
+ "rootPath": str(workspace),
+ "sandboxPath": str(workspace / "sandbox"),
+ },
+ )
+
+ session = tools.project_session_id("foo12345")
+ monkeypatch.setattr(studio_db, "get_chat_thread", lambda tid: {"id": tid})
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "mine.csv").write_text("a,b\n", encoding = "utf-8")
+ assert workdir != (workspace / "sandbox").resolve()
+
+ # The row goes first, so from here the id reads as the project's session.
+ monkeypatch.setattr(studio_db, "get_chat_thread", lambda tid: None)
+ assert tools.remove_session_sandbox(session, delete_files = True) is True
+ assert not workdir.exists(), "the chat's own files were left behind"
+ assert (workspace / "sandbox" / "shared.csv").is_file(), "the project's files went"
+
+
+def test_a_download_sends_no_more_than_it_promised(tmp_path, monkeypatch):
+ """Another call can append to the file after the length is captured, and a
+ body longer than Content-Length is cut off or refused."""
+ import asyncio
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from routes import inference
+
+ sandbox = tmp_path / "sandbox"
+ sandbox.mkdir()
+ (sandbox / "report.csv").write_text("a,b\n", encoding = "utf-8")
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ monkeypatch.setattr(
+ inference,
+ "_sandbox_dir_for",
+ lambda session_id, create = False: str(sandbox),
+ )
+
+ loop = asyncio.new_event_loop()
+ response = loop.run_until_complete(
+ inference.serve_sandbox_file(
+ "thread-1",
+ "report.csv",
+ request = None,
+ token = None,
+ session = None,
+ )
+ )
+ declared = int(response.headers["content-length"])
+ with open(sandbox / "report.csv", "a", encoding = "utf-8") as fh:
+ fh.write("c,d\ne,f\n") # the tool call is still writing
+
+ body = b""
+
+ async def drain():
+ nonlocal body
+ async for chunk in response.body_iterator:
+ body += chunk
+
+ loop.run_until_complete(drain())
+ assert len(body) == declared, f"sent {len(body)} bytes for a declared {declared}"
+
+
+def test_an_interrupted_delete_is_finished_when_studio_starts(tmp_path, monkeypatch):
+ """It waited for the next Python or terminal call, and ordinary chat, a
+ listing and a download never make one."""
+ import inspect
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from core.inference import tools
+
+ _forget_sandbox_state(tools)
+ tools._swept_detached = False
+ root = Path(tools.sandbox_root())
+ root.mkdir(parents = True, exist_ok = True)
+ stranded = root / "chat-killed-1.deleting-abcdef12"
+ stranded.mkdir()
+ (stranded / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ thread = tools.start_sandbox_recovery()
+ if thread is not None:
+ thread.join(timeout = 10)
+ assert not stranded.exists(), "the tree a killed run left was kept"
+
+ import main
+
+ assert "start_sandbox_recovery()" in inspect.getsource(main.lifespan)
+
+
+def test_a_retry_that_still_keeps_the_files_offers_again():
+ """The request succeeds and the files stay: a tool is still running, a fork
+ still shows them, or the folder would not go."""
+ src = Path(__file__).resolve().parents[2] / "frontend/src"
+ offer = (src / "features/chat/utils/offer-kept-sandbox-files.ts").read_text(encoding = "utf-8")
+ assert "if (stillKept.length > 0) offerToDeleteKeptSandboxes(stillKept);" in offer
+
+
+def test_a_finely_timestamped_volume_is_not_read_twice_per_call(tmp_path, monkeypatch):
+ """Hashing every artifact was ~90% of a snapshot, and two snapshots run per
+ tool call. Where mtime already separates the writes, nothing is read."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_fine1"))
+ if not tools._volume_timestamps_finely(str(workdir)):
+ pytest.skip("this filesystem records whole seconds, where digests are the point")
+ (workdir / "report.csv").write_text("a,b\n", encoding = "utf-8")
+
+ read = []
+ real_key = tools._content_key
+ monkeypatch.setattr(
+ tools, "_content_key",
+ lambda path, size: (read.append(path), real_key(path, size))[1],
+ )
+ snapshot = tools._snapshot_workdir_files(str(workdir))
+
+ assert snapshot["report.csv"][2] is None, "the file was hashed anyway"
+ assert not read, f"the snapshot read {read}"
+
+
+def test_one_whole_second_stamp_is_not_taken_for_a_coarse_volume(tmp_path, monkeypatch):
+ """A directory that happens to land on a whole second is chance. Reading
+ only mtime would pin the volume to hashing for the life of the process."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+
+ tools._workdirs.clear()
+ workdir = Path(tools.get_sandbox_workdir("__LOCALID_stamp1"))
+ if not tools._volume_timestamps_finely(str(workdir)):
+ pytest.skip("this filesystem records whole seconds")
+ tools._fine_mtime_devices.clear()
+ real_stat = os.stat
+ monkeypatch.setattr(
+ os, "stat",
+ lambda p, *a, **k: (
+ _WholeSecondMtime(real_stat(p, *a, **k)) if str(p) == str(workdir)
+ else real_stat(p, *a, **k)
+ ),
+ )
+ assert tools._volume_timestamps_finely(str(workdir)), "one whole second was enough"
+
+
+class _WholeSecondMtime:
+ """A stat result whose mtime lost its sub-second part, and nothing else."""
+
+ def __init__(self, stat):
+ self._stat = stat
+
+ st_mtime_ns = property(lambda self: self._stat.st_mtime_ns // 10**9 * 10**9)
+
+ def __getattr__(self, name):
+ return getattr(self._stat, name)
+
+
+if __name__ == "__main__":
+ sys.exit(pytest.main([__file__, "-q", "-s"]))
diff --git a/studio/backend/tests/test_tool_sandbox_per_thread.py b/studio/backend/tests/test_tool_sandbox_per_thread.py
index 13bd95c9eda..1fa7f7bfb18 100644
--- a/studio/backend/tests/test_tool_sandbox_per_thread.py
+++ b/studio/backend/tests/test_tool_sandbox_per_thread.py
@@ -8,7 +8,7 @@ time, so a shared working directory would let one overwrite the other's files.
The session id is the chat's thread id (or project-<id> for project chats), and
the dir is derived from it here.
-HOME is redirected at import time, so nothing touches the real ~/studio_sandbox.
+UNSLOTH_STUDIO_HOME is redirected per test, so nothing touches the real install.
"""
import os
@@ -20,13 +20,22 @@ _backend = os.path.join(os.path.dirname(__file__), "..")
sys.path.insert(0, _backend)
+def sandbox_root(tmp_path):
+ """Where the sandboxes live for these tests: under the studio home."""
+ return tmp_path / "sandbox"
+
+
@pytest.fixture
def workdir(tmp_path, monkeypatch):
- """_get_workdir with HOME pointed at tmp_path and its cache cleared."""
+ """_get_workdir against a throwaway studio home, with its cache cleared."""
from core.inference import tools
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.delenv("UNSLOTH_STUDIO_SANDBOX_HOME", raising = False)
monkeypatch.setattr(os.path, "expanduser", lambda path: str(tmp_path))
monkeypatch.setattr(tools, "_workdirs", {})
+ monkeypatch.setattr(tools, "_legacy_sandbox_migrated", True)
return tools._get_workdir
@@ -37,7 +46,7 @@ def test_two_conversations_get_two_directories(workdir, tmp_path):
assert os.path.basename(a) == "thread-alpha"
assert os.path.basename(b) == "thread-beta"
assert os.path.isdir(a) and os.path.isdir(b)
- assert os.path.dirname(a) == os.path.dirname(b) == str(tmp_path / "studio_sandbox")
+ assert os.path.dirname(a) == os.path.dirname(b) == str(tmp_path / "sandbox")
def test_the_same_conversation_keeps_its_directory(workdir):
@@ -46,11 +55,14 @@ def test_the_same_conversation_keeps_its_directory(workdir):
def test_a_directory_is_private_to_its_conversation(workdir):
+ from core.inference import tools
+
a = workdir("thread-alpha")
b = workdir("thread-beta")
with open(os.path.join(a, "secret.txt"), "w", encoding = "utf-8") as f:
f.write("alpha")
- assert os.listdir(b) == []
+ # Our own ownership marker aside, nothing of alpha's is visible here.
+ assert os.listdir(b) == [tools._SANDBOX_MARKER]
def test_project_chats_deliberately_share_one_workspace(workdir, monkeypatch):
@@ -66,9 +78,12 @@ def test_project_chats_deliberately_share_one_workspace(workdir, monkeypatch):
)
def test_a_session_id_cannot_escape_the_sandbox_root(workdir, tmp_path, session_id):
resolved = workdir(session_id) if session_id else workdir(None)
- root = os.path.realpath(str(tmp_path / "studio_sandbox"))
+ root = os.path.realpath(str(tmp_path / "sandbox"))
assert os.path.realpath(resolved).startswith(root + os.sep)
- assert os.path.basename(resolved) in {"_invalid", "_default"}
+ # A name the filesystem can hold, derived from the id rather than the id
+ # itself, so nothing in it can traverse and no two ids share it.
+ name = os.path.basename(resolved)
+ assert name == "_default" if not session_id else name.startswith("_id-")
def test_no_session_id_falls_back_to_default(workdir):
diff --git a/studio/backend/utils/cache_cleanup.py b/studio/backend/utils/cache_cleanup.py
index 210735973d8..41f1ede863a 100644
--- a/studio/backend/utils/cache_cleanup.py
+++ b/studio/backend/utils/cache_cleanup.py
@@ -9,6 +9,7 @@ selectively between model loads, preserving model-agnostic components (Trainers)
that spawned subprocesses need.
"""
+import os
import shutil
import structlog
from loggers import get_logger
@@ -28,9 +29,139 @@ _CACHE_DIRS = [
]
+def _configured_cache_dirs() -> List[Path]:
+ """Cache dirs outside the source tree: the configured one, and the CWD.
+
+ The candidates above are all source-tree relative, so a cache created in
+ the launcher's CWD (the user profile on Windows) was invisible to cleanup.
+ The CWD is still checked for installs that predate the pinned location.
+ """
+ import os
+
+ dirs: List[Path] = []
+ configured = (os.environ.get("UNSLOTH_COMPILE_LOCATION") or "").strip()
+ if configured:
+ dirs.append(Path(configured).expanduser())
+ try:
+ dirs.append(Path.cwd() / "unsloth_compiled_cache")
+ except OSError:
+ pass
+ return dirs
+
+
def get_existing_cache_dirs() -> List[Path]:
"""Return known compiled-cache directories that currently exist on disk."""
- return [d for d in _CACHE_DIRS if d.exists()]
+ seen: set = set()
+ found: List[Path] = []
+ for candidate in [*_CACHE_DIRS, *_configured_cache_dirs()]:
+ try:
+ key = candidate.resolve()
+ except OSError:
+ key = candidate
+ if key in seen:
+ continue
+ seen.add(key)
+ if candidate.exists():
+ found.append(candidate)
+ return found
+
+
+# Written when Studio creates the directory, so "we made this" is a fact rather
+# than an inference from the contents.
+CACHE_MARKER = ".unsloth_compiled_cache"
+
+# Names only the compiler produces, so a cache Studio did not create is still
+# recognised once it has been written into.
+import re as _re
+
+_GENERATED_NAME_RE = _re.compile(r"\A(unsloth_compiled_module_.+|Unsloth.+Trainer)\.py\Z")
+# What may be deleted from a directory we do not own. Narrower on purpose:
+# Unsloth*Trainer.py is a convention a user's own subclass can match, and there
+# the marker is the only thing that would say we wrote it.
+_OWNED_DELETE_RE = _re.compile(r"\Aunsloth_compiled_module_.+\.py\Z")
+
+
+def _is_dedicated_cache(path: Path) -> bool:
+ """True only for a directory Studio created for the cache and nothing else.
+
+ A real file, not a link: exists() follows one, so a marker symlinked at any
+ existing path would license the rmtree below over somebody's own directory.
+ """
+ marker = path / CACHE_MARKER
+ try:
+ return marker.is_file() and not marker.is_symlink()
+ except OSError:
+ return False
+
+
+def _trusted_cache_paths() -> set:
+ """Where a cache is ours by where it is: the source-tree candidates, and
+ whatever UNSLOTH_COMPILE_LOCATION names, since that is the caller's answer
+ to where the cache lives. Never the launch directory."""
+ trusted = _builtin_cache_paths()
+ configured = (os.environ.get("UNSLOTH_COMPILE_LOCATION") or "").strip()
+ if configured:
+ trusted.add(str(Path(configured).expanduser()))
+ return trusted
+
+
+def _entries(path: Path) -> list:
+ try:
+ return list(path.iterdir())
+ except OSError:
+ return []
+
+
+def _holds_generated_modules(path: Path) -> bool:
+ """True when the compiler has written into this directory.
+
+ A shape test is not enough to own the directory: a directory of plain .py
+ files is someone's package, and this decides what gets deleted.
+ """
+ try:
+ return any(
+ item.is_file() and _GENERATED_NAME_RE.match(item.name) for item in path.iterdir()
+ )
+ except OSError:
+ return False
+
+
+def _builtin_cache_paths() -> set:
+ """Paths that are ours by construction, so they need no marker.
+
+ The CWD candidate is deliberately not one: Studio is launched from wherever
+ the shell happens to be, and a directory there is only ours if it says so.
+ """
+ return {str(p) for p in _CACHE_DIRS}
+
+
+def _cleanable_cache_dirs() -> "List[tuple]":
+ """``(directory, dedicated)`` for every cache dir something may be removed from.
+
+ UNSLOTH_COMPILE_LOCATION is a user-set variable, so it can name a directory
+ that holds other things (`$HOME/.cache`). Built-in paths, and any directory
+ carrying the marker, are ours whole. Anywhere else only the generated files
+ are ours, so only those may go.
+ """
+ builtin = _builtin_cache_paths()
+ cleanable: "List[tuple]" = []
+ for cache_dir in get_existing_cache_dirs():
+ # A built-in path is ours by construction only while it IS the directory.
+ # Through a link, the marker on the target is the only proof, since the
+ # clearing below resolves it and would take whatever it points at.
+ owned_by_path = str(cache_dir) in builtin and not cache_dir.is_symlink()
+ if owned_by_path or _is_dedicated_cache(cache_dir):
+ cleanable.append((cache_dir, True))
+ elif _holds_generated_modules(cache_dir):
+ cleanable.append((cache_dir, False))
+ else:
+ logger.warning(
+ "Not clearing %s: Studio did not create it and it holds no generated "
+ "modules. Point UNSLOTH_COMPILE_LOCATION at a directory used only for "
+ "the compiled cache.",
+ cache_dir,
+ )
+ return cleanable
def register_compiled_cache_on_path() -> None:
@@ -47,7 +178,20 @@ def register_compiled_cache_on_path() -> None:
# Iterate in reverse so earlier _CACHE_DIRS entries (higher priority) are
# inserted last and thus end up first in sys.path / PYTHONPATH.
- for cache_dir in reversed(get_existing_cache_dirs()):
+ # Same ownership test as cleanup: a directory in the launch dir that merely
+ # has the name would otherwise shadow real dependencies for every worker.
+ # A directory in the launch dir needs a file only the compiler writes:
+ # Unsloth*Trainer.py is a name a user's own subclass can carry, and that
+ # directory goes on sys.path. Where we put it is ours anyway.
+ trusted = _trusted_cache_paths()
+ registrable = [
+ d
+ for d, dedicated in _cleanable_cache_dirs()
+ if dedicated
+ or str(d) in trusted
+ or any(_OWNED_DELETE_RE.match(item.name) for item in _entries(d))
+ ]
+ for cache_dir in reversed(registrable):
resolved = str(cache_dir.resolve())
if resolved not in sys.path:
sys.path.insert(0, resolved)
@@ -66,11 +210,21 @@ def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None)
(e.g., ["Unsloth*Trainer.py"]). If None or empty,
the entire cache directory is deleted (legacy behavior).
"""
- for cache_dir in _CACHE_DIRS:
- if not cache_dir.exists():
- continue
-
- if preserve_patterns:
+ for cache_dir, dedicated in _cleanable_cache_dirs():
+ if not dedicated:
+ # A shared directory we only ever wrote generated modules into, so
+ # they are the only thing here that may be removed.
+ logger.info(f"Cleaning generated modules from shared directory: {cache_dir}")
+ for item in cache_dir.iterdir():
+ if not item.is_file() or not _OWNED_DELETE_RE.match(item.name):
+ continue
+ if preserve_patterns and any(item.match(p) for p in preserve_patterns):
+ continue
+ try:
+ item.unlink()
+ except OSError as e:
+ logger.debug(f"Could not delete {item}: {e}")
+ elif preserve_patterns:
logger.info(
f"Cleaning unsloth compiled cache (preserving {preserve_patterns}): " f"{cache_dir}"
)
@@ -88,6 +242,19 @@ def clear_unsloth_compiled_cache(preserve_patterns: Optional[List[str]] = None)
# Always clear __pycache__ and other subdirectories
shutil.rmtree(item, ignore_errors = True)
else:
- # Legacy: remove the entire directory
+ # Legacy: remove the entire directory. Resolved first: rmtree refuses
+ # a symlink, and ignore_errors would leave the whole cache in place.
logger.info(f"Removing unsloth compiled cache: {cache_dir}")
- shutil.rmtree(cache_dir, ignore_errors = True)
+ shutil.rmtree(Path(os.path.realpath(cache_dir)), ignore_errors = True)
+ # The marker goes with whatever was cleared and nothing rewrites it
+ # (setup_cache_env writes it only when it first sets the variable), so
+ # the next cleanup would demote our own cache to "shared".
+ # A built-in path needs no marker, so no restoring either, unless it
+ # is a link: the clear removed the target and left it dangling.
+ if dedicated and (str(cache_dir) not in _builtin_cache_paths() or cache_dir.is_symlink()):
+ try:
+ restored = Path(os.path.realpath(cache_dir))
+ restored.mkdir(parents = True, exist_ok = True)
+ (restored / CACHE_MARKER).touch(exist_ok = True)
+ except OSError as e:
+ logger.debug(f"Could not restore the cache marker in {cache_dir}: {e}")
diff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.py
index 0b1398f6d23..1d64d8519f5 100644
--- a/studio/backend/utils/paths/storage_roots.py
+++ b/studio/backend/utils/paths/storage_roots.py
@@ -288,18 +288,47 @@ def _setup_cache_env() -> None:
defaults: dict[str, str] = {
"UV_CACHE_DIR": str(root / "uv"),
"VLLM_CACHE_ROOT": str(root / "vllm"),
+ # unsloth_zoo defaults this to a bare relative name, which resolves
+ # against the CWD, and the Windows launcher runs Studio with
+ # WorkingDirectory=%USERPROFILE%, so the cache landed in the user home.
+ # Must be set before unsloth_zoo.compiler imports: it reads the value
+ # at import time and puts it on sys.path.
+ "UNSLOTH_COMPILE_LOCATION": str(root.parent / "compiled_cache"),
}
for key, value in defaults.items():
- if key not in os.environ:
+ # Blank counts as unset: an inherited KEY= would otherwise pin the
+ # cache to "", which puts an empty entry on sys.path and sends the
+ # compiler to the system temp directory instead.
+ if not (os.environ.get(key) or "").strip():
os.environ[key] = value
# Best-effort: a non-writable custom HF_HOME must not crash startup;
# HF surfaces a clear error at download time instead.
try:
- Path(value).mkdir(parents = True, exist_ok = True)
- except OSError:
+ created = True
+ try:
+ Path(value).mkdir(parents = True, exist_ok = False)
+ except FileExistsError:
+ created = False
+ if key == "UNSLOTH_COMPILE_LOCATION" and created:
+ # Marks the directory as ours, so the cleanup can delete
+ # from it without inferring that from its contents. Only when
+ # this call made it: the marker is what licenses an rmtree.
+ from utils.cache_cleanup import CACHE_MARKER
+ (Path(value) / CACHE_MARKER).touch(exist_ok = True)
+ except (OSError, ImportError):
pass
+def setup_cache_env() -> None:
+ """Seed the cache env vars without creating every studio directory.
+
+ For `uvicorn main:app`, which bypasses run.py and so never reaches
+ ensure_studio_directories, but still has to pin UNSLOTH_COMPILE_LOCATION
+ before unsloth_zoo.compiler is imported.
+ """
+ _setup_cache_env()
+
+
def ensure_studio_directories() -> None:
"""Create all standard studio directories on startup."""
for dir_fn in (
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 24af28a0c2c..b9342343d3b 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -1223,21 +1223,32 @@ export function AppSidebar() {
closeMobileIfOpen();
}
- async function handleDeleteThread(item: Parameters<typeof deleteChatItem>[0]) {
- await deleteChatItem(item, activeThreadId, (view) => {
- navigate({
- to: "/chat",
- search: item.projectId
- ? { project: item.projectId }
- : { new: view.newThreadNonce },
- });
- });
+ async function handleDeleteThread(
+ item: Parameters<typeof deleteChatItem>[0],
+ args: { deleteFiles?: boolean } = {},
+ ) {
+ await deleteChatItem(
+ item,
+ activeThreadId,
+ (view) => {
+ navigate({
+ to: "/chat",
+ search: item.projectId
+ ? { project: item.projectId }
+ : { new: view.newThreadNonce },
+ });
+ },
+ args,
+ );
}
// Shared chat delete: same error toast and pin cleanup with or without the confirm dialog.
- async function deleteChatWithCleanup(item: SidebarItem) {
+ async function deleteChatWithCleanup(
+ item: SidebarItem,
+ args: { deleteFiles?: boolean } = {},
+ ) {
try {
- await handleDeleteThread(item);
+ await handleDeleteThread(item, args);
unpinChat(item.id);
} catch (err) {
toast.error(translate("shell.toast.failedToDeleteChat"), {
@@ -1395,18 +1406,36 @@ export function AppSidebar() {
| { kind: "run"; run: TrainingRunSummary };
const [confirmingDelete, setConfirmingDelete] =
useState<DeleteTarget | null>(null);
- const [deleteProjectFiles, setDeleteProjectFiles] = useState(false);
+ const [deleteFilesOnDelete, setDeleteFilesOnDelete] = useState(false);
+
+ /** Always through here: a stale switch would delete an unrelated sandbox. */
+ function openDeleteDialog(target: DeleteTarget) {
+ setDeleteFilesOnDelete(false);
+ setConfirmingDelete(target);
+ }
+
+ /** Only where a sandbox can actually be removed. A training run has none.
+ * A chat in a project still has one: anything it wrote before the move is in
+ * its own folder, and deletion never touches the project workspace. */
+ function deleteTargetHasFiles(target: DeleteTarget | null): boolean {
+ if (!target) return false;
+ return target.kind === "project" || target.kind === "chat";
+ }
async function commitDelete() {
const target = confirmingDelete;
if (!target) return;
const shouldDeleteProjectFiles =
- target.kind === "project" && deleteProjectFiles;
+ target.kind === "project" && deleteFilesOnDelete;
+ const shouldDeleteChatFiles =
+ deleteTargetHasFiles(target) && target.kind === "chat" && deleteFilesOnDelete;
setConfirmingDelete(null);
- // Reset so the next project delete never inherits this checkbox.
- setDeleteProjectFiles(false);
+ // Reset so the next delete never inherits this switch.
+ setDeleteFilesOnDelete(false);
if (target.kind === "chat") {
- await deleteChatWithCleanup(target.item);
+ await deleteChatWithCleanup(target.item, {
+ deleteFiles: shouldDeleteChatFiles,
+ });
return;
}
if (target.kind === "project") {
@@ -1803,7 +1832,7 @@ export function AppSidebar() {
variant="destructive"
onSelect={() =>
confirmDeleteChats
- ? setConfirmingDelete({ kind: "chat", item })
+ ? openDeleteDialog({ kind: "chat", item })
: void deleteChatWithCleanup(item)
}
>
@@ -2318,9 +2347,7 @@ export function AppSidebar() {
variant="destructive"
onSelect={() => {
// Start each delete with the file toggle off: Cancel closes programmatically and skips the
- // dialog onOpenChange reset.
- setDeleteProjectFiles(false);
- setConfirmingDelete({ kind: "project", project });
+ openDeleteDialog({ kind: "project", project });
}}
>
<HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
@@ -2480,7 +2507,7 @@ export function AppSidebar() {
variant="destructive"
disabled={run.status === "running"}
onSelect={() =>
- setConfirmingDelete({ kind: "run", run })
+ openDeleteDialog({ kind: "run", run })
}
>
<HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-icon" />
@@ -2754,7 +2781,7 @@ export function AppSidebar() {
onOpenChange={(open) => {
if (!open) {
setConfirmingDelete(null);
- setDeleteProjectFiles(false);
+ setDeleteFilesOnDelete(false);
}
}}
>
@@ -2791,23 +2818,24 @@ export function AppSidebar() {
) : null}
</DialogDescription>
</DialogHeader>
- {confirmingDelete?.kind === "project" ? (
+ {deleteTargetHasFiles(confirmingDelete) ? (
<div className="flex items-start justify-between gap-4 rounded-md border border-border/60 bg-muted/35 px-3 py-2.5">
- <label htmlFor="delete-project-files" className="min-w-0 space-y-1">
+ <label htmlFor="delete-files-on-delete" className="min-w-0 space-y-1">
<span className="block text-sm font-medium text-foreground">
Delete files and sandbox folder
</span>
<span className="block break-words text-xs leading-5 text-muted-foreground">
- {confirmingDelete.project.rootPath
- ? confirmingDelete.project.rootPath
- : "The project workspace folder will be removed from disk."}
+ {confirmingDelete?.kind === "project"
+ ? (confirmingDelete.project.rootPath ??
+ "The project workspace folder will be removed from disk.")
+ : "This chat's own sandbox folder is removed from disk. Files it wrote inside a project stay in that project's workspace."}
</span>
</label>
<Switch
- id="delete-project-files"
- checked={deleteProjectFiles}
- onCheckedChange={setDeleteProjectFiles}
- aria-label="Delete project files and sandbox folder"
+ id="delete-files-on-delete"
+ checked={deleteFilesOnDelete}
+ onCheckedChange={setDeleteFilesOnDelete}
+ aria-label="Delete files and sandbox folder"
/>
</div>
) : null}
@@ -2824,7 +2852,7 @@ export function AppSidebar() {
variant="destructive"
onClick={() => void commitDelete()}
>
- {confirmingDelete?.kind === "project" && deleteProjectFiles
+ {deleteTargetHasFiles(confirmingDelete) && deleteFilesOnDelete
? "Delete all"
: t("common.delete")}
</Button>
diff --git a/studio/frontend/src/components/assistant-ui/python-tool-image-path.ts b/studio/frontend/src/components/assistant-ui/python-tool-image-path.ts
index fdf43f1fe6f..cd92b01e286 100644
--- a/studio/frontend/src/components/assistant-ui/python-tool-image-path.ts
+++ b/studio/frontend/src/components/assistant-ui/python-tool-image-path.ts
@@ -1,9 +1,14 @@
// 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 { sandboxFilePath } from "./sandbox-files.ts";
+
export function pythonToolImagePath(
sessionId: string,
filename: string,
): string {
- return `/api/inference/sandbox/${encodeURIComponent(sessionId)}/${encodeURIComponent(filename)}`;
+ // Segment by segment, like the file cards: a chart written to outputs/ keeps
+ // a real "/" in the URL, and an encoded one is refused by proxies before the
+ // route ever sees it.
+ return sandboxFilePath(sessionId, filename);
}
diff --git a/studio/frontend/src/components/assistant-ui/sandbox-files-view.tsx b/studio/frontend/src/components/assistant-ui/sandbox-files-view.tsx
new file mode 100644
index 00000000000..1cfb1a60463
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/sandbox-files-view.tsx
@@ -0,0 +1,102 @@
+// 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 { Download01Icon, File02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useCallback, useState } from "react";
+import { toast } from "sonner";
+
+import { authFetch, getAuthToken } from "@/features/auth";
+import { apiUrl } from "@/lib/api-base";
+import { downloadUrlStreaming, isDownloadCancelled } from "@/lib/native-files";
+
+import { sandboxFilePath, type SandboxFile } from "./sandbox-files";
+
+function formatSize(size: number | null): string {
+ if (size === null || size === undefined || Number.isNaN(size)) return "";
+ if (size < 1024) return `${size} B`;
+ if (size < 1024 * 1024) return `${Math.round(size / 1024)} KB`;
+ return `${(size / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+function SandboxFileRow({
+ sessionId,
+ file,
+}: {
+ sessionId: string;
+ file: SandboxFile;
+}) {
+ const [busy, setBusy] = useState(false);
+
+ // Streamed to the chosen path rather than buffered: a tool can write a
+ // multi-gigabyte artifact, and a Blob plus its IPC copy would be two more of
+ // it in the renderer. The bearer goes in the query: no headers are sent.
+ const save = useCallback(async () => {
+ setBusy(true);
+ try {
+ const path = sandboxFilePath(sessionId, file.name);
+ // The bearer rides in the URL, so nothing refreshes it: an expired
+ // access token would save a 401 body under the file's name. authFetch
+ // refreshes and retries, and the HEAD settles that the file is there.
+ const probe = await authFetch(apiUrl(path), { method: "HEAD" });
+ if (!probe.ok) throw new Error(`Download refused (${probe.status})`);
+ const token = getAuthToken();
+ const separator = path.includes("?") ? "&" : "?";
+ // Absolute: the native command parses this and rejects a relative URL,
+ // so a bare /api path failed before the request was made.
+ const url = apiUrl(
+ token ? `${path}${separator}token=${encodeURIComponent(token)}` : path,
+ );
+ await downloadUrlStreaming(url, file.name);
+ } catch (error) {
+ if (!isDownloadCancelled(error)) {
+ toast.error(`Could not save ${file.name}.`);
+ }
+ } finally {
+ setBusy(false);
+ }
+ }, [file.name, sessionId]);
+
+ return (
+ <button
+ type="button"
+ onClick={save}
+ disabled={busy}
+ title={`Save ${file.name}`}
+ className="flex items-center gap-2 rounded border border-border px-2 py-1 text-xs text-foreground hover:bg-muted disabled:opacity-60"
+ >
+ <HugeiconsIcon icon={File02Icon} className="size-3.5 shrink-0" />
+ <span className="truncate font-mono">{file.name}</span>
+ {file.size !== null && (
+ <span className="text-muted-foreground">{formatSize(file.size)}</span>
+ )}
+ <HugeiconsIcon icon={Download01Icon} className="size-3.5 shrink-0" />
+ </button>
+ );
+}
+
+/**
+ * "Files created" row under a tool card. Without it the only trace of a written
+ * file was the model mentioning it in prose.
+ */
+export function SandboxFiles({
+ sessionId,
+ files,
+}: {
+ sessionId: string;
+ files: SandboxFile[];
+}) {
+ if (!sessionId || files.length === 0) return null;
+ return (
+ <div className="mt-2 border-t border-dashed pt-2">
+ <span className="text-xs font-medium text-muted-foreground">
+ {files.length === 1 ? "file created" : "files created"}
+ </span>
+ <div className="mt-1 flex flex-wrap gap-1.5">
+ {files.map((file) => (
+ <SandboxFileRow key={file.name} sessionId={sessionId} file={file} />
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/sandbox-files.ts b/studio/frontend/src/components/assistant-ui/sandbox-files.ts
new file mode 100644
index 00000000000..5a6757c7eba
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/sandbox-files.ts
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** One file a tool call created in the chat's sandbox. */
+export type SandboxFile = {
+ name: string;
+ size: number | null;
+};
+
+const FILES_MARKER = "\n__FILES__:";
+
+/** The tools that emit the file envelope. Nothing else's output is an envelope. */
+export const SANDBOX_FILE_TOOLS = new Set(["python", "terminal"]);
+
+function isSandboxFile(entry: unknown): entry is SandboxFile {
+ if (typeof entry !== "object" || entry === null) return false;
+ const { name, size } = entry as { name?: unknown; size?: unknown };
+ return (
+ typeof name === "string" &&
+ name.length > 0 &&
+ (size === null || size === undefined || typeof size === "number")
+ );
+}
+
+/**
+ * Split a tool result into its visible text and the files the call created.
+ *
+ * `__FILES__` sits ahead of `__IMAGES__` because older clients slice from that
+ * marker to the end. An unparseable payload leaves the text untouched.
+ */
+export function extractCreatedFiles(raw: string): {
+ text: string;
+ files: SandboxFile[];
+} {
+ const start = raw.lastIndexOf(FILES_MARKER);
+ if (start === -1) return { text: raw, files: [] };
+
+ const payloadStart = start + FILES_MARKER.length;
+ const nextMarker = raw.indexOf("\n__", payloadStart);
+ const end = nextMarker === -1 ? raw.length : nextMarker;
+ try {
+ const parsed: unknown = JSON.parse(raw.slice(payloadStart, end));
+ // Every entry, not just the array: a tool printing `__FILES__:[null]` would
+ // otherwise have its output eaten and throw while rendering file.name.
+ if (!Array.isArray(parsed) || !parsed.every(isSandboxFile)) {
+ return { text: raw, files: [] };
+ }
+ return { text: raw.slice(0, start) + raw.slice(end), files: parsed };
+ } catch {
+ return { text: raw, files: [] };
+ }
+}
+
+/** Ids a path segment can carry: ASGI decodes %2F before it matches a route. */
+const PATH_SAFE_SESSION = /^[A-Za-z0-9_-]{1,64}$/;
+
+/** Where this session's files live, as the routes expect to be asked. */
+export function sandboxRoutePrefix(sessionId: string): {
+ prefix: string;
+ query: string;
+} {
+ if (PATH_SAFE_SESSION.test(sessionId)) {
+ return {
+ prefix: `/api/inference/sandbox/${encodeURIComponent(sessionId)}`,
+ query: "",
+ };
+ }
+ // An API client can pick anything; carry it where it survives the round trip.
+ return {
+ prefix: "/api/inference/sandbox/_",
+ query: `?session=${encodeURIComponent(sessionId)}`,
+ };
+}
+
+export function sandboxFilePath(sessionId: string, filename: string): string {
+ // Segment by segment: a file written to outputs/report.csv keeps a real "/"
+ // in the URL, which encodeURIComponent on the whole name would have escaped.
+ const path = filename
+ .split("/")
+ .map((segment) => encodeURIComponent(segment))
+ .join("/");
+ const { prefix, query } = sandboxRoutePrefix(sessionId);
+ return `${prefix}/${path}${query}`;
+}
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
index 04a38624a84..5df11548e0f 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
@@ -5,6 +5,10 @@
import { Spinner } from "@/components/ui/spinner";
import { authFetch } from "@/features/auth";
+
+import { SandboxFiles } from "./sandbox-files-view";
+import type { SandboxFile } from "./sandbox-files";
+import { isSandboxFileList } from "@/features/chat/api/chat-adapter";
import {
preferSanitizedFullToolOutput,
useChatRuntimeStore,
@@ -31,15 +35,19 @@ interface StructuredResult {
text: string;
images: string[];
sessionId: string;
+ files?: SandboxFile[];
}
function isStructuredResult(val: unknown): val is StructuredResult {
+ if (typeof val !== "object" || val === null) return false;
+ const v = val as { files?: unknown };
return (
- typeof val === "object" &&
- val !== null &&
"text" in val &&
"images" in val &&
- "sessionId" in val
+ "sessionId" in val &&
+ // Persisted content can carry anything, and the card maps over this and
+ // reads name off each entry.
+ isSandboxFileList(v.files)
);
}
@@ -143,11 +151,13 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({
let output: string;
let images: string[] = [];
+ let files: SandboxFile[] = [];
let sessionId = "";
if (isStructuredResult(result)) {
output = result.text;
images = result.images;
+ files = result.files ?? [];
sessionId = result.sessionId;
} else if (result != null) {
output = stringifyToolResult(result);
@@ -222,6 +232,9 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({
</div>
) : null}
+ {/* Anything the script wrote, as a real download */}
+ <SandboxFiles sessionId={sessionId} files={files} />
+
{/* Images from Python tool execution */}
{images.length > 0 && sessionId && (
<div className="mt-2 flex flex-col gap-2">
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
index af620963e47..03c1ddbbbc4 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
@@ -16,7 +16,10 @@ import {
import { CopyBtn, ToolCodeCell } from "./tool-code-cell";
import { ToolLiveOutput } from "./tool-live-output";
import { ToolResultOutput } from "./tool-result-output";
+import { SandboxFiles } from "./sandbox-files-view";
+import type { SandboxFile } from "./sandbox-files";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import { isSandboxToolResult } from "@/features/chat/api/chat-adapter";
import { stringifyToolResult } from "@/lib/strip-ansi";
import {
@@ -37,7 +40,21 @@ const TerminalToolUIImpl: ToolCallMessagePartComponent = ({
// Args still streaming = the model is WRITING the command, not running it yet.
const { propStatus } = useToolArgsStatus();
const isWritingCommand = isRunning && propStatus.command === "streaming";
- const output = result == null ? "" : stringifyToolResult(result);
+ // A command that wrote files arrives as the python tool's structured shape;
+ // a plain string means it wrote none.
+ // The same test the adapter applies: a foreign result that merely has text
+ // would otherwise be rendered as that field alone.
+ const structured = isSandboxToolResult(result)
+ ? (result as unknown as { text: string; sessionId?: string; files?: SandboxFile[] })
+ : null;
+ const files = structured?.files ?? [];
+ const sessionId = structured?.sessionId ?? "";
+ const output =
+ structured !== null
+ ? stringifyToolResult(structured.text)
+ : result == null
+ ? ""
+ : stringifyToolResult(result);
// Show the fuller live stream over a truncated result, keeping its exit
// status. Session-transient: after a reload only the result remains.
@@ -99,6 +116,8 @@ const TerminalToolUIImpl: ToolCallMessagePartComponent = ({
<ToolResultOutput text={displayOutput} />
</div>
) : null}
+ {/* Files the command wrote; this card used to show nothing for them */}
+ <SandboxFiles sessionId={sessionId} files={files} />
</div>
</ToolFallbackContent>
</ToolFallbackRoot>
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index b21529882f1..8b8b4666c05 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -21,6 +21,11 @@ import { resolveInitialConfig } from "@/features/model-picker";
import { isMlxId } from "@/features/model-picker/components/model-selector/recommended-fit";
import { usePlatformStore } from "@/config/env";
import { projectHasSources } from "@/features/rag/api/rag-api";
+import {
+ SANDBOX_FILE_TOOLS,
+ extractCreatedFiles,
+ type SandboxFile,
+} from "@/components/assistant-ui/sandbox-files";
import { apiUrl } from "@/lib/api-base";
import { parseParamCountB } from "@/lib/model-size";
import { createLoadingToastIcon, toast } from "@/lib/toast";
@@ -966,6 +971,77 @@ export interface McpImageToolResult {
images: { data: string; mimeType: string }[];
}
+/**
+ * A python/terminal result carrying the chat's sandbox context alongside the
+ * text the model actually saw.
+ */
+/** ``files`` as the cards need it: absent, or entries with a usable name. */
+export function isSandboxFileList(val: unknown): boolean {
+ if (val === undefined || val === null) return true;
+ if (!Array.isArray(val)) return false;
+ return val.every(
+ (entry) =>
+ typeof entry === "object" &&
+ entry !== null &&
+ typeof (entry as { name?: unknown }).name === "string",
+ );
+}
+
+export function isSandboxToolResult(
+ val: unknown,
+): val is { text: string; sessionId: string } {
+ if (typeof val !== "object" || val === null) return false;
+ const v = val as {
+ text?: unknown;
+ sessionId?: unknown;
+ images?: unknown;
+ files?: unknown;
+ };
+ // images too: it is always in Studio's own wrapper, and a tool result that
+ // merely has text and sessionId is someone else's, whose other fields would
+ // be dropped on export.
+ return (
+ typeof v.text === "string" &&
+ typeof v.sessionId === "string" &&
+ Array.isArray(v.images) &&
+ // Persisted content can carry anything: the cards map over this and read
+ // name off each entry, so anything else takes the whole chat view down.
+ isSandboxFileList(v.files)
+ );
+}
+
+/**
+ * The text the model actually saw, for a result that may be wrapped.
+ *
+ * Chat replay and every export path have to agree on this: exports feed
+ * fine-tuning datasets, so a wrapper serialized whole would train on the card's
+ * sessionId/images/files instead of the tool's output.
+ */
+export function toolResultModelText(
+ result: unknown,
+ toolName?: string,
+): unknown {
+ if (isMcpImageToolResult(result) || isSandboxWrapper(result, toolName)) {
+ return result.text;
+ }
+ return result;
+}
+
+/**
+ * A wrapper this app put around a result, rather than a result shaped like one.
+ *
+ * The shape is only that: an MCP or custom tool answering with text, sessionId
+ * and images is someone else's, and unwrapping it drops every other field it
+ * returned. The backend gates the same strip on the tool name.
+ */
+function isSandboxWrapper(
+ result: unknown,
+ toolName?: string,
+): result is { text: string; sessionId: string } {
+ if (toolName !== undefined && !SANDBOX_FILE_TOOLS.has(toolName)) return false;
+ return isSandboxToolResult(result);
+}
+
export function isMcpImageToolResult(
val: unknown,
): val is McpImageToolResult {
@@ -1007,7 +1083,12 @@ function serializeToolResultPart(
// content; serialise a sentinel JSON so legitimately empty tool
// outputs still round-trip the follow-up turn to the provider.
content = result.length > 0 ? result : JSON.stringify({ result: "" });
- } else if (isMcpImageToolResult(result)) {
+ } else if (
+ isMcpImageToolResult(result) ||
+ isSandboxWrapper(result, tc.toolName ?? "")
+ ) {
+ // Replay the stdout the model saw, not the card's sessionId/images/files:
+ // stringifying the wrapper feeds it internal metadata instead of the output.
content = result.text.length > 0 ? result.text : JSON.stringify({ result: "" });
} else {
try {
@@ -5284,14 +5365,26 @@ export function createOpenAIStreamAdapter(
(p) => p.toolCallId === id,
);
if (idx !== -1) {
- const rawResult = (toolEvent.result as string) ?? "";
+ const rawEvent = (toolEvent.result as string) ?? "";
+ // Pulled out first, ahead of __IMAGES__, so the image
+ // slice below is unchanged. Only from the tools that emit
+ // it: elsewhere that line is content, not an envelope.
+ const { text: rawResult, files: createdFiles } =
+ SANDBOX_FILE_TOOLS.has(toolCallParts[idx].toolName ?? "")
+ ? extractCreatedFiles(rawEvent)
+ : { text: rawEvent, files: [] as SandboxFile[] };
const imgMarker = "\n__IMAGES__:";
const imgIdx = rawResult.lastIndexOf(imgMarker);
const mcpImgMarker = "\n__MCP_IMAGES__:";
const mcpImgIdx = rawResult.lastIndexOf(mcpImgMarker);
let parsedResult:
| string
- | { text: string; images: string[]; sessionId: string }
+ | {
+ text: string;
+ images: string[];
+ sessionId: string;
+ files?: SandboxFile[];
+ }
| McpImageToolResult
| {
image_b64: string;
@@ -5348,10 +5441,24 @@ export function createOpenAIStreamAdapter(
const images = JSON.parse(
rawResult.slice(imgIdx + imgMarker.length),
) as string[];
- parsedResult = { text, images, sessionId };
+ parsedResult = {
+ text,
+ images,
+ sessionId,
+ files: createdFiles,
+ };
} catch {
parsedResult = rawResult;
}
+ } else if (createdFiles.length > 0) {
+ // Files but no images: still structured, so the card can
+ // offer downloads.
+ parsedResult = {
+ text: rawResult,
+ images: [],
+ sessionId: sandboxSessionId || "_default",
+ files: createdFiles,
+ };
} else {
parsedResult = rawResult;
}
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index db914e16937..07c29f297a8 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -803,15 +803,20 @@ export async function getForkCount(
return data.count;
}
-export async function deleteChatThreads(threadIds: string[]): Promise<void> {
- if (threadIds.length === 0) return;
+/** Thread ids whose sandbox still holds files, for a caller that never asked. */
+export async function deleteChatThreads(
+ threadIds: string[],
+ args: { deleteFiles?: boolean } = {},
+): Promise<string[]> {
+ if (threadIds.length === 0) return [];
const response = await authFetch("/api/chat/threads", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: threadIds }),
+ body: JSON.stringify({ ids: threadIds, delete_files: !!args.deleteFiles }),
});
- await parseJsonOrThrow<unknown>(response);
+ const data = await parseJsonOrThrow<{ sandboxes_kept?: string[] }>(response);
notifyChatHistoryUpdated();
+ return Array.isArray(data?.sandboxes_kept) ? data.sandboxes_kept : [];
}
export async function listChatProjects(
@@ -868,10 +873,11 @@ export async function updateChatProject(
return project;
}
+/** Member thread ids whose sandbox still holds files, from the route. */
export async function deleteChatProject(
projectId: string,
args: { deleteFiles?: boolean } = {},
-): Promise<void> {
+): Promise<string[]> {
const params = new URLSearchParams();
if (args.deleteFiles) params.set("delete_files", "true");
const qs = params.toString();
@@ -879,8 +885,11 @@ export async function deleteChatProject(
`/api/chat/projects/${encodeURIComponent(projectId)}${qs ? `?${qs}` : ""}`,
{ method: "DELETE" },
);
- await parseJsonOrThrow<ProjectRecord>(response);
+ const data = await parseJsonOrThrow<
+ ProjectRecord & { sandboxes_kept?: string[] }
+ >(response);
notifyChatProjectsUpdated();
+ return Array.isArray(data?.sandboxes_kept) ? data.sandboxes_kept : [];
}
export async function listChatMessages(
@@ -978,14 +987,19 @@ export async function countBackendChats(): Promise<number> {
return data.count;
}
+/** Thread ids whose sandbox still holds files, passed through from the route. */
export async function clearBackendChats(
- options: { notify?: boolean } = {},
-): Promise<void> {
- const response = await authFetch("/api/chat", { method: "DELETE" });
- await parseJsonOrThrow<unknown>(response);
+ options: { notify?: boolean; deleteFiles?: boolean } = {},
+): Promise<string[]> {
+ const response = await authFetch(
+ `/api/chat${options.deleteFiles ? "?delete_files=true" : ""}`,
+ { method: "DELETE" },
+ );
+ const data = await parseJsonOrThrow<{ sandboxes_kept?: string[] }>(response);
if (options.notify !== false) {
notifyChatHistoryUpdated();
}
+ return Array.isArray(data?.sandboxes_kept) ? data.sandboxes_kept : [];
}
export async function buildBackendChatExport(): Promise<{
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-projects.ts b/studio/frontend/src/features/chat/hooks/use-chat-projects.ts
index 86f540654d8..fe93ec4249c 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-projects.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-projects.ts
@@ -12,6 +12,7 @@ import {
moveStoredChatItemToProject,
updateStoredChatProject,
} from "../utils/chat-history-storage";
+import { offerToDeleteKeptSandboxes } from "../utils/offer-kept-sandbox-files";
import type { SidebarItem } from "./use-chat-sidebar-items";
let cachedProjects: ProjectRecord[] = [];
@@ -142,7 +143,11 @@ export async function deleteChatProject(
projectId: string,
args: { deleteFiles?: boolean } = {},
): Promise<void> {
- await deleteStoredChatProject(projectId, args);
+ const kept = await deleteStoredChatProject(projectId, args);
+ // The member chats went with the project, so their own sandboxes are
+ // reachable from nothing: the same offer an ordinary chat delete makes, and
+ // a sandbox the backend could not remove is kept even when asked to go.
+ offerToDeleteKeptSandboxes(kept);
}
export async function moveChatItemToProject(
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
index 2edfc91fe44..398b3b771fc 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
@@ -17,6 +17,7 @@ import {
updateStoredChatThread,
} from "../utils/chat-history-storage";
import { clearComposerDraft } from "../utils/composer-draft";
+import { offerToDeleteKeptSandboxes } from "../utils/offer-kept-sandbox-files";
import { stopChatThread } from "../utils/stop-chat-thread";
import {
markChatThreadsDeleted,
@@ -289,6 +290,7 @@ export async function deleteChatItem(
item: SidebarItem,
activeId: string | undefined,
onSelect: (view: { mode: "single"; newThreadNonce: string }) => void,
+ args: { deleteFiles?: boolean } = {},
) {
const threadIds: string[] =
item.type === "single"
@@ -319,7 +321,11 @@ export async function deleteChatItem(
}
try {
- await deleteStoredChatThreads(threadIds);
+ const kept = await deleteStoredChatThreads(threadIds, args);
+ // Whether or not deletion was asked for: a sandbox that could not be
+ // removed leaves files with no card left to reach them from, and the chat
+ // is already gone, so this offer is the only notice and the only retry.
+ offerToDeleteKeptSandboxes(kept);
} catch (error) {
removeChatThreadTombstones(threadIds);
notifyChatHistoryUpdated();
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 51c50b75e8f..113756c953f 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -140,6 +140,7 @@ export { StopRunningChatsDialog } from "./components/stop-running-chats-dialog";
export { setTrainingCompareHandoff } from "./lib/training-compare-handoff";
export type { ProjectRecord } from "./types";
export { clearAllChats, countAllChats } from "./utils/clear-all-chats";
+export { offerToDeleteKeptSandboxes } from "./utils/offer-kept-sandbox-files";
export { pasteClipboardFiles } from "./utils/clipboard-files";
export {
deleteStoredChatThreads,
diff --git a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
index 989f64ce7dc..0fbd3702da2 100644
--- a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
+++ b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
@@ -56,7 +56,7 @@ import {
syncStoredChatMessages,
} from "../utils/chat-history-storage";
import { notifyChatHistoryUpdated } from "../api/chat-api";
-import { isMcpImageToolResult } from "../api/chat-adapter";
+import { toolResultModelText } from "../api/chat-adapter";
import { usePlusMenuPrefsStore } from "../stores/plus-menu-prefs-store";
import type { ThreadRecord, MessageRecord } from "../types";
import { createConversationMarkdownExporter } from "../utils/conversation-markdown-export";
@@ -166,9 +166,12 @@ function contentBlocksToText(content: unknown): string {
parts.push("[thinking]\n" + thinkText + "\n[/thinking]");
}
} else if (p.type === "tool-call") {
- // Keep base64 image payloads out of every export format: use the
- // model-visible text for MCP image results (matches chat replay).
- const result = isMcpImageToolResult(p.result) ? p.result.text : p.result;
+ // Keep base64 image payloads and sandbox card metadata out of every
+ // export format: use the model-visible text (matches chat replay).
+ const result = toolResultModelText(
+ p.result,
+ typeof p.toolName === "string" ? p.toolName : undefined,
+ );
parts.push(
JSON.stringify({
tool_call: p.toolName,
@@ -261,8 +264,7 @@ function messageToText(msg: { content: unknown; attachments?: unknown }): string
// Markdown counterpart to messageToText: same content and attachments, but each
// part keeps its shape so the renderer can fence tool calls and collapse thinking.
function messageToMarkdown(msg: { content: unknown; attachments?: unknown }): string {
- const normalizeToolResult = (result: unknown): unknown =>
- isMcpImageToolResult(result) ? result.text : result;
+ const normalizeToolResult = toolResultModelText;
const blocks = contentBlocksToMarkdownBlocks(msg.content, normalizeToolResult);
if (Array.isArray(msg.attachments)) {
for (const attachment of msg.attachments as Array<{ content?: unknown }>) {
@@ -332,12 +334,9 @@ function messageToOpenAI(msg: { role: unknown; content: unknown; attachments?: u
// Keep base64 image payloads out of exports: MCP image results carry
// their model-visible text alongside the data, so serialize the text
// (matching chat replay) instead of the full object.
+ const modelText = toolResultModelText(p.result, name);
const resultStr =
- typeof p.result === "string"
- ? p.result
- : isMcpImageToolResult(p.result)
- ? p.result.text
- : JSON.stringify(p.result);
+ typeof modelText === "string" ? modelText : JSON.stringify(modelText);
toolResults.push({ role: "tool", tool_call_id: id, name, content: resultStr });
}
}
diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
index 2ed17c26a0b..c3cf5a964b1 100644
--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
@@ -666,8 +666,8 @@ export async function updateStoredChatProject(
export async function deleteStoredChatProject(
projectId: string,
args: { deleteFiles?: boolean } = {},
-): Promise<void> {
- await deleteChatProject(projectId, args);
+): Promise<string[]> {
+ return deleteChatProject(projectId, args);
}
export async function moveStoredChatItemToProject(
@@ -731,15 +731,18 @@ export async function updateStoredChatThread(
return updateChatThread(threadId, patch);
}
+/** Thread ids whose sandbox still holds files, passed through from the route. */
export async function deleteStoredChatThreads(
idsToDelete: string[],
-): Promise<void> {
- // Incognito threads were never stored, so there's nothing to delete --
- // drop them to skip the no-op backend DELETE (and the history-refresh
- // event it would fire) when the active temporary chat is closed.
+ args: { deleteFiles?: boolean } = {},
+): Promise<string[]> {
+ // An incognito chat stores no history row, but a tool call it made sent this
+ // id as the sandbox session, so closing it is the last thing that can name
+ // that folder. Only the Dexie work below is skipped: it holds nothing.
const ids = idsToDelete.filter((id) => !isThreadIncognito(id));
- if (ids.length === 0) return;
- await deleteChatThreads(ids);
+ if (idsToDelete.length === 0) return [];
+ const kept = await deleteChatThreads(idsToDelete, args);
+ if (ids.length === 0) return kept;
await db
.transaction("rw", db.threads, db.messages, async () => {
await db.messages.where("threadId").anyOf(ids).delete();
@@ -747,6 +750,7 @@ export async function deleteStoredChatThreads(
})
.catch(() => undefined);
markChatThreadsDeleted(ids);
+ return kept;
}
export async function countStoredChats(): Promise<number> {
@@ -758,6 +762,8 @@ export interface ClearStoredChatsResult {
legacy: "cleared" | "failed" | "skipped";
deletedThreadIds: string[];
failedThreadIds: string[];
+ /** Ids whose sandbox still holds files, so the offer can be made once. */
+ sandboxesKept: string[];
}
export async function clearStoredChats(): Promise<ClearStoredChatsResult> {
@@ -783,11 +789,12 @@ export async function clearStoredChats(): Promise<ClearStoredChatsResult> {
legacy: "skipped",
deletedThreadIds: [],
failedThreadIds: [],
+ sandboxesKept: [],
};
try {
// Defer the history refresh until Dexie clear and tombstones finalize,
// so listeners never observe the composite clear mid-flight.
- await clearBackendChats({ notify: false });
+ result.sandboxesKept = await clearBackendChats({ notify: false });
result.backend = "cleared";
} catch (error) {
result.backend = "failed";
diff --git a/studio/frontend/src/features/chat/utils/conversation-markdown.ts b/studio/frontend/src/features/chat/utils/conversation-markdown.ts
index f82b230332c..eb5b17de5e3 100644
--- a/studio/frontend/src/features/chat/utils/conversation-markdown.ts
+++ b/studio/frontend/src/features/chat/utils/conversation-markdown.ts
@@ -534,7 +534,9 @@ function withoutGeneratedAudioBytes(text: string): string {
export function contentBlocksToMarkdownBlocks(
content: unknown,
- normalizeToolResult: (result: unknown) => unknown = (result) => result,
+ normalizeToolResult: (result: unknown, toolName?: string) => unknown = (
+ result,
+ ) => result,
): ConversationMarkdownBlock[] {
if (typeof content === "string") {
return [{ kind: "text", text: withoutGeneratedAudioBytes(content) }];
@@ -562,11 +564,14 @@ export function contentBlocksToMarkdownBlocks(
: "";
if (thinkText) blocks.push({ kind: "thinking", text: thinkText });
} else if (p.type === "tool-call") {
+ const toolName = typeof p.toolName === "string" ? p.toolName : "unknown";
blocks.push({
kind: "tool-call",
- name: typeof p.toolName === "string" ? p.toolName : "unknown",
+ name: toolName,
args: withoutNativePartBytes(p.args),
- result: withoutGeneratedImageBytes(normalizeToolResult(p.result)),
+ result: withoutGeneratedImageBytes(
+ normalizeToolResult(p.result, toolName),
+ ),
});
} else if (
p.type === "source" &&
diff --git a/studio/frontend/src/features/chat/utils/offer-kept-sandbox-files.ts b/studio/frontend/src/features/chat/utils/offer-kept-sandbox-files.ts
new file mode 100644
index 00000000000..0e28d3c3cab
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/offer-kept-sandbox-files.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 { toast } from "sonner";
+import { deleteStoredChatThreads } from "./chat-history-storage";
+
+/**
+ * Offer to delete sandbox files a delete kept.
+ *
+ * Once the chats are gone there is no card left to reach those folders from,
+ * so every delete surface that cannot ask up front makes the offer here.
+ */
+export function offerToDeleteKeptSandboxes(keptThreadIds: string[]): void {
+ if (keptThreadIds.length === 0) return;
+ toast(
+ keptThreadIds.length === 1
+ ? "Files from this chat were kept."
+ : `Files from ${keptThreadIds.length} chats were kept.`,
+ {
+ description:
+ keptThreadIds.length === 1
+ ? "Its sandbox folder is no longer reachable from Studio."
+ : "Their sandbox folders are no longer reachable from Studio.",
+ action: {
+ label: "Delete files",
+ onClick: () => {
+ void deleteStoredChatThreads(keptThreadIds, { deleteFiles: true })
+ .then((stillKept) => {
+ // A tool still running in there, a surviving fork, or a folder
+ // that would not go: the request succeeded and the files did not,
+ // so this offer is the only way back to them.
+ if (stillKept.length > 0) offerToDeleteKeptSandboxes(stillKept);
+ })
+ .catch(() => {
+ toast.error("Could not delete the files.");
+ });
+ },
+ },
+ },
+ );
+}
diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsx
index 58571660a2b..9e4737c4a65 100644
--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx
@@ -34,6 +34,7 @@ import {
downloadChatExport,
exportFineTuneJsonl,
importConversationsFromFile,
+ offerToDeleteKeptSandboxes,
useChatPreferencesStore,
useChatRuntimeStore,
useChatSidebarItems,
@@ -318,6 +319,8 @@ export function DataTab() {
try {
const result = await clearAllChats();
const clearedCount = result.deletedThreadIds.length;
+ // Clear-all has no switch, so the same offer the sidebar makes.
+ offerToDeleteKeptSandboxes(result.sandboxesKept);
const hasFailedStore =
result.backend === "failed" || result.legacy === "failed";
if (!hasFailedStore && result.failedThreadIds.length === 0) {
diff --git a/studio/frontend/tests/python-tool-image-path.test.ts b/studio/frontend/tests/python-tool-image-path.test.ts
index b79c23b7a46..982b9aba724 100644
--- a/studio/frontend/tests/python-tool-image-path.test.ts
+++ b/studio/frontend/tests/python-tool-image-path.test.ts
@@ -7,9 +7,12 @@ import test from "node:test";
import { pythonToolImagePath } from "../src/components/assistant-ui/python-tool-image-path.ts";
test("escapes Python tool image path segments", () => {
+ // An id with a path separator now travels in the query rather than in the
+ // path: an encoded slash is rejected or decoded by proxies before the route
+ // sees it, so it did not survive the round trip.
assert.equal(
pythonToolImagePath("session/id", "loss curve #1.png"),
- "/api/inference/sandbox/session%2Fid/loss%20curve%20%231.png",
+ "/api/inference/sandbox/_/loss%20curve%20%231.png?session=session%2Fid",
);
});