Skip to content

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

Studio: bring back the scheduled task model picker and model loading (#15255)

Daniel Han136074fd4d7a
diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.py
index b496342d245..d3789f1881d 100644
--- a/studio/backend/core/inference/llama_keepwarm.py
+++ b/studio/backend/core/inference/llama_keepwarm.py
@@ -45,6 +45,11 @@ _preview_swap_generation = 0
# entry and rejects if a swap was in progress.
_preview_swap_inflight = 0
_last_active = time.monotonic()
+# _last_active minus scheduled runs and their swaps: one run must not make the next look attended.
+_last_attended = _last_active
+_unattended: contextvars.ContextVar[bool] = contextvars.ContextVar(
+ "keepwarm_unattended", default = False
+)
# The (id, quant) idle-unload last freed, so an alias/unknown request that would otherwise 503 against an empty backend
# can reload it (set on unload, cleared on reload). The quant lets the reload restore the exact freed variant.
_last_unloaded_model = None
@@ -162,11 +167,18 @@ def _note_start(is_preview: bool = False) -> None:
_preview_inflight += 1
+def _stamp_active() -> None:
+ global _last_active, _last_attended
+ _last_active = time.monotonic()
+ if not _unattended.get():
+ _last_attended = _last_active
+
+
def _note_end(is_preview: bool = False) -> None:
- global _inflight, _last_active, _preview_inflight
+ global _inflight, _preview_inflight
with _lock:
_inflight = max(0, _inflight - 1)
- _last_active = time.monotonic()
+ _stamp_active()
if is_preview:
_preview_inflight = max(0, _preview_inflight - 1)
@@ -198,13 +210,15 @@ class InferenceActivityReservation:
_note_start()
self._state = "started"
- def finish(self) -> None:
- """Balance a pending or started reservation. Idempotent."""
+ def finish(self, scope = None) -> None:
+ """Balance a pending or started reservation. Idempotent. A ``scope`` the producer already
+ untracked (an external-provider request) dropped the started count itself."""
with self._state_lock:
if self._state == "pending":
_note_unpending()
elif self._state == "started":
- _note_end()
+ if not (isinstance(scope, dict) and scope.get(_UNTRACKED_SCOPE_KEY)):
+ _note_end()
else:
return
self._state = "finished"
@@ -225,16 +239,41 @@ def _is_idle(ttl_seconds: float) -> bool:
return _inflight == 0 and _pending == 0 and (time.monotonic() - _last_active) >= ttl_seconds
+def idle_for(seconds: float) -> bool:
+ """No in-flight, pending or attended (non-scheduled) activity for ``seconds``."""
+ with _lock:
+ return _inflight == 0 and _pending == 0 and (time.monotonic() - _last_attended) >= seconds
+
+
+def attended_stamp() -> float:
+ """Changes whenever someone's inference request ends or their model load lands."""
+ with _lock:
+ return _last_attended
+
+
def inference_in_flight() -> bool:
with _lock:
return _inflight > 0 or _pending > 0
-def _note_activity() -> None:
+def unattended_activity():
+ """Mark inference and loads inside as Unsloth's own for idle_for(); follows into to_thread() and child tasks."""
+ token = _unattended.set(True)
+ try:
+ yield
+ finally:
+ _unattended.reset(token)
+
+
+def _note_activity(attended: bool = True) -> None:
"""Stamp activity, e.g. on a (re)load, so the model survives at least one TTL."""
global _last_active
with _lock:
- _last_active = time.monotonic()
+ if attended:
+ _stamp_active()
+ else:
+ _last_active = time.monotonic()
def other_inference_request_count(
@@ -848,6 +887,17 @@ def _loaded_identity(backend):
return (*identity, companion_roots) if companion_roots else identity
+def loaded_identity():
+ """The loaded GGUF's reload identity (path, quant, advertised id), or None when none is loaded."""
+ from routes.inference import get_llama_cpp_backend
+ return _loaded_identity(get_llama_cpp_backend())
+
+
+def stash_for_reload(identity) -> None:
+ """Let the next reload-only request bring ``identity`` back, as after an idle unload."""
+ _set_last_unloaded(identity)
+
+
def _note_idle_unload_event(freed, reason: str = "idle") -> None:
"""Monitor row for an idle auto-unload (or a swap, via ``reason``). Best-effort; uses the
stash's advertised repo id so the row never shows the on-disk load path."""
@@ -908,7 +958,8 @@ async def idle_unload_loop(poll_seconds: float = 15.0) -> None:
if current != seen_model:
seen_model = current
if current is not None:
- _note_activity()
+ # The loop's own context: whoever loaded it already stamped whether it was attended.
+ _note_activity(attended = False)
_set_last_unloaded(None) # a model is loaded; drop stale stash
if backend.is_loaded and await asyncio.to_thread(_user_pinned, backend):
# loaded from the UI, so the user wants it resident; only models the API loaded are freed
diff --git a/studio/backend/core/scheduled_tasks/scheduler.py b/studio/backend/core/scheduled_tasks/scheduler.py
index 1a67c26405e..0d8ef9b1560 100644
--- a/studio/backend/core/scheduled_tasks/scheduler.py
+++ b/studio/backend/core/scheduled_tasks/scheduler.py
@@ -37,6 +37,8 @@ _STOP_GRACE_SECONDS = 5.0
_SETTLE_ATTEMPTS = 3
_SETTLE_RETRY_SECONDS = 1.0
_ERROR_TEXT_LIMIT = 500
+# Studio counts as in use this long after its last inference request; a run then asks before swapping.
+_AWAY_SECONDS = 5 * 60
_YIELD_SECONDS = 5 * 60
_YIELD_POLL_SECONDS = 2.0
@@ -64,6 +66,29 @@ class Answer:
# What Chat selects to continue the conversation; `model` is the reply's display name.
checkpoint: Optional[str] = None
gguf_variant: Optional[str] = None
+ provider: Optional[dict] = None
+
+
+@dataclass
+class _Swap:
+ """A run that loads its task's model in place of what was loaded, put back afterwards."""
+
+ previous: Optional[tuple]
+ model: Optional[str] = None
+ subject: Optional[str] = None
+ timezone: str = "UTC"
+ task_id: Optional[str] = None
+ # llama_keepwarm.attended_stamp() at the swap: a different one later means someone came back.
+ attended: Optional[float] = None
+ # A Transformers or MLX model in the primary has no GGUF identity: it is loaded back by name.
+ previous_model: Optional[str] = None
+
+
+@dataclass
+class SwapHolder:
+ """A swap left for the next run, so back-to-back runs on one model load it once."""
+
+ pending: Optional[_Swap] = None
@dataclass
@@ -109,10 +134,20 @@ def _loop_cancelled(current: Optional[asyncio.Task], stopping: bool) -> bool:
return bool(cancelling()) if cancelling is not None else stopping
-def _producer_request(app: Any, run_id: str, cancel_event: threading.Event, tz: str) -> Request:
+def _producer_request(
+ app: Any,
+ run_id: str,
+ cancel_event: threading.Event,
+ tz: str,
+ loaded_only: bool = True,
+) -> Request:
from utils.current_date_prompt_settings import CURRENT_DATE_TIMEZONE_HEADER
from utils.keyless_api_access import KEYLESS_ADMISSION_STATE_KEY
- from routes.inference import LOADED_MODELS_ONLY_SCOPE_KEY, REQUIRE_TEXT_HEADER
+ from routes.inference import (
+ LOADED_MODELS_ONLY_SCOPE_KEY,
+ REQUIRE_TEXT_HEADER,
+ disable_auto_download_for_request,
+ )
path = f"/api/scheduled-tasks/runs/{run_id}"
scope = {
@@ -131,8 +166,6 @@ def _producer_request(app: Any, run_id: str, cancel_event: threading.Event, tz:
"client": ("127.0.0.1", 0),
"server": ("127.0.0.1", 0),
"app": app,
- # The kept model it names may be unloaded before routing: never load it back.
- LOADED_MODELS_ONLY_SCOPE_KEY: True,
"state": {
"generation_cancel_event": cancel_event,
"api_monitor_via_api_key": False,
@@ -141,6 +174,11 @@ def _producer_request(app: Any, run_id: str, cancel_event: threading.Event, tz:
},
}
+ if loaded_only:
+ # The kept model it names may be unloaded before routing: never load it back.
+ scope[LOADED_MODELS_ONLY_SCOPE_KEY] = True
+ disable_auto_download_for_request(scope)
+
async def receive():
return {"type": "http.request", "body": b"", "more_body": False}
@@ -199,102 +237,408 @@ def _sole_kept_model() -> Optional[str]:
return names[0] if len(names) == 1 else None
-async def generate_answer(app: Any, task: dict, run: dict, cancel_event: threading.Event) -> Answer:
- """Ask the loaded chat model to do the task. Text only: tools never run unattended."""
- from fastapi import HTTPException
+def _primary_serves(model: str) -> bool:
+ from routes.inference import _loaded_identity_satisfies, _loaded_satisfies
+ return _loaded_satisfies(model) or _loaded_identity_satisfies(model)
- from core.inference.gpu_arbiter import GpuBusyForAnotherAccountError
- from core.inference.llama_keepwarm import InferenceActivityReservation, end_in_process_request
- from models.inference import ChatCompletionRequest
- from routes.inference import produce_openai_chat_completions
- loop = asyncio.get_running_loop()
- deadline = loop.time() + _RUN_TIMEOUT_SECONDS
- request = _producer_request(app, run["id"], cancel_event, task["timezone"])
- activity = InferenceActivityReservation()
- activity.reserve()
- producer: Optional[asyncio.Future] = None
- response = None
- try:
- # The deadline covers the wait for a model load or unload to let go too: one that never
- # does must not keep the scheduler from every other task.
- try:
- await asyncio.wait_for(activity.start(cancel_event), timeout = _RUN_TIMEOUT_SECONDS)
- except TimeoutError:
- raise RunFailed("timeout") from None
- if cancel_event.is_set():
- raise RunFailed("cancelled")
- # Built once admitted: a model kept alongside is chosen as it stands now, not before a load or unload.
- payload = ChatCompletionRequest.model_validate(
+def _model_is_loaded(model: str) -> bool:
+ """Loaded as the primary or alongside it; the producer routes to whichever serves it."""
+ from core.inference import model_slots
+
+ if _primary_serves(model):
+ return True
+ candidates = model_slots.visible()
+ return (
+ bool(candidates)
+ and model_slots.serving_slot(model, candidates, _primary_serves) is not None
+ )
+
+
+# Levels the request accepts; a template may list others, which a run never sends.
+_EFFORT_LEVELS = ("minimal", "low", "medium", "high", "max", "xhigh")
+
+
+def _reasoning_fields(effort: Optional[str], connection: bool, on_loaded_model: bool) -> dict:
+ """The request fields for a task's thinking effort; None keeps the model's default."""
+ if effort is None:
+ return {}
+ relative = {"off": "none", "lowest": "low", "highest": "high"}
+ if connection:
+ return {"reasoning_effort": relative.get(effort, effort)}
+ if effort not in relative:
+ return {"enable_thinking": True, "reasoning_effort": effort}
+ backend = None
+ if on_loaded_model:
+ from routes.inference import get_llama_cpp_backend
+ backend = get_llama_cpp_backend()
+ if not getattr(backend, "is_loaded", False):
+ backend = None
+ if backend is None:
+ if effort == "off":
+ return {"enable_thinking": False}
+ return {
+ "enable_thinking": True,
+ "reasoning_effort": "low" if effort == "lowest" else "high",
+ }
+ if not backend.supports_reasoning:
+ return {}
+ style = backend.reasoning_style
+ if effort == "off":
+ if backend.reasoning_always_on or style == "reasoning_effort":
+ return {}
+ return {"enable_thinking": False}
+ if style == "enable_thinking":
+ return {"enable_thinking": True}
+ levels = [
+ level
+ for level in (backend.reasoning_effort_levels or ["low", "medium", "high"])
+ if level in _EFFORT_LEVELS
+ ] or ["low", "high"]
+ fields = {"reasoning_effort": levels[0] if effort == "lowest" else levels[-1]}
+ if style == "enable_thinking_effort":
+ fields["enable_thinking"] = True
+ return fields
+
+
+def _model_fields(model: Optional[str], may_load: bool) -> tuple[dict, Optional[dict], bool]:
+ """The request fields that pick the task's model, and whether it must be loaded; raises RunFailed."""
+ from routes.inference import _connection_model_ref
+ from storage import providers_db
+ from utils.openai_auto_switch_settings import get_openai_auto_switch_enabled
+
+ if not model:
+ return {}, None, False
+ connection = _connection_model_ref(model)
+ if connection is not None:
+ provider_id, external_model = connection
+ config = providers_db.get_provider(provider_id)
+ if config is None or not config["is_enabled"]:
+ raise RunFailed("connection_unavailable")
+ # The proxy relays a stream:false provider body as is, so stream and collect the chunks.
+ return (
{
- # No model: the loaded one answers, and an idle-unloaded one is brought back. Naming
- # one could switch models under the user.
- "messages": [
- {"role": "system", "content": system_prompt(task, db.now_ms())},
- {"role": "user", "content": task["prompt"]},
- ],
- "stream": False,
- "cancel_id": run["id"],
- # Both opt-outs: --enable-tools overrides enable_tools, and an omitted enabled_tools
- # means every built-in, python and terminal included.
- "tool_choice": "none",
- "enabled_tools": [],
- **({"model": kept} if (kept := _sole_kept_model()) else {}),
- }
+ "model": model,
+ "provider_id": provider_id,
+ "external_model": external_model,
+ "stream": True,
+ "stream_options": {"include_usage": True},
+ },
+ config,
+ False,
)
+ if _model_is_loaded(model):
+ return {"model": model}, None, False
+ # Loading replaces Chat's model, so only with the user's yes; otherwise RunFailed asks for it.
+ if may_load or get_openai_auto_switch_enabled():
+ return {"model": model}, None, True
+ raise RunFailed("model_not_loaded")
+
+
+async def _plan_swap(task: dict, model: str, unattended: bool, carried: Optional[_Swap]) -> _Swap:
+ """What a load must put back; an unattended run swaps only a restorable GGUF while Studio is idle."""
+ from core.inference.llama_keepwarm import attended_stamp, idle_for, loaded_identity
+ from routes.inference import (
+ _loaded_slot_ident,
+ _resident_npu_model,
+ _training_is_active,
+ get_inference_backend,
+ )
+ from hub.services.models import account_access
+
+ if unattended:
+ unrestorable = _resident_npu_model() is not None or getattr(
+ await asyncio.to_thread(get_inference_backend), "active_model_name", None
+ )
+ # Another account's model, which this account could not load back afterwards.
+ resident = _loaded_slot_ident()
+ foreign = resident is not None and account_access.resident_hidden("chat", resident)
+ if (
+ unrestorable
+ or foreign
+ or not idle_for(_AWAY_SECONDS)
+ or await asyncio.to_thread(_training_is_active)
+ ):
+ raise RunFailed("model_busy")
+ # A model loaded since the carried swap is the user's latest choice, and the one to put back.
+ keep_carried = carried is not None and carried.model and _model_is_loaded(carried.model)
+ previous = carried.previous if keep_carried else loaded_identity()
+ previous_model = carried.previous_model if keep_carried else None
+ if not keep_carried and previous is None and _resident_npu_model() is None:
+ previous_model = getattr(
+ await asyncio.to_thread(get_inference_backend), "active_model_name", None
+ )
+ return _Swap(
+ previous,
+ model = model,
+ subject = task["ownerSubject"],
+ timezone = task["timezone"],
+ task_id = task["id"],
+ attended = attended_stamp(),
+ previous_model = previous_model,
+ )
- serving: dict = {}
- async def produce() -> Any:
- # Settled in this task: slot routing lives in its context, which the caller never sees.
- reply = None
+async def _restore_after_swap(swap: _Swap, app: Any) -> None:
+ """Put back what the run's load replaced, unless someone used or loaded a model since. Best effort."""
+ from core.inference.llama_keepwarm import (
+ attended_stamp,
+ end_in_process_request,
+ idle_for,
+ loaded_identity,
+ stash_for_reload,
+ unattended_activity,
+ )
+ from models.inference import UnloadRequest
+ from routes.inference import (
+ _RELOAD_ONLY_MODEL,
+ _maybe_auto_switch_model,
+ _unload_model_impl,
+ allow_model_switch_for_request,
+ get_inference_backend,
+ )
+
+ try:
+ if not idle_for(0) or attended_stamp() != swap.attended:
+ return
+ with unattended_activity():
+ current = loaded_identity()
+ if not _primary_serves(swap.model) and _model_is_loaded(swap.model):
+ # Loaded beside the primary (Keep multiple models loaded with a speech model in it): the primary
+ # was never replaced, so only the task model goes.
+ # Its own task: unloading routes to the slot through a context variable, which must not stick to the loop.
+ await asyncio.ensure_future(
+ _unload_model_impl(UnloadRequest(model_path = swap.model), swap.subject)
+ )
+ return
+ if _model_is_loaded(swap.model):
+ # A Transformers or MLX task model has no GGUF identity; it holds the primary all the same.
+ target = (
+ current[0]
+ if current is not None
+ else getattr(
+ await asyncio.to_thread(get_inference_backend), "active_model_name", None
+ )
+ )
+ if target:
+ await _unload_model_impl(UnloadRequest(model_path = target), swap.subject)
+ elif current is not None:
+ return
+ if swap.previous is None and not swap.previous_model:
+ return
+ if swap.previous is not None:
+ stash_for_reload(swap.previous)
+ # Named for a non-GGUF model, which must not be held to what is loaded now.
+ request = _producer_request(
+ app,
+ f"{swap.task_id}:restore",
+ threading.Event(),
+ swap.timezone,
+ loaded_only = swap.previous is not None,
+ )
+ allow_model_switch_for_request(request.scope)
+ restored = False
try:
- reply = await produce_openai_chat_completions(
- payload,
+ await _maybe_auto_switch_model(
+ _RELOAD_ONLY_MODEL if swap.previous is not None else swap.previous_model,
request,
- task["ownerSubject"],
- cancel_on_disconnect = False,
+ swap.subject,
)
- serving.update(_serving_checkpoint())
- return reply
+ restored = True
finally:
- end_in_process_request(
- request.scope,
- answered = reply is not None and int(getattr(reply, "status_code", 200)) < 400,
- )
+ # No middleware ends this in-process request; its admission would block previews.
+ end_in_process_request(request.scope, answered = restored)
+ except Exception as exc: # noqa: BLE001 - the run's own outcome stands
+ logger.warning(
+ "Scheduled task %s could not restore the earlier model: %s", swap.task_id, exc
+ )
- producer = asyncio.ensure_future(produce())
- done, _ = await asyncio.wait({producer}, timeout = max(0.0, deadline - loop.time()))
- if not done:
- raise RunFailed("timeout")
+
+def _pins_local_model(model: Optional[str]) -> bool:
+ from routes.inference import _connection_model_ref
+ return bool(model) and _connection_model_ref(model) is None
+
+
+async def generate_answer(
+ app: Any,
+ task: dict,
+ run: dict,
+ cancel_event: threading.Event,
+ holder: Optional[SwapHolder] = None,
+) -> Answer:
+ """Ask the chat model to do the task, text only (tools never run unattended)."""
+ from fastapi import HTTPException
+
+ from core.inference.gpu_arbiter import GpuBusyForAnotherAccountError
+ from core.inference.llama_keepwarm import (
+ InferenceActivityReservation,
+ end_in_process_request,
+ unattended_activity,
+ )
+ from fastapi.responses import StreamingResponse
+
+ from models.inference import ChatCompletionRequest
+ from routes.inference import (
+ _chat_completion_from_connection_stream,
+ _relay_split_thinking,
+ allow_model_switch_for_request,
+ load_alongside_for_request,
+ produce_openai_chat_completions,
+ )
+
+ carried = holder.pending if holder is not None else None
+ if carried is not None and not _pins_local_model(task.get("model")):
+ holder.pending = None
+ await _restore_after_swap(carried, app)
+ carried = None
+ model_fields, provider, allow_switch = _model_fields(
+ task.get("model"), bool(task.get("allowModelLoad") or run.get("allowModelLoad"))
+ )
+ swap = (
+ await _plan_swap(
+ task,
+ task["model"],
+ run.get("source") == "schedule" and not run.get("allowModelLoad"),
+ carried,
+ )
+ if allow_switch
+ else None
+ )
+ if holder is not None:
+ holder.pending = swap or carried
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + _RUN_TIMEOUT_SECONDS
+ request = _producer_request(
+ app, run["id"], cancel_event, task["timezone"], loaded_only = not task.get("model")
+ )
+ if allow_switch:
+ allow_model_switch_for_request(request.scope)
+ # Keep multiple models loaded: the task model goes beside the user's when it fits, as from Chat's picker.
+ load_alongside_for_request(request.scope)
+ with unattended_activity():
+ activity = InferenceActivityReservation()
+ activity.reserve()
+ producer: Optional[asyncio.Future] = None
+ response = None
try:
- response = producer.result()
- except HTTPException as exc:
- # A named kept model answered for itself, so its refusal is not "nothing loaded",
- # unless it was unloaded before the request reached it.
- named = "model" in payload.model_fields_set
- if (not named and not _chat_model_loaded()) or (named and _sole_kept_model() is None):
- raise RunFailed("no_model") from None
- raise RunFailed(None, _error_text(exc.detail)) from None
- except GpuBusyForAnotherAccountError as exc:
- raise RunFailed(None, _error_text(exc.as_http_exception().detail)) from None
- finally:
- if producer is not None and not producer.done():
- # A timeout or shutdown: stop the generation itself, not just this wait.
- cancel_event.set()
- producer.cancel()
- await asyncio.wait({producer}, timeout = _CANCEL_GRACE_SECONDS)
-
- def release(*_: Any) -> None:
- activity.finish()
- if producer is None:
- end_in_process_request(request.scope, answered = False)
-
- if producer is not None and not producer.done():
- # Its worker has not unwound yet: the model stays busy until it does.
- producer.add_done_callback(release)
- else:
- release()
+ # The deadline covers the wait for a model load or unload to let go too: one that never
+ # does must not keep the scheduler from every other task.
+ try:
+ await asyncio.wait_for(activity.start(cancel_event), timeout = _RUN_TIMEOUT_SECONDS)
+ except TimeoutError:
+ raise RunFailed("timeout") from None
+ if cancel_event.is_set():
+ raise RunFailed("cancelled")
+ # Built once admitted: a model kept alongside is chosen as it stands now, not before a load or unload.
+ if not task.get("model") and (kept := _sole_kept_model()):
+ model_fields = {"model": kept}
+ payload = ChatCompletionRequest.model_validate(
+ {
+ "messages": [
+ {"role": "system", "content": system_prompt(task, db.now_ms())},
+ {"role": "user", "content": task["prompt"]},
+ ],
+ "stream": False,
+ "cancel_id": run["id"],
+ # Both opt-outs: --enable-tools overrides enable_tools, and an omitted enabled_tools
+ # means every built-in, python and terminal included.
+ "tool_choice": "none",
+ "enabled_tools": [],
+ **model_fields,
+ **_reasoning_fields(
+ task.get("reasoningEffort"),
+ provider is not None,
+ # Only the primary's levels are known here: a model kept beside it gets the generic fields.
+ on_loaded_model = not allow_switch
+ and (
+ not model_fields.get("model") or _primary_serves(model_fields["model"])
+ ),
+ ),
+ }
+ )
+
+ serving: dict = {}
+
+ async def produce() -> Any:
+ # Settled in this task: slot routing lives in its context, which the caller never sees.
+ reply = None
+ try:
+ reply = await produce_openai_chat_completions(
+ payload,
+ request,
+ task["ownerSubject"],
+ cancel_on_disconnect = False,
+ )
+ if provider is not None and isinstance(reply, StreamingResponse):
+ reply.body_iterator = _relay_split_thinking(
+ reply.body_iterator,
+ payload.stop,
+ parse_thinking = payload.enable_thinking is not False,
+ )
+ reply = await _chat_completion_from_connection_stream(reply, payload.model)
+ elif provider is None:
+ serving.update(_serving_checkpoint())
+ # Checked before the request ends, while nobody else can have loaded a model yet.
+ if allow_switch and int(getattr(reply, "status_code", 200)) < 400:
+ serving["loaded"] = _model_is_loaded(payload.model)
+ return reply
+ finally:
+ end_in_process_request(
+ request.scope,
+ answered = reply is not None
+ and int(getattr(reply, "status_code", 200)) < 400,
+ )
+
+ producer = asyncio.ensure_future(produce())
+ done, _ = await asyncio.wait({producer}, timeout = max(0.0, deadline - loop.time()))
+ if not done:
+ raise RunFailed("timeout")
+ try:
+ response = producer.result()
+ except HTTPException as exc:
+ if allow_switch and not _model_is_loaded(payload.model):
+ raise RunFailed("model_load_failed", _error_text(exc.detail)) from None
+ # A named kept model answered for itself, so its refusal is not "nothing loaded",
+ # unless it was unloaded before the request reached it.
+ if provider is None and not task.get("model"):
+ named = "model" in payload.model_fields_set
+ if (not named and not _chat_model_loaded()) or (
+ named and _sole_kept_model() is None
+ ):
+ raise RunFailed("no_model") from None
+ raise RunFailed(None, _error_text(exc.detail)) from None
+ except GpuBusyForAnotherAccountError as exc:
+ raise RunFailed(None, _error_text(exc.as_http_exception().detail)) from None
+ if serving.get("loaded") is False:
+ raise RunFailed("model_load_failed")
+ finally:
+ if producer is not None and not producer.done():
+ # A timeout or shutdown: stop the generation itself, not just this wait.
+ cancel_event.set()
+ producer.cancel()
+ await asyncio.wait({producer}, timeout = _CANCEL_GRACE_SECONDS)
+
+ def release(*_: Any) -> None:
+ activity.finish(request.scope)
+ if producer is None:
+ end_in_process_request(request.scope, answered = False)
+
+ if producer is not None and not producer.done():
+ # Its worker has not unwound yet: the model stays busy until it does.
+ producer.add_done_callback(release)
+ else:
+ release()
+ if holder is None and swap is not None and not cancel_event.is_set():
+ await _restore_after_swap(swap, app)
+ elif (
+ holder is not None
+ and carried is not None
+ and holder.pending is swap
+ and not _model_is_loaded(swap.model)
+ and _model_is_loaded(carried.model)
+ ):
+ # This load failed and left the carried model in place: that swap still has to be put back.
+ holder.pending = carried
if cancel_event.is_set():
raise RunFailed("cancelled")
body = getattr(response, "body", None)
@@ -314,6 +658,7 @@ async def generate_answer(app: Any, task: dict, run: dict, cancel_event: threadi
model = data.get("model") or None,
checkpoint = serving.get("checkpoint"),
gguf_variant = serving.get("gguf_variant"),
+ provider = provider,
)
@@ -362,8 +707,15 @@ def save_chat(task: dict, run: dict, answer: Answer, started_at: int, finished_a
"modelId": checkpoint,
"modelLabel": model,
"responseModelId": model,
- "providerName": "Local model",
- "providerType": "local",
+ **(
+ {
+ "providerId": answer.provider["id"],
+ "providerName": answer.provider["display_name"],
+ "providerType": answer.provider["provider_type"],
+ }
+ if answer.provider
+ else {"providerName": "Local model", "providerType": "local"}
+ ),
"startedAt": started_at,
"finishedAt": answered_at,
"durationMs": answered_at - started_at,
@@ -427,6 +779,8 @@ class ScheduledTaskScheduler:
self._active: Optional[_ActiveRun] = None
self._last_account: Optional[str] = None
self._due: Optional[int] = None
+ self._swap = SwapHolder()
+ self._swap_account: Optional[AccountContext] = None
def start(self) -> None:
if self._task is not None:
@@ -485,8 +839,14 @@ class ScheduledTaskScheduler:
if self._stopping:
await asyncio.to_thread(self._release, account, task, run)
return
+ swapped_by = self._swap_account
+ if swapped_by is not None and swapped_by.account_id != account.account_id:
+ await self._restore_swap()
await arun_as(account, self._execute(account, task, run))
+ if self._swap.pending is not None:
+ self._swap_account = account
continue
+ await self._restore_swap()
# Sleep until the next run is due (APScheduler, Celery beat); wake() cuts it short on any change.
delay = _POLL_SECONDS
if self._due is not None:
@@ -502,6 +862,19 @@ class ScheduledTaskScheduler:
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(self._wake.wait(), timeout = delay)
+ async def _restore_swap(self) -> None:
+ swap, account = self._swap.pending, self._swap_account
+ self._swap.pending = self._swap_account = None
+ if swap is None or self._stopping:
+ return
+ from core.inference.llama_keepwarm import unattended_activity
+
+ with unattended_activity():
+ if account is None:
+ await _restore_after_swap(swap, self.app)
+ else:
+ await arun_as(account, _restore_after_swap(swap, self.app))
+
async def _yield_to_inference(self, cancel_event: threading.Event) -> None:
from core.inference.llama_keepwarm import inference_in_flight
deadline = asyncio.get_running_loop().time() + _YIELD_SECONDS
@@ -572,7 +945,7 @@ class ScheduledTaskScheduler:
await self._yield_to_inference(cancel_event)
if cancel_event.is_set():
raise RunFailed("cancelled")
- answer = await generate_answer(self.app, task, run, cancel_event)
+ answer = await generate_answer(self.app, task, run, cancel_event, self._swap)
if not await asyncio.to_thread(db.task_exists, task["id"]):
return
saving = True
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index fc5f7fa948d..1e2a3c2f269 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -10588,6 +10588,43 @@ def disable_openai_auto_switch_for_request(scope) -> None:
scope[_DISABLE_OPENAI_AUTO_SWITCH_SCOPE_KEY] = True
+_ALLOW_MODEL_SWITCH_SCOPE_KEY = "unsloth.allow_model_switch"
+
+
+def allow_model_switch_for_request(scope) -> None:
+ """Let one in-process request load its named model with auto-switch off; a scope key, so no HTTP client can set it."""
+ if isinstance(scope, dict):
+ scope[_ALLOW_MODEL_SWITCH_SCOPE_KEY] = True
+
+
+def _model_switch_allowed_for_request(fastapi_request) -> bool:
+ scope = getattr(fastapi_request, "scope", None)
+ return isinstance(scope, dict) and bool(scope.get(_ALLOW_MODEL_SWITCH_SCOPE_KEY))
+
+
+_LOAD_ALONGSIDE_SCOPE_KEY = "unsloth.load_alongside"
+
+
+def load_alongside_for_request(scope) -> None:
+ """Under Keep multiple models loaded, let this in-process request's switch load beside the loaded model, as Chat's picker does."""
+ if isinstance(scope, dict):
+ scope[_LOAD_ALONGSIDE_SCOPE_KEY] = True
+
+
+def _load_alongside_for_request(fastapi_request) -> bool:
+ scope = getattr(fastapi_request, "scope", None)
+ return isinstance(scope, dict) and bool(scope.get(_LOAD_ALONGSIDE_SCOPE_KEY))
+
+
+_NO_AUTO_DOWNLOAD_SCOPE_KEY = "unsloth.no_auto_download"
+
+
+def disable_auto_download_for_request(scope) -> None:
+ """Stop an in-process scheduled run from auto-downloading; a model gone from disk fails the run."""
+ if isinstance(scope, dict):
+ scope[_NO_AUTO_DOWNLOAD_SCOPE_KEY] = True
+
+
async def _keyless_caller_held_back(fastapi_request) -> bool:
"""Keyless caller that may not POST /api/inference/load itself, so it may not switch models."""
from auth.authentication import request_admitted_without_credential
@@ -10856,6 +10893,9 @@ async def _maybe_auto_download_model(
if not requested_model or not get_openai_auto_download_enabled():
return
+ scope = getattr(fastapi_request, "scope", None)
+ if isinstance(scope, dict) and scope.get(_NO_AUTO_DOWNLOAD_SCOPE_KEY):
+ return
if not is_downloadable_ref(requested_model):
return
# The resolver never serves a Decision API repo, so fetching one would only fill the disk.
@@ -11972,7 +12012,9 @@ async def _maybe_auto_switch_model(
if claim_resident:
_claim_slot_for_non_preview(fastapi_request)
return
- auto_switch_on = get_openai_auto_switch_enabled()
+ auto_switch_on = get_openai_auto_switch_enabled() or _model_switch_allowed_for_request(
+ fastapi_request
+ )
def _refuse_non_gguf_endpoint() -> None:
"""Refuse a switch target this endpoint cannot serve.
@@ -12458,6 +12500,8 @@ async def _maybe_auto_switch_model(
try:
# Hold the keep-warm gate across the swap so no new inference can
# start on the model while it is being torn down and replaced.
+ from utils.multi_model_settings import get_multi_model_enabled
+
# Beside: load_model_gated takes the load gate itself; the primary keeps serving.
beside = await asyncio.to_thread(
_switch_loads_beside,
@@ -12468,6 +12512,10 @@ async def _maybe_auto_switch_model(
and _target_speech_audio_type(target_id, target_is_gguf, variant)
is not None
),
+ ) or (
+ # The load itself still replaces the loaded model when it does not fit beside it.
+ _load_alongside_for_request(fastapi_request)
+ and await asyncio.to_thread(get_multi_model_enabled)
)
async with AsyncExitStack() as swap_gates:
if not beside:
diff --git a/studio/backend/routes/scheduled_tasks.py b/studio/backend/routes/scheduled_tasks.py
index 2b73002f1d1..a32a4510854 100644
--- a/studio/backend/routes/scheduled_tasks.py
+++ b/studio/backend/routes/scheduled_tasks.py
@@ -33,9 +33,14 @@ Prompt = Annotated[str, Field(max_length = 20_000), AfterValidator(_not_blank)]
TimeZoneName = Annotated[str, Field(max_length = 64)]
# Which finished runs get a toast and system notification; every run's chat still shows unread in Recents.
Notify = Literal["all", "failures", "none"]
+TaskModel = Annotated[str, Field(max_length = 512), AfterValidator(_not_blank)]
+# lowest/highest are relative and resolved per run (local levels are known only once loaded); null = model default.
+ReasoningEffort = Literal[
+ "off", "lowest", "highest", "minimal", "low", "medium", "high", "xhigh", "max"
+]
ProjectId = Annotated[str, Field(max_length = 128), AfterValidator(_not_blank)]
# Fields an update may set back to null, unlike the rest, where null means unchanged.
-_CLEARABLE = ("projectId",)
+_CLEARABLE = ("model", "reasoningEffort", "projectId")
class ScheduledTaskCreate(BaseModel):
@@ -48,6 +53,9 @@ class ScheduledTaskCreate(BaseModel):
enabled: bool = True
notify: Notify = "all"
named: bool = True
+ model: Optional[TaskModel] = None
+ reasoningEffort: Optional[ReasoningEffort] = None
+ allowModelLoad: bool = False
archiveSuccessful: bool = False
projectId: Optional[ProjectId] = None
@@ -62,10 +70,19 @@ class ScheduledTaskUpdate(BaseModel):
enabled: Optional[bool] = None
notify: Optional[Notify] = None
named: Optional[bool] = None
+ model: Optional[TaskModel] = None
+ reasoningEffort: Optional[ReasoningEffort] = None
+ allowModelLoad: Optional[bool] = None
archiveSuccessful: Optional[bool] = None
projectId: Optional[ProjectId] = None
+class RunNowRequest(BaseModel):
+ model_config = ConfigDict(extra = "forbid")
+
+ loadModel: bool = False
+
+
class ScheduledTaskRun(BaseModel):
id: str
taskId: str
@@ -77,7 +94,7 @@ class ScheduledTaskRun(BaseModel):
finishedAt: Optional[int] = None
threadId: Optional[str] = None
model: Optional[str] = None
- # no_model, timeout, cancelled, interrupted or empty.
+ # no_model, model_not_loaded, model_load_failed, connection_unavailable, timeout, cancelled, interrupted or empty.
errorCode: Optional[str] = None
error: Optional[str] = None
@@ -85,6 +102,7 @@ class ScheduledTaskRun(BaseModel):
class FinishedScheduledTaskRun(ScheduledTaskRun):
taskTitle: str
taskNotify: Notify
+ taskModel: Optional[str] = None
class ScheduledTask(BaseModel):
@@ -96,6 +114,9 @@ class ScheduledTask(BaseModel):
enabled: bool
notify: Notify
named: bool
+ model: Optional[str] = None
+ reasoningEffort: Optional[ReasoningEffort] = None
+ allowModelLoad: bool = False
archiveSuccessful: bool = False
projectId: Optional[str] = None
status: Literal["active", "paused", "completed"]
@@ -144,7 +165,7 @@ def _next_run(task: dict, now: int) -> Optional[int]:
def _require_ui_session(via_api_key: bool) -> None:
- """Tasks run as the account: signed-in users only, never API keys."""
+ """Tasks run as the account and may load models or spend saved keys: signed-in users only, never API keys."""
if via_api_key:
raise HTTPException(
status_code = 403,
@@ -182,6 +203,9 @@ def create_scheduled_task(
"enabled": payload.enabled,
"notify": payload.notify,
"named": payload.named,
+ "model": payload.model,
+ "reasoningEffort": payload.reasoningEffort,
+ "allowModelLoad": payload.allowModelLoad,
"archiveSuccessful": payload.archiveSuccessful,
"projectId": _existing_project(payload.projectId),
"createdAt": now,
@@ -261,13 +285,14 @@ def delete_scheduled_task(
def run_scheduled_task_now(
task_id: str,
request: Request,
+ payload: Optional[RunNowRequest] = None,
current_subject: str = Depends(get_current_subject),
via_api_key: bool = Depends(authenticated_via_api_key),
):
"""Queue a run outside the schedule; the next scheduled run is unaffected."""
_require_ui_session(via_api_key)
try:
- run = db.request_run(task_id)
+ run = db.request_run(task_id, allow_model_load = payload is not None and payload.loadModel)
except db.TaskRunActive:
raise HTTPException(status_code = 409, detail = "This task is already running.") from None
if run is None:
diff --git a/studio/backend/storage/scheduled_tasks_db.py b/studio/backend/storage/scheduled_tasks_db.py
index 844344d5d21..f9ec246f491 100644
--- a/studio/backend/storage/scheduled_tasks_db.py
+++ b/studio/backend/storage/scheduled_tasks_db.py
@@ -77,6 +77,9 @@ def _task_from_row(row: sqlite3.Row) -> dict:
"enabled": bool(row["enabled"]),
"notify": row["notify"],
"named": bool(row["named"]),
+ "model": row["model"],
+ "reasoningEffort": row["reasoning_effort"],
+ "allowModelLoad": bool(row["allow_model_load"]),
"archiveSuccessful": bool(row["archive_successful"]),
"projectId": row["project_id"],
"nextRunAt": row["next_run_at"],
@@ -99,6 +102,7 @@ def _run_from_row(row: sqlite3.Row) -> dict:
"model": row["model"],
"errorCode": row["error_code"],
"error": row["error"],
+ "allowModelLoad": bool(row["allow_model_load"]),
}
@@ -154,6 +158,9 @@ _TASK_COLUMNS = (
"enabled",
"notify",
"named",
+ "model",
+ "reasoning_effort",
+ "allow_model_load",
"archive_successful",
"project_id",
"next_run_at",
@@ -169,6 +176,9 @@ def _task_values(task: dict) -> tuple:
1 if task["enabled"] else 0,
task["notify"],
1 if task["named"] else 0,
+ task.get("model"),
+ task.get("reasoningEffort"),
+ 1 if task.get("allowModelLoad") else 0,
1 if task.get("archiveSuccessful") else 0,
task.get("projectId"),
task["nextRunAt"],
@@ -233,7 +243,7 @@ def delete_task(task_id: str) -> bool:
return cursor.rowcount > 0
-def request_run(task_id: str) -> Optional[dict]:
+def request_run(task_id: str, allow_model_load: bool = False) -> Optional[dict]:
"""Queue a run now, outside the schedule. None when the task does not exist."""
with _connect("BEGIN IMMEDIATE") as conn:
if (
@@ -250,9 +260,9 @@ def request_run(task_id: str) -> Optional[dict]:
run_id = str(uuid.uuid4())
conn.execute(
"INSERT INTO scheduled_task_runs"
- " (id, task_id, source, status, created_at)"
- " VALUES (?, ?, 'manual', 'queued', ?)",
- (run_id, task_id, now_ms()),
+ " (id, task_id, source, status, created_at, allow_model_load)"
+ " VALUES (?, ?, 'manual', 'queued', ?, ?)",
+ (run_id, task_id, now_ms(), 1 if allow_model_load else 0),
)
row = conn.execute("SELECT * FROM scheduled_task_runs WHERE id = ?", (run_id,)).fetchone()
return _run_from_row(row)
@@ -497,7 +507,7 @@ def activity(since: Optional[int]) -> dict:
if since is not None:
rows = conn.execute(
"""
- SELECT r.*, t.title AS task_title, t.notify AS task_notify
+ SELECT r.*, t.title AS task_title, t.notify AS task_notify, t.model AS task_model
FROM scheduled_task_runs r
JOIN scheduled_tasks t ON t.id = r.task_id
WHERE r.finished_at IS NOT NULL AND r.finished_at >= ?
@@ -511,6 +521,7 @@ def activity(since: Optional[int]) -> dict:
**_run_from_row(row),
"taskTitle": row["task_title"],
"taskNotify": row["task_notify"],
+ "taskModel": row["task_model"],
}
for row in rows[:ACTIVITY_LIMIT]
]
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 675e5e9b2a7..a40f9a54f4b 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -874,6 +874,9 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
updated_at INTEGER NOT NULL,
notify TEXT NOT NULL DEFAULT 'all',
named INTEGER NOT NULL DEFAULT 1,
+ model TEXT,
+ reasoning_effort TEXT,
+ allow_model_load INTEGER NOT NULL DEFAULT 0,
archive_successful INTEGER NOT NULL DEFAULT 0,
project_id TEXT
)
@@ -886,6 +889,14 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
conn.execute("ALTER TABLE scheduled_tasks ADD COLUMN notify TEXT NOT NULL DEFAULT 'all'")
if "named" not in scheduled_task_cols:
conn.execute("ALTER TABLE scheduled_tasks ADD COLUMN named INTEGER NOT NULL DEFAULT 1")
+ if "model" not in scheduled_task_cols:
+ conn.execute("ALTER TABLE scheduled_tasks ADD COLUMN model TEXT")
+ if "reasoning_effort" not in scheduled_task_cols:
+ conn.execute("ALTER TABLE scheduled_tasks ADD COLUMN reasoning_effort TEXT")
+ if "allow_model_load" not in scheduled_task_cols:
+ conn.execute(
+ "ALTER TABLE scheduled_tasks ADD COLUMN allow_model_load INTEGER NOT NULL DEFAULT 0"
+ )
if "archive_successful" not in scheduled_task_cols:
conn.execute(
"ALTER TABLE scheduled_tasks ADD COLUMN archive_successful INTEGER NOT NULL DEFAULT 0"
@@ -911,10 +922,18 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
thread_id TEXT REFERENCES chat_threads(id) ON DELETE SET NULL,
model TEXT,
error_code TEXT,
- error TEXT
+ error TEXT,
+ allow_model_load INTEGER NOT NULL DEFAULT 0
)
"""
)
+ scheduled_run_cols = {
+ row[1] for row in conn.execute("PRAGMA table_info(scheduled_task_runs)").fetchall()
+ }
+ if "allow_model_load" not in scheduled_run_cols:
+ conn.execute(
+ "ALTER TABLE scheduled_task_runs ADD COLUMN allow_model_load INTEGER NOT NULL DEFAULT 0"
+ )
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_scheduled_task_runs_task"
" ON scheduled_task_runs(task_id, created_at)"
diff --git a/studio/backend/tests/test_scheduled_tasks.py b/studio/backend/tests/test_scheduled_tasks.py
index 04fde9c8264..af3c1c7f691 100644
--- a/studio/backend/tests/test_scheduled_tasks.py
+++ b/studio/backend/tests/test_scheduled_tasks.py
@@ -310,6 +310,32 @@ def create(client, **overrides):
return client.post("/api/scheduled-tasks", json = body)
+def test_a_task_keeps_its_model_and_reasoning_until_cleared(client):
+ connection = "external::conn-1::gpt-5-mini"
+ task = create(client, model = connection, reasoningEffort = "highest").json()
+ assert (task["model"], task["reasoningEffort"]) == (connection, "highest")
+ renamed = client.patch(f"/api/scheduled-tasks/{task['id']}", json = {"title": "Renamed"}).json()
+ assert (renamed["model"], renamed["reasoningEffort"]) == (connection, "highest")
+ cleared = client.patch(
+ f"/api/scheduled-tasks/{task['id']}", json = {"model": None, "reasoningEffort": None}
+ ).json()
+ assert (cleared["model"], cleared["reasoningEffort"]) == (None, None)
+ assert create(client, reasoningEffort = "extreme").status_code == 422
+ assert create(client).json()["model"] is None
+
+
+def test_run_now_can_carry_a_one_time_permission_to_load_the_model(client):
+ task = create(client, model = "unsloth/Qwen3-1.7B-GGUF").json()
+ assert task["allowModelLoad"] is False
+ run = client.post(f"/api/scheduled-tasks/{task['id']}/run", json = {"loadModel": True})
+ assert run.status_code == 202
+ assert db.list_runs(task["id"])[0]["allowModelLoad"] is True
+ allowed = client.patch(f"/api/scheduled-tasks/{task['id']}", json = {"allowModelLoad": True})
+ assert allowed.json()["allowModelLoad"] is True
+ renamed = client.patch(f"/api/scheduled-tasks/{task['id']}", json = {"title": "Renamed"})
+ assert renamed.json()["allowModelLoad"] is True
+
+
def make_project(project_id = "proj-1"):
return studio_db.upsert_chat_project(
{"id": project_id, "name": "Reports", "instructions": "", "createdAt": 1, "updatedAt": 1}
@@ -1066,6 +1092,7 @@ def test_a_run_skips_a_speech_primary_for_the_text_model_kept_alongside(monkeypa
def test_a_run_never_loads_a_model_and_a_vanished_kept_model_means_no_model(monkeypatch):
request = scheduler_module._producer_request(None, "run-1", threading.Event(), "UTC")
assert request.scope[inference_routes.LOADED_MODELS_ONLY_SCOPE_KEY] is True
+ assert not inference_routes._load_alongside_for_request(request)
# Named the kept model, which was unloaded before the request reached it.
names = iter(["kept/model", None])
@@ -1119,8 +1146,569 @@ def test_a_refusal_from_a_loaded_model_keeps_its_reason(monkeypatch):
assert (failure.value.code, failure.value.message) == (None, "Too long.")
+def test_a_task_can_pin_the_loaded_model_and_its_reasoning(monkeypatch):
+ monkeypatch.setattr(inference_routes, "_loaded_satisfies", lambda model: True)
+ producer = FakeProducer(completion("Dawn light."))
+ generate(
+ monkeypatch, producer, make_task(model = "unsloth/Qwen3-1.7B-GGUF", reasoningEffort = "lowest")
+ )
+ payload = producer.payload
+ assert payload.model == "unsloth/Qwen3-1.7B-GGUF"
+ assert (payload.enable_thinking, payload.reasoning_effort) == (True, "low")
+ assert payload.provider_id is None
+
+
+def test_reasoning_off_turns_thinking_off_on_a_local_model(monkeypatch):
+ producer = FakeProducer(completion("Dawn light."))
+ generate(monkeypatch, producer, make_task(reasoningEffort = "off"))
+ assert (producer.payload.enable_thinking, producer.payload.reasoning_effort) == (False, None)
+ assert "model" not in producer.payload.model_fields_set
+
+
+def loaded_gguf(monkeypatch, **reasoning):
+ backend = SimpleNamespace(
+ is_loaded = True,
+ supports_reasoning = True,
+ reasoning_style = "enable_thinking",
+ reasoning_effort_levels = [],
+ reasoning_always_on = False,
+ )
+ for key, value in reasoning.items():
+ setattr(backend, key, value)
+ monkeypatch.setattr(inference_routes, "get_llama_cpp_backend", lambda: backend)
+
+
+ "reasoning, effort, expected",
+ [
+ (
+ {
+ "reasoning_style": "reasoning_effort",
+ "reasoning_effort_levels": ["minimal", "low", "medium", "high", "xhigh"],
+ },
+ "highest",
+ {"reasoning_effort": "xhigh"},
+ ),
+ (
+ {
+ "reasoning_style": "reasoning_effort",
+ "reasoning_effort_levels": ["minimal", "low", "medium", "high", "xhigh"],
+ },
+ "lowest",
+ {"reasoning_effort": "minimal"},
+ ),
+ ({"reasoning_style": "reasoning_effort"}, "lowest", {"reasoning_effort": "low"}),
+ ({"reasoning_style": "reasoning_effort"}, "off", {}),
+ ({}, "lowest", {"enable_thinking": True}),
+ ({}, "off", {"enable_thinking": False}),
+ ({"reasoning_always_on": True}, "off", {}),
+ (
+ {
+ "reasoning_style": "enable_thinking_effort",
+ "reasoning_effort_levels": ["low", "high", "max"],
+ },
+ "highest",
+ {"enable_thinking": True, "reasoning_effort": "max"},
+ ),
+ ({"supports_reasoning": False}, "highest", {}),
+ ],
+)
+def test_thinking_effort_resolves_to_the_loaded_model(monkeypatch, reasoning, effort, expected):
+ loaded_gguf(monkeypatch, **reasoning)
+ assert scheduler_module._reasoning_fields(effort, False, on_loaded_model = True) == expected
+
+
+def test_thinking_effort_for_a_model_not_yet_loaded_or_a_connection(monkeypatch):
+ loaded_gguf(monkeypatch, supports_reasoning = False, model_identifier = "/models/gemma.gguf")
+ assert scheduler_module._reasoning_fields("highest", False, on_loaded_model = False) == {
+ "enable_thinking": True,
+ "reasoning_effort": "high",
+ }
+ assert scheduler_module._reasoning_fields("off", True, on_loaded_model = True) == {
+ "reasoning_effort": "none"
+ }
+ assert scheduler_module._reasoning_fields(None, False, on_loaded_model = True) == {}
+
+
+def test_a_connection_task_names_its_level_and_a_local_one_resolves_it(monkeypatch):
+ loaded_gguf(monkeypatch, reasoning_style = "reasoning_effort")
+ assert scheduler_module._reasoning_fields("xhigh", True, on_loaded_model = False) == {
+ "reasoning_effort": "xhigh"
+ }
+ assert scheduler_module._reasoning_fields("medium", False, on_loaded_model = True) == {
+ "enable_thinking": True,
+ "reasoning_effort": "medium",
+ }
+
+
+def test_a_chosen_model_that_is_not_loaded_fails_rather_than_switching(monkeypatch):
+ from utils import openai_auto_switch_settings
+
+ monkeypatch.setattr(inference_routes, "_loaded_satisfies", lambda model: False)
+ monkeypatch.setattr(inference_routes, "_loaded_identity_satisfies", lambda model: False)
+ monkeypatch.setattr(
+ openai_auto_switch_settings, "get_openai_auto_switch_enabled", lambda: False
+ )
+ producer = FakeProducer(completion("Dawn light."))
+ with pytest.raises(RunFailed) as failure:
+ generate(monkeypatch, producer, make_task(model = "unsloth/Qwen3-1.7B-GGUF"))
+ assert failure.value.code == "model_not_loaded"
+ assert producer.payload is None
+
+ monkeypatch.setattr(openai_auto_switch_settings, "get_openai_auto_switch_enabled", lambda: True)
+ db.delete_task("task-1")
+ producer = LoadsItsModel(monkeypatch, completion("Dawn light."))
+ generate(monkeypatch, producer, make_task(model = "unsloth/Qwen3-1.7B-GGUF"))
+ assert producer.payload.model == "unsloth/Qwen3-1.7B-GGUF"
+
+
+def test_a_task_allowed_to_load_its_model_lets_only_its_own_request_switch(monkeypatch):
+ from utils import openai_auto_switch_settings
+
+ monkeypatch.setattr(inference_routes, "_loaded_satisfies", lambda model: False)
+ monkeypatch.setattr(inference_routes, "_loaded_identity_satisfies", lambda model: False)
+ monkeypatch.setattr(
+ openai_auto_switch_settings, "get_openai_auto_switch_enabled", lambda: False
+ )
+ producer = LoadsItsModel(monkeypatch, completion("Dawn light."))
+ generate(
+ monkeypatch,
+ producer,
+ make_task(model = "unsloth/Qwen3-1.7B-GGUF", allowModelLoad = True),
+ )
+ assert producer.payload.model == "unsloth/Qwen3-1.7B-GGUF"
+ assert inference_routes._model_switch_allowed_for_request(producer.request)
+ # Keep multiple models loaded applies to the run's load as to Chat's picker.
+ assert inference_routes._load_alongside_for_request(producer.request)
+
+
+def test_a_one_time_yes_lets_that_run_alone_load_the_model(monkeypatch):
+ from utils import openai_auto_switch_settings
+
+ monkeypatch.setattr(inference_routes, "_loaded_satisfies", lambda model: False)
+ monkeypatch.setattr(inference_routes, "_loaded_identity_satisfies", lambda model: False)
+ monkeypatch.setattr(
+ openai_auto_switch_settings, "get_openai_auto_switch_enabled", lambda: False
+ )
+ monkeypatch.setattr(
+ inference_routes,
+ "produce_openai_chat_completions",
+ LoadsItsModel(monkeypatch, completion("Ok.")),
+ )
+ task = make_task(model = "unsloth/Qwen3-1.7B-GGUF")
+ app = SimpleNamespace(state = SimpleNamespace())
+ granted = {"id": "run-1", "allowModelLoad": True}
+ asyncio.run(generate_answer(app, task, granted, threading.Event()))
+ monkeypatch.setattr(inference_routes, "_loaded_satisfies", lambda model: False)
+ with pytest.raises(RunFailed) as failure:
+ asyncio.run(generate_answer(app, task, {"id": "run-2"}, threading.Event()))
+ assert failure.value.code == "model_not_loaded"
+
+
+def test_a_permitted_load_that_still_finds_no_model_says_the_load_failed(monkeypatch):
+ from utils import openai_auto_switch_settings
+
+ monkeypatch.setattr(inference_routes, "_loaded_satisfies", lambda model: False)
+ monkeypatch.setattr(inference_routes, "_loaded_identity_satisfies", lambda model: False)
+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: None)
+ monkeypatch.setattr(
+ openai_auto_switch_settings, "get_openai_auto_switch_enabled", lambda: False
+ )
+ producer = FakeProducer(error = HTTPException(status_code = 400, detail = "No model loaded."))
+ with pytest.raises(RunFailed) as failure:
+ generate(
+ monkeypatch,
+ producer,
+ make_task(model = "unsloth/Qwen3-1.7B-GGUF", allowModelLoad = True),
+ )
+ assert failure.value.code == "model_load_failed"
+
+
+class SwapWorld:
+ """The model slot around one run: what is loaded, and what restoring did to it."""
+
+ EARLIER = ("/models/gemma.gguf", "Q4_K_M", "unsloth/gemma-3-GGUF")
+ TASK_MODEL = "unsloth/Qwen3-1.7B-GGUF"
+
+ def __init__(
+ self,
+ monkeypatch,
+ *,
+ idle = True,
+ earlier = EARLIER,
+ ):
+ from core.inference import llama_keepwarm
+ from utils import openai_auto_switch_settings
+
+ self.loaded = earlier
+ self.unloaded, self.stashed, self.reloads = [], [], []
+ self.idle = idle
+ monkeypatch.setattr(llama_keepwarm, "idle_for", lambda seconds: self.idle)
+ monkeypatch.setattr(llama_keepwarm, "loaded_identity", lambda: self.loaded)
+ monkeypatch.setattr(llama_keepwarm, "stash_for_reload", self.stashed.append)
+ monkeypatch.setattr(
+ inference_routes,
+ "_loaded_satisfies",
+ lambda model: self.loaded is not None and self.loaded[2] == model,
+ )
+ monkeypatch.setattr(inference_routes, "_loaded_identity_satisfies", lambda model: False)
+ monkeypatch.setattr(inference_routes, "_resident_npu_model", lambda: None)
+ self.training = False
+ monkeypatch.setattr(inference_routes, "_training_is_active", lambda: self.training)
+ monkeypatch.setattr(
+ inference_routes,
+ "get_inference_backend",
+ lambda: SimpleNamespace(active_model_name = None),
+ )
+ monkeypatch.setattr(
+ openai_auto_switch_settings, "get_openai_auto_switch_enabled", lambda: False
+ )
+
+ async def unload(request, subject):
+ self.unloaded.append(request.model_path)
+ self.loaded = None
+
+ async def reload(model, request, subject, **kwargs):
+ self.reloads.append(
+ (model, inference_routes._model_switch_allowed_for_request(request))
+ )
+ self.loaded = self.stashed[-1]
+
+ monkeypatch.setattr(inference_routes, "_unload_model_impl", unload)
+ monkeypatch.setattr(inference_routes, "_maybe_auto_switch_model", reload)
+
+ def producer(self):
+ world = self
+
+ class LoadsTheTaskModel(FakeProducer):
+ async def __call__(self, payload, request, current_subject, *, cancel_on_disconnect):
+ world.loaded = ("/models/qwen.gguf", "Q4_K_M", world.TASK_MODEL)
+ return await super().__call__(
+ payload, request, current_subject, cancel_on_disconnect = cancel_on_disconnect
+ )
+
+ return LoadsTheTaskModel(completion("Dawn light."))
+
+ def run(
+ self,
+ monkeypatch,
+ run,
+ producer = None,
+ ):
+ producer = producer or self.producer()
+ monkeypatch.setattr(inference_routes, "produce_openai_chat_completions", producer)
+ task = make_task(model = self.TASK_MODEL, allowModelLoad = True)
+ app = SimpleNamespace(state = SimpleNamespace())
+ asyncio.run(generate_answer(app, task, run, threading.Event()))
+ return producer
+
+
+def test_a_scheduled_run_leaves_the_model_alone_while_studio_is_in_use(monkeypatch):
+ world = SwapWorld(monkeypatch, idle = False)
+ producer = world.producer()
+ with pytest.raises(RunFailed) as failure:
+ world.run(monkeypatch, {"id": "run-1", "source": "schedule"}, producer)
+ assert failure.value.code == "model_busy"
+ assert producer.payload is None
+ assert world.loaded == SwapWorld.EARLIER
+
+
+def test_a_scheduled_run_while_away_switches_back_to_the_earlier_model(monkeypatch):
+ world = SwapWorld(monkeypatch)
+ world.run(monkeypatch, {"id": "run-1", "source": "schedule"})
+ assert world.unloaded == ["/models/qwen.gguf"]
+ assert world.stashed == [SwapWorld.EARLIER]
+ assert world.reloads == [(inference_routes._RELOAD_ONLY_MODEL, True)]
+ assert world.loaded == SwapWorld.EARLIER
+
+
+def test_switching_back_unloads_only_a_task_model_loaded_beside_the_primary(monkeypatch):
+ from core.inference.orchestrator import routed_slot
+
+ world = SwapWorld(monkeypatch)
+ kept = []
+ monkeypatch.setattr(
+ scheduler_module,
+ "_model_is_loaded",
+ lambda model: model in kept or (world.loaded is not None and world.loaded[2] == model),
+ )
+
+ class LoadsBeside(FakeProducer):
+ async def __call__(self, payload, request, current_subject, *, cancel_on_disconnect):
+ kept.append(SwapWorld.TASK_MODEL)
+ return await super().__call__(
+ payload, request, current_subject, cancel_on_disconnect = cancel_on_disconnect
+ )
+
+ async def unload(request, subject):
+ # The real unload routes to the kept slot by setting this context variable.
+ routed_slot.set(object())
+ world.unloaded.append(request.model_path)
+ kept.remove(request.model_path)
+
+ monkeypatch.setattr(inference_routes, "_unload_model_impl", unload)
+ holder = scheduler_module.SwapHolder()
+ task = make_task(model = SwapWorld.TASK_MODEL, allowModelLoad = True)
+ monkeypatch.setattr(
+ inference_routes, "produce_openai_chat_completions", LoadsBeside(completion("Ok."))
+ )
+
+ async def run_then_restore():
+ app = SimpleNamespace(state = SimpleNamespace())
+ await generate_answer(
+ app, task, {"id": "run-1", "source": "schedule"}, threading.Event(), holder
+ )
+ await scheduler_module._restore_after_swap(holder.pending, app)
+ # Later runs in the scheduler's task must see the primary, not the dropped slot.
+ return routed_slot.get()
+
+ assert asyncio.run(run_then_restore()) is None
+ assert world.unloaded == [SwapWorld.TASK_MODEL] and kept == []
+ assert world.loaded == SwapWorld.EARLIER and world.reloads == []
+
+
+def test_a_run_that_found_nothing_loaded_leaves_nothing_loaded(monkeypatch):
+ world = SwapWorld(monkeypatch, earlier = None)
+ world.run(monkeypatch, {"id": "run-1", "source": "schedule"})
+ assert world.unloaded == ["/models/qwen.gguf"]
+ assert world.reloads == [] and world.loaded is None
+
+
+def test_a_run_now_swaps_even_while_studio_is_in_use_and_still_switches_back(monkeypatch):
+ world = SwapWorld(monkeypatch, idle = False)
+ world.run(monkeypatch, {"id": "run-1", "source": "manual"})
+ assert world.loaded[2] == SwapWorld.TASK_MODEL and world.unloaded == []
+ db.delete_task("task-1")
+ world = SwapWorld(monkeypatch, idle = True)
+ world.run(monkeypatch, {"id": "run-2", "source": "manual"})
+ assert world.loaded == SwapWorld.EARLIER
+
+
+def test_restoring_leaves_alone_a_model_the_user_loaded_meanwhile(monkeypatch):
+ from core.inference import llama_keepwarm
+
+ world = SwapWorld(monkeypatch)
+ picked = ("/models/llama.gguf", "Q8_0", "unsloth/Llama-3.2-3B-GGUF")
+ ended = llama_keepwarm.end_in_process_request
+
+ def user_picks_another(scope, answered):
+ ended(scope, answered)
+ world.loaded = picked
+
+ monkeypatch.setattr(llama_keepwarm, "end_in_process_request", user_picks_another)
+ world.run(monkeypatch, {"id": "run-1", "source": "schedule"})
+ assert world.unloaded == [] and world.reloads == [] and world.loaded == picked
+
+
+def test_a_header_cannot_turn_on_the_switch_opt_in():
+ from starlette.requests import Request
+
+ request = Request(
+ {"type": "http", "headers": [(b"unsloth.allow_model_switch", b"1")], "path": "/"}
+ )
+ assert not inference_routes._model_switch_allowed_for_request(request)
+ inference_routes.allow_model_switch_for_request(request.scope)
+ assert inference_routes._model_switch_allowed_for_request(request)
+ spoofed = Request({"type": "http", "headers": [(b"unsloth.load_alongside", b"1")], "path": "/"})
+ assert not inference_routes._load_alongside_for_request(spoofed)
+
+
+def test_a_scheduled_run_leaves_the_model_alone_while_training(monkeypatch):
+ world = SwapWorld(monkeypatch)
+ world.training = True
+ producer = world.producer()
+ with pytest.raises(RunFailed) as failure:
+ world.run(monkeypatch, {"id": "run-1", "source": "schedule"}, producer)
+ assert failure.value.code == "model_busy"
+ assert producer.payload is None and world.loaded == SwapWorld.EARLIER
+
+
+def test_a_scheduled_run_leaves_alone_another_accounts_model(monkeypatch):
+ from hub.services.models import account_access
+
+ world = SwapWorld(monkeypatch)
+ monkeypatch.setattr(inference_routes, "_loaded_slot_ident", lambda: "gemma")
+ monkeypatch.setattr(account_access, "resident_hidden", lambda modality, reference: True)
+ with pytest.raises(RunFailed) as failure:
+ world.run(monkeypatch, {"id": "run-1", "source": "schedule"})
+ assert failure.value.code == "model_busy"
+ assert world.loaded == SwapWorld.EARLIER
+
+
+def keepwarm_module():
+ from core.inference import llama_keepwarm
+ return llama_keepwarm
+
+
+def run_held(world, monkeypatch, task, run, holder):
+ monkeypatch.setattr(inference_routes, "produce_openai_chat_completions", world.producer())
+ app = SimpleNamespace(state = SimpleNamespace())
+ return asyncio.run(generate_answer(app, task, run, threading.Event(), holder))
+
+
+def test_back_to_back_runs_on_one_model_load_it_once_and_switch_back_once(monkeypatch):
+ world = SwapWorld(monkeypatch)
+ holder = scheduler_module.SwapHolder()
+ first = make_task(model = SwapWorld.TASK_MODEL, allowModelLoad = True)
+ second = make_task(id = "task-2", model = SwapWorld.TASK_MODEL, allowModelLoad = True)
+ run_held(world, monkeypatch, first, {"id": "run-1", "source": "schedule"}, holder)
+ assert world.loaded[2] == SwapWorld.TASK_MODEL and world.reloads == []
+ run_held(world, monkeypatch, second, {"id": "run-2", "source": "schedule"}, holder)
+ assert world.unloaded == [] and holder.pending.previous == SwapWorld.EARLIER
+ asyncio.run(scheduler_module._restore_after_swap(holder.pending, None))
+ assert world.unloaded == ["/models/qwen.gguf"]
+ assert world.reloads == [(inference_routes._RELOAD_ONLY_MODEL, True)]
+ assert world.loaded == SwapWorld.EARLIER
+
+
+def test_a_failed_load_keeps_the_carried_swap_to_put_back(monkeypatch):
+ world = SwapWorld(monkeypatch)
+ holder = scheduler_module.SwapHolder()
+ first = make_task(model = SwapWorld.TASK_MODEL, allowModelLoad = True)
+ run_held(world, monkeypatch, first, {"id": "run-1", "source": "schedule"}, holder)
+ carried = holder.pending
+ other = make_task(id = "task-2", model = "unsloth/gemma-3-1b-it-GGUF", allowModelLoad = True)
+ monkeypatch.setattr(
+ inference_routes, "produce_openai_chat_completions", FakeProducer(completion("Ok."))
+ )
+ with pytest.raises(RunFailed) as failure:
+ asyncio.run(
+ generate_answer(
+ SimpleNamespace(state = SimpleNamespace()),
+ other,
+ {"id": "run-2", "source": "schedule"},
+ threading.Event(),
+ holder,
+ )
+ )
+ assert failure.value.code == "model_load_failed"
+ assert holder.pending is carried and carried.previous == SwapWorld.EARLIER
+
+
+def test_a_run_on_the_loaded_model_gets_the_users_model_back_first(monkeypatch):
+ world = SwapWorld(monkeypatch)
+ holder = scheduler_module.SwapHolder()
+ pinned = make_task(model = SwapWorld.TASK_MODEL, allowModelLoad = True)
+ run_held(world, monkeypatch, pinned, {"id": "run-1", "source": "schedule"}, holder)
+ unpinned = make_task(id = "task-2")
+ producer = FakeProducer(completion("Ok."))
+ monkeypatch.setattr(inference_routes, "produce_openai_chat_completions", producer)
+ app = SimpleNamespace(state = SimpleNamespace())
+ run = {"id": "run-2", "source": "schedule"}
+ asyncio.run(generate_answer(app, unpinned, run, threading.Event(), holder))
+ assert world.loaded == SwapWorld.EARLIER and holder.pending is None
+ assert "model" not in producer.payload.model_fields_set
+
+
+def test_the_scheduler_switches_back_after_a_timed_out_run_but_not_at_shutdown(monkeypatch):
+ world = SwapWorld(monkeypatch)
+ world.loaded = ("/models/qwen.gguf", "Q4_K_M", SwapWorld.TASK_MODEL)
+ swap = scheduler_module._Swap(
+ SwapWorld.EARLIER,
+ model = SwapWorld.TASK_MODEL,
+ subject = "unsloth",
+ task_id = "task-1",
+ attended = keepwarm_module().attended_stamp(),
+ )
+ scheduler = new_scheduler()
+ scheduler._swap.pending = swap
+ scheduler._stopping = True
+ asyncio.run(scheduler._restore_swap())
+ assert world.loaded[2] == SwapWorld.TASK_MODEL and scheduler._swap.pending is None
+ scheduler._stopping = False
+ scheduler._swap.pending = swap
+ asyncio.run(scheduler._restore_swap())
+ assert world.loaded == SwapWorld.EARLIER
+
+
+def test_switching_back_leaves_a_model_someone_used_since_the_swap(monkeypatch):
+ keepwarm = keepwarm_module()
+ world = SwapWorld(monkeypatch)
+ holder = scheduler_module.SwapHolder()
+ task = make_task(model = SwapWorld.TASK_MODEL, allowModelLoad = True)
+ run_held(world, monkeypatch, task, {"id": "run-1", "source": "schedule"}, holder)
+ keepwarm._note_start()
+ keepwarm._note_end()
+ asyncio.run(scheduler_module._restore_after_swap(holder.pending, None))
+ assert world.loaded[2] == SwapWorld.TASK_MODEL and world.reloads == []
+
+
+def test_studios_own_runs_do_not_count_as_someone_using_it(monkeypatch):
+ import time
+
+ keepwarm = keepwarm_module()
+ monkeypatch.setattr(keepwarm, "_last_attended", time.monotonic() - 3600)
+ assert keepwarm.idle_for(300)
+ with keepwarm.unattended_activity():
+ keepwarm._note_start()
+ keepwarm._note_end()
+ keepwarm._note_activity()
+ assert keepwarm.idle_for(300)
+ assert time.monotonic() - keepwarm._last_active < 60
+ keepwarm._note_start()
+ assert not keepwarm.idle_for(0)
+ keepwarm._note_end()
+ assert not keepwarm.idle_for(300)
+
+
+def test_the_idle_loop_noticing_a_swap_does_not_count_as_someone_using_studio(monkeypatch):
+ import inspect
+ import time
+
+ keepwarm = keepwarm_module()
+ monkeypatch.setattr(keepwarm, "_last_attended", time.monotonic() - 3600)
+ # The loop runs in its own long-lived context, outside the run's unattended_activity().
+ keepwarm._note_activity(attended = False)
+ assert keepwarm.idle_for(300)
+ assert "_note_activity(attended = False)" in inspect.getsource(keepwarm.idle_unload_loop)
+
+
+def test_a_run_answered_by_another_model_than_its_own_fails(monkeypatch):
+ from utils import openai_auto_switch_settings
+
+ monkeypatch.setattr(inference_routes, "_loaded_satisfies", lambda model: False)
+ monkeypatch.setattr(inference_routes, "_loaded_identity_satisfies", lambda model: False)
+ monkeypatch.setattr(
+ openai_auto_switch_settings, "get_openai_auto_switch_enabled", lambda: False
+ )
+ with pytest.raises(RunFailed) as failure:
+ generate(
+ monkeypatch,
+ FakeProducer(completion("From gemma.")),
+ make_task(model = "unsloth/Qwen3-1.7B-GGUF", allowModelLoad = True),
+ )
+ assert failure.value.code == "model_load_failed"
+
+
+def test_a_run_never_starts_a_download(monkeypatch):
+ from starlette.requests import Request
+
+ from core.inference import openai_auto_download
+ from utils import openai_auto_switch_settings
+
+ producer = FakeProducer(completion("Ok."))
+ generate(monkeypatch, producer)
+ monkeypatch.setattr(
+ openai_auto_switch_settings, "get_openai_auto_download_enabled", lambda: True
+ )
+ monkeypatch.setattr(openai_auto_download, "is_downloadable_ref", lambda model: True)
+ monkeypatch.setattr(inference_routes, "_loaded_satisfies", lambda model: False)
+ started = []
+
+ async def download(*args, **kwargs):
+ started.append(args)
+
+ monkeypatch.setattr(openai_auto_download, "maybe_auto_download", download)
+ model = "unsloth/Qwen3-1.7B-GGUF"
+ asyncio.run(inference_routes._maybe_auto_download_model(model, producer.request))
+ assert started == []
+ plain = Request({"type": "http", "headers": [], "path": "/"})
+ asyncio.run(inference_routes._maybe_auto_download_model(model, plain))
+ assert len(started) == 1
+
+
def test_a_scheduled_run_waits_for_a_reply_being_generated(monkeypatch):
- keepwarm = llama_keepwarm
+ keepwarm = keepwarm_module()
busy = iter([True, True, False])
monkeypatch.setattr(keepwarm, "inference_in_flight", lambda: next(busy))
monkeypatch.setattr(scheduler_module, "_YIELD_POLL_SECONDS", 0.0)
@@ -1143,18 +1731,62 @@ def test_only_a_signed_in_user_changes_tasks(client):
}
for method, path, body in (
("post", "", new_task),
- ("patch", f"/{task['id']}", {"title": "Renamed"}),
- ("post", f"/{task['id']}/run", {}),
+ ("patch", f"/{task['id']}", {"allowModelLoad": True}),
+ ("post", f"/{task['id']}/run", {"loadModel": True}),
("delete", f"/{task['id']}", None),
):
kwargs = {} if body is None else {"json": body}
response = getattr(client, method)(f"/api/scheduled-tasks{path}", **kwargs)
assert response.status_code == 403, (method, path)
listed = client.get("/api/scheduled-tasks").json()["tasks"]
- assert [entry["title"] for entry in listed] == [task["title"]]
+ assert [entry["allowModelLoad"] for entry in listed] == [False]
assert client.get("/api/scheduled-tasks/runs?since=0").status_code == 200
+def test_a_missing_or_disabled_connection_fails_with_its_own_reason(monkeypatch):
+ from storage import providers_db
+ task = make_task(model = "external::conn-1::gpt-5-mini")
+ for config in (None, {"id": "conn-1", "is_enabled": 0}):
+ monkeypatch.setattr(providers_db, "get_provider", lambda provider_id, config = config: config)
+ producer = FakeProducer(completion("unused"))
+ with pytest.raises(RunFailed) as failure:
+ generate(monkeypatch, producer, task)
+ assert failure.value.code == "connection_unavailable"
+ assert producer.payload is None
+
+
+def test_a_connection_run_streams_and_records_which_connection_answered(monkeypatch):
+ import json as jsonlib
+
+ from fastapi.responses import StreamingResponse
+ from storage import providers_db
+
+ config = {"id": "conn-1", "is_enabled": 1, "display_name": "OpenAI", "provider_type": "openai"}
+ monkeypatch.setattr(providers_db, "get_provider", lambda provider_id: config)
+
+ async def chunks():
+ for delta in ({"content": "Dawn "}, {"content": "light."}):
+ chunk = {"id": "c1", "model": "gpt-5-mini", "choices": [{"index": 0, "delta": delta}]}
+ yield f"data: {jsonlib.dumps(chunk)}\n\n".encode()
+ yield b"data: [DONE]\n\n"
+
+ producer = FakeProducer(StreamingResponse(chunks(), media_type = "text/event-stream"))
+ answer = generate(
+ monkeypatch,
+ producer,
+ make_task(model = "external::conn-1::gpt-5-mini", reasoningEffort = "off"),
+ )
+ payload = producer.payload
+ assert (payload.provider_id, payload.external_model, payload.stream) == (
+ "conn-1",
+ "gpt-5-mini",
+ True,
+ )
+ assert payload.reasoning_effort == "none" and payload.enable_thinking is None
+ assert answer.content == "Dawn light."
+ assert answer.provider == config
+
+
def test_a_new_chat_per_run_can_go_to_a_project_and_be_archived():
make_project()
task, run = claim_manual_run()
@@ -1472,3 +2104,189 @@ def test_the_system_prompt_falls_back_to_utc_for_an_unknown_zone():
{"timezone": "Gone/Zone"}, ms("2026-10-14T06:00:00+00:00")
)
assert "Wednesday, October 14, 2026 at 06:00 (Gone/Zone)" in prompt
+
+
+def test_a_carried_swap_restores_the_model_the_user_picked_since(monkeypatch):
+ world = SwapWorld(monkeypatch)
+ holder = scheduler_module.SwapHolder()
+ first = make_task(model = SwapWorld.TASK_MODEL, allowModelLoad = True)
+ run_held(world, monkeypatch, first, {"id": "run-1", "source": "schedule"}, holder)
+ picked = ("/models/llama.gguf", "Q8_0", "unsloth/Llama-3.2-3B-GGUF")
+ world.loaded = picked
+ second = make_task(id = "task-2", model = SwapWorld.TASK_MODEL, allowModelLoad = True)
+ run_held(world, monkeypatch, second, {"id": "run-2", "source": "schedule"}, holder)
+ assert holder.pending.previous == picked
+
+
+def test_switching_back_gives_back_the_restore_requests_admission(monkeypatch):
+ from core.inference import llama_keepwarm
+
+ world = SwapWorld(monkeypatch)
+ before = llama_keepwarm.other_admitted_inference_count()
+ reload = inference_routes._maybe_auto_switch_model
+
+ async def admitting_reload(model, request, subject, **kwargs):
+ llama_keepwarm.note_admitted_inference(request.scope)
+ await reload(model, request, subject, **kwargs)
+
+ monkeypatch.setattr(inference_routes, "_maybe_auto_switch_model", admitting_reload)
+ world.run(monkeypatch, {"id": "run-1", "source": "schedule"})
+ assert world.loaded == SwapWorld.EARLIER
+ assert llama_keepwarm.other_admitted_inference_count() == before
+
+
+def test_a_connection_run_leaves_a_concurrent_local_request_counted(monkeypatch):
+ import json as jsonlib
+
+ from fastapi.responses import StreamingResponse
+ from core.inference import llama_keepwarm
+ from storage import providers_db
+
+ config = {"id": "conn-1", "is_enabled": 1, "display_name": "OpenAI", "provider_type": "openai"}
+ monkeypatch.setattr(providers_db, "get_provider", lambda provider_id: config)
+
+ async def chunks():
+ chunk = {
+ "id": "c1",
+ "model": "gpt-5-mini",
+ "choices": [{"index": 0, "delta": {"content": "Hi."}}],
+ }
+ yield f"data: {jsonlib.dumps(chunk)}\n\n".encode()
+ yield b"data: [DONE]\n\n"
+
+ class ExternalProducer(FakeProducer):
+ async def __call__(self, payload, request, current_subject, *, cancel_on_disconnect):
+ # What the real producer does for a connection, while someone's local chat starts.
+ llama_keepwarm.untrack_current_request(request.scope)
+ llama_keepwarm._note_start()
+ return await super().__call__(
+ payload, request, current_subject, cancel_on_disconnect = cancel_on_disconnect
+ )
+
+ producer = ExternalProducer(StreamingResponse(chunks(), media_type = "text/event-stream"))
+ try:
+ generate(monkeypatch, producer, make_task(model = "external::conn-1::gpt-5-mini"))
+ assert llama_keepwarm.inference_in_flight()
+ finally:
+ llama_keepwarm._note_end()
+
+
[email protected]("may_load", [False, True])
+def test_a_task_model_loaded_alongside_the_primary_answers_without_a_swap(monkeypatch, may_load):
+ from core.inference import model_slots
+
+ world = SwapWorld(monkeypatch)
+ beside = object()
+ monkeypatch.setattr(model_slots, "visible", lambda: [beside])
+ monkeypatch.setattr(
+ model_slots,
+ "serving_slot",
+ lambda requested, candidates, satisfies: beside
+ if requested == SwapWorld.TASK_MODEL
+ else None,
+ )
+ producer = FakeProducer(completion("Dawn light."))
+ monkeypatch.setattr(inference_routes, "produce_openai_chat_completions", producer)
+ task = make_task(model = SwapWorld.TASK_MODEL, allowModelLoad = may_load)
+ app = SimpleNamespace(state = SimpleNamespace())
+ answer = asyncio.run(
+ generate_answer(app, task, {"id": "run-1", "source": "schedule"}, threading.Event())
+ )
+ assert answer.content == "Dawn light." and producer.payload.model == SwapWorld.TASK_MODEL
+ assert world.unloaded == [] and world.reloads == [] and world.loaded == SwapWorld.EARLIER
+
+
+def test_thinking_off_reaches_a_model_kept_beside_a_primary_without_reasoning(monkeypatch):
+ from core.inference import model_slots
+
+ world = SwapWorld(monkeypatch)
+ loaded_gguf(monkeypatch, supports_reasoning = False, model_identifier = "/models/gemma.gguf")
+ beside = object()
+ monkeypatch.setattr(model_slots, "visible", lambda: [beside])
+ monkeypatch.setattr(
+ model_slots,
+ "serving_slot",
+ lambda requested, candidates, satisfies: beside
+ if requested == SwapWorld.TASK_MODEL
+ else None,
+ )
+ producer = FakeProducer(completion("Dawn light."))
+ monkeypatch.setattr(inference_routes, "produce_openai_chat_completions", producer)
+ task = make_task(model = SwapWorld.TASK_MODEL, reasoningEffort = "off")
+ asyncio.run(
+ generate_answer(
+ SimpleNamespace(state = SimpleNamespace()),
+ task,
+ {"id": "run-1", "source": "schedule"},
+ threading.Event(),
+ )
+ )
+ assert producer.payload.enable_thinking is False
+ assert world.unloaded == [] and world.loaded == SwapWorld.EARLIER
+
+
+def test_switching_back_reloads_a_transformers_model_the_run_replaced_by_name(monkeypatch):
+ world = SwapWorld(monkeypatch, earlier = None)
+ backend = SimpleNamespace(active_model_name = "Qwen/Qwen3-0.6B")
+ monkeypatch.setattr(inference_routes, "get_inference_backend", lambda: backend)
+ reloads = []
+
+ async def reload(model, request, subject, **kwargs):
+ reloads.append(
+ (
+ model,
+ inference_routes._model_switch_allowed_for_request(request),
+ request.scope.get(inference_routes.LOADED_MODELS_ONLY_SCOPE_KEY, False),
+ )
+ )
+ world.loaded, backend.active_model_name = None, model
+
+ monkeypatch.setattr(inference_routes, "_maybe_auto_switch_model", reload)
+
+ class ReplacesIt(FakeProducer):
+ async def __call__(self, payload, request, current_subject, *, cancel_on_disconnect):
+ backend.active_model_name = None
+ world.loaded = ("/models/qwen.gguf", "Q4_K_M", SwapWorld.TASK_MODEL)
+ return await super().__call__(
+ payload, request, current_subject, cancel_on_disconnect = cancel_on_disconnect
+ )
+
+ world.run(monkeypatch, {"id": "run-1", "source": "manual"}, ReplacesIt(completion("Ok.")))
+ assert world.unloaded == ["/models/qwen.gguf"]
+ assert reloads == [("Qwen/Qwen3-0.6B", True, False)]
+ assert backend.active_model_name == "Qwen/Qwen3-0.6B"
+
+
+def test_switching_back_unloads_a_non_gguf_task_model_first(monkeypatch):
+ world = SwapWorld(monkeypatch)
+ backend = SimpleNamespace(active_model_name = None)
+ monkeypatch.setattr(inference_routes, "get_inference_backend", lambda: backend)
+ monkeypatch.setattr(
+ inference_routes,
+ "_loaded_satisfies",
+ lambda model: (backend.active_model_name == model)
+ or (world.loaded is not None and world.loaded[2] == model),
+ )
+
+ class LoadsATransformersModel(FakeProducer):
+ async def __call__(self, payload, request, current_subject, *, cancel_on_disconnect):
+ # A Transformers checkpoint replaces the GGUF: no GGUF identity is left.
+ world.loaded = None
+ backend.active_model_name = SwapWorld.TASK_MODEL
+ return await super().__call__(
+ payload, request, current_subject, cancel_on_disconnect = cancel_on_disconnect
+ )
+
+ async def unload(request, subject):
+ world.unloaded.append(request.model_path)
+ backend.active_model_name = None
+ world.loaded = None
+
+ monkeypatch.setattr(inference_routes, "_unload_model_impl", unload)
+ world.run(
+ monkeypatch,
+ {"id": "run-1", "source": "schedule"},
+ LoadsATransformersModel(completion("Ok.")),
+ )
+ assert world.unloaded == [SwapWorld.TASK_MODEL]
+ assert world.loaded == SwapWorld.EARLIER
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index c880e499021..f2232e6f20b 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -346,6 +346,11 @@ export {
isExternalModelId,
parseExternalModelId,
} from "./external-providers";
+export type { ExternalProviderConfig } from "./external-providers";
+export {
+ externalReasoningTakesEffort,
+ getExternalReasoningCapabilities,
+} from "./provider-capabilities";
// A provider catalogue lands async, so capability reads need to re-run when it does.
export { modelCatalogVersion, subscribeModelCatalog } from "./model-catalog";
// What a per-model reasoning pin displaced in the live runtime, so clearing it can put it back.
diff --git a/studio/frontend/src/features/scheduled-tasks/api.ts b/studio/frontend/src/features/scheduled-tasks/api.ts
index cd366668d6a..7abc587d576 100644
--- a/studio/frontend/src/features/scheduled-tasks/api.ts
+++ b/studio/frontend/src/features/scheduled-tasks/api.ts
@@ -10,6 +10,17 @@ export const SCHEDULED_TASKS_API = "/api/scheduled-tasks";
export type TaskRunStatus = "queued" | "running" | "succeeded" | "failed";
export type TaskNotify = "all" | "failures" | "none";
+/** lowest/highest are relative ends resolved per run for local models; null = model default. */
+export type TaskReasoningEffort =
+ | "off"
+ | "lowest"
+ | "highest"
+ | "minimal"
+ | "low"
+ | "medium"
+ | "high"
+ | "xhigh"
+ | "max";
export interface ScheduledTaskRun {
id: string;
@@ -29,6 +40,7 @@ export interface ScheduledTaskRun {
export interface FinishedScheduledTaskRun extends ScheduledTaskRun {
taskTitle: string;
taskNotify: TaskNotify;
+ taskModel: string | null;
}
export interface ScheduledTask {
@@ -40,6 +52,9 @@ export interface ScheduledTask {
enabled: boolean;
notify: TaskNotify;
named: boolean;
+ model: string | null;
+ reasoningEffort: TaskReasoningEffort | null;
+ allowModelLoad: boolean;
archiveSuccessful: boolean;
projectId: string | null;
status: "active" | "paused" | "completed";
@@ -56,6 +71,9 @@ export interface ScheduledTaskInput {
timezone: string;
notify: TaskNotify;
named: boolean;
+ model?: string | null;
+ reasoningEffort?: TaskReasoningEffort | null;
+ allowModelLoad?: boolean;
archiveSuccessful?: boolean;
projectId?: string | null;
}
@@ -118,8 +136,11 @@ export function deleteScheduledTask(id: string): Promise<void> {
return request(taskPath(id), { method: "DELETE" });
}
-export function runScheduledTaskNow(id: string): Promise<ScheduledTaskRun> {
- return request(taskPath(id, "/run"), { method: "POST" });
+export function runScheduledTaskNow(id: string, loadModel = false): Promise<ScheduledTaskRun> {
+ return request(taskPath(id, "/run"), {
+ method: "POST",
+ ...(loadModel ? { body: JSON.stringify({ loadModel: true }) } : {}),
+ });
}
export function getScheduledTaskActivity(since: number | null): Promise<ScheduledTaskActivity> {
diff --git a/studio/frontend/src/features/scheduled-tasks/model-load-prompt.tsx b/studio/frontend/src/features/scheduled-tasks/model-load-prompt.tsx
new file mode 100644
index 00000000000..c55d9b270c2
--- /dev/null
+++ b/studio/frontend/src/features/scheduled-tasks/model-load-prompt.tsx
@@ -0,0 +1,80 @@
+// 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 { useId, useState } from "react";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Checkbox } from "@/components/ui/checkbox";
+import { useT } from "@/i18n";
+import { toast } from "@/lib/toast";
+import type { FinishedScheduledTaskRun } from "./api";
+import { useScheduledTasksStore } from "./store";
+
+function modelName(model: string): string {
+ return model.split(/[\\/]/).filter(Boolean).pop() ?? model;
+}
+
+/** Asks whether a task may load its model, which replaces the one in Chat: once, or for good. */
+export default function ModelLoadPrompt({
+ run,
+ onDone,
+}: {
+ run: FinishedScheduledTaskRun;
+ onDone: () => void;
+}) {
+ const t = useT();
+ const checkboxId = useId();
+ const [always, setAlways] = useState(false);
+ const model = modelName(run.taskModel ?? "");
+
+ async function load() {
+ onDone();
+ const { update, runNow } = useScheduledTasksStore.getState();
+ try {
+ if (always) await update(run.taskId, { allowModelLoad: true });
+ await runNow(run.taskId, true);
+ } catch (error) {
+ toast.error(t("scheduledTasks.errors.runFailed"), {
+ description: error instanceof Error ? error.message : undefined,
+ });
+ }
+ }
+
+ return (
+ <AlertDialog open={true} onOpenChange={(open) => !open && onDone()}>
+ <AlertDialogContent onOverlayClick={onDone}>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t("scheduledTasks.loadPrompt.title", { model })}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t("scheduledTasks.loadPrompt.description", { title: run.taskTitle, model })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <label htmlFor={checkboxId} className="flex cursor-pointer items-start gap-2.5 text-ui-14">
+ <Checkbox
+ id={checkboxId}
+ checked={always}
+ onCheckedChange={(on) => setAlways(on === true)}
+ className="mt-0.5"
+ />
+ {t("scheduledTasks.loadPrompt.always")}
+ </label>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t("scheduledTasks.loadPrompt.notNow")}</AlertDialogCancel>
+ <AlertDialogAction onClick={() => void load()}>
+ {t("scheduledTasks.loadPrompt.load")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/studio/frontend/src/features/scheduled-tasks/results.ts b/studio/frontend/src/features/scheduled-tasks/results.ts
index 6ed68559c33..f10e351240c 100644
--- a/studio/frontend/src/features/scheduled-tasks/results.ts
+++ b/studio/frontend/src/features/scheduled-tasks/results.ts
@@ -180,10 +180,28 @@ export function readInRecents(
return threads.filter((id) => before.has(id) && !now.has(id));
}
+/** A run that stopped because its model was not loaded and awaits a yes (not `model_busy`, which reports as skipped). */
+export function asksToLoadModel(run: { errorCode: string | null; taskModel?: string | null }): boolean {
+ return run.errorCode === "model_not_loaded" && Boolean(run.taskModel);
+}
+
+/** Runs asking to load their task's model, newest per task, regardless of the task's Notifications. */
+export function runsAskingToLoad<
+ T extends { taskId: string; errorCode: string | null; taskModel?: string | null },
+>(runs: readonly T[]): T[] {
+ const byTask = new Map<string, T>();
+ for (const run of runs) if (asksToLoadModel(run)) byTask.set(run.taskId, run);
+ return [...byTask.values()];
+}
+
type Translate = (key: TranslationKey, values?: InterpolationValues) => string;
const ERROR_KEYS: Record<string, TranslationKey> = {
no_model: "scheduledTasks.errors.noModel",
+ model_not_loaded: "scheduledTasks.errors.modelNotLoaded",
+ model_load_failed: "scheduledTasks.errors.modelLoadFailed",
+ model_busy: "scheduledTasks.errors.modelBusy",
+ connection_unavailable: "scheduledTasks.errors.connectionUnavailable",
timeout: "scheduledTasks.errors.timeout",
cancelled: "scheduledTasks.errors.cancelled",
interrupted: "scheduledTasks.errors.interrupted",
diff --git a/studio/frontend/src/features/scheduled-tasks/run-notifier.tsx b/studio/frontend/src/features/scheduled-tasks/run-notifier.tsx
index 2afb401218d..b6ef47c05f0 100644
--- a/studio/frontend/src/features/scheduled-tasks/run-notifier.tsx
+++ b/studio/frontend/src/features/scheduled-tasks/run-notifier.tsx
@@ -2,7 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useNavigate, useRouterState } from "@tanstack/react-router";
-import { useEffect, useRef } from "react";
+import { Suspense, lazy, useEffect, useRef, useState } from "react";
import { AUTH_SESSION_STORED_EVENT, getAuthSessionEpoch, hasSettledAuthSession } from "@/features/auth";
import { notifyChatHistoryUpdated, useChatNavigationStore } from "@/features/chat";
import { translate } from "@/i18n";
@@ -13,6 +13,7 @@ import { toast } from "@/lib/toast";
import { type FinishedScheduledTaskRun, getScheduledTaskActivity } from "./api";
import {
IDLE_POLL_MS,
+ asksToLoadModel,
SCHEDULED_TASKS_CHANGED_EVENT,
SCHEDULED_TASKS_WRITTEN_KEY,
SCHEDULED_TASK_RUNS_FINISHED_EVENT,
@@ -25,6 +26,7 @@ import {
readSeenRuns,
runErrorText,
runsToAnnounce,
+ runsAskingToLoad,
runsToNotify,
readInRecents,
unseenChatChanges,
@@ -34,6 +36,7 @@ import { useUnseenScheduledRuns } from "./unseen";
// More than this at once, e.g. on reopening Studio, and one toast speaks for them all.
const INDIVIDUAL_TOASTS = 2;
+const ModelLoadPrompt = lazy(() => import("./model-load-prompt"));
const RECHECK_MS = 500;
// Lock one tab holds while claiming what to announce (account name appended).
const ANNOUNCE_LOCK_PREFIX = "unsloth-scheduled-task-results:";
@@ -119,6 +122,7 @@ function notifySystem(runs: FinishedScheduledTaskRun[]): void {
/** Watches for scheduled results: refreshes Recents, marks chats unread, toasts and notifies. Renders nothing. */
export function ScheduledTaskRunNotifier() {
const navigate = useNavigate();
+ const [asking, setAsking] = useState<FinishedScheduledTaskRun[]>([]);
const navigateRef = useRef(navigate);
const pathname = useRouterState({ select: (state) => state.location.pathname });
const pathnameRef = useRef(pathname);
@@ -193,7 +197,14 @@ export function ScheduledTaskRunNotifier() {
})),
pathnameRef.current === "/tasks",
);
- const notified = runsToNotify(runs);
+ const asks = runsAskingToLoad(runs);
+ if (asks.length > 0) {
+ setAsking((current) => [
+ ...current.filter((run) => !asks.some((ask) => ask.taskId === run.taskId)),
+ ...asks,
+ ]);
+ }
+ const notified = runsToNotify(runs.filter((run) => !asksToLoadModel(run)));
if (notified.length === 0) return;
if (notified.length > INDIVIDUAL_TOASTS) {
toast(translate("scheduledTasks.toast.many", { count: notified.length }), {
@@ -303,5 +314,16 @@ export function ScheduledTaskRunNotifier() {
};
}, []);
- return null;
+ const ask = asking[0];
+ if (!ask) return null;
+ return (
+ <Suspense fallback={null}>
+ <ModelLoadPrompt
+ key={ask.id}
+ run={ask}
+ // By id: Load and run closes the dialog too, and both must not drop the next prompt.
+ onDone={() => setAsking((current) => current.filter((run) => run.id !== ask.id))}
+ />
+ </Suspense>
+ );
}
diff --git a/studio/frontend/src/features/scheduled-tasks/store.ts b/studio/frontend/src/features/scheduled-tasks/store.ts
index 8062c8077d8..e00a2f9488b 100644
--- a/studio/frontend/src/features/scheduled-tasks/store.ts
+++ b/studio/frontend/src/features/scheduled-tasks/store.ts
@@ -42,7 +42,7 @@ interface ScheduledTasksState {
create: (input: ScheduledTaskInput) => Promise<ScheduledTask>;
update: (id: string, patch: ScheduledTaskPatch) => Promise<ScheduledTask>;
remove: (id: string) => Promise<void>;
- runNow: (id: string) => Promise<void>;
+ runNow: (id: string, loadModel?: boolean) => Promise<void>;
}
let refreshGeneration = 0;
@@ -130,9 +130,9 @@ export const useScheduledTasksStore = create<ScheduledTasksState>()((set, get) =
// Its chat survives but the run record went with the task, so the results poll never reports it.
notifyChatHistoryUpdated();
},
- runNow: async (id) => {
+ runNow: async (id, loadModel = false) => {
await write(
- () => runScheduledTaskNow(id),
+ () => runScheduledTaskNow(id, loadModel),
(run) =>
set((state) => ({
tasks: state.tasks.map((task) =>
diff --git a/studio/frontend/src/features/scheduled-tasks/task-dialog.tsx b/studio/frontend/src/features/scheduled-tasks/task-dialog.tsx
index 1c2d02f2187..d60eef809db 100644
--- a/studio/frontend/src/features/scheduled-tasks/task-dialog.tsx
+++ b/studio/frontend/src/features/scheduled-tasks/task-dialog.tsx
@@ -1,9 +1,9 @@
// 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 { Folder01Icon } from "@hugeicons/core-free-icons";
+import { Folder01Icon, InformationCircleIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { type ReactNode, useId, useRef, useState } from "react";
+import { type ReactNode, useId, useMemo, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -17,20 +17,33 @@ import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
+ SelectGroup,
SelectItem,
+ SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
-import { useChatProjects } from "@/features/chat";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import {
+ buildExternalModelId,
+ chatLocalModelOptions,
+ type ExternalProviderConfig,
+ externalReasoningTakesEffort,
+ getExternalReasoningCapabilities,
+ useChatProjects,
+ useChatRuntimeStore,
+ useExternalProvidersStore,
+} from "@/features/chat";
+import { useDeviceInventorySources } from "@/features/hub";
import { type TranslationKey, useLocale, useT } from "@/i18n";
import { isTauri } from "@/lib/api-base";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { primeNativeNotificationPermission } from "@/lib/native-notifications";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
-import type { ScheduledTask, ScheduledTaskPatch, TaskNotify } from "./api";
+import type { ScheduledTask, ScheduledTaskPatch, TaskNotify, TaskReasoningEffort } from "./api";
import {
ISO_WEEKDAYS,
REPEAT_KINDS,
@@ -77,12 +90,35 @@ function askToNotify(): void {
}
}
-function Row({ id, label, children }: { id?: string; label: string; children: ReactNode }) {
+function Row({
+ id,
+ label,
+ hint,
+ children,
+}: { id?: string; label: string; hint?: string; children: ReactNode }) {
return (
<div className="flex min-h-14 flex-wrap items-center justify-between gap-x-4 gap-y-2 px-5 py-2">
- <label htmlFor={id} className="text-ui-15 text-foreground">
- {label}
- </label>
+ <span className="flex items-center gap-1.5">
+ <label htmlFor={id} className="text-ui-15 text-foreground">
+ {label}
+ </label>
+ {hint && (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={hint}
+ className="inline-flex rounded text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <HugeiconsIcon icon={InformationCircleIcon} className="size-[var(--ui-icon-size-hint)]" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-[calc(300px*var(--ui-space-scale,1))] text-ui-11 leading-snug">
+ {hint}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </span>
{children}
</div>
);
@@ -99,8 +135,89 @@ const BARE_INPUT =
const LONG_LIST =
"max-h-[min(--spacing(72),var(--radix-select-content-available-height))] [&_[data-slot^=select-scroll]]:bg-transparent";
-// Select values cannot be empty, so null (no project) has a stand-in.
+// Select values cannot be empty, so null (the loaded model, the model's default) has a stand-in.
+const LOADED_MODEL = "__loaded__";
const NO_PROJECT = "__none__";
+const DEFAULT_EFFORT = "__default__";
+const RELATIVE_LABELS: Partial<Record<TaskReasoningEffort, TranslationKey>> = {
+ off: "scheduledTasks.form.reasoningOff",
+ lowest: "scheduledTasks.form.reasoningLowest",
+ highest: "scheduledTasks.form.reasoningHighest",
+};
+const ALL_EFFORTS: readonly TaskReasoningEffort[] = ["off", "lowest", "highest"];
+const CONNECTION_LEVELS: readonly TaskReasoningEffort[] = ["minimal", "low", "medium", "high", "xhigh", "max"];
+
+/** A connection's level as the Chat composer names it (formatReasoningEffortLabel). */
+function levelLabel(level: TaskReasoningEffort, modelId: string | undefined): string {
+ if (level === "max") return "Max";
+ if (level === "xhigh") {
+ const normalized = modelId?.trim().toLowerCase() ?? "";
+ return normalized.startsWith("claude-opus-4-6") || normalized.startsWith("claude-sonnet-4-6")
+ ? "Max"
+ : "Extra High";
+ }
+ return level.charAt(0).toUpperCase() + level.slice(1);
+}
+
+type LoadedReasoning = { supportsReasoning: boolean; reasoningStyle: string; reasoningAlwaysOn: boolean };
+
+type ConnectionChoice = { id: string; modelId: string; provider: ExternalProviderConfig };
+
+/** Models a task can run on: local and connected providers, never one needing a download. */
+function useModelChoices(current: string | null) {
+ const inventory = useDeviceInventorySources(["localModels", "cachedGguf"]);
+ const providers = useExternalProvidersStore((state) => state.providers);
+ const connectionsEnabled = useExternalProvidersStore((state) => state.connectionsEnabled);
+ return useMemo(() => {
+ const local = chatLocalModelOptions(inventory.localModels.rows).map(({ id, name }) => ({ id, name }));
+ // GGUF only: a run switches back afterwards only to a GGUF.
+ for (const repo of inventory.cachedGguf.rows) {
+ if (!local.some((option) => option.id === repo.repo_id)) {
+ local.push({ id: repo.repo_id, name: repo.repo_id });
+ }
+ }
+ const connections = (connectionsEnabled ? providers : []).map((provider) => ({
+ provider,
+ models: provider.models.map(
+ (modelId): ConnectionChoice => ({ id: buildExternalModelId(provider.id, modelId), modelId, provider }),
+ ),
+ }));
+ const known =
+ current === null ||
+ local.some((option) => option.id === current) ||
+ connections.some((group) => group.models.some((option) => option.id === current));
+ // A saved choice that is gone (deleted, disconnected) stays visible rather than silently changing.
+ const missing = known ? null : current;
+ const connection = connections.flatMap((group) => group.models).find((option) => option.id === current);
+ return { local, connections, missing, connection };
+ }, [inventory.localModels.rows, inventory.cachedGguf.rows, providers, connectionsEnabled, current]);
+}
+
+/** Efforts the task's model takes; all of them for an unloaded model (a run resolves it), empty when none. */
+function effortChoices(
+ connection: ConnectionChoice | undefined,
+ loaded: LoadedReasoning | null,
+): readonly TaskReasoningEffort[] {
+ if (!connection) {
+ if (!loaded) return ALL_EFFORTS;
+ if (!loaded.supportsReasoning) return [];
+ return loaded.reasoningAlwaysOn || loaded.reasoningStyle === "reasoning_effort"
+ ? ["lowest", "highest"]
+ : ALL_EFFORTS;
+ }
+ const { provider, modelId } = connection;
+ const caps = getExternalReasoningCapabilities(provider.providerType, modelId, {
+ isReasoningProvider: provider.isReasoningModel === true,
+ baseUrl: provider.baseUrl ?? null,
+ apiType: provider.apiType,
+ reasoningConfig: provider.reasoningConfig,
+ });
+ if (!externalReasoningTakesEffort(caps)) return [];
+ const levels = CONNECTION_LEVELS.filter((level) =>
+ (caps.reasoningEffortLevels as readonly string[]).includes(level),
+ );
+ return caps.supportsReasoningOff ? ["off", ...levels] : levels;
+}
export function TaskDialog({
task,
@@ -125,10 +242,24 @@ export function TaskDialog({
task ? formFromSchedule(task.schedule, now) : defaultScheduleForm(now),
);
const [notify, setNotify] = useState<TaskNotify>(task?.notify ?? "all");
+ const [model, setModel] = useState<string | null>(task?.model ?? null);
+ const [allowLoad, setAllowLoad] = useState(task?.allowModelLoad ?? false);
const [archiveSuccessful, setArchiveSuccessful] = useState(task?.archiveSuccessful ?? false);
const [projectId, setProjectId] = useState<string | null>(task?.projectId ?? null);
const { projects } = useChatProjects();
const openProjects = projects.filter((project) => !project.archived || project.id === projectId);
+ const [chosenEffort, setEffort] = useState<TaskReasoningEffort | null>(task?.reasoningEffort ?? null);
+ const models = useModelChoices(model);
+ const checkpoint = useChatRuntimeStore((state) => state.params.checkpoint);
+ const supportsReasoning = useChatRuntimeStore((state) => state.supportsReasoning);
+ const reasoningStyle = useChatRuntimeStore((state) => state.reasoningStyle);
+ const reasoningAlwaysOn = useChatRuntimeStore((state) => state.reasoningAlwaysOn);
+ const loadedReasoning =
+ checkpoint && !models.connection && (model === null || model === checkpoint)
+ ? { supportsReasoning, reasoningStyle, reasoningAlwaysOn }
+ : null;
+ const efforts = effortChoices(models.connection, loadedReasoning);
+ const effort = chosenEffort !== null && efforts.includes(chosenEffort) ? chosenEffort : null;
const [advanced, setAdvanced] = useState(
() =>
task !== null &&
@@ -163,6 +294,10 @@ export function TaskDialog({
if (!sameSchedule(schedule, task.schedule)) patch.schedule = schedule;
if (named !== task.named) patch.named = named;
if (notify !== task.notify) patch.notify = notify;
+ if (model !== task.model) patch.model = model;
+ // Only a changed choice: a saved level the current model does not offer is kept, not cleared.
+ if (chosenEffort !== task.reasoningEffort) patch.reasoningEffort = effort;
+ if (allowLoad !== task.allowModelLoad) patch.allowModelLoad = allowLoad;
if (archiveSuccessful !== task.archiveSuccessful) patch.archiveSuccessful = archiveSuccessful;
if (projectId !== task.projectId) patch.projectId = projectId;
if (Object.keys(patch).length > 0) await update(task.id, patch);
@@ -174,6 +309,9 @@ export function TaskDialog({
timezone,
notify,
named,
+ model,
+ reasoningEffort: effort,
+ allowModelLoad: allowLoad,
archiveSuccessful,
projectId,
});
@@ -248,6 +386,103 @@ export function TaskDialog({
<p id={`${ids}-prompt-hint`} className="sr-only">
{t("scheduledTasks.form.instructionsHint")}
</p>
+ <div className={CARD}>
+ <Row id={`${ids}-model`} label={t("scheduledTasks.form.model")}>
+ <Select
+ value={model ?? LOADED_MODEL}
+ onValueChange={(value) => setModel(value === LOADED_MODEL ? null : value)}
+ disabled={busy}
+ >
+ <SelectTrigger id={`${ids}-model`} className={cn(BARE_SELECT, "max-w-[60%]")}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end" className={cn(LONG_LIST, "max-w-80")}>
+ <SelectItem value={LOADED_MODEL}>{t("scheduledTasks.form.modelLoaded")}</SelectItem>
+ {models.missing && (
+ <SelectItem value={models.missing}>
+ {t("scheduledTasks.form.modelMissing", { model: models.missing })}
+ </SelectItem>
+ )}
+ {models.local.length > 0 && (
+ <SelectGroup>
+ <SelectLabel>{t("scheduledTasks.form.modelOnDevice")}</SelectLabel>
+ {models.local.map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ {option.name}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ )}
+ {models.connections.map(
+ (group) =>
+ group.models.length > 0 && (
+ <SelectGroup key={group.provider.id}>
+ <SelectLabel>{group.provider.name}</SelectLabel>
+ {group.models.map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ {option.modelId}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ ),
+ )}
+ {models.local.length === 0 && models.connections.every((group) => group.models.length === 0) && (
+ <p className="max-w-64 px-3 py-2 text-ui-12 text-muted-foreground">
+ {t("scheduledTasks.form.modelEmpty")}
+ </p>
+ )}
+ </SelectContent>
+ </Select>
+ </Row>
+ {model !== null && !models.connection && (
+ <Row
+ id={`${ids}-allow-load`}
+ label={t("scheduledTasks.form.allowLoad")}
+ hint={t("scheduledTasks.form.allowLoadHint")}
+ >
+ <Switch
+ id={`${ids}-allow-load`}
+ checked={allowLoad}
+ onCheckedChange={setAllowLoad}
+ disabled={busy}
+ className="mr-2"
+ />
+ </Row>
+ )}
+ {efforts.length > 0 && (
+ <Row id={`${ids}-effort`} label={t("scheduledTasks.form.reasoning")}>
+ <Select
+ value={effort ?? DEFAULT_EFFORT}
+ onValueChange={(value) =>
+ setEffort(value === DEFAULT_EFFORT ? null : (value as TaskReasoningEffort))
+ }
+ disabled={busy}
+ >
+ <SelectTrigger id={`${ids}-effort`} className={BARE_SELECT}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ {efforts.includes("off") && (
+ <SelectItem value="off">{t("scheduledTasks.form.reasoningOff")}</SelectItem>
+ )}
+ <SelectItem value={DEFAULT_EFFORT}>{t("scheduledTasks.form.reasoningDefault")}</SelectItem>
+ {efforts.filter((choice) => choice !== "off").map((choice) => (
+ <SelectItem key={choice} value={choice}>
+ {RELATIVE_LABELS[choice]
+ ? t(RELATIVE_LABELS[choice])
+ : levelLabel(choice, models.connection?.modelId)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Row>
+ )}
+ </div>
+ {model !== null && !models.connection && (
+ <p className="-mt-2 px-1 text-ui-13 text-muted-foreground">
+ {allowLoad ? t("scheduledTasks.form.modelNoteAllowed") : t("scheduledTasks.form.modelNote")}
+ </p>
+ )}
<div className={CARD}>
<Row id={`${ids}-repeat`} label={t("scheduledTasks.form.repeat")}>
<Select
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index fbb26f89f41..61d16131cf8 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -4363,6 +4363,21 @@ export const ar = {
archiveSuccessful: "أرشفة عمليات التشغيل الناجحة",
project: "المشروع",
projectNone: "بلا",
+ model: "النموذج",
+ modelLoaded: "أي نموذج محمّل",
+ modelOnDevice: "على هذا الجهاز",
+ modelNote: "إذا لم يكن هذا النموذج محمّلًا عند تشغيل المهمة، يسألك Unsloth أولًا.",
+ modelNoteAllowed: "ينتقل إلى هذا النموذج فقط أثناء ابتعادك عن Unsloth، ثم يعود إلى ما كان لديك.",
+ modelEmpty: "نزّل نموذجًا من مركز النماذج أو أضف اتصالًا لاختيار نموذج آخر.",
+ modelMissing: "{model} (ليس على هذا الجهاز)",
+ allowLoad: "التبديل تلقائيًا أثناء ابتعادي",
+ allowLoadHint:
+ "عندما يحين موعد هذه المهمة ولم تستخدم Unsloth منذ 5 دقائق، تحمّل هذا النموذج دون سؤال وتنفّذ المهمة ثم تعود إلى النموذج الذي كان لديك. إذا كنت تستخدم Unsloth أو يجري تدريب في ذلك الوقت، يتم تخطي التشغيل ويبقى نموذجك كما هو. عند إيقاف الخيار، يسأل Unsloth قبل التحميل.",
+ reasoning: "جهد التفكير",
+ reasoningDefault: "افتراضي",
+ reasoningOff: "إيقاف",
+ reasoningLowest: "الأدنى",
+ reasoningHighest: "الأعلى",
create: "إنشاء",
},
deleteDialog: {
@@ -4371,6 +4386,10 @@ export const ar = {
},
errors: {
noModel: "لم يكن هناك نموذج مُحمَّل. حمّل نموذجًا في المحادثة، ثم شغّل المهمة مرة أخرى.",
+ modelNotLoaded: "لم يكن نموذج المهمة محمّلًا. حمّله في الدردشة ثم شغّل المهمة مجددًا.",
+ modelLoadFailed: "تعذّر تحميل نموذج المهمة. تأكّد أنه لا يزال منزّلًا في مركز النماذج.",
+ modelBusy: "تم تخطيها أثناء استخدامك Unsloth، فلم يتغيّر نموذجك.",
+ connectionUnavailable: "اتصال المهمة مفقود أو متوقف. تحقّق منه في الاتصالات.",
timeout: "استغرق النموذج وقتًا طويلًا جدًا للإجابة.",
cancelled: "توقف التشغيل قبل اكتماله.",
interrupted: "أُغلق Unsloth قبل اكتمال التشغيل.",
@@ -4381,6 +4400,13 @@ export const ar = {
deleteFailed: "تعذّر حذف المهمة",
runFailed: "تعذّر بدء المهمة",
},
+ loadPrompt: {
+ title: "تحميل {model}؟",
+ description: "تعمل «{title}» على {model}، وهو غير محمّل. تشغيلها ينقل الدردشة إلى {model} حتى تنتهي، ثم يعيدها.",
+ always: "لا تسألني مجددًا. بدّل فقط أثناء ابتعادي عن Unsloth.",
+ notNow: "ليس الآن",
+ load: "تحميل وتشغيل",
+ },
toast: {
finished: "«{title}» جاهزة",
failed: "فشلت «{title}»",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 13d7205e199..60f23556232 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -4438,6 +4438,21 @@ export const de = {
archiveSuccessful: "Erfolgreiche Ausführungen archivieren",
project: "Projekt",
projectNone: "Keins",
+ model: "Modell",
+ modelLoaded: "Das jeweils geladene Modell",
+ modelOnDevice: "Auf diesem Gerät",
+ modelNote: "Ist dieses Modell beim Ausführen nicht geladen, fragt Unsloth zuerst.",
+ modelNoteAllowed: "Wechselt nur zu diesem Modell, während Sie Unsloth nicht nutzen, und danach zurück.",
+ modelEmpty: "Laden Sie ein Modell im Model Hub herunter oder fügen Sie eine Verbindung hinzu, um ein anderes zu wählen.",
+ modelMissing: "{model} (nicht auf diesem Gerät)",
+ allowLoad: "Automatisch wechseln, wenn ich weg bin",
+ allowLoadHint:
+ "Wenn diese Aufgabe fällig ist und du Unsloth seit 5 Minuten nicht benutzt hast, lädt sie dieses Modell ohne Nachfrage, führt die Aufgabe aus und wechselt dann zurück zu deinem vorherigen Modell. Benutzt du Unsloth gerade oder läuft ein Training, wird der Lauf übersprungen und dein Modell bleibt unverändert. Ist die Option aus, fragt Unsloth vor dem Laden.",
+ reasoning: "Denkaufwand",
+ reasoningDefault: "Standard",
+ reasoningOff: "Aus",
+ reasoningLowest: "Niedrigste",
+ reasoningHighest: "Höchste",
create: "Erstellen",
},
deleteDialog: {
@@ -4446,6 +4461,10 @@ export const de = {
},
errors: {
noModel: "Es war kein Modell geladen. Laden Sie im Chat ein Modell und führen Sie die Aufgabe erneut aus.",
+ modelNotLoaded: "Das Modell der Aufgabe war nicht geladen. Laden Sie es im Chat und führen Sie die Aufgabe erneut aus.",
+ modelLoadFailed: "Das Modell der Aufgabe konnte nicht geladen werden. Prüfen Sie, ob es im Model Hub noch heruntergeladen ist.",
+ modelBusy: "Übersprungen, während Sie Unsloth genutzt haben; Ihr Modell blieb unverändert.",
+ connectionUnavailable: "Die Verbindung der Aufgabe fehlt oder ist deaktiviert. Prüfen Sie sie unter Verbindungen.",
timeout: "Das Modell hat zu lange für die Antwort gebraucht.",
cancelled: "Die Ausführung wurde vor dem Ende gestoppt.",
interrupted: "Unsloth wurde geschlossen, bevor die Ausführung fertig war.",
@@ -4456,6 +4475,13 @@ export const de = {
deleteFailed: "Aufgabe konnte nicht gelöscht werden",
runFailed: "Aufgabe konnte nicht gestartet werden",
},
+ loadPrompt: {
+ title: "{model} laden?",
+ description: "„{title}“ läuft mit {model}, das nicht geladen ist. Beim Ausführen wechselt der Chat bis zum Ende zu {model}, danach zurück.",
+ always: "Nicht mehr fragen. Nur wechseln, während ich Unsloth nicht nutze.",
+ notNow: "Nicht jetzt",
+ load: "Laden und ausführen",
+ },
toast: {
finished: "„{title}“ ist fertig",
failed: "„{title}“ ist fehlgeschlagen",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index a4caf868793..80c338bc434 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -4425,6 +4425,21 @@ export const en = {
archiveSuccessful: "Archive successful runs",
project: "Project",
projectNone: "None",
+ model: "Model",
+ modelLoaded: "Whichever model is loaded",
+ modelOnDevice: "On this device",
+ modelNote: "If this model isn't loaded when the task runs, Unsloth asks first.",
+ modelNoteAllowed: "Loads this model only while you're away from Unsloth, then puts back what you had.",
+ modelEmpty: "Download a model in Model hub or add a connection to choose another.",
+ modelMissing: "{model} (not on this device)",
+ allowLoad: "Switch automatically when I'm away",
+ allowLoadHint:
+ "When this task is due and you haven't used Unsloth for 5 minutes, it loads this model without asking, runs the task, then switches back to the model you had. If you're using Unsloth or training at that time, the run is skipped and your model is left alone. Off, Unsloth asks before loading.",
+ reasoning: "Thinking effort",
+ reasoningDefault: "Default",
+ reasoningOff: "Off",
+ reasoningLowest: "Lowest",
+ reasoningHighest: "Highest",
create: "Create",
},
deleteDialog: {
@@ -4433,6 +4448,10 @@ export const en = {
},
errors: {
noModel: "No model was loaded. Load a model in Chat, then run the task again.",
+ modelNotLoaded: "The task's model wasn't loaded. Load it in Chat, then run the task again.",
+ modelLoadFailed: "Couldn't load the task's model. Make sure it's still downloaded in Model hub.",
+ modelBusy: "Skipped while you were using Unsloth, so your model was left alone.",
+ connectionUnavailable: "The task's connection is missing or turned off. Check it in Connections.",
timeout: "The model took too long to answer.",
cancelled: "The run was stopped before it finished.",
interrupted: "Unsloth closed before the run finished.",
@@ -4443,6 +4462,14 @@ export const en = {
deleteFailed: "Could not delete the task",
runFailed: "Could not start the task",
},
+ // Asked when a task's model is not loaded: loading it replaces the model in Chat.
+ loadPrompt: {
+ title: "Load {model}?",
+ description: "“{title}” runs on {model}, which isn't loaded. Running it loads {model} until it finishes, then puts back what you had.",
+ always: "Don't ask again. Switch only while I'm away from Unsloth.",
+ notNow: "Not now",
+ load: "Load and run",
+ },
toast: {
finished: "“{title}” is ready",
failed: "“{title}” failed",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 87b4f2d78fe..4e3d63be32f 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -4437,6 +4437,21 @@ export const es = {
archiveSuccessful: "Archivar ejecuciones correctas",
project: "Proyecto",
projectNone: "Ninguno",
+ model: "Modelo",
+ modelLoaded: "El modelo que esté cargado",
+ modelOnDevice: "En este dispositivo",
+ modelNote: "Si este modelo no está cargado cuando se ejecuta la tarea, Unsloth pregunta primero.",
+ modelNoteAllowed: "Cambia a este modelo solo mientras no usas Unsloth y luego vuelve al que tenías.",
+ modelEmpty: "Descarga un modelo en Model Hub o añade una conexión para elegir otro.",
+ modelMissing: "{model} (no está en este dispositivo)",
+ allowLoad: "Cambiar automáticamente cuando no esté",
+ allowLoadHint:
+ "Cuando toca esta tarea y no has usado Unsloth en 5 minutos, carga este modelo sin preguntar, ejecuta la tarea y luego vuelve al modelo que tenías. Si estás usando Unsloth o entrenando en ese momento, la ejecución se omite y tu modelo no se toca. Si está desactivado, Unsloth pregunta antes de cargarlo.",
+ reasoning: "Esfuerzo de pensamiento",
+ reasoningDefault: "Predeterminado",
+ reasoningOff: "Desactivado",
+ reasoningLowest: "Mínimo",
+ reasoningHighest: "Máximo",
create: "Crear",
},
deleteDialog: {
@@ -4445,6 +4460,10 @@ export const es = {
},
errors: {
noModel: "No había ningún modelo cargado. Carga un modelo en el chat y vuelve a ejecutar la tarea.",
+ modelNotLoaded: "El modelo de la tarea no estaba cargado. Cárgalo en el chat y vuelve a ejecutar la tarea.",
+ modelLoadFailed: "No se pudo cargar el modelo de la tarea. Comprueba que siga descargado en Model Hub.",
+ modelBusy: "Omitida mientras usabas Unsloth, así que tu modelo no se tocó.",
+ connectionUnavailable: "La conexión de la tarea no existe o está desactivada. Revísala en Conexiones.",
timeout: "El modelo tardó demasiado en responder.",
cancelled: "La ejecución se detuvo antes de terminar.",
interrupted: "Unsloth se cerró antes de que terminara la ejecución.",
@@ -4455,6 +4474,13 @@ export const es = {
deleteFailed: "No se pudo eliminar la tarea",
runFailed: "No se pudo iniciar la tarea",
},
+ loadPrompt: {
+ title: "¿Cargar {model}?",
+ description: "«{title}» usa {model}, que no está cargado. Ejecutarla cambia el chat a {model} hasta que termine y luego vuelve.",
+ always: "No volver a preguntar. Cambiar solo mientras no uso Unsloth.",
+ notNow: "Ahora no",
+ load: "Cargar y ejecutar",
+ },
toast: {
finished: "«{title}» está lista",
failed: "«{title}» falló",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 92824c8f2c5..bebcc28c5fb 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -4449,6 +4449,21 @@ export const fr = {
archiveSuccessful: "Archiver les exécutions réussies",
project: "Projet",
projectNone: "Aucun",
+ model: "Modèle",
+ modelLoaded: "Le modèle chargé à ce moment-là",
+ modelOnDevice: "Sur cet appareil",
+ modelNote: "Si ce modèle n’est pas chargé au moment de la tâche, Unsloth demande d’abord.",
+ modelNoteAllowed: "Passe à ce modèle uniquement quand vous n’utilisez pas Unsloth, puis revient au vôtre.",
+ modelEmpty: "Téléchargez un modèle dans Model Hub ou ajoutez une connexion pour en choisir un autre.",
+ modelMissing: "{model} (absent de cet appareil)",
+ allowLoad: "Changer automatiquement en mon absence",
+ allowLoadHint:
+ "Quand cette tâche arrive à échéance et que vous n'avez pas utilisé Unsloth depuis 5 minutes, elle charge ce modèle sans demander, exécute la tâche, puis revient au modèle que vous aviez. Si vous utilisez Unsloth ou qu'un entraînement est en cours, l'exécution est ignorée et votre modèle n'est pas touché. Désactivé, Unsloth demande avant de charger.",
+ reasoning: "Effort de réflexion",
+ reasoningDefault: "Par défaut",
+ reasoningOff: "Désactivé",
+ reasoningLowest: "Minimal",
+ reasoningHighest: "Maximal",
create: "Créer",
},
deleteDialog: {
@@ -4457,6 +4472,10 @@ export const fr = {
},
errors: {
noModel: "Aucun modèle n’était chargé. Chargez un modèle dans le chat, puis relancez la tâche.",
+ modelNotLoaded: "Le modèle de la tâche n’était pas chargé. Chargez-le dans le chat, puis relancez la tâche.",
+ modelLoadFailed: "Impossible de charger le modèle de la tâche. Vérifiez qu’il est toujours téléchargé dans Model Hub.",
+ modelBusy: "Ignorée pendant que vous utilisiez Unsloth ; votre modèle n’a pas été touché.",
+ connectionUnavailable: "La connexion de la tâche est introuvable ou désactivée. Vérifiez-la dans Connexions.",
timeout: "Le modèle a mis trop de temps à répondre.",
cancelled: "L’exécution a été arrêtée avant la fin.",
interrupted: "Unsloth a été fermé avant la fin de l’exécution.",
@@ -4467,6 +4486,13 @@ export const fr = {
deleteFailed: "Impossible de supprimer la tâche",
runFailed: "Impossible de lancer la tâche",
},
+ loadPrompt: {
+ title: "Charger {model} ?",
+ description: "« {title} » utilise {model}, qui n’est pas chargé. L’exécuter passe le chat sur {model} jusqu’à la fin, puis revient.",
+ always: "Ne plus demander. Changer uniquement quand je n’utilise pas Unsloth.",
+ notNow: "Pas maintenant",
+ load: "Charger et exécuter",
+ },
toast: {
finished: "« {title} » est prête",
failed: "« {title} » a échoué",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 4f35a29aa4b..f0363b8e3d5 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -4481,6 +4481,21 @@ export const he = {
archiveSuccessful: "להעביר לארכיון הרצות שהצליחו",
project: "פרויקט",
projectNone: "ללא",
+ model: "מודל",
+ modelLoaded: "המודל שטעון באותו רגע",
+ modelOnDevice: "במכשיר הזה",
+ modelNote: "אם המודל הזה לא טעון כשהמשימה רצה, Unsloth שואל קודם.",
+ modelNoteAllowed: "עובר למודל הזה רק כשאינך משתמש ב-Unsloth, ואז חוזר למה שהיה.",
+ modelEmpty: "הורד מודל ממרכז המודלים או הוסף חיבור כדי לבחור מודל אחר.",
+ modelMissing: "{model} (לא במכשיר הזה)",
+ allowLoad: "להחליף אוטומטית כשאני לא כאן",
+ allowLoadHint:
+ "כשמגיע זמן המשימה ולא השתמשת ב-Unsloth במשך 5 דקות, היא טוענת את המודל הזה בלי לשאול, מריצה את המשימה ואז חוזרת למודל שהיה לך. אם באותו זמן אתה משתמש ב-Unsloth או שמתבצע אימון, ההרצה מדולגת והמודל שלך נשאר כמו שהוא. כשהאפשרות כבויה, Unsloth שואל לפני הטעינה.",
+ reasoning: "מאמץ חשיבה",
+ reasoningDefault: "ברירת מחדל",
+ reasoningOff: "כבוי",
+ reasoningLowest: "הנמוך ביותר",
+ reasoningHighest: "הגבוה ביותר",
create: "יצירה",
},
deleteDialog: {
@@ -4489,6 +4504,10 @@ export const he = {
},
errors: {
noModel: "לא היה מודל טעון. טען מודל בצ'אט ואז הפעל את המשימה שוב.",
+ modelNotLoaded: "המודל של המשימה לא היה טעון. טען אותו בצ'אט והרץ את המשימה שוב.",
+ modelLoadFailed: "לא ניתן היה לטעון את המודל של המשימה. ודא שהוא עדיין מוריד במרכז המודלים.",
+ modelBusy: "דולגה בזמן שהשתמשת ב-Unsloth, כך שהמודל שלך לא שונה.",
+ connectionUnavailable: "החיבור של המשימה חסר או כבוי. בדוק אותו בחיבורים.",
timeout: "למודל לקח יותר מדי זמן לענות.",
cancelled: "ההרצה נעצרה לפני שהסתיימה.",
interrupted: "Unsloth נסגר לפני שההרצה הסתיימה.",
@@ -4499,6 +4518,13 @@ export const he = {
deleteFailed: "לא ניתן למחוק את המשימה",
runFailed: "לא ניתן להפעיל את המשימה",
},
+ loadPrompt: {
+ title: "לטעון את {model}?",
+ description: "„{title}” רצה על {model}, שאינו טעון. הרצתה מעבירה את הצ'אט ל-{model} עד שתסתיים, ואז חוזרת.",
+ always: "לא לשאול שוב. להחליף רק כשאני לא משתמש ב-Unsloth.",
+ notNow: "לא עכשיו",
+ load: "לטעון ולהריץ",
+ },
toast: {
finished: "\"{title}\" מוכנה",
failed: "\"{title}\" נכשלה",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 2f8be66b70c..6cd73aa70c4 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -4374,6 +4374,21 @@ export const hi = {
archiveSuccessful: "सफल रन संग्रहित करें",
project: "प्रोजेक्ट",
projectNone: "कोई नहीं",
+ model: "मॉडल",
+ modelLoaded: "जो भी मॉडल लोड हो",
+ modelOnDevice: "इस डिवाइस पर",
+ modelNote: "टास्क चलने पर यह मॉडल लोड न हो, तो Unsloth पहले पूछता है।",
+ modelNoteAllowed: "केवल तब इस मॉडल पर जाता है जब आप Unsloth इस्तेमाल नहीं कर रहे, फिर पहले वाले पर लौट आता है।",
+ modelEmpty: "दूसरा चुनने के लिए Model hub में मॉडल डाउनलोड करें या कनेक्शन जोड़ें।",
+ modelMissing: "{model} (इस डिवाइस पर नहीं)",
+ allowLoad: "मेरे दूर रहने पर अपने आप बदलें",
+ allowLoadHint:
+ "जब इस कार्य का समय होता है और आपने 5 मिनट से Unsloth का उपयोग नहीं किया है, तो यह बिना पूछे यह मॉडल लोड करता है, कार्य चलाता है, फिर आपके पिछले मॉडल पर वापस आ जाता है। अगर उस समय आप Unsloth का उपयोग कर रहे हैं या ट्रेनिंग चल रही है, तो रन छोड़ दिया जाता है और आपका मॉडल वैसा ही रहता है। बंद होने पर, Unsloth लोड करने से पहले पूछता है।",
+ reasoning: "सोचने का प्रयास",
+ reasoningDefault: "डिफ़ॉल्ट",
+ reasoningOff: "बंद",
+ reasoningLowest: "न्यूनतम",
+ reasoningHighest: "अधिकतम",
create: "बनाएँ",
},
deleteDialog: {
@@ -4382,6 +4397,10 @@ export const hi = {
},
errors: {
noModel: "कोई मॉडल लोड नहीं था। चैट में मॉडल लोड करें, फिर टास्क दोबारा चलाएँ।",
+ modelNotLoaded: "टास्क का मॉडल लोड नहीं था। इसे चैट में लोड करें, फिर टास्क दोबारा चलाएँ।",
+ modelLoadFailed: "टास्क का मॉडल लोड नहीं हो सका। पक्का करें कि यह अब भी Model hub में डाउनलोड है।",
+ modelBusy: "आप Unsloth इस्तेमाल कर रहे थे, इसलिए छोड़ा गया और आपका मॉडल नहीं बदला।",
+ connectionUnavailable: "टास्क का कनेक्शन मौजूद नहीं है या बंद है। इसे कनेक्शन में जाँचें।",
timeout: "मॉडल ने जवाब देने में बहुत ज़्यादा समय लिया।",
cancelled: "रन पूरा होने से पहले रोक दिया गया।",
interrupted: "रन पूरा होने से पहले Unsloth बंद हो गया।",
@@ -4392,6 +4411,13 @@ export const hi = {
deleteFailed: "टास्क हटाया नहीं जा सका",
runFailed: "टास्क शुरू नहीं हो सका",
},
+ loadPrompt: {
+ title: "{model} लोड करें?",
+ description: "“{title}” {model} पर चलता है, जो लोड नहीं है। इसे चलाने से चैट खत्म होने तक {model} पर जाएगी, फिर वापस।",
+ always: "दोबारा न पूछें। सिर्फ़ तब बदलें जब मैं Unsloth इस्तेमाल न कर रहा हूँ।",
+ notNow: "अभी नहीं",
+ load: "लोड करें और चलाएँ",
+ },
toast: {
finished: "“{title}” तैयार है",
failed: "“{title}” विफल रहा",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 09a1208556d..eadb712fc79 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -4439,6 +4439,21 @@ export const it = {
archiveSuccessful: "Archivia le esecuzioni riuscite",
project: "Progetto",
projectNone: "Nessuno",
+ model: "Modello",
+ modelLoaded: "Il modello caricato in quel momento",
+ modelOnDevice: "Su questo dispositivo",
+ modelNote: "Se questo modello non è caricato quando l’attività parte, Unsloth chiede prima.",
+ modelNoteAllowed: "Passa a questo modello solo mentre non usi Unsloth, poi torna al tuo.",
+ modelEmpty: "Scarica un modello da Model Hub o aggiungi una connessione per sceglierne un altro.",
+ modelMissing: "{model} (non su questo dispositivo)",
+ allowLoad: "Cambia automaticamente quando non ci sono",
+ allowLoadHint:
+ "Quando questa attività è in scadenza e non usi Unsloth da 5 minuti, carica questo modello senza chiedere, esegue l'attività e poi torna al modello che avevi. Se in quel momento stai usando Unsloth o è in corso un addestramento, l'esecuzione viene saltata e il tuo modello resta com'è. Se è disattivato, Unsloth chiede prima di caricarlo.",
+ reasoning: "Sforzo di ragionamento",
+ reasoningDefault: "Predefinito",
+ reasoningOff: "Disattivato",
+ reasoningLowest: "Minimo",
+ reasoningHighest: "Massimo",
create: "Crea",
},
deleteDialog: {
@@ -4447,6 +4462,10 @@ export const it = {
},
errors: {
noModel: "Nessun modello era caricato. Carica un modello nella chat, poi esegui di nuovo l’attività.",
+ modelNotLoaded: "Il modello dell’attività non era caricato. Caricalo nella chat, poi esegui di nuovo l’attività.",
+ modelLoadFailed: "Impossibile caricare il modello dell’attività. Verifica che sia ancora scaricato in Model Hub.",
+ modelBusy: "Saltata mentre usavi Unsloth: il tuo modello non è stato toccato.",
+ connectionUnavailable: "La connessione dell’attività non esiste o è disattivata. Controllala in Connessioni.",
timeout: "Il modello ha impiegato troppo tempo a rispondere.",
cancelled: "L’esecuzione è stata interrotta prima della fine.",
interrupted: "Unsloth è stato chiuso prima della fine dell’esecuzione.",
@@ -4457,6 +4476,13 @@ export const it = {
deleteFailed: "Impossibile eliminare l’attività",
runFailed: "Impossibile avviare l’attività",
},
+ loadPrompt: {
+ title: "Caricare {model}?",
+ description: "«{title}» usa {model}, che non è caricato. Eseguirla porta la chat su {model} fino alla fine, poi torna indietro.",
+ always: "Non chiedere più. Cambia solo mentre non uso Unsloth.",
+ notNow: "Non ora",
+ load: "Carica ed esegui",
+ },
toast: {
finished: "«{title}» è pronta",
failed: "«{title}» non è riuscita",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 94e543a79cb..a5fa9b37c2e 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -4313,6 +4313,21 @@ export const ja = {
archiveSuccessful: "成功した実行をアーカイブ",
project: "プロジェクト",
projectNone: "なし",
+ model: "モデル",
+ modelLoaded: "その時に読み込まれているモデル",
+ modelOnDevice: "このデバイス",
+ modelNote: "実行時にこのモデルが読み込まれていなければ、先に確認します。",
+ modelNoteAllowed: "Unsloth を使っていない間だけこのモデルに切り替え、終わったら元に戻します。",
+ modelEmpty: "別のモデルを選ぶには、Model Hub でダウンロードするか接続を追加してください。",
+ modelMissing: "{model}(このデバイスにありません)",
+ allowLoad: "離席中は自動で切り替える",
+ allowLoadHint:
+ "このタスクの時刻になり、Unsloth を 5 分間使っていない場合は、確認せずにこのモデルを読み込んでタスクを実行し、その後元のモデルに戻します。その時点で Unsloth を使用中か学習中の場合、実行はスキップされ、モデルはそのままです。オフにすると、読み込む前に Unsloth が確認します。",
+ reasoning: "思考の深さ",
+ reasoningDefault: "デフォルト",
+ reasoningOff: "オフ",
+ reasoningLowest: "最低",
+ reasoningHighest: "最高",
create: "作成",
},
deleteDialog: {
@@ -4321,6 +4336,10 @@ export const ja = {
},
errors: {
noModel: "モデルが読み込まれていませんでした。チャットでモデルを読み込んでから、もう一度タスクを実行してください。",
+ modelNotLoaded: "タスクのモデルが読み込まれていませんでした。チャットで読み込んでから、もう一度実行してください。",
+ modelLoadFailed: "タスクのモデルを読み込めませんでした。Model Hub にダウンロードされたままか確認してください。",
+ modelBusy: "Unsloth を使用中だったためスキップし、モデルはそのままにしました。",
+ connectionUnavailable: "タスクの接続が見つからないか、オフになっています。接続を確認してください。",
timeout: "モデルの応答に時間がかかりすぎました。",
cancelled: "実行は完了前に停止されました。",
interrupted: "実行が完了する前に Unsloth が閉じられました。",
@@ -4331,6 +4350,13 @@ export const ja = {
deleteFailed: "タスクを削除できませんでした",
runFailed: "タスクを開始できませんでした",
},
+ loadPrompt: {
+ title: "{model} を読み込みますか?",
+ description: "「{title}」は {model} で実行されますが、読み込まれていません。実行すると終わるまでチャットが {model} に切り替わり、その後元に戻ります。",
+ always: "今後は確認しない。Unsloth を使っていない間だけ切り替える。",
+ notNow: "今はしない",
+ load: "読み込んで実行",
+ },
toast: {
finished: "「{title}」が完了しました",
failed: "「{title}」が失敗しました",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 1611ca27727..53bfb37974d 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -4352,6 +4352,21 @@ export const ko = {
archiveSuccessful: "성공한 실행 보관",
project: "프로젝트",
projectNone: "없음",
+ model: "모델",
+ modelLoaded: "로드되어 있는 모델",
+ modelOnDevice: "이 기기",
+ modelNote: "작업 실행 시 이 모델이 로드되어 있지 않으면 먼저 묻습니다.",
+ modelNoteAllowed: "Unsloth를 사용하지 않는 동안에만 이 모델로 전환하고, 끝나면 원래 모델로 돌아갑니다.",
+ modelEmpty: "다른 모델을 고르려면 Model Hub에서 모델을 다운로드하거나 연결을 추가하세요.",
+ modelMissing: "{model} (이 기기에 없음)",
+ allowLoad: "자리를 비우면 자동으로 전환",
+ allowLoadHint:
+ "이 작업 시간이 되었고 5분 동안 Unsloth를 사용하지 않았다면, 묻지 않고 이 모델을 로드해 작업을 실행한 뒤 원래 모델로 되돌립니다. 그때 Unsloth를 사용 중이거나 학습 중이면 실행을 건너뛰고 모델은 그대로 둡니다. 끄면 로드하기 전에 Unsloth가 묻습니다.",
+ reasoning: "사고 수준",
+ reasoningDefault: "기본값",
+ reasoningOff: "끄기",
+ reasoningLowest: "최저",
+ reasoningHighest: "최고",
create: "만들기",
},
deleteDialog: {
@@ -4360,6 +4375,10 @@ export const ko = {
},
errors: {
noModel: "로드된 모델이 없었습니다. 채팅에서 모델을 로드한 다음 작업을 다시 실행하세요.",
+ modelNotLoaded: "작업의 모델이 로드되지 않았습니다. 채팅에서 로드한 후 다시 실행하세요.",
+ modelLoadFailed: "작업의 모델을 로드하지 못했습니다. Model Hub에 아직 다운로드되어 있는지 확인하세요.",
+ modelBusy: "Unsloth 사용 중이어서 건너뛰었고 모델은 그대로 두었습니다.",
+ connectionUnavailable: "작업의 연결이 없거나 꺼져 있습니다. 연결에서 확인하세요.",
timeout: "모델이 응답하는 데 너무 오래 걸렸습니다.",
cancelled: "실행이 완료되기 전에 중지되었습니다.",
interrupted: "실행이 끝나기 전에 Unsloth가 닫혔습니다.",
@@ -4370,6 +4389,13 @@ export const ko = {
deleteFailed: "작업을 삭제하지 못했습니다",
runFailed: "작업을 시작하지 못했습니다",
},
+ loadPrompt: {
+ title: "{model}을(를) 로드할까요?",
+ description: "“{title}” 작업은 {model}에서 실행되지만 로드되어 있지 않습니다. 실행하면 끝날 때까지 채팅이 {model}로 전환되고 이후 돌아갑니다.",
+ always: "다시 묻지 않기. Unsloth를 사용하지 않을 때만 전환합니다.",
+ notNow: "나중에",
+ load: "로드하고 실행",
+ },
toast: {
finished: "\"{title}\" 완료",
failed: "\"{title}\" 실패",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index af8852b6e9f..0fbfb24eb88 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -4397,6 +4397,21 @@ export const ptBR = {
archiveSuccessful: "Arquivar execuções bem-sucedidas",
project: "Projeto",
projectNone: "Nenhum",
+ model: "Modelo",
+ modelLoaded: "O modelo que estiver carregado",
+ modelOnDevice: "Neste dispositivo",
+ modelNote: "Se este modelo não estiver carregado quando a tarefa rodar, o Unsloth pergunta antes.",
+ modelNoteAllowed: "Muda para este modelo só enquanto você não usa o Unsloth e depois volta ao que você tinha.",
+ modelEmpty: "Baixe um modelo no Model Hub ou adicione uma conexão para escolher outro.",
+ modelMissing: "{model} (não está neste dispositivo)",
+ allowLoad: "Trocar automaticamente quando eu estiver fora",
+ allowLoadHint:
+ "Quando esta tarefa vence e você não usa o Unsloth há 5 minutos, ela carrega este modelo sem perguntar, executa a tarefa e depois volta para o modelo que você tinha. Se você estiver usando o Unsloth ou treinando nesse momento, a execução é pulada e seu modelo fica como está. Desativado, o Unsloth pergunta antes de carregar.",
+ reasoning: "Esforço de raciocínio",
+ reasoningDefault: "Padrão",
+ reasoningOff: "Desligado",
+ reasoningLowest: "Mínimo",
+ reasoningHighest: "Máximo",
create: "Criar",
},
deleteDialog: {
@@ -4405,6 +4420,10 @@ export const ptBR = {
},
errors: {
noModel: "Nenhum modelo estava carregado. Carregue um modelo no chat e execute a tarefa de novo.",
+ modelNotLoaded: "O modelo da tarefa não estava carregado. Carregue-o no chat e execute a tarefa novamente.",
+ modelLoadFailed: "Não foi possível carregar o modelo da tarefa. Verifique se ele ainda está baixado no Model Hub.",
+ modelBusy: "Pulada enquanto você usava o Unsloth; seu modelo não foi alterado.",
+ connectionUnavailable: "A conexão da tarefa não existe ou está desativada. Verifique em Conexões.",
timeout: "O modelo demorou demais para responder.",
cancelled: "A execução foi interrompida antes de terminar.",
interrupted: "O Unsloth foi fechado antes de a execução terminar.",
@@ -4415,6 +4434,13 @@ export const ptBR = {
deleteFailed: "Não foi possível excluir a tarefa",
runFailed: "Não foi possível iniciar a tarefa",
},
+ loadPrompt: {
+ title: "Carregar {model}?",
+ description: "“{title}” usa {model}, que não está carregado. Executá-la troca o chat para {model} até terminar e depois volta.",
+ always: "Não perguntar de novo. Trocar só enquanto eu não uso o Unsloth.",
+ notNow: "Agora não",
+ load: "Carregar e executar",
+ },
toast: {
finished: "“{title}” está pronta",
failed: "“{title}” falhou",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 053f2905535..dc264db2086 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -4395,6 +4395,21 @@ export const ru = {
archiveSuccessful: "Архивировать успешные запуски",
project: "Проект",
projectNone: "Нет",
+ model: "Модель",
+ modelLoaded: "Любая загруженная модель",
+ modelOnDevice: "На этом устройстве",
+ modelNote: "Если при запуске задачи модель не загружена, Unsloth сначала спросит.",
+ modelNoteAllowed: "Переключается на эту модель, только пока вы не пользуетесь Unsloth, а потом возвращает вашу.",
+ modelEmpty: "Чтобы выбрать другую, скачайте модель в Model Hub или добавьте подключение.",
+ modelMissing: "{model} (нет на этом устройстве)",
+ allowLoad: "Переключать автоматически, когда меня нет",
+ allowLoadHint:
+ "Когда подходит время задачи и вы не пользовались Unsloth 5 минут, она без вопроса загружает эту модель, выполняет задачу и возвращает прежнюю модель. Если в это время вы работаете в Unsloth или идёт обучение, запуск пропускается, а ваша модель остаётся как есть. Если выключено, Unsloth спрашивает перед загрузкой.",
+ reasoning: "Глубина рассуждений",
+ reasoningDefault: "По умолчанию",
+ reasoningOff: "Выкл.",
+ reasoningLowest: "Минимальная",
+ reasoningHighest: "Максимальная",
create: "Создать",
},
deleteDialog: {
@@ -4403,6 +4418,10 @@ export const ru = {
},
errors: {
noModel: "Модель не была загружена. Загрузите модель в чате и запустите задачу снова.",
+ modelNotLoaded: "Модель задачи не была загружена. Загрузите её в чате и запустите задачу снова.",
+ modelLoadFailed: "Не удалось загрузить модель задачи. Проверьте, что она всё ещё скачана в Model Hub.",
+ modelBusy: "Пропущено, пока вы пользовались Unsloth: модель не тронута.",
+ connectionUnavailable: "Подключение задачи отсутствует или отключено. Проверьте его в разделе «Подключения».",
timeout: "Модель отвечала слишком долго.",
cancelled: "Запуск был остановлен до завершения.",
interrupted: "Unsloth закрылся до завершения запуска.",
@@ -4413,6 +4432,13 @@ export const ru = {
deleteFailed: "Не удалось удалить задачу",
runFailed: "Не удалось запустить задачу",
},
+ loadPrompt: {
+ title: "Загрузить {model}?",
+ description: "«{title}» работает на {model}, но она не загружена. Запуск переключит чат на {model} до завершения, затем вернёт обратно.",
+ always: "Больше не спрашивать. Переключать, только пока я не пользуюсь Unsloth.",
+ notNow: "Не сейчас",
+ load: "Загрузить и запустить",
+ },
toast: {
finished: "«{title}»: готово",
failed: "«{title}»: ошибка",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 6980e40e6e5..b1d13acc4db 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -4616,6 +4616,21 @@ export const sv = {
archiveSuccessful: "Arkivera lyckade körningar",
project: "Projekt",
projectNone: "Inget",
+ model: "Modell",
+ modelLoaded: "Den modell som är inläst",
+ modelOnDevice: "På den här enheten",
+ modelNote: "Om modellen inte är inläst när uppgiften körs frågar Unsloth först.",
+ modelNoteAllowed: "Byter till den här modellen bara när du inte använder Unsloth och sedan tillbaka.",
+ modelEmpty: "Ladda ner en modell i Model Hub eller lägg till en anslutning för att välja en annan.",
+ modelMissing: "{model} (finns inte på den här enheten)",
+ allowLoad: "Byt automatiskt när jag är borta",
+ allowLoadHint:
+ "När uppgiften ska köras och du inte har använt Unsloth på 5 minuter läser den in den här modellen utan att fråga, kör uppgiften och byter sedan tillbaka till modellen du hade. Om du använder Unsloth eller tränar just då hoppas körningen över och din modell lämnas orörd. Avstängt frågar Unsloth innan modellen läses in.",
+ reasoning: "Tankeinsats",
+ reasoningDefault: "Standard",
+ reasoningOff: "Av",
+ reasoningLowest: "Lägsta",
+ reasoningHighest: "Högsta",
create: "Skapa",
},
deleteDialog: {
@@ -4624,6 +4639,10 @@ export const sv = {
},
errors: {
noModel: "Ingen modell var inläst. Läs in en modell i chatten och kör sedan uppgiften igen.",
+ modelNotLoaded: "Uppgiftens modell var inte inläst. Läs in den i chatten och kör uppgiften igen.",
+ modelLoadFailed: "Det gick inte att läsa in uppgiftens modell. Kontrollera att den fortfarande är nedladdad i Model Hub.",
+ modelBusy: "Hoppades över medan du använde Unsloth, så din modell lämnades ifred.",
+ connectionUnavailable: "Uppgiftens anslutning saknas eller är avstängd. Kontrollera den under Anslutningar.",
timeout: "Modellen tog för lång tid på sig att svara.",
cancelled: "Körningen stoppades innan den var klar.",
interrupted: "Unsloth stängdes innan körningen var klar.",
@@ -4634,6 +4653,13 @@ export const sv = {
deleteFailed: "Det gick inte att ta bort uppgiften",
runFailed: "Det gick inte att starta uppgiften",
},
+ loadPrompt: {
+ title: "Läsa in {model}?",
+ description: "”{title}” körs med {model}, som inte är inläst. Att köra den byter chatten till {model} tills den är klar och sedan tillbaka.",
+ always: "Fråga inte igen. Byt bara när jag inte använder Unsloth.",
+ notNow: "Inte nu",
+ load: "Läs in och kör",
+ },
toast: {
finished: "”{title}” är klar",
failed: "”{title}” misslyckades",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 77f6383c8ed..c0601c46a2b 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -4265,6 +4265,21 @@ export const zhCN = {
archiveSuccessful: "归档成功的运行",
project: "项目",
projectNone: "无",
+ model: "模型",
+ modelLoaded: "当前已加载的任意模型",
+ modelOnDevice: "此设备",
+ modelNote: "如果任务运行时此模型未加载,Unsloth 会先询问。",
+ modelNoteAllowed: "仅在你离开 Unsloth 时切换到此模型,完成后切回原来的模型。",
+ modelEmpty: "在模型中心下载模型或添加连接,即可选择其他模型。",
+ modelMissing: "{model}(不在此设备上)",
+ allowLoad: "离开时自动切换",
+ allowLoadHint:
+ "到了任务时间且你已 5 分钟未使用 Unsloth 时,它会直接加载此模型、运行任务,然后切换回你原来的模型。如果当时你正在使用 Unsloth 或正在训练,本次运行会被跳过,你的模型保持不变。关闭时,Unsloth 会在加载前询问。",
+ reasoning: "思考强度",
+ reasoningDefault: "默认",
+ reasoningOff: "关闭",
+ reasoningLowest: "最低",
+ reasoningHighest: "最高",
create: "创建",
},
deleteDialog: {
@@ -4273,6 +4288,10 @@ export const zhCN = {
},
errors: {
noModel: "当时没有加载模型。请在聊天中加载模型,然后重新运行任务。",
+ modelNotLoaded: "任务的模型未加载。请在聊天中加载后再次运行任务。",
+ modelLoadFailed: "无法加载任务的模型。请确认它仍已下载到模型中心。",
+ modelBusy: "因你正在使用 Unsloth 而跳过,你的模型未被更换。",
+ connectionUnavailable: "任务的连接不存在或已关闭。请在“连接”中检查。",
timeout: "模型回答用时过长。",
cancelled: "运行在完成前被停止。",
interrupted: "运行完成前 Unsloth 已关闭。",
@@ -4283,6 +4302,13 @@ export const zhCN = {
deleteFailed: "无法删除任务",
runFailed: "无法启动任务",
},
+ loadPrompt: {
+ title: "加载 {model}?",
+ description: "“{title}”使用 {model} 运行,但它尚未加载。运行时聊天会切换到 {model},完成后再切回。",
+ always: "不再询问。仅在我不使用 Unsloth 时切换。",
+ notNow: "暂不",
+ load: "加载并运行",
+ },
toast: {
finished: "“{title}”已完成",
failed: "“{title}”运行失败",
diff --git a/studio/frontend/tests/scheduled-tasks.test.ts b/studio/frontend/tests/scheduled-tasks.test.ts
index f7d13382d48..2bfd4d135d0 100644
--- a/studio/frontend/tests/scheduled-tasks.test.ts
+++ b/studio/frontend/tests/scheduled-tasks.test.ts
@@ -23,6 +23,7 @@ import {
readSeenRuns,
runErrorText,
runsToAnnounce,
+ runsAskingToLoad,
runsToNotify,
readInRecents,
unseenChatChanges,
@@ -297,6 +298,7 @@ function finished(id: string, finishedAt: number): ScheduledTasksApi.FinishedSch
error: null,
taskTitle: "Morning brief",
taskNotify: "all",
+ taskModel: null,
};
}
@@ -726,3 +728,25 @@ test("a task left unnamed is named after its instructions' first line", () => {
assert.ok(!/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(emoji), "no lone surrogate");
assert.equal(Array.from(emoji).length, 61);
});
+
+test("a run whose model was not loaded asks once per task, whatever its notifications say", () => {
+ const run = (id: string, taskId: string, errorCode: string | null, taskModel: string | null) => ({
+ ...finished(id, 1_000),
+ status: "failed" as const,
+ taskId,
+ errorCode,
+ taskModel,
+ taskNotify: "none" as const,
+ });
+ const asks = runsAskingToLoad([
+ run("a", "task-1", "model_not_loaded", "unsloth/Qwen3-1.7B-GGUF"),
+ run("b", "task-1", "model_not_loaded", "unsloth/Qwen3-1.7B-GGUF"),
+ run("c", "task-2", "no_model", null),
+ run("e", "task-4", "model_busy", "unsloth/gemma-3-GGUF"),
+ run("d", "task-3", "model_not_loaded", null),
+ ]);
+ assert.deepEqual(
+ asks.map((ask) => ask.id),
+ ["b"],
+ );
+});