Repository navigation
Studio: show the files a tool call creates, and keep them in one place - #8256
Conversation
Files written by the python or terminal tool were unreachable from the chat:
only images could be fetched back, nothing could list a chat's files, the
terminal tool reported none at all, and the model was never told what happens to
what it writes, so it guessed at a temporary directory and users had to search
the disk.
- both executors report created files via a __FILES__ sentinel, stripped before
the model sees it
- non-images download as attachments, images still render inline
- GET /sandbox/{session_id} lists a chat's files and its path
- tool cards get a 'files created' row with working downloads
- the sandbox moves under the studio home (migrated, overridable) instead of a
third folder in the user's home
- UNSLOTH_COMPILE_LOCATION is pinned before unsloth_zoo reads it, so the
compiled cache stops landing in the launcher's working directory
- deleting a chat cleans up its sandbox
Serving or listing a file resolves the sandbox path instead of creating it, so a GET no longer leaves a folder behind for every id it is asked about. Session ids matching a Windows device name (CON, NUL, COM1) now collapse to _invalid, and the compiled-cache cleanup follows the configured location rather than only the defaults.
Files written into a subdirectory are now found, listed and downloadable, and a run that wrote its file before timing out or being cancelled still reports it. Clearing all chats removes their sandboxes like deleting them one by one does. The legacy migration is serialised and runs for a read too, so an upgraded install does not 404 until some tool happens to run. The image list is capped like the file list, the __FILES__ envelope is only stripped when it parses, and a direct `uvicorn main:app` start pins the compiled-cache location as well.
# Conflicts: # studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
A file-producing call was replayed to the model as the whole card object rather than the stdout it saw; the same shape was already reaching that path for image results, so both go through their text now. The snapshot walk and the download route share one segment limit, so the card cannot advertise a file the route would refuse, and both ends of the __FILES__ envelope check each entry rather than only that it is a list. Size joins mtime in the change key for volumes with coarse timestamps.
The snapshot and the listing apply the download route's own per-segment allowlist, so a name containing a backslash or a control character is never offered as a chip that would then 404. Dotfiles a tool wrote are reported now, since .gitignore is a real artifact and the route serves it; dot-directories stay out, which is where the noise lives. Deleting a chat runs the legacy migration first, so a delete before any tool has run still finds the folder.
UNSLOTH_COMPILE_LOCATION is user-set, and routing the cleanup through it let a value naming a shared directory take that whole tree at startup; a configured path now has to look like a compiled cache before anything deletes from it. The read-only resolver applies the containment check the executing one always had, so a session entry that is a symlink out of the root no longer becomes the root and serves its target. The listing walk drops directory segments the download route would refuse, and executor scratch no longer keeps a deleted chat's folder alive forever.
The export paths feed fine-tuning datasets, and they serialised the card wrapper whole; they share one helper with replay now, which also covers the image shape they never unwrapped either. A file the user named studio_exec_results.csv is no longer treated as the executor's scratch, which is specifically studio_exec_<random>.py. And a sandbox root Studio did not create keeps its permissions, since the override can name a shared directory.
A directory of plain .py files is somebody's package, so the shape test was still too loose: Studio writes a marker file when it creates the location, and a configured path needs that marker or a generated module name before anything deletes from it. Containment moved into one helper applied to cached session paths too, so a directory swapped for a symlink after it was cached stops resolving there.
A directory holding a generated module was treated as ours whole, so a UNSLOTH_COMPILE_LOCATION pointing at a shared directory lost its siblings. Only a directory Studio created (marker) is cleared whole; anywhere else just the generated modules go. Also cap directories visited during the sandbox snapshot, and treat a RecursionError from an oversized __FILES__ payload like the invalid JSON it is.
The listing route grew its own copy of the walk and drifted from the snapshot: no directory budget, a prefix match that hid the user's own studio_exec_results.csv, and a hardcoded file cap. It now shares all three with the snapshot walk. Migration flagged itself complete even when a move raised, so a file locked on Windows was stranded once the destination directory appeared. It reports whether anything movable is left, and only then is it done. Clear-all-chats takes the same delete_files opt-in as DELETE /threads, still off by default.
A session entry replaced by a symlink to a sibling passed the realpath containment check, so deleting that chat took the other one's files. The link itself is dropped and its target left alone. Startup clears the cache it just created, and nothing rewrote the marker afterwards, so the next cleanup demoted our own cache to shared. It is restored after clearing a directory we own. A chat's first turn has no thread id yet but still runs in a real workdir (_default, which the UI and the download route both resolve), so its files get a download chip too. The model- and API-facing message is still stripped, which is the boundary that has to stay clean.
The executor's scratch script moves out of the sandbox, so a tool writing studio_exec_results.py keeps it: nothing in the sandbox belongs to Studio except the remap sidecar it writes itself, which is excluded by exact name. That sidecar was being reported as a user file, which also made a streamed result differ from a non-streamed one. A folder named unsloth_compiled_cache in the launch directory is no longer ours by construction; it needs the marker or generated modules like any other configured location. Containment uses commonpath, so a sandbox root that is a filesystem or volume root no longer sends every chat to _invalid.
Moving it to the system temp directory changed sys.path[0], so a module an earlier call wrote stopped importing, __file__ pointed outside the sandbox, and the script's directory became world-writable /tmp. It is back in the workdir; the reporting exclusion is now this call's exact filename rather than a pattern reserved over user names. A turn with no chat id runs in the shared _default workdir, so reporting its files pinned a card to a directory the next new chat would overwrite. Gated again until a per-chat sandbox exists. register_compiled_cache_on_path applies the same ownership test as cleanup, so an unrelated folder in the launch directory cannot shadow dependencies.
Deleting a chat mid-call removed the empty workdir out from under the running tool, and a process whose cwd is gone fails every relative write. Sessions with a call in flight are tracked and refuse removal. mkdir(exist_ok=True) does not mean Studio created the directory, but the marker that followed licensed an rmtree of it. It is written only when this call actually made the directory.
The busy check released the lock before touching the filesystem, so a tool could start in the window and end up running in a directory the same call then removed. The check and the unlink are one critical section. Chat delete now offers the same switch project delete has, so a chat that wrote files is not left with an unreachable folder. Off by default, and the sandbox is only removed when the user asks.
A delete refused because a tool was running was dropped, and the thread was already gone from history, so nothing would ever name that session again. It is queued and performed when the call ends. The delete switch appeared for training runs and for chats inside a project, where nothing it promises happens. It is shown only where a sandbox can actually be removed, and every opener clears it so it cannot arrive preselected from a cancelled dialog. rmtree refuses a symlink and ignore_errors hid it, so a symlinked UNSLOTH_COMPILE_LOCATION was never cleared. Resolved first.
Resolving the cache path made rmtree follow a link, so a built-in path that is a symlink would have taken its target with it. Being at a built-in path proves ownership of the directory, not of what a link there points at; only the marker on the target does. _default and _invalid are ordinary directories in a writable sandbox, so one replaced by a symlink became the root every unchecked request read from. They go through the same containment as a session. A file delete now detaches the directory under the lock and removes the tree afterwards, so a large sandbox no longer blocks every tool start or the event loop of the route that asked.
…it checked, and reclaim a fork's source
…wrap only our own tools
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c04ff6d956
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # 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) |
There was a problem hiding this comment.
Return 404 when a checked download disappears
When another tool call renames or deletes an artifact between os.open() and this revalidation, os.stat(again) raises FileNotFoundError. The surrounding except BaseException closes the descriptor but re-raises the raw filesystem exception, so an ordinary concurrent file update produces a 500 response instead of the route's intended 404 and the download fails noisily. Convert this revalidation failure to HTTPException(404) as is already done for the initial open.
Useful? React with 👍 / 👎.
| # 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 |
There was a problem hiding this comment.
Protect workspaces reused by a different project ID
When project A is deleted with delete_files=true, the new waits and worker calls leave time for another request to create project B before the workspace removal. _default_project_root uses the project name plus only the first eight sanitized ID characters, so distinct IDs can legitimately resolve to the same existing root; this check looks up only A's ID, remains false, and the later delete_project_workspace(project) recursively deletes B's live workspace. Recheck whether any live project owns the exact root or sandbox immediately before removing it, rather than checking only for reuse of the deleted ID.
Useful? React with 👍 / 👎.
| with open(os.path.join(_orphan_records_dir(), name), "w", encoding = "utf-8") as fh: | ||
| fh.write(_json.dumps(record)) |
There was a problem hiding this comment.
Write orphan records atomically before deleting rows
This record becomes the only durable pointer to a deleted project's custom workspace and to kept chat sandboxes, but opening the final path with "w" truncates it in place. If Studio exits during this write, or two deletion paths write the same record concurrently, the DB row is already gone and the next startup silently ignores the partial JSON, leaving the workspace unreachable and preventing pending deletion or surviving file cards from resolving it. Write a temporary file and atomically replace the record only after the complete JSON is flushed.
Useful? React with 👍 / 👎.
| 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)) |
There was a problem hiding this comment.
Preserve older workspaces when a project ID is reused
The record filename is derived only from the record kind and project ID, but the code explicitly supports recreating the same project ID at a different workspace. If the first deletion left a pending old workspace and the recreated project is then deleted, this write replaces the old record before collection runs; an immediate successful deletion can subsequently unlink the replacement too. The original workspace is then neither resolvable nor collectible, and surviving file cards can lose their only path. Keep records per workspace generation or safely process an existing record before replacing it.
Useful? React with 👍 / 👎.
|
Before/after from two isolated installs, one built at this PR's merge base BEFORE, the card ends at The card is the visible end of it; these come from the same servers that were photographed:
Two notes on reading the picture. The AFTER half is one turn further down its transcript because the model answered the first prompt with a code block instead of calling the tool, so the scene sent it again; both halves are the same request answered by the same tool call. And the ordinary attachment type is deliberate rather than a widened allowlist: the model picks these filenames, so an inline |
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |

Files that a python or terminal tool call writes were effectively unreachable from the chat that produced them, and Studio scattered three folders through the user's home to hold them.
This replaces #8169 with the same fix and none of the multi-process coordination that grew on top of it. See "What is deliberately not here" at the end.
Files a tool call creates
GET /sandbox/{session_id}/{filename}only served six image extensions, so a.csv,.txtor.zipcame back403 File type not allowed. Nothing could list a chat's files._python_execreported new images through the__IMAGES__sentinel and_bash_execreported nothing at all, so a command that wrote a file rendered as(no output). The tool description never said what happens to a written file, so models filled the gap themselves: asked where a file went, Qwen3-8B answered "in the tool's environment, files are stored in a temporary directory", which is why this reads to users as the model inventing files it never wrote.This adds:
__FILES__sentinel from a snapshot helper shared by both executors, listing every file the call created or overwrote with its size. Stripped instrip_result_for_modelso the model never sees it, capped at 25 entries, and it skips the executor's ownstudio_exec_*scratch files. It sits ahead of__IMAGES__because older clients slice from that marker to the end of the string.application/octet-streamwith an RFC 5987Content-Disposition. The allowlist is deliberately not just widened: the model picks these filenames, so an inlinetext/htmlorimage/svg+xmlwould be same-origin script execution.GET /sandbox/{session_id}, returning the sandbox path and its files. The path is the direct answer to "where did my file go".Storage locations
~/studio_sandboxwas the only storage root that ignoredUNSLOTH_STUDIO_HOME, so even an install pinned elsewhere left a stray folder in the user's home. It now lives at<studio home>/sandbox, withUNSLOTH_STUDIO_SANDBOX_HOMEto override and a one-shot migration that moves existing sessions across. A session already present at the new root wins and its old copy is left alone, so nothing is silently overwritten. The migration runs from the lifespan hook rather than the first request, since across filesystems it is a copy.unsloth_compiled_cachewas the bare relative default from unsloth_zoo, resolved against the current directory, andinstall.ps1launches Studio with-WorkingDirectory $env:USERPROFILE, so on Windows it landed next to.unsloth.UNSLOTH_COMPILE_LOCATIONis now pinned in_setup_cache_env(), which runs beforeunsloth_zoo.compileris imported. That ordering matters: the compiler reads the variable at import time and inserts the value intosys.path.cache_cleanupalso looks at the configured location and the current directory, so a cache left by an older install is finally visible to it, and it only deletes files it can prove are generated ones.Deleting a chat now removes its sandbox. An empty one always goes, which is the common case; one with files in it needs an explicit
delete_files, since those files are the user's and are downloadable from the chat. Project workspaces are shared between chats and keep their own delete flow.Not serving or deleting what is not ours
UNSLOTH_STUDIO_SANDBOX_HOMEcan point at a folder the user already keeps things in, and a chat id can name something already in there. Every directory Studio creates gets a.unsloth_sandboxmarker naming the chat that owns it, written withO_EXCLso exactly one id claims a name. A directory that is already there without a marker is stepped around rather than run in, a session entry that is a symlink is never followed or deleted, and every resolved path is checked to be inside the root withcommonpathrather than a prefix test. Ids the filesystem cannot hold become a derived_id-<hash>name, which no chat can be called.Tests
studio/backend/tests/test_sandbox_files_and_storage_roots.py, 127 tests. Covers the sandbox root and its override, the legacy migration, the inline/attachment split, the listing route, both executors reporting files, scratch files staying hidden, the pinned compiled cache, cleanup discovery, and sandbox removal including containment against.., absolute paths, symlinked entries and project sessions.test_tool_sandbox_per_thread.pyis updated for the new root.Verified on
ubuntu-latest,windows-latestandmacos-14, and end to end against installed Studios on all three: the server reports its sandbox under the studio home, and a.csvwritten by a real model in the real UI comes back200where it was403.What is deliberately not here
#8169 grew a second layer for two Studio instances sharing one
UNSLOTH_STUDIO_HOME: asandbox_owners.jsonledger with an interprocess lock, per-process busy leases with a TTL and a heartbeat, deferred deletes, staged cross-filesystem moves and tombstoned deletes that survive a kill mid-way. None of it is in this PR. It is worth judging on its own, since it is a lot of concurrency machinery for a configuration that has to be set up on purpose.The one behaviour that costs: in a root the user pointed us at, a tool that deletes its own
.unsloth_sandboxmarker and then restarts Studio gets a fresh directory, and the earlier files stay on disk under the old name rather than following the chat. At the default root that case is handled, because a directory with no marker there could not have come from anywhere else.