Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: MCP errors, cancels and chat controls agents can act on (#14081)
Etherl43ceef8c0471
diff --git a/studio/MCP.md b/studio/MCP.mdindex a0057137d30..9b3b5a62189 100644--- a/studio/MCP.md+++ b/studio/MCP.md@@ -78,8 +78,10 @@ your API key, so it sees what that key may see and nothing more.### Turn it on-The server is off by default. While it is off, `/mcp/` answers 404. Start Unsloth-Studio with `UNSLOTH_STUDIO_ENABLE_MCP=1` to turn it on.+The server is off by default. While it is off, `/mcp/` answers 404. The Unsloth+Studio owner turns it on in Settings > API with **Allow agent connections**.+Starting Unsloth Studio with `UNSLOTH_STUDIO_ENABLE_MCP=1` also turns it on and+locks the switch, which then reads "Set by UNSLOTH_STUDIO_ENABLE_MCP."The endpoint is `http://127.0.0.1:8888/mcp/` on the default port. Always usethe trailing slash. Use your own address and port when they differ, for example@@ -184,10 +186,16 @@ claude mcp add --transport http --scope user unsloth-studio http://127.0.0.1:888```bashcodex mcp add unsloth-studio --url http://127.0.0.1:8888/mcp/ --bearer-token-env-var UNSLOTH_API_KEY-# Optional, for long jobs, in ~/.codex/config.toml under [mcp_servers.unsloth-studio]:-# tool_timeout_sec = 300```+Then set `tool_timeout_sec = 300` under `[mcp_servers.unsloth-studio]` in+`~/.codex/config.toml`.++**Long calls.** A long chat reply, a song or a first model download can take+minutes, so raise your client's tool timeout above 240 s. For Codex that is+`tool_timeout_sec = 300` above. For Claude Code, start it with+`MCP_TOOL_TIMEOUT=300000 claude` (the value is in milliseconds).+**OpenCode**, in `~/.config/opencode/opencode.json`:```json@@ -270,8 +278,8 @@ api_key_format = "Bearer {token}"| `list_models` | Models Unsloth Studio can serve, by kind or by Audio page `workflow`. With `model`, its training defaults. With `source="catalog"`, the image, video and audio models it can download, with their size and whether they fit on the GPU now. || `load_model` | Load a chat, image, video or speech-to-text model, downloading it first if needed. Reports progress. || `unload_model` | Unload a model. |-| `chat` | Ask the loaded model, with optional images. Returns a `cancel_id`. |-| `embed` | Embed up to 2048 texts. |+| `chat` | Ask the loaded model, with optional images, thinking controls and a `response_format`. Reports progress and returns a `cancel_id`. |+| `embed` | Embed up to 2048 texts, or rank them against a `query` and return the `top_k` best matches. || `system_one` | Ask the Decision API typed questions. The Decision API must be on. || `generate_image` | Text to image, image to image, inpaint, edit, reference, outpaint and upscale, one image or a batch of seeds or prompts. Left out, steps and guidance follow the loaded model. || `generate_audio` | Clone, speak, edit, convert, music and separate, on the loaded model or a named `model`. |@@ -286,7 +294,7 @@ api_key_format = "Bearer {token}"| `start_training` | Start LLM or image LoRA training. Follow it with `studio_status`. || `list_training_runs` | Past runs and their checkpoints, by name. || `export_model` | Export a checkpoint to GGUF, merged weights, a LoRA adapter or the base model. |-| `cancel` | Stop training, a start request, image training, an export, a recipe, an image or video generation, a chat reply or a dataset download. |+| `cancel` | Stop running work of a given kind; the kinds are listed in the tool's schema. |Long work returns at once. Start it, then poll `get_job` or `studio_status`,and stop it with `cancel`. Audio runs cannot be cancelled. Unsloth Studio runs onediff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 17af1dd96c5..0204ab91d61 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -3326,10 +3326,19 @@ class TrainingBackend:elif etype == "complete":msg = event.get("status_message", "Training completed")- stopped = self._should_stop or msg.strip().lower() in {+ stopped = self._should_stop or msg.strip().lower().rstrip(".") in {"training cancelled","training stopped",}+ # A stop that lands during the final save or the drafter phase still gets "completed".+ completed = re.match(r"(?:\w+ )?training completed!?\s*", msg, flags = re.IGNORECASE)+ if stopped and completed:+ rest = msg[completed.end() :]+ msg = (+ "Training cancelled."+ if self._cancel_requested+ else f"Training stopped. {rest}".rstrip()+ )# Save is done by now; let the stop watchdog start its grace timer.self._complete_seen.set()self._progress.is_training = Falsediff --git a/studio/backend/mcp_server.py b/studio/backend/mcp_server.pyindex e4c35c0a42e..4b17fad62e0 100644--- a/studio/backend/mcp_server.py+++ b/studio/backend/mcp_server.py@@ -23,20 +23,22 @@ from studio_mcp.tools import (video,)-INSTRUCTIONS = (- "Unsloth Studio runs models, generates media, trains and exports. "- "Call studio_status first to see what is loaded and running, and list_models to find models. "- "Load a model with load_model before chat, generate_image, generate_audio or generate_video; embed "- "and transcribe fall back to Unsloth Studio's own embedding and speech-to-text models. "- "Unsloth Studio may unload one model to fit another on the GPU (load_model lists what it unloaded), "- "so check studio_status before reusing a model you loaded earlier. "- "Long work returns at once: start it, then poll get_job (video, recipe, export) or studio_status "- "(training), and stop it with cancel. "- "File paths in inputs work only when you run on the Unsloth Studio computer; otherwise send data or an "- "Unsloth Studio id. "- "Generated images, audio and videos are saved to the Unsloth Studio galleries and returned with their id "- "and URL. "- "Training, generation and exports use the GPU and can take minutes."+INSTRUCTIONS = " ".join(+ (+ "Unsloth Studio runs local AI models for chat, embed, images, audio, transcribe, video, datasets, fine-tune and export.",+ "Call studio_status first to see what is loaded and running, and list_models to find models.",+ "Load a model with load_model before chat, generate_image, generate_audio or generate_video; embed and transcribe fall back to Unsloth Studio's own embedding and speech-to-text models.",+ "Unsloth Studio may unload one model to fit another on the GPU, so load a model, generate, then unload_model before you switch kinds; speech-to-text models stay loaded beside them.",+ "load_model lists what it unloaded in evicted, so check studio_status before reusing a model you loaded earlier.",+ "generate_audio can speak, clone a voice, edit or convert speech, make music (a song or sfx) and separate stems, with a tts or audio model loaded.",+ "chat, generate_audio and transcribe wait for their result and report progress every 2 s.",+ "Video, recipe, export and training jobs return at once: poll get_job (video, recipe, export) or studio_status (training) every 15 to 30 s.",+ "Stop work with cancel: a chat by the cancel_id you passed when starting it, a video by its id.",+ "To fine-tune, find a dataset with datasets, check the config with start_training(validate_only=true), start it, then export_model the finished run.",+ "Errors start with a tag such as [gpu_busy retry_after=12] or [not_loaded kind=image]; the hint after the message says what to do.",+ "File paths in inputs work only when you run on the Unsloth Studio computer; otherwise send data or an Unsloth Studio id.",+ "Generated images, audio and videos are saved to the Unsloth Studio galleries and returned with their id and URL.",+ ))diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex b45308db5a4..96ea2eaee45 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -2846,6 +2846,9 @@ def _build_training_status("total_steps": getattr(progress, "total_steps", 0),"loss": getattr(progress, "loss", None),"learning_rate": getattr(progress, "learning_rate", None),+ "elapsed_seconds": getattr(progress, "elapsed_seconds", None),+ # A stopped run keeps its last ETA; only a live run has time remaining.+ "eta_seconds": getattr(progress, "eta_seconds", None) if is_active else None,"output_dir": getattr(backend, "_output_dir", None) or None,"drafter": getattr(progress, "drafter", None),"model_download_repo_id": (diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex b4bcd90c4ef..08d55ab7131 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -820,10 +820,40 @@ async def video_generate_progress(current_subject: str = Depends(get_current_subreturn VideoGenerateProgressResponse(**progress)+_CANCEL_BODY_MSG = 'Send a JSON object such as {"video_id": "..."}, or no body.'+++async def _cancel_video_id(request: Request) -> Optional[str]:+ """The optional ``video_id`` a cancel names; no body means the running render."""+ import json++ raw = await request.body()+ if not raw.strip():+ return None+ try:+ body = json.loads(raw)+ except ValueError:+ raise HTTPException(status_code = 422, detail = _CANCEL_BODY_MSG)+ if not isinstance(body, dict):+ raise HTTPException(status_code = 422, detail = _CANCEL_BODY_MSG)+ video_id = body.get("video_id")+ if video_id is not None and not isinstance(video_id, str):+ raise HTTPException(status_code = 422, detail = _CANCEL_BODY_MSG)+ if video_id is not None and not video_id.strip():+ # An empty id must not widen into a cancel of whatever is rendering.+ raise HTTPException(+ status_code = 422, detail = "video_id is empty; leave it out to stop the running render."+ )+ return video_id++@router.post("/video/generate/cancel")-async def cancel_video_generation(current_subject: str = Depends(get_current_subject)):+async def cancel_video_generation(+ request: Request, current_subject: str = Depends(get_current_subject)+):from core.inference.video import get_video_backend+ video_id = await _cancel_video_id(request)backend = get_video_backend()# One read serves check and recheck: a second read could name a successor and hand it back# as expected_account.@@ -834,17 +864,23 @@ async def cancel_video_generation(current_subject: str = Depends(get_current_subwith _generation_lock:started_by = _generation_accountif _generation_hidden(backend, started_by):- return {"cancelled": False}- if started_by is None and account_access.foreign_work_active():- return {"cancelled": False}- if reserved is None:- # No reservation yet: bind the cancel to the caller, else an account reserving before the- # executor runs would receive it.- from utils.account_context import current_account- expected = current_account().account_id+ cancelled = False+ elif started_by is None and account_access.foreign_work_active():+ cancelled = Falseelse:- expected = reserved- cancelled = await asyncio.to_thread(backend.cancel_generate, expected_account = expected)+ if reserved is None:+ # No reservation yet: bind the cancel to the caller so a later reservation can't receive it.+ from utils.account_context import current_account+ expected = current_account().account_id+ else:+ expected = reserved+ # The id is rechecked under the backend's lock, so a finished render's successor is safe.+ cancelled = await asyncio.to_thread(+ backend.cancel_generate, expected_video_id = video_id, expected_account = expected+ )+ if video_id is not None and not cancelled:+ # Hidden and foreign renders answer the same, so this reveals nothing about them.+ raise HTTPException(status_code = 409, detail = "That video is not rendering.")return {"cancelled": cancelled}diff --git a/studio/backend/studio_mcp/errors.py b/studio/backend/studio_mcp/errors.pyindex b52d248ec55..31f39a2ec77 100644--- a/studio/backend/studio_mcp/errors.py+++ b/studio/backend/studio_mcp/errors.py@@ -1,7 +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-"""Turn a forwarded route's failure into an MCP ToolError the agent can act on. Unsloth Studio routes fail in several shapes (``{"detail"}`` on /api, the OpenAI envelope on /v1, gpu_busy three ways, a 200 that carries ``_deferred_error`` or ``status: "error"``, an NDJSON error line), and every message is scrubbed of host paths before it leaves."""+"""Turn a forwarded route's failure into an MCP ToolError the agent can act on. Unsloth Studio routes fail in several shapes (``{"detail"}`` on /api, the OpenAI envelope on /v1, gpu_busy three ways, a 200 that carries ``_deferred_error`` or ``status: "error"``, an NDJSON error line), and every message is scrubbed of host paths before it leaves.++A failure the agent can branch on starts with a tag, ``[<code> k=v] <message>``, such as ``[gpu_busy retry_after=12]`` or ``[not_loaded kind=image]``. A plain refusal has no tag."""from __future__ import annotations@@ -20,24 +22,112 @@ from studio_mcp.forward import parse_json_ROUTE_CLAUSE = re.compile(r"\s*\b(?:Call|Use|See) (?:GET|POST|PUT|PATCH|DELETE) /[\w/{}.:-]*(?: first)?\.(?=\s|$)")+# The load and unload routes offer a force_cancel_active flag the MCP tools do not have.+_FORCE_CANCEL_CLAUSE = re.compile(r",? or retry with force_cancel_active(?=[.\s]|$)")+_FORCE_CANCEL_SENTENCE = re.compile(r"\s*[^.]*\bforce_cancel_active\b[^.]*\.?")def _scrub(text: Any) -> str:- return redact_paths_in_text(_ROUTE_CLAUSE.sub("", text) if isinstance(text, str) else text)+ if isinstance(text, str):+ text = _ROUTE_CLAUSE.sub("", text)+ if "force_cancel_active" in text:+ text = _FORCE_CANCEL_SENTENCE.sub("", _FORCE_CANCEL_CLAUSE.sub("", text))+ return redact_paths_in_text(text)_MAX_MESSAGE_CHARS = 2000_DEFERRED_ERROR_KEY = "_deferred_error"REFUSAL_HEADER = "x-unsloth-refusal"MEMORY_REFUSAL = "memory-estimate"+MULTI_MODEL_REFUSAL = "multi-model-always"+# Copy the Keep multiple models loaded refusal uses when no header or code came with it.+MULTI_MODEL_MARKERS = ("is set to Always", "is set to keep loaded")++_TAG_CODE = re.compile(r"^[a-z][a-z0-9_]{1,63}$")+_TAG_VALUE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")++UNLOAD_KINDS = {"chat": "llm", "audio": "audio", "image": "image", "video": "video"}+MULTI_MODEL_HINT = "Call unload_model(kind='{kind}') to free the GPU; retrying won't help."+MULTI_MODEL_HINT_ANY = (+ "Call unload_model(kind=…) for the model it names to free the GPU; retrying won't help."+)+ACTIVE_GENERATIONS_HINT = (+ "Wait for the running chats to finish, or cancel a chat you started with"+ " cancel(kind='chat', id=<its cancel_id>)."+)+MEMORY_HINT = "Pass allow_oversized=true to try anyway."+# Guidance for a route's own error code, used in place of the tool's status hint.+CODE_HINTS: dict[str, str] = {}++_UNLOAD_KIND = re.compile(r"would unload the (\w+) model")+_NOT_LOADED = re.compile(r"^No (?:(diffusion|image|video|GGUF) )?model (?:is )?loaded")+# The kind a "No <word> model loaded" names outright, whatever route said it.+_NOT_LOADED_WORDS = {"diffusion": "image", "image": "image", "video": "video", "GGUF": "chat"}+# The kind a bare "No model loaded" is about, by the route that said it. First match wins.+_NOT_LOADED_PATHS = (+ ("/v1/audio/transcriptions", "stt"),+ ("/api/inference/audio/stt/", "stt"),+ ("/v1/audio/", "audio"),+ ("/api/inference/audio/", "audio"),+ ("/v1/images/", "image"),+ ("/api/inference/images/", "image"),+ ("/v1/videos", "video"),+ ("/api/inference/video/", "video"),+)++# llama-server's startup output, as core/inference/llama_cpp.py _with_startup_diagnostics frames it.+_LLAMA_OUTPUT = "\n\nllama-server output:\n"+_LLAMA_LOG = "\n\nFull log:"+_LLAMA_ERRORS = "\n\nllama-server errors:\n"+_ERROR_LINE = re.compile(+ r"error|fail|exception|abort|unable|cannot|out of memory|not enough|invalid|missing",+ re.IGNORECASE,+)+++def _brief(text: Any) -> Any:+ """Keep llama-server's error lines, not its whole startup log, so the cause fits the cap."""+ if not isinstance(text, str):+ return text+ text = text.split(_LLAMA_LOG, 1)[0]+ head, found, output = text.partition(_LLAMA_OUTPUT)+ if not found:+ return text+ lines = [line.strip() for line in output.splitlines() if line.strip()]+ lines = ([line for line in lines if _ERROR_LINE.search(line)] or lines[-5:])[-8:]+ room = _MAX_MESSAGE_CHARS - 40 - len(head) - len(_LLAMA_ERRORS)+ while len(lines) > 1 and len("\n".join(lines)) > room:+ lines.pop(0)+ return f"{head}{_LLAMA_ERRORS}{chr(10).join(lines)}" if lines else head+++def _tag(code: Any, **fields: Any) -> Optional[str]:+ """``code k=v``, or None for a code that is not a plain identifier. A bad value drops its pair."""+ if not isinstance(code, str) or not _TAG_CODE.match(code):+ return None+ pairs = [+ f"{key}={value}"+ for key, value in fields.items()+ if value is not None and not isinstance(value, bool) and _TAG_VALUE.match(str(value))+ ]+ return " ".join([code, *pairs])-def tool_error(message: Any, hint: Optional[str] = None) -> ToolError:- """A scrubbed ToolError. ``hint`` is the tool's own guidance and goes on after the scrub, which would otherwise read a route like /v1/models as a path and drop it."""- text = _scrub(message).strip() or "Unsloth Studio returned an error"+def tool_error(+ message: Any,+ hint: Optional[str] = None,+ *,+ tag: Optional[str] = None,+) -> ToolError:+ """A scrubbed ToolError. ``hint`` is the tool's own guidance and goes on after the scrub, which would otherwise read a route like /v1/models as a path and drop it. ``tag`` (``code k=v``) leads the message in brackets."""+ text = _scrub(_brief(message)).strip() or "Unsloth Studio returned an error"if len(text) > _MAX_MESSAGE_CHARS:text = text[:_MAX_MESSAGE_CHARS] + "…"- return ToolError(f"{text} {hint}" if hint else text)+ if hint:+ text = f"{text} {hint}"+ if tag and _TAG_CODE.match(tag.split(" ", 1)[0]):+ text = f"[{tag}] {text}"+ return ToolError(text)def _text(value: Any) -> str:@@ -83,7 +173,26 @@ def _detail_message(detail: Any) -> str:return _text(detail)-def _describe(status: int, body: Any, headers: Mapping[str, str]) -> str:+def _refusal(headers: Mapping[str, str]) -> str:+ return str(headers.get(REFUSAL_HEADER) or "").strip().lower()+++def _not_loaded_kind(message: str, path: str) -> Optional[str]:+ match = _NOT_LOADED.match(message.strip())+ if match is None:+ return None+ if match.group(1):+ return _NOT_LOADED_WORDS[match.group(1)]+ return next((kind for prefix, kind in _NOT_LOADED_PATHS if path.startswith(prefix)), "chat")+++def _describe(+ status: int,+ body: Any,+ headers: Mapping[str, str],+ path: str = "",+) -> tuple[Optional[str], str, Optional[str]]:+ """(tag, message, own hint). An own hint replaces the tool's status hint."""# Scrubbed before the hints go on: the redactor drops everything after a path it finds.retry_after = headers.get("retry-after")busy = _gpu_busy(body)@@ -91,32 +200,67 @@ def _describe(status: int, body: Any, headers: Mapping[str, str]) -> str:message, body_retry = busyseconds = retry_after or body_retryhint = f" Retry after {seconds} s." if seconds is not None else ""- return f"GPU busy: {_scrub(message).rstrip('.')}.{hint}"+ tag = _tag("gpu_busy", retry_after = seconds)+ return tag, f"GPU busy: {_scrub(message).rstrip('.')}.{hint}", ""+ detail = body.get("detail") if isinstance(body, dict) else None+ envelope = body.get("error") if isinstance(body, dict) else None+ code = Noneif isinstance(body, dict) and "detail" in body:- if isinstance(body["detail"], list):- return _scrub(_validation_summary(body["detail"]))- message = _detail_message(body["detail"])- elif isinstance(body, dict) and isinstance(body.get("error"), dict):- envelope = body["error"]- message = _scrub(_text(envelope.get("message")))+ if isinstance(detail, list):+ return None, _scrub(_validation_summary(detail)), None+ message = _detail_message(detail)+ if isinstance(detail, dict):+ code = detail.get("code")+ if code is None and detail.get("error") == "download_busy":+ seconds = detail.get("retry_after")+ hint = f" Retry after {seconds} s." if seconds is not None else ""+ tag = _tag("download_busy", retry_after = seconds)+ return tag, f"Another speech-to-text download is running.{hint}", ""+ elif isinstance(envelope, dict):+ message = _text(envelope.get("message"))# /v1 validation is a 400 whose envelope names the offending field.+ code = envelope.get("code")if status == 400 and envelope.get("param"):- return f"Invalid arguments: {message}"- if envelope.get("code"):- message = f"{message} ({envelope['code']})"+ return _tag(code), f"Invalid arguments: {_scrub(message)}", Noneelif isinstance(body, dict) and isinstance(body.get("message"), str):message = body["message"]else:message = _text(body)-- message = _scrub(message)- if status == 400 and headers.get(REFUSAL_HEADER) == MEMORY_REFUSAL:- return f"{message} Pass allow_oversized=true to try anyway."- message = f"{message} (HTTP {status})"+ message = _brief(message)+ scrubbed = _scrub(message)+ suffix = f"{scrubbed} (HTTP {status})"++ if (+ _refusal(headers) == MULTI_MODEL_REFUSAL+ or code == "multi_model_always"+ or (status == 409 and any(marker in message for marker in MULTI_MODEL_MARKERS))+ ):+ # Retrying cannot help: the setting keeps the other model loaded until it is unloaded.+ found = detail.get("kind") if isinstance(detail, dict) else None+ if not isinstance(found, str):+ match = _UNLOAD_KIND.search(message)+ found = match.group(1) if match else None+ kind = UNLOAD_KINDS.get(found or "")+ if kind is None:+ return _tag("multi_model_always"), suffix, MULTI_MODEL_HINT_ANY+ return _tag("multi_model_always", kind = found), suffix, MULTI_MODEL_HINT.format(kind = kind)++ if isinstance(detail, dict) and "active_generations" in (detail.get("error"), code):+ # The route's thread_ids are browser conversation ids; an agent can only cancel its own chats.+ tag = _tag("active_generations", running = detail.get("running"))+ return tag, suffix, ACTIVE_GENERATIONS_HINT++ if status == 400 and _refusal(headers) == MEMORY_REFUSAL:+ return _tag("memory_estimate"), f"{scrubbed} {MEMORY_HINT}", None++ tag = _tag(code)+ if tag is None:+ kind = _not_loaded_kind(message, path)+ tag = _tag("not_loaded", kind = kind) if kind else Noneif status == 503 and retry_after:- message += f" Retry after {retry_after} s."- return message+ suffix += f" Retry after {retry_after} s."+ return tag, suffix, CODE_HINTS.get(code) if isinstance(code, str) else Nonedef _body(resp: httpx.Response) -> Any:@@ -126,8 +270,16 @@ def _body(resp: httpx.Response) -> Any:return resp.text.strip()-def raise_for_payload(payload: Any) -> Any:- """Raise for an error carried inside a successful response; return the payload otherwise."""+def _request_path(resp: httpx.Response) -> str:+ # A Response built by hand (tests) has no request, and .request raises then.+ try:+ return resp.request.url.path+ except RuntimeError:+ return ""+++def raise_for_payload(payload: Any, *, path: str = "") -> Any:+ """Raise for an error carried inside a successful response; return the payload otherwise. ``path`` is the route that answered, for the tag's kind."""if isinstance(payload, dict):deferred = payload.get(_DEFERRED_ERROR_KEY)if deferred is not None:@@ -135,7 +287,14 @@ def raise_for_payload(payload: Any) -> Any:deferred = deferred if isinstance(deferred, dict) else {"detail": deferred}status = deferred.get("status_code")status = status if isinstance(status, int) else 500- raise tool_error(_describe(status, {"detail": deferred.get("detail")}, {}))+ # Headers are lost on a padded answer unless the route copied them in.+ sent = deferred.get("headers")+ sent = sent if isinstance(sent, dict) else {}+ headers = {str(key).lower(): str(value) for key, value in sent.items()}+ tag, message, hint = _describe(+ status, {"detail": deferred.get("detail")}, headers, path+ )+ raise tool_error(message, hint, tag = tag)if payload.get("type") == "error":nested = payload.get("error")message = payload.get("message") or (@@ -158,17 +317,18 @@ def raise_for_route(payload: Any = None,hints: Optional[Mapping[int, str]] = None,) -> Any:- """Raise a ToolError when the forwarded call failed; otherwise return its parsed JSON (or ``payload`` when the caller already parsed it, e.g. the last NDJSON line). ``hints`` maps a status to what the agent should do about it; a GPU-busy answer keeps its retry hint instead."""+ """Raise a ToolError when the forwarded call failed; otherwise return its parsed JSON (or ``payload`` when the caller already parsed it, e.g. the last NDJSON line). ``hints`` maps a status to what the agent should do about it; an answer with its own guidance (gpu_busy, Keep multiple models loaded, running chats) keeps that instead."""+ path = _request_path(resp)if resp.status_code >= 400:- body = _body(resp)- hint = None if _gpu_busy(body) is not None else (hints or {}).get(resp.status_code)- raise tool_error(_describe(resp.status_code, body, resp.headers), hint)+ tag, message, own = _describe(resp.status_code, _body(resp), resp.headers, path)+ hint = own if own is not None else (hints or {}).get(resp.status_code)+ raise tool_error(message, hint or None, tag = tag)if payload is None:try:payload = parse_json(resp.content) if resp.content.strip() else Noneexcept (ValueError, UnicodeDecodeError):return None- return raise_for_payload(payload)+ return raise_for_payload(payload, path = path)# Audio failures carry a code (detail.code on /api, error.code on /v1); each gets what to do next.diff --git a/studio/backend/studio_mcp/outputs.py b/studio/backend/studio_mcp/outputs.pyindex 2d4f1953ad8..f65d9839774 100644--- a/studio/backend/studio_mcp/outputs.py+++ b/studio/backend/studio_mcp/outputs.py@@ -186,6 +186,7 @@ class TrainingSlot(ToolOutput):loss: Optional[float] = Noneprogress_percent: Optional[float] = Noneeta_seconds: Optional[float] = None+ elapsed_seconds: Optional[float] = Noneclass ExportSlot(ToolOutput):@@ -280,10 +281,18 @@ class ChatResult(ToolOutput):cancel_id: Optional[str] = None+class EmbedMatch(ToolOutput):+ index: int+ score: float+ text: str++class EmbedResult(ToolOutput):model: Optional[RouteText] = Nonedimensions: int- embeddings: list[list[float]]+ embeddings: Optional[list[list[float]]] = None+ # With a query: the best matches, highest score first, instead of vectors.+ matches: Optional[list[EmbedMatch]] = Noneclass DecisionAnswer(ToolOutput):@@ -465,6 +474,12 @@ class VideoJobRef(ToolOutput):id: RouteTextstatus: RouteTextprogress: Optional[int] = None+ progress_percent: Optional[float] = None++ def model_post_init(self, context: Any) -> None:+ if self.progress_percent is None and self.progress is not None:+ self.progress_percent = float(self.progress)+model: Optional[RouteText] = Noneseconds: Optional[RouteText] = Nonesize: Optional[RouteText] = None@@ -512,6 +527,14 @@ class JobSummary(ToolOutput):progress_percent: Optional[float] = None+class ExportJobSummary(JobSummary):+ format: RouteText+ phase: RouteText+ # Relative to Unsloth Studio's exports folder, or only a name; never a host path.+ output: Optional[RouteText] = None+ error: Optional[RouteText] = None++class RecipeError(ToolOutput):message: RouteTextpath: Optional[RouteText] = None@@ -548,10 +571,11 @@ class JobStatus(ToolOutput):status: Optional[RouteText] = Noneprogress_percent: Optional[float] = Noneerror: Optional[RouteText] = None+ error_code: Optional[RouteText] = Nonevideo: Optional[VideoInfo] = Nonerecipe: Optional[RecipeInfo] = Noneexport: Optional[ExportInfo] = None- jobs: Optional[list[JobSummary]] = None+ jobs: Optional[list[Union[ExportJobSummary, JobSummary]]] = Noneclass LocalDataset(ToolOutput):diff --git a/studio/backend/studio_mcp/progress.py b/studio/backend/studio_mcp/progress.pynew file mode 100644index 00000000000..e78d35ca6ef--- /dev/null+++ b/studio/backend/studio_mcp/progress.py@@ -0,0 +1,81 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A heartbeat for tools that wait on one long Unsloth Studio call (a chat reply, a song, a transcript), so the agent's client sees the call is alive instead of timing it out."""++from __future__ import annotations++import asyncio+import functools+import time+from typing import Any, Awaitable, Callable, Optional, TypeVar++HEARTBEAT_S = 2.0+NOTE_TTL_S = 3 * HEARTBEAT_S++_Fn = TypeVar("_Fn", bound = Callable[..., Awaitable[Any]])+++class _Relay:+ """Stands in for the tool's ctx. MCP progress may only go up, so the tool's own reports (a download fraction) become the heartbeat's message instead of going out themselves."""++ def __init__(self, ctx: Any) -> None:+ self._ctx = ctx+ self._note: Optional[str] = None+ self._note_at = 0.0++ async def report_progress(+ self,+ progress: float,+ total: Optional[float] = None,+ message: Optional[str] = None,+ ) -> None:+ percent = f" {100 * progress / total:.0f}%" if total else ""+ self._note = f"{message or 'Working'}{percent}"+ self._note_at = time.monotonic()++ @property+ def note(self) -> Optional[str]:+ # A finished phase (a model download) sends no last report, so a quiet note has ended.+ if time.monotonic() - self._note_at > NOTE_TTL_S:+ return None+ return self._note++ def __getattr__(self, name: str) -> Any:+ return getattr(self._ctx, name)+++async def _beat(ctx: Any, relay: _Relay, label: str, started: float) -> None:+ last = 0.0+ while True:+ await asyncio.sleep(HEARTBEAT_S)+ elapsed = max(round(time.monotonic() - started, 1), last + 0.1)+ last = elapsed+ note = f": {relay.note}" if relay.note else ""+ try:+ await ctx.report_progress(elapsed, None, f"{label}{note}, {elapsed:.0f} s")+ except Exception:+ # A client that went away or never asked for progress is not the tool's failure.+ pass+++def with_heartbeat(label: str) -> Callable[[_Fn], _Fn]:+ """Report elapsed time every 2 s while the tool runs. The tool must take ``ctx`` as a keyword; FastMCP passes it that way and still sees the Context parameter through ``functools.wraps``."""++ def decorate(fn: _Fn) -> _Fn:+ @functools.wraps(fn)+ async def wrapper(*args: Any, **kwargs: Any) -> Any:+ ctx = kwargs.get("ctx")+ if ctx is None:+ return await fn(*args, **kwargs)+ relay = _Relay(ctx)+ # A sibling task: the tool itself keeps running in the caller's task and context.+ beat = asyncio.create_task(_beat(ctx, relay, label, time.monotonic()))+ try:+ return await fn(*args, **{**kwargs, "ctx": relay})+ finally:+ beat.cancel()++ return wrapper # type: ignore[return-value]++ return decoratediff --git a/studio/backend/studio_mcp/tools/audio.py b/studio/backend/studio_mcp/tools/audio.pyindex 83db470599c..971f30f7e00 100644--- a/studio/backend/studio_mcp/tools/audio.py+++ b/studio/backend/studio_mcp/tools/audio.py@@ -40,6 +40,7 @@ from studio_mcp.outputs import (TranscriptResult,TranscriptSegment,)+from studio_mcp.progress import with_heartbeatfrom studio_mcp.tools import WRITES, opt_text, present, route_json, strings, try_jsonLOAD_AUDIO_HINT = "Load a text-to-speech or music model with load_model(kind='tts') first."@@ -241,6 +242,7 @@ async def _run_takes(_CANCELLED[key] = time.monotonic()+@with_heartbeat("Generating audio")async def generate_audio(workflow: Literal["clone", "speak", "edit", "convert", "music", "separate"],model: Optional[str] = None,@@ -284,6 +286,7 @@ async def generate_audio(Optional[int], Field(ge = 32, le = 1024, description = "Unused for audio, which has no preview.")] = None,options: Optional[dict[str, Any]] = None,+ ctx: Optional[Context] = None,) -> ToolResult:"""Run an Audio page workflow with the audio model loaded in Unsloth Studio, or with ``model`` (an id from list_models(workflow=...)), which Unsloth Studio loads first when "Switch model by request" is on in Settings > API; a model that cannot run the workflow is refused before anything is unloaded, and the refusal names the pages it runs on. Clips are saved to Audio history and returned as links, or inline with return_media="inline" when the WAV fits 1.5 MiB. clone: speak ``text`` in the voice of ``reference`` (a clip, or a saved voice as voice_id; ``reference_text`` is its transcript). speak: ``text`` in the loaded model's default voice, or a saved voice via ``reference``. edit: change the words or delivery of ``source`` per ``edit``. convert: make ``source`` sound like ``target``. music: ``mode`` song or sfx from ``text`` (the style) and ``lyrics``; ``variations`` up to 4 share a group_id. separate: split ``source`` into stems. ``options`` are the loaded model's ``audio_options`` that studio_status lists, such as a built-in ``voice``. Audio inputs are an Unsloth Studio id, inline base64 with a filename, or a path on the Unsloth Studio computer. Failures start with a [code] tag, such as [runtime_stopped] (retry once, then reload) or [out_of_memory] (CPU or a smaller variant)."""caller = current_caller()@@ -527,6 +530,7 @@ async def _transcribe_source()+@with_heartbeat("Transcribing")async def transcribe(audio: AudioInput,language: Optional[str] = None,diff --git a/studio/backend/studio_mcp/tools/cancel.py b/studio/backend/studio_mcp/tools/cancel.pyindex cb9d3c8635e..1fe9437e0c3 100644--- a/studio/backend/studio_mcp/tools/cancel.py+++ b/studio/backend/studio_mcp/tools/cancel.py@@ -42,7 +42,7 @@ ROUTES = {"diffusion_training": ("/api/train/diffusion/stop", "save"),"recipe": ("/api/data-recipe/jobs/{id}/cancel", None),"image": ("/api/inference/images/generate/cancel", None),- "video": ("/api/inference/video/generate/cancel", None),+ "video": ("/api/inference/video/generate/cancel", "video_id"),"chat": ("/api/inference/cancel", "cancel_id"),"audio": ("/api/inference/audio/cancel", "cancel_id"),"dataset_download": ("/api/hub/datasets/download/cancel", "repo_id"),@@ -108,7 +108,18 @@ async def cancel(id: Optional[str] = None,save: bool = True,) -> CancelResult:- """Stop Unsloth Studio work. "training" stops the LLM training run ``id`` (or the current one) at its next safe point, saving a checkpoint unless ``save`` is false. "training_start" withdraws a start request that has not begun. "diffusion_training" stops image LoRA training, saving the partial adapter unless ``save`` is false. "export" stops the running export and unloads its checkpoint; with ``id`` (an export_model job) only that job's own step, never someone else's export. "recipe" stops recipe job ``id``. "image" and "video" stop the generation in progress. "chat" stops the reply with cancel_id ``id``. "dataset_download" stops downloading the dataset ``id`` (its repo id). "audio" stops the generate_audio run whose cancel_id is ``id``; takes it already finished stay in Audio history. ``cancelled`` says whether this call stopped something."""+ """Stop Unsloth Studio work.+ "training" stops the LLM training run ``id`` (or the current one) at its next safe point, saving a checkpoint unless ``save`` is false.+ "training_start" withdraws a start request that has not begun.+ "diffusion_training" stops image LoRA training, saving the partial adapter unless ``save`` is false.+ "export" stops the running export and unloads its checkpoint; with ``id`` (an export_model job) only that job's own step, never someone else's export.+ "recipe" stops recipe job ``id``.+ "image" stops the generation in progress; "video" stops the render in progress, or with ``id`` only that video, refusing if it is not the one rendering.+ "chat" stops the reply with cancel_id ``id``.+ "audio" stops the generate_audio run whose cancel_id is ``id``; takes it already finished stay in Audio history.+ "dataset_download" stops downloading the dataset ``id`` (its repo id).+ ``cancelled`` says whether this call stopped something.+ """caller = current_caller()def done(cancelled: bool, message: Optional[str]) -> CancelResult:@@ -116,6 +127,10 @@ async def cancel(if kind in NEEDS_ID and not id:raise ToolError(f"cancel(kind={kind!r}) needs id: {NEEDS_ID[kind]}.")+ if kind in ("image", "diffusion_training") and id:+ raise ToolError(+ f"cancel(kind={kind!r}) takes no id: this cancel stops the running one; leave id out."+ )if kind == "training":if not id:status = await route_json("GET", "/api/train/status", caller = caller)diff --git a/studio/backend/studio_mcp/tools/jobs.py b/studio/backend/studio_mcp/tools/jobs.pyindex 6d17aafb67d..37e2549f7ed 100644--- a/studio/backend/studio_mcp/tools/jobs.py+++ b/studio/backend/studio_mcp/tools/jobs.py@@ -29,6 +29,7 @@ from studio_mcp.media import (from studio_mcp import export_jobsfrom studio_mcp.outputs import (ExportInfo,+ ExportJobSummary,JobStatus,JobSummary,RecipeError,@@ -75,9 +76,10 @@ async def _video_job(status = JobStatus(kind = "video",id = opt_text(job.get("id")) or video_id,- status = opt_text(job.get("status")),+ status = "cancelled" if error.get("code") == "cancelled" else opt_text(job.get("status")),progress_percent = number(job.get("progress")),error = opt_text(error.get("message")),+ error_code = opt_text(error.get("code")),video = video,seed = integer(job.get("seed")),)@@ -90,7 +92,11 @@ async def _video_jobs(caller: Caller) -> ToolResult:jobs = [JobSummary.from_route(row,- status = opt_text(row.get("status")) or "queued",+ status = (+ "cancelled"+ if as_dict(row.get("error")).get("code") == "cancelled"+ else opt_text(row.get("status")) or "queued"+ ),progress_percent = number(row.get("progress")),)for row in rows or []@@ -168,8 +174,15 @@ def _export_status(job: export_jobs.ExportJob) -> JobStatus:async def _export_job(caller: Caller, job_id: Optional[str]) -> ToolResult:if job_id is None:jobs = [- JobSummary(id = job.job_id, status = job.status)- for job in export_jobs.jobs_of(caller.account_id)+ ExportJobSummary(+ id = job.job_id,+ status = job.status,+ format = job.format,+ phase = job.phase,+ output = job.output,+ error = job.error,+ )+ for job in reversed(export_jobs.jobs_of(caller.account_id))]return media_result([], JobStatus(kind = "export", jobs = jobs))# Settles from its own export call, not the export status (that is whichever op ran last).diff --git a/studio/backend/studio_mcp/tools/status.py b/studio/backend/studio_mcp/tools/status.pyindex 97bce1c37d0..d9eba465ecb 100644--- a/studio/backend/studio_mcp/tools/status.py+++ b/studio/backend/studio_mcp/tools/status.py@@ -137,9 +137,11 @@ def _training(payload: dict) -> TrainingSlot:payload,step = step,total_steps = total,- loss = number(details.get("loss")),+ # Step 0 carries a 0.0 placeholder until the first logged loss.+ loss = number(details.get("loss")) if step else None,progress_percent = round(100.0 * step / total, 1) if step is not None and total else None,eta_seconds = number(details.get("eta_seconds")),+ elapsed_seconds = number(details.get("elapsed_seconds")),)diff --git a/studio/backend/studio_mcp/tools/text.py b/studio/backend/studio_mcp/tools/text.pyindex 62b2e7be6dd..57ab9964699 100644--- a/studio/backend/studio_mcp/tools/text.py+++ b/studio/backend/studio_mcp/tools/text.py@@ -6,9 +6,11 @@from __future__ import annotationsimport json+import mathimport uuidfrom typing import Annotated, Any, Literal, Optional, Union+from fastmcp import Contextfrom fastmcp.exceptions import ToolErrorfrom pydantic import BaseModel, ConfigDict, Field@@ -17,10 +19,19 @@ from studio_mcp.caller import current_callerfrom studio_mcp.errors import raise_for_routefrom studio_mcp.forward import forwardfrom studio_mcp.inputs import ImageInput, resolve_images-from studio_mcp.outputs import ChatResult, DecisionAnswer, EmbedResult, SystemOneResult, Usage+from studio_mcp.outputs import (+ ChatResult,+ DecisionAnswer,+ EmbedMatch,+ EmbedResult,+ SystemOneResult,+ Usage,+)+from studio_mcp.progress import with_heartbeatfrom studio_mcp.tools import READ_ONLY, WRITES, integer, number, opt_text, present, route_jsonMAX_EMBED_INPUTS = 2048+DEFAULT_TOP_K = 10LOAD_CHAT_HINT = "Load a chat model with load_model first; list_models shows the downloaded ones."NOT_LOADED = "No model loaded"# The chat route takes 128 MiB of base64 images per request.@@ -59,6 +70,7 @@ async def _attach_images(turns: list[dict], images: list[ImageInput]) -> None:last_user["content"] = [{"type": "text", "text": last_user["content"]}, *parts]+@with_heartbeat("Waiting for the reply")async def chat(messages: Optional[list[ChatTurn]] = None,prompt: Optional[str] = None,@@ -66,12 +78,42 @@ async def chat(images: Optional[list[ImageInput]] = None,max_tokens: Optional[int] = None,temperature: Optional[float] = None,+ enable_thinking: Annotated[+ Optional[bool],+ Field(+ description = "Turn a thinking model's reasoning on or off; unset keeps the model's default."+ ),+ ] = None,+ reasoning_effort: Annotated[+ Optional[Literal["none", "minimal", "low", "medium", "high", "max", "xhigh"]],+ Field(+ description = "Reasoning depth on models with effort levels; unset keeps the model's default."+ ),+ ] = None,+ response_format: Annotated[+ Optional[dict[str, Any]],+ Field(+ description = 'Constrain the reply, e.g. {"type": "json_object"} or {"type": "json_schema", "json_schema": {...}}; a backend that cannot constrain it refuses the request.'+ ),+ ] = None,model: Optional[str] = None,cancel_id: Annotated[Optional[str], Field(min_length = 8, max_length = 64, pattern = r"^[A-Za-z0-9_-]+$")] = None,+ ctx: Optional[Context] = None,) -> ChatResult:- """Chat with the model loaded in Unsloth Studio and return its reply. Send either ``prompt`` (one user turn) or ``messages`` (the whole conversation), plus an optional ``system`` prompt. ``images`` go with the last user turn and need a vision model. ``model`` names which loaded model should answer; without it the active one does. Load a model with load_model first. A thinking model spends tokens on reasoning before the reply, so leave ``max_tokens`` unset or give it a few hundred or more. Unsloth Studio's server-side tools are not used. To be able to stop a long reply from another call, pass your own ``cancel_id`` (8-64 letters, digits, - or _) and call cancel(kind="chat", id=cancel_id)."""+ """Chat with the model loaded in Unsloth Studio and return its reply.+ Send either ``prompt`` (one user turn) or ``messages`` (the whole conversation), plus an optional ``system`` prompt.+ ``images`` go with the last user turn and need a vision model.+ ``model`` names which loaded model should answer; without it the active one does.+ Load a model with load_model first.+ A thinking model spends tokens on reasoning before the reply, so leave ``max_tokens`` unset or give it a few hundred or more.+ ``enable_thinking`` turns that reasoning on or off, and ``reasoning_effort`` sets its depth on models with effort levels.+ ``response_format`` asks for JSON ({"type": "json_object"}) or a JSON schema; a backend that cannot constrain the reply refuses it.+ Unsloth Studio's server-side tools are not used.+ While the reply is being written, the call reports progress every few seconds.+ To be able to stop a long reply from another call, pass your own ``cancel_id`` (8-64 letters, digits, - or _) and call cancel(kind="chat", id=cancel_id).+ """if (messages is None) == (prompt is None):raise ToolError("Send either prompt or messages, not both and not neither.")turns = (@@ -94,7 +136,13 @@ async def chat("enable_tools": False,# Per-run id (the route scopes it to the caller's account), so only a cancel aimed at this chat stops it."cancel_id": cancel_id,- **present(max_tokens = max_tokens, temperature = temperature),+ **present(+ max_tokens = max_tokens,+ temperature = temperature,+ enable_thinking = enable_thinking,+ reasoning_effort = reasoning_effort,+ response_format = response_format,+ ),}# Beats a CLI --enable-tools too; forward's task copies this context into the route.with tools_force_disabled():@@ -112,28 +160,61 @@ async def chat(answered = opt_text(payload.get("model"))text = message.get("content") if isinstance(message.get("content"), str) else ""finish_reason = opt_text(choices[0].get("finish_reason"))- note = None+ notes = []if model and answered and not _same_model(model, answered):- note = f"{answered} answered; {model} is not the model that served this request."- elif not text.strip() and finish_reason == "length":- # Thinking models can spend the whole budget before the visible reply starts.- note = "The reply ran out of tokens before any text, likely spent on the model's reasoning; raise max_tokens."+ notes.append(f"{answered} answered; {model} is not the model that served this request.")+ if finish_reason == "length":+ notes.append(+ # Thinking models can spend the whole budget before the visible reply starts.+ "The reply ran out of tokens before any text, likely spent on the model's reasoning; raise max_tokens."+ if not text.strip()+ else "The reply was cut off at max_tokens; raise max_tokens for the rest."+ )return ChatResult(text = text,model = answered,finish_reason = finish_reason,usage = Usage.from_route(usage) if usage else None,- note = note,+ note = " ".join(notes) or None,cancel_id = cancel_id,)+def _cosine(a: list[float], b: list[float]) -> float:+ norm = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))+ return sum(x * y for x, y in zip(a, b)) / norm if norm else 0.0++async def embed(texts: Annotated[list[str], Field(min_length = 1, max_length = MAX_EMBED_INPUTS)],model: Optional[str] = None,+ query: Annotated[+ Optional[str],+ Field(+ description = "Rank texts by cosine similarity to this text and return the best matches instead of vectors."+ ),+ ] = None,+ top_k: Annotated[+ Optional[int],+ Field(+ ge = 1,+ le = MAX_EMBED_INPUTS,+ description = "How many matches to return with query (default 10)",+ ),+ ] = None,) -> EmbedResult:- """Embed up to 2048 texts and return one vector per text, in order. Uses the embedding GGUF loaded in Unsloth Studio when there is one, else Unsloth Studio's configured embedding model. ``model`` names a specific one; the result names the model that answered. Compare vectors with cosine similarity."""- body = {"input": texts}+ """Embed up to 2048 texts and return one vector per text, in order.+ Uses the embedding GGUF loaded in Unsloth Studio when there is one, else Unsloth Studio's configured embedding model.+ ``model`` names a specific one; the result names the model that answered.+ Compare vectors with cosine similarity.+ With ``query`` (and at most 2047 texts), the call ranks the texts by cosine similarity to it and returns the ``top_k`` best (default 10) as ``matches``, with no vectors.+ """+ if top_k is not None and query is None:+ raise ToolError("top_k needs query.")+ if query is not None and len(texts) > MAX_EMBED_INPUTS - 1:+ raise ToolError(f"With query, texts may hold at most {MAX_EMBED_INPUTS - 1}.")+ inputs = texts if query is None else [query, *texts]+ body: dict[str, Any] = {"input": inputs}if model:body["model"] = modelpayload = await route_json(@@ -148,11 +229,23 @@ async def embed(),key = lambda row: integer(row.get("index")) or 0,)- if len(rows) != len(texts):- raise ToolError(f"Unsloth Studio returned {len(rows)} embeddings for {len(texts)} texts")+ if len(rows) != len(inputs):+ raise ToolError(f"Unsloth Studio returned {len(rows)} embeddings for {len(inputs)} texts")embeddings = [[float(value) for value in row["embedding"]] for row in rows]+ model_name = opt_text(payload.get("model"))+ if query is None:+ return EmbedResult(model = model_name, dimensions = len(embeddings[0]), embeddings = embeddings)+ scored = sorted(+ ((_cosine(embeddings[0], vector), index) for index, vector in enumerate(embeddings[1:])),+ key = lambda pair: (-pair[0], pair[1]),+ )return EmbedResult(- model = opt_text(payload.get("model")), dimensions = len(embeddings[0]), embeddings = embeddings+ model = model_name,+ dimensions = len(embeddings[0]),+ matches = [+ EmbedMatch(index = index, score = score, text = texts[index])+ for score, index in scored[: top_k or DEFAULT_TOP_K]+ ],)diff --git a/studio/backend/tests/test_job_accounts.py b/studio/backend/tests/test_job_accounts.pyindex 2f5acbe7f1f..ddc61bf7ed2 100644--- a/studio/backend/tests/test_job_accounts.py+++ b/studio/backend/tests/test_job_accounts.py@@ -812,6 +812,8 @@ def test_owner_training_start_status_cancel_bytes_are_unchanged(training, monkey"total_steps": 0,"loss": None,"learning_rate": None,+ "elapsed_seconds": None,+ "eta_seconds": None,"output_dir": None,"drafter": None,"model_download_repo_id": None,diff --git a/studio/backend/tests/test_mcp_errors.py b/studio/backend/tests/test_mcp_errors.pyindex 3b957b7ea54..388e82094c4 100644--- a/studio/backend/tests/test_mcp_errors.py+++ b/studio/backend/tests/test_mcp_errors.py@@ -80,7 +80,7 @@ CASES = DETAIL_CASES + [),pytest.param(_v1(404, f"No model {SENTINEL}", type = "not_found_error", code = "model_not_found"),- ["No model", "(model_not_found)", "(HTTP 404)"],+ ["[model_not_found] No model", "(HTTP 404)"],id = "v1-envelope",),pytest.param(@@ -102,11 +102,28 @@ CASES = DETAIL_CASES + [[BUSY_OUT, "Retry after 9 s."],id = "gpu-busy-detail-wrapped",),+ pytest.param(+ _response(409, {"detail": {"error": "download_busy", "retry_after": 1}}),+ [+ "[download_busy retry_after=1] Another speech-to-text download is running. Retry after 1 s."+ ],+ id = "download-busy-detail",+ ),pytest.param(_v1(400, "messages: Field required", param = "messages"),["Invalid arguments: messages: Field required"],id = "v1-validation-400",),+ pytest.param(+ _v1(+ 400,+ "response_format is not supported.",+ param = "response_format",+ code = "unsupported_parameter",+ ),+ ["[unsupported_parameter] Invalid arguments: response_format is not supported."],+ id = "v1-validation-400-keeps-its-code",+ ),pytest.param(_response(422, VALIDATION_422),["Invalid arguments: max_tokens: Input should be a valid integer; query.name: bad"],@@ -202,7 +219,9 @@ def test_tool_guidance_survives_the_scrub():{"error": "gpu_busy", "message": "Another account is generating.", "retry_after": 3},headers = {"Retry-After": "3"},)- assert _message(busy, hints = {409: "x"}) == f"{BUSY_OUT}. Retry after 3 s."+ message = _message(busy, hints = {409: "x"})+ assert message.startswith("[gpu_busy retry_after=3] ")+ assert message.endswith(f"] {BUSY_OUT}. Retry after 3 s.")def test_a_routes_own_call_this_route_hint_is_dropped():@@ -210,3 +229,249 @@ def test_a_routes_own_call_this_route_hint_is_dropped():assert str(error) == "No model loaded. Load a chat model."# A path outside a route hint is scrubbed, not dropped.assert str(tool_error("Saved to /srv/mcp-sentinel/x.png")) == "Saved to <path>"+++# The Keep multiple models loaded refusal, as the owner and a managed account see it.+OWNER_ALWAYS = (+ "Loading this model would unload the chat model unsloth/Qwen3-0.6B, and Keep multiple models"+ " loaded is set to Always. Unload that model first, or choose When they fit."+)+MANAGED_ALWAYS = (+ "Loading this model would unload the chat model unsloth/Qwen3-0.6B, which Unsloth Studio is"+ " set to keep loaded. Unload that model first, or ask the Unsloth Studio owner."+)+ALWAYS_TAG = "[multi_model_always kind=chat] "+TOOL_HINT = "Wait for the load to finish, then retry."+++def _padded(deferred):+ return _response(200, content = b" " * 64 + json.dumps({"_deferred_error": deferred}).encode())+++def _assert_always(message, tag = ALWAYS_TAG):+ assert message.startswith(tag), message+ assert "unload_model(kind='llm')" in message+ assert "retrying won't help" in message+ assert "Retry after" not in message+ assert "force_cancel_active" not in message+ assert TOOL_HINT not in message+++ "resp",+ [+ _padded({"status_code": 409, "detail": OWNER_ALWAYS}),+ _response(+ 409,+ {"detail": OWNER_ALWAYS},+ headers = {"X-Unsloth-Refusal": "multi-model-always", "Retry-After": "5"},+ ),+ _response(409, {"detail": MANAGED_ALWAYS}),+ _v1(409, OWNER_ALWAYS, type = "conflict_error", param = "model", code = "multi_model_always"),+ # A route that copies the headers into the padded body; the copy is not the marker text.+ _padded(+ {+ "status_code": 409,+ "detail": "Loading this model would unload the chat model x.",+ "headers": {"X-UNSLOTH-REFUSAL": "multi-model-always"},+ }+ ),+ _response(+ 409, {"detail": {"code": "multi_model_always", "kind": "chat", "message": "No."}}+ ),+ ],+ ids = ["padded-deferred", "header", "managed-phrase", "v1-code", "deferred-headers", "code"],+)+def test_a_multi_model_always_refusal_is_tagged_and_names_unload_model(resp):+ _assert_always(_message(resp, hints = {409: TOOL_HINT}))+++def test_a_multi_model_always_refusal_of_an_unknown_kind_keeps_a_bare_tag():+ resp = _response(409, {"detail": "Keep multiple models loaded is set to Always."})+ message = _message(resp, hints = {409: TOOL_HINT})+ assert message.startswith("[multi_model_always] ")+ assert message.endswith(+ "Call unload_model(kind=…) for the model it names to free the GPU; retrying won't help."+ )+++def test_always_wording_on_another_status_is_not_a_refusal():+ message = _message(_response(500, {"detail": "Keep multiple models loaded is set to Always."}))+ assert not message.startswith("[")+ assert "unload_model" not in message+++ "resp",+ [+ _response(409, {"error": "gpu_busy", "message": BUSY, "retry_after": 12}),+ _response(409, {"detail": {"error": "gpu_busy", "message": BUSY, "retry_after": 12}}),+ _v1(409, BUSY, type = "conflict_error", code = "gpu_busy", headers = {"Retry-After": "12"}),+ ],+ ids = ["top-level", "detail-wrapped", "v1-envelope"],+)+def test_gpu_busy_is_tagged_with_its_retry_after(resp):+ message = _message(resp, hints = {409: TOOL_HINT})+ assert message.startswith("[gpu_busy retry_after=12] GPU busy: Another account")+ assert message.endswith("Retry after 12 s.")+ assert TOOL_HINT not in message+++def test_gpu_busy_without_a_number_keeps_a_bare_tag():+ message = _message(_response(409, {"error": "gpu_busy", "message": "Busy."}))+ assert message.startswith("[gpu_busy] GPU busy: Busy.")+++def test_a_detail_code_becomes_the_tag():+ resp = _response(500, {"detail": {"code": "out_of_memory", "message": f"OOM at {SENTINEL}"}})+ message = _message(resp)+ assert message.startswith("[out_of_memory] OOM at <path>")+ assert message.endswith("(HTTP 500)")+ # Not a plain identifier: the message stays, the tag goes.+ bad = _message(_response(500, {"detail": {"code": "Bad Code!", "message": "boom"}}))+ assert bad.startswith("boom")+++def test_a_plain_string_detail_has_no_tag():+ message = _message(_response(409, {"detail": "Another model is loading"}))+ assert not message.startswith("[")+ assert message.startswith("Another model is loading (HTTP 409)")+++ACTIVE = {+ "error": "active_generations",+ "message": (+ "Unloading would stop 1 chat that is still generating. Stop them first, or retry with"+ " force_cancel_active."+ ),+ "running": 1,+ "thread_ids": ["thread-secret"],+}+++ "resp",+ [_response(409, {"detail": ACTIVE}), _padded({"status_code": 409, "detail": ACTIVE})],+ ids = ["direct", "padded"],+)+def test_running_chats_tell_the_agent_to_wait_or_cancel_its_own(resp):+ message = _message(resp, hints = {409: TOOL_HINT})+ assert message.startswith("[active_generations running=1] Unloading would stop 1 chat")+ assert "Stop them first. (HTTP 409)" in message+ assert message.endswith("cancel(kind='chat', id=<its cancel_id>).")+ assert "Wait for the running chats to finish" in message+ assert "thread" not in message+ assert "force_cancel_active" not in message+ assert TOOL_HINT not in message+++def _at(status, body, path):+ return httpx.Response(+ status,+ content = json.dumps(body).encode(),+ headers = {"content-type": "application/json"},+ request = httpx.Request("POST", f"http://x{path}"),+ )+++ "resp,kind",+ [+ (_at(400, {"detail": "No model loaded."}, "/v1/audio/run"), "audio"),+ (_at(400, {"detail": "No model loaded."}, "/v1/audio/transcriptions"), "stt"),+ (_at(409, {"detail": "No model loaded"}, "/api/inference/audio/stt/load"), "stt"),+ (_at(400, {"detail": "No model loaded."}, "/v1/images/generations"), "image"),+ (_at(400, {"detail": "No model loaded."}, "/v1/chat/completions"), "chat"),+ (_at(400, {"detail": "No model loaded."}, "/api/inference/unload"), "chat"),+ (_response(409, {"detail": "No diffusion model is loaded."}), "image"),+ (_response(503, {"detail": "No video model loaded. Load a video model first."}), "video"),+ (_v1(400, "No model loaded. Call POST /inference/load first."), "chat"),+ (+ _at(+ 503, {"detail": "No GGUF model loaded. Load a GGUF model first."}, "/v1/embeddings"+ ),+ "chat",+ ),+ (+ _at(+ 503,+ {"detail": "No image model loaded. Load an image model first."},+ "/v1/images/generations",+ ),+ "image",+ ),+ ],+ ids = [+ "audio-path",+ "stt-v1-path",+ "stt-api-path",+ "image-path",+ "chat-path",+ "unload-path",+ "diffusion-wording",+ "video-wording",+ "no-request",+ "gguf-wording",+ "image-wording",+ ],+)+def test_not_loaded_names_the_kind(resp, kind):+ assert _message(resp).startswith(f"[not_loaded kind={kind}] No ")+++def test_a_deferred_not_loaded_uses_the_route_path():+ padded = httpx.Response(+ 200,+ content = json.dumps(+ {"_deferred_error": {"status_code": 400, "detail": "No model loaded."}}+ ).encode(),+ request = httpx.Request("POST", "http://x/api/inference/audio/load"),+ )+ assert _message(padded).startswith("[not_loaded kind=audio] ")+++NOISE = [f"load_tensors: layer {i} assigned to device CUDA0" for i in range(300)]+ERRORS = [+ "llama_model_load: error loading model: tensor 'blk.0' has wrong shape",+ "llama_init_from_model: failed to load model",+ "main: exiting due to model loading error",+]+HEAD = "llama-server failed to start (exit code 1)."+LLAMA_FAILURE = (+ f"{HEAD}\n\nllama-server output:\n"+ + "\n".join(NOISE[:150] + ERRORS[:1] + NOISE[150:] + ERRORS[1:])+ + "\n\nFull log: /srv/mcp-sentinel/logs/llama.log"+)+++ "error",+ [+ lambda: tool_error(LLAMA_FAILURE),+ lambda: _caught(_response(500, {"detail": LLAMA_FAILURE})),+ ],+ ids = ["tool-error", "route"],+)+def test_llama_server_output_is_cut_to_its_error_lines(error):+ message = str(error())+ assert message.startswith(HEAD)+ assert message.removesuffix(" (HTTP 500)").endswith(ERRORS[-1])+ assert len(message) <= 2000+ assert "load_tensors" not in message+ assert "Full log" not in message+ for line in ERRORS:+ assert line in message+ assert str(tool_error(message)) == message+++def _caught(resp):+ with pytest.raises(ToolError) as caught:+ raise_for_route(resp)+ return caught.value+++def test_a_tag_that_is_not_a_plain_code_is_dropped():+ assert str(tool_error("boom", tag = "Bad Tag")) == "boom"+ assert str(tool_error("boom", "Try again.", tag = "out_of_memory")).startswith(+ "[out_of_memory] boom Try again."+ )diff --git a/studio/backend/tests/test_mcp_progress.py b/studio/backend/tests/test_mcp_progress.pynew file mode 100644index 00000000000..9a2c5e56995--- /dev/null+++ b/studio/backend/tests/test_mcp_progress.py@@ -0,0 +1,141 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import asyncio+import inspect+from types import SimpleNamespace+from typing import Optional++import pytest++from studio_mcp import progress+from studio_mcp.progress import with_heartbeat+++class _Ctx:+ def __init__(self, fail: bool = False):+ self.reports = []+ self.fail = fail+ self.session_id = "session-1"++ async def report_progress(+ self,+ value,+ total = None,+ message = None,+ ):+ self.reports.append((value, total, message))+ if self.fail:+ raise RuntimeError("client went away")+++def fast_beat(monkeypatch):+ monkeypatch.setattr(progress, "HEARTBEAT_S", 0.01)+++async def _until(ctx, count):+ while len(ctx.reports) < count:+ await asyncio.sleep(0.005)+++def test_without_ctx_the_tool_runs_as_is():+ @with_heartbeat("Waiting")+ async def tool(x: int, ctx: Optional[object] = None) -> int:+ assert ctx is None+ return x + 1++ assert asyncio.run(tool(1)) == 2+++def test_the_wrapper_keeps_the_tool_signature():+ async def tool(prompt: str, ctx: Optional[object] = None) -> str:+ """Doc."""+ return prompt++ wrapped = with_heartbeat("Waiting")(tool)+ assert inspect.signature(wrapped) == inspect.signature(tool)+ assert wrapped.__doc__ == "Doc." and wrapped.__name__ == "tool"+++def test_the_heartbeat_reports_strictly_increasing_elapsed_seconds(monkeypatch, fast_beat):+ # A clock that never moves still yields increasing progress, which MCP requires.+ monkeypatch.setattr(progress, "time", SimpleNamespace(monotonic = lambda: 100.0))+ ctx = _Ctx()++ @with_heartbeat("Waiting for the reply")+ async def tool(ctx = None):+ await _until(ctx._ctx, 4)+ return "done"++ assert asyncio.run(tool(ctx = ctx)) == "done"+ values = [value for value, _total, _message in ctx.reports]+ assert values == sorted(set(values)) and len(values) >= 4+ assert all(total is None for _value, total, _message in ctx.reports)+ assert all(message.startswith("Waiting for the reply, ") for *_, message in ctx.reports)+ assert ctx.reports[0][2].endswith(" s")+++def test_the_tools_own_progress_becomes_the_heartbeat_note(fast_beat):+ ctx = _Ctx()++ @with_heartbeat("Transcribing")+ async def tool(ctx = None):+ await ctx.report_progress(0.25, 1.0, "Downloading whisper")+ await _until(ctx._ctx, 2)+ await ctx.report_progress(1, None)+ await _until(ctx._ctx, len(ctx._ctx.reports) + 2)+ return ctx.session_id++ assert asyncio.run(tool(ctx = ctx)) == "session-1"+ messages = [message for *_, message in ctx.reports]+ assert any(m.startswith("Transcribing: Downloading whisper 25%, ") for m in messages)+ assert messages[-1].startswith("Transcribing: Working, ")+ # The tool's own fraction never reaches the client as progress.+ assert all(value != 0.25 for value, *_ in ctx.reports)++[email protected]("raises", [False, True])+def test_the_heartbeat_stops_when_the_tool_ends(fast_beat, raises):+ ctx = _Ctx()++ @with_heartbeat("Generating audio")+ async def tool(ctx = None):+ await _until(ctx._ctx, 1)+ if raises:+ raise ValueError("route failed")+ return "ok"++ async def run():+ try:+ result = await tool(ctx = ctx)+ except ValueError:+ result = "raised"+ seen = len(ctx.reports)+ await asyncio.sleep(0.05)+ return result, seen++ result, seen = asyncio.run(run())+ assert result == ("raised" if raises else "ok")+ assert len(ctx.reports) == seen+++def test_a_client_that_rejects_progress_does_not_fail_the_tool(fast_beat):+ ctx = _Ctx(fail = True)++ @with_heartbeat("Waiting")+ async def tool(ctx = None):+ await _until(ctx._ctx, 3)+ return "ok"++ assert asyncio.run(tool(ctx = ctx)) == "ok"+++def test_a_note_the_tool_stopped_sending_expires(monkeypatch):+ clock = [100.0]+ monkeypatch.setattr(progress.time, "monotonic", lambda: clock[0])+ relay = progress._Relay(SimpleNamespace())+ asyncio.run(relay.report_progress(0.63, 1.0, "Downloading"))+ assert relay.note == "Downloading 63%"+ clock[0] += progress.NOTE_TTL_S + 1+ assert relay.note is Nonediff --git a/studio/backend/tests/test_mcp_server.py b/studio/backend/tests/test_mcp_server.pyindex 8695f68919c..e079d3ef19f 100644--- a/studio/backend/tests/test_mcp_server.py+++ b/studio/backend/tests/test_mcp_server.py@@ -117,3 +117,26 @@ def test_instructions_point_agents_at_the_workflow():for phrase in ("studio_status", "list_models", "load_model", "get_job", "cancel"):assert phrase in INSTRUCTIONSassert "Studio computer" in INSTRUCTIONS and "galleries" in INSTRUCTIONS+ for keyword in (+ "chat",+ "images",+ "audio",+ "speak",+ "clone",+ "edit",+ "convert",+ "music",+ "sfx",+ "separate",+ "transcribe",+ "video",+ "datasets",+ "fine-tune",+ "export",+ ):+ assert keyword in INSTRUCTIONS, keyword+ assert "load a model, generate, then unload_model" in INSTRUCTIONS+ assert "speech-to-text models stay loaded" in INSTRUCTIONS+ assert len(INSTRUCTIONS) <= 1900+ for absent in ("wait_s", "alongside", "signed"):+ assert absent not in INSTRUCTIONS, absentdiff --git a/studio/backend/tests/test_mcp_tool_contract.py b/studio/backend/tests/test_mcp_tool_contract.pyindex e2d4056d389..71eb90501dd 100644--- a/studio/backend/tests/test_mcp_tool_contract.py+++ b/studio/backend/tests/test_mcp_tool_contract.py@@ -8,6 +8,7 @@ from typing import Optionalimport pytestfrom fastapi.responses import JSONResponse+from studio_mcp.errors import ACTIVE_GENERATIONS_HINTfrom studio_mcp.inputs import PATH_REMOTEfrom studio_mcp.outputs import RouteText, ToolOutput, Usage@@ -63,6 +64,7 @@ REFUSED = [("chat", {"prompt": "x", "images": [{"data_url": data_url(b"text", "image/png")}]}, None),("embed", {"texts": []}, None),("embed", {"texts": ["x"] * 2049}, None),+ ("embed", {"texts": ["x"], "top_k": 3}, "top_k needs query."),("system_one", {"state": "x", "questions": {}}, None),("system_one", {"state": "x", "questions": {f"q{i}": {} for i in range(65)}}, None),("system_one", {"state": "x", "questions": {"q": {"type": "maybe"}}}, None),@@ -107,6 +109,14 @@ REFUSED = [("cancel", {"kind": kind}, "needs id")for kind in ("training_start", "recipe", "chat", "dataset_download")],+ *[+ (+ "cancel",+ {"kind": kind, "id": "x"},+ f"cancel(kind='{kind}') takes no id: this cancel stops the running one; leave id out.",+ )+ for kind in ("image", "diffusion_training")+ ],*[("export_model", {**EXPORT, "save_directory": directory}, None)for directory in ("/srv/out", "C:\\out", "~/out", "a/../../etc", "..", " ")@@ -131,6 +141,16 @@ def _detail(detail, status, **headers):SYSTEM_ONE = ("POST", "/v1/systemone")IMAGES = ("POST", "/api/inference/images/generate")+# The load and unload routes' refusal while chats run; the chat route never sends it.+ACTIVE_GENERATIONS = {+ "error": "active_generations",+ "message": (+ "Load would stop 2 chats that are still generating. Stop them first, or retry with"+ " force_cancel_active."+ ),+ "running": 2,+ "thread_ids": ["thread-a", "thread-b"],+}STT_LOAD = ("POST", "/api/inference/audio/stt/load")# (tool, args, the studio's routes, then the whole message or (check, text) pairs).@@ -139,13 +159,24 @@ ROUTE_ERRORS = ["chat",{"prompt": "hi"},{CHAT: openai_error("No model loaded. Call POST /inference/load first.", 400)},+ ("starts", "[not_loaded kind=chat] No model loaded. (HTTP 400) "),("ends", "Load a chat model with load_model first; list_models shows the downloaded ones."),),("chat",{"prompt": "hi"},{CHAT: openai_error("Busy.", 409, code = "gpu_busy", headers = {"Retry-After": "5"})},- "GPU busy: Busy. Retry after 5 s.",+ ("starts", "[gpu_busy retry_after=5] "),+ ("ends", "] GPU busy: Busy. Retry after 5 s."),+ ),+ (+ "chat",+ {"prompt": "hi"},+ {CHAT: _detail(ACTIVE_GENERATIONS, 409)},+ ("starts", "[active_generations running=2] Load would stop 2 chats"),+ ("ends", " (HTTP 409) " + ACTIVE_GENERATIONS_HINT),+ ("lacks", "force_cancel_active"),+ ("lacks", "thread"),),("embed",@@ -176,7 +207,12 @@ ROUTE_ERRORS = ["generate_audio",{"workflow": "speak", "text": "Hi"},{("POST", "/v1/audio/run"): openai_error("No model loaded.", 400)},- "No model loaded. (HTTP 400) Load a text-to-speech or music model with load_model(kind='tts') first.",+ ("starts", "[not_loaded kind=audio] "),+ (+ "ends",+ "] No model loaded. (HTTP 400) Load a text-to-speech or music model with"+ " load_model(kind='tts') first.",+ ),),("generate_audio",@@ -211,13 +247,23 @@ ROUTE_ERRORS = ["generate_video",{"prompt": "waves"},{("POST", "/v1/videos"): openai_error("No video model is loaded.", 503)},- "No video model is loaded. (HTTP 503) Load a video model with load_model(kind='video') first.",+ ("starts", "[not_loaded kind=video] "),+ (+ "ends",+ "] No video model is loaded. (HTTP 503) Load a video model with"+ " load_model(kind='video') first.",+ ),),("generate_image",{"prompt": "x"},{IMAGES: _detail("No diffusion model is loaded.", 409)},- "No diffusion model is loaded. (HTTP 409) Load an image model with load_model(kind='image') first.",+ ("starts", "[not_loaded kind=image] "),+ (+ "ends",+ "] No diffusion model is loaded. (HTTP 409) Load an image model with"+ " load_model(kind='image') first.",+ ),),("generate_image",@@ -229,7 +275,8 @@ ROUTE_ERRORS = ["generate_image",{"prompt": "x", "width": 2048, "height": 2048},{IMAGES: _detail("Needs 30 GB.", 400, **{"X-Unsloth-Refusal": "memory-estimate"})},- "Needs 30 GB. Pass allow_oversized=true to try anyway.",+ ("starts", "[memory_estimate] "),+ ("ends", "] Needs 30 GB. Pass allow_oversized=true to try anyway."),),("run_recipe",diff --git a/studio/backend/tests/test_mcp_tools_audio.py b/studio/backend/tests/test_mcp_tools_audio.pyindex 5e424c4d177..a23e612dbe0 100644--- a/studio/backend/tests/test_mcp_tools_audio.py+++ b/studio/backend/tests/test_mcp_tools_audio.py@@ -16,11 +16,14 @@ from .mcp_harness import (b64,bodies,call_to,+ call_with_progress,+ fake_studio,fast_polls, # noqa: F401 (fixture)form,openai_error,run_tool,sequence,+ slow,stt_state,)@@ -607,3 +610,17 @@ def test_an_ndjson_error_line_or_early_stop_is_a_tool_error(monkeypatch, events,result, _studio = _from_source(monkeypatch, {"audio": {"clip_id": "clip-7"}}, events)assert result["isError"] is Trueassert message is None or result["content"][0]["text"] == message+++def test_a_slow_song_sends_a_heartbeat_and_still_returns_its_clip(monkeypatch):+ from studio_mcp import progress as progress_module++ monkeypatch.setattr(progress_module, "HEARTBEAT_S", 0.05)+ studio = fake_studio({("POST", "/v1/audio/run"): slow(RUN, 0.3), **GALLERY})+ progress, result = call_with_progress(+ monkeypatch, studio, "generate_audio", {"workflow": "speak", "text": "Hi"}+ )+ assert result["isError"] is False+ assert result["structuredContent"]["clips"][0]["id"] == "clip-1"+ assert len(progress) >= 2+ assert all(p["message"].startswith("Generating audio") for p in progress)diff --git a/studio/backend/tests/test_mcp_tools_cancel.py b/studio/backend/tests/test_mcp_tools_cancel.pyindex 9efd52a2a06..86f8a7e62a6 100644--- a/studio/backend/tests/test_mcp_tools_cancel.py+++ b/studio/backend/tests/test_mcp_tools_cancel.py@@ -5,6 +5,7 @@ import asyncioimport typesimport pytest+from fastapi.responses import JSONResponsefrom studio_mcp import export_jobs@@ -13,6 +14,7 @@ from .mcp_harness import bodies, register_export_job, run_tool, sequenceSTART = "/api/train/start-requests/req-1/cancel"RECIPE = "/api/data-recipe/jobs/rec-1/cancel"DOWNLOAD = "/api/hub/datasets/download/cancel"+VIDEO = "/api/inference/video/generate/cancel"STOPPING = "Stop requested. Training will stop at the next safe step."PAYLOADS = {("GET", "/api/train/status"): {"job_id": "job-7", "is_training_running": True},@@ -65,7 +67,8 @@ def _call(),({"kind": "recipe", "id": "rec-1"}, RECIPE, None),({"kind": "image"}, "/api/inference/images/generate/cancel", None),- ({"kind": "video"}, "/api/inference/video/generate/cancel", None),+ ({"kind": "video"}, VIDEO, {"video_id": None}),+ ({"kind": "video", "id": "vid-1"}, VIDEO, {"video_id": "vid-1"}),({"kind": "chat", "id": "mcp-abc"}, "/api/inference/cancel", {"cancel_id": "mcp-abc"}),({"kind": "dataset_download", "id": "a/b"}, DOWNLOAD, {"repo_id": "a/b"}),],@@ -79,6 +82,24 @@ def test_each_kind_reaches_its_route(monkeypatch, args, route, body):assert (bodies(studio, route)[0] if call[3] else None) == body+def test_a_video_id_that_is_not_rendering_is_reported(monkeypatch):+ refused = JSONResponse({"detail": "That video is not rendering."}, status_code = 409)+ result, _studio = _call(+ monkeypatch, {"kind": "video", "id": "vid-2"}, {("POST", VIDEO): refused}+ )+ assert result["isError"] is True+ assert "That video is not rendering." in result["content"][0]["text"]++[email protected]("kind", ["image", "diffusion_training"])+def test_an_id_on_a_kind_that_takes_none_is_refused_before_any_route(monkeypatch, kind):+ result, studio = _call(monkeypatch, {"kind": kind, "id": "x-1"})+ assert result["isError"] is True+ text = result["content"][0]["text"]+ assert f"cancel(kind='{kind}') takes no id: this cancel stops the running one" in text+ assert studio.state.calls == []++def test_training_without_an_id_stops_the_running_job(monkeypatch):result, studio = _call(monkeypatch, {"kind": "training"})assert result["structuredContent"] == {diff --git a/studio/backend/tests/test_mcp_tools_export.py b/studio/backend/tests/test_mcp_tools_export.pyindex b72c21beaae..0c99587cc98 100644--- a/studio/backend/tests/test_mcp_tools_export.py+++ b/studio/backend/tests/test_mcp_tools_export.py@@ -114,11 +114,29 @@ def test_the_registry_runs_settles_fails_and_cancels_tasks():def test_without_an_id_only_this_accounts_jobs_are_listed(monkeypatch):- register_export_job(job_id = "mine", status = "completed")+ register_export_job(job_id = "mine", status = "completed", phase = "done", output = "my-gguf")register_export_job(account_id = "alice-id", job_id = "theirs")+ register_export_job(job_id = "newer", status = "failed", phase = "exporting", error = "Disk full")result, _studio = _get(monkeypatch, {"kind": "export"})assert result["structuredContent"]["jobs"] == [- {"id": "mine", "status": "completed", "progress_percent": None}+ {+ "id": "newer",+ "status": "failed",+ "progress_percent": None,+ "format": "gguf",+ "phase": "exporting",+ "output": None,+ "error": "Disk full",+ },+ {+ "id": "mine",+ "status": "completed",+ "progress_percent": None,+ "format": "gguf",+ "phase": "done",+ "output": "my-gguf",+ "error": None,+ },]diff --git a/studio/backend/tests/test_mcp_tools_loading.py b/studio/backend/tests/test_mcp_tools_loading.pyindex 6aa9c5dd19a..da518c7110d 100644--- a/studio/backend/tests/test_mcp_tools_loading.py+++ b/studio/backend/tests/test_mcp_tools_loading.py@@ -4,7 +4,7 @@import jsonimport pytest-from fastapi.responses import Response+from fastapi.responses import JSONResponse, Responsefrom .mcp_harness import (DEFERRED,@@ -481,3 +481,41 @@ def test_stt_unload_names_the_engine_and_model_in_the_query(assert queries(studio, f"{STT}/unload") == ([query] if query else [])unloads = [c[3] for c in studio.state.calls if c[1].endswith("/unload")]assert unloads == ([b""] if unloaded else [])+++def test_a_padded_keep_loaded_refusal_names_unload_model(monkeypatch):+ refusal = (+ "Loading this model would unload the chat model unsloth/Qwen3-0.6B, and Keep multiple"+ " models loaded is set to Always. Unload that model first, or choose When they fit."+ )+ padded = " " * 40 + json.dumps({"_deferred_error": {"status_code": 409, "detail": refusal}})+ routes = {**PAYLOADS, LOAD: Response(padded.encode(), media_type = "application/json")}+ result, _studio = run_tool(monkeypatch, routes, "load_model", {"model": LLM})+ message = result["content"][0]["text"]+ assert result["isError"] is True+ assert message.startswith("[multi_model_always kind=chat] Loading this model")+ assert message.endswith("Call unload_model(kind='llm') to free the GPU; retrying won't help.")+ assert "Retry after" not in message+++def test_running_chats_block_a_load_with_a_wait_or_cancel_hint(monkeypatch):+ detail = {+ "error": "active_generations",+ "message": (+ "Load would stop 1 chat that is still generating. Stop them first, or retry with"+ " force_cancel_active."+ ),+ "running": 1,+ "thread_ids": ["thread-a"],+ }+ routes = {**PAYLOADS, LOAD: JSONResponse({"detail": detail}, status_code = 409)}+ result, _studio = run_tool(monkeypatch, routes, "load_model", {"model": LLM})+ message = result["content"][0]["text"]+ assert result["isError"] is True+ assert message.startswith("[active_generations running=1] Load would stop 1 chat")+ assert message.endswith(+ "Wait for the running chats to finish, or cancel a chat you started with"+ " cancel(kind='chat', id=<its cancel_id>)."+ )+ assert "thread" not in message+ assert "force_cancel_active" not in messagediff --git a/studio/backend/tests/test_mcp_tools_status.py b/studio/backend/tests/test_mcp_tools_status.pyindex eaffadf5e7b..4e69157a4d9 100644--- a/studio/backend/tests/test_mcp_tools_status.py+++ b/studio/backend/tests/test_mcp_tools_status.py@@ -171,6 +171,7 @@ def test_every_slot_is_reported(monkeypatch):"loss": 1.25,"progress_percent": 25.0,"eta_seconds": None,+ "elapsed_seconds": None,}# Image LoRA training runs on its own trainer: start_training(kind="diffusion") is followed here.assert status["diffusion_training"] == {@@ -184,6 +185,7 @@ def test_every_slot_is_reported(monkeypatch):"loss": 0.5,"progress_percent": 2.4,"eta_seconds": None,+ "elapsed_seconds": None,}assert status["export"] == {"active": False,@@ -295,3 +297,29 @@ def test_unloaded_slots_name_no_model(monkeypatch):"generating": False,}assert status["video"] == {"loaded": False, "model": None, **VIDEO_EXTRAS, "generating": False}+++def _training_slot(monkeypatch, details):+ payload = {**TRAINING, "details": details}+ overrides = {("GET", "/api/train/status"): payload}+ return _status(monkeypatch, overrides)[0]["structuredContent"]["training"]+++def test_the_step_zero_loss_placeholder_reads_as_no_loss(monkeypatch):+ for step in (0, None):+ slot = _training_slot(monkeypatch, {"step": step, "total_steps": 100, "loss": 0.0})+ assert slot["loss"] is None+ slot = _training_slot(monkeypatch, {"step": 1, "total_steps": 100, "loss": 0.0})+ assert slot["loss"] == 0.0+++def test_training_eta_and_elapsed_pass_through(monkeypatch):+ details = {+ "step": 25,+ "total_steps": 100,+ "loss": 1.25,+ "eta_seconds": 90.5,+ "elapsed_seconds": 30.0,+ }+ slot = _training_slot(monkeypatch, details)+ assert (slot["loss"], slot["eta_seconds"], slot["elapsed_seconds"]) == (1.25, 90.5, 30.0)diff --git a/studio/backend/tests/test_mcp_tools_text.py b/studio/backend/tests/test_mcp_tools_text.pyindex 1574ad7b07f..fa29db380f8 100644--- a/studio/backend/tests/test_mcp_tools_text.py+++ b/studio/backend/tests/test_mcp_tools_text.py@@ -1,10 +1,23 @@# 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 asyncio+import pytestfrom fastapi.responses import JSONResponse, Response-from .mcp_harness import JPEG, PNG, PNG_URL, bodies, call_to, data_url, run_tool+from .mcp_harness import (+ JPEG,+ PNG,+ PNG_URL,+ bodies,+ call_to,+ call_with_progress,+ data_url,+ fake_studio,+ run_tool,+ slow,+)LLM = "unsloth/Llama-3.2-1B-Instruct-GGUF"COMPLETION = {@@ -189,6 +202,86 @@ def test_an_empty_reply_cut_off_by_the_budget_says_so(monkeypatch, content, finiassert ("raise max_tokens" in out["note"]) if noted else out["note"] is None+def _cut_off(content):+ return {**COMPLETION, "choices": [{"message": {"content": content}, "finish_reason": "length"}]}+++def test_a_reply_cut_off_mid_text_says_to_raise_max_tokens(monkeypatch):+ result, _studio = _chat(monkeypatch, {"prompt": "hi", "max_tokens": 8}, _cut_off("Paris is"))+ assert result["structuredContent"]["note"] == (+ "The reply was cut off at max_tokens; raise max_tokens for the rest."+ )+++def test_a_different_model_and_a_cut_off_reply_are_both_noted(monkeypatch):+ args = {"prompt": "hi", "model": "unsloth/Qwen3-0.6B"}+ result, _studio = _chat(monkeypatch, args, _cut_off("Paris is"))+ note = result["structuredContent"]["note"]+ assert note.startswith(f"{LLM} answered; unsloth/Qwen3-0.6B is not the model")+ assert note.endswith(". The reply was cut off at max_tokens; raise max_tokens for the rest.")+++def test_thinking_controls_and_response_format_reach_the_route(monkeypatch):+ schema = {"type": "json_schema", "json_schema": {"name": "a", "schema": {"type": "object"}}}+ args = {+ "prompt": "hi",+ "enable_thinking": False,+ "reasoning_effort": "low",+ "response_format": schema,+ }+ _result, studio = _chat(monkeypatch, args)+ run_tool(monkeypatch, studio, "chat", {"prompt": "hi"})+ sent, plain = bodies(studio, "/v1/chat/completions")+ assert (sent["enable_thinking"], sent["reasoning_effort"]) == (False, "low")+ assert sent["response_format"] == schema+ assert not {"enable_thinking", "reasoning_effort", "response_format"} & set(plain)+ refused, studio = _chat(monkeypatch, {"prompt": "hi", "reasoning_effort": "extreme"})+ assert refused["isError"] is True and bodies(studio, "/v1/chat/completions") == []+++def test_a_slow_reply_sends_a_heartbeat(monkeypatch):+ from studio_mcp import progress as progress_module++ monkeypatch.setattr(progress_module, "HEARTBEAT_S", 0.05)+ studio = fake_studio({**PAYLOADS, CHAT: slow(COMPLETION, 0.3)})+ progress, result = call_with_progress(monkeypatch, studio, "chat", {"prompt": "hi"})+ assert result["structuredContent"]["text"] == "Paris."+ assert len(progress) >= 2+ values = [p["progress"] for p in progress]+ assert values == sorted(set(values))+ assert all(p["message"].startswith("Waiting for the reply") for p in progress)+++# Tool -> the properties it listed before the heartbeat; ctx never shows.+SCHEMA_BEFORE = {+ "generate_audio": set(+ "workflow model text language instructions reference source emotion target"+ " reference_text source_text mode lyrics instrumental duration_s variations edit convert"+ " speed seed max_tokens cancel_id return_media preview_px options".split()+ ),+ "transcribe": {+ "audio",+ "language",+ "translate",+ "timestamps",+ "speakers",+ "expected_text",+ "model",+ },+ "chat": set(+ "messages prompt system images max_tokens temperature enable_thinking reasoning_effort"+ " response_format model cancel_id".split()+ ),+}+++def test_the_heartbeat_keeps_ctx_out_of_the_schemas():+ from mcp_server import create_studio_mcp+ tools = {tool.name: tool for tool in asyncio.run(create_studio_mcp().list_tools())}+ for name, expected in SCHEMA_BEFORE.items():+ assert set(tools[name].parameters["properties"]) == expected, name++@pytest.mark.parametrize("model", [None, "bge-m3"])def test_embed_returns_vectors_in_input_order(monkeypatch, model):args = {"texts": ["first", "second"], **({"model": model} if model else {})}@@ -197,6 +290,7 @@ def test_embed_returns_vectors_in_input_order(monkeypatch, model):"model": "nomic-embed-text-v1.5","dimensions": 3,"embeddings": [[1.0, 0.0, 0.25], [0.0, 1.0, 0.5]],+ "matches": None,}assert bodies(studio, "/v1/embeddings") == [{"input": args["texts"], **({"model": model} if model else {})}@@ -217,6 +311,57 @@ def test_embed_accepts_the_limit_and_refuses_a_short_answer(monkeypatch, rows, tassert len(result["structuredContent"]["embeddings"]) == texts+def _query_answer(vectors):+ return {+ "model": "m",+ "data": [{"index": i, "embedding": v} for i, v in enumerate(vectors)],+ }+++def test_embed_with_a_query_ranks_the_texts(monkeypatch):+ # Row 0 is the query; a zero vector scores 0.0 and ties fall back to input order.+ vectors = [[1.0, 0.0], [0.0, 1.0], [3.0, 4.0], [1.0, 0.0], [0.0, 0.0], [0.0, 2.0]]+ texts = ["north", "slant", "east", "nothing", "north again"]+ args = {"texts": texts, "query": "east?", "top_k": 4}+ result, studio = run_tool(+ monkeypatch, {("POST", "/v1/embeddings"): _query_answer(vectors)}, "embed", args+ )+ out = result["structuredContent"]+ assert bodies(studio, "/v1/embeddings") == [{"input": ["east?", *texts]}]+ assert out["embeddings"] is None and out["dimensions"] == 2+ assert out["matches"] == [+ {"index": 2, "score": 1.0, "text": "east"},+ {"index": 1, "score": 0.6, "text": "slant"},+ {"index": 0, "score": 0.0, "text": "north"},+ {"index": 3, "score": 0.0, "text": "nothing"},+ ]+++def test_embed_with_a_query_keeps_ten_by_default(monkeypatch):+ vectors = [[1.0]] * 13+ result, _studio = run_tool(+ monkeypatch,+ {("POST", "/v1/embeddings"): _query_answer(vectors)},+ "embed",+ {"texts": [f"t{i}" for i in range(12)], "query": "q"},+ )+ assert [m["index"] for m in result["structuredContent"]["matches"]] == list(range(10))+++ "args,message",+ [+ ({"texts": ["a"], "top_k": 3}, "top_k needs query."),+ ({"texts": ["a"] * 2048, "query": "q"}, "With query, texts may hold at most 2047."),+ ],+)+def test_embed_refuses_top_k_alone_and_a_query_over_the_limit(monkeypatch, args, message):+ result, studio = run_tool(monkeypatch, PAYLOADS, "embed", args)+ assert result["isError"] is True+ assert message in result["content"][0]["text"]+ assert bodies(studio, "/v1/embeddings") == []++def _decide(monkeypatch,args,diff --git a/studio/backend/tests/test_mcp_tools_video.py b/studio/backend/tests/test_mcp_tools_video.pyindex 2b925f1c650..0a0f5fdbdba 100644--- a/studio/backend/tests/test_mcp_tools_video.py+++ b/studio/backend/tests/test_mcp_tools_video.py@@ -85,6 +85,7 @@ def test_generate_video_starts_a_job_with_string_fields(monkeypatch):"id": "video-1","status": "queued","progress": 0,+ "progress_percent": 0.0,"model": "Lightricks/LTX-Video","seconds": "4","size": "704x480",@@ -111,6 +112,7 @@ def test_a_completed_job_returns_its_thumbnail_and_a_link_never_the_mp4(monkeypa"status": "completed","progress_percent": 100.0,"error": None,+ "error_code": None,"video": {"url": "http://192.168.1.20:8888/v1/videos/video-1/content","download_url": "http://192.168.1.20:8888/api/inference/video/gallery/video-1/file-signed?token=t.1",@@ -160,11 +162,27 @@ def test_an_unfinished_job_reports_progress_and_error_without_media(monkeypatch,assert out["status"] == job["status"]assert out["progress_percent"] == float(job["progress"])assert out["error"] == (job["error"] or {}).get("message")+ assert out["error_code"] == (job["error"] or {}).get("code")assert out["video"] is Noneassert [c["type"] for c in result["content"]] == ["text"]assert [c[1] for c in studio.state.calls] == [path]+def test_a_cancelled_job_reads_cancelled_not_failed(monkeypatch):+ # The /v1 job API has no cancelled status: it reports failed with error code "cancelled".+ job = _job(+ "video-4",+ "failed",+ 30,+ error = {"code": "cancelled", "message": "Video generation was cancelled."},+ )+ result, _studio = _get_job(monkeypatch, {"id": "video-4"}, {("GET", "/v1/videos/video-4"): job})+ out = result["structuredContent"]+ assert (out["status"], out["error_code"]) == ("cancelled", "cancelled")+ assert out["error"].startswith("Video generation was cancelled")+ assert out["video"] is None++def test_without_an_id_recent_jobs_are_listed(monkeypatch):result, studio = _get_job(monkeypatch, {})assert result["structuredContent"]["jobs"] == [@@ -172,3 +190,9 @@ def test_without_an_id_recent_jobs_are_listed(monkeypatch):{"id": "video-1", "status": "completed", "progress_percent": 100.0},]assert [c[1] for c in studio.state.calls] == ["/v1/videos"]+++def test_a_cancelled_job_reads_cancelled_in_the_recent_list(monkeypatch):+ cancelled = _job("video-4", "failed", 30, error = {"code": "cancelled", "message": "Cancelled."})+ result, _studio = _get_job(monkeypatch, {}, {("GET", "/v1/videos"): {"data": [cancelled]}})+ assert result["structuredContent"]["jobs"][0]["status"] == "cancelled"diff --git a/studio/backend/tests/test_training_finalizing_phase.py b/studio/backend/tests/test_training_finalizing_phase.pyindex 6df56f0c646..518e78c9b85 100644--- a/studio/backend/tests/test_training_finalizing_phase.py+++ b/studio/backend/tests/test_training_finalizing_phase.py@@ -172,3 +172,8 @@ def test_frontend_phase_union_covers_the_backend_literal():union = set(re.findall(r'\|\s*"([a-z_]+)"', runtime_ts.read_text(encoding = "utf-8")))missing = _phase_literals() - unionassert not missing, f"TrainingPhase is missing backend phases: {sorted(missing)}"+++def test_a_stopped_run_reports_no_eta():+ src = _ROUTES_TRAINING.read_text(encoding = "utf-8")+ assert '"eta_seconds": getattr(progress, "eta_seconds", None) if is_active else None' in srcdiff --git a/studio/backend/tests/test_training_status_eta_and_stop.py b/studio/backend/tests/test_training_status_eta_and_stop.pynew file mode 100644index 00000000000..15a3ef14829--- /dev/null+++ b/studio/backend/tests/test_training_status_eta_and_stop.py@@ -0,0 +1,77 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""/api/train/status reports eta and elapsed time, and a stopped run never reads "Training completed"."""++from __future__ import annotations++import asyncio++from .test_training_status_terminal import _DONE, _run_route_helpers_inline, _running, rt++__all__ = ["_run_route_helpers_inline"]+++def _status():+ return asyncio.run(rt.get_training_status(current_subject = "t"))+++def test_status_details_carry_elapsed_and_eta(monkeypatch):+ b = _running(monkeypatch)+ b._progress.elapsed_seconds = 30.0+ b._progress.eta_seconds = 90.5+ details = _status().details+ assert (details["elapsed_seconds"], details["eta_seconds"]) == (30.0, 90.5)+++def test_status_details_eta_is_none_before_the_first_log(monkeypatch):+ _running(monkeypatch)+ details = _status().details+ assert (details["elapsed_seconds"], details["eta_seconds"]) == (None, None)+++def test_a_cancel_during_the_final_save_reads_cancelled(monkeypatch):+ # The worker checked the stop before saving, so it still sends "Training completed!".+ b = _running(monkeypatch)+ b._should_stop = b._cancel_requested = True+ b._handle_event(dict(_DONE))+ st = _status()+ assert st.phase == "stopped"+ assert st.message == "Training cancelled."+ assert b._progress.is_completed is False+ assert b._terminal_finalize_payload["status"] == "stopped"+++def test_a_stop_during_the_drafter_phase_reads_stopped_and_keeps_the_save(monkeypatch):+ b = _running(monkeypatch)+ b._should_stop = True+ b._handle_event(dict(_DONE))+ st = _status()+ assert st.phase == "stopped"+ assert st.message == "Training stopped. Model saved to /tmp/out"+ assert st.details["output_dir"] == "/tmp/out"+++def test_a_cancelled_message_with_a_period_counts_as_stopped(monkeypatch):+ b = _running(monkeypatch)+ b._handle_event({**_DONE, "status_message": "Training cancelled."})+ assert b._progress.is_completed is False+ assert b._terminal_finalize_payload["status"] == "stopped"+++def test_a_run_with_no_stop_stays_completed(monkeypatch):+ b = _running(monkeypatch)+ b._handle_event(dict(_DONE))+ st = _status()+ assert st.phase == "completed"+ assert st.message.startswith("Training completed!")+ assert b._progress.is_completed is True+++def test_a_stop_during_the_embedding_save_reads_stopped(monkeypatch):+ b = _running(monkeypatch)+ b._should_stop = True+ b._handle_event({**_DONE, "status_message": "Embedding training completed"})+ st = _status()+ assert st.phase == "stopped"+ assert st.message == "Training stopped."diff --git a/studio/backend/tests/test_video_cancel_by_id.py b/studio/backend/tests/test_video_cancel_by_id.pynew file mode 100644index 00000000000..c08247c0d11--- /dev/null+++ b/studio/backend/tests/test_video_cancel_by_id.py@@ -0,0 +1,83 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""POST /video/generate/cancel with a ``video_id``: only that render stops, any other id is a 409."""++from __future__ import annotations++import threading++import pytest++import core.inference.video as video_module+from core.inference.video_families import VIDEO_CANCELLED_MSG++from .test_video_routes import _healthy_diffusers, _wait_terminal, client # noqa: F401++CANCEL = "/api/inference/video/generate/cancel"+++def rendering(client, monkeypatch): # noqa: F811+ """A render of /v1 job ``vid-1`` that runs until it is cancelled."""+ backend = video_module.get_video_backend()+ backend.loaded = True+ started = threading.Event()++ def wait_for_cancel(*, cancel_event = None, **kwargs):+ started.set()+ assert cancel_event is not None and cancel_event.wait(5)+ raise RuntimeError(VIDEO_CANCELLED_MSG)++ begin = backend.begin_generate+ monkeypatch.setattr(+ backend, "begin_generate", lambda **kwargs: begin(**{**kwargs, "video_id": "vid-1"})+ )+ monkeypatch.setattr(backend, "generate", wait_for_cancel)+ assert client.post("/api/inference/video/generate", json = {"prompt": "p"}).status_code == 200+ assert started.wait(5)+ return backend+++def test_a_wrong_id_is_refused_and_the_render_keeps_going(client, rendering): # noqa: F811+ resp = client.post(CANCEL, json = {"video_id": "vid-2"})+ assert resp.status_code == 409+ assert resp.json()["detail"] == "That video is not rendering."+ assert client.get("/api/inference/video/generate-progress").json()["active"] is True+ assert client.post(CANCEL).json() == {"cancelled": True}+ assert _wait_terminal(client)["error"] == VIDEO_CANCELLED_MSG+++def test_the_matching_id_cancels(client, rendering): # noqa: F811+ resp = client.post(CANCEL, json = {"video_id": "vid-1"})+ assert resp.status_code == 200 and resp.json() == {"cancelled": True}+ progress = _wait_terminal(client)+ assert progress["phase"] == "failed" and progress["error"] == VIDEO_CANCELLED_MSG++[email protected]("body", [None, {}, {"video_id": None}])+def test_without_an_id_an_idle_cancel_still_answers_false(client, body): # noqa: F811+ resp = client.post(CANCEL, **({} if body is None else {"json": body}))+ assert resp.status_code == 200 and resp.json() == {"cancelled": False}+++def test_an_id_with_nothing_rendering_is_a_409(client): # noqa: F811+ resp = client.post(CANCEL, json = {"video_id": "vid-1"})+ assert resp.status_code == 409++[email protected]("content", [b"{not json", b"[1]", b'"vid-1"', b'{"video_id": 7}'])+def test_a_bad_body_is_a_422(client, content): # noqa: F811+ resp = client.post(CANCEL, content = content, headers = {"Content-Type": "application/json"})+ assert resp.status_code == 422+ assert "no body" in resp.json()["detail"]++[email protected]("video_id", ["", " "])+def test_an_empty_id_is_a_422_and_the_render_keeps_going(client, rendering, video_id): # noqa: F811+ resp = client.post(CANCEL, json = {"video_id": video_id})+ assert resp.status_code == 422+ assert "leave it out" in resp.json()["detail"]+ assert client.get("/api/inference/video/generate-progress").json()["active"] is True+ assert client.post(CANCEL).json() == {"cancelled": True}+ assert _wait_terminal(client)["error"] == VIDEO_CANCELLED_MSGdiff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 204c2862069..338a4c6fb1a 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -3133,14 +3133,14 @@ export const ar = {},mcp: {title: "وصول الوكلاء (MCP)",- description: "اسمح لوكلاء البرمجة مثل Claude Code وCodex باستخدام Unsloth عبر MCP. يسجّل الوكلاء الدخول بتوكن وصول من هذه الصفحة.",+ description: "اسمح لوكلاء البرمجة مثل Claude Code وCodex باستخدام Unsloth عبر MCP. يسجّل الوكلاء الدخول بمفتاح API لـ Unsloth من هذه الصفحة.",enable: "السماح باتصالات الوكلاء",- enableDescription: "يخدم /mcp/ للطلبات التي تحمل توكن وصول من Unsloth.",+ enableDescription: "يخدم /mcp/ للطلبات التي تحمل مفتاح API لـ Unsloth.",lockedByEnv: "مضبوط بواسطة {name}.",loadError: "تعذّر تحميل إعدادات وصول الوكلاء.",saveError: "تعذّر حفظ إعداد وصول الوكلاء.",agent: "الوكيل",- exportKeyHint: "اضبط {name} على توكن وصول من هذه الصفحة قبل تشغيل الوكيل.",+ exportKeyHint: "اضبط {name} على مفتاح API لـ Unsloth من هذه الصفحة قبل تشغيل الوكيل.",configFileHint: "أضف هذا إلى {path}.",keywords: "mcp model context protocol agents claude codex tools وكلاء وكيل أدوات بروتوكول سياق النموذج",},diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 05fd23043d2..91fc268038e 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -3179,14 +3179,14 @@ export const de = {},mcp: {title: "Agentenzugriff (MCP)",- description: "Lass Coding-Agenten wie Claude Code und Codex Unsloth über MCP nutzen. Agenten melden sich mit einem Zugriffstoken von dieser Seite an.",+ description: "Lass Coding-Agenten wie Claude Code und Codex Unsloth über MCP nutzen. Agenten melden sich mit einem Unsloth-Studio-API-Schlüssel von dieser Seite an.",enable: "Agentenverbindungen erlauben",- enableDescription: "Stellt /mcp/ für Anfragen mit einem Unsloth-Zugriffstoken bereit.",+ enableDescription: "Stellt /mcp/ für Anfragen mit einem Unsloth-Studio-API-Schlüssel bereit.",lockedByEnv: "Festgelegt durch {name}.",loadError: "Die Einstellungen für den Agentenzugriff konnten nicht geladen werden.",saveError: "Die Einstellung für den Agentenzugriff konnte nicht gespeichert werden.",agent: "Agent",- exportKeyHint: "Setze {name} auf ein Zugriffstoken von dieser Seite, bevor du den Agenten startest.",+ exportKeyHint: "Setze {name} auf einen Unsloth-Studio-API-Schlüssel von dieser Seite, bevor du den Agenten startest.",configFileHint: "Füge das zu {path} hinzu.",keywords: "mcp model context protocol agents claude codex tools Agenten Agent Werkzeuge Tools Modellkontextprotokoll",},diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 8bef26755e8..85f2aac0bc2 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -3182,14 +3182,14 @@ export const en = {},mcp: {title: "Agent access (MCP)",- description: "Let coding agents such as Claude Code and Codex use Unsloth over MCP. Agents sign in with an access token from this page.",+ description: "Let coding agents such as Claude Code and Codex use Unsloth over MCP. Agents sign in with an Unsloth API key from this page.",enable: "Allow agent connections",- enableDescription: "Serves /mcp/ to requests that carry an Unsloth access token.",+ enableDescription: "Serves /mcp/ to requests that carry an Unsloth API key.",lockedByEnv: "Set by {name}.",loadError: "Couldn't load agent access settings.",saveError: "Couldn't save the agent access setting.",agent: "Agent",- exportKeyHint: "Set {name} to an access token from this page before you start the agent.",+ exportKeyHint: "Set {name} to an Unsloth API key from this page before you start the agent.",configFileHint: "Add this to {path}.",keywords: "mcp model context protocol agents claude codex tools",},diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 8af0cfee4dc..dd02ee81ec2 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -3172,14 +3172,14 @@ export const es = {},mcp: {title: "Acceso de agentes (MCP)",- description: "Permite que agentes de código como Claude Code y Codex usen Unsloth mediante MCP. Los agentes inician sesión con un token de acceso de esta página.",+ description: "Permite que agentes de código como Claude Code y Codex usen Unsloth mediante MCP. Los agentes inician sesión con una clave de API de Unsloth de esta página.",enable: "Permitir conexiones de agentes",- enableDescription: "Sirve /mcp/ a las solicitudes que llevan un token de acceso de Unsloth.",+ enableDescription: "Sirve /mcp/ a las solicitudes que llevan una clave de API de Unsloth.",lockedByEnv: "Definido por {name}.",loadError: "No se pudo cargar la configuración de acceso de agentes.",saveError: "No se pudo guardar la configuración de acceso de agentes.",agent: "Agente",- exportKeyHint: "Define {name} con un token de acceso de esta página antes de iniciar el agente.",+ exportKeyHint: "Define {name} con una clave de API de Unsloth de esta página antes de iniciar el agente.",configFileHint: "Añade esto a {path}.",keywords: "mcp model context protocol agents claude codex tools agentes agente herramientas protocolo de contexto de modelo",},diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex db19ca43bf2..62be5d0df97 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -3180,14 +3180,14 @@ export const fr = {},mcp: {title: "Accès des agents (MCP)",- description: "Permettez aux agents de code comme Claude Code et Codex d’utiliser Unsloth via MCP. Les agents se connectent avec un jeton d’accès de cette page.",+ description: "Permettez aux agents de code comme Claude Code et Codex d’utiliser Unsloth via MCP. Les agents se connectent avec une clé API Unsloth de cette page.",enable: "Autoriser les connexions des agents",- enableDescription: "Sert /mcp/ aux requêtes qui portent un jeton d’accès Unsloth.",+ enableDescription: "Sert /mcp/ aux requêtes qui portent une clé API Unsloth.",lockedByEnv: "Défini par {name}.",loadError: "Impossible de charger les paramètres d’accès des agents.",saveError: "Impossible d’enregistrer le paramètre d’accès des agents.",agent: "Agent",- exportKeyHint: "Définissez {name} sur un jeton d’accès de cette page avant de lancer l’agent.",+ exportKeyHint: "Définissez {name} sur une clé API Unsloth de cette page avant de lancer l’agent.",configFileHint: "Ajoutez ceci à {path}.",keywords: "mcp model context protocol agents claude codex tools agents agent outils protocole de contexte de modèle",},diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex e172f570536..0077eae8cce 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -3256,14 +3256,14 @@ export const he = {},mcp: {title: "גישת סוכנים (MCP)",- description: "אפשר לסוכני קוד כמו Claude Code ו-Codex להשתמש ב-Unsloth דרך MCP. סוכנים מתחברים עם טוקן גישה מהדף הזה.",+ description: "אפשר לסוכני קוד כמו Claude Code ו-Codex להשתמש ב-Unsloth דרך MCP. סוכנים מתחברים עם מפתח API של Unsloth מהדף הזה.",enable: "אפשר חיבורי סוכנים",- enableDescription: "מגיש את /mcp/ לבקשות שנושאות טוקן גישה של Unsloth.",+ enableDescription: "מגיש את /mcp/ לבקשות שנושאות מפתח API של Unsloth.",lockedByEnv: "נקבע על ידי {name}.",loadError: "לא ניתן לטעון את הגדרות גישת הסוכנים.",saveError: "לא ניתן לשמור את הגדרת גישת הסוכנים.",agent: "סוכן",- exportKeyHint: "הגדר את {name} לטוקן גישה מהדף הזה לפני שתפעיל את הסוכן.",+ exportKeyHint: "הגדר את {name} למפתח API של Unsloth מהדף הזה לפני שתפעיל את הסוכן.",configFileHint: "הוסף את זה ל-{path}.",keywords: "mcp model context protocol agents claude codex tools סוכנים סוכן כלים פרוטוקול הקשר מודל",},diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 69f1f184899..9a4d16199b6 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -3142,14 +3142,14 @@ export const hi = {},mcp: {title: "एजेंट एक्सेस (MCP)",- description: "Claude Code और Codex जैसे कोडिंग एजेंट को MCP के ज़रिए Unsloth इस्तेमाल करने दें। एजेंट इस पेज के एक्सेस टोकन से साइन इन करते हैं।",+ description: "Claude Code और Codex जैसे कोडिंग एजेंट को MCP के ज़रिए Unsloth इस्तेमाल करने दें। एजेंट इस पेज की Unsloth API कुंजी से साइन इन करते हैं।",enable: "एजेंट कनेक्शन की अनुमति दें",- enableDescription: "Unsloth एक्सेस टोकन वाले अनुरोधों के लिए /mcp/ उपलब्ध कराता है।",+ enableDescription: "Unsloth API कुंजी वाले अनुरोधों के लिए /mcp/ उपलब्ध कराता है।",lockedByEnv: "{name} द्वारा सेट।",loadError: "एजेंट एक्सेस सेटिंग्स लोड नहीं हो सकीं।",saveError: "एजेंट एक्सेस सेटिंग सहेजी नहीं जा सकी।",agent: "एजेंट",- exportKeyHint: "एजेंट शुरू करने से पहले {name} को इस पेज के किसी एक्सेस टोकन पर सेट करें।",+ exportKeyHint: "एजेंट शुरू करने से पहले {name} को इस पेज की किसी Unsloth API कुंजी पर सेट करें।",configFileHint: "इसे {path} में जोड़ें।",keywords: "mcp model context protocol agents claude codex tools एजेंट टूल्स मॉडल कॉन्टेक्स्ट प्रोटोकॉल",},diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex f1d68cba976..118ef13eb8f 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -3085,14 +3085,14 @@ export const it = {},mcp: {title: "Accesso degli agenti (MCP)",- description: "Consenti ad agenti di programmazione come Claude Code e Codex di usare Unsloth tramite MCP. Gli agenti accedono con un token di accesso di questa pagina.",+ description: "Consenti ad agenti di programmazione come Claude Code e Codex di usare Unsloth tramite MCP. Gli agenti accedono con una chiave API di Unsloth di questa pagina.",enable: "Consenti connessioni degli agenti",- enableDescription: "Rende disponibile /mcp/ alle richieste che portano un token di accesso di Unsloth.",+ enableDescription: "Rende disponibile /mcp/ alle richieste che portano una chiave API di Unsloth.",lockedByEnv: "Impostato da {name}.",loadError: "Impossibile caricare le impostazioni di accesso degli agenti.",saveError: "Impossibile salvare l’impostazione di accesso degli agenti.",agent: "Agente",- exportKeyHint: "Imposta {name} su un token di accesso di questa pagina prima di avviare l’agente.",+ exportKeyHint: "Imposta {name} su una chiave API di Unsloth di questa pagina prima di avviare l’agente.",configFileHint: "Aggiungi questo a {path}.",keywords: "mcp model context protocol agents claude codex tools agenti agente strumenti protocollo di contesto del modello",},diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 4bb7828ac77..b99ce27ea06 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -3102,14 +3102,14 @@ export const ja = {},mcp: {title: "エージェントアクセス (MCP)",- description: "Claude Code や Codex などのコーディングエージェントが MCP 経由で Unsloth を使えるようにします。エージェントはこのページのアクセストークンでサインインします。",+ description: "Claude Code や Codex などのコーディングエージェントが MCP 経由で Unsloth を使えるようにします。エージェントはこのページの Unsloth API キーでサインインします。",enable: "エージェントの接続を許可",- enableDescription: "Unsloth のアクセストークンを持つリクエストに /mcp/ を提供します。",+ enableDescription: "Unsloth の API キーを持つリクエストに /mcp/ を提供します。",lockedByEnv: "{name} で設定されています。",loadError: "エージェントアクセスの設定を読み込めませんでした。",saveError: "エージェントアクセスの設定を保存できませんでした。",agent: "エージェント",- exportKeyHint: "エージェントを起動する前に、{name} にこのページのアクセストークンを設定してください。",+ exportKeyHint: "エージェントを起動する前に、{name} にこのページの Unsloth API キーを設定してください。",configFileHint: "これを {path} に追加してください。",keywords: "mcp model context protocol agents claude codex tools エージェント ツール モデルコンテキストプロトコル",},diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex f88637b4e1c..5306e76dc09 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -3121,14 +3121,14 @@ export const ko = {},mcp: {title: "에이전트 액세스 (MCP)",- description: "Claude Code, Codex 같은 코딩 에이전트가 MCP로 Unsloth를 사용하게 합니다. 에이전트는 이 페이지의 액세스 토큰으로 로그인합니다.",+ description: "Claude Code, Codex 같은 코딩 에이전트가 MCP로 Unsloth를 사용하게 합니다. 에이전트는 이 페이지의 Unsloth API 키로 로그인합니다.",enable: "에이전트 연결 허용",- enableDescription: "Unsloth 액세스 토큰이 있는 요청에 /mcp/를 제공합니다.",+ enableDescription: "Unsloth API 키가 있는 요청에 /mcp/를 제공합니다.",lockedByEnv: "{name}(으)로 설정됨.",loadError: "에이전트 액세스 설정을 불러오지 못했습니다.",saveError: "에이전트 액세스 설정을 저장하지 못했습니다.",agent: "에이전트",- exportKeyHint: "에이전트를 시작하기 전에 {name}에 이 페이지의 액세스 토큰을 설정하세요.",+ exportKeyHint: "에이전트를 시작하기 전에 {name}에 이 페이지의 Unsloth API 키를 설정하세요.",configFileHint: "이 내용을 {path}에 추가하세요.",keywords: "mcp model context protocol agents claude codex tools 에이전트 도구 모델 컨텍스트 프로토콜",},diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex c8781c03fda..75614e1d0f6 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -3151,14 +3151,14 @@ export const ptBR = {},mcp: {title: "Acesso de agentes (MCP)",- description: "Permita que agentes de código como Claude Code e Codex usem o Unsloth via MCP. Os agentes entram com um token de acesso desta página.",+ description: "Permita que agentes de código como Claude Code e Codex usem o Unsloth via MCP. Os agentes entram com uma chave de API do Unsloth desta página.",enable: "Permitir conexões de agentes",- enableDescription: "Atende /mcp/ para solicitações que trazem um token de acesso do Unsloth.",+ enableDescription: "Atende /mcp/ para solicitações que trazem uma chave de API do Unsloth.",lockedByEnv: "Definido por {name}.",loadError: "Não foi possível carregar as configurações de acesso de agentes.",saveError: "Não foi possível salvar a configuração de acesso de agentes.",agent: "Agente",- exportKeyHint: "Defina {name} com um token de acesso desta página antes de iniciar o agente.",+ exportKeyHint: "Defina {name} com uma chave de API do Unsloth desta página antes de iniciar o agente.",configFileHint: "Adicione isto a {path}.",keywords: "mcp model context protocol agents claude codex tools agentes agente ferramentas protocolo de contexto de modelo",},diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 4d8de89e1df..1f2e30ff36b 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -3147,14 +3147,14 @@ export const ru = {},mcp: {title: "Доступ агентов (MCP)",- description: "Разрешите агентам для программирования, таким как Claude Code и Codex, работать с Unsloth через MCP. Агенты входят с токеном доступа с этой страницы.",+ description: "Разрешите агентам для программирования, таким как Claude Code и Codex, работать с Unsloth через MCP. Агенты входят с ключом API Unsloth с этой страницы.",enable: "Разрешить подключения агентов",- enableDescription: "Обслуживает /mcp/ для запросов с токеном доступа Unsloth.",+ enableDescription: "Обслуживает /mcp/ для запросов с ключом API Unsloth.",lockedByEnv: "Задано через {name}.",loadError: "Не удалось загрузить настройки доступа агентов.",saveError: "Не удалось сохранить настройку доступа агентов.",agent: "Агент",- exportKeyHint: "Перед запуском агента задайте в {name} токен доступа с этой страницы.",+ exportKeyHint: "Перед запуском агента задайте в {name} ключ API Unsloth с этой страницы.",configFileHint: "Добавьте это в {path}.",keywords: "mcp model context protocol agents claude codex tools агенты агент инструменты протокол контекста модели",},diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex f02f1b771b2..0d911c7523d 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -3360,14 +3360,14 @@ export const sv = {},mcp: {title: "Agentåtkomst (MCP)",- description: "Låt kodagenter som Claude Code och Codex använda Unsloth via MCP. Agenter loggar in med en åtkomsttoken från den här sidan.",+ description: "Låt kodagenter som Claude Code och Codex använda Unsloth via MCP. Agenter loggar in med en API-nyckel för Unsloth från den här sidan.",enable: "Tillåt agentanslutningar",- enableDescription: "Betjänar /mcp/ för förfrågningar som har en åtkomsttoken för Unsloth.",+ enableDescription: "Betjänar /mcp/ för förfrågningar som har en API-nyckel för Unsloth.",lockedByEnv: "Angiven av {name}.",loadError: "Det gick inte att läsa in inställningarna för agentåtkomst.",saveError: "Det gick inte att spara inställningen för agentåtkomst.",agent: "Agent",- exportKeyHint: "Sätt {name} till en åtkomsttoken från den här sidan innan du startar agenten.",+ exportKeyHint: "Sätt {name} till en API-nyckel för Unsloth från den här sidan innan du startar agenten.",configFileHint: "Lägg till det här i {path}.",keywords: "mcp model context protocol agents claude codex tools agenter agent verktyg modellkontextprotokoll",},diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex a7a141a65ee..e797c551979 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -3080,14 +3080,14 @@ export const zhCN = {},mcp: {title: "智能体访问 (MCP)",- description: "允许 Claude Code、Codex 等编程智能体通过 MCP 使用 Unsloth。智能体使用本页的访问 token 登录。",+ description: "允许 Claude Code、Codex 等编程智能体通过 MCP 使用 Unsloth。智能体使用本页的 Unsloth API 密钥登录。",enable: "允许智能体连接",- enableDescription: "为携带 Unsloth 访问 token 的请求提供 /mcp/。",+ enableDescription: "为携带 Unsloth API 密钥的请求提供 /mcp/。",lockedByEnv: "由 {name} 设置。",loadError: "无法加载智能体访问设置。",saveError: "无法保存智能体访问设置。",agent: "智能体",- exportKeyHint: "启动智能体前,请将 {name} 设置为本页的访问 token。",+ exportKeyHint: "启动智能体前,请将 {name} 设置为本页的 Unsloth API 密钥。",configFileHint: "将此内容添加到 {path}。",keywords: "mcp model context protocol agents claude codex tools 智能体 代理 工具 模型上下文协议",},diff --git a/studio/frontend/tests/mcp-access-section.test.ts b/studio/frontend/tests/mcp-access-section.test.tsindex b43e514cce4..d85346eaff3 100644--- a/studio/frontend/tests/mcp-access-section.test.ts+++ b/studio/frontend/tests/mcp-access-section.test.ts@@ -122,7 +122,7 @@ test("the setup snippet shows only while on, targets the usage examples' address);assert.equal(en.settings.apiKeys.mcp.exportKeyHint,- "Set {name} to an access token from this page before you start the agent.",+ "Set {name} to an Unsloth API key from this page before you start the agent.",);});