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
Let idle auto-unload spare models loaded from the UI (#8146)
Daniel Han19fecfc082d2
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 3f92187a55c..2cd8a35646d 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -3334,6 +3334,11 @@ class LlamaCppBackend:# spawned, so a save landing in that window still has a launch to# compare against.self._memory_launch_pending: bool = False+ # True when the resident model came from an explicit UI load rather than+ # the OpenAI API, so the idle unload can be scoped to API-loaded models.+ # Not on GgufLoadIntent: that is compared for equality to detect+ # duplicate loads, and a provenance field there would force a reload.+ self._loaded_by_user_action: bool = Falseself._n_ubatch: int = self._DEFAULT_N_UBATCHself._flash_attn_enabled: bool = Trueself._effective_cache_types: tuple[str, str] = ("f16", "f16")@@ -13258,6 +13263,7 @@ class LlamaCppBackend:self._memory_policy_active = Falseself._memory_mlock_applicable = Trueself._memory_launch_pending = False+ self._loaded_by_user_action = Falseself._n_ubatch = self._DEFAULT_N_UBATCHself._flash_attn_enabled = Trueself._effective_cache_types = ("f16", "f16")diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.pyindex 73519a23109..b150b8f653f 100644--- a/studio/backend/core/inference/llama_keepwarm.py+++ b/studio/backend/core/inference/llama_keepwarm.py@@ -371,10 +371,17 @@ def _note_idle_unload_event(freed) -> None:async def idle_unload_loop(poll_seconds: float = 15.0) -> None:"""Unload the loaded GGUF once idle past the configured TTL. Inert when off."""from utils.openai_auto_switch_settings import (+ get_auto_unload_api_only,get_auto_unload_idle_seconds,get_auto_unload_keep_kv,)+ def _user_pinned(b) -> bool:+ """Whether the setting spares this model. Re-read like the other+ settings: a KV save can outlive the user turning this on. getattr keeps+ a foreign backend (tests, MLX) on the old unload-everything path."""+ return get_auto_unload_api_only() and getattr(b, "_loaded_by_user_action", False)+seen_model = Nonewhile True:await asyncio.sleep(poll_seconds)@@ -396,6 +403,10 @@ async def idle_unload_loop(poll_seconds: float = 15.0) -> None:if current is not None:_note_activity()_set_last_unloaded(None) # a model is loaded; drop stale stash+ if backend.is_loaded and _user_pinned(backend):+ # Loaded from the UI, so the user wants it resident; only+ # models the API loaded are freed.+ continueif backend.is_loaded and _is_idle(ttl):freed = _loaded_identity(backend)manifest = None@@ -409,7 +420,7 @@ async def idle_unload_loop(poll_seconds: float = 15.0) -> None:logger.debug("slot save before idle unload failed: %s", exc)# Re-read settings: the save can outlive a settings change.ttl = get_auto_unload_idle_seconds()- if ttl <= 0 or not _is_idle(ttl):+ if ttl <= 0 or not _is_idle(ttl) or _user_pinned(backend):if manifest:_delete_resume_files(manifest)continuediff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex abed1a7d405..5ff81cc050e 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -5214,6 +5214,9 @@ async def _maybe_auto_switch_model(# Advertise the repo id (not the concrete load path) as the loaded# model's public id and override key for /v1/models and idle stash.get_llama_cpp_backend()._openai_advertised_id = override_id+ # API provenance: idle auto-unload may free this one even when+ # scoped to API loads.+ get_llama_cpp_backend()._loaded_by_user_action = Falsefinally:# Deregister before releasing the gate: otherwise a swap on another# loop counts this finished request as queued and unloads its model.@@ -6711,11 +6714,18 @@ async def load_model(GGUF models load via llama-server (llama.cpp) instead of Unsloth."""return await _tunnel_safe_json(- load_model_gated(request, fastapi_request, current_subject), label = "Model load"+ load_model_gated(request, fastapi_request, current_subject, user_initiated = True),+ label = "Model load",)-async def load_model_gated(request: LoadRequest, fastapi_request: Request, current_subject: str):+async def load_model_gated(+ request: LoadRequest,+ fastapi_request: Request,+ current_subject: str,+ *,+ user_initiated: bool = False,+):"""Everything ``POST /load`` does except the tunnel-safe padding.In-process callers (preview) must await THIS, not the route: the route's slow@@ -6737,7 +6747,7 @@ async def load_model_gated(request: LoadRequest, fastapi_request: Request, curre_raise_if_sidecar_swap_in_progress()# The active-generation gate runs inside _load_model_impl, once it knows this is a real# reload, and still under the lifecycle gate so the check stays atomic with the teardown.- return await _load_model_impl(+ response = await _load_model_impl(request,fastapi_request,current_subject,@@ -6747,6 +6757,11 @@ async def load_model_gated(request: LoadRequest, fastapi_request: Request, currecancel = cancel,),)+ # Record provenance only once the model is resident, and here rather than+ # inside the impl so the already-loaded fast paths are covered too. Preview+ # keeps the False default: only an explicit UI load pins.+ get_llama_cpp_backend()._loaded_by_user_action = user_initiated+ return responseasync def _load_model_impl(diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 0342f166ef5..7ae08fcfefe 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -49,6 +49,7 @@ from utils.model_memory_settings import (from utils.openai_auto_switch_settings import (BATCH_SIZE_MAX,BATCH_SIZE_MIN,+ DEFAULT_AUTO_UNLOAD_API_ONLY,DEFAULT_AUTO_UNLOAD_KEEP_KV,DEFAULT_OPENAI_AUTO_DOWNLOAD_ENABLED,DEFAULT_OPENAI_AUTO_SWITCH_ENABLED,@@ -56,6 +57,7 @@ from utils.openai_auto_switch_settings import (PARALLEL_SLOTS_MAX,PARALLEL_SLOTS_MIN,cached_repo_alias_keys,+ get_auto_unload_api_only,get_auto_unload_idle_seconds,get_auto_unload_keep_kv,get_model_overrides,@@ -163,6 +165,7 @@ class OpenAIAutoSwitchPayload(BaseModel):auto_unload_idle_seconds: Optional[int] = Field(default = None, ge = 0)auto_unload_keep_kv: Optional[bool] = Noneauto_download_model: Optional[bool] = None+ auto_unload_api_only: Optional[bool] = Noneclass OpenAIAutoSwitchResponse(BaseModel):@@ -176,6 +179,8 @@ class OpenAIAutoSwitchResponse(BaseModel):auto_unload_keep_kv: bool = DEFAULT_AUTO_UNLOAD_KEEP_KV# Stored, not effective: the UI must round-trip the saved value across an auto-switch toggle.auto_download_model: bool = DEFAULT_OPENAI_AUTO_DOWNLOAD_ENABLED+ # When true, the idle unload spares models loaded from the UI, not just via the API.+ auto_unload_api_only: bool = DEFAULT_AUTO_UNLOAD_API_ONLY# A quant suffix, as modelOverrideKey builds it. Matched against the loader's quant pattern,@@ -489,6 +494,7 @@ def get_openai_auto_switch(idle_unload_active = get_auto_unload_idle_seconds() > 0,auto_unload_keep_kv = get_auto_unload_keep_kv(),auto_download_model = get_stored_openai_auto_download_enabled(),+ auto_unload_api_only = get_auto_unload_api_only(),)@@ -497,11 +503,12 @@ def update_openai_auto_switch(payload: OpenAIAutoSwitchPayload, current_subject: str = Depends(get_current_subject)) -> OpenAIAutoSwitchResponse:try:- enabled, idle_seconds, keep_kv, auto_download = set_openai_auto_switch(+ enabled, idle_seconds, keep_kv, auto_download, api_only = set_openai_auto_switch(payload.enabled,payload.auto_unload_idle_seconds,payload.auto_unload_keep_kv,payload.auto_download_model,+ payload.auto_unload_api_only,)except ValueError as exc:raise log_and_http_error(@@ -523,6 +530,7 @@ def update_openai_auto_switch(idle_unload_active = idle_unload_active,auto_unload_keep_kv = keep_kv,auto_download_model = auto_download,+ auto_unload_api_only = api_only,)diff --git a/studio/backend/tests/test_openai_auto_download.py b/studio/backend/tests/test_openai_auto_download.pyindex 027df84e369..2b12418d74b 100644--- a/studio/backend/tests/test_openai_auto_download.py+++ b/studio/backend/tests/test_openai_auto_download.py@@ -1082,7 +1082,7 @@ def test_setter_round_trips_auto_download_in_one_transaction(monkeypatch):monkeypatch.setattr(settings, "_cached_setting", lambda k, d = None: store.get(k, d))result = settings.set_openai_auto_switch(True, 120, None, True)- assert result == (True, 120, True, True)+ assert result == (True, 120, True, True, False)assert len(calls) == 1assert calls[0][settings.OPENAI_AUTO_DOWNLOAD_SETTING_KEY] is Truediff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex b7066467acc..e9ea88b2101 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -37,6 +37,7 @@ class _FakeBackend:effective_parallel_slots = 1_slot_save_binary = None_gguf_path = None+ _loaded_by_user_action = Falsedef __init__(self,@@ -627,7 +628,7 @@ def test_disabling_idle_unload_purges_saved_kv(monkeypatch, tmp_path):"slots": [{"id": 0, "filename": saved.name}],}monkeypatch.setattr(- settings_route, "set_openai_auto_switch", lambda *a: (False, 300, True, False)+ settings_route, "set_openai_auto_switch", lambda *a: (False, 300, True, False, False))monkeypatch.setattr(settings_route, "get_auto_unload_idle_seconds", lambda: 0)@@ -652,7 +653,7 @@ def test_residency_does_not_purge_saved_kv(monkeypatch, tmp_path):}kw._kv_resume = manifestmonkeypatch.setattr(- settings_route, "set_openai_auto_switch", lambda *a: (True, 300, True, False)+ settings_route, "set_openai_auto_switch", lambda *a: (True, 300, True, False, False))monkeypatch.setattr(settings_route, "get_auto_unload_idle_seconds", lambda: 0)monkeypatch.setattr(settings_route, "idle_unload_is_configured", lambda: True)@@ -5217,11 +5218,11 @@ def test_keep_kv_only_update_leaves_env_idle_ttl_active(monkeypatch):monkeypatch.setenv(settings.MODEL_IDLE_TTL_ENV_VAR, "600")assert settings_route.OpenAIAutoSwitchPayload(enabled = False).auto_unload_idle_seconds is None- enabled, idle, keep_kv, auto_dl = settings.set_openai_auto_switch(False, None, False)+ enabled, idle, keep_kv, auto_dl, api_only = settings.set_openai_auto_switch(False, None, False)assert settings.AUTO_UNLOAD_IDLE_SETTING_KEY not in store # idle untouchedassert settings.OPENAI_AUTO_DOWNLOAD_SETTING_KEY not in store # nor auto-downloadassert settings.get_auto_unload_idle_seconds() == 600 # env TTL still active- assert (enabled, idle, keep_kv, auto_dl) == (False, 600, False, False)+ assert (enabled, idle, keep_kv, auto_dl, api_only) == (False, 600, False, False, False)def test_load_impl_notes_loaded_with_backend_off_loop():@@ -6936,3 +6937,161 @@ def test_mlx_kv_bits_survives_the_whole_override_projection():kwargs = settings.model_override_load_kwargs({"mlx_kv_bits": 4}, is_gguf = is_gguf)assert kwargs["mlx_kv_bits"] == 4assert LoadRequest(model_path = "unsloth/A", **kwargs).mlx_kv_bits == 4+++def _idle_backend(kw, monkeypatch, *, user_loaded):+ """A loaded, long-idle GGUF backend wired into the idle loop."""+ import time++ kw._inflight = 0+ kw._pending = 0+ kw._last_active = time.monotonic() - 3600+ kw._last_unloaded_model = None+ kw._kv_resume = None+ backend = _FakeBackend("unsloth/Idle-GGUF", hf_variant = "Q4_K_M")+ backend._loaded_by_user_action = user_loaded++ def _unload():+ backend.is_loaded = False++ backend.unload_model = _unload+ monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0.005)+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: True)+ monkeypatch.setattr(settings, "get_auto_unload_keep_kv", lambda: False)+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: backend)+ return backend+++def test_api_only_setting_roundtrip_and_default(monkeypatch):+ import storage.studio_db as db++ store = {}+ monkeypatch.setattr(db, "upsert_app_settings", lambda m: store.update(m))+ monkeypatch.setattr(settings, "_cached_setting", lambda k, d = None: store.get(k, d))++ # Off on an install that never stored it, so existing setups are unchanged.+ assert settings.get_auto_unload_api_only() is False+ assert settings.AUTO_UNLOAD_API_ONLY_SETTING_KEY not in store+ assert settings.set_openai_auto_switch(True, 60, None, None, True)[4] is True+ assert settings.get_auto_unload_api_only() is True+ # None leaves the stored value untouched (older clients can't reset it).+ assert settings.set_openai_auto_switch(True, 60, None, None, None)[4] is True+ with pytest.raises(ValueError, match = "true or false"):+ settings.set_openai_auto_switch(True, 60, None, None, "garbage")+++def test_idle_unload_still_frees_a_user_loaded_model_by_default(monkeypatch):+ # Backwards compatibility: with the toggle off, provenance changes nothing.+ from core.inference import llama_keepwarm as kw++ backend = _idle_backend(kw, monkeypatch, user_loaded = True)+ monkeypatch.setattr(settings, "get_auto_unload_api_only", lambda: False)++ _drive_idle_loop(kw)+ assert backend.is_loaded is False+++def test_api_only_spares_a_user_loaded_model_but_not_an_api_one(monkeypatch):+ from core.inference import llama_keepwarm as kw++ monkeypatch.setattr(settings, "get_auto_unload_api_only", lambda: True)++ pinned = _idle_backend(kw, monkeypatch, user_loaded = True)+ _drive_idle_loop(kw)+ assert pinned.is_loaded is True+ assert kw.get_last_unloaded_model() is None # nothing stashed either++ api_loaded = _idle_backend(kw, monkeypatch, user_loaded = False)+ _drive_idle_loop(kw)+ assert api_loaded.is_loaded is False+++def test_an_idle_restored_model_is_api_provenance(monkeypatch):+ # The restore runs through the auto-switch path, so the model it brings back+ # is unloadable again on the next idle rather than pinned forever.+ from core.inference import llama_keepwarm as kw++ monkeypatch.setattr(settings, "get_auto_unload_api_only", lambda: True)+ backend = _idle_backend(kw, monkeypatch, user_loaded = True)+ backend.is_loaded = False+ backend.model_identifier = None+ rec = _LoadRecorder(backend)+ _wire(+ monkeypatch,+ enabled = True,+ resolves_to = ("unsloth/B-GGUF", None, "unsloth/B-GGUF"),+ backend = backend,+ recorder = rec,+ )+ _run_hook("unsloth/B-GGUF")+ assert rec.calls and backend._loaded_by_user_action is False++ backend.unload_model = lambda: setattr(backend, "is_loaded", False)+ _drive_idle_loop(kw)+ assert backend.is_loaded is False+++def test_unload_clears_the_user_load_flag():+ # Otherwise the next API load inherits the pin and never frees its VRAM.+ import inspect+ from core.inference.llama_cpp import LlamaCppBackend++ backend = LlamaCppBackend()+ assert backend._loaded_by_user_action is False # off until a UI load says otherwise+ backend._loaded_by_user_action = True+ backend.unload_model()+ assert backend._loaded_by_user_action is False+ # Not cleared on a bare process kill: a respawn or MTP-free reload replays+ # the same load and must keep the provenance it had.+ assert "_loaded_by_user_action" not in inspect.getsource(LlamaCppBackend._kill_process)+++def test_the_load_route_pins_and_other_load_surfaces_do_not(monkeypatch):+ import inspect++ backend = _FakeBackend("unsloth/A-GGUF")+ backend._loaded_by_user_action = False+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: backend)++ async def _already_loaded(*_a, **_kw):+ return None # the dedupe path returns without touching the backend++ monkeypatch.setattr(inference_route, "_load_model_impl", _already_loaded)+ request = LoadRequest(model_path = "unsloth/A-GGUF")++ # An explicit UI load pins, including when it deduped onto the resident model.+ asyncio.run(inference_route.load_model_gated(request, object(), "tester", user_initiated = True))+ assert backend._loaded_by_user_action is True++ # Preview shares this helper and must not pin, so it keeps the default.+ asyncio.run(inference_route.load_model_gated(request, object(), "tester"))+ assert backend._loaded_by_user_action is False+ import routes.preview as preview_route++ assert "user_initiated" not in inspect.getsource(preview_route._serve_chat)+++def test_api_only_turned_on_mid_save_still_spares_the_model(monkeypatch, tmp_path):+ # A KV save can take seconds; the loop re-reads the TTL and keep-KV after it+ # for exactly that reason, so provenance has to be re-read there too.+ from core.inference import llama_keepwarm as kw++ on = {"now": False}+ monkeypatch.setattr(settings, "get_auto_unload_api_only", lambda: on["now"])+ backend = _idle_backend(kw, monkeypatch, user_loaded = True)+ monkeypatch.setattr(settings, "get_auto_unload_keep_kv", lambda: True)++ manifest = {"dir": str(tmp_path), "slots": [{"id": 0, "filename": "f.bin", "n_saved": 1}]}+ deleted = []+ monkeypatch.setattr(kw, "_delete_resume_files", lambda m: deleted.append(m))++ def _save(should_abort = None):+ on["now"] = True # the user flips the toggle while the save runs+ return manifest++ backend.save_slots_for_resume = _save++ _drive_idle_loop(kw)+ assert backend.is_loaded is True+ assert deleted == [manifest] # nothing was unloaded, so nothing may be stashed+ assert kw._kv_resume is Nonediff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.pyindex 8f55ca86146..c239d3dadc1 100644--- a/studio/backend/utils/openai_auto_switch_settings.py+++ b/studio/backend/utils/openai_auto_switch_settings.py@@ -36,6 +36,7 @@ OPENAI_AUTO_SWITCH_SETTING_KEY = "openai_api_auto_switch_model"OPENAI_AUTO_DOWNLOAD_SETTING_KEY = "openai_api_auto_download_model"AUTO_UNLOAD_IDLE_SETTING_KEY = "openai_api_auto_unload_idle_seconds"AUTO_UNLOAD_KEEP_KV_SETTING_KEY = "openai_api_auto_unload_keep_kv"+AUTO_UNLOAD_API_ONLY_SETTING_KEY = "openai_api_auto_unload_api_only"MODEL_OVERRIDES_SETTING_KEY = "openai_api_auto_switch_overrides"MODEL_IDLE_TTL_ENV_VAR = "UNSLOTH_MODEL_IDLE_TTL"@@ -43,6 +44,7 @@ DEFAULT_OPENAI_AUTO_SWITCH_ENABLED = FalseDEFAULT_OPENAI_AUTO_DOWNLOAD_ENABLED = FalseDEFAULT_AUTO_UNLOAD_IDLE_SECONDS = 0DEFAULT_AUTO_UNLOAD_KEEP_KV = True+DEFAULT_AUTO_UNLOAD_API_ONLY = FalseMIN_AUTO_UNLOAD_IDLE_SECONDS = 60_CACHE_TTL_S = 2.0@@ -209,12 +211,19 @@ def get_auto_unload_keep_kv() -> bool:return parsed if parsed is not None else DEFAULT_AUTO_UNLOAD_KEEP_KV+def get_auto_unload_api_only() -> bool:+ """Whether the idle unload spares models a user loaded from the UI."""+ parsed = _coerce_bool(_cached_setting(AUTO_UNLOAD_API_ONLY_SETTING_KEY, None))+ return parsed if parsed is not None else DEFAULT_AUTO_UNLOAD_API_ONLY++def set_openai_auto_switch(enabled: Any,idle_seconds: Any,keep_kv: Any = None,auto_download: Any = None,-) -> tuple[bool, int, bool, bool]:+ api_only: Any = None,+) -> tuple[bool, int, bool, bool, bool]:"""One-transaction write; ``None`` leaves a stored value untouched."""parsed_enabled = _coerce_bool(enabled)if parsed_enabled is None:@@ -239,6 +248,11 @@ def set_openai_auto_switch(parsed_auto_download = _coerce_bool(auto_download)if parsed_auto_download is None:raise ValueError("Auto-download missing models must be true or false.")+ parsed_api_only = None+ if api_only is not None:+ parsed_api_only = _coerce_bool(api_only)+ if parsed_api_only is None:+ raise ValueError("Auto-unload API-loaded only must be true or false.")from storage.studio_db import upsert_app_settingsupdates: dict[str, Any] = {OPENAI_AUTO_SWITCH_SETTING_KEY: parsed_enabled}@@ -248,6 +262,8 @@ def set_openai_auto_switch(updates[AUTO_UNLOAD_KEEP_KV_SETTING_KEY] = parsed_keep_kvif parsed_auto_download is not None:updates[OPENAI_AUTO_DOWNLOAD_SETTING_KEY] = parsed_auto_download+ if parsed_api_only is not None:+ updates[AUTO_UNLOAD_API_ONLY_SETTING_KEY] = parsed_api_onlyupsert_app_settings(updates)_invalidate(OPENAI_AUTO_SWITCH_SETTING_KEY)if parsed_idle is not None:@@ -256,6 +272,8 @@ def set_openai_auto_switch(_invalidate(AUTO_UNLOAD_KEEP_KV_SETTING_KEY)if parsed_auto_download is not None:_invalidate(OPENAI_AUTO_DOWNLOAD_SETTING_KEY)+ if parsed_api_only is not None:+ _invalidate(AUTO_UNLOAD_API_ONLY_SETTING_KEY)return (parsed_enabled,parsed_idle if parsed_idle is not None else get_stored_auto_unload_idle_seconds(),@@ -265,6 +283,7 @@ def set_openai_auto_switch(if parsed_auto_download is not Noneelse get_stored_openai_auto_download_enabled()),+ parsed_api_only if parsed_api_only is not None else get_auto_unload_api_only(),)diff --git a/studio/frontend/src/features/settings/api/openai-auto-switch.ts b/studio/frontend/src/features/settings/api/openai-auto-switch.tsindex 3a5e4c3a6ef..7b191a64853 100644--- a/studio/frontend/src/features/settings/api/openai-auto-switch.ts+++ b/studio/frontend/src/features/settings/api/openai-auto-switch.ts@@ -15,6 +15,8 @@ export type OpenAIAutoSwitchSettings = {autoUnloadKeepKv: boolean;// Fetch a GGUF named in an API request; stored independently of `enabled`, gated on it.autoDownloadModel: boolean;+ // Spare models loaded from the UI on idle unload; only free API-loaded ones.+ autoUnloadApiOnly: boolean;};type ApiOpenAIAutoSwitchSettings = {@@ -29,6 +31,8 @@ type ApiOpenAIAutoSwitchSettings = {auto_unload_keep_kv?: boolean;// biome-ignore lint/style/useNamingConvention: API schemaauto_download_model?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_unload_api_only?: boolean;};let cachedSettings: OpenAIAutoSwitchSettings | null = null;@@ -48,6 +52,7 @@ function fromApi(idleUnloadActive: settings.idle_unload_active ?? false,autoUnloadKeepKv: settings.auto_unload_keep_kv ?? true,autoDownloadModel: settings.auto_download_model ?? false,+ autoUnloadApiOnly: settings.auto_unload_api_only ?? false,};}@@ -125,6 +130,7 @@ export async function updateOpenAIAutoSwitchSettings(autoUnloadIdleSeconds?: number,autoUnloadKeepKv?: boolean,autoDownloadModel?: boolean,+ autoUnloadApiOnly?: boolean,): Promise<OpenAIAutoSwitchSettings> {// Read BEFORE the request: idleUnloadActive depends on the Model Memory// setting, so a residency write landing mid-flight makes this response stale@@ -148,6 +154,10 @@ export async function updateOpenAIAutoSwitchSettings(? {}: // biome-ignore lint/style/useNamingConvention: API schema{ auto_download_model: autoDownloadModel }),+ ...(autoUnloadApiOnly === undefined+ ? {}+ : // biome-ignore lint/style/useNamingConvention: API schema+ { auto_unload_api_only: autoUnloadApiOnly }),}),});if (!res.ok) {diff --git a/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx b/studio/frontend/src/features/settings/components/model-auto-switch-section.tsxindex bf32ce0dfcc..6d4ba81429f 100644--- a/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx+++ b/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx@@ -66,6 +66,7 @@ export function ModelAutoSwitchSection() {syncDraft = true,keepKv?: boolean,autoDownload?: boolean,+ apiOnly?: boolean,) => {setIsSaving(true);setError(null);@@ -75,6 +76,7 @@ export function ModelAutoSwitchSection() {idleSeconds,keepKv,autoDownload,+ apiOnly,);setSettings(saved);if (syncDraft) {@@ -124,6 +126,18 @@ export function ModelAutoSwitchSection() {void persist(settings.enabled, undefined, false, undefined, autoDownload);};+ const handleApiOnlyToggle = (apiOnly: boolean) => {+ if (!settings) return;+ void persist(+ settings.enabled,+ undefined,+ false,+ undefined,+ undefined,+ apiOnly,+ );+ };+return (<SettingsSection title={t("settings.general.modelAutoSwitch.sectionTitle")}><SettingsRow@@ -198,16 +212,32 @@ export function ModelAutoSwitchSection() {</div></SettingsRow>{settings?.idleUnloadActive ? (- <SettingsRow- label={t("settings.general.modelAutoSwitch.keepKv")}- description={t("settings.general.modelAutoSwitch.keepKvDescription")}- >- <Switch- checked={settings.autoUnloadKeepKv}- disabled={isSaving}- onCheckedChange={handleKeepKvToggle}- />- </SettingsRow>+ <>+ <SettingsRow+ label={t("settings.general.modelAutoSwitch.keepKv")}+ description={t(+ "settings.general.modelAutoSwitch.keepKvDescription",+ )}+ >+ <Switch+ checked={settings.autoUnloadKeepKv}+ disabled={isSaving}+ onCheckedChange={handleKeepKvToggle}+ />+ </SettingsRow>+ <SettingsRow+ label={t("settings.general.modelAutoSwitch.apiOnly")}+ description={t(+ "settings.general.modelAutoSwitch.apiOnlyDescription",+ )}+ >+ <Switch+ checked={settings.autoUnloadApiOnly}+ disabled={isSaving}+ onCheckedChange={handleApiOnlyToggle}+ />+ </SettingsRow>+ </>) : null}</SettingsSection>);diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex e98e25d808c..159474d4853 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -378,6 +378,9 @@ export const ar = {keepKv: "الاحتفاظ بسياق المحادثة عند التفريغ التلقائي بسبب الخمول",keepKvDescription:"يحفظ ذاكرة KV المؤقتة قبل التفريغ التلقائي عند الخمول، حتى لا تعيد المحادثات المستأنفة قراءة السجل. بحد أقصى 10 جيجابايت على القرص.",+ apiOnly: "تفريغ النماذج التي حمّلتها واجهة API فقط",+ apiOnlyDescription:+ "يُبقي التفريغ التلقائي عند الخمول النموذج الذي حمّلته من Studio في الذاكرة، ولا يفرّغ سوى النماذج التي حمّلها طلب عبر واجهة API.",},previewSharing: {sectionTitle: "مشاركة المعاينة",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex eed93554fc5..94f77831c4d 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -393,6 +393,9 @@ export const de = {keepKv: "Chat-Kontext beim automatischen Entladen behalten",keepKvDescription:"Speichert den KV-Cache vor dem Entladen bei Inaktivität, damit der Verlauf bei fortgesetzten Chats nicht erneut eingelesen werden muss. Bis zu 10 GB auf der Festplatte.",+ apiOnly: "Nur über die API geladene Modelle entladen",+ apiOnlyDescription:+ "Das automatische Entladen bei Inaktivität lässt ein von dir in Studio geladenes Modell im Speicher und gibt nur solche frei, die eine API-Anfrage geladen hat.",},previewSharing: {sectionTitle: "Vorschau-Freigabe",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex d2cd937582e..6f5c86fc9af 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -372,6 +372,9 @@ export const en = {keepKv: "Keep chat context across idle unload",keepKvDescription:"Save the KV cache before an idle unload so resumed chats skip re-reading history. Up to 10 GB on disk.",+ apiOnly: "Only unload models loaded by the API",+ apiOnlyDescription:+ "Idle unload leaves a model you loaded from Studio in memory, and frees only the ones an API request loaded.",},previewSharing: {sectionTitle: "Preview sharing",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 84d3c75ea57..d2f068f61ad 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -389,6 +389,9 @@ export const es = {keepKv: "Conservar el contexto del chat al liberar el modelo por inactividad",keepKvDescription:"Guarda la caché KV antes de liberar el modelo por inactividad para que los chats reanudados no vuelvan a leer el historial. Hasta 10 GB en disco.",+ apiOnly: "Liberar solo los modelos cargados por la API",+ apiOnlyDescription:+ "La liberación por inactividad mantiene en memoria el modelo que cargaste desde Studio y solo libera los que cargó una solicitud a la API.",},previewSharing: {sectionTitle: "Compartir vista previa",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 14d8d864b22..d1e670aaba8 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -392,6 +392,9 @@ export const fr = {"Conserver le contexte de la discussion après un déchargement en cas d'inactivité",keepKvDescription:"Enregistrer le cache KV avant un déchargement en cas d'inactivité, afin qu'une discussion reprise n'ait pas à relire l'historique. Jusqu'à 10 Go sur le disque.",+ apiOnly: "Décharger uniquement les modèles chargés par l'API",+ apiOnlyDescription:+ "Le déchargement en cas d'inactivité laisse en mémoire un modèle que vous avez chargé depuis Studio et ne libère que ceux chargés par une requête API.",},previewSharing: {sectionTitle: "Partage de l'aperçu",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 315a61033b2..207490fbee4 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -381,6 +381,9 @@ export const hi = {keepKv: "निष्क्रियता पर अनलोड होने के बाद भी चैट का संदर्भ बनाए रखें",keepKvDescription:"निष्क्रियता पर अनलोड होने से पहले KV कैश सहेजता है, ताकि दोबारा शुरू की गई चैट को इतिहास फिर से न पढ़ना पड़े। डिस्क पर 10 GB तक।",+ apiOnly: "केवल API द्वारा लोड किए गए मॉडल अनलोड करें",+ apiOnlyDescription:+ "निष्क्रियता पर अनलोड करते समय Studio से आपके द्वारा लोड किया गया मॉडल मेमोरी में बना रहता है, और केवल वही मॉडल हटाए जाते हैं जिन्हें किसी API अनुरोध ने लोड किया था।",},previewSharing: {sectionTitle: "पूर्वावलोकन साझाकरण",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex f8b885b8cfa..95c6ff1624d 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -360,6 +360,9 @@ export const it = {"Mantieni il contesto della chat dopo lo scaricamento dalla memoria per inattività",keepKvDescription:"Salva la cache KV prima dello scaricamento dalla memoria per inattività, così le chat riprese non rileggono la cronologia. Fino a 10 GB su disco.",+ apiOnly: "Scarica solo i modelli caricati dall'API",+ apiOnlyDescription:+ "Lo scaricamento per inattività lascia in memoria un modello caricato da te in Studio e libera solo quelli caricati da una richiesta API.",},previewSharing: {sectionTitle: "Condivisione delle anteprime",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 6dad373b012..2996b716e23 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -371,6 +371,9 @@ export const ja = {keepKv: "アイドル時の自動アンロードをまたいでチャットのコンテキストを保持",keepKvDescription:"アイドル時の自動アンロードの前に KV キャッシュを保存し、再開したチャットが履歴を読み直さずに済むようにします。ディスク使用量は最大 10 GB です。",+ apiOnly: "API が読み込んだモデルのみアンロード",+ apiOnlyDescription:+ "アイドル時の自動アンロードでは、Studio から自分で読み込んだモデルはメモリに残し、API リクエストが読み込んだモデルだけを解放します。",},previewSharing: {sectionTitle: "プレビュー共有",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex e526e89aefa..c61b5c2076c 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -375,6 +375,9 @@ export const ko = {keepKv: "유휴 해제 후에도 채팅 컨텍스트 유지",keepKvDescription:"유휴 해제 전에 KV 캐시를 저장해, 이어서 하는 채팅이 기록을 다시 읽지 않도록 합니다. 디스크를 최대 10GB 사용합니다.",+ apiOnly: "API가 불러온 모델만 해제",+ apiOnlyDescription:+ "유휴 해제 시 Studio에서 직접 불러온 모델은 메모리에 남기고, API 요청이 불러온 모델만 해제합니다.",},previewSharing: {sectionTitle: "미리보기 공유",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 97bea62facd..6d0f510e965 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -382,6 +382,9 @@ export const ptBR = {keepKv: "Manter o contexto do chat ao descarregar por inatividade",keepKvDescription:"Salva o cache KV antes de um descarregamento por inatividade, para que chats retomados não releiam o histórico. Até 10 GB em disco.",+ apiOnly: "Descarregar apenas modelos carregados pela API",+ apiOnlyDescription:+ "O descarregamento por inatividade mantém na memória o modelo que você carregou pelo Studio e libera apenas os que uma requisição da API carregou.",},previewSharing: {sectionTitle: "Compartilhamento de pré-visualização",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 8fa2576a1c3..e39bdbf087a 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -380,6 +380,9 @@ export const ru = {keepKv: "Сохранять контекст чата при автовыгрузке",keepKvDescription:"Сохраняет KV-кеш перед автовыгрузкой при простое, чтобы возобновлённые чаты не перечитывали историю. До 10 ГБ на диске.",+ apiOnly: "Выгружать только модели, загруженные через API",+ apiOnlyDescription:+ "Автовыгрузка при простое оставляет в памяти модель, которую вы загрузили в Studio, и освобождает только те, что загрузил запрос через API.",},previewSharing: {sectionTitle: "Публикация предпросмотра",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex fd4fd357041..f3e892e5839 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -362,6 +362,9 @@ export const zhCN = {keepKv: "空闲卸载后保留聊天上下文",keepKvDescription:"在空闲卸载前保存 KV 缓存,让恢复的聊天无需重新读取历史。最多占用 10 GB 磁盘空间。",+ apiOnly: "仅卸载由 API 加载的模型",+ apiOnlyDescription:+ "空闲卸载会将你在 Studio 中加载的模型保留在内存中,只释放由 API 请求加载的模型。",},previewSharing: {sectionTitle: "预览分享",diff --git a/studio/frontend/tests/auto-unload-api-only.test.ts b/studio/frontend/tests/auto-unload-api-only.test.tsnew file mode 100644index 00000000000..9e5be695497--- /dev/null+++ b/studio/frontend/tests/auto-unload-api-only.test.ts@@ -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++// The API-only toggle rides the shared auto-switch PUT, so it must round-trip+// without dragging the other switches along: an omitted field keeps its stored+// value, and a backend that predates the field must read as off, not on.++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++import { installLocalStorageFake } from "./helpers/kit.ts";++// The settings API modules reach authFetch through the auth barrel, which+// re-exports login-page.tsx. See helpers/auth-stub.mjs.+register("./helpers/settings-api-resolver.mjs", import.meta.url);+installLocalStorageFake();++const API = {+ enabled: true,+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_unload_idle_seconds: 300,+ // biome-ignore lint/style/useNamingConvention: API schema+ default_enabled: false,+ // biome-ignore lint/style/useNamingConvention: API schema+ idle_unload_active: true,+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_unload_keep_kv: true,+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_download_model: false,+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_unload_api_only: false,+};++let nextBody: Record<string, unknown> = { ...API };+const bodies: string[] = [];++globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {+ if (init?.body) bodies.push(String(init.body));+ return new Response(JSON.stringify(nextBody), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+}) as typeof fetch;++const {+ invalidateOpenAIAutoSwitchSettings,+ loadOpenAIAutoSwitchSettings,+ updateOpenAIAutoSwitchSettings,+} = await import("../src/features/settings/api/openai-auto-switch.ts");++test("a backend without the field reads as off", async () => {+ invalidateOpenAIAutoSwitchSettings();+ const { auto_unload_api_only: _omitted, ...older } = API;+ nextBody = older;+ const settings = await loadOpenAIAutoSwitchSettings();+ assert.equal(settings.autoUnloadApiOnly, false);+ nextBody = { ...API };+});++test("the toggle round-trips", async () => {+ invalidateOpenAIAutoSwitchSettings();+ nextBody = { ...API, auto_unload_api_only: true };+ const saved = await updateOpenAIAutoSwitchSettings(+ true,+ undefined,+ undefined,+ undefined,+ true,+ );+ assert.equal(saved.autoUnloadApiOnly, true);+ nextBody = { ...API };+});++test("saving it alone leaves the other switches untouched", async () => {+ invalidateOpenAIAutoSwitchSettings();+ bodies.length = 0;+ await updateOpenAIAutoSwitchSettings(+ true,+ undefined,+ undefined,+ undefined,+ true,+ );+ assert.deepEqual(JSON.parse(bodies[0] ?? "{}"), {+ enabled: true,+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_unload_api_only: true,+ });+});