Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: add a Sandbox settings tab with a Windows MXC opt-in and one-click host preparation (#12215)
Daniel Hanf57a7deea98e
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 1c0f6cfe8db..97bcdcb82f0 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -36319,7 +36319,6 @@ class LlamaCppBackend:build_rag_autoinject,execute_tool,has_text_only_provisional_card,- is_always_safe_tool,is_high_risk_tool_call,mcp_image_share,never_needs_approval,@@ -36330,7 +36329,13 @@ class LlamaCppBackend:# "auto"; unknown falls back to the stricter "ask". An explicit# confirm_tool_calls=True with no mode is already resolved to "ask" at the# request layer, so it never arrives here as an ambiguous unset.- from state.tool_policy import account_tool_stream, normalize_tool_permissions+ from state.tool_policy import (+ account_tool_stream,+ needs_tool_confirmation,+ normalize_tool_permissions,+ requires_os_isolation,+ tool_call_may_prompt,+ )permission_mode, bypass_permissions = normalize_tool_permissions(permission_mode, bypass_permissions@@ -37439,11 +37444,11 @@ class LlamaCppBackend:# prompts, so it must stream its early card too; mirror# that here instead of gating on the raw confirm flag._confirm_gated = (- confirm_tool_calls- and not bypass_permissions- and not (- permission_mode == "auto"- and is_always_safe_tool(current_name)+ tool_call_may_prompt(+ confirm_tool_calls = bool(confirm_tool_calls),+ bypass_permissions = bypass_permissions,+ permission_mode = permission_mode,+ name = current_name,)# A text-preview card still streams while gated;# hiding it blanks the chat.@@ -37586,6 +37591,15 @@ class LlamaCppBackend:_sniffedand not (_confirm_gated_iteration+ and (+ permission_mode != "off"+ or tool_call_may_prompt(+ confirm_tool_calls = True,+ bypass_permissions = False,+ permission_mode = "off",+ name = _sniffed,+ )+ )and not has_text_only_provisional_card(_sniffed)@@ -38572,21 +38586,29 @@ class LlamaCppBackend:)# Bypass wins here too, so a direct internal caller with both- # flags never prompts. "auto" pauses only high-risk calls;- # "off" never prompts (sandbox stays on).- needs_confirm = (- bool(confirm_tool_calls)- and not bypass_permissions- and permission_mode != "off"- and not never_needs_approval(decision.tool_name)+ # flags never prompts. "auto" pauses only high-risk calls; "off"+ # pauses only a high-risk python/terminal call without OS isolation.+ needs_confirm = needs_tool_confirmation(+ confirm_tool_calls = bool(confirm_tool_calls),+ bypass_permissions = bypass_permissions,+ permission_mode = permission_mode,+ name = decision.tool_name,+ arguments = decision.arguments,+ is_high_risk = is_high_risk_tool_call,+ never_needs = never_needs_approval,)- if needs_confirm and permission_mode == "auto":- needs_confirm = is_high_risk_tool_call(- decision.tool_name, decision.arguments- )# Sending the user's image always asks, whatever the permission mode.image_share = mcp_image_share(decision.tool_name, decision.arguments, mcp_image)needs_confirm = needs_confirm or image_share is not None+ strict_isolation = requires_os_isolation(+ confirm_tool_calls = bool(confirm_tool_calls),+ bypass_permissions = bypass_permissions,+ permission_mode = permission_mode,+ name = decision.tool_name,+ arguments = decision.arguments,+ prompted = needs_confirm,+ is_high_risk = is_high_risk_tool_call,+ )approval_id = new_approval_id() if needs_confirm else ""decision_slot = (begin_tool_decision(session_id, approval_id) if needs_confirm else None@@ -38940,6 +38962,7 @@ class LlamaCppBackend:_output_callback,_decision = decision,_approved = _host_access_approved,+ _strict = strict_isolation,):# execute_tool is injectable and may be monkey-patched with the# pre-PR signature; forward output_callback only if it's accepted.@@ -38951,6 +38974,9 @@ class LlamaCppBackend:rag_scope = rag_scope,disable_sandbox = bypass_permissions,)+ # 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"# 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/mxc_host_prep_job.py b/studio/backend/core/inference/mxc_host_prep_job.pynew file mode 100644index 00000000000..0dc8f2e9b8e--- /dev/null+++ b/studio/backend/core/inference/mxc_host_prep_job.py@@ -0,0 +1,141 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""One-click MXC host preparation from Settings: the elevated `--prepare-host` run as a background job."""++from __future__ import annotations++from collections import deque+from dataclasses import asdict, dataclass, field+import logging+import subprocess+import sys+import threading+import time+from typing import Callable+import uuid++logger = logging.getLogger(__name__)++OUTPUT_TAIL_LINES = 20+_DECLINED_MARKER = "administrator prompt was declined"+_PREPARED_PREFIX = "[mxc-prebuilt] host prepared:"+_ALREADY_PREPARED = "[mxc-prebuilt] host already prepared"++_lock = threading.Lock()+# Shared with the Settings setup job: never two elevated helpers.+HOST_CHANGE_LOCK = threading.Lock()+_current: "HostPrepJob | None" = None+_on_finish: list[Callable[[], None]] = []+++@dataclass+class HostPrepJob:+ id: str+ state: str = "running" # running | succeeded | declined | failed+ started_at: float = field(default_factory = time.time)+ finished_at: float | None = None+ exit_code: int | None = None+ output_tail: list[str] = field(default_factory = list)+ steps: list[str] = field(default_factory = list)++ def as_dict(self) -> dict:+ return asdict(self)+++def current() -> HostPrepJob | None:+ with _lock:+ return _current+++def add_finish_hook(hook: Callable[[], None]) -> None:+ if hook not in _on_finish:+ _on_finish.append(hook)+++def _steps(lines: list[str]) -> list[str]:+ for line in reversed(lines):+ text = line.strip()+ if text.startswith(_PREPARED_PREFIX):+ return [s.strip() for s in text[len(_PREPARED_PREFIX) :].split(",") if s.strip()]+ if text.startswith(_ALREADY_PREPARED):+ return []+ return []+++def _spawn(argv: list[str]) -> subprocess.Popen:+ from utils.process_lifetime import child_popen_kwargs, spawn_on_lifetime_thread++ kwargs = dict(+ stdin = subprocess.DEVNULL,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ **child_popen_kwargs(),+ )+ if sys.platform == "win32":+ kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW+ return spawn_on_lifetime_thread(lambda: subprocess.Popen(argv, **kwargs))+++def _invalidate() -> None:+ from . import mxc_probe, tools+ for reset in (mxc_probe.invalidate_cache, tools.reset_terminal_profile_cache, *_on_finish):+ try:+ reset()+ except Exception as exc: # noqa: BLE001 - a stale cache only delays the new verdict+ logger.warning("MXC host preparation: cache reset failed: %s", exc)+++def _run(job: HostPrepJob, proc: subprocess.Popen) -> None:+ tail: deque[str] = deque(maxlen = OUTPUT_TAIL_LINES)+ try:+ for line in proc.stdout:+ tail.append(line.rstrip("\r\n"))+ job.output_tail = list(tail)+ # No timeout: killing the helper mid ACL propagation would leave the host half prepared.+ code = proc.wait()+ except Exception as exc: # noqa: BLE001 - reported on the job, never raised into a thread+ tail.append(f"Unsloth lost track of the preparation run: {exc}")+ code = None+ lines = list(tail)+ job.output_tail = lines+ job.exit_code = code+ job.steps = _steps(lines)+ job.finished_at = time.time()+ if code == 0:+ state = "succeeded"+ elif any(_DECLINED_MARKER in line for line in lines):+ state = "declined"+ else:+ state = "failed"+ logger.info("MXC host preparation finished: state=%s exit=%s", state, code)+ # Caches first: a poller that sees the end must not then read the pre-preparation verdict.+ _invalidate()+ job.state = state+++def start() -> HostPrepJob:+ global _current+ from . import mxc_probe, sandbox_setup_job, sandbox_setup_plan++ with HOST_CHANGE_LOCK:+ setup = sandbox_setup_job.current()+ if setup is not None and setup.state == "running":+ # Only the chained setup ends in this preparation; a runtime-only install never does.+ return sandbox_setup_job._joined(setup, sandbox_setup_plan.WINDOWS_SETUP)+ with _lock:+ if _current is not None and _current.state == "running":+ return _current+ job = HostPrepJob(id = uuid.uuid4().hex)+ try:+ proc = _spawn(mxc_probe.host_prep_command())+ except Exception as exc: # noqa: BLE001 - surfaced as a failed job+ job.state, job.finished_at = "failed", time.time()+ job.output_tail = [f"Could not start the host preparation: {exc}"]+ _current = job+ return job+ _current = job+ threading.Thread(target = _run, args = (job, proc), name = "mxc-host-prep", daemon = True).start()+ return jobdiff --git a/studio/backend/core/inference/mxc_policy.py b/studio/backend/core/inference/mxc_policy.pyindex 4a346653f53..d6c4ffe5a0d 100644--- a/studio/backend/core/inference/mxc_policy.py+++ b/studio/backend/core/inference/mxc_policy.py@@ -58,8 +58,14 @@ class MxcPolicyError(RuntimeError):def dacl_fallback_enabled() -> bool:- """Host opt-in to MXC's AppContainer tier, which temporarily adds ACEs to the granted host paths."""- return os.environ.get(DACL_FALLBACK_ENV, "").strip() == "1"+ """Opt-in to the AppContainer tier (temporarily adds ACEs); env var if set, else the saved choice."""+ if DACL_FALLBACK_ENV in os.environ:+ return os.environ[DACL_FALLBACK_ENV].strip() == "1"+ try:+ from utils.mxc_isolation_settings import dacl_fallback_setting+ return dacl_fallback_setting()+ except Exception: # noqa: BLE001 - outside the backend (installer, probe child) there is no setting+ return Falsedef _reject_grants_over_dacl_journal(grants: list[str]) -> None:@@ -438,6 +444,8 @@ def build_launch_request(readonly = _without_nested(runtime_roots + _model_read_roots(workdir, runtime_roots))_reject_grants_over_dacl_journal([workdir, *readonly])# Tier 3 walks every readonly tree per launch; a one-time grant on the runtime folders skips it.+ # Read fresh: a grant made on a stale cached "on" would outlive another process's opt-out.+ mxc_read_grants.refresh_saved_switches()if dacl_fallback_enabled():mxc_read_grants.ensure(runtime_roots)else:diff --git a/studio/backend/core/inference/mxc_probe.py b/studio/backend/core/inference/mxc_probe.pyindex a3cca4b580a..fffd003eb6e 100644--- a/studio/backend/core/inference/mxc_probe.py+++ b/studio/backend/core/inference/mxc_probe.py@@ -15,7 +15,7 @@ import threadingimport timefrom types import SimpleNamespace-from . import mxc_adapter, mxc_drive_alias, mxc_policy, mxc_runtime+from . import mxc_adapter, mxc_drive_alias, mxc_policy, mxc_read_grants, mxc_runtime_lock = threading.Lock()_cache: dict[tuple, tuple[float, bool, str]] = {}@@ -37,6 +37,21 @@ def invalidate_cache() -> None:with _lock:_cache.clear()_host_prep_cache.clear()+ # Only when already loaded: the MXC child paths import this module without the tool stack.+ os_sandbox = sys.modules.get(f"{__package__}.os_sandbox")+ if os_sandbox is not None:+ os_sandbox.forget_tool_isolation()+++def host_prep_command() -> list[str]:+ """The elevated host preparation, as argv; Settings > Sandbox runs exactly this."""+ return [+ sys.executable,+ str(Path(__file__).resolve().parents[3] / "install_mxc_prebuilt.py"),+ "--prepare-host",+ "--install-dir",+ str(mxc_runtime._installed_package_root()),+ ]def host_prep_remediation() -> str | None:@@ -52,15 +67,7 @@ def host_prep_remediation() -> str | None:steps = mxc_runtime.probe_host_prep_steps(env = mxc_adapter._control_environment())advice = Noneif steps:- command = subprocess.list2cmdline(- [- sys.executable,- str(Path(__file__).resolve().parents[3] / "install_mxc_prebuilt.py"),- "--prepare-host",- "--install-dir",- str(mxc_runtime._installed_package_root()),- ]- )+ command = subprocess.list2cmdline(host_prep_command())reboot = (" (prepare-null-device is undone by every reboot)"if ("prepare-null-device" in steps)@@ -68,7 +75,8 @@ def host_prep_remediation() -> str | None:)advice = (f"MXC reports missing host preparation: {', '.join(steps)}{reboot}. "- f"Run {command} and approve the administrator prompt."+ f"Run {command} and approve the administrator prompt, or use Settings > Sandbox > "+ "Prepare this PC.")with _lock:_host_prep_cache[identity] = (time.monotonic() + NEGATIVE_TTL, advice)@@ -240,7 +248,10 @@ def _probe()except Exception:lease = None+ grant_lease = Nonetry:+ # The probe reads Python through the same grants, so a revocation waits for it too.+ grant_lease = mxc_read_grants.hold_if_needed()request = (mxc_policy.build_launch_request(probe_plan, cwd_alias = lease.root)if lease@@ -284,6 +295,8 @@ def _probe(mxc_adapter.release_runtime(proc)if lease is not None:lease.release()+ if grant_lease is not None:+ grant_lease.release()if (proc.returncode != 0or result.get("exitCode") != 0diff --git a/studio/backend/core/inference/mxc_read_grants.py b/studio/backend/core/inference/mxc_read_grants.pyindex 255d3a3e212..392fbca4d3d 100644--- a/studio/backend/core/inference/mxc_read_grants.py+++ b/studio/backend/core/inference/mxc_read_grants.py@@ -53,7 +53,14 @@ def _on_windows() -> bool:def enabled() -> bool:- return os.environ.get(PERSISTENT_GRANTS_ENV, "").strip() != "0"+ """The environment variable decides whenever it is set; otherwise the Settings > Sandbox choice."""+ if PERSISTENT_GRANTS_ENV in os.environ:+ return os.environ[PERSISTENT_GRANTS_ENV].strip() != "0"+ try:+ from utils.mxc_isolation_settings import persistent_grants_setting+ return persistent_grants_setting()+ except Exception: # noqa: BLE001 - outside the backend the shipped default applies+ return Truedef record_path() -> Path:@@ -472,8 +479,111 @@ def ensure(roots: list[str]) -> tuple[str, ...]:return tuple(covered)+def _leases_dir() -> Path:+ return record_path().parent / "read-grant-users"+++def _lease_is_live(path: Path) -> bool:+ """Windows refuses to delete a file a process still holds open, so a crashed holder's lease goes."""+ try:+ path.unlink()+ except FileNotFoundError:+ return False+ except OSError:+ return True+ return False+++def _live_leases() -> int:+ try:+ entries = list(_leases_dir().iterdir())+ except OSError:+ return 0+ return sum(_lease_is_live(entry) for entry in entries)+++class WorkloadLease:+ """Held open for one MXC workload's lifetime: the ACEs it may have skipped stay until release."""++ def __init__(self, path: Path, handle):+ self._path, self._handle = path, handle++ def release(self) -> None:+ if self._handle is None:+ return+ self._handle.close()+ self._handle = None+ with contextlib.suppress(OSError):+ self._path.unlink()+ _revoke_if_turned_off()+++def hold() -> WorkloadLease | None:+ """Mark a launch as relying on the grants from spawn to exit, across Studio processes.++ Raises ReadGrantError when the lease cannot be recorded: a launch that may skip wxc-exec's own+ grant must not run with nothing stopping a revocation under it.+ """+ if not _on_windows():+ return None+ path = _leases_dir() / f"{os.getpid()}-{uuid.uuid4().hex}"+ try:+ # Under the record lock: a revocation either finished before this or sees the lease.+ with _transaction():+ path.parent.mkdir(parents = True, exist_ok = True)+ handle = open(path, "w", encoding = "utf-8")+ except OSError as exc:+ raise ReadGrantError(+ f"could not record this MXC workload for the read grants: {exc}"+ ) from exc+ return WorkloadLease(path, handle)+++def hold_if_needed() -> WorkloadLease | None:+ """A lease for every MXC launch or probe, so no revocation runs under it.++ Taken while a switch is off too: a revocation deferred for a running workload leaves the entries+ in place (wxc-exec then skips its own grant), and a switch turned on before the request is built+ installs them. Only a launch that needs the grants refuses when the lease cannot be recorded.+ """+ from . import mxc_policy++ refresh_saved_switches()+ needed = mxc_policy.dacl_fallback_enabled() and enabled()+ try:+ return hold()+ except ReadGrantError:+ if needed:+ raise+ return None+++def refresh_saved_switches() -> None:+ """Drop this process's 1 s settings cache: another Studio process may have just turned a switch off."""+ try:+ from utils.mxc_isolation_settings import forget_cached_setting+ forget_cached_setting()+ except Exception: # noqa: BLE001 - outside the backend there is no saved setting to cache+ pass+++def _revoke_if_turned_off() -> None:+ """Finish a revocation the settings switch or an earlier launch deferred for running workloads."""+ try:+ from . import mxc_policy+ refresh_saved_switches()+ if not (mxc_policy.dacl_fallback_enabled() and enabled()):+ revoke_recorded()+ except Exception as exc: # noqa: BLE001 - cleanup, the next launch or check retries+ logger.warning("Deferred MXC read-grant cleanup failed: %s", exc)++def revoke_recorded() -> tuple[str, ...]:- """Remove every grant Studio recorded; returns the roots that were restored."""+ """Remove every grant Studio recorded; returns the roots that were restored.++ Waits while an MXC workload holds a lease: its container may read through these ACEs, so the+ last lease to release finishes the job.+ """if not _on_windows() or not record_path().exists():return ()restored: list[str] = []@@ -488,6 +598,12 @@ def revoke_recorded() -> tuple[str, ...]:stack.push(transaction)if not record:return ()+ running = _live_leases()+ if running:+ logger.info(+ "Deferring the MXC read-grant cleanup until %d running call(s) exit", running+ )+ return ()for key in list(record):if _revoke_recorded_root(record, key) == "revoked":restored.append(key)diff --git a/studio/backend/core/inference/os_sandbox.py b/studio/backend/core/inference/os_sandbox.pyindex fb04119f794..caa5ccf5c29 100644--- a/studio/backend/core/inference/os_sandbox.py+++ b/studio/backend/core/inference/os_sandbox.py@@ -874,6 +874,159 @@ def capability_snapshot()+# Last answer per tool; the "off" permission gate reads it on every call without probing.+_TOOL_ISOLATION_TTL_SECONDS = 60.0+ISOLATED_TOOLS = ("python", "terminal")+_tool_isolation_lock = threading.Lock()+_tool_isolation: dict[str, tuple[float, bool, str, str]] = {}+_tool_isolation_refreshing: set[str] = set()+# Every check takes a number when it starts; a reset raises the floor. An answer from a check that+# started before the reset, or before the one already recorded for that tool, is dropped.+_tool_isolation_generation = 0+_tool_isolation_floor = 0+_tool_isolation_noted: dict[str, int] = {}+++# Set to 1: no startup or background probes; only real launches update the answer.+WARMUP_DISABLE_ENV = "UNSLOTH_DISABLE_SANDBOX_WARMUP"+++def _background_probes_disabled() -> bool:+ return os.environ.get(WARMUP_DISABLE_ENV, "").strip() == "1"+++def tool_isolation_target(tool: str) -> str | None:+ if tool == "python":+ return sys.executable+ if sys.platform != "win32":+ return shutil.which("bash") or "bash"+ from . import tools++ if tools._terminal_profile(False) == "cmd_isolated":+ return tools._windows_system_cmd()+ return tools._windows_bash() or tools._windows_system_cmd()+++def note_tool_isolation(+ tool: str | None,+ available: bool,+ *,+ backend: str = "",+ reason: str = "",+ generation: int | None = None,+) -> None:+ global _tool_isolation_generation+ if tool not in ISOLATED_TOOLS:+ return+ with _tool_isolation_lock:+ if generation is None:+ _tool_isolation_generation += 1+ generation = _tool_isolation_generation+ elif generation < _tool_isolation_floor or generation < _tool_isolation_noted.get(tool, 0):+ return+ _tool_isolation_noted[tool] = generation+ _tool_isolation[tool] = (time.monotonic(), bool(available), backend, reason)+++def tool_isolation_generation() -> int:+ """Take before a check and pass to note_tool_isolation(generation=...): an older check stays out."""+ global _tool_isolation_generation+ with _tool_isolation_lock:+ _tool_isolation_generation += 1+ return _tool_isolation_generation+++def forget_tool_isolation() -> None:+ global _tool_isolation_floor+ with _tool_isolation_lock:+ _tool_isolation.clear()+ _tool_isolation_noted.clear()+ _tool_isolation_floor = _tool_isolation_generation + 1+++def refresh_tool_isolation(tool: str, *, force: bool = False) -> bool:+ """Blocking: the capability for one tool, remembered for cached_tool_isolation."""+ generation = tool_isolation_generation()+ try:+ capability = capability_snapshot(+ force = force,+ execution_kind = tool,+ selected_executable = tool_isolation_target(tool),+ )+ available, backend, reason = (+ bool(capability.available),+ capability.backend,+ capability.reason,+ )+ except Exception as exc: # noqa: BLE001 - an unknown answer reads as not isolated+ logger.debug("tool isolation refresh for %s failed: %s", tool, exc)+ available, backend, reason = False, "none", f"the capability check failed: {exc}"+ note_tool_isolation(tool, available, backend = backend, reason = reason, generation = generation)+ return available+++def _refresh_tool_isolation_in_background(tool: str) -> None:+ try:+ refresh_tool_isolation(tool)+ finally:+ with _tool_isolation_lock:+ _tool_isolation_refreshing.discard(tool)+++def has_tool_isolation_answer(tool: str) -> bool:+ with _tool_isolation_lock:+ return tool in _tool_isolation+++def cached_tool_isolation(tool: str) -> bool | None:+ """Never blocks: whether ``tool`` last qualified for OS isolation (None before the first answer)."""+ cached = cached_tool_capability(tool)+ return None if cached is None else cached[0]+++def cached_tool_capability(tool: str) -> tuple[bool, str, str] | None:+ """Never blocks: last (available, backend, reason) or None; stale starts a background refresh."""+ now = time.monotonic()+ with _tool_isolation_lock:+ entry = _tool_isolation.get(tool)+ start = (+ tool in ISOLATED_TOOLS+ and not _background_probes_disabled()+ and (entry is None or now - entry[0] >= _TOOL_ISOLATION_TTL_SECONDS)+ and tool not in _tool_isolation_refreshing+ )+ if start:+ _tool_isolation_refreshing.add(tool)+ if start:+ try:+ threading.Thread(+ target = _refresh_tool_isolation_in_background,+ args = (tool,),+ name = f"unsloth-tool-isolation-{tool}",+ daemon = True,+ ).start()+ except RuntimeError:+ with _tool_isolation_lock:+ _tool_isolation_refreshing.discard(tool)+ return None if entry is None else (entry[1], entry[2], entry[3])+++def warm_tool_isolation() -> None:+ for tool in ISOLATED_TOOLS:+ refresh_tool_isolation(tool)+++def start_tool_isolation_warmup() -> threading.Thread | None:+ """warm_tool_isolation on a daemon thread. Not on Windows: the MXC check launches a container."""+ if _background_probes_disabled() or sys.platform == "win32":+ return None+ thread = threading.Thread(+ target = warm_tool_isolation, name = "unsloth-sandbox-warmup", daemon = True+ )+ thread.start()+ return thread++def _record(plan: ToolLaunchPlan,capability: SandboxCapability,@@ -941,12 +1094,22 @@ def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:),)+ # 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(execution_kind = plan.execution_kind,selected_executable = plan.argv[0] if plan.argv else None,cancel_event = plan.cancel_event,)+ note_tool_isolation(+ plan.execution_kind,+ capability.available,+ backend = capability.backend,+ reason = capability.reason,+ generation = generation,+ )+if plan.cancel_event is not None and plan.cancel_event.is_set():raise SandboxBuildError("execution cancelled before sandbox launch")@@ -997,6 +1160,14 @@ def prepare_tool_launch(plan: ToolLaunchPlan) -> PreparedSandboxLaunch:"and `required` cannot promise a boundary it did not verify. ""Start a new chat, or use `auto` to run with software safeguards.")+ except (WorkdirUnsafeError, SandboxBuildError):+ raise # can be tool-induced; says nothing about the backend itself+ except SandboxUnavailableError:+ # The cached pass is stale (bwrap removed or no longer trusted): the next call checks again,+ # so "off" asks instead of skipping the prompt and failing until the cache expires.+ from .sandbox_probe import reset_probe_cache+ reset_probe_cache()+ raiseexcept OSError as exc:# Must be typed: raw, tools.py's general except would fall back to software safeguards.raise SandboxBuildError(f"the sandbox could not be built on this host: {exc}") from excdiff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.pyindex 2f5f8ce3327..4dea3918ac9 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -680,7 +680,13 @@ def run_safetensors_tool_loop(# no mode is already resolved to "ask" at the request layer, so it never# arrives here as an ambiguous unset.from core.inference.tool_stream_exec import stream_tool_execution- from state.tool_policy import account_tool_stream, normalize_tool_permissions+ from state.tool_policy import (+ account_tool_stream,+ needs_tool_confirmation,+ normalize_tool_permissions,+ requires_os_isolation,+ tool_call_may_prompt,+ )permission_mode, bypass_permissions = normalize_tool_permissions(permission_mode, bypass_permissions@@ -852,12 +858,11 @@ def run_safetensors_tool_loop(# as "running" before the user has approved it. Suppress the early card in that case. In auto mode render_html# is always safe and never prompts, so keep its early canvas card; mirrors the GGUF path's _confirm_gated# exemption.- from core.inference.tools import is_always_safe_tool-- _provisional_confirm_gated = (- bool(confirm_tool_calls)- and not bypass_permissions- and not (permission_mode == "auto" and is_always_safe_tool("render_html"))+ _provisional_confirm_gated = tool_call_may_prompt(+ confirm_tool_calls = bool(confirm_tool_calls),+ bypass_permissions = bypass_permissions,+ permission_mode = permission_mode,+ name = "render_html",)def _should_start_provisional_render_html(content: str) -> bool:@@ -1492,22 +1497,28 @@ def run_safetensors_tool_loop(assistant_msg.setdefault("tool_calls", []).append(decision.as_assistant_tool_call())# Bypass wins here too, so a direct internal caller with both flags- # never prompts. "auto" pauses only high-risk calls; "off" never- # prompts (sandbox stays on).- from core.inference.tools import mcp_image_share, never_needs_approval-- needs_confirm = (- bool(confirm_tool_calls)- and not bypass_permissions- and permission_mode != "off"- and not never_needs_approval(decision.tool_name)+ # never prompts. "auto" pauses only high-risk calls; "off" pauses only a+ # high-risk python/terminal call without OS isolation.+ from core.inference.tools import mcp_image_share++ needs_confirm = needs_tool_confirmation(+ confirm_tool_calls = bool(confirm_tool_calls),+ bypass_permissions = bypass_permissions,+ permission_mode = permission_mode,+ name = decision.tool_name,+ arguments = decision.arguments,)- if needs_confirm and permission_mode == "auto":- from core.inference.tools import is_high_risk_tool_call- needs_confirm = is_high_risk_tool_call(decision.tool_name, decision.arguments)# Sending the user's image always asks, whatever the permission mode.image_share = mcp_image_share(decision.tool_name, decision.arguments, mcp_image)needs_confirm = needs_confirm or image_share is not None+ strict_isolation = requires_os_isolation(+ confirm_tool_calls = bool(confirm_tool_calls),+ bypass_permissions = bypass_permissions,+ permission_mode = permission_mode,+ name = decision.tool_name,+ arguments = decision.arguments,+ prompted = needs_confirm,+ )approval_id = new_approval_id() if needs_confirm else ""decision_slot = begin_tool_decision(session_id, approval_id) if needs_confirm else Nonestart_event = decision.tool_start_event()@@ -1595,6 +1606,7 @@ def run_safetensors_tool_loop(_output_callback,_decision = decision,_approved = _host_access_approved,+ _strict = strict_isolation,):kwargs = dict(cancel_event = cancel_event,@@ -1604,6 +1616,9 @@ def run_safetensors_tool_loop(rag_scope = rag_scope,disable_sandbox = bypass_permissions,)+ # 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"if _accepts_kwarg(execute_tool, "conversation_branch"):kwargs["conversation_branch"] = request_branchif _approved and _accepts_kwarg(execute_tool, "host_access_approved"):diff --git a/studio/backend/core/inference/sandbox_probe.py b/studio/backend/core/inference/sandbox_probe.pyindex 491f1ccd632..c0e81c0c042 100644--- a/studio/backend/core/inference/sandbox_probe.py+++ b/studio/backend/core/inference/sandbox_probe.py@@ -41,37 +41,94 @@ _CACHE_MAX_ENTRIES = 8# ``sun_path`` is 108 bytes and multiprocessing appends about 32._MAX_PROBE_BASE_LEN = 59+# A stale PASS is served while one background re-probe runs; a FAIL never is.+_STALE_GRACE_SECONDS = 3600.0+_cache_lock = threading.Lock()_cache: dict[tuple[str, str], tuple[float, bool, str]] = {}+_refreshing: set[tuple[str, str]] = set()+_generation = 0def reset_probe_cache() -> None:- """Forget every cached verdict. For tests only."""+ """Forget every cached verdict (tests, and a launch that failed under a cached PASS)."""+ global _generationwith _cache_lock:_cache.clear()+ _generation += 1+ try:+ from .os_sandbox import forget_tool_isolation+ except Exception: # noqa: BLE001 - a partially imported package has nothing cached yet+ return+ forget_tool_isolation()-def _cache_get(key: tuple[str, str]) -> tuple[bool, str] | None:+def _cache_get(key: tuple[str, str]) -> tuple[bool, str, bool] | None:+ """(available, reason, stale); None when nothing may be served."""now = time.monotonic()with _cache_lock:entry = _cache.get(key)if entry is None:return Noneexpires_at, available, reason = entry- if expires_at <= now:- _cache.pop(key, None)- return None- return available, reason---def _cache_put(key: tuple[str, str], available: bool, reason: str) -> None:+ if expires_at > now:+ return available, reason, False+ if available and now < expires_at + _STALE_GRACE_SECONDS:+ return available, reason, True+ _cache.pop(key, None)+ return None+++def _cache_put(+ key: tuple[str, str],+ available: bool,+ reason: str,+ *,+ generation: int | None = None,+) -> None:with _cache_lock:+ if generation is not None and generation != _generation:+ returnttl = _CACHE_TTL_SECONDS if available else _CACHE_TTL_UNAVAILABLE_SECONDS+ _cache.pop(key, None)_cache[key] = (time.monotonic() + ttl, available, reason)while len(_cache) > _CACHE_MAX_ENTRIES:_cache.pop(next(iter(_cache)))+def _background_probes_disabled() -> bool:+ try:+ from .os_sandbox import _background_probes_disabled as disabled+ except Exception: # noqa: BLE001 - a partially imported package: stay in the foreground+ return True+ return disabled()+++def _refresh_in_background(backend: Any, key: tuple[str, str]) -> None:+ with _cache_lock:+ if key in _refreshing:+ return+ _refreshing.add(key)+ generation = _generation++ def run() -> None:+ try:+ from .os_sandbox import ToolLaunchPlan+ available, reason = _run_probe(backend, key[0], ToolLaunchPlan)+ _cache_put(key, available, reason, generation = generation)+ except Exception as exc: # noqa: BLE001 - the stale PASS just ages out+ logger.debug("background sandbox re-probe failed: %s", exc)+ finally:+ with _cache_lock:+ _refreshing.discard(key)++ try:+ threading.Thread(target = run, name = "unsloth-sandbox-reprobe", daemon = True).start()+ except RuntimeError:+ with _cache_lock:+ _refreshing.discard(key)++_PREAMBLE = '''import multiprocessing.reduction, os, socket, subprocess, sys@@ -289,10 +346,18 @@ def probe(backend: Any, *, force: bool = False) -> tuple[bool, str]:if not force:cached = _cache_get(key)if cached is not None:- return cached+ available, reason, stale = cached+ if not stale:+ return available, reason+ if not _background_probes_disabled():+ _refresh_in_background(backend, key)+ return available, reason+ # Background probes are off: re-probe here.+ with _cache_lock:+ generation = _generationavailable, reason = _run_probe(backend, backend_name, ToolLaunchPlan)- _cache_put(key, available, reason)+ _cache_put(key, available, reason, generation = generation)return available, reasondiff --git a/studio/backend/core/inference/sandbox_setup_job.py b/studio/backend/core/inference/sandbox_setup_job.pynew file mode 100644index 00000000000..77b3abc7dc9--- /dev/null+++ b/studio/backend/core/inference/sandbox_setup_job.py@@ -0,0 +1,265 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""One-click OS sandbox setup from Unsloth: install bubblewrap on Linux, install and prepare MXC on Windows.++Nothing from a request reaches the command line: the operation name picks a constant plan.+"""++from __future__ import annotations++from collections import deque+from dataclasses import asdict, dataclass, field+import logging+import os+import shlex+import subprocess+import sys+import threading+import time+from typing import Callable+import uuid++from . import sandbox_setup_plan+from .mxc_host_prep_job import HOST_CHANGE_LOCK, _DECLINED_MARKER, _steps as _prepared_steps++logger = logging.getLogger(__name__)++OUTPUT_TAIL_LINES = 20+PKEXEC_DISMISSED = 126+PKEXEC_NOT_AUTHORIZED = 127+# install_mxc_prebuilt.py: a running MXC process holds the runtime files.+_RUNTIME_IN_USE = 3+_SUDO_NEEDS_PASSWORD = "a password is required"++_lock = threading.Lock()+_current: "SetupJob | None" = None+_on_finish: list[Callable[[], None]] = []+++class SetupUnavailable(ValueError):+ """The requested operation does not apply to this host right now."""+++@dataclass+class SetupJob:+ id: str+ operation: str+ state: str = "running" # running | succeeded | declined | failed+ started_at: float = field(default_factory = time.time)+ finished_at: float | None = None+ exit_code: int | None = None+ output_tail: list[str] = field(default_factory = list)+ steps: list[str] = field(default_factory = list)+ manual_command: str = ""+ note: str = ""++ def as_dict(self) -> dict:+ return asdict(self)+++def current() -> SetupJob | None:+ with _lock:+ return _current+++def add_finish_hook(hook: Callable[[], None]) -> None:+ if hook not in _on_finish:+ _on_finish.append(hook)+++def running() -> bool:+ job = current()+ return job is not None and job.state == "running"+++def _spawn(argv: list[str], env: dict | None = None) -> subprocess.Popen:+ from utils.process_lifetime import child_popen_kwargs, spawn_on_lifetime_thread++ kwargs = dict(+ env = env,+ stdin = subprocess.DEVNULL,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ **child_popen_kwargs(),+ )+ if sys.platform == "win32":+ kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW+ return spawn_on_lifetime_thread(lambda: subprocess.Popen(argv, **kwargs))+++def _invalidate() -> None:+ from . import mxc_probe, os_sandbox, sandbox_probe, tools++ resets = (+ sandbox_probe.reset_probe_cache,+ os_sandbox._linux_userns_blocked_by_apparmor.cache_clear,+ mxc_probe.invalidate_cache,+ tools.reset_terminal_profile_cache,+ sandbox_setup_plan.invalidate,+ *_on_finish,+ )+ for reset in resets:+ try:+ reset()+ except Exception as exc: # noqa: BLE001 - a stale cache only delays the new verdict+ logger.warning("Sandbox setup: cache reset failed: %s", exc)+ try:+ if not os_sandbox._background_probes_disabled():+ os_sandbox.warm_tool_isolation()+ except Exception as exc: # noqa: BLE001 - the next read checks on its own+ logger.warning("Sandbox setup: re-check after setup failed: %s", exc)+++def pkexec_script(steps) -> str:+ return "set -e\n" + "\n".join(shlex.join(list(step)) for step in steps) + "\n"+++def _commands(plan: sandbox_setup_plan.SetupPlan) -> tuple[list[list[str]], dict | None]:+ """(argv list, env). Linux steps run as root: programs pinned to system binaries, never PATH."""+ if plan.action != sandbox_setup_plan.LINUX_INSTALL:+ return [list(step) for step in plan.steps], None+ kind, path = sandbox_setup_plan.linux_elevation(force = True)+ if kind is None:+ raise SetupUnavailable(+ "Neither passwordless sudo nor a desktop password prompt is available."+ )+ try:+ steps = sandbox_setup_plan.elevated_steps(plan.steps)+ shell = sandbox_setup_plan.trusted_system_binary("sh") if kind == "pkexec" else None+ except LookupError as exc:+ raise SetupUnavailable(f"{exc}; run the command in a terminal instead.") from exc+ env = dict(sandbox_setup_plan.ELEVATED_ENV)+ if kind == "root":+ return steps, env+ if kind == "sudo":+ return [[path, "-n", *step] for step in steps], env+ if shell is None:+ raise SetupUnavailable(+ "No trusted /bin/sh was found; run the command in a terminal instead."+ )+ # trusted_system_binary resolves links; BusyBox (Alpine) picks its applet from argv[0], so name it.+ shell_argv = [shell, "sh"] if os.path.basename(shell) == "busybox" else [shell]+ return [[path, *shell_argv, "-c", pkexec_script(steps)]], env+++def _drain(job: SetupJob, proc: subprocess.Popen, tail: deque) -> int | None:+ try:+ for line in proc.stdout:+ tail.append(line.rstrip("\r\n"))+ job.output_tail = list(tail)+ # No timeout: a package manager or ACL helper stopped mid-run leaves the host half changed.+ return proc.wait()+ except Exception as exc: # noqa: BLE001 - reported on the job, never raised into a thread+ tail.append(f"Unsloth lost track of the setup run: {exc}")+ return None+++def _outcome(job: SetupJob, argv: list[str], code: int | None, lines: list[str]) -> str:+ if code == 0:+ return "succeeded"+ if job.operation == sandbox_setup_plan.LINUX_INSTALL:+ if argv and argv[0].endswith("pkexec"):+ if code == PKEXEC_DISMISSED:+ job.note = "The password prompt was dismissed."+ return "declined"+ if code == PKEXEC_NOT_AUTHORIZED:+ job.note = "Not authorized, or no authentication agent is running on this desktop."+ return "failed"+ if any(_SUDO_NEEDS_PASSWORD in line for line in lines):+ job.note = "sudo needs a password here; run the command in a terminal instead."+ return "failed"+ return "failed"+ if any(_DECLINED_MARKER in line for line in lines):+ job.note = "The administrator prompt was declined."+ return "declined"+ if (+ "install_mxc_prebuilt.py" in " ".join(argv)+ and "--prepare-host" not in argv+ and code == _RUNTIME_IN_USE+ ):+ job.note = "A running Python or Terminal call is using the runtime; try again once it ends."+ return "failed"+++def _run(+ job: SetupJob,+ commands: list[list[str]],+ env: dict | None = None,+) -> None:+ tail: deque[str] = deque(maxlen = OUTPUT_TAIL_LINES)+ state, code = "succeeded", 0+ for argv in commands:+ try:+ proc = _spawn(argv, env)+ except Exception as exc: # noqa: BLE001 - surfaced as a failed job+ tail.append(f"Could not start the setup step: {exc}")+ state, code = "failed", None+ break+ code = _drain(job, proc, tail)+ lines = list(tail)+ if "--prepare-host" in argv:+ job.steps = _prepared_steps(lines)+ state = _outcome(job, argv, code, lines)+ if state != "succeeded":+ break+ job.output_tail = list(tail)+ job.exit_code = code+ job.finished_at = time.time()+ if state != "succeeded" and not job.note and code is not None:+ job.note = f"The setup step exited with code {code}."+ logger.info("Sandbox setup finished: operation=%s state=%s exit=%s", job.operation, state, code)+ _invalidate()+ job.state = state+++def _joined(running: SetupJob, operation: str) -> SetupJob:+ """The run already in progress, but only for the same request: another one never stands in."""+ if running.operation != operation:+ raise SetupUnavailable(+ f"Another sandbox setup ({running.operation}) is still running; "+ "start this one once it finishes."+ )+ return running+++def start(operation: str) -> SetupJob:+ """Start the setup for `operation`, or return the run of the same operation already in progress."""+ global _current+ from . import mxc_host_prep_job++ if operation not in sandbox_setup_plan.OPERATIONS:+ raise SetupUnavailable(f"Unknown setup operation: {operation}")+ in_progress = current()+ if in_progress is not None and in_progress.state == "running":+ return _joined(in_progress, operation)+ if operation == sandbox_setup_plan.WINDOWS_RUNTIME:+ plan = sandbox_setup_plan.windows_runtime_plan()+ else:+ plan = sandbox_setup_plan.detect(force = True)+ if plan.action != operation:+ raise SetupUnavailable(plan.reason or "There is nothing to set up on this computer.")+ commands, env = _commands(plan)+ with HOST_CHANGE_LOCK:+ with _lock:+ if _current is not None and _current.state == "running":+ return _joined(_current, operation)+ prep = mxc_host_prep_job.current()+ if prep is not None and prep.state == "running":+ return _joined(+ SetupJob(+ id = prep.id,+ operation = sandbox_setup_plan.WINDOWS_SETUP,+ started_at = prep.started_at,+ ),+ operation,+ )+ job = SetupJob(id = uuid.uuid4().hex, operation = operation, manual_command = plan.manual_command)+ with _lock:+ _current = job+ threading.Thread(+ target = _run, args = (job, commands, env), name = "sandbox-setup", daemon = True+ ).start()+ return jobdiff --git a/studio/backend/core/inference/sandbox_setup_plan.py b/studio/backend/core/inference/sandbox_setup_plan.pynew file mode 100644index 00000000000..4b59aaea1a8--- /dev/null+++ b/studio/backend/core/inference/sandbox_setup_plan.py@@ -0,0 +1,522 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""What it takes to get OS isolation on this computer, and whether Unsloth can do it from Settings.++Detection only: nothing here runs a privileged command.+"""++from __future__ import annotations++from dataclasses import asdict, dataclass+import os+import re+import shlex+import shutil+import subprocess+import sys+import threading+import time+from pathlib import Path++LINUX_INSTALL = "linux-install"+WINDOWS_SETUP = "windows-setup"+WINDOWS_RUNTIME = "windows-runtime"+OPERATIONS = (LINUX_INSTALL, WINDOWS_SETUP, WINDOWS_RUNTIME)++_APPARMOR_SYSCTL = "/proc/sys/kernel/apparmor_restrict_unprivileged_userns"+_APPARMOR_PROFILE = "/etc/apparmor.d/bwrap-userns-restrict"+_APPARMOR_EXTRA_PROFILE = "/usr/share/apparmor/extra-profiles/bwrap-userns-restrict"+_CACHE_SECONDS = 5.0+# The elevation check is logged (auth.log) and may mail root: ask rarely.+_ELEVATION_CACHE_SECONDS = 600.0+SYSTEM_BIN_DIRS = ("/usr/sbin", "/usr/bin", "/sbin", "/bin")+ELEVATED_ENV = {+ "PATH": ":".join(SYSTEM_BIN_DIRS),+ "LANG": "C",+ "LC_ALL": "C",+ "DEBIAN_FRONTEND": "noninteractive",+}++# Must match os_sandbox's _BWRAP_INSTALL_COMMANDS / _BWRAP_APPARMOR_FIX (and install.sh).+_APT_INSTALL = ("apt-get", "-o", "DPkg::Lock::Timeout=120", "install", "-y")+_INSTALL_STEPS = {+ "apt-get": (("apt-get", "update"), (*_APT_INSTALL, "bubblewrap")),+ "dnf": (("dnf", "install", "-y", "bubblewrap"),),+ "pacman": (("pacman", "-S", "--needed", "--noconfirm", "bubblewrap"),),+ "zypper": (("zypper", "--non-interactive", "install", "bubblewrap"),),+ "apk": (("apk", "add", "bubblewrap"),),+}+++def _apparmor_load() -> tuple[str, ...]:+ return ("apparmor_parser", "-r", _APPARMOR_PROFILE)+++def _apparmor_steps() -> tuple[tuple[str, ...], ...]:+ return (+ (*_APT_INSTALL, "apparmor-profiles"),+ ("install", "-m", "644", _APPARMOR_EXTRA_PROFILE, "/etc/apparmor.d/"),+ _apparmor_load(),+ )+++_lock = threading.Lock()+_cache: dict[tuple, tuple[float, "SetupPlan"]] = {}+_elevation_cache: "tuple[float, tuple[str | None, str | None]] | None" = None+++@dataclass(frozen = True)+class SetupPlan:+ platform: str+ # One of OPERATIONS; on Linux running it also needs linux_elevation().+ action: str | None = None+ elevation: str | None = None+ steps: tuple[tuple[str, ...], ...] = ()+ manual_command: str = ""+ reason: str = ""+ needs_consent: bool = False++ def as_dict(self) -> dict:+ data = asdict(self)+ data["steps"] = [list(step) for step in self.steps]+ return data+++def invalidate() -> None:+ with _lock:+ _cache.clear()+++def detect(available: bool | None = None, *, force: bool = False) -> SetupPlan:+ if available is None:+ available = _os_isolation_available()+ key = (sys.platform, bool(available))+ now = time.monotonic()+ with _lock:+ cached = _cache.get(key)+ if not force and cached is not None and now < cached[0]:+ return cached[1]+ if available:+ plan = SetupPlan(+ platform = sys.platform, reason = "OS isolation already works on this computer."+ )+ elif sys.platform == "win32":+ plan = _windows_plan()+ elif sys.platform == "darwin":+ plan = SetupPlan(+ platform = sys.platform,+ reason = "The macOS sandbox (Seatbelt) did not pass its live check.",+ )+ elif sys.platform.startswith("linux"):+ plan = _linux_plan()+ else:+ plan = SetupPlan(+ platform = sys.platform, reason = "No OS sandbox is supported on this platform."+ )+ with _lock:+ _cache[key] = (time.monotonic() + _CACHE_SECONDS, plan)+ return plan+++def _os_isolation_available() -> bool:+ """Both tools, as the status and capability reads count it: Python alone is not "works"."""+ from . import os_sandbox+ try:+ return all(+ os_sandbox.capability_snapshot(+ execution_kind = tool,+ selected_executable = os_sandbox.tool_isolation_target(tool),+ ).available+ for tool in os_sandbox.ISOLATED_TOOLS+ )+ except Exception: # noqa: BLE001 - an unreadable verdict is not a working sandbox+ return False+++def _running_as_root() -> bool:+ return hasattr(os, "geteuid") and os.geteuid() == 0+++def manual_command(steps) -> str:+ prefix = "" if _running_as_root() else "sudo "+ return " && ".join(f"{prefix}{shlex.join(step)}" for step in steps)+++def trusted_system_binary(name: str) -> str | None:+ """`name` from SYSTEM_BIN_DIRS only (never PATH), root-owned and not writable by others."""+ from .sandbox_linux import _trusted_system_file++ for directory in SYSTEM_BIN_DIRS:+ candidate = os.path.join(directory, name)+ if not os.path.exists(candidate):+ continue+ resolved = os.path.realpath(candidate)+ if not _trusted_system_file(resolved):+ continue+ try:+ parent = os.stat(os.path.dirname(resolved))+ except OSError:+ continue+ if parent.st_uid == 0 and not parent.st_mode & 0o022:+ return resolved+ return None+++def elevated_steps(steps) -> list[list[str]]:+ """Each step with its program pinned to a trusted absolute path; LookupError if one has none."""+ pinned = []+ for step in steps:+ program = trusted_system_binary(step[0])+ if program is None:+ raise LookupError(f"{step[0]} was not found in {', '.join(SYSTEM_BIN_DIRS)}")+ pinned.append([program, *step[1:]])+ return pinned+++def _apparmor_restricts_userns() -> bool:+ try:+ with open(_APPARMOR_SYSCTL, encoding = "utf-8") as f:+ return f.read().strip() == "1"+ except OSError:+ return False+++def _package_manager() -> str | None:+ from . import os_sandbox+ for manager, _command in os_sandbox._BWRAP_INSTALL_COMMANDS:+ if shutil.which(manager):+ return manager+ return None+++def _is_wsl() -> bool:+ if os.environ.get("WSL_DISTRO_NAME") or os.environ.get("WSL_INTEROP"):+ return True+ try:+ with open("/proc/version", encoding = "utf-8") as f:+ return "microsoft" in f.read().lower()+ except OSError:+ return False+++def _trusted_tool(name: str) -> str | None:+ from .sandbox_linux import _trusted_system_file++ candidate = shutil.which(name)+ if candidate is None:+ return None+ resolved = os.path.realpath(candidate)+ if not _trusted_system_file(resolved):+ return None+ try:+ parent = os.stat(os.path.dirname(resolved))+ except OSError:+ return None+ if parent.st_uid != 0 or parent.st_mode & 0o022:+ return None+ return resolved+++def _sudo_without_password(sudo: str) -> bool:+ try:+ probe = subprocess.run(+ [sudo, "-n", "true"],+ stdin = subprocess.DEVNULL,+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,+ timeout = 5,+ )+ except (OSError, subprocess.SubprocessError):+ return False+ return probe.returncode == 0+++def _graphical_session() -> bool:+ return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))+++def linux_elevation(*, force: bool = False) -> tuple[str | None, str | None]:+ """(kind, trusted path): already root, passwordless sudo, then pkexec on a desktop, else neither."""+ global _elevation_cache+ now = time.monotonic()+ with _lock:+ cached = _elevation_cache+ if not force and cached is not None and now < cached[0]:+ return cached[1]+ found = _linux_elevation()+ with _lock:+ _elevation_cache = (time.monotonic() + _ELEVATION_CACHE_SECONDS, found)+ return found+++def forget_elevation() -> None:+ global _elevation_cache+ with _lock:+ _elevation_cache = None+++def _linux_elevation() -> tuple[str | None, str | None]:+ if _running_as_root():+ return "root", None # e.g. a container: the pinned steps run as they are+ sudo = _trusted_tool("sudo")+ if sudo is not None and _sudo_without_password(sudo):+ return "sudo", sudo+ if _is_wsl() or not _graphical_session():+ return None, None+ pkexec = _trusted_tool("pkexec")+ if pkexec is not None:+ return "pkexec", pkexec+ return None, None+++def _bwrap_state() -> str:+ """As the launcher sees it: "trusted", "missing", or "shadowed" (PATH finds an untrusted copy first)."""+ from . import sandbox_linux++ try:+ sandbox_linux._trusted_bwrap_path()+ return "trusted"+ except Exception: # noqa: BLE001 - any refusal means the launcher will not run it+ pass+ if shutil.which("bwrap") is None or trusted_system_binary("bwrap") is None:+ return "missing"+ return "shadowed"+++def _linux_plan() -> SetupPlan:+ from . import os_sandbox++ reason = os_sandbox.linux_unavailable_remediation()+ manager = _package_manager()+ state = _bwrap_state()+ if state == "shadowed":+ # Installing changes nothing: the system copy is there, PATH just finds another one first.+ return SetupPlan(+ platform = sys.platform,+ reason = (+ f"{shutil.which('bwrap')} comes first on PATH but is not a root-owned system copy, "+ f"so Unsloth will not run it. Remove it, or put {os.path.dirname(trusted_system_binary('bwrap'))} "+ "ahead of it on PATH; nothing needs installing."+ ),+ )+ bwrap_missing = state == "missing"+ if bwrap_missing and manager is None:+ return SetupPlan(platform = sys.platform, reason = reason)+ steps: list[tuple[str, ...]] = []+ if bwrap_missing:+ steps.extend(_INSTALL_STEPS[manager])+ blocked = _apparmor_restricts_userns() and (+ bwrap_missing or os_sandbox._linux_userns_blocked_by_apparmor()+ )+ if blocked and os.path.exists(_APPARMOR_PROFILE):+ steps.append(_apparmor_load())+ elif blocked and manager == "apt-get":+ if not bwrap_missing:+ steps.append(("apt-get", "update"))+ steps.extend(_apparmor_steps())+ if not steps:+ return SetupPlan(platform = sys.platform, reason = reason)+ # The steps carry the command, so the row only needs to say what is wrong.+ return SetupPlan(+ platform = sys.platform,+ action = LINUX_INSTALL,+ steps = tuple(steps),+ manual_command = manual_command(steps),+ reason = (+ "bubblewrap is not installed."+ if bwrap_missing+ else "Ubuntu's AppArmor setting stops bubblewrap from starting a sandbox."+ ),+ )+++# Same floor as mxc_probe: older Windows has no MXC ProcessContainer to run.+MXC_MIN_WINDOWS_BUILD = 26100+++def windows_runtime_unsupported() -> str | None:+ """None when this Windows can run MXC; else "arch" (not x64) or "build" (older than 26100)."""+ import platform++ if platform.machine().lower() not in ("amd64", "x86_64"):+ return "arch"+ try:+ build = sys.getwindowsversion().build+ except AttributeError: # not Windows+ return None+ return "build" if build < MXC_MIN_WINDOWS_BUILD else None+++def windows_runtime_supported() -> bool:+ """The MXC runtime Unsloth installs is built for x64 Windows 11 build 26100 or newer."""+ return windows_runtime_unsupported() is None+++_UNSUPPORTED_NOTES = {+ "arch": "The MXC runtime is built for x64 Windows, and this PC is not x64.",+ "build": (+ f"The MXC sandbox needs Windows 11 build {MXC_MIN_WINDOWS_BUILD} (24H2) or newer, "+ "and this PC runs an older build."+ ),+}+++def windows_runtime_installed() -> bool:+ from . import mxc_runtime+ try:+ mxc_runtime.installation_identity()+ except Exception: # noqa: BLE001 - no runtime yet+ return False+ return True+++def windows_runtime_plan() -> SetupPlan:+ if windows_runtime_installed():+ return SetupPlan(platform = sys.platform, reason = "The MXC runtime is already installed.")+ unsupported = windows_runtime_unsupported()+ if unsupported is not None:+ return SetupPlan(platform = sys.platform, reason = _UNSUPPORTED_NOTES[unsupported])+ step = tuple(windows_runtime_install_command())+ return SetupPlan(+ platform = sys.platform,+ action = WINDOWS_RUNTIME,+ steps = (step,),+ manual_command = powershell_command((step,)),+ reason = "The MXC runtime is not installed.",+ )+++def powershell_command(steps) -> str:+ """What to paste into PowerShell (5.1 has no `&&`): one call-operator line per step."""++ def quote(arg: str) -> str:+ # PowerShell also ends a single-quoted string at a curly quote (about_Quoting_Rules).+ return "'" + re.sub("(['‘’‚‛])", r"\1\1", str(arg)) + "'"++ return "\n".join("& " + " ".join(quote(arg) for arg in step) for step in steps)+++def windows_runtime_install_command() -> list[str]:+ from . import mxc_runtime+ return [+ sys.executable,+ str(Path(__file__).resolve().parents[3] / "install_mxc_prebuilt.py"),+ "--install-dir",+ str(mxc_runtime._installed_package_root()),+ ]+++def _windows_plan() -> SetupPlan:+ from . import mxc_adapter, mxc_policy, mxc_probe, mxc_runtime+ from utils import mxc_isolation_settings as saved++ unsupported = windows_runtime_unsupported()+ if unsupported is not None:+ return SetupPlan(platform = sys.platform, reason = _UNSUPPORTED_NOTES[unsupported])+ installed = windows_runtime_installed()+ missing = None+ if installed:+ try:+ missing = mxc_runtime.probe_host_prep_steps(env = mxc_adapter._control_environment())+ except Exception: # noqa: BLE001 - unknown: prepare anyway, the helper is idempotent+ missing = None+ opted_in = mxc_policy.dacl_fallback_enabled()+ locked_off = not opted_in and saved.locked_by_environment(mxc_policy.DACL_FALLBACK_ENV)+ steps: list[tuple[str, ...]] = []+ if not installed:+ steps.append(tuple(windows_runtime_install_command()))+ if not installed or missing is None or missing:+ steps.append(tuple(mxc_probe.host_prep_command()))+ manual = powershell_command(steps)+ if locked_off:+ return SetupPlan(+ platform = sys.platform,+ manual_command = manual,+ reason = (+ f"{mxc_policy.DACL_FALLBACK_ENV} is set in the environment Unsloth runs in and keeps "+ "MXC's AppContainer tier off."+ ),+ )+ if not steps and opted_in:+ return SetupPlan(+ platform = sys.platform,+ reason = "MXC is installed, allowed and prepared, but its live check did not pass.",+ )+ parts = []+ if not installed:+ parts.append("the MXC runtime is not installed")+ if not opted_in:+ parts.append("the Windows sandbox is not turned on yet")+ if installed and missing:+ # Plain words; the MXC step names mean nothing to a user. Only the null device step repeats per boot.+ again = list(missing) == ["prepare-null-device"]+ parts.append(+ "this PC needs its administrator step again after the restart"+ if again+ else "this PC still needs its one-time administrator step"+ )+ elif installed and missing is None:+ parts.append("Unsloth could not tell whether this PC had its administrator step")+ return SetupPlan(+ platform = sys.platform,+ action = WINDOWS_SETUP,+ elevation = "uac" if any("--prepare-host" in step for step in steps) else None,+ steps = tuple(steps),+ manual_command = manual,+ reason = _sentence("; ".join(parts)),+ needs_consent = not opted_in,+ )+++def _sentence(text: str) -> str:+ return f"{text[:1].upper()}{text[1:]}." if text else ""+++def setup_fields_for(+ request,+ user = None,+ *,+ available: bool | None = None,+) -> dict:+ """Setup fields for a capability response: the action only for the owner on a local request."""+ from utils.client_ip import is_direct_local_request++ plan = detect(available)+ local = False+ try:+ local = is_direct_local_request(request)+ except Exception: # noqa: BLE001 - an unreadable request is not local+ local = False+ owner = _is_owner(user)+ can_run = can_run_here(plan, owner = owner, local = local)+ blocked = None+ if plan.action and not can_run:+ blocked = "not_owner" if not owner else "not_local" if not local else "no_elevation"+ # Windows commands leak this install's paths (account name, home): owner only.+ command = plan.manual_command if owner or not sys.platform.startswith("win") else ""+ return {+ "setup_action": plan.action if can_run else None,+ "manual_command": command,+ "can_run_setup": can_run,+ "setup_blocked": blocked,+ "needs_consent": plan.needs_consent if can_run else False,+ "reason": plan.reason,+ }+++def can_run_here(plan: SetupPlan, *, owner: bool, local: bool) -> bool:+ """Whether this caller gets the setup button. Blocking: may run the Linux elevation check."""+ if not (plan.action and owner and local):+ return False+ if plan.action == LINUX_INSTALL:+ return linux_elevation()[0] is not None+ return True+++def _is_owner(user) -> bool:+ if user is None:+ from utils.account_context import is_owner_context+ return is_owner_context()+ if isinstance(user, bool):+ return user+ return bool(getattr(user, "is_owner", False))diff --git a/studio/backend/core/inference/sandbox_windows_mxc.py b/studio/backend/core/inference/sandbox_windows_mxc.pyindex c6f33e8ed64..8b3e1a845eb 100644--- a/studio/backend/core/inference/sandbox_windows_mxc.py+++ b/studio/backend/core/inference/sandbox_windows_mxc.py@@ -112,17 +112,19 @@ def capability_snapshot(elif dacl:remediation = ("Install the pinned Microsoft WXC runtime and prepare this host once as an "- "administrator; the null device step repeats after every reboot."+ "administrator (Settings > Sandbox > Prepare this PC); the null device step repeats "+ "after every reboot.")else:remediation = ("Install the pinned Microsoft WXC runtime and enable BaseContainer/PSEC. On Windows "- f"builds without it, set {mxc_policy.DACL_FALLBACK_ENV}=1 to use the AppContainer "+ "builds without it, turn on Settings > Sandbox > Turn on the Windows sandbox (or "+ f"set {mxc_policy.DACL_FALLBACK_ENV}=1) to use the AppContainer ""tier: it adds temporary permission entries to the granted host folders, removed ""on exit, and needs a one-time administrator host preparation plus one per reboot. ""Studio's own Python runtime folders get a permanent read-only entry instead, so "- f"launches stay fast; set {mxc_read_grants.PERSISTENT_GRANTS_ENV}=0 to keep every "- "entry temporary."+ "launches stay fast; turn that off in the same place (or set "+ f"{mxc_read_grants.PERSISTENT_GRANTS_ENV}=0) to keep every entry temporary.")# Only in DACL mode: a bare --probe allows the fallback, so it warns on hosts Studio never uses it on.host_prep = (@@ -148,7 +150,10 @@ def capability_snapshot(def prepare(plan, capability):lease, alias_limitations = _workdir_alias(plan)+ grant_lease = Nonetry:+ # Before the request is built, so a revocation racing this launch either finishes first or waits.+ grant_lease = mxc_read_grants.hold_if_needed()request = (mxc_policy.build_launch_request(plan, cwd_alias = lease.root)if lease@@ -157,6 +162,8 @@ def prepare(plan, capability):except Exception as exc:if lease is not None:lease.release()+ if grant_lease is not None:+ grant_lease.release()raise SandboxBuildError(f"Windows MXC policy construction failed: {exc}") from exclaunch_limitations = tuple(request.get("launchLimitations", ())) + alias_limitationsrecord = _record(@@ -190,6 +197,9 @@ def prepare(plan, capability):execution_record = record,launch_limitations = launch_limitations,)+ if grant_lease is not None:+ # Appended first so it runs last (LIFO): the grants outlive the workload that may use them.+ prepared.cleanup_callbacks.append(grant_lease.release)if lease is not None:# Runs on every exit path, spawned or not; release_runtime drops it first once the workload is gone.prepared.cleanup_callbacks.append(lease.release)diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex 6b22b7d991d..9d15addae17 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -1267,7 +1267,12 @@ async def stream_with_studio_tools(tool_choice = run.tool_choice if run.tool_choice is not None else "auto"allowed_tool_names = _tool_names(tools)tool_call_timeout = policy.timeout- from state.tool_policy import account_tool_stream, normalize_tool_permissions+ from state.tool_policy import (+ account_tool_stream,+ needs_tool_confirmation,+ normalize_tool_permissions,+ requires_os_isolation,+ )permission_mode, bypass_permissions = normalize_tool_permissions(policy.permission_mode, policy.bypass_permissions@@ -1745,14 +1750,15 @@ async def stream_with_studio_tools(call_id = decision.tool_call_id# Same id for a call the provider named; for one it did not, the card answers to the id the client mintedcard_id = decision.card_id- needs_confirmation = (- confirm_tool_calls- and not bypass_permissions- and permission_mode != "off"- and not never_needs_approval(name)+ needs_confirmation = needs_tool_confirmation(+ confirm_tool_calls = confirm_tool_calls,+ bypass_permissions = bypass_permissions,+ permission_mode = permission_mode,+ name = name,+ arguments = arguments,+ is_high_risk = is_high_risk_tool_call,+ never_needs = never_needs_approval,)- if needs_confirmation and permission_mode == "auto":- needs_confirmation = is_high_risk_tool_call(name, arguments)# Sending the user's image always asks, whatever the permission mode.image_share = (await asyncio.to_thread(mcp_image_share, name, arguments, mcp_image)@@ -1760,6 +1766,15 @@ async def stream_with_studio_tools(else None)needs_confirmation = needs_confirmation or image_share is not None+ strict_isolation = requires_os_isolation(+ confirm_tool_calls = confirm_tool_calls,+ bypass_permissions = bypass_permissions,+ permission_mode = permission_mode,+ name = name,+ arguments = arguments,+ prompted = needs_confirmation,+ is_high_risk = is_high_risk_tool_call,+ )approval_id = new_approval_id() if needs_confirmation else ""decision_slot = (begin_tool_decision(session_id, approval_id) if needs_confirmation else None@@ -1851,6 +1866,7 @@ async def stream_with_studio_tools(output_callback: Any,call = decision,approved = host_access_approved,+ strict = strict_isolation,) -> str:kwargs: dict[str, Any] = {"cancel_event": cancel_event,@@ -1860,6 +1876,9 @@ async def stream_with_studio_tools("rag_scope": rag_scope,"disable_sandbox": bypass_permissions,}+ # 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"# 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.pyindex 9a4c4680512..9b2022c6629 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -10181,10 +10181,11 @@ def _windows_system_cmd() -> str:def _terminal_profile(disable_sandbox: bool = False) -> str:"""Which shell the Terminal runs: "bash", "cmd_isolated" or "cmd_fallback".- Git Bash cannot start inside MXC (microsoft/mxc#1061), so when the MXC probe names exactly that- failure and cmd.exe qualifies instead, Auto runs the Terminal isolated on cmd rather than- unsandboxed on bash. Only the MSYS verdict triggers the cmd probe, so hosts without a working MXC- pay nothing extra. Full access and UNSLOTH_MXC_TERMINAL_CMD=0 keep the host shell.+ Git Bash cannot start inside MXC (microsoft/mxc#1061), so when bash fails the MXC probe and+ cmd.exe qualifies instead, Auto runs the Terminal isolated on cmd rather than unsandboxed on bash.+ Any bash failure counts, not only the MSYS verdict: on a freshly prepared host bash fails without+ that signature while cmd passes. Only a failed bash probes cmd. Full access and+ UNSLOTH_MXC_TERMINAL_CMD=0 keep the host shell."""if sys.platform != "win32":return "bash"@@ -10193,14 +10194,12 @@ def _terminal_profile(disable_sandbox: bool = False) -> str:if disable_sandbox or os.environ.get("UNSLOTH_MXC_TERMINAL_CMD") == "0":return host_defaulttry:- from . import mxc_probe-if bash:- # Either MXC tier: BaseContainer hosts hit the same MSYS failure as the DACL tier.+ # Either MXC tier: any bash failure tries cmd.verdict = os_sandbox.capability_snapshot(execution_kind = "terminal", selected_executable = bash)- if verdict.available or verdict.reason != mxc_probe.MSYS_NAMESPACE_REASON:+ if verdict.available:return "bash"cmd = os_sandbox.capability_snapshot(execution_kind = "terminal", selected_executable = _windows_system_cmd()@@ -10215,12 +10214,25 @@ def _terminal_profile(disable_sandbox: bool = False) -> str:_request_profile: list = [None, 0.0]_request_profile_lock = threading.Lock()_REQUEST_PROFILE_REFRESH_SECONDS = 240.0+# Bumped by every reset: a refresh that started earlier must not publish the profile it computed.+_request_profile_generation = 0+++def reset_terminal_profile_cache() -> None:+ """Forget the advertised Terminal profile, so the next request re-checks it (isolation settings changed)."""+ global _request_profile_generation+ with _request_profile_lock:+ _request_profile[:] = [None, 0.0]+ _request_profile_generation += 1def _refresh_request_profile() -> str:+ with _request_profile_lock:+ generation = _request_profile_generationprofile = _terminal_profile(False)with _request_profile_lock:- _request_profile[:] = [profile, time.monotonic()]+ if generation == _request_profile_generation:+ _request_profile[:] = [profile, time.monotonic()]return profilediff --git a/studio/backend/main.py b/studio/backend/main.pyindex 2cefc5586f8..a4480008d7a 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -271,7 +271,6 @@ _no_sentencepiece()del _no_sentencepieceimport hashlib-import ipaddressimport mimetypesimport re as _reimport shutil@@ -367,6 +366,7 @@ from hub.utils.download_registry import (terminate_active_downloads as terminate_hub_downloads,)from routes.settings import router as settings_router+from routes.sandbox_capability import router as sandbox_capability_routerfrom routes.systemone import MCP_PATH as DECISIONS_MCP_PATH, RequireStudioAuth, decisions_mcpfrom routes.systemone import router as systemone_routerfrom routes.prompts import router as prompts_router@@ -784,6 +784,13 @@ async def lifespan(app: FastAPI):except Exception: # noqa: BLE001pass+ # Warm the OS sandbox probe so the "off" gate has an answer.+ try:+ from core.inference.os_sandbox import start_tool_isolation_warmup+ start_tool_isolation_warmup()+ except Exception: # noqa: BLE001 -- the first tool call probes instead+ _lifespan_log.warning("could not start the sandbox warm-up", exc_info = True)+try:from hub.services.models.account_access import adopt_unnamed_public_proofsfrom utils.hub_settings import operator_hf_endpoint@@ -1743,6 +1750,7 @@ app.include_router(providers_router, prefix = "/api/providers", tags = ["provideapp.include_router(openai_codex_auth_router, prefix = "/api/providers", tags = ["providers"])app.include_router(settings_router, prefix = "/api/settings", tags = ["settings"])+app.include_router(sandbox_capability_router, prefix = "/api/sandbox", tags = ["sandbox"])app.include_router(mcp_servers_router, prefix = "/api/mcp/servers", tags = ["mcp"])app.include_router(skills_router, prefix = "/api/skills", tags = ["skills"])app.include_router(prompts_router, prefix = "/api/prompts", tags = ["prompts"])@@ -2956,56 +2964,14 @@ def _origin_of(url: Optional[str]) -> Optional[tuple[str, str, int]]:return _canonical_origin(parsed.scheme, parsed.netloc)-def _is_loopback_ip(host: Optional[str]) -> bool:- """Return whether ``host`` is a loopback IP, including IPv4-mapped IPv6."""- if not host or "%" in host: # a scope id (::1%eth0) is never a plain loopback- return False- try:- ip = ipaddress.ip_address(host)- except (TypeError, ValueError):- return False- mapped = getattr(ip, "ipv4_mapped", None)- return ip.is_loopback or (mapped is not None and mapped.is_loopback)---# A loopback peer carrying any of these is a proxy/tunnel relaying a remote client, so the peer is the-# proxy, not the caller: cloudflared sets cf-connecting-ip, reverse proxies set the rest.-_PROXIED_CLIENT_HEADERS = (- "cf-connecting-ip",- "forwarded",- "x-forwarded-for",- "x-forwarded-host",- "x-real-ip",+# Shared with the routes that must only answer the person at this computer (Settings > Sandbox).+from utils.client_ip import ( # noqa: E402+ _PROXIED_CLIENT_HEADERS,+ _is_loopback_ip,+ is_direct_local_request as _is_local_bootstrap_request,)-def _host_header_is_loopback(host_header: Optional[str]) -> bool:- """Loopback/localhost check on the raw Host header, read directly so a malformed or absent Host- cannot fall back to ``request.url.hostname``'s (loopback) ASGI server address."""- if not host_header:- return False- host = host_header.strip()- if host.startswith("["): # [IPv6] or [IPv6]:port- end = host.find("]")- if end == -1 or (host[end + 1 :] and not host[end + 1 :].startswith(":")):- return False # unclosed bracket or junk after ] (e.g. [::1]evil)- host = host[1:end]- elif host.count(":") == 1: # host:port- host = host.split(":", 1)[0]- host = host.lower().rstrip(".")- return host == "localhost" or _is_loopback_ip(host)---def _is_local_bootstrap_request(request: Request) -> bool:- """Allow bootstrap injection only through a direct loopback authority."""- client = request.client- if client is None or not _is_loopback_ip(client.host):- return False- if any(request.headers.get(h) is not None for h in _PROXIED_CLIENT_HEADERS):- return False- return _host_header_is_loopback(request.headers.get("host"))--def _is_same_origin_request(request: Request) -> bool:"""True when Origin is missing or matches request's scheme://host:port. Missing Origin counts as same-origin(top-level GETs omit it); both sides are canonicalised via :func:`_canonical_origin`, and callers mustdiff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 3962790b37a..7a45d8a87be 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2439,6 +2439,8 @@ class ChatCompletionRequest(BaseModel):# Accept unknown fields so future OpenAI fields aren't dropped before route# code runs. Mirrors AnthropicMessagesRequest and ResponsesRequest.model_config = {"extra": "allow"}+ # "off" with the client's own confirm_tool_calls=false: no prompt at all, even without OS isolation.+ _off_confirm_opt_out: bool = PrivateAttr(default = False)model: str = Field("default",@@ -3057,6 +3059,9 @@ class ChatCompletionRequest(BaseModel):# Legacy bypass callers map onto Full access (mirrors the tool loop).self.permission_mode = "full"elif self.permission_mode == "off":+ self._off_confirm_opt_out = (+ "confirm_tool_calls" in self.model_fields_set and self.confirm_tool_calls is False+ )# "Off" never prompts, so route guards must see confirm disabled.self.confirm_tool_calls = Falseelif (@@ -3976,7 +3981,7 @@ class AnthropicMessagesRequest(BaseModel):)permission_mode: Optional[str] = Field(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' never pauses (sandbox stays on), '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.",+ 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.",)auto_heal_tool_calls: Optional[bool] = Field(True,diff --git a/studio/backend/routes/chat_generation_runs.py b/studio/backend/routes/chat_generation_runs.pyindex 7c3393ab7a8..c728f78eaa5 100644--- a/studio/backend/routes/chat_generation_runs.py+++ b/studio/backend/routes/chat_generation_runs.py@@ -240,6 +240,10 @@ def _sanitize_request(payload: CreateChatGenerationRun) -> dict[str, Any]:if (request.n or 1) != 1:raise HTTPException(status_code = 400, detail = "Durable chat runs require n=1")sanitized = request.model_dump(mode = "json", exclude_none = True)+ if request.permission_mode == "off" and not request._off_confirm_opt_out:+ # The validator forces confirm_tool_calls=False for "off"; persisted, the replay would read that as the+ # caller's explicit opt-out and never arm the no-OS-sandbox confirm gate.+ sanitized.pop("confirm_tool_calls", None)for field in _EXTERNAL_ROUTING_FIELDS:sanitized.pop(field, None)sanitized["stream"] = Truediff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex fbde1e49287..25119d40592 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -5027,6 +5027,20 @@ def _permission_mode_confirm(payload) -> bool:return bool(getattr(payload, "stream", False))+def _off_mode_sandbox_gate(payload, ui_events: bool) -> bool:+ """Whether an "off" request arms the confirm gate: only on a stream that can show a prompt.++ Elsewhere "off" stays unprompted, so no route guard or non-streaming client sees a change.+ """+ return (+ getattr(payload, "permission_mode", None) == "off"+ and not getattr(payload, "_off_confirm_opt_out", False)+ and not getattr(payload, "bypass_permissions", False)+ and bool(getattr(payload, "stream", False))+ and bool(ui_events)+ )++def _catalog_names(tools) -> list[str]:"""Tool names out of a resolved catalogue, for the confirm-gate classifier."""names = []@@ -27525,7 +27539,8 @@ async def _proxy_to_external_provider(),timeout = payload.tool_call_timeout or 300,permission_mode = payload.permission_mode or "auto",- confirm_calls = _permission_mode_confirm(payload),+ confirm_calls = _permission_mode_confirm(payload)+ or _off_mode_sandbox_gate(payload, _ui_events),bypass_permissions = bool(payload.bypass_permissions),rag_scope = payload.rag_scope,nudge_tool_calls = payload.nudge_tool_calls,@@ -27947,7 +27962,8 @@ async def _proxy_to_external_provider(),timeout = payload.tool_call_timeout or 300,permission_mode = payload.permission_mode or "auto",- confirm_calls = _permission_mode_confirm(payload),+ confirm_calls = _permission_mode_confirm(payload)+ or _off_mode_sandbox_gate(payload, _ui_events),bypass_permissions = bool(payload.bypass_permissions),rag_scope = payload.rag_scope,auto_heal = payload.auto_heal_tool_calls,@@ -30246,6 +30262,8 @@ async def produce_openai_chat_completions(param = "confirm_tool_calls",),)+ # After the channel check, which "off" never trips.+ _effective_confirm = _effective_confirm or _off_mode_sandbox_gate(payload, _ui_events)if _wants_multiple_choices(payload):raise _reject_unsupported_n("GGUF tool chat completions")# main's tool turn: the date and the caller's prompt, not the template's chat default.@@ -32366,6 +32384,8 @@ async def produce_openai_chat_completions(param = "confirm_tool_calls",),)+ # After the channel check, which "off" never trips (see the GGUF branch).+ _sf_effective_confirm = _sf_effective_confirm or _off_mode_sandbox_gate(payload, _ui_events)_sf_nudge = _build_tool_action_nudge(tools = _sf_tools_to_use,model_name = model_name,diff --git a/studio/backend/routes/managed_engine_chat.py b/studio/backend/routes/managed_engine_chat.pyindex 12a8d2ba4b2..9e1a294fde1 100644--- a/studio/backend/routes/managed_engine_chat.py+++ b/studio/backend/routes/managed_engine_chat.py@@ -227,7 +227,8 @@ async def managed_tool_chat(else 25,timeout = payload.tool_call_timeout or 300,permission_mode = payload.permission_mode or "auto",- confirm_calls = api._permission_mode_confirm(payload),+ confirm_calls = api._permission_mode_confirm(payload)+ or api._off_mode_sandbox_gate(payload, ui_events),bypass_permissions = bool(payload.bypass_permissions),rag_scope = payload.rag_scope,auto_heal = payload.auto_heal_tool_calls,diff --git a/studio/backend/routes/sandbox_capability.py b/studio/backend/routes/sandbox_capability.pynew file mode 100644index 00000000000..25b98e72414--- /dev/null+++ b/studio/backend/routes/sandbox_capability.py@@ -0,0 +1,90 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What OS sandbox the Python and Terminal tools get here, for any signed-in user."""++import asyncio+import sys+from typing import Optional++from fastapi import APIRouter, Depends, Request+from pydantic import BaseModel++from auth.authentication import get_current_subject++router = APIRouter()+++class SandboxCapabilityResponse(BaseModel):+ platform: str+ python_os_isolated: bool+ terminal_os_isolated: bool+ backend: str+ reason: str+ setup_action: Optional[str] = None+ manual_command: str = ""+ can_run_setup: bool = False+ setup_blocked: Optional[str] = None+ needs_consent: bool = False+++def _setup_fields_for(request: Request, isolated: bool) -> dict:+ from core.inference import sandbox_setup_plan++ try:+ fields = sandbox_setup_plan.setup_fields_for(request, available = isolated)+ except Exception: # noqa: BLE001 - the capability stays useful without the setup hint+ return {}+ fields["setup_reason"] = fields.pop("reason", None) or ""+ return fields+++def _refresh(force: bool) -> None:+ from core.inference import os_sandbox+ if os_sandbox._background_probes_disabled():+ return # UNSLOTH_DISABLE_SANDBOX_WARMUP=1: answers come only from real launches+ for tool in os_sandbox.ISOLATED_TOOLS:+ if force or not os_sandbox.has_tool_isolation_answer(tool):+ os_sandbox.refresh_tool_isolation(tool, force = force)+++def _capability() -> dict:+ from core.inference.os_sandbox import cached_tool_capability++ python = cached_tool_capability("python")+ terminal = cached_tool_capability("terminal")+ if python is None or terminal is None:+ # "unknown" keeps the client waiting: one tool's answer says nothing about the other.+ backend, reason = "unknown", "The sandbox check has not finished yet."+ else:+ isolated = [item for item in (python, terminal) if item[0]]+ backend = (isolated or [python])[0][1]+ reason = python[2] if not python[0] else terminal[2]+ return {+ "platform": sys.platform,+ "python_os_isolated": bool(python and python[0]),+ "terminal_os_isolated": bool(terminal and terminal[0]),+ "backend": backend,+ "reason": reason,+ }++[email protected]("/capability", response_model = SandboxCapabilityResponse)+async def sandbox_capability(+ request: Request,+ refresh: bool = False,+ current_subject: str = Depends(get_current_subject),+) -> SandboxCapabilityResponse:+ """Probe when the cached answer is missing, so "not isolated" is never a guess. Force: owner only."""+ from utils.account_context import is_owner_context++ force = bool(refresh) and is_owner_context()+ await asyncio.to_thread(_refresh, force)+ capability = _capability()+ isolated = capability["python_os_isolated"] and capability["terminal_os_isolated"]+ setup = await asyncio.to_thread(_setup_fields_for, request, isolated)+ # The dialog shows the command on its own; the probe reason would repeat it inside a sentence.+ short_reason = setup.pop("setup_reason", "")+ if short_reason and setup.get("manual_command"):+ capability["reason"] = short_reason+ return SandboxCapabilityResponse(**capability, **setup)diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 274abeb7959..8e828c380f5 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -4580,6 +4580,492 @@ def export_debug_logs()+class SandboxToolStatus(BaseModel):+ backend: str+ available: bool+ reason: str+ protection_state: str = "unavailable"+ limitations: list[str] = Field(default_factory = list)+ remediation: str = ""+++class SandboxWindowsStatus(BaseModel):+ runtime_installed: bool+ # None: this Windows can run MXC; "arch" (not x64) or "build" (older than 26100) otherwise.+ runtime_unsupported: Optional[Literal["arch", "build"]] = None+ allow_dacl_fallback: bool+ allow_dacl_fallback_saved: bool+ dacl_locked_by_environment: bool+ persistent_read_grants: bool+ persistent_read_grants_saved: bool+ grants_locked_by_environment: bool+ # None: MXC could not tell; [] prepared; otherwise the wxc-host-prep verbs still missing.+ host_prep_missing: Optional[list[str]] = None+ prepare_repeats_after_restart: bool = True+++class SandboxSetupStatus(BaseModel):+ action: Optional[str] = None+ # sudo | pkexec | uac, or None.+ elevation: Optional[str] = None+ manual_command: str = ""+ reason: str = ""+ needs_consent: bool = False+ can_run: bool = False+++class SandboxStatusResponse(BaseModel):+ platform: str+ python: SandboxToolStatus+ terminal: SandboxToolStatus+ terminal_shell: Optional[str] = None+ windows: Optional[SandboxWindowsStatus] = None+ setup: Optional[SandboxSetupStatus] = None+ checked_at: float+ grants_restored: Optional[int] = None+++class SandboxSettingsPayload(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ allow_dacl_fallback: Optional[StrictBool] = None+ persistent_read_grants: Optional[StrictBool] = None+++class SandboxSetupPayload(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ operation: Literal["linux-install", "windows-setup", "windows-runtime"]+ consent_dacl_fallback: StrictBool = False+++class SandboxSetupJob(BaseModel):+ state: Literal["idle", "running", "succeeded", "declined", "failed"]+ id: Optional[str] = None+ operation: Optional[str] = None+ started_at: Optional[float] = None+ finished_at: Optional[float] = None+ exit_code: Optional[int] = None+ output_tail: list[str] = Field(default_factory = list)+ steps: list[str] = Field(default_factory = list)+ manual_command: str = ""+ note: str = ""+++class SandboxPrepareJob(BaseModel):+ state: Literal["idle", "running", "succeeded", "declined", "failed"]+ id: Optional[str] = None+ started_at: Optional[float] = None+ finished_at: Optional[float] = None+ exit_code: Optional[int] = None+ output_tail: list[str] = Field(default_factory = list)+ steps: list[str] = Field(default_factory = list)+++_SANDBOX_STATUS_TTL_SECONDS = 30.0+_sandbox_status_lock = threading.Lock()+_sandbox_status_cache: Optional[tuple[float, SandboxStatusResponse]] = None+# Bumped by every change: a status built before a save must not be cached after it.+_sandbox_status_generation = 0+++def _forget_sandbox_status() -> None:+ global _sandbox_status_cache, _sandbox_status_generation+ with _sandbox_status_lock:+ _sandbox_status_cache = None+ _sandbox_status_generation += 1+++def _sandbox_tool_status(capability) -> SandboxToolStatus:+ return SandboxToolStatus(+ backend = capability.backend,+ available = capability.available,+ reason = capability.reason,+ protection_state = capability.protection_state,+ limitations = list(capability.limitations),+ remediation = capability.remediation,+ )+++def _sandbox_terminal_target() -> tuple[str, Optional[str]]:+ import shutil+ import sys++ from core.inference import tools++ if sys.platform != "win32":+ return shutil.which("bash") or "bash", None+ profile = tools._terminal_profile(False)+ if profile == "cmd_isolated":+ return tools._windows_system_cmd(), profile+ return tools._windows_bash() or tools._windows_system_cmd(), profile+++def _sandbox_windows_status() -> SandboxWindowsStatus:+ from core.inference import (+ mxc_adapter,+ mxc_policy,+ mxc_read_grants,+ mxc_runtime,+ sandbox_setup_plan,+ )+ from utils import mxc_isolation_settings as saved++ try:+ mxc_runtime.installation_identity()+ installed = True+ except Exception:+ installed = False+ missing: Optional[list[str]] = None+ if installed:+ steps = mxc_runtime.probe_host_prep_steps(env = mxc_adapter._control_environment())+ missing = None if steps is None else list(steps)+ return SandboxWindowsStatus(+ runtime_installed = installed,+ runtime_unsupported = sandbox_setup_plan.windows_runtime_unsupported(),+ allow_dacl_fallback = mxc_policy.dacl_fallback_enabled(),+ allow_dacl_fallback_saved = saved.dacl_fallback_setting(),+ dacl_locked_by_environment = saved.locked_by_environment(mxc_policy.DACL_FALLBACK_ENV),+ persistent_read_grants = mxc_read_grants.enabled(),+ persistent_read_grants_saved = saved.persistent_grants_setting(),+ grants_locked_by_environment = saved.locked_by_environment(+ mxc_read_grants.PERSISTENT_GRANTS_ENV+ ),+ host_prep_missing = missing,+ )+++def _build_sandbox_status(force: bool) -> SandboxStatusResponse:+ """Blocking (live probes); run off the event loop. Never elevates: probes only."""+ import sys++ from core.inference import os_sandbox++ windows_refresh = force and sys.platform == "win32"+ if windows_refresh:+ # The Terminal's bash-or-cmd choice reads cached verdicts; a Refresh must choose from fresh ones.+ from core.inference import mxc_probe, sandbox_probe, tools++ sandbox_probe.reset_probe_cache()+ mxc_probe.invalidate_cache()+ tools.reset_terminal_profile_cache()+ # After the resets above: they raise the floor an earlier generation is dropped under.+ generation = os_sandbox.tool_isolation_generation()+ python = os_sandbox.capability_snapshot(+ force = force, execution_kind = "python", selected_executable = sys.executable+ )+ terminal_exe, shell = _sandbox_terminal_target()+ # On Windows the choice above just probed this executable.+ terminal = os_sandbox.capability_snapshot(+ force = force and not windows_refresh,+ execution_kind = "terminal",+ selected_executable = terminal_exe,+ )+ for tool, capability in (("python", python), ("terminal", terminal)):+ os_sandbox.note_tool_isolation(+ tool,+ capability.available,+ backend = capability.backend,+ reason = capability.reason,+ generation = generation,+ )+ return SandboxStatusResponse(+ platform = sys.platform,+ python = _sandbox_tool_status(python),+ terminal = _sandbox_tool_status(terminal),+ terminal_shell = shell,+ windows = _sandbox_windows_status() if sys.platform == "win32" else None,+ setup = _sandbox_setup_status(python.available and terminal.available),+ checked_at = time.time(),+ )+++def _sandbox_setup_status(available: bool) -> Optional[SandboxSetupStatus]:+ from core.inference import sandbox_setup_plan+ try:+ plan = sandbox_setup_plan.detect(available)+ except Exception as exc: # noqa: BLE001 - the status stays useful without the setup hint+ logger.warning("settings.sandbox_setup_plan_failed: %s", exc)+ return None+ return SandboxSetupStatus(+ action = plan.action,+ elevation = plan.elevation,+ manual_command = plan.manual_command,+ reason = plan.reason,+ needs_consent = plan.needs_consent,+ )+++def _for_request(status: SandboxStatusResponse, request: Request) -> SandboxStatusResponse:+ """Blocking. Only a direct local request may be offered the setup button."""+ from core.inference import sandbox_setup_plan+ from utils.client_ip import is_direct_local_request++ setup = status.setup+ if setup is None:+ return status+ local = bool(setup.action) and is_direct_local_request(request)+ update: dict = {"can_run": False}+ if local and setup.action == sandbox_setup_plan.LINUX_INSTALL:+ elevation, _path = sandbox_setup_plan.linux_elevation()+ update = {"can_run": elevation is not None, "elevation": elevation}+ elif local:+ update = {"can_run": True}+ return status.model_copy(update = {"setup": setup.model_copy(update = update)})+++def _sandbox_status(refresh: bool = False) -> SandboxStatusResponse:+ global _sandbox_status_cache+ with _sandbox_status_lock:+ cached, generation = _sandbox_status_cache, _sandbox_status_generation+ if not refresh and cached is not None and time.monotonic() < cached[0]:+ return cached[1]+ status = _build_sandbox_status(force = refresh)+ with _sandbox_status_lock:+ if generation == _sandbox_status_generation:+ _sandbox_status_cache = (time.monotonic() + _SANDBOX_STATUS_TTL_SECONDS, status)+ return status+++def _sandbox_invalidate() -> None:+ from core.inference import mxc_probe, tools++ mxc_probe.invalidate_cache()+ tools.reset_terminal_profile_cache()+ _forget_sandbox_status()+++def _sandbox_apply(payload: SandboxSettingsPayload) -> Optional[int]:+ """Blocking: save, reset every cached verdict, and take the read grants back once they are off."""+ from core.inference import mxc_policy, mxc_read_grants+ from utils import mxc_isolation_settings as saved++ if payload.allow_dacl_fallback is not None:+ saved.set_dacl_fallback_setting(payload.allow_dacl_fallback)+ if payload.persistent_read_grants is not None:+ saved.set_persistent_grants_setting(payload.persistent_read_grants)+ saved.forget_cached_setting()+ _sandbox_invalidate()+ if not (mxc_policy.dacl_fallback_enabled() and mxc_read_grants.enabled()):+ return len(mxc_read_grants.revoke_recorded())+ return None+++def _sandbox_job_response(job) -> SandboxPrepareJob:+ return (+ SandboxPrepareJob(**job.as_dict()) if job is not None else SandboxPrepareJob(state = "idle")+ )+++@_owner_settings_router.get("/sandbox", response_model = SandboxStatusResponse)+async def get_sandbox_status(+ request: Request,+ refresh: bool = False,+ current_subject: str = Depends(get_current_subject),+) -> SandboxStatusResponse:+ """What Python and the Terminal get from the OS sandbox on this machine, plus the Windows opt-in."""+ try:+ status = await asyncio.to_thread(_sandbox_status, refresh)+ return await asyncio.to_thread(_for_request, status, request)+ except Exception as exc:+ raise log_and_http_error(+ exc,+ 500,+ "Could not read the sandbox status.",+ event = "settings.sandbox_status_failed",+ log = logger,+ ) from exc+++@_owner_settings_router.put("/sandbox", response_model = SandboxStatusResponse)+async def update_sandbox_settings(+ payload: SandboxSettingsPayload,+ request: Request,+ current_subject: str = Depends(get_current_subject),+ # Host policy: changed at the console, never by an API key the owner happens to hold.+ _ui_session: None = Depends(_require_ui_session),+) -> SandboxStatusResponse:+ """Save the Windows MXC opt-in and the persistent read grant choice. Applies to the next launch."""+ import sys++ from core.inference import mxc_policy, mxc_read_grants+ from utils import mxc_isolation_settings as saved++ if sys.platform != "win32":+ raise HTTPException(status_code = 409, detail = "These settings only apply on Windows.")+ locks = (+ (payload.allow_dacl_fallback, mxc_policy.DACL_FALLBACK_ENV),+ (payload.persistent_read_grants, mxc_read_grants.PERSISTENT_GRANTS_ENV),+ )+ for value, env in locks:+ if value is not None and saved.locked_by_environment(env):+ raise HTTPException(+ status_code = 409,+ detail = f"{env} is set in the environment Unsloth runs in, which decides this.",+ )+ try:+ restored = await asyncio.to_thread(_sandbox_apply, payload)+ status = await asyncio.to_thread(_sandbox_status, False)+ except Exception as exc:+ raise log_and_http_error(+ exc,+ 500,+ "Could not save the sandbox settings.",+ event = "settings.sandbox_update_failed",+ log = logger,+ ) from exc+ logger.info(+ "settings.sandbox_updated subject=%s dacl=%s grants=%s",+ current_subject,+ payload.allow_dacl_fallback,+ payload.persistent_read_grants,+ )+ status = await asyncio.to_thread(_for_request, status, request)+ return status.model_copy(update = {"grants_restored": restored})+++@_owner_settings_router.get("/sandbox/prepare", response_model = SandboxPrepareJob)+def get_sandbox_prepare(current_subject: str = Depends(get_current_subject)) -> SandboxPrepareJob:+ return _sandbox_job_response(_newest_host_job(prepares_host = True))+++@_owner_settings_router.post("/sandbox/prepare", response_model = SandboxPrepareJob)+async def start_sandbox_prepare(+ request: Request,+ current_subject: str = Depends(get_current_subject),+ _ui_session: None = Depends(_require_ui_session),+) -> SandboxPrepareJob:+ """Run MXC's elevated host preparation; Windows shows its administrator prompt on this computer."""+ import sys++ from core.inference import mxc_host_prep_job, mxc_runtime, sandbox_setup_job+ from utils.client_ip import is_direct_local_request++ # Stricter than client_ip(): a loopback peer carrying proxy headers is a remote browser relayed here.+ if not is_direct_local_request(request):+ raise HTTPException(+ status_code = 403,+ detail = (+ "Prepare this PC from the computer running Unsloth: the Windows administrator "+ "prompt appears there, not in this browser."+ ),+ )+ if sys.platform != "win32":+ raise HTTPException(status_code = 409, detail = "Host preparation is Windows-only.")+ try:+ await asyncio.to_thread(mxc_runtime.installation_identity)+ except Exception as exc:+ raise HTTPException(+ status_code = 409,+ detail = "The MXC runtime is not installed; install it from Settings > Sandbox first.",+ ) from exc+ mxc_host_prep_job.add_finish_hook(_forget_sandbox_status)+ try:+ job = await asyncio.to_thread(mxc_host_prep_job.start)+ except sandbox_setup_job.SetupUnavailable as exc:+ raise HTTPException(status_code = 409, detail = str(exc)) from exc+ logger.info("settings.sandbox_prepare_started subject=%s job=%s", current_subject, job.id)+ return _sandbox_job_response(job)+++def _sandbox_setup_response(job) -> SandboxSetupJob:+ if job is None:+ return SandboxSetupJob(state = "idle")+ data = job.as_dict()+ data.setdefault("operation", "windows-setup")+ return SandboxSetupJob(**data)+++@_owner_settings_router.get("/sandbox/setup", response_model = SandboxSetupJob)+def get_sandbox_setup(current_subject: str = Depends(get_current_subject)) -> SandboxSetupJob:+ return _sandbox_setup_response(_newest_host_job())+++def _newest_host_job(prepares_host: bool = False):+ """``prepares_host``: the prepare row reads this, so a runtime-only install is not its result."""+ from core.inference import mxc_host_prep_job, sandbox_setup_job, sandbox_setup_plan++ job = sandbox_setup_job.current()+ if prepares_host and job is not None and job.operation != sandbox_setup_plan.WINDOWS_SETUP:+ job = None+ prep = mxc_host_prep_job.current()+ if prep is not None and (job is None or prep.started_at > job.started_at):+ return prep+ return job+++@_owner_settings_router.post("/sandbox/setup", response_model = SandboxSetupJob)+async def start_sandbox_setup(+ payload: SandboxSetupPayload,+ request: Request,+ current_subject: str = Depends(get_current_subject),+ _ui_session: None = Depends(_require_ui_session),+) -> SandboxSetupJob:+ """Install or prepare the OS sandbox here; the password or administrator prompt appears on this computer.++ The Windows runtime-only install needs no prompt, so unlike the rest it also works from a remote browser.+ """+ import sys++ from core.inference import mxc_policy, sandbox_setup_job, sandbox_setup_plan+ from utils import mxc_isolation_settings as saved+ from utils.client_ip import is_direct_local_request++ # Stricter than client_ip(): a loopback peer carrying proxy headers is a remote browser relayed here.+ # The runtime-only install has no prompt (it is setup.ps1's unelevated step), so it works remotely.+ if payload.operation != sandbox_setup_plan.WINDOWS_RUNTIME and not is_direct_local_request(+ request+ ):+ raise HTTPException(+ status_code = 403,+ detail = (+ "Set up the sandbox from the computer running Unsloth: the password or administrator "+ "prompt appears there, not in this browser."+ ),+ )+ platform_operations = (+ (sandbox_setup_plan.WINDOWS_SETUP, sandbox_setup_plan.WINDOWS_RUNTIME)+ if sys.platform == "win32"+ else (sandbox_setup_plan.LINUX_INSTALL,)+ if sys.platform.startswith("linux")+ else ()+ )+ if payload.operation not in platform_operations:+ raise HTTPException(+ status_code = 409, detail = f"{payload.operation} does not apply to this computer."+ )+ consent = (+ payload.operation == sandbox_setup_plan.WINDOWS_SETUP+ and payload.consent_dacl_fallback+ and not mxc_policy.dacl_fallback_enabled()+ )+ if consent and saved.locked_by_environment(mxc_policy.DACL_FALLBACK_ENV):+ raise HTTPException(+ status_code = 409,+ detail = (+ f"{mxc_policy.DACL_FALLBACK_ENV} is set in the environment Unsloth runs in, "+ "which decides this."+ ),+ )+ sandbox_setup_job.add_finish_hook(_forget_sandbox_status)+ try:+ job = await asyncio.to_thread(sandbox_setup_job.start, payload.operation)+ except sandbox_setup_job.SetupUnavailable as exc:+ raise HTTPException(status_code = 409, detail = str(exc)) from exc+ if consent:+ # Only once accepted: turned on first, the plan reads "already works" and never prepares.+ await asyncio.to_thread(_sandbox_apply, SandboxSettingsPayload(allow_dacl_fallback = True))+ sandbox_setup_plan.invalidate()+ _forget_sandbox_status()+ logger.info(+ "settings.sandbox_setup_started subject=%s operation=%s job=%s",+ current_subject,+ payload.operation,+ job.id,+ )+ return _sandbox_setup_response(job)++router.include_router(_account_settings_router)router.include_router(_shared_settings_router)router.include_router(_owner_settings_router)diff --git a/studio/backend/state/tool_policy.py b/studio/backend/state/tool_policy.pyindex 716f75d4736..51124ad51c6 100644--- a/studio/backend/state/tool_policy.py+++ b/studio/backend/state/tool_policy.py@@ -71,6 +71,78 @@ def normalize_tool_permissions(return permission_mode, False+OS_SANDBOXED_TOOLS = frozenset({"python", "terminal"})+++def off_mode_still_gates(name: str) -> 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+ 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+) -> 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)+ if permission_mode == "auto":+ from core.inference.tools import is_always_safe_tool+ return not is_always_safe_tool(name)+ return True+++def needs_tool_confirmation(+ *,+ confirm_tool_calls: bool,+ bypass_permissions: bool,+ permission_mode: Optional[str],+ name: str,+ arguments,+ is_high_risk = None,+ never_needs = None,+) -> bool:+ if is_high_risk is None or never_needs is None:+ from core.inference import tools+ is_high_risk = is_high_risk or tools.is_high_risk_tool_call+ never_needs = never_needs or tools.never_needs_approval+ 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)+ if permission_mode == "auto":+ return is_high_risk(name, arguments)+ return True+++def requires_os_isolation(+ *,+ confirm_tool_calls: bool,+ bypass_permissions: bool,+ permission_mode: Optional[str],+ name: str,+ arguments,+ prompted: bool,+ is_high_risk = None,+) -> bool:+ """Whether this call must launch with tool_execution_mode="required" (no software fallback).++ ``prompted`` is needs_tool_confirmation's decision; re-reading the cache here could race a refresh.+ """+ if prompted or not confirm_tool_calls or bypass_permissions or permission_mode != "off":+ return False+ if name not in OS_SANDBOXED_TOOLS:+ 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))++def account_tool_stream(stream):from utils.account_context import current_account, is_owner_context, run_asdiff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 035776cff64..0a5a9d3a404 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -126,6 +126,34 @@ def _no_real_mxc_drive_aliases(monkeypatch):monkeypatch.setenv("UNSLOTH_MXC_DRIVE_ALIAS", "0")[email protected](autouse = True)+def _forget_mxc_isolation_settings():+ # Held for a second across tests that each get their own Studio home; only when already imported.+ def _forget():+ settings = sys.modules.get("utils.mxc_isolation_settings")+ if settings is not None:+ settings.forget_cached_setting()++ _forget()+ yield+ _forget()++[email protected](autouse = True)+def _no_background_sandbox_probes(monkeypatch):+ # No warm-up thread and no background re-probe; each test starts with no cached tool answer.+ monkeypatch.setenv("UNSLOTH_DISABLE_SANDBOX_WARMUP", "1")++ def _forget():+ os_sandbox = sys.modules.get("core.inference.os_sandbox")+ if os_sandbox is not None:+ os_sandbox.forget_tool_isolation()++ _forget()+ yield+ _forget()++@pytest.fixture(autouse = True)def _no_restricted_region_defaults(monkeypatch):# A host where Hugging Face is restricted would otherwise default the model source to ModelScope.diff --git a/studio/backend/tests/test_account_integration_wiring.py b/studio/backend/tests/test_account_integration_wiring.pyindex 8869c860f41..3cef0de4e45 100644--- a/studio/backend/tests/test_account_integration_wiring.py+++ b/studio/backend/tests/test_account_integration_wiring.py@@ -215,6 +215,8 @@ def test_scan_folders_schema_is_initialised_for_each_account(tmp_path, monkeypatmonkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))monkeypatch.setattr(studio_db, "_schema_ready", set())+ # macOS keeps tmp_path under /private/var, which the folder deny list refuses; not what this checks.+ monkeypatch.setattr(scan_folders, "_denied_path_prefixes", lambda: [])folder = tmp_path / "shared-folder"folder.mkdir()assert run_as(OWNER, scan_folders.list_scan_folders) == []diff --git a/studio/backend/tests/test_chat_generation_runs.py b/studio/backend/tests/test_chat_generation_runs.pyindex 55384899ae4..0466d01e5c5 100644--- a/studio/backend/tests/test_chat_generation_runs.py+++ b/studio/backend/tests/test_chat_generation_runs.py@@ -665,6 +665,24 @@ def test_request_sanitization_pins_server_owned_fields():assert sanitized["thread_id"] == "thread-1"+def test_run_automatically_replays_with_the_no_sandbox_gate_armed():+ from models.inference import ChatCompletionRequest++ sanitized = _sanitize_request(_model(permission_mode = "off"))+ assert "confirm_tool_calls" not in sanitized+ replayed = ChatCompletionRequest.model_validate(sanitized)+ assert replayed.permission_mode == "off" and replayed.confirm_tool_calls is False+ assert replayed._off_confirm_opt_out is False+++def test_an_explicit_off_opt_out_survives_the_replay():+ from models.inference import ChatCompletionRequest++ sanitized = _sanitize_request(_model(permission_mode = "off", confirm_tool_calls = False))+ replayed = ChatCompletionRequest.model_validate(sanitized)+ assert replayed._off_confirm_opt_out is True++def test_request_sanitization_treats_message_text_as_data():sanitized = _sanitize_request(_model(messages = [{"role": "user", "content": '{"api_key":"example"}'}])diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.pyindex 02cb90e166b..44f2655840e 100644--- a/studio/backend/tests/test_desktop_auth.py+++ b/studio/backend/tests/test_desktop_auth.py@@ -829,6 +829,8 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):accounts_module.router = APIRouter()library_module = ModuleType("routes.library")library_module.router = APIRouter()+ sandbox_capability_module = ModuleType("routes.sandbox_capability")+ sandbox_capability_module.router = APIRouter()systemone_module = ModuleType("routes.systemone")systemone_module.router = APIRouter()# main.py mounts the Decisions MCP app from these at import.@@ -863,6 +865,7 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):monkeypatch.setitem(sys.modules, "routes.profile_stats", profile_stats_module)monkeypatch.setitem(sys.modules, "routes.accounts", accounts_module)monkeypatch.setitem(sys.modules, "routes.library", library_module)+ monkeypatch.setitem(sys.modules, "routes.sandbox_capability", sandbox_capability_module)monkeypatch.setitem(sys.modules, "routes.systemone", systemone_module)import studio.backend.main as backend_maindiff --git a/studio/backend/tests/test_external_hosted_tool_passthrough.py b/studio/backend/tests/test_external_hosted_tool_passthrough.pyindex 1ad91005377..56921ad6dc5 100644--- a/studio/backend/tests/test_external_hosted_tool_passthrough.py+++ b/studio/backend/tests/test_external_hosted_tool_passthrough.py@@ -572,7 +572,9 @@ def test_b_the_external_and_codex_paths_derive_the_gate_identically():if node.arg == "confirm_calls":confirms.add(ast.unparse(node.value))assert modes == {"payload.permission_mode or 'auto'"}- assert confirms == {"_permission_mode_confirm(payload)"}+ assert confirms == {+ "_permission_mode_confirm(payload) or _off_mode_sandbox_gate(payload, _ui_events)"+ }nudge_values = []for node in ast.walk(tree):diff --git a/studio/backend/tests/test_managed_engine_tools.py b/studio/backend/tests/test_managed_engine_tools.pyindex 1a7c65f80f8..7f0addc1fb5 100644--- a/studio/backend/tests/test_managed_engine_tools.py+++ b/studio/backend/tests/test_managed_engine_tools.py@@ -262,6 +262,33 @@ def test_studio_loop_executes_and_replays_native_tool_calls(native, monkeypatch)assert api.active_generations.count() == 0+def test_run_automatically_streams_arm_the_no_sandbox_gate(native, monkeypatch):+ # Same rule as the llama.cpp and safetensors loops: a streaming UI chat in "off" arms the confirm+ # gate, and the loop then asks only for a risky Python/Terminal call without OS isolation.+ from core.inference import studio_tool_loop+ from routes import managed_engine_chat++ seen = []+ original = managed_engine_chat.stream_with_studio_tools++ def capture(*args, **kwargs):+ seen.append(kwargs["policy"].confirm_calls)+ return original(*args, **kwargs)++ monkeypatch.setattr(managed_engine_chat, "stream_with_studio_tools", capture)+ monkeypatch.setattr(studio_tool_loop, "execute_tool", lambda *a, **k: "3973")+ run(+ route_test._request(+ enable_tools = True,+ enabled_tools = ["python"],+ permission_mode = "off",+ max_tool_calls_per_message = 1,+ stream = True,+ )+ )+ assert seen == [True]++@pytest.mark.parametrize("choice", ["auto", "required", "none", {"type": "function", "function": {"name": "lookup"}}])diff --git a/studio/backend/tests/test_mxc_cmd_command_line.py b/studio/backend/tests/test_mxc_cmd_command_line.pyindex 0ea29363935..0a63dd4c922 100644--- a/studio/backend/tests/test_mxc_cmd_command_line.py+++ b/studio/backend/tests/test_mxc_cmd_command_line.py@@ -203,6 +203,8 @@ def _cmd_probe(quoted_file,alias_root = None,started_in = None,+ spawned = None,+ released = None,):seen = {}@@ -243,9 +245,15 @@ def _cmd_probe()monkeypatch.setattr(mxc_probe.mxc_runtime, "wxc_path", lambda: tmp_path / "wxc-exec.exe")monkeypatch.setattr(mxc_probe.mxc_policy, "build_launch_request", build)- monkeypatch.setattr(mxc_probe.mxc_adapter, "spawn", lambda *_a, **_k: Finished())+ events = spawned if spawned is not None else []+ monkeypatch.setattr(+ mxc_probe.mxc_adapter, "spawn", lambda *_a, **_k: events.append("spawned") or Finished()+ )monkeypatch.setattr(mxc_probe.mxc_adapter, "abort", lambda _proc: None)- monkeypatch.setattr(mxc_probe.mxc_adapter, "release_runtime", lambda _proc: None)+ ends = released if released is not None else []+ monkeypatch.setattr(+ mxc_probe.mxc_adapter, "release_runtime", lambda _proc: ends.append("workload released")+ )monkeypatch.setattr(mxc_probe.mxc_adapter,"completion_result",@@ -276,3 +284,30 @@ def test_cmd_probe_runs_from_the_drive_alias_like_production(monkeypatch, tmp_pa)assert available is False and "controls failed" in reasonassert seen["lease"].released+++def test_the_probe_holds_the_read_grants_until_its_workload_is_released(monkeypatch, tmp_path):+ from core.inference import mxc_read_grants++ events = []+ lease = SimpleNamespace(release = lambda: events.append("grants released"))+ monkeypatch.setattr(mxc_read_grants, "hold_if_needed", lambda: events.append("held") or lease)+ available = _cmd_probe(+ monkeypatch, tmp_path, quoted_file = True, spawned = events, released = events+ )[0]+ assert available is True+ assert events == ["held", "spawned", "workload released", "grants released"]+++def test_a_probe_that_cannot_record_its_lease_never_spawns(monkeypatch, tmp_path):+ from core.inference import mxc_read_grants++ def refuse():+ raise mxc_read_grants.ReadGrantError("controlled lease failure")++ events = []+ monkeypatch.setattr(mxc_read_grants, "hold_if_needed", refuse)+ available, reason = _cmd_probe(monkeypatch, tmp_path, quoted_file = True, spawned = events)+ assert available is False+ assert "controlled lease failure" in reason+ assert events == []diff --git a/studio/backend/tests/test_mxc_host_prep_job.py b/studio/backend/tests/test_mxc_host_prep_job.pynew file mode 100644index 00000000000..223568ee54f--- /dev/null+++ b/studio/backend/tests/test_mxc_host_prep_job.py@@ -0,0 +1,132 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The Settings "Prepare this PC" job: one run at a time, its outcome read from the helper's output."""++import threading+import time++import pytest++from core.inference import mxc_host_prep_job, mxc_probe, tools+++class _FakeProc:+ def __init__(+ self,+ lines,+ code,+ gate = None,+ ):+ self._lines, self._code, self._gate = lines, code, gate+ self.stdout = self._stream()++ def _stream(self):+ for line in self._lines:+ yield line + "\n"+ if self._gate is not None:+ self._gate.wait(60)++ def wait(self):+ return self._code+++def job_env(monkeypatch):+ calls = {"invalidate": 0, "profile": 0, "spawned": []}+ monkeypatch.setattr(mxc_host_prep_job, "_current", None)+ monkeypatch.setattr(mxc_host_prep_job, "_on_finish", [])+ monkeypatch.setattr(+ mxc_probe, "host_prep_command", lambda: ["python", "install_mxc_prebuilt.py"]+ )+ monkeypatch.setattr(+ mxc_probe,+ "invalidate_cache",+ lambda: calls.__setitem__("invalidate", calls["invalidate"] + 1),+ )+ monkeypatch.setattr(+ tools,+ "reset_terminal_profile_cache",+ lambda: calls.__setitem__("profile", calls["profile"] + 1),+ )+ return calls+++def _run(+ monkeypatch,+ calls,+ proc,+ settle = True,+):+ def spawn(argv):+ calls["spawned"].append(argv)+ return proc++ monkeypatch.setattr(mxc_host_prep_job, "_spawn", spawn)+ job = mxc_host_prep_job.start()+ deadline = time.monotonic() + 30+ while settle and job.state == "running" and time.monotonic() < deadline:+ time.sleep(0.01)+ return job+++def test_success_reports_the_steps_and_resets_the_caches(monkeypatch, job_env):+ hook = []+ mxc_host_prep_job.add_finish_hook(lambda: hook.append(1))+ job = _run(+ monkeypatch,+ job_env,+ _FakeProc(["[mxc-prebuilt] host prepared: prepare-system-drive, prepare-null-device"], 0),+ )+ assert job.state == "succeeded" and job.exit_code == 0+ assert job.steps == ["prepare-system-drive", "prepare-null-device"]+ assert job_env["invalidate"] == 1 and job_env["profile"] == 1 and hook == [1]+ assert job_env["spawned"] == [["python", "install_mxc_prebuilt.py"]]+ assert mxc_host_prep_job.current() is job+++def test_already_prepared_has_no_steps(monkeypatch, job_env):+ job = _run(monkeypatch, job_env, _FakeProc(["[mxc-prebuilt] host already prepared"], 0))+ assert job.state == "succeeded" and job.steps == []+++def test_a_declined_prompt_is_named(monkeypatch, job_env):+ job = _run(+ monkeypatch,+ job_env,+ _FakeProc(["[mxc-prebuilt] the Windows administrator prompt was declined"], 1),+ )+ assert job.state == "declined" and job.exit_code == 1+++def test_a_failure_keeps_the_tail_of_the_output(monkeypatch, job_env):+ lines = [f"line {i}" for i in range(30)] + ["[mxc-prebuilt] wxc-host-prep failed"]+ job = _run(monkeypatch, job_env, _FakeProc(lines, 1))+ assert job.state == "failed"+ assert len(job.output_tail) == mxc_host_prep_job.OUTPUT_TAIL_LINES+ assert job.output_tail[-1] == "[mxc-prebuilt] wxc-host-prep failed"+ assert job_env["invalidate"] == 1+++def test_a_spawn_error_is_a_failed_job(monkeypatch, job_env):+ def boom(_argv):+ raise OSError("python is gone")++ monkeypatch.setattr(mxc_host_prep_job, "_spawn", boom)+ job = mxc_host_prep_job.start()+ assert job.state == "failed" and "python is gone" in job.output_tail[0]+++def test_only_one_run_at_a_time(monkeypatch, job_env):+ gate = threading.Event()+ first = _run(monkeypatch, job_env, _FakeProc(["working"], 0, gate = gate), settle = False)+ assert first.state == "running"+ again = mxc_host_prep_job.start()+ assert again is first and len(job_env["spawned"]) == 1+ gate.set()+ deadline = time.monotonic() + 30+ while first.state == "running" and time.monotonic() < deadline:+ time.sleep(0.01)+ assert first.state == "succeeded"+ second = mxc_host_prep_job.start()+ assert second is not first and len(job_env["spawned"]) == 2diff --git a/studio/backend/tests/test_mxc_isolation_settings.py b/studio/backend/tests/test_mxc_isolation_settings.pynew file mode 100644index 00000000000..e102bf41742--- /dev/null+++ b/studio/backend/tests/test_mxc_isolation_settings.py@@ -0,0 +1,174 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Settings > Sandbox switches for Windows MXC: env first, then the owner's saved choice."""++from pathlib import Path+import subprocess+import sys++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference import mxc_policy, mxc_probe, mxc_read_grants, tools+from storage import studio_db+from utils import mxc_isolation_settings as settings+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")++[email protected](autouse = True)+def isolated_home(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ monkeypatch.delenv(mxc_policy.DACL_FALLBACK_ENV, raising = False)+ monkeypatch.delenv(mxc_read_grants.PERSISTENT_GRANTS_ENV, raising = False)+ settings.forget_cached_setting()+ yield+ settings.forget_cached_setting()+++def test_defaults_are_off_for_the_opt_in_and_on_for_grants():+ assert mxc_policy.dacl_fallback_enabled() is False+ assert mxc_read_grants.enabled() is True+++def test_saved_choices_apply_when_the_environment_is_silent():+ settings.set_dacl_fallback_setting(True)+ settings.set_persistent_grants_setting(False)+ assert mxc_policy.dacl_fallback_enabled() is True+ assert mxc_read_grants.enabled() is False+++ "value, expected", [("1", True), (" 1 ", True), ("0", False), ("", False), ("yes", False)]+)+def test_a_present_environment_variable_decides_as_before(monkeypatch, value, expected):+ settings.set_dacl_fallback_setting(not expected)+ monkeypatch.setenv(mxc_policy.DACL_FALLBACK_ENV, value)+ assert mxc_policy.dacl_fallback_enabled() is expected+ assert settings.locked_by_environment(mxc_policy.DACL_FALLBACK_ENV) is True++[email protected]("value, expected", [("0", False), ("1", True), ("", True)])+def test_the_grants_environment_variable_decides_as_before(monkeypatch, value, expected):+ settings.set_persistent_grants_setting(not expected)+ monkeypatch.setenv(mxc_read_grants.PERSISTENT_GRANTS_ENV, value)+ assert mxc_read_grants.enabled() is expected+++def test_an_unreadable_store_keeps_the_shipped_defaults(monkeypatch):+ settings.set_dacl_fallback_setting(True)+ settings.set_persistent_grants_setting(False)+ settings.forget_cached_setting()++ def boom(*_args, **_kwargs):+ raise OSError("unable to open database file")++ monkeypatch.setattr(studio_db, "get_app_settings", boom)+ assert mxc_policy.dacl_fallback_enabled() is False+ assert mxc_read_grants.enabled() is True+ assert settings._cached is None # a failure is never held+++def test_a_missing_settings_module_means_off(monkeypatch):+ monkeypatch.setitem(sys.modules, "utils.mxc_isolation_settings", None)+ assert mxc_policy.dacl_fallback_enabled() is False+ assert mxc_read_grants.enabled() is True+++ "stored, expected", [(True, True), ("true", True), ("off", False), (7, False), (None, False)]+)+def test_stored_value_coercion(monkeypatch, stored, expected):+ monkeypatch.setattr(+ studio_db, "get_app_settings", lambda _keys: {settings.DACL_SETTING_KEY: stored}+ )+ assert settings.dacl_fallback_setting() is expected+++def test_setters_reject_non_booleans():+ with pytest.raises(ValueError):+ settings.set_dacl_fallback_setting("yes")+++def test_the_owner_choice_is_what_a_managed_account_reads():+ settings.set_dacl_fallback_setting(True)+ settings.forget_cached_setting()+ token = bind_account(ALICE)+ try:+ assert mxc_policy.dacl_fallback_enabled() is True+ settings.set_dacl_fallback_setting(False) # still lands in the owner's store+ finally:+ reset_account(token)+ token = bind_account(OWNER)+ try:+ assert settings.dacl_fallback_setting() is False+ finally:+ reset_account(token)+++def test_a_read_in_flight_cannot_republish_what_a_write_replaced(monkeypatch):+ settings.set_dacl_fallback_setting(True)+ settings.forget_cached_setting()+ real = studio_db.get_app_settings++ def write_lands_mid_read(keys):+ stored = real(keys)+ monkeypatch.setattr(studio_db, "get_app_settings", real)+ settings.set_dacl_fallback_setting(False)+ return stored++ monkeypatch.setattr(studio_db, "get_app_settings", write_lands_mid_read)+ assert settings.dacl_fallback_setting() is True # the answer this call was committed to+ assert settings._cached is None+ assert settings.dacl_fallback_setting() is False+++def test_repeated_reads_hit_the_store_once(monkeypatch):+ calls = []+ real = studio_db.get_app_settings+ monkeypatch.setattr(+ studio_db, "get_app_settings", lambda keys: calls.append(keys) or real(keys)+ )+ for _ in range(5):+ mxc_policy.dacl_fallback_enabled()+ mxc_read_grants.enabled()+ assert len(calls) == 1+++def test_reset_terminal_profile_cache_forgets_the_advertised_profile():+ tools._request_profile[:] = ["cmd_isolated", 123.0]+ tools.reset_terminal_profile_cache()+ assert tools._request_profile == [None, 0.0]+++def test_a_refresh_started_before_a_reset_does_not_publish_its_profile(monkeypatch):+ monkeypatch.setattr(tools, "_request_profile", [None, 0.0])++ def profile_computed_under_the_old_setting(_disable_sandbox = False):+ tools.reset_terminal_profile_cache() # the setting flips while the probe runs+ return "cmd_isolated"++ monkeypatch.setattr(tools, "_terminal_profile", profile_computed_under_the_old_setting)+ assert tools._refresh_request_profile() == "cmd_isolated"+ assert tools._request_profile == [None, 0.0]+++def test_the_remediation_names_the_same_host_prep_command(monkeypatch):+ monkeypatch.setattr(mxc_probe, "_host_prep_cache", {})+ monkeypatch.setattr(mxc_probe.mxc_runtime, "installation_identity", lambda: "id")+ monkeypatch.setattr(+ mxc_probe.mxc_runtime, "probe_host_prep_steps", lambda **_kwargs: ("prepare-null-device",)+ )+ monkeypatch.setattr(mxc_probe.mxc_adapter, "_control_environment", lambda: {})+ command = mxc_probe.host_prep_command()+ assert command[2:4] == ["--prepare-host", "--install-dir"]+ assert command[1].endswith("install_mxc_prebuilt.py")+ advice = mxc_probe.host_prep_remediation()+ assert subprocess.list2cmdline(command) in advice+ assert "Settings > Sandbox" in advicediff --git a/studio/backend/tests/test_mxc_read_grants.py b/studio/backend/tests/test_mxc_read_grants.pyindex a29a8445e3f..4c553d05d2d 100644--- a/studio/backend/tests/test_mxc_read_grants.py+++ b/studio/backend/tests/test_mxc_read_grants.py@@ -279,6 +279,137 @@ def test_an_unreadable_identity_keeps_the_record_for_a_later_revoke(host, monkeyassert ("revoke", os.path.normcase(venv)) not in host.calls+def test_revocation_waits_for_a_running_workload_and_its_release_finishes_it(host, monkeypatch):+ # On Windows a lease held open cannot be deleted; here an existing file stands in for that.+ monkeypatch.setattr(mxc_read_grants, "_lease_is_live", lambda path: path.exists())+ venv = _runtime(host)+ mxc_read_grants.ensure([venv])+ lease = mxc_read_grants.hold()+ monkeypatch.setenv(mxc_read_grants.PERSISTENT_GRANTS_ENV, "0")+ assert mxc_read_grants.revoke_recorded() == ()+ assert mxc_read_grants.ensure([venv]) == ()+ assert ("revoke", os.path.normcase(venv)) not in host.calls+ assert _states() == {os.path.normcase(venv): "complete"}+ lease.release()+ assert host.calls[-1] == ("revoke", os.path.normcase(venv))+ assert _record() == {}+ lease.release()+ assert host.calls.count(("revoke", os.path.normcase(venv))) == 1+++def test_release_keeps_the_grants_while_they_are_still_on(host, monkeypatch):+ from core.inference import mxc_policy++ monkeypatch.setattr(mxc_policy, "dacl_fallback_enabled", lambda: True)+ venv = _runtime(host)+ mxc_read_grants.ensure([venv])+ mxc_read_grants.hold().release()+ assert host.calls == [("grant", venv)]+ assert _states() == {os.path.normcase(venv): "complete"}+++def test_a_lease_left_by_a_crashed_process_never_blocks_revocation(host, monkeypatch):+ venv = _runtime(host)+ mxc_read_grants.ensure([venv])+ stale = mxc_read_grants._leases_dir() / "4242-crashed"+ stale.parent.mkdir(parents = True, exist_ok = True)+ stale.write_text("")+ monkeypatch.setenv(mxc_read_grants.PERSISTENT_GRANTS_ENV, "0")+ assert mxc_read_grants.revoke_recorded() == (os.path.normcase(venv),)+ assert not stale.exists()+++def test_a_lease_waits_for_a_revocation_already_in_progress(host):+ import threading++ leases = []+ with mxc_read_grants._transaction():+ worker = threading.Thread(target = lambda: leases.append(mxc_read_grants.hold()))+ worker.start()+ worker.join(0.5)+ assert worker.is_alive() and not leases+ worker.join(10)+ assert leases and leases[0] is not None+ leases[0].release()+++def test_release_reads_the_switches_fresh_after_another_process_opts_out(host, monkeypatch):+ from core.inference import mxc_policy+ from storage import studio_db+ from utils import account_context, mxc_isolation_settings as saved++ store = {saved.DACL_SETTING_KEY: True, saved.GRANTS_SETTING_KEY: True}+ monkeypatch.delenv(mxc_policy.DACL_FALLBACK_ENV, raising = False)+ monkeypatch.setattr(studio_db, "get_app_settings", lambda keys: {k: store[k] for k in keys})+ monkeypatch.setattr(account_context, "run_as", lambda _who, fn, *a, **k: fn(*a, **k))+ monkeypatch.setattr(mxc_read_grants, "_lease_is_live", lambda path: path.exists())+ saved.forget_cached_setting()+ venv = _runtime(host)+ lease = mxc_read_grants.hold_if_needed()+ assert lease is not None and mxc_read_grants.ensure([venv]) == (venv,)+ assert saved.persistent_grants_setting() # cached "on" in this process+ store[saved.GRANTS_SETTING_KEY] = False # another Studio process turns it off, no local write+ lease.release()+ assert host.calls[-1] == ("revoke", os.path.normcase(venv))+ assert _record() == {}+ saved.forget_cached_setting()+++def test_a_lease_that_cannot_be_recorded_refuses_instead_of_running_unguarded(host):+ blocker = mxc_read_grants._leases_dir()+ blocker.parent.mkdir(parents = True, exist_ok = True)+ blocker.write_text("") # a file where the lease folder belongs+ with pytest.raises(mxc_read_grants.ReadGrantError, match = "could not record"):+ mxc_read_grants.hold()++[email protected]("dacl, grants", [(False, True), (True, False)])+def test_a_lease_that_cannot_be_recorded_only_blocks_a_launch_that_needs_the_grants(+ host, monkeypatch, dacl, grants+):+ from core.inference import mxc_policy++ def refuse():+ raise mxc_read_grants.ReadGrantError("could not record")++ monkeypatch.setattr(mxc_read_grants, "hold", refuse)+ monkeypatch.setattr(mxc_policy, "dacl_fallback_enabled", lambda: dacl)+ monkeypatch.setattr(mxc_read_grants, "enabled", lambda: grants)+ assert mxc_read_grants.hold_if_needed() is None+ monkeypatch.setattr(mxc_policy, "dacl_fallback_enabled", lambda: True)+ monkeypatch.setattr(mxc_read_grants, "enabled", lambda: True)+ with pytest.raises(mxc_read_grants.ReadGrantError):+ mxc_read_grants.hold_if_needed()+++def test_a_launch_during_a_deferred_revocation_keeps_the_grants_until_it_exits(host, monkeypatch):+ from core.inference import mxc_policy++ switch = {"on": True}+ monkeypatch.setattr(mxc_policy, "dacl_fallback_enabled", lambda: True)+ monkeypatch.setattr(mxc_read_grants, "enabled", lambda: switch["on"])+ monkeypatch.setattr(mxc_read_grants, "_lease_is_live", lambda path: path.exists())+ venv = _runtime(host)+ first = mxc_read_grants.hold_if_needed()+ mxc_read_grants.ensure([venv])+ switch["on"] = False # the owner turns the grants off while the first call runs+ assert mxc_read_grants.revoke_recorded() == ()+ second = mxc_read_grants.hold_if_needed() # starts while the entries are still in place+ assert second is not None+ first.release()+ assert ("revoke", os.path.normcase(venv)) not in host.calls+ second.release()+ assert host.calls[-1] == ("revoke", os.path.normcase(venv))++[email protected](sys.platform != "win32", reason = "Windows refuses to delete a file held open")+def test_an_open_lease_is_live_until_released(host):+ lease = mxc_read_grants.hold()+ assert mxc_read_grants._live_leases() == 1+ lease.release()+ assert mxc_read_grants._live_leases() == 0++def test_a_replaced_folder_is_not_adopted_through_a_stale_record(host, tmp_path):venv = _runtime(host)mxc_read_grants.ensure([venv])diff --git a/studio/backend/tests/test_mxc_windows_backend.py b/studio/backend/tests/test_mxc_windows_backend.pyindex 68e6979eab4..3ec130c316e 100644--- a/studio/backend/tests/test_mxc_windows_backend.py+++ b/studio/backend/tests/test_mxc_windows_backend.py@@ -640,6 +640,71 @@ def test_policy_mutation_is_refused_before_wxc_dispatch(monkeypatch):mxc_adapter.spawn(request)+# Held with a switch off too: a deferred revocation or a switch turned on mid-build leaves entries it reads.[email protected]("dacl, grants", [(True, True), (True, False), (False, True)])+def test_a_launch_holds_the_read_grants_until_its_last_cleanup(monkeypatch, tmp_path, dacl, grants):+ from core.inference import sandbox_windows_mxc++ released = []+ lease = type("Lease", (), {"release": lambda self: released.append("grants")})()+ monkeypatch.setattr(sandbox_windows_mxc.mxc_policy, "dacl_fallback_enabled", lambda: dacl)+ monkeypatch.setattr(mxc_read_grants, "enabled", lambda: grants)+ monkeypatch.setattr(mxc_read_grants, "hold", lambda: released.append("hold") or lease)++ def build(_plan, **_kw):+ released.append("build")+ return {"policyHash": "sha256:controlled"}++ monkeypatch.setattr(sandbox_windows_mxc.mxc_policy, "build_launch_request", build)+ capability = os_sandbox.SandboxCapability(+ backend = "mxc-processcontainer",+ available = True,+ reason = "qualified",+ environment = "win32",+ profile_id = mxc_runtime.PROFILE_ID,+ )+ prepared = sandbox_windows_mxc.prepare(_plan(tmp_path), capability)+ prepared.cleanup_callbacks.append(lambda: released.append("workload"))+ prepared.cleanup()+ assert released == ["hold", "build", "workload", "grants"]+++def test_a_launch_that_fails_to_build_gives_its_grant_lease_back(monkeypatch, tmp_path):+ from core.inference import sandbox_windows_mxc++ released = []+ lease = type("Lease", (), {"release": lambda self: released.append("grants")})()+ monkeypatch.setattr(sandbox_windows_mxc.mxc_policy, "dacl_fallback_enabled", lambda: True)+ monkeypatch.setattr(mxc_read_grants, "enabled", lambda: True)+ monkeypatch.setattr(mxc_read_grants, "hold", lambda: lease)++ def refuse(_plan, **_kw):+ raise sandbox_windows_mxc.mxc_policy.MxcPolicyError("controlled refusal")++ monkeypatch.setattr(sandbox_windows_mxc.mxc_policy, "build_launch_request", refuse)+ with pytest.raises(os_sandbox.SandboxBuildError, match = "controlled refusal"):+ sandbox_windows_mxc.prepare(_plan(tmp_path), _unavailable())+ assert released == ["grants"]+++def test_a_launch_whose_grant_lease_cannot_be_recorded_is_refused(monkeypatch, tmp_path):+ from core.inference import sandbox_windows_mxc++ def refuse():+ raise mxc_read_grants.ReadGrantError("controlled lease failure")++ built = []+ monkeypatch.setattr(mxc_read_grants, "hold_if_needed", refuse)+ monkeypatch.setattr(+ sandbox_windows_mxc.mxc_policy,+ "build_launch_request",+ lambda _plan, **_kw: built.append(True) or {"policyHash": "sha256:controlled"},+ )+ with pytest.raises(os_sandbox.SandboxBuildError, match = "controlled lease failure"):+ sandbox_windows_mxc.prepare(_plan(tmp_path), _unavailable())+ assert built == []++def test_launch_failure_is_not_replayed(monkeypatch, tmp_path):calls = []prepared = os_sandbox.PreparedSandboxLaunch(diff --git a/studio/backend/tests/test_permission_mode.py b/studio/backend/tests/test_permission_mode.pyindex d07d2cc061a..57d40b7af7a 100644--- a/studio/backend/tests/test_permission_mode.py+++ b/studio/backend/tests/test_permission_mode.py@@ -2865,12 +2865,14 @@ def test_unset_mode_behaves_as_auto():assert starts and starts[0]["awaiting_confirmation"] is False-def test_off_mode_never_gates_and_keeps_sandbox():- # "Off": no prompts even for unsafe calls, but the sandbox stays on.+def test_off_mode_never_gates_under_os_isolation_and_keeps_sandbox():+ from core.inference import os_sandbox++ os_sandbox.note_tool_isolation("python", True, backend = "bubblewrap")events, exec_fn = _drive([_tool_call("python", '{"code": "import os; os.remove(\\"x\\")"}'), "final"],[],- confirm_tool_calls = True, # off must win over a stray confirm flag+ confirm_tool_calls = True, # the route arms the gate wherever it can promptpermission_mode = "off",)starts = _tool_starts(events)@@ -2879,6 +2881,32 @@ def test_off_mode_never_gates_and_keeps_sandbox():assert exec_fn.disable_sandbox_seen == [False], _diag(events, exec_fn)+def test_off_mode_asks_for_a_risky_call_without_os_isolation():+ from core.inference import os_sandbox++ os_sandbox.note_tool_isolation("python", False, backend = "none")+ events, exec_fn = _drive(+ [_tool_call("python", '{"code": "import os; os.remove(\\"x\\")"}'), "final"],+ ["allow"],+ confirm_tool_calls = True,+ permission_mode = "off",+ )+ starts = _tool_starts(events)+ assert starts and starts[0]["awaiting_confirmation"] is True, _diag(events, exec_fn)+ assert exec_fn.disable_sandbox_seen == [False], _diag(events, exec_fn)+++def test_off_mode_without_an_armed_gate_never_asks():+ events, exec_fn = _drive(+ [_tool_call("python", '{"code": "import os; os.remove(\\"x\\")"}'), "final"],+ [],+ confirm_tool_calls = False,+ permission_mode = "off",+ )+ starts = _tool_starts(events)+ assert starts and starts[0]["awaiting_confirmation"] is False, _diag(events, exec_fn)++def test_full_mode_never_gates_and_drops_sandbox():events, exec_fn = _drive([_tool_call("python", '{"code": "import os; os.remove(\\"x\\")"}'), "final"],diff --git a/studio/backend/tests/test_permission_mode_degrade.py b/studio/backend/tests/test_permission_mode_degrade.pynew file mode 100644index 00000000000..7bf20f0869a--- /dev/null+++ b/studio/backend/tests/test_permission_mode_degrade.py@@ -0,0 +1,724 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++""" "off" (Run automatically) asks before a risky python/terminal call without OS isolation."""++import itertools+import sys+import threading+import time++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth.authentication import get_current_subject+from core.inference import os_sandbox, sandbox_probe+from state import tool_policy++MODES = ("ask", "auto", "off", "full")+TOOLS = ("python", "terminal", "web_search", "edit_file")+ISOLATION = (True, False, None)+++def _risk(name, arguments):+ return bool(arguments.get("risky"))+++def _never(name):+ return name == "search_conversation"+++def _expected(mode, tool, isolated, risky):+ if mode == "full":+ return False+ if mode == "ask":+ return True+ if mode == "auto":+ return risky+ return tool in ("python", "terminal") and isolated is not True and risky+++def isolation(monkeypatch):+ state = {}+ monkeypatch.setattr(os_sandbox, "cached_tool_isolation", lambda tool: state.get(tool))+ return state+++ "mode,tool,isolated,risky", list(itertools.product(MODES, TOOLS, ISOLATION, (True, False)))+)+def test_decision_matrix(isolation, mode, tool, isolated, risky):+ isolation["python"] = isolation["terminal"] = isolated+ got = tool_policy.needs_tool_confirmation(+ confirm_tool_calls = True,+ bypass_permissions = mode == "full",+ permission_mode = mode,+ name = tool,+ arguments = {"risky": risky},+ is_high_risk = _risk,+ never_needs = _never,+ )+ assert got is _expected(mode, tool, isolated, risky)++[email protected]("mode", MODES)+def test_an_unarmed_gate_never_asks(isolation, mode):+ isolation["python"] = False+ assert not tool_policy.needs_tool_confirmation(+ confirm_tool_calls = False,+ bypass_permissions = False,+ permission_mode = mode,+ name = "python",+ arguments = {"risky": True},+ is_high_risk = _risk,+ never_needs = _never,+ )++[email protected]("mode", ("ask", "auto", "off"))+def test_search_conversation_never_asks(isolation, mode):+ assert not tool_policy.needs_tool_confirmation(+ confirm_tool_calls = True,+ bypass_permissions = False,+ permission_mode = mode,+ name = "search_conversation",+ arguments = {"risky": True},+ is_high_risk = _risk,+ never_needs = _never,+ )+++def test_default_classifiers_are_the_tools_module_ones(isolation):+ isolation["python"] = False+ common = dict(confirm_tool_calls = True, bypass_permissions = False, permission_mode = "off")+ assert not tool_policy.needs_tool_confirmation(+ name = "python", arguments = {"code": "print(1)"}, **common+ )+ assert tool_policy.needs_tool_confirmation(+ name = "python", arguments = {"code": 'open("/etc/shadow").read()'}, **common+ )++[email protected]("isolated", ISOLATION)+def test_may_prompt_before_arguments(isolation, isolated):+ isolation["python"] = isolation["terminal"] = isolated+ kw = dict(confirm_tool_calls = True, bypass_permissions = False)+ assert tool_policy.tool_call_may_prompt(permission_mode = "ask", name = "render_html", **kw)+ assert not tool_policy.tool_call_may_prompt(permission_mode = "off", name = "render_html", **kw)+ assert tool_policy.tool_call_may_prompt(permission_mode = "off", name = "python", **kw) is (+ isolated is not True+ )+ assert not tool_policy.tool_call_may_prompt(+ permission_mode = "ask", name = "python", confirm_tool_calls = True, bypass_permissions = True+ )+++class _Payload:+ def __init__(self, **kw):+ self.permission_mode = kw.get("permission_mode")+ self.bypass_permissions = kw.get("bypass_permissions", False)+ self.stream = kw.get("stream", True)+++ "mode,stream,ui_events,bypass,armed",+ [+ ("off", True, True, False, True),+ ("off", False, True, False, False),+ ("off", True, False, False, False),+ ("off", True, True, True, False),+ ("auto", True, True, False, False),+ ("ask", True, True, False, False),+ (None, True, True, False, False),+ ],+)+def test_off_gate_is_armed_only_where_a_prompt_can_reach_the_caller(+ mode, stream, ui_events, bypass, armed+):+ import routes.inference as inference_route+ payload = _Payload(permission_mode = mode, stream = stream, bypass_permissions = bypass)+ assert inference_route._off_mode_sandbox_gate(payload, ui_events) is armed+++ "body,armed",+ [+ ({}, True),+ ({"confirm_tool_calls": False}, False),+ # An explicit true is the Ask-every-time contract, not an opt-out.+ ({"confirm_tool_calls": True}, True),+ ],+)+def test_an_explicit_confirm_opt_out_keeps_off_unprompted(body, armed):+ import routes.inference as inference_route+ from models.inference import ChatCompletionRequest++ payload = ChatCompletionRequest(+ messages = [{"role": "user", "content": "hi"}],+ stream = True,+ permission_mode = "off",+ **body,+ )+ assert payload.confirm_tool_calls is False+ assert inference_route._off_mode_sandbox_gate(payload, True) is armed+++def _gguf_client(monkeypatch, captured):+ import routes.inference as inference_route+ from .llama_backend_double import FakeLlamaCppBackend++ class _Backend(FakeLlamaCppBackend):+ supports_tools = True+ context_length = 8192++ def generate_chat_completion_with_tools(self, **kwargs):+ captured.update(kwargs)+ yield {"type": "content", "text": "done"}+ yield {+ "type": "metadata",+ "usage": {"prompt_tokens": 3, "completion_tokens": 1, "total_tokens": 4},+ "timings": {"prompt_n": 3, "predicted_n": 1},+ "finish_reason": "stop",+ }++ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Backend())+ monkeypatch.setattr(inference_route, "_effective_enable_tools", lambda payload: True)++ async def _select(payload, **_kwargs):+ return [{"type": "function", "function": {"name": "python"}}]++ monkeypatch.setattr(inference_route, "_select_request_tools", _select)+ app = FastAPI()+ app.include_router(inference_route.router)+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ return TestClient(app)+++ "stream,headers,armed",+ [+ (True, {"X-Unsloth-Events": "1"}, True),+ (False, {}, False),+ ],+)+def test_gguf_route_hands_the_loop_an_armed_gate_for_off(monkeypatch, stream, headers, armed):+ captured = {}+ response = _gguf_client(monkeypatch, captured).post(+ "/chat/completions",+ json = {+ "messages": [{"role": "user", "content": "run it"}],+ "stream": stream,+ "enable_tools": True,+ "permission_mode": "off",+ },+ headers = headers,+ )+ assert response.status_code == 200, response.text+ assert captured["permission_mode"] == "off"+ assert captured["confirm_tool_calls"] is armed+ assert captured["bypass_permissions"] is False+++def test_cached_isolation_never_blocks_and_refreshes_once(monkeypatch):+ monkeypatch.delenv(os_sandbox.WARMUP_DISABLE_ENV, raising = False)+ release = threading.Event()+ calls = []++ def slow_refresh(tool, *, force = False):+ calls.append(tool)+ release.wait(5)+ os_sandbox.note_tool_isolation(tool, True, backend = "bubblewrap")+ return True++ monkeypatch.setattr(os_sandbox, "refresh_tool_isolation", slow_refresh)+ started = time.monotonic()+ assert os_sandbox.cached_tool_isolation("python") is None+ assert os_sandbox.cached_tool_isolation("python") is None+ assert time.monotonic() - started < 1.0+ release.set()+ deadline = time.monotonic() + 5+ while os_sandbox.cached_tool_isolation("python") is not True and time.monotonic() < deadline:+ time.sleep(0.01)+ assert os_sandbox.cached_tool_isolation("python") is True+ assert calls == ["python"]+++def test_cached_isolation_starts_nothing_when_background_probes_are_off(monkeypatch):+ monkeypatch.setenv(os_sandbox.WARMUP_DISABLE_ENV, "1")+ monkeypatch.setattr(+ os_sandbox,+ "refresh_tool_isolation",+ lambda *a, **k: pytest.fail("probed in the background"),+ )+ assert os_sandbox.cached_tool_isolation("python") is None+ assert os_sandbox.start_tool_isolation_warmup() is None+++def test_a_real_launch_updates_the_cached_answer():+ os_sandbox.note_tool_isolation("terminal", False, backend = "none", reason = "blocked")+ assert os_sandbox.cached_tool_capability("terminal") == (False, "none", "blocked")+ os_sandbox.note_tool_isolation("unknown-tool", True)+ assert os_sandbox.cached_tool_capability("unknown-tool") is None+++def test_forget_discards_a_refresh_that_started_before_it(monkeypatch):+ generation = os_sandbox.tool_isolation_generation()+ os_sandbox.forget_tool_isolation()+ os_sandbox.note_tool_isolation("python", True, generation = generation)+ assert os_sandbox.cached_tool_capability("python") is None+++def test_an_older_check_that_finishes_last_never_overwrites_a_newer_one():+ stale = os_sandbox.tool_isolation_generation() # background refresh of an expired answer+ forced = os_sandbox.tool_isolation_generation() # a forced refresh started after it+ os_sandbox.note_tool_isolation("python", True, backend = "bubblewrap", generation = forced)+ os_sandbox.note_tool_isolation("python", False, backend = "none", generation = stale)+ assert os_sandbox.cached_tool_capability("python")[:2] == (True, "bubblewrap")+ os_sandbox.note_tool_isolation("python", False, backend = "none") # a real launch, just now+ assert os_sandbox.cached_tool_capability("python")[:2] == (False, "none")+ os_sandbox.note_tool_isolation("terminal", True, generation = stale) # other tools are separate+ assert os_sandbox.cached_tool_capability("terminal")[0] is True+++def test_probe_cache_reset_forgets_the_cached_answer():+ os_sandbox.note_tool_isolation("python", True)+ sandbox_probe.reset_probe_cache()+ assert os_sandbox.cached_tool_capability("python") is None+++def test_warmup_runs_off_the_calling_thread(monkeypatch):+ monkeypatch.delenv(os_sandbox.WARMUP_DISABLE_ENV, raising = False)+ monkeypatch.setattr(sys, "platform", "linux")+ seen = []+ done = threading.Event()++ def refresh(tool, *, force = False):+ seen.append((tool, threading.current_thread().name))+ if len(seen) == 2:+ done.set()+ return False++ monkeypatch.setattr(os_sandbox, "refresh_tool_isolation", refresh)+ thread = os_sandbox.start_tool_isolation_warmup()+ assert thread is not None and thread.daemon+ assert done.wait(5)+ assert [tool for tool, _ in seen] == ["python", "terminal"]+ assert all(name == "unsloth-sandbox-warmup" for _, name in seen)+++def test_no_startup_warmup_on_windows(monkeypatch):+ # The MXC check launches a container and applies read grants: never at every server start.+ monkeypatch.delenv(os_sandbox.WARMUP_DISABLE_ENV, raising = False)+ monkeypatch.setattr(sys, "platform", "win32")+ called = []+ monkeypatch.setattr(os_sandbox, "refresh_tool_isolation", lambda *a, **k: called.append(a))+ assert os_sandbox.start_tool_isolation_warmup() is None+ assert called == []+++class _Clock:+ def __init__(self):+ self.now = 1000.0++ def __call__(self):+ return self.now+++def probe_env(monkeypatch):+ monkeypatch.setenv(os_sandbox.WARMUP_DISABLE_ENV, "0")+ sandbox_probe.reset_probe_cache()+ clock = _Clock()+ import types++ monkeypatch.setattr(+ sandbox_probe,+ "time",+ types.SimpleNamespace(monotonic = clock, time = time.time, sleep = time.sleep),+ )+ monkeypatch.setattr(os_sandbox, "_runtime_identity", lambda: "identity")+ verdicts = []+ gate = threading.Event()+ gate.set()+ calls = []++ def run_probe(backend, name, plan_cls):+ calls.append(threading.current_thread().name)+ gate.wait(5)+ return verdicts.pop(0)++ monkeypatch.setattr(sandbox_probe, "_run_probe", run_probe)+ yield clock, verdicts, gate, calls+ sandbox_probe.reset_probe_cache()+++class _Backend:+ BACKEND_NAME = "fake"+++def _wait_for(predicate, timeout = 5.0):+ deadline = time.time() + timeout+ while not predicate() and time.time() < deadline:+ time.sleep(0.01)+ return predicate()+++def test_a_stale_pass_is_served_while_one_reprobe_runs(probe_env):+ clock, verdicts, gate, calls = probe_env+ verdicts.extend([(True, "first"), (True, "second")])+ assert sandbox_probe.probe(_Backend()) == (True, "first")+ clock.now += sandbox_probe._CACHE_TTL_SECONDS + 1+ gate.clear()+ assert sandbox_probe.probe(_Backend()) == (True, "first")+ assert sandbox_probe.probe(_Backend()) == (True, "first")+ assert _wait_for(lambda: len(calls) == 2)+ assert calls[1] == "unsloth-sandbox-reprobe"+ gate.set()+ assert _wait_for(lambda: sandbox_probe.probe(_Backend()) == (True, "second"))+ assert len(calls) == 2+++def test_a_failed_reprobe_replaces_the_stale_pass(probe_env):+ clock, verdicts, gate, calls = probe_env+ verdicts.extend([(True, "ok"), (False, "now blocked")])+ sandbox_probe.probe(_Backend())+ clock.now += sandbox_probe._CACHE_TTL_SECONDS + 1+ assert sandbox_probe.probe(_Backend()) == (True, "ok")+ assert _wait_for(lambda: sandbox_probe.probe(_Backend()) == (False, "now blocked"))+++def test_a_fail_is_never_served_stale(probe_env):+ clock, verdicts, gate, calls = probe_env+ verdicts.extend([(False, "blocked"), (True, "fixed")])+ assert sandbox_probe.probe(_Backend()) == (False, "blocked")+ clock.now += sandbox_probe._CACHE_TTL_UNAVAILABLE_SECONDS + 1+ assert sandbox_probe.probe(_Backend()) == (True, "fixed")+ assert all(name != "unsloth-sandbox-reprobe" for name in calls)+++def test_a_pass_past_the_grace_is_probed_in_the_foreground(probe_env):+ clock, verdicts, gate, calls = probe_env+ verdicts.extend([(True, "old"), (True, "new")])+ sandbox_probe.probe(_Backend())+ clock.now += sandbox_probe._CACHE_TTL_SECONDS + sandbox_probe._STALE_GRACE_SECONDS + 1+ assert sandbox_probe.probe(_Backend()) == (True, "new")+ assert all(name != "unsloth-sandbox-reprobe" for name in calls)+++def test_a_stale_pass_is_reprobed_in_the_foreground_when_background_probes_are_off(+ probe_env, monkeypatch+):+ clock, verdicts, gate, calls = probe_env+ monkeypatch.setenv(os_sandbox.WARMUP_DISABLE_ENV, "1")+ verdicts.extend([(True, "old"), (False, "broke")])+ sandbox_probe.probe(_Backend())+ clock.now += sandbox_probe._CACHE_TTL_SECONDS + 1+ assert sandbox_probe.probe(_Backend()) == (False, "broke")+ assert all(name != "unsloth-sandbox-reprobe" for name in calls)+ assert not sandbox_probe._refreshing+++def test_a_reset_during_a_reprobe_keeps_its_result_out(probe_env):+ clock, verdicts, gate, calls = probe_env+ verdicts.extend([(True, "ok"), (True, "from before the reset"), (False, "after")])+ sandbox_probe.probe(_Backend())+ clock.now += sandbox_probe._CACHE_TTL_SECONDS + 1+ gate.clear()+ sandbox_probe.probe(_Backend())+ assert _wait_for(lambda: len(calls) == 2)+ sandbox_probe.reset_probe_cache()+ gate.set()+ assert _wait_for(lambda: not sandbox_probe._refreshing)+ assert sandbox_probe.probe(_Backend()) == (False, "after")++[email protected](autouse = True)+def _no_host_setup_probe(monkeypatch):+ # The setup plan would run `sudo -n true` on this host; the capability tests only need its shape.+ from core.inference import sandbox_setup_plan+ monkeypatch.setattr(+ sandbox_setup_plan,+ "detect",+ lambda *a, **k: sandbox_setup_plan.SetupPlan(platform = sys.platform, reason = "test"),+ )+++def _capability_client(authenticated = True):+ from routes.sandbox_capability import router++ app = FastAPI()+ app.include_router(router, prefix = "/api/sandbox")+ if authenticated:+ app.dependency_overrides[get_current_subject] = lambda: "someone"+ return TestClient(app)+++def test_capability_requires_a_signed_in_user():+ response = _capability_client(authenticated = False).get("/api/sandbox/capability")+ assert response.status_code in (401, 403)+++def test_capability_before_the_first_answer():+ body = _capability_client().get("/api/sandbox/capability").json()+ assert body["python_os_isolated"] is False+ assert body["terminal_os_isolated"] is False+ assert body["backend"] == "unknown"+ assert body["setup_action"] is None and body["can_run_setup"] is False++[email protected]("known", ["python", "terminal"])+def test_capability_stays_unknown_until_both_tools_have_an_answer(known):+ os_sandbox.note_tool_isolation(known, True, backend = "bubblewrap", reason = "passed")+ body = _capability_client().get("/api/sandbox/capability").json()+ assert body["backend"] == "unknown"+ assert body["setup_action"] is None and body["can_run_setup"] is False+++def test_capability_reports_the_cached_answers():+ os_sandbox.note_tool_isolation("python", True, backend = "bubblewrap", reason = "passed")+ os_sandbox.note_tool_isolation("terminal", False, backend = "none", reason = "no bash")+ body = _capability_client().get("/api/sandbox/capability").json()+ assert body["python_os_isolated"] is True+ assert body["terminal_os_isolated"] is False+ assert body["backend"] == "bubblewrap"+ assert body["reason"] == "no bash"+++ "mode,tool,isolated,risky", list(itertools.product(MODES, TOOLS, ISOLATION, (True, False)))+)+def test_strict_launch_matrix(isolation, mode, 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},+ is_high_risk = _risk,+ )+ prompted = tool_policy.needs_tool_confirmation(**decision, never_needs = lambda _n: False)+ strict = tool_policy.requires_os_isolation(**decision, prompted = prompted)+ assert strict is (+ mode == "off" and tool in ("python", "terminal") and isolated is True and risky+ )+++def test_a_refresh_between_the_two_decisions_cannot_skip_both(isolation):+ # The launch must follow the prompt decision, not re-read a cache refreshed in between.+ isolation["python"] = True+ decision = dict(+ confirm_tool_calls = True,+ bypass_permissions = False,+ permission_mode = "off",+ name = "python",+ arguments = {"risky": True},+ is_high_risk = _risk,+ )+ prompted = tool_policy.needs_tool_confirmation(**decision, never_needs = lambda _n: False)+ isolation["python"] = False+ assert prompted is False+ assert tool_policy.requires_os_isolation(**decision, prompted = prompted) is True+++def test_an_approved_prompt_runs_without_the_strict_launch(isolation):+ isolation["python"] = False+ assert not tool_policy.requires_os_isolation(+ confirm_tool_calls = True,+ bypass_permissions = False,+ permission_mode = "off",+ name = "python",+ arguments = {"risky": True},+ is_high_risk = _risk,+ prompted = True,+ )+++def test_strict_launch_needs_an_armed_gate(isolation):+ isolation["python"] = True+ assert not tool_policy.requires_os_isolation(+ confirm_tool_calls = False,+ bypass_permissions = False,+ permission_mode = "off",+ name = "python",+ arguments = {"risky": True},+ is_high_risk = _risk,+ prompted = False,+ )+++class _ModeRecordingExecuteTool:+ def __init__(self):+ self.modes = []++ 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",+ ):+ self.modes.append(tool_execution_mode)+ return f"RESULT[{name}]"+++ "mode,code,expected",+ [+ ("off", 'import os; os.remove(\\"x\\")', "required"),+ ("off", "print(1)", "auto"),+ ("auto", "print(1)", "auto"),+ ],+)+def test_the_loop_launches_an_unasked_risky_call_strictly(mode, code, expected):+ import uuid++ from core.inference.safetensors_agentic import run_safetensors_tool_loop++ os_sandbox.note_tool_isolation("python", True, backend = "bubblewrap")+ turns = iter(+ [f'<tool_call>{{"name": "python", "arguments": {{"code": "{code}"}}}}</tool_call>', "final"]+ )++ def single_turn(_messages):+ try:+ yield next(turns)+ except StopIteration:+ return++ exec_fn = _ModeRecordingExecuteTool()+ events = list(+ run_safetensors_tool_loop(+ single_turn = single_turn,+ messages = [{"role": "user", "content": "hi"}],+ tools = [{"type": "function", "function": {"name": "python"}}],+ execute_tool = exec_fn,+ session_id = f"strict-{uuid.uuid4().hex}",+ confirm_tool_calls = True,+ permission_mode = mode,+ )+ )+ starts = [e for e in events if e["type"] == "tool_start"]+ assert starts and starts[0]["awaiting_confirmation"] is False+ assert exec_fn.modes == [expected]+++def test_a_strict_launch_is_refused_when_the_sandbox_stopped_working(monkeypatch):+ from core.inference import tools++ os_sandbox.note_tool_isolation("python", True, backend = "bubblewrap")+ monkeypatch.setattr(+ os_sandbox,+ "capability_snapshot",+ lambda **_kw: os_sandbox.SandboxCapability(+ backend = "bubblewrap",+ available = False,+ reason = "bwrap: setting up uid map: Permission denied",+ protection_state = "unavailable",+ limitations = (),+ remediation = "Load the AppArmor profile.",+ ),+ )+ tools._last_tool_execution_record = None+ out = tools.execute_tool(+ "python",+ {"code": "print('RAN')"},+ session_id = "__LOCALID_strict_refusal",+ timeout = 60,+ tool_execution_mode = "required",+ )+ assert "OS_ISOLATION_UNAVAILABLE" in out and "RAN" not in out+ record = tools._last_tool_execution_record+ assert record is None or record.effective_mode != "software_safeguards"+ auto = tools.execute_tool(+ "python", {"code": "print('RAN')"}, session_id = "__LOCALID_strict_refusal", timeout = 60+ )+ assert "RAN" in auto+++def test_every_loop_launches_strictly_through_the_mode_parameter():+ import inspect++ 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 "requires_os_isolation(" in source, module.__name__+ assert 'kwargs["tool_execution_mode"] = "required"' in source, module.__name__+++def test_a_launch_does_not_republish_an_answer_a_reset_cleared(monkeypatch, tmp_path):+ # Settings or a failed launch reset the cached answers while this launch was still checking.+ def snapshot(**_kw):+ os_sandbox.forget_tool_isolation()+ return os_sandbox.SandboxCapability(+ backend = "bubblewrap",+ available = False,+ reason = "stubbed",+ protection_state = "unavailable",+ limitations = (),+ )++ monkeypatch.setattr(os_sandbox, "capability_snapshot", snapshot)+ plan = os_sandbox.ToolLaunchPlan(+ argv = (sys.executable, "-c", "pass"),+ workdir = str(tmp_path),+ env = {},+ execution_kind = "python",+ )+ try:+ os_sandbox.prepare_tool_launch(plan)+ except Exception: # noqa: BLE001 - only the cached answer matters here+ pass+ assert not os_sandbox.has_tool_isolation_answer("python")++[email protected](sys.platform == "win32", reason = "the Windows backend prepares through MXC")+ "error,forgotten",+ [+ (os_sandbox.SandboxUnavailableError("bubblewrap (bwrap) is not installed"), True),+ (os_sandbox.WorkdirUnsafeError("a host channel in the workdir"), False),+ ],+)+def test_a_backend_that_refuses_at_preparation_drops_the_cached_pass(+ monkeypatch, tmp_path, error, forgotten+):+ import importlib++ backend = importlib.import_module(+ "core.inference.sandbox_linux"+ if sys.platform == "linux"+ else "core.inference.sandbox_macos"+ )+ monkeypatch.setenv(os_sandbox.WARMUP_DISABLE_ENV, "1")+ monkeypatch.setattr(+ os_sandbox,+ "capability_snapshot",+ lambda **_kw: os_sandbox.SandboxCapability(+ backend = backend.BACKEND_NAME, available = True, reason = "cached pass"+ ),+ )++ def refuse(_plan, *_args):+ raise error++ monkeypatch.setattr(backend, "prepare", refuse)+ plan = os_sandbox.ToolLaunchPlan(+ argv = (sys.executable, "-c", "pass"),+ workdir = str(tmp_path),+ env = {},+ requested_mode = "required",+ timeout_seconds = 10,+ execution_kind = "python",+ )+ with pytest.raises(type(error)):+ os_sandbox.prepare_tool_launch(plan)+ assert (os_sandbox.cached_tool_capability("python") is None) is forgottendiff --git a/studio/backend/tests/test_sandbox_probe.py b/studio/backend/tests/test_sandbox_probe.pyindex edc0eda2a85..0c4f8b15c51 100644--- a/studio/backend/tests/test_sandbox_probe.py+++ b/studio/backend/tests/test_sandbox_probe.py@@ -373,12 +373,15 @@ def test_linux_runtime_identity_includes_the_verified_bwrap(monkeypatch):def test_an_expired_verdict_is_re_probed(monkeypatch):- """Set before the first probe: the expiry is stamped when the verdict is stored."""+ """Set before the first probe: the expiry is stamped when the verdict is stored. With no stale+ grace the re-probe is in the foreground (test_permission_mode_degrade covers the grace)."""monkeypatch.setattr(sandbox_probe, "_CACHE_TTL_SECONDS", 0.0)+ monkeypatch.setattr(sandbox_probe, "_STALE_GRACE_SECONDS", 0.0)backend = _Backend("confining", _confining)sandbox_probe.probe(backend)sandbox_probe.probe(backend)assert backend.calls == 2+ assert not sandbox_probe._refreshingdef test_the_cache_cannot_grow_without_bound():@@ -406,7 +409,12 @@ def test_this_host_reports_unavailable_with_something_actionable():!= 0)if blocked and os.path.exists("/proc/sys/kernel/apparmor_restrict_unprivileged_userns"):- assert "apparmor_restrict_unprivileged_userns" in capability.remediation+ if shutil.which("bwrap") is None:+ # Not installed yet: the one copy-paste installs it and loads Ubuntu's profile.+ if "apt-get" in (os_sandbox.bwrap_install_command() or ""):+ assert os_sandbox._BWRAP_APPARMOR_FIX in capability.remediation+ else:+ assert "apparmor_restrict_unprivileged_userns" in capability.remediationdef test_the_abstract_socket_control_is_paired_like_every_other(monkeypatch):diff --git a/studio/backend/tests/test_sandbox_runtime_install.py b/studio/backend/tests/test_sandbox_runtime_install.pynew file mode 100644index 00000000000..3868e8f5b88--- /dev/null+++ b/studio/backend/tests/test_sandbox_runtime_install.py@@ -0,0 +1,251 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Settings > Sandbox > Install runtime: the plan, the one-at-a-time job, and its route."""++from pathlib import Path+import sys+import time+import types as _types++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++import platform++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import routes.settings as settings+from core.inference import (+ mxc_host_prep_job,+ mxc_probe,+ mxc_runtime,+ sandbox_probe,+ sandbox_setup_job as job_mod,+ sandbox_setup_plan as plan_mod,+ tools,+)+from utils import client_ip+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+++class _Proc:+ def __init__(self, lines, code):+ self.stdout = iter(line + "\n" for line in lines)+ self._code = code++ def wait(self):+ return self._code+++def x64_windows(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(platform, "machine", lambda: "AMD64")+ monkeypatch.setattr(+ sys, "getwindowsversion", lambda: _types.SimpleNamespace(build = 26100), raising = False+ )+ monkeypatch.setattr(plan_mod, "windows_runtime_installed", lambda: False)+ monkeypatch.setattr(+ mxc_runtime, "_installed_package_root", lambda: Path("C:/studio/mxc-runtime")+ )+ monkeypatch.setattr(mxc_host_prep_job, "current", lambda: None)+ resets = []+ monkeypatch.setattr(sandbox_probe, "reset_probe_cache", lambda: resets.append("probe"))+ monkeypatch.setattr(mxc_probe, "invalidate_cache", lambda: resets.append("mxc"))+ monkeypatch.setattr(tools, "reset_terminal_profile_cache", lambda: resets.append("terminal"))+ monkeypatch.setattr(job_mod, "_current", None)+ monkeypatch.setattr(job_mod, "_on_finish", [])+ return resets+++def _wait(job, limit = 5.0):+ deadline = time.monotonic() + limit+ while job.state == "running" and time.monotonic() < deadline:+ time.sleep(0.01)+ return job+++ "machine, build, expected",+ [+ ("AMD64", 26100, None),+ ("x86_64", 26200, None),+ ("ARM64", 26100, "arch"),+ ("AMD64", 22631, "build"),+ ],+)+def test_only_x64_windows_11_24h2_or_newer_can_run_mxc(monkeypatch, machine, build, expected):+ monkeypatch.setattr(platform, "machine", lambda: machine)+ monkeypatch.setattr(+ sys, "getwindowsversion", lambda: _types.SimpleNamespace(build = build), raising = False+ )+ assert plan_mod.windows_runtime_unsupported() == expected+ assert plan_mod.windows_runtime_supported() is (expected is None)+++def test_the_plan_is_the_setup_ps1_install_call(x64_windows):+ plan = plan_mod.windows_runtime_plan()+ assert plan.action == plan_mod.WINDOWS_RUNTIME+ (step,) = plan.steps+ assert step[0] == sys.executable+ assert step[1].endswith("install_mxc_prebuilt.py") and Path(step[1]).is_file()+ assert step[2:] == ("--install-dir", str(Path("C:/studio/mxc-runtime")))+ assert plan.manual_command.startswith("& '")+++def test_every_powershell_single_quote_stays_inside_the_pasted_path():+ path = "C:\\Users\\O’Neil‘s ‚x‛ 'y'\\python.exe"+ line = plan_mod.powershell_command([(path, "--flag")])+ assert line == "& 'C:\\Users\\O’’Neil‘‘s ‚‚x‛‛ ''y''\\python.exe' '--flag'"+++def test_no_plan_when_installed_or_unsupported(x64_windows, monkeypatch):+ monkeypatch.setattr(plan_mod, "windows_runtime_installed", lambda: True)+ assert plan_mod.windows_runtime_plan().action is None+ monkeypatch.setattr(plan_mod, "windows_runtime_installed", lambda: False)+ monkeypatch.setattr(platform, "machine", lambda: "ARM64")+ plan = plan_mod.windows_runtime_plan()+ assert plan.action is None and "x64" in plan.reason+++def test_a_successful_install_resets_every_cache(x64_windows, monkeypatch):+ spawned = []+ monkeypatch.setattr(+ job_mod, "_spawn", lambda argv, *_env: spawned.append(argv) or _Proc(["installed"], 0)+ )+ finished = []+ job_mod.add_finish_hook(lambda: finished.append(True))+ job = _wait(job_mod.start(plan_mod.WINDOWS_RUNTIME))+ assert job.state == "succeeded" and job.exit_code == 0 and job.output_tail == ["installed"]+ assert len(spawned) == 1 and spawned[0][1].endswith("install_mxc_prebuilt.py")+ assert set(x64_windows) == {"probe", "mxc", "terminal"} and finished == [True]+++def test_a_runtime_in_use_says_so(x64_windows, monkeypatch):+ monkeypatch.setattr(job_mod, "_spawn", lambda argv, *_env: _Proc(["busy"], 3))+ job = _wait(job_mod.start(plan_mod.WINDOWS_RUNTIME))+ assert job.state == "failed" and job.exit_code == 3+ assert "using the runtime" in job.note+++def test_a_spawn_failure_is_a_failed_job(x64_windows, monkeypatch):+ def boom(argv, *_env):+ raise OSError("no python")++ monkeypatch.setattr(job_mod, "_spawn", boom)+ job = _wait(job_mod.start(plan_mod.WINDOWS_RUNTIME))+ assert job.state == "failed" and "no python" in job.output_tail[-1]+++def test_one_install_at_a_time(x64_windows, monkeypatch):+ running = job_mod.SetupJob(id = "j1", operation = plan_mod.WINDOWS_RUNTIME)+ monkeypatch.setattr(job_mod, "_current", running)+ assert job_mod.start(plan_mod.WINDOWS_RUNTIME) is running+++def test_never_beside_prepare_this_pc(x64_windows, monkeypatch):+ monkeypatch.setattr(+ mxc_host_prep_job, "current", lambda: mxc_host_prep_job.HostPrepJob(id = "prep")+ )+ with pytest.raises(job_mod.SetupUnavailable, match = "still running"):+ job_mod.start(plan_mod.WINDOWS_RUNTIME)+++def test_unknown_operation_and_nothing_to_do_are_refused(x64_windows, monkeypatch):+ with pytest.raises(job_mod.SetupUnavailable):+ job_mod.start("format-the-disk")+ monkeypatch.setattr(plan_mod, "windows_runtime_installed", lambda: True)+ with pytest.raises(job_mod.SetupUnavailable, match = "already installed"):+ job_mod.start(plan_mod.WINDOWS_RUNTIME)+++def _client(account, via_api_key = False):+ app = FastAPI()+ app.include_router(settings.router)++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[settings.get_current_subject] = subject+ app.dependency_overrides[settings.authenticated_via_api_key] = lambda: via_api_key+ return TestClient(app, raise_server_exceptions = False)+++def route(x64_windows, monkeypatch):+ started = []++ def start(operation):+ started.append(operation)+ return job_mod.SetupJob(id = "rt1", operation = operation)++ monkeypatch.setattr(job_mod, "start", start)+ return started+++def test_owner_starts_the_install_even_from_a_remote_browser(route, monkeypatch):+ # No administrator prompt is involved, so the local-console rule of Prepare this PC does not apply.+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: False)+ with _client(OWNER) as client:+ response = client.post("/sandbox/setup", json = {"operation": "windows-runtime"})+ assert response.status_code == 200, response.text+ body = response.json()+ assert body["state"] == "running" and body["operation"] == "windows-runtime"+ assert route == ["windows-runtime"]+++def test_reading_the_job_when_none_ran(route):+ with _client(OWNER) as client:+ assert client.get("/sandbox/setup").json()["state"] == "idle"+++def test_api_keys_and_other_accounts_cannot_install(route):+ with _client(OWNER, via_api_key = True) as client:+ assert (+ client.post("/sandbox/setup", json = {"operation": "windows-runtime"}).status_code == 403+ )+ with _client(ALICE) as client:+ assert (+ client.post("/sandbox/setup", json = {"operation": "windows-runtime"}).status_code == 403+ )+ assert client.get("/sandbox/setup").status_code == 403+ assert route == []+++ "body", [{"operation": "format-the-disk"}, {"operation": "windows-runtime", "x": 1}, {}]+)+def test_only_the_fixed_operation_is_accepted(route, body):+ with _client(OWNER) as client:+ assert client.post("/sandbox/setup", json = body).status_code == 422+ assert route == []+++def test_not_on_other_platforms(route, monkeypatch):+ monkeypatch.setattr(sys, "platform", "linux")+ with _client(OWNER) as client:+ assert (+ client.post("/sandbox/setup", json = {"operation": "windows-runtime"}).status_code == 409+ )+ assert route == []+++def test_an_unavailable_install_is_a_conflict(x64_windows, monkeypatch):+ monkeypatch.setattr(platform, "machine", lambda: "ARM64")+ with _client(OWNER) as client:+ response = client.post("/sandbox/setup", json = {"operation": "windows-runtime"})+ assert response.status_code == 409 and "x64" in response.json()["detail"]diff --git a/studio/backend/tests/test_sandbox_settings_route.py b/studio/backend/tests/test_sandbox_settings_route.pynew file mode 100644index 00000000000..0b44a0933d3--- /dev/null+++ b/studio/backend/tests/test_sandbox_settings_route.py@@ -0,0 +1,344 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Owner-only; writes need a UI session, prepare also a loopback client (the UAC prompt is local)."""++from pathlib import Path+import sys+import types as _types++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import routes.settings as settings+from core.inference import (+ mxc_host_prep_job,+ mxc_policy,+ mxc_probe,+ mxc_read_grants,+ mxc_runtime,+ os_sandbox,+ tools,+)+from utils import client_ip, mxc_isolation_settings+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+++def _cap(available = True, backend = "bubblewrap"):+ return os_sandbox.SandboxCapability(+ backend = backend,+ available = available,+ reason = "probe passed" if available else "probe failed",+ protection_state = "preview" if available else "unavailable",+ limitations = ("network_not_confined",),+ )+++def host(monkeypatch):+ calls = {"snapshot": 0, "invalidate": 0, "profile_reset": 0, "revoke": 0, "start": 0}+ saved = {"dacl": False, "grants": True}++ def snapshot(**_kw):+ calls["snapshot"] += 1+ return _cap()++ monkeypatch.setattr(os_sandbox, "capability_snapshot", snapshot)+ monkeypatch.setattr(settings, "_sandbox_windows_status", lambda: _windows_block(saved))+ monkeypatch.setattr(settings, "_sandbox_terminal_target", lambda: ("/bin/bash", None))+ monkeypatch.setattr(+ mxc_probe,+ "invalidate_cache",+ lambda: calls.__setitem__("invalidate", calls["invalidate"] + 1),+ )+ monkeypatch.setattr(+ tools,+ "reset_terminal_profile_cache",+ lambda: calls.__setitem__("profile_reset", calls["profile_reset"] + 1),+ )++ def revoke():+ calls["revoke"] += 1+ return ("C:\\runtime",)++ monkeypatch.setattr(mxc_read_grants, "revoke_recorded", revoke)+ monkeypatch.setattr(mxc_policy, "dacl_fallback_enabled", lambda: saved["dacl"])+ monkeypatch.setattr(mxc_read_grants, "enabled", lambda: saved["grants"])+ monkeypatch.setattr(+ mxc_isolation_settings, "set_dacl_fallback_setting", lambda v: saved.__setitem__("dacl", v)+ )+ monkeypatch.setattr(+ mxc_isolation_settings,+ "set_persistent_grants_setting",+ lambda v: saved.__setitem__("grants", v),+ )+ monkeypatch.setattr(mxc_isolation_settings, "locked_by_environment", lambda _name: False)+ monkeypatch.setattr(mxc_runtime, "installation_identity", lambda: "identity")++ def start():+ calls["start"] += 1+ return mxc_host_prep_job.HostPrepJob(id = "job1")++ monkeypatch.setattr(mxc_host_prep_job, "start", start)+ monkeypatch.setattr(mxc_host_prep_job, "current", lambda: None)+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: True)+ settings._forget_sandbox_status()+ return calls, saved+++def _windows_block(saved):+ return settings.SandboxWindowsStatus(+ runtime_installed = True,+ allow_dacl_fallback = saved["dacl"],+ allow_dacl_fallback_saved = saved["dacl"],+ dacl_locked_by_environment = False,+ persistent_read_grants = saved["grants"],+ persistent_read_grants_saved = saved["grants"],+ grants_locked_by_environment = False,+ host_prep_missing = ["prepare-null-device"],+ )+++def windows(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+++def posix(monkeypatch):+ monkeypatch.setattr(sys, "platform", "linux")+++def _client(account, via_api_key = False):+ app = FastAPI()+ app.include_router(settings.router)++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[settings.get_current_subject] = subject+ app.dependency_overrides[settings.authenticated_via_api_key] = lambda: via_api_key+ return TestClient(app, raise_server_exceptions = False)+++def test_owner_reads_status_and_it_is_cached_until_refresh(host, posix):+ calls, _saved = host+ with _client(OWNER) as client:+ first = client.get("/sandbox")+ assert first.status_code == 200, first.text+ body = first.json()+ assert body["python"]["backend"] == "bubblewrap" and body["python"]["available"] is True+ assert body["terminal"]["limitations"] == ["network_not_confined"]+ assert body["windows"] is None+ client.get("/sandbox")+ assert calls["snapshot"] == 2 # python + terminal, once+ client.get("/sandbox", params = {"refresh": "true"})+ assert calls["snapshot"] == 4+++def test_a_windows_refresh_picks_the_terminal_from_fresh_verdicts(host, windows, monkeypatch):+ from core.inference import sandbox_probe++ calls, _saved = host+ order = []+ monkeypatch.setattr(sandbox_probe, "reset_probe_cache", lambda: order.append("reset"))+ monkeypatch.setattr(+ settings, "_sandbox_terminal_target", lambda: order.append("target") or ("cmd.exe", None)+ )+ forced = []++ def snapshot(force = False, **kw):+ forced.append((kw["execution_kind"], force))+ return _cap()++ monkeypatch.setattr(os_sandbox, "capability_snapshot", snapshot)+ with _client(OWNER) as client:+ client.get("/sandbox", params = {"refresh": "true"})+ assert order == ["reset", "target"]+ assert calls["invalidate"] == 1 and calls["profile_reset"] == 1+ assert forced == [("python", True), ("terminal", False)]+++def test_a_windows_refresh_still_records_what_it_just_checked(host, windows, monkeypatch):+ monkeypatch.setattr(settings, "_sandbox_terminal_target", lambda: ("cmd.exe", "cmd_isolated"))+ monkeypatch.setattr(settings, "_sandbox_setup_status", lambda _ready: None)+ os_sandbox.forget_tool_isolation()+ with _client(OWNER) as client:+ assert client.get("/sandbox", params = {"refresh": "true"}).status_code == 200+ assert os_sandbox.cached_tool_isolation("python") is True+ assert os_sandbox.cached_tool_isolation("terminal") is True+ os_sandbox.forget_tool_isolation()+++def test_windows_status_carries_the_opt_in_block(host, windows):+ with _client(OWNER) as client:+ body = client.get("/sandbox").json()+ assert body["platform"] == "win32"+ assert body["windows"]["host_prep_missing"] == ["prepare-null-device"]+ assert body["windows"]["prepare_repeats_after_restart"] is True+++def test_managed_account_is_refused(host, windows):+ with _client(ALICE) as client:+ assert client.get("/sandbox").status_code == 403+ assert client.put("/sandbox", json = {"allow_dacl_fallback": True}).status_code == 403+ assert client.post("/sandbox/prepare").status_code == 403+ calls, saved = host+ assert saved["dacl"] is False and calls["start"] == 0+++def test_api_key_cannot_change_or_prepare(host, windows):+ calls, saved = host+ with _client(OWNER, via_api_key = True) as client:+ assert client.put("/sandbox", json = {"allow_dacl_fallback": True}).status_code == 403+ assert client.post("/sandbox/prepare").status_code == 403+ assert saved["dacl"] is False and calls["start"] == 0+++def test_turning_on_saves_and_resets_every_cache(host, windows):+ calls, saved = host+ with _client(OWNER) as client:+ client.get("/sandbox")+ response = client.put("/sandbox", json = {"allow_dacl_fallback": True})+ assert response.status_code == 200, response.text+ assert saved["dacl"] is True+ assert response.json()["windows"]["allow_dacl_fallback"] is True+ assert calls["invalidate"] == 1 and calls["profile_reset"] == 1+ assert calls["revoke"] == 0 and response.json()["grants_restored"] is None+++def test_turning_off_takes_the_read_grants_back(host, windows):+ calls, saved = host+ saved["dacl"] = True+ with _client(OWNER) as client:+ response = client.put("/sandbox", json = {"allow_dacl_fallback": False})+ assert response.status_code == 200, response.text+ assert calls["revoke"] == 1 and response.json()["grants_restored"] == 1+++def test_a_setting_held_by_the_environment_is_refused(host, windows, monkeypatch):+ monkeypatch.setattr(+ mxc_isolation_settings,+ "locked_by_environment",+ lambda name: name == mxc_policy.DACL_FALLBACK_ENV,+ )+ _calls, saved = host+ with _client(OWNER) as client:+ response = client.put("/sandbox", json = {"allow_dacl_fallback": True})+ assert response.status_code == 409+ assert mxc_policy.DACL_FALLBACK_ENV in response.json()["detail"]+ assert client.put("/sandbox", json = {"persistent_read_grants": False}).status_code == 200+ assert saved["dacl"] is False and saved["grants"] is False++[email protected]("body", [{"allow_dacl_fallback": "yes"}, {"unknown": True}])+def test_malformed_bodies_are_refused(host, windows, body):+ with _client(OWNER) as client:+ assert client.put("/sandbox", json = body).status_code == 422+++def test_settings_are_windows_only(host, posix):+ with _client(OWNER) as client:+ assert client.put("/sandbox", json = {"allow_dacl_fallback": True}).status_code == 409+ assert client.post("/sandbox/prepare").status_code == 409+++def test_prepare_starts_one_job_from_the_local_console(host, windows):+ calls, _saved = host+ with _client(OWNER) as client:+ response = client.post("/sandbox/prepare")+ assert response.status_code == 200, response.text+ assert response.json()["state"] == "running" and response.json()["id"] == "job1"+ assert client.get("/sandbox/prepare").json() == {+ "state": "idle",+ "id": None,+ "started_at": None,+ "finished_at": None,+ "exit_code": None,+ "output_tail": [],+ "steps": [],+ }+ assert calls["start"] == 1+++def test_prepare_refused_while_another_setup_runs_is_a_conflict(host, windows, monkeypatch):+ from core.inference import mxc_host_prep_job, sandbox_setup_job++ def busy():+ raise sandbox_setup_job.SetupUnavailable(+ "Another sandbox setup (windows-runtime) is still running"+ )++ monkeypatch.setattr(mxc_host_prep_job, "start", busy)+ with _client(OWNER) as client:+ response = client.post("/sandbox/prepare")+ assert response.status_code == 409 and "windows-runtime" in response.json()["detail"]+++def test_prepare_is_refused_from_a_remote_browser(host, windows, monkeypatch):+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: False)+ calls, _saved = host+ with _client(OWNER) as client:+ response = client.post("/sandbox/prepare")+ assert response.status_code == 403+ assert "computer running Unsloth" in response.json()["detail"]+ assert calls["start"] == 0+++def test_a_loopback_peer_relaying_a_remote_browser_is_not_local():+ from types import SimpleNamespace++ def request(+ peer,+ host = "127.0.0.1:8888",+ **headers,+ ):+ return SimpleNamespace(+ client = SimpleNamespace(host = peer, port = 0), headers = {"host": host, **headers}+ )++ assert client_ip.is_direct_local_request(request("127.0.0.1")) is True+ # A reverse proxy or tunnel on this machine: the peer is loopback, the browser is not.+ for headers in ({"x-forwarded-for": "203.0.113.7"}, {"cf-connecting-ip": "203.0.113.7"}):+ assert client_ip.is_direct_local_request(request("127.0.0.1", **headers)) is False+ assert client_ip.is_direct_local_request(request("127.0.0.1", "studio.example.com")) is False+ assert client_ip.is_direct_local_request(request("192.168.1.10")) is False+++def test_prepare_without_the_runtime_is_refused(host, windows, monkeypatch):+ def missing():+ raise mxc_runtime.MxcRuntimeUnavailable("the managed MXC runtime is not installed")++ monkeypatch.setattr(mxc_runtime, "installation_identity", missing)+ calls, _saved = host+ with _client(OWNER) as client:+ assert client.post("/sandbox/prepare").status_code == 409+ assert calls["start"] == 0+++def test_a_status_built_before_a_save_is_not_cached(host, windows, monkeypatch):+ real_build = settings._build_sandbox_status++ def build_then_save(force):+ status = real_build(force)+ settings._forget_sandbox_status() # a PUT landed while this status was being built+ return status++ monkeypatch.setattr(settings, "_build_sandbox_status", build_then_save)+ settings._sandbox_status()+ assert settings._sandbox_status_cache is Nonediff --git a/studio/backend/tests/test_sandbox_setup_job.py b/studio/backend/tests/test_sandbox_setup_job.pynew file mode 100644index 00000000000..7fa79789947--- /dev/null+++ b/studio/backend/tests/test_sandbox_setup_job.py@@ -0,0 +1,416 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The Settings sandbox setup job, run against fake sudo, pkexec and helper scripts on this host.++The fakes record their argv and exit with a chosen code; nothing privileged ever runs.+"""++import json+import os+import shlex+import sys+import threading+import time++import pytest++from core.inference import (+ mxc_host_prep_job,+ mxc_probe,+ os_sandbox,+ sandbox_probe,+ sandbox_setup_job as job_mod,+ sandbox_setup_plan as plan_mod,+ tools,+)++pytestmark = pytest.mark.skipif(sys.platform == "win32", reason = "the fakes are POSIX shell scripts")++_STEPS = (+ ("apt-get", "install", "-y", "bubblewrap"),+ ("apparmor_parser", "-r", "/etc/apparmor.d/bwrap-userns-restrict"),+)+++def env(monkeypatch, tmp_path):+ calls = {"resets": 0, "hooks": 0}+ record = tmp_path / "calls.jsonl"+ monkeypatch.setattr(job_mod, "_current", None)+ monkeypatch.setattr(job_mod, "_on_finish", [])+ monkeypatch.setattr(mxc_host_prep_job, "_current", None)++ def count():+ calls["resets"] += 1++ monkeypatch.setattr(sandbox_probe, "reset_probe_cache", count)+ monkeypatch.setattr(+ plan_mod,+ "elevated_steps",+ lambda steps: [[f"/pinned/{step[0]}", *step[1:]] for step in steps],+ )+ monkeypatch.setattr(+ plan_mod, "trusted_system_binary", lambda name: "/bin/sh" if name == "sh" else None+ )+ monkeypatch.setattr(os_sandbox, "_linux_userns_blocked_by_apparmor", _Clearable(count))+ monkeypatch.setattr(mxc_probe, "invalidate_cache", count)+ monkeypatch.setattr(tools, "reset_terminal_profile_cache", count)+ monkeypatch.setattr(plan_mod, "invalidate", count)++ def fake(+ name,+ code = 0,+ output = "",+ gate = None,+ ):+ path = tmp_path / name+ wait = f'while [ ! -e "{gate}" ]; do sleep 0.05; done\n' if gate else ""+ path.write_text(+ "#!/bin/sh\n"+ f"{shlex.quote(sys.executable)} -c "+ '\'import json, sys; open(sys.argv[1], "a").write(json.dumps(sys.argv[2:]) + "\\n")\' '+ f'{shlex.quote(str(record))} "$0" "$@"\n'+ + (f"printf '%s\\n' {shlex.quote(output)}\n" if output else "")+ + wait+ + f"exit {code}\n"+ )+ path.chmod(0o755)+ return str(path)++ def recorded():+ if not record.exists():+ return []+ return [json.loads(line) for line in record.read_text().splitlines()]++ calls["fake"], calls["recorded"] = fake, recorded+ return calls+++class _Clearable:+ def __init__(self, hook):+ self.cache_clear = hook++ def __call__(self):+ return False+++def _linux_plan(monkeypatch, elevation, path):+ plan = plan_mod.SetupPlan(+ platform = "linux",+ action = plan_mod.LINUX_INSTALL,+ elevation = elevation,+ steps = _STEPS,+ manual_command = "sudo apt-get install -y bubblewrap && sudo apparmor_parser -r x",+ )+ monkeypatch.setattr(plan_mod, "detect", lambda *a, **k: plan)+ monkeypatch.setattr(plan_mod, "linux_elevation", lambda **_kw: (elevation, path))+ return plan+++def _pinned(step):+ return [f"/pinned/{step[0]}", *step[1:]]+++def _settle(job, seconds = 30):+ deadline = time.monotonic() + seconds+ while job.state == "running" and time.monotonic() < deadline:+ time.sleep(0.02)+ return job+++def test_sudo_runs_each_fixed_step_non_interactively(monkeypatch, env):+ sudo = env["fake"]("sudo")+ _linux_plan(monkeypatch, "sudo", sudo)+ job_mod.add_finish_hook(lambda: env.__setitem__("hooks", env["hooks"] + 1))+ job = _settle(job_mod.start(plan_mod.LINUX_INSTALL))+ assert job.state == "succeeded" and job.exit_code == 0+ assert env["recorded"]() == [+ [sudo, "-n", *_pinned(_STEPS[0])],+ [sudo, "-n", *_pinned(_STEPS[1])],+ ]+ assert env["resets"] >= 5 and env["hooks"] == 1+++def test_a_root_process_runs_each_pinned_step_directly(monkeypatch, env):+ _linux_plan(monkeypatch, "root", None)+ commands, run_env = job_mod._commands(plan_mod.detect())+ assert commands == [_pinned(step) for step in _STEPS]+ assert run_env == dict(plan_mod.ELEVATED_ENV)+++def test_sudo_wanting_a_password_stops_and_hands_over_the_command(monkeypatch, env):+ sudo = env["fake"]("sudo", code = 1, output = "sudo: a password is required")+ plan = _linux_plan(monkeypatch, "sudo", sudo)+ job = _settle(job_mod.start(plan_mod.LINUX_INSTALL))+ assert job.state == "failed" and "password" in job.note+ assert len(env["recorded"]()) == 1+ assert job.manual_command == plan.manual_command+++def test_pkexec_asks_once_for_one_constant_script(monkeypatch, env):+ pkexec = env["fake"]("pkexec")+ _linux_plan(monkeypatch, "pkexec", pkexec)+ job = _settle(job_mod.start(plan_mod.LINUX_INSTALL))+ assert job.state == "succeeded"+ (call,) = env["recorded"]()+ assert call[:3] == [pkexec, "/bin/sh", "-c"]+ assert call[3] == (+ "set -e\n/pinned/apt-get install -y bubblewrap\n"+ "/pinned/apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict\n"+ )+ assert call[3] == job_mod.pkexec_script([_pinned(step) for step in _STEPS])+++def test_busybox_sh_is_run_as_its_sh_applet(monkeypatch, env):+ # Alpine: /bin/sh is a link to /bin/busybox, which picks the applet from argv[0].+ pkexec = env["fake"]("pkexec")+ _linux_plan(monkeypatch, "pkexec", pkexec)+ monkeypatch.setattr(+ plan_mod, "trusted_system_binary", lambda name: "/bin/busybox" if name == "sh" else None+ )+ _settle(job_mod.start(plan_mod.LINUX_INSTALL))+ (call,) = env["recorded"]()+ assert call[:4] == [pkexec, "/bin/busybox", "sh", "-c"]+++def test_a_dismissed_polkit_prompt_is_declined(monkeypatch, env):+ _linux_plan(monkeypatch, "pkexec", env["fake"]("pkexec", code = job_mod.PKEXEC_DISMISSED))+ job = _settle(job_mod.start(plan_mod.LINUX_INSTALL))+ assert job.state == "declined" and job.manual_command+++def test_no_polkit_agent_is_a_named_failure(monkeypatch, env):+ _linux_plan(monkeypatch, "pkexec", env["fake"]("pkexec", code = job_mod.PKEXEC_NOT_AUTHORIZED))+ job = _settle(job_mod.start(plan_mod.LINUX_INSTALL))+ assert job.state == "failed" and "authentication agent" in job.note+++def test_no_elevation_means_no_job(monkeypatch, env):+ plan = plan_mod.SetupPlan(platform = "linux", manual_command = "sudo apt-get install -y bubblewrap")+ monkeypatch.setattr(plan_mod, "detect", lambda *a, **k: plan)+ with pytest.raises(job_mod.SetupUnavailable):+ job_mod.start(plan_mod.LINUX_INSTALL)+ _linux_plan(monkeypatch, None, None)+ with pytest.raises(job_mod.SetupUnavailable):+ job_mod.start(plan_mod.LINUX_INSTALL)+ with pytest.raises(job_mod.SetupUnavailable):+ job_mod.start("rm-rf")+ assert job_mod.current() is None+++def test_one_setup_at_a_time_across_both_jobs(monkeypatch, env, tmp_path):+ gate = tmp_path / "open"+ _linux_plan(monkeypatch, "sudo", env["fake"]("sudo", gate = gate))+ first = job_mod.start(plan_mod.LINUX_INSTALL)+ try:+ assert job_mod.start(plan_mod.LINUX_INSTALL) is first+ with pytest.raises(job_mod.SetupUnavailable):+ mxc_host_prep_job.start() # a different run never stands in for the preparation+ finally:+ gate.write_text("")+ _settle(first)+ assert first.state == "succeeded"+ assert len(env["recorded"]()) == 2+++def test_a_running_setup_never_stands_in_for_a_different_operation(monkeypatch, env, tmp_path):+ gate = tmp_path / "open"+ install = env["fake"]("install-runtime", gate = gate)+ runtime = plan_mod.SetupPlan(+ platform = "win32", action = plan_mod.WINDOWS_RUNTIME, steps = ((install,),)+ )+ monkeypatch.setattr(plan_mod, "windows_runtime_plan", lambda: runtime)+ first = job_mod.start(plan_mod.WINDOWS_RUNTIME)+ try:+ assert job_mod.start(plan_mod.WINDOWS_RUNTIME) is first+ with pytest.raises(job_mod.SetupUnavailable, match = "windows-runtime"):+ job_mod.start(plan_mod.WINDOWS_SETUP)+ finally:+ gate.write_text("")+ _settle(first)+ assert len(env["recorded"]()) == 1+++def test_host_preparation_joins_only_the_chained_windows_setup(monkeypatch, env):+ running = job_mod.SetupJob(id = "chain", operation = plan_mod.WINDOWS_SETUP)+ monkeypatch.setattr(job_mod, "_current", running)+ assert mxc_host_prep_job.start() is running+ running.operation = plan_mod.WINDOWS_RUNTIME+ with pytest.raises(job_mod.SetupUnavailable, match = "windows-runtime"):+ mxc_host_prep_job.start()+++def test_windows_setup_installs_then_prepares_in_order(monkeypatch, env):+ install = env["fake"]("install-runtime")+ prepare = env["fake"](+ "prepare-host",+ output = "[mxc-prebuilt] host prepared: prepare-system-drive, prepare-null-device",+ )+ plan = plan_mod.SetupPlan(+ platform = "win32",+ action = plan_mod.WINDOWS_SETUP,+ elevation = "uac",+ steps = ((install,), (prepare, "--prepare-host")),+ )+ monkeypatch.setattr(plan_mod, "detect", lambda *a, **k: plan)+ job = _settle(job_mod.start(plan_mod.WINDOWS_SETUP))+ assert job.state == "succeeded"+ assert env["recorded"]() == [[install], [prepare, "--prepare-host"]]+ assert job.steps == ["prepare-system-drive", "prepare-null-device"]+++def test_windows_declined_administrator_prompt(monkeypatch, env):+ install = env["fake"]("install-runtime")+ prepare = env["fake"]("prepare-host", code = 2, output = "the administrator prompt was declined")+ plan = plan_mod.SetupPlan(+ platform = "win32",+ action = plan_mod.WINDOWS_SETUP,+ steps = ((install,), (prepare, "--prepare-host")),+ )+ monkeypatch.setattr(plan_mod, "detect", lambda *a, **k: plan)+ job = _settle(job_mod.start(plan_mod.WINDOWS_SETUP))+ assert job.state == "declined" and job.exit_code == 2+++def test_windows_runtime_failure_stops_before_preparing(monkeypatch, env):+ install = env["fake"]("install-runtime", code = 1, output = "download failed")+ prepare = env["fake"]("prepare-host")+ plan = plan_mod.SetupPlan(+ platform = "win32",+ action = plan_mod.WINDOWS_SETUP,+ steps = ((install,), (prepare, "--prepare-host")),+ )+ monkeypatch.setattr(plan_mod, "detect", lambda *a, **k: plan)+ job = _settle(job_mod.start(plan_mod.WINDOWS_SETUP))+ assert job.state == "failed" and env["recorded"]() == [[install]]+ assert "download failed" in job.output_tail+++def test_consent_only_windows_setup_finishes_without_a_process(monkeypatch, env):+ plan = plan_mod.SetupPlan(platform = "win32", action = plan_mod.WINDOWS_SETUP, needs_consent = True)+ monkeypatch.setattr(plan_mod, "detect", lambda *a, **k: plan)+ job = _settle(job_mod.start(plan_mod.WINDOWS_SETUP))+ assert job.state == "succeeded" and env["recorded"]() == []+++def test_a_spawn_error_is_a_failed_job(monkeypatch, env):+ _linux_plan(monkeypatch, "sudo", os.path.join(os.sep, "nonexistent", "sudo"))+ job = _settle(job_mod.start(plan_mod.LINUX_INSTALL))+ assert job.state == "failed" and job.exit_code is None+++def test_elevated_steps_run_with_only_a_fixed_environment(monkeypatch, env):+ monkeypatch.setenv("LD_PRELOAD", "/tmp/evil.so")+ monkeypatch.setenv("PYTHONPATH", "/tmp/evil")+ spawned = []++ class _Done:+ stdout = iter(())++ def wait(self):+ return 0++ monkeypatch.setattr(+ job_mod, "_spawn", lambda argv, env = None: spawned.append((argv, env)) or _Done()+ )+ _linux_plan(monkeypatch, "sudo", "/usr/bin/sudo")+ job = _settle(job_mod.start(plan_mod.LINUX_INSTALL))+ assert job.state == "succeeded" and len(spawned) == 2+ for argv, child_env in spawned:+ assert argv[:2] == ["/usr/bin/sudo", "-n"] and argv[2].startswith("/pinned/")+ assert child_env == plan_mod.ELEVATED_ENV+ assert child_env["PATH"] == "/usr/sbin:/usr/bin:/sbin:/bin"+++def test_a_step_without_a_trusted_binary_is_not_run(monkeypatch, env):+ _linux_plan(monkeypatch, "sudo", env["fake"]("sudo"))++ def refuse(steps):+ raise LookupError("apt-get was not found in /usr/sbin, /usr/bin, /sbin, /bin")++ monkeypatch.setattr(plan_mod, "elevated_steps", refuse)+ with pytest.raises(job_mod.SetupUnavailable, match = "terminal"):+ job_mod.start(plan_mod.LINUX_INSTALL)+ assert env["recorded"]() == [] and job_mod.current() is None+++def test_the_elevation_is_checked_again_right_before_starting(monkeypatch, env):+ seen = []+ _linux_plan(monkeypatch, "sudo", env["fake"]("sudo"))+ monkeypatch.setattr(+ plan_mod, "linux_elevation", lambda **kw: seen.append(kw) or ("sudo", env["fake"]("sudo"))+ )+ _settle(job_mod.start(plan_mod.LINUX_INSTALL))+ assert seen == [{"force": True}]+++def test_the_runtime_operation_only_installs_the_runtime(monkeypatch, env):+ install = env["fake"]("install-runtime")+ plan = plan_mod.SetupPlan(+ platform = "win32", action = plan_mod.WINDOWS_RUNTIME, steps = ((install,),)+ )+ monkeypatch.setattr(plan_mod, "windows_runtime_plan", lambda: plan)+ monkeypatch.setattr(+ plan_mod, "detect", lambda *a, **k: pytest.fail("the full plan is not used")+ )+ job = _settle(job_mod.start(plan_mod.WINDOWS_RUNTIME))+ assert job.state == "succeeded" and env["recorded"]() == [[install]]+ monkeypatch.setattr(+ plan_mod, "windows_runtime_plan", lambda: plan_mod.SetupPlan(platform = "win32", reason = "x")+ )+ with pytest.raises(job_mod.SetupUnavailable):+ job_mod.start(plan_mod.WINDOWS_RUNTIME)+++def test_setup_rechecks_the_tools_before_it_reads_as_finished(monkeypatch, env):+ monkeypatch.setenv(os_sandbox.WARMUP_DISABLE_ENV, "0")+ order = []+ monkeypatch.setattr(os_sandbox, "warm_tool_isolation", lambda: order.append("warm"))+ _linux_plan(monkeypatch, "sudo", env["fake"]("sudo"))+ job = job_mod.start(plan_mod.LINUX_INSTALL)+ _settle(job)+ assert job.state == "succeeded" and order == ["warm"]+++def test_two_near_simultaneous_starts_never_run_two_helpers(monkeypatch, env, tmp_path):+ gate = tmp_path / "open"+ _linux_plan(monkeypatch, "sudo", env["fake"]("sudo", gate = gate))+ prep_spawns = []+ monkeypatch.setattr(mxc_host_prep_job, "_spawn", lambda argv: prep_spawns.append(argv) or None)+ monkeypatch.setattr(mxc_probe, "host_prep_command", lambda: ["prepare"])+ monkeypatch.setattr(mxc_host_prep_job, "_run", lambda job, proc: None)+ barrier = threading.Barrier(2)+ results = {}++ def setup():+ barrier.wait()+ try:+ results["setup"] = job_mod.start(plan_mod.LINUX_INSTALL)+ except job_mod.SetupUnavailable as exc:+ results["setup"] = exc # host preparation won; a different operation is refused++ def prepare():+ barrier.wait()+ try:+ results["prepare"] = mxc_host_prep_job.start()+ except job_mod.SetupUnavailable as exc:+ results["prepare"] = exc # the install won; host preparation is refused++ threads = [threading.Thread(target = setup), threading.Thread(target = prepare)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(10)+ try:+ started_setup = job_mod.current() is not None+ started_prep = bool(prep_spawns)+ assert started_setup != started_prep+ if started_prep:+ assert isinstance(results["setup"], job_mod.SetupUnavailable)+ else:+ assert isinstance(results["prepare"], job_mod.SetupUnavailable)+ finally:+ gate.write_text("")+ if job_mod.current() is not None:+ _settle(job_mod.current())diff --git a/studio/backend/tests/test_sandbox_setup_plan.py b/studio/backend/tests/test_sandbox_setup_plan.pynew file mode 100644index 00000000000..1d89d35c93e--- /dev/null+++ b/studio/backend/tests/test_sandbox_setup_plan.py@@ -0,0 +1,454 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The OS sandbox setup plan: which fixed steps a host needs, and who may run them from Settings."""++import os+import platform+import sys++import pytest++from core.inference import os_sandbox, sandbox_setup_plan as plan_mod+from utils import client_ip++[email protected](autouse = True)+def _fresh():+ plan_mod.invalidate()+ plan_mod.forget_elevation()+ yield+ plan_mod.invalidate()+ plan_mod.forget_elevation()+++def linux(monkeypatch, tmp_path):+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setenv("PATH", str(bin_dir))+ monkeypatch.delenv("DISPLAY", raising = False)+ monkeypatch.delenv("WAYLAND_DISPLAY", raising = False)+ state = {"restricted": False, "blocked": False, "sudo_ok": True, "wsl": False}+ monkeypatch.setattr(plan_mod, "_apparmor_restricts_userns", lambda: state["restricted"])+ monkeypatch.setattr(os_sandbox, "_linux_userns_blocked_by_apparmor", lambda: state["blocked"])+ monkeypatch.setattr(plan_mod, "_APPARMOR_PROFILE", str(tmp_path / "bwrap-userns-restrict"))+ monkeypatch.setattr(plan_mod, "_is_wsl", lambda: state["wsl"])+ monkeypatch.setattr(plan_mod, "_running_as_root", lambda: state["root"])+ state["bwrap"] = None # None: follow PATH, as a trusted copy would++ def bwrap_state():+ if state["bwrap"] is not None:+ return state["bwrap"]+ return "trusted" if plan_mod.shutil.which("bwrap") else "missing"++ monkeypatch.setattr(plan_mod, "_bwrap_state", bwrap_state)+ state["root"] = False+ state["sudo_checks"] = 0++ def sudo_check(_sudo):+ state["sudo_checks"] += 1+ return state["sudo_ok"]++ monkeypatch.setattr(plan_mod, "_sudo_without_password", sudo_check)+ monkeypatch.setattr(plan_mod, "_trusted_tool", lambda name: plan_mod.shutil.which(name))++ def tool(*names):+ for name in names:+ path = bin_dir / name+ path.write_text("#!/bin/sh\nexit 0\n")+ path.chmod(0o755)++ state["tool"] = tool+ state["profile"] = tmp_path / "bwrap-userns-restrict"+ return state+++UPDATE = ("apt-get", "update")+APT = ("apt-get", "-o", "DPkg::Lock::Timeout=120", "install", "-y")+++def _profile_steps(profile):+ return (+ (*APT, "apparmor-profiles"),+ (+ "install",+ "-m",+ "644",+ "/usr/share/apparmor/extra-profiles/bwrap-userns-restrict",+ "/etc/apparmor.d/",+ ),+ ("apparmor_parser", "-r", str(profile)),+ )++[email protected](os.name == "nt", reason = "resolves POSIX system binary paths")+def test_apt_host_with_the_apparmor_restriction_gets_bwrap_and_the_profile(linux):+ linux["tool"]("apt-get")+ linux["restricted"] = True+ plan = plan_mod.detect(False)+ assert plan.action == plan_mod.LINUX_INSTALL and plan.elevation is None+ # A stale package list failed the install on a real Ubuntu 24.04 host: update first.+ assert plan.steps == (UPDATE, (*APT, "bubblewrap"), *_profile_steps(linux["profile"]))+ assert plan.manual_command == " && ".join("sudo " + " ".join(step) for step in plan.steps)+++def test_the_steps_install_what_install_sh_and_the_remediation_name():+ for manager, command in os_sandbox._BWRAP_INSTALL_COMMANDS:+ assert plan_mod._INSTALL_STEPS[manager][-1][-1] == command.split()[-1] == "bubblewrap"+ fix = os_sandbox._BWRAP_APPARMOR_FIX+ assert "apparmor-profiles" in fix and plan_mod._APPARMOR_EXTRA_PROFILE in fix+ assert " ".join(plan_mod._apparmor_load()) in fix+++def test_apt_host_without_the_restriction_only_installs_bwrap(linux):+ linux["tool"]("apt-get")+ plan = plan_mod.detect(False)+ assert plan.steps == (UPDATE, (*APT, "bubblewrap"))+++ "manager,flag",+ [("dnf", "-y"), ("pacman", "--noconfirm"), ("zypper", "--non-interactive"), ("apk", "add")],+)+def test_other_package_managers_install_bwrap_and_never_the_ubuntu_profile(linux, manager, flag):+ linux["tool"](manager)+ linux["restricted"] = True+ plan = plan_mod.detect(False)+ assert plan.steps == plan_mod._INSTALL_STEPS[manager] and len(plan.steps) == 1+ assert plan.steps[0][0] == manager and flag in plan.steps[0]+ assert "apparmor" not in plan.manual_command+++def test_installed_but_blocked_bwrap_only_needs_the_profile(linux):+ linux["tool"]("apt-get", "bwrap")+ linux["restricted"] = linux["blocked"] = True+ plan = plan_mod.detect(False)+ assert plan.steps == (UPDATE, *_profile_steps(linux["profile"]))+ assert "bubblewrap" not in plan.manual_command+++def test_a_profile_that_is_there_but_not_in_force_is_only_loaded(linux):+ linux["tool"]("apt-get", "bwrap")+ linux["restricted"] = linux["blocked"] = True+ linux["profile"].write_text("profile")+ plan = plan_mod.detect(False)+ assert plan.action == plan_mod.LINUX_INSTALL+ assert plan.steps == (("apparmor_parser", "-r", str(linux["profile"])),)+++def test_an_untrusted_bwrap_on_path_still_gets_the_install(linux):+ linux["tool"]("apt-get", "bwrap")+ linux["bwrap"] = "missing" # e.g. ~/.local/bin/bwrap and no system copy+ plan = plan_mod.detect(False)+ assert plan.action == plan_mod.LINUX_INSTALL+ assert "bubblewrap" in plan.manual_command+++def test_a_system_bwrap_shadowed_on_path_is_named_not_reinstalled(linux, monkeypatch):+ linux["tool"]("apt-get", "bwrap")+ linux["bwrap"] = "shadowed"+ monkeypatch.setattr(plan_mod, "trusted_system_binary", lambda name: f"/usr/bin/{name}")+ plan = plan_mod.detect(False)+ assert plan.action is None and plan.manual_command == ""+ assert plan_mod.shutil.which("bwrap") in plan.reason and "/usr/bin" in plan.reason+++ os.name == "nt",+ reason = "the trust check reads POSIX uid and mode bits, which Windows does not have",+)+def test_bwrap_state_follows_the_launchers_trust_check(monkeypatch, tmp_path):+ from core.inference import sandbox_linux++ fake = tmp_path / "bwrap"+ fake.write_text("#!/bin/sh\n")+ fake.chmod(0o755)+ monkeypatch.setenv("PATH", str(tmp_path))+ monkeypatch.setattr(plan_mod, "trusted_system_binary", lambda name: None)+ if os.geteuid() != 0:+ with pytest.raises(Exception):+ sandbox_linux._trusted_bwrap_path()+ assert plan_mod._bwrap_state() == "missing"+ monkeypatch.setattr(plan_mod, "trusted_system_binary", lambda name: "/usr/bin/bwrap")+ if os.geteuid() != 0:+ assert plan_mod._bwrap_state() == "shadowed"+++def test_an_unblocked_host_with_bwrap_needs_nothing(linux):+ linux["tool"]("apt-get", "bwrap")+ linux["restricted"] = True+ plan = plan_mod.detect(False)+ assert plan.action is None and plan.steps == () and plan.reason+++def test_an_unknown_package_manager_gets_no_command(linux):+ plan = plan_mod.detect(False)+ assert plan.action is None and plan.manual_command == ""+++def test_detection_never_runs_the_elevation_check(linux):+ linux["tool"]("apt-get", "sudo")+ plan_mod.detect(False)+ assert linux["sudo_checks"] == 0++[email protected](os.name == "nt", reason = "resolves POSIX system binary paths")+def test_passwordless_sudo_is_the_first_choice(linux):+ linux["tool"]("sudo")+ kind, path = plan_mod.linux_elevation()+ assert kind == "sudo" and path.endswith("/sudo")+++def test_without_passwordless_sudo_a_desktop_uses_pkexec(linux, monkeypatch):+ linux["tool"]("sudo", "pkexec")+ linux["sudo_ok"] = False+ monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0")+ assert plan_mod.linux_elevation()[0] == "pkexec"+++def test_without_sudo_or_a_desktop_only_the_command_is_offered(linux, monkeypatch):+ linux["tool"]("apt-get", "sudo", "pkexec")+ linux["sudo_ok"] = False+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: True)+ assert plan_mod.linux_elevation() == (None, None)+ fields = plan_mod.setup_fields_for(object(), True, available = False)+ assert fields["setup_action"] is None and fields["can_run_setup"] is False+ assert fields["manual_command"].startswith("sudo apt-get update && sudo apt-get")+++def test_a_root_process_runs_the_steps_itself_and_shows_them_without_sudo(linux, monkeypatch):+ linux["tool"]("apt-get")+ linux["root"] = True+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: True)+ assert plan_mod.linux_elevation() == ("root", None)+ assert linux["sudo_checks"] == 0+ fields = plan_mod.setup_fields_for(object(), True, available = False)+ assert fields["can_run_setup"] is True and fields["setup_action"] == plan_mod.LINUX_INSTALL+ assert fields["manual_command"].startswith("apt-get update && apt-get")+ assert "sudo" not in fields["manual_command"]+++def test_wsl_never_uses_pkexec(linux, monkeypatch):+ linux["tool"]("sudo", "pkexec")+ linux["sudo_ok"] = False+ linux["wsl"] = True+ monkeypatch.setenv("DISPLAY", ":0")+ assert plan_mod.linux_elevation() == (None, None)+++def test_the_elevation_check_is_remembered_until_forced(linux):+ linux["tool"]("sudo")+ plan_mod.linux_elevation()+ plan_mod.linux_elevation()+ assert linux["sudo_checks"] == 1+ plan_mod.linux_elevation(force = True)+ assert linux["sudo_checks"] == 2++[email protected]("owner,local", [(False, True), (True, False), (False, False)])+def test_nobody_but_the_owner_here_makes_unsloth_check_sudo(linux, monkeypatch, owner, local):+ linux["tool"]("apt-get", "sudo")+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: local)+ fields = plan_mod.setup_fields_for(object(), owner, available = False)+ assert linux["sudo_checks"] == 0+ assert fields["setup_action"] is None and fields["manual_command"]+++def test_elevated_steps_ignore_path_and_untrusted_folders(monkeypatch, tmp_path):+ planted = tmp_path / "planted"+ planted.mkdir()+ (planted / "apt-get").write_text("#!/bin/sh\n")+ (planted / "apt-get").chmod(0o755)+ monkeypatch.setenv("PATH", str(planted))+ monkeypatch.setattr(plan_mod, "SYSTEM_BIN_DIRS", (str(planted),))+ assert plan_mod.trusted_system_binary("apt-get") is None+ with pytest.raises(LookupError):+ plan_mod.elevated_steps([("apt-get", "update")])++[email protected](not os.path.exists("/usr/bin/env"), reason = "needs a POSIX /usr/bin")+def test_elevated_steps_pin_a_root_owned_system_binary():+ if os.stat("/usr/bin/env").st_uid != 0:+ pytest.skip(+ reason = "the pin only accepts a root-owned binary and this host's /usr/bin/env is not owned by root"+ )+ assert plan_mod.elevated_steps([("env", "true")]) == [+ [os.path.realpath("/usr/bin/env"), "true"]+ ]+++def test_a_working_sandbox_needs_nothing(linux):+ linux["tool"]("apt-get", "sudo")+ plan = plan_mod.detect(True)+ assert plan.action is None and plan.steps == () and plan.manual_command == ""+++def test_detection_is_cached_until_invalidated(linux):+ linux["tool"]("apt-get", "sudo")+ first = plan_mod.detect(False)+ linux["tool"]("bwrap")+ assert plan_mod.detect(False) is first+ plan_mod.invalidate()+ assert plan_mod.detect(False).steps == ()+++ os.name == "nt",+ reason = "the trust check reads POSIX uid and mode bits, which Windows does not have",+)+def test_untrusted_elevation_tools_are_ignored(monkeypatch, tmp_path):+ fake = tmp_path / "sudo"+ fake.write_text("#!/bin/sh\n")+ fake.chmod(0o755)+ monkeypatch.setenv("PATH", str(tmp_path))+ if os.geteuid() != 0:+ assert plan_mod._trusted_tool("sudo") is None+++def test_macos_has_nothing_to_install(monkeypatch):+ monkeypatch.setattr(sys, "platform", "darwin")+ plan = plan_mod.detect(False)+ assert plan.action is None and plan.manual_command == "" and "Seatbelt" in plan.reason+++def windows(monkeypatch):+ from core.inference import mxc_policy, mxc_probe, mxc_runtime+ from utils import mxc_isolation_settings++ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(platform, "machine", lambda: "AMD64")+ state = {+ "installed": True,+ "missing": ("prepare-null-device",),+ "opted_in": False,+ "locked": False,+ }++ def identity():+ if not state["installed"]:+ raise FileNotFoundError("no runtime")+ return "identity"++ monkeypatch.setattr(mxc_runtime, "installation_identity", identity)+ monkeypatch.setattr(mxc_runtime, "probe_host_prep_steps", lambda **_kw: state["missing"])+ monkeypatch.setattr(mxc_policy, "dacl_fallback_enabled", lambda: state["opted_in"])+ monkeypatch.setattr(+ mxc_isolation_settings, "locked_by_environment", lambda _name: state["locked"]+ )+ monkeypatch.setattr(+ mxc_probe,+ "host_prep_command",+ lambda: ["python", "install_mxc_prebuilt.py", "--prepare-host"],+ )+ monkeypatch.setattr(+ plan_mod, "windows_runtime_install_command", lambda: ["python", "install_mxc_prebuilt.py"]+ )+ return state+++def test_windows_without_the_runtime_installs_then_prepares(windows):+ windows["installed"] = False+ plan = plan_mod.detect(False)+ assert plan.action == plan_mod.WINDOWS_SETUP and plan.elevation == "uac"+ assert plan.steps == (+ ("python", "install_mxc_prebuilt.py"),+ ("python", "install_mxc_prebuilt.py", "--prepare-host"),+ )+ assert plan.needs_consent is True+ assert "MXC runtime is not installed" in plan.reason+++def test_windows_after_a_reboot_only_prepares(windows):+ windows["opted_in"] = True+ plan = plan_mod.detect(False)+ assert plan.steps == (("python", "install_mxc_prebuilt.py", "--prepare-host"),)+ assert plan.needs_consent is False+ assert plan.reason == "This PC needs its administrator step again after the restart."+++def test_windows_prepared_but_not_allowed_only_needs_consent(windows):+ windows["missing"] = ()+ plan = plan_mod.detect(False)+ assert plan.action == plan_mod.WINDOWS_SETUP and plan.steps == () and plan.needs_consent+ assert plan.elevation is None+++def test_windows_allowed_and_prepared_has_nothing_left(windows):+ windows["missing"] = ()+ windows["opted_in"] = True+ assert plan_mod.detect(False).action is None+++def test_windows_opt_in_locked_off_by_the_environment_is_not_offered(windows):+ windows["locked"] = True+ plan = plan_mod.detect(False)+ assert plan.action is None and "UNSLOTH_MXC_ALLOW_DACL_FALLBACK" in plan.reason+ assert "--prepare-host" in plan.manual_command+++def test_windows_arm64_is_not_offered_a_runtime_it_cannot_run(windows, monkeypatch):+ windows["installed"] = False+ monkeypatch.setattr(platform, "machine", lambda: "ARM64")+ plan = plan_mod.detect(False)+ assert plan.action is None and "x64" in plan.reason+ assert plan_mod.windows_runtime_plan().action is None+++def test_windows_runtime_only_installs_the_runtime(windows, monkeypatch):+ windows["installed"] = False+ plan = plan_mod.windows_runtime_plan()+ assert plan.action == plan_mod.WINDOWS_RUNTIME and plan.elevation is None+ assert plan.steps == (("python", "install_mxc_prebuilt.py"),)+ windows["installed"] = True+ assert plan_mod.windows_runtime_plan().action is None+++def test_both_tools_must_work_before_nothing_is_offered(monkeypatch):+ seen = []++ def snapshot(*, execution_kind, selected_executable):+ seen.append(execution_kind)+ return os_sandbox.SandboxCapability(+ backend = "x",+ available = execution_kind == "python",+ reason = "",+ protection_state = "preview",+ limitations = (),+ )++ monkeypatch.setattr(os_sandbox, "capability_snapshot", snapshot)+ monkeypatch.setattr(os_sandbox, "tool_isolation_target", lambda tool: tool)+ assert plan_mod._os_isolation_available() is False+ assert seen == ["python", "terminal"]+++def test_setup_fields_name_the_action_only_for_the_owner_here(linux, monkeypatch):+ linux["tool"]("apt-get", "sudo")+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: True)+ owner = plan_mod.setup_fields_for(object(), True, available = False)+ assert owner["setup_action"] == plan_mod.LINUX_INSTALL and owner["can_run_setup"] is True+ other = plan_mod.setup_fields_for(object(), False, available = False)+ assert other["setup_action"] is None and other["can_run_setup"] is False+ assert other["manual_command"] == owner["manual_command"] != ""+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: False)+ remote = plan_mod.setup_fields_for(object(), True, available = False)+ assert remote["setup_action"] is None and remote["manual_command"]+++def test_windows_commands_paste_into_windows_powershell():+ steps = (+ (+ r"C:\Users\Jane Doe\python.exe",+ r"C:\Users\Jane Doe\studio\install_mxc_prebuilt.py",+ "--install-dir",+ "x",+ ),+ (r"C:\it's\python.exe", "--prepare-host"),+ )+ assert plan_mod.powershell_command(steps) == (+ "& 'C:\\Users\\Jane Doe\\python.exe' 'C:\\Users\\Jane Doe\\studio\\install_mxc_prebuilt.py' "+ "'--install-dir' 'x'\n& 'C:\\it''s\\python.exe' '--prepare-host'"+ )diff --git a/studio/backend/tests/test_sandbox_setup_route.py b/studio/backend/tests/test_sandbox_setup_route.pynew file mode 100644index 00000000000..9284734ead4--- /dev/null+++ b/studio/backend/tests/test_sandbox_setup_route.py@@ -0,0 +1,434 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Route policy for /api/settings/sandbox/setup: owner, UI session, and the computer running Unsloth."""++from pathlib import Path+import sys+import types as _types++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import routes.settings as settings+from core.inference import (+ mxc_host_prep_job,+ mxc_policy,+ mxc_probe,+ mxc_read_grants,+ os_sandbox,+ sandbox_setup_job,+ sandbox_setup_plan,+ tools,+)+from utils import client_ip, mxc_isolation_settings+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+++def _cap(available):+ return os_sandbox.SandboxCapability(+ backend = "bubblewrap",+ available = available,+ reason = "probe passed" if available else "probe failed",+ protection_state = "preview" if available else "unavailable",+ limitations = (),+ )+++def host(monkeypatch):+ calls = {"start": [], "revoke": 0}+ saved = {"dacl": False, "locked": False, "available": False}+ plan = {+ "value": sandbox_setup_plan.SetupPlan(+ platform = "linux",+ action = sandbox_setup_plan.LINUX_INSTALL,+ elevation = "sudo",+ steps = (("apt-get", "install", "-y", "bubblewrap"),),+ manual_command = "sudo apt-get install -y bubblewrap",+ reason = "bubblewrap (bwrap) is not installed.",+ )+ }+ monkeypatch.setattr(os_sandbox, "capability_snapshot", lambda **_kw: _cap(saved["available"]))+ monkeypatch.setattr(settings, "_sandbox_terminal_target", lambda: ("/bin/bash", None))+ monkeypatch.setattr(settings, "_sandbox_windows_status", lambda: None)+ monkeypatch.setattr(sandbox_setup_plan, "detect", lambda *a, **k: plan["value"])+ calls["elevation_checks"] = 0++ def elevation(**_kw):+ calls["elevation_checks"] += 1+ return saved.get("elevation", ("sudo", "/usr/bin/sudo"))++ monkeypatch.setattr(sandbox_setup_plan, "linux_elevation", elevation)+ monkeypatch.setattr(mxc_probe, "invalidate_cache", lambda: None)+ monkeypatch.setattr(tools, "reset_terminal_profile_cache", lambda: None)+ monkeypatch.setattr(mxc_policy, "dacl_fallback_enabled", lambda: saved["dacl"])+ monkeypatch.setattr(mxc_read_grants, "enabled", lambda: True)++ def revoke():+ calls["revoke"] += 1+ return ()++ monkeypatch.setattr(mxc_read_grants, "revoke_recorded", revoke)+ monkeypatch.setattr(+ mxc_isolation_settings, "set_dacl_fallback_setting", lambda v: saved.__setitem__("dacl", v)+ )+ monkeypatch.setattr(+ mxc_isolation_settings, "locked_by_environment", lambda _name: saved["locked"]+ )++ def start(operation):+ calls["start"].append(operation)+ return sandbox_setup_job.SetupJob(id = "job1", operation = operation)++ monkeypatch.setattr(sandbox_setup_job, "start", start)+ monkeypatch.setattr(sandbox_setup_job, "current", lambda: None)+ monkeypatch.setattr(mxc_host_prep_job, "current", lambda: None)+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: True)+ settings._forget_sandbox_status()+ return calls, saved, plan+++def linux(monkeypatch):+ monkeypatch.setattr(sys, "platform", "linux")+++def windows(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+++def _client(account, via_api_key = False):+ app = FastAPI()+ app.include_router(settings.router)++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[settings.get_current_subject] = subject+ app.dependency_overrides[settings.authenticated_via_api_key] = lambda: via_api_key+ return TestClient(app, raise_server_exceptions = False)+++def test_owner_starts_the_linux_install_from_this_computer(host, linux):+ calls, _saved, _plan = host+ with _client(OWNER) as client:+ response = client.post("/sandbox/setup", json = {"operation": "linux-install"})+ assert response.status_code == 200, response.text+ body = response.json()+ assert body["state"] == "running" and body["operation"] == "linux-install"+ assert client.get("/sandbox/setup").json()["state"] == "idle"+ assert calls["start"] == ["linux-install"]+++def test_status_names_the_setup_for_this_host(host, linux):+ with _client(OWNER) as client:+ setup = client.get("/sandbox").json()["setup"]+ assert setup["action"] == "linux-install" and setup["elevation"] == "sudo"+ assert setup["manual_command"] == "sudo apt-get install -y bubblewrap"+++def test_status_offers_the_button_only_to_this_computer(host, linux, monkeypatch):+ with _client(OWNER) as client:+ assert client.get("/sandbox").json()["setup"]["can_run"] is True+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: False)+ setup = client.get("/sandbox").json()["setup"]+ assert setup["can_run"] is False and setup["manual_command"]+++def _capability_client(account):+ from routes.sandbox_capability import router as capability_router++ app = FastAPI()+ app.include_router(capability_router, prefix = "/api/sandbox")++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[settings.get_current_subject] = subject+ return TestClient(app, raise_server_exceptions = False)+++def test_capability_offers_setup_to_the_local_owner(host, linux):+ body = _capability_client(OWNER).get("/api/sandbox/capability").json()+ assert body["setup_action"] == "linux-install" and body["can_run_setup"] is True+ assert body["manual_command"] == "sudo apt-get install -y bubblewrap"+++def test_capability_reason_is_the_short_setup_reason_when_a_command_is_shown(host, linux):+ body = _capability_client(OWNER).get("/api/sandbox/capability").json()+ assert body["reason"] == "bubblewrap (bwrap) is not installed."+ assert "setup_reason" not in body++[email protected]("who", ["other_account", "remote_owner"])+def test_capability_gives_everyone_else_only_the_command(host, linux, monkeypatch, who):+ calls, _saved, _plan = host+ account = ALICE+ if who == "remote_owner":+ account = OWNER+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: False)+ body = _capability_client(account).get("/api/sandbox/capability").json()+ assert body["setup_action"] is None and body["can_run_setup"] is False+ assert body["manual_command"] == "sudo apt-get install -y bubblewrap"+ assert body["setup_blocked"] == ("not_owner" if who == "other_account" else "not_local")+ assert calls["elevation_checks"] == 0+++def test_capability_tells_the_owner_here_when_no_password_prompt_is_possible(host, linux):+ _calls, saved, _plan = host+ saved["elevation"] = (None, None)+ body = _capability_client(OWNER).get("/api/sandbox/capability").json()+ assert body["setup_action"] is None and body["can_run_setup"] is False+ assert body["setup_blocked"] == "no_elevation" and body["manual_command"]+++def test_capability_names_no_block_when_the_button_is_offered(host, linux):+ body = _capability_client(OWNER).get("/api/sandbox/capability").json()+ assert body["can_run_setup"] is True and body["setup_blocked"] is None+++def test_a_remote_status_read_never_checks_elevation(host, linux, monkeypatch):+ calls, _saved, _plan = host+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: False)+ with _client(OWNER) as client:+ setup = client.get("/sandbox").json()["setup"]+ assert setup["can_run"] is False and calls["elevation_checks"] == 0+++def test_no_elevation_here_means_the_command_only(host, linux):+ calls, saved, _plan = host+ saved["elevation"] = (None, None)+ with _client(OWNER) as client:+ setup = client.get("/sandbox").json()["setup"]+ assert setup["can_run"] is False and setup["manual_command"]+ body = _capability_client(OWNER).get("/api/sandbox/capability").json()+ assert body["setup_action"] is None and body["can_run_setup"] is False+++def test_the_capability_read_checks_a_tool_it_has_no_answer_for(host, linux, monkeypatch):+ from core.inference import os_sandbox++ monkeypatch.setenv(os_sandbox.WARMUP_DISABLE_ENV, "0")+ refreshed = []++ def refresh(tool, *, force = False):+ refreshed.append((tool, force))+ os_sandbox.note_tool_isolation(tool, True, backend = "bubblewrap", reason = "passed")+ return True++ monkeypatch.setattr(os_sandbox, "refresh_tool_isolation", refresh)+ os_sandbox.forget_tool_isolation()+ body = _capability_client(OWNER).get("/api/sandbox/capability").json()+ assert body["python_os_isolated"] is True and body["terminal_os_isolated"] is True+ assert refreshed == [("python", False), ("terminal", False)]+ refreshed.clear()+ _capability_client(OWNER).get("/api/sandbox/capability")+ assert refreshed == []+ _capability_client(OWNER).get("/api/sandbox/capability", params = {"refresh": "1"})+ assert refreshed == [("python", True), ("terminal", True)]+ refreshed.clear()+ _capability_client(ALICE).get("/api/sandbox/capability", params = {"refresh": "1"})+ assert refreshed == []+ os_sandbox.forget_tool_isolation()+++def test_a_remote_browser_is_refused(host, linux, monkeypatch):+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: False)+ calls, _saved, _plan = host+ with _client(OWNER) as client:+ response = client.post("/sandbox/setup", json = {"operation": "linux-install"})+ assert response.status_code == 403 and "computer running Unsloth" in response.json()["detail"]+ assert calls["start"] == []+++def test_api_keys_and_other_accounts_are_refused(host, linux):+ calls, _saved, _plan = host+ with _client(OWNER, via_api_key = True) as client:+ assert client.post("/sandbox/setup", json = {"operation": "linux-install"}).status_code == 403+ with _client(ALICE) as client:+ assert client.post("/sandbox/setup", json = {"operation": "linux-install"}).status_code == 403+ assert client.get("/sandbox/setup").status_code == 403+ assert calls["start"] == []+++ "body",+ [+ {"operation": "rm -rf /"},+ {"operation": "linux-install", "command": "id"},+ {"operation": "windows-setup", "consent_dacl_fallback": "yes"},+ ],+)+def test_nothing_but_a_known_operation_is_accepted(host, linux, body):+ calls, _saved, _plan = host+ with _client(OWNER) as client:+ assert client.post("/sandbox/setup", json = body).status_code == 422+ assert calls["start"] == []+++def test_the_operation_must_match_the_platform(host, linux, monkeypatch):+ calls, _saved, _plan = host+ with _client(OWNER) as client:+ assert client.post("/sandbox/setup", json = {"operation": "windows-setup"}).status_code == 409+ assert (+ client.post("/sandbox/setup", json = {"operation": "windows-runtime"}).status_code == 409+ )+ monkeypatch.setattr(sys, "platform", "win32")+ with _client(OWNER) as client:+ assert client.post("/sandbox/setup", json = {"operation": "linux-install"}).status_code == 409+ monkeypatch.setattr(sys, "platform", "darwin")+ with _client(OWNER) as client:+ assert client.post("/sandbox/setup", json = {"operation": "linux-install"}).status_code == 409+ assert calls["start"] == []+++def test_nothing_to_set_up_is_a_conflict(host, linux, monkeypatch):+ def unavailable(_operation):+ raise sandbox_setup_job.SetupUnavailable("OS isolation already works on this computer.")++ monkeypatch.setattr(sandbox_setup_job, "start", unavailable)+ with _client(OWNER) as client:+ response = client.post("/sandbox/setup", json = {"operation": "linux-install"})+ assert response.status_code == 409 and "already works" in response.json()["detail"]+++def test_windows_consent_turns_the_opt_in_on_once_the_setup_is_accepted(host, windows, monkeypatch):+ calls, saved, _plan = host+ seen = []++ def start(operation):+ # The opt-in must still be off while the job is decided, or the plan reads "already works".+ seen.append(saved["dacl"])+ return sandbox_setup_job.SetupJob(id = "job1", operation = operation)++ monkeypatch.setattr(sandbox_setup_job, "start", start)+ with _client(OWNER) as client:+ response = client.post(+ "/sandbox/setup", json = {"operation": "windows-setup", "consent_dacl_fallback": True}+ )+ assert response.status_code == 200, response.text+ assert seen == [False] and saved["dacl"] is True+++def test_windows_consent_is_not_saved_when_the_setup_is_refused(host, windows, monkeypatch):+ _calls, saved, _plan = host++ def unavailable(_operation):+ raise sandbox_setup_job.SetupUnavailable("OS isolation already works on this computer.")++ monkeypatch.setattr(sandbox_setup_job, "start", unavailable)+ with _client(OWNER) as client:+ response = client.post(+ "/sandbox/setup", json = {"operation": "windows-setup", "consent_dacl_fallback": True}+ )+ assert response.status_code == 409 and saved["dacl"] is False+++def test_windows_runtime_only_is_a_windows_operation(host, windows):+ calls, saved, _plan = host+ with _client(OWNER) as client:+ response = client.post(+ "/sandbox/setup", json = {"operation": "windows-runtime", "consent_dacl_fallback": True}+ )+ assert response.status_code == 200 and calls["start"] == ["windows-runtime"]+ assert saved["dacl"] is False+++def test_a_remote_owner_may_install_the_runtime_but_not_prepare(host, windows, monkeypatch):+ # The runtime install has no administrator prompt; the chained setup ends in one (UAC).+ monkeypatch.setattr(client_ip, "is_direct_local_request", lambda _request: False)+ calls, _saved, _plan = host+ with _client(OWNER) as client:+ assert (+ client.post("/sandbox/setup", json = {"operation": "windows-runtime"}).status_code == 200+ )+ assert client.post("/sandbox/setup", json = {"operation": "windows-setup"}).status_code == 403+ assert calls["start"] == ["windows-runtime"]+++def test_windows_setup_without_consent_leaves_the_opt_in_alone(host, windows):+ calls, saved, _plan = host+ with _client(OWNER) as client:+ assert client.post("/sandbox/setup", json = {"operation": "windows-setup"}).status_code == 200+ assert saved["dacl"] is False and calls["start"] == ["windows-setup"]+++def test_windows_consent_held_off_by_the_environment_is_refused(host, windows):+ calls, saved, _plan = host+ saved["locked"] = True+ with _client(OWNER) as client:+ response = client.post(+ "/sandbox/setup", json = {"operation": "windows-setup", "consent_dacl_fallback": True}+ )+ assert response.status_code == 409 and mxc_policy.DACL_FALLBACK_ENV in response.json()["detail"]+ assert saved["dacl"] is False and calls["start"] == []+++def test_the_prepare_job_is_reported_by_the_setup_route(host, windows, monkeypatch):+ prep = mxc_host_prep_job.HostPrepJob(id = "prep1")+ monkeypatch.setattr(mxc_host_prep_job, "current", lambda: prep)+ with _client(OWNER) as client:+ body = client.get("/sandbox/setup").json()+ assert (+ body["id"] == "prep1"+ and body["operation"] == "windows-setup"+ and body["state"] == "running"+ )+++def test_a_setup_run_is_reported_by_the_prepare_route(host, windows, monkeypatch):+ setup = sandbox_setup_job.SetupJob(id = "setup1", operation = "windows-setup")+ monkeypatch.setattr(sandbox_setup_job, "current", lambda: setup)+ with _client(OWNER) as client:+ body = client.get("/sandbox/prepare").json()+ assert body["id"] == "setup1" and body["state"] == "running"++[email protected]("operation", ["windows-runtime", "linux-install"])+def test_a_job_that_does_not_prepare_the_host_stays_out_of_the_prepare_route(+ host, windows, monkeypatch, operation+):+ setup = sandbox_setup_job.SetupJob(id = "setup1", operation = operation, state = "succeeded")+ monkeypatch.setattr(sandbox_setup_job, "current", lambda: setup)+ monkeypatch.setattr(mxc_host_prep_job, "current", lambda: None)+ with _client(OWNER) as client:+ body = client.get("/sandbox/prepare").json()+ assert client.get("/sandbox/setup").json()["id"] == "setup1"+ assert body["state"] == "idle" and body.get("id") is None+++def test_windows_commands_with_host_paths_stay_with_the_owner(host, windows):+ _calls, _saved, plan = host+ plan["value"] = sandbox_setup_plan.SetupPlan(+ platform = "win32",+ action = sandbox_setup_plan.WINDOWS_SETUP,+ elevation = "uac",+ steps = (("C:\\Users\\owner\\python.exe", "--prepare-host"),),+ manual_command = "& 'C:\\Users\\owner\\python.exe' '--prepare-host'",+ reason = "host preparation is missing",+ )+ other = _capability_client(ALICE).get("/api/sandbox/capability").json()+ owner = _capability_client(OWNER).get("/api/sandbox/capability").json()+ assert other["manual_command"] == "" and other["setup_blocked"] == "not_owner"+ assert "owner" in owner["manual_command"]diff --git a/studio/backend/tests/test_windows_cmd_terminal_profile.py b/studio/backend/tests/test_windows_cmd_terminal_profile.pyindex 7eddbee2083..ff3363e4468 100644--- a/studio/backend/tests/test_windows_cmd_terminal_profile.py+++ b/studio/backend/tests/test_windows_cmd_terminal_profile.py@@ -70,7 +70,19 @@ MSYS = mxc_probe.MSYS_NAMESPACE_REASON(BASH, _cap(True), _cap(True), "bash"),(BASH, _cap(False, MSYS), _cap(True), "cmd_isolated"),(BASH, _cap(False, MSYS), _cap(False, "no"), "bash"),- (BASH, _cap(False, "the live MXC probe did not complete cleanly"), _cap(True), "bash"),+ # A freshly prepared host fails bash without the MSYS signature while cmd passes.+ (+ BASH,+ _cap(False, "the live MXC probe did not complete cleanly"),+ _cap(True),+ "cmd_isolated",+ ),+ (+ BASH,+ _cap(False, "the live MXC probe did not complete cleanly"),+ _cap(False, "no"),+ "bash",+ ),(None, None, _cap(True), "cmd_isolated"),(None, None, _cap(False, "no"), "cmd_fallback"),],@@ -80,10 +92,8 @@ def test_profile_matrix(windows, bash, bash_cap, cmd_cap, expected):assert tools._terminal_profile() == expected-def test_cmd_is_only_probed_after_the_msys_verdict(windows):- calls = windows(- bash_cap = _cap(False, "the live MXC probe did not complete cleanly"), cmd_cap = _cap(True)- )+def test_cmd_is_only_probed_after_bash_fails(windows):+ calls = windows(bash_cap = _cap(True), cmd_cap = _cap(True))tools._terminal_profile()assert calls == [BASH]diff --git a/studio/backend/utils/client_ip.py b/studio/backend/utils/client_ip.pyindex 7faead0a6a7..3505eb2c838 100644--- a/studio/backend/utils/client_ip.py+++ b/studio/backend/utils/client_ip.py@@ -69,3 +69,51 @@ def client_ip(request) -> str:if cf:return cfreturn peer or "_unknown"+++def _is_loopback_ip(host: str | None) -> bool:+ if not host or "%" in host: # a scope id (::1%eth0) is never a plain loopback+ return False+ try:+ ip = ipaddress.ip_address(host)+ except (TypeError, ValueError):+ return False+ mapped = getattr(ip, "ipv4_mapped", None)+ return ip.is_loopback or (mapped is not None and mapped.is_loopback)+++# A loopback peer carrying any of these is a proxy/tunnel relaying a remote client, so the peer is the+# proxy, not the caller: cloudflared sets cf-connecting-ip, reverse proxies set the rest.+_PROXIED_CLIENT_HEADERS = (+ "cf-connecting-ip",+ "forwarded",+ "x-forwarded-for",+ "x-forwarded-host",+ "x-real-ip",+)+++def _host_header_is_loopback(host_header: str | None) -> bool:+ """Raw Host header, so a bad Host cannot fall back to the (loopback) ASGI server address."""+ if not host_header:+ return False+ host = host_header.strip()+ if host.startswith("["): # [IPv6] or [IPv6]:port+ end = host.find("]")+ if end == -1 or (host[end + 1 :] and not host[end + 1 :].startswith(":")):+ return False # unclosed bracket or junk after ] (e.g. [::1]evil)+ host = host[1:end]+ elif host.count(":") == 1: # host:port+ host = host.split(":", 1)[0]+ host = host.lower().rstrip(".")+ return host == "localhost" or _is_loopback_ip(host)+++def is_direct_local_request(request) -> bool:+ """A direct loopback connection to a loopback Host: not relayed by a proxy or tunnel, not DNS rebinding."""+ client = request.client+ if client is None or not _is_loopback_ip(client.host):+ return False+ if any(request.headers.get(h) is not None for h in _PROXIED_CLIENT_HEADERS):+ return False+ return _host_header_is_loopback(request.headers.get("host"))diff --git a/studio/backend/utils/mxc_isolation_settings.py b/studio/backend/utils/mxc_isolation_settings.pynew file mode 100644index 00000000000..bb1cd1539f3--- /dev/null+++ b/studio/backend/utils/mxc_isolation_settings.py@@ -0,0 +1,103 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Saved Settings > Sandbox MXC switches; a present env var always wins (mxc_policy / mxc_read_grants)."""++from __future__ import annotations++import os+import threading+import time+from typing import Any++DACL_SETTING_KEY = "mxc_allow_dacl_fallback"+GRANTS_SETTING_KEY = "mxc_persistent_read_grants"+DEFAULT_DACL_FALLBACK = False+DEFAULT_PERSISTENT_GRANTS = True++# A write drops the entry; the TTL only bounds staleness from ANOTHER process.+_CACHE_TTL_SECONDS = 1.0+_cache_lock = threading.Lock()+_cached: tuple[float, dict[str, Any]] | None = None+# Bumped by every write: a read that started earlier must not publish what it saw.+_generation = 0+++def forget_cached_setting() -> None:+ global _cached, _generation+ with _cache_lock:+ _cached = None+ _generation += 1+++def _coerce_bool(value: Any) -> bool | None:+ if isinstance(value, bool):+ return value+ if isinstance(value, str):+ normalized = value.strip().lower()+ if normalized in {"1", "true", "yes", "on"}:+ return True+ if normalized in {"0", "false", "no", "off", ""}:+ return False+ return None+++def _stored() -> dict[str, Any] | None:+ """Both keys from one owner-store snapshot, or None when the store cannot be read."""+ global _cached+ with _cache_lock:+ if _cached is not None and _cached[0] > time.monotonic():+ return _cached[1]+ generation = _generation+ try:+ from storage.studio_db import get_app_settings+ from utils.account_context import OWNER, run_as++ # Installation-wide: the owner's store, whichever account's tool call is asking.+ stored = run_as(OWNER, get_app_settings, [DACL_SETTING_KEY, GRANTS_SETTING_KEY])+ except Exception: # noqa: BLE001 - an unreadable store falls back to the shipped defaults+ return None+ with _cache_lock:+ if generation == _generation:+ _cached = (time.monotonic() + _CACHE_TTL_SECONDS, stored)+ return stored+++def _setting(key: str, default: bool) -> bool:+ stored = _stored()+ parsed = _coerce_bool(stored.get(key)) if stored is not None else None+ return default if parsed is None else parsed+++def dacl_fallback_setting() -> bool:+ """Saved opt-in to MXC's AppContainer tier; off by default and when the store cannot be read."""+ return _setting(DACL_SETTING_KEY, DEFAULT_DACL_FALLBACK)+++def persistent_grants_setting() -> bool:+ """Saved choice to keep Studio's runtime read grants; a read failure keeps the shipped default (on)."""+ return _setting(GRANTS_SETTING_KEY, DEFAULT_PERSISTENT_GRANTS)+++def _write(key: str, value: Any) -> None:+ if not isinstance(value, bool):+ raise ValueError("MXC isolation settings must be true or false.")+ from storage.studio_db import upsert_app_settings+ from utils.account_context import OWNER, run_as++ run_as(OWNER, upsert_app_settings, {key: value})+ # Dropped, not replaced: a write that did not land must not be believed.+ forget_cached_setting()+++def set_dacl_fallback_setting(value: bool) -> None:+ _write(DACL_SETTING_KEY, value)+++def set_persistent_grants_setting(value: bool) -> None:+ _write(GRANTS_SETTING_KEY, value)+++def locked_by_environment(name: str) -> bool:+ """True when the environment decides ``name``, even set to an empty string."""+ return name in os.environdiff --git a/studio/frontend/src/components/command-palette.tsx b/studio/frontend/src/components/command-palette.tsxindex 203c91fbd41..22c304cc8db 100644--- a/studio/frontend/src/components/command-palette.tsx+++ b/studio/frontend/src/components/command-palette.tsx@@ -150,6 +150,7 @@ const SETTINGS_TAB_LABELS: Record<SettingsTab, TranslationKey> = {connections: "settings.tabs.connections",library: "shell.navigation.library",data: "settings.tabs.data",+ sandbox: "settings.tabs.sandbox","api-keys": "settings.tabs.apiKeys","remote-lan": "settings.tabs.remoteLan",agents: "settings.tabs.agents",diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 712a60616ff..0f542481aab 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -6446,7 +6446,7 @@ export function createOpenAIStreamAdapter(],mcp_enabled: mcpEnabledForChat,permission_mode: permissionMode,- ...(permissionMode === "auto"+ ...(permissionMode === "auto" || permissionMode === "off"? {}: { confirm_tool_calls: permissionMode === "ask" }),bypass_permissions: bypassPermissions,@@ -6624,9 +6624,10 @@ export function createOpenAIStreamAdapter(: {}),// Sent for every local chat, since `unsloth run --enable-tools` can open the tool loop with// no pill lit. "auto" OMITS confirm_tool_calls (an explicit true would force a stream and- // defeat the safe-only exception); "ask" sends true, off/full send false.+ // 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.permission_mode: permissionMode,- ...(permissionMode === "auto"+ ...(permissionMode === "auto" || permissionMode === "off"? {}: { confirm_tool_calls: permissionMode === "ask" }),bypass_permissions: bypassPermissions,diff --git a/studio/frontend/src/features/chat/api/sandbox-capability.ts b/studio/frontend/src/features/chat/api/sandbox-capability.tsnew file mode 100644index 00000000000..cfdd0925a51--- /dev/null+++ b/studio/frontend/src/features/chat/api/sandbox-capability.ts@@ -0,0 +1,250 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";++const CAPABILITY_ROUTE = "/api/sandbox/capability";+const SETUP_ROUTE = "/api/settings/sandbox/setup";+const CAPABILITY_TTL_MS = 30_000;++export type SandboxSetupAction = "linux-install" | "windows-setup";+export type SandboxSetupOperation = SandboxSetupAction | "windows-runtime";++export type SandboxCapability = {+ pythonOsIsolated: boolean;+ terminalOsIsolated: boolean;+ backend: string;+ platform: string;+ reason: string;+ setupAction: SandboxSetupAction | null;+ manualCommand: string;+ canRunSetup: boolean;+ // "no_elevation": owner is local but there is no passwordless sudo or desktop prompt.+ setupBlocked: "not_owner" | "not_local" | "no_elevation" | null;+ needsConsent: boolean;+};++export type SandboxSetupState =+ | "idle"+ | "running"+ | "succeeded"+ | "declined"+ | "failed";++export type SandboxSetupJob = {+ id: string | null;+ operation: string | null;+ state: SandboxSetupState;+ startedAt: number | null;+ finishedAt: number | null;+ exitCode: number | null;+ outputTail: string[];+ steps: string[];+ manualCommand: string;+ note: string;+};++type ApiCapability = {+ // biome-ignore lint/style/useNamingConvention: API schema+ python_os_isolated?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ terminal_os_isolated?: boolean;+ backend?: string;+ platform?: string;+ reason?: string;+ // biome-ignore lint/style/useNamingConvention: API schema+ setup_action?: string | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ manual_command?: string | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ can_run_setup?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ setup_blocked?: string | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ needs_consent?: boolean;+};++type ApiSetupJob = {+ id?: string | null;+ operation?: string | null;+ state?: SandboxSetupState;+ // biome-ignore lint/style/useNamingConvention: API schema+ started_at?: number | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ finished_at?: number | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ exit_code?: number | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ output_tail?: string[];+ steps?: string[];+ // biome-ignore lint/style/useNamingConvention: API schema+ manual_command?: string | null;+ note?: string | null;+};++function setupActionFromApi(+ value: string | null | undefined,+): SandboxSetupAction | null {+ return value === "linux-install" || value === "windows-setup" ? value : null;+}++export function capabilityFromApi(body: ApiCapability): SandboxCapability {+ const setupAction = setupActionFromApi(body.setup_action);+ const canRunSetup = setupAction !== null && (body.can_run_setup ?? false);+ return {+ pythonOsIsolated: body.python_os_isolated ?? false,+ terminalOsIsolated: body.terminal_os_isolated ?? false,+ backend: body.backend ?? "none",+ platform: body.platform ?? "",+ reason: body.reason ?? "",+ setupAction,+ manualCommand: body.manual_command ?? "",+ canRunSetup,+ setupBlocked:+ body.setup_blocked === "not_owner" ||+ body.setup_blocked === "not_local" ||+ body.setup_blocked === "no_elevation"+ ? body.setup_blocked+ : null,+ needsConsent:+ canRunSetup &&+ setupAction === "windows-setup" &&+ (body.needs_consent ?? false),+ };+}++export function setupJobFromApi(job: ApiSetupJob): SandboxSetupJob {+ return {+ id: job.id ?? null,+ operation: job.operation ?? null,+ state: job.state ?? "idle",+ startedAt: job.started_at ?? null,+ finishedAt: job.finished_at ?? null,+ exitCode: job.exit_code ?? null,+ outputTail: job.output_tail ?? [],+ steps: job.steps ?? [],+ manualCommand: job.manual_command ?? "",+ note: job.note ?? "",+ };+}++export function sandboxReady(capability: SandboxCapability): boolean {+ return capability.pythonOsIsolated && capability.terminalOsIsolated;+}++export function capabilityPending(capability: SandboxCapability): boolean {+ return capability.backend === "unknown" && !sandboxReady(capability);+}++let cached: { at: number; value: SandboxCapability | null } | null = null;+let inFlight: Promise<SandboxCapability | null> | null = null;+// Only the latest request writes the cache: an older one finishing last must not replace it.+let latestRequest = 0;+const changeListeners = new Set<() => void>();++/** Called after a new answer is cached or the cache is dropped (a setup finished). */+export function onSandboxCapabilityChange(listener: () => void): () => void {+ changeListeners.add(listener);+ return () => {+ changeListeners.delete(listener);+ };+}++function notifyCapabilityChange(): void {+ for (const listener of [...changeListeners]) listener();+}++export function loadSandboxCapability({+ force = false,+}: { force?: boolean } = {}): Promise<SandboxCapability | null> {+ if (!force && cached && Date.now() - cached.at < CAPABILITY_TTL_MS) {+ return Promise.resolve(cached.value);+ }+ if (!force && inFlight) return inFlight;+ const id = ++latestRequest;+ const request = authFetch(+ force ? `${CAPABILITY_ROUTE}?refresh=1` : CAPABILITY_ROUTE,+ )+ .then(async (res) => {+ if (!res.ok) return null;+ return capabilityFromApi((await res.json()) as ApiCapability);+ })+ .catch(() => null)+ .then((value) => {+ if (id === latestRequest) {+ cached = { at: Date.now(), value };+ notifyCapabilityChange();+ }+ return value;+ })+ .finally(() => {+ if (inFlight === request) inFlight = null;+ });+ inFlight = request;+ return request;+}++const PENDING_RETRY_MS = 1500;++/** A forced read that retries a few times while the backend is still "unknown". */+export async function loadSettledSandboxCapability({+ attempts = 3,+ delayMs = PENDING_RETRY_MS,+}: {+ attempts?: number;+ delayMs?: number;+} = {}): Promise<SandboxCapability | null> {+ let capability = await loadSandboxCapability({ force: true });+ for (let left = attempts - 1; left > 0; left--) {+ if (capability === null || !capabilityPending(capability)) break;+ await new Promise((resolve) => setTimeout(resolve, delayMs));+ capability = await loadSandboxCapability({ force: true });+ }+ return capability;+}++export function cachedSandboxCapability(): SandboxCapability | null {+ return cached?.value ?? null;+}++export function forgetSandboxCapability(): void {+ cached = null;+ inFlight = null;+ latestRequest++;+ notifyCapabilityChange();+}++async function checkedSetup(+ res: Response,+ fallbackMessage: string,+): Promise<SandboxSetupJob> {+ if (!res.ok) {+ throw new Error(await readFastApiError(res, fallbackMessage));+ }+ return setupJobFromApi((await res.json()) as ApiSetupJob);+}++export async function startSandboxSetup(+ operation: SandboxSetupOperation,+ { consentDaclFallback = false }: { consentDaclFallback?: boolean },+ fallbackMessage: string,+): Promise<SandboxSetupJob> {+ const res = await authFetch(SETUP_ROUTE, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ operation,+ // biome-ignore lint/style/useNamingConvention: API schema+ consent_dacl_fallback: consentDaclFallback,+ }),+ });+ return checkedSetup(res, fallbackMessage);+}++export async function loadSandboxSetup(+ fallbackMessage: string,+): Promise<SandboxSetupJob> {+ const res = await authFetch(SETUP_ROUTE);+ return checkedSetup(res, fallbackMessage);+}diff --git a/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx b/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsxindex aac688ae9a4..f3296c21732 100644--- a/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx+++ b/studio/frontend/src/features/chat/bypass-permissions-menu-item.tsx@@ -16,6 +16,7 @@ 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.@@ -23,6 +24,7 @@ export function BypassPermissionsMenuItem() {const setBypassConfirmOpen = useChatRuntimeStore((s) => s.setBypassConfirmOpen,);+ const setSandboxSetupOpen = useSandboxSetupDialogStore((s) => s.setOpen);return (<DropdownMenuSub>@@ -38,6 +40,9 @@ export function BypassPermissionsMenuItem() {onRequestFullAccess={() =>setTimeout(() => setBypassConfirmOpen(true), 0)}+ onRequestSandboxSetup={() =>+ setTimeout(() => setSandboxSetupOpen(true), 0)+ }/></DropdownMenuSubContent></DropdownMenuSub>diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 203f5084d0a..f96b2231da6 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -239,6 +239,7 @@ import {SharedComposer,} from "./shared-composer";import { BypassPermissionsConfirmDialog } from "./bypass-permissions-menu-item";+import { RootSandboxSetupDialog } from "./sandbox-setup-dialog";import {CHAT_CODE_TOOLS_ENABLED_KEY,CHAT_IMAGE_TOOLS_ENABLED_KEY,@@ -4479,6 +4480,7 @@ export function ChatPage({so it must live at one stable root, or Compare mode's composers would each render a copy.It also portals to body, so gate it on `active`. */}{active && <BypassPermissionsConfirmDialog />}+ {active && <RootSandboxSetupDialog />}{/* The MCP servers dialog: its chord has to work before MCP is switched on, and the pill thatused to own it only renders once it is. Mounted through the route change so it can closeitself on the way out. */}diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsxindex a96fa1d2569..46621966a16 100644--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx@@ -78,7 +78,11 @@ import {useSyncExternalStore,} from "react";import { OpenAICodeExecSection } from "./components/openai-code-exec-section";-import { PermissionModeDropdown } from "./permission-mode-select";+import {+ PermissionModeDropdown,+ pickSandboxedMode,+} from "./permission-mode-select";+import { useSandboxSetupDialogStore } from "./sandbox-setup-dialog";import { resyncInferenceStatusAfterServerModelChange } from "./hooks/use-chat-model-runtime";import {type ExternalProviderConfig,@@ -2032,7 +2036,9 @@ function NudgeToolCallsToggle() {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">@@ -2045,7 +2051,8 @@ function ConfirmToolCallsToggle() {When on, every local Unsloth tool call pauses for your approvalbefore it runs (the "Ask for approval" level). When off, tool callsrun without prompts inside the sandbox (the "Run automatically"- level).+ level); on a computer without a working OS sandbox, risky Python+ and Terminal calls still ask.Provider-hosted tools are not gated here.</InfoHint></div>@@ -2058,7 +2065,17 @@ function ConfirmToolCallsToggle() {<SwitchclassName="panel-switch shrink-0"checked={permissionMode === "ask"}- onCheckedChange={setConfirmToolCalls}+ onCheckedChange={(checked) => {+ 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),+ );+ }+ }}disabled={permissionMode === "full"}/></div>diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex c032241e67b..672135b4add 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -91,6 +91,14 @@ export {} from "./tool-output-scope";export { useToolAwaitingApproval } from "./tool-approval";export { PermissionModeDropdown, useActivePermissionMode } from "./permission-mode-select";+export {+ type SandboxSetupAction,+ type SandboxSetupJob,+ type SandboxSetupOperation,+ forgetSandboxCapability,+ loadSandboxSetup,+ startSandboxSetup,+} from "./api/sandbox-capability";export { useChatSearchStore } from "./stores/chat-search-store";export type { ChatNavigationState } from "./stores/chat-navigation-store";export {diff --git a/studio/frontend/src/features/chat/permission-mode-select.tsx b/studio/frontend/src/features/chat/permission-mode-select.tsxindex ef6db8c078f..ff2b7890366 100644--- a/studio/frontend/src/features/chat/permission-mode-select.tsx+++ b/studio/frontend/src/features/chat/permission-mode-select.tsx@@ -7,6 +7,7 @@ import type { ComponentType } from "react";import { useEffect, useRef, useState } from "react";import { useFullAccessAllowed } from "@/features/auth/account-session";import { useSettingsDialogStore } from "@/features/settings";+import { useT } from "@/i18n";import {AlertDialog,@@ -37,6 +38,20 @@ import {InternetIcon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";+import {+ capabilityPending,+ loadSandboxCapability,+ onSandboxCapabilityChange,+ sandboxReady,+} from "./api/sandbox-capability";+import {+ pickSandboxedMode as pickSandboxedModeWith,+ samePickIsIgnored,+} from "./sandbox-pick";+import {+ SandboxSetupDialog,+ useSandboxSetupDialogStore,+} from "./sandbox-setup-dialog";import {type PermissionMode,useChatRuntimeStore,@@ -145,13 +160,62 @@ 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);+ useEffect(() => {+ 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),+ );+ }+ });+ };+ read();+ const stop = onSandboxCapabilityChange(read);+ return () => {+ 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();+ }),+ );+}+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 (<>@@ -159,11 +223,13 @@ export function PermissionModeMenuItems({<DropdownMenuItemkey={option.value}onSelect={() => {- if (option.value === permissionMode) {+ if (samePickIsIgnored(option.value, permissionMode, sandboxUnavailable)) {return;}if (option.value === "full") {onRequestFullAccess();+ } else if (option.value === "off") {+ void pickSandboxedMode(setPermissionMode, onRequestSandboxSetup);} else {setPermissionMode(option.value);}@@ -179,6 +245,11 @@ 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@@ -333,6 +404,7 @@ export function PermissionModeDropdown({} = {}) {const { permissionMode, fullAccessAllowed } = useAccountPermissionMode();const [confirmOpen, setConfirmOpen] = useState(false);+ const [sandboxSetupOpen, setSandboxSetupOpen] = useState(false);const active = permissionModeOption(permissionMode);const ActiveIcon = active.icon;@@ -366,6 +438,9 @@ export function PermissionModeDropdown({onRequestFullAccess={() =>setTimeout(() => setConfirmOpen(true), 0)}+ onRequestSandboxSetup={() =>+ setTimeout(() => setSandboxSetupOpen(true), 0)+ }/></DropdownMenuContent></DropdownMenu>@@ -373,6 +448,10 @@ export function PermissionModeDropdown({open={confirmOpen}onOpenChange={setConfirmOpen}/>+ <SandboxSetupDialog+ open={sandboxSetupOpen}+ onOpenChange={setSandboxSetupOpen}+ /></>);}@@ -389,6 +468,7 @@ export function PermissionModeComposerPill({const setBypassConfirmOpen = useChatRuntimeStore((s) => s.setBypassConfirmOpen,);+ const setSandboxSetupOpen = useSandboxSetupDialogStore((s) => s.setOpen);const active = permissionModeOption(permissionMode);const ActiveIcon = active.icon;@@ -426,6 +506,9 @@ export function PermissionModeComposerPill({onRequestFullAccess={() =>setTimeout(() => setBypassConfirmOpen(true), 0)}+ onRequestSandboxSetup={() =>+ setTimeout(() => setSandboxSetupOpen(true), 0)+ }/></DropdownMenuContent></DropdownMenu>diff --git a/studio/frontend/src/features/chat/sandbox-pick.ts b/studio/frontend/src/features/chat/sandbox-pick.tsnew file mode 100644index 00000000000..d7d0ffbbfc5--- /dev/null+++ b/studio/frontend/src/features/chat/sandbox-pick.ts@@ -0,0 +1,59 @@+// 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 {+ type SandboxCapability,+ cachedSandboxCapability,+ capabilityPending,+ loadSettledSandboxCapability,+ sandboxReady,+} from "./api/sandbox-capability";+import type { PermissionMode } from "./stores/chat-runtime-store";++let sandboxedPicks = 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,+ 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 known = peek();+ if (known !== null && sandboxReady(known)) {+ setPermissionMode("off");+ 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 (+ capability !== null &&+ !capabilityPending(capability) &&+ !sandboxReady(capability)+ ) {+ onRequestSandboxSetup();+ } else {+ setPermissionMode("off");+ }+ });+}diff --git a/studio/frontend/src/features/chat/sandbox-setup-dialog.tsx b/studio/frontend/src/features/chat/sandbox-setup-dialog.tsxnew file mode 100644index 00000000000..0bc87533de3--- /dev/null+++ b/studio/frontend/src/features/chat/sandbox-setup-dialog.tsx@@ -0,0 +1,341 @@+// 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 { useCallback, useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { create } from "zustand";++import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";+import { Spinner } from "@/components/ui/spinner";+import { useT } from "@/i18n";+import { copyToClipboard } from "@/lib/copy-to-clipboard";+import {+ type SandboxCapability,+ type SandboxSetupJob,+ forgetSandboxCapability,+ loadSandboxSetup,+ loadSettledSandboxCapability,+ sandboxReady,+ startSandboxSetup,+} from "./api/sandbox-capability";+import { SANDBOX_SETUP_POLL_MS, sandboxSetupView } from "./sandbox-setup-state";+import { useChatRuntimeStore } from "./stores/chat-runtime-store";++/** Mounted once at the chat-page root so it outlives the menu that opened it. */+export const useSandboxSetupDialogStore = create<{+ open: boolean;+ setOpen: (open: boolean) => void;+}>((set) => ({+ open: false,+ setOpen: (open) => set({ open }),+}));++const NOTE_CLASS = "text-xs leading-relaxed";++/** Picking the mode never starts a setup; only the install button does. */+export function SandboxSetupDialog({+ open,+ onOpenChange,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) {+ return (+ <AlertDialog open={open} onOpenChange={onOpenChange}>+ {/* Mounted per opening, so every opening starts from a fresh check. */}+ {open ? <SandboxSetupContent onOpenChange={onOpenChange} /> : null}+ </AlertDialog>+ );+}++function SandboxSetupContent({+ onOpenChange,+}: {+ onOpenChange: (open: boolean) => void;+}) {+ const t = useT();+ const setPermissionMode = useChatRuntimeStore((s) => s.setPermissionMode);+ const [capability, setCapability] = useState<SandboxCapability | null>(null);+ const [loadFailed, setLoadFailed] = useState(false);+ const [job, setJob] = useState<SandboxSetupJob | null>(null);+ const [consent, setConsent] = useState(false);+ const [stillUnavailable, setStillUnavailable] = useState(false);+ const [actionError, setActionError] = useState<string | null>(null);+ 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);++ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);++ const check = useCallback(() => {+ const id = ++checks.current;+ void loadSettledSandboxCapability().then((next) => {+ if (!mounted.current || id !== checks.current) return;+ if (next === null) {+ setLoadFailed(true);+ return;+ }+ setCapability(next);+ if (next.canRunSetup) {+ void loadSandboxSetup(t("sandboxSetup.startError"))+ .then((current) => {+ if (mounted.current && current.state === "running") setJob(current);+ })+ .catch(() => undefined);+ }+ });+ }, [t]);++ useEffect(() => {+ check();+ }, [check]);++ const retry = () => {+ setLoadFailed(false);+ check();+ };++ const finish = useCallback(+ (finished: SandboxSetupJob) => {+ if (finished.state !== "succeeded") return;+ forgetSandboxCapability();+ void loadSettledSandboxCapability().then((next) => {+ if (!mounted.current) return;+ if (next) setCapability(next);+ if (next && sandboxReady(next)) {+ if (useChatRuntimeStore.getState().permissionMode === modeAtOpen.current) {+ setPermissionMode("off");+ }+ toast.success(t("sandboxSetup.succeeded"));+ onOpenChange(false);+ } else {+ setStillUnavailable(true);+ }+ });+ },+ [onOpenChange, setPermissionMode, t],+ );++ useEffect(() => {+ if (job?.state !== "running") return;+ const timer = window.setTimeout(() => {+ void loadSandboxSetup(t("sandboxSetup.startError"))+ .then((next) => {+ if (!mounted.current) return;+ setJob(next);+ if (next.state !== "running") finish(next);+ })+ .catch((pollError) => {+ if (!mounted.current) return;+ setActionError(+ pollError instanceof Error+ ? pollError.message+ : t("sandboxSetup.startError"),+ );+ setJob(null);+ });+ }, SANDBOX_SETUP_POLL_MS);+ return () => window.clearTimeout(timer);+ }, [job, t, finish]);++ const view = sandboxSetupView({ capability, job, consent, loadFailed });++ const install = async () => {+ const operation = capability?.setupAction;+ if (!operation) return;+ setActionError(null);+ setStillUnavailable(false);+ try {+ const started = await startSandboxSetup(+ operation,+ { consentDaclFallback: view.showConsent && consent },+ t("sandboxSetup.startError"),+ );+ if (!mounted.current) return;+ setJob(started);+ if (started.state !== "running") finish(started);+ } catch (startError) {+ if (!mounted.current) return;+ setActionError(+ startError instanceof Error+ ? startError.message+ : t("sandboxSetup.startError"),+ );+ }+ };++ const copy = async () => {+ if (await copyToClipboard(view.command)) {+ toast.success(t("sandboxSetup.copied"));+ } else {+ toast.error(t("sandboxSetup.copyFailed"));+ }+ };++ return (+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("sandboxSetup.title")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t("sandboxSetup.description")}+ </AlertDialogDescription>+ </AlertDialogHeader>++ <div className="flex min-w-0 flex-col gap-3">+ {view.loadFailed ? (+ <p className={`${NOTE_CLASS} text-destructive`}>+ {t("sandboxSetup.checkFailed")}+ </p>+ ) : null}+ {view.checking ? (+ <p+ className={`${NOTE_CLASS} flex items-center gap-2 text-muted-foreground`}+ >+ <Spinner />+ {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")}+ </p>+ <label className="flex items-center gap-2 text-sm">+ <Checkbox+ checked={consent}+ disabled={view.running}+ onCheckedChange={(checked) => setConsent(checked === true)}+ />+ {t("settings.sandbox.optInLabel")}+ </label>+ </div>+ ) : null}+ {view.running ? (+ <p+ className={`${NOTE_CLASS} flex items-center gap-2 text-muted-foreground`}+ >+ <Spinner />+ {t("sandboxSetup.running")}+ </p>+ ) : null}+ {view.running ? (+ <p className={`${NOTE_CLASS} text-muted-foreground`}>+ {t("sandboxSetup.keepsRunning")}+ </p>+ ) : null}+ {stillUnavailable ? (+ <p className={`${NOTE_CLASS} text-destructive`}>+ {t("sandboxSetup.stillUnavailable")}+ </p>+ ) : null}+ {view.result === "declined" ? (+ <p className={`${NOTE_CLASS} text-destructive`}>+ {t("sandboxSetup.declined")}+ </p>+ ) : null}+ {view.result === "failed" ? (+ <p className={`${NOTE_CLASS} text-destructive`}>+ {t("sandboxSetup.failed")}+ </p>+ ) : null}+ {view.note ? (+ <p className={`${NOTE_CLASS} text-destructive`}>{view.note}</p>+ ) : null}+ {view.outputLines.length > 0 ? (+ <pre className="whitespace-pre-wrap break-words font-mono text-ui-11 text-muted-foreground">+ {view.outputLines.join("\n")}+ </pre>+ ) : null}+ {actionError ? (+ <p className={`${NOTE_CLASS} text-destructive`}>{actionError}</p>+ ) : null}+ {view.showOwnerOnly && !view.command ? (+ <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">+ {view.loadFailed ? (+ <Button size="sm" onClick={retry}>+ {t("sandboxSetup.retry")}+ </Button>+ ) : null}+ {view.install ? (+ <Button+ size="sm"+ disabled={view.installDisabled}+ onClick={() => void install()}+ >+ {view.running ? <Spinner /> : null}+ {view.install === "windows"+ ? t("sandboxSetup.windowsSetup")+ : t("sandboxSetup.install")}+ </Button>+ ) : null}+ {view.command ? (+ <Button size="sm" variant="outline" onClick={() => void copy()}>+ {t("sandboxSetup.copyCommand")}+ </Button>+ ) : null}+ <Button+ size="sm"+ variant="outline"+ disabled={view.checking}+ onClick={() => {+ setPermissionMode("off");+ onOpenChange(false);+ }}+ >+ {t("sandboxSetup.useAnyway")}+ </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>+ </AlertDialogFooter>+ </AlertDialogContent>+ );+}++export function RootSandboxSetupDialog() {+ const open = useSandboxSetupDialogStore((s) => s.open);+ const setOpen = useSandboxSetupDialogStore((s) => s.setOpen);+ return <SandboxSetupDialog open={open} onOpenChange={setOpen} />;+}diff --git a/studio/frontend/src/features/chat/sandbox-setup-state.ts b/studio/frontend/src/features/chat/sandbox-setup-state.tsnew file mode 100644index 00000000000..b67ec7eb983--- /dev/null+++ b/studio/frontend/src/features/chat/sandbox-setup-state.ts@@ -0,0 +1,93 @@+// 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 { type JobResult, jobOutputLines, jobResult } from "@/features/settings";+import type {+ SandboxCapability,+ SandboxSetupJob,+} from "./api/sandbox-capability";++export const SANDBOX_SETUP_POLL_MS = 2000;++export type SandboxSetupView = {+ checking: boolean;+ loadFailed: boolean;+ install: "linux" | "windows" | null;+ showConsent: boolean;+ installDisabled: boolean;+ command: string;+ showOwnerOnly: boolean;+ showRunInTerminal: boolean;+ running: boolean;+ result: JobResult;+ outputLines: string[];+ note: string;+};++export function sandboxSetupView({+ capability,+ job,+ consent,+ loadFailed = false,+}: {+ capability: SandboxCapability | null;+ job: SandboxSetupJob | null;+ consent: boolean;+ loadFailed?: boolean;+}): SandboxSetupView {+ const running = job?.state === "running";+ const result = jobResult(job);+ const note =+ (result === "failed" || result === "declined") && job?.note ? job.note : "";+ if (!capability) {+ return {+ checking: !loadFailed,+ loadFailed,+ install: null,+ showConsent: false,+ installDisabled: true,+ command: "",+ showOwnerOnly: false,+ showRunInTerminal: false,+ running,+ result,+ outputLines: jobOutputLines(job),+ note,+ };+ }+ const action = capability.canRunSetup ? capability.setupAction : null;+ const install =+ action === "linux-install"+ ? "linux"+ : action === "windows-setup"+ ? "windows"+ : null;+ const showConsent = install === "windows" && capability.needsConsent;+ const command =+ (result === "failed" || result === "declined") && job?.manualCommand+ ? job.manualCommand+ : capability.manualCommand;+ return {+ checking: false,+ loadFailed: false,+ install,+ showConsent,+ installDisabled: running || (showConsent && !consent),+ command,+ // Windows commands name this install's paths: owner only.+ showOwnerOnly:+ install === null &&+ (command !== "" ||+ capability.setupBlocked === "not_owner" ||+ capability.setupBlocked === "not_local") &&+ capability.setupBlocked !== "no_elevation",+ showRunInTerminal:+ install === null &&+ command !== "" &&+ capability.setupBlocked === "no_elevation",+ running,+ result,+ outputLines: jobOutputLines(job),+ note,+ };+}diff --git a/studio/frontend/src/features/settings/api/sandbox-isolation.ts b/studio/frontend/src/features/settings/api/sandbox-isolation.tsnew file mode 100644index 00000000000..01ce513265b--- /dev/null+++ b/studio/frontend/src/features/settings/api/sandbox-isolation.ts@@ -0,0 +1,287 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";++import { SettingsRouteAbsentError } from "./settings-route-absent";++const ROUTE = "/api/settings/sandbox";+const PREPARE_ROUTE = "/api/settings/sandbox/prepare";++export type SandboxToolStatus = {+ backend: string;+ available: boolean;+ reason: string;+ limitations: string[];+ protectionState: string | null;+ remediation: string;+};++export type TerminalShell = "bash" | "cmd_isolated" | "cmd_fallback";++// "arch": not x64 Windows; "build": older than Windows 11 build 26100. MXC cannot run on either.+export type RuntimeUnsupported = "arch" | "build";++export type WindowsSandboxStatus = {+ runtimeInstalled: boolean;+ runtimeUnsupported: RuntimeUnsupported | null;+ allowDaclFallback: boolean;+ allowDaclFallbackSaved: boolean;+ daclLockedByEnvironment: boolean;+ persistentReadGrants: boolean;+ persistentReadGrantsSaved: boolean;+ grantsLockedByEnvironment: boolean;+ // null: MXC could not tell which host preparation steps are missing.+ hostPrepMissing: string[] | null;+ prepareRepeatsAfterRestart: boolean;+};++export type SandboxSetupPlan = {+ action: "linux-install" | "windows-setup" | null;+ elevation: string | null;+ manualCommand: string;+ reason: string;+ canRun: boolean;+};++export type SandboxStatus = {+ platform: string;+ python: SandboxToolStatus;+ terminal: SandboxToolStatus;+ terminalShell: TerminalShell | null;+ windows: WindowsSandboxStatus | null;+ setup: SandboxSetupPlan | null;+ checkedAt: number;+ restored?: number;+};++export type SandboxSettingsUpdate = {+ allowDaclFallback?: boolean;+ persistentReadGrants?: boolean;+};++export type HostPrepState =+ | "idle"+ | "running"+ | "succeeded"+ | "declined"+ | "failed";++export type HostPrepJob = {+ id: string | null;+ state: HostPrepState;+ startedAt: number | null;+ finishedAt: number | null;+ exitCode: number | null;+ outputTail: string[];+ steps: string[];+};++type ApiToolStatus = {+ backend?: string;+ available?: boolean;+ reason?: string;+ limitations?: string[];+ // biome-ignore lint/style/useNamingConvention: API schema+ protection_state?: string | null;+ remediation?: string | null;+};++type ApiSetupPlan = {+ action?: string | null;+ elevation?: string | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ manual_command?: string | null;+ reason?: string | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ can_run?: boolean;+};++type ApiWindowsStatus = {+ // biome-ignore lint/style/useNamingConvention: API schema+ runtime_installed?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ runtime_unsupported?: string | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ allow_dacl_fallback?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ allow_dacl_fallback_saved?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ dacl_locked_by_environment?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ persistent_read_grants?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ persistent_read_grants_saved?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ grants_locked_by_environment?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ host_prep_missing?: string[] | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ prepare_repeats_after_restart?: boolean;+};++type ApiSandboxStatus = {+ platform?: string;+ python?: ApiToolStatus;+ terminal?: ApiToolStatus;+ // biome-ignore lint/style/useNamingConvention: API schema+ terminal_shell?: TerminalShell | null;+ windows?: ApiWindowsStatus | null;+ setup?: ApiSetupPlan | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ checked_at?: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ grants_restored?: number | null;+};++type ApiHostPrepJob = {+ id?: string | null;+ state?: HostPrepState;+ // biome-ignore lint/style/useNamingConvention: API schema+ started_at?: number | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ finished_at?: number | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ exit_code?: number | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ output_tail?: string[];+ steps?: string[];+};++function toolFromApi(tool: ApiToolStatus | undefined): SandboxToolStatus {+ return {+ backend: tool?.backend ?? "none",+ available: tool?.available ?? false,+ reason: tool?.reason ?? "",+ limitations: tool?.limitations ?? [],+ protectionState: tool?.protection_state ?? null,+ remediation: tool?.remediation ?? "",+ };+}++function setupFromApi(setup: ApiSetupPlan | null | undefined): SandboxSetupPlan | null {+ if (!setup) return null;+ const action =+ setup.action === "linux-install" || setup.action === "windows-setup"+ ? setup.action+ : null;+ return {+ action,+ elevation: setup.elevation ?? null,+ manualCommand: setup.manual_command ?? "",+ reason: setup.reason ?? "",+ canRun: action !== null && (setup.can_run ?? true),+ };+}++function windowsFromApi(+ windows: ApiWindowsStatus | null | undefined,+): WindowsSandboxStatus | null {+ if (!windows) return null;+ return {+ runtimeInstalled: windows.runtime_installed ?? false,+ runtimeUnsupported:+ windows.runtime_unsupported === "arch" ||+ windows.runtime_unsupported === "build"+ ? windows.runtime_unsupported+ : null,+ allowDaclFallback: windows.allow_dacl_fallback ?? false,+ allowDaclFallbackSaved: windows.allow_dacl_fallback_saved ?? false,+ daclLockedByEnvironment: windows.dacl_locked_by_environment ?? false,+ persistentReadGrants: windows.persistent_read_grants ?? true,+ persistentReadGrantsSaved: windows.persistent_read_grants_saved ?? true,+ grantsLockedByEnvironment: windows.grants_locked_by_environment ?? false,+ hostPrepMissing:+ windows.host_prep_missing === undefined+ ? null+ : windows.host_prep_missing,+ prepareRepeatsAfterRestart: windows.prepare_repeats_after_restart ?? true,+ };+}++export function statusFromApi(status: ApiSandboxStatus): SandboxStatus {+ const out: SandboxStatus = {+ platform: status.platform ?? "",+ python: toolFromApi(status.python),+ terminal: toolFromApi(status.terminal),+ terminalShell: status.terminal_shell ?? null,+ windows: windowsFromApi(status.windows),+ setup: setupFromApi(status.setup),+ checkedAt: status.checked_at ?? 0,+ };+ if (typeof status.grants_restored === "number") out.restored = status.grants_restored;+ return out;+}++export function jobFromApi(job: ApiHostPrepJob): HostPrepJob {+ return {+ id: job.id ?? null,+ state: job.state ?? "idle",+ startedAt: job.started_at ?? null,+ finishedAt: job.finished_at ?? null,+ exitCode: job.exit_code ?? null,+ outputTail: job.output_tail ?? [],+ steps: job.steps ?? [],+ };+}++// Older backends lack these routes: reported apart from a failure so the tab can say so.+async function checked(+ res: Response,+ route: string,+ fallbackMessage: string,+): Promise<Response> {+ if (res.status === 404) {+ throw new SettingsRouteAbsentError(route);+ }+ if (!res.ok) {+ throw new Error(await readFastApiError(res, fallbackMessage));+ }+ return res;+}++export async function loadSandboxStatus(+ refresh: boolean,+ fallbackMessage: string,+): Promise<SandboxStatus> {+ const res = await authFetch(refresh ? `${ROUTE}?refresh=1` : ROUTE);+ await checked(res, ROUTE, fallbackMessage);+ return statusFromApi(await res.json());+}++export async function updateSandboxSettings(+ update: SandboxSettingsUpdate,+ fallbackMessage: string,+): Promise<SandboxStatus> {+ const body: Record<string, boolean> = {};+ if (update.allowDaclFallback !== undefined) {+ body.allow_dacl_fallback = update.allowDaclFallback;+ }+ if (update.persistentReadGrants !== undefined) {+ body.persistent_read_grants = update.persistentReadGrants;+ }+ const res = await authFetch(ROUTE, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });+ await checked(res, ROUTE, fallbackMessage);+ return statusFromApi(await res.json());+}++export async function startHostPreparation(+ fallbackMessage: string,+): Promise<HostPrepJob> {+ const res = await authFetch(PREPARE_ROUTE, { method: "POST" });+ await checked(res, PREPARE_ROUTE, fallbackMessage);+ return jobFromApi(await res.json());+}++export async function loadHostPreparation(+ fallbackMessage: string,+): Promise<HostPrepJob> {+ const res = await authFetch(PREPARE_ROUTE);+ await checked(res, PREPARE_ROUTE, fallbackMessage);+ return jobFromApi(await res.json());+}diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.tsindex df2986a6734..28ad15ba469 100644--- a/studio/frontend/src/features/settings/index.ts+++ b/studio/frontend/src/features/settings/index.ts@@ -2,6 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0export { SettingsDialogMount } from "./settings-dialog-mount";+export {+ type JobResult,+ jobOutputLines,+ jobResult,+} from "./tabs/sandbox-tab-state";export {type DownloadTransportMode,type DownloadTransportSettings,diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsxindex a54cd6398a2..142d4399980 100644--- a/studio/frontend/src/features/settings/settings-dialog.tsx+++ b/studio/frontend/src/features/settings/settings-dialog.tsx@@ -33,6 +33,7 @@ import {PaintBrush02Icon,Search01Icon,Settings02Icon,+ Shield01Icon,UserCircleIcon,} from "@hugeicons/core-free-icons";import { MessageCircleIcon } from "@/lib/hugeicons-derived";@@ -77,6 +78,8 @@ const TAB_LOADERS = {resources: () =>import("./tabs/resources-tab").then((m) => ({ default: m.ResourcesTab })),chat: () => import("./tabs/chat-tab").then((m) => ({ default: m.ChatTab })),+ sandbox: () =>+ import("./tabs/sandbox-tab").then((m) => ({ default: m.SandboxTab })),browser: () =>import("./tabs/browser-tab").then((m) => ({ default: m.BrowserTab })),voice: () =>@@ -209,6 +212,11 @@ const TABS: TabDef[] = [labelKey: "settings.tabs.chat",icon: MessageCircleIcon,},+ {+ id: "sandbox",+ labelKey: "settings.tabs.sandbox",+ icon: Shield01Icon,+ },{id: "api-keys",labelKey: "settings.tabs.apiKeys",@@ -431,6 +439,7 @@ export function SettingsDialog() {appearance: null,resources: null,chat: null,+ sandbox: null,browser: null,voice: null,connections: null,diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex c446d95cab0..7a1418e090b 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -293,6 +293,12 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {"settings.keyboardShortcuts.actions.renameChat.label","settings.keyboardShortcuts.actions.openKeyboardShortcuts.label",],+ // The Windows rows render only on Windows, so only the rows every platform shows are indexed.+ sandbox: [+ "settings.sandbox.toolsSection",+ "settings.sandbox.python",+ "settings.sandbox.terminal",+ ],debugging: ["settings.debugging.logSection","settings.debugging.source",@@ -369,6 +375,7 @@ export const SETTINGS_SEARCH_KEYWORDS: Partial<> = {"settings.resources.storage.modelsFolder":"settings.resources.storage.modelsFolderKeywords",+ "settings.sandbox.toolsSection": "settings.sandbox.setupKeywords",// "purge", "prune" and the tool names are in none of the labels, so the row// the feature is named after was unreachable by search."settings.resources.storage.caches.label":diff --git a/studio/frontend/src/features/settings/settings-tab-visibility.ts b/studio/frontend/src/features/settings/settings-tab-visibility.tsindex ce70062ea5b..06c857caf6f 100644--- a/studio/frontend/src/features/settings/settings-tab-visibility.ts+++ b/studio/frontend/src/features/settings/settings-tab-visibility.ts@@ -10,6 +10,7 @@ export const OWNER_ONLY_SETTINGS_TABS: ReadonlySet<SettingsTab> = new Set<Settin"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.tsindex b5aa12d7ab1..97312bf71b0 100644--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts@@ -14,6 +14,7 @@ export const SETTINGS_TABS = ["appearance","resources","chat",+ "sandbox","voice","connections","library",diff --git a/studio/frontend/src/features/settings/tabs/sandbox-tab-state.ts b/studio/frontend/src/features/settings/tabs/sandbox-tab-state.tsnew file mode 100644index 00000000000..bef7564c4e0--- /dev/null+++ b/studio/frontend/src/features/settings/tabs/sandbox-tab-state.ts@@ -0,0 +1,215 @@+// 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 type {+ HostPrepJob,+ RuntimeUnsupported,+ SandboxStatus,+ SandboxToolStatus,+ TerminalShell,+ WindowsSandboxStatus,+} from "../api/sandbox-isolation";++export const HOST_PREP_POLL_MS = 2000;++// The one step wxc-host-prep undoes on every restart; missing alone, the PC was prepared before.+const REPEATING_STEP = "prepare-null-device";++const BACKEND_LABELS: Record<string, string> = {+ bubblewrap: "bubblewrap",+ "macos-seatbelt": "Seatbelt",+ "mxc-processcontainer": "MXC",+};++export type ToolRowView = {+ isolated: boolean;+ backendLabel: string;+ reason: string;+ remediation: string;+ runsInCmd: boolean;+};++export function toolRowView(+ tool: SandboxToolStatus,+ shell: TerminalShell | null = null,+): ToolRowView {+ return {+ isolated: tool.available,+ backendLabel: BACKEND_LABELS[tool.backend] ?? tool.backend,+ reason: tool.reason,+ remediation: tool.available ? "" : tool.remediation,+ runsInCmd: shell === "cmd_isolated",+ };+}++export type HostPrepStatus =+ | "runtimeMissing"+ | "off"+ | "prepared"+ | "needsPreparing"+ | "needsPreparingAgain"+ | "unknown";++export type WindowsView = {+ // MXC cannot run on this Windows at all: one note instead of the controls.+ unsupported: RuntimeUnsupported | null;+ runtimeMissing: boolean;+ showInstallRuntime: boolean;+ optInChecked: boolean;+ optInDisabled: boolean;+ optInLocked: boolean;+ showGrantsRow: boolean;+ grantsChecked: boolean;+ grantsDisabled: boolean;+ grantsLocked: boolean;+ prep: HostPrepStatus;+ showPrepareButton: boolean;+ prepareDisabled: boolean;+};++export function hostPrepStatus(windows: WindowsSandboxStatus): HostPrepStatus {+ if (!windows.runtimeInstalled) return "runtimeMissing";+ if (!windows.allowDaclFallback) return "off";+ const missing = windows.hostPrepMissing;+ if (missing === null) return "unknown";+ if (missing.length === 0) return "prepared";+ if (missing.length === 1 && missing[0] === REPEATING_STEP) {+ return "needsPreparingAgain";+ }+ return "needsPreparing";+}++export function windowsView(+ windows: WindowsSandboxStatus,+ job: HostPrepJob | null,+ saving: boolean,+): WindowsView {+ const prep = hostPrepStatus(windows);+ const running = job?.state === "running";+ const runtimeMissing = prep === "runtimeMissing";+ const unsupported = windows.runtimeUnsupported;+ return {+ unsupported,+ runtimeMissing,+ showInstallRuntime: runtimeMissing && unsupported === null,+ optInChecked: windows.allowDaclFallback,+ optInDisabled:+ runtimeMissing || windows.daclLockedByEnvironment || saving || running,+ optInLocked: windows.daclLockedByEnvironment,+ showGrantsRow: !runtimeMissing && windows.allowDaclFallback,+ grantsChecked: windows.persistentReadGrants,+ grantsDisabled: windows.grantsLockedByEnvironment || saving || running,+ grantsLocked: windows.grantsLockedByEnvironment,+ prep,+ // A running job keeps the button so its progress stays where the owner clicked.+ showPrepareButton:+ running ||+ prep === "needsPreparing" ||+ prep === "needsPreparingAgain" ||+ prep === "unknown",+ prepareDisabled: running || saving,+ };+}++/** A section below already says why and what to do: the Python and Terminal rows keep only their badge. */+export function toolRowsQuiet(+ setupRowShown: boolean,+ windows: WindowsView | null,+): boolean {+ if (setupRowShown) return true;+ if (!windows) return false;+ return (+ windows.unsupported !== null ||+ windows.prep === "runtimeMissing" ||+ windows.prep === "off" ||+ windows.prep === "needsPreparing" ||+ windows.prep === "needsPreparingAgain"+ );+}++export type JobResult = "succeeded" | "declined" | "failed" | null;++export function jobResult(job: HostPrepJob | null): JobResult {+ if (!job) return null;+ if (+ job.state === "succeeded" ||+ job.state === "declined" ||+ job.state === "failed"+ ) {+ return job.state;+ }+ return null;+}++export function shouldPollJob(job: HostPrepJob | null): boolean {+ return job?.state === "running";+}++// A read that returns after this tab started a newer job must not replace it.+type JobStamp = Pick<HostPrepJob, "id" | "startedAt">;++export function isOlderJob(+ loaded: JobStamp,+ current: JobStamp | null,+): boolean {+ if (!current || current.id === null || loaded.id === current.id) return false;+ return (loaded.startedAt ?? 0) <= (current.startedAt ?? 0);+}++// Only a failure shows the helper's output; the last few lines are the ones that name the cause.+export function jobOutputLines(job: HostPrepJob | null, max = 6): string[] {+ if (!job || job.state !== "failed") return [];+ return job.outputTail.filter((line) => line.trim() !== "").slice(-max);+}++export type SetupRowView = {+ show: boolean;+ builtIn: boolean;+ showInstall: boolean;+ installDisabled: boolean;+ command: string;+ reason: string;+};++const HIDDEN_SETUP_ROW: SetupRowView = {+ show: false,+ builtIn: false,+ showInstall: false,+ installDisabled: true,+ command: "",+ reason: "",+};++export function setupRowView(+ status: SandboxStatus,+ job: HostPrepJob | null,+ manualCommandFromJob = "",+): SetupRowView {+ if (status.platform === "win32") return HIDDEN_SETUP_ROW;+ const isolated = status.python.available && status.terminal.available;+ const running = job?.state === "running";+ if (status.platform === "darwin") {+ if (isolated) return HIDDEN_SETUP_ROW;+ return {+ ...HIDDEN_SETUP_ROW,+ show: true,+ builtIn: true,+ reason: status.setup?.reason || status.python.reason,+ };+ }+ const setup = status.setup;+ if (!setup) return HIDDEN_SETUP_ROW;+ const showInstall = setup.action === "linux-install" && setup.canRun;+ const failed = job?.state === "failed" || job?.state === "declined";+ const command =+ failed && manualCommandFromJob ? manualCommandFromJob : setup.manualCommand;+ if (!showInstall && command === "" && !running) return HIDDEN_SETUP_ROW;+ return {+ show: true,+ builtIn: false,+ showInstall: showInstall || running,+ installDisabled: running,+ command,+ reason: setup.reason,+ };+}diff --git a/studio/frontend/src/features/settings/tabs/sandbox-tab.tsx b/studio/frontend/src/features/settings/tabs/sandbox-tab.tsxnew file mode 100644index 00000000000..bf531c297b8--- /dev/null+++ b/studio/frontend/src/features/settings/tabs/sandbox-tab.tsx@@ -0,0 +1,652 @@+// 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 { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Spinner } from "@/components/ui/spinner";+import { Switch } from "@/components/ui/switch";+import {+ type SandboxSetupJob,+ type SandboxSetupOperation,+ forgetSandboxCapability,+ loadSandboxSetup,+ startSandboxSetup,+} 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 { toast } from "sonner";+import {+ type HostPrepJob,+ type SandboxSettingsUpdate,+ type SandboxStatus,+ type SandboxToolStatus,+ loadHostPreparation,+ loadSandboxStatus,+ startHostPreparation,+ updateSandboxSettings,+} from "../api/sandbox-isolation";+import { isSettingsRouteAbsent } from "../api/settings-route-absent";+import { SettingsRow } from "../components/settings-row";+import { SettingsSection } from "../components/settings-section";+import {+ HOST_PREP_POLL_MS,+ type HostPrepStatus,+ isOlderJob,+ jobOutputLines,+ jobResult,+ setupRowView,+ shouldPollJob,+ toolRowView,+ toolRowsQuiet,+ windowsView,+} from "./sandbox-tab-state";++const PREP_STATUS_KEYS: Record<HostPrepStatus, TranslationKey | null> = {+ runtimeMissing: null,+ off: null,+ prepared: "settings.sandbox.prepPrepared",+ needsPreparing: "settings.sandbox.prepNeeds",+ needsPreparingAgain: "settings.sandbox.prepNeedsAgain",+ unknown: "settings.sandbox.prepUnknown",+};++const NOTE_CLASS =+ "max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs";++function ToolRow({+ label,+ tool,+ shell,+ quiet = false,+ withRemediation = true,+}: {+ label: string;+ tool: SandboxToolStatus;+ shell?: SandboxStatus["terminalShell"];+ /** The setup row below already says why and what to run; repeating it per tool is noise. */+ quiet?: boolean;+ /** Off on Windows: the generic MXC remediation repeats what the Windows section offers. */+ withRemediation?: boolean;+}) {+ const t = useT();+ const view = toolRowView(tool, shell ?? null);+ const reason = view.reason || t("settings.sandbox.noReason");+ const description = quiet && !view.isolated ? undefined : view.isolated ? (+ view.runsInCmd ? (+ t("settings.sandbox.runsInCmd")+ ) : undefined+ ) : withRemediation && view.remediation ? (+ <>+ <span className="block">{reason}</span>+ <span className="mt-1 block">{view.remediation}</span>+ </>+ ) : (+ reason+ );+ return (+ <SettingsRow label={label} description={description}>+ <Badge variant={view.isolated ? "secondary" : "outline"}>+ {view.isolated+ ? t("settings.sandbox.osIsolation", { backend: view.backendLabel })+ : t("settings.sandbox.softwareSafeguards")}+ </Badge>+ </SettingsRow>+ );+}++export function SandboxTab() {+ const t = useT();+ const [status, setStatus] = useState<SandboxStatus | null>(null);+ const [job, setJob] = useState<HostPrepJob | null>(null);+ const [error, setError] = useState<string | null>(null);+ // Save and prepare failures sit with the Windows controls, e.g. the remote-browser refusal.+ const [actionError, setActionError] = useState<string | null>(null);+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [restored, setRestored] = useState<number | null>(null);+ const [absent, setAbsent] = useState(false);+ // The Linux install and the Windows runtime install; the Windows prepare step keeps `job`.+ const [setupJob, setSetupJob] = useState<SandboxSetupJob | null>(null);+ const [setupError, setSetupError] = useState<string | null>(null);+ const mounted = useRef(true);+ // Bumped by every read and save: an older status read must not overwrite a newer answer.+ const statusGeneration = useRef(0);++ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);++ // Callers set `loading`: a synchronous setState from the mount effect would cascade a render.+ const refresh = useCallback(+ (force: boolean) => {+ const generation = ++statusGeneration.current;+ const current = () =>+ mounted.current && generation === statusGeneration.current;+ return loadSandboxStatus(force, t("settings.sandbox.loadError"))+ .then((loaded) => {+ if (!current()) return;+ setStatus(loaded);+ setError(null);+ })+ .catch((loadError) => {+ if (!current()) return;+ if (isSettingsRouteAbsent(loadError)) {+ setAbsent(true);+ return;+ }+ setError(+ loadError instanceof Error+ ? loadError.message+ : t("settings.sandbox.loadError"),+ );+ })+ .finally(() => {+ if (current()) setLoading(false);+ });+ },+ [t],+ );++ useEffect(() => {+ void refresh(false);+ // A job started from another window, or before this tab was reopened, keeps reporting here.+ void loadHostPreparation(t("settings.sandbox.prepareError"))+ .then((current) => {+ if (!mounted.current || current.state === "idle") return;+ setJob((shown) => (isOlderJob(current, shown) ? shown : current));+ })+ .catch(() => undefined);+ void loadSandboxSetup(t("sandboxSetup.startError"))+ .then((current) => {+ if (!mounted.current || current.state === "idle") return;+ setSetupJob((shown) => (isOlderJob(current, shown) ? shown : current));+ })+ .catch(() => undefined);+ }, [refresh, t]);++ useEffect(() => {+ if (!shouldPollJob(setupJob)) return;+ const timer = window.setTimeout(() => {+ void loadSandboxSetup(t("sandboxSetup.startError"))+ .then((next) => {+ if (!mounted.current) return;+ setSetupJob(next);+ if (!shouldPollJob(next)) {+ forgetSandboxCapability();+ setLoading(true);+ void refresh(true);+ }+ })+ .catch((pollError) => {+ if (!mounted.current) return;+ setSetupError(+ pollError instanceof Error+ ? pollError.message+ : t("sandboxSetup.startError"),+ );+ setSetupJob(null);+ });+ }, HOST_PREP_POLL_MS);+ return () => window.clearTimeout(timer);+ }, [setupJob, refresh, t]);++ // Poll while the elevated helper runs; the status is re-read once it finishes.+ useEffect(() => {+ if (!shouldPollJob(job)) return;+ const timer = window.setTimeout(() => {+ void loadHostPreparation(t("settings.sandbox.prepareError"))+ .then((next) => {+ if (!shouldPollJob(next)) forgetSandboxCapability();+ if (!mounted.current) return;+ setJob(next);+ if (!shouldPollJob(next)) {+ setLoading(true);+ void refresh(true);+ }+ })+ .catch((pollError) => {+ if (!mounted.current) return;+ setActionError(+ pollError instanceof Error+ ? pollError.message+ : t("settings.sandbox.prepareError"),+ );+ setJob(null);+ });+ }, HOST_PREP_POLL_MS);+ return () => window.clearTimeout(timer);+ }, [job, refresh, t]);++ const save = async (update: SandboxSettingsUpdate) => {+ const generation = ++statusGeneration.current;+ setSaving(true);+ setActionError(null);+ setRestored(null);+ try {+ const next = await updateSandboxSettings(+ update,+ t("settings.sandbox.saveError"),+ );+ // The chat picker's cached answer predates this change (the opt-in decides MXC).+ forgetSandboxCapability();+ if (!mounted.current) return;+ if (generation === statusGeneration.current) setStatus(next);+ setLoading(false);+ if (next.restored) setRestored(next.restored);+ } catch (saveError) {+ if (!mounted.current) return;+ setActionError(+ saveError instanceof Error+ ? saveError.message+ : t("settings.sandbox.saveError"),+ );+ } finally {+ if (mounted.current) setSaving(false);+ }+ };++ const prepare = async () => {+ setActionError(null);+ try {+ const started = await startHostPreparation(+ t("settings.sandbox.prepareError"),+ );+ if (!mounted.current) return;+ setJob(started);+ if (!shouldPollJob(started)) {+ setLoading(true);+ void refresh(true);+ }+ } catch (prepareError) {+ if (!mounted.current) return;+ setActionError(+ prepareError instanceof Error+ ? prepareError.message+ : t("settings.sandbox.prepareError"),+ );+ }+ };++ const runSetup = async (+ operation: SandboxSetupOperation,+ consentDaclFallback: boolean,+ ) => {+ setSetupError(null);+ try {+ const started = await startSandboxSetup(+ operation,+ { consentDaclFallback },+ t("sandboxSetup.startError"),+ );+ if (!mounted.current) return;+ setSetupJob(started);+ if (!shouldPollJob(started)) {+ forgetSandboxCapability();+ setLoading(true);+ void refresh(true);+ }+ } catch (startError) {+ if (!mounted.current) return;+ setSetupError(+ startError instanceof Error+ ? startError.message+ : t("sandboxSetup.startError"),+ );+ }+ };++ const copyCommand = async (command: string) => {+ if (await copyToClipboard(command)) {+ toast.success(t("sandboxSetup.copied"));+ } else {+ toast.error(t("sandboxSetup.copyFailed"));+ }+ };++ const windows = status?.windows ?? null;+ const view = windows ? windowsView(windows, job, saving) : null;+ // The runtime-only install reports under its own row; the setup row keeps the other operations.+ const runtimeJob = setupJob?.operation === "windows-runtime" ? setupJob : null;+ const runtimeRunning = runtimeJob?.state === "running";+ const runtimeFailed = jobResult(runtimeJob) === "failed";+ const runtimeOutput = jobOutputLines(runtimeJob);+ const result = jobResult(job);+ const outputLines = jobOutputLines(job);+ const prepKey = view ? PREP_STATUS_KEYS[view.prep] : null;+ const setupRow = status+ ? setupRowView(status, setupJob, setupJob?.manualCommand ?? "")+ : null;+ const quietTools = toolRowsQuiet(setupRow?.show ?? false, view);+ const setupResult = jobResult(setupJob);+ const setupOutput = jobOutputLines(setupJob);+ const setupNote =+ setupResult === "declined" || setupResult === "failed"+ ? (setupJob?.note ?? "")+ : "";+ 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")}+ </p>+ ) : (+ <>+ <SettingsSection title={t("settings.sandbox.toolsSection")}>+ {status ? (+ <>+ <ToolRow+ label={t("settings.sandbox.python")}+ tool={status.python}+ quiet={quietTools}+ withRemediation={!windows}+ />+ <ToolRow+ label={t("settings.sandbox.terminal")}+ tool={status.terminal}+ shell={status.terminalShell}+ quiet={quietTools}+ withRemediation={!windows}+ />+ {setupRow?.show ? (+ <SettingsRow+ label={t("settings.sandbox.setupLabel")}+ description={+ setupRow.builtIn ? (+ <>+ <span className="block">+ {t("settings.sandbox.macosBuiltIn")}+ </span>+ {setupRow.reason ? (+ <span className="mt-1 block">+ {setupRow.reason}+ </span>+ ) : null}+ </>+ ) : (+ setupRow.reason || status.python.reason || undefined+ )+ }+ >+ <div className="flex flex-col items-end gap-1">+ {setupRow.showInstall ? (+ <Button+ size="sm"+ variant="outline"+ disabled={setupRow.installDisabled}+ onClick={() => void runSetup("linux-install", false)}+ >+ {setupRunning ? <Spinner /> : null}+ {t("sandboxSetup.install")}+ </Button>+ ) : null}+ {setupRunning ? (+ <span className={`${NOTE_CLASS} text-muted-foreground`}>+ {t("sandboxSetup.running")}+ </span>+ ) : null}+ {setupResult === "succeeded" ? (+ <span className={`${NOTE_CLASS} text-muted-foreground`}>+ {t("settings.sandbox.setupSucceeded")}+ </span>+ ) : null}+ {setupResult === "declined" ? (+ <span className={`${NOTE_CLASS} text-destructive`}>+ {t("sandboxSetup.declined")}+ </span>+ ) : null}+ {setupResult === "failed" ? (+ <span className={`${NOTE_CLASS} text-destructive`}>+ {t("sandboxSetup.failed")}+ </span>+ ) : null}+ {setupNote ? (+ <span className={`${NOTE_CLASS} text-destructive`}>+ {setupNote}+ </span>+ ) : null}+ {setupOutput.length > 0 ? (+ <pre className="max-w-[calc(360px*var(--ui-space-scale,1))] whitespace-pre-wrap break-words text-right font-mono text-ui-11 text-muted-foreground">+ {setupOutput.join("\n")}+ </pre>+ ) : null}+ {setupRow.command ? (+ <>+ <span+ className={`${NOTE_CLASS} text-muted-foreground`}+ >+ {t("settings.sandbox.setupCommandHint")}+ </span>+ <pre className="max-w-[calc(360px*var(--ui-space-scale,1))] whitespace-pre-wrap break-all rounded-md bg-muted px-2 py-1.5 text-left font-mono text-ui-11">+ {setupRow.command}+ </pre>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => void copyCommand(setupRow.command)}+ >+ {t("sandboxSetup.copyCommand")}+ </Button>+ </>+ ) : null}+ {setupError ? (+ <span className={`${NOTE_CLASS} text-destructive`}>+ {setupError}+ </span>+ ) : null}+ </div>+ </SettingsRow>+ ) : null}+ </>+ ) : null}+ <div className="flex items-center justify-end gap-2 py-2">+ {error ? (+ <span className={`${NOTE_CLASS} text-destructive`}>+ {error}+ </span>+ ) : null}+ <Button+ size="sm"+ variant="outline"+ // A read started mid-save can see the old value and would drop the save's answer.+ disabled={loading || saving}+ onClick={() => {+ setLoading(true);+ void refresh(true);+ }}+ >+ {loading ? (+ <Spinner />+ ) : (+ <HugeiconsIcon strokeWidth={1.75} icon={RefreshIcon} />+ )}+ {t("settings.sandbox.refresh")}+ </Button>+ </div>+ </SettingsSection>++ {windows && view ? (+ <SettingsSection+ title={t("settings.sandbox.windowsSection")}+ description={t("settings.sandbox.windowsDescription")}+ >+ {view.unsupported ? (+ <p className="py-3 text-sm text-muted-foreground">+ {view.unsupported === "arch"+ ? t("settings.sandbox.unsupportedArch")+ : t("settings.sandbox.unsupportedBuild")}+ </p>+ ) : view.runtimeMissing ? (+ <div className="flex flex-col gap-2 py-3">+ <SettingsRow+ label={t("settings.sandbox.runtimeLabel")}+ description={t("settings.sandbox.runtimeMissing")}+ >+ {view.showInstallRuntime || runtimeRunning ? (+ <Button+ size="sm"+ variant="outline"+ disabled={setupRunning}+ onClick={() => void runSetup("windows-runtime", false)}+ >+ {runtimeRunning ? <Spinner /> : null}+ {runtimeRunning+ ? t("settings.sandbox.installingRuntime")+ : t("settings.sandbox.installRuntime")}+ </Button>+ ) : null}+ </SettingsRow>+ {runtimeFailed ? (+ <p className="text-xs text-destructive">+ {runtimeJob?.note ||+ t("settings.sandbox.installRuntimeFailed")}+ </p>+ ) : null}+ {runtimeOutput.length > 0 ? (+ <pre className="whitespace-pre-wrap break-words font-mono text-ui-11 text-muted-foreground">+ {runtimeOutput.join("\n")}+ </pre>+ ) : null}+ {setupError ? (+ <p className="text-xs text-destructive">{setupError}</p>+ ) : null}+ </div>+ ) : (+ <>+ <SettingsRow+ label={t("settings.sandbox.optInLabel")}+ description={t("settings.sandbox.optInDescription")}+ >+ <div className="flex flex-col items-end gap-1">+ <Switch+ aria-label={t("settings.sandbox.optInLabel")}+ checked={view.optInChecked}+ disabled={view.optInDisabled}+ onCheckedChange={(allowDaclFallback) =>+ void save({ allowDaclFallback })+ }+ />+ {view.optInLocked ? (+ <span className={`${NOTE_CLASS} text-muted-foreground`}>+ {t("settings.sandbox.lockedDacl")}+ </span>+ ) : null}+ </div>+ </SettingsRow>+ <p className="pb-2 text-xs text-muted-foreground leading-relaxed">+ {t("settings.sandbox.disclosure")}+ </p>+ {restored ? (+ <p className="pb-2 text-xs text-muted-foreground">+ {t("settings.sandbox.restored", { count: restored })}+ </p>+ ) : null}+ {view.showGrantsRow ? (+ <SettingsRow+ label={t("settings.sandbox.grantsLabel")}+ description={t("settings.sandbox.grantsDescription")}+ >+ <div className="flex flex-col items-end gap-1">+ <Switch+ aria-label={t("settings.sandbox.grantsLabel")}+ checked={view.grantsChecked}+ disabled={view.grantsDisabled}+ onCheckedChange={(persistentReadGrants) =>+ void save({ persistentReadGrants })+ }+ />+ {view.grantsLocked ? (+ <span+ className={`${NOTE_CLASS} text-muted-foreground`}+ >+ {t("settings.sandbox.lockedGrants")}+ </span>+ ) : null}+ </div>+ </SettingsRow>+ ) : null}+ {prepKey ? (+ <SettingsRow+ label={t("settings.sandbox.hostPrepLabel")}+ description={t(prepKey)}+ >+ <div className="flex flex-col items-end gap-1">+ {view.showPrepareButton ? (+ <Button+ size="sm"+ variant="outline"+ disabled={view.prepareDisabled}+ onClick={() => void prepare()}+ >+ {job?.state === "running" ? <Spinner /> : null}+ {t("settings.sandbox.prepareButton")}+ </Button>+ ) : null}+ {job?.state === "running" ? (+ <span+ className={`${NOTE_CLASS} text-muted-foreground`}+ >+ {t("settings.sandbox.preparing")}+ </span>+ ) : null}+ {result === "succeeded" ? (+ <span+ className={`${NOTE_CLASS} text-muted-foreground`}+ >+ {t("settings.sandbox.prepSucceeded")}+ </span>+ ) : null}+ {result === "declined" ? (+ <span className={`${NOTE_CLASS} text-destructive`}>+ {t("settings.sandbox.prepDeclined")}+ </span>+ ) : null}+ {result === "failed" ? (+ <span className={`${NOTE_CLASS} text-destructive`}>+ {t("settings.sandbox.prepFailed")}+ </span>+ ) : null}+ {outputLines.length > 0 ? (+ <pre className="max-w-[calc(360px*var(--ui-space-scale,1))] whitespace-pre-wrap break-words text-right font-mono text-ui-11 text-muted-foreground">+ {outputLines.join("\n")}+ </pre>+ ) : null}+ </div>+ </SettingsRow>+ ) : null}+ {actionError ? (+ <p className="pb-2 text-xs text-destructive">+ {actionError}+ </p>+ ) : null}+ </>+ )}+ </SettingsSection>+ ) : null}+ </>+ )}+ </div>+ );+}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 117c038620a..2d3aed80dd9 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -299,6 +299,32 @@ export const ar = {},// English fallback until this experimental feature is translated.managedEngines: en.managedEngines,+ sandboxSetup: {+ unavailable: "وضع حماية نظام التشغيل غير متاح",+ title: "لا يوجد وضع حماية لنظام التشغيل على هذا الكمبيوتر بعد",+ description: "يُبقي التشغيل تلقائيًا Python والطرفية داخل وضع حماية نظام التشغيل. إلى أن يعمل هنا، تطلب استدعاءاتهما الخطرة الموافقة أولًا.",+ checking: "جارٍ فحص وضع الحماية على هذا الكمبيوتر…",+ install: "تثبيت وضع الحماية",+ windowsSetup: "إعداد وضع حماية Windows",+ copyCommand: "نسخ الأمر",+ copied: "تم نسخ الأمر",+ copyFailed: "تعذّر نسخ الأمر",+ commandHint: "أو شغّل هذا على الكمبيوتر الذي يشغّل Unsloth، ثم اختر الوضع مجددًا:",+ ownerOnly: "لا يمكن تثبيته إلا للمالك، من الكمبيوتر الذي يشغّل Unsloth.",+ runInTerminal: "لا يستطيع Unsloth طلب كلمة المرور هنا. شغّل هذا في طرفية على الكمبيوتر الذي يشغّل Unsloth، ثم اختر الوضع مرة أخرى:",+ useAnyway: "استخدامه على أي حال (ستطلب الاستدعاءات الخطرة الموافقة)",+ cancel: "إلغاء",+ close: "إغلاق",+ running: "جارٍ الإعداد. وافق على طلب كلمة المرور أو المسؤول على الكمبيوتر الذي يشغّل Unsloth…",+ succeeded: "وضع حماية نظام التشغيل جاهز. تم تفعيل التشغيل تلقائيًا.",+ stillUnavailable: "اكتمل الإعداد، لكن وضع حماية نظام التشغيل لا يجتاز الفحص بعد.",+ declined: "تم رفض طلب كلمة المرور أو المسؤول.",+ failed: "فشل الإعداد.",+ startError: "تعذّر بدء إعداد وضع الحماية",+ checkFailed: "تعذّر فحص وضع الحماية على هذا الكمبيوتر.",+ retry: "إعادة المحاولة",+ keepsRunning: "إغلاق هذه النافذة لا يوقف الإعداد. تظهر نتيجته في الإعدادات > وضع الحماية.",+ },composerSettings: {title: "كتابة الرسائل",plainText: "محرر نص عادي",@@ -784,6 +810,7 @@ export const ar = {lastVisited: "آخر ما تمت زيارته",},tabs: {+ sandbox: "وضع الحماية",accounts: "الحسابات",general: "عام",profile: "الملف الشخصي",@@ -1056,6 +1083,55 @@ export const ar = {},},},+ sandbox: {+ title: "وضع الحماية",+ description: "ما إذا كانت استدعاءات أدوات Python والطرفية تعمل داخل وضع حماية نظام التشغيل على هذا الكمبيوتر.",+ toolsSection: "هذا الكمبيوتر",+ refresh: "تحديث",+ python: "Python",+ terminal: "الطرفية",+ osIsolation: "وضع حماية نظام التشغيل ({backend})",+ softwareSafeguards: "ضمانات برمجية",+ noReason: "لا يعمل أي وضع حماية لنظام التشغيل هنا بعد، لذا يفحص Unsloth كل استدعاء بدلًا من ذلك.",+ runsInCmd: "يعمل في cmd.exe، لأن Git Bash لا يمكنه البدء داخل وضع حماية Windows.",+ loadError: "تعذّر تحميل حالة وضع الحماية",+ saveError: "تعذّر حفظ إعداد وضع الحماية",+ prepareError: "تعذّر تجهيز هذا الكمبيوتر",+ unsupported: "لا يُبلغ خادم Unsloth هذا عن حالة وضع الحماية بعد. حدّث Unsloth لإدارتها هنا.",+ windowsSection: "وضع حماية Windows (معاينة)",+ windowsDescription: "وضع حماية MXC من Microsoft، لإصدارات Windows التي لا تتضمن وضع حماية مدمجًا.",+ optInLabel: "تشغيل وضع حماية Windows",+ optInDescription: "بعدها لا يمكن لـ Python والطرفية تغيير الملفات إلا في مجلد المحادثة.",+ disclosure: "يتطلب خطوة مسؤول لمرة واحدة، تجهيز هذا الكمبيوتر، ويجب تكرارها بعد كل إعادة تشغيل. أثناء تشغيل أداة، يمنحها Unsloth وصولًا مؤقتًا إلى المجلدات التي تحتاجها. لا يزال MXC معاينة، وليس حدًا أمنيًا.",+ lockedDacl: "مضبوط بواسطة UNSLOTH_MXC_ALLOW_DACL_FALLBACK",+ grantsLabel: "بدء أسرع للأدوات",+ grantsDescription: "يحتفظ بوصول للقراءة فقط إلى مجلدات بيئة التشغيل الخاصة بـ Unsloth بين الاستدعاءات. عند إيقافه، يبدأ كل استدعاء أبطأ ببضع ثوانٍ.",+ lockedGrants: "مضبوط بواسطة UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ restored: "تمت إزالة الوصول من المجلدات: {count}.",+ hostPrepLabel: "إعداد المسؤول",+ prepPrepared: "تم",+ prepNeeds: "مطلوب",+ prepNeedsAgain: "مطلوب مجددًا بعد آخر إعادة تشغيل",+ prepUnknown: "غير معروف",+ prepareButton: "تجهيز هذا الكمبيوتر",+ preparing: "بانتظار طلب المسؤول…",+ prepSucceeded: "هذا الكمبيوتر مُجهّز.",+ prepDeclined: "تم رفض طلب المسؤول.",+ prepFailed: "فشل التجهيز.",+ setupLabel: "وضع حماية نظام التشغيل",+ setupCommandHint: "شغّل هذا على الكمبيوتر الذي يشغّل Unsloth:",+ macosBuiltIn: "يتضمن macOS وضع حماية مدمجًا، لذا لا يوجد ما يجب تثبيته.",+ setupKeywords: "تثبيت إعداد bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "وضع حماية نظام التشغيل جاهز.",+ runtimeMissing: "غير مثبتة بعد. لا يحتاج تثبيتها إلى موافقة المسؤول.",+ runtimeLabel: "بيئة تشغيل وضع حماية Windows",+ installRuntime: "تثبيت بيئة التشغيل",+ installingRuntime: "جارٍ التثبيت…",+ installRuntimeFailed: "فشل تثبيت بيئة التشغيل.",+ installRuntimeError: "تعذر بدء تثبيت بيئة التشغيل.",+ unsupportedArch: "يعمل وضع حماية Windows (MXC) على Windows x64 فقط، لذا فهو غير متاح على هذا الكمبيوتر.",+ unsupportedBuild: "يتطلب وضع حماية Windows (MXC) إصدار Windows 11 24H2 (البنية 26100) أو أحدث، لذا فهو غير متاح على هذا الكمبيوتر.",+ },debugging: {logSection: "ملف السجل",source: "ملف السجل",@@ -1570,7 +1646,7 @@ export const ar = {auto:"يشغّل استدعاءات الأدوات المعتادة تلقائيًا ولا يطلب الموافقة إلا عندما يبدو الإجراء خطرًا، مثل قراءة بيانات الاعتماد أو رفع الصلاحيات أو تشغيل أوامر مدمّرة.",off:- "يشغّل كل استدعاءات الأدوات دون سؤال. تظل شيفرة Python والطرفية تعمل داخل صندوق العزل، الذي يحدّ من الملفات التي يمكنها الوصول إليها على جهازك.",+ "يشغّل كل استدعاءات الأدوات دون سؤال. تظل شيفرة Python والطرفية تعمل داخل صندوق العزل، الذي يحدّ من الملفات التي يمكنها الوصول إليها على جهازك. إذا لم يكن على هذا الكمبيوتر وضع حماية يعمل لنظام التشغيل، فإن استدعاءات Python والطرفية الخطرة تطلب الموافقة أولًا.",full:"يشغّل كل استدعاءات الأدوات دون سؤال ويوقف صندوق عزل الشيفرة، فيمكن لشيفرة Python والطرفية قراءة أي ملف يصل إليه حسابك وتغييره. الأنسب للمهام الموثوقة التي تحتاج إلى العمل خارج صندوق العزل.",},diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex ca7b5b69548..90108084f44 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -299,6 +299,32 @@ 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.",+ 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:",+ 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",+ 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.",+ 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.",+ startError: "Die Sandbox-Einrichtung konnte nicht gestartet werden",+ checkFailed: "Die Sandbox auf diesem Computer konnte nicht geprüft werden.",+ retry: "Erneut versuchen",+ keepsRunning: "Das Schließen beendet die Einrichtung nicht. Das Ergebnis erscheint unter Einstellungen > Sandbox.",+ },composerSettings: {title: "Nachrichteneingabe",plainText: "Eingabe als Klartext",@@ -788,6 +814,7 @@ export const de = {lastVisited: "Zuletzt besucht",},tabs: {+ sandbox: "Sandbox",accounts: "Konten",general: "Allgemein",profile: "Profil",@@ -1060,6 +1087,55 @@ export const de = {},},},+ sandbox: {+ title: "Sandbox",+ description: "Ob Python- und Terminal-Tool-Aufrufe auf diesem Computer in einer OS-Sandbox laufen.",+ toolsSection: "Dieser Computer",+ refresh: "Aktualisieren",+ python: "Python",+ terminal: "Terminal",+ osIsolation: "OS-Sandbox ({backend})",+ softwareSafeguards: "Software-Schutzmaßnahmen",+ noReason: "Hier funktioniert noch keine OS-Sandbox, daher prüft Unsloth stattdessen jeden Aufruf.",+ runsInCmd: "Läuft in cmd.exe, da Git Bash in der Windows-Sandbox nicht starten kann.",+ loadError: "Sandbox-Status konnte nicht geladen werden",+ saveError: "Sandbox-Einstellung konnte nicht gespeichert werden",+ prepareError: "Dieser PC konnte nicht vorbereitet werden",+ unsupported: "Dieser Unsloth-Server meldet noch keinen Sandbox-Status. Aktualisiere Unsloth, um ihn hier zu verwalten.",+ windowsSection: "Windows-Sandbox (Vorschau)",+ windowsDescription: "Die MXC-Sandbox von Microsoft, für Windows-Versionen ohne eingebaute Sandbox.",+ optInLabel: "Windows-Sandbox aktivieren",+ optInDescription: "Python und Terminal können dann nur Dateien im Ordner des Chats ändern.",+ disclosure: "Erfordert einen einmaligen Administratorschritt, Diesen PC vorbereiten, der nach jedem Neustart wiederholt werden muss. Während ein Tool läuft, gibt Unsloth ihm vorübergehend Zugriff auf die benötigten Ordner. MXC ist noch eine Vorschau, keine Sicherheitsgrenze.",+ lockedDacl: "Festgelegt durch UNSLOTH_MXC_ALLOW_DACL_FALLBACK",+ grantsLabel: "Schnellerer Tool-Start",+ grantsDescription: "Behält zwischen Aufrufen den Nur-Lese-Zugriff auf die eigenen Laufzeitordner von Unsloth. Wenn aus, startet jeder Aufruf einige Sekunden langsamer.",+ lockedGrants: "Festgelegt durch UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ restored: "Zugriff auf {count} Ordner entfernt.",+ hostPrepLabel: "Administrator-Einrichtung",+ prepPrepared: "Erledigt",+ prepNeeds: "Erforderlich",+ prepNeedsAgain: "Nach dem letzten Neustart erneut erforderlich",+ prepUnknown: "Unbekannt",+ prepareButton: "Diesen PC vorbereiten",+ preparing: "Warte auf die Administratorabfrage…",+ prepSucceeded: "Dieser PC ist vorbereitet.",+ prepDeclined: "Die Administratorabfrage wurde abgelehnt.",+ prepFailed: "Vorbereitung fehlgeschlagen.",+ setupLabel: "OS-Sandbox",+ setupCommandHint: "Führe dies auf dem Computer aus, auf dem Unsloth läuft:",+ macosBuiltIn: "macOS hat eine eingebaute Sandbox, daher muss nichts installiert werden.",+ setupKeywords: "installieren einrichten bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "Die OS-Sandbox ist bereit.",+ runtimeMissing: "Noch nicht installiert. Die Installation braucht keine Administratorfreigabe.",+ runtimeLabel: "Laufzeit der Windows-Sandbox",+ installRuntime: "Laufzeit installieren",+ installingRuntime: "Wird installiert…",+ installRuntimeFailed: "Die Installation der Laufzeit ist fehlgeschlagen.",+ 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.",+ },debugging: {logSection: "Protokolldatei",source: "Protokolldatei",@@ -1596,7 +1672,7 @@ export const de = {auto:"Führt gewöhnliche Tool-Aufrufe selbst aus und fragt nur nach, wenn eine Aktion riskant wirkt, etwa beim Lesen von Zugangsdaten, beim Erhöhen von Rechten oder bei zerstörerischen Befehlen.",off:- "Führt jeden Tool-Aufruf ohne Nachfrage aus. Python- und Terminal-Code läuft weiterhin in der Sandbox, die begrenzt, auf welche Dateien deines Computers er zugreifen kann.",+ "Führt jeden Tool-Aufruf ohne Nachfrage aus. Python- und Terminal-Code läuft weiterhin in der Sandbox, die begrenzt, auf welche Dateien deines Computers er zugreifen kann. Hat dieser Computer keine funktionierende OS-Sandbox, fragen riskante Python- und Terminal-Aufrufe zuerst nach.",full:"Führt jeden Tool-Aufruf ohne Nachfrage aus und schaltet die Code-Sandbox ab, sodass Python- und Terminal-Code jede Datei lesen und ändern kann, auf die dein Konto zugreifen kann. Ideal für vertrauenswürdige Aufgaben, die außerhalb der Sandbox arbeiten müssen.",},diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 4adf2a007c3..238d7d203be 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -335,6 +335,32 @@ export const en = {cancelled: "Installation cancelled. You can retry.",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.",+ 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:",+ 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",+ running: "Setting up. Approve the password or administrator prompt on the computer running Unsloth…",+ succeeded: "The OS sandbox is ready. Run automatically 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.",+ startError: "Failed to start the sandbox setup",+ checkFailed: "Could not check the sandbox on this computer.",+ retry: "Retry",+ keepsRunning: "Closing this does not stop the setup. Its result shows in Settings > Sandbox.",+ },composerSettings: {title: "Composer",plainText: "Plain text composer",@@ -830,6 +856,7 @@ export const en = {lastVisited: "Last visited",},tabs: {+ sandbox: "Sandbox",accounts: "Accounts",general: "General",profile: "Profile",@@ -1102,6 +1129,55 @@ export const en = {},},},+ sandbox: {+ title: "Sandbox",+ description: "Whether Python and Terminal tool calls run inside an OS sandbox on this computer.",+ toolsSection: "This computer",+ refresh: "Refresh",+ python: "Python",+ terminal: "Terminal",+ osIsolation: "OS sandbox ({backend})",+ softwareSafeguards: "Software safeguards",+ noReason: "No OS sandbox works here yet, so Unsloth checks each call instead.",+ runsInCmd: "Runs in cmd.exe, since Git Bash cannot start in the Windows sandbox.",+ loadError: "Failed to load the sandbox status",+ saveError: "Failed to save the sandbox setting",+ prepareError: "Failed to prepare this PC",+ unsupported: "This Unsloth server does not report sandbox status yet. Update Unsloth to manage it here.",+ windowsSection: "Windows sandbox (preview)",+ windowsDescription: "Microsoft's MXC sandbox, for Windows versions without a built-in one.",+ optInLabel: "Turn on the Windows sandbox",+ optInDescription: "Python and Terminal can then only change files in the chat's folder.",+ disclosure: "Needs a one-time administrator step, Prepare this PC, which has to be repeated after each restart. While a tool runs, Unsloth gives it temporary access to the folders it needs. MXC is still a preview, not a security boundary.",+ lockedDacl: "Set by UNSLOTH_MXC_ALLOW_DACL_FALLBACK",+ grantsLabel: "Faster tool starts",+ grantsDescription: "Keeps read-only access to Unsloth's own runtime folders between calls. When off, each call starts a few seconds slower.",+ lockedGrants: "Set by UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ restored: "Removed access from {count} folders.",+ hostPrepLabel: "Administrator setup",+ prepPrepared: "Done",+ prepNeeds: "Needed",+ prepNeedsAgain: "Needed again after the last restart",+ prepUnknown: "Unknown",+ prepareButton: "Prepare this PC",+ preparing: "Waiting for the administrator prompt…",+ prepSucceeded: "This PC is prepared.",+ prepDeclined: "The administrator prompt was declined.",+ prepFailed: "Preparation failed.",+ setupLabel: "OS sandbox",+ setupCommandHint: "Run this on the computer running Unsloth:",+ macosBuiltIn: "macOS has a built-in sandbox, so there is nothing to install.",+ setupKeywords: "install setup bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "The OS sandbox is ready.",+ runtimeMissing: "Not installed yet. Installing it needs no administrator prompt.",+ runtimeLabel: "Windows sandbox runtime",+ installRuntime: "Install runtime",+ installingRuntime: "Installing…",+ installRuntimeFailed: "The runtime install failed.",+ 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.",+ },debugging: {logSection: "Log file",source: "Log file",@@ -1478,7 +1554,7 @@ export const en = {auto:"Runs routine tool calls on its own and only asks when an action looks risky, such as reading credentials, escalating privileges or running destructive commands.",off:- "Runs every tool call without asking. Python and terminal code still run in the sandbox, which limits which files they can reach on your computer.",+ "Runs every tool call without asking. Python and terminal code still run in the sandbox, which limits which files they can reach on your computer. If this computer has no working OS sandbox, risky Python and terminal calls ask first.",full:"Runs every tool call without asking and turns off the code sandbox, so Python and terminal code can read and change any file your account can access. Best for trusted tasks that need to work outside the sandbox.",},diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 68e2d1df349..38be637ece2 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -299,6 +299,32 @@ 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.",+ 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:",+ 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",+ 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.",+ 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ó.",+ startError: "No se pudo iniciar la configuración del sandbox",+ checkFailed: "No se pudo comprobar el sandbox en este equipo.",+ retry: "Reintentar",+ keepsRunning: "Cerrar esto no detiene la configuración. El resultado aparece en Ajustes > Sandbox.",+ },composerSettings: {title: "Redacción de mensajes",plainText: "Redactor de texto sin formato",@@ -787,6 +813,7 @@ export const es = {lastVisited: "Última visitada",},tabs: {+ sandbox: "Sandbox",accounts: "Cuentas",general: "General",profile: "Perfil",@@ -1059,6 +1086,55 @@ export const es = {},},},+ sandbox: {+ title: "Sandbox",+ description: "Si las llamadas a herramientas de Python y Terminal se ejecutan dentro de un sandbox del sistema en este equipo.",+ toolsSection: "Este equipo",+ refresh: "Actualizar",+ python: "Python",+ terminal: "Terminal",+ osIsolation: "Sandbox del sistema ({backend})",+ softwareSafeguards: "Protecciones por software",+ noReason: "Aquí todavía no funciona ningún sandbox del sistema, así que Unsloth revisa cada llamada.",+ runsInCmd: "Se ejecuta en cmd.exe, porque Git Bash no puede iniciarse en el sandbox de Windows.",+ loadError: "No se pudo cargar el estado de la sandbox",+ saveError: "No se pudo guardar el ajuste de la sandbox",+ prepareError: "No se pudo preparar este PC",+ unsupported: "Este servidor de Unsloth aún no informa del estado de la sandbox. Actualiza Unsloth para gestionarlo aquí.",+ windowsSection: "Sandbox de Windows (versión preliminar)",+ windowsDescription: "El sandbox MXC de Microsoft, para versiones de Windows sin uno integrado.",+ optInLabel: "Activar el sandbox de Windows",+ optInDescription: "Así, Python y Terminal solo pueden modificar archivos en la carpeta del chat.",+ disclosure: "Requiere un paso único de administrador, Preparar este PC, que hay que repetir después de cada reinicio. Mientras se ejecuta una herramienta, Unsloth le da acceso temporal a las carpetas que necesita. MXC todavía es una versión preliminar, no una barrera de seguridad.",+ lockedDacl: "Definido por UNSLOTH_MXC_ALLOW_DACL_FALLBACK",+ grantsLabel: "Inicio más rápido de herramientas",+ grantsDescription: "Mantiene el acceso de solo lectura a las carpetas de runtime propias de Unsloth entre llamadas. Si está desactivado, cada llamada tarda unos segundos más en iniciarse.",+ lockedGrants: "Definido por UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ restored: "Se quitó el acceso a {count} carpetas.",+ hostPrepLabel: "Configuración de administrador",+ prepPrepared: "Listo",+ prepNeeds: "Necesario",+ prepNeedsAgain: "Necesario de nuevo tras el último reinicio",+ prepUnknown: "Desconocido",+ prepareButton: "Preparar este PC",+ preparing: "Esperando la solicitud de administrador…",+ prepSucceeded: "Este PC está preparado.",+ prepDeclined: "Se rechazó la solicitud de administrador.",+ prepFailed: "La preparación falló.",+ setupLabel: "Sandbox del sistema",+ setupCommandHint: "Ejecuta esto en el equipo donde se ejecuta Unsloth:",+ macosBuiltIn: "macOS tiene un sandbox integrado, así que no hay nada que instalar.",+ setupKeywords: "instalar configurar bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "El sandbox del sistema está listo.",+ runtimeMissing: "Aún no está instalado. Instalarlo no requiere permiso de administrador.",+ runtimeLabel: "Runtime del sandbox de Windows",+ installRuntime: "Instalar runtime",+ installingRuntime: "Instalando…",+ installRuntimeFailed: "No se pudo instalar el runtime.",+ 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.",+ },debugging: {logSection: "Archivo de registro",source: "Archivo de registro",@@ -1591,7 +1667,7 @@ export const es = {auto:"Ejecuta por sí solo las llamadas habituales y solo pregunta cuando una acción parece arriesgada, como leer credenciales, elevar privilegios o ejecutar comandos destructivos.",off:- "Ejecuta todas las llamadas a herramientas sin preguntar. El código de Python y terminal sigue ejecutándose en el sandbox, que limita a qué archivos de tu equipo puede acceder.",+ "Ejecuta todas las llamadas a herramientas sin preguntar. El código de Python y terminal sigue ejecutándose en el sandbox, que limita a qué archivos de tu equipo puede acceder. Si este equipo no tiene un sandbox del sistema que funcione, las llamadas arriesgadas de Python y terminal preguntan primero.",full:"Ejecuta todas las llamadas a herramientas sin preguntar y desactiva el sandbox de código, así el código de Python y terminal puede leer y cambiar cualquier archivo al que tenga acceso tu cuenta. Ideal para tareas de confianza que necesitan trabajar fuera del sandbox.",},diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 0fda112f20d..7b137006fbf 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -299,6 +299,32 @@ 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.",+ 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 :",+ 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",+ 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é.",+ 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é.",+ startError: "Impossible de lancer la configuration du bac à sable",+ checkFailed: "Impossible de vérifier le bac à sable sur cet ordinateur.",+ retry: "Réessayer",+ keepsRunning: "Fermer cette fenêtre n'arrête pas la configuration. Le résultat s'affiche dans Paramètres > Sandbox.",+ },composerSettings: {title: "Saisie des messages",plainText: "Saisie en texte brut",@@ -788,6 +814,7 @@ export const fr = {lastVisited: "Dernier visité",},tabs: {+ sandbox: "Sandbox",accounts: "Comptes",general: "Général",profile: "Profil",@@ -1060,6 +1087,55 @@ export const fr = {},},},+ sandbox: {+ title: "Sandbox",+ description: "Indique si les appels d'outils Python et Terminal s'exécutent dans un bac à sable du système sur cet ordinateur.",+ toolsSection: "Cet ordinateur",+ refresh: "Actualiser",+ python: "Python",+ terminal: "Terminal",+ osIsolation: "Bac à sable du système ({backend})",+ softwareSafeguards: "Protections logicielles",+ noReason: "Aucun bac à sable du système ne fonctionne encore ici, donc Unsloth vérifie chaque appel à la place.",+ runsInCmd: "S'exécute dans cmd.exe, car Git Bash ne peut pas démarrer dans le bac à sable Windows.",+ loadError: "Impossible de charger l'état de la sandbox",+ saveError: "Impossible d'enregistrer le réglage de la sandbox",+ prepareError: "Impossible de préparer ce PC",+ unsupported: "Ce serveur Unsloth n'indique pas encore l'état de la sandbox. Mettez Unsloth à jour pour le gérer ici.",+ windowsSection: "Bac à sable Windows (aperçu)",+ windowsDescription: "Le bac à sable MXC de Microsoft, pour les versions de Windows qui n'en intègrent pas.",+ optInLabel: "Activer le bac à sable Windows",+ optInDescription: "Python et Terminal ne peuvent alors modifier que les fichiers du dossier de la conversation.",+ disclosure: "Nécessite une étape administrateur ponctuelle, Préparer ce PC, à répéter après chaque redémarrage. Pendant l'exécution d'un outil, Unsloth lui donne un accès temporaire aux dossiers dont il a besoin. MXC est encore un aperçu, pas une frontière de sécurité.",+ lockedDacl: "Défini par UNSLOTH_MXC_ALLOW_DACL_FALLBACK",+ grantsLabel: "Démarrage plus rapide des outils",+ grantsDescription: "Conserve l'accès en lecture seule aux dossiers d'exécution propres à Unsloth entre les appels. Désactivé, chaque appel démarre quelques secondes plus lentement.",+ lockedGrants: "Défini par UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ restored: "Accès retiré pour {count} dossiers.",+ hostPrepLabel: "Configuration administrateur",+ prepPrepared: "Terminé",+ prepNeeds: "Requis",+ prepNeedsAgain: "De nouveau requis après le dernier redémarrage",+ prepUnknown: "Inconnu",+ prepareButton: "Préparer ce PC",+ preparing: "En attente de la demande administrateur…",+ prepSucceeded: "Ce PC est préparé.",+ prepDeclined: "La demande administrateur a été refusée.",+ prepFailed: "La préparation a échoué.",+ setupLabel: "Bac à sable du système",+ setupCommandHint: "Exécutez ceci sur l'ordinateur qui fait tourner Unsloth :",+ macosBuiltIn: "macOS dispose d'un bac à sable intégré, il n'y a donc rien à installer.",+ setupKeywords: "installer configurer bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "Le bac à sable du système est prêt.",+ runtimeMissing: "Pas encore installé. L'installation ne demande pas de droits administrateur.",+ runtimeLabel: "Runtime du bac à sable Windows",+ installRuntime: "Installer le runtime",+ installingRuntime: "Installation…",+ installRuntimeFailed: "L'installation du runtime a échoué.",+ 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.",+ },debugging: {logSection: "Fichier journal",source: "Fichier journal",@@ -1594,7 +1670,7 @@ export const fr = {auto:"Exécute seul les appels d'outils courants et ne demande votre accord que lorsqu'une action semble risquée, comme lire des identifiants, élever des privilèges ou lancer des commandes destructrices.",off:- "Exécute chaque appel d'outil sans demander. Le code Python et terminal reste exécuté dans le bac à sable, qui limite les fichiers auxquels il peut accéder sur votre ordinateur.",+ "Exécute chaque appel d'outil sans demander. Le code Python et terminal reste exécuté dans le bac à sable, qui limite les fichiers auxquels il peut accéder sur votre ordinateur. Si cet ordinateur n'a pas de bac à sable système fonctionnel, les appels Python et terminal risqués demandent d'abord.",full:"Exécute chaque appel d'outil sans demander et désactive le bac à sable du code : le code Python et terminal peut lire et modifier tout fichier accessible à votre compte. Idéal pour les tâches de confiance qui doivent travailler hors du bac à sable.",},diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex c181925a3ce..b665abc925a 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -299,6 +299,32 @@ export const hi = {},// English fallback until this experimental feature is translated.managedEngines: en.managedEngines,+ sandboxSetup: {+ unavailable: "OS सैंडबॉक्स उपलब्ध नहीं है",+ title: "इस कंप्यूटर पर अभी कोई OS सैंडबॉक्स नहीं है",+ description: "अपने आप चलाएं Python और टर्मिनल को OS सैंडबॉक्स में रखता है। जब तक यह यहाँ काम नहीं करता, उनकी जोखिम भरी कॉल पहले पूछती हैं।",+ checking: "इस कंप्यूटर का सैंडबॉक्स जाँचा जा रहा है…",+ install: "सैंडबॉक्स इंस्टॉल करें",+ windowsSetup: "Windows सैंडबॉक्स सेट अप करें",+ copyCommand: "कमांड कॉपी करें",+ copied: "कमांड कॉपी हो गया",+ copyFailed: "कमांड कॉपी नहीं हो सका",+ commandHint: "या Unsloth चला रहे कंप्यूटर पर यह चलाएँ, फिर मोड दोबारा चुनें:",+ ownerOnly: "इसे सिर्फ़ मालिक ही Unsloth चला रहे कंप्यूटर से इंस्टॉल कर सकता है।",+ runInTerminal: "Unsloth यहाँ आपका पासवर्ड नहीं माँग सकता। Unsloth चला रहे कंप्यूटर के टर्मिनल में इसे चलाएँ, फिर मोड दोबारा चुनें:",+ useAnyway: "फिर भी इस्तेमाल करें (जोखिम भरी कॉल के लिए पूछा जाएगा)",+ cancel: "रद्द करें",+ close: "बंद करें",+ running: "सेट अप हो रहा है। Unsloth चला रहे कंप्यूटर पर पासवर्ड या एडमिनिस्ट्रेटर संकेत को मंज़ूरी दें…",+ succeeded: "OS सैंडबॉक्स तैयार है। अपने आप चलाएं चालू है।",+ stillUnavailable: "सेटअप पूरा हो गया, लेकिन OS सैंडबॉक्स अभी भी अपनी जाँच में पास नहीं हुआ।",+ declined: "पासवर्ड या एडमिनिस्ट्रेटर संकेत अस्वीकार कर दिया गया।",+ failed: "सेटअप विफल रहा।",+ startError: "सैंडबॉक्स सेटअप शुरू नहीं हो सका",+ checkFailed: "इस कंप्यूटर पर सैंडबॉक्स की जांच नहीं हो सकी।",+ retry: "फिर से कोशिश करें",+ keepsRunning: "इसे बंद करने से सेटअप नहीं रुकता। इसका परिणाम सेटिंग्स > सैंडबॉक्स में दिखता है।",+ },composerSettings: {title: "संदेश लिखना",plainText: "सादा टेक्स्ट इनपुट",@@ -787,6 +813,7 @@ export const hi = {lastVisited: "पिछली बार देखा गया",},tabs: {+ sandbox: "सैंडबॉक्स",accounts: "खाते",general: "सामान्य",profile: "प्रोफ़ाइल",@@ -1059,6 +1086,55 @@ export const hi = {},},},+ sandbox: {+ title: "सैंडबॉक्स",+ description: "क्या इस कंप्यूटर पर Python और टर्मिनल टूल कॉल OS सैंडबॉक्स के अंदर चलती हैं।",+ toolsSection: "यह कंप्यूटर",+ refresh: "रीफ़्रेश करें",+ python: "Python",+ terminal: "टर्मिनल",+ osIsolation: "OS सैंडबॉक्स ({backend})",+ softwareSafeguards: "सॉफ़्टवेयर सुरक्षा उपाय",+ noReason: "यहाँ अभी कोई OS सैंडबॉक्स काम नहीं करता, इसलिए Unsloth इसके बजाय हर कॉल की जाँच करता है।",+ runsInCmd: "cmd.exe में चलता है, क्योंकि Git Bash Windows सैंडबॉक्स में शुरू नहीं हो सकता।",+ loadError: "सैंडबॉक्स की स्थिति लोड नहीं हो सकी",+ saveError: "सैंडबॉक्स सेटिंग सहेजी नहीं जा सकी",+ prepareError: "यह PC तैयार नहीं किया जा सका",+ unsupported: "यह Unsloth सर्वर अभी सैंडबॉक्स की स्थिति नहीं बताता। इसे यहाँ प्रबंधित करने के लिए Unsloth अपडेट करें।",+ windowsSection: "Windows सैंडबॉक्स (पूर्वावलोकन)",+ windowsDescription: "Microsoft का MXC सैंडबॉक्स, उन Windows संस्करणों के लिए जिनमें अपना सैंडबॉक्स नहीं है।",+ optInLabel: "Windows सैंडबॉक्स चालू करें",+ optInDescription: "तब Python और टर्मिनल केवल चैट के फ़ोल्डर में फ़ाइलें बदल सकते हैं।",+ disclosure: "एक बार का व्यवस्थापक चरण, यह PC तैयार करें, ज़रूरी है, जिसे हर रीस्टार्ट के बाद दोहराना पड़ता है। जब कोई टूल चलता है, तो Unsloth उसे ज़रूरी फ़ोल्डरों तक अस्थायी पहुँच देता है। MXC अभी पूर्वावलोकन है, सुरक्षा सीमा नहीं।",+ lockedDacl: "UNSLOTH_MXC_ALLOW_DACL_FALLBACK द्वारा सेट",+ grantsLabel: "टूल तेज़ी से शुरू करें",+ grantsDescription: "कॉल के बीच Unsloth के अपने रनटाइम फ़ोल्डरों पर केवल-पढ़ने की पहुँच बनाए रखता है। बंद होने पर हर कॉल कुछ सेकंड धीमी शुरू होती है।",+ lockedGrants: "UNSLOTH_MXC_PERSISTENT_READ_GRANTS द्वारा सेट",+ restored: "{count} फ़ोल्डरों से पहुँच हटाई गई।",+ hostPrepLabel: "व्यवस्थापक सेटअप",+ prepPrepared: "पूरा हुआ",+ prepNeeds: "ज़रूरी",+ prepNeedsAgain: "पिछले रीस्टार्ट के बाद फिर से ज़रूरी",+ prepUnknown: "अज्ञात",+ prepareButton: "यह PC तैयार करें",+ preparing: "व्यवस्थापक संकेत की प्रतीक्षा की जा रही है…",+ prepSucceeded: "यह PC तैयार है।",+ prepDeclined: "व्यवस्थापक संकेत अस्वीकार कर दिया गया।",+ prepFailed: "तैयारी विफल रही।",+ setupLabel: "OS सैंडबॉक्स",+ setupCommandHint: "Unsloth चला रहे कंप्यूटर पर यह चलाएँ:",+ macosBuiltIn: "macOS में सैंडबॉक्स पहले से मौजूद है, इसलिए कुछ भी इंस्टॉल करने की ज़रूरत नहीं है।",+ setupKeywords: "इंस्टॉल सेटअप bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "OS सैंडबॉक्स तैयार है।",+ runtimeMissing: "अभी इंस्टॉल नहीं है। इसे इंस्टॉल करने के लिए एडमिनिस्ट्रेटर अनुमति नहीं चाहिए।",+ runtimeLabel: "Windows सैंडबॉक्स रनटाइम",+ installRuntime: "रनटाइम इंस्टॉल करें",+ installingRuntime: "इंस्टॉल हो रहा है…",+ installRuntimeFailed: "रनटाइम इंस्टॉल नहीं हो सका।",+ installRuntimeError: "रनटाइम इंस्टॉल शुरू नहीं हो सका।",+ unsupportedArch: "Windows सैंडबॉक्स (MXC) केवल x64 Windows पर चलता है, इसलिए यह इस PC पर उपलब्ध नहीं है।",+ unsupportedBuild: "Windows सैंडबॉक्स (MXC) के लिए Windows 11 24H2 (बिल्ड 26100) या नया चाहिए, इसलिए यह इस PC पर उपलब्ध नहीं है।",+ },debugging: {logSection: "लॉग फ़ाइल",source: "लॉग फ़ाइल",@@ -1573,7 +1649,7 @@ export const hi = {auto:"सामान्य टूल कॉल अपने आप चलाता है और सिर्फ़ तब पूछता है जब कोई काम जोखिम भरा लगे, जैसे क्रेडेंशियल पढ़ना, अधिकार बढ़ाना या विनाशकारी कमांड चलाना।",off:- "हर टूल कॉल बिना पूछे चलाता है। Python और टर्मिनल कोड फिर भी सैंडबॉक्स में चलता है, जो सीमित करता है कि वह आपके कंप्यूटर की किन फ़ाइलों तक पहुंच सकता है।",+ "हर टूल कॉल बिना पूछे चलाता है। Python और टर्मिनल कोड फिर भी सैंडबॉक्स में चलता है, जो सीमित करता है कि वह आपके कंप्यूटर की किन फ़ाइलों तक पहुंच सकता है। अगर इस कंप्यूटर पर कोई काम करने वाला OS सैंडबॉक्स नहीं है, तो जोखिम भरी Python और टर्मिनल कॉल पहले पूछती हैं।",full:"हर टूल कॉल बिना पूछे चलाता है और कोड सैंडबॉक्स बंद कर देता है, ताकि Python और टर्मिनल कोड आपके खाते की पहुंच वाली कोई भी फ़ाइल पढ़ और बदल सके। उन भरोसेमंद कामों के लिए सबसे अच्छा, जिन्हें सैंडबॉक्स के बाहर काम करना हो।",},diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex d58ecb53988..bf1d4b50163 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -298,6 +298,32 @@ 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.",+ 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à:",+ 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",+ 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.",+ 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.",+ startError: "Impossibile avviare la configurazione della sandbox",+ checkFailed: "Impossibile verificare la sandbox su questo computer.",+ retry: "Riprova",+ keepsRunning: "Chiudere non interrompe la configurazione. Il risultato compare in Impostazioni > Sandbox.",+ },composerSettings: {title: "Composizione dei messaggi",plainText: "Composizione in testo semplice",@@ -744,6 +770,7 @@ export const it = {lastVisited: "Ultima visitata",},tabs: {+ sandbox: "Sandbox",accounts: "Account",general: "Generali",profile: "Profilo",@@ -1016,6 +1043,55 @@ export const it = {},},},+ sandbox: {+ title: "Sandbox",+ description: "Indica se le chiamate agli strumenti Python e Terminale vengono eseguite in una sandbox del sistema su questo computer.",+ toolsSection: "Questo computer",+ refresh: "Aggiorna",+ python: "Python",+ terminal: "Terminale",+ osIsolation: "Sandbox del sistema ({backend})",+ softwareSafeguards: "Protezioni software",+ noReason: "Qui non funziona ancora nessuna sandbox del sistema, quindi Unsloth controlla ogni chiamata.",+ runsInCmd: "Viene eseguito in cmd.exe, perché Git Bash non può avviarsi nella sandbox di Windows.",+ loadError: "Impossibile caricare lo stato della sandbox",+ saveError: "Impossibile salvare l'impostazione della sandbox",+ prepareError: "Impossibile preparare questo PC",+ unsupported: "Questo server Unsloth non segnala ancora lo stato della sandbox. Aggiorna Unsloth per gestirlo qui.",+ windowsSection: "Sandbox di Windows (anteprima)",+ windowsDescription: "La sandbox MXC di Microsoft, per le versioni di Windows che non ne hanno una integrata.",+ optInLabel: "Attiva la sandbox di Windows",+ optInDescription: "Python e Terminale potranno modificare solo i file nella cartella della chat.",+ disclosure: "Richiede un passaggio di amministratore una tantum, Prepara questo PC, da ripetere dopo ogni riavvio. Mentre uno strumento è in esecuzione, Unsloth gli dà accesso temporaneo alle cartelle di cui ha bisogno. MXC è ancora un'anteprima, non un confine di sicurezza.",+ lockedDacl: "Impostato da UNSLOTH_MXC_ALLOW_DACL_FALLBACK",+ grantsLabel: "Avvio più rapido degli strumenti",+ grantsDescription: "Mantiene l'accesso in sola lettura alle cartelle di runtime di Unsloth tra una chiamata e l'altra. Se disattivato, ogni chiamata si avvia qualche secondo più lentamente.",+ lockedGrants: "Impostato da UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ restored: "Accesso rimosso da {count} cartelle.",+ hostPrepLabel: "Configurazione amministratore",+ prepPrepared: "Fatto",+ prepNeeds: "Necessaria",+ prepNeedsAgain: "Necessaria di nuovo dopo l'ultimo riavvio",+ prepUnknown: "Sconosciuto",+ prepareButton: "Prepara questo PC",+ preparing: "In attesa della richiesta di amministratore…",+ prepSucceeded: "Questo PC è preparato.",+ prepDeclined: "La richiesta di amministratore è stata rifiutata.",+ prepFailed: "Preparazione non riuscita.",+ setupLabel: "Sandbox del sistema",+ setupCommandHint: "Esegui questo sul computer su cui gira Unsloth:",+ macosBuiltIn: "macOS ha una sandbox integrata, quindi non c'è nulla da installare.",+ setupKeywords: "installa configura bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "La sandbox del sistema è pronta.",+ runtimeMissing: "Non ancora installato. L'installazione non richiede l'amministratore.",+ runtimeLabel: "Runtime della sandbox di Windows",+ installRuntime: "Installa runtime",+ installingRuntime: "Installazione…",+ installRuntimeFailed: "Installazione del runtime non riuscita.",+ 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.",+ },debugging: {logSection: "File di log",source: "File di log",@@ -1416,7 +1492,7 @@ export const it = {auto:"Esegue da solo le chiamate abituali e chiede conferma solo quando un'azione sembra rischiosa, come leggere credenziali, aumentare i privilegi o eseguire comandi distruttivi.",off:- "Esegue ogni chiamata agli strumenti senza chiedere. Il codice Python e da terminale viene comunque eseguito nella sandbox, che limita i file del tuo computer a cui può accedere.",+ "Esegue ogni chiamata agli strumenti senza chiedere. Il codice Python e da terminale viene comunque eseguito nella sandbox, che limita i file del tuo computer a cui può accedere. Se questo computer non ha una sandbox del sistema funzionante, le chiamate rischiose di Python e terminale chiedono prima.",full:"Esegue ogni chiamata agli strumenti senza chiedere e disattiva la sandbox del codice, così il codice Python e da terminale può leggere e modificare qualsiasi file accessibile al tuo account. Ideale per attività affidabili che devono lavorare fuori dalla sandbox.",},diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex ffe2bb74665..2b10cb9d0fc 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -300,6 +300,32 @@ export const ja = {},// English fallback until this experimental feature is translated.managedEngines: en.managedEngines,+ sandboxSetup: {+ unavailable: "OS サンドボックスは利用できません",+ title: "このコンピューターにはまだ OS サンドボックスがありません",+ description: "自動で実行は Python とターミナルを OS サンドボックス内で動かします。ここで動作するまでは、危険な呼び出しは先に確認します。",+ checking: "このコンピューターのサンドボックスを確認しています…",+ install: "サンドボックスをインストール",+ windowsSetup: "Windows サンドボックスを設定",+ copyCommand: "コマンドをコピー",+ copied: "コマンドをコピーしました",+ copyFailed: "コマンドをコピーできませんでした",+ commandHint: "または、Unsloth を実行しているコンピューターでこれを実行してから、もう一度モードを選んでください:",+ ownerOnly: "インストールできるのは、Unsloth を実行しているコンピューター上の所有者だけです。",+ runInTerminal: "Unsloth はここでパスワードを尋ねられません。Unsloth を実行しているコンピューターのターミナルでこれを実行してから、もう一度モードを選んでください:",+ useAnyway: "このまま使う (危険な呼び出しは確認します)",+ cancel: "キャンセル",+ close: "閉じる",+ running: "設定中です。Unsloth を実行しているコンピューターでパスワードまたは管理者の確認を承認してください…",+ succeeded: "OS サンドボックスの準備ができました。自動で実行が有効です。",+ stillUnavailable: "設定は完了しましたが、OS サンドボックスはまだチェックに合格していません。",+ declined: "パスワードまたは管理者の確認が拒否されました。",+ failed: "設定に失敗しました。",+ startError: "サンドボックスの設定を開始できませんでした",+ checkFailed: "このコンピューターのサンドボックスを確認できませんでした。",+ retry: "再試行",+ keepsRunning: "閉じても設定は止まりません。結果は 設定 > サンドボックス に表示されます。",+ },composerSettings: {title: "入力欄",plainText: "プレーンテキスト入力",@@ -786,6 +812,7 @@ export const ja = {lastVisited: "前回開いたタブ",},tabs: {+ sandbox: "サンドボックス",accounts: "アカウント",general: "一般",profile: "プロフィール",@@ -1058,6 +1085,55 @@ export const ja = {},},},+ sandbox: {+ title: "サンドボックス",+ description: "このコンピューターで Python とターミナルのツール呼び出しを OS サンドボックス内で実行するかどうか。",+ toolsSection: "このコンピューター",+ refresh: "更新",+ python: "Python",+ terminal: "ターミナル",+ osIsolation: "OS サンドボックス ({backend})",+ softwareSafeguards: "ソフトウェアによる保護",+ noReason: "ここではまだ OS サンドボックスが動作しないため、Unsloth が代わりに各呼び出しを確認します。",+ runsInCmd: "Git Bash は Windows サンドボックスで起動できないため、cmd.exe で実行します。",+ loadError: "サンドボックスの状態を読み込めませんでした",+ saveError: "サンドボックスの設定を保存できませんでした",+ prepareError: "この PC を準備できませんでした",+ unsupported: "この Unsloth サーバーはまだサンドボックスの状態を報告しません。ここで管理するには Unsloth を更新してください。",+ windowsSection: "Windows サンドボックス (プレビュー)",+ windowsDescription: "Microsoft の MXC サンドボックス。サンドボックスが組み込まれていない Windows バージョン向けです。",+ optInLabel: "Windows サンドボックスを有効にする",+ optInDescription: "Python とターミナルは、チャットのフォルダー内のファイルだけを変更できるようになります。",+ disclosure: "1 回限りの管理者手順「この PC を準備」が必要で、再起動のたびに繰り返す必要があります。ツールの実行中、Unsloth は必要なフォルダーへの一時的なアクセスを与えます。MXC はまだプレビューであり、セキュリティ境界ではありません。",+ lockedDacl: "UNSLOTH_MXC_ALLOW_DACL_FALLBACK で設定されています",+ grantsLabel: "ツールの起動を高速化",+ grantsDescription: "Unsloth 自身のランタイムフォルダーへの読み取り専用アクセスを呼び出し間で保持します。オフにすると、各呼び出しの起動が数秒遅くなります。",+ lockedGrants: "UNSLOTH_MXC_PERSISTENT_READ_GRANTS で設定されています",+ restored: "{count} 個のフォルダーからアクセスを削除しました。",+ hostPrepLabel: "管理者による設定",+ prepPrepared: "完了",+ prepNeeds: "必要",+ prepNeedsAgain: "前回の再起動後に再度必要",+ prepUnknown: "不明",+ prepareButton: "この PC を準備",+ preparing: "管理者の確認を待っています…",+ prepSucceeded: "この PC は準備済みです。",+ prepDeclined: "管理者の確認が拒否されました。",+ prepFailed: "準備に失敗しました。",+ setupLabel: "OS サンドボックス",+ setupCommandHint: "Unsloth を実行しているコンピューターでこれを実行してください:",+ macosBuiltIn: "macOS にはサンドボックスが組み込まれているため、インストールするものはありません。",+ setupKeywords: "インストール 設定 bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "OS サンドボックスの準備ができました。",+ runtimeMissing: "まだインストールされていません。インストールに管理者の承認は不要です。",+ runtimeLabel: "Windows サンドボックスのランタイム",+ installRuntime: "ランタイムをインストール",+ installingRuntime: "インストール中…",+ installRuntimeFailed: "ランタイムのインストールに失敗しました。",+ installRuntimeError: "ランタイムのインストールを開始できませんでした。",+ unsupportedArch: "Windows サンドボックス (MXC) は x64 版 Windows でのみ動作するため、この PC では使用できません。",+ unsupportedBuild: "Windows サンドボックス (MXC) には Windows 11 24H2 (ビルド 26100) 以降が必要なため、この PC では使用できません。",+ },debugging: {logSection: "ログファイル",source: "ログファイル",@@ -1554,7 +1630,7 @@ export const ja = {auto:"通常のツール呼び出しは自動で実行し、認証情報の読み取り、権限昇格、破壊的なコマンドなど、危険そうな操作のときだけ確認します。",off:- "すべてのツール呼び出しを確認なしで実行します。Python とターミナルのコードは引き続きサンドボックス内で実行され、コンピューター上でアクセスできるファイルが制限されます。",+ "すべてのツール呼び出しを確認なしで実行します。Python とターミナルのコードは引き続きサンドボックス内で実行され、コンピューター上でアクセスできるファイルが制限されます。このコンピューターで OS サンドボックスが動作しない場合、危険な Python とターミナルの呼び出しは先に確認します。",full:"すべてのツール呼び出しを確認なしで実行し、コードサンドボックスをオフにします。Python とターミナルのコードは、アカウントがアクセスできる任意のファイルを読み取り、変更できます。サンドボックスの外で作業する必要がある、信頼できるタスクに最適です。",},diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 78b0f8dc227..1b64c037c63 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -299,6 +299,32 @@ export const ko = {},// English fallback until this experimental feature is translated.managedEngines: en.managedEngines,+ sandboxSetup: {+ unavailable: "OS 샌드박스를 사용할 수 없음",+ title: "이 컴퓨터에는 아직 OS 샌드박스가 없습니다",+ description: "자동 실행은 Python과 터미널을 OS 샌드박스 안에서 실행합니다. 여기서 작동할 때까지 위험한 호출은 먼저 묻습니다.",+ checking: "이 컴퓨터의 샌드박스를 확인하는 중…",+ install: "샌드박스 설치",+ windowsSetup: "Windows 샌드박스 설정",+ copyCommand: "명령 복사",+ copied: "명령을 복사했습니다",+ copyFailed: "명령을 복사하지 못했습니다",+ commandHint: "또는 Unsloth가 실행 중인 컴퓨터에서 이 명령을 실행한 뒤 모드를 다시 선택하세요:",+ ownerOnly: "Unsloth가 실행 중인 컴퓨터에서 소유자만 설치할 수 있습니다.",+ runInTerminal: "Unsloth가 여기서 비밀번호를 요청할 수 없습니다. Unsloth가 실행 중인 컴퓨터의 터미널에서 이 명령을 실행한 뒤 모드를 다시 선택하세요:",+ useAnyway: "그대로 사용 (위험한 호출은 묻습니다)",+ cancel: "취소",+ close: "닫기",+ running: "설정 중입니다. Unsloth가 실행 중인 컴퓨터에서 암호 또는 관리자 확인을 승인하세요…",+ succeeded: "OS 샌드박스가 준비되었습니다. 자동 실행이 켜졌습니다.",+ stillUnavailable: "설정은 끝났지만 OS 샌드박스가 아직 검사를 통과하지 못했습니다.",+ declined: "암호 또는 관리자 확인이 거부되었습니다.",+ failed: "설정하지 못했습니다.",+ startError: "샌드박스 설정을 시작하지 못했습니다",+ checkFailed: "이 컴퓨터의 샌드박스를 확인하지 못했습니다.",+ retry: "다시 시도",+ keepsRunning: "닫아도 설정은 멈추지 않습니다. 결과는 설정 > 샌드박스에 표시됩니다.",+ },composerSettings: {title: "메시지 입력",plainText: "일반 텍스트 입력",@@ -784,6 +810,7 @@ export const ko = {lastVisited: "마지막으로 본 탭",},tabs: {+ sandbox: "샌드박스",accounts: "계정",general: "일반",profile: "프로필",@@ -1056,6 +1083,55 @@ export const ko = {},},},+ sandbox: {+ title: "샌드박스",+ description: "이 컴퓨터에서 Python 및 터미널 도구 호출을 OS 샌드박스 안에서 실행할지 여부입니다.",+ toolsSection: "이 컴퓨터",+ refresh: "새로 고침",+ python: "Python",+ terminal: "터미널",+ osIsolation: "OS 샌드박스 ({backend})",+ softwareSafeguards: "소프트웨어 보호 조치",+ noReason: "아직 여기서 작동하는 OS 샌드박스가 없으므로 Unsloth가 대신 각 호출을 확인합니다.",+ runsInCmd: "Git Bash는 Windows 샌드박스에서 시작할 수 없으므로 cmd.exe에서 실행됩니다.",+ loadError: "샌드박스 상태를 불러오지 못했습니다",+ saveError: "샌드박스 설정을 저장하지 못했습니다",+ prepareError: "이 PC를 준비하지 못했습니다",+ unsupported: "이 Unsloth 서버는 아직 샌드박스 상태를 보고하지 않습니다. 여기서 관리하려면 Unsloth를 업데이트하세요.",+ windowsSection: "Windows 샌드박스 (미리 보기)",+ windowsDescription: "기본 제공 샌드박스가 없는 Windows 버전을 위한 Microsoft의 MXC 샌드박스입니다.",+ optInLabel: "Windows 샌드박스 켜기",+ optInDescription: "그러면 Python과 터미널은 채팅 폴더의 파일만 변경할 수 있습니다.",+ disclosure: "한 번만 하는 관리자 단계인 이 PC 준비가 필요하며, 다시 시작할 때마다 반복해야 합니다. 도구가 실행되는 동안 Unsloth는 필요한 폴더에 대한 임시 액세스 권한을 부여합니다. MXC는 아직 미리 보기이며 보안 경계가 아닙니다.",+ lockedDacl: "UNSLOTH_MXC_ALLOW_DACL_FALLBACK으로 설정됨",+ grantsLabel: "더 빠른 도구 시작",+ grantsDescription: "호출 사이에 Unsloth 자체 런타임 폴더에 대한 읽기 전용 액세스를 유지합니다. 끄면 각 호출이 몇 초 더 느리게 시작됩니다.",+ lockedGrants: "UNSLOTH_MXC_PERSISTENT_READ_GRANTS로 설정됨",+ restored: "폴더 {count}개에서 액세스를 제거했습니다.",+ hostPrepLabel: "관리자 설정",+ prepPrepared: "완료",+ prepNeeds: "필요",+ prepNeedsAgain: "마지막으로 다시 시작한 후 다시 필요",+ prepUnknown: "알 수 없음",+ prepareButton: "이 PC 준비",+ preparing: "관리자 확인을 기다리는 중…",+ prepSucceeded: "이 PC가 준비되었습니다.",+ prepDeclined: "관리자 확인이 거부되었습니다.",+ prepFailed: "준비에 실패했습니다.",+ setupLabel: "OS 샌드박스",+ setupCommandHint: "Unsloth가 실행 중인 컴퓨터에서 이 명령을 실행하세요:",+ macosBuiltIn: "macOS에는 샌드박스가 기본 제공되므로 설치할 것이 없습니다.",+ setupKeywords: "설치 설정 bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "OS 샌드박스가 준비되었습니다.",+ runtimeMissing: "아직 설치되지 않았습니다. 설치에 관리자 승인이 필요하지 않습니다.",+ runtimeLabel: "Windows 샌드박스 런타임",+ installRuntime: "런타임 설치",+ installingRuntime: "설치 중…",+ installRuntimeFailed: "런타임을 설치하지 못했습니다.",+ installRuntimeError: "런타임 설치를 시작하지 못했습니다.",+ unsupportedArch: "Windows 샌드박스(MXC)는 x64 Windows에서만 실행되므로 이 PC에서는 사용할 수 없습니다.",+ unsupportedBuild: "Windows 샌드박스(MXC)는 Windows 11 24H2(빌드 26100) 이상이 필요하므로 이 PC에서는 사용할 수 없습니다.",+ },debugging: {logSection: "로그 파일",source: "로그 파일",@@ -1566,7 +1642,7 @@ export const ko = {auto:"일반적인 도구 호출은 알아서 실행하고, 자격 증명 읽기, 권한 상승, 파괴적인 명령 실행처럼 위험해 보이는 작업일 때만 묻습니다.",off:- "모든 도구 호출을 묻지 않고 실행합니다. Python과 터미널 코드는 여전히 샌드박스 안에서 실행되어 컴퓨터에서 접근할 수 있는 파일이 제한됩니다.",+ "모든 도구 호출을 묻지 않고 실행합니다. Python과 터미널 코드는 여전히 샌드박스 안에서 실행되어 컴퓨터에서 접근할 수 있는 파일이 제한됩니다. 이 컴퓨터에 작동하는 OS 샌드박스가 없으면 위험한 Python 및 터미널 호출은 먼저 묻습니다.",full:"모든 도구 호출을 묻지 않고 실행하며 코드 샌드박스를 꺼서, Python과 터미널 코드가 계정이 접근할 수 있는 모든 파일을 읽고 변경할 수 있습니다. 샌드박스 밖에서 작업해야 하는 신뢰할 수 있는 작업에 적합합니다.",},diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 070de84fc05..7a773f0451c 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -299,6 +299,32 @@ 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.",+ 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:",+ 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",+ 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.",+ 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.",+ startError: "Não foi possível iniciar a configuração do sandbox",+ checkFailed: "Não foi possível verificar o sandbox neste computador.",+ retry: "Tentar novamente",+ keepsRunning: "Fechar isto não interrompe a configuração. O resultado aparece em Configurações > Sandbox.",+ },composerSettings: {title: "Composição de mensagens",plainText: "Composição em texto simples",@@ -786,6 +812,7 @@ export const ptBR = {lastVisited: "Última visitada",},tabs: {+ sandbox: "Sandbox",accounts: "Contas",general: "Geral",profile: "Perfil",@@ -1058,6 +1085,55 @@ export const ptBR = {},},},+ sandbox: {+ title: "Sandbox",+ description: "Indica se as chamadas de ferramentas de Python e Terminal rodam dentro de um sandbox do sistema neste computador.",+ toolsSection: "Este computador",+ refresh: "Atualizar",+ python: "Python",+ terminal: "Terminal",+ osIsolation: "Sandbox do sistema ({backend})",+ softwareSafeguards: "Proteções por software",+ noReason: "Nenhum sandbox do sistema funciona aqui ainda, então o Unsloth verifica cada chamada.",+ runsInCmd: "Roda no cmd.exe, pois o Git Bash não consegue iniciar no sandbox do Windows.",+ loadError: "Falha ao carregar o status da sandbox",+ saveError: "Falha ao salvar a configuração da sandbox",+ prepareError: "Falha ao preparar este PC",+ unsupported: "Este servidor do Unsloth ainda não informa o status da sandbox. Atualize o Unsloth para gerenciá-lo aqui.",+ windowsSection: "Sandbox do Windows (prévia)",+ windowsDescription: "O sandbox MXC da Microsoft, para versões do Windows sem um integrado.",+ optInLabel: "Ativar o sandbox do Windows",+ optInDescription: "Assim, Python e Terminal só podem alterar arquivos na pasta do chat.",+ disclosure: "Exige uma etapa única de administrador, Preparar este PC, que precisa ser repetida após cada reinício. Enquanto uma ferramenta roda, o Unsloth dá a ela acesso temporário às pastas de que precisa. O MXC ainda é uma prévia, não uma barreira de segurança.",+ lockedDacl: "Definido por UNSLOTH_MXC_ALLOW_DACL_FALLBACK",+ grantsLabel: "Início mais rápido das ferramentas",+ grantsDescription: "Mantém o acesso somente leitura às pastas de runtime do próprio Unsloth entre as chamadas. Quando desativado, cada chamada inicia alguns segundos mais devagar.",+ lockedGrants: "Definido por UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ restored: "Acesso removido de {count} pastas.",+ hostPrepLabel: "Configuração de administrador",+ prepPrepared: "Concluído",+ prepNeeds: "Necessário",+ prepNeedsAgain: "Necessário de novo após o último reinício",+ prepUnknown: "Desconhecido",+ prepareButton: "Preparar este PC",+ preparing: "Aguardando o pedido de administrador…",+ prepSucceeded: "Este PC está preparado.",+ prepDeclined: "O pedido de administrador foi recusado.",+ prepFailed: "A preparação falhou.",+ setupLabel: "Sandbox do sistema",+ setupCommandHint: "Execute isto no computador onde o Unsloth roda:",+ macosBuiltIn: "O macOS tem um sandbox integrado, então não há nada para instalar.",+ setupKeywords: "instalar configurar bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "O sandbox do sistema está pronto.",+ runtimeMissing: "Ainda não instalado. A instalação não pede permissão de administrador.",+ runtimeLabel: "Runtime do sandbox do Windows",+ installRuntime: "Instalar runtime",+ installingRuntime: "Instalando…",+ installRuntimeFailed: "A instalação do runtime falhou.",+ 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.",+ },debugging: {logSection: "Arquivo de log",source: "Arquivo de log",@@ -1583,7 +1659,7 @@ export const ptBR = {auto:"Executa sozinho as chamadas comuns e só pergunta quando uma ação parece arriscada, como ler credenciais, elevar privilégios ou executar comandos destrutivos.",off:- "Executa todas as chamadas de ferramentas sem perguntar. O código de Python e terminal continua rodando no sandbox, que limita quais arquivos do seu computador ele pode acessar.",+ "Executa todas as chamadas de ferramentas sem perguntar. O código de Python e terminal continua rodando no sandbox, que limita quais arquivos do seu computador ele pode acessar. Se este computador não tiver um sandbox do sistema funcionando, chamadas arriscadas de Python e terminal perguntam primeiro.",full:"Executa todas as chamadas de ferramentas sem perguntar e desativa o sandbox de código, assim o código de Python e terminal pode ler e alterar qualquer arquivo que sua conta acessa. Ideal para tarefas confiáveis que precisam trabalhar fora do sandbox.",},diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 74bfe3c7c05..f2c47917ef2 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -299,6 +299,32 @@ export const ru = {},// English fallback until this experimental feature is translated.managedEngines: en.managedEngines,+ sandboxSetup: {+ unavailable: "Песочница ОС недоступна",+ title: "На этом компьютере пока нет песочницы ОС",+ description: "Выполнять автоматически держит Python и терминал в песочнице ОС. Пока она здесь не работает, их рискованные вызовы сначала требуют подтверждения.",+ checking: "Проверка песочницы на этом компьютере…",+ install: "Установить песочницу",+ windowsSetup: "Настроить песочницу Windows",+ copyCommand: "Скопировать команду",+ copied: "Команда скопирована",+ copyFailed: "Не удалось скопировать команду",+ commandHint: "Или выполните это на компьютере, где запущен Unsloth, и снова выберите режим:",+ ownerOnly: "Установить её может только владелец, с компьютера, где запущен Unsloth.",+ runInTerminal: "Unsloth не может запросить здесь ваш пароль. Выполните это в терминале на компьютере, где запущен Unsloth, и снова выберите режим:",+ useAnyway: "Всё равно использовать (рискованные вызовы будут спрашивать)",+ cancel: "Отмена",+ close: "Закрыть",+ running: "Идёт настройка. Подтвердите запрос пароля или администратора на компьютере, где запущен Unsloth…",+ succeeded: "Песочница ОС готова. Выполнять автоматически включено.",+ stillUnavailable: "Настройка завершена, но песочница ОС всё ещё не проходит проверку.",+ declined: "Запрос пароля или администратора отклонён.",+ failed: "Не удалось выполнить настройку.",+ startError: "Не удалось запустить настройку песочницы",+ checkFailed: "Не удалось проверить песочницу на этом компьютере.",+ retry: "Повторить",+ keepsRunning: "Закрытие не останавливает настройку. Результат появится в разделе Настройки > Песочница.",+ },composerSettings: {title: "Ввод сообщений",plainText: "Обычный текст",@@ -786,6 +812,7 @@ export const ru = {lastVisited: "Последняя открытая",},tabs: {+ sandbox: "Песочница",accounts: "Учётные записи",general: "Общие",profile: "Профиль",@@ -1058,6 +1085,55 @@ export const ru = {},},},+ sandbox: {+ title: "Песочница",+ description: "Выполняются ли вызовы инструментов Python и терминала в песочнице ОС на этом компьютере.",+ toolsSection: "Этот компьютер",+ refresh: "Обновить",+ python: "Python",+ terminal: "Терминал",+ osIsolation: "Песочница ОС ({backend})",+ softwareSafeguards: "Программные меры защиты",+ noReason: "Здесь пока не работает ни одна песочница ОС, поэтому Unsloth проверяет каждый вызов.",+ runsInCmd: "Выполняется в cmd.exe, так как Git Bash не запускается в песочнице Windows.",+ loadError: "Не удалось загрузить состояние песочницы",+ saveError: "Не удалось сохранить настройку песочницы",+ prepareError: "Не удалось подготовить этот ПК",+ unsupported: "Этот сервер Unsloth пока не сообщает состояние песочницы. Обновите Unsloth, чтобы управлять им здесь.",+ windowsSection: "Песочница Windows (предварительная версия)",+ windowsDescription: "Песочница MXC от Microsoft для версий Windows без встроенной песочницы.",+ optInLabel: "Включить песочницу Windows",+ optInDescription: "Тогда Python и терминал смогут изменять файлы только в папке чата.",+ disclosure: "Требуется разовый шаг администратора, «Подготовить этот ПК», который нужно повторять после каждой перезагрузки. Пока инструмент работает, Unsloth даёт ему временный доступ к нужным папкам. MXC пока предварительная версия, а не граница безопасности.",+ lockedDacl: "Задано через UNSLOTH_MXC_ALLOW_DACL_FALLBACK",+ grantsLabel: "Более быстрый запуск инструментов",+ grantsDescription: "Сохраняет доступ только для чтения к собственным папкам среды Unsloth между вызовами. Если выключено, каждый вызов запускается на несколько секунд дольше.",+ lockedGrants: "Задано через UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ restored: "Доступ удалён для папок: {count}.",+ hostPrepLabel: "Настройка администратора",+ prepPrepared: "Готово",+ prepNeeds: "Требуется",+ prepNeedsAgain: "Снова требуется после последней перезагрузки",+ prepUnknown: "Неизвестно",+ prepareButton: "Подготовить этот ПК",+ preparing: "Ожидание запроса администратора…",+ prepSucceeded: "Этот ПК подготовлен.",+ prepDeclined: "Запрос администратора отклонён.",+ prepFailed: "Подготовка не удалась.",+ setupLabel: "Песочница ОС",+ setupCommandHint: "Выполните это на компьютере, где запущен Unsloth:",+ macosBuiltIn: "В macOS есть встроенная песочница, поэтому устанавливать ничего не нужно.",+ setupKeywords: "установить настроить bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "Песочница ОС готова.",+ runtimeMissing: "Ещё не установлена. Для установки не нужны права администратора.",+ runtimeLabel: "Среда песочницы Windows",+ installRuntime: "Установить среду",+ installingRuntime: "Установка…",+ installRuntimeFailed: "Не удалось установить среду.",+ installRuntimeError: "Не удалось начать установку среды.",+ unsupportedArch: "Песочница Windows (MXC) работает только на Windows x64, поэтому на этом ПК она недоступна.",+ unsupportedBuild: "Песочнице Windows (MXC) нужна Windows 11 24H2 (сборка 26100) или новее, поэтому на этом ПК она недоступна.",+ },debugging: {logSection: "Файл журнала",source: "Файл журнала",@@ -1575,7 +1651,7 @@ export const ru = {auto:"Сам выполняет обычные вызовы инструментов и спрашивает, только когда действие выглядит рискованным, например чтение учётных данных, повышение привилегий или разрушительные команды.",off:- "Выполняет все вызовы инструментов без вопросов. Код Python и терминала по-прежнему запускается в песочнице, которая ограничивает доступ к файлам на вашем компьютере.",+ "Выполняет все вызовы инструментов без вопросов. Код Python и терминала по-прежнему запускается в песочнице, которая ограничивает доступ к файлам на вашем компьютере. Если на этом компьютере нет рабочей песочницы ОС, рискованные вызовы Python и терминала сначала требуют подтверждения.",full:"Выполняет все вызовы инструментов без вопросов и отключает песочницу для кода, поэтому код Python и терминала может читать и изменять любые файлы, доступные вашей учётной записи. Подходит для надёжных задач, которым нужно работать вне песочницы.",},diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex f79672b2573..c3a72f34b28 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -299,6 +299,32 @@ export const zhCN = {},// English fallback until this experimental feature is translated.managedEngines: en.managedEngines,+ sandboxSetup: {+ unavailable: "系统沙箱不可用",+ title: "这台电脑还没有系统沙箱",+ description: "自动运行会让 Python 和终端在系统沙箱中运行。在这里可用之前,它们的高风险调用会先询问。",+ checking: "正在检查这台电脑上的沙箱…",+ install: "安装沙箱",+ windowsSetup: "设置 Windows 沙箱",+ copyCommand: "复制命令",+ copied: "已复制命令",+ copyFailed: "无法复制命令",+ commandHint: "或者在运行 Unsloth 的电脑上执行以下命令,然后重新选择该模式:",+ ownerOnly: "只有所有者能在运行 Unsloth 的电脑上安装。",+ runInTerminal: "Unsloth 无法在这里请求你的密码。请在运行 Unsloth 的电脑的终端中运行以下命令,然后重新选择该模式:",+ useAnyway: "仍然使用(高风险调用会询问)",+ cancel: "取消",+ close: "关闭",+ running: "正在设置。请在运行 Unsloth 的电脑上批准密码或管理员提示…",+ succeeded: "系统沙箱已就绪。自动运行已开启。",+ stillUnavailable: "设置已完成,但系统沙箱仍未通过检查。",+ declined: "密码或管理员提示被拒绝。",+ failed: "设置失败。",+ startError: "无法开始设置沙箱",+ checkFailed: "无法检查这台电脑上的沙箱。",+ retry: "重试",+ keepsRunning: "关闭不会停止设置。结果会显示在 设置 > 沙盒 中。",+ },composerSettings: {title: "消息输入",plainText: "纯文本输入",@@ -782,6 +808,7 @@ export const zhCN = {lastVisited: "上次访问",},tabs: {+ sandbox: "沙盒",accounts: "账户",general: "通用",profile: "个人资料",@@ -1054,6 +1081,55 @@ export const zhCN = {},},},+ sandbox: {+ title: "沙盒",+ description: "Python 和终端工具调用是否在此计算机上的系统沙箱中运行。",+ toolsSection: "此计算机",+ refresh: "刷新",+ python: "Python",+ terminal: "终端",+ osIsolation: "系统沙箱 ({backend})",+ softwareSafeguards: "软件防护",+ noReason: "这里还没有可用的系统沙箱,因此 Unsloth 会改为检查每次调用。",+ runsInCmd: "在 cmd.exe 中运行,因为 Git Bash 无法在 Windows 沙箱中启动。",+ loadError: "无法加载沙盒状态",+ saveError: "无法保存沙盒设置",+ prepareError: "无法准备此电脑",+ unsupported: "此 Unsloth 服务器尚未报告沙盒状态。请更新 Unsloth 以便在此管理。",+ windowsSection: "Windows 沙箱(预览)",+ windowsDescription: "Microsoft 的 MXC 沙箱,适用于没有内置沙箱的 Windows 版本。",+ optInLabel: "开启 Windows 沙箱",+ optInDescription: "开启后,Python 和终端只能更改聊天文件夹中的文件。",+ disclosure: "需要一次性的管理员步骤“准备此电脑”,每次重启后都要重新执行。工具运行时,Unsloth 会临时授予它所需文件夹的访问权限。MXC 仍是预览版,不是安全边界。",+ lockedDacl: "由 UNSLOTH_MXC_ALLOW_DACL_FALLBACK 设置",+ grantsLabel: "更快启动工具",+ grantsDescription: "在调用之间保留对 Unsloth 自身运行时文件夹的只读访问。关闭后,每次调用的启动会慢几秒。",+ lockedGrants: "由 UNSLOTH_MXC_PERSISTENT_READ_GRANTS 设置",+ restored: "已移除 {count} 个文件夹的访问权限。",+ hostPrepLabel: "管理员设置",+ prepPrepared: "已完成",+ prepNeeds: "需要",+ prepNeedsAgain: "上次重启后需要再次执行",+ prepUnknown: "未知",+ prepareButton: "准备此电脑",+ preparing: "正在等待管理员提示…",+ prepSucceeded: "此电脑已准备就绪。",+ prepDeclined: "管理员提示被拒绝。",+ prepFailed: "准备失败。",+ setupLabel: "系统沙箱",+ setupCommandHint: "在运行 Unsloth 的电脑上执行以下命令:",+ macosBuiltIn: "macOS 自带沙箱,无需安装任何内容。",+ setupKeywords: "安装 设置 bubblewrap bwrap seatbelt mxc sudo pkexec apparmor uac",+ setupSucceeded: "系统沙箱已就绪。",+ runtimeMissing: "尚未安装。安装无需管理员授权。",+ runtimeLabel: "Windows 沙箱运行时",+ installRuntime: "安装运行时",+ installingRuntime: "正在安装…",+ installRuntimeFailed: "运行时安装失败。",+ installRuntimeError: "无法开始安装运行时。",+ unsupportedArch: "Windows 沙箱 (MXC) 仅支持 x64 版 Windows,因此在此电脑上不可用。",+ unsupportedBuild: "Windows 沙箱 (MXC) 需要 Windows 11 24H2(版本 26100)或更高版本,因此在此电脑上不可用。",+ },debugging: {logSection: "日志文件",source: "日志文件",@@ -1548,7 +1624,7 @@ export const zhCN = {auto:"常规工具调用会自动执行,只有在操作看起来有风险时才会询问,例如读取凭据、提升权限或执行破坏性命令。",off:- "所有工具调用都不再询问。Python 和终端代码仍在沙箱中运行,沙箱会限制它们能访问你电脑上的哪些文件。",+ "所有工具调用都不再询问。Python 和终端代码仍在沙箱中运行,沙箱会限制它们能访问你电脑上的哪些文件。如果这台电脑没有可用的系统沙箱,高风险的 Python 和终端调用会先询问。",full:"所有工具调用都不再询问,并关闭代码沙箱,Python 和终端代码可以读取和修改你的账户能访问的任何文件。适合需要在沙箱外工作的可信任务。",},diff --git a/studio/frontend/tests/account-permissions.test.ts b/studio/frontend/tests/account-permissions.test.tsindex 6547f780d27..e866b69e0c5 100644--- a/studio/frontend/tests/account-permissions.test.ts+++ b/studio/frontend/tests/account-permissions.test.ts@@ -9,7 +9,17 @@ import {type StubElement,} from "./helpers/module-stubs.ts";-function permissionUi(owner: boolean, permissionMode: string, loginMode = "multi") {+type Capability = {+ pythonOsIsolated: boolean;+ terminalOsIsolated: boolean;+} | null;++function permissionUi(+ owner: boolean,+ permissionMode: string,+ loginMode = "multi",+ capability: Capability = null,+) {const accountSession = loadWithStubs<{useFullAccessAllowed: () => boolean;}>(new URL("../src/features/auth/account-session.ts", import.meta.url), {@@ -24,6 +34,16 @@ function permissionUi(owner: boolean, permissionMode: string, loginMode = "multi},});const changes: string[] = [];+ const capabilityStub = {+ loadSandboxCapability: async () => capability,+ loadSettledSandboxCapability: async () => capability,+ // Nothing cached: every pick reads, so these cases see the settled answer.+ cachedSandboxCapability: () => null,+ onSandboxCapabilityChange: () => () => {},+ sandboxReady: (value: NonNullable<Capability>) =>+ value.pythonOsIsolated && value.terminalOsIsolated,+ capabilityPending: () => false,+ };const state = {permissionMode,setPermissionMode: (value: string) => {@@ -33,7 +53,14 @@ function permissionUi(owner: boolean, permissionMode: string, loginMode = "multiconst component = loadWithStubs<{PermissionModeMenuItems: (props: {onRequestFullAccess: () => void;+ onRequestSandboxSetup: () => 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;@@ -58,6 +85,15 @@ function permissionUi(owner: boolean, permissionMode: string, loginMode = "multi},"@/i18n": { useT: () => (key: string) => key },"@/features/auth/account-session": accountSession,+ "./api/sandbox-capability": capabilityStub,+ "./sandbox-pick": loadWithStubs(+ new URL("../src/features/chat/sandbox-pick.ts", import.meta.url),+ { "./api/sandbox-capability": capabilityStub },+ ),+ "./sandbox-setup-dialog": {+ SandboxSetupDialog: "SandboxSetupDialog",+ useSandboxSetupDialogStore: () => () => {},+ },"@/components/ui/alert-dialog": { AlertDialog: "AlertDialog" },"@/components/ui/button": { Button: "Button" },"@/components/ui/dropdown-menu": { DropdownMenuItem: "DropdownMenuItem" },@@ -69,8 +105,10 @@ function permissionUi(owner: boolean, permissionMode: string, loginMode = "multi"@/lib/utils": { cn: () => "" },"@hugeicons/react": {},"./stores/chat-runtime-store": {- useChatRuntimeStore: (selector: (state: unknown) => unknown) =>- selector(state),+ useChatRuntimeStore: Object.assign(+ (selector: (state: unknown) => unknown) => selector(state),+ { getState: () => state, subscribe: () => () => {} },+ ),},},);@@ -83,6 +121,7 @@ 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);@@ -103,7 +142,63 @@ test("multi-user policy leaves non-full preferences untouched", () => {onRequestFullAccess() {assert.fail("Full access must be unavailable");},+ onRequestSandboxSetup() {},});assert.deepEqual(ui.changes, []);}});++test("the stored values keep their order and their names", () => {+ const ui = permissionUi(true, "auto");+ assert.deepEqual(+ ui.component.PERMISSION_MODE_OPTIONS.map((option) => [+ option.value,+ option.label,+ ]),+ [+ ["ask", "Ask for approval"],+ ["auto", "Approve for me"],+ ["off", "Run automatically"],+ ["full", "Full access"],+ ],+ );+ 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",+ ],+] as const) {+ test(`picking Run automatically with ${name} is ${expected}`, async () => {+ const ui = permissionUi(true, "auto", "single", capability);+ const applied: string[] = [];+ let setupRequested = 0;+ await ui.component.pickSandboxedMode(+ (mode) => applied.push(mode),+ () => {+ setupRequested += 1;+ },+ );+ if (expected === "applied") {+ assert.deepEqual(applied, ["off"]);+ assert.equal(setupRequested, 0);+ } else {+ assert.deepEqual(applied, []);+ assert.equal(setupRequested, 1);+ }+ });+}diff --git a/studio/frontend/tests/sandbox-settings-api.test.ts b/studio/frontend/tests/sandbox-settings-api.test.tsnew file mode 100644index 00000000000..09037109195--- /dev/null+++ b/studio/frontend/tests/sandbox-settings-api.test.ts@@ -0,0 +1,312 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { loadWithStubs } from "./helpers/module-stubs.ts";++type Api = {+ loadSandboxStatus: (+ refresh: boolean,+ fallback: string,+ ) => Promise<Record<string, unknown>>;+ updateSandboxSettings: (+ update: Record<string, boolean>,+ fallback: string,+ ) => Promise<Record<string, unknown>>;+ startHostPreparation: (fallback: string) => Promise<Record<string, unknown>>;+ loadHostPreparation: (fallback: string) => Promise<Record<string, unknown>>;+};++type Call = { url: string; init?: RequestInit };++function loadApi(respond: (call: Call) => Response): {+ api: Api;+ calls: Call[];+} {+ const calls: Call[] = [];+ const api = loadWithStubs<Api>(+ new URL(+ "../src/features/settings/api/sandbox-isolation.ts",+ import.meta.url,+ ),+ {+ "@/features/auth": {+ authFetch: async (url: string, init?: RequestInit) => {+ const call = { url, init };+ calls.push(call);+ return respond(call);+ },+ },+ "@/lib/format-fastapi-error": {+ readFastApiError: async (response: Response, fallback: string) => {+ const body = (await response.json().catch(() => null)) as {+ detail?: string;+ } | null;+ return body?.detail ?? fallback;+ },+ },+ },+ { relativePassthrough: true },+ );+ return { api, calls };+}++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });++const WINDOWS_STATUS = {+ platform: "win32",+ python: {+ backend: "mxc-processcontainer",+ available: true,+ reason: "passed",+ limitations: ["mxc_preview_not_a_security_boundary"],+ protection_state: "preview",+ },+ terminal: {+ backend: "mxc-processcontainer",+ available: false,+ reason: "bash failed",+ limitations: [],+ },+ terminal_shell: "cmd_isolated",+ windows: {+ runtime_installed: true,+ allow_dacl_fallback: true,+ allow_dacl_fallback_saved: false,+ dacl_locked_by_environment: true,+ persistent_read_grants: false,+ persistent_read_grants_saved: true,+ grants_locked_by_environment: false,+ host_prep_missing: ["prepare-null-device"],+ prepare_repeats_after_restart: true,+ },+ checked_at: 12,+};++test("the status maps to camelCase and keeps the saved and effective values apart", async () => {+ const { api, calls } = loadApi(() => json(WINDOWS_STATUS));+ const status = await api.loadSandboxStatus(true, "fallback");+ assert.equal(calls[0].url, "/api/settings/sandbox?refresh=1");+ assert.deepEqual(status, {+ platform: "win32",+ python: {+ backend: "mxc-processcontainer",+ available: true,+ reason: "passed",+ limitations: ["mxc_preview_not_a_security_boundary"],+ protectionState: "preview",+ remediation: "",+ },+ terminal: {+ backend: "mxc-processcontainer",+ available: false,+ reason: "bash failed",+ limitations: [],+ protectionState: null,+ remediation: "",+ },+ terminalShell: "cmd_isolated",+ windows: {+ runtimeInstalled: true,+ runtimeUnsupported: null,+ allowDaclFallback: true,+ allowDaclFallbackSaved: false,+ daclLockedByEnvironment: true,+ persistentReadGrants: false,+ persistentReadGrantsSaved: true,+ grantsLockedByEnvironment: false,+ hostPrepMissing: ["prepare-null-device"],+ prepareRepeatsAfterRestart: true,+ },+ setup: null,+ checkedAt: 12,+ });+});++test("the setup plan and per-tool remediation reach the tab", async () => {+ const { api } = loadApi(() =>+ json({+ platform: "linux",+ python: {+ backend: "bubblewrap",+ available: false,+ reason: "bwrap is not installed",+ limitations: [],+ remediation: "apt-get install bubblewrap",+ },+ terminal: { backend: "bubblewrap", available: false, reason: "x" },+ windows: null,+ setup: {+ action: "linux-install",+ elevation: "pkexec",+ manual_command: "apt-get install -y bubblewrap",+ reason: "bubblewrap is missing",+ can_run: true,+ },+ }),+ );+ const status = await api.loadSandboxStatus(false, "fallback");+ assert.equal(+ (status.python as { remediation: string }).remediation,+ "apt-get install bubblewrap",+ );+ assert.deepEqual(status.setup, {+ action: "linux-install",+ elevation: "pkexec",+ manualCommand: "apt-get install -y bubblewrap",+ reason: "bubblewrap is missing",+ canRun: true,+ });+});++test("an unknown setup action or a refused request never offers the button", async () => {+ for (const setup of [+ { action: "rm-rf", manual_command: "x", can_run: true },+ { action: "linux-install", manual_command: "x", can_run: false },+ ]) {+ const { api } = loadApi(() =>+ json({ platform: "linux", python: {}, terminal: {}, setup }),+ );+ const status = await api.loadSandboxStatus(false, "fallback");+ assert.equal((status.setup as { canRun: boolean }).canRun, false);+ }+});++test("a non-Windows status has no Windows block and a plain load skips refresh", async () => {+ const { api, calls } = loadApi(() =>+ json({+ platform: "linux",+ python: {+ backend: "bubblewrap",+ available: true,+ reason: "",+ limitations: [],+ },+ terminal: {+ backend: "bubblewrap",+ available: true,+ reason: "",+ limitations: [],+ },+ terminal_shell: null,+ windows: null,+ checked_at: 1,+ }),+ );+ const status = await api.loadSandboxStatus(false, "fallback");+ assert.equal(calls[0].url, "/api/settings/sandbox");+ assert.equal(status.windows, null);+ assert.equal(status.terminalShell, null);+});++test("an unknown host preparation stays null rather than reading as prepared", async () => {+ const { api } = loadApi(() =>+ json({+ ...WINDOWS_STATUS,+ windows: { ...WINDOWS_STATUS.windows, host_prep_missing: null },+ }),+ );+ const status = await api.loadSandboxStatus(false, "fallback");+ assert.equal(+ (status.windows as { hostPrepMissing: unknown }).hostPrepMissing,+ null,+ );+});++test("a save sends only the fields it changes, in snake_case, and reports restored grants", async () => {+ const { api, calls } = loadApi(() =>+ json({ ...WINDOWS_STATUS, grants_restored: 2 }),+ );+ const status = await api.updateSandboxSettings(+ { allowDaclFallback: false },+ "fallback",+ );+ assert.equal(calls[0].init?.method, "PUT");+ assert.deepEqual(JSON.parse(String(calls[0].init?.body)), {+ allow_dacl_fallback: false,+ });+ assert.equal(status.restored, 2);+});++test("an older backend without the routes is told apart from a failure", async () => {+ const { api } = loadApi(() => new Response(null, { status: 404 }));+ await assert.rejects(api.loadSandboxStatus(false, "fallback"), {+ name: "SettingsRouteAbsentError",+ });+ await assert.rejects(api.startHostPreparation("fallback"), {+ name: "SettingsRouteAbsentError",+ });+});++test("a refused request surfaces the server's reason, else the fallback", async () => {+ const { api } = loadApi((call) =>+ call.init?.method === "POST"+ ? json(+ { detail: "Open Unsloth on the computer running it to prepare it." },+ 403,+ )+ : new Response("boom", { status: 500 }),+ );+ await assert.rejects(+ api.startHostPreparation("fallback"),+ /on the computer running it/,+ );+ await assert.rejects(+ api.loadHostPreparation("Failed to prepare"),+ /Failed to prepare/,+ );+});++test("a job maps its fields and an idle answer carries no id", async () => {+ const { api } = loadApi((call) =>+ call.init?.method === "POST"+ ? json({+ id: "j1",+ state: "running",+ started_at: 5,+ finished_at: null,+ exit_code: null,+ output_tail: ["preparing"],+ steps: ["prepare-null-device"],+ })+ : json({ state: "idle" }),+ );+ assert.deepEqual(await api.startHostPreparation("fallback"), {+ id: "j1",+ state: "running",+ startedAt: 5,+ finishedAt: null,+ exitCode: null,+ outputTail: ["preparing"],+ steps: ["prepare-null-device"],+ });+ const idle = await api.loadHostPreparation("fallback");+ assert.equal(idle.state, "idle");+ assert.equal(idle.id, null);+});++test("an unsupported Windows is passed through, anything unknown is dropped", async () => {+ for (const [value, expected] of [+ ["arch", "arch"],+ ["build", "build"],+ ["later", null],+ ] as const) {+ const { api } = loadApi(() =>+ json({+ ...WINDOWS_STATUS,+ windows: { ...WINDOWS_STATUS.windows, runtime_unsupported: value },+ }),+ );+ const status = await api.loadSandboxStatus(false, "fallback");+ assert.equal(+ (status.windows as { runtimeUnsupported: unknown }).runtimeUnsupported,+ expected,+ );+ }+});diff --git a/studio/frontend/tests/sandbox-settings-state.test.ts b/studio/frontend/tests/sandbox-settings-state.test.tsnew file mode 100644index 00000000000..d6d1832bca9--- /dev/null+++ b/studio/frontend/tests/sandbox-settings-state.test.ts@@ -0,0 +1,271 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import type {+ HostPrepJob,+ WindowsSandboxStatus,+} from "../src/features/settings/api/sandbox-isolation.ts";+import {+ hostPrepStatus,+ isOlderJob,+ jobOutputLines,+ jobResult,+ shouldPollJob,+ toolRowView,+ toolRowsQuiet,+ windowsView,+} from "../src/features/settings/tabs/sandbox-tab-state.ts";++const windows = (+ overrides: Partial<WindowsSandboxStatus> = {},+): WindowsSandboxStatus => ({+ runtimeInstalled: true,+ runtimeUnsupported: null,+ allowDaclFallback: true,+ allowDaclFallbackSaved: true,+ daclLockedByEnvironment: false,+ persistentReadGrants: true,+ persistentReadGrantsSaved: true,+ grantsLockedByEnvironment: false,+ hostPrepMissing: [],+ prepareRepeatsAfterRestart: true,+ ...overrides,+});++const job = (overrides: Partial<HostPrepJob> = {}): HostPrepJob => ({+ id: "j1",+ state: "running",+ startedAt: 1,+ finishedAt: null,+ exitCode: null,+ outputTail: [],+ steps: [],+ ...overrides,+});++test("tool rows name the OS backend when isolated and the reason when not", () => {+ const tool = {+ backend: "macos-seatbelt",+ available: true,+ reason: "",+ limitations: [],+ protectionState: null,+ remediation: "",+ };+ assert.deepEqual(toolRowView(tool), {+ isolated: true,+ backendLabel: "Seatbelt",+ reason: "",+ remediation: "",+ runsInCmd: false,+ });+ assert.equal(+ toolRowView({ ...tool, backend: "bubblewrap" }).backendLabel,+ "bubblewrap",+ );+ assert.equal(+ toolRowView({ ...tool, backend: "mxc-processcontainer" }, "cmd_isolated")+ .runsInCmd,+ true,+ );+ assert.equal(+ toolRowView({ ...tool, backend: "mxc-processcontainer" }, "bash").runsInCmd,+ false,+ );+ const fallback = toolRowView({+ ...tool,+ backend: "none",+ available: false,+ reason: "bwrap: denied",+ });+ assert.equal(fallback.isolated, false);+ assert.equal(fallback.reason, "bwrap: denied");+ assert.equal(+ toolRowView({ ...tool, available: false, remediation: "run this" })+ .remediation,+ "run this",+ );+ assert.equal(+ toolRowView({ ...tool, remediation: "run this" }).remediation,+ "",+ );+});++test("host preparation reads a lone null-device step as a post-restart repeat", () => {+ assert.equal(hostPrepStatus(windows({ hostPrepMissing: [] })), "prepared");+ assert.equal(+ hostPrepStatus(windows({ hostPrepMissing: ["prepare-null-device"] })),+ "needsPreparingAgain",+ );+ assert.equal(+ hostPrepStatus(+ windows({+ hostPrepMissing: ["prepare-system-drive", "prepare-null-device"],+ }),+ ),+ "needsPreparing",+ );+ assert.equal(+ hostPrepStatus(windows({ hostPrepMissing: ["prepare-system-drive"] })),+ "needsPreparing",+ );+ assert.equal(hostPrepStatus(windows({ hostPrepMissing: null })), "unknown");+ assert.equal(+ hostPrepStatus(+ windows({ allowDaclFallback: false, hostPrepMissing: ["x"] }),+ ),+ "off",+ );+ assert.equal(+ hostPrepStatus(windows({ runtimeInstalled: false })),+ "runtimeMissing",+ );+});++test("the prepare button shows only when something is missing or unknown", () => {+ assert.equal(windowsView(windows(), null, false).showPrepareButton, false);+ assert.equal(+ windowsView(windows({ hostPrepMissing: null }), null, false)+ .showPrepareButton,+ true,+ );+ assert.equal(+ windowsView(+ windows({ hostPrepMissing: ["prepare-null-device"] }),+ null,+ false,+ ).showPrepareButton,+ true,+ );+ assert.equal(+ windowsView(windows({ allowDaclFallback: false }), null, false)+ .showPrepareButton,+ false,+ );+ // A running job keeps its button, disabled, even once the status says prepared.+ const running = windowsView(windows(), job(), false);+ assert.equal(running.showPrepareButton, true);+ assert.equal(running.prepareDisabled, true);+ assert.equal(running.optInDisabled, true);+});++test("environment locks disable their switch and nothing else", () => {+ const locked = windowsView(+ windows({ daclLockedByEnvironment: true }),+ null,+ false,+ );+ assert.equal(locked.optInLocked, true);+ assert.equal(locked.optInDisabled, true);+ assert.equal(locked.grantsDisabled, false);+ const grants = windowsView(+ windows({ grantsLockedByEnvironment: true }),+ null,+ false,+ );+ assert.equal(grants.grantsLocked, true);+ assert.equal(grants.grantsDisabled, true);+ assert.equal(grants.optInDisabled, false);+});++test("the grants switch appears only with the opt-in on and a runtime installed", () => {+ assert.equal(windowsView(windows(), null, false).showGrantsRow, true);+ assert.equal(+ windowsView(windows({ allowDaclFallback: false }), null, false)+ .showGrantsRow,+ false,+ );+ const missing = windowsView(+ windows({ runtimeInstalled: false }),+ null,+ false,+ );+ assert.equal(missing.showGrantsRow, false);+ assert.equal(missing.runtimeMissing, true);+ assert.equal(missing.optInDisabled, true);+});++test("a save in flight disables both switches", () => {+ const saving = windowsView(windows(), null, true);+ assert.equal(saving.optInDisabled, true);+ assert.equal(saving.grantsDisabled, true);+ assert.equal(saving.prepareDisabled, true);+});++test("job results, polling and output lines", () => {+ assert.equal(jobResult(null), null);+ assert.equal(jobResult(job()), null);+ assert.equal(jobResult(job({ state: "idle" })), null);+ assert.equal(jobResult(job({ state: "declined" })), "declined");+ assert.equal(shouldPollJob(job()), true);+ assert.equal(shouldPollJob(job({ state: "succeeded" })), false);+ assert.equal(shouldPollJob(null), false);+ const lines = ["a", "", "b", "c", "d", "e", "f", "g"];+ assert.deepEqual(+ jobOutputLines(job({ state: "failed", outputTail: lines })),+ ["b", "c", "d", "e", "f", "g"],+ );+ assert.deepEqual(+ jobOutputLines(job({ state: "succeeded", outputTail: lines })),+ [],+ );+});++test("a late read of an earlier job never replaces the one this tab started", () => {+ const started = job({ id: "j2", startedAt: 20 });+ const stale = job({ id: "j1", state: "failed", startedAt: 10 });+ assert.equal(isOlderJob(stale, started), true);+ assert.equal(isOlderJob(stale, null), false);+ assert.equal(+ isOlderJob(job({ id: "j2", state: "succeeded", startedAt: 20 }), started),+ false,+ );+ assert.equal(isOlderJob(job({ id: "j3", startedAt: 30 }), started), false);+});++test("the setup job's first read is held to the same rule", () => {+ const started = { id: "s2", startedAt: 20 };+ assert.equal(isOlderJob({ id: "s1", startedAt: 10 }, started), true);+ assert.equal(isOlderJob({ id: "s2", startedAt: 20 }, started), false);+});++test("a missing runtime offers the install unless this Windows cannot run MXC", () => {+ const missing = windowsView(windows({ runtimeInstalled: false }), null, false);+ assert.equal(missing.runtimeMissing, true);+ assert.equal(missing.showInstallRuntime, true);+ assert.equal(missing.unsupported, null);+ for (const reason of ["arch", "build"] as const) {+ const view = windowsView(+ windows({ runtimeInstalled: false, runtimeUnsupported: reason }),+ null,+ false,+ );+ assert.equal(view.unsupported, reason);+ assert.equal(view.showInstallRuntime, false);+ }+ // Installed on a build that cannot run it: the note still replaces the controls.+ assert.equal(+ windowsView(windows({ runtimeUnsupported: "build" }), null, false)+ .unsupported,+ "build",+ );+});++test("the tool rows keep only their badge while a section below has the answer", () => {+ assert.equal(toolRowsQuiet(true, null), true);+ assert.equal(toolRowsQuiet(false, null), false);+ const view = (overrides: Partial<WindowsSandboxStatus>) =>+ windowsView(windows(overrides), null, false);+ assert.equal(toolRowsQuiet(false, view({ runtimeInstalled: false })), true);+ assert.equal(toolRowsQuiet(false, view({ allowDaclFallback: false })), true);+ assert.equal(+ toolRowsQuiet(false, view({ hostPrepMissing: ["prepare-null-device"] })),+ true,+ );+ assert.equal(toolRowsQuiet(false, view({ runtimeUnsupported: "build" })), true);+ // Prepared, yet a tool still fails: its own reason is the only clue left.+ assert.equal(toolRowsQuiet(false, view({})), false);+});diff --git a/studio/frontend/tests/sandbox-setup.test.ts b/studio/frontend/tests/sandbox-setup.test.tsnew file mode 100644index 00000000000..639dc76f6a8--- /dev/null+++ b/studio/frontend/tests/sandbox-setup.test.ts@@ -0,0 +1,749 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import type {+ SandboxCapability,+ SandboxSetupJob,+} from "../src/features/chat/api/sandbox-capability.ts";+import type { SandboxStatus } from "../src/features/settings/api/sandbox-isolation.ts";+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";++type Call = { url: string; init?: RequestInit };++type CapabilityApi = {+ loadSandboxCapability: (options?: {+ force?: boolean;+ }) => Promise<SandboxCapability | null>;+ forgetSandboxCapability: () => void;+ cachedSandboxCapability: () => SandboxCapability | null;+ capabilityFromApi: (body: Record<string, unknown>) => SandboxCapability;+ sandboxReady: (capability: SandboxCapability) => boolean;+ startSandboxSetup: (+ operation: string,+ options: { consentDaclFallback?: boolean },+ fallback: string,+ ) => Promise<SandboxSetupJob>;+ loadSandboxSetup: (fallback: string) => Promise<SandboxSetupJob>;+ loadSettledSandboxCapability: (options?: {+ attempts?: number;+ delayMs?: number;+ }) => Promise<SandboxCapability | null>;+};++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });++function loadCapabilityApi(+ respond: (call: Call) => Response | Promise<Response>,+) {+ const calls: Call[] = [];+ const api = loadWithStubs<CapabilityApi>(+ new URL("../src/features/chat/api/sandbox-capability.ts", import.meta.url),+ {+ "@/features/auth": {+ authFetch: async (url: string, init?: RequestInit) => {+ const call = { url, init };+ calls.push(call);+ return respond(call);+ },+ },+ "@/lib/format-fastapi-error": {+ readFastApiError: async (response: Response, fallback: string) => {+ const body = (await response.json().catch(() => null)) as {+ detail?: string;+ } | null;+ return body?.detail ?? fallback;+ },+ },+ },+ );+ return { api, calls };+}++const LINUX_UNAVAILABLE = {+ python_os_isolated: false,+ terminal_os_isolated: false,+ backend: "bubblewrap",+ platform: "linux",+ reason: "bwrap: setting up uid map: Permission denied",+ setup_action: "linux-install",+ manual_command: "apt-get install -y apparmor-profiles",+ can_run_setup: true,+};++test("the capability maps to camelCase and is cached between picker opens", async () => {+ const { api, calls } = loadCapabilityApi(() => json(LINUX_UNAVAILABLE));+ const first = await api.loadSandboxCapability();+ assert.deepEqual(first, {+ pythonOsIsolated: false,+ terminalOsIsolated: false,+ backend: "bubblewrap",+ platform: "linux",+ reason: "bwrap: setting up uid map: Permission denied",+ setupAction: "linux-install",+ manualCommand: "apt-get install -y apparmor-profiles",+ canRunSetup: true,+ setupBlocked: null,+ needsConsent: false,+ });+ await api.loadSandboxCapability();+ assert.equal(calls.length, 1);+ await api.loadSandboxCapability({ force: true });+ assert.equal(calls.length, 2);+ assert.equal(calls[1].url, "/api/sandbox/capability?refresh=1");+ assert.equal(api.sandboxReady(first as SandboxCapability), false);+});++test("an older server (404) or a failed check leaves the capability unknown", async () => {+ for (const response of [json({ detail: "Not Found" }, 404), json({}, 500)]) {+ const { api } = loadCapabilityApi(() => response);+ assert.equal(await api.loadSandboxCapability(), null);+ }+ const { api } = loadCapabilityApi(() => {+ throw new Error("offline");+ });+ assert.equal(await api.loadSandboxCapability(), null);+});++test("a setup the server did not name cannot be run, whatever the flag says", async () => {+ const { api } = loadCapabilityApi(() =>+ json({+ ...LINUX_UNAVAILABLE,+ setup_action: "curl-bash",+ can_run_setup: true,+ }),+ );+ const capability = await api.loadSandboxCapability();+ assert.equal(capability?.setupAction, null);+ assert.equal(capability?.canRunSetup, false);+});++test("starting a setup sends only the operation and the consent", async () => {+ const { api, calls } = loadCapabilityApi(() =>+ json({+ id: "s1",+ operation: "windows-setup",+ state: "running",+ output_tail: [],+ }),+ );+ const job = await api.startSandboxSetup(+ "windows-setup",+ { consentDaclFallback: true },+ "fallback",+ );+ assert.equal(calls[0].url, "/api/settings/sandbox/setup");+ assert.equal(calls[0].init?.method, "POST");+ assert.deepEqual(JSON.parse(String(calls[0].init?.body)), {+ operation: "windows-setup",+ consent_dacl_fallback: true,+ });+ assert.equal(job.state, "running");+ assert.equal(job.operation, "windows-setup");+});++test("a refused setup surfaces the server's reason", async () => {+ const { api } = loadCapabilityApi(() =>+ json(+ { detail: "Set up the sandbox from the computer running Unsloth." },+ 403,+ ),+ );+ await assert.rejects(+ api.startSandboxSetup("linux-install", {}, "fallback"),+ /computer running Unsloth/,+ );+});++test("Windows consent is asked only while the opt-in is off, and only of who can run it", async () => {+ const windows = {+ ...LINUX_UNAVAILABLE,+ platform: "win32",+ setup_action: "windows-setup",+ needs_consent: true,+ };+ for (const [body, expected] of [+ [windows, true],+ [{ ...windows, needs_consent: false }, false],+ [{ ...windows, can_run_setup: false }, false],+ [{ ...LINUX_UNAVAILABLE, needs_consent: true }, false],+ ] as const) {+ const { api } = loadCapabilityApi(() => json(body));+ assert.equal((await api.loadSandboxCapability())?.needsConsent, expected);+ }+});++test("the runtime-only operation is sent as is and the job note is kept", async () => {+ const { api, calls } = loadCapabilityApi(() =>+ json({+ id: "s2",+ operation: "windows-runtime",+ state: "failed",+ note: "a password is required",+ manual_command: "python install_mxc_prebuilt.py",+ }),+ );+ const job = await api.startSandboxSetup("windows-runtime", {}, "fallback");+ assert.deepEqual(JSON.parse(String(calls[0].init?.body)), {+ operation: "windows-runtime",+ consent_dacl_fallback: false,+ });+ assert.equal(job.note, "a password is required");+ assert.equal(job.manualCommand, "python install_mxc_prebuilt.py");+});++test("a settled read waits out a check that has not answered yet, but not a real no", async () => {+ const pending = { ...LINUX_UNAVAILABLE, backend: "unknown" };+ const ready = {+ ...LINUX_UNAVAILABLE,+ python_os_isolated: true,+ terminal_os_isolated: true,+ };+ let n = 0;+ const { api, calls } = loadCapabilityApi(() =>+ json(n++ < 2 ? pending : ready),+ );+ const settled = await api.loadSettledSandboxCapability({ delayMs: 1 });+ assert.equal(calls.length, 3);+ assert.ok(calls.every((call) => call.url.endsWith("?refresh=1")));+ assert.equal(settled && api.sandboxReady(settled), true);++ const denied = loadCapabilityApi(() => json(LINUX_UNAVAILABLE));+ const no = await denied.api.loadSettledSandboxCapability({ delayMs: 1 });+ assert.equal(denied.calls.length, 1);+ assert.equal(no?.backend, "bubblewrap");++ const stuck = loadCapabilityApi(() => json(pending));+ await stuck.api.loadSettledSandboxCapability({ attempts: 2, delayMs: 1 });+ assert.equal(stuck.calls.length, 2);+});++type PickModule = typeof import("../src/features/chat/sandbox-pick.ts");++const pickModule = loadWithStubs<PickModule>(+ new URL("../src/features/chat/sandbox-pick.ts", import.meta.url),+ {+ "./api/sandbox-capability": {+ loadSettledSandboxCapability: async () => null,+ cachedSandboxCapability: () => null,+ sandboxReady: (c: SandboxCapability) =>+ c.pythonOsIsolated && c.terminalOsIsolated,+ capabilityPending: (c: SandboxCapability) =>+ c.backend === "unknown" &&+ !(c.pythonOsIsolated && c.terminalOsIsolated),+ },+ },+);++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) => {+ resolve = r;+ });+ return { promise, resolve };+}++test("a slow capability read does not undo a mode picked while it was in flight", async () => {+ let mode: string = "auto";+ 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,+ );+ mode = "ask";+ read.resolve(null);+ await pending;+ assert.deepEqual(applied, []);+ assert.equal(dialogs, 0);+});++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";+ 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);+ },+ );+ setMode("ask");+ setMode("auto");+ read.resolve(capability({ pythonOsIsolated: false }));+ await pending;+ assert.deepEqual(applied, []);+ assert.equal(dialogs, 0);+ assert.equal(listeners.size, 0);+});++test("only the latest pick acts; a missing sandbox opens the setup instead of applying", async () => {+ let mode: string = "auto";+ 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 }),+ );+ 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.deepEqual(applied, ["off"]);+});++test("a sandbox already known to work applies Run automatically without a fresh probe", 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 }),+ );+ assert.deepEqual(applied, ["off"]);+ assert.equal(reads, 0);+});++type SetupState = typeof import("../src/features/chat/sandbox-setup-state.ts");++const setupState = loadWithStubs<SetupState>(+ new URL("../src/features/chat/sandbox-setup-state.ts", import.meta.url),+ { "@/features/settings": tabState },+);++const capability = (+ overrides: Partial<SandboxCapability> = {},+): SandboxCapability => ({+ pythonOsIsolated: false,+ terminalOsIsolated: false,+ backend: "bubblewrap",+ platform: "linux",+ reason: "denied",+ setupAction: "linux-install",+ manualCommand: "apt-get install -y bubblewrap",+ canRunSetup: true,+ setupBlocked: null,+ needsConsent: false,+ ...overrides,+});++const setupJob = (+ overrides: Partial<SandboxSetupJob> = {},+): SandboxSetupJob => ({+ id: "s1",+ operation: "linux-install",+ state: "running",+ startedAt: 1,+ finishedAt: null,+ exitCode: null,+ outputTail: [],+ steps: [],+ manualCommand: "",+ note: "",+ ...overrides,+});++test("the dialog shows a check in progress before the capability arrives", () => {+ const view = setupState.sandboxSetupView({+ capability: null,+ job: null,+ consent: false,+ });+ assert.equal(view.checking, true);+ assert.equal(view.install, null);+ assert.equal(view.command, "");+});++test("the owner on Linux gets Install sandbox and the command", () => {+ const view = setupState.sandboxSetupView({+ capability: capability(),+ job: null,+ consent: false,+ });+ assert.equal(view.install, "linux");+ assert.equal(view.installDisabled, false);+ assert.equal(view.showConsent, false);+ assert.equal(view.command, "apt-get install -y bubblewrap");+ assert.equal(view.showOwnerOnly, false);+});++test("Windows needs the MXC consent before the setup can start", () => {+ const windows = capability({+ platform: "win32",+ backend: "mxc-processcontainer",+ setupAction: "windows-setup",+ manualCommand: "",+ needsConsent: true,+ });+ const without = setupState.sandboxSetupView({+ capability: windows,+ job: null,+ consent: false,+ });+ assert.equal(without.install, "windows");+ assert.equal(without.showConsent, true);+ assert.equal(without.installDisabled, true);+ assert.equal(without.command, "");+ const withConsent = setupState.sandboxSetupView({+ capability: windows,+ job: null,+ consent: true,+ });+ assert.equal(withConsent.installDisabled, false);+});++test("someone who cannot run the setup gets the command and who can", () => {+ const view = setupState.sandboxSetupView({+ capability: capability({ canRunSetup: false }),+ job: null,+ consent: false,+ });+ assert.equal(view.install, null);+ assert.equal(view.showOwnerOnly, true);+ const macos = setupState.sandboxSetupView({+ capability: capability({+ platform: "darwin",+ setupAction: null,+ canRunSetup: false,+ manualCommand: "",+ }),+ job: null,+ consent: false,+ });+ assert.equal(macos.showOwnerOnly, false);+ assert.equal(macos.install, null);+});++test("another account on Windows gets the owner note without the host's paths", () => {+ const view = setupState.sandboxSetupView({+ capability: capability({+ platform: "win32",+ setupAction: null,+ canRunSetup: false,+ manualCommand: "",+ setupBlocked: "not_owner",+ }),+ job: null,+ consent: false,+ });+ assert.equal(view.command, "");+ assert.equal(view.showOwnerOnly, true);+});++test("the owner here without a way to ask for the password is told to run the command", () => {+ const view = setupState.sandboxSetupView({+ capability: capability({+ canRunSetup: false,+ setupAction: null,+ setupBlocked: "no_elevation",+ }),+ job: null,+ consent: false,+ });+ assert.equal(view.install, null);+ assert.equal(view.showOwnerOnly, false);+ assert.equal(view.showRunInTerminal, true);+ const { api } = loadCapabilityApi(() => json({}));+ assert.equal(+ api.capabilityFromApi({ setup_blocked: "no_elevation" }).setupBlocked,+ "no_elevation",+ );+ assert.equal(+ api.capabilityFromApi({ setup_blocked: "other" }).setupBlocked,+ null,+ );+});++test("a running job disables the button; a failure shows its output and command", () => {+ const running = setupState.sandboxSetupView({+ capability: capability(),+ job: setupJob(),+ consent: false,+ });+ assert.equal(running.running, true);+ assert.equal(running.installDisabled, true);+ const failed = setupState.sandboxSetupView({+ capability: capability(),+ job: setupJob({+ state: "failed",+ exitCode: 100,+ outputTail: ["", "E: Unable to locate package bubblewrap"],+ manualCommand: "apt-get update && apt-get install -y bubblewrap",+ }),+ consent: false,+ });+ assert.equal(failed.result, "failed");+ assert.deepEqual(failed.outputLines, [+ "E: Unable to locate package bubblewrap",+ ]);+ assert.equal(+ failed.command,+ "apt-get update && apt-get install -y bubblewrap",+ );+ const declined = setupState.sandboxSetupView({+ capability: capability(),+ job: setupJob({ state: "declined", exitCode: 126 }),+ consent: false,+ });+ assert.equal(declined.result, "declined");+ assert.equal(declined.command, "apt-get install -y bubblewrap");+});++test("a failed check shows Retry instead of an endless spinner", () => {+ const view = setupState.sandboxSetupView({+ capability: null,+ job: null,+ consent: false,+ loadFailed: true,+ });+ assert.equal(view.checking, false);+ assert.equal(view.loadFailed, true);+ assert.equal(view.install, null);+});++test("Windows skips the consent once the opt-in is on (after a reboot, only preparation)", () => {+ const view = setupState.sandboxSetupView({+ capability: capability({+ platform: "win32",+ setupAction: "windows-setup",+ needsConsent: false,+ }),+ job: null,+ consent: false,+ });+ assert.equal(view.install, "windows");+ assert.equal(view.showConsent, false);+ assert.equal(view.installDisabled, false);+});++test("the server's note shows for a declined or failed setup only", () => {+ const note = "Not authorized, or no authentication agent";+ for (const [state, shown] of [+ ["failed", note],+ ["declined", note],+ ["running", ""],+ ["succeeded", ""],+ ] as const) {+ const view = setupState.sandboxSetupView({+ capability: capability(),+ job: setupJob({ state, note }),+ consent: false,+ });+ assert.equal(view.note, shown, state);+ }+});++const status = (overrides: Partial<SandboxStatus> = {}): SandboxStatus => ({+ platform: "linux",+ python: {+ backend: "bubblewrap",+ available: false,+ reason: "missing",+ limitations: [],+ protectionState: null,+ remediation: "",+ },+ terminal: {+ backend: "bubblewrap",+ available: false,+ reason: "missing",+ limitations: [],+ protectionState: null,+ remediation: "",+ },+ terminalShell: "bash",+ windows: null,+ setup: {+ action: "linux-install",+ elevation: "sudo",+ manualCommand: "apt-get install -y bubblewrap",+ reason: "bubblewrap is not installed",+ canRun: true,+ },+ checkedAt: 1,+ ...overrides,+});++test("Linux shows Install sandbox with the command; a remote owner only the command", () => {+ const row = setupRowView(status(), null);+ assert.equal(row.show, true);+ assert.equal(row.showInstall, true);+ assert.equal(row.command, "apt-get install -y bubblewrap");+ const remote = setupRowView(+ status({ setup: { ...status().setup!, canRun: false } }),+ null,+ );+ assert.equal(remote.showInstall, false);+ assert.equal(remote.command, "apt-get install -y bubblewrap");+});++test("a working Linux sandbox, an older server and Windows hide the row", () => {+ assert.equal(+ setupRowView(+ status({+ setup: {+ action: null,+ elevation: null,+ manualCommand: "",+ reason: "",+ canRun: false,+ },+ }),+ null,+ ).show,+ false,+ );+ assert.equal(setupRowView(status({ setup: null }), null).show, false);+ assert.equal(setupRowView(status({ platform: "win32" }), null).show, false);+});++test("macOS explains Seatbelt instead of offering an install, and only when it fails", () => {+ const failing = setupRowView(+ status({ platform: "darwin", setup: null }),+ null,+ );+ assert.equal(failing.show, true);+ assert.equal(failing.builtIn, true);+ assert.equal(failing.showInstall, false);+ assert.equal(failing.reason, "missing");+ const working = status({ platform: "darwin", setup: null });+ working.python.available = true;+ working.terminal.available = true;+ assert.equal(setupRowView(working, null).show, false);+});++test("a failed install shows the job's command; a running one keeps the button", () => {+ const failed = setupRowView(+ status(),+ { ...setupJob({ state: "failed" }) },+ "apt-get update && apt-get install -y bubblewrap",+ );+ assert.equal(+ failed.command,+ "apt-get update && apt-get install -y bubblewrap",+ );+ const running = setupRowView(+ status({ setup: { ...status().setup!, canRun: false, manualCommand: "" } }),+ setupJob(),+ );+ assert.equal(running.show, true);+ assert.equal(running.showInstall, true);+ 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(+ () => new Promise<Response>((resolve) => replies.push(resolve)),+ );+ const older = api.loadSandboxCapability();+ const newer = api.loadSandboxCapability({ force: true });+ await new Promise((resolve) => setTimeout(resolve, 0));+ replies[1](+ json({+ ...LINUX_UNAVAILABLE,+ python_os_isolated: true,+ terminal_os_isolated: true,+ }),+ );+ await newer;+ replies[0](json(LINUX_UNAVAILABLE));+ await older;+ assert.equal(api.cachedSandboxCapability()?.pythonOsIsolated, true);+ const stale = api.loadSandboxCapability({ force: true });+ await new Promise((resolve) => setTimeout(resolve, 0));+ api.forgetSandboxCapability();+ replies[2](json(LINUX_UNAVAILABLE));+ await stale;+ assert.equal(api.cachedSandboxCapability(), null);+});diff --git a/studio/frontend/tests/settings-tab-visibility.test.ts b/studio/frontend/tests/settings-tab-visibility.test.tsindex e6bd14078e2..323b18db201 100644--- a/studio/frontend/tests/settings-tab-visibility.test.ts+++ b/studio/frontend/tests/settings-tab-visibility.test.ts@@ -20,7 +20,7 @@ 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", "debugging"] as const) {+ for (const tab of ["accounts", "resources", "remote-lan", "agents", "sandbox", "debugging"] as const) {assert.ok(OWNER_ONLY_SETTINGS_TABS.has(tab), tab);assert.equal(resolveSettingsTab(tab, false), "general");}diff --git a/studio/src-tauri/src/app_menu.rs b/studio/src-tauri/src/app_menu.rsindex e2bc96bcadd..1a2182abb6f 100644--- a/studio/src-tauri/src/app_menu.rs+++ b/studio/src-tauri/src/app_menu.rs@@ -72,6 +72,7 @@ const SETTINGS_ROWS: &[Row] = &[Row::Action("settings-appearance", "Appearance", ""),Row::Action("settings-resources", "System", ""),Row::Action("settings-chat", "Chat", ""),+ Row::Action("settings-sandbox", "Sandbox", ""),Row::Action("settings-api-keys", "API", ""),Row::Action("settings-remote-lan", "Remote & LAN", ""),Row::Action("settings-connections", "Connections", ""),diff --git a/tests/studio/playwright_chat_ui.py b/tests/studio/playwright_chat_ui.pyindex b1e4bd34ede..63e4b040ac2 100644--- a/tests/studio/playwright_chat_ui.py+++ b/tests/studio/playwright_chat_ui.py@@ -234,6 +234,30 @@ def exercise_permission_mode_controls(page, shoot):pill = page.locator('button[aria-label="Permission level for tool calls"]:visible').firstexpect(pill).to_be_visible()+ # Stub the sandbox capability so level checks do not depend on the runner's user namespaces.+ sandbox_answer = {"ready": True}++ def answer_sandbox_capability(route):+ ready = sandbox_answer["ready"]+ route.fulfill(+ status = 200,+ content_type = "application/json",+ body = json.dumps(+ {+ "python_os_isolated": ready,+ "terminal_os_isolated": ready,+ "backend": "bubblewrap",+ "platform": "linux",+ "reason": "" if ready else "bwrap: setting up uid map: Permission denied",+ "setup_action": None,+ "manual_command": "" if ready else "apt-get install -y bubblewrap",+ "can_run_setup": False,+ }+ ),+ )++ page.route("**/api/sandbox/capability*", answer_sandbox_capability)+def expect_mode(label):expect(pill).to_have_attribute("data-pill-label", label)expect(pill).to_contain_text(label)@@ -516,10 +540,40 @@ 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.+ choose("Approve for me")+ expect_mode("Approve for me")+ # Landed on the install first, or the reload hydrates the previous "off" back.+ expect_server_mode("auto")+ sandbox_answer["ready"] = False+ reload_and_wait_for_pill()+ expect_mode("Approve for me")+ choose("Run automatically")+ 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("button", name = "Copy command")).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()+ expect(setup).to_be_hidden()+ expect_mode("Run automatically")+ sandbox_answer["ready"] = True+ reload_and_wait_for_pill()+# Leave the full chat smoke in the fresh-install default.choose("Approve for me")expect_mode("Approve for me")+ expect_server_mode("auto")shoot("04-permission-levels")+ # The stub is for the level checks only. Left in place it intercepts this page for the rest of the run, which+ # also turns off its HTTP cache, and the later sign-out step wedged on it on Windows.+ page.unroute("**/api/sandbox/capability*", answer_sandbox_capability)def login_via_api(pw):diff --git a/tests/studio/playwright_settings_tabs.py b/tests/studio/playwright_settings_tabs.pyindex a2c4e29657f..88b95b43618 100644--- a/tests/studio/playwright_settings_tabs.py+++ b/tests/studio/playwright_settings_tabs.py@@ -47,6 +47,7 @@ TABS = ["keyboard-shortcuts","browser","debugging",+ "sandbox","about","accounts",]diff --git a/tests/studio/playwright_thread_scoped_settings.py b/tests/studio/playwright_thread_scoped_settings.pyindex 783ad7a3545..c63b15d29d7 100644--- a/tests/studio/playwright_thread_scoped_settings.py+++ b/tests/studio/playwright_thread_scoped_settings.py@@ -500,6 +500,16 @@ def main():browser = playwright.chromium.launch(args = ["--no-sandbox", "--disable-dev-shm-usage"])context = browser.new_context(viewport = {"width": 1280, "height": 900})context.add_init_script(CHAT_TRAFFIC_JS)+ # "Run automatically" only switches straight away when the OS sandbox works; answer+ # for the host so this test does not depend on the runner's user namespaces.+ context.route(+ "**/api/sandbox/capability*",+ lambda route: route.fulfill(+ status = 200,+ content_type = "application/json",+ body = json.dumps({"python_os_isolated": True, "terminal_os_isolated": True}),+ ),+ )page = context.new_page()page.set_default_timeout(TIMEOUT_MS)page_errors = []