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.

add a way to open a chat's sandbox folder from the ui (#8661)

Maheswar Kumare2b86860dec7
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 2475eb33c7d..b3a03b50a55 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -15691,6 +15691,58 @@ async def list_sandbox_files(
return {"path": sandbox_dir, "files": files}
[email protected]("/sandbox/{session_id}/reveal")
+async def reveal_sandbox_dir(
+ session_id: str,
+ request: Request,
+ token: Optional[str] = None,
+ session: Optional[str] = None,
+):
+ """Open this chat's sandbox directory in the OS file manager.
+
+ The file manager is the backend host's, so this only means anything when the
+ backend runs on the user's own machine, which is the desktop app.
+ """
+ await _authenticate_header_or_query(request, token)
+
+ from starlette.concurrency import run_in_threadpool
+
+ def _resolve_existing() -> "str | None":
+ sandbox_dir = _sandbox_dir_for(session or session_id, create = False)
+ if not os.path.isdir(sandbox_dir):
+ # One more resolve, as the listing does: the legacy move can rename
+ # the tree into place between resolving it and looking.
+ sandbox_dir = _sandbox_dir_for(session or session_id, create = False)
+ return sandbox_dir if os.path.isdir(sandbox_dir) else None
+
+ # Resolving scans the sandbox root, so it stays off the event loop.
+ sandbox_dir = await run_in_threadpool(_resolve_existing)
+ if sandbox_dir is None:
+ raise HTTPException(status_code = 404, detail = "This chat has no folder yet")
+
+ from pathlib import Path
+
+ from utils.paths.path_utils import reveal_in_file_manager
+
+ try:
+ # expect_dir: a sandbox is always a directory, and a running tool can
+ # replace its own with a file, which would take the file branch and show
+ # the parent, here the root holding every other chat's sandbox.
+ await run_in_threadpool(reveal_in_file_manager, Path(sandbox_dir), expect_dir = True)
+ except FileNotFoundError:
+ # Two things raise this: the sandbox going between resolve and open, and
+ # Popen not finding the file manager at all. Only the first is "no
+ # folder"; the second reported that way hides a missing xdg-open.
+ if os.path.isdir(sandbox_dir):
+ logger.error(f"Failed to reveal sandbox {sandbox_dir}", exc_info = True)
+ raise HTTPException(status_code = 500, detail = "Failed to open file manager")
+ raise HTTPException(status_code = 404, detail = "This chat has no folder yet")
+ except Exception:
+ logger.error(f"Failed to reveal sandbox {sandbox_dir}", exc_info = True)
+ raise HTTPException(status_code = 500, detail = "Failed to open file manager")
+ return {"status": "ok", "path": sandbox_dir}
+
+
@router.api_route("/sandbox/{session_id}/{filename:path}", methods = ["GET", "HEAD"])
async def serve_sandbox_file(
session_id: str,
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index fc42b4f17ca..549f170a41e 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -4869,51 +4869,6 @@ def _resolve_cached_model_path(repo_id: str, variant: Optional[str]) -> Path:
raise HTTPException(status_code = 404, detail = "Cached model path not found")
-def _wsl_reveal_in_explorer(path: Path) -> bool:
- import subprocess
-
- from utils.paths.path_utils import _IS_WSL
-
- if not _IS_WSL:
- return False
- try:
- windows_path = subprocess.run(
- ["wslpath", "-w", str(path)],
- capture_output = True,
- text = True,
- encoding = "utf-8",
- errors = "replace",
- check = True,
- timeout = 10,
- ).stdout.strip()
- if not windows_path:
- return False
- argument = f"/select,{windows_path}" if path.is_file() else windows_path
- subprocess.Popen(["explorer.exe", argument])
- return True
- except (OSError, subprocess.SubprocessError):
- return False
-
-
-def _reveal_in_file_manager(path: Path) -> None:
- """Open the OS file manager with *path* selected (best effort per platform)."""
- import subprocess
-
- target = str(path)
- if sys.platform == "darwin":
- cmd = ["open", "-R", target] if path.is_file() else ["open", target]
- subprocess.Popen(cmd)
- elif os.name == "nt":
- if path.is_file():
- subprocess.Popen(["explorer", f"/select,{target}"])
- else:
- os.startfile(target) # noqa: S606 - local user's own file manager
- elif not _wsl_reveal_in_explorer(path):
- # No cross-desktop "select file" standard on Linux; open the directory.
- directory = target if path.is_dir() else str(path.parent)
- subprocess.Popen(["xdg-open", directory])
-
-
class CachedModelPathResponse(BaseModel):
path: str
is_dir: bool
@@ -4939,12 +4894,14 @@ async def reveal_cached_model(
current_subject: str = Depends(get_current_subject),
):
"""Reveal a cached repo (or one GGUF variant's file) in the OS file manager."""
+ from utils.paths.path_utils import reveal_in_file_manager
+
if not _is_valid_repo_id(repo_id):
raise HTTPException(status_code = 400, detail = "Invalid repo_id format")
variant = (variant or "").strip() or None
path = await asyncio.to_thread(_resolve_cached_model_path, repo_id, variant)
try:
- await asyncio.to_thread(_reveal_in_file_manager, path)
+ await asyncio.to_thread(reveal_in_file_manager, path)
except Exception as e:
logger.error(f"Failed to reveal {path}: {e}")
raise HTTPException(status_code = 500, detail = "Failed to open file manager")
diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
index e6e73ddb315..4cabe17b593 100644
--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py
+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
@@ -13,6 +13,7 @@ import hashlib
import json
import os
import shutil
+import subprocess
import sys
import tempfile
import threading
@@ -124,7 +125,11 @@ def test_sandbox_listing_route_exists():
sandbox_routes = sorted(r.path for r in router.routes if "sandbox" in r.path)
print(f"\nsandbox routes = {sandbox_routes}")
# :path so a file written into a subdirectory is reachable.
- assert sandbox_routes == ["/sandbox/{session_id}", "/sandbox/{session_id}/{filename:path}"]
+ assert sandbox_routes == [
+ "/sandbox/{session_id}",
+ "/sandbox/{session_id}/reveal",
+ "/sandbox/{session_id}/{filename:path}",
+ ]
import inspect
from routes import inference
@@ -1681,16 +1686,17 @@ def test_a_real_project_workspace_is_still_left_alone(tmp_path, monkeypatch):
def test_a_foreign_tool_result_keeps_its_own_fields():
"""Studio's wrapper always carries images; anything else with text and
sessionId is someone else's result and must not be reduced to its text."""
- adapter = (
+ # The predicate lives beside the rest of the sandbox contract, and the
+ # adapter and both tool cards share that one copy.
+ contract = (
Path(__file__).resolve().parents[2]
/ "frontend"
/ "src"
- / "features"
- / "chat"
- / "api"
- / "chat-adapter.ts"
+ / "components"
+ / "assistant-ui"
+ / "sandbox-files.ts"
).read_text(encoding = "utf-8")
- predicate = adapter.split("export function isSandboxToolResult(", 1)[1].split("\n}", 1)[0]
+ predicate = contract.split("export function isSandboxToolResult(", 1)[1].split("\n}", 1)[0]
assert "Array.isArray(v.images)" in predicate, predicate
@@ -2217,14 +2223,16 @@ def test_the_delete_switch_reaches_a_chat_moved_into_a_project():
def test_a_persisted_files_value_that_is_not_a_list_is_not_a_wrapper():
"""The cards map over it, so anything else takes the chat view down."""
root = Path(__file__).resolve().parents[2] / "frontend" / "src"
- adapter = (root / "features" / "chat" / "api" / "chat-adapter.ts").read_text(encoding = "utf-8")
+ contract = (root / "components" / "assistant-ui" / "sandbox-files.ts").read_text(
+ encoding = "utf-8"
+ )
python_card = (root / "components" / "assistant-ui" / "tool-ui-python.tsx").read_text(
encoding = "utf-8"
)
- assert "export function isSandboxFileList" in adapter
+ assert "export function isSandboxFileList" in contract
# Every entry, not just the array: the rows read name off each one.
- assert 'typeof (entry as { name?: unknown }).name === "string"' in adapter
- for source in (adapter, python_card):
+ assert 'typeof (entry as { name?: unknown }).name === "string"' in contract
+ for source in (contract, python_card):
assert "isSandboxFileList(v.files)" in source
@@ -4775,6 +4783,304 @@ def test_a_sandbox_listing_does_not_resolve_on_the_event_loop(tmp_path, monkeypa
assert ran_on and loop_thread not in ran_on, "resolution ran on the event loop"
+def test_revealing_a_sandbox_opens_the_directory_it_resolved(tmp_path, monkeypatch):
+ """The route hands the file manager the resolved sandbox, not the raw id."""
+ import asyncio
+
+ from pathlib import Path as _Path
+
+ from routes import inference
+ from utils.paths import path_utils
+
+ sandbox = tmp_path / "sandbox" / "thread-1"
+ sandbox.mkdir(parents = True)
+ opened = []
+
+ monkeypatch.setattr(inference, "_sandbox_dir_for", lambda session_id, create: str(sandbox))
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ monkeypatch.setattr(
+ path_utils,
+ "reveal_in_file_manager",
+ lambda path, expect_dir = False: opened.append(path),
+ )
+
+ result = asyncio.new_event_loop().run_until_complete(
+ inference.reveal_sandbox_dir("thread-1", request = None, token = None, session = None)
+ )
+ assert result["path"] == str(sandbox)
+ assert opened == [_Path(str(sandbox))]
+
+
+def test_a_sandbox_deleted_mid_request_does_not_reveal_the_root(tmp_path, monkeypatch):
+ """The Linux branch opens the parent when the target is not a directory, and
+ a sandbox's parent is the root holding every other chat's."""
+ import asyncio
+
+ from fastapi import HTTPException
+
+ from routes import inference
+
+ root = tmp_path / "sandbox"
+ sandbox = root / "thread-1"
+ sandbox.mkdir(parents = True)
+ opened = []
+
+ def resolve_then_delete(session_id, create):
+ # Stands in for the chat being deleted between the check and the open.
+ shutil.rmtree(sandbox, ignore_errors = True)
+ return str(sandbox)
+
+ monkeypatch.setattr(inference, "_sandbox_dir_for", resolve_then_delete)
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ monkeypatch.setattr(subprocess, "Popen", lambda cmd, **kw: opened.append(list(cmd)))
+
+ with pytest.raises(HTTPException) as caught:
+ asyncio.new_event_loop().run_until_complete(
+ inference.reveal_sandbox_dir("thread-1", request = None, token = None, session = None)
+ )
+ assert caught.value.status_code == 404
+ assert opened == [], "the parent directory must never be opened"
+
+
+def test_revealing_a_sandbox_that_was_never_created_is_a_404(tmp_path, monkeypatch):
+ """A chat whose tools never ran has no folder, and opening one for it would
+ materialise a directory the user never asked for."""
+ import asyncio
+
+ from fastapi import HTTPException
+
+ from routes import inference
+ from utils.paths import path_utils
+
+ missing = tmp_path / "sandbox" / "thread-1"
+ opened = []
+
+ monkeypatch.setattr(inference, "_sandbox_dir_for", lambda session_id, create: str(missing))
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ monkeypatch.setattr(
+ path_utils,
+ "reveal_in_file_manager",
+ lambda path, expect_dir = False: opened.append(path),
+ )
+
+ with pytest.raises(HTTPException) as caught:
+ asyncio.new_event_loop().run_until_complete(
+ inference.reveal_sandbox_dir("thread-1", request = None, token = None, session = None)
+ )
+ assert caught.value.status_code == 404
+ assert not missing.exists()
+ assert opened == []
+
+
+def test_a_missing_file_manager_is_not_reported_as_a_missing_folder(tmp_path, monkeypatch):
+ """``xdg-open`` is absent on a headless host, and ``Popen`` then raises the
+ same ``FileNotFoundError`` as a missing target. Conflating them tells a user
+ whose files are right there that the chat has no folder."""
+ import asyncio
+
+ from fastapi import HTTPException
+
+ from routes import inference
+ from utils.paths import path_utils
+
+ sandbox = tmp_path / "sandbox" / "thread-1"
+ sandbox.mkdir(parents = True)
+
+ def no_launcher(path, expect_dir = False):
+ raise FileNotFoundError(2, "No such file or directory", "xdg-open")
+
+ monkeypatch.setattr(inference, "_sandbox_dir_for", lambda session_id, create: str(sandbox))
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ monkeypatch.setattr(path_utils, "reveal_in_file_manager", no_launcher)
+
+ with pytest.raises(HTTPException) as caught:
+ asyncio.new_event_loop().run_until_complete(
+ inference.reveal_sandbox_dir("thread-1", request = None, token = None, session = None)
+ )
+ assert caught.value.status_code == 500
+ assert sandbox.is_dir(), "the folder was there the whole time"
+
+
+def test_revealing_a_sandbox_demands_a_directory(tmp_path, monkeypatch):
+ """A tool can replace its own sandbox with a file between the route's isdir
+ check and the open, and the file branch names the parent, here the root
+ holding every other chat's. The route says up front that it only reveals a
+ directory rather than re-checking and losing the same race."""
+ import asyncio
+ import inspect
+
+ from routes import inference
+ from utils.paths import path_utils
+
+ sandbox = tmp_path / "sandbox" / "thread-1"
+ sandbox.mkdir(parents = True)
+ seen = []
+
+ monkeypatch.setattr(inference, "_sandbox_dir_for", lambda session_id, create: str(sandbox))
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ monkeypatch.setattr(
+ path_utils,
+ "reveal_in_file_manager",
+ lambda path, expect_dir = False: seen.append((path, expect_dir)),
+ )
+
+ asyncio.new_event_loop().run_until_complete(
+ inference.reveal_sandbox_dir("thread-1", request = None, token = None, session = None)
+ )
+ assert seen and seen[0][1] is True, "the sandbox reveal must demand a directory"
+
+ # The cached-model reveal shares the helper and legitimately points at a
+ # file, so it must NOT inherit the flag.
+ from routes import models
+
+ assert "expect_dir" not in inspect.getsource(models.reveal_cached_model)
+
+
+def test_revealing_reads_the_session_query_the_frontend_falls_back_to(tmp_path, monkeypatch):
+ """ASGI decodes ``%2F`` before routing, so a slashed id travels as
+ ``/sandbox/_/reveal?session=``. The listing route already reads it and this
+ one must agree, or such a chat silently reveals the wrong folder."""
+ import asyncio
+
+ from routes import inference
+ from utils.paths import path_utils
+
+ asked = []
+ sandbox = tmp_path / "sandbox" / "resolved"
+ sandbox.mkdir(parents = True)
+
+ def resolve(session_id, create):
+ asked.append(session_id)
+ return str(sandbox)
+
+ monkeypatch.setattr(inference, "_sandbox_dir_for", resolve)
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ monkeypatch.setattr(path_utils, "reveal_in_file_manager", lambda path, expect_dir = False: None)
+
+ asyncio.new_event_loop().run_until_complete(
+ inference.reveal_sandbox_dir("_", request = None, token = None, session = "thread/with/slashes")
+ )
+ assert asked == ["thread/with/slashes"], "the placeholder segment was resolved instead"
+
+
+def test_revealing_authenticates_before_it_touches_the_filesystem(tmp_path, monkeypatch):
+ """Resolution scans the sandbox root, so an unauthenticated caller must not
+ reach it -- and must certainly not reach the file manager."""
+ import asyncio
+
+ from fastapi import HTTPException
+
+ from routes import inference
+
+ resolved = []
+ opened = []
+
+ async def refuse(request, token):
+ raise HTTPException(status_code = 401, detail = "Not authenticated")
+
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", refuse)
+ monkeypatch.setattr(inference, "_sandbox_dir_for", lambda *a, **k: resolved.append(a) or "")
+ monkeypatch.setattr(subprocess, "Popen", lambda cmd, **kw: opened.append(list(cmd)))
+
+ with pytest.raises(HTTPException) as caught:
+ asyncio.new_event_loop().run_until_complete(
+ inference.reveal_sandbox_dir("thread-1", request = None, token = None, session = None)
+ )
+ assert caught.value.status_code == 401
+ assert resolved == [] and opened == []
+
+
+def test_a_traversal_id_stays_inside_the_sandbox_root_and_opens_nothing(tmp_path, monkeypatch):
+ """The id is a name, not a path. Every one of these must derive a name
+ inside the root, find nothing there, and launch nothing."""
+ import asyncio
+
+ from fastapi import HTTPException
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+
+ from routes import inference
+
+ monkeypatch.setattr(inference, "_authenticate_header_or_query", _noop_async)
+ opened = []
+ monkeypatch.setattr(subprocess, "Popen", lambda cmd, **kw: opened.append(list(cmd)))
+
+ for probe in (
+ "../../../../etc",
+ "..",
+ "/etc",
+ "thread/../../../etc",
+ "..\\..\\windows",
+ "C:\\Windows",
+ "con",
+ "x" * 300,
+ ):
+ with pytest.raises(HTTPException) as caught:
+ asyncio.new_event_loop().run_until_complete(
+ inference.reveal_sandbox_dir("_", request = None, token = None, session = probe)
+ )
+ assert caught.value.status_code == 404, probe
+ resolved = inference._sandbox_dir_for(probe, create = False)
+ assert not os.path.exists("/etc/.unsloth_sandbox")
+ assert (
+ Path(resolved).is_relative_to(tmp_path / "home") or not Path(resolved).exists()
+ ), probe
+ assert opened == [], "a refused id must never reach the file manager"
+
+
+def test_a_sandbox_file_named_reveal_is_still_served(tmp_path):
+ """The POST route shares the path the download route matches with
+ ``{filename:path}``. Being POST-only keeps a file called ``reveal``
+ reachable, which widening the method list later would silently undo."""
+ from routes.inference import router
+
+ scope = {
+ "type": "http",
+ "method": "GET",
+ "path": "/sandbox/thread-1/reveal",
+ "headers": [],
+ "root_path": "",
+ }
+ matched = [r for r in router.routes if r.matches(scope)[0].name == "FULL"]
+ assert [r.endpoint.__name__ for r in matched] == ["serve_sandbox_file"]
+
+ scope["method"] = "POST"
+ matched = [r for r in router.routes if r.matches(scope)[0].name == "FULL"]
+ assert [r.endpoint.__name__ for r in matched] == ["reveal_sandbox_dir"]
+
+
+def test_the_cached_model_reveal_still_goes_through_the_moved_helper(tmp_path, monkeypatch):
+ """The moved helper's one prior caller must behave as at the merge base,
+ including for the symlinked entries an HF cache is made of."""
+ import asyncio
+
+ from routes import models
+ from utils.paths import path_utils
+
+ real = tmp_path / "blobs" / "model.gguf"
+ real.parent.mkdir(parents = True)
+ real.write_bytes(b"gguf")
+ link = tmp_path / "snapshot" / "model.gguf"
+ link.parent.mkdir(parents = True)
+ link.symlink_to(real)
+
+ opened = []
+ monkeypatch.setattr(models, "_resolve_cached_model_path", lambda repo_id, variant: link)
+ monkeypatch.setattr(
+ path_utils,
+ "reveal_in_file_manager",
+ lambda path, expect_dir = False: opened.append(path),
+ )
+
+ result = asyncio.new_event_loop().run_until_complete(
+ models.reveal_cached_model(
+ repo_id = "unsloth/Llama-3.2-1B", variant = None, current_subject = "unsloth"
+ )
+ )
+ assert result == {"status": "ok", "path": str(link)}
+ assert opened == [link], "a symlinked cache entry must still be revealed"
+
+
def test_a_kept_sandbox_is_offered_even_when_deletion_was_asked_for():
"""A sandbox the backend could not remove comes back as kept, and by then
the chat has gone: this offer is the only notice and the only retry."""
diff --git a/studio/backend/utils/paths/__init__.py b/studio/backend/utils/paths/__init__.py
index e812fa9e615..5ed7ae102c0 100644
--- a/studio/backend/utils/paths/__init__.py
+++ b/studio/backend/utils/paths/__init__.py
@@ -11,6 +11,7 @@ from .path_utils import (
resolve_cached_repo_id_case,
get_cache_case_resolution_stats,
reset_cache_case_resolution_state,
+ reveal_in_file_manager,
)
from .storage_roots import (
studio_root,
@@ -61,6 +62,7 @@ __all__ = [
"resolve_cached_repo_id_case",
"get_cache_case_resolution_stats",
"reset_cache_case_resolution_state",
+ "reveal_in_file_manager",
"studio_root",
"assets_root",
"datasets_root",
diff --git a/studio/backend/utils/paths/path_utils.py b/studio/backend/utils/paths/path_utils.py
index 55fafeeb0e5..12c177b5982 100644
--- a/studio/backend/utils/paths/path_utils.py
+++ b/studio/backend/utils/paths/path_utils.py
@@ -207,3 +207,74 @@ def reset_cache_case_resolution_state() -> None:
_CACHE_CASE_RESOLUTION_MEMO.clear()
for key in _CACHE_CASE_RESOLUTION_STATS:
_CACHE_CASE_RESOLUTION_STATS[key] = 0
+
+
+def _wsl_reveal_in_explorer(path: Path, is_file: bool) -> bool:
+ import subprocess
+ if not _IS_WSL:
+ return False
+ try:
+ windows_path = subprocess.run(
+ ["wslpath", "-w", str(path)],
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ check = True,
+ timeout = 10,
+ ).stdout.strip()
+ if not windows_path:
+ return False
+ argument = f"/select,{windows_path}" if is_file else windows_path
+ subprocess.Popen(["explorer.exe", argument])
+ return True
+ except (OSError, subprocess.SubprocessError):
+ return False
+
+
+def reveal_in_file_manager(path: Path, expect_dir: bool = False) -> None:
+ """Open the OS file manager with *path* selected (best effort per platform).
+
+ Raises ``FileNotFoundError`` when the target is gone: the Linux branch falls
+ back to the parent, which for a sandbox is the root holding every other
+ chat's.
+
+ ``expect_dir`` refuses anything that is not a real directory, symlinks
+ included, since both would take the file branch and name that same parent.
+ One ``lstat`` answers type and link-ness together, leaving no window between
+ the checks (``is_dir()`` follows links; ``follow_symlinks = False`` is 3.13+
+ only, and this runs on 3.10). Off by default: the cached-model reveal points
+ at a file, and a symlinked one, as an HF cache snapshot is a link farm.
+ """
+ import stat as stat_module
+ import subprocess
+
+ if expect_dir:
+ try:
+ entry = os.lstat(path) # No-follow, and the only stat here.
+ except OSError as exc:
+ raise FileNotFoundError(str(path)) from exc
+ if not stat_module.S_ISDIR(entry.st_mode):
+ raise FileNotFoundError(str(path))
+ is_dir, is_file = True, False
+ else:
+ if not path.exists():
+ raise FileNotFoundError(str(path))
+ # Decided ONCE and then only read; each branch used to re-stat.
+ is_dir = path.is_dir()
+ is_file = not is_dir and path.is_file()
+ if not is_dir and not is_file:
+ raise FileNotFoundError(str(path))
+
+ target = str(path)
+ if sys.platform == "darwin":
+ cmd = ["open", "-R", target] if is_file else ["open", target]
+ subprocess.Popen(cmd)
+ elif os.name == "nt":
+ if is_file:
+ subprocess.Popen(["explorer", f"/select,{target}"])
+ else:
+ os.startfile(target) # noqa: S606 - local user's own file manager
+ elif not _wsl_reveal_in_explorer(path, is_file):
+ # No cross-desktop "select file" standard on Linux; open the directory.
+ subprocess.Popen(["xdg-open", str(path.parent) if is_file else target])
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 1b5a4422626..1f79bf533b0 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -78,6 +78,7 @@ import {
Edit03Icon,
FolderAddIcon,
FolderExportIcon,
+ FolderOpenIcon,
Folder01Icon,
FlimSlateIcon,
Globe02Icon,
@@ -104,6 +105,7 @@ import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
import {
Tooltip,
TooltipContent,
+ TooltipTrigger,
} from "@/components/ui/tooltip";
import { Tooltip as TooltipPrimitive } from "radix-ui";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -120,8 +122,10 @@ import {
clearNewChatDraft,
deleteChatProject,
deleteChatItem,
+ listStoredChatMessages,
listStoredChatThreads,
moveChatItemToProject,
+ recordedSandboxSessionId,
notifyChatHistoryUpdated,
renameChatItem,
renameChatProject,
@@ -138,6 +142,11 @@ import {
type ProjectRecord,
type SidebarItem,
} from "@/features/chat";
+import { sandboxSessionIdFor } from "@/components/assistant-ui/sandbox-files";
+import {
+ revealSandbox,
+ sandboxHasFiles,
+} from "@/components/assistant-ui/sandbox-reveal";
import { NewProjectDialog } from "@/features/chat/components/new-project-dialog";
import {
useAppearanceCustomStore,
@@ -325,6 +334,55 @@ function preloadSilently(request: Promise<unknown>): void {
}
// "New" pill for recent tabs. Same recipe as the brand "beta" badge.
+/**
+ * "Open chat folder" for a browser session, where the backend's file manager is
+ * not the user's. Radix's `disabled` takes the row's pointer events away and a
+ * tooltip is blocked while the menu owns the screen, so the row stays enabled,
+ * refuses the select itself, and drives a controlled tooltip off a
+ * pointer-events-none anchor (as the MCP rows do).
+ *
+ * The reason is carried twice: the tooltip hangs off an aria-hidden anchor and
+ * opens on hover, which a screen reader never reaches and a touch device does
+ * not have, so `title` describes the row itself and selecting it (tap or Enter)
+ * opens the hint rather than doing nothing.
+ */
+function OpenChatFolderUnavailableItem() {
+ const [hintOpen, setHintOpen] = useState(false);
+
+ return (
+ <DropdownMenuItem
+ aria-disabled={true}
+ title="Opening the folder needs the desktop app. In a browser, save a file from the card that created it."
+ className="relative opacity-50"
+ onSelect={(event) => {
+ event.preventDefault();
+ setHintOpen(true);
+ }}
+ onPointerEnter={() => setHintOpen(true)}
+ onPointerLeave={() => setHintOpen(false)}
+ onFocus={() => setHintOpen(true)}
+ onBlur={() => setHintOpen(false)}
+ >
+ <HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />
+ <span>Open chat folder</span>
+ <Tooltip open={hintOpen}>
+ {/* Our wrapper, not the raw primitive: it registers the trigger element,
+ without which the tooltip counts itself blocked by the open menu. */}
+ <TooltipTrigger asChild={true}>
+ <span
+ aria-hidden={true}
+ className="pointer-events-none absolute inset-y-0 right-0 w-0"
+ />
+ </TooltipTrigger>
+ <TooltipContent side="right" className="max-w-[220px]">
+ Opening the folder needs the desktop app. In a browser, save a file
+ from the card that created it.
+ </TooltipContent>
+ </Tooltip>
+ </DropdownMenuItem>
+ );
+}
+
function NavBadge({ label, className }: { label: string; className?: string }) {
return (
<span
@@ -1567,6 +1625,12 @@ export function AppSidebar() {
) {
const threadIds = getSidebarItemThreadIds(item);
const isPinned = pinnedIdSet.has(item.id);
+ // A compare row outside a project spans two sandboxes, and there is no
+ // honest single folder to offer for it.
+ const sandboxSessionId =
+ item.type === "single" || item.projectId
+ ? sandboxSessionIdFor(threadIds[0] ?? item.id, item.projectId)
+ : undefined;
// A compare row's id is the pair id while runningByThreadId is per pane thread; aggregate.
const isGenerating =
item.type === "compare"
@@ -1775,6 +1839,77 @@ export function AppSidebar() {
<HugeiconsIcon icon={isPinned ? PinOffIcon : PinIcon} strokeWidth={1.75} className="size-icon" />
<span>{isPinned ? "Unpin chat" : "Pin chat"}</span>
</DropdownMenuItem>
+ {sandboxSessionId ? (
+ isTauri ? (
+ <DropdownMenuItem
+ title="Open the folder this chat's tool calls read and write"
+ onSelect={() => {
+ void (async () => {
+ try {
+ // A chat moved between projects keeps the sandbox it
+ // wrote to, so its own history names the folder, not
+ // current membership. Every pane is read, since a
+ // compare row can hold one folder per pane.
+ // One at a time, not Promise.all: this file's export
+ // contract forbids a concurrent await here, and two
+ // panes win nothing. A failed read stops the loop and
+ // is reported below rather than being caught per pane,
+ // which would read as "never ran a tool" and fall back
+ // to current membership, the answer the recorded id
+ // exists to override.
+ const ids =
+ threadIds.length > 0 ? threadIds : [item.id];
+ const recorded: (string | undefined)[] = [];
+ for (const threadId of ids) {
+ recorded.push(
+ recordedSandboxSessionId(
+ await listStoredChatMessages(threadId),
+ ),
+ );
+ }
+ let distinct = [...new Set(recorded.filter(Boolean))];
+ if (distinct.length === 0 && item.projectId) {
+ // Chats stored before results carried a session
+ // recorded nothing, so one that ran loose and has
+ // since joined a project would be sent to the project
+ // workspace. Its thread sandbox is the only other
+ // candidate, and files there are this chat's. Only in
+ // this direction: a chat moved OUT wrote under
+ // project-<id>, and nothing retains which one.
+ const held: string[] = [];
+ for (const threadId of ids) {
+ if (await sandboxHasFiles(threadId)) {
+ held.push(threadId);
+ }
+ }
+ distinct = [...new Set(held)];
+ }
+ if (distinct.length > 1) {
+ toast.error("This chat wrote to more than one folder.", {
+ description:
+ "Its panes ran before it joined this project, so open the folder from a tool card instead.",
+ });
+ return;
+ }
+ await revealSandbox(distinct[0] ?? sandboxSessionId);
+ } catch (error) {
+ toast.error("Could not open the chat folder.", {
+ description:
+ error instanceof Error
+ ? error.message
+ : String(error),
+ });
+ }
+ })();
+ }}
+ >
+ <HugeiconsIcon icon={FolderOpenIcon} strokeWidth={1.75} className="size-icon" />
+ <span>Open chat folder</span>
+ </DropdownMenuItem>
+ ) : (
+ <OpenChatFolderUnavailableItem />
+ )
+ ) : null}
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<HugeiconsIcon icon={FolderExportIcon} strokeWidth={1.75} className="size-icon" />
diff --git a/studio/frontend/src/components/assistant-ui/sandbox-files-view.tsx b/studio/frontend/src/components/assistant-ui/sandbox-files-view.tsx
index 1cfb1a60463..287e8270ca5 100644
--- a/studio/frontend/src/components/assistant-ui/sandbox-files-view.tsx
+++ b/studio/frontend/src/components/assistant-ui/sandbox-files-view.tsx
@@ -1,16 +1,21 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { Download01Icon, File02Icon } from "@hugeicons/core-free-icons";
+import {
+ Download01Icon,
+ File02Icon,
+ FolderOpenIcon,
+} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useCallback, useState } from "react";
import { toast } from "sonner";
import { authFetch, getAuthToken } from "@/features/auth";
-import { apiUrl } from "@/lib/api-base";
+import { apiUrl, isTauri } from "@/lib/api-base";
import { downloadUrlStreaming, isDownloadCancelled } from "@/lib/native-files";
import { sandboxFilePath, type SandboxFile } from "./sandbox-files";
+import { revealSandbox } from "./sandbox-reveal";
function formatSize(size: number | null): string {
if (size === null || size === undefined || Number.isNaN(size)) return "";
@@ -75,6 +80,47 @@ function SandboxFileRow({
);
}
+/**
+ * The row's heading, doubling as the way into the folder itself on desktop.
+ * The backend opens the file manager, so in a browser it stays plain text and
+ * says why.
+ */
+function SandboxFolderLabel({
+ sessionId,
+ label,
+}: {
+ sessionId: string;
+ label: string;
+}) {
+ const open = useCallback(() => {
+ revealSandbox(sessionId).catch(() => {
+ toast.error("Could not open the chat folder.");
+ });
+ }, [sessionId]);
+
+ if (!isTauri) {
+ return (
+ <span
+ className="text-xs font-medium text-muted-foreground"
+ title="Opening the folder needs the desktop app. In a browser, save a file with the button below."
+ >
+ {label}
+ </span>
+ );
+ }
+ return (
+ <button
+ type="button"
+ onClick={open}
+ title="Open the folder these files were written to"
+ className="flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground"
+ >
+ <HugeiconsIcon icon={FolderOpenIcon} className="size-3.5 shrink-0" />
+ {label}
+ </button>
+ );
+}
+
/**
* "Files created" row under a tool card. Without it the only trace of a written
* file was the model mentioning it in prose.
@@ -89,9 +135,10 @@ export function SandboxFiles({
if (!sessionId || files.length === 0) return null;
return (
<div className="mt-2 border-t border-dashed pt-2">
- <span className="text-xs font-medium text-muted-foreground">
- {files.length === 1 ? "file created" : "files created"}
- </span>
+ <SandboxFolderLabel
+ sessionId={sessionId}
+ label={files.length === 1 ? "file created" : "files created"}
+ />
<div className="mt-1 flex flex-wrap gap-1.5">
{files.map((file) => (
<SandboxFileRow key={file.name} sessionId={sessionId} file={file} />
diff --git a/studio/frontend/src/components/assistant-ui/sandbox-files.ts b/studio/frontend/src/components/assistant-ui/sandbox-files.ts
index 5a6757c7eba..67d4bcc92e1 100644
--- a/studio/frontend/src/components/assistant-ui/sandbox-files.ts
+++ b/studio/frontend/src/components/assistant-ui/sandbox-files.ts
@@ -51,6 +51,45 @@ export function extractCreatedFiles(raw: string): {
}
}
+/** ``files`` as the cards need it: absent, or entries with a usable name. */
+export function isSandboxFileList(val: unknown): boolean {
+ if (val === undefined || val === null) return true;
+ if (!Array.isArray(val)) return false;
+ return val.every(
+ (entry) =>
+ typeof entry === "object" &&
+ entry !== null &&
+ typeof (entry as { name?: unknown }).name === "string",
+ );
+}
+
+/**
+ * A python/terminal result carrying the chat's sandbox context alongside the
+ * text the model actually saw.
+ */
+export function isSandboxToolResult(
+ val: unknown,
+): val is { text: string; sessionId: string } {
+ if (typeof val !== "object" || val === null) return false;
+ const v = val as {
+ text?: unknown;
+ sessionId?: unknown;
+ images?: unknown;
+ files?: unknown;
+ };
+ // images too: it is always in Studio's own wrapper, and a tool result that
+ // merely has text and sessionId is someone else's, whose other fields would
+ // be dropped on export.
+ return (
+ typeof v.text === "string" &&
+ typeof v.sessionId === "string" &&
+ Array.isArray(v.images) &&
+ // Persisted content can carry anything: the cards map over this and read
+ // name off each entry, so anything else takes the whole chat view down.
+ isSandboxFileList(v.files)
+ );
+}
+
/** Ids a path segment can carry: ASGI decodes %2F before it matches a route. */
const PATH_SAFE_SESSION = /^[A-Za-z0-9_-]{1,64}$/;
@@ -72,6 +111,18 @@ export function sandboxRoutePrefix(sessionId: string): {
};
}
+/**
+ * The sandbox a chat's tool calls run in. Threads inside a project share the
+ * project's workspace, so their files land in one place instead of one folder
+ * per thread.
+ */
+export function sandboxSessionIdFor(
+ threadId: string | undefined,
+ projectId: string | null | undefined,
+): string | undefined {
+ return projectId ? `project-${projectId}` : threadId;
+}
+
export function sandboxFilePath(sessionId: string, filename: string): string {
// Segment by segment: a file written to outputs/report.csv keeps a real "/"
// in the URL, which encodeURIComponent on the whole name would have escaped.
diff --git a/studio/frontend/src/components/assistant-ui/sandbox-reveal.ts b/studio/frontend/src/components/assistant-ui/sandbox-reveal.ts
new file mode 100644
index 00000000000..edbc2b94bc1
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/sandbox-reveal.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { authFetch } from "@/features/auth";
+
+import { sandboxRoutePrefix } from "./sandbox-files";
+
+/** Route that opens a session's sandbox in the OS file manager. */
+export function sandboxRevealPath(sessionId: string): string {
+ const { prefix, query } = sandboxRoutePrefix(sessionId);
+ return `${prefix}/reveal${query}`;
+}
+
+/**
+ * Whether this session's sandbox holds anything, to tell a candidate folder
+ * apart from one never written to. A missing sandbox already lists as an empty
+ * array, so a non-OK is something else and is thrown: swallowing it would send
+ * the caller to its fallback and silently open a different workspace.
+ */
+export async function sandboxHasFiles(sessionId: string): Promise<boolean> {
+ const { prefix, query } = sandboxRoutePrefix(sessionId);
+ const response = await authFetch(`${prefix}${query}`);
+ if (!response.ok) {
+ throw new Error(`Could not read the chat's folder (${response.status})`);
+ }
+ const body: unknown = await response.json();
+ const files = (body as { files?: unknown } | null)?.files;
+ return Array.isArray(files) && files.length > 0;
+}
+
+/**
+ * Open a chat's sandbox folder in the OS file manager.
+ *
+ * The backend does the opening, so the folder lands on the user's own desktop
+ * only when the backend runs there. Callers gate this on the desktop app.
+ */
+export async function revealSandbox(sessionId: string): Promise<void> {
+ const response = await authFetch(sandboxRevealPath(sessionId), {
+ method: "POST",
+ });
+ if (!response.ok) {
+ let detail = "";
+ try {
+ const body: unknown = await response.json();
+ if (body && typeof body === "object" && "detail" in body) {
+ const value = (body as { detail?: unknown }).detail;
+ if (typeof value === "string") detail = value;
+ }
+ } catch {
+ // A non-JSON error body leaves the status as the only thing to report.
+ }
+ throw new Error(detail || `Request failed (${response.status})`);
+ }
+}
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
index 5df11548e0f..e09187c8576 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
@@ -7,8 +7,7 @@ import { Spinner } from "@/components/ui/spinner";
import { authFetch } from "@/features/auth";
import { SandboxFiles } from "./sandbox-files-view";
-import type { SandboxFile } from "./sandbox-files";
-import { isSandboxFileList } from "@/features/chat/api/chat-adapter";
+import { isSandboxFileList, type SandboxFile } from "./sandbox-files";
import {
preferSanitizedFullToolOutput,
useChatRuntimeStore,
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
index 03c1ddbbbc4..e91e2d3737b 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
@@ -17,9 +17,8 @@ import { CopyBtn, ToolCodeCell } from "./tool-code-cell";
import { ToolLiveOutput } from "./tool-live-output";
import { ToolResultOutput } from "./tool-result-output";
import { SandboxFiles } from "./sandbox-files-view";
-import type { SandboxFile } from "./sandbox-files";
+import { isSandboxToolResult, type SandboxFile } from "./sandbox-files";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
-import { isSandboxToolResult } from "@/features/chat/api/chat-adapter";
import { stringifyToolResult } from "@/lib/strip-ansi";
import {
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 0f1f9c0cbdc..452f7c645a4 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -24,7 +24,10 @@ import { projectHasSources } from "@/features/rag/api/rag-api";
import {
SANDBOX_FILE_TOOLS,
extractCreatedFiles,
+ isSandboxFileList,
+ isSandboxToolResult,
type SandboxFile,
+ sandboxSessionIdFor,
} from "@/components/assistant-ui/sandbox-files";
import { apiUrl } from "@/lib/api-base";
import { parseParamCountB } from "@/lib/model-size";
@@ -998,45 +1001,6 @@ export interface McpImageToolResult {
images: { data: string; mimeType: string }[];
}
-/**
- * A python/terminal result carrying the chat's sandbox context alongside the
- * text the model actually saw.
- */
-/** ``files`` as the cards need it: absent, or entries with a usable name. */
-export function isSandboxFileList(val: unknown): boolean {
- if (val === undefined || val === null) return true;
- if (!Array.isArray(val)) return false;
- return val.every(
- (entry) =>
- typeof entry === "object" &&
- entry !== null &&
- typeof (entry as { name?: unknown }).name === "string",
- );
-}
-
-export function isSandboxToolResult(
- val: unknown,
-): val is { text: string; sessionId: string } {
- if (typeof val !== "object" || val === null) return false;
- const v = val as {
- text?: unknown;
- sessionId?: unknown;
- images?: unknown;
- files?: unknown;
- };
- // images too: it is always in Studio's own wrapper, and a tool result that
- // merely has text and sessionId is someone else's, whose other fields would
- // be dropped on export.
- return (
- typeof v.text === "string" &&
- typeof v.sessionId === "string" &&
- Array.isArray(v.images) &&
- // Persisted content can carry anything: the cards map over this and read
- // name off each entry, so anything else takes the whole chat view down.
- isSandboxFileList(v.files)
- );
-}
-
/**
* The text the model actually saw, for a result that may be wrapped.
*
@@ -1823,7 +1787,7 @@ async function resolveSandboxSessionId(
readThreadRecord?: ThreadRecordReader,
): Promise<string | undefined> {
const projectId = await resolveProjectId(threadId, readThreadRecord);
- return projectId ? `project-${projectId}` : threadId;
+ return sandboxSessionIdFor(threadId, projectId);
}
/** Wait for an in-progress model load to finish (polls store every 500ms). */
@@ -5729,9 +5693,18 @@ export function createOpenAIStreamAdapter(
} catch {
parsedResult = rawResult;
}
- } else if (createdFiles.length > 0) {
- // Files but no images: still structured, so the card can
- // offer downloads.
+ } else if (
+ createdFiles.length > 0 ||
+ SANDBOX_FILE_TOOLS.has(toolCallParts[idx].toolName ?? "")
+ ) {
+ // Structured with files, for the download card, and with
+ // neither, because the session is the only record of WHERE
+ // this call ran: _created_file_sentinels emits nothing
+ // when a concurrent call shared the directory, so a run
+ // that wrote files can arrive bare and a moved chat would
+ // then name a folder from its current scope. Downstream is
+ // unaffected: both toolResultModelText and the outbound
+ // translator unwrap a sandbox wrapper to this same .text.
parsedResult = {
text: rawResult,
images: [],
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 7bee6b990f6..ffa0b58e785 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -162,9 +162,11 @@ export {
deleteStoredChatThreads,
ensureStoredChatThread,
isThreadIncognito,
+ listStoredChatMessages,
listStoredChatThreads,
markThreadIncognito,
} from "./utils/chat-history-storage";
+export { recordedSandboxSessionId } from "./utils/recorded-sandbox-session";
export {
markChatThreadDeleted,
removeChatThreadTombstones,
diff --git a/studio/frontend/src/features/chat/utils/recorded-sandbox-session.ts b/studio/frontend/src/features/chat/utils/recorded-sandbox-session.ts
new file mode 100644
index 00000000000..9d635687ebd
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/recorded-sandbox-session.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import {
+ SANDBOX_FILE_TOOLS,
+ isSandboxToolResult,
+} from "@/components/assistant-ui/sandbox-files";
+
+import type { MessageRecord } from "../types";
+
+/**
+ * The sandbox a chat's tool calls actually wrote to, read back from its history.
+ *
+ * Moving a chat between projects rewrites only its `projectId` while the files
+ * stay put, so a scope from current membership can name a folder this chat
+ * never used; the id recorded on a tool result is the one its files are under.
+ *
+ * Gated on the tool name and the full wrapper shape, as the adapter is: a
+ * custom or MCP tool with its own `sessionId` would name an unrelated folder.
+ */
+export function recordedSandboxSessionId(
+ messages: MessageRecord[],
+): string | undefined {
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const content = messages[index]?.content;
+ if (!Array.isArray(content)) continue;
+ for (let part = content.length - 1; part >= 0; part -= 1) {
+ const entry = content[part] as {
+ type?: unknown;
+ toolName?: unknown;
+ result?: unknown;
+ } | null;
+ if (entry?.type !== "tool-call") continue;
+ if (
+ typeof entry.toolName !== "string" ||
+ !SANDBOX_FILE_TOOLS.has(entry.toolName)
+ ) {
+ continue;
+ }
+ const result: unknown = entry.result;
+ if (!isSandboxToolResult(result)) continue;
+ if (result.sessionId.length > 0) return result.sessionId;
+ }
+ }
+ return undefined;
+}
diff --git a/studio/frontend/tests/recorded-sandbox-session.test.ts b/studio/frontend/tests/recorded-sandbox-session.test.ts
new file mode 100644
index 00000000000..f2afc30ee49
--- /dev/null
+++ b/studio/frontend/tests/recorded-sandbox-session.test.ts
@@ -0,0 +1,238 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { recordedSandboxSessionId } = await import(
+ "../src/features/chat/utils/recorded-sandbox-session.ts"
+);
+
+type Message = Parameters<typeof recordedSandboxSessionId>[0][number];
+
+function toolMessage(sessionId: string): Message {
+ return {
+ id: "m2",
+ threadId: "thread-1",
+ role: "assistant",
+ createdAt: 2,
+ content: [
+ { type: "text", text: "ran it" },
+ {
+ type: "tool-call",
+ toolCallId: "call-1",
+ toolName: "python",
+ result: {
+ text: "wrote report.csv",
+ images: [],
+ sessionId,
+ files: [{ name: "report.csv", size: 8 }],
+ },
+ },
+ ],
+ } as unknown as Message;
+}
+
+test("a chat moved into a project still names the sandbox its files are in", () => {
+ // Written while the chat was loose, so the id is the thread's, not project-<id>.
+ const messages = [toolMessage("thread-1")];
+ assert.equal(recordedSandboxSessionId(messages), "thread-1");
+});
+
+test("the most recent tool result wins when the scope changed mid-chat", () => {
+ const messages = [toolMessage("thread-1"), toolMessage("project-p1")];
+ assert.equal(recordedSandboxSessionId(messages), "project-p1");
+});
+
+test("a chat that never ran a tool records nothing, leaving the caller its default", () => {
+ const messages = [
+ {
+ id: "m1",
+ threadId: "thread-1",
+ role: "user",
+ createdAt: 1,
+ content: [{ type: "text", text: "hello" }],
+ } as unknown as Message,
+ ];
+ assert.equal(recordedSandboxSessionId(messages), undefined);
+});
+
+test("an mcp tool answering with its own session id is not read as a sandbox", () => {
+ const messages = [
+ {
+ id: "m2",
+ threadId: "thread-1",
+ role: "assistant",
+ createdAt: 2,
+ content: [
+ {
+ type: "tool-call",
+ toolCallId: "call-1",
+ toolName: "search_docs",
+ result: {
+ text: "found 3 hits",
+ images: [],
+ sessionId: "someone-elses-session",
+ files: [],
+ },
+ },
+ ],
+ } as unknown as Message,
+ ];
+ assert.equal(recordedSandboxSessionId(messages), undefined);
+});
+
+test("a python result missing the wrapper shape is not read as a sandbox", () => {
+ const messages = [
+ {
+ id: "m2",
+ threadId: "thread-1",
+ role: "assistant",
+ createdAt: 2,
+ content: [
+ {
+ type: "tool-call",
+ toolCallId: "call-1",
+ toolName: "python",
+ // No images/files: the app's own wrapper always carries both.
+ result: { text: "ok", sessionId: "not-a-wrapper" },
+ },
+ ],
+ } as unknown as Message,
+ ];
+ assert.equal(recordedSandboxSessionId(messages), undefined);
+});
+
+test("a result without a session id is skipped rather than read as one", () => {
+ const messages = [
+ {
+ id: "m2",
+ threadId: "thread-1",
+ role: "assistant",
+ createdAt: 2,
+ content: [
+ {
+ type: "tool-call",
+ toolCallId: "c",
+ toolName: "python",
+ result: "plain text",
+ },
+ {
+ type: "tool-call",
+ toolCallId: "d",
+ toolName: "python",
+ result: { text: "ok", images: [], sessionId: "", files: [] },
+ },
+ ],
+ } as unknown as Message,
+ ];
+ assert.equal(recordedSandboxSessionId(messages), undefined);
+});
+
+test("a run that created no files still names the sandbox it ran in", () => {
+ // No __FILES__ envelope is emitted when the call changed nothing AND when a
+ // concurrent call shared the directory, so a run that DID write files can
+ // arrive bare. The adapter wraps python and terminal results either way.
+ const messages = [
+ {
+ id: "m2",
+ threadId: "t",
+ role: "assistant",
+ createdAt: 2,
+ content: [
+ {
+ type: "tool-call",
+ toolCallId: "c",
+ toolName: "python",
+ result: {
+ text: "42\n",
+ images: [],
+ sessionId: "project-p1",
+ files: [],
+ },
+ },
+ ],
+ } as unknown as Message,
+ ];
+ assert.equal(recordedSandboxSessionId(messages), "project-p1");
+});
+
+test("content that is not an array is skipped rather than thrown on", () => {
+ // Legacy and imported chats carry a plain string here, and this runs from a
+ // menu handler: throwing would take the click, not just the answer.
+ const messages = [
+ { id: "m1", threadId: "t", role: "user", createdAt: 1, content: "hello" },
+ { id: "m2", threadId: "t", role: "assistant", createdAt: 2, content: null },
+ { id: "m3", threadId: "t", role: "assistant", createdAt: 3 },
+ ] as unknown as Message[];
+ assert.equal(recordedSandboxSessionId(messages), undefined);
+});
+
+test("a null part inside a real content array does not stop the scan", () => {
+ const messages = [
+ {
+ id: "m2",
+ threadId: "t",
+ role: "assistant",
+ createdAt: 2,
+ content: [
+ null,
+ {
+ type: "tool-call",
+ toolCallId: "c",
+ toolName: "terminal",
+ result: { text: "ok", images: [], sessionId: "thread-1", files: [] },
+ },
+ null,
+ ],
+ } as unknown as Message,
+ ];
+ assert.equal(recordedSandboxSessionId(messages), "thread-1");
+});
+
+test("a tool-result shaped part is not mistaken for a tool call", () => {
+ // Only "tool-call" parts carry the result this reads. A part typed
+ // "tool-result" is a different shape and must not be half-read.
+ const messages = [
+ {
+ id: "m2",
+ threadId: "t",
+ role: "assistant",
+ createdAt: 2,
+ content: [
+ {
+ type: "tool-result",
+ toolName: "python",
+ result: { text: "ok", images: [], sessionId: "thread-1", files: [] },
+ },
+ ],
+ } as unknown as Message,
+ ];
+ assert.equal(recordedSandboxSessionId(messages), undefined);
+});
+
+test("a long history answers from the newest message without walking it all", () => {
+ // Runs on a menu click over a chat of thousands of turns. Walking backwards
+ // makes it one part when the newest message carries the answer.
+ const messages: Message[] = [];
+ for (let i = 0; i < 5000; i += 1) {
+ messages.push({
+ id: `m${i}`,
+ threadId: "t",
+ role: "user",
+ createdAt: i,
+ content: [{ type: "text", text: "x" }],
+ } as unknown as Message);
+ }
+ messages.push(toolMessage("newest-session"));
+ const started = performance.now();
+ assert.equal(recordedSandboxSessionId(messages), "newest-session");
+ assert.ok(
+ performance.now() - started < 50,
+ "the newest message must answer it",
+ );
+});
diff --git a/studio/frontend/tests/sandbox-reveal-path.test.ts b/studio/frontend/tests/sandbox-reveal-path.test.ts
new file mode 100644
index 00000000000..b9e0818c118
--- /dev/null
+++ b/studio/frontend/tests/sandbox-reveal-path.test.ts
@@ -0,0 +1,200 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { register } from "node:module";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+// sandbox-reveal reaches authFetch through the auth barrel, which re-exports
+// login-page.tsx. See helpers/auth-stub.mjs.
+register("./helpers/settings-api-resolver.mjs", import.meta.url);
+
+const { sandboxRevealPath, revealSandbox, sandboxHasFiles } = await import(
+ "../src/components/assistant-ui/sandbox-reveal.ts"
+);
+
+test("a path-safe session id reveals through its own path segment", () => {
+ assert.equal(
+ sandboxRevealPath("thread-1"),
+ "/api/inference/sandbox/thread-1/reveal",
+ );
+});
+
+test("an id the router cannot carry moves to the query, after the verb", () => {
+ // ASGI decodes %2F before matching, so a slashed id cannot ride in the path.
+ // The suffix must land BEFORE the query or the backend answers the listing.
+ assert.equal(
+ sandboxRevealPath("thread/with/slashes"),
+ "/api/inference/sandbox/_/reveal?session=thread%2Fwith%2Fslashes",
+ );
+});
+
+test("a project workspace id is path-safe and stays in the segment", () => {
+ assert.equal(
+ sandboxRevealPath("project-p1"),
+ "/api/inference/sandbox/project-p1/reveal",
+ );
+});
+
+test("an id past the path-safe length falls back to the query rather than truncating", () => {
+ const long = "a".repeat(65);
+ assert.equal(
+ sandboxRevealPath(long),
+ `/api/inference/sandbox/_/reveal?session=${long}`,
+ );
+});
+
+function respond(status: number, body: string, ok = false): Response {
+ return {
+ ok,
+ status,
+ json: async () => JSON.parse(body) as unknown,
+ } as unknown as Response;
+}
+
+test("the backend's reason is what the user is shown", async () => {
+ globalThis.fetch = (async () =>
+ respond(
+ 404,
+ JSON.stringify({ detail: "This chat has no folder yet" }),
+ )) as typeof fetch;
+ await assert.rejects(revealSandbox("thread-1"), {
+ message: "This chat has no folder yet",
+ });
+});
+
+test("a body that is not JSON leaves the status as the only thing to report", async () => {
+ globalThis.fetch = (async () =>
+ respond(500, "<html>502</html>")) as typeof fetch;
+ await assert.rejects(revealSandbox("thread-1"), {
+ message: "Request failed (500)",
+ });
+});
+
+test("an old backend with no reveal route rejects rather than resolving silently", async () => {
+ // A self-updating desktop bundle can meet a backend predating this route.
+ // It answers 405: the download route claims the same path for GET/HEAD.
+ globalThis.fetch = (async () =>
+ respond(
+ 405,
+ JSON.stringify({ detail: "Method Not Allowed" }),
+ )) as typeof fetch;
+ await assert.rejects(revealSandbox("thread-1"), {
+ message: "Method Not Allowed",
+ });
+});
+
+test("a successful reveal resolves without reading the body", async () => {
+ function refuse(): Promise<unknown> {
+ return Promise.reject(new Error("the body must not be read on success"));
+ }
+ globalThis.fetch = (async () =>
+ ({
+ ok: true,
+ status: 200,
+ json: refuse,
+ }) as unknown as Response) as typeof fetch;
+ await revealSandbox("thread-1");
+});
+
+const SIDEBAR = readFileSync(
+ fileURLToPath(new URL("../src/components/app-sidebar.tsx", import.meta.url)),
+ "utf-8",
+);
+
+test("a failed history read is reported, not mistaken for a chat that ran no tools", () => {
+ // No React renderer here, so this asserts on source, like ~50 sibling tests.
+ // A per-pane catch makes a failed read look like "never ran a tool", and the
+ // fallback is project membership, the answer the recorded id overrides.
+ const start = SIDEBAR.indexOf("const recorded: (string | undefined)[] = [];");
+ const end = SIDEBAR.indexOf("let distinct = ");
+ assert.ok(start !== -1 && end > start, "the read block moved");
+ const block = SIDEBAR.slice(start, end);
+ assert.ok(block.includes("recordedSandboxSessionId"), "the read block moved");
+ assert.ok(
+ !block.includes(".catch("),
+ "a per-pane catch turns a failed read into a wrong folder",
+ );
+});
+
+test("a sandbox holding files is told apart from one that was never written", async () => {
+ // The legacy-folder probe. A missing sandbox lists as 200 with an empty
+ // array rather than an error, so both cases must read as "not this one".
+ globalThis.fetch = (async () =>
+ ({
+ ok: true,
+ status: 200,
+ json: async () => ({ path: "/s/thread-1", files: [{ name: "a.csv" }] }),
+ }) as unknown as Response) as typeof fetch;
+ assert.equal(await sandboxHasFiles("thread-1"), true);
+
+ globalThis.fetch = (async () =>
+ ({
+ ok: true,
+ status: 200,
+ json: async () => ({ path: "/s/thread-1", files: [] }),
+ }) as unknown as Response) as typeof fetch;
+ assert.equal(await sandboxHasFiles("thread-1"), false);
+});
+
+test("a probe that could not be answered is reported, not read as an empty folder", async () => {
+ // "No sandbox" is already a 200 with an empty list, so a non-OK is a backend
+ // or storage failure. Reading it as "no files" would fall through to the
+ // current project scope and open a different workspace, silently.
+ globalThis.fetch = (async () =>
+ ({
+ ok: false,
+ status: 500,
+ json: async () => ({}),
+ }) as unknown as Response) as typeof fetch;
+ await assert.rejects(sandboxHasFiles("thread-1"), {
+ message: "Could not read the chat's folder (500)",
+ });
+});
+
+test("the legacy probe runs only for a chat now inside a project", () => {
+ // A chat moved OUT of a project wrote under project-<id>, and nothing retains
+ // which one, so there is no candidate to probe in that direction.
+ const block = SIDEBAR.slice(
+ SIDEBAR.indexOf("let distinct = [...new Set(recorded.filter(Boolean))];"),
+ SIDEBAR.indexOf("if (distinct.length > 1)"),
+ );
+ assert.ok(block.includes("distinct.length === 0 && item.projectId"));
+ assert.ok(block.includes("sandboxHasFiles(threadId)"));
+});
+
+test("a sandbox tool result is wrapped even when it carries no envelope", () => {
+ // chat-adapter.ts reaches JSX barrels and cannot be imported, so this asserts
+ // on source. The session id is the only record of WHERE a call ran, and the
+ // backend suppresses __FILES__ when a concurrent call shared the directory,
+ // so a run that did write files can arrive bare and a moved chat would then
+ // name a folder from its current scope that it never wrote to.
+ const adapter = readFileSync(
+ fileURLToPath(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ ),
+ "utf-8",
+ );
+ const branch = adapter.slice(
+ adapter.indexOf(
+ "} else if (\n createdFiles.length > 0 ||",
+ ),
+ adapter.indexOf("// Merge tool_end args first"),
+ );
+ assert.ok(branch.length > 0, "the sandbox result branch moved");
+ assert.ok(
+ branch.includes("SANDBOX_FILE_TOOLS.has(toolCallParts[idx].toolName"),
+ "python and terminal results must be wrapped without an envelope too",
+ );
+ assert.ok(branch.includes("sessionId: sandboxSessionId"));
+});
+
+test("the sandbox reads stay off Promise.all, as the export contract requires", () => {
+ // test_desktop_reliability_frontend_contract.py forbids `await Promise.all(`
+ // here: every batch ends in a native save dialog, and concurrent ones race
+ // and lose cancellation. Asserted from this side so the reason travels with
+ // the code, not only with the Python guard that fails the build.
+ assert.ok(!SIDEBAR.includes("await Promise.all("));
+});
diff --git a/tests/studio/test_reveal_file_manager.py b/tests/studio/test_reveal_file_manager.py
index 8a1df586e50..16a7e6f316a 100644
--- a/tests/studio/test_reveal_file_manager.py
+++ b/tests/studio/test_reveal_file_manager.py
@@ -49,7 +49,6 @@ pytest.importorskip("fastapi")
pytest.importorskip("huggingface_hub")
try:
- from routes import models as routes_models
from utils.paths import path_utils
except Exception as exc:
pytest.skip(f"studio backend import unavailable: {exc}", allow_module_level = True)
@@ -86,14 +85,14 @@ def test_wsl_file_is_selected_in_explorer(linux_host, spawned, monkeypatch, tmp_
monkeypatch.setattr(path_utils, "_IS_WSL", True)
target = tmp_path / "model.gguf"
target.write_bytes(b"gguf")
- routes_models._reveal_in_file_manager(target)
+ path_utils.reveal_in_file_manager(target)
assert spawned.run == [["wslpath", "-w", str(target)]]
assert spawned.popen == [["explorer.exe", f"/select,{_WINDOWS_PATH}"]]
def test_wsl_directory_opens_in_explorer(linux_host, spawned, monkeypatch, tmp_path):
monkeypatch.setattr(path_utils, "_IS_WSL", True)
- routes_models._reveal_in_file_manager(tmp_path)
+ path_utils.reveal_in_file_manager(tmp_path)
assert spawned.popen == [["explorer.exe", _WINDOWS_PATH]]
@@ -102,7 +101,7 @@ def test_wsl_without_interop_falls_back_to_xdg_open(linux_host, spawned, monkeyp
spawned.run_error = FileNotFoundError("wslpath")
target = tmp_path / "model.gguf"
target.write_bytes(b"gguf")
- routes_models._reveal_in_file_manager(target)
+ path_utils.reveal_in_file_manager(target)
assert spawned.popen == [["xdg-open", str(tmp_path)]]
@@ -113,7 +112,7 @@ def test_wsl_empty_conversion_falls_back_to_xdg_open(linux_host, spawned, monkey
return types.SimpleNamespace(stdout = "\n")
monkeypatch.setattr(subprocess, "run", empty_run)
- routes_models._reveal_in_file_manager(tmp_path)
+ path_utils.reveal_in_file_manager(tmp_path)
assert spawned.popen == [["xdg-open", str(tmp_path)]]
@@ -123,6 +122,6 @@ def test_native_linux_keeps_xdg_open_on_parent_directory(
monkeypatch.setattr(path_utils, "_IS_WSL", False)
target = tmp_path / "model.gguf"
target.write_bytes(b"gguf")
- routes_models._reveal_in_file_manager(target)
+ path_utils.reveal_in_file_manager(target)
assert spawned.run == []
assert spawned.popen == [["xdg-open", str(tmp_path)]]
diff --git a/tests/studio/test_reveal_file_manager_matrix.py b/tests/studio/test_reveal_file_manager_matrix.py
new file mode 100644
index 00000000000..075f31b1c80
--- /dev/null
+++ b/tests/studio/test_reveal_file_manager_matrix.py
@@ -0,0 +1,387 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Every platform branch of ``reveal_in_file_manager``, and how each one fails.
+
+``test_reveal_file_manager.py`` beside this covers WSL and native Linux; this
+completes the matrix with macOS, native Windows, and the failure modes once a
+branch is chosen. Launchers are stubbed and argv asserted exactly, since what
+breaks a path here is a space, comma or non-ASCII splitting one argument in two.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+
+def _find_repo_root() -> Path | None:
+ env = os.environ.get("UNSLOTH_REPO_ROOT")
+ if env:
+ p = Path(env).resolve()
+ if (p / "studio" / "backend").is_dir():
+ return p
+ here = Path(__file__).resolve()
+ for parent in (here, *here.parents):
+ if (parent / "studio" / "backend").is_dir():
+ return parent
+ return None
+
+
+_REPO_ROOT = _find_repo_root()
+if _REPO_ROOT is None:
+ pytest.skip(
+ "Could not locate studio/backend. Set UNSLOTH_REPO_ROOT or run from "
+ "the repository checkout.",
+ allow_module_level = True,
+ )
+
+_STUDIO_BACKEND = _REPO_ROOT / "studio" / "backend"
+if str(_STUDIO_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_STUDIO_BACKEND))
+
+pytest.importorskip("fastapi")
+pytest.importorskip("huggingface_hub")
+
+try:
+ from utils.paths import path_utils
+except Exception as exc:
+ pytest.skip(f"studio backend import unavailable: {exc}", allow_module_level = True)
+
+
+# Characters that get split into two argv elements by string-built commands.
+_AWKWARD_NAME = "rapport final, v2 (draft) — 90% ✅"
+
+
+def spawned(monkeypatch):
+ """Record what would have been launched, and launch nothing.
+
+ ``startfile`` is Windows-only, so ``raising = False`` installs it rather
+ than replacing it, which is what exercises that branch from Linux.
+ """
+ calls = types.SimpleNamespace(run = [], popen = [], startfile = [], popen_error = None)
+
+ def fake_run(cmd, **kwargs):
+ calls.run.append(list(cmd))
+ return types.SimpleNamespace(stdout = "C:\\converted\n")
+
+ def fake_popen(cmd, **kwargs):
+ if calls.popen_error is not None:
+ raise calls.popen_error
+ calls.popen.append(list(cmd))
+ return types.SimpleNamespace()
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.setattr(subprocess, "Popen", fake_popen)
+ monkeypatch.setattr(os, "startfile", calls.startfile.append, raising = False)
+ return calls
+
+
+def macos(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setattr(os, "name", "posix")
+
+
+def windows(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(os, "name", "nt")
+
+
+def native_linux(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(os, "name", "posix")
+ monkeypatch.setattr(path_utils, "_IS_WSL", False)
+
+
+# ---------------------------------------------------------------------------
+# macOS
+# ---------------------------------------------------------------------------
+def test_macos_reveals_a_file_with_open_dash_r(macos, spawned, tmp_path):
+ """``open -R`` selects the file in its enclosing folder; plain ``open``
+ would hand the file to whichever application claims the extension."""
+ target = tmp_path / "report.csv"
+ target.write_text("a,b\n")
+ path_utils.reveal_in_file_manager(target)
+ assert spawned.popen == [["open", "-R", str(target)]]
+
+
+def test_macos_opens_a_directory_rather_than_revealing_it(macos, spawned, tmp_path):
+ """``open -R`` on a directory shows its PARENT with it selected, which for
+ a sandbox is the root holding every other chat's."""
+ path_utils.reveal_in_file_manager(tmp_path)
+ assert spawned.popen == [["open", str(tmp_path)]]
+
+
+def test_macos_keeps_an_awkward_name_in_one_argument(macos, spawned, tmp_path):
+ target = tmp_path / _AWKWARD_NAME
+ target.mkdir()
+ path_utils.reveal_in_file_manager(target)
+ assert spawned.popen == [["open", str(target)]]
+ assert len(spawned.popen[0]) == 2
+
+
+# ---------------------------------------------------------------------------
+# Windows
+# ---------------------------------------------------------------------------
+def test_windows_selects_a_file_in_explorer(windows, spawned, tmp_path):
+ target = tmp_path / "report.csv"
+ target.write_text("a,b\n")
+ path_utils.reveal_in_file_manager(target)
+ assert spawned.popen == [["explorer", f"/select,{target}"]]
+ assert spawned.startfile == []
+
+
+def test_windows_opens_a_directory_with_startfile(windows, spawned, tmp_path):
+ path_utils.reveal_in_file_manager(tmp_path)
+ assert spawned.startfile == [str(tmp_path)]
+ assert spawned.popen == []
+
+
+def test_windows_never_waits_on_explorer_or_reads_its_exit_code(windows, spawned, tmp_path):
+ """``explorer.exe`` exits 1 even when it worked (microsoft/WSL#6565), so
+ ``run(..., check = True)`` here would raise on every SUCCESSFUL reveal.
+ ``Popen`` without a wait is what makes that harmless."""
+ target = tmp_path / "report.csv"
+ target.write_text("a,b\n")
+ path_utils.reveal_in_file_manager(target)
+ assert spawned.run == [], "explorer must not be run and waited on"
+ assert spawned.popen and spawned.popen[0][0] == "explorer"
+
+
+def test_windows_keeps_a_comma_in_the_path_out_of_the_select_flag(windows, spawned, tmp_path):
+ """``/select,`` is comma-delimited and a filename may contain one. Recorded,
+ not asserted-correct: it is one argv element, so parsing is Explorer's
+ problem, not the shell's."""
+ target = tmp_path / "q3, final.csv"
+ target.write_text("a,b\n")
+ path_utils.reveal_in_file_manager(target)
+ assert spawned.popen == [["explorer", f"/select,{target}"]]
+ assert len(spawned.popen[0]) == 2
+
+
+# ---------------------------------------------------------------------------
+# WSL and native Linux -- the fallback chain
+# ---------------------------------------------------------------------------
+def test_wsl_falls_back_to_xdg_open_when_wslpath_times_out(monkeypatch, spawned, tmp_path):
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(os, "name", "posix")
+ monkeypatch.setattr(path_utils, "_IS_WSL", True)
+
+ def timing_out(cmd, **kwargs):
+ raise subprocess.TimeoutExpired(cmd, 10)
+
+ monkeypatch.setattr(subprocess, "run", timing_out)
+ path_utils.reveal_in_file_manager(tmp_path)
+ assert spawned.popen == [["xdg-open", str(tmp_path)]]
+
+
+def test_wsl_falls_back_to_xdg_open_when_wslpath_fails(monkeypatch, spawned, tmp_path):
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(os, "name", "posix")
+ monkeypatch.setattr(path_utils, "_IS_WSL", True)
+
+ def failing(cmd, **kwargs):
+ raise subprocess.CalledProcessError(1, cmd)
+
+ monkeypatch.setattr(subprocess, "run", failing)
+ path_utils.reveal_in_file_manager(tmp_path)
+ assert spawned.popen == [["xdg-open", str(tmp_path)]]
+
+
+def test_native_linux_opens_a_directory_directly(native_linux, spawned, tmp_path):
+ path_utils.reveal_in_file_manager(tmp_path)
+ assert spawned.run == []
+ assert spawned.popen == [["xdg-open", str(tmp_path)]]
+
+
+def test_native_linux_keeps_an_awkward_name_in_one_argument(native_linux, spawned, tmp_path):
+ target = tmp_path / _AWKWARD_NAME
+ target.mkdir()
+ path_utils.reveal_in_file_manager(target)
+ assert spawned.popen == [["xdg-open", str(target)]]
+ assert len(spawned.popen[0]) == 2
+
+
+def test_a_deeply_nested_path_is_passed_through_whole(native_linux, spawned, tmp_path):
+ """Sandbox names are derived, but a project workspace can sit arbitrarily
+ deep under a home the user chose."""
+ target = tmp_path.joinpath(*[f"level_{i}" for i in range(40)])
+ target.mkdir(parents = True)
+ path_utils.reveal_in_file_manager(target)
+ assert spawned.popen == [["xdg-open", str(target)]]
+ assert len(str(target)) > 255
+
+
+# ---------------------------------------------------------------------------
+# Failing, on every platform
+# ---------------------------------------------------------------------------
[email protected]("host", ["macos", "windows", "native_linux"])
+def test_a_missing_target_launches_nothing_anywhere(host, spawned, tmp_path, request):
+ request.getfixturevalue(host)
+ with pytest.raises(FileNotFoundError):
+ path_utils.reveal_in_file_manager(tmp_path / "never-existed")
+ assert spawned.popen == []
+ assert spawned.run == []
+ assert spawned.startfile == []
+
+
[email protected]("host", ["macos", "windows", "native_linux"])
+def test_a_broken_symlink_launches_nothing_anywhere(host, spawned, tmp_path, request):
+ """``exists()`` follows links, so a dangling one is "missing" -- which is
+ the answer that matters: the old code would have opened its parent."""
+ request.getfixturevalue(host)
+ link = tmp_path / "link"
+ link.symlink_to(tmp_path / "gone")
+ with pytest.raises(FileNotFoundError):
+ path_utils.reveal_in_file_manager(link)
+ assert spawned.popen == []
+ assert spawned.startfile == []
+
+
+class _VanishesAfterTheGuard:
+ """There for the existence guard, gone by the branch. The two are separate
+ stats, and a chat deleted or migrated in between is what the endpoint's own
+ tests already simulate one layer up."""
+
+ def __init__(self, real: Path) -> None:
+ self._real = real
+
+ def exists(self) -> bool:
+ return True
+
+ def is_dir(self) -> bool:
+ return False
+
+ def is_file(self) -> bool:
+ return False
+
+ @property
+ def parent(self) -> Path:
+ return self._real.parent
+
+ def __str__(self) -> str:
+ return str(self._real)
+
+ def __fspath__(self) -> str:
+ return str(self._real)
+
+
+def test_a_target_that_vanishes_after_the_guard_never_opens_its_parent(
+ native_linux, spawned, tmp_path
+):
+ """The parent of a sandbox is the root holding every other chat's, so the
+ Linux fallback must fail closed rather than widen to it."""
+ root = tmp_path / "sandbox"
+ (root / "thread-1").mkdir(parents = True)
+ with pytest.raises(FileNotFoundError):
+ path_utils.reveal_in_file_manager(_VanishesAfterTheGuard(root / "thread-1"))
+ assert spawned.popen == [], "the sandbox root must never be opened"
+
+
+class _SwappedForAFile:
+ """A checked directory replaced by a regular file before the open. A tool
+ runs inside its own sandbox and can do this, and the file branch names the
+ parent on every platform."""
+
+ def __init__(self, real: Path) -> None:
+ self._real = real
+
+ def exists(self) -> bool:
+ return True
+
+ def is_dir(self) -> bool:
+ return False
+
+ def is_file(self) -> bool:
+ return True
+
+ @property
+ def parent(self) -> Path:
+ return self._real.parent
+
+ def __str__(self) -> str:
+ return str(self._real)
+
+ def __fspath__(self) -> str:
+ return str(self._real)
+
+
[email protected]("host", ["macos", "windows", "native_linux"])
+def test_a_sandbox_swapped_for_a_file_is_refused_not_revealed(host, spawned, tmp_path, request):
+ """``expect_dir`` is what the sandbox route passes, since a sandbox's parent
+ is the root holding every other chat's. A real file on disk, not a fake:
+ the one ``lstat`` leaves no gap between check and use for a fake to sit in,
+ which is the property under test."""
+ request.getfixturevalue(host)
+ root = tmp_path / "sandbox"
+ root.mkdir(parents = True)
+ (root / "thread-1").write_bytes(b"not a directory any more")
+ with pytest.raises(FileNotFoundError):
+ path_utils.reveal_in_file_manager(root / "thread-1", expect_dir = True)
+ assert spawned.popen == []
+ assert spawned.startfile == []
+
+
[email protected]("host", ["macos", "windows", "native_linux"])
+def test_a_sandbox_swapped_for_a_directory_symlink_is_refused(host, spawned, tmp_path, request):
+ """``is_dir()`` follows links, so a sandbox replaced by one would pass a
+ naive check and open the TARGET. The guard asks for the link's own type."""
+ request.getfixturevalue(host)
+ elsewhere = tmp_path / "somewhere-else"
+ elsewhere.mkdir()
+ link = tmp_path / "sandbox" / "thread-1"
+ link.parent.mkdir(parents = True)
+ link.symlink_to(elsewhere, target_is_directory = True)
+ assert link.is_dir(), "the premise: it looks like a directory"
+
+ with pytest.raises(FileNotFoundError):
+ path_utils.reveal_in_file_manager(link, expect_dir = True)
+ assert spawned.popen == []
+ assert spawned.startfile == []
+
+
[email protected]("host", ["macos", "windows", "native_linux"])
+def test_a_symlinked_cache_entry_is_still_revealed_without_expect_dir(
+ host, spawned, tmp_path, request
+):
+ """A Hugging Face snapshot is a link farm, so the cached-model reveal must
+ keep following links. Only the sandbox caller opts into the strict check."""
+ request.getfixturevalue(host)
+ blob = tmp_path / "blob.gguf"
+ blob.write_bytes(b"gguf")
+ link = tmp_path / "snapshot" / "model.gguf"
+ link.parent.mkdir(parents = True)
+ link.symlink_to(blob)
+ path_utils.reveal_in_file_manager(link)
+ assert spawned.popen or spawned.startfile
+
+
[email protected]("host", ["macos", "windows", "native_linux"])
+def test_the_same_swap_is_still_revealed_without_expect_dir(host, spawned, tmp_path, request):
+ """The cached-model reveal points at a real file, so the flag is opt-in and
+ the default behaviour is unchanged."""
+ request.getfixturevalue(host)
+ target = tmp_path / "model.gguf"
+ path_utils.reveal_in_file_manager(_SwappedForAFile(target))
+ assert spawned.popen or spawned.startfile
+
+
+def test_a_missing_launcher_is_reported_as_a_missing_launcher(native_linux, spawned, tmp_path):
+ """``xdg-open`` is absent on a headless host, and ``Popen`` then raises
+ ``FileNotFoundError`` for the LAUNCHER just as for a missing target. The
+ helper cannot tell them apart, so this pins the payload as the launcher,
+ which is what lets the route answer 500 rather than "no folder"."""
+ spawned.popen_error = FileNotFoundError(2, "No such file or directory", "xdg-open")
+ with pytest.raises(FileNotFoundError) as caught:
+ path_utils.reveal_in_file_manager(tmp_path)
+ assert caught.value.filename == "xdg-open"
+ assert tmp_path.is_dir(), "the folder was there the whole time"