Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: walk the sandbox once per tool call boundary for the files card and file history (#15793)
Daniel Hanb581e15d31d4
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 03f8f70765a..e5f3a40d0a7 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -21278,40 +21278,71 @@ def _snapshot_skips_dir(base: str, name: str) -> bool:def _snapshot_workdir_files(workdir: str | None, history: bool = False) -> "dict[str, tuple]":"""Maps every regular file to a change key; digests are added only on coarse-timestamp volumes."""- snapshot: "dict[str, tuple]" = {}+ return _snapshot_workdir_views(workdir, (history,))[0]+++def _snapshot_workdir_views(workdir: "str | None", views: "tuple") -> "list":+ """One walk giving each view (False: files card, True: file history) exactly its own walk."""+ snapshots: "list[dict[str, tuple]]" = [{} for _ in views]if not workdir or not os.path.isdir(workdir):- return snapshot- max_files, max_dirs = (+ return snapshots+ caps = [(_MAX_HISTORY_FILES, _MAX_HISTORY_DIRS)if historyelse (_MAX_SNAPSHOT_FILES, _MAX_SNAPSHOT_DIRS)- )+ for history in views+ ]# Directories are budgeted separately: empty folders never reach the file cap.- visited = 0- hash_budget = 0 if _volume_timestamps_finely(workdir) else _MAX_SNAPSHOT_HASH_BYTES+ visited = [0] * len(views)+ hash_budget = [0 if _volume_timestamps_finely(workdir) else _MAX_SNAPSHOT_HASH_BYTES] * len(+ views+ )+ live = set(range(len(views)))+ # Pre-order restricted to a view's directories is that view's own walk order.+ owners: "dict[str, list[int]]" = {workdir: sorted(live)}+ digests: "dict[str, str | None]" = {}# walked to include nested outputs such as outputs/report.csv that a top-level listing drops.for base, dirs, names in os.walk(workdir):- visited += 1- if visited > max_dirs:- return _CappedSnapshot(snapshot)+ here = []+ for v in owners.pop(base, ()):+ if v not in live:+ continue+ visited[v] += 1+ if visited[v] > caps[v][1]:+ snapshots[v] = _CappedSnapshot(snapshots[v])+ live.discard(v)+ else:+ here.append(v)+ if not live:+ break+ if not here:+ dirs[:] = []+ continue# depth 0 is the workdir itself, whose files are one segment.folder = base[len(workdir) :].strip(os.sep)depth = len(_user_path_parts(folder.split(os.sep) if folder else []))prefix = folder.replace(os.sep, "/") + "/" if folder else ""# skip noisy dot directories except attachments; dot files like .gitignore remain valid artifacts.- dirs[:] = (- []- if not history and depth >= _MAX_SANDBOX_PATH_SEGMENTS - 1- else [- d- for d in dirs- if (not d.startswith(".") or (base == workdir and d == _ATTACHMENTS_DIR))- and _servable_segment(d)- and not _snapshot_skips_dir(base, d)+ kept = [+ d+ for d in dirs+ if (not d.startswith(".") or (base == workdir and d == _ATTACHMENTS_DIR))+ and _servable_segment(d)+ and not _snapshot_skips_dir(base, d)+ ]+ children: "dict[str, list[int]]" = {}+ for v in here:+ history = views[v]+ if not history and depth >= _MAX_SANDBOX_PATH_SEGMENTS - 1:+ continue+ for d in kept:# history drops scratch anyway; a torch.compile cache there would spend the whole budget.- and not (history and base == workdir and not file_history.tracked(d + "/", ()))- ]- )+ if history and base == workdir and not file_history.tracked(d + "/", ()):+ continue+ children.setdefault(d, []).append(v)+ dirs[:] = [d for d in kept if d in children]+ for d in dirs:+ owners[os.path.join(base, d)] = children[d]for name in names:# ignore internal markers only at the root; nested files with these names remain valid artifacts.if base == workdir and name in _INTERNAL_SANDBOX_FILES:@@ -21322,20 +21353,30 @@ def _snapshot_workdir_files(workdir: str | None, history: bool = False) -> "dicttry:# one lstat replaces isfile, islink, and stat while rejecting the same non-regular entries.stat = os.lstat(path)- if not S_ISREG(stat.st_mode):+ except OSError:+ continue+ if not S_ISREG(stat.st_mode):+ continue+ relative = prefix + name+ for v in here:+ if v not in live:continue- relative = prefix + namecontent = None- if hash_budget and hash_budget >= stat.st_size:- content = _content_key(path, stat.st_size)+ if hash_budget[v] and hash_budget[v] >= stat.st_size:+ if path not in digests:+ digests[path] = _content_key(path, stat.st_size)+ content = digests[path]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_files:- return _CappedSnapshot(snapshot)- return snapshot+ hash_budget[v] -= stat.st_size+ snapshots[v][relative] = (stat.st_mtime_ns, stat.st_size, content)+ if len(snapshots[v]) >= caps[v][0]:+ snapshots[v] = _CappedSnapshot(snapshots[v])+ live.discard(v)+ if live.isdisjoint(here):+ break+ if not live:+ break+ return snapshotsclass _CappedSnapshot(dict):@@ -21386,35 +21427,53 @@ def _call_finished(token: "dict | None") -> None:_workdir_calls.pop(token["workdir"], None)-def _history_walk(workdir: str) -> "tuple[dict, bool]":+def _history_walk(workdir: str, snap: "dict | None" = None) -> "tuple[dict, bool]":"""The walk as file history keeps it: without scratch scripts and Studio's own trees. The flagsays whether the walk was whole, since a capped one cannot prove a file is gone."""- snap = _snapshot_workdir_files(workdir, history = True)+ if snap is None:+ snap = _snapshot_workdir_files(workdir, history = True)with _scratch_lock:scratch = set(_active_scratch)kept = {rel: key for rel, key in snap.items() if file_history.tracked(rel, scratch)}return kept, not isinstance(snap, _CappedSnapshot)-def _history_begin(call_token: dict, session_id: "str | None") -> None:+def _history_begin(+ call_token: dict,+ session_id: "str | None",+ walked: "dict | None" = None,+) -> None:if file_history.current_turn() is None:return- snap, complete = _history_walk(call_token["workdir"])+ snap, complete = _history_walk(call_token["workdir"], walked)call_token["history"] = file_history.begin_call(session_id, call_token.get("workdir"), snap, complete = complete)-def _history_end(call_token: "dict | None") -> None:+def _history_end(call_token: "dict | None", walked: "dict | None" = None) -> None:if not call_token or call_token.get("history") is None:return- snap, complete = _history_walk(call_token["workdir"])+ snap, complete = _history_walk(call_token["workdir"], walked)# Checked after the walk: an upload landing mid-walk is in `snap` and must not read as ours.if call_token.get("shared"):call_token["history"].ambiguous = Truefile_history.end_call(call_token["history"], snap, complete = complete)+def _snapshot_and_history_begin(+ workdir: "str | None", call_token: dict, session_id: "str | None"+) -> dict:+ """The pre-run files snapshot, then `_history_begin`, from one walk when history is on."""+ if file_history.current_turn() is None or call_token.get("workdir") != workdir:+ before = _snapshot_workdir_files(workdir)+ _history_begin(call_token, session_id)+ return before+ before, walked = _snapshot_workdir_views(workdir, (False, True))+ _history_begin(call_token, session_id, walked)+ return before++def _walk_lists(workdir: str, rel: str) -> bool:"""Whether `_history_walk` would list *rel*, so a file edit_file records is nevertaken for a deletion by the next python or terminal walk."""@@ -21497,8 +21556,12 @@ def _created_file_sentinels(# 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)- _history_end(token)+ if token is not None and token.get("history") is not None and token.get("workdir") == workdir:+ after, walked = _snapshot_workdir_views(workdir, (False, True))+ _history_end(token, walked)+ else:+ after = _snapshot_workdir_files(workdir)+ _history_end(token)if token is not None and token.get("shared"):# Calls started mid-walk write into `after`, indistinguishable from ours; only known sharing skips.return ""@@ -21617,8 +21680,7 @@ def _python_exec(spill_dir = workdir if session_id else Nonecall_token = _call_started(workdir)# Snapshot mtimes to detect new and overwritten files.- _before = _snapshot_workdir_files(workdir)- _history_begin(call_token, session_id)+ _before = _snapshot_and_history_begin(workdir, call_token, session_id)try:# In the workdir: sys.path[0] keeps earlier helpers importable and __file__ in the sandbox.fd, tmp_path = tempfile.mkstemp(suffix = ".py", prefix = "studio_exec_", dir = workdir)@@ -21865,8 +21927,7 @@ def _bash_exec(spill_dir = workdir if session_id else Nonecall_token = _call_started(workdir)# Same pre-run snapshot as _python_exec, so files a command writes are reported, not "(no output)".- _before = _snapshot_workdir_files(workdir)- _history_begin(call_token, session_id)+ _before = _snapshot_and_history_begin(workdir, call_token, session_id)safe_env = (_build_bypass_env(workdir)if disable_sandboxdiff --git a/studio/backend/tests/test_file_history.py b/studio/backend/tests/test_file_history.pyindex 5d903eec5ae..29d55bd14fe 100644--- a/studio/backend/tests/test_file_history.py+++ b/studio/backend/tests/test_file_history.py@@ -453,17 +453,17 @@ def test_an_upload_during_the_last_walk_is_never_undone_with_it(chat, monkeypatcworkdir, history = chatfile_history.set_turn("chat-1", "u1")_edit("seed.txt", "", "s\n") # the baseline- real_walk, walks = tools._snapshot_workdir_files, []+ real_walk, walks = tools._snapshot_workdir_views, []- def walk_with_an_upload(path, history = False):- walks.append(history)- if history and walks.count(True) == 2:+ def walk_with_an_upload(path, views):+ walks.append(True in views)+ if True in views and walks.count(True) == 2:tools.save_sandbox_upload("s", "upload.txt", [b"mine\n"])- return real_walk(path, history = history)+ return real_walk(path, views)- monkeypatch.setattr(tools, "_snapshot_workdir_files", walk_with_an_upload)+ monkeypatch.setattr(tools, "_snapshot_workdir_views", walk_with_an_upload)execute_tool("python", {"code": "open('out.txt', 'w').write('x')"}, session_id = "s")- monkeypatch.setattr(tools, "_snapshot_workdir_files", real_walk)+ monkeypatch.setattr(tools, "_snapshot_workdir_views", real_walk)report = _rewind(history, ["u1"])assert "upload.txt" in report.conflictsdiff --git a/studio/backend/tests/test_tool_snapshot_shared_walk.py b/studio/backend/tests/test_tool_snapshot_shared_walk.pynew file mode 100644index 00000000000..03034963c7b--- /dev/null+++ b/studio/backend/tests/test_tool_snapshot_shared_walk.py@@ -0,0 +1,175 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""A python or terminal call with file history on walks its folder once per boundary, and that one+walk gives the files card and the history exactly what their own walks gave."""++import os+import random+import sys+from pathlib import Path++import pytest++_BACKEND_ROOT = Path(__file__).resolve().parents[1]+if str(_BACKEND_ROOT) not in sys.path:+ sys.path.insert(0, str(_BACKEND_ROOT))++from core.inference import file_history, tools+from core.inference.tools import execute_tool+++def _reference_walk(workdir, history = False):+ """The single-view walk as it stood before views were shared, kept here as the oracle."""+ snapshot = {}+ if not workdir or not os.path.isdir(workdir):+ return snapshot+ max_files, max_dirs = (+ (tools._MAX_HISTORY_FILES, tools._MAX_HISTORY_DIRS)+ if history+ else (tools._MAX_SNAPSHOT_FILES, tools._MAX_SNAPSHOT_DIRS)+ )+ visited = 0+ hash_budget = 0 if tools._volume_timestamps_finely(workdir) else tools._MAX_SNAPSHOT_HASH_BYTES+ for base, dirs, names in os.walk(workdir):+ visited += 1+ if visited > max_dirs:+ return tools._CappedSnapshot(snapshot)+ folder = base[len(workdir) :].strip(os.sep)+ depth = len(tools._user_path_parts(folder.split(os.sep) if folder else []))+ prefix = folder.replace(os.sep, "/") + "/" if folder else ""+ dirs[:] = (+ []+ if not history and depth >= tools._MAX_SANDBOX_PATH_SEGMENTS - 1+ else [+ d+ for d in dirs+ if (not d.startswith(".") or (base == workdir and d == tools._ATTACHMENTS_DIR))+ and tools._servable_segment(d)+ and not tools._snapshot_skips_dir(base, d)+ and not (history and base == workdir and not file_history.tracked(d + "/", ()))+ ]+ )+ for name in names:+ if base == workdir and name in tools._INTERNAL_SANDBOX_FILES:+ continue+ if not tools._servable_segment(name):+ continue+ path = os.path.join(base, name)+ try:+ stat = os.lstat(path)+ if not tools.S_ISREG(stat.st_mode):+ continue+ content = None+ if hash_budget and hash_budget >= stat.st_size:+ content = tools._content_key(path, stat.st_size)+ if content is not None:+ hash_budget -= stat.st_size+ snapshot[prefix + name] = (stat.st_mtime_ns, stat.st_size, content)+ except OSError:+ continue+ if len(snapshot) >= max_files:+ return tools._CappedSnapshot(snapshot)+ return snapshot+++_DIR_NAMES = [+ "a", "b", "src", "out", ".git", ".hidden", "node_modules", "__pycache__", "venv",+ "unsloth-tmp", ".unsloth_tool_output", tools._ATTACHMENTS_DIR, "deep",+] # fmt: skip+_FILE_NAMES = ["x.txt", "y.py", ".gitignore", "data.csv", "big.bin", "z", tools._SANDBOX_MARKER]+++def _random_tree(root: Path, rng: random.Random) -> None:+ def fill(folder: Path, depth: int) -> None:+ for name in rng.sample(_FILE_NAMES, rng.randint(0, len(_FILE_NAMES))):+ size = rng.choice([0, 3, 100, 5000])+ (folder / name).write_bytes(bytes(rng.getrandbits(8) for _ in range(size)))+ if depth >= 6:+ return+ for name in rng.sample(_DIR_NAMES, rng.randint(0, 4)):+ sub = folder / name+ sub.mkdir(exist_ok = True)+ if name == "venv":+ (sub / "pyvenv.cfg").write_text("home = x\n", encoding = "utf-8")+ fill(sub, depth + 1)+ if rng.random() < 0.3 and hasattr(os, "symlink"):+ try:+ os.symlink(str(folder), str(folder / "loop"))+ os.symlink(str(folder / "x.txt"), str(folder / "link.txt"))+ except OSError:+ pass++ fill(root, 0)++[email protected]("seed", range(40))+def test_shared_walk_gives_each_view_its_own_walk(tmp_path, monkeypatch, seed):+ rng = random.Random(seed)+ workdir = tmp_path / "w"+ workdir.mkdir()+ _random_tree(workdir, rng)+ monkeypatch.setattr(tools, "_MAX_SNAPSHOT_FILES", rng.choice([2000, 1, 5, 20]))+ monkeypatch.setattr(tools, "_MAX_SNAPSHOT_DIRS", rng.choice([2000, 1, 3, 10]))+ monkeypatch.setattr(tools, "_MAX_HISTORY_FILES", rng.choice([20000, 1, 7, 30]))+ monkeypatch.setattr(tools, "_MAX_HISTORY_DIRS", rng.choice([20000, 1, 4, 12]))+ monkeypatch.setattr(tools, "_MAX_SNAPSHOT_HASH_BYTES", rng.choice([64 << 20, 4000, 6000]))+ monkeypatch.setattr(tools, "_volume_timestamps_finely", lambda path, fine = seed % 2: bool(fine))++ for target in (str(workdir), str(tmp_path / "missing"), None):+ card, history = tools._snapshot_workdir_views(target, (False, True))+ for got, want in (+ (card, _reference_walk(target)),+ (history, _reference_walk(target, True)),+ ):+ assert got == want+ assert type(got) is type(want)+ assert tools._snapshot_workdir_files(target) == _reference_walk(target)+ assert type(tools._snapshot_workdir_files(target, history = True)) is type(+ _reference_walk(target, True)+ )+++def chat(tmp_path, monkeypatch):+ workdir = tmp_path / "sandbox"+ workdir.mkdir()+ history = file_history.FileHistory(str(tmp_path / "file_history"))+ monkeypatch.setattr(tools, "_get_workdir", lambda session_id = None: str(workdir))+ monkeypatch.setattr(file_history, "store", lambda: history)+ yield workdir, history+ file_history.set_turn(None, None)++[email protected]("tool", ["python", "terminal"])+def test_a_call_with_history_lists_each_folder_once_per_boundary(chat, monkeypatch, tool):+ workdir, _ = chat+ for i in range(5):+ (workdir / f"d{i}").mkdir()+ (workdir / f"d{i}" / "f.txt").write_text("x\n", encoding = "utf-8")+ real_walk, listed = os.walk, []++ def counting_walk(top, *args, **kwargs):+ # tools.os is os: skip the sandbox's own pre-launch scan (seatbelt / bwrap), same on main.+ counted = sys._getframe(1).f_globals.get("__name__") == tools.__name__+ return _counted(real_walk(top, *args, **kwargs), counted)++ def _counted(walk, counted):+ for entry in walk:+ if counted and entry[0].startswith(str(workdir)):+ listed.append(entry[0])+ yield entry++ monkeypatch.setattr(tools.os, "walk", counting_walk)+ file_history.set_turn("chat-1", "u1")+ code = "open('out.txt', 'w').write('x')"+ # Forward slashes and quotes: the terminal tool runs bash on Windows too, which eats backslashes.+ _exe = sys.executable.replace(os.sep, "/")+ args = {"code": code} if tool == "python" else {"command": f'"{_exe}" -c "{code}"'}+ result = execute_tool(tool, args, session_id = "s")+ monkeypatch.setattr(tools.os, "walk", real_walk)++ assert "out.txt" in result+ for folder in [workdir] + [workdir / f"d{i}" for i in range(5)]:+ assert listed.count(str(folder)) == 2, (folder, listed)+ assert len(listed) == len(set(listed)) + 6, listed