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
Studio: ask before risky calls when a chat folder is too large to check (#13914)
Nilay6d203e3a645f
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 8b8e933c2eb..a6f4fadbc64 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -40444,6 +40444,7 @@ class LlamaCppBackend:permission_mode = permission_mode,name = current_name,sandbox_level = sandbox_level,+ session_id = session_id,)# A text-preview card still streams while gated;# hiding it blanks the chat.@@ -40594,6 +40595,7 @@ class LlamaCppBackend:permission_mode = "off",name = _sniffed,sandbox_level = sandbox_level,+ session_id = session_id,))and not has_text_only_provisional_card(@@ -41613,6 +41615,7 @@ class LlamaCppBackend:is_high_risk = is_high_risk_tool_call,never_needs = never_needs_approval,sandbox_level = sandbox_level,+ session_id = session_id,)# Sending the user's image always asks, whatever the permission mode.needs_confirm = needs_confirm or image_share is not Nonediff --git a/studio/backend/core/inference/mxc_policy.py b/studio/backend/core/inference/mxc_policy.pyindex 704b831499d..7f65da1a288 100644--- a/studio/backend/core/inference/mxc_policy.py+++ b/studio/backend/core/inference/mxc_policy.py@@ -191,8 +191,8 @@ def _scan_workdir(workdir: str, *, required: bool) -> tuple[str, ...]:raise MxcPolicyError(str(exc)) from excif required and os_sandbox.WORKDIR_SCAN_INCOMPLETE in limitations:raise MxcPolicyError(- "the session workdir is too large to check for host channels, and `required` "- "cannot promise a boundary it did not verify. Start a new chat, or use `auto`."+ "the session workdir is too large to check for host channels, "+ "so this call needs the user's approval. Call the tool again to ask for it.")return limitationsdiff --git a/studio/backend/core/inference/os_sandbox.py b/studio/backend/core/inference/os_sandbox.pyindex ba2216477af..fb8263e5322 100644--- a/studio/backend/core/inference/os_sandbox.py+++ b/studio/backend/core/inference/os_sandbox.py@@ -232,6 +232,9 @@ WORKDIR_SCAN_SECONDS = 5.0CACHE_SCAN_ENTRIES = 50_000CACHE_SCAN_SECONDS = 3.0_SCAN_JOIN_GRACE_SECONDS = 0.5+_overran_workdirs: set[str] = set()+_overrun_recheck_after: dict[str, float] = {}+OVERRUN_RECHECK_SECONDS = 60.0TOOL_TEMP_DIRNAME = "unsloth-tmp"TOOL_TEMP_MODE = 0o700@@ -499,6 +502,7 @@ def clear_stale_tool_ipc(workdir: str, deadline: "float | None" = None) -> tupledef scan_workdir_for_host_channels(workdir: str) -> tuple[str, ...]:"""Scan the writable workdir: a hazard fails the call, an overrun budget is recorded, not refused."""+ key = os.path.realpath(workdir)try:hazard = _hazard_within_wall_clock(workdir,@@ -508,12 +512,40 @@ def scan_workdir_for_host_channels(workdir: str) -> tuple[str, ...]:)except _ScanBudgetExceeded as exc:logger.warning("The session workdir %s: %s", workdir, exc)+ _overran_workdirs.add(key)return (WORKDIR_SCAN_INCOMPLETE,)+ _overran_workdirs.discard(key)if hazard is not None:raise WorkdirUnsafeError(f"the session workdir {hazard}")return ()+def workdir_scan_overran(workdir: str) -> bool:+ return bool(_overran_workdirs) and os.path.realpath(workdir) in _overran_workdirs+++def recheck_overran_workdir(workdir: str) -> None:+ """For a folder launched without a scan: forget the overrun once it scans clean, at most once a minute."""+ if not workdir_scan_overran(workdir):+ return+ key = os.path.realpath(workdir)+ now = time.monotonic()+ if now < _overrun_recheck_after.get(key, 0.0):+ return+ _overrun_recheck_after[key] = now + OVERRUN_RECHECK_SECONDS+ try:+ hazard = _hazard_within_wall_clock(+ workdir,+ WORKDIR_SCAN_ENTRIES,+ WORKDIR_SCAN_SECONDS,+ prepare = lambda deadline: clear_stale_tool_ipc(workdir, deadline),+ )+ except _ScanBudgetExceeded:+ return+ if hazard is None:+ _overran_workdirs.discard(key)++def cache_share_hazard(path: str, witness: "list[tuple] | None" = None) -> str | None:"""Return a reason not to share this writable cache component, or None."""try:@@ -1236,8 +1268,7 @@ def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:prepared.cleanup()raise WorkdirUnsafeError("the session workdir is too large to check for host channels, "- "and `required` cannot promise a boundary it did not verify. "- "Start a new chat, or use `auto` to run with software safeguards."+ "so this call needs the user's approval. Call the tool again to ask for it.")except (WorkdirUnsafeError, SandboxBuildError):raise # can be tool-induced; says nothing about the backend itselfdiff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.pyindex ecba0478c77..05188df43ea 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -1591,6 +1591,7 @@ def run_safetensors_tool_loop(name = decision.tool_name,arguments = decision.arguments,sandbox_level = sandbox_level,+ session_id = session_id,)# Sending the user's image always asks, whatever the permission mode.needs_confirm = needs_confirm or image_share is not Nonediff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex d42ebb800ca..1e7032a62cf 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -1959,6 +1959,7 @@ async def stream_with_studio_tools(is_high_risk = is_high_risk_tool_call,never_needs = never_needs_approval,sandbox_level = sandbox_level,+ session_id = session_id,)# Sending the user's image always asks, whatever the permission mode.needs_confirmation = needs_confirmation or image_share is not Nonediff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 35c2f7d0d96..8a70af1b08b 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -10153,6 +10153,8 @@ def _prepare_tool_launch(user_folder: bool = False,):"""Fall back only when the backend is unavailable; unsafe workdirs, build failures and (outside `full`) planner errors refuse."""+ if user_folder and plan.requested_mode == "auto":+ os_sandbox.recheck_overran_workdir(plan.workdir)if host_access_approved and plan.requested_mode == "auto":return _software_safeguards_launch(plan, "user_approved_host_access")# A project folder the owner picked is host access they granted: the isolation's workdir scan would refuse common@@ -10516,6 +10518,11 @@ def _workdir_key(session_id: "str | None") -> tuple[str, str]:return current_account_id(), session_id or _ANON_KEY+def workdir_scan_overran(session_id: "str | None") -> bool:+ workdir = _workdirs.get(_workdir_key(session_id))+ return workdir is not None and os_sandbox.workdir_scan_overran(workdir)++def _session_key(session_id: "str | None") -> tuple[str, str]:"""Lifecycle key for a session id.diff --git a/studio/backend/state/tool_policy.py b/studio/backend/state/tool_policy.pyindex 6686119666d..32ecff7174a 100644--- a/studio/backend/state/tool_policy.py+++ b/studio/backend/state/tool_policy.py@@ -92,15 +92,20 @@ def runs_without_os_sandbox(name: str, sandbox_level: Optional[str]) -> bool:return name in OS_SANDBOXED_TOOLS and sandbox_level == "low"-def off_mode_still_gates(name: str, sandbox_level: Optional[str] = None) -> bool:+def off_mode_still_gates(+ name: str,+ sandbox_level: Optional[str] = None,+ session_id: Optional[str] = None,+) -> bool:"""Whether "off" must still ask for this tool. Cached only; unknown counts as not isolated."""if name not in OS_SANDBOXED_TOOLS:return Falseif runs_without_os_sandbox(name, sandbox_level):return Truefrom core.inference.os_sandbox import cached_tool_isolation+ from core.inference.tools import workdir_scan_overran- return cached_tool_isolation(name) is not True+ return cached_tool_isolation(name) is not True or workdir_scan_overran(session_id)def tool_call_may_prompt(@@ -110,12 +115,13 @@ def tool_call_may_prompt(permission_mode: Optional[str],name: str,sandbox_level: Optional[str] = None,+ session_id: Optional[str] = None,) -> bool:"""Before the arguments are known: whether a call to ``name`` could stop and ask."""if not confirm_tool_calls or bypass_permissions:return Falseif permission_mode == "off":- return off_mode_still_gates(name, sandbox_level)+ return off_mode_still_gates(name, sandbox_level, session_id)if permission_mode == "auto":from core.inference.tools import is_always_safe_toolreturn not is_always_safe_tool(name)@@ -132,6 +138,7 @@ def needs_tool_confirmation(is_high_risk = None,never_needs = None,sandbox_level: Optional[str] = None,+ session_id: Optional[str] = None,) -> bool:if is_high_risk is None or never_needs is None:from core.inference import tools@@ -140,7 +147,7 @@ def needs_tool_confirmation(if not confirm_tool_calls or bypass_permissions or never_needs(name):return Falseif permission_mode == "off":- return off_mode_still_gates(name, sandbox_level) and _classify(+ return off_mode_still_gates(name, sandbox_level, session_id) and _classify(is_high_risk, name, arguments, sandbox_level)if permission_mode == "auto":diff --git a/studio/backend/tests/test_permission_mode_degrade.py b/studio/backend/tests/test_permission_mode_degrade.pyindex 7bf20f0869a..109e348b800 100644--- a/studio/backend/tests/test_permission_mode_degrade.py+++ b/studio/backend/tests/test_permission_mode_degrade.py@@ -4,6 +4,8 @@""" "off" (Run automatically) asks before a risky python/terminal call without OS isolation."""import itertools+import os+import socketimport sysimport threadingimport time@@ -611,6 +613,182 @@ def test_the_loop_launches_an_unasked_risky_call_strictly(mode, code, expected):assert exec_fn.modes == [expected]+def _first_python_call(session_id):+ from core.inference.safetensors_agentic import run_safetensors_tool_loop++ turns = iter(+ [+ '<tool_call>{"name": "python", "arguments": {"code": "import shutil; shutil.rmtree(\\"dist\\")"}}</tool_call>',+ "done",+ ]+ )++ def single_turn(_messages):+ try:+ yield next(turns)+ except StopIteration:+ return++ exec_fn = _ModeRecordingExecuteTool()+ loop = run_safetensors_tool_loop(+ single_turn = single_turn,+ messages = [{"role": "user", "content": "clean dist"}],+ tools = [{"type": "function", "function": {"name": "python"}}],+ execute_tool = exec_fn,+ session_id = session_id,+ confirm_tool_calls = True,+ permission_mode = "off",+ )+ start = next(e for e in loop if e["type"] == "tool_start")+ if start["awaiting_confirmation"]:+ loop.close()+ else:+ list(loop)+ return start["awaiting_confirmation"], exec_fn.modes+++def test_run_automatically_asks_once_the_chat_folder_is_too_large_to_check(monkeypatch, tmp_path):+ import uuid++ from core.inference import tools++ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path))+ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_ENTRIES", 3)+ os_sandbox.note_tool_isolation("python", True, backend = "bubblewrap")+ big, small = f"big-{uuid.uuid4().hex}", f"small-{uuid.uuid4().hex}"+ workdir = tools._get_workdir(big)+ tools._get_workdir(small)+ for i in range(8):+ with open(os.path.join(workdir, f"f{i}"), "w"):+ pass++ assert os_sandbox.scan_workdir_for_host_channels(workdir) == (+ os_sandbox.WORKDIR_SCAN_INCOMPLETE,+ )+ assert _first_python_call(big) == (True, [])+ assert _first_python_call(small) == (False, ["required"])++ for i in range(8):+ os.remove(os.path.join(workdir, f"f{i}"))+ assert os_sandbox.scan_workdir_for_host_channels(workdir) == ()+ assert _first_python_call(big) == (False, ["required"])+++def test_a_chosen_project_folder_stops_asking_once_it_is_small_again(monkeypatch, tmp_path):+ from core.inference import tools++ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_ENTRIES", 3)+ monkeypatch.setattr(os_sandbox, "OVERRUN_RECHECK_SECONDS", 0.0)+ for i in range(8):+ (tmp_path / f"f{i}").write_text("")+ os_sandbox.scan_workdir_for_host_channels(str(tmp_path))+ plan = os_sandbox.ToolLaunchPlan(+ argv = ("/bin/true",), workdir = str(tmp_path), env = {}, requested_mode = "auto"+ )++ tools._prepare_tool_launch(plan, user_folder = True)+ assert os_sandbox.workdir_scan_overran(str(tmp_path))++ for i in range(8):+ (tmp_path / f"f{i}").unlink()+ scratch = tmp_path / os_sandbox.TOOL_TEMP_DIRNAME+ scratch.mkdir(mode = os_sandbox.TOOL_TEMP_MODE)+ monkeypatch.chdir(scratch)+ dead = socket.socket(socket.AF_UNIX)+ dead.bind("s")+ dead.close()+ tools._prepare_tool_launch(plan, host_access_approved = True, user_folder = True)+ assert not os_sandbox.workdir_scan_overran(str(tmp_path))+++def test_an_oversized_project_folder_is_rechecked_at_most_once_a_minute(monkeypatch, tmp_path):+ from core.inference import tools++ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_ENTRIES", 3)+ for i in range(8):+ (tmp_path / f"f{i}").write_text("")+ os_sandbox.scan_workdir_for_host_channels(str(tmp_path))+ walks = []+ real = os_sandbox._walk_for_host_channels+ monkeypatch.setattr(+ os_sandbox, "_walk_for_host_channels", lambda *a: walks.append(a) or real(*a)+ )+ plan = os_sandbox.ToolLaunchPlan(+ argv = ("/bin/true",), workdir = str(tmp_path), env = {}, requested_mode = "auto"+ )++ for _ in range(3):+ tools._prepare_tool_launch(plan, user_folder = True)+ assert len(walks) == 1+ assert os_sandbox.workdir_scan_overran(str(tmp_path))+++def test_windows_asks_the_model_to_retry_when_the_chat_folder_is_too_large(monkeypatch, tmp_path):+ from core.inference import mxc_policy++ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_ENTRIES", 3)+ for i in range(8):+ (tmp_path / f"f{i}").write_text("")++ with pytest.raises(mxc_policy.MxcPolicyError, match = "Call the tool again"):+ mxc_policy._scan_workdir(str(tmp_path), required = True)+ assert os_sandbox.workdir_scan_overran(str(tmp_path))+++ sys.platform != "linux" or not os_sandbox.capability_snapshot().available,+ reason = "needs a host that can build the OS sandbox",+)+def test_an_oversized_chat_folder_refuses_once_then_asks_and_runs_isolated(monkeypatch, tmp_path):+ import uuid++ from core.inference import tools+ from core.inference.safetensors_agentic import run_safetensors_tool_loop+ from state.tool_approvals import resolve_tool_decision++ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path))+ monkeypatch.setattr(os_sandbox, "WORKDIR_SCAN_ENTRIES", 3)+ session = f"big-real-{uuid.uuid4().hex}"+ workdir = tools._get_workdir(session)+ for i in range(8):+ with open(os.path.join(workdir, f"f{i}"), "w"):+ pass+ capability = os_sandbox.capability_snapshot()+ os_sandbox.note_tool_isolation("python", True, backend = capability.backend)+ call = '<tool_call>{"name": "python", "arguments": {"code": "import shutil; shutil.rmtree(\\"dist%d\\", ignore_errors=True); print(\\"RAN\\" + \\"_OK\\")"}}</tool_call>'+ turns = iter([call % 1, call % 2, "done"])++ def single_turn(_messages):+ try:+ yield next(turns)+ except StopIteration:+ return++ starts, results, records = [], [], []+ for ev in run_safetensors_tool_loop(+ single_turn = single_turn,+ messages = [{"role": "user", "content": "clean dist"}],+ tools = [{"type": "function", "function": {"name": "python"}}],+ execute_tool = tools.execute_tool,+ session_id = session,+ confirm_tool_calls = True,+ permission_mode = "off",+ ):+ if ev["type"] == "tool_start":+ starts.append(ev["awaiting_confirmation"])+ if ev["awaiting_confirmation"]:+ resolve_tool_decision(ev["approval_id"], "allow", session_id = session)+ elif ev["type"] == "tool_end":+ results.append(ev["result"])+ records.append(tools._last_tool_execution_record)++ assert starts == [False, True]+ assert "Call the tool again" in results[0] and "RAN_OK" not in results[0]+ assert "RAN_OK" in results[1]+ assert records[1].os_isolation is True+ assert os_sandbox.WORKDIR_SCAN_INCOMPLETE in records[1].limitations++def test_a_strict_launch_is_refused_when_the_sandbox_stopped_working(monkeypatch):from core.inference import tools