Repository navigation
Studio: show the files a tool call creates, and keep them in one place - #8169
danielhanchen wants to merge 60 commits into
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.
|
Follow-up verification, plus five fixes pushed to this branch. What happened before, and what happens now
Real or notReal. All three were reproduced on a live install before any change. One detail from the report is off: the folder is Does merging break anythingNo new hardware path, and nothing here varies by device. Checked:
Fixes in this pushFound while building the simulations:
Testing
|
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.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 15ca2ce33c
ℹ️ 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".
| const response = await authFetch(sandboxFilePath(sessionId, file.name)); | ||
| if (!response.ok) { | ||
| toast.error(`Could not open ${file.name}.`); | ||
| return; | ||
| } | ||
| await downloadFile(await response.blob(), file.name); |
There was a problem hiding this comment.
Stream large sandbox downloads instead of buffering them
When a tool creates a large artifact such as a multi-gigabyte archive or checkpoint, clicking its new download row first materializes the entire response as a Blob; in Tauri, downloadFile then copies it again through arrayBuffer() into a Uint8Array before invoking Rust. Although FileResponse streams from disk, this path defeats that streaming and can exhaust the Studio process's memory, so arbitrary sandbox files need a streaming/native-path download flow or an explicit supported-size limit.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. downloadFile is the shipped path every download in Studio already uses, including the image route this PR did not touch, so the buffering is pre-existing rather than something introduced here. Replacing it with a streaming or native-path flow is a real change to that helper and belongs in its own PR where it can be tested against the other callers; an arbitrary size cap would just break legitimate large downloads instead. Happy to see it raised on the helper itself.
# 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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1932590573
ℹ️ 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".
| continue | ||
| relative = os.path.relpath(path, workdir).replace(os.sep, "/") | ||
| stat = os.stat(path) | ||
| snapshot[relative] = (stat.st_mtime_ns, stat.st_size) |
There was a problem hiding this comment.
Detect same-size overwrites on coarse filesystems
When the sandbox is on FAT/exFAT or another filesystem with coarse timestamps, overwriting a file with same-length content within one timestamp tick leaves both values in this change key unchanged, so _created_file_sentinels reports no download despite the file being modified. Fresh evidence in this revision is that the attempted fix records only (mtime_ns, size), which still misses common replacements such as changing 0 to 1; include metadata or content identity that also distinguishes same-size overwrites.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The remaining case needs the sandbox on FAT/exFAT, a same-size overwrite, inside one 10ms tick, of a file that already existed before the call. I could not reproduce the coarse-timestamp case at all on ext4 last round, and said so when I took the cheap half of it. Closing the rest means hashing file contents on every tool call, over a directory that can hold checkpoints, which is a real per-call cost for an edge I cannot demonstrate. Open to it with a reproduction.
| after = _snapshot_workdir_files(workdir) | ||
| changed = sorted( | ||
| name for name, key in after.items() if name not in before or before[name] != key | ||
| ) |
There was a problem hiding this comment.
Isolate file attribution across concurrent project tools
When two chats in the same project execute tools concurrently, they deliberately share one project workspace, so this whole-directory before/after comparison cannot identify which process wrote each changed file. For example, if both calls snapshot an empty workspace, one writes b.csv and finishes, and the other later writes a.csv, the latter reports both files on its card even though it created only one. Serialize executions per shared workspace or track writes per invocation so concurrent project chats do not claim each other's artifacts.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Real observation, but not taking it. The failure is a chip appearing on the wrong card in a shared project workspace: the file exists, downloads correctly, and nothing is lost or corrupted. Both suggested fixes are heavy for that -- serialising tool execution per workspace changes concurrency behaviour for every project user, and per-invocation write tracking needs filesystem instrumentation. Sharing the workspace is the point of a project, so imprecise attribution between concurrent calls in it is a tradeoff I would rather keep than pay for that way.
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.
…hat's The derived _id- names are reserved: an id that already looks like one is derived too, so a literal id can no longer land on the directory of whichever unusable id hashes to it. Migration bookkeeping moved into its own object for the same reason, where no session id can name it. A read decides on what is already there, so it now checks ownership of the disambiguated name as well and returns a path under a directory we never create when the answer is no. An entry that is a symlink is stepped around whether its target is inside the root or not: claiming through one writes our marker into a directory somebody else made. The record outranks the marker when reclaiming, since all marker contents are writable from the sandbox and a valid-looking overwrite is no different from a deleted one. Chat deletion runs in a worker: right after an upgrade it also runs the legacy move, which is not something the event loop can wait on. The delete switch is offered for a chat in a project too, whose pre-move files are in its own folder. A files value that is not a list is not a wrapper, since the cards map over it. And a compiled cache in the launch directory needs a file only the compiler writes before it goes on sys.path.
A tool that only ran mkdir, or deleted what it wrote, left a directory tree with no files in it, which the default delete refused and no chat could reach again. Empty now means no files of the user's. A built-in cache path that is a symlink had its target removed by the clear and nothing put back, so the link dangled and the next compile could not write through it. The listing walks up to a couple of thousand entries and stats each one, so it moved into a worker like the delete paths. A persisted files array is only a wrapper if every entry has a name: the rows read it, and one null took the whole chat view down.
The marker is written and read without following a link, so one replaced by a symlink no longer truncates whatever it points at, and does not read as an owner either. A cached path gets the checks a fresh resolve makes. A tool can rename its own directory and leave a link to another chat's in its place, and containment alone accepts that. A recorded directory is only used when it could have been ours: inside the root, not a link, named after this session, and not held by another one. The ledger is under the studio home, which a relative path from a sandbox still reaches, so an entry in it must not be able to name anything this chat would not have been given anyway. A recorded move target that names another root is stale: the override can change between the interrupted move and the retry.
A delete that keeps the files was clearing the note of where they are, which after a tool has taken the marker is the only thing left saying that directory is this session's. It goes now when the removal really happened, and deletion checks ownership through the same trusted-record test the resolver uses.
Two Studios can share a studio home, so the read-modify-write of the ownership file takes a lock file as well as the in-process one, steals one a dead process left behind, and proceeds rather than losing a write if it cannot get it. A _default or _invalid that was already sitting in a shared root is the user's: a call with no session id used to run straight in it. We make one of our own instead, claim it and remember it, so it is the same folder on the next call rather than a new one each time. A name kept on both sides of an interrupted move is deliberate, so the move is finished with it. It was reading as failure, which left the migration flag unset and rescanned the whole legacy tree on every first tool call. An id a path segment cannot carry now rides in a query parameter: ASGI decodes %2F before it matches a route, so a slash in an API client's id arrived as a different id and a different filename.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b0deb94848
ℹ️ 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".
| if _usable_session_id(session_id) and not session_id.startswith(_DERIVED_PREFIX): | ||
| 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. | ||
| return _DERIVED_PREFIX + hashlib.sha256(session_id.encode("utf-8")).hexdigest()[:16] |
There was a problem hiding this comment.
Keep legacy invalid-ID sandboxes reachable
When upgrading a chat whose session ID does not match _SESSION_ID_RE (for example, chat.v1), the previous implementation stored its artifacts in ~/studio_sandbox/_invalid, and migration moves that directory to the new root under the literal _invalid name. This new hashing then resolves the same session to _id-<hash> instead, so persisted image/download cards and subsequent tool calls can no longer find the migrated files. Add a read/migration fallback for the legacy _invalid bucket before assigning invalid IDs their new isolated directories.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
I do not think a fallback is the right answer here. That bucket was shared by every id that failed the pattern, which is exactly the exposure this PR removed at your suggestion two rounds ago: pointing chat.v1 at it would handed it every other invalid-id chat's files, and there is no way to tell which of them are its own. Nothing is lost either, the directory is still sitting in the sandbox root under _invalid where the user can open it, and the cards for those chats were pointing at a shared folder to begin with. I would rather leave it visible than re-create a cross-chat read.
A call in flight is noted in the ledger as well as in memory, so a second Studio sharing this home does not rename a directory its tool is working in. A delete that arrives then is left in the ledger and carried out at the next startup, once nobody holds it. An entry older than a tool call can run is ignored, so a process that died holding one does not keep the folder for good. A cross-filesystem move is assembled under a name nothing resolves and renamed into place, per directory and per file, so a download card opened during the migration cannot read a file that is half copied.
A recorded directory has to carry a name this session could have been given, or a marker naming this session. A prefix test let a chat called a name the folder of one called ab. The busy note is one entry per process and keyed the way the in-memory count is, so two Studios in one sandbox both hold it, the first to finish does not clear the other's note, and two ids differing only in case see each other's. A delete handed over by another Studio carries the exact id and is drained when our own call ends, not only at the next startup. A move interrupted between the copy and the rename is put in place on the next launch: the legacy entry is gone by then, so nothing else would ever look at the staging directory again.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bb403e644a
ℹ️ 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".
| # Longer than a tool call can run, so a process that died holding an entry does | ||
| # not keep a folder alive for good. | ||
| _BUSY_TTL_SECONDS = 900 |
There was a problem hiding this comment.
Refresh busy leases for unlimited tool calls
When the UI's tool timeout is set to “Max,” both safetensors_agentic.py and llama_cpp.py pass timeout=None, so a Python or terminal call can legitimately remain active for longer than 900 seconds. After that point _busy_owners silently discards this lease; another Studio process sharing the same home can consequently delete the chat with files enabled and remove the sandbox while the original process is still using it. Refresh the lease while the call runs or tie its expiry to the actual configured timeout rather than assuming every call ends within 15 minutes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and a call can be given no timeout at all, so the lease could lapse under one that was still running. There is now a single daemon thread that re-writes this process's entries every _BUSY_TTL_SECONDS / 3 while any session is in flight, and stops once none is. Covered by test_a_lease_is_renewed_while_a_call_is_still_running, which expires the entry mid-call and checks it comes back.
Fixed in 7ab0918.
| with _busy_lock: | ||
| owners = _busy_owners(session_id) | ||
| if busy: | ||
| owners[mine] = time.time() |
There was a problem hiding this comment.
Lock the busy-owner read-modify-write
When two Studio processes begin calls for the same session concurrently, each can execute _busy_owners before either reaches _record_workdir; the interprocess file lock is acquired only by the later write, so the second writer can replace the first PID instead of merging it. If the recorded process then finishes first, it clears the only lease while the other call is still active, allowing a subsequent cross-process chat deletion to remove that call's working directory. The owner read and updated ledger write need to occur under one interprocess lock (or use independent per-PID records).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, the read was outside the file lock, so two processes could each save a ledger that never had the other's entry in it. _owners_file_lock is reentrant now and _mark_busy takes it around the read and the write together; _record_workdir still asks for it inside and gets the one already held. test_two_processes_marking_busy_do_not_lose_each_other checks the other pid is visible from inside the critical section and survives the write.
Fixed in 7ab0918.
| try: | ||
| os.rename(staged, target) |
There was a problem hiding this comment.
Claim recovered staging directories in shared roots
When a cross-filesystem legacy migration into UNSLOTH_STUDIO_SANDBOX_HOME is interrupted after shutil.move removes the source but before the final rename, restart reaches this recovery path and renames the staged directory without calling _mark_migrated or recording it in the sessions ledger. Because an overridden root is treated as shared, _session_dir subsequently considers the unmarked target foreign and routes the chat to a different directory, leaving all recovered files inaccessible through its cards and future tool calls. Claim and record the target after promotion just as the normal migration path does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct. The rename put the files back but left them unclaimed and unrecorded, so under an overridden root the next call read the recovered folder as the user's and served nothing. Promotion now does what the ordinary path does: _mark_migrated, record the workdir, clear the migrating entry. test_a_recovered_staging_directory_is_claimed_and_recorded fails on the old code.
Fixed in 7ab0918.
| try: | ||
| names = [n for n in os.listdir(root) if _STAGING_SUFFIX in n] |
There was a problem hiding this comment.
Restrict staging promotion to recorded migrations
During an upgrade where the legacy sandbox directory still exists, this scans the configured sandbox root and treats every directory containing .arriving- as Studio migration state. If UNSLOTH_STUDIO_SANDBOX_HOME points at a shared directory, an unrelated user folder such as reports.arriving-backup is therefore renamed to reports without any marker or ledger evidence that Studio created it. Only promote a precisely shaped staging name whose target matches an active _MIGRATING record.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Yes, a substring test would have renamed a user's own report.arriving-backup over their report. Promotion is now gated on both the exact .arriving-<8 hex> shape and a matching migrating record, so only what a move of ours actually staged is touched. test_a_users_own_arriving_folder_is_left_alone covers the folder and the right-shape-but-never-staged case.
Fixed in 7ab0918.
| name = _sandbox_name(session_id) | ||
| allowed = {name, os.path.basename(_disambiguated_session_dir(root, session_id))} | ||
| if os.path.basename(recorded) not in allowed and _marker_owner(recorded) != name: | ||
| return None |
There was a problem hiding this comment.
Trust recorded fallback directories after marker removal
When both the canonical and disambiguated names are occupied, _ensure_session_dir deliberately creates a random mkdtemp fallback and records it in the ledger. If a tool later deletes or overwrites .unsloth_sandbox, this check rejects that legitimate record because the random basename is not in allowed and the marker no longer identifies it; after restart the chat is assigned another directory, so its existing files disappear from downloads and subsequent tool calls. Preserve a verifiable ledger identity for these fallback names that does not depend solely on the tool-writable marker.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, that was a real regression from the exact-name rule: a tool deleting the marker stranded the fallback directory, which is the only place that chat's files are. A recorded path is trusted again when its basename starts with <name>-. The separator is what keeps it safe, ab-1234 does not start with a-, and test_a_similarly_named_chat_still_cannot_claim_the_fallback pins that alongside test_a_recorded_fallback_survives_losing_its_marker.
Fixed in 7ab0918.
| _record_workdir( | ||
| _session_key(session_id), | ||
| f"{'1' if delete_files else '0'}|{session_id}", | ||
| _PENDING_DELETE, |
There was a problem hiding this comment.
Merge cross-process pending deletion requests
When another Studio is using the sandbox, every deferred deletion overwrites the single _PENDING_DELETE string. Thus a later default deletion can replace an earlier delete_files=True request, or deleting two case-variant IDs that share the folded busy key can retain only the last exact ID; once the active call ends, files the user explicitly requested to remove—or one entire deleted chat's sandbox—remain orphaned. Accumulate all exact IDs and OR each ID's delete_files flag, matching the in-process _pending_removals behavior below.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, one slot per key meant the second request cancelled the first, and the two case variants of an id are two different directories. The entry is now a list keyed by session id with the delete_files flags OR'd together, drained one by one. Both test_two_queued_deletes_are_both_carried_out and test_a_queued_delete_keeps_the_stronger_request fail without it.
Fixed in 7ab0918.
| thread_ids = [thread["id"] for thread in list_chat_threads()] | ||
| _cancel_active_research(request, thread_ids) | ||
| clear_chat_history() |
There was a problem hiding this comment.
Capture cleared thread IDs atomically
When another Studio process creates a thread after list_chat_threads() returns but before clear_chat_history() commits, the clear deletes that new database row too, while _remove_sandboxes receives only the earlier snapshot. The new chat is therefore gone but its sandbox is never considered for cleanup, even when delete_files=true, leaving its artifacts permanently unreachable. Have the clearing transaction return the exact IDs it deleted, or otherwise take the inventory and delete under the same database transaction.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. clear_chat_history() now returns the ids it deleted, read inside the same BEGIN IMMEDIATE transaction as the delete, and the route cleans up those plus the ones it listed. A thread added between the listing and the delete no longer leaves its sandbox stranded. test_clearing_every_chat_reports_what_it_deleted checks the select precedes the delete inside the transaction and that the route uses the result.
Fixed in 7ab0918.
| sandbox_root_path = sandbox_root() | ||
| root_existed = os.path.isdir(sandbox_root_path) | ||
| _migrate_legacy_sandbox(sandbox_root_path) |
There was a problem hiding this comment.
Avoid blocking first tool calls on background migration
When the legacy sandbox is large or lies on another filesystem, startup begins its copy in migrate_legacy_sandbox_in_background, but a tool call arriving before that copy finishes invokes _migrate_legacy_sandbox again here and blocks on _legacy_sandbox_lock for the entire remaining migration. This makes the first Python or terminal call appear hung for potentially minutes despite the explicit startup design of moving the work off request paths. Let calls resolve independently while migration runs, or await only migration of the requested session rather than the whole legacy tree.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, that lock covers the whole tree and across filesystems the copy is minutes. The request path now moves only the requested session, under its own lock, and kicks off the whole-tree pass in the background (one at a time) instead of waiting on it. test_a_first_tool_call_does_not_wait_for_the_whole_legacy_tree makes the whole-tree lock fail if the request path takes it, and still expects that chat's own files to be there.
Fixed in 7ab0918.
…irst tool call Busy leases are renewed while a call is still running, so a call with no timeout cannot have its folder deleted out from under it, and the read and write of the busy entry now happen under one interprocess lock. A recovered staging directory is claimed and recorded like an ordinary move, and only directories a migration of ours actually staged are promoted. Queued deletes accumulate per session instead of overwriting each other, a recorded fallback directory survives losing its marker, clearing every chat reports the ids it deleted, and the first tool call migrates only its own folder while the rest of the tree moves in the background.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8ad71cd117
ℹ️ 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".
| return False | ||
| # The folder may still be at the legacy root right after an upgrade. | ||
| # Outside the lock below: it moves a tree and takes a lock of its own. | ||
| _migrate_legacy_sandbox(sandbox_root()) |
There was a problem hiding this comment.
Migrate only the sandbox being deleted
When a user deletes a chat shortly after upgrading and the legacy sandbox is large or on another filesystem, this call either performs the entire legacy-tree migration or waits for the startup migration's _legacy_sandbox_lock. The DELETE route runs cleanup in a worker but still awaits that worker, so the delete request and UI can remain pending for the full multi-minute copy. Migrate only this session here, as the tool-start path now does, or defer its deletion until the background pass completes.
Useful? React with 👍 / 👎.
| if _busy_elsewhere(session_id): | ||
| # Another Studio is running in there. Left for whichever process is | ||
| # still up when that call ends, rather than pulled out from under it. | ||
| # The id rides along: the key is folded, and the removal is not. | ||
| _queue_pending_delete(session_id, delete_files) |
There was a problem hiding this comment.
Serialize cross-process tool starts with deletion
With two Studio processes sharing the same home, the busy check and sandbox removal are not atomic with the other process entering _session_in_flight: a tool can increment its local count just before publishing its ledger lease, while this process observes no owner and removes the directory. The tool then recreates the sandbox and writes files after the chat has already been deleted, leaving unreachable artifacts despite delete_files=True; if it had already acquired the old cwd, removal can instead disrupt the active call. Coordinate tool starts and deletion with a per-session interprocess lock rather than relying on a check-before-remove lease.
Useful? React with 👍 / 👎.
| with _legacy_one_lock: | ||
| if not os.path.isdir(source): | ||
| return # the background pass got there first |
There was a problem hiding this comment.
Coordinate per-session and background migrations
When the first tool call for a large legacy session overlaps the startup migration on that same session, this separate lock does not exclude the background pass, which holds _legacy_sandbox_lock instead. On a cross-filesystem move both threads can begin copying the same source into different .arriving-* directories; one completes and clears the migrating record while the other fails as the source is removed, leaving its partial or duplicate staging tree permanently hidden because _promote_staged_moves only promotes entries with a matching active record. Use one per-session interprocess migration lock in both paths or have the losing path remove its staging directory.
Useful? React with 👍 / 👎.
| _record_workdir( | ||
| key, | ||
| ",".join(f"{'1' if flag else '0'}|{sid}" for sid, flag in queued.items()), | ||
| _PENDING_DELETE, |
There was a problem hiding this comment.
Encode deferred deletion session IDs losslessly
When an imported or API-created thread ID contains a comma and its deletion is deferred because another Studio process is using the sandbox, this comma-separated encoding changes the ID when _parse_pending splits it. For example, victim,second is later interpreted as victim; the requested sandbox is left behind and, with delete_files=True, an unrelated chat actually named victim can have its files removed. Thread IDs are unrestricted strings and the sandbox resolver explicitly supports non-path-safe IDs, so store this queue as structured JSON or otherwise escape delimiters.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8ad71cd117
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if _busy_heartbeat is not None and _busy_heartbeat.is_alive(): | ||
| return | ||
| _busy_heartbeat_stop.clear() |
There was a problem hiding this comment.
Restart the heartbeat when the old one is stopping
When a new tool call starts after _stop_busy_heartbeat_if_idle has set the stop event but before the old daemon has actually exited, this early return leaves _busy_heartbeat_stop set and starts no replacement. The old thread then terminates, so a Max/no-timeout call can run past _BUSY_TTL_SECONDS without lease refresh; another Studio sharing the home can see no busy owner and delete the sandbox under it.
Useful? React with 👍 / 👎.
| queued[session_id] = delete_files or queued.get(session_id, False) | ||
| _record_workdir( | ||
| key, | ||
| ",".join(f"{'1' if flag else '0'}|{sid}" for sid, flag in queued.items()), |
There was a problem hiding this comment.
Encode queued delete IDs losslessly
When an arbitrary session ID contains a comma, which the new query-based sandbox routes otherwise support for IDs that are not safe path segments, this comma-separated serialization cannot round-trip it because _parse_pending splits the value into different IDs. A cross-process delete queued while that chat is busy will later call remove_session_sandbox for the truncated/mangled ID and leave the real sandbox behind, so store the pending list as JSON or otherwise escape session IDs.
Useful? React with 👍 / 👎.
| if owner is None and not (os.path.isdir(plain) and not _root_is_ours()): | ||
| return plain |
There was a problem hiding this comment.
Step around file collisions in shared sandbox roots
When UNSLOTH_STUDIO_SANDBOX_HOME points at an existing directory that already contains a regular file named like the chat ID, this condition treats that path as usable because it only steps around existing directories. _ensure_session_dir then calls os.makedirs(..., exist_ok=True) on the file and the Python tool path raises before its try block, so that chat cannot run tools; shared-root collisions need to avoid any pre-existing entry, not just directories.
Useful? React with 👍 / 👎.
| if last and session_id: | ||
| _mark_busy(session_id, False) |
There was a problem hiding this comment.
Do not clear a lease after a successor starts
When one call is finishing and another call for the same session starts after the active-session lock is released but before this finalizer runs, the new call records the same PID as busy and then the old call immediately removes that PID. Other Studio processes then see no busy owner for the new still-running call until the next heartbeat refresh, so a cross-process delete can remove its working directory in that window.
Useful? React with 👍 / 👎.
| mine = str(os.getpid()) | ||
| # Both sides under one lock: two processes reading before either writes | ||
| # would each save a ledger without the other's lease in it. | ||
| with _busy_lock, _owners_file_lock(_owners_path() or ""): |
There was a problem hiding this comment.
Create the owners lock directory before locking
On a fresh Studio home, studio_root()/run does not exist when the first _session_in_flight call reaches _mark_busy, so this outer _owners_file_lock cannot create sandbox_owners.json.lock and silently proceeds without the interprocess lock. If two Studio processes start tool calls for the same session in that state, each can read an empty busy entry and then write only its own PID, reintroducing the lost-owner race this ledger is meant to prevent.
Useful? React with 👍 / 👎.
| session = name.rsplit(_STAGING_SUFFIX, 1)[0] | ||
| target = os.path.join(root, session) | ||
| # Only what a move of ours was in the middle of: a shared root can hold | ||
| # a reports.arriving-backup of the user's own. | ||
| if _recorded_workdir(session, _MIGRATING) != target: |
There was a problem hiding this comment.
Match staged moves by recorded target path
When the migration target basename differs from the legacy session ID, such as a shared-root collision moving notes to notes-<hash> or a reserved/derived ID being mapped under _id-..., deriving session from the staging directory name makes the _MIGRATING lookup use the target basename instead of the original ledger key. After an interruption between shutil.move and the final rename, promotion skips the staged directory, the legacy source is already gone, and the chat's files stay hidden under .arriving-*.
Useful? React with 👍 / 👎.
| staged = f"{above}{_STAGING_SUFFIX}{uuid.uuid4().hex[:8]}" | ||
| shutil.move(below, staged) | ||
| os.rename(staged, above) |
There was a problem hiding this comment.
Recover per-file staging names before clearing migration
During _finish_partial_move, an interruption after shutil.move(below, staged) but before os.rename(staged, above) leaves the user file inside the destination as *.arriving-<hex>. The next retry only lists the legacy source, so once that original entry is gone it can remove the source and clear the migration while the file remains under the hidden staging name, breaking existing download cards for that artifact.
Useful? React with 👍 / 👎.
| if not _root_is_ours(): | ||
| return False | ||
| try: | ||
| os.unlink(entry) | ||
| return True |
There was a problem hiding this comment.
Resolve recorded sandboxes before handling name symlinks
When a chat had to use a recorded disambiguated sandbox because root/<session> is a symlink, deletion returns here after unlinking, or refusing to unlink in a shared root, that symlink and never removes the recorded directory that actually contains the chat's files. Deleting such a chat therefore reports success at the default root while leaving its sandbox orphaned, and in a shared root it simply cannot clean up the recorded sandbox.
Useful? React with 👍 / 👎.
|
Superseded by #8256, which carries the same fix: the files a tool call creates are listed and downloadable, the sandbox and the compiled cache move under the studio home, and deleting a chat removes its folder. What is not in #8256 is the second layer this PR grew: the sandbox_owners.json ledger with its interprocess lock, per-process busy leases with a TTL and a heartbeat, deferred deletes, staged cross-filesystem moves and tombstoned deletes. That exists for two Studio instances sharing one UNSLOTH_STUDIO_HOME, which has to be set up on purpose, and it is a lot of concurrency machinery to carry alongside the fix people are actually waiting on. It is worth judging separately, so I would rather bring it back on its own once the core has landed. Closing this in favour of #8256. The open review comments here are all about that second layer. |
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.
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.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.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.Tests
studio/backend/tests/test_sandbox_files_and_storage_roots.py, 12 tests, every one of which fails on main. 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 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.