Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Full access swaps the tool schemas and nudge to host wording; other modes keep the sandbox text."""
import asyncio
import json
import os
import sys
import pytest
from core.inference import tools
from core.inference.tools import (
ALL_TOOLS,
PYTHON_TOOL,
PYTHON_TOOL_FULL_ACCESS,
TERMINAL_TOOL,
TERMINAL_TOOL_FULL_ACCESS,
apply_full_access_tool_descriptions,
)
from models.inference import ChatCompletionRequest, ChatCountTokensRequest
from routes.inference import (
_append_to_codex_instructions,
_build_tool_action_nudge,
_full_access_tip,
_project_folder_tip,
_select_request_tools,
)
def _desc(tool: dict) -> str:
return tool["function"]["description"]
def _named(tools: list[dict], name: str) -> dict:
return next(t for t in tools if t["function"]["name"] == name)
def test_sandboxed_descriptions_are_unchanged():
"""The default pair is what every existing importer gets."""
assert "in a sandbox" in _desc(PYTHON_TOOL)
assert "do not exist" in _desc(PYTHON_TOOL) or "Windows" in _desc(PYTHON_TOOL)
assert "return stdout/stderr" in _desc(TERMINAL_TOOL)
@pytest.mark.parametrize(
"tool",
[PYTHON_TOOL_FULL_ACCESS, TERMINAL_TOOL_FULL_ACCESS],
ids = ["python", "terminal"],
)
def test_full_access_descriptions_drop_the_isolation_claim(tool):
description = _desc(tool)
assert "in a sandbox" not in description
# Outright false with the sandbox off.
assert "do not exist" not in description
assert "sandbox is disabled" in description
assert "wherever Unsloth Studio is running" in description
# Docker deployments see only mounted paths, so reach is the process's, not the machine's.
assert "container with only some paths mounted" in description
# Remote modes (--secure, -H 0.0.0.0) run tools on the server, not the user's device.
assert "user's own machine" not in description
# Bypass mode still uses the per-session workdir (_build_bypass_env repoints HOME/TMPDIR).
assert "persists for this conversation" in description
assert "download link" in description
def test_full_access_schemas_keep_name_and_parameters():
"""Only descriptions may differ; a changed name or schema breaks dispatcher matching."""
for sandboxed, full in (
(PYTHON_TOOL, PYTHON_TOOL_FULL_ACCESS),
(TERMINAL_TOOL, TERMINAL_TOOL_FULL_ACCESS),
):
assert full["type"] == sandboxed["type"]
assert full["function"]["name"] == sandboxed["function"]["name"]
assert full["function"]["parameters"] == sandboxed["function"]["parameters"]
@pytest.mark.parametrize("platform", ["linux", "darwin", "win32"])
@pytest.mark.parametrize("tool_name", ["python", "terminal"])
def test_the_substitutions_land_on_every_platform(monkeypatch, platform, tool_name):
"""Rebuild the sandbox note per platform: module constants are built once for the host platform."""
monkeypatch.setattr(sys, "platform", platform)
sandboxed = "Execute Python code in a sandbox and return stdout/stderr." + (
tools._build_sandbox_paths_note()
)
full = tools._to_full_access(sandboxed, tool_name)
assert full != sandboxed
assert "in a sandbox" not in full
assert "do not exist" not in full
assert "sandbox is disabled" in full
assert "do resolve" in full
assert "user's own machine" not in full
assert "wherever Unsloth Studio is running" in full
# sitecustomize stays on PYTHONPATH under Full access, so python (not a plain shell) still
# remaps missing-parent paths onto the workdir; the split is per tool, not per OS.
if tool_name == "python":
assert "absolute paths under a directory that exists do resolve" in full
# Convention prefixes overwrite; other missing parents raise if the basename is taken.
assert "the rest of the path is kept relative to the working directory" in full
assert "replacing any file already sitting there" in full
assert "only the base name is kept" in full
# A different invented path with the same basename raises; the same path is allowed (remap sidecar).
assert "fails outright if that name is taken by an unrelated file" in full
assert "rewriting the same absolute path just replaces" in full
# Only open/io.open/os.open and mkdir are wrapped; os.makedirs outside convention prefixes
# hits the real host path because _makedirs only calls _remap.
assert "The convention rewrite covers open() and the mkdir calls" in full
assert "the other covers open() alone" in full
assert "os.makedirs under a missing parent outside those prefixes" in full
assert "is not rewritten and attempts the real host path" in full
assert "missing absolute parent is not rewritten at all" not in full
assert "shutil.copy can write the rewritten file and still raise" in full
else:
assert "absolute paths do resolve as the shell resolves them" in full
# PYTHONPATH also reaches terminal subprocesses, so python launched from a shell gets the shim.
assert "Python you launch from here is the exception" in full
assert "gets the same rewrites" in full
# A real /mnt/data mount is never shadowed, so no categorical 'not real' claim may appear.
assert "not real there" not in full
if tool_name == "python":
assert "when the directory does not exist" in full
assert "persists for this conversation" in full
assert "download link" in full
if platform == "win32":
assert "You are on Windows" in full
def test_python_full_access_description_still_omits_the_shell():
"""Naming a shell would send the model to subprocess/os.system, not the terminal tool."""
assert "shell" not in _desc(PYTHON_TOOL_FULL_ACCESS).lower()
def test_full_access_drops_the_local_desktop_promise(monkeypatch):
"""Full access must not promise a desktop window for Git Bash: Unsloth may be remote."""
monkeypatch.setattr(sys, "platform", "win32")
monkeypatch.setattr(tools, "_windows_bash", lambda: r"C:\bash.exe")
note = tools._build_terminal_shell_note()
assert "opens a window on the user's desktop" in note
full = tools._to_full_access("X." + note, "terminal")
assert "opens a window on the user's desktop" not in full
assert "on that machine's desktop" in full
assert "The shell is bash (Git for Windows)" in full
def test_terminal_full_access_keeps_the_shell_note():
"""Platform-derived shell note must stay in both modes, else cmd/bash confusion returns."""
for marker in ("cmd, not bash", "bash (Git for Windows)"):
assert (marker in _desc(TERMINAL_TOOL)) == (marker in _desc(TERMINAL_TOOL_FULL_ACCESS))
def test_swap_leaves_other_tools_alone_and_does_not_mutate():
before = list(ALL_TOOLS)
swapped = apply_full_access_tool_descriptions(list(ALL_TOOLS))
assert _named(swapped, "python") is PYTHON_TOOL_FULL_ACCESS
assert _named(swapped, "terminal") is TERMINAL_TOOL_FULL_ACCESS
for name in ("web_search", "render_html", "search_knowledge_base"):
assert _named(swapped, name) is _named(ALL_TOOLS, name)
# ALL_TOOLS is shared across requests; the swap must not mutate it.
assert ALL_TOOLS == before
assert _desc(_named(ALL_TOOLS, "python")) == _desc(PYTHON_TOOL)
def test_swap_is_a_no_op_without_the_sandboxed_builtins():
tools = [t for t in ALL_TOOLS if t["function"]["name"] == "web_search"]
assert apply_full_access_tool_descriptions(tools) is tools
assert apply_full_access_tool_descriptions([]) == []
def _select(**payload_kwargs) -> list[dict]:
payload = ChatCompletionRequest(
model = "test-model",
messages = [{"role": "user", "content": "hi"}],
enable_tools = True,
enabled_tools = ["python", "terminal", "web_search"],
stream = True,
**payload_kwargs,
)
return asyncio.run(_select_request_tools(payload, tools_on = True, mcp_allowed = False))
@pytest.mark.parametrize("mode", ["ask", "auto", "off"])
def test_non_full_modes_keep_the_sandboxed_schemas(mode):
tools = _select(permission_mode = mode)
assert _desc(_named(tools, "python")) == _desc(PYTHON_TOOL)
assert _desc(_named(tools, "terminal")) == _desc(TERMINAL_TOOL)
def test_omitted_mode_keeps_the_sandboxed_schemas():
tools = _select()
assert _desc(_named(tools, "python")) == _desc(PYTHON_TOOL)
@pytest.mark.parametrize(
"payload_kwargs",
[{"permission_mode": "full"}, {"bypass_permissions": True}],
ids = ["permission_mode", "legacy_bypass_flag"],
)
def test_full_access_selection_swaps_the_schemas(payload_kwargs):
"""Both spellings fold to bypass_permissions=True, so both must swap."""
tools = _select(**payload_kwargs)
assert _desc(_named(tools, "python")) == _desc(PYTHON_TOOL_FULL_ACCESS)
assert _desc(_named(tools, "terminal")) == _desc(TERMINAL_TOOL_FULL_ACCESS)
assert _named(tools, "web_search") is _named(ALL_TOOLS, "web_search")
_CODE_TOOLS = [PYTHON_TOOL, TERMINAL_TOOL]
_WEB_ONLY = [t for t in ALL_TOOLS if t["function"]["name"] == "web_search"]
def test_nudge_is_unchanged_without_full_access():
plain = _build_tool_action_nudge(tools = _CODE_TOOLS, model_name = "test-8B")
assert "sandbox" not in plain
assert "code execution" in plain
assert plain == _build_tool_action_nudge(
tools = _CODE_TOOLS, model_name = "test-8B", full_access = False
)
def test_nudge_states_the_environment_under_full_access():
nudge = _build_tool_action_nudge(tools = _CODE_TOOLS, model_name = "test-8B", full_access = True)
assert "where Unsloth Studio is running" in nudge
assert "code sandbox and the approval prompts disabled" in nudge
assert "whatever that process can reach" in nudge
assert "container that mounts only some" in nudge
# Only python/terminal get disable_sandbox; web_search and MCP tools may run elsewhere.
assert nudge.count("The python and terminal tools run where") == 1
@pytest.mark.parametrize(
("enabled", "expected"),
[
(["python"], "The python tool runs where"),
(["terminal"], "The terminal tool runs where"),
(["python", "terminal"], "The python and terminal tools run where"),
# Order comes from _LOCAL_CODE_TOOLS, not the caller's list.
(["terminal", "python"], "The python and terminal tools run where"),
],
ids = ["python_only", "terminal_only", "both", "reversed"],
)
def test_the_tip_names_only_the_selected_code_tools(enabled, expected):
"""enabled_tools=["python"] leaves terminal out of the request's schemas, so
naming it would advertise a tool the loop would refuse to run."""
tools = [t for t in ALL_TOOLS if t["function"]["name"] in enabled]
nudge = _build_tool_action_nudge(tools = tools, model_name = "test-8B", full_access = True)
assert expected in nudge
for absent in {"python", "terminal"} - set(enabled):
assert f"The {absent} tool runs where" not in nudge
assert f"and {absent} tools run where" not in nudge
assert "not necessarily the device the user is viewing this on" in nudge
assert "check with a tool call" in nudge
def test_full_access_only_returns_the_sentence_alone():
"""Codex studio tools never got the general nudge, so they get just the Full access tip."""
only = _build_tool_action_nudge(
tools = _CODE_TOOLS, model_name = "test-8B", full_access = True, full_access_only = True
)
assert only == _full_access_tip(["python", "terminal"])
assert "The current date is" not in only
assert "Tools are available when they materially improve" not in only
@pytest.mark.parametrize(
"kwargs",
[{"full_access": False}, {"full_access": True, "tools": _WEB_ONLY}],
ids = ["not_full_access", "no_code_tool"],
)
def test_full_access_only_is_empty_when_it_does_not_apply(kwargs):
tools = kwargs.pop("tools", _CODE_TOOLS)
assert (
_build_tool_action_nudge(tools = tools, model_name = "test-8B", full_access_only = True, **kwargs)
== ""
)
def test_full_access_tip_needs_a_code_tool():
"""web_search alone runs nothing locally, so a sandbox sentence would be false noise."""
nudge = _build_tool_action_nudge(tools = _WEB_ONLY, model_name = "test-8B", full_access = True)
assert "where Unsloth Studio is running" not in nudge
assert nudge == _build_tool_action_nudge(tools = _WEB_ONLY, model_name = "test-8B")
_FOLDER_MARKER = "the current working directory is the folder the user chose for it"
@pytest.mark.parametrize("full_access", [False, True], ids = ["sandboxed", "full_access"])
def test_a_chosen_project_folder_is_named_in_every_mode(full_access):
"""In Ask/Approve for me the tools run in the user's folder (_prepare_tool_launch's
user_working_folder), yet the schemas still say sandbox: without this sentence a model
answers "What project/files?", as reported on Reddit. Full access runs there too."""
plain = _build_tool_action_nudge(
tools = _CODE_TOOLS, model_name = "test-8B", full_access = full_access
)
nudge = _build_tool_action_nudge(
tools = _CODE_TOOLS, model_name = "test-8B", full_access = full_access, user_folder = True
)
assert _FOLDER_MARKER not in plain
assert _FOLDER_MARKER in nudge
assert "list and read them with the terminal or python tool first" in nudge
assert "rather than asking the user to upload or paste them" in nudge
# A read can fail or an approval be denied: the model reports that, not a blanket "no access".
assert "if a read fails or is denied, say what failed" in nudge
# Additive: nothing the nudge said before is dropped.
assert nudge == plain + " " + _project_folder_tip({"python", "terminal"})
assert ("where Unsloth Studio is running" in nudge) == full_access
@pytest.mark.parametrize("names", [{"web_search"}, {"edit_file"}, {"web_search", "edit_file"}])
def test_the_folder_sentence_needs_a_tool_that_can_read(names):
"""Neither web_search nor edit_file can list or read the folder, so the sentence would ask
for a look the model cannot take."""
tools = [t for t in ALL_TOOLS if t["function"]["name"] in names]
nudge = _build_tool_action_nudge(tools = tools, model_name = "test-8B", user_folder = True)
assert _FOLDER_MARKER not in nudge
assert nudge == _build_tool_action_nudge(tools = tools, model_name = "test-8B")
@pytest.mark.parametrize(
("names", "reader", "web"),
[
({"terminal"}, "with the terminal tool first", False),
({"python", "edit_file"}, "with the python tool first", False),
({"python", "terminal", "web_search"}, "with the terminal or python tool first", True),
],
)
def test_the_folder_sentence_names_the_tools_that_can_read(names, reader, web):
"""Told only "a tool call", Qwen3.5-4B listed the folder and then web-searched how to read
app.py until it gave up with an empty answer."""
tip = _project_folder_tip(names)
assert reader in tip
assert ("web_search cannot see them" in tip) == web
@pytest.mark.parametrize("full_access", [False, True], ids = ["sandboxed", "full_access"])
def test_the_studio_tool_loop_paths_carry_the_folder_sentence(full_access):
"""External providers and Codex run python/terminal in the same workdir, with only the
environment sentences."""
only = _build_tool_action_nudge(
tools = _CODE_TOOLS,
model_name = "test-8B",
full_access = full_access,
full_access_only = True,
user_folder = True,
)
assert _FOLDER_MARKER in only
assert "Tools are available when they materially improve" not in only
assert ("where Unsloth Studio is running" in only) == full_access
def test_every_nudge_call_site_passes_the_folder_flag():
"""Structural on purpose: the eight call sites are completions and counts on different
backends, and one that drops the flag silently loses the sentence or skews the count."""
import ast
from pathlib import Path
import routes.inference as inference
tree = ast.parse(Path(inference.__file__).read_text(encoding = "utf-8"))
calls = [
node
for node in ast.walk(tree)
if isinstance(node, ast.Call)
and getattr(node.func, "id", None) == "_build_tool_action_nudge"
]
assert len(calls) >= 8
for call in calls:
assert "user_folder" in {kw.arg for kw in call.keywords}, ast.unparse(call)
def test_count_request_carries_the_session():
assert _count_request(session_id = "project-p1").session_id == "project-p1"
def test_full_access_tip_needs_tools_at_all():
assert _build_tool_action_nudge(tools = [], model_name = "test-8B", full_access = True) == ""
def _count_request(**kwargs) -> ChatCountTokensRequest:
return ChatCountTokensRequest(
model = "test-model",
messages = [{"role": "user", "content": "hi"}],
enable_tools = True,
enabled_tools = ["python", "terminal"],
**kwargs,
)
def test_codex_instructions_skip_a_developer_message():
"""Only system turns fold into Responses instructions; a developer turn would drop the nudge."""
messages = [
{"role": "developer", "content": "house style"},
{"role": "user", "content": "hi"},
]
out = _append_to_codex_instructions(messages, "NUDGE")
assert out[0] == {"role": "system", "content": "NUDGE"}
assert out[1] == messages[0]
assert messages[0]["content"] == "house style"
def test_codex_instructions_extend_an_existing_system_message():
messages = [{"role": "system", "content": "base"}, {"role": "user", "content": "hi"}]
out = _append_to_codex_instructions(messages, "NUDGE")
assert out[0]["content"] == "base\n\nNUDGE"
assert len(out) == 2
assert messages[0]["content"] == "base"
def test_codex_instructions_are_a_no_op_without_an_addition():
messages = [{"role": "user", "content": "hi"}]
assert _append_to_codex_instructions(messages, "") is messages
def test_count_request_reads_the_flag_when_omitted():
"""The count route reaches for payload.bypass_permissions unconditionally,
so the field has to exist rather than arrive via extra='allow'."""
assert _count_request().bypass_permissions is None
@pytest.mark.parametrize(
"kwargs",
[{"permission_mode": "full"}, {"bypass_permissions": True}],
ids = ["permission_mode", "legacy_bypass_flag"],
)
def test_count_request_folds_full_access(kwargs):
request = _count_request(**kwargs)
assert request.bypass_permissions is True
assert request.permission_mode == "full"
@pytest.mark.parametrize("mode", ["ask", "auto", "off"])
def test_count_request_leaves_other_modes_alone(mode):
assert _count_request(permission_mode = mode).bypass_permissions is None
def test_count_request_selection_matches_the_completion():
"""Counted tool list must match the one the completion renders, carrying the flag."""
counted = asyncio.run(
_select_request_tools(
_count_request(permission_mode = "full"), tools_on = True, mcp_allowed = False
)
)
assert _desc(_named(counted, "python")) == _desc(PYTHON_TOOL_FULL_ACCESS)
def _sandbox_site_dir():
from pathlib import Path
return Path(tools.__file__).resolve().parent / "sandbox_site"
# skipif args evaluate at import; calling os.geteuid() there breaks collection on Windows.
@pytest.mark.skipif(sys.platform == "win32", reason = "POSIX directory modes")
@pytest.mark.skipif(
hasattr(os, "geteuid") and os.geteuid() == 0,
reason = "root ignores a mode-500 directory",
)
def test_the_mkdir_clause_promises_an_attempt_not_a_created_directory(tmp_path):
"""The mkdir clause promises only an attempt: os.makedirs is wrapped, but _makedirs calls only
_remap, so an unwritable path outside convention prefixes raises and creates nothing."""
import subprocess
workdir = tmp_path / "work"
readonly = tmp_path / "readonly"
workdir.mkdir()
readonly.mkdir()
readonly.chmod(0o500)
try:
probe = subprocess.run(
[
sys.executable,
"-c",
"import json, os, sys\n"
"target = sys.argv[1] + '/missing/child'\n"
"try:\n"
" os.makedirs(target)\n"
" outcome = 'created'\n"
"except OSError as exc:\n"
" outcome = type(exc).__name__\n"
"print(json.dumps({'outcome': outcome, 'host': os.path.exists(target),\n"
" 'workdir': sorted(os.listdir('.'))}))\n",
str(readonly),
],
cwd = workdir,
env = {**os.environ, "PYTHONPATH": str(_sandbox_site_dir())},
capture_output = True,
text = True,
timeout = 120,
)
finally:
readonly.chmod(0o700)
assert probe.returncode == 0, probe.stderr
measured = json.loads(probe.stdout.strip().splitlines()[-1])
assert measured["outcome"] == "PermissionError", measured
assert measured["host"] is False, "nothing was created on the host"
assert measured["workdir"] == [], "and nothing fell back into the working directory"
full = tools._to_full_access(
"Execute Python code in a sandbox and return stdout/stderr."
+ tools._build_sandbox_paths_note(),
"python",
)
assert (
"really does create it" not in full
), "the clause promises a directory the filesystem may refuse to create"
assert "outside those prefixes is not rewritten" in full
assert "attempts the real host path" in full
@pytest.mark.skipif(sys.platform == "win32", reason = "POSIX directory modes")
@pytest.mark.skipif(os.path.exists("/mnt/data"), reason = "a real mount is never shadowed")
def test_the_mkdir_clause_is_scoped_to_parents_outside_the_convention_prefixes(tmp_path):
"""Inside a convention prefix, makedirs IS rewritten, so the clause cannot be flat.
``_makedirs`` calls ``_remap``, and ``_remap``'s convention branch keeps the
suffix under the working directory before it reaches the generic fallback. So
``/mnt/data/reports`` has a missing absolute parent and still lands in the
workdir. A clause saying makedirs under a missing absolute parent is not
rewritten at all would have the model report a host path for a directory
sitting in its working directory, which is the one thing the closing sentence
asks it not to do.
"""
import subprocess
workdir = tmp_path / "work"
workdir.mkdir()
probe = subprocess.run(
[
sys.executable,
"-c",
"import json, os\n"
"target = '/mnt/data/reports'\n"
"try:\n"
" os.makedirs(target)\n"
" outcome = 'created'\n"
"except OSError as exc:\n"
" outcome = type(exc).__name__\n"
"print(json.dumps({'outcome': outcome, 'host': os.path.exists(target),\n"
" 'workdir': sorted(os.listdir('.'))}))\n",
],
cwd = workdir,
env = {**os.environ, "PYTHONPATH": str(_sandbox_site_dir())},
capture_output = True,
text = True,
timeout = 120,
)
assert probe.returncode == 0, probe.stderr
measured = json.loads(probe.stdout.strip().splitlines()[-1])
assert measured["outcome"] == "created", measured
assert measured["host"] is False, "the absent prefix is not created on the host"
assert measured["workdir"] == ["reports"], measured