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 memory limit setting to Settings > Sandbox (#13194)
Daniel Hanfc6cf42d1a18
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 15c2b842f36..4748cf829f6 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -89,6 +89,7 @@ from core.inference.mcp_client import (from storage import mcp_servers_dbfrom utils.account_context import account_thread, current_account_id, is_owner_contextfrom utils.current_date_prompt_settings import strip_current_date_update_note+from utils import sandbox_memory_limitfrom core.inference.tool_confinement import ToolConfinementUnavailable, account_confinementfrom pathlib import Pathfrom utils.paths.storage_roots import RetiredAccountError, ensure_dir@@ -9877,6 +9878,15 @@ def _build_bypass_env(workdir: str) -> dict[str, str]:return env+# Read by _sandbox_preexec after the fork, so it is resolved here first: the settings store cannot be read in the child.+_sandbox_as_bytes = 8 * 1024 * 1024 * 1024+++def _refresh_sandbox_memory_limit() -> None:+ global _sandbox_as_bytes+ _sandbox_as_bytes = sandbox_memory_limit.memory_limit_bytes()++def _sandbox_preexec():"""Best-effort sandbox setup for sandboxed subprocesses (modules are resolved at import time sothe forked child runs no imports)."""@@ -9916,8 +9926,9 @@ def _sandbox_preexec():except (ValueError, OSError):passtry:- as_bytes = int(os.environ.get("UNSLOTH_STUDIO_SANDBOX_AS_GB", "8")) * 1024 * 1024 * 1024- _resource.setrlimit(_resource.RLIMIT_AS, (as_bytes, as_bytes))+ as_bytes = _sandbox_as_bytes+ if as_bytes is not None:+ _resource.setrlimit(_resource.RLIMIT_AS, (as_bytes, as_bytes))except (ValueError, OSError, AttributeError):passtry:@@ -22621,6 +22632,8 @@ def _python_exec(if sys.platform == "win32"else (_bypass_preexec if disable_sandbox else _sandbox_preexec))+ if base_preexec is _sandbox_preexec:+ _refresh_sandbox_memory_limit()# Managed accounts keep their own boundary as the outer contract; `confines`, not `is not None` (placeholder).if confinement is None or not confinement.confines:prepared = _prepare_tool_launch(@@ -22880,6 +22893,8 @@ def _bash_exec(if sys.platform == "win32"else (_bypass_preexec if disable_sandbox else _sandbox_preexec))+ if base_preexec is _sandbox_preexec:+ _refresh_sandbox_memory_limit()if confinement is None or not confinement.confines:prepared = _prepare_tool_launch(os_sandbox.ToolLaunchPlan(diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex a186fa7d9b9..52a246ed961 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -89,7 +89,7 @@ from utils.helper_precache_settings import (helper_model_disabled_by_env,set_helper_precache_enabled,)-from utils import systemone_settings+from utils import sandbox_memory_limit, systemone_settingsfrom utils.download_transport_settings import (get_download_transport_mode,set_download_transport_mode,@@ -4803,12 +4803,24 @@ class SandboxSetupStatus(BaseModel):can_run: bool = False+class SandboxMemoryStatus(BaseModel):+ # GiB the next sandboxed run is capped at; None = no cap.+ limit_gb: Optional[int] = None+ saved_gb: int+ default_gb: int+ min_gb: int+ max_gb: int+ locked_by_environment: bool++class SandboxStatusResponse(BaseModel):platform: strpython: SandboxToolStatusterminal: SandboxToolStatusterminal_shell: Optional[str] = Nonewindows: Optional[SandboxWindowsStatus] = None+ # None off Linux, where the rlimit never applied.+ memory: Optional[SandboxMemoryStatus] = Nonesetup: Optional[SandboxSetupStatus] = Nonechecked_at: floatgrants_restored: Optional[int] = None@@ -4819,6 +4831,11 @@ class SandboxSettingsPayload(BaseModel):allow_dacl_fallback: Optional[StrictBool] = Nonepersistent_read_grants: Optional[StrictBool] = None+ memory_limit_gb: Optional[StrictInt] = Field(+ default = None,+ ge = sandbox_memory_limit.MIN_MEMORY_LIMIT_GB,+ le = sandbox_memory_limit.MAX_MEMORY_LIMIT_GB,+ )class SandboxSetupPayload(BaseModel):@@ -5004,11 +5021,30 @@ def _sandbox_setup_status(available: bool) -> Optional[SandboxSetupStatus]:)+def _sandbox_memory_status() -> Optional[SandboxMemoryStatus]:+ import sys++ # Linux only: Windows never set this rlimit, and on macOS setrlimit(RLIMIT_AS) fails once the forked child+ # already maps more than the cap, so tool runs there were never capped.+ if sys.platform != "linux":+ return None+ return SandboxMemoryStatus(+ limit_gb = sandbox_memory_limit.effective_memory_limit_gb(),+ saved_gb = sandbox_memory_limit.saved_memory_limit_gb(),+ default_gb = sandbox_memory_limit.DEFAULT_MEMORY_LIMIT_GB,+ min_gb = sandbox_memory_limit.MIN_MEMORY_LIMIT_GB,+ max_gb = sandbox_memory_limit.MAX_MEMORY_LIMIT_GB,+ locked_by_environment = sandbox_memory_limit.locked_by_environment(),+ )++def _for_request(status: SandboxStatusResponse, request: Request) -> SandboxStatusResponse:"""Blocking. The setup button: a direct local request, or a Linux install that prompts nobody here."""from core.inference import sandbox_setup_planfrom utils.client_ip import is_direct_local_request+ # Read per request, not from the probe cache: a save must show at once.+ status = status.model_copy(update = {"memory": _sandbox_memory_status()})setup = status.setupif setup is None:return status@@ -5048,6 +5084,10 @@ def _sandbox_apply(payload: SandboxSettingsPayload) -> Optional[int]:from core.inference import mxc_policy, mxc_read_grantsfrom utils import mxc_isolation_settings as saved+ if payload.memory_limit_gb is not None:+ sandbox_memory_limit.set_memory_limit_gb(payload.memory_limit_gb)+ # The route refuses it beside the Windows switches, so the MXC state below is untouched.+ return Noneif payload.allow_dacl_fallback is not None:saved.set_dacl_fallback_setting(payload.allow_dacl_fallback)if payload.persistent_read_grants is not None:@@ -5093,13 +5133,27 @@ async def update_sandbox_settings(# 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."""+ """Save the Windows MXC opt-in, the persistent read grant choice, or the Linux memory limit. Applies to the next+ launch."""import sysfrom core.inference import mxc_policy, mxc_read_grantsfrom utils import mxc_isolation_settings as saved- if sys.platform != "win32":+ windows_fields = (+ payload.allow_dacl_fallback is not None or payload.persistent_read_grants is not None+ )+ if payload.memory_limit_gb is not None:+ if sys.platform != "linux":+ raise HTTPException(+ status_code = 409, detail = "The sandbox memory limit only applies on Linux."+ )+ if sandbox_memory_limit.locked_by_environment():+ raise HTTPException(+ status_code = 409,+ detail = f"{sandbox_memory_limit.MEMORY_LIMIT_ENV} is set in the environment Unsloth runs in, which decides this.",+ )+ if sys.platform != "win32" and (windows_fields or payload.memory_limit_gb is None):raise HTTPException(status_code = 409, detail = "These settings only apply on Windows.")locks = ((payload.allow_dacl_fallback, mxc_policy.DACL_FALLBACK_ENV),@@ -5123,10 +5177,11 @@ async def update_sandbox_settings(log = logger,) from exclogger.info(- "settings.sandbox_updated subject=%s dacl=%s grants=%s",+ "settings.sandbox_updated subject=%s dacl=%s grants=%s memory_gb=%s",current_subject,payload.allow_dacl_fallback,payload.persistent_read_grants,+ payload.memory_limit_gb,)status = await asyncio.to_thread(_for_request, status, request)return status.model_copy(update = {"grants_restored": restored})diff --git a/studio/backend/tests/test_sandbox_memory_limit.py b/studio/backend/tests/test_sandbox_memory_limit.pynew file mode 100644index 00000000000..cb139747ec0--- /dev/null+++ b/studio/backend/tests/test_sandbox_memory_limit.py@@ -0,0 +1,72 @@+# 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 memory limit: env first, then the owner's saved value, then 8 GiB."""++from pathlib import Path+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 storage import studio_db+from utils import sandbox_memory_limit as limit+from utils.account_context import AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+GIB = 1024**3++[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(limit.MEMORY_LIMIT_ENV, raising = False)+++def test_default_is_eight_gib():+ assert limit.saved_memory_limit_gb() == 8+ assert limit.memory_limit_bytes() == 8 * GIB+++def test_a_saved_value_applies_and_saving_again_is_a_no_op():+ for _ in range(2):+ assert limit.set_memory_limit_gb(32) == 32+ assert limit.memory_limit_bytes() == 32 * GIB+++ "value, expected",+ [("16", 16 * GIB), ("abc", None), ("16.5", None)],+)+def test_a_present_environment_variable_decides_as_before(monkeypatch, value, expected):+ limit.set_memory_limit_gb(32)+ monkeypatch.setenv(limit.MEMORY_LIMIT_ENV, value)+ assert limit.locked_by_environment() is True+ assert limit.memory_limit_bytes() == expected++[email protected]("value", [0, 4097, True, None, "x"])+def test_setter_rejects_out_of_range(value):+ with pytest.raises(ValueError):+ limit.set_memory_limit_gb(value)+++def test_an_unreadable_store_keeps_the_default(monkeypatch):+ def boom(*_args, **_kwargs):+ raise RuntimeError("database is locked")++ monkeypatch.setattr(studio_db, "get_app_setting", boom)+ assert limit.memory_limit_bytes() == 8 * GIB+++def test_a_managed_account_reads_the_owner_value():+ limit.set_memory_limit_gb(24)+ token = bind_account(ALICE)+ try:+ assert limit.memory_limit_bytes() == 24 * GIB+ finally:+ reset_account(token)diff --git a/studio/backend/tests/test_sandbox_settings_route.py b/studio/backend/tests/test_sandbox_settings_route.pyindex cc2d1223053..190a5ff4249 100644--- a/studio/backend/tests/test_sandbox_settings_route.py+++ b/studio/backend/tests/test_sandbox_settings_route.py@@ -403,3 +403,89 @@ def test_a_status_built_before_a_save_is_not_cached(host, windows, monkeypatch):monkeypatch.setattr(settings, "_build_sandbox_status", build_then_save)settings._sandbox_status()assert settings._sandbox_status_cache is None+++def memory(monkeypatch):+ from utils import sandbox_memory_limit++ stored = {}+ monkeypatch.delenv(sandbox_memory_limit.MEMORY_LIMIT_ENV, raising = False)+ monkeypatch.setattr(+ sandbox_memory_limit,+ "saved_memory_limit_gb",+ lambda: stored.get("gb", sandbox_memory_limit.DEFAULT_MEMORY_LIMIT_GB),+ )+ monkeypatch.setattr(+ sandbox_memory_limit, "set_memory_limit_gb", lambda v: stored.__setitem__("gb", v)+ )+ return stored+++def test_posix_status_carries_the_memory_limit(host, posix, memory):+ with _client(OWNER) as client:+ body = client.get("/sandbox").json()+ assert body["memory"] == {+ "limit_gb": 8,+ "saved_gb": 8,+ "default_gb": 8,+ "min_gb": 1,+ "max_gb": 4096,+ "locked_by_environment": False,+ }+++def test_saving_the_memory_limit_shows_at_once_and_repeats_cleanly(host, posix, memory):+ calls, _saved = host+ with _client(OWNER) as client:+ client.get("/sandbox")+ for _ in range(2):+ response = client.put("/sandbox", json = {"memory_limit_gb": 32})+ assert response.status_code == 200, response.text+ assert response.json()["memory"]["limit_gb"] == 32+ assert client.get("/sandbox").json()["memory"]["saved_gb"] == 32+ assert memory == {"gb": 32}+ # Memory-only saves never touch the Windows MXC state.+ assert calls["invalidate"] == 0 and calls["revoke"] == 0+++def test_the_memory_limit_env_var_wins_and_refuses_a_save(host, posix, memory, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_AS_GB", "16")+ with _client(OWNER) as client:+ body = client.get("/sandbox").json()["memory"]+ assert body["limit_gb"] == 16 and body["locked_by_environment"] is True+ response = client.put("/sandbox", json = {"memory_limit_gb": 32})+ assert response.status_code == 409+ assert "UNSLOTH_STUDIO_SANDBOX_AS_GB" in response.json()["detail"]+ assert memory == {}++[email protected]("value", [0, 4097, "16", 1.5, True])+def test_out_of_range_memory_limits_are_refused(host, posix, memory, value):+ with _client(OWNER) as client:+ assert client.put("/sandbox", json = {"memory_limit_gb": value}).status_code == 422+ assert memory == {}+++def test_the_memory_limit_is_owner_and_ui_session_only(host, posix, memory):+ with _client(ALICE) as client:+ assert client.put("/sandbox", json = {"memory_limit_gb": 32}).status_code == 403+ with _client(OWNER, via_api_key = True) as client:+ assert client.put("/sandbox", json = {"memory_limit_gb": 32}).status_code == 403+ assert memory == {}++[email protected]("platform", ["win32", "darwin"])+def test_only_linux_has_the_memory_limit(host, memory, monkeypatch, platform):+ monkeypatch.setattr(sys, "platform", platform)+ with _client(OWNER) as client:+ assert client.get("/sandbox").json()["memory"] is None+ assert client.put("/sandbox", json = {"memory_limit_gb": 32}).status_code == 409+ assert memory == {}+++def test_an_empty_windows_save_still_resets_every_cache(host, windows, memory):+ calls, _saved = host+ with _client(OWNER) as client:+ assert client.put("/sandbox", json = {}).status_code == 200+ assert calls["invalidate"] == 1 and calls["profile_reset"] == 1diff --git a/studio/backend/tests/test_tool_sandbox_wiring.py b/studio/backend/tests/test_tool_sandbox_wiring.pyindex 4a0d592714a..c0ad1ec0065 100644--- a/studio/backend/tests/test_tool_sandbox_wiring.py+++ b/studio/backend/tests/test_tool_sandbox_wiring.py@@ -881,3 +881,34 @@ def test_a_stop_during_the_sandbox_probe_reads_as_a_cancel(monkeypatch, executordef test_an_approved_ansi_c_quoted_host_path_is_recognised(command):"""The approval classifier decodes $'...' and prompts; the reach check must agree, or the approved call stays jailed."""assert tools._reaches_host_paths("terminal", command)++[email protected](sys.platform != "linux", reason = "the cap only applies on Linux")+ "env, saved, expected",+ [+ (None, None, 8),+ (None, 24, 24),+ ("12", 24, 12),+ ],+ ids = ["default", "saved", "env-wins"],+)+def test_a_sandboxed_run_gets_the_configured_memory_limit(monkeypatch, env, saved, expected):+ from utils import sandbox_memory_limit++ if env is None:+ monkeypatch.delenv(sandbox_memory_limit.MEMORY_LIMIT_ENV, raising = False)+ else:+ monkeypatch.setenv(sandbox_memory_limit.MEMORY_LIMIT_ENV, env)+ monkeypatch.setattr(+ sandbox_memory_limit,+ "saved_memory_limit_gb",+ lambda: saved or sandbox_memory_limit.DEFAULT_MEMORY_LIMIT_GB,+ )+ code = "import resource\nprint('AS', resource.getrlimit(resource.RLIMIT_AS)[0])"+ for out in (+ tools._python_exec(code, None, 60, _SESSION),+ tools._bash_exec(f"python3 -c \"{code.replace(chr(10), ';')}\"", None, 60, _SESSION),+ ):+ lines = dict(line.split(" ", 1) for line in out.splitlines() if line.startswith("AS "))+ assert int(lines["AS"]) == expected * 1024**3, outdiff --git a/studio/backend/utils/sandbox_memory_limit.py b/studio/backend/utils/sandbox_memory_limit.pynew file mode 100644index 00000000000..2b8237a81d7--- /dev/null+++ b/studio/backend/utils/sandbox_memory_limit.py@@ -0,0 +1,72 @@+# 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 memory limit (RLIMIT_AS) for sandboxed Python and Terminal runs; a present env var always wins."""++from __future__ import annotations++import os+from typing import Any++MEMORY_LIMIT_ENV = "UNSLOTH_STUDIO_SANDBOX_AS_GB"+MEMORY_LIMIT_SETTING_KEY = "sandbox_memory_limit_gb"+DEFAULT_MEMORY_LIMIT_GB = 8+MIN_MEMORY_LIMIT_GB = 1+MAX_MEMORY_LIMIT_GB = 4096+_BYTES_PER_GB = 1024 * 1024 * 1024+++def _coerce_gb(value: Any) -> int | None:+ if isinstance(value, bool):+ return None+ try:+ parsed = int(value)+ except (TypeError, ValueError):+ return None+ if parsed < MIN_MEMORY_LIMIT_GB or parsed > MAX_MEMORY_LIMIT_GB:+ return None+ return parsed+++def locked_by_environment() -> bool:+ return MEMORY_LIMIT_ENV in os.environ+++def saved_memory_limit_gb() -> int:+ try:+ from storage.studio_db import get_app_setting+ 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_setting, MEMORY_LIMIT_SETTING_KEY, None)+ except Exception: # noqa: BLE001 - an unreadable store keeps the shipped default+ stored = None+ return _coerce_gb(stored) or DEFAULT_MEMORY_LIMIT_GB+++def effective_memory_limit_gb() -> int | None:+ """GiB the next sandboxed run is capped at; None = no cap (an env value int() rejects, as before)."""+ if locked_by_environment():+ try:+ return int(os.environ[MEMORY_LIMIT_ENV])+ except ValueError:+ return None+ return saved_memory_limit_gb()+++def memory_limit_bytes() -> int | None:+ gb = effective_memory_limit_gb()+ return None if gb is None else gb * _BYTES_PER_GB+++def set_memory_limit_gb(value: Any) -> int:+ parsed = _coerce_gb(value)+ if parsed is None:+ raise ValueError(+ f"Memory limit must be a whole number from {MIN_MEMORY_LIMIT_GB} to {MAX_MEMORY_LIMIT_GB} GB."+ )+ from storage.studio_db import upsert_app_settings+ from utils.account_context import OWNER, run_as++ run_as(OWNER, upsert_app_settings, {MEMORY_LIMIT_SETTING_KEY: parsed})+ return parseddiff --git a/studio/frontend/src/features/settings/api/sandbox-isolation.ts b/studio/frontend/src/features/settings/api/sandbox-isolation.tsindex d723a7972ea..ad17a0c7c34 100644--- a/studio/frontend/src/features/settings/api/sandbox-isolation.ts+++ b/studio/frontend/src/features/settings/api/sandbox-isolation.ts@@ -47,12 +47,24 @@ export type SandboxSetupPlan = {canRun: boolean;};+// null off Linux and on backends without the setting.+export type SandboxMemoryStatus = {+ // null: no cap.+ limitGb: number | null;+ savedGb: number;+ defaultGb: number;+ minGb: number;+ maxGb: number;+ lockedByEnvironment: boolean;+};+export type SandboxStatus = {platform: string;python: SandboxToolStatus;terminal: SandboxToolStatus;terminalShell: TerminalShell | null;windows: WindowsSandboxStatus | null;+ memory: SandboxMemoryStatus | null;setup: SandboxSetupPlan | null;checkedAt: number;restored?: number;@@ -61,6 +73,7 @@ export type SandboxStatus = {export type SandboxSettingsUpdate = {allowDaclFallback?: boolean;persistentReadGrants?: boolean;+ memoryLimitGb?: number;};export type HostPrepState =@@ -125,6 +138,21 @@ type ApiWindowsStatus = {builtin_container?: boolean | null;};+type ApiMemoryStatus = {+ // biome-ignore lint/style/useNamingConvention: API schema+ limit_gb?: number | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ saved_gb?: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ default_gb?: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ min_gb?: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ max_gb?: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ locked_by_environment?: boolean;+};+type ApiSandboxStatus = {platform?: string;python?: ApiToolStatus;@@ -132,6 +160,7 @@ type ApiSandboxStatus = {// biome-ignore lint/style/useNamingConvention: API schematerminal_shell?: TerminalShell | null;windows?: ApiWindowsStatus | null;+ memory?: ApiMemoryStatus | null;setup?: ApiSetupPlan | null;// biome-ignore lint/style/useNamingConvention: API schemachecked_at?: number;@@ -205,6 +234,20 @@ function windowsFromApi(};}+function memoryFromApi(+ memory: ApiMemoryStatus | null | undefined,+): SandboxMemoryStatus | null {+ if (!memory || typeof memory.saved_gb !== "number") return null;+ return {+ limitGb: memory.limit_gb ?? null,+ savedGb: memory.saved_gb,+ defaultGb: memory.default_gb ?? 8,+ minGb: memory.min_gb ?? 1,+ maxGb: memory.max_gb ?? 4096,+ lockedByEnvironment: memory.locked_by_environment ?? false,+ };+}+export function statusFromApi(status: ApiSandboxStatus): SandboxStatus {const out: SandboxStatus = {platform: status.platform ?? "",@@ -212,6 +255,7 @@ export function statusFromApi(status: ApiSandboxStatus): SandboxStatus {terminal: toolFromApi(status.terminal),terminalShell: status.terminal_shell ?? null,windows: windowsFromApi(status.windows),+ memory: memoryFromApi(status.memory),setup: setupFromApi(status.setup),checkedAt: status.checked_at ?? 0,};@@ -259,13 +303,16 @@ export async function updateSandboxSettings(update: SandboxSettingsUpdate,fallbackMessage: string,): Promise<SandboxStatus> {- const body: Record<string, boolean> = {};+ const body: Record<string, boolean | number> = {};if (update.allowDaclFallback !== undefined) {body.allow_dacl_fallback = update.allowDaclFallback;}if (update.persistentReadGrants !== undefined) {body.persistent_read_grants = update.persistentReadGrants;}+ if (update.memoryLimitGb !== undefined) {+ body.memory_limit_gb = update.memoryLimitGb;+ }const res = await authFetch(ROUTE, {method: "PUT",headers: { "Content-Type": "application/json" },diff --git a/studio/frontend/src/features/settings/tabs/sandbox-tab.tsx b/studio/frontend/src/features/settings/tabs/sandbox-tab.tsxindex 0cc84af9fe5..880eaaa6edf 100644--- a/studio/frontend/src/features/settings/tabs/sandbox-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/sandbox-tab.tsx@@ -3,6 +3,7 @@import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";import { Spinner } from "@/components/ui/spinner";import { Switch } from "@/components/ui/switch";import { useIsAccountOwner } from "@/features/auth";@@ -30,6 +31,7 @@ import { useCallback, useEffect, useId, useRef, useState } from "react";import { toast } from "sonner";import {type HostPrepJob,+ type SandboxMemoryStatus,type SandboxSettingsUpdate,type SandboxStatus,type SandboxToolStatus,@@ -113,6 +115,98 @@ function ToolRow({);}+function MemoryLimitRow({+ memory,+ saving,+ error,+ onSave,+}: {+ memory: SandboxMemoryStatus;+ saving: boolean;+ error: string | null;+ onSave: (memoryLimitGb: number) => void;+}) {+ const t = useT();+ const shown = memory.lockedByEnvironment ? memory.limitGb : memory.savedGb;+ const [draft, setDraft] = useState(shown === null ? "" : String(shown));+ const [invalid, setInvalid] = useState(false);+ const submit = () => {+ const value = Number(draft.trim());+ if (+ !Number.isInteger(value) ||+ value < memory.minGb ||+ value > memory.maxGb+ ) {+ setInvalid(true);+ return;+ }+ setInvalid(false);+ if (value !== memory.savedGb) onSave(value);+ };+ const note = memory.lockedByEnvironment+ ? t("settings.sandbox.memoryLocked")+ : invalid+ ? t("settings.sandbox.memoryInvalid", {+ min: String(memory.minGb),+ max: String(memory.maxGb),+ })+ : error;+ return (+ <SettingsRow+ label={t("settings.sandbox.memoryLabel")}+ description={t("settings.sandbox.memoryDescription", {+ defaultSize: String(memory.defaultGb),+ })}+ below={+ note ? (+ <span+ className={cn(+ NOTE_CLASS,+ memory.lockedByEnvironment+ ? "text-muted-foreground"+ : "text-destructive",+ )}+ >+ {note}+ </span>+ ) : null+ }+ >+ <div className="flex items-center gap-2">+ <div className="flex items-center gap-1.5">+ <Input+ type="number"+ min={memory.minGb}+ max={memory.maxGb}+ step={1}+ value={draft}+ disabled={memory.lockedByEnvironment}+ aria-label={t("settings.sandbox.memoryLabel")}+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") submit();+ }}+ className="h-8 w-24"+ />+ <span className="text-xs font-medium text-muted-foreground">+ GB+ </span>+ </div>+ {memory.lockedByEnvironment ? null : (+ <Button+ variant="outline"+ size="sm"+ disabled={saving}+ onClick={submit}+ >+ {saving ? t("common.saving") : t("common.save")}+ </Button>+ )}+ </div>+ </SettingsRow>+ );+}+const SANDBOX_LEVEL_TEXT = {off: { name: "settings.sandbox.levelOff", detail: "settings.sandbox.levelFullAccessNote" },low: { name: "settings.sandbox.levelLow", detail: "settings.sandbox.levelLowDetail" },@@ -645,6 +739,16 @@ function OsSandboxSections() {</div></SettingsRow>) : null}+ {status.memory ? (+ <MemoryLimitRow+ // A saved or reloaded value resets the draft.+ key={`${status.memory.savedGb}:${status.memory.limitGb}`}+ memory={status.memory}+ saving={saving}+ error={actionError}+ onSave={(memoryLimitGb) => void save({ memoryLimitGb })}+ />+ ) : null}</>) : null}{error ? (diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 7cddf749b77..592c9e89a28 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -1190,6 +1190,10 @@ export const ar = {grantsLabel: "بدء أسرع للأدوات",grantsDescription: "يحتفظ بوصول للقراءة فقط إلى مجلدات بيئة التشغيل الخاصة بـ Unsloth بين الاستدعاءات. عند إيقافه، يبدأ كل استدعاء أبطأ ببضع ثوانٍ.",lockedGrants: "مضبوط بواسطة UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ memoryLabel: "حد الذاكرة",+ memoryDescription: "أقصى قدر من الذاكرة يمكن لاستدعاء Python أو Terminal واحد داخل وضع الحماية حجزه. يسري من الاستدعاء التالي. القيمة الافتراضية {defaultSize} GB.",+ memoryLocked: "مضبوط بواسطة UNSLOTH_STUDIO_SANDBOX_AS_GB",+ memoryInvalid: "أدخل عددًا صحيحًا من {min} إلى {max}.",restored: "تمت إزالة الوصول من المجلدات: {count}.",hostPrepLabel: "إعداد المسؤول",prepPrepared: "تم",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 51ff2854199..835ff07ab0b 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -1194,6 +1194,10 @@ export const de = {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",+ memoryLabel: "Speicherlimit",+ memoryDescription: "Maximaler Speicher, den ein Python- oder Terminal-Aufruf in der Sandbox reservieren kann. Gilt ab dem nächsten Aufruf. Standard ist {defaultSize} GB.",+ memoryLocked: "Festgelegt durch UNSLOTH_STUDIO_SANDBOX_AS_GB",+ memoryInvalid: "Gib eine ganze Zahl von {min} bis {max} ein.",restored: "Zugriff auf {count} Ordner entfernt.",hostPrepLabel: "Administrator-Einrichtung",prepPrepared: "Erledigt",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex c8a1274d869..bc147dba920 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -1273,6 +1273,10 @@ export const en = {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",+ memoryLabel: "Memory limit",+ memoryDescription: "Most memory one sandboxed Python or Terminal call can reserve. Applies from the next call. Default is {defaultSize} GB.",+ memoryLocked: "Set by UNSLOTH_STUDIO_SANDBOX_AS_GB",+ memoryInvalid: "Enter a whole number from {min} to {max}.",restored: "Removed access from {count} folders.",hostPrepLabel: "Administrator setup",prepPrepared: "Done",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex d99a48107fd..c3fb43e094c 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -1193,6 +1193,10 @@ export const es = {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",+ memoryLabel: "Límite de memoria",+ memoryDescription: "Memoria máxima que puede reservar una llamada de Python o Terminal en el sandbox. Se aplica desde la próxima llamada. El valor predeterminado es {defaultSize} GB.",+ memoryLocked: "Definido por UNSLOTH_STUDIO_SANDBOX_AS_GB",+ memoryInvalid: "Introduce un número entero de {min} a {max}.",restored: "Se quitó el acceso a {count} carpetas.",hostPrepLabel: "Configuración de administrador",prepPrepared: "Listo",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex c3cf1eed601..432fa72f9f9 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -1194,6 +1194,10 @@ export const fr = {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",+ memoryLabel: "Limite de mémoire",+ memoryDescription: "Mémoire maximale qu'un appel Python ou Terminal dans le sandbox peut réserver. S'applique dès le prochain appel. La valeur par défaut est {defaultSize} Go.",+ memoryLocked: "Défini par UNSLOTH_STUDIO_SANDBOX_AS_GB",+ memoryInvalid: "Saisissez un nombre entier de {min} à {max}.",restored: "Accès retiré pour {count} dossiers.",hostPrepLabel: "Configuration administrateur",prepPrepared: "Terminé",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 0b563a29759..c8c90606f25 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -1280,6 +1280,10 @@ export const he = {grantsDescription:"שומר גישת קריאה בלבד לתיקיות זמן הריצה של Unsloth בין קריאות. כשהאפשרות כבויה, כל קריאה מתחילה כמה שניות לאט יותר.",lockedGrants: "הוגדר על ידי UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ memoryLabel: "מגבלת זיכרון",+ memoryDescription: "הזיכרון המרבי שקריאת Python או Terminal אחת בארגז החול יכולה לשריין. חל מהקריאה הבאה. ברירת המחדל היא {defaultSize} GB.",+ memoryLocked: "הוגדר על ידי UNSLOTH_STUDIO_SANDBOX_AS_GB",+ memoryInvalid: "יש להזין מספר שלם מ-{min} עד {max}.",restored: "הגישה הוסרה מ-{count} תיקיות.",hostPrepLabel: "הגדרת מנהל מערכת",prepPrepared: "בוצע",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 8d3136a9752..b5475358768 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -1193,6 +1193,10 @@ export const hi = {grantsLabel: "टूल तेज़ी से शुरू करें",grantsDescription: "कॉल के बीच Unsloth के अपने रनटाइम फ़ोल्डरों पर केवल-पढ़ने की पहुँच बनाए रखता है। बंद होने पर हर कॉल कुछ सेकंड धीमी शुरू होती है।",lockedGrants: "UNSLOTH_MXC_PERSISTENT_READ_GRANTS द्वारा सेट",+ memoryLabel: "मेमोरी सीमा",+ memoryDescription: "सैंडबॉक्स में एक Python या Terminal कॉल अधिकतम कितनी मेमोरी आरक्षित कर सकती है। अगली कॉल से लागू होता है। डिफ़ॉल्ट {defaultSize} GB है।",+ memoryLocked: "UNSLOTH_STUDIO_SANDBOX_AS_GB द्वारा सेट",+ memoryInvalid: "{min} से {max} तक की पूर्ण संख्या दर्ज करें।",restored: "{count} फ़ोल्डरों से पहुँच हटाई गई।",hostPrepLabel: "व्यवस्थापक सेटअप",prepPrepared: "पूरा हुआ",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 66b90b563ae..5cd58fd46ac 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1150,6 +1150,10 @@ export const it = {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",+ memoryLabel: "Limite di memoria",+ memoryDescription: "Memoria massima che una chiamata Python o Terminale nella sandbox può riservare. Si applica dalla prossima chiamata. Il valore predefinito è {defaultSize} GB.",+ memoryLocked: "Impostato da UNSLOTH_STUDIO_SANDBOX_AS_GB",+ memoryInvalid: "Inserisci un numero intero da {min} a {max}.",restored: "Accesso rimosso da {count} cartelle.",hostPrepLabel: "Configurazione amministratore",prepPrepared: "Fatto",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex f1f5e6f71b7..c9d5b6a52f9 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -1192,6 +1192,10 @@ export const ja = {grantsLabel: "ツールの起動を高速化",grantsDescription: "Unsloth 自身のランタイムフォルダーへの読み取り専用アクセスを呼び出し間で保持します。オフにすると、各呼び出しの起動が数秒遅くなります。",lockedGrants: "UNSLOTH_MXC_PERSISTENT_READ_GRANTS で設定されています",+ memoryLabel: "メモリ上限",+ memoryDescription: "サンドボックス内の Python または Terminal の 1 回の呼び出しが確保できるメモリの上限です。次の呼び出しから適用されます。既定値は {defaultSize} GB です。",+ memoryLocked: "UNSLOTH_STUDIO_SANDBOX_AS_GB で設定されています",+ memoryInvalid: "{min} から {max} までの整数を入力してください。",restored: "{count} 個のフォルダーからアクセスを削除しました。",hostPrepLabel: "管理者による設定",prepPrepared: "完了",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 3f8cd85e3c5..5f3fce84b67 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -1190,6 +1190,10 @@ export const ko = {grantsLabel: "더 빠른 도구 시작",grantsDescription: "호출 사이에 Unsloth 자체 런타임 폴더에 대한 읽기 전용 액세스를 유지합니다. 끄면 각 호출이 몇 초 더 느리게 시작됩니다.",lockedGrants: "UNSLOTH_MXC_PERSISTENT_READ_GRANTS로 설정됨",+ memoryLabel: "메모리 한도",+ memoryDescription: "샌드박스에서 Python 또는 Terminal 호출 한 번이 예약할 수 있는 최대 메모리입니다. 다음 호출부터 적용됩니다. 기본값은 {defaultSize} GB입니다.",+ memoryLocked: "UNSLOTH_STUDIO_SANDBOX_AS_GB로 설정됨",+ memoryInvalid: "{min}에서 {max} 사이의 정수를 입력하세요.",restored: "폴더 {count}개에서 액세스를 제거했습니다.",hostPrepLabel: "관리자 설정",prepPrepared: "완료",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex f36e06e8fed..2a7d9eb9f4a 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -1192,6 +1192,10 @@ export const ptBR = {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",+ memoryLabel: "Limite de memória",+ memoryDescription: "Memória máxima que uma chamada de Python ou Terminal no sandbox pode reservar. Vale a partir da próxima chamada. O padrão é {defaultSize} GB.",+ memoryLocked: "Definido por UNSLOTH_STUDIO_SANDBOX_AS_GB",+ memoryInvalid: "Digite um número inteiro de {min} a {max}.",restored: "Acesso removido de {count} pastas.",hostPrepLabel: "Configuração de administrador",prepPrepared: "Concluído",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex a1322609374..e5d7f10d622 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -1192,6 +1192,10 @@ export const ru = {grantsLabel: "Более быстрый запуск инструментов",grantsDescription: "Сохраняет доступ только для чтения к собственным папкам среды Unsloth между вызовами. Если выключено, каждый вызов запускается на несколько секунд дольше.",lockedGrants: "Задано через UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ memoryLabel: "Лимит памяти",+ memoryDescription: "Максимальный объём памяти, который может зарезервировать один вызов Python или Terminal в песочнице. Действует со следующего вызова. По умолчанию {defaultSize} ГБ.",+ memoryLocked: "Задано через UNSLOTH_STUDIO_SANDBOX_AS_GB",+ memoryInvalid: "Введите целое число от {min} до {max}.",restored: "Доступ удалён для папок: {count}.",hostPrepLabel: "Настройка администратора",prepPrepared: "Готово",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex a4a3ee8d44e..e66ced3e1e7 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -1309,6 +1309,10 @@ export const sv = {grantsDescription:"Behåller läsåtkomst till Unsloths egna körmiljömappar mellan anrop. När det är av startar varje anrop några sekunder långsammare.",lockedGrants: "Inställt av UNSLOTH_MXC_PERSISTENT_READ_GRANTS",+ memoryLabel: "Minnesgräns",+ memoryDescription: "Mest minne som ett Python- eller Terminal-anrop i sandlådan kan reservera. Gäller från nästa anrop. Standard är {defaultSize} GB.",+ memoryLocked: "Inställt av UNSLOTH_STUDIO_SANDBOX_AS_GB",+ memoryInvalid: "Ange ett heltal från {min} till {max}.",restored: "Tog bort åtkomst från {count} mappar.",hostPrepLabel: "Administratörskonfiguration",prepPrepared: "Klar",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 4c56800287d..bfed2c89648 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -1188,6 +1188,10 @@ export const zhCN = {grantsLabel: "更快启动工具",grantsDescription: "在调用之间保留对 Unsloth 自身运行时文件夹的只读访问。关闭后,每次调用的启动会慢几秒。",lockedGrants: "由 UNSLOTH_MXC_PERSISTENT_READ_GRANTS 设置",+ memoryLabel: "内存上限",+ memoryDescription: "沙盒中单次 Python 或 Terminal 调用可预留的最大内存。从下一次调用起生效。默认值为 {defaultSize} GB。",+ memoryLocked: "由 UNSLOTH_STUDIO_SANDBOX_AS_GB 设置",+ memoryInvalid: "请输入 {min} 到 {max} 之间的整数。",restored: "已移除 {count} 个文件夹的访问权限。",hostPrepLabel: "管理员设置",prepPrepared: "已完成",diff --git a/studio/frontend/tests/sandbox-settings-api.test.ts b/studio/frontend/tests/sandbox-settings-api.test.tsindex 1a3cc10f918..0b7df8d30e0 100644--- a/studio/frontend/tests/sandbox-settings-api.test.ts+++ b/studio/frontend/tests/sandbox-settings-api.test.ts@@ -12,7 +12,7 @@ type Api = {fallback: string,) => Promise<Record<string, unknown>>;updateSandboxSettings: (- update: Record<string, boolean>,+ update: Record<string, boolean | number>,fallback: string,) => Promise<Record<string, unknown>>;startHostPreparation: (fallback: string) => Promise<Record<string, unknown>>;@@ -126,6 +126,7 @@ test("the status maps to camelCase and keeps the saved and effective values apar// An older server does not say which MXC tier runs.builtinContainer: null,},+ memory: null,setup: null,checkedAt: 12,});@@ -223,6 +224,60 @@ test("a non-Windows status has no Windows block and a plain load skips refresh",assert.equal(status.terminalShell, null);});+test("the memory limit maps to camelCase, and an older backend without it maps to null", async () => {+ const linux = {+ platform: "linux",+ python: {+ backend: "bubblewrap",+ available: true,+ reason: "",+ limitations: [],+ },+ terminal: {+ backend: "bubblewrap",+ available: true,+ reason: "",+ limitations: [],+ },+ windows: null,+ checked_at: 1,+ };+ const { api } = loadApi(() =>+ json({+ ...linux,+ memory: {+ limit_gb: 16,+ saved_gb: 32,+ default_gb: 8,+ min_gb: 1,+ max_gb: 4096,+ locked_by_environment: true,+ },+ }),+ );+ assert.deepEqual((await api.loadSandboxStatus(false, "fallback")).memory, {+ limitGb: 16,+ savedGb: 32,+ defaultGb: 8,+ minGb: 1,+ maxGb: 4096,+ lockedByEnvironment: true,+ });+ const older = loadApi(() => json(linux));+ assert.equal(+ (await older.api.loadSandboxStatus(false, "fallback")).memory,+ null,+ );+});++test("a memory limit save sends only memory_limit_gb", async () => {+ const { api, calls } = loadApi(() => json(WINDOWS_STATUS));+ await api.updateSandboxSettings({ memoryLimitGb: 24 }, "fallback");+ assert.deepEqual(JSON.parse(String(calls[0].init?.body)), {+ memory_limit_gb: 24,+ });+});+test("an unknown host preparation stays null rather than reading as prepared", async () => {const { api } = loadApi(() =>json({diff --git a/studio/frontend/tests/sandbox-setup.test.ts b/studio/frontend/tests/sandbox-setup.test.tsindex 931e673a235..4149b169c55 100644--- a/studio/frontend/tests/sandbox-setup.test.ts+++ b/studio/frontend/tests/sandbox-setup.test.ts@@ -588,6 +588,7 @@ const status = (overrides: Partial<SandboxStatus> = {}): SandboxStatus => ({},terminalShell: "bash",windows: null,+ memory: null,setup: {action: "linux-install",elevation: "sudo",