Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: Sandbox Low/High and Permissions under Settings > Sandbox (#12802)

Daniel Hanbcdede6d1fa5
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 00232f86c32..3abf5518dc5 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -36315,6 +36315,7 @@ class LlamaCppBackend:
thinking_budget_tokens: Optional[int] = None,
mcp_image = None,
instruction_anchor_ids = None,
+ sandbox_level: Optional[str] = None,
) -> Generator[dict, None, None]:
"""
Agentic loop: let the model call tools, execute them, and continue.
@@ -36352,14 +36353,17 @@ class LlamaCppBackend:
from state.tool_policy import (
account_tool_stream,
needs_tool_confirmation,
+ normalize_sandbox_level,
normalize_tool_permissions,
requires_os_isolation,
+ runs_without_os_sandbox,
tool_call_may_prompt,
)
permission_mode, bypass_permissions = normalize_tool_permissions(
permission_mode, bypass_permissions
)
+ sandbox_level = normalize_sandbox_level(sandbox_level)
stream_tool_execution = account_tool_stream(stream_tool_execution)
if not self.is_loaded:
@@ -37469,6 +37473,7 @@ class LlamaCppBackend:
bypass_permissions = bypass_permissions,
permission_mode = permission_mode,
name = current_name,
+ sandbox_level = sandbox_level,
)
# A text-preview card still streams while gated;
# hiding it blanks the chat.
@@ -37618,6 +37623,7 @@ class LlamaCppBackend:
bypass_permissions = False,
permission_mode = "off",
name = _sniffed,
+ sandbox_level = sandbox_level,
)
)
and not has_text_only_provisional_card(
@@ -38616,6 +38622,7 @@ class LlamaCppBackend:
arguments = decision.arguments,
is_high_risk = is_high_risk_tool_call,
never_needs = never_needs_approval,
+ sandbox_level = sandbox_level,
)
# Sending the user's image always asks, whatever the permission mode.
image_share = mcp_image_share(decision.tool_name, decision.arguments, mcp_image)
@@ -38628,6 +38635,7 @@ class LlamaCppBackend:
arguments = decision.arguments,
prompted = needs_confirm,
is_high_risk = is_high_risk_tool_call,
+ sandbox_level = sandbox_level,
)
approval_id = new_approval_id() if needs_confirm else ""
decision_slot = (
@@ -38997,6 +39005,10 @@ class LlamaCppBackend:
# Run unasked only because the OS sandbox was on: refuse if it is not any more.
if _strict and accepts_kwarg(execute_tool, "tool_execution_mode"):
kwargs["tool_execution_mode"] = "required"
+ elif runs_without_os_sandbox(
+ _decision.tool_name, sandbox_level
+ ) and accepts_kwarg(execute_tool, "tool_execution_mode"):
+ kwargs["tool_execution_mode"] = "software"
# Same branch the forced recall is filtered against, so a
# model-initiated search cannot reach a sibling response the
# forced recall correctly refused.
diff --git a/studio/backend/core/inference/openai_codex_tool_loop.py b/studio/backend/core/inference/openai_codex_tool_loop.py
index b4d85c820d0..e586ae8ce51 100644
--- a/studio/backend/core/inference/openai_codex_tool_loop.py
+++ b/studio/backend/core/inference/openai_codex_tool_loop.py
@@ -50,6 +50,7 @@ class CodexToolPolicy:
bypass_permissions: bool
rag_scope: dict[str, Any] | None
nudge_tool_calls: bool | None = None
+ sandbox_level: str = "high"
class CodexTransport:
@@ -122,6 +123,7 @@ def stream_codex_with_studio_tools(
rag_scope = policy.rag_scope,
auto_heal = False,
nudge_tool_calls = policy.nudge_tool_calls,
+ sandbox_level = policy.sandbox_level,
),
cancel_event = cancel_event,
mcp_image = mcp_image,
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index c69152abc47..3975189b513 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -3064,6 +3064,7 @@ class InferenceOrchestrator:
confirm_tool_calls: bool = False,
bypass_permissions: bool = False,
permission_mode: Optional[str] = None,
+ sandbox_level: Optional[str] = None,
use_adapter: Optional[Union[bool, str]] = None,
stats_holder: Optional[dict] = None,
presence_penalty: float = 0.0,
@@ -3265,6 +3266,7 @@ class InferenceOrchestrator:
mcp_image = mcp_image,
bypass_permissions = bypass_permissions,
permission_mode = permission_mode,
+ sandbox_level = sandbox_level,
reasoning_prefilled = reasoning_prefilled,
continue_final_message = continue_final_message,
# So a conversation search can be sized against what this model can hold.
diff --git a/studio/backend/core/inference/os_sandbox.py b/studio/backend/core/inference/os_sandbox.py
index 4ca318e431e..49eebd05764 100644
--- a/studio/backend/core/inference/os_sandbox.py
+++ b/studio/backend/core/inference/os_sandbox.py
@@ -23,8 +23,9 @@ from loggers import get_logger
logger = get_logger(__name__)
-ToolExecutionMode = Literal["auto", "required", "full"]
-TOOL_EXECUTION_MODES = ("auto", "required", "full")
+# "software" is Sandbox Low: software safeguards without the OS sandbox, never Full access.
+ToolExecutionMode = Literal["auto", "required", "full", "software"]
+TOOL_EXECUTION_MODES = ("auto", "required", "full", "software")
PUBLIC_TOOL_EXECUTION_MODES = ("auto", "required")
PROFILE_VERSION = "unsloth-sandbox-v1"
@@ -1065,6 +1066,20 @@ def _software_only_limitations() -> tuple[str, ...]:
return tuple(limitations)
+def _software_launch(plan: ToolLaunchPlan, record: ToolExecutionRecord) -> PreparedSandboxLaunch:
+ return PreparedSandboxLaunch(
+ argv = plan.argv,
+ workdir = plan.workdir,
+ env = plan.env,
+ preexec_fn = plan.preexec_fn,
+ backend = "software-safeguards",
+ timeout_seconds = plan.timeout_seconds,
+ close_fds = plan.close_fds,
+ terminate_descendants = plan.terminate_descendants,
+ execution_record = record,
+ )
+
+
def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
"""Unavailable hosts fall back in auto; unsafe workdirs and build failures refuse."""
if plan.cancel_event is not None and plan.cancel_event.is_set():
@@ -1099,6 +1114,27 @@ def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
),
)
+ if plan.requested_mode == "software":
+ # Chosen, not a fallback: no probe, so a host with a working OS sandbox is not checked for it.
+ return _software_launch(
+ plan,
+ ToolExecutionRecord(
+ requested_mode = plan.requested_mode,
+ effective_mode = "software_safeguards",
+ environment = sys.platform,
+ backend = "software-safeguards",
+ profile_id = "software-safeguards-v1",
+ probe_generation = "",
+ os_isolation = False,
+ retained_safeguards = tuple(
+ item
+ for item in _SOFTWARE_SAFEGUARDS
+ if item != "timeout" or plan.timeout_seconds is not None
+ ),
+ limitations = _software_only_limitations(),
+ ),
+ )
+
# Taken before the check: a reset while it runs must not be undone by this launch's answer.
generation = tool_isolation_generation()
capability = capability_snapshot(
@@ -1124,16 +1160,9 @@ def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:
f"OS_ISOLATION_UNAVAILABLE: {capability.reason}",
remediation = capability.remediation,
)
- return PreparedSandboxLaunch(
- argv = plan.argv,
- workdir = plan.workdir,
- env = plan.env,
- preexec_fn = plan.preexec_fn,
- backend = "software-safeguards",
- timeout_seconds = plan.timeout_seconds,
- close_fds = plan.close_fds,
- terminate_descendants = plan.terminate_descendants,
- execution_record = _record(
+ return _software_launch(
+ plan,
+ _record(
plan,
capability,
effective_mode = "software_safeguards",
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index 8a900ea4a9b..e665f76b96e 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -631,6 +631,7 @@ def run_safetensors_tool_loop(
mcp_image = None,
bypass_permissions: bool = False,
permission_mode: Optional[str] = None,
+ sandbox_level: Optional[str] = None,
reasoning_prefilled: bool = False,
continue_final_message: bool = False,
markup = None,
@@ -696,14 +697,17 @@ def run_safetensors_tool_loop(
from state.tool_policy import (
account_tool_stream,
needs_tool_confirmation,
+ normalize_sandbox_level,
normalize_tool_permissions,
requires_os_isolation,
+ runs_without_os_sandbox,
tool_call_may_prompt,
)
permission_mode, bypass_permissions = normalize_tool_permissions(
permission_mode, bypass_permissions
)
+ sandbox_level = normalize_sandbox_level(sandbox_level)
stream_tool_execution = account_tool_stream(stream_tool_execution)
from core.inference.skill_mentions import load_mentioned_skills
@@ -1529,6 +1533,7 @@ def run_safetensors_tool_loop(
permission_mode = permission_mode,
name = decision.tool_name,
arguments = decision.arguments,
+ sandbox_level = sandbox_level,
)
# Sending the user's image always asks, whatever the permission mode.
image_share = mcp_image_share(decision.tool_name, decision.arguments, mcp_image)
@@ -1540,6 +1545,7 @@ def run_safetensors_tool_loop(
name = decision.tool_name,
arguments = decision.arguments,
prompted = needs_confirm,
+ sandbox_level = sandbox_level,
)
approval_id = new_approval_id() if needs_confirm else ""
decision_slot = begin_tool_decision(session_id, approval_id) if needs_confirm else None
@@ -1641,6 +1647,10 @@ def run_safetensors_tool_loop(
# Run unasked only because the OS sandbox was on: refuse if it is not any more.
if _strict and _accepts_kwarg(execute_tool, "tool_execution_mode"):
kwargs["tool_execution_mode"] = "required"
+ elif runs_without_os_sandbox(
+ _decision.tool_name, sandbox_level
+ ) and _accepts_kwarg(execute_tool, "tool_execution_mode"):
+ kwargs["tool_execution_mode"] = "software"
if _accepts_kwarg(execute_tool, "conversation_branch"):
kwargs["conversation_branch"] = _extend_live_branch(conversation)
if _approved and _accepts_kwarg(execute_tool, "host_access_approved"):
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index 0a005dcb1c9..ad95524d78d 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -402,6 +402,7 @@ class ToolLoopPolicy:
# Called when a provider turn ends, however it ended. Headerless only: clears the stripper's withheld-call flag,
# which the wire cannot always close because a turn may end on [DONE] alone.
on_provider_turn_end: Callable[[], None] | None = None
+ sandbox_level: str = "high"
def _split_top_level_json_objects(text: str) -> tuple[list[str], str]:
@@ -1351,8 +1352,10 @@ async def stream_with_studio_tools(
from state.tool_policy import (
account_tool_stream,
needs_tool_confirmation,
+ normalize_sandbox_level,
normalize_tool_permissions,
requires_os_isolation,
+ runs_without_os_sandbox,
)
permission_mode, bypass_permissions = normalize_tool_permissions(
@@ -1361,6 +1364,7 @@ async def stream_with_studio_tools(
scoped_tool_stream = account_tool_stream(stream_tool_execution)
confirm_tool_calls = policy.confirm_calls
rag_scope = policy.rag_scope
+ sandbox_level = normalize_sandbox_level(policy.sandbox_level)
from core.inference.skill_mentions import load_mentioned_skills
@@ -1868,6 +1872,7 @@ async def stream_with_studio_tools(
arguments = arguments,
is_high_risk = is_high_risk_tool_call,
never_needs = never_needs_approval,
+ sandbox_level = sandbox_level,
)
# Sending the user's image always asks, whatever the permission mode.
image_share = (
@@ -1884,6 +1889,7 @@ async def stream_with_studio_tools(
arguments = arguments,
prompted = needs_confirmation,
is_high_risk = is_high_risk_tool_call,
+ sandbox_level = sandbox_level,
)
approval_id = new_approval_id() if needs_confirmation else ""
decision_slot = (
@@ -1989,6 +1995,10 @@ async def stream_with_studio_tools(
# Run unasked only because the OS sandbox was on: refuse if it is not any more.
if strict and accepts_kwarg(execute_tool, "tool_execution_mode"):
kwargs["tool_execution_mode"] = "required"
+ elif runs_without_os_sandbox(call.tool_name, sandbox_level) and accepts_kwarg(
+ execute_tool, "tool_execution_mode"
+ ):
+ kwargs["tool_execution_mode"] = "software"
# Provider loops share the local catalogue selector, so search_conversation is advertised here too
# once a thread has an archive and needs the same branch: the stored rows are the whole DAG, and Retry
# leaves the replaced response in them.
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index e7847441e52..9e92c7ce991 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -5947,12 +5947,32 @@ def _cmd_reading(command: str) -> str:
return _CMD_CONTROL_RE.sub(" & ", text)
+# The request's sandbox level while a call is classified: Low runs the Terminal on the host shell,
+# so the classifier must not probe for (or assume) the isolated cmd profile.
+_classifying_sandbox_level: "ContextVar[str | None]" = ContextVar(
+ "unsloth_classifying_sandbox_level", default = None
+)
+
+
+def classifying_under(sandbox_level: "str | None"):
+ token = _classifying_sandbox_level.set(sandbox_level)
+ try:
+ yield
+ finally:
+ _classifying_sandbox_level.reset(token)
+
+
+# Both run the command through cmd.exe: the isolated one inside MXC, the fallback on a host without Git Bash.
+_CMD_PROFILES = ("cmd_isolated", "cmd_fallback")
+
+
def _reads_differently_under_cmd(command: str) -> bool:
- """True when the isolated cmd Terminal will run ``command`` and cmd would split it unlike bash."""
+ """True when cmd.exe will run ``command`` and would split it unlike bash."""
return (
sys.platform == "win32"
and _cmd_reading(command) != command
- and _terminal_profile() == "cmd_isolated"
+ and _terminal_profile(_classifying_sandbox_level.get() == "low") in _CMD_PROFILES
)
@@ -10246,7 +10266,9 @@ def _profile_for_request() -> str:
return profile
-def apply_terminal_profile_for_request(tools: list[dict]) -> list[dict]:
+def apply_terminal_profile_for_request(
+ tools: list[dict], sandbox_level: "str | None" = None
+) -> list[dict]:
"""Sandboxed requests only: advertise the shell _bash_exec will pick for this request. Only the
first call can block on the MXC probe, so async callers run it in a worker thread; later calls
reuse the last profile and refresh it in the background. A list without the Terminal never probes."""
@@ -10255,7 +10277,8 @@ def apply_terminal_profile_for_request(tools: list[dict]) -> list[dict]:
for t in tools or ()
):
return tools
- return apply_terminal_profile_description(tools, _profile_for_request())
+ profile = _terminal_profile(True) if sandbox_level == "low" else _profile_for_request()
+ return apply_terminal_profile_description(tools, profile)
def _shell_argv(command: str, workdir: str, confinement) -> "tuple[list[str], str | None]":
@@ -22162,7 +22185,8 @@ def _bash_exec(
return _STUDIO_CREDENTIAL_BLOCKED
# Chosen once, so the blocklist, env and argv all agree on the shell that will run this call.
- profile = _terminal_profile(disable_sandbox)
+ # Sandbox Low runs on the host shell: cmd is only picked to stay inside MXC.
+ profile = _terminal_profile(disable_sandbox or tool_execution_mode == "software")
if profile == "cmd_isolated":
# Models often end a command with a newline; cmd /s /c cannot carry one.
command = command.strip()
@@ -22171,9 +22195,9 @@ def _bash_exec(
# Block dangerous commands (skipped when the sandbox is disabled)
if not disable_sandbox:
- if profile == "cmd_isolated":
+ if profile in _CMD_PROFILES:
# The cmd lexer misses separators glued to a word (a&powershell), cmd drops ^ escapes and
- # ' does not quote, so screen every reading; defence in depth, MXC is the boundary.
+ # ' does not quote, so screen every reading.
unescaped = command.replace("^", "")
blocked = set().union(
*(
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index f7bd6d3d10b..8beb9329e52 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2466,6 +2466,25 @@ def _normalize_permission_mode(value: Any) -> Any:
return value
+def _normalize_sandbox_level(value: Any) -> Any:
+ # Unlike permission_mode, an unknown level is a 422: degrading it either way would guess at
+ # the isolation the user picked. Absent or null is "high", today's behaviour.
+ if value is None:
+ return "high"
+ if isinstance(value, str):
+ return value.strip().lower()
+ return value
+
+
+_SANDBOX_LEVEL_DESCRIPTION = (
+ "[x-unsloth] Sandbox level for the Python and Terminal tools. 'high' (default) runs them "
+ "in the OS sandbox when it works and on software safeguards otherwise. 'low' runs them on "
+ "software safeguards only, so on a streaming UI chat 'off' still asks before their "
+ "high-risk calls; elsewhere 'off' never prompts, as before. Full access overrides both. "
+ "Case-insensitive; any other value is rejected."
+)
+
+
class SandboxAttachment(BaseModel):
sha256: str = Field(..., pattern = r"^[0-9a-f]{64}$")
name: str = Field(..., max_length = 1024)
@@ -2729,6 +2748,10 @@ class ChatCompletionRequest(BaseModel):
"newer client) is treated as 'ask'."
),
)
+ sandbox_level: Literal["high", "low"] = Field(
+ "high",
+ description = _SANDBOX_LEVEL_DESCRIPTION,
+ )
auto_heal_tool_calls: Optional[bool] = Field(
True,
description = "[x-unsloth] Auto-detect and fix malformed tool calls from model output.",
@@ -3098,6 +3121,11 @@ class ChatCompletionRequest(BaseModel):
def _map_thinking_to_enable_thinking(self) -> "ChatCompletionRequest":
return resolve_thinking_onto_enable_thinking(self)
+ @field_validator("sandbox_level", mode = "before")
+ @classmethod
+ def _coerce_sandbox_level(cls, value: Any) -> Any:
+ return _normalize_sandbox_level(value)
+
@field_validator("permission_mode", mode = "before")
@classmethod
def _coerce_permission_mode(cls, value: Any) -> Any:
@@ -3221,6 +3249,10 @@ class ChatCountTokensRequest(ReasoningControlsRequest):
"a pending turn under a retrieval scope is countable. A count that omits this prices a "
"prompt the completion will not send, or declines one it could have priced.",
)
+ sandbox_level: Literal["high", "low"] = Field(
+ "high",
+ description = _SANDBOX_LEVEL_DESCRIPTION,
+ )
bypass_permissions: Optional[bool] = Field(
None,
description = "[x-unsloth] Equivalent of permission_mode='full'. Declared explicitly (not "
@@ -3239,6 +3271,11 @@ class ChatCountTokensRequest(ReasoningControlsRequest):
"tool loop, so a count that never sees it prices a catalog the relay does not render.",
)
+ @field_validator("sandbox_level", mode = "before")
+ @classmethod
+ def _coerce_sandbox_level(cls, value: Any) -> Any:
+ return _normalize_sandbox_level(value)
+
@field_validator("permission_mode", mode = "before")
@classmethod
def _coerce_permission_mode(cls, value: Any) -> Any:
@@ -4040,6 +4077,10 @@ class AnthropicMessagesRequest(BaseModel):
None,
description = "[x-unsloth] Permission level for local tool calls: 'ask' pauses every call, 'auto' ('Approve for me') only pauses calls detected as high risk, 'off' ('Run automatically') never pauses while Python and Terminal run in the OS sandbox and otherwise pauses their high-risk calls in a streaming UI chat, 'full' equals bypass_permissions=true. Unset defaults to 'auto' for the per-call gate; a non-streaming request without an explicit mode runs the loop. An unrecognized value (e.g. from a newer client) is treated as 'ask'. Declared explicitly so omitted requests default to None instead of raising AttributeError.",
)
+ sandbox_level: Literal["high", "low"] = Field(
+ "high",
+ description = _SANDBOX_LEVEL_DESCRIPTION,
+ )
auto_heal_tool_calls: Optional[bool] = Field(
True,
description = "[x-unsloth] Auto-detect and fix malformed tool calls from model output (mirrors the Chat Completions field; applies to the client-tool passthrough).",
@@ -4105,6 +4146,11 @@ class AnthropicMessagesRequest(BaseModel):
normalized["system"] = _merge_anthropic_system(normalized.get("system"), system_additions)
return normalized
+ @field_validator("sandbox_level", mode = "before")
+ @classmethod
+ def _coerce_sandbox_level(cls, value: Any) -> Any:
+ return _normalize_sandbox_level(value)
+
@field_validator("permission_mode", mode = "before")
@classmethod
def _coerce_permission_mode(cls, value: Any) -> Any:
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 55f823043ef..1f78feac53a 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -511,6 +511,7 @@ class ChatSettingsPayload(BaseModel):
confirmToolCalls: Optional[bool] = None
# "full" (Full access) is session-only by design and never persisted.
permissionMode: Optional[Literal["ask", "auto", "off"]] = None
+ sandboxLevel: Optional[Literal["high", "low"]] = None
ragSource: Optional[
Annotated[
Union[ChatRagThreadSource, ChatRagKnowledgeBaseSource],
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index a9fa9b58b0e..ac28f1abcc8 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -6501,7 +6501,9 @@ async def _select_request_tools(
elif sys.platform == "win32":
# The isolated Windows Terminal runs cmd, not the host's Git Bash; say so in the schema.
from core.inference.tools import apply_terminal_profile_for_request
- tools = await asyncio.to_thread(apply_terminal_profile_for_request, tools)
+ tools = await asyncio.to_thread(
+ apply_terminal_profile_for_request, tools, getattr(payload, "sandbox_level", None)
+ )
if mcp_allowed:
tools = tools + await get_enabled_mcp_tools()
# getattr: callers hand in lighter payload objects than the request models, not all of
@@ -27870,6 +27872,7 @@ async def _proxy_to_external_provider(
),
timeout = payload.tool_call_timeout or 300,
permission_mode = payload.permission_mode or "auto",
+ sandbox_level = payload.sandbox_level,
confirm_calls = _permission_mode_confirm(payload)
or _off_mode_sandbox_gate(payload, _ui_events),
bypass_permissions = bool(payload.bypass_permissions),
@@ -28343,6 +28346,7 @@ async def _proxy_to_external_provider(
),
timeout = payload.tool_call_timeout or 300,
permission_mode = payload.permission_mode or "auto",
+ sandbox_level = payload.sandbox_level,
confirm_calls = _permission_mode_confirm(payload)
or _off_mode_sandbox_gate(payload, _ui_events),
bypass_permissions = bool(payload.bypass_permissions),
@@ -30859,6 +30863,7 @@ async def produce_openai_chat_completions(
mcp_image = _mcp_image,
bypass_permissions = bool(payload.bypass_permissions),
permission_mode = payload.permission_mode,
+ sandbox_level = payload.sandbox_level,
perf_callback = _gguf_perf_callback,
on_conversation_grew = _gguf_recost,
# Only the streaming path parks and reclaims, so only it can use a slot. An attached MCP
@@ -32970,6 +32975,7 @@ async def produce_openai_chat_completions(
mcp_image = _mcp_image,
bypass_permissions = bool(payload.bypass_permissions),
permission_mode = payload.permission_mode,
+ sandbox_level = payload.sandbox_level,
use_adapter = payload.use_adapter,
stats_holder = _sf_stats_holder,
reasoning_prefilled = _sf_reasoning_prefilled,
@@ -40450,7 +40456,11 @@ async def anthropic_count_tokens(
openai_tools = apply_full_access_tool_descriptions(openai_tools)
elif sys.platform == "win32":
from core.inference.tools import apply_terminal_profile_for_request
- openai_tools = await asyncio.to_thread(apply_terminal_profile_for_request, openai_tools)
+ openai_tools = await asyncio.to_thread(
+ apply_terminal_profile_for_request,
+ openai_tools,
+ getattr(payload, "sandbox_level", None),
+ )
_count_nudge = _build_tool_action_nudge(
tools = openai_tools,
model_name = _llama_public_model_id(llama_backend, payload.model),
@@ -41221,7 +41231,11 @@ async def anthropic_messages(
openai_tools = apply_full_access_tool_descriptions(openai_tools)
elif sys.platform == "win32":
from core.inference.tools import apply_terminal_profile_for_request
- openai_tools = await asyncio.to_thread(apply_terminal_profile_for_request, openai_tools)
+ openai_tools = await asyncio.to_thread(
+ apply_terminal_profile_for_request,
+ openai_tools,
+ getattr(payload, "sandbox_level", None),
+ )
server_tool_choice = openai_tool_choice
if isinstance(server_tool_choice, dict):
@@ -41304,6 +41318,7 @@ async def anthropic_messages(
disable_parallel_tool_use = _disable_parallel,
bypass_permissions = bool(payload.bypass_permissions),
permission_mode = getattr(payload, "permission_mode", None),
+ sandbox_level = getattr(payload, "sandbox_level", None),
promote_reasoning_only = False,
perf_callback = _monitor_perf_callback(
monitor_id,
diff --git a/studio/backend/routes/managed_engine_chat.py b/studio/backend/routes/managed_engine_chat.py
index 9e1a294fde1..a6de6230056 100644
--- a/studio/backend/routes/managed_engine_chat.py
+++ b/studio/backend/routes/managed_engine_chat.py
@@ -227,6 +227,7 @@ async def managed_tool_chat(
else 25,
timeout = payload.tool_call_timeout or 300,
permission_mode = payload.permission_mode or "auto",
+ sandbox_level = payload.sandbox_level,
confirm_calls = api._permission_mode_confirm(payload)
or api._off_mode_sandbox_gate(payload, ui_events),
bypass_permissions = bool(payload.bypass_permissions),
diff --git a/studio/backend/state/tool_policy.py b/studio/backend/state/tool_policy.py
index 51124ad51c6..6686119666d 100644
--- a/studio/backend/state/tool_policy.py
+++ b/studio/backend/state/tool_policy.py
@@ -74,23 +74,48 @@ def normalize_tool_permissions(
OS_SANDBOXED_TOOLS = frozenset({"python", "terminal"})
-def off_mode_still_gates(name: str) -> bool:
+SANDBOX_LEVELS = ("high", "low")
+
+
+def normalize_sandbox_level(value: Optional[str]) -> str:
+ """Absent reads as "high"; anything else is a caller bug, so it never silently loosens to "low"."""
+ if value is None:
+ return "high"
+ level = str(value).strip().lower()
+ if level not in SANDBOX_LEVELS:
+ raise ValueError(f"sandbox_level must be 'high' or 'low', not {value!r}")
+ return level
+
+
+def runs_without_os_sandbox(name: str, sandbox_level: Optional[str]) -> bool:
+ """Low: Python and Terminal run on software safeguards only, so they never claim OS isolation."""
+ return name in OS_SANDBOXED_TOOLS and sandbox_level == "low"
+
+
+def off_mode_still_gates(name: str, sandbox_level: 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 False
+ if runs_without_os_sandbox(name, sandbox_level):
+ return True
from core.inference.os_sandbox import cached_tool_isolation
return cached_tool_isolation(name) is not True
def tool_call_may_prompt(
- *, confirm_tool_calls: bool, bypass_permissions: bool, permission_mode: Optional[str], name: str
+ *,
+ confirm_tool_calls: bool,
+ bypass_permissions: bool,
+ permission_mode: Optional[str],
+ name: str,
+ sandbox_level: 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 False
if permission_mode == "off":
- return off_mode_still_gates(name)
+ return off_mode_still_gates(name, sandbox_level)
if permission_mode == "auto":
from core.inference.tools import is_always_safe_tool
return not is_always_safe_tool(name)
@@ -106,6 +131,7 @@ def needs_tool_confirmation(
arguments,
is_high_risk = None,
never_needs = None,
+ sandbox_level: Optional[str] = None,
) -> bool:
if is_high_risk is None or never_needs is None:
from core.inference import tools
@@ -114,12 +140,21 @@ def needs_tool_confirmation(
if not confirm_tool_calls or bypass_permissions or never_needs(name):
return False
if permission_mode == "off":
- return off_mode_still_gates(name) and is_high_risk(name, arguments)
+ return off_mode_still_gates(name, sandbox_level) and _classify(
+ is_high_risk, name, arguments, sandbox_level
+ )
if permission_mode == "auto":
- return is_high_risk(name, arguments)
+ return _classify(is_high_risk, name, arguments, sandbox_level)
return True
+def _classify(is_high_risk, name: str, arguments, sandbox_level: Optional[str]) -> bool:
+ """The risk check, told the level: under Low the Terminal's shell is the host's."""
+ from core.inference.tools import classifying_under
+ with classifying_under(sandbox_level):
+ return bool(is_high_risk(name, arguments))
+
+
def requires_os_isolation(
*,
confirm_tool_calls: bool,
@@ -129,6 +164,7 @@ def requires_os_isolation(
arguments,
prompted: bool,
is_high_risk = None,
+ sandbox_level: Optional[str] = None,
) -> bool:
"""Whether this call must launch with tool_execution_mode="required" (no software fallback).
@@ -136,11 +172,11 @@ def requires_os_isolation(
"""
if prompted or not confirm_tool_calls or bypass_permissions or permission_mode != "off":
return False
- if name not in OS_SANDBOXED_TOOLS:
+ if name not in OS_SANDBOXED_TOOLS or runs_without_os_sandbox(name, sandbox_level):
return False
if is_high_risk is None:
from core.inference.tools import is_high_risk_tool_call as is_high_risk
- return bool(is_high_risk(name, arguments))
+ return _classify(is_high_risk, name, arguments, sandbox_level)
def account_tool_stream(stream):
diff --git a/studio/backend/tests/test_chat_settings_payload.py b/studio/backend/tests/test_chat_settings_payload.py
index 3fe8b641736..91bcadbb551 100644
--- a/studio/backend/tests/test_chat_settings_payload.py
+++ b/studio/backend/tests/test_chat_settings_payload.py
@@ -131,6 +131,12 @@ def test_unset_fields_stay_out_of_the_merge():
assert payload.model_dump(exclude_unset = True) == {"ragTopK": 5}
[email protected]("level", ["high", "low"])
+def test_sandbox_level_survives_the_payload(level):
+ payload = ChatSettingsPayload.model_validate({"sandboxLevel": level})
+ assert payload.model_dump(exclude_unset = True) == {"sandboxLevel": level}
+
+
def test_max_tool_calls_off_survives_the_payload():
payload = ChatSettingsPayload.model_validate({"maxToolCallsPerMessage": 0})
assert payload.model_dump(exclude_unset = True) == {"maxToolCallsPerMessage": 0}
@@ -141,6 +147,7 @@ def test_max_tool_calls_off_survives_the_payload():
[
# Full access disables the sandbox, so it is re-accepted each session.
{"permissionMode": "full"},
+ {"sandboxLevel": "medium"},
{"ragTopK": 0},
{"ragTopK": 51},
{"ragAutoInjectMinScore": 2},
diff --git a/studio/backend/tests/test_llama_admission_compat_matrix.py b/studio/backend/tests/test_llama_admission_compat_matrix.py
index 209fe29f8bf..51940885abb 100644
--- a/studio/backend/tests/test_llama_admission_compat_matrix.py
+++ b/studio/backend/tests/test_llama_admission_compat_matrix.py
@@ -245,6 +245,17 @@ class TestOldCallers:
_TOOL_LOOP_HOOKS
), f"the hooks must stay together in order, got {hooks}"
+ def test_the_sandbox_level_was_appended_rather_than_inserted(self):
+ import inspect
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ names = list(
+ inspect.signature(LlamaCppBackend.generate_chat_completion_with_tools).parameters
+ )
+ assert names[-1] == "sandbox_level"
+ assert names.index("promote_reasoning_only") == names.index("permission_mode") + 1
+
def test_the_wait_timeout_has_a_sane_default(self):
import inspect
diff --git a/studio/backend/tests/test_sandbox_level.py b/studio/backend/tests/test_sandbox_level.py
new file mode 100644
index 00000000000..416b201a9de
--- /dev/null
+++ b/studio/backend/tests/test_sandbox_level.py
@@ -0,0 +1,595 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Sandbox Low/High: Low runs Python and Terminal on software safeguards only.
+
+High is the behaviour before the level existed. Low never probes or uses the OS sandbox, so its
+calls count as not isolated: "off" asks before their risky calls. Full access overrides both.
+"""
+
+import ast
+import asyncio
+import inspect
+import itertools
+import json
+import sys
+import textwrap
+import threading
+import uuid
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+_BACKEND_ROOT = Path(__file__).resolve().parents[1]
+if str(_BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_ROOT))
+
+from core.inference import mxc_policy, mxc_probe, os_sandbox, tools
+from models.inference import (
+ AnthropicMessagesRequest,
+ ChatCompletionRequest,
+ ChatCountTokensRequest,
+)
+from state import tool_policy
+
+MODES = ("ask", "auto", "off", "full")
+LEVELS = ("high", "low")
+ISOLATION = (True, False, None)
+TOOLS = ("python", "terminal", "web_search")
+_SESSION = "__LOCALID_sandbox_level"
+
+
+def _risk(name, arguments):
+ return bool(arguments.get("risky"))
+
+
+def _never(name):
+ return False
+
+
+def isolation(monkeypatch):
+ state = {}
+ monkeypatch.setattr(os_sandbox, "cached_tool_isolation", lambda tool: state.get(tool))
+ return state
+
+
+def _confirm_expected(mode, level, tool, isolated, risky):
+ if mode == "full":
+ return False
+ if mode == "ask":
+ return True
+ if mode == "auto":
+ return risky
+ os_tool = tool in ("python", "terminal")
+ return os_tool and (level == "low" or isolated is not True) and risky
+
+
+ "mode,level,tool,isolated,risky",
+ list(itertools.product(MODES, LEVELS, TOOLS, ISOLATION, (True, False))),
+)
+def test_decision_matrix(isolation, mode, level, tool, isolated, risky):
+ isolation["python"] = isolation["terminal"] = isolated
+ decision = dict(
+ confirm_tool_calls = True,
+ bypass_permissions = mode == "full",
+ permission_mode = mode,
+ name = tool,
+ arguments = {"risky": risky},
+ sandbox_level = level,
+ )
+ prompted = tool_policy.needs_tool_confirmation(
+ **decision, is_high_risk = _risk, never_needs = _never
+ )
+ assert prompted is _confirm_expected(mode, level, tool, isolated, risky)
+ strict = tool_policy.requires_os_isolation(**decision, prompted = prompted, is_high_risk = _risk)
+ # Low never demands the OS sandbox; High keeps today's strict launch for an unasked risky call.
+ assert strict is (
+ level == "high"
+ and mode == "off"
+ and tool in ("python", "terminal")
+ and risky
+ and not prompted
+ )
+
+
[email protected]("level,isolated", list(itertools.product(LEVELS, ISOLATION)))
+def test_off_may_prompt_for_low_even_when_the_os_sandbox_works(isolation, level, isolated):
+ isolation["python"] = isolated
+ may_prompt = tool_policy.tool_call_may_prompt(
+ confirm_tool_calls = True,
+ bypass_permissions = False,
+ permission_mode = "off",
+ name = "python",
+ sandbox_level = level,
+ )
+ assert may_prompt is (level == "low" or isolated is not True)
+ assert tool_policy.off_mode_still_gates("python", level) is may_prompt
+ assert tool_policy.off_mode_still_gates("web_search", level) is False
+
+
+def test_the_policy_level_defaults_to_high_and_rejects_typos():
+ assert tool_policy.normalize_sandbox_level(None) == "high"
+ assert tool_policy.normalize_sandbox_level(" LOW ") == "low"
+ with pytest.raises(ValueError):
+ tool_policy.normalize_sandbox_level("lowest")
+
+
+def _chat(**extra):
+ return ChatCompletionRequest(messages = [{"role": "user", "content": "hi"}], **extra)
+
+
+def _count(**extra):
+ return ChatCountTokensRequest(messages = [{"role": "user", "content": "hi"}], **extra)
+
+
+def _anthropic(**extra):
+ return AnthropicMessagesRequest(
+ model = "m", max_tokens = 8, messages = [{"role": "user", "content": "hi"}], **extra
+ )
+
+
[email protected]("build", [_chat, _count, _anthropic], ids = ["chat", "count", "anthropic"])
+ "sent,expected",
+ [
+ ({}, "high"),
+ ({"sandbox_level": None}, "high"),
+ ({"sandbox_level": " LOW "}, "low"),
+ ({"sandbox_level": "High"}, "high"),
+ ],
+)
+def test_the_request_field_is_normalized(build, sent, expected):
+ assert build(**sent).sandbox_level == expected
+
+
+def test_an_unknown_level_is_a_422():
+ app = FastAPI()
+
+ @app.post("/chat")
+ def chat(payload: ChatCompletionRequest):
+ return {"level": payload.sandbox_level}
+
+ @app.post("/messages")
+ def messages(payload: AnthropicMessagesRequest):
+ return {"level": payload.sandbox_level}
+
+ client = TestClient(app)
+ chat_body = {"messages": [{"role": "user", "content": "hi"}]}
+ anthropic_body = {**chat_body, "model": "m", "max_tokens": 8}
+ for path, body in (("/chat", chat_body), ("/messages", anthropic_body)):
+ assert client.post(path, json = {**body, "sandbox_level": "Low"}).json() == {"level": "low"}
+ for bad in ("medium", "", 1, True):
+ response = client.post(path, json = {**body, "sandbox_level": bad})
+ assert response.status_code == 422, (path, bad)
+
+
+def no_probe(monkeypatch):
+ def probe(**_kw):
+ raise AssertionError("Sandbox Low must not probe the OS sandbox")
+
+ monkeypatch.setattr(os_sandbox, "capability_snapshot", probe)
+
+
+def test_the_software_mode_is_internal_only():
+ assert "software" in os_sandbox.TOOL_EXECUTION_MODES
+ assert os_sandbox.PUBLIC_TOOL_EXECUTION_MODES == ("auto", "required")
+
+
+def test_the_planner_runs_low_on_software_safeguards_without_a_probe(no_probe, tmp_path):
+ os_sandbox.forget_tool_isolation()
+ plan = os_sandbox.ToolLaunchPlan(
+ argv = (sys.executable, "-c", "pass"),
+ workdir = str(tmp_path),
+ env = {},
+ execution_kind = "python",
+ requested_mode = "software",
+ timeout_seconds = 5,
+ )
+ launch = os_sandbox.prepare_tool_launch(plan)
+ record = launch.execution_record
+ assert launch.argv == plan.argv and launch.backend == "software-safeguards"
+ assert record.requested_mode == "software"
+ assert record.effective_mode == "software_safeguards"
+ assert record.os_isolation is False
+ assert "no_os_isolation" in record.limitations
+ assert "timeout" in record.retained_safeguards
+ assert not os_sandbox.has_tool_isolation_answer("python")
+
+
+ "run,expected",
+ [
+ (
+ lambda: tools._python_exec(
+ "print(6 * 7)", None, 60, _SESSION, tool_execution_mode = "software"
+ ),
+ "42",
+ ),
+ (
+ lambda: tools._bash_exec("echo 42", None, 60, _SESSION, tool_execution_mode = "software"),
+ "42",
+ ),
+ ],
+ ids = ["python", "terminal"],
+)
+def test_low_runs_both_tools_on_software_safeguards(no_probe, run, expected):
+ tools._last_tool_execution_record = None
+ assert expected in run()
+ record = tools._last_tool_execution_record
+ assert record.requested_mode == "software"
+ assert record.effective_mode == "software_safeguards"
+ assert record.os_isolation is False
+
+
+def test_full_access_overrides_low(no_probe):
+ tools._last_tool_execution_record = None
+ out = tools._python_exec(
+ "print(5)", None, 60, _SESSION, disable_sandbox = True, tool_execution_mode = "software"
+ )
+ assert "5" in out
+ assert tools._last_tool_execution_record.effective_mode == "full"
+
+
+class _RecordingConfinement:
+ preexec = None
+ confines = True
+
+ def __init__(self):
+ self.wrapped = []
+
+ def wrap(self, argv):
+ self.wrapped.append(list(argv))
+ return argv
+
+
+ "function,payload",
+ [(tools._python_exec, "print('MANAGED_OK')"), (tools._bash_exec, "echo MANAGED_OK")],
+ ids = ["python", "terminal"],
+)
+def test_low_keeps_the_managed_account_boundary(monkeypatch, no_probe, function, payload):
+ confinement = _RecordingConfinement()
+ monkeypatch.setattr(tools, "_account_confinement", lambda: confinement)
+ tools._last_tool_execution_record = None
+ assert "MANAGED_OK" in function(payload, None, 60, _SESSION, tool_execution_mode = "software")
+ assert confinement.wrapped, "the account boundary was skipped"
+ assert tools._last_tool_execution_record is None
+
+
+_BASH = r"C:\Program Files\Git\bin\bash.exe"
+
+
+def windows_cmd_host(monkeypatch):
+ """Git Bash fails inside MXC and cmd qualifies, so High runs the Terminal isolated on cmd."""
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setenv("SystemRoot", r"C:\Windows")
+ monkeypatch.delenv("UNSLOTH_MXC_TERMINAL_CMD", raising = False)
+ monkeypatch.setattr(tools, "_request_profile", [None, 0.0])
+ monkeypatch.setattr(tools, "_windows_bash", lambda: _BASH)
+ monkeypatch.setattr(mxc_policy, "dacl_fallback_enabled", lambda: True)
+
+ def snapshot(*, selected_executable = None, **_kw):
+ available = selected_executable != _BASH
+ reason = "" if available else mxc_probe.MSYS_NAMESPACE_REASON
+ return os_sandbox.SandboxCapability(backend = "mxc", available = available, reason = reason)
+
+ monkeypatch.setattr(os_sandbox, "capability_snapshot", snapshot)
+
+
+def _terminal_tool():
+ return [{"type": "function", "function": {"name": "terminal", "description": "Run a command."}}]
+
+
+def test_windows_low_advertises_the_host_shell(windows_cmd_host):
+ assert tools._terminal_profile() == "cmd_isolated"
+ high = tools.apply_terminal_profile_for_request(_terminal_tool(), "high")
+ low = tools.apply_terminal_profile_for_request(_terminal_tool(), "low")
+ assert low == tools.apply_terminal_profile_description(_terminal_tool(), "bash")
+ assert high == tools.apply_terminal_profile_description(_terminal_tool(), "cmd_isolated")
+ assert low != high
+
+
+def test_windows_low_launches_on_the_host_shell(windows_cmd_host, monkeypatch):
+ seen = []
+
+ class _Stop(Exception):
+ pass
+
+ def profile(disable_sandbox = False):
+ seen.append(disable_sandbox)
+ raise _Stop
+
+ monkeypatch.setattr(tools, "_terminal_profile", profile)
+ for mode in ("auto", "software"):
+ with pytest.raises(_Stop):
+ tools._bash_exec("echo hi", None, 60, _SESSION, tool_execution_mode = mode)
+ assert seen == [False, True]
+
+
[email protected]("level,expected", [("high", [False]), ("low", [True])])
+def test_the_risk_check_reads_the_terminal_shell_of_the_requested_level(
+ windows_cmd_host, monkeypatch, level, expected
+):
+ from state import tool_policy
+
+ seen = []
+ real = tools._terminal_profile
+
+ def profile(disable_sandbox = False):
+ seen.append(disable_sandbox)
+ return real(disable_sandbox)
+
+ monkeypatch.setattr(tools, "_terminal_profile", profile)
+ # cmd reads ' and ^ unlike bash, so only the isolated cmd profile looks twice.
+ tool_policy.needs_tool_confirmation(
+ confirm_tool_calls = True,
+ bypass_permissions = False,
+ permission_mode = "auto",
+ name = "terminal",
+ arguments = {"command": "echo 'a ^& b'"},
+ sandbox_level = level,
+ )
+ assert seen[:1] == expected
+ assert tools._classifying_sandbox_level.get() is None
+
+
+class _ModeRecordingExecuteTool:
+ def __init__(self):
+ self.calls = []
+
+ def __call__(
+ self,
+ name,
+ arguments,
+ *,
+ cancel_event = None,
+ timeout = None,
+ session_id = None,
+ thread_id = None,
+ rag_scope = None,
+ disable_sandbox = False,
+ tool_execution_mode = "auto",
+ **_kwargs,
+ ):
+ self.calls.append((name, tool_execution_mode, disable_sandbox))
+ return f"RESULT[{name}]"
+
+
+_LOOP_CASES = [
+ # level, tool, bypass, expected mode
+ ("low", "python", False, "software"),
+ ("low", "terminal", False, "software"),
+ ("low", "web_search", False, "auto"),
+ ("high", "python", False, "auto"),
+ ("low", "python", True, "full"),
+]
+
+
+def _arguments(tool):
+ return {"query": "x"} if tool == "web_search" else {"code": "print(1)", "command": "echo 1"}
+
+
[email protected]("level,tool,bypass,expected", _LOOP_CASES)
+def test_the_safetensors_loop_launches_low_in_software_mode(level, tool, bypass, expected):
+ from core.inference.safetensors_agentic import run_safetensors_tool_loop
+
+ call = json.dumps({"name": tool, "arguments": _arguments(tool)})
+ turns = iter([f"<tool_call>{call}</tool_call>", "final"])
+
+ def single_turn(_messages):
+ try:
+ yield next(turns)
+ except StopIteration:
+ return
+
+ exec_fn = _ModeRecordingExecuteTool()
+ list(
+ run_safetensors_tool_loop(
+ single_turn = single_turn,
+ messages = [{"role": "user", "content": "hi"}],
+ tools = [{"type": "function", "function": {"name": tool}}],
+ execute_tool = exec_fn,
+ session_id = f"level-{uuid.uuid4().hex}",
+ confirm_tool_calls = False,
+ bypass_permissions = bypass,
+ permission_mode = "full" if bypass else "off",
+ sandbox_level = level,
+ )
+ )
+ assert len(exec_fn.calls) == 1
+ _name, mode, disable_sandbox = exec_fn.calls[0]
+ assert disable_sandbox is bypass
+ # Full access wins inside execute_tool, whatever mode rides along.
+ assert tools._requested_execution_mode(mode, disable_sandbox) == expected
+
+
+def _studio_call_line(tool):
+ function = {"name": tool, "arguments": json.dumps(_arguments(tool))}
+ delta = {"tool_calls": [{"index": 0, "id": "c1", "type": "function", "function": function}]}
+ return "data: " + json.dumps({"choices": [{"index": 0, "delta": delta}]})
+
+
+class _FakeTransport:
+ heals_text_tool_calls = False
+
+ def __init__(self, turns):
+ self.turns = [list(turn) for turn in turns]
+
+ def stream(self, *, messages, tools, tool_choice, cancel_event):
+ lines = self.turns.pop(0) if self.turns else ["data: [DONE]"]
+
+ async def _gen():
+ for line in lines:
+ yield line
+
+ return _gen()
+
+
[email protected]("level,tool,bypass,expected", _LOOP_CASES)
+def test_the_shared_loop_launches_low_in_software_mode(monkeypatch, level, tool, bypass, expected):
+ from core.inference import studio_tool_loop as loop_mod
+
+ exec_fn = _ModeRecordingExecuteTool()
+ monkeypatch.setattr(loop_mod, "execute_tool", exec_fn)
+ monkeypatch.setattr(loop_mod, "build_rag_autoinject", lambda *a, **k: None)
+ finish = "data: " + json.dumps(
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]}
+ )
+ transport = _FakeTransport([[_studio_call_line(tool), finish], ["data: [DONE]"]])
+
+ async def _collect():
+ stream = loop_mod.stream_with_studio_tools(
+ transport,
+ run = loop_mod.ToolLoopRun(
+ messages = [{"role": "user", "content": "hi"}], session_id = "s1", thread_id = "t1"
+ ),
+ policy = loop_mod.ToolLoopPolicy(
+ tools = [{"type": "function", "function": {"name": tool, "parameters": {}}}],
+ max_calls = 5,
+ timeout = 60,
+ permission_mode = "full" if bypass else "off",
+ confirm_calls = False,
+ bypass_permissions = bypass,
+ rag_scope = None,
+ sandbox_level = level.upper(),
+ ),
+ cancel_event = threading.Event(),
+ )
+ return [line async for line in stream]
+
+ asyncio.run(asyncio.wait_for(_collect(), timeout = 30))
+ assert len(exec_fn.calls) == 1
+ _name, mode, disable_sandbox = exec_fn.calls[0]
+ assert tools._requested_execution_mode(mode, disable_sandbox) == expected
+
+
+def _calls_in(source, names):
+ tree = ast.parse(textwrap.dedent(source))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Call):
+ func = node.func
+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None)
+ if name in names:
+ yield name, node
+
+
+def test_every_decision_in_the_gguf_loop_reads_the_level():
+ # The GGUF loop needs a live llama-server, so (as the other llama_cpp tests do) read its source.
+ from core.inference import llama_cpp
+
+ source = inspect.getsource(llama_cpp.LlamaCppBackend.generate_chat_completion_with_tools)
+ decisions = {"tool_call_may_prompt", "needs_tool_confirmation", "requires_os_isolation"}
+ found = list(_calls_in(source, decisions))
+ assert {name for name, _ in found} == decisions
+ for name, node in found:
+ assert "sandbox_level" in {kw.arg for kw in node.keywords}, name
+ assert 'kwargs["tool_execution_mode"] = "software"' in source
+ assert "sandbox_level = normalize_sandbox_level(sandbox_level)" in source
+
+
+def test_every_loop_launches_low_through_the_mode_parameter():
+ from core.inference import llama_cpp, safetensors_agentic, studio_tool_loop
+ for module in (studio_tool_loop, llama_cpp, safetensors_agentic):
+ source = inspect.getsource(module)
+ assert 'kwargs["tool_execution_mode"] = "software"' in source, module.__name__
+ assert "runs_without_os_sandbox(" in source, module.__name__
+
+
+ "path", ["routes/inference.py", "routes/managed_engine_chat.py"], ids = ["inference", "managed"]
+)
+def test_every_route_that_forwards_the_mode_forwards_the_level(path):
+ source = (_BACKEND_ROOT / path).read_text(encoding = "utf-8")
+ forwarded = 0
+ for node in ast.walk(ast.parse(source)):
+ if not isinstance(node, ast.Call):
+ continue
+ keywords = {kw.arg: kw.value for kw in node.keywords}
+ mode = keywords.get("permission_mode")
+ if mode is None or "payload" not in ast.unparse(mode):
+ continue
+ func = node.func
+ callee = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
+ if callee == "load_mentioned_skills":
+ continue
+ assert "sandbox_level" in keywords, f"{path}:{node.lineno} {callee}"
+ forwarded += 1
+ assert forwarded
+
+
+def test_the_safetensors_orchestrator_forwards_the_level():
+ from core.inference.orchestrator import InferenceOrchestrator
+
+ function = InferenceOrchestrator.generate_chat_completion_with_tools
+ assert "sandbox_level" in inspect.signature(function).parameters
+ loops = list(_calls_in(inspect.getsource(function), {"run_safetensors_tool_loop"}))
+ assert loops
+ for _name, node in loops:
+ level = {kw.arg: kw.value for kw in node.keywords}.get("sandbox_level")
+ assert isinstance(level, ast.Name) and level.id == "sandbox_level"
+
+
+def test_the_codex_loop_forwards_the_level(monkeypatch):
+ from core.inference import openai_codex_tool_loop as loop_mod
+
+ entered = {}
+
+ def _loop(*a, **k):
+ entered.update(k)
+
+ async def gen():
+ yield "data: [DONE]\n\n"
+
+ return gen()
+
+ monkeypatch.setattr(loop_mod, "stream_with_studio_tools", _loop)
+ run = loop_mod.CodexRunContext(
+ provider_id = "p",
+ thread_id = None,
+ session_id = None,
+ messages = [],
+ model = "m",
+ reasoning_effort = None,
+ )
+ policy = loop_mod.CodexToolPolicy(
+ tools = [],
+ max_calls = 1,
+ timeout = 1,
+ permission_mode = "off",
+ confirm_calls = False,
+ bypass_permissions = False,
+ rag_scope = None,
+ sandbox_level = "low",
+ )
+ loop_mod.stream_codex_with_studio_tools(
+ object(), run = run, policy = policy, cancel_event = threading.Event()
+ )
+ assert entered["policy"].sandbox_level == "low"
+
+
[email protected]("sent,expected", [("low", "low"), ("LOW", "low"), (None, "high")])
+def test_a_durable_run_keeps_the_level_for_resume(sent, expected):
+ from routes.chat_generation_runs import CreateChatGenerationRun, _sanitize_request
+
+ request = {"messages": [{"role": "user", "content": "hi"}], "permission_mode": "off"}
+ if sent is not None:
+ request["sandbox_level"] = sent
+ sanitized = _sanitize_request(
+ CreateChatGenerationRun(
+ runId = "run1",
+ threadId = "thread1",
+ userMessageId = "u1",
+ assistantMessageId = "a1",
+ requestPayload = request,
+ )
+ )
+ assert sanitized["sandbox_level"] == expected
+ # The stored payload is replayed through the same model on resume and retry.
+ replayed = ChatCompletionRequest.model_validate(json.loads(json.dumps(sanitized)))
+ assert replayed.sandbox_level == expected
diff --git a/studio/backend/tests/test_windows_cmd_terminal_profile.py b/studio/backend/tests/test_windows_cmd_terminal_profile.py
index ff3363e4468..40e66a6935e 100644
--- a/studio/backend/tests/test_windows_cmd_terminal_profile.py
+++ b/studio/backend/tests/test_windows_cmd_terminal_profile.py
@@ -377,6 +377,19 @@ def test_approval_reads_a_cmd_command_the_way_cmd_splits_it(windows, monkeypatch
assert tools._terminal_is_high_risk(command) is False # bash keeps the whole thing one argument
+def test_the_host_cmd_fallback_is_read_as_cmd_too(windows, monkeypatch, tmp_path):
+ """No Git Bash (or Sandbox Low on such a host): `cmd /c` runs the command, so ' does not quote."""
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ monkeypatch.setattr(tools, "_terminal_profile", lambda *_a, **_k: "cmd_fallback")
+ assert tools._terminal_is_high_risk("echo 'hi & del victim.txt & echo bye'") is True
+ monkeypatch.setattr(
+ tools, "_BLOCKED_COMMANDS", tools._BLOCKED_COMMANDS_COMMON | tools._BLOCKED_COMMANDS_WIN
+ )
+ plan, result = _exec(monkeypatch, tmp_path, "echo 'x & rmdir /s /q y'")
+ assert plan is None
+ assert result.startswith("Blocked command(s) for safety: rmdir"), result
+
+
def test_cmd_echo_off_prefix_does_not_hide_the_command(windows, monkeypatch, tmp_path):
windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
monkeypatch.setattr(
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index ce58c359274..9d3da38ca6a 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -2109,6 +2109,7 @@ export async function buildLocalTokenCountExtras(
bypassPermissions,
deepResearchEnabled,
permissionMode,
+ sandboxLevel,
maxToolCallsPerMessage,
ragAutoInject,
ragAutoInjectMinScore,
@@ -2125,6 +2126,7 @@ export async function buildLocalTokenCountExtras(
return {
enable_tools: false,
bypass_permissions: bypassPermissions,
+ sandbox_level: sandboxLevel,
...threadField,
};
}
@@ -2153,6 +2155,7 @@ export async function buildLocalTokenCountExtras(
return {
enable_tools: false,
bypass_permissions: bypassPermissions,
+ sandbox_level: sandboxLevel,
...threadField,
};
}
@@ -2164,6 +2167,7 @@ export async function buildLocalTokenCountExtras(
// Ask holds first-pass retrieval behind the gate, so the count prices a pending RAG
// turn rather than declining one the completion never retrieves for.
permission_mode: permissionMode,
+ sandbox_level: sandboxLevel,
// Off suppresses the loop, and the relay renders no schemas or nudge: same zero.
max_tool_calls_per_message: maxToolCallsPerMessage,
// Full access swaps the python/terminal descriptions and adds a nudge
@@ -6539,6 +6543,7 @@ export function createOpenAIStreamAdapter(
],
mcp_enabled: mcpEnabledForChat,
permission_mode: permissionMode,
+ sandbox_level: runtime.sandboxLevel,
...(permissionMode === "auto" || permissionMode === "off"
? {}
: { confirm_tool_calls: permissionMode === "ask" }),
@@ -6727,7 +6732,9 @@ export function createOpenAIStreamAdapter(
// no pill lit. "auto" OMITS confirm_tool_calls (an explicit true would force a stream and
// defeat the safe-only exception); "off" omits it too, since an explicit false opts out of
// its risky-call prompt without an OS sandbox; "ask" sends true, full sends false.
+ // sandbox_level "low" runs Python/Terminal on software safeguards only; Full access overrides it.
permission_mode: permissionMode,
+ sandbox_level: runtime.sandboxLevel,
...(permissionMode === "auto" || permissionMode === "off"
? {}
: { confirm_tool_calls: permissionMode === "ask" }),
diff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.ts
index 2e0dd322d23..32360f20b59 100644
--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts
@@ -5,6 +5,7 @@ import { authFetch } from "@/features/auth";
import type { ChatPresetSource } from "../presets/preset-policy";
import type {
PermissionMode,
+ SandboxLevel,
RagAutoInject,
RagMode,
RagSource,
@@ -59,6 +60,7 @@ export interface PersistedChatSettings {
confirmToolCalls?: boolean;
/** "full" (Full access) is session-only and never leaves the browser. */
permissionMode?: Exclude<PermissionMode, "full">;
+ sandboxLevel?: SandboxLevel;
ragSource?: RagSource;
ragMode?: RagMode;
ragTopK?: number;
diff --git a/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx b/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx
index f3296c21732..2af06441cf3 100644
--- a/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx
+++ b/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx
@@ -16,7 +16,6 @@ import {
PermissionMenuLabel,
PermissionModeMenuItems,
} from "./permission-mode-select";
-import { useSandboxSetupDialogStore } from "./sandbox-setup-dialog";
// Dictation-only "+" menu fallback: the composer pill is the normal control, but it is hidden
// while recording, so this is the sole way to reach permission mode then.
@@ -24,7 +23,6 @@ export function BypassPermissionsMenuItem() {
const setBypassConfirmOpen = useChatRuntimeStore(
(s) => s.setBypassConfirmOpen,
);
- const setSandboxSetupOpen = useSandboxSetupDialogStore((s) => s.setOpen);
return (
<DropdownMenuSub>
@@ -33,16 +31,13 @@ export function BypassPermissionsMenuItem() {
Tool permissions
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="unsloth-plus-menu w-[calc(330px*var(--ui-space-scale,1))]">
- <PermissionMenuLabel learnMore />
+ <PermissionMenuLabel sandboxControls />
<PermissionModeMenuItems
// Defer past Radix's menu-close focus restoration, or the dropdown grabs focus back
// and breaks the dialog's focus trap.
onRequestFullAccess={() =>
setTimeout(() => setBypassConfirmOpen(true), 0)
}
- onRequestSandboxSetup={() =>
- setTimeout(() => setSandboxSetupOpen(true), 0)
- }
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 46621966a16..ddb5bdb562b 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -78,11 +78,7 @@ import {
useSyncExternalStore,
} from "react";
import { OpenAICodeExecSection } from "./components/openai-code-exec-section";
-import {
- PermissionModeDropdown,
- pickSandboxedMode,
-} from "./permission-mode-select";
-import { useSandboxSetupDialogStore } from "./sandbox-setup-dialog";
+import { PermissionModeDropdown } from "./permission-mode-select";
import { resyncInferenceStatusAfterServerModelChange } from "./hooks/use-chat-model-runtime";
import {
type ExternalProviderConfig,
@@ -2038,7 +2034,6 @@ function ConfirmToolCallsToggle() {
const setConfirmToolCalls = useChatRuntimeStore((s) => s.setConfirmToolCalls);
const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);
const permissionMode = useChatRuntimeStore((s) => s.permissionMode);
- const setSandboxSetupOpen = useSandboxSetupDialogStore((s) => s.setOpen);
return (
<div className="flex min-h-8 items-center justify-between gap-3">
@@ -2069,11 +2064,8 @@ function ConfirmToolCallsToggle() {
if (checked) {
setConfirmToolCalls(true);
} else {
- // Same path as picking "Run automatically": offer the setup when there is no
- // working OS sandbox instead of switching silently.
- void pickSandboxedMode(setPermissionMode, () =>
- setSandboxSetupOpen(true),
- );
+ // Same as picking "Run automatically".
+ setPermissionMode("off");
}
}}
disabled={permissionMode === "full"}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 9aa46c6975b..21272f21093 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -90,7 +90,14 @@ export {
useToolPaneScope,
} from "./tool-output-scope";
export { useToolAwaitingApproval } from "./tool-approval";
-export { PermissionModeDropdown, useActivePermissionMode } from "./permission-mode-select";
+export {
+ PermissionModeDropdown,
+ useActivePermissionMode,
+ useSandboxCapability,
+} from "./permission-mode-select";
+export { sandboxSwitchState } from "./sandbox-level";
+export { pickSandboxLevel } from "./sandbox-pick";
+export { SandboxSetupDialog } from "./sandbox-setup-dialog";
export {
type SandboxSetupAction,
type SandboxSetupJob,
diff --git a/studio/frontend/src/features/chat/permission-mode-select.tsx b/studio/frontend/src/features/chat/permission-mode-select.tsx
index ff2b7890366..c0a02880e3c 100644
--- a/studio/frontend/src/features/chat/permission-mode-select.tsx
+++ b/studio/frontend/src/features/chat/permission-mode-select.tsx
@@ -4,7 +4,7 @@
import { ChevronDown, Hand, ShieldCheck } from "lucide-react";
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";
import type { ComponentType } from "react";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useId, useRef, useState } from "react";
import { useFullAccessAllowed } from "@/features/auth/account-session";
import { useSettingsDialogStore } from "@/features/settings";
import { useT } from "@/i18n";
@@ -27,6 +27,7 @@ import {
DropdownMenuLabel,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { Switch } from "@/components/ui/switch";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { ShieldAlertGlyph } from "@/lib/shield-alert-icon";
import { SparklesGlyph } from "@/lib/sparkles-icon";
@@ -35,18 +36,20 @@ import { cn } from "@/lib/utils";
import {
ComputerTerminal01Icon,
Folder01Icon,
+ HelpCircleIcon,
InternetIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import {
- capabilityPending,
+ type SandboxCapability,
+ cachedSandboxCapability,
loadSandboxCapability,
onSandboxCapabilityChange,
sandboxReady,
} from "./api/sandbox-capability";
+import { sandboxSwitchState } from "./sandbox-level";
import {
- pickSandboxedMode as pickSandboxedModeWith,
- samePickIsIgnored,
+ pickSandboxLevel,
} from "./sandbox-pick";
import {
SandboxSetupDialog,
@@ -120,31 +123,95 @@ export function permissionModeOption(mode: PermissionMode) {
);
}
-/** Menu heading. `learnMore` links to the fuller explanation in Settings. */
-export function PermissionMenuLabel({ learnMore }: { learnMore: boolean }) {
- const openSettings = useSettingsDialogStore((s) => s.openDialog);
+/** Menu heading. `sandboxControls` adds the Sandbox Low/High switch; Settings shows its own row.
+ * `onOsSandboxMissing` opens the install popup; by default the one at the chat-page root. */
+export function PermissionMenuLabel({
+ sandboxControls,
+ onOsSandboxMissing,
+}: {
+ sandboxControls: boolean;
+ onOsSandboxMissing?: () => void;
+}) {
+ const t = useT();
return (
<DropdownMenuLabel className="flex items-center justify-between gap-3">
- <span>Tool call permissions</span>
- {learnMore ? (
- // A menu item, so arrow keys reach it and selecting closes the menu.
- <DropdownMenuPrimitive.Item
- className="shrink-0 cursor-pointer rounded-sm underline underline-offset-2 outline-hidden hover:text-foreground focus-visible:text-foreground data-[highlighted]:text-foreground"
- // Deferred past the menu's focus restore.
- onSelect={() =>
- setTimeout(
- () => openSettings("general", { scrollTarget: "general-permissions" }),
- 0,
- )
- }
- >
- Learn more
- </DropdownMenuPrimitive.Item>
- ) : null}
+ <span>{t("settings.general.permissions.sectionTitle")}</span>
+ {sandboxControls ? <SandboxLevelMenuSwitch onOsSandboxMissing={onOsSandboxMissing} /> : null}
</DropdownMenuLabel>
);
}
+/** Switch on = High (OS sandboxing), off = Low (software sandboxing). A checkbox item, so arrow
+ * keys reach it and Enter or Space toggles it. It keeps the menu open, except when High may need
+ * the setup popup, which cannot open over the menu. The question mark next to it opens Settings. */
+function SandboxLevelMenuSwitch({ onOsSandboxMissing }: { onOsSandboxMissing?: () => void }) {
+ const t = useT();
+ const sandboxLevel = useChatRuntimeStore((s) => s.sandboxLevel);
+ const setSandboxLevel = useChatRuntimeStore((s) => s.setSandboxLevel);
+ const setSandboxSetupOpen = useSandboxSetupDialogStore((s) => s.setOpen);
+ const openSettings = useSettingsDialogStore((s) => s.openDialog);
+ const { permissionMode } = useAccountPermissionMode();
+ const capability = useSandboxCapability(sandboxLevel === "high");
+ const { checked, disabled } = sandboxSwitchState(sandboxLevel, permissionMode, capability);
+ const descriptionId = useId();
+ const help = t("settings.sandbox.levelHelp");
+ return (
+ <span className="flex shrink-0 items-center gap-1">
+ <DropdownMenuPrimitive.CheckboxItem
+ checked={checked}
+ disabled={disabled}
+ aria-describedby={descriptionId}
+ onSelect={(event) => {
+ const known = cachedSandboxCapability();
+ if (checked || (known !== null && sandboxReady(known))) event.preventDefault();
+ }}
+ onCheckedChange={(next) => {
+ void pickSandboxLevel(next === true ? "high" : "low", setSandboxLevel, () =>
+ // Deferred past the menu's focus restore.
+ setTimeout(onOsSandboxMissing ?? (() => setSandboxSetupOpen(true)), 0),
+ );
+ }}
+ className="flex shrink-0 cursor-pointer items-center gap-2 rounded-sm font-normal outline-hidden hover:text-foreground focus-visible:text-foreground data-[disabled]:cursor-not-allowed data-[highlighted]:text-foreground"
+ >
+ <span>{t("settings.sandbox.levelLabel")}</span>
+ <span className="min-w-[2.25em] text-right text-muted-foreground">
+ {checked ? t("settings.sandbox.levelHigh") : t("settings.sandbox.levelLow")}
+ </span>
+ {/* Presentation only: the item carries the state and the keyboard. */}
+ <Switch
+ size="sm"
+ checked={checked}
+ disabled={disabled}
+ tabIndex={-1}
+ aria-hidden={true}
+ className="pointer-events-none"
+ />
+ </DropdownMenuPrimitive.CheckboxItem>
+ <DropdownMenuPrimitive.Item
+ aria-label={help}
+ title={help}
+ className="flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground outline-hidden hover:text-foreground focus-visible:text-foreground data-[highlighted]:text-foreground"
+ // Deferred past the menu's focus restore.
+ onSelect={() =>
+ setTimeout(
+ () => openSettings("sandbox", { scrollTarget: "sandbox-permissions" }),
+ 0,
+ )
+ }
+ >
+ <HugeiconsIcon icon={HelpCircleIcon} strokeWidth={2} className="size-3.5" />
+ </DropdownMenuPrimitive.Item>
+ <span id={descriptionId} className="sr-only">
+ {disabled
+ ? t("settings.sandbox.levelFullAccessNote")
+ : checked
+ ? t("settings.sandbox.levelHighShort")
+ : t("settings.sandbox.levelLowShort")}
+ </span>
+ </span>
+ );
+}
+
/** The option rows shared by every permission dropdown or submenu. Non-full levels apply
* directly; picking Full access must go through the caller's danger confirmation. */
function useAccountPermissionMode() {
@@ -160,23 +227,19 @@ function useAccountPermissionMode() {
};
}
-/** False while unknown or when the server is too old to say; follows later reads and resets. */
-function useSandboxUnavailable(): boolean {
- const [unavailable, setUnavailable] = useState(false);
+/** Null while unknown, when the server is too old to say, or when `enabled` is false (Low needs no
+ * OS sandbox answer, and the read probes it); follows later reads and resets. */
+export function useSandboxCapability(enabled: boolean): SandboxCapability | null {
+ const [capability, setCapability] = useState<SandboxCapability | null>(null);
useEffect(() => {
+ if (!enabled) return;
let live = true;
// Only the newest read applies: an older answer resolving last must not undo a newer one.
let reads = 0;
const read = () => {
const id = ++reads;
- void loadSandboxCapability().then((capability) => {
- if (live && id === reads) {
- setUnavailable(
- capability !== null &&
- !capabilityPending(capability) &&
- !sandboxReady(capability),
- );
- }
+ void loadSandboxCapability().then((next) => {
+ if (live && id === reads) setCapability(next);
});
};
read();
@@ -185,37 +248,17 @@ function useSandboxUnavailable(): boolean {
live = false;
stop();
};
- }, []);
- return unavailable;
-}
-
-export function pickSandboxedMode(
- setPermissionMode: (mode: PermissionMode) => void,
- onRequestSandboxSetup: () => void,
-): Promise<void> {
- return pickSandboxedModeWith(
- setPermissionMode,
- onRequestSandboxSetup,
- () => useChatRuntimeStore.getState().permissionMode,
- undefined,
- (onChange) =>
- useChatRuntimeStore.subscribe((state, previous) => {
- if (state.permissionMode !== previous.permissionMode) onChange();
- }),
- );
+ }, [enabled]);
+ return enabled ? capability : null;
}
export function PermissionModeMenuItems({
onRequestFullAccess,
- onRequestSandboxSetup,
}: {
onRequestFullAccess: () => void;
- onRequestSandboxSetup: () => void;
}) {
- const t = useT();
const { permissionMode, fullAccessAllowed } = useAccountPermissionMode();
const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);
- const sandboxUnavailable = useSandboxUnavailable();
return (
<>
@@ -223,13 +266,11 @@ export function PermissionModeMenuItems({
<DropdownMenuItem
key={option.value}
onSelect={() => {
- if (samePickIsIgnored(option.value, permissionMode, sandboxUnavailable)) {
- return;
- }
+ if (option.value === permissionMode) return;
+ // Run automatically applies at once: without an OS sandbox the switch reads Low and
+ // risky Python and Terminal calls still ask.
if (option.value === "full") {
onRequestFullAccess();
- } else if (option.value === "off") {
- void pickSandboxedMode(setPermissionMode, onRequestSandboxSetup);
} else {
setPermissionMode(option.value);
}
@@ -245,11 +286,6 @@ export function PermissionModeMenuItems({
<span className="text-xs font-normal leading-snug text-muted-foreground">
{option.description}
</span>
- {option.value === "off" && sandboxUnavailable ? (
- <span className="text-xs font-normal leading-snug text-muted-foreground">
- {t("sandboxSetup.unavailable")}
- </span>
- ) : null}
</span>
{permissionMode === option.value ? (
<HugeiconsIcon
@@ -342,8 +378,8 @@ export function FullAccessConfirmContent({
className="cursor-pointer text-foreground underline underline-offset-2"
onClick={() => {
onClose();
- openSettings("general", {
- scrollTarget: "general-permissions",
+ openSettings("sandbox", {
+ scrollTarget: "sandbox-permissions",
opener: returnFocusRef.current,
});
}}
@@ -389,18 +425,18 @@ export function FullAccessConfirmDialog({
}
/** Select-style dropdown (like the MCP composer menu) for picking the permission level. Used in
- * General settings and the chat settings sheet. */
+ * Settings > Sandbox and the chat settings sheet. */
export function PermissionModeDropdown({
side = "bottom",
align = "end",
triggerClassName,
- learnMore = true,
+ sandboxControls = true,
}: {
side?: "top" | "bottom";
align?: "start" | "end";
triggerClassName?: string;
- /** Off in Settings, which already shows the full explanation. */
- learnMore?: boolean;
+ /** Off in Settings, which shows the level and the setup in their own rows. */
+ sandboxControls?: boolean;
} = {}) {
const { permissionMode, fullAccessAllowed } = useAccountPermissionMode();
const [confirmOpen, setConfirmOpen] = useState(false);
@@ -431,16 +467,16 @@ export function PermissionModeDropdown({
className="w-[calc(330px*var(--ui-space-scale,1))]"
avoidCollisions={true}
>
- <PermissionMenuLabel learnMore={learnMore} />
+ <PermissionMenuLabel
+ sandboxControls={sandboxControls}
+ onOsSandboxMissing={() => setSandboxSetupOpen(true)}
+ />
<PermissionModeMenuItems
// Defer past the menu-close focus restoration so the dialog's focus trap is not broken by the
// dropdown grabbing focus back.
onRequestFullAccess={() =>
setTimeout(() => setConfirmOpen(true), 0)
}
- onRequestSandboxSetup={() =>
- setTimeout(() => setSandboxSetupOpen(true), 0)
- }
/>
</DropdownMenuContent>
</DropdownMenu>
@@ -468,7 +504,6 @@ export function PermissionModeComposerPill({
const setBypassConfirmOpen = useChatRuntimeStore(
(s) => s.setBypassConfirmOpen,
);
- const setSandboxSetupOpen = useSandboxSetupDialogStore((s) => s.setOpen);
const active = permissionModeOption(permissionMode);
const ActiveIcon = active.icon;
@@ -500,15 +535,12 @@ export function PermissionModeComposerPill({
avoidCollisions={true}
className="unsloth-plus-menu w-[calc(330px*var(--ui-space-scale,1))]"
>
- <PermissionMenuLabel learnMore={true} />
+ <PermissionMenuLabel sandboxControls={true} />
<PermissionModeMenuItems
// Defer past the menu-close focus restoration (see PermissionModeDropdown).
onRequestFullAccess={() =>
setTimeout(() => setBypassConfirmOpen(true), 0)
}
- onRequestSandboxSetup={() =>
- setTimeout(() => setSandboxSetupOpen(true), 0)
- }
/>
</DropdownMenuContent>
</DropdownMenu>
diff --git a/studio/frontend/src/features/chat/sandbox-level.ts b/studio/frontend/src/features/chat/sandbox-level.ts
new file mode 100644
index 00000000000..809bec0c983
--- /dev/null
+++ b/studio/frontend/src/features/chat/sandbox-level.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Type-only imports keep this module loadable by the node tests.
+import type { SandboxCapability } from "./api/sandbox-capability";
+import type { PermissionMode, SandboxLevel } from "./stores/chat-runtime-store";
+
+/** A settled answer says Python or Terminal runs without OS isolation. Unknown (no answer, an old
+ * server) or still probing is not "missing". */
+export function osSandboxMissing(capability: SandboxCapability | null): boolean {
+ if (capability === null) return false;
+ if (capability.pythonOsIsolated && capability.terminalOsIsolated) return false;
+ // Same as capabilityPending: the startup probe has not answered yet.
+ return capability.backend !== "unknown";
+}
+
+/** Switch on = High (OS sandboxing). Without an OS sandbox the calls run on software sandboxing,
+ * so the switch shows Low whatever was saved. Full access drops the sandbox, so the switch is
+ * disabled there and keeps showing the level. */
+export function sandboxSwitchState(
+ level: SandboxLevel,
+ permissionMode: PermissionMode,
+ capability: SandboxCapability | null = null,
+): { checked: boolean; disabled: boolean } {
+ return {
+ checked: level === "high" && !osSandboxMissing(capability),
+ disabled: permissionMode === "full",
+ };
+}
diff --git a/studio/frontend/src/features/chat/sandbox-pick.ts b/studio/frontend/src/features/chat/sandbox-pick.ts
index d7d0ffbbfc5..4cb076b9753 100644
--- a/studio/frontend/src/features/chat/sandbox-pick.ts
+++ b/studio/frontend/src/features/chat/sandbox-pick.ts
@@ -8,52 +8,39 @@ import {
loadSettledSandboxCapability,
sandboxReady,
} from "./api/sandbox-capability";
-import type { PermissionMode } from "./stores/chat-runtime-store";
+import type { SandboxLevel } from "./stores/chat-runtime-store";
-let sandboxedPicks = 0;
+let levelPicks = 0;
-/** Re-picking "Run automatically" without a working sandbox reopens the setup dialog. */
-export function samePickIsIgnored(
- value: PermissionMode,
- current: PermissionMode,
- sandboxUnavailable: boolean,
-): boolean {
- return value === current && !(value === "off" && sandboxUnavailable);
-}
-
-/** Without a working OS sandbox, offers setup instead of applying. A stale read does nothing. */
-export function pickSandboxedMode(
- setPermissionMode: (mode: PermissionMode) => void,
- onRequestSandboxSetup: () => void,
- currentMode: () => PermissionMode,
+/** Switching to High without a working OS sandbox opens the setup popup instead of applying;
+ * Low always applies. A stale read (a later switch) does nothing. */
+export function pickSandboxLevel(
+ next: SandboxLevel,
+ setSandboxLevel: (level: SandboxLevel) => void,
+ onOsSandboxMissing: () => void,
load: () => Promise<SandboxCapability | null> = loadSettledSandboxCapability,
- watchModeChanges?: (onChange: () => void) => () => void,
peek: () => SandboxCapability | null = cachedSandboxCapability,
): Promise<void> {
- const pick = ++sandboxedPicks;
- // Known ready: apply at once instead of waiting on a fresh probe. The backend still checks each call.
+ const pick = ++levelPicks;
+ if (next === "low") {
+ setSandboxLevel("low");
+ return Promise.resolve();
+ }
const known = peek();
if (known !== null && sandboxReady(known)) {
- setPermissionMode("off");
+ setSandboxLevel("high");
return Promise.resolve();
}
- const before = currentMode();
- let changed = false;
- const stopWatching = watchModeChanges?.(() => {
- changed = true;
- });
return load().then((capability) => {
- stopWatching?.();
- if (changed || pick !== sandboxedPicks || currentMode() !== before) return;
- // Still unknown: apply it; the backend asks before risky calls until isolation is confirmed.
+ if (pick !== levelPicks) return;
if (
capability !== null &&
!capabilityPending(capability) &&
!sandboxReady(capability)
) {
- onRequestSandboxSetup();
+ onOsSandboxMissing();
} else {
- setPermissionMode("off");
+ setSandboxLevel("high");
}
});
}
diff --git a/studio/frontend/src/features/chat/sandbox-setup-dialog.tsx b/studio/frontend/src/features/chat/sandbox-setup-dialog.tsx
index 0bc87533de3..25f8e1fabc9 100644
--- a/studio/frontend/src/features/chat/sandbox-setup-dialog.tsx
+++ b/studio/frontend/src/features/chat/sandbox-setup-dialog.tsx
@@ -16,6 +16,7 @@ import {
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Spinner } from "@/components/ui/spinner";
+import { useSettingsDialogStore } from "@/features/settings";
import { useT } from "@/i18n";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import {
@@ -41,29 +42,38 @@ export const useSandboxSetupDialogStore = create<{
const NOTE_CLASS = "text-xs leading-relaxed";
-/** Picking the mode never starts a setup; only the install button does. */
+/** Switching the sandbox to High without an OS sandbox. Opening it never starts a setup; only the
+ * install button does, and a setup that works turns High on. */
export function SandboxSetupDialog({
open,
onOpenChange,
+ onLearnMore,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
+ /** Defaults to opening Settings > Sandbox at Permissions. */
+ onLearnMore?: () => void;
}) {
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
{/* Mounted per opening, so every opening starts from a fresh check. */}
- {open ? <SandboxSetupContent onOpenChange={onOpenChange} /> : null}
+ {open ? (
+ <SandboxSetupContent onOpenChange={onOpenChange} onLearnMore={onLearnMore} />
+ ) : null}
</AlertDialog>
);
}
function SandboxSetupContent({
onOpenChange,
+ onLearnMore,
}: {
onOpenChange: (open: boolean) => void;
+ onLearnMore?: () => void;
}) {
const t = useT();
- const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);
+ const setSandboxLevel = useChatRuntimeStore((s) => s.setSandboxLevel);
+ const openSettings = useSettingsDialogStore((s) => s.openDialog);
const [capability, setCapability] = useState<SandboxCapability | null>(null);
const [loadFailed, setLoadFailed] = useState(false);
const [job, setJob] = useState<SandboxSetupJob | null>(null);
@@ -73,8 +83,8 @@ function SandboxSetupContent({
const mounted = useRef(true);
// Only the newest check applies (a retry can overtake a slow first read).
const checks = useRef(0);
- // A level picked while the setup ran wins over turning Run automatically on at the end.
- const modeAtOpen = useRef(useChatRuntimeStore.getState().permissionMode);
+ // A level picked while the setup ran wins over turning High on at the end.
+ const levelAtOpen = useRef(useChatRuntimeStore.getState().sandboxLevel);
useEffect(() => {
mounted.current = true;
@@ -119,8 +129,8 @@ function SandboxSetupContent({
if (!mounted.current) return;
if (next) setCapability(next);
if (next && sandboxReady(next)) {
- if (useChatRuntimeStore.getState().permissionMode === modeAtOpen.current) {
- setPermissionMode("off");
+ if (useChatRuntimeStore.getState().sandboxLevel === levelAtOpen.current) {
+ setSandboxLevel("high");
}
toast.success(t("sandboxSetup.succeeded"));
onOpenChange(false);
@@ -129,7 +139,7 @@ function SandboxSetupContent({
}
});
},
- [onOpenChange, setPermissionMode, t],
+ [onOpenChange, setSandboxLevel, t],
);
useEffect(() => {
@@ -182,7 +192,8 @@ function SandboxSetupContent({
const copy = async () => {
if (await copyToClipboard(view.command)) {
- toast.success(t("sandboxSetup.copied"));
+ // The command itself stays out of the popup; Settings > Sandbox shows it in full.
+ toast.success(t("sandboxSetup.copiedRunIt"));
} else {
toast.error(t("sandboxSetup.copyFailed"));
}
@@ -191,9 +202,9 @@ function SandboxSetupContent({
return (
<AlertDialogContent>
<AlertDialogHeader>
- <AlertDialogTitle>{t("sandboxSetup.title")}</AlertDialogTitle>
+ <AlertDialogTitle>{t("sandboxSetup.levelTitle")}</AlertDialogTitle>
<AlertDialogDescription>
- {t("sandboxSetup.description")}
+ {t("sandboxSetup.levelDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
@@ -211,15 +222,10 @@ function SandboxSetupContent({
{t("sandboxSetup.checking")}
</p>
) : null}
- {capability?.reason ? (
- <p className={`${NOTE_CLASS} text-muted-foreground`}>
- {capability.reason}
- </p>
- ) : null}
{view.showConsent ? (
<div className="flex flex-col gap-2">
<p className={`${NOTE_CLASS} text-muted-foreground`}>
- {t("settings.sandbox.disclosure")}
+ {t("sandboxSetup.windowsNote")}
</p>
<label className="flex items-center gap-2 text-sm">
<Checkbox
@@ -270,25 +276,11 @@ function SandboxSetupContent({
{actionError ? (
<p className={`${NOTE_CLASS} text-destructive`}>{actionError}</p>
) : null}
- {view.showOwnerOnly && !view.command ? (
+ {view.showOwnerOnly ? (
<p className={`${NOTE_CLASS} text-muted-foreground`}>
{t("sandboxSetup.ownerOnly")}
</p>
) : null}
- {view.command ? (
- <div className="flex min-w-0 flex-col gap-1">
- <p className={`${NOTE_CLASS} text-muted-foreground`}>
- {view.showOwnerOnly
- ? t("sandboxSetup.ownerOnly")
- : view.showRunInTerminal
- ? t("sandboxSetup.runInTerminal")
- : t("sandboxSetup.commandHint")}
- </p>
- <pre className="max-h-40 overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted px-2 py-1.5 font-mono text-ui-11">
- {view.command}
- </pre>
- </div>
- ) : null}
</div>
<AlertDialogFooter className="flex-wrap">
@@ -310,24 +302,43 @@ function SandboxSetupContent({
</Button>
) : null}
{view.command ? (
- <Button size="sm" variant="outline" onClick={() => void copy()}>
+ <Button
+ size="sm"
+ variant="outline"
+ title={view.command}
+ onClick={() => void copy()}
+ >
{t("sandboxSetup.copyCommand")}
</Button>
) : null}
<Button
size="sm"
variant="outline"
- disabled={view.checking}
onClick={() => {
- setPermissionMode("off");
+ // Closing does not stop a running setup; its result shows in Settings > Sandbox.
onOpenChange(false);
+ if (onLearnMore) {
+ onLearnMore();
+ } else {
+ // Deferred past the dialog's focus restore.
+ setTimeout(
+ () => openSettings("sandbox", { scrollTarget: "sandbox-permissions" }),
+ 0,
+ );
+ }
}}
>
- {t("sandboxSetup.useAnyway")}
+ {t("settings.sandbox.learnMore")}
</Button>
- <Button size="sm" variant="ghost" onClick={() => onOpenChange(false)}>
- {/* Closing does not stop a running setup; its result shows in Settings > Sandbox. */}
- {view.running ? t("sandboxSetup.close") : t("sandboxSetup.cancel")}
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => {
+ setSandboxLevel("low");
+ onOpenChange(false);
+ }}
+ >
+ {t("sandboxSetup.useLow")}
</Button>
</AlertDialogFooter>
</AlertDialogContent>
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 9cbcae04b2e..323c97deac2 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -150,10 +150,13 @@ export const MODELS_FIT_ON_DEVICE_ONLY_KEY =
"unsloth_models_fit_on_device_only";
export const CHAT_BYPASS_PERMISSIONS_KEY = "unsloth_chat_bypass_permissions";
export const CHAT_PERMISSION_MODE_KEY = "unsloth_chat_permission_mode";
+export const CHAT_SANDBOX_LEVEL_KEY = "unsloth_chat_sandbox_level";
/** Local tool-call gate: "ask" every call, "auto" only high-risk ones, "off" never but keeps the
* sandbox, "full" drops both and is session-only. */
export type PermissionMode = "ask" | "auto" | "off" | "full";
+/** "high" adds the OS sandbox (bubblewrap, Seatbelt, MXC) to the software safeguards; "low" uses only those. */
+export type SandboxLevel = "high" | "low";
export const CHAT_WEB_FETCH_TOOLS_ENABLED_KEY =
"unsloth_chat_web_fetch_tools_enabled";
export const CHAT_RAG_SOURCE_KEY = "unsloth_chat_rag_source";
@@ -726,6 +729,7 @@ const MIRRORED_SETTINGS = {
? loadPermissionMode()
: undefined,
},
+ sandboxLevel: { storageKey: CHAT_SANDBOX_LEVEL_KEY, ...STRING_SETTING },
ragSource: { storageKey: CHAT_RAG_SOURCE_KEY, ...JSON_SETTING },
ragMode: { storageKey: CHAT_RAG_MODE_KEY, ...STRING_SETTING },
ragTopK: { storageKey: CHAT_RAG_TOP_K_KEY, ...NUMBER_SETTING },
@@ -1829,6 +1833,15 @@ export function resolvePreserveThinkingOnLoad(resp: {
/** "full" is never restored: it disables the sandbox and every confirmation gate, so it needs
* the warning dialog each session. First run derives from the legacy confirm toggle. */
+/** Anything but an explicit "low" (missing, garbled, a newer value) reads as the default, "high". */
+export function normalizeSandboxLevel(raw: unknown): SandboxLevel {
+ return raw === "low" ? "low" : "high";
+}
+
+export function loadSandboxLevel(): SandboxLevel {
+ return normalizeSandboxLevel(readStorageValue(CHAT_SANDBOX_LEVEL_KEY));
+}
+
function loadPermissionMode(): PermissionMode {
return normalizeStoredPermissionMode(
readStorageValue(CHAT_PERMISSION_MODE_KEY),
@@ -2346,6 +2359,7 @@ type ChatRuntimeStore = {
/** Permission level. Single source of truth for the bypass dropdowns; bypassPermissions and
* confirmToolCalls mirror it. "full" is session-only. */
permissionMode: PermissionMode;
+ sandboxLevel: SandboxLevel;
/** Whether the bypass warning dialog is open. Lifted out of the composer menu so confirming
* it does not leave the menu frozen. */
bypassConfirmOpen: boolean;
@@ -2621,6 +2635,7 @@ type ChatRuntimeStore = {
setConfirmToolCalls: (enabled: boolean) => void;
setBypassPermissions: (enabled: boolean) => void;
setPermissionMode: (mode: PermissionMode) => void;
+ setSandboxLevel: (level: SandboxLevel) => void;
setBypassConfirmOpen: (open: boolean) => void;
allowToolAlways: (sessionId: string, toolName: string) => void;
setToolConfirmation: (
@@ -2731,6 +2746,7 @@ type ScalarSettingKey =
| "mcpEnabledForChat"
| "confirmToolCalls"
| "permissionMode"
+ | "sandboxLevel"
| "ragSource"
| "ragMode"
| "ragTopK"
@@ -2780,6 +2796,7 @@ const SCALAR_SETTING_KEYS = [
"mcpEnabledForChat",
"confirmToolCalls",
"permissionMode",
+ "sandboxLevel",
"ragSource",
"ragMode",
"ragTopK",
@@ -4135,6 +4152,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// confirmation gate, so it needs the warning dialog each session.
bypassPermissions: false,
permissionMode: INITIAL_PERMISSION_MODE,
+ sandboxLevel: loadSandboxLevel(),
bypassConfirmOpen: false,
alwaysAllowToolsBySession: new Map<string, Set<string>>(),
toolConfirmations: {},
@@ -5425,6 +5443,11 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
};
}),
+ setSandboxLevel: (sandboxLevel) =>
+ set((state) => {
+ saveString(CHAT_SANDBOX_LEVEL_KEY, sandboxLevel);
+ return { sandboxLevel, queuedSettingsEpoch: state.queuedSettingsEpoch + 1 };
+ }),
setPermissionMode: (permissionMode) =>
set((state) => {
// "full" is session-only (see init); ask/auto/off persist and keep the legacy confirm toggle in sync.
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 9b707c75b19..d556e10b061 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -706,6 +706,9 @@ export interface OpenAIChatCompletionsRequest {
* call, "auto" only on calls flagged unsafe, "off" never, "full" never and drops the
* sandbox. Unset behaves as "ask". */
permission_mode?: "ask" | "auto" | "off" | "full";
+ /** "high" (default) adds the OS sandbox when it works; "low" runs Python/Terminal on software
+ * safeguards only. Full access overrides both. */
+ sandbox_level?: "high" | "low";
/** Local models + enable_tools only. Full-access escape hatch. */
bypass_permissions?: boolean;
/** `kb_id` is exclusive; otherwise project and thread scopes may combine. */
diff --git a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts
index 8e87167db82..92436a39b33 100644
--- a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts
+++ b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts
@@ -28,6 +28,7 @@ const MIRRORED_BOOLEAN_KEYS = [
const MIRRORED_ENUM_VALUES = {
// "full" (Full access) is session-only and never persisted.
permissionMode: ["ask", "auto", "off"],
+ sandboxLevel: ["high", "low"],
ragMode: ["hybrid", "lexical", "dense"],
ragAutoInject: ["auto", "on", "off"],
speculativeType: ["auto", "ngram", "off"],
diff --git a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts
index c14e48ad5c5..0a26c30ca47 100644
--- a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts
+++ b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts
@@ -23,6 +23,7 @@ const QUEUED_SETTING_KEYS = [
"confirmToolCalls",
"bypassPermissions",
"permissionMode",
+ "sandboxLevel",
"webFetchToolsEnabled",
"deepResearchEnabled",
"researchWebsitePolicy",
diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsx
index 236759ec6a9..ff0ad521a5a 100644
--- a/studio/frontend/src/features/settings/settings-dialog.tsx
+++ b/studio/frontend/src/features/settings/settings-dialog.tsx
@@ -341,7 +341,7 @@ export function SettingsDialog() {
}
return visibleTabs.map((tab) => {
const tabLabel = t(tab.labelKey);
- const entries = renderedSearchEntries(SETTINGS_SEARCH_INDEX, tab.id, hubSource)
+ const entries = renderedSearchEntries(SETTINGS_SEARCH_INDEX, tab.id, hubSource, isOwner)
.filter((key) => {
if (t(key).toLowerCase().includes(q)) {
return true;
@@ -358,7 +358,7 @@ export function SettingsDialog() {
tabMatches: tabLabel.toLowerCase().includes(q),
};
}).filter((r) => r.tabMatches || r.entries.length > 0);
- }, [query, t, visibleTabs, hubSource]);
+ }, [query, t, visibleTabs, hubSource, isOwner]);
const [pendingScroll, setPendingScroll] = useState<{
tab: SettingsTab;
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index ba70c627a68..f77dcdd2b66 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -296,6 +296,8 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
],
// The Windows rows render only on Windows, so only the rows every platform shows are indexed.
sandbox: [
+ "settings.general.permissions.sectionTitle",
+ "settings.sandbox.levelLabel",
"settings.sandbox.toolsSection",
"settings.sandbox.python",
"settings.sandbox.terminal",
@@ -356,14 +358,24 @@ const HUGGING_FACE_ONLY_ENTRIES: ReadonlySet<TranslationKey> = new Set([
"settings.general.hub.datasetsServer",
]);
+// Rows of a tab every account sees that render only for the owner (the OS sandbox sections).
+const OWNER_ONLY_ENTRIES: ReadonlySet<TranslationKey> = new Set([
+ "settings.sandbox.toolsSection",
+ "settings.sandbox.python",
+ "settings.sandbox.terminal",
+]);
+
export function renderedSearchEntries(
index: Record<SettingsTab, TranslationKey[]>,
tab: SettingsTab,
hubSource: HubSource,
+ isOwner = true,
): TranslationKey[] {
- return hubSource === "modelscope"
- ? index[tab].filter((key) => !HUGGING_FACE_ONLY_ENTRIES.has(key))
- : index[tab];
+ return index[tab].filter(
+ (key) =>
+ !(hubSource === "modelscope" && HUGGING_FACE_ONLY_ENTRIES.has(key)) &&
+ (isOwner || !OWNER_ONLY_ENTRIES.has(key)),
+ );
}
/**
diff --git a/studio/frontend/src/features/settings/settings-tab-visibility.ts b/studio/frontend/src/features/settings/settings-tab-visibility.ts
index 06c857caf6f..ea603024d94 100644
--- a/studio/frontend/src/features/settings/settings-tab-visibility.ts
+++ b/studio/frontend/src/features/settings/settings-tab-visibility.ts
@@ -4,13 +4,13 @@
import type { SettingsTab } from "./stores/settings-dialog-store";
// Tabs whose every backing route is owner-only (installation-wide settings), so a managed account
-// would only see controls that fail with 403.
+// would only see controls that fail with 403. Sandbox is not one: its Permissions section is per
+// account, and only the OS sandbox sections below it are owner-only (SandboxTab skips them).
export const OWNER_ONLY_SETTINGS_TABS: ReadonlySet<SettingsTab> = new Set<SettingsTab>([
"accounts",
"resources",
"remote-lan",
"agents",
- "sandbox",
"debugging",
]);
diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
index 447cabf193c..4752547240e 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -37,9 +37,11 @@ export type SettingsScrollTarget =
| "chat-composer"
| "browser-html-network"
| "general-hub"
+ /** Old name of sandbox-permissions, from when Permissions lived in General. */
| "general-permissions"
| "library-storage"
- | "resources-caches";
+ | "resources-caches"
+ | "sandbox-permissions";
/** Which archive the Data tab should open straight into. */
export type ArchivedShelf = "chats" | "images" | "videos" | "audio";
@@ -140,11 +142,23 @@ const SCROLL_TARGET_TAB: Record<SettingsScrollTarget, SettingsTab> = {
"appearance-sidebar-nav": "appearance",
"browser-html-network": "browser",
"general-hub": "general",
- "general-permissions": "general",
+ "general-permissions": "sandbox",
"library-storage": "library",
"resources-caches": "resources",
+ "sandbox-permissions": "sandbox",
};
+/** Permissions moved from General to the top of Sandbox; an old link still lands there. */
+export function resolveScrollRequest(
+ tab: SettingsTab | undefined,
+ target: SettingsScrollTarget | undefined,
+): { tab: SettingsTab | undefined; target: SettingsScrollTarget | undefined } {
+ if (target === "general-permissions" || target === "sandbox-permissions") {
+ return { tab: "sandbox", target: "sandbox-permissions" };
+ }
+ return { tab, target };
+}
+
/**
* The unconsumed deep-link requests that outlive a navigation landing on `tab`.
*
@@ -193,15 +207,16 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
logSourcePathRequested: null,
logRequestSeq: 0,
connectionRequested: null,
- openDialog: (tab, options) =>
+ openDialog: (requestedTab, options) =>
set((state) => {
+ const { tab, target } = resolveScrollRequest(requestedTab, options?.scrollTarget);
const next = tab ?? state.activeTab;
const pending = requestsFor(state, next);
return {
open: true,
activeTab: next,
// A caller that names a target replaces whatever was still pending.
- scrollTarget: options?.scrollTarget ?? pending.scrollTarget,
+ scrollTarget: target ?? pending.scrollTarget,
archivedRequested: pending.archivedRequested,
logFamilyRequested: pending.logFamilyRequested,
logSourcePathRequested: pending.logSourcePathRequested,
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index a6a18b3af2a..3226dea8e6c 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -12,11 +12,7 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
-import {
- PermissionModeDropdown,
- useActivePermissionMode,
- useChatRuntimeStore,
-} from "@/features/chat";
+import { useChatRuntimeStore } from "@/features/chat";
// From the keys module, not the barrel or the store: both are in an import cycle with this file,
// so the key was still in its temporal dead zone when the module-scope list below read it, killing
// the module graph. The keys module imports nothing, so it is always evaluated first.
@@ -88,7 +84,6 @@ import { useDesktopBooleanSetting } from "../hooks/use-desktop-boolean-setting";
import { KEYBOARD_SHORTCUTS_STORAGE_KEY } from "../stores/keyboard-shortcuts-store";
import { INTERFACE_SCALE_STORAGE_KEY } from "../stores/interface-scale-store";
import { SETTINGS_PANEL_PREFS_STORAGE_KEY } from "../stores/settings-panel-prefs-store";
-import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import { CHAT_PROJECT_ATTACHMENT_TARGET_KEY } from "@/features/chat/utils/project-attachment-target";
// Keys cleared by "Reset all local preferences". NEVER include auth/session keys here -- that
@@ -123,6 +118,7 @@ const PREFS_KEYS: string[] = [
CHAT_PROJECT_ATTACHMENT_TARGET_KEY,
"unsloth_chat_auto_title",
"unsloth_chat_permission_mode",
+ "unsloth_chat_sandbox_level",
// Legacy confirm key: loadPermissionMode falls back to it, so clear both or a reset restores it.
"unsloth_chat_confirm_tool_calls",
"unsloth_hf_token",
@@ -197,20 +193,6 @@ function resetAllPrefs() {
export function GeneralTab() {
const isOwner = useIsAccountOwner();
const t = useT();
- const permissionsRef = useRef<HTMLElement | null>(null);
- const activePermission = useActivePermissionMode();
- const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
- const consumeScrollTarget = useSettingsDialogStore((s) => s.consumeScrollTarget);
-
- // Learn more in the permission menus.
- useEffect(() => {
- if (scrollTarget !== "general-permissions") return;
- const frame = window.requestAnimationFrame(() => {
- permissionsRef.current?.scrollIntoView({ block: "start", behavior: "smooth" });
- consumeScrollTarget("general-permissions");
- });
- return () => window.cancelAnimationFrame(frame);
- }, [consumeScrollTarget, scrollTarget]);
const hfToken = useChatRuntimeStore((s) => s.hfToken);
const setHfToken = useChatRuntimeStore((s) => s.setHfToken);
@@ -564,19 +546,6 @@ export function GeneralTab() {
</SettingsRow>
</SettingsSection>
- <SettingsSection
- ref={permissionsRef}
- title={t("settings.general.permissions.sectionTitle")}
- >
- {/* The selected level, explained in full. */}
- <SettingsRow
- label={t(`settings.general.permissions.names.${activePermission.value}`)}
- description={t(`settings.general.permissions.details.${activePermission.value}`)}
- >
- <PermissionModeDropdown learnMore={false} />
- </SettingsRow>
- </SettingsSection>
-
{isTauri ? (
<SettingsSection title={t("settings.general.startup.sectionTitle")}>
<SettingsRow
diff --git a/studio/frontend/src/features/settings/tabs/sandbox-tab.tsx b/studio/frontend/src/features/settings/tabs/sandbox-tab.tsx
index bf531c297b8..be64adb6de9 100644
--- a/studio/frontend/src/features/settings/tabs/sandbox-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/sandbox-tab.tsx
@@ -5,18 +5,26 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
+import { useIsAccountOwner } from "@/features/auth";
import {
+ PermissionModeDropdown,
+ SandboxSetupDialog,
type SandboxSetupJob,
type SandboxSetupOperation,
forgetSandboxCapability,
loadSandboxSetup,
+ pickSandboxLevel,
+ sandboxSwitchState,
startSandboxSetup,
+ useActivePermissionMode,
+ useChatRuntimeStore,
+ useSandboxCapability,
} from "@/features/chat";
import { type TranslationKey, useT } from "@/i18n";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { RefreshIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useId, useRef, useState } from "react";
import { toast } from "sonner";
import {
type HostPrepJob,
@@ -31,6 +39,7 @@ import {
import { isSettingsRouteAbsent } from "../api/settings-route-absent";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
import {
HOST_PREP_POLL_MS,
type HostPrepStatus,
@@ -97,7 +106,116 @@ function ToolRow({
);
}
+/** Per account, so every account sees it; the OS sandbox sections below are the owner's. */
+function PermissionsSection() {
+ const t = useT();
+ const permissionsRef = useRef<HTMLElement | null>(null);
+ const activePermission = useActivePermissionMode();
+ const sandboxLevel = useChatRuntimeStore((s) => s.sandboxLevel);
+ const setSandboxLevel = useChatRuntimeStore((s) => s.setSandboxLevel);
+ const capability = useSandboxCapability(sandboxLevel === "high");
+ const { checked, disabled } = sandboxSwitchState(
+ sandboxLevel,
+ activePermission.value,
+ capability,
+ );
+ const [setupOpen, setSetupOpen] = useState(false);
+ const levelDescriptionId = useId();
+ const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
+ const consumeScrollTarget = useSettingsDialogStore((s) => s.consumeScrollTarget);
+
+ useEffect(() => {
+ if (scrollTarget !== "sandbox-permissions") return;
+ const frame = window.requestAnimationFrame(() => {
+ permissionsRef.current?.scrollIntoView({ block: "start", behavior: "smooth" });
+ consumeScrollTarget("sandbox-permissions");
+ });
+ return () => window.cancelAnimationFrame(frame);
+ }, [consumeScrollTarget, scrollTarget]);
+
+ const levelDescription = disabled
+ ? t("settings.sandbox.levelFullAccessNote")
+ : checked
+ ? t("settings.sandbox.levelHighDescription")
+ : t("settings.sandbox.levelLowDescription");
+
+ return (
+ <SettingsSection
+ ref={permissionsRef}
+ title={t("settings.general.permissions.sectionTitle")}
+ description={t("settings.sandbox.permissionsIntro")}
+ >
+ {/* The selected level, explained in full. */}
+ <SettingsRow
+ label={t(`settings.general.permissions.names.${activePermission.value}`)}
+ description={t(`settings.general.permissions.details.${activePermission.value}`)}
+ >
+ <PermissionModeDropdown sandboxControls={false} />
+ </SettingsRow>
+ <SettingsRow
+ label={t("settings.sandbox.levelLabel")}
+ description={<span id={levelDescriptionId}>{levelDescription}</span>}
+ >
+ <span className="flex items-center gap-2">
+ <span className="text-xs text-muted-foreground">
+ {checked ? t("settings.sandbox.levelHigh") : t("settings.sandbox.levelLow")}
+ </span>
+ <Switch
+ checked={checked}
+ disabled={disabled}
+ aria-label={t("settings.sandbox.levelLabel")}
+ aria-describedby={levelDescriptionId}
+ onCheckedChange={(next) =>
+ void pickSandboxLevel(next ? "high" : "low", setSandboxLevel, () =>
+ setSetupOpen(true),
+ )
+ }
+ />
+ </span>
+ </SettingsRow>
+ {/* Its own instance: the chat-page root dialog is not mounted on every page. */}
+ <SandboxSetupDialog
+ open={setupOpen}
+ onOpenChange={setSetupOpen}
+ onLearnMore={() =>
+ permissionsRef.current?.scrollIntoView({ block: "start", behavior: "smooth" })
+ }
+ />
+ </SettingsSection>
+ );
+}
+
export function SandboxTab() {
+ const t = useT();
+ const isOwner = useIsAccountOwner();
+ return (
+ <div className="settings-page">
+ <header className="flex min-w-0 flex-col gap-1">
+ <h1
+ data-settings-label={t("settings.sandbox.title")}
+ className="text-xl font-semibold font-heading"
+ >
+ {t("settings.sandbox.title")}
+ </h1>
+ <p
+ data-settings-label={t("settings.sandbox.description")}
+ className="text-xs text-muted-foreground"
+ >
+ {t("settings.sandbox.description")}
+ </p>
+ </header>
+ <PermissionsSection />
+ {/* Not mounted for managed accounts, so none of the owner-only sandbox routes are called. */}
+ {isOwner ? (
+ <OsSandboxSections />
+ ) : (
+ <p className="text-xs text-muted-foreground">{t("settings.sandbox.managedNote")}</p>
+ )}
+ </div>
+ );
+}
+
+function OsSandboxSections() {
const t = useT();
const [status, setStatus] = useState<SandboxStatus | null>(null);
const [job, setJob] = useState<HostPrepJob | null>(null);
@@ -332,22 +450,7 @@ export function SandboxTab() {
const setupRunning = setupJob?.state === "running";
return (
- <div className="settings-page">
- <header className="flex min-w-0 flex-col gap-1">
- <h1
- data-settings-label={t("settings.sandbox.title")}
- className="text-xl font-semibold font-heading"
- >
- {t("settings.sandbox.title")}
- </h1>
- <p
- data-settings-label={t("settings.sandbox.description")}
- className="text-xs text-muted-foreground"
- >
- {t("settings.sandbox.description")}
- </p>
- </header>
-
+ <>
{absent ? (
<p className="text-sm text-muted-foreground">
{t("settings.sandbox.unsupported")}
@@ -647,6 +750,6 @@ export function SandboxTab() {
) : null}
</>
)}
- </div>
+ </>
);
}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 1d6f0fdec1e..ff300e56c29 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -298,23 +298,20 @@ export const ar = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "وضع حماية نظام التشغيل غير متاح",
- title: "لا يوجد وضع حماية لنظام التشغيل على هذا الكمبيوتر بعد",
- description: "يُبقي التشغيل تلقائيًا Python والطرفية داخل وضع حماية نظام التشغيل. إلى أن يعمل هنا، تطلب استدعاءاتهما الخطرة الموافقة أولًا.",
+ levelTitle: "وضع حماية نظام التشغيل غير متاح",
+ levelDescription: "ثبّته لاستخدام عالٍ، أو ابقَ على منخفض (حماية برمجية).",
+ useLow: "استخدام وضع الحماية المنخفض",
checking: "جارٍ فحص وضع الحماية على هذا الكمبيوتر…",
install: "تثبيت وضع الحماية",
windowsSetup: "إعداد وضع حماية Windows",
copyCommand: "نسخ الأمر",
copied: "تم نسخ الأمر",
copyFailed: "تعذّر نسخ الأمر",
- commandHint: "أو شغّل هذا على الكمبيوتر الذي يشغّل Unsloth، ثم اختر الوضع مجددًا:",
+ copiedRunIt: "تم نسخ الأمر. شغّله في طرفية على الكمبيوتر الذي يشغّل Unsloth، ثم بدّل إلى عالٍ.",
ownerOnly: "لا يمكن تثبيته إلا للمالك، من الكمبيوتر الذي يشغّل Unsloth.",
- runInTerminal: "لا يستطيع Unsloth طلب كلمة المرور هنا. شغّل هذا في طرفية على الكمبيوتر الذي يشغّل Unsloth، ثم اختر الوضع مرة أخرى:",
- useAnyway: "استخدامه على أي حال (ستطلب الاستدعاءات الخطرة الموافقة)",
- cancel: "إلغاء",
- close: "إغلاق",
+ windowsNote: "يحتاج إلى خطوة مسؤول بعد كل إعادة تشغيل. MXC معاينة وليس حدًا أمنيًا.",
running: "جارٍ الإعداد. وافق على طلب كلمة المرور أو المسؤول على الكمبيوتر الذي يشغّل Unsloth…",
- succeeded: "وضع حماية نظام التشغيل جاهز. تم تفعيل التشغيل تلقائيًا.",
+ succeeded: "وضع حماية نظام التشغيل جاهز. تم تفعيل المستوى العالي.",
stillUnavailable: "اكتمل الإعداد، لكن وضع حماية نظام التشغيل لا يجتاز الفحص بعد.",
declined: "تم رفض طلب كلمة المرور أو المسؤول.",
failed: "فشل الإعداد.",
@@ -1129,6 +1126,18 @@ export const ar = {
installRuntimeError: "تعذر بدء تثبيت بيئة التشغيل.",
unsupportedArch: "يعمل وضع حماية Windows (MXC) على Windows x64 فقط، لذا فهو غير متاح على هذا الكمبيوتر.",
unsupportedBuild: "يتطلب وضع حماية Windows (MXC) إصدار Windows 11 24H2 (البنية 26100) أو أحدث، لذا فهو غير متاح على هذا الكمبيوتر.",
+ permissionsIntro: "اختر متى تسأل الأدوات أولاً، وما إذا كان Python والطرفية يعملان أيضاً داخل وضع حماية نظام التشغيل.",
+ levelLabel: "وضع الحماية",
+ levelHigh: "عالٍ",
+ levelLow: "منخفض",
+ levelHighShort: "حماية على مستوى النظام",
+ levelLowShort: "حماية برمجية",
+ levelHelp: "منخفض: حماية برمجية. عالٍ: حماية على مستوى النظام. اعرف المزيد في الإعدادات > وضع الحماية.",
+ levelHighDescription: "عالٍ: حماية على مستوى النظام. يعمل Python والطرفية داخل وضع حماية نظام التشغيل (bubblewrap أو Seatbelt أو MXC) إضافة إلى الضمانات البرمجية. من دون وضع حماية يعمل، تسأل الاستدعاءات الخطرة أولاً.",
+ levelLowDescription: "منخفض: حماية برمجية. يعمل Python والطرفية بالضمانات البرمجية فقط، خارج وضع حماية نظام التشغيل. تسأل الاستدعاءات الخطرة أولاً ما لم تختر الوصول الكامل.",
+ levelFullAccessNote: "الوصول الكامل يوقف وضع الحماية. يُطبَّق هذا الإعداد مجدداً عند اختيار مستوى آخر.",
+ learnMore: "مزيد من المعلومات",
+ managedNote: "يُعدّ مالك خادم Unsloth هذا وضع حماية نظام التشغيل.",
},
debugging: {
logSection: "ملف السجل",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index c4a8b2a86f4..ef319870e27 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -298,23 +298,20 @@ export const de = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "OS-Sandbox nicht verfügbar",
- title: "Noch keine OS-Sandbox auf diesem Computer",
- description: "Automatisch ausführen hält Python und Terminal in der OS-Sandbox. Bis sie hier funktioniert, fragen deren riskante Aufrufe zuerst nach.",
+ levelTitle: "OS-Sandbox ist nicht verfügbar",
+ levelDescription: "Installiere sie, um Hoch zu nutzen, oder bleib bei Niedrig (Software-Sandbox).",
+ useLow: "Sandbox Niedrig verwenden",
checking: "Sandbox auf diesem Computer wird geprüft…",
install: "Sandbox installieren",
windowsSetup: "Windows-Sandbox einrichten",
copyCommand: "Befehl kopieren",
copied: "Befehl kopiert",
copyFailed: "Der Befehl konnte nicht kopiert werden",
- commandHint: "Oder führe dies auf dem Computer aus, auf dem Unsloth läuft, und wähle den Modus dann erneut:",
+ copiedRunIt: "Befehl kopiert. Führe ihn in einem Terminal auf dem Computer aus, auf dem Unsloth läuft, und schalte dann auf Hoch.",
ownerOnly: "Nur der Besitzer kann sie installieren, und zwar an dem Computer, auf dem Unsloth läuft.",
- runInTerminal: "Unsloth kann hier nicht nach deinem Passwort fragen. Führe das in einem Terminal auf dem Computer aus, auf dem Unsloth läuft, und wähle den Modus dann erneut:",
- useAnyway: "Trotzdem verwenden (riskante Aufrufe fragen nach)",
- cancel: "Abbrechen",
- close: "Schließen",
+ windowsNote: "Braucht nach jedem Neustart einen Administratorschritt. MXC ist eine Vorschau, keine Sicherheitsgrenze.",
running: "Wird eingerichtet. Bestätige die Passwort- oder Administratorabfrage auf dem Computer, auf dem Unsloth läuft…",
- succeeded: "Die OS-Sandbox ist bereit. Automatisch ausführen ist aktiv.",
+ succeeded: "Die OS-Sandbox ist bereit. Sandbox Hoch ist aktiv.",
stillUnavailable: "Die Einrichtung ist abgeschlossen, aber die OS-Sandbox besteht ihre Prüfung noch nicht.",
declined: "Die Passwort- oder Administratorabfrage wurde abgelehnt.",
failed: "Die Einrichtung ist fehlgeschlagen.",
@@ -1133,6 +1130,18 @@ export const de = {
installRuntimeError: "Die Installation der Laufzeit konnte nicht gestartet werden.",
unsupportedArch: "Die Windows-Sandbox (MXC) läuft nur unter x64-Windows und ist auf diesem PC daher nicht verfügbar.",
unsupportedBuild: "Die Windows-Sandbox (MXC) braucht Windows 11 24H2 (Build 26100) oder neuer und ist auf diesem PC daher nicht verfügbar.",
+ permissionsIntro: "Lege fest, wann Tools zuerst fragen und ob Python und Terminal zusätzlich in der OS-Sandbox laufen.",
+ levelLabel: "Sandbox",
+ levelHigh: "Hoch",
+ levelLow: "Niedrig",
+ levelHighShort: "OS-Sandboxing",
+ levelLowShort: "Software-Sandboxing",
+ levelHelp: "Niedrig: Software-Sandboxing. Hoch: OS-Sandboxing. Mehr dazu unter Einstellungen > Sandbox.",
+ levelHighDescription: "Hoch: OS-Sandboxing. Python und Terminal laufen zusätzlich zu den Software-Schutzmaßnahmen in der OS-Sandbox (bubblewrap, Seatbelt oder MXC). Ohne funktionierende OS-Sandbox fragen riskante Aufrufe zuerst.",
+ levelLowDescription: "Niedrig: Software-Sandboxing. Python und Terminal laufen nur mit den Software-Schutzmaßnahmen, außerhalb der OS-Sandbox. Riskante Aufrufe fragen zuerst, außer bei Vollzugriff.",
+ levelFullAccessNote: "Vollzugriff schaltet die Sandbox aus. Diese Einstellung gilt wieder, sobald du eine andere Stufe wählst.",
+ learnMore: "Weitere Informationen",
+ managedNote: "Der Besitzer dieses Unsloth-Servers richtet die OS-Sandbox ein.",
},
debugging: {
logSection: "Protokolldatei",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 3aa8316979d..96b99460228 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -334,23 +334,20 @@ export const en = {
scope: "Text and image chat on NVIDIA GPUs. First load may take longer.",
},
sandboxSetup: {
- unavailable: "OS sandbox not available",
- title: "No OS sandbox on this computer yet",
- description: "Run automatically keeps Python and Terminal in the OS sandbox. Until it works here, their risky calls ask first.",
+ levelTitle: "OS sandbox is not available",
+ levelDescription: "Install it to use High, or keep Low (software sandboxing).",
+ useLow: "Use Low sandbox",
checking: "Checking the sandbox on this computer…",
install: "Install sandbox",
windowsSetup: "Set up Windows sandbox",
copyCommand: "Copy command",
copied: "Command copied",
copyFailed: "Could not copy the command",
- commandHint: "Or run this on the computer running Unsloth, then pick the mode again:",
+ copiedRunIt: "Command copied. Run it in a terminal on the computer running Unsloth, then switch to High.",
ownerOnly: "Only the owner can install it, from the computer running Unsloth.",
- runInTerminal: "Unsloth cannot ask for your password here. Run this in a terminal on the computer running Unsloth, then pick the mode again:",
- useAnyway: "Use it anyway (risky calls will ask)",
- cancel: "Cancel",
- close: "Close",
+ windowsNote: "Needs an administrator step after each restart. MXC is a preview, not a security boundary.",
running: "Setting up. Approve the password or administrator prompt on the computer running Unsloth…",
- succeeded: "The OS sandbox is ready. Run automatically is on.",
+ succeeded: "The OS sandbox is ready. Sandbox High is on.",
stillUnavailable: "Setup finished, but the OS sandbox still does not pass its check.",
declined: "The password or administrator prompt was declined.",
failed: "Setup failed.",
@@ -1175,6 +1172,18 @@ export const en = {
installRuntimeError: "Could not start the runtime install.",
unsupportedArch: "The Windows sandbox (MXC) only runs on x64 Windows, so it is not available on this PC.",
unsupportedBuild: "The Windows sandbox (MXC) needs Windows 11 24H2 (build 26100) or newer, so it is not available on this PC.",
+ permissionsIntro: "Choose when tools ask first, and whether Python and Terminal also run inside the OS sandbox.",
+ levelLabel: "Sandbox",
+ levelHigh: "High",
+ levelLow: "Low",
+ levelHighShort: "OS sandboxing",
+ levelLowShort: "Software sandboxing",
+ levelHelp: "Low: software sandboxing. High: OS sandboxing. Learn more in Settings > Sandbox.",
+ levelHighDescription: "High: OS sandboxing. Python and Terminal run inside the OS sandbox (bubblewrap, Seatbelt or MXC) on top of software sandboxing. Without a working OS sandbox, risky calls ask first.",
+ levelLowDescription: "Low: software sandboxing. Python and Terminal run with software sandboxing only, outside the OS sandbox. Risky calls ask first unless you chose Full access.",
+ levelFullAccessNote: "Full access turns the sandbox off. This setting applies again when you pick another level.",
+ learnMore: "Learn more",
+ managedNote: "The owner of this Unsloth server sets up the OS sandbox.",
},
debugging: {
logSection: "Log file",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 5385e3a03d7..a1cd40b78ef 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -298,23 +298,20 @@ export const es = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "Sandbox del sistema no disponible",
- title: "Todavía no hay sandbox del sistema en este equipo",
- description: "Ejecutar automáticamente mantiene Python y Terminal en el sandbox del sistema. Hasta que funcione aquí, sus llamadas arriesgadas preguntan primero.",
+ levelTitle: "El sandbox del sistema no está disponible",
+ levelDescription: "Instálalo para usar Alto o quédate en Bajo (sandbox de software).",
+ useLow: "Usar sandbox Bajo",
checking: "Comprobando el sandbox de este equipo…",
install: "Instalar sandbox",
windowsSetup: "Configurar el sandbox de Windows",
copyCommand: "Copiar comando",
copied: "Comando copiado",
copyFailed: "No se pudo copiar el comando",
- commandHint: "O ejecuta esto en el equipo donde se ejecuta Unsloth y vuelve a elegir el modo:",
+ copiedRunIt: "Comando copiado. Ejecútalo en una terminal del equipo donde se ejecuta Unsloth y cambia a Alto.",
ownerOnly: "Solo el propietario puede instalarlo, desde el equipo donde se ejecuta Unsloth.",
- runInTerminal: "Unsloth no puede pedir tu contraseña aquí. Ejecuta esto en una terminal del equipo donde se ejecuta Unsloth y vuelve a elegir el modo:",
- useAnyway: "Usarlo de todos modos (las llamadas arriesgadas preguntarán)",
- cancel: "Cancelar",
- close: "Cerrar",
+ windowsNote: "Necesita un paso de administrador tras cada reinicio. MXC es una vista previa, no un límite de seguridad.",
running: "Configurando. Aprueba la solicitud de contraseña o de administrador en el equipo donde se ejecuta Unsloth…",
- succeeded: "El sandbox del sistema está listo. Ejecutar automáticamente está activado.",
+ succeeded: "El sandbox del sistema está listo. Sandbox Alto está activado.",
stillUnavailable: "La configuración terminó, pero el sandbox del sistema todavía no supera su comprobación.",
declined: "Se rechazó la solicitud de contraseña o de administrador.",
failed: "La configuración falló.",
@@ -1132,6 +1129,18 @@ export const es = {
installRuntimeError: "No se pudo iniciar la instalación del runtime.",
unsupportedArch: "El sandbox de Windows (MXC) solo funciona en Windows x64, así que no está disponible en este PC.",
unsupportedBuild: "El sandbox de Windows (MXC) necesita Windows 11 24H2 (compilación 26100) o posterior, así que no está disponible en este PC.",
+ permissionsIntro: "Elige cuándo preguntan primero las herramientas y si Python y Terminal también se ejecutan en el sandbox del sistema.",
+ levelLabel: "Sandbox",
+ levelHigh: "Alto",
+ levelLow: "Bajo",
+ levelHighShort: "Sandbox del sistema",
+ levelLowShort: "Sandbox de software",
+ levelHelp: "Bajo: sandbox de software. Alto: sandbox del sistema. Más información en Ajustes > Sandbox.",
+ levelHighDescription: "Alto: sandbox del sistema. Python y Terminal se ejecutan en el sandbox del sistema (bubblewrap, Seatbelt o MXC) además de las protecciones de software. Sin un sandbox del sistema que funcione, las llamadas arriesgadas preguntan primero.",
+ levelLowDescription: "Bajo: sandbox de software. Python y Terminal se ejecutan solo con las protecciones de software, fuera del sandbox del sistema. Las llamadas arriesgadas preguntan primero, salvo con Acceso total.",
+ levelFullAccessNote: "Acceso total desactiva el sandbox. Este ajuste vuelve a aplicarse cuando elijas otro nivel.",
+ learnMore: "Más información",
+ managedNote: "El propietario de este servidor de Unsloth configura el sandbox del sistema.",
},
debugging: {
logSection: "Archivo de registro",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 0f6d712b05a..2152f7f0176 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -298,23 +298,20 @@ export const fr = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "Bac à sable du système indisponible",
- title: "Pas encore de bac à sable système sur cet ordinateur",
- description: "Exécuter automatiquement garde Python et le terminal dans le bac à sable du système. Tant qu'il ne fonctionne pas ici, leurs appels risqués demandent d'abord.",
+ levelTitle: "Le bac à sable du système n'est pas disponible",
+ levelDescription: "Installez-le pour utiliser Élevé, ou restez sur Faible (bac à sable logiciel).",
+ useLow: "Utiliser le bac à sable Faible",
checking: "Vérification du bac à sable de cet ordinateur…",
install: "Installer le bac à sable",
windowsSetup: "Configurer le bac à sable Windows",
copyCommand: "Copier la commande",
copied: "Commande copiée",
copyFailed: "Impossible de copier la commande",
- commandHint: "Ou exécutez ceci sur l'ordinateur qui fait tourner Unsloth, puis choisissez à nouveau le mode :",
+ copiedRunIt: "Commande copiée. Exécutez-la dans un terminal sur l'ordinateur qui fait tourner Unsloth, puis passez sur Élevé.",
ownerOnly: "Seul le propriétaire peut l'installer, depuis l'ordinateur qui fait tourner Unsloth.",
- runInTerminal: "Unsloth ne peut pas demander votre mot de passe ici. Exécutez ceci dans un terminal sur l'ordinateur qui fait tourner Unsloth, puis choisissez à nouveau le mode :",
- useAnyway: "L'utiliser quand même (les appels risqués demanderont)",
- cancel: "Annuler",
- close: "Fermer",
+ windowsNote: "Demande une étape administrateur après chaque redémarrage. MXC est une préversion, pas une frontière de sécurité.",
running: "Configuration en cours. Approuvez la demande de mot de passe ou d'administrateur sur l'ordinateur qui fait tourner Unsloth…",
- succeeded: "Le bac à sable du système est prêt. Exécuter automatiquement est activé.",
+ succeeded: "Le bac à sable du système est prêt. Sandbox Élevé est activé.",
stillUnavailable: "La configuration est terminée, mais le bac à sable du système ne réussit toujours pas sa vérification.",
declined: "La demande de mot de passe ou d'administrateur a été refusée.",
failed: "La configuration a échoué.",
@@ -1133,6 +1130,18 @@ export const fr = {
installRuntimeError: "Impossible de lancer l'installation du runtime.",
unsupportedArch: "Le bac à sable Windows (MXC) ne fonctionne que sous Windows x64, il n'est donc pas disponible sur ce PC.",
unsupportedBuild: "Le bac à sable Windows (MXC) nécessite Windows 11 24H2 (build 26100) ou plus récent, il n'est donc pas disponible sur ce PC.",
+ permissionsIntro: "Choisissez quand les outils demandent d'abord, et si Python et le Terminal s'exécutent aussi dans le bac à sable du système.",
+ levelLabel: "Sandbox",
+ levelHigh: "Élevé",
+ levelLow: "Faible",
+ levelHighShort: "Bac à sable du système",
+ levelLowShort: "Bac à sable logiciel",
+ levelHelp: "Faible : bac à sable logiciel. Élevé : bac à sable du système. En savoir plus dans Paramètres > Sandbox.",
+ levelHighDescription: "Élevé : bac à sable du système. Python et le Terminal s'exécutent dans le bac à sable du système (bubblewrap, Seatbelt ou MXC) en plus des protections logicielles. Sans bac à sable du système fonctionnel, les appels risqués demandent d'abord.",
+ levelLowDescription: "Faible : bac à sable logiciel. Python et le Terminal s'exécutent avec les seules protections logicielles, hors du bac à sable du système. Les appels risqués demandent d'abord, sauf en Accès complet.",
+ levelFullAccessNote: "L'Accès complet désactive le bac à sable. Ce réglage s'applique de nouveau quand vous choisissez un autre niveau.",
+ learnMore: "En savoir plus",
+ managedNote: "Le propriétaire de ce serveur Unsloth configure le bac à sable du système.",
},
debugging: {
logSection: "Fichier journal",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index ecbbf490384..31a9db33716 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -298,23 +298,20 @@ export const hi = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "OS सैंडबॉक्स उपलब्ध नहीं है",
- title: "इस कंप्यूटर पर अभी कोई OS सैंडबॉक्स नहीं है",
- description: "अपने आप चलाएं Python और टर्मिनल को OS सैंडबॉक्स में रखता है। जब तक यह यहाँ काम नहीं करता, उनकी जोखिम भरी कॉल पहले पूछती हैं।",
+ levelTitle: "OS सैंडबॉक्स उपलब्ध नहीं है",
+ levelDescription: "उच्च का उपयोग करने के लिए इसे इंस्टॉल करें, या निम्न (सॉफ़्टवेयर सैंडबॉक्स) पर रहें।",
+ useLow: "निम्न सैंडबॉक्स इस्तेमाल करें",
checking: "इस कंप्यूटर का सैंडबॉक्स जाँचा जा रहा है…",
install: "सैंडबॉक्स इंस्टॉल करें",
windowsSetup: "Windows सैंडबॉक्स सेट अप करें",
copyCommand: "कमांड कॉपी करें",
copied: "कमांड कॉपी हो गया",
copyFailed: "कमांड कॉपी नहीं हो सका",
- commandHint: "या Unsloth चला रहे कंप्यूटर पर यह चलाएँ, फिर मोड दोबारा चुनें:",
+ copiedRunIt: "कमांड कॉपी हो गया। इसे Unsloth चला रहे कंप्यूटर के टर्मिनल में चलाएँ, फिर उच्च पर स्विच करें।",
ownerOnly: "इसे सिर्फ़ मालिक ही Unsloth चला रहे कंप्यूटर से इंस्टॉल कर सकता है।",
- runInTerminal: "Unsloth यहाँ आपका पासवर्ड नहीं माँग सकता। Unsloth चला रहे कंप्यूटर के टर्मिनल में इसे चलाएँ, फिर मोड दोबारा चुनें:",
- useAnyway: "फिर भी इस्तेमाल करें (जोखिम भरी कॉल के लिए पूछा जाएगा)",
- cancel: "रद्द करें",
- close: "बंद करें",
+ windowsNote: "हर रीस्टार्ट के बाद एक एडमिनिस्ट्रेटर चरण चाहिए। MXC अभी प्रीव्यू है, सुरक्षा सीमा नहीं।",
running: "सेट अप हो रहा है। Unsloth चला रहे कंप्यूटर पर पासवर्ड या एडमिनिस्ट्रेटर संकेत को मंज़ूरी दें…",
- succeeded: "OS सैंडबॉक्स तैयार है। अपने आप चलाएं चालू है।",
+ succeeded: "OS सैंडबॉक्स तैयार है। सैंडबॉक्स उच्च चालू है।",
stillUnavailable: "सेटअप पूरा हो गया, लेकिन OS सैंडबॉक्स अभी भी अपनी जाँच में पास नहीं हुआ।",
declined: "पासवर्ड या एडमिनिस्ट्रेटर संकेत अस्वीकार कर दिया गया।",
failed: "सेटअप विफल रहा।",
@@ -1132,6 +1129,18 @@ export const hi = {
installRuntimeError: "रनटाइम इंस्टॉल शुरू नहीं हो सका।",
unsupportedArch: "Windows सैंडबॉक्स (MXC) केवल x64 Windows पर चलता है, इसलिए यह इस PC पर उपलब्ध नहीं है।",
unsupportedBuild: "Windows सैंडबॉक्स (MXC) के लिए Windows 11 24H2 (बिल्ड 26100) या नया चाहिए, इसलिए यह इस PC पर उपलब्ध नहीं है।",
+ permissionsIntro: "चुनें कि टूल कब पहले पूछें, और क्या Python और टर्मिनल OS सैंडबॉक्स के अंदर भी चलें।",
+ levelLabel: "सैंडबॉक्स",
+ levelHigh: "उच्च",
+ levelLow: "निम्न",
+ levelHighShort: "OS सैंडबॉक्सिंग",
+ levelLowShort: "सॉफ़्टवेयर सैंडबॉक्सिंग",
+ levelHelp: "निम्न: सॉफ़्टवेयर सैंडबॉक्सिंग। उच्च: OS सैंडबॉक्सिंग। ज़्यादा जानकारी सेटिंग्स > सैंडबॉक्स में।",
+ levelHighDescription: "उच्च: OS सैंडबॉक्सिंग। Python और टर्मिनल सॉफ़्टवेयर सुरक्षा के साथ OS सैंडबॉक्स (bubblewrap, Seatbelt या MXC) के अंदर चलते हैं। काम करने वाले OS सैंडबॉक्स के बिना, जोखिम भरे कॉल पहले पूछते हैं।",
+ levelLowDescription: "निम्न: सॉफ़्टवेयर सैंडबॉक्सिंग। Python और टर्मिनल केवल सॉफ़्टवेयर सुरक्षा के साथ, OS सैंडबॉक्स के बाहर चलते हैं। पूरी पहुंच को छोड़कर, जोखिम भरे कॉल पहले पूछते हैं।",
+ levelFullAccessNote: "पूरी पहुंच सैंडबॉक्स बंद कर देता है। दूसरा स्तर चुनने पर यह सेटिंग फिर से लागू होती है।",
+ learnMore: "और जानें",
+ managedNote: "OS सैंडबॉक्स इस Unsloth सर्वर का स्वामी सेट अप करता है।",
},
debugging: {
logSection: "लॉग फ़ाइल",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 165ef23cd77..50abba27bdf 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -297,23 +297,20 @@ export const it = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "Sandbox del sistema non disponibile",
- title: "Nessuna sandbox del sistema su questo computer",
- description: "Esegui automaticamente tiene Python e Terminale nella sandbox del sistema. Finché qui non funziona, le loro chiamate rischiose chiedono prima.",
+ levelTitle: "La sandbox del sistema non è disponibile",
+ levelDescription: "Installala per usare Alto, oppure resta su Basso (sandbox software).",
+ useLow: "Usa la sandbox Basso",
checking: "Verifica della sandbox su questo computer…",
install: "Installa sandbox",
windowsSetup: "Configura la sandbox di Windows",
copyCommand: "Copia comando",
copied: "Comando copiato",
copyFailed: "Impossibile copiare il comando",
- commandHint: "Oppure esegui questo sul computer su cui gira Unsloth, poi scegli di nuovo la modalità:",
+ copiedRunIt: "Comando copiato. Eseguilo in un terminale del computer dove gira Unsloth, poi passa ad Alto.",
ownerOnly: "Solo il proprietario può installarla, dal computer su cui gira Unsloth.",
- runInTerminal: "Unsloth non può chiedere la tua password qui. Esegui questo comando in un terminale del computer dove gira Unsloth, poi scegli di nuovo la modalità:",
- useAnyway: "Usala comunque (le chiamate rischiose chiederanno)",
- cancel: "Annulla",
- close: "Chiudi",
+ windowsNote: "Richiede un passaggio da amministratore dopo ogni riavvio. MXC è un'anteprima, non un confine di sicurezza.",
running: "Configurazione in corso. Approva la richiesta di password o di amministratore sul computer su cui gira Unsloth…",
- succeeded: "La sandbox del sistema è pronta. Esegui automaticamente è attivo.",
+ succeeded: "La sandbox del sistema è pronta. Sandbox Alto è attivo.",
stillUnavailable: "La configurazione è terminata, ma la sandbox del sistema non supera ancora la verifica.",
declined: "La richiesta di password o di amministratore è stata rifiutata.",
failed: "Configurazione non riuscita.",
@@ -1089,6 +1086,18 @@ export const it = {
installRuntimeError: "Impossibile avviare l'installazione del runtime.",
unsupportedArch: "La sandbox di Windows (MXC) funziona solo su Windows x64, quindi non è disponibile su questo PC.",
unsupportedBuild: "La sandbox di Windows (MXC) richiede Windows 11 24H2 (build 26100) o successivo, quindi non è disponibile su questo PC.",
+ permissionsIntro: "Scegli quando gli strumenti chiedono prima e se Python e Terminale vengono eseguiti anche nella sandbox del sistema.",
+ levelLabel: "Sandbox",
+ levelHigh: "Alto",
+ levelLow: "Basso",
+ levelHighShort: "Sandbox del sistema",
+ levelLowShort: "Sandbox software",
+ levelHelp: "Basso: sandbox software. Alto: sandbox del sistema. Scopri di più in Impostazioni > Sandbox.",
+ levelHighDescription: "Alto: sandbox del sistema. Python e Terminale vengono eseguiti nella sandbox del sistema (bubblewrap, Seatbelt o MXC) oltre alle protezioni software. Senza una sandbox del sistema funzionante, le chiamate rischiose chiedono prima.",
+ levelLowDescription: "Basso: sandbox software. Python e Terminale vengono eseguiti solo con le protezioni software, fuori dalla sandbox del sistema. Le chiamate rischiose chiedono prima, tranne con Accesso completo.",
+ levelFullAccessNote: "Accesso completo disattiva la sandbox. Questa impostazione torna valida quando scegli un altro livello.",
+ learnMore: "Scopri di più",
+ managedNote: "Il proprietario di questo server Unsloth configura la sandbox del sistema.",
},
debugging: {
logSection: "File di log",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index e1bc14147f4..2a06cdf8643 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -299,23 +299,20 @@ export const ja = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "OS サンドボックスは利用できません",
- title: "このコンピューターにはまだ OS サンドボックスがありません",
- description: "自動で実行は Python とターミナルを OS サンドボックス内で動かします。ここで動作するまでは、危険な呼び出しは先に確認します。",
+ levelTitle: "OS サンドボックスを利用できません",
+ levelDescription: "高を使うにはインストールしてください。低 (ソフトウェア サンドボックス) のままでもかまいません。",
+ useLow: "低のサンドボックスを使う",
checking: "このコンピューターのサンドボックスを確認しています…",
install: "サンドボックスをインストール",
windowsSetup: "Windows サンドボックスを設定",
copyCommand: "コマンドをコピー",
copied: "コマンドをコピーしました",
copyFailed: "コマンドをコピーできませんでした",
- commandHint: "または、Unsloth を実行しているコンピューターでこれを実行してから、もう一度モードを選んでください:",
+ copiedRunIt: "コマンドをコピーしました。Unsloth を実行しているコンピューターのターミナルで実行してから、高 に切り替えてください。",
ownerOnly: "インストールできるのは、Unsloth を実行しているコンピューター上の所有者だけです。",
- runInTerminal: "Unsloth はここでパスワードを尋ねられません。Unsloth を実行しているコンピューターのターミナルでこれを実行してから、もう一度モードを選んでください:",
- useAnyway: "このまま使う (危険な呼び出しは確認します)",
- cancel: "キャンセル",
- close: "閉じる",
+ windowsNote: "再起動のたびに管理者の操作が必要です。MXC はプレビューであり、セキュリティ境界ではありません。",
running: "設定中です。Unsloth を実行しているコンピューターでパスワードまたは管理者の確認を承認してください…",
- succeeded: "OS サンドボックスの準備ができました。自動で実行が有効です。",
+ succeeded: "OS サンドボックスの準備ができました。サンドボックスは高になりました。",
stillUnavailable: "設定は完了しましたが、OS サンドボックスはまだチェックに合格していません。",
declined: "パスワードまたは管理者の確認が拒否されました。",
failed: "設定に失敗しました。",
@@ -1131,6 +1128,18 @@ export const ja = {
installRuntimeError: "ランタイムのインストールを開始できませんでした。",
unsupportedArch: "Windows サンドボックス (MXC) は x64 版 Windows でのみ動作するため、この PC では使用できません。",
unsupportedBuild: "Windows サンドボックス (MXC) には Windows 11 24H2 (ビルド 26100) 以降が必要なため、この PC では使用できません。",
+ permissionsIntro: "ツールが先に確認するタイミングと、Python とターミナルを OS サンドボックス内でも実行するかを選びます。",
+ levelLabel: "サンドボックス",
+ levelHigh: "高",
+ levelLow: "低",
+ levelHighShort: "OS サンドボックス",
+ levelLowShort: "ソフトウェア サンドボックス",
+ levelHelp: "低: ソフトウェア サンドボックス。高: OS サンドボックス。詳しくは 設定 > サンドボックス を参照してください。",
+ levelHighDescription: "高: OS サンドボックス。Python とターミナルは、ソフトウェアの保護に加えて OS サンドボックス (bubblewrap、Seatbelt または MXC) 内で実行されます。OS サンドボックスが動作しない場合、危険な呼び出しは先に確認します。",
+ levelLowDescription: "低: ソフトウェア サンドボックス。Python とターミナルはソフトウェアの保護のみで、OS サンドボックスの外で実行されます。フルアクセス以外では、危険な呼び出しは先に確認します。",
+ levelFullAccessNote: "フルアクセスではサンドボックスがオフになります。別のレベルを選ぶと、この設定が再び適用されます。",
+ learnMore: "詳細",
+ managedNote: "OS サンドボックスは、この Unsloth サーバーの所有者が設定します。",
},
debugging: {
logSection: "ログファイル",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 25ed3867188..516c5c3a4f8 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -298,23 +298,20 @@ export const ko = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "OS 샌드박스를 사용할 수 없음",
- title: "이 컴퓨터에는 아직 OS 샌드박스가 없습니다",
- description: "자동 실행은 Python과 터미널을 OS 샌드박스 안에서 실행합니다. 여기서 작동할 때까지 위험한 호출은 먼저 묻습니다.",
+ levelTitle: "OS 샌드박스를 사용할 수 없습니다",
+ levelDescription: "높음을 사용하려면 설치하거나 낮음(소프트웨어 샌드박스)을 유지하세요.",
+ useLow: "낮음 샌드박스 사용",
checking: "이 컴퓨터의 샌드박스를 확인하는 중…",
install: "샌드박스 설치",
windowsSetup: "Windows 샌드박스 설정",
copyCommand: "명령 복사",
copied: "명령을 복사했습니다",
copyFailed: "명령을 복사하지 못했습니다",
- commandHint: "또는 Unsloth가 실행 중인 컴퓨터에서 이 명령을 실행한 뒤 모드를 다시 선택하세요:",
+ copiedRunIt: "명령을 복사했습니다. Unsloth가 실행 중인 컴퓨터의 터미널에서 실행한 뒤 높음으로 전환하세요.",
ownerOnly: "Unsloth가 실행 중인 컴퓨터에서 소유자만 설치할 수 있습니다.",
- runInTerminal: "Unsloth가 여기서 비밀번호를 요청할 수 없습니다. Unsloth가 실행 중인 컴퓨터의 터미널에서 이 명령을 실행한 뒤 모드를 다시 선택하세요:",
- useAnyway: "그대로 사용 (위험한 호출은 묻습니다)",
- cancel: "취소",
- close: "닫기",
+ windowsNote: "재시작할 때마다 관리자 단계가 필요합니다. MXC는 미리 보기이며 보안 경계가 아닙니다.",
running: "설정 중입니다. Unsloth가 실행 중인 컴퓨터에서 암호 또는 관리자 확인을 승인하세요…",
- succeeded: "OS 샌드박스가 준비되었습니다. 자동 실행이 켜졌습니다.",
+ succeeded: "OS 샌드박스가 준비되었습니다. 샌드박스 높음이 켜졌습니다.",
stillUnavailable: "설정은 끝났지만 OS 샌드박스가 아직 검사를 통과하지 못했습니다.",
declined: "암호 또는 관리자 확인이 거부되었습니다.",
failed: "설정하지 못했습니다.",
@@ -1129,6 +1126,18 @@ export const ko = {
installRuntimeError: "런타임 설치를 시작하지 못했습니다.",
unsupportedArch: "Windows 샌드박스(MXC)는 x64 Windows에서만 실행되므로 이 PC에서는 사용할 수 없습니다.",
unsupportedBuild: "Windows 샌드박스(MXC)는 Windows 11 24H2(빌드 26100) 이상이 필요하므로 이 PC에서는 사용할 수 없습니다.",
+ permissionsIntro: "도구가 먼저 묻는 시점과 Python 및 터미널을 OS 샌드박스 안에서도 실행할지 선택합니다.",
+ levelLabel: "샌드박스",
+ levelHigh: "높음",
+ levelLow: "낮음",
+ levelHighShort: "OS 샌드박스",
+ levelLowShort: "소프트웨어 샌드박스",
+ levelHelp: "낮음: 소프트웨어 샌드박스. 높음: OS 샌드박스. 자세한 내용은 설정 > 샌드박스에서 확인하세요.",
+ levelHighDescription: "높음: OS 샌드박스. Python과 터미널이 소프트웨어 보호에 더해 OS 샌드박스(bubblewrap, Seatbelt 또는 MXC) 안에서 실행됩니다. 작동하는 OS 샌드박스가 없으면 위험한 호출은 먼저 묻습니다.",
+ levelLowDescription: "낮음: 소프트웨어 샌드박스. Python과 터미널이 소프트웨어 보호만으로 OS 샌드박스 밖에서 실행됩니다. 전체 액세스가 아니면 위험한 호출은 먼저 묻습니다.",
+ levelFullAccessNote: "전체 액세스는 샌드박스를 끕니다. 다른 수준을 선택하면 이 설정이 다시 적용됩니다.",
+ learnMore: "자세히 알아보기",
+ managedNote: "OS 샌드박스는 이 Unsloth 서버의 소유자가 설정합니다.",
},
debugging: {
logSection: "로그 파일",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 4ffd68f2209..6c0c86fd8ae 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -298,23 +298,20 @@ export const ptBR = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "Sandbox do sistema indisponível",
- title: "Ainda não há sandbox do sistema neste computador",
- description: "Executar automaticamente mantém Python e Terminal no sandbox do sistema. Até que funcione aqui, as chamadas arriscadas deles perguntam primeiro.",
+ levelTitle: "O sandbox do sistema não está disponível",
+ levelDescription: "Instale-o para usar Alto ou continue em Baixo (sandbox de software).",
+ useLow: "Usar sandbox Baixo",
checking: "Verificando o sandbox deste computador…",
install: "Instalar sandbox",
windowsSetup: "Configurar o sandbox do Windows",
copyCommand: "Copiar comando",
copied: "Comando copiado",
copyFailed: "Não foi possível copiar o comando",
- commandHint: "Ou execute isto no computador onde o Unsloth roda e escolha o modo de novo:",
+ copiedRunIt: "Comando copiado. Execute-o em um terminal no computador onde o Unsloth roda e mude para Alto.",
ownerOnly: "Somente o proprietário pode instalar, a partir do computador onde o Unsloth roda.",
- runInTerminal: "O Unsloth não consegue pedir sua senha aqui. Execute isto em um terminal no computador onde o Unsloth roda e escolha o modo de novo:",
- useAnyway: "Usar mesmo assim (chamadas arriscadas vão perguntar)",
- cancel: "Cancelar",
- close: "Fechar",
+ windowsNote: "Precisa de uma etapa de administrador após cada reinício. O MXC é uma prévia, não uma barreira de segurança.",
running: "Configurando. Aprove o pedido de senha ou de administrador no computador onde o Unsloth roda…",
- succeeded: "O sandbox do sistema está pronto. Executar automaticamente está ativado.",
+ succeeded: "O sandbox do sistema está pronto. Sandbox Alto está ativado.",
stillUnavailable: "A configuração terminou, mas o sandbox do sistema ainda não passa na verificação.",
declined: "O pedido de senha ou de administrador foi recusado.",
failed: "A configuração falhou.",
@@ -1131,6 +1128,18 @@ export const ptBR = {
installRuntimeError: "Não foi possível iniciar a instalação do runtime.",
unsupportedArch: "O sandbox do Windows (MXC) só funciona no Windows x64, então não está disponível neste PC.",
unsupportedBuild: "O sandbox do Windows (MXC) precisa do Windows 11 24H2 (build 26100) ou mais recente, então não está disponível neste PC.",
+ permissionsIntro: "Escolha quando as ferramentas perguntam antes e se Python e Terminal também rodam dentro do sandbox do sistema.",
+ levelLabel: "Sandbox",
+ levelHigh: "Alto",
+ levelLow: "Baixo",
+ levelHighShort: "Sandbox do sistema",
+ levelLowShort: "Sandbox de software",
+ levelHelp: "Baixo: sandbox de software. Alto: sandbox do sistema. Saiba mais em Configurações > Sandbox.",
+ levelHighDescription: "Alto: sandbox do sistema. Python e Terminal rodam dentro do sandbox do sistema (bubblewrap, Seatbelt ou MXC) além das proteções de software. Sem um sandbox do sistema funcionando, chamadas arriscadas perguntam antes.",
+ levelLowDescription: "Baixo: sandbox de software. Python e Terminal rodam somente com as proteções de software, fora do sandbox do sistema. Chamadas arriscadas perguntam antes, exceto com Acesso total.",
+ levelFullAccessNote: "Acesso total desliga o sandbox. Esta configuração volta a valer quando você escolher outro nível.",
+ learnMore: "Saiba mais",
+ managedNote: "O proprietário deste servidor Unsloth configura o sandbox do sistema.",
},
debugging: {
logSection: "Arquivo de log",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 9e7c30601a6..691685feef4 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -298,23 +298,20 @@ export const ru = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "Песочница ОС недоступна",
- title: "На этом компьютере пока нет песочницы ОС",
- description: "Выполнять автоматически держит Python и терминал в песочнице ОС. Пока она здесь не работает, их рискованные вызовы сначала требуют подтверждения.",
+ levelTitle: "Песочница ОС недоступна",
+ levelDescription: "Установите её, чтобы использовать Высокий, или оставьте Низкий (программная песочница).",
+ useLow: "Использовать уровень Низкий",
checking: "Проверка песочницы на этом компьютере…",
install: "Установить песочницу",
windowsSetup: "Настроить песочницу Windows",
copyCommand: "Скопировать команду",
copied: "Команда скопирована",
copyFailed: "Не удалось скопировать команду",
- commandHint: "Или выполните это на компьютере, где запущен Unsloth, и снова выберите режим:",
+ copiedRunIt: "Команда скопирована. Выполните её в терминале на компьютере, где запущен Unsloth, и переключитесь на Высокий.",
ownerOnly: "Установить её может только владелец, с компьютера, где запущен Unsloth.",
- runInTerminal: "Unsloth не может запросить здесь ваш пароль. Выполните это в терминале на компьютере, где запущен Unsloth, и снова выберите режим:",
- useAnyway: "Всё равно использовать (рискованные вызовы будут спрашивать)",
- cancel: "Отмена",
- close: "Закрыть",
+ windowsNote: "После каждой перезагрузки нужен шаг администратора. MXC пока предварительная версия, а не граница безопасности.",
running: "Идёт настройка. Подтвердите запрос пароля или администратора на компьютере, где запущен Unsloth…",
- succeeded: "Песочница ОС готова. Выполнять автоматически включено.",
+ succeeded: "Песочница ОС готова. Уровень песочницы Высокий включён.",
stillUnavailable: "Настройка завершена, но песочница ОС всё ещё не проходит проверку.",
declined: "Запрос пароля или администратора отклонён.",
failed: "Не удалось выполнить настройку.",
@@ -1131,6 +1128,18 @@ export const ru = {
installRuntimeError: "Не удалось начать установку среды.",
unsupportedArch: "Песочница Windows (MXC) работает только на Windows x64, поэтому на этом ПК она недоступна.",
unsupportedBuild: "Песочнице Windows (MXC) нужна Windows 11 24H2 (сборка 26100) или новее, поэтому на этом ПК она недоступна.",
+ permissionsIntro: "Выберите, когда инструменты спрашивают заранее и запускаются ли Python и Терминал также в песочнице ОС.",
+ levelLabel: "Песочница",
+ levelHigh: "Высокий",
+ levelLow: "Низкий",
+ levelHighShort: "Песочница ОС",
+ levelLowShort: "Программная песочница",
+ levelHelp: "Низкий: программная песочница. Высокий: песочница ОС. Подробнее в разделе Настройки > Песочница.",
+ levelHighDescription: "Высокий: песочница ОС. Python и Терминал работают в песочнице ОС (bubblewrap, Seatbelt или MXC) поверх программной защиты. Без рабочей песочницы ОС рискованные вызовы сначала спрашивают.",
+ levelLowDescription: "Низкий: программная песочница. Python и Терминал работают только с программной защитой, вне песочницы ОС. Рискованные вызовы сначала спрашивают, кроме режима Полный доступ.",
+ levelFullAccessNote: "Полный доступ отключает песочницу. Эта настройка снова действует, когда вы выберете другой уровень.",
+ learnMore: "Подробнее",
+ managedNote: "Песочницу ОС настраивает владелец этого сервера Unsloth.",
},
debugging: {
logSection: "Файл журнала",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index cbeb80bce1a..b17f061e672 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -298,23 +298,20 @@ export const zhCN = {
// English fallback until this experimental feature is translated.
managedEngines: en.managedEngines,
sandboxSetup: {
- unavailable: "系统沙箱不可用",
- title: "这台电脑还没有系统沙箱",
- description: "自动运行会让 Python 和终端在系统沙箱中运行。在这里可用之前,它们的高风险调用会先询问。",
+ levelTitle: "操作系统沙盒不可用",
+ levelDescription: "安装后即可使用高,或保持低(软件沙盒)。",
+ useLow: "使用低级沙盒",
checking: "正在检查这台电脑上的沙箱…",
install: "安装沙箱",
windowsSetup: "设置 Windows 沙箱",
copyCommand: "复制命令",
copied: "已复制命令",
copyFailed: "无法复制命令",
- commandHint: "或者在运行 Unsloth 的电脑上执行以下命令,然后重新选择该模式:",
+ copiedRunIt: "已复制命令。请在运行 Unsloth 的电脑的终端中运行,然后切换到高。",
ownerOnly: "只有所有者能在运行 Unsloth 的电脑上安装。",
- runInTerminal: "Unsloth 无法在这里请求你的密码。请在运行 Unsloth 的电脑的终端中运行以下命令,然后重新选择该模式:",
- useAnyway: "仍然使用(高风险调用会询问)",
- cancel: "取消",
- close: "关闭",
+ windowsNote: "每次重启后都需要一次管理员操作。MXC 仍是预览版,不是安全边界。",
running: "正在设置。请在运行 Unsloth 的电脑上批准密码或管理员提示…",
- succeeded: "系统沙箱已就绪。自动运行已开启。",
+ succeeded: "操作系统沙盒已就绪。沙盒已切换为高。",
stillUnavailable: "设置已完成,但系统沙箱仍未通过检查。",
declined: "密码或管理员提示被拒绝。",
failed: "设置失败。",
@@ -1127,6 +1124,18 @@ export const zhCN = {
installRuntimeError: "无法开始安装运行时。",
unsupportedArch: "Windows 沙箱 (MXC) 仅支持 x64 版 Windows,因此在此电脑上不可用。",
unsupportedBuild: "Windows 沙箱 (MXC) 需要 Windows 11 24H2(版本 26100)或更高版本,因此在此电脑上不可用。",
+ permissionsIntro: "选择工具何时先询问,以及 Python 和终端是否也在操作系统沙盒中运行。",
+ levelLabel: "沙盒",
+ levelHigh: "高",
+ levelLow: "低",
+ levelHighShort: "操作系统沙盒",
+ levelLowShort: "软件沙盒",
+ levelHelp: "低:软件沙盒。高:操作系统沙盒。在 设置 > 沙盒 中了解详情。",
+ levelHighDescription: "高:操作系统沙盒。Python 和终端在软件防护之外,还在操作系统沙盒(bubblewrap、Seatbelt 或 MXC)中运行。没有可用的操作系统沙盒时,有风险的调用会先询问。",
+ levelLowDescription: "低:软件沙盒。Python 和终端仅使用软件防护,在操作系统沙盒之外运行。除完全访问外,有风险的调用会先询问。",
+ levelFullAccessNote: "完全访问会关闭沙盒。选择其他级别后,此设置将重新生效。",
+ learnMore: "了解详情",
+ managedNote: "操作系统沙盒由此 Unsloth 服务器的所有者设置。",
},
debugging: {
logSection: "日志文件",
diff --git a/studio/frontend/tests/account-permissions.test.ts b/studio/frontend/tests/account-permissions.test.ts
index e866b69e0c5..923f2dbcd42 100644
--- a/studio/frontend/tests/account-permissions.test.ts
+++ b/studio/frontend/tests/account-permissions.test.ts
@@ -12,6 +12,7 @@ import {
type Capability = {
pythonOsIsolated: boolean;
terminalOsIsolated: boolean;
+ backend?: string;
} | null;
function permissionUi(
@@ -19,6 +20,7 @@ function permissionUi(
permissionMode: string,
loginMode = "multi",
capability: Capability = null,
+ sandboxLevel = "high",
) {
const accountSession = loadWithStubs<{
useFullAccessAllowed: () => boolean;
@@ -34,6 +36,9 @@ function permissionUi(
},
});
const changes: string[] = [];
+ const levels: string[] = [];
+ const popups: boolean[] = [];
+ const opened: [string, unknown][] = [];
const capabilityStub = {
loadSandboxCapability: async () => capability,
loadSettledSandboxCapability: async () => capability,
@@ -46,6 +51,10 @@ function permissionUi(
};
const state = {
permissionMode,
+ sandboxLevel,
+ setSandboxLevel: (value: string) => {
+ levels.push(value);
+ },
setPermissionMode: (value: string) => {
changes.push(value);
},
@@ -53,14 +62,13 @@ function permissionUi(
const component = loadWithStubs<{
PermissionModeMenuItems: (props: {
onRequestFullAccess: () => void;
- onRequestSandboxSetup: () => void;
+ }) => StubElement;
+ PermissionMenuLabel: (props: {
+ sandboxControls: boolean;
+ onOsSandboxMissing?: () => void;
}) => StubElement;
PERMISSION_MODE_OPTIONS: readonly { value: string; label: string }[];
permissionModeOption: (mode: string) => { value: string; label: string };
- pickSandboxedMode: (
- setPermissionMode: (mode: string) => void,
- onRequestSandboxSetup: () => void,
- ) => Promise<void>;
FullAccessConfirmDialog: (props: {
open: boolean;
onOpenChange: () => void;
@@ -71,17 +79,29 @@ function permissionUi(
"react/jsx-runtime": stubJsxRuntime(),
react: {
useEffect: (effect: () => void) => effect(),
- useState: () => [false, () => {}],
+ // The capability hook starts at null; the menu sees the stubbed answer.
+ useState: (initial: unknown) => [initial === null ? capability : initial, () => {}],
+ useId: () => "id",
+ useRef: (current: unknown) => ({ current }),
},
"lucide-react": {
ChevronDown: "ChevronDown",
Hand: "Hand",
ShieldCheck: "ShieldCheck",
},
- "radix-ui": { DropdownMenu: { Item: "DropdownMenuPrimitive.Item" } },
+ "radix-ui": {
+ DropdownMenu: {
+ Item: "DropdownMenuPrimitive.Item",
+ CheckboxItem: "DropdownMenuPrimitive.CheckboxItem",
+ },
+ },
"@/features/settings": {
useSettingsDialogStore: (selector: (state: unknown) => unknown) =>
- selector({ openDialog: () => {} }),
+ selector({
+ openDialog: (tab: string, options?: { scrollTarget?: string }) => {
+ opened.push([tab, options?.scrollTarget]);
+ },
+ }),
},
"@/i18n": { useT: () => (key: string) => key },
"@/features/auth/account-session": accountSession,
@@ -92,10 +112,20 @@ function permissionUi(
),
"./sandbox-setup-dialog": {
SandboxSetupDialog: "SandboxSetupDialog",
- useSandboxSetupDialogStore: () => () => {},
+ useSandboxSetupDialogStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ setOpen: (open: boolean) => {
+ popups.push(open);
+ },
+ }),
},
"@/components/ui/alert-dialog": { AlertDialog: "AlertDialog" },
"@/components/ui/button": { Button: "Button" },
+ "@/components/ui/switch": { Switch: "Switch" },
+ "./sandbox-level": loadWithStubs(
+ new URL("../src/features/chat/sandbox-level.ts", import.meta.url),
+ {},
+ ),
"@/components/ui/dropdown-menu": { DropdownMenuItem: "DropdownMenuItem" },
"@/lib/chevron-icons": {},
"@/lib/sparkles-icon": { SparklesGlyph: "SparklesGlyph" },
@@ -112,7 +142,7 @@ function permissionUi(
},
},
);
- return { component, changes };
+ return { component, changes, levels, popups, opened };
}
for (const loginMode of ["single", "multi"]) {
@@ -121,7 +151,6 @@ for (const loginMode of ["single", "multi"]) {
const ui = permissionUi(owner, "full", loginMode);
const menu = ui.component.PermissionModeMenuItems({
onRequestFullAccess() {},
- onRequestSandboxSetup() {},
});
const rows = menu.props.children as StubElement[];
assert.equal(rows.length, owner ? 4 : 3);
@@ -142,7 +171,6 @@ test("multi-user policy leaves non-full preferences untouched", () => {
onRequestFullAccess() {
assert.fail("Full access must be unavailable");
},
- onRequestSandboxSetup() {},
});
assert.deepEqual(ui.changes, []);
}
@@ -165,40 +193,113 @@ test("the stored values keep their order and their names", () => {
assert.equal(ui.component.permissionModeOption("bogus").value, "auto");
});
-for (const [name, capability, expected] of [
- ["an older server that cannot say", null, "applied"],
- [
- "a working OS sandbox",
- { pythonOsIsolated: true, terminalOsIsolated: true },
- "applied",
- ],
- [
- "a Terminal without OS isolation",
- { pythonOsIsolated: true, terminalOsIsolated: false },
- "setup",
- ],
- [
- "no OS sandbox",
- { pythonOsIsolated: false, terminalOsIsolated: false },
- "setup",
- ],
+const NO_OS_SANDBOX = { pythonOsIsolated: false, terminalOsIsolated: false, backend: "bubblewrap" };
+const OS_SANDBOX = { pythonOsIsolated: true, terminalOsIsolated: true, backend: "bubblewrap" };
+const tick = () => new Promise((resolve) => setTimeout(resolve, 5));
+
+for (const [name, capability] of [
+ ["no OS sandbox", NO_OS_SANDBOX],
+ ["a working OS sandbox", OS_SANDBOX],
+ ["an older server that cannot say", null],
] as const) {
- test(`picking Run automatically with ${name} is ${expected}`, async () => {
+ test(`picking Run automatically with ${name} applies it, with no popup and no row hint`, () => {
const ui = permissionUi(true, "auto", "single", capability);
- const applied: string[] = [];
- let setupRequested = 0;
- await ui.component.pickSandboxedMode(
- (mode) => applied.push(mode),
- () => {
- setupRequested += 1;
+ const rows = ui.component.PermissionModeMenuItems({
+ onRequestFullAccess() {
+ assert.fail("not Full access");
},
- );
- if (expected === "applied") {
- assert.deepEqual(applied, ["off"]);
- assert.equal(setupRequested, 0);
- } else {
- assert.deepEqual(applied, []);
- assert.equal(setupRequested, 1);
- }
+ }).props.children as StubElement[];
+ const off = rows[2];
+ (off.props.onSelect as () => void)();
+ assert.deepEqual(ui.changes, ["off"]);
+ assert.deepEqual(ui.popups, []);
+ // The row holds its icon and the label/description column only: no "not available" line.
+ const [, column] = off.props.children as [StubElement, StubElement];
+ assert.equal((column.props.children as unknown[]).length, 2);
+ });
+}
+
+function menuSwitch(ui: ReturnType<typeof permissionUi>, onOsSandboxMissing?: () => void) {
+ const label = ui.component.PermissionMenuLabel({ sandboxControls: true, onOsSandboxMissing });
+ const [heading, control] = label.props.children as [StubElement, StubElement];
+ const rendered = (control.type as (props: unknown) => StubElement)(control.props);
+ const [checkbox, help] = rendered.props.children as [StubElement, StubElement];
+ return { heading, checkbox, help };
+}
+
+test("the menu heading says Permissions and has no switch where Settings shows its own", () => {
+ const ui = permissionUi(true, "auto", "single", OS_SANDBOX);
+ const label = ui.component.PermissionMenuLabel({ sandboxControls: false });
+ const [heading, control] = label.props.children as [StubElement, unknown];
+ assert.equal(heading.props.children, "settings.general.permissions.sectionTitle");
+ assert.equal(control, null);
+});
+
+for (const [name, capability, level, mode, checked, disabled] of [
+ ["High with a working OS sandbox", OS_SANDBOX, "high", "auto", true, false],
+ ["High saved but no OS sandbox", NO_OS_SANDBOX, "high", "auto", false, false],
+ ["Low", OS_SANDBOX, "low", "auto", false, false],
+ ["Full access", OS_SANDBOX, "high", "full", true, true],
+] as const) {
+ test(`the Sandbox switch for ${name}`, () => {
+ const ui = permissionUi(true, mode, "single", capability, level);
+ const { checkbox } = menuSwitch(ui);
+ assert.equal(checkbox.props.checked, checked);
+ assert.equal(checkbox.props.disabled, disabled);
});
}
+
+test("sliding to High without an OS sandbox opens the install popup and keeps Low", async () => {
+ const ui = permissionUi(true, "auto", "single", NO_OS_SANDBOX, "low");
+ const { checkbox } = menuSwitch(ui);
+ // Not prevented: the menu closes so the popup can take focus.
+ let prevented = false;
+ (checkbox.props.onSelect as (event: { preventDefault: () => void }) => void)({
+ preventDefault: () => {
+ prevented = true;
+ },
+ });
+ assert.equal(prevented, false);
+ (checkbox.props.onCheckedChange as (next: boolean) => void)(true);
+ await tick();
+ assert.deepEqual(ui.popups, [true]);
+ assert.deepEqual(ui.levels, []);
+
+ const local: string[] = [];
+ const own = menuSwitch(permissionUi(true, "auto", "single", NO_OS_SANDBOX, "low"), () =>
+ local.push("popup"),
+ );
+ (own.checkbox.props.onCheckedChange as (next: boolean) => void)(true);
+ await tick();
+ assert.deepEqual(local, ["popup"]);
+});
+
+test("sliding to High with a working OS sandbox applies it; sliding to Low keeps the menu open", async () => {
+ const ui = permissionUi(true, "auto", "single", OS_SANDBOX, "low");
+ const { checkbox } = menuSwitch(ui);
+ (checkbox.props.onCheckedChange as (next: boolean) => void)(true);
+ await tick();
+ assert.deepEqual(ui.levels, ["high"]);
+ assert.deepEqual(ui.popups, []);
+
+ const high = permissionUi(true, "auto", "single", OS_SANDBOX, "high");
+ const on = menuSwitch(high).checkbox;
+ let prevented = false;
+ (on.props.onSelect as (event: { preventDefault: () => void }) => void)({
+ preventDefault: () => {
+ prevented = true;
+ },
+ });
+ assert.equal(prevented, true);
+ (on.props.onCheckedChange as (next: boolean) => void)(false);
+ assert.deepEqual(high.levels, ["low"]);
+});
+
+test("the question mark next to the switch opens Settings > Sandbox at Permissions", async () => {
+ const ui = permissionUi(true, "auto", "single", OS_SANDBOX);
+ const { help } = menuSwitch(ui);
+ assert.equal(help.props["aria-label"], "settings.sandbox.levelHelp");
+ (help.props.onSelect as () => void)();
+ await tick();
+ assert.deepEqual(ui.opened, [["sandbox", "sandbox-permissions"]]);
+});
diff --git a/studio/frontend/tests/permission-mode-learn-more.test.ts b/studio/frontend/tests/permission-mode-learn-more.test.ts
index 8c4396786ab..437481594f0 100644
--- a/studio/frontend/tests/permission-mode-learn-more.test.ts
+++ b/studio/frontend/tests/permission-mode-learn-more.test.ts
@@ -9,22 +9,49 @@ const MENU = await readFile(
new URL("../src/features/chat/permission-mode-select.tsx", import.meta.url),
"utf8",
);
-const GENERAL = await readFile(
+const SANDBOX_TAB = await readFile(
+ new URL("../src/features/settings/tabs/sandbox-tab.tsx", import.meta.url),
+ "utf8",
+);
+const OLD_GENERAL = await readFile(
new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),
"utf8",
);
-test("Learn more opens the Permissions section of Settings", () => {
- assert.match(MENU, /openSettings\("general", \{ scrollTarget: "general-permissions" \}\)/);
- assert.match(GENERAL, /if \(scrollTarget !== "general-permissions"\) return;/);
- assert.match(GENERAL, /ref=\{permissionsRef\}/);
+test("the question mark opens the Permissions section of Settings > Sandbox", () => {
+ assert.match(MENU, /openSettings\("sandbox", \{ scrollTarget: "sandbox-permissions" \}\)/);
+ assert.match(SANDBOX_TAB, /if \(scrollTarget !== "sandbox-permissions"\) return;/);
+ assert.match(SANDBOX_TAB, /ref=\{permissionsRef\}/);
+ assert.doesNotMatch(OLD_GENERAL, /permissionsRef|PermissionModeDropdown|general-permissions/);
+});
+
+test("Settings explains only the selected level and drops the menu's sandbox controls", () => {
+ assert.match(SANDBOX_TAB, /label=\{t\(`settings\.general\.permissions\.names\.\$\{activePermission\.value\}`\)\}/);
+ assert.match(SANDBOX_TAB, /t\(`settings\.general\.permissions\.details\.\$\{activePermission\.value\}`\)/);
+ assert.match(SANDBOX_TAB, /<PermissionModeDropdown sandboxControls=\{false\} \/>/);
+ assert.doesNotMatch(SANDBOX_TAB, /permissions\.bypass(Label|Description)/);
+});
+
+test("the menu heading carries the Sandbox switch and a question mark in place of Learn more", () => {
+ const label = MENU.slice(
+ MENU.indexOf("export function PermissionMenuLabel"),
+ MENU.indexOf("/** The option rows shared"),
+ );
+ assert.doesNotMatch(label, /Learn more|Tool call permissions/);
+ assert.match(label, /settings\.general\.permissions\.sectionTitle/);
+ assert.match(label, /<DropdownMenuPrimitive\.CheckboxItem/);
+ // The keyboard toggles it without closing the menu or picking a row.
+ assert.match(label, /event\.preventDefault\(\)/);
+ assert.match(label, /<Switch\b/);
+ assert.match(label, /settings\.sandbox\.levelLowShort/);
+ assert.match(label, /icon=\{HelpCircleIcon\}/);
+ assert.match(label, /settings\.sandbox\.levelHelp/);
});
-test("Settings explains only the selected level and drops its own Learn more", () => {
- assert.match(GENERAL, /label=\{t\(`settings\.general\.permissions\.names\.\$\{activePermission\.value\}`\)\}/);
- assert.match(GENERAL, /t\(`settings\.general\.permissions\.details\.\$\{activePermission\.value\}`\)/);
- assert.match(GENERAL, /<PermissionModeDropdown learnMore=\{false\} \/>/);
- assert.doesNotMatch(GENERAL, /permissions\.bypass(Label|Description)/);
+test("the rows carry no sandbox hint and no setup banner", () => {
+ const rows = MENU.slice(MENU.indexOf("export function PermissionModeMenuItems"));
+ assert.doesNotMatch(rows, /sandboxSetup\.unavailable|levelLowRowHint|notSetUp|SandboxSetupBanner/);
+ assert.doesNotMatch(MENU, /SandboxSetupBanner|sandboxBanner/);
});
test("menu descriptions stay to one short line", () => {
@@ -35,7 +62,7 @@ test("menu descriptions stay to one short line", () => {
});
test("Full access looks like every other level and asks in a short, neutral confirmation", () => {
- for (const source of [MENU, GENERAL]) assert.doesNotMatch(source, /text-bypass|data-variant=\{fullAccess/);
+ for (const source of [MENU, SANDBOX_TAB]) assert.doesNotMatch(source, /text-bypass|data-variant=\{fullAccess/);
assert.match(MENU, /icon: ShieldAlertGlyph,/);
assert.match(MENU, /Turn on Full access\?/);
assert.doesNotMatch(MENU, /text-sky-/);
@@ -54,15 +81,15 @@ const DICTATION = await readFile(
);
const EN = await readFile(new URL("../src/i18n/locales/en.ts", import.meta.url), "utf8");
-test("the dictation submenu has the heading and Learn more too", () => {
- assert.match(DICTATION, /<PermissionMenuLabel learnMore \/>\s*<PermissionModeMenuItems/);
+test("the dictation submenu has the heading and the Sandbox switch too", () => {
+ assert.match(DICTATION, /<PermissionMenuLabel sandboxControls \/>\s*<PermissionModeMenuItems/);
});
test("confirmation Learn more hands Settings the focus from before the dialog", () => {
assert.match(MENU, /returnFocusRef\.current = lastFocusOutsideMenus\(\);/);
// A closing menu resolves to its trigger, which outlives it.
assert.match(MENU, /menu\.getAttribute\("aria-labelledby"\)/);
- assert.match(MENU, /scrollTarget: "general-permissions",\s*opener: returnFocusRef\.current,/);
+ assert.match(MENU, /openSettings\("sandbox", \{\s*scrollTarget: "sandbox-permissions",\s*opener: returnFocusRef\.current,/);
});
test("Ask says provider-hosted tools are not paused", () => {
diff --git a/studio/frontend/tests/sandbox-level.test.ts b/studio/frontend/tests/sandbox-level.test.ts
new file mode 100644
index 00000000000..cef8005c882
--- /dev/null
+++ b/studio/frontend/tests/sandbox-level.test.ts
@@ -0,0 +1,221 @@
+// 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 type { SandboxCapability } from "../src/features/chat/api/sandbox-capability.ts";
+import type { PersistedChatSettings } from "../src/features/chat/api/chat-settings-api.ts";
+import {
+ osSandboxMissing,
+ sandboxSwitchState,
+} from "../src/features/chat/sandbox-level.ts";
+import { assignSanitizedMirroredSettings } from "../src/features/chat/utils/mirrored-chat-settings.ts";
+import { settingsTabVisible } from "../src/features/settings/settings-tab-visibility.ts";
+import {
+ SETTINGS_SEARCH_INDEX,
+ renderedSearchEntries,
+} from "../src/features/settings/settings-search.ts";
+import { useSettingsDialogStore } from "../src/features/settings/stores/settings-dialog-store.ts";
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+const { store: localStorageFake } = installLocalStorageFake();
+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");
+register("./store-settings-resolver.mjs", import.meta.url);
+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");
+const { useChatRuntimeStore, loadSandboxLevel, CHAT_SANDBOX_LEVEL_KEY } = await import(
+ "../src/features/chat/stores/chat-runtime-store.ts"
+);
+
+const LEVEL_KEY = "unsloth_chat_sandbox_level";
+
+test("the sandbox level defaults to High; only an explicit Low reads as Low", () => {
+ assert.equal(CHAT_SANDBOX_LEVEL_KEY, LEVEL_KEY);
+ // A profile from before the setting existed.
+ localStorageFake.delete(LEVEL_KEY);
+ assert.equal(loadSandboxLevel(), "high");
+ assert.equal(useChatRuntimeStore.getState().sandboxLevel, "high");
+ for (const garbled of ["", "LOW", "medium", "null"]) {
+ localStorageFake.set(LEVEL_KEY, garbled);
+ assert.equal(loadSandboxLevel(), "high", garbled);
+ }
+ localStorageFake.set(LEVEL_KEY, "low");
+ assert.equal(loadSandboxLevel(), "low");
+ localStorageFake.delete(LEVEL_KEY);
+});
+
+test("setting the level stores it, and a saved server value hydrates it", async () => {
+ useChatRuntimeStore.getState().setSandboxLevel("low");
+ assert.equal(useChatRuntimeStore.getState().sandboxLevel, "low");
+ assert.equal(localStorageFake.get(LEVEL_KEY), "low");
+ useChatRuntimeStore.getState().setSandboxLevel("high");
+ assert.equal(localStorageFake.get(LEVEL_KEY), "high");
+
+ settingsHttp.settings = { sandboxLevel: "low" };
+ useChatRuntimeStore.setState({ settingsHydrated: false });
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+ assert.equal(useChatRuntimeStore.getState().sandboxLevel, "low");
+ useChatRuntimeStore.getState().setSandboxLevel("high");
+});
+
+test("the mirrored patch keeps high and low and drops anything else", () => {
+ for (const level of ["high", "low"]) {
+ const out: PersistedChatSettings = {};
+ assignSanitizedMirroredSettings({ sandboxLevel: level }, out);
+ assert.equal(out.sandboxLevel, level);
+ }
+ const out: PersistedChatSettings = {};
+ assignSanitizedMirroredSettings({ sandboxLevel: "medium" }, out);
+ assert.equal("sandboxLevel" in out, false);
+});
+
+const ADAPTER = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+);
+
+test("every request that carries permission_mode carries sandbox_level next to it", () => {
+ const sites = [...ADAPTER.matchAll(/^(\s*)permission_mode: permissionMode,\n\s*(.*)$/gm)];
+ // Token count extras, the hosted-provider body with local tools, the local chat body.
+ assert.equal(sites.length, 3);
+ for (const site of sites) {
+ assert.match(site[2], /^sandbox_level: (runtime\.)?sandboxLevel,$/);
+ }
+ const countExtras = ADAPTER.slice(
+ ADAPTER.indexOf("export async function buildLocalTokenCountExtras"),
+ ADAPTER.indexOf("permission_mode: permissionMode,"),
+ );
+ assert.match(countExtras, /^\s*sandboxLevel,$/m);
+});
+
+function capability(overrides: Partial<SandboxCapability>): SandboxCapability {
+ return {
+ pythonOsIsolated: true,
+ terminalOsIsolated: true,
+ backend: "bubblewrap",
+ platform: "linux",
+ reason: "",
+ setupAction: null,
+ manualCommand: "",
+ canRunSetup: false,
+ setupBlocked: null,
+ needsConsent: false,
+ ...overrides,
+ };
+}
+
+test("the OS sandbox counts as missing only on a settled answer without Python or Terminal isolation", () => {
+ const neither = capability({ pythonOsIsolated: false, terminalOsIsolated: false, backend: "none" });
+ assert.equal(osSandboxMissing(capability({ terminalOsIsolated: false, backend: "none" })), true);
+ assert.equal(osSandboxMissing(capability({ pythonOsIsolated: false, backend: "none" })), true);
+ assert.equal(osSandboxMissing(neither), true);
+ assert.equal(osSandboxMissing(capability({})), false);
+ // No answer yet, or an old server that cannot say.
+ assert.equal(osSandboxMissing(null), false);
+ assert.equal(osSandboxMissing({ ...neither, backend: "unknown" }), false);
+});
+
+test("without an OS sandbox the switch reads Low even with High saved", () => {
+ const neither = capability({ pythonOsIsolated: false, terminalOsIsolated: false, backend: "none" });
+ assert.deepEqual(sandboxSwitchState("high", "auto", neither), { checked: false, disabled: false });
+ assert.deepEqual(sandboxSwitchState("high", "auto", capability({})), { checked: true, disabled: false });
+ assert.deepEqual(sandboxSwitchState("high", "auto", null), { checked: true, disabled: false });
+ assert.deepEqual(sandboxSwitchState("high", "full", neither), { checked: false, disabled: true });
+});
+
+test("the switch is on for High and disabled with the saved value under Full access", () => {
+ assert.deepEqual(sandboxSwitchState("high", "auto"), { checked: true, disabled: false });
+ assert.deepEqual(sandboxSwitchState("low", "ask"), { checked: false, disabled: false });
+ assert.deepEqual(sandboxSwitchState("low", "full"), { checked: false, disabled: true });
+ assert.deepEqual(sandboxSwitchState("high", "full"), { checked: true, disabled: true });
+});
+
+const SANDBOX_TAB = readFileSync(
+ new URL("../src/features/settings/tabs/sandbox-tab.tsx", import.meta.url),
+ "utf8",
+);
+
+test("a managed account sees the Sandbox tab, with Permissions only and no owner-only reads", () => {
+ assert.equal(settingsTabVisible("sandbox", false), true);
+ const tab = SANDBOX_TAB.slice(
+ SANDBOX_TAB.indexOf("export function SandboxTab()"),
+ SANDBOX_TAB.indexOf("function OsSandboxSections()"),
+ );
+ assert.match(tab, /<PermissionsSection \/>/);
+ assert.match(tab, /\{isOwner \? \(\s*<OsSandboxSections \/>/);
+ // The owner-only routes (/api/settings/sandbox and the setup) are read only below.
+ const permissions = SANDBOX_TAB.slice(
+ SANDBOX_TAB.indexOf("function PermissionsSection()"),
+ SANDBOX_TAB.indexOf("function OsSandboxSections()"),
+ );
+ assert.doesNotMatch(
+ permissions,
+ /loadSandboxStatus|loadSandboxSetup|loadHostPreparation|startSandboxSetup|updateSandboxSettings/,
+ );
+ // Search does not offer the owner's rows to a managed account.
+ const managed = renderedSearchEntries(SETTINGS_SEARCH_INDEX, "sandbox", "huggingface", false);
+ assert.ok(managed.includes("settings.general.permissions.sectionTitle"));
+ assert.ok(!managed.includes("settings.sandbox.toolsSection"));
+ assert.ok(
+ renderedSearchEntries(SETTINGS_SEARCH_INDEX, "sandbox", "huggingface", true).includes(
+ "settings.sandbox.toolsSection",
+ ),
+ );
+});
+
+test("the old general-permissions link opens Permissions under Settings > Sandbox", () => {
+ // An explicit opener skips reading document focus, which node does not have.
+ const dialog = useSettingsDialogStore;
+ dialog.getState().openDialog("general", { scrollTarget: "general-permissions", opener: null });
+ assert.equal(dialog.getState().activeTab, "sandbox");
+ assert.equal(dialog.getState().scrollTarget, "sandbox-permissions");
+ dialog.getState().closeDialog();
+ dialog.getState().openDialog("sandbox", { scrollTarget: "sandbox-permissions", opener: null });
+ assert.equal(dialog.getState().activeTab, "sandbox");
+ assert.equal(dialog.getState().scrollTarget, "sandbox-permissions");
+ // Reselecting the tab keeps the pending jump; another tab drops it.
+ dialog.getState().setActiveTab("sandbox");
+ assert.equal(dialog.getState().scrollTarget, "sandbox-permissions");
+ dialog.getState().setActiveTab("general");
+ assert.equal(dialog.getState().scrollTarget, null);
+ dialog.getState().closeDialog();
+ dialog.getState().openDialog("general", { scrollTarget: "general-hub", opener: null });
+ assert.equal(dialog.getState().activeTab, "general");
+ assert.equal(dialog.getState().scrollTarget, "general-hub");
+ dialog.getState().closeDialog();
+});
+
+test("a queued run keeps the level it was queued under, and a switch invalidates the queue", async () => {
+ const { snapshotQueuedChatRunSettings } = await import(
+ "../src/features/chat/utils/queued-chat-run-settings.ts"
+ );
+ useChatRuntimeStore.getState().setSandboxLevel("high");
+ const queued = snapshotQueuedChatRunSettings(useChatRuntimeStore.getState());
+ assert.equal(queued.sandboxLevel, "high");
+ const epoch = useChatRuntimeStore.getState().queuedSettingsEpoch;
+ useChatRuntimeStore.getState().setSandboxLevel("low");
+ assert.equal(useChatRuntimeStore.getState().queuedSettingsEpoch, epoch + 1);
+ assert.equal(queued.sandboxLevel, "high");
+ useChatRuntimeStore.getState().setSandboxLevel("high");
+});
+
+test("every token count body carries sandbox_level, also when no tool is selected", () => {
+ const start = ADAPTER.indexOf("export async function buildLocalTokenCountExtras");
+ const countExtras = ADAPTER.slice(start, ADAPTER.indexOf("\n}\n", start));
+ const bodies = [...countExtras.matchAll(/return \{\n([\s\S]*?)\n\s*\};/g)].map((m) => m[1]);
+ assert.equal(bodies.length, 3);
+ for (const body of bodies) assert.match(body, /sandbox_level: sandboxLevel,/);
+});
+
+const MENU = readFileSync(
+ new URL("../src/features/chat/permission-mode-select.tsx", import.meta.url),
+ "utf8",
+);
+
+test("Low reads no OS sandbox capability, in the menu and in Settings", () => {
+ assert.match(MENU, /useSandboxCapability\(sandboxLevel === "high"\)/);
+ assert.match(MENU, /if \(!enabled\) return;/);
+ assert.match(SANDBOX_TAB, /useSandboxCapability\(sandboxLevel === "high"\)/);
+});
diff --git a/studio/frontend/tests/sandbox-setup.test.ts b/studio/frontend/tests/sandbox-setup.test.ts
index 639dc76f6a8..931e673a235 100644
--- a/studio/frontend/tests/sandbox-setup.test.ts
+++ b/studio/frontend/tests/sandbox-setup.test.ts
@@ -13,7 +13,12 @@ import {
setupRowView,
} from "../src/features/settings/tabs/sandbox-tab-state.ts";
import * as tabState from "../src/features/settings/tabs/sandbox-tab-state.ts";
-import { loadWithStubs } from "./helpers/module-stubs.ts";
+import { readFileSync } from "node:fs";
+import {
+ loadWithStubs,
+ stubJsxRuntime,
+ type StubElement,
+} from "./helpers/module-stubs.ts";
type Call = { url: string; init?: RequestInit };
@@ -245,13 +250,6 @@ const pickModule = loadWithStubs<PickModule>(
},
);
-test("re-picking Run automatically without a sandbox is the way back to setup", () => {
- assert.equal(pickModule.samePickIsIgnored("off", "off", true), false);
- assert.equal(pickModule.samePickIsIgnored("off", "off", false), true);
- assert.equal(pickModule.samePickIsIgnored("auto", "auto", true), true);
- assert.equal(pickModule.samePickIsIgnored("ask", "auto", true), false);
-});
-
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((r) => {
@@ -260,112 +258,85 @@ function deferred<T>() {
return { promise, resolve };
}
-test("a slow capability read does not undo a mode picked while it was in flight", async () => {
- let mode: string = "auto";
+test("switching to Low applies at once and reads nothing", async () => {
const applied: string[] = [];
- let dialogs = 0;
- const read = deferred<SandboxCapability | null>();
- const pending = pickModule.pickSandboxedMode(
- (next) => {
- applied.push(next);
- mode = next;
- },
- () => dialogs++,
- () => mode as never,
- () => read.promise,
+ await pickModule.pickSandboxLevel(
+ "low",
+ (level) => applied.push(level),
+ () => assert.fail("no popup for Low"),
+ async () => assert.fail("no read for Low"),
);
- mode = "ask";
- read.resolve(null);
- await pending;
- assert.deepEqual(applied, []);
- assert.equal(dialogs, 0);
+ assert.deepEqual(applied, ["low"]);
});
-test("a mode change that ends back on the same mode still cancels a pending pick", async () => {
- // auto -> (pick off, read pending) -> ask -> auto: the old read must not act.
- let mode: string = "auto";
+test("switching to High with a working OS sandbox applies it; a known one skips the read", async () => {
const applied: string[] = [];
- let dialogs = 0;
- const listeners = new Set<() => void>();
- const setMode = (next: string) => {
- mode = next;
- for (const listener of listeners) listener();
- };
- const read = deferred<SandboxCapability | null>();
- const pending = pickModule.pickSandboxedMode(
- (next) => {
- applied.push(next);
- mode = next;
- },
- () => dialogs++,
- () => mode as never,
- () => read.promise,
- (onChange) => {
- listeners.add(onChange);
- return () => listeners.delete(onChange);
+ let reads = 0;
+ await pickModule.pickSandboxLevel(
+ "high",
+ (level) => applied.push(level),
+ () => assert.fail("no popup"),
+ async () => {
+ reads++;
+ return null;
},
+ () => capability({ pythonOsIsolated: true, terminalOsIsolated: true }),
);
- setMode("ask");
- setMode("auto");
- read.resolve(capability({ pythonOsIsolated: false }));
- await pending;
- assert.deepEqual(applied, []);
- assert.equal(dialogs, 0);
- assert.equal(listeners.size, 0);
+ await pickModule.pickSandboxLevel(
+ "high",
+ (level) => applied.push(level),
+ () => assert.fail("no popup"),
+ async () => capability({ pythonOsIsolated: true, terminalOsIsolated: true }),
+ );
+ assert.deepEqual(applied, ["high", "high"]);
+ assert.equal(reads, 0);
});
-test("only the latest pick acts; a missing sandbox opens the setup instead of applying", async () => {
- let mode: string = "auto";
+test("switching to High without an OS sandbox opens the popup instead of applying", async () => {
const applied: string[] = [];
- let dialogs = 0;
- const set = (next: string) => {
- applied.push(next);
- mode = next;
- };
- const first = deferred<SandboxCapability | null>();
- const older = pickModule.pickSandboxedMode(
- set as never,
- () => dialogs++,
- () => mode as never,
- () => first.promise,
- );
- const newer = pickModule.pickSandboxedMode(
- set as never,
- () => dialogs++,
- () => mode as never,
- async () => capability({ pythonOsIsolated: false }),
+ let popups = 0;
+ await pickModule.pickSandboxLevel(
+ "high",
+ (level) => applied.push(level),
+ () => popups++,
+ async () => capability({ pythonOsIsolated: true }),
);
- await newer;
- first.resolve(null);
- await older;
- assert.equal(dialogs, 1);
assert.deepEqual(applied, []);
- await pickModule.pickSandboxedMode(
- set as never,
- () => dialogs++,
- () => mode as never,
- async () =>
- capability({ pythonOsIsolated: true, terminalOsIsolated: true }),
+ assert.equal(popups, 1);
+});
+
+test("an answer still unknown applies High; the backend still checks every call", async () => {
+ const applied: string[] = [];
+ await pickModule.pickSandboxLevel(
+ "high",
+ (level) => applied.push(level),
+ () => assert.fail("no popup while unknown"),
+ async () => capability({ pythonOsIsolated: true, backend: "unknown" }),
+ );
+ await pickModule.pickSandboxLevel(
+ "high",
+ (level) => applied.push(level),
+ () => assert.fail("no popup for an older server"),
+ async () => null,
);
- assert.deepEqual(applied, ["off"]);
+ assert.deepEqual(applied, ["high", "high"]);
});
-test("a sandbox already known to work applies Run automatically without a fresh probe", async () => {
+test("a switch made while a High check is in flight wins over that check", async () => {
const applied: string[] = [];
- let reads = 0;
- await pickModule.pickSandboxedMode(
- (next) => applied.push(next),
- () => assert.fail("no setup dialog"),
- () => "auto" as never,
- async () => {
- reads++;
- return null;
- },
- undefined,
- () => capability({ pythonOsIsolated: true, terminalOsIsolated: true }),
+ let popups = 0;
+ const read = deferred<SandboxCapability | null>();
+ const pending = pickModule.pickSandboxLevel(
+ "high",
+ (level) => applied.push(level),
+ () => popups++,
+ () => read.promise,
);
- assert.deepEqual(applied, ["off"]);
- assert.equal(reads, 0);
+ await pickModule.pickSandboxLevel("low", (level) => applied.push(level), () => popups++);
+ read.resolve(capability({ pythonOsIsolated: false }));
+ await pending;
+ assert.deepEqual(applied, ["low"]);
+ assert.equal(popups, 0);
});
type SetupState = typeof import("../src/features/chat/sandbox-setup-state.ts");
@@ -695,32 +666,6 @@ test("a failed install shows the job's command; a running one keeps the button",
assert.equal(running.installDisabled, true);
});
-test("a capability still unknown applies the mode instead of offering an install", async () => {
- let mode: string = "auto";
- const applied: string[] = [];
- let dialogs = 0;
- const set = (next: string) => {
- applied.push(next);
- mode = next;
- };
- await pickModule.pickSandboxedMode(
- set as never,
- () => dialogs++,
- () => mode as never,
- async () => capability({ pythonOsIsolated: true, backend: "unknown" }),
- );
- assert.deepEqual(applied, ["off"]);
- assert.equal(dialogs, 0);
- mode = "auto";
- await pickModule.pickSandboxedMode(
- set as never,
- () => dialogs++,
- () => mode as never,
- async () => capability({ pythonOsIsolated: true }),
- );
- assert.equal(dialogs, 1);
-});
-
test("an older capability read that finishes last never replaces a newer one", async () => {
const replies: Array<(response: Response) => void> = [];
const { api } = loadCapabilityApi(
@@ -747,3 +692,150 @@ test("an older capability read that finishes last never replaces a newer one", a
await stale;
assert.equal(api.cachedSandboxCapability(), null);
});
+
+function sandboxPopup(capabilityNow: SandboxCapability | null) {
+ const levels: string[] = [];
+ const opened: [string, unknown][] = [];
+ const state = { sandboxLevel: "low", setSandboxLevel: (level: string) => levels.push(level) };
+ const store = Object.assign(
+ (selector: (s: unknown) => unknown) => selector(state),
+ { getState: () => state },
+ );
+ const dialog = loadWithStubs<{
+ SandboxSetupDialog: (props: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onLearnMore?: () => void;
+ }) => StubElement;
+ }>(new URL("../src/features/chat/sandbox-setup-dialog.tsx", import.meta.url), {
+ "react/jsx-runtime": stubJsxRuntime(),
+ react: {
+ // The capability read has answered.
+ useState: (initial: unknown) => [initial === null ? capabilityNow : initial, () => {}],
+ useRef: (current: unknown) => ({ current }),
+ useEffect: () => {},
+ useCallback: (fn: unknown) => fn,
+ },
+ sonner: { toast: { success() {}, error() {} } },
+ zustand: {
+ create: (init: (set: unknown) => unknown) => {
+ const value = init(() => {});
+ return Object.assign((selector: (s: unknown) => unknown) => selector(value), {
+ getState: () => value,
+ });
+ },
+ },
+ "@/components/ui/alert-dialog": {
+ AlertDialog: "AlertDialog",
+ AlertDialogContent: "AlertDialogContent",
+ AlertDialogDescription: "AlertDialogDescription",
+ AlertDialogFooter: "AlertDialogFooter",
+ AlertDialogHeader: "AlertDialogHeader",
+ AlertDialogTitle: "AlertDialogTitle",
+ },
+ "@/components/ui/button": { Button: "Button" },
+ "@/components/ui/checkbox": { Checkbox: "Checkbox" },
+ "@/components/ui/spinner": { Spinner: "Spinner" },
+ "@/features/settings": {
+ useSettingsDialogStore: (selector: (s: unknown) => unknown) =>
+ selector({
+ openDialog: (tab: string, options?: { scrollTarget?: string }) => {
+ opened.push([tab, options?.scrollTarget]);
+ },
+ }),
+ },
+ "@/i18n": { useT: () => (key: string) => key },
+ "@/lib/copy-to-clipboard": { copyToClipboard: async () => true },
+ "./api/sandbox-capability": {
+ forgetSandboxCapability() {},
+ loadSandboxSetup: async () => setupJob({ state: "idle" as never }),
+ loadSettledSandboxCapability: async () => capabilityNow,
+ sandboxReady: (c: SandboxCapability) => c.pythonOsIsolated && c.terminalOsIsolated,
+ startSandboxSetup: async () => setupJob(),
+ },
+ "./sandbox-setup-state": setupState,
+ "./stores/chat-runtime-store": { useChatRuntimeStore: store },
+ });
+ const render = (props: { onLearnMore?: () => void } = {}) => {
+ const closes: boolean[] = [];
+ const root = dialog.SandboxSetupDialog({
+ open: true,
+ onOpenChange: (open) => closes.push(open),
+ ...props,
+ });
+ const inner = root.props.children as StubElement;
+ const content = (inner.type as (p: unknown) => StubElement)(inner.props);
+ const all: StubElement[] = [];
+ const walk = (node: unknown) => {
+ if (Array.isArray(node)) return node.forEach(walk);
+ if (node && typeof node === "object" && "props" in node) {
+ all.push(node as StubElement);
+ walk((node as StubElement).props.children);
+ }
+ };
+ walk(content);
+ const text = (el: StubElement) =>
+ ([] as unknown[]).concat(el.props.children).filter((c) => typeof c === "string").join("");
+ const button = (key: string) => {
+ const hit = all.find((el) => el.type === "Button" && text(el) === key);
+ assert.ok(hit, `no ${key} button`);
+ return hit.props.onClick as () => void;
+ };
+ const title = all.find((el) => el.type === "AlertDialogTitle");
+ return { closes, button, title: title ? text(title) : "", texts: all.map(text) };
+ };
+ return { render, levels, opened };
+}
+
+test("the High popup names the missing OS sandbox and offers Install, Learn more and Use Low", async () => {
+ const popup = sandboxPopup(capability());
+ const view = popup.render();
+ assert.equal(view.title, "sandboxSetup.levelTitle");
+ view.button("sandboxSetup.install");
+ view.button("sandboxSetup.copyCommand");
+ assert.ok(!view.texts.includes("sandboxSetup.useAnyway"));
+
+ view.button("sandboxSetup.useLow")();
+ assert.deepEqual(popup.levels, ["low"]);
+ assert.deepEqual(view.closes, [false]);
+
+ const other = popup.render();
+ other.button("settings.sandbox.learnMore")();
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ assert.deepEqual(other.closes, [false]);
+ assert.deepEqual(popup.opened, [["sandbox", "sandbox-permissions"]]);
+
+ let learned = 0;
+ const inSettings = popup.render({ onLearnMore: () => learned++ });
+ inSettings.button("settings.sandbox.learnMore")();
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ assert.equal(learned, 1);
+ assert.equal(popup.opened.length, 1, "Settings scrolls itself; it opens nothing");
+});
+
+test("the High popup stays short: no probe reason, no command block, a one-line Windows note", () => {
+ const noElevation = sandboxPopup(
+ capability({ canRunSetup: false, setupAction: null, setupBlocked: "no_elevation" }),
+ ).render();
+ noElevation.button("sandboxSetup.copyCommand");
+ for (const verbose of ["denied", "apt-get install -y bubblewrap", "sandboxSetup.runInTerminal", "sandboxSetup.commandHint"]) {
+ assert.ok(!noElevation.texts.includes(verbose), `popup shows ${verbose}`);
+ }
+
+ const windows = sandboxPopup(
+ capability({ platform: "windows", backend: "mxc-processcontainer", setupAction: "windows-setup", needsConsent: true }),
+ ).render();
+ windows.button("sandboxSetup.windowsSetup");
+ assert.ok(windows.texts.includes("sandboxSetup.windowsNote"));
+ assert.ok(!windows.texts.includes("settings.sandbox.disclosure"));
+});
+
+test("an install that makes the OS sandbox pass turns High on", () => {
+ const source = readFileSync(
+ new URL("../src/features/chat/sandbox-setup-dialog.tsx", import.meta.url),
+ "utf8",
+ );
+ const finish = source.slice(source.indexOf("const finish = useCallback("), source.indexOf("useEffect(() => {\n if (job?.state"));
+ assert.match(finish, /if \(next && sandboxReady\(next\)\) \{\s*if \(useChatRuntimeStore\.getState\(\)\.sandboxLevel === levelAtOpen\.current\) \{\s*setSandboxLevel\("high"\);/);
+ assert.doesNotMatch(source, /setPermissionMode/);
+});
diff --git a/studio/frontend/tests/settings-tab-visibility.test.ts b/studio/frontend/tests/settings-tab-visibility.test.ts
index 323b18db201..72e91db104a 100644
--- a/studio/frontend/tests/settings-tab-visibility.test.ts
+++ b/studio/frontend/tests/settings-tab-visibility.test.ts
@@ -20,11 +20,11 @@ test("the owner sees every settings tab", () => {
test("a managed account never sees a tab whose routes are all owner-only", () => {
const hidden = SETTINGS_TABS.filter((tab) => !settingsTabVisible(tab, false));
assert.deepEqual(new Set(hidden), OWNER_ONLY_SETTINGS_TABS);
- for (const tab of ["accounts", "resources", "remote-lan", "agents", "sandbox", "debugging"] as const) {
+ for (const tab of ["accounts", "resources", "remote-lan", "agents", "debugging"] as const) {
assert.ok(OWNER_ONLY_SETTINGS_TABS.has(tab), tab);
assert.equal(resolveSettingsTab(tab, false), "general");
}
- for (const tab of ["general", "api-keys", "data", "chat", "connections"] as const) {
+ for (const tab of ["general", "api-keys", "data", "chat", "connections", "sandbox"] as const) {
assert.equal(resolveSettingsTab(tab, false), tab);
}
});
diff --git a/tests/studio/playwright_chat_ui.py b/tests/studio/playwright_chat_ui.py
index 63e4b040ac2..5363890ec3c 100644
--- a/tests/studio/playwright_chat_ui.py
+++ b/tests/studio/playwright_chat_ui.py
@@ -399,12 +399,16 @@ def exercise_permission_mode_controls(page, shoot):
#
# So: wait for the level to actually be ON the installation before reloading and asserting on it. Assert what was
# achieved, not what was commanded.
- def expect_server_mode(expected, timeout_ms = 15_000):
+ def expect_server_mode(
+ expected,
+ timeout_ms = 15_000,
+ key = "permissionMode",
+ ):
deadline = time.monotonic() + timeout_ms / 1000.0
seen = "<never read>"
while True:
seen = page.evaluate(
- """async () => {
+ """async (key) => {
const token = localStorage.getItem("unsloth_auth_token");
const res = await fetch("/api/chat/settings", {
headers: token ? { Authorization: "Bearer " + token } : {},
@@ -412,8 +416,9 @@ def exercise_permission_mode_controls(page, shoot):
});
if (!res.ok) return "<http " + res.status + ">";
const body = await res.json();
- return (body && body.settings && body.settings.permissionMode) ?? null;
- }"""
+ return (body && body.settings && body.settings[key]) ?? null;
+ }""",
+ key,
)
if seen == expected:
return
@@ -422,7 +427,7 @@ def exercise_permission_mode_controls(page, shoot):
page.wait_for_timeout(100)
fail(
f"permission level never reached the installation: /api/chat/settings "
- f"reports permissionMode={seen!r} after {timeout_ms}ms, expected "
+ f"reports {key}={seen!r} after {timeout_ms}ms, expected "
f"{expected!r} -- the debounced mirror never landed"
)
@@ -540,7 +545,8 @@ def exercise_permission_mode_controls(page, shoot):
reload_and_wait_for_pill()
expect_mode("Run automatically")
- # Without a sandbox: Cancel keeps the previous level, "Use it anyway" applies it.
+ # Without a sandbox: Run automatically applies at once, the Sandbox switch reads Low, and sliding it
+ # to High opens the install popup, whose "Use Low sandbox" keeps Low.
choose("Approve for me")
expect_mode("Approve for me")
# Landed on the install first, or the reload hydrates the previous "off" back.
@@ -549,22 +555,49 @@ def exercise_permission_mode_controls(page, shoot):
reload_and_wait_for_pill()
expect_mode("Approve for me")
choose("Run automatically")
+ expect_mode("Run automatically")
+ if page.get_by_role("alertdialog").count() != 0:
+ fail("picking Run automatically without a sandbox opened a dialog")
+ # Reopening the menu straight after a pick races its close; a reload also proves the level persisted.
+ # Landed on the install first, or the reload hydrates the previous "auto" back.
+ expect_server_mode("off")
+ reload_and_wait_for_pill()
+ expect_mode("Run automatically")
+ menu = open_menu()
+ expect(menu.get_by_text("Permissions", exact = True)).to_be_visible()
+ if menu.get_by_text("OS sandbox not available").count() != 0:
+ fail("the Run automatically row still carries the 'OS sandbox not available' hint")
+ switch = menu.get_by_role("menuitemcheckbox")
+ expect(switch).to_have_attribute("aria-checked", "false")
+ expect(switch).to_contain_text("Low")
+ switch.click()
setup = page.get_by_role("alertdialog")
- expect(setup.get_by_role("heading", name = "No OS sandbox on this computer yet")).to_be_visible()
- expect(setup).to_contain_text("apt-get install -y bubblewrap")
+ expect(setup.get_by_role("heading", name = "OS sandbox is not available")).to_be_visible()
+ # The command rides on Copy command (and Settings > Sandbox), not as a block of text in the popup.
+ expect(setup).not_to_contain_text("apt-get install -y bubblewrap")
expect(setup.get_by_role("button", name = "Copy command")).to_be_visible()
+ expect(setup.get_by_role("button", name = "Copy command")).to_have_attribute(
+ "title", re.compile(r"apt-get install -y bubblewrap")
+ )
+ expect(setup.get_by_role("button", name = "Learn more")).to_be_visible()
if setup.get_by_role("button", name = "Install sandbox").count() != 0:
- fail("setup dialog offered Install sandbox to a request the server did not allow")
- setup.get_by_role("button", name = "Cancel").click()
- expect(setup).to_be_hidden()
- expect_mode("Approve for me")
- choose("Run automatically")
- expect(setup).to_be_visible()
- setup.get_by_role("button", name = "Use it anyway (risky calls will ask)").click()
+ fail("setup popup offered Install sandbox to a request the server did not allow")
+ setup.get_by_role("button", name = "Use Low sandbox").click()
expect(setup).to_be_hidden()
+ level = page.evaluate("() => localStorage.getItem('unsloth_chat_sandbox_level')")
+ if level != "low":
+ fail(f"Use Low sandbox stored {level!r}, expected 'low'")
expect_mode("Run automatically")
+ expect_server_mode("low", key = "sandboxLevel")
sandbox_answer["ready"] = True
reload_and_wait_for_pill()
+ # With a working sandbox the switch turns High again, and stays High for the next browser's run.
+ switch = open_menu().get_by_role("menuitemcheckbox")
+ expect(switch).to_contain_text("Low")
+ switch.click()
+ page.wait_for_function("() => localStorage.getItem('unsloth_chat_sandbox_level') === 'high'")
+ page.keyboard.press("Escape")
+ expect_server_mode("high", key = "sandboxLevel")
# Leave the full chat smoke in the fresh-install default.
choose("Approve for me")