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: offer a download for files edit_file creates (#13448)

Daniel Han38898e2db643
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index 72445fc7500..d0413a46050 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -979,6 +979,8 @@ def _strip_rag_sources_sentinel(result: str) -> str:
# 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"})
+# edit_file emits it too, for a file it created.
+_FILE_SENTINEL_TOOLS = _SANDBOX_TOOLS | {"edit_file"}
# Only an MCP result can carry the UI envelope; mcp_client defuses tool-written ones.
_MCP_TOOL_PREFIX = "mcp__"
@@ -1047,7 +1049,7 @@ def strip_result_for_model(
# After the image strip, which leaves the UI envelope as the tail.
if tool_name is None or tool_name.startswith(_MCP_TOOL_PREFIX):
result = _strip_mcp_ui_suffix(result)
- if tool_name is None or tool_name in _SANDBOX_TOOLS:
+ if tool_name is None or tool_name in _FILE_SENTINEL_TOOLS:
result = _strip_files_sentinel(result)
if tool_name is None or tool_name in _IMAGE_SENTINEL_TOOLS:
result = _strip_images_sentinel(result)
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 4e791d97d4f..dfcee1b83b5 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -12514,6 +12514,28 @@ def _edit_file_replace_all(value: object) -> "bool | None":
return None
+def _edit_file_created_sentinel(target: str, workdir: str) -> str:
+ """The ``__FILES__`` row for a file edit_file just created, so its card offers the download
+ python and terminal cards do. Only files the download route can serve: inside the workdir,
+ within its depth, every segment servable. Edits are not reported; the creating call's row
+ already downloads the current bytes."""
+ try:
+ root = os.path.realpath(workdir)
+ relative = os.path.relpath(target, root)
+ size = os.stat(target).st_size
+ except (OSError, ValueError):
+ return ""
+ parts = relative.split(os.sep)
+ if (
+ parts[0] == os.pardir
+ or os.path.isabs(relative)
+ or len(_user_path_parts(parts, root)) > _MAX_SANDBOX_PATH_SEGMENTS
+ or not all(_servable_segment(part) for part in parts)
+ ):
+ return ""
+ return "\n__FILES__:" + json.dumps([{"name": "/".join(parts), "size": size}])
+
+
def _edit_file_create(
target: str,
new: str,
@@ -12770,7 +12792,18 @@ def _edit_file(
session_id: "str | None" = None,
disable_sandbox: bool = False,
) -> str:
- """Replace exact strings in a file. See the notes above."""
+ """Replace exact strings in a file. See the notes above. The receipt can echo a model-chosen name, so it is
+ defused before the files row of a created file is appended."""
+ created: "list[str]" = []
+ text = _defuse_sentinels(_edit_file_apply(arguments, session_id, disable_sandbox, created))
+ if session_id and created:
+ text += _edit_file_created_sentinel(created[0], _get_workdir(session_id))
+ return text
+
+
+def _edit_file_apply(
+ arguments: dict, session_id: "str | None", disable_sandbox: bool, created: "list[str]"
+) -> str:
# The receipt echoes a window of the file back, so an edit is a read, and Bypass Permissions
# lifts the containment that would otherwise keep it out.
if _references_studio_credential(str(arguments.get("path") or "")):
@@ -12799,13 +12832,16 @@ def _edit_file(
f"combined with the other {len(edits) - 1} edit(s). Create the file "
"in one call, then edit it in the next."
)
- return _edit_file_create(
+ result = _edit_file_create(
target,
edits[0][1],
name,
"\n",
workdir = None if disable_sandbox else _get_workdir(session_id),
)
+ if result.startswith("Created "):
+ created.append(target)
+ return result
for index, (old, new, _) in enumerate(edits, 1):
if not old:
return (
@@ -22608,6 +22644,16 @@ def _defuse_sentinels(text: str) -> str:
_MAX_SNAPSHOT_HASH_BYTES = 64 * 1024 * 1024
+# Dependency and bytecode trees. Walked early, their thousands of files spent the walk's budget and a file the call
+# wrote beside them got no download row.
+_SNAPSHOT_SKIP_DIRS = frozenset({"node_modules", "__pycache__"})
+
+
+def _snapshot_skips_dir(base: str, name: str) -> bool:
+ """`node_modules`, `__pycache__`, or a virtualenv (marked by its pyvenv.cfg, whatever it is named)."""
+ return name in _SNAPSHOT_SKIP_DIRS or os.path.isfile(os.path.join(base, name, "pyvenv.cfg"))
+
+
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
@@ -22638,6 +22684,7 @@ def _snapshot_workdir_files(workdir: str | None) -> "dict[str, tuple]":
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)
]
)
for name in names:
diff --git a/studio/backend/core/rag/conversation_archive.py b/studio/backend/core/rag/conversation_archive.py
index 217caab12e2..484644d8023 100644
--- a/studio/backend/core/rag/conversation_archive.py
+++ b/studio/backend/core/rag/conversation_archive.py
@@ -925,8 +925,8 @@ _EMPTY_TOOL_RESULT = '{"result":""}'
# legitimately be called `web_search`, so the marker or a Gemini native part has to be there too, as the frontend also
# requires.
_SERVER_BUILTIN_NAMES = frozenset({"web_search", "web_fetch", "code_execution", "image_generation"})
-# `SANDBOX_FILE_TOOLS`, and `tool_loop_controller._SANDBOX_TOOLS`. Only these two wrap.
-_SANDBOX_TOOL_NAMES = frozenset({"python", "terminal"})
+# `SANDBOX_FILE_TOOLS`, and `tool_loop_controller._FILE_SENTINEL_TOOLS`. Only these wrap.
+_SANDBOX_TOOL_NAMES = frozenset({"python", "terminal", "edit_file"})
# `search-images.ts`. `re.ASCII` on the scheme because Python's IGNORECASE folds Unicode, so `http\u017f://` would
# match where JavaScript's `/i` does not.
diff --git a/studio/backend/tests/test_conversation_archive.py b/studio/backend/tests/test_conversation_archive.py
index 05d164c807f..a16aec7d082 100644
--- a/studio/backend/tests/test_conversation_archive.py
+++ b/studio/backend/tests/test_conversation_archive.py
@@ -3997,6 +3997,8 @@ def test_a_sandbox_result_is_replayed_as_the_text_the_model_saw():
}
assert _tool_content(_row("terminal", sandbox)) == ["token ZQX-5150"]
+ # edit_file is wrapped the same way when it created a file.
+ assert _tool_content(_row("edit_file", sandbox)) == ["token ZQX-5150"]
assert _tool_content(_row("python", mcp_image)) == ["chart rendered"]
# An empty wrapper text still takes the sentinel, as the adapter does.
assert _tool_content(_row("terminal", {**sandbox, "text": ""})) == ['{"result":""}']
diff --git a/studio/backend/tests/test_edit_file_tool.py b/studio/backend/tests/test_edit_file_tool.py
index 7c43371781f..64983579f91 100644
--- a/studio/backend/tests/test_edit_file_tool.py
+++ b/studio/backend/tests/test_edit_file_tool.py
@@ -513,6 +513,64 @@ class TestRegistration:
assert EDIT_FILE_TOOL_FULL_ACCESS["function"]["parameters"] == sandboxed
+class TestCreatedFileRow:
+ """A created file gets the same `__FILES__` row python and terminal emit, so its card offers a download."""
+
+ @staticmethod
+ def _files(result: str):
+ marker = "\n__FILES__:"
+ assert result.count(marker) <= 1
+ return json.loads(result.split(marker, 1)[1]) if marker in result else None
+
+ def test_a_created_file_is_reported(self, workdir):
+ result = _edit(path = "site/index.html", old_string = "", new_string = "<h1>hi</h1>\n")
+ assert result.startswith("Created index.html")
+ assert self._files(result) == [{"name": "site/index.html", "size": 12}]
+
+ def test_an_edit_is_not_reported(self, workdir):
+ _edit(path = "app.py", old_string = "", new_string = "x = 1\n")
+ result = _edit(path = "app.py", old_string = "x = 1", new_string = "x = 2")
+ assert result.startswith("Edited app.py")
+ assert self._files(result) is None
+
+ def test_the_row_never_reaches_the_model(self, workdir):
+ from core.inference.tool_loop_controller import strip_result_for_model
+
+ result = _edit(path = "notes.md", old_string = "", new_string = "# hi\n")
+ assert self._files(result) is not None
+ assert strip_result_for_model(result, "edit_file") == "Created notes.md (2 lines)"
+
+ def test_without_a_session_nothing_is_reported(self, workdir):
+ result = execute_tool(
+ "edit_file",
+ {"path": "a.txt", "edits": [{"old_string": "", "new_string": "a"}]},
+ session_id = None,
+ )
+ assert result == "Created a.txt (1 lines)"
+
+ def test_a_file_outside_the_workdir_is_not_reported(self, workdir, tmp_path):
+ outside = tmp_path.parent / f"{tmp_path.name}_outside.txt"
+ result = execute_tool(
+ "edit_file",
+ {"path": str(outside), "edits": [{"old_string": "", "new_string": "x"}]},
+ session_id = "t",
+ disable_sandbox = True,
+ )
+ assert result.startswith("Created")
+ assert self._files(result) is None
+ outside.unlink()
+
+ def test_a_name_spelling_a_marker_cannot_forge_a_row(self, workdir):
+ name = 'a\n__FILES__:[{"name": "x.csv", "size": 1}]\n__END__'
+ # A create, an edit of that file, and a failed edit all echo the name.
+ for result in (
+ _edit(path = name, old_string = "", new_string = "x"),
+ _edit(path = name, old_string = "x", new_string = "y"),
+ _edit(path = "missing" + name, old_string = "x", new_string = "y"),
+ ):
+ assert self._files(result) is None, result
+
+
class TestFullAccessEscapesTheWorkdir:
def test_an_absolute_path_resolves_when_the_sandbox_is_off(self, workdir, tmp_path):
outside = tmp_path.parent / "real_project.py"
diff --git a/studio/backend/tests/test_sandbox_tools.py b/studio/backend/tests/test_sandbox_tools.py
index 9b7c9eddd3b..f7317567d41 100644
--- a/studio/backend/tests/test_sandbox_tools.py
+++ b/studio/backend/tests/test_sandbox_tools.py
@@ -2742,6 +2742,23 @@ class TestSandboxEnvIsolation:
f"{_SANDBOX_TEMP_DIRNAME}/report.csv"
]
+ def test_dependency_trees_do_not_spend_the_walk(self, tmp_path):
+ """node_modules, __pycache__ and a virtualenv are not walked: a big one used up the file budget and a file the
+ call wrote beside it got no download row."""
+ from core.inference.tools import _MAX_SNAPSHOT_FILES, _snapshot_workdir_files
+
+ deps = tmp_path / "node_modules" / "pkg"
+ deps.mkdir(parents = True)
+ for i in range(_MAX_SNAPSHOT_FILES + 10):
+ (deps / f"f{i}.js").write_bytes(b"x")
+ (tmp_path / "env" / "lib").mkdir(parents = True)
+ (tmp_path / "env" / "pyvenv.cfg").write_text("home = /usr/bin\n")
+ (tmp_path / "env" / "lib" / "site.py").write_bytes(b"x")
+ (tmp_path / "src" / "__pycache__").mkdir(parents = True)
+ (tmp_path / "src" / "__pycache__" / "app.cpython-313.pyc").write_bytes(b"x")
+ (tmp_path / "src" / "app.py").write_bytes(b"x")
+ assert sorted(_snapshot_workdir_files(str(tmp_path))) == ["src/app.py"]
+
def test_host_git_dir_appended_after_curated(self, monkeypatch, tmp_path):
# #7317: Windows Git lives under Program Files, not System32. Sandbox
# PATH resolves bare `git` by appending the dir of the git the HOST
diff --git a/studio/frontend/src/components/assistant-ui/sandbox-files.ts b/studio/frontend/src/components/assistant-ui/sandbox-files.ts
index be09b2976a2..a48605fad72 100644
--- a/studio/frontend/src/components/assistant-ui/sandbox-files.ts
+++ b/studio/frontend/src/components/assistant-ui/sandbox-files.ts
@@ -9,8 +9,11 @@ export type SandboxFile = {
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"]);
+/** The tools that run code in the sandbox. Their result is always wrapped: the session is the only record of where it ran. */
+export const SANDBOX_RUN_TOOLS = new Set(["python", "terminal"]);
+
+/** The tools that emit the file envelope; edit_file only for a file it created. Nothing else's output is an envelope. */
+export const SANDBOX_FILE_TOOLS = new Set([...SANDBOX_RUN_TOOLS, "edit_file"]);
/**
* The tools that emit the image envelope: the sandbox ones, and the provider's hosted
@@ -18,7 +21,7 @@ export const SANDBOX_FILE_TOOLS = new Set(["python", "terminal"]);
* well-formed `__IMAGES__` line from any other tool as content the model reads, so
* the card has to keep it too, or the user sees less than the model was given.
*/
-export const IMAGE_SENTINEL_TOOLS = new Set([...SANDBOX_FILE_TOOLS, "code_execution"]);
+export const IMAGE_SENTINEL_TOOLS = new Set([...SANDBOX_RUN_TOOLS, "code_execution"]);
function isSandboxFile(entry: unknown): entry is SandboxFile {
if (typeof entry !== "object" || entry === null) return false;
@@ -97,7 +100,7 @@ export function isSandboxToolResult(
);
}
-/** Whether a python/terminal call's card shows a created-files row. */
+/** Whether a sandbox tool call's card shows a created-files row. */
export function hasCreatedFiles(toolName: unknown, result: unknown): boolean {
if (typeof toolName !== "string" || !SANDBOX_FILE_TOOLS.has(toolName)) return false;
if (!isSandboxToolResult(result)) return false;
diff --git a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
index 2a476e76462..7c5054ba516 100644
--- a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
@@ -24,7 +24,13 @@ import {
type McpUiToolResult,
isMcpUiToolResult,
} from "@/features/chat/mcp-apps/mcp-ui";
-import { sandboxSessionIdFor } from "@/components/assistant-ui/sandbox-files";
+import {
+ SANDBOX_FILE_TOOLS,
+ type SandboxFile,
+ isSandboxToolResult,
+ sandboxSessionIdFor,
+} from "@/components/assistant-ui/sandbox-files";
+import { SandboxFiles } from "@/components/assistant-ui/sandbox-files-view";
import { useChatProjectScope } from "@/features/chat/chat-project-scope";
import { stripAnsi, stringifyToolResult } from "@/lib/strip-ansi";
import { cn } from "@/lib/utils";
@@ -484,9 +490,16 @@ const ToolFallbackImpl: ToolCallMessagePartComponent = ({
const isCancelled = isToolCallCancelled(status);
// A widget result's pane shows the text (and images) the model saw, never its UI seed.
const widget = isMcpUiToolResult(result, toolName) ? result : null;
- const shown = widget?.images?.length
- ? { text: widget.text, images: widget.images }
- : (widget?.text ?? result);
+ // edit_file comes wrapped when it created a file: the pane shows its text, the file row sits below.
+ const created =
+ SANDBOX_FILE_TOOLS.has(toolName) && isSandboxToolResult(result)
+ ? (result as { text: string; sessionId: string; files?: SandboxFile[] })
+ : null;
+ const shown = created
+ ? created.text
+ : widget?.images?.length
+ ? { text: widget.text, images: widget.images }
+ : (widget?.text ?? result);
return (
<ToolFallbackRoot
@@ -514,6 +527,14 @@ const ToolFallbackImpl: ToolCallMessagePartComponent = ({
/>
{!isCancelled && <ToolFallbackResult result={shown} />}
</ToolFallbackContent>
+ {/* Files stay outside even when the card is collapsed (#10425) */}
+ {created && (
+ <SandboxFiles
+ className="ml-5"
+ sessionId={created.sessionId}
+ files={created.files ?? []}
+ />
+ )}
</ToolFallbackRoot>
);
};
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 43b30605f2c..4f11af2e992 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -77,6 +77,7 @@ import { projectHasSources } from "@/features/rag/api/rag-api";
import {
IMAGE_SENTINEL_TOOLS,
SANDBOX_FILE_TOOLS,
+ SANDBOX_RUN_TOOLS,
extractCreatedFiles,
isSandboxFileList,
isSandboxToolResult,
@@ -7812,7 +7813,7 @@ export function createOpenAIStreamAdapter(
}
} else if (
createdFiles.length > 0 ||
- SANDBOX_FILE_TOOLS.has(toolCallParts[idx].toolName ?? "")
+ SANDBOX_RUN_TOOLS.has(toolCallParts[idx].toolName ?? "")
) {
// Structured even with neither files nor images, because the session is the only record of
// WHERE this call ran: _created_file_sentinels emits nothing when a concurrent call shared
diff --git a/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts b/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts
index ca663de330a..13dd48a70fc 100644
--- a/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts
+++ b/studio/frontend/src/features/chat/utils/generation-tool-recovery.ts
@@ -3,6 +3,7 @@
import {
SANDBOX_FILE_TOOLS,
+ SANDBOX_RUN_TOOLS,
extractCreatedFiles,
} from "@/components/assistant-ui/sandbox-files";
import {
@@ -111,7 +112,7 @@ function recoveredToolResult(
// Keep malformed envelopes as text.
}
}
- if (sandbox) {
+ if (sandbox && (SANDBOX_RUN_TOOLS.has(toolName as string) || files.length > 0)) {
return { text, images: [], sessionId, files };
}
if (toolName === SEARCH_IMAGE_TOOL) {
diff --git a/studio/frontend/tests/generation-tool-recovery.test.ts b/studio/frontend/tests/generation-tool-recovery.test.ts
index cf253da57ad..fc7f594dc8d 100644
--- a/studio/frontend/tests/generation-tool-recovery.test.ts
+++ b/studio/frontend/tests/generation-tool-recovery.test.ts
@@ -236,6 +236,33 @@ test("sandbox results retain files, images and the run's session", () => {
});
});
+test("an edit_file result is wrapped only when it created a file", () => {
+ const carried: Carried[] = [];
+ const replay = createGenerationToolRecovery(carried, "run").apply;
+ replay(start("a"), 0, 1);
+ replay(
+ {
+ ...end("a"),
+ result: 'Created index.html (2 lines)\n__FILES__:[{"name":"index.html","size":12}]',
+ },
+ 0,
+ 2,
+ "saved-session",
+ );
+ replay(start("b"), 0, 3);
+ replay({ ...end("b"), result: "Edited index.html (1 replacement)" }, 0, 4, "saved-session");
+ assert.deepEqual((carried[0].part as Record<string, unknown>).result, {
+ text: "Created index.html (2 lines)",
+ files: [{ name: "index.html", size: 12 }],
+ images: [],
+ sessionId: "saved-session",
+ });
+ assert.equal(
+ (carried[1].part as Record<string, unknown>).result,
+ "Edited index.html (1 replacement)",
+ );
+});
+
test("MCP image results remain structured and malformed envelopes remain readable", () => {
for (const [result, expected] of [
[
diff --git a/studio/frontend/tests/image-sentinel-tools.test.ts b/studio/frontend/tests/image-sentinel-tools.test.ts
index f20555be520..51b421bb9bb 100644
--- a/studio/frontend/tests/image-sentinel-tools.test.ts
+++ b/studio/frontend/tests/image-sentinel-tools.test.ts
@@ -6,9 +6,8 @@ import test from "node:test";
import { readSrc } from "./helpers/kit.ts";
-const { IMAGE_SENTINEL_TOOLS, SANDBOX_FILE_TOOLS } = await import(
- "../src/components/assistant-ui/sandbox-files.ts"
-);
+const { IMAGE_SENTINEL_TOOLS, SANDBOX_FILE_TOOLS, SANDBOX_RUN_TOOLS, hasCreatedFiles } =
+ await import("../src/components/assistant-ui/sandbox-files.ts");
test("only the tools that emit the image envelope are in the set", () => {
for (const emitter of ["python", "terminal", "code_execution"]) {
@@ -17,9 +16,25 @@ test("only the tools that emit the image envelope are in the set", () => {
for (const reader of ["mcp__fs__read_file", "web_search", "search_knowledge_base", ""]) {
assert.ok(!IMAGE_SENTINEL_TOOLS.has(reader), reader);
}
- for (const sandbox of SANDBOX_FILE_TOOLS) {
+ for (const sandbox of SANDBOX_RUN_TOOLS) {
assert.ok(IMAGE_SENTINEL_TOOLS.has(sandbox), `${sandbox} emits both envelopes`);
}
+ // edit_file emits the file envelope only.
+ assert.ok(!IMAGE_SENTINEL_TOOLS.has("edit_file"));
+});
+
+test("a file edit_file created gets the files row", () => {
+ assert.ok(SANDBOX_FILE_TOOLS.has("edit_file"));
+ assert.ok(!SANDBOX_RUN_TOOLS.has("edit_file"));
+ const wrapped = {
+ text: "Created index.html (2 lines)",
+ images: [],
+ sessionId: "chat-1",
+ files: [{ name: "index.html", size: 12 }],
+ };
+ assert.ok(hasCreatedFiles("edit_file", wrapped));
+ assert.ok(!hasCreatedFiles("edit_file", "Edited index.html (1 replacement)"));
+ assert.ok(!hasCreatedFiles("mcp__fs__write_file", wrapped));
});
// Asserted against the source like the other chat-adapter tests: importing the adapter
diff --git a/studio/frontend/tests/sandbox-reveal-path.test.ts b/studio/frontend/tests/sandbox-reveal-path.test.ts
index d541bc2df16..2ce38908c18 100644
--- a/studio/frontend/tests/sandbox-reveal-path.test.ts
+++ b/studio/frontend/tests/sandbox-reveal-path.test.ts
@@ -271,7 +271,7 @@ test("a sandbox tool result is wrapped even when it carries no envelope", () =>
);
assert.ok(branch.length > 0, "the sandbox result branch moved");
assert.ok(
- branch.includes("SANDBOX_FILE_TOOLS.has(toolCallParts[idx].toolName"),
+ branch.includes("SANDBOX_RUN_TOOLS.has(toolCallParts[idx].toolName"),
"python and terminal results must be wrapped without an envelope too",
);
assert.ok(branch.includes("sessionId: sandboxSessionId"));