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
Reduce comment volume across the studio frontend and backend routes (#10503)
Daniel Han8e312991792f
diff --git a/studio/backend/_platform_compat.py b/studio/backend/_platform_compat.pyindex 95f6cacce34..0cc6adf510e 100644--- a/studio/backend/_platform_compat.py+++ b/studio/backend/_platform_compat.py@@ -1,20 +1,8 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Compatibility shim for Anaconda/conda-forge Python builds.--Anaconda puts distributor metadata between pipes in sys.version, e.g.-'3.12.4 | packaged by Anaconda, Inc. | (main, ...) [MSC ...]'. The regex in-platform._sys_version() can't parse this and raises ValueError (cpython#102396,-closed as "not planned").--We seed platform._sys_version_cache so the stdlib parser never sees the bad-string, fixing the import chain:- structlog -> rich.pretty -> attrs._compat -> platform.python_implementation()--Import before any library that may trigger that chain. Idempotent.-"""+"""Import before structlog/rich: Anaconda's ``|...|`` metadata in sys.version makes+platform._sys_version() raise (cpython#102396, wontfix), so seed its cache first."""import platformimport re@@ -22,17 +10,14 @@ import sysdef _seed_sys_version_cache() -> None:- """Parse a cleaned sys.version and seed the cache once."""raw = sys.version- # Strip paired |...| segments (Anaconda, conda-forge metadata)cleaned = re.sub(r"\s*\|[^|]*\|\s*", " ", raw).strip()# Pipe-strip can leave two consecutive (...) groups; drop the second.cleaned = re.sub(r"(\([^)]*\))\s+\([^)]*\)", r"\1", cleaned)if "|" in cleaned:- # Unpaired pipe left: keep version + everything from "(" onwardm = re.match(r"([\w.+]+)\s*", cleaned)p = cleaned.find("(")if m and p > 0:@@ -46,7 +31,6 @@ def _seed_sys_version_cache() -> None:except ValueError:return- # Seed the cache so future calls with the raw string skip parsingcache = getattr(platform, "_sys_version_cache", None)if isinstance(cache, dict):cache[raw] = resultdiff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.pyindex 8a4f13923bd..65d1b275ebf 100644--- a/studio/backend/auth/authentication.py+++ b/studio/backend/auth/authentication.py@@ -45,13 +45,11 @@ def is_keyless(credentials: Optional[HTTPAuthorizationCredentials]) -> bool:def _names_a_session(token: str) -> bool:- """Whether this bearer claims an Unsloth sign-in this install actually knows.-- A session token stays authoritative even under keyless API access: letting an- expired one through would leave the app running as the admin instead of prompting- for a sign-in. The subject is confirmed against storage because the claim itself is- unverified here, so a token merely shaped like a JWT -- which is a legal value for- the ``api_key`` the OpenAI SDKs always send -- is treated as the credential it is.+ """Whether this bearer claims an Unsloth sign-in this install actually knows. A session token stays+ authoritative even under keyless API access: letting an expired one through would leave the app running as+ the admin instead of prompting for a sign-in. The subject is confirmed against storage because the claim+ itself is unverified here, so a token merely shaped like a JWT -- which is a legal value for the ``api_key``+ the OpenAI SDKs always send -- is treated as the credential it is."""subject = _decode_subject_without_verification(token)return subject is not None and get_user_and_secret(subject) is not None@@ -63,11 +61,9 @@ def bearer_names_a_session(token: str) -> bool:def bearer_is_valid_api_key(token: str) -> bool:- """Whether this bearer is an sk-unsloth key this install still accepts.-- Such a key authenticates as itself even while keyless API access is on, so the- callers below must not treat it as a credential the setting had to stand in for.- Asked ahead of the real validation, so it leaves ``last_used_at`` to that one.+ """Whether this bearer is an sk-unsloth key this install still accepts. Such a key authenticates as itself+ even while keyless API access is on, so the callers below must not treat it as a credential the setting had+ to stand in for. Asked ahead of the real validation, so it leaves ``last_used_at`` to that one."""return (token.startswith(API_KEY_PREFIX)@@ -76,11 +72,9 @@ def bearer_is_valid_api_key(token: str) -> bool:def admitted_without_credential(credentials: Optional[HTTPAuthorizationCredentials]) -> bool:- """True when the keyless setting alone let this caller in.-- Narrower than ``is_keyless``, which also covers a working API key that happened- to arrive while the setting was on. Routes whose effect outlives the setting need- this stricter form: turning keyless access back off has to undo what it allowed.+ """True when the keyless setting alone let this caller in. Narrower than ``is_keyless``, which also covers a+ working API key that happened to arrive while the setting was on. Routes whose effect outlives the setting+ need this stricter form: turning keyless access back off has to undo what it allowed."""if credentials is None:return False@@ -119,11 +113,8 @@ def _request_would_use_keyless(request: Any) -> bool:def request_admitted_without_credential(request: Request) -> bool:- """``admitted_without_credential`` for a caller that holds only the request.-- Costs a key validation, so ask it late: past the cheap disqualifiers, next to the- effect being guarded.- """+ """``admitted_without_credential`` for a caller that holds only the request. Costs a key+ validation, so ask it late: past the cheap disqualifiers, next to the effect being guarded."""from utils.keyless_api_access import request_was_admitted_keylessrecorded = request_was_admitted_keyless(request)@@ -131,11 +122,9 @@ def request_admitted_without_credential(request: Request) -> bool:def admitted_without_session(request: Any) -> bool:- """True when keyless API access lets this request through with no Unsloth sign-in.-- The single predicate behind both the auth dependency below and the route-level- checks that ask whether a caller is the Unsloth UI or a programmatic client.- """+ """True when keyless API access lets this request through with no Unsloth sign-in. The single+ predicate behind both the auth dependency below and the route-level checks that ask whether a+ caller is the Unsloth UI or a programmatic client."""from utils.keyless_api_access import request_was_admitted_keylessrecorded = request_was_admitted_keyless(request)@@ -143,9 +132,8 @@ def admitted_without_session(request: Any) -> bool:class _BearerOrKeyless(HTTPBearer):- """Read ``Authorization: Bearer <token>``, admitting a caller without one.-- When the setting is off this behaves exactly like ``HTTPBearer``, errors included.+ """Read ``Authorization: Bearer <token>``, admitting a caller without one. When the setting is off this+ behaves exactly like ``HTTPBearer``, errors included."""async def __call__(self, request: Request) -> Optional[HTTPAuthorizationCredentials]:@@ -227,13 +215,9 @@ def create_access_token(desktop: bool = False,secret: Optional[str] = None,) -> str:- """- Create a signed JWT for the given subject (e.g. username).-- Valid across restarts: the signing secret is stored in SQLite. Callers that- already verified a credential pass ``secret`` so a rotation landing mid-request- cannot sign the token with the credential that just replaced it.- """+ """Create a signed JWT for the given subject (e.g. username). Valid across restarts: the signing+ secret is stored in SQLite. Callers that already verified a credential pass ``secret`` so a+ rotation landing mid-request cannot sign the token with the credential that just replaced it."""to_encode = {"sub": subject}if desktop:to_encode["desktop"] = True@@ -276,12 +260,9 @@ def create_refresh_token(desktop: bool = False,secret: Optional[str] = None,) -> str:- """- Create a random refresh token, store its hash in SQLite, and return it.-- Refresh tokens are opaque (not JWTs); expire after REFRESH_TOKEN_EXPIRE_DAYS.- ``secret`` stamps the token with the credential version the caller verified,- so a rotation cannot leave a token minted from the replaced credential valid.+ """Create a random refresh token, store its hash in SQLite, and return it. Refresh tokens are opaque (not+ JWTs); expire after REFRESH_TOKEN_EXPIRE_DAYS. ``secret`` stamps the token with the credential version the+ caller verified, so a rotation cannot leave a token minted from the replaced credential valid."""token = secrets.token_urlsafe(48)expires_at = datetime.now(timezone.utc) + timedelta(days = REFRESH_TOKEN_EXPIRE_DAYS)@@ -296,11 +277,8 @@ def create_refresh_token(def refresh_access_token(refresh_token: str) -> Tuple[Optional[str], Optional[str], bool]:- """- Validate a refresh token and issue a new access token.-- The refresh token is NOT consumed; it stays valid until expiry.- Returns a new access_token, or None if the refresh token is invalid/expired.+ """Validate a refresh token and issue a new access token. The refresh token is NOT consumed; it stays valid+ until expiry. Returns a new access_token, or None if the refresh token is invalid/expired."""verified = verify_refresh_token(refresh_token)if verified is None:@@ -314,11 +292,8 @@ def refresh_access_token(refresh_token: str) -> Tuple[Optional[str], Optional[stdef reload_secret() -> None:- """- Legacy API compat for callers expecting auth storage init.-- Auth now resolves the current signing secret directly from SQLite.- """+ """Legacy API compat for callers expecting auth storage init. Auth now resolves the current signing+ secret directly from SQLite."""load_jwt_secret()@@ -334,11 +309,8 @@ async def get_current_subject(credentials: HTTPAuthorizationCredentials = Dependasync def get_current_credential(credentials: HTTPAuthorizationCredentials = Depends(security),) -> Tuple[str, Optional[str]]:- """As get_current_subject, but also returns the credential generation.-- For routes that persist a new credential and must not do so on behalf of one- a concurrent reset has revoked.- """+ """As get_current_subject, but also returns the credential generation, for routes that persist a+ new credential and must not do so on behalf of one a concurrent reset has revoked."""return await _get_current_credential(credentials,allow_password_change = False,@@ -348,13 +320,10 @@ async def get_current_credential(async def authenticated_via_api_key(credentials: HTTPAuthorizationCredentials = Depends(security),) -> bool:- """True when the caller used an sk-unsloth API key, not a UI session JWT.-- Lets routes treat programmatic API callers differently from the Unsloth UI- (e.g. refuse a teardown the UI would allow). A keyless caller counts as an API- caller too: it is the same programmatic surface, only without the key, so every- guard an API key faces still applies to it.- """+ """True when the caller used an sk-unsloth API key, not a UI session JWT. Lets routes treat+ programmatic API callers differently from the Unsloth UI (e.g. refuse a teardown the UI would+ allow). A keyless caller counts as an API caller too: it is the same programmatic surface, only+ without the key, so every guard an API key faces still applies to it."""if is_keyless(credentials):return Truereturn bool(credentials and credentials.credentials.startswith(API_KEY_PREFIX))@@ -363,13 +332,10 @@ async def authenticated_via_api_key(async def credentials_for_token(request: Any, token: Optional[str]) -> Optional[HTTPAuthorizationCredentials]:- """What ``security`` would resolve for a bearer the route read for itself.-- Routes that take the token from somewhere the dependency cannot see, such as the- ``?token=`` query param an ``<img src>`` has to use, would otherwise miss keyless- API access entirely and answer 401 on a scope that covers them. None means no- usable credential and no setting to stand in for one.- """+ """What ``security`` would resolve for a bearer the route read for itself. Routes that take the+ token from somewhere the dependency cannot see, such as the ``?token=`` query param an ``<img+ src>`` has to use, would otherwise miss keyless API access entirely and answer 401 on a scope+ that covers them. None means no usable credential and no setting to stand in for one."""from utils.keyless_api_access import APPROVED_DUMMY_BEARERS, keyless_request_allowed# /api/health slices the bearer out itself, so a blank one arrives as "", not as None.@@ -396,11 +362,9 @@ async def authenticated_without_credential(def require_ui_session_for_local_commands(via_api_key: bool) -> None:- """Refuse an sk-unsloth API key that asks to define a local (stdio) MCP command.-- stdio MCP runs a command on this host as the backend user, outside the- python/terminal sandbox, so only a UI session may choose what runs. API keys- keep http(s) MCP, and stdio servers the owner already configured.+ """Refuse an sk-unsloth API key that asks to define a local (stdio) MCP command. stdio MCP runs a command on+ this host as the backend user, outside the python/terminal sandbox, so only a UI session may choose what+ runs. API keys keep http(s) MCP, and stdio servers the owner already configured."""if via_api_key:raise HTTPException(@@ -411,12 +375,10 @@ def require_ui_session_for_local_commands(via_api_key: bool) -> None:async def allow_ambient_hf_token(via_api_key: bool = Depends(authenticated_via_api_key)) -> bool:- """Whether a download this caller starts may fall back to the backend's own HF_TOKEN.-- A UI session already gets the saved token from Settings, so the ambient one grants it- nothing new. ``require_ui_session`` refuses an sk-unsloth API key that same token, so it- must not reach private repos by naming one in a download instead; it sends its own token- in ``X-Unsloth-HF-Token``.+ """Whether a download this caller starts may fall back to the backend's own HF_TOKEN. A UI session already+ gets the saved token from Settings, so the ambient one grants it nothing new. ``require_ui_session`` refuses+ an sk-unsloth API key that same token, so it must not reach private repos by naming one in a download+ instead; it sends its own token in ``X-Unsloth-HF-Token``."""return not via_api_key@@ -424,10 +386,8 @@ async def allow_ambient_hf_token(via_api_key: bool = Depends(authenticated_via_aasync def authenticated_via_desktop_jwt(credentials: HTTPAuthorizationCredentials = Depends(security),) -> bool:- """True when the caller is the local desktop app, not a browser session or API key.-- Lets routes treat the desktop as an authority of its own: it authenticates- with a local secret rather than the account password.+ """True when the caller is the local desktop app, not a browser session or API key. Lets routes treat the+ desktop as an authority of its own: it authenticates with a local secret rather than the account password."""return await run_in_threadpool(is_desktop_access_token, credentials.credentials)@@ -473,14 +433,10 @@ def _admin_credential() -> Tuple[str, Optional[str]]:async def _get_current_credential(credentials: HTTPAuthorizationCredentials, *, allow_password_change: bool) -> Tuple[str, Optional[str]]:- """Validate the bearer and return ``(subject, credential generation)``.-- The generation is the credential version this request actually authenticated- against. Routes that persist new credentials must bind their write to it, or- a reset landing mid-request would bless what it just revoked.-- Credential reads run in the threadpool so stalled SQLite cannot block the event loop.- """+ """Validate the bearer and return ``(subject, credential generation)``. The generation is the+ credential version this request actually authenticated against; routes that persist new+ credentials must bind their write to it, or a reset landing mid-request would bless what it just+ revoked. Credential reads run in the threadpool so stalled SQLite cannot block the event loop."""if credentials.scheme == KEYLESS_SCHEME:return await run_in_threadpool(_admin_credential)diff --git a/studio/backend/auth/bootstrap_timeout.py b/studio/backend/auth/bootstrap_timeout.pyindex 57e24101538..5b6ee49e503 100644--- a/studio/backend/auth/bootstrap_timeout.py+++ b/studio/backend/auth/bootstrap_timeout.py@@ -3,16 +3,14 @@"""Auto-shutdown for an exposed first-run Unsloth whose admin password is unchanged.-On a fresh install the seeded bootstrap admin password stays a valid login-credential until first login changes it. When the web UI is put on the network-(``--secure`` / ``0.0.0.0``) and nobody completes that first-login change within-a deadline, tear Unsloth down so a fresh, unconfigured instance does not stay-publicly reachable indefinitely. If the password was changed, Unsloth keeps-running.--Scope: web UI launches only (never ``--api-only``, which authenticates by API-key rather than the admin password, and never Colab). Configurable via-``UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT`` (seconds; default 3600; ``0`` disables).+On a fresh install the seeded bootstrap admin password stays a valid login credential until first login changes+it. When the web UI is put on the network (``--secure`` / ``0.0.0.0``) and nobody completes that first-login+change within a deadline, tear Unsloth down so a fresh, unconfigured instance does not stay publicly reachable+indefinitely. If the password was changed, Unsloth keeps running.++Scope: web UI launches only (never ``--api-only``, which authenticates by API key rather than the admin+password, and never Colab). Configurable via ``UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT`` (seconds; default 3600; ``0``+disables)."""import os@@ -48,10 +46,8 @@ def bootstrap_deadline_remaining_seconds() -> Optional[int]:def bootstrap_timeout_seconds(env = None) -> int:- """Resolve the deadline in seconds. ``0`` (or invalid/negative) disables it.-- A malformed value falls back to the default rather than disabling, so a typo- cannot silently remove the protection.+ """Resolve the deadline in seconds. ``0`` (or invalid/negative) disables it. A malformed value falls back to+ the default rather than disabling, so a typo cannot silently remove the protection."""env = os.environ if env is None else envraw = env.get(BOOTSTRAP_TIMEOUT_ENV_VAR)@@ -120,11 +116,8 @@ def enforce_bootstrap_password_deadline(timeout_seconds: int,logger = None,) -> bool:- """Deadline handler: shut down iff the seeded admin password is still unchanged.-- Returns True if it shut Unsloth down, False if it left it running (the- password was changed in time).- """+ """Deadline handler: shut down iff the seeded admin password is still unchanged. Returns True if it+ shut Unsloth down, False if it left it running (the password was changed in time)."""try:still_default = storage.requires_password_change(storage.DEFAULT_ADMIN_USERNAME)except Exception:diff --git a/studio/backend/auth/hashing.py b/studio/backend/auth/hashing.pyindex 0a1b0c15beb..4d97b835fe6 100644--- a/studio/backend/auth/hashing.py+++ b/studio/backend/auth/hashing.py@@ -1,9 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Password hashing utilities using PBKDF2.-"""+"""Password hashing utilities using PBKDF2."""import hashlibimport hmac@@ -12,11 +10,7 @@ from typing import Tupledef hash_password(password: str, salt: str | None = None) -> Tuple[str, str]:- """- Hash a password using PBKDF2-HMAC-SHA256.-- Returns (salt, hex_hash) tuple.- """+ """Hash a password using PBKDF2-HMAC-SHA256. Returns (salt, hex_hash) tuple."""if salt is None:salt = secrets.token_hex(16)dk = hashlib.pbkdf2_hmac(@@ -29,11 +23,7 @@ def hash_password(password: str, salt: str | None = None) -> Tuple[str, str]:def verify_password(password: str, salt: str, hashed: str) -> bool:- """- Verify a password against a stored salt and hash.-- Uses constant-time comparison to prevent timing attacks.- """+ """Verify a password against a stored salt and hash, in constant time to prevent timing attacks."""dk = hashlib.pbkdf2_hmac("sha256",password.encode("utf-8"),diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.pyindex fb10ecba168..5958c826b5f 100644--- a/studio/backend/auth/storage.py+++ b/studio/backend/auth/storage.py@@ -33,19 +33,14 @@ _bootstrap_password: Optional[str] = Nonedef _bootstrap_file_bytes(password: str) -> bytes:- """Exact on-disk form: the secret plus one LF.-- Bytes, not text: text mode writes CRLF on Windows, and `$(cat ...)` strips- the LF but leaves the CR attached to the credential.- """+ """Exact on-disk form: the secret plus one LF. Bytes, not text: text mode writes CRLF on Windows,+ and `$(cat ...)` strips the LF but leaves the CR attached to the credential."""return (password + "\n").encode("utf-8")def _persist_bootstrap_password(password: str) -> None:- """Atomically write the bootstrap password 0600, LF terminated on every OS.-- A partial write would destroy the only plaintext recovery credential.- """+ """Atomically write the bootstrap password 0600, LF terminated on every OS: a partial write would+ destroy the only plaintext recovery credential."""fd, tmp_name = tempfile.mkstemp(prefix = f".{_BOOTSTRAP_PW_PATH.name}.", dir = _BOOTSTRAP_PW_PATH.parent)@@ -66,17 +61,12 @@ def _persist_bootstrap_password(password: str) -> None:def _normalise_bootstrap_file(raw: bytes, password: str) -> None:- """Append the LF a pre-newline release left off.-- Append-only, and only when the file is exactly the credential:- clear_bootstrap_password() may unlink or (when unlink fails, notably on- Windows while this descriptor is open) truncate through another descriptor- after we read, so a rewrite could restore revoked plaintext. An append- cannot: worst case is a lone "\\n" over a cleared file, which strips back to- no bootstrap password. Pre-newline releases wrote no terminator at all, so- that is the only shape in the wild; anything else reads fine, since every- reader strips, and is left alone.- """+ """Append the LF a pre-newline release left off. Append-only, and only when the file is exactly the+ credential: clear_bootstrap_password() may unlink or (when unlink fails, notably on Windows+ while this descriptor is open) truncate through another descriptor after we read, so a rewrite+ could restore revoked plaintext. An append cannot: worst case is a lone terminator over a+ cleared file, which strips back to no bootstrap password. Pre-newline releases wrote no+ terminator at all, so that is the only shape in the wild."""if raw != password.encode("utf-8"):return@@ -120,24 +110,18 @@ def _read_persisted_bootstrap_password() -> Optional[str]:def generate_bootstrap_password() -> str:- """Generate a 4-word diceware passphrase and persist it to disk.-- Persisted (the DB stores only the hash) so it survives restarts; later- calls return the persisted value.- """+ """Generate a 4-word diceware passphrase and persist it to disk. Persisted (the DB stores only the+ hash) so it survives restarts; later calls return it."""global _bootstrap_password- # Cached in this process?if _bootstrap_password is not None:return _bootstrap_password- # Persisted from a previous run?persisted = _read_persisted_bootstrap_password()if persisted:_bootstrap_password = persistedreturn _bootstrap_password- # First startup: generate a fresh passphrase.import diceware_bootstrap_password = diceware.get_passphrase(@@ -152,28 +136,21 @@ def generate_bootstrap_password() -> str:def get_bootstrap_password() -> Optional[str]:- """Return the cached bootstrap password, or None if not yet generated."""return _bootstrap_passworddef _load_bootstrap_password() -> Optional[str]:- """Load an existing bootstrap password without creating one.-- Upgrades take this path, not generate_bootstrap_password()- (ensure_default_admin short-circuits once the admin row exists), so it has- to normalise too.- """+ """Load an existing bootstrap password without creating one. Upgrades take this path, not+ generate_bootstrap_password() (ensure_default_admin short-circuits once the admin row exists),+ so it has to normalise too."""global _bootstrap_password_bootstrap_password = _read_persisted_bootstrap_password()return _bootstrap_passworddef clear_bootstrap_password() -> None:- """Delete the persisted bootstrap password file (after a password change).-- Best-effort: the new hash is already committed, so a locked/undeletable file- (Windows AV, read-only auth dir) must not fail the change.- """+ """Delete the persisted bootstrap password file (after a password change). Best-effort: the new+ hash is already committed, so a locked or undeletable file must not fail the change."""global _bootstrap_password_bootstrap_password = Noneif _BOOTSTRAP_PW_PATH.is_file():@@ -204,13 +181,10 @@ def clear_bootstrap_password() -> None:def _hash_token(token: str) -> str:- """SHA-256 hash helper for refresh token storage.-- Plain SHA-256 is intentional: refresh tokens are 384-bit random strings, so- a slow KDF adds no security while costing per-refresh latency. API keys use- the separate ``_pbkdf2_api_key`` helper, only to satisfy CodeQL's- ``py/weak-sensitive-data-hashing`` query, not for crypto reasons.- """+ """SHA-256 hash helper for refresh token storage. Plain SHA-256 is intentional: refresh tokens are+ 384-bit random strings, so a slow KDF adds no security while costing per-refresh latency. API+ keys use the separate ``_pbkdf2_api_key`` helper, only to satisfy CodeQL's+ ``py/weak-sensitive-data-hashing`` query."""return hashlib.sha256(token.encode("utf-8")).hexdigest()@@ -219,11 +193,9 @@ class CredentialRotated(Exception):def credential_generation(jwt_secret: str) -> str:- """Marker for the credential version a refresh token was issued under.-- Every password change rotates ``jwt_secret``, so a token stamped with the- previous one is rejected even if it was inserted after the revoking DELETE.- """+ """Marker for the credential version a refresh token was issued under. Every password change+ rotates ``jwt_secret``, so a token stamped with the previous one is rejected even if it was+ inserted after the revoking DELETE."""return hashlib.sha256(jwt_secret.encode("utf-8")).hexdigest()@@ -260,7 +232,6 @@ def credential_generation_guard(username: str, expect_gen: Optional[str]) -> Itedef get_connection() -> sqlite3.Connection:- """Get a connection to the auth database, creating tables if needed."""ensure_dir(DB_PATH.parent)conn = sqlite3.connect(DB_PATH)# sqlite3.connect would create the DB 0644 under a 022 umask, exposing identity secrets and password hashes.@@ -348,11 +319,8 @@ _api_key_pbkdf2_salt_cache: Optional[bytes] = Nonedef _get_or_create_api_key_pbkdf2_salt() -> bytes:- """Return the persistent API-key PBKDF2 salt, generating it once if missing.-- Hex-encoded 32-byte random value in ``app_secrets``. Regenerated only when- the row is missing (fresh install, or operator deleted it).- """+ """Return the persistent API-key PBKDF2 salt, generating it once if missing. Hex-encoded 32-byte+ random value in ``app_secrets``, regenerated only when the row is missing."""global _api_key_pbkdf2_salt_cacheif _api_key_pbkdf2_salt_cache is not None:return _api_key_pbkdf2_salt_cache@@ -458,11 +426,10 @@ def get_or_create_credential_encryption_key() -> bytes:def compute_identity_proof(nonce: bytes, host: str, port: int) -> str:- """HMAC-SHA256 proof that the caller holds this install's identity secret,- bound to the loopback address and port the connection landed on. A proof- relayed from an Unsloth on a different address/port (a squatter proxying to the- real one, e.g. localhost resolving to ::1 while Unsloth is on 127.0.0.1) was- computed for that other endpoint and won't match the one the client dialed."""+ """HMAC-SHA256 proof that the caller holds this install's identity secret, bound to the loopback+ address and port the connection landed on. A proof relayed from an Unsloth on a different+ address or port was computed for that other endpoint and will not match the one the client+ dialed."""try:host = ipaddress.ip_address(host).compressedexcept ValueError:@@ -532,13 +499,10 @@ _DESKTOP_SECRET_CREATED_AT_KEY = "desktop_secret_created_at"def _pbkdf2_api_key(raw_key: str) -> str:- """PBKDF2-HMAC-SHA256 an API key with a persistent server-side salt.-- For API-key storage ONLY, not refresh tokens. The slow KDF is only to- appease CodeQL's ``py/weak-sensitive-data-hashing`` query, not a crypto- requirement (API keys are random 128-bit tokens). The salt lives in- ``app_secrets`` so dumping ``api_keys`` alone can't derive hashes.- """+ """PBKDF2-HMAC-SHA256 an API key with a persistent server-side salt. For API-key storage ONLY, not+ refresh tokens: the slow KDF is only to appease CodeQL's ``py/weak-sensitive-data-hashing``+ query, since API keys are random 128-bit tokens. The salt lives in ``app_secrets`` so dumping+ ``api_keys`` alone cannot derive hashes."""salt = _get_or_create_api_key_pbkdf2_salt()dk = hashlib.pbkdf2_hmac("sha256",@@ -570,14 +534,12 @@ def _api_key_cache_id(raw_key: str) -> str:def _reset_api_key_hash_cache() -> None:- """Drop memoized derivations (tests / salt change)."""with _api_key_hash_cache_lock:_api_key_hash_cache.clear()_api_key_internal_cache.clear()def is_initialized() -> bool:- """Check if auth is ready for login (at least one user exists in DB)."""conn = get_connection()cur = conn.execute("SELECT COUNT(*) AS c FROM auth_user")row = cur.fetchone()@@ -592,11 +554,8 @@ def create_initial_user(*,must_change_password: bool = False,) -> None:- """- Create the initial admin user in the database.-- Raises sqlite3.IntegrityError if username already exists.- """+ """Create the initial admin user in the database. Raises sqlite3.IntegrityError if username already+ exists."""from .hashing import hash_passwordsalt, pwd_hash = hash_password(password)@@ -621,11 +580,8 @@ def create_initial_user(def delete_user(username: str) -> None:- """- Delete a user from the database.-- Used for rollback when user creation fails partway through bootstrap.- """+ """Delete a user from the database, for rollback when user creation fails partway through+ bootstrap."""conn = get_connection()try:conn.execute("DELETE FROM auth_user WHERE username = ?", (username,))@@ -635,12 +591,8 @@ def delete_user(username: str) -> None:def get_user_and_secret(username: str) -> Optional[Tuple[str, str, str, bool]]:- """- Get user's password salt, hash, and JWT secret.-- Returns (password_salt, password_hash, jwt_secret, must_change_password)- or None if user not found.- """+ """Get user's password salt, hash, and JWT secret. Returns (password_salt, password_hash,+ jwt_secret, must_change_password) or None."""conn = get_connection()try:cur = conn.execute(@@ -665,7 +617,6 @@ def get_user_and_secret(username: str) -> Optional[Tuple[str, str, str, bool]]:def get_jwt_secret(username: str) -> Optional[str]:- """Return the current JWT signing secret for a user."""conn = get_connection()try:cur = conn.execute(@@ -679,7 +630,6 @@ def get_jwt_secret(username: str) -> Optional[str]:def requires_password_change(username: str) -> bool:- """Return whether the user must change the seeded default password."""conn = get_connection()try:cur = conn.execute(@@ -693,11 +643,7 @@ def requires_password_change(username: str) -> bool:def load_jwt_secret() -> str:- """- Load the JWT secret from the database.-- Raises RuntimeError if no auth user has been created yet.- """+ """Load the JWT secret from the database. Raises RuntimeError if no auth user has been created yet."""conn = get_connection()try:cur = conn.execute("SELECT jwt_secret FROM auth_user LIMIT 1")@@ -712,11 +658,8 @@ def load_jwt_secret() -> str:def ensure_default_admin() -> bool:- """Seed the default admin account on first startup.-- Uses a randomly generated diceware passphrase as the bootstrap password.- Returns True when the default admin was created in this call.- """+ """Seed the default admin account on first startup, using a randomly generated diceware passphrase+ as the bootstrap password. Returns True when it was created in this call."""if get_user_and_secret(DEFAULT_ADMIN_USERNAME) is not None:_load_bootstrap_password()return False@@ -742,26 +685,15 @@ def update_password(expect_password_hash: Optional[str] = None,preserve_desktop_secret: bool = False,) -> Optional[str]:- """Update password, clear first-login requirement, rotate JWT secret.-- Returns the new JWT secret, or None when nothing was updated. Callers that- mint tokens for the caller must sign with the returned secret: re-reading it- would pick up a reset that landed between this commit and the mint.-- ``revoke_refresh_tokens`` deletes the user's refresh tokens in the SAME- transaction: a separate delete could fail after the password commit and- leave a pre-change token still able to mint access tokens.-- ``expect_password_hash`` makes the write conditional on the credential the- caller verified still being current, so a request that checked the old- password cannot overwrite a reset that landed while it was in flight.- Returns False when the credential moved underneath it.-- ``preserve_desktop_secret`` keeps the local desktop credential valid. It is- for a caller that already authenticated as the desktop app: revoking the- secret it is currently using would break desktop auto-auth for a change the- desktop itself made.- """+ """Update password, clear first-login requirement, rotate JWT secret. Returns the new JWT secret,+ or None when nothing was updated. Callers that mint tokens must sign with the returned secret:+ re-reading it would pick up a reset that landed between this commit and the mint.+ ``revoke_refresh_tokens`` deletes the user's refresh tokens in the SAME transaction, since a+ separate delete could fail after the password commit and leave a pre-change token able to mint+ access tokens. ``expect_password_hash`` makes the write conditional on the credential the caller+ verified still being current, returning False when it moved underneath.+ ``preserve_desktop_secret`` keeps the local desktop credential valid, for a caller that already+ authenticated as the desktop app and would otherwise break its own auto-auth."""from .hashing import hash_passwordsalt, pwd_hash = hash_password(new_password)@@ -807,13 +739,9 @@ def save_refresh_token(is_desktop: bool = False,secret_gen: Optional[str] = None,) -> None:- """- Store a hashed refresh token with its associated username and expiry.-- ``secret_gen`` binds the token to a credential version; it defaults to the- current one, and callers that already verified a credential must pass the- version they verified rather than let this re-read a rotated one.- """+ """Store a hashed refresh token with its associated username and expiry. ``secret_gen`` binds the+ token to a credential version; it defaults to the current one, and callers that already verified+ a credential must pass the version they verified."""token_hash = _hash_token(token)conn = get_connection()try:@@ -832,14 +760,11 @@ def save_refresh_token(def consume_refresh_token(token: str) -> Optional[Tuple[str, bool, str]]:- """Atomically validate-and-delete a refresh token for single-use rotation.-- DELETE RETURNING fuses validate and delete into one statement so two- concurrent refresh requests cannot both consume the same token. Returns- ``(username, is_desktop, jwt_secret)``; the caller must mint the replacement- tokens against that secret so a rotation landing mid-refresh cannot issue a- post-rotation session from a pre-rotation token.- """+ """Atomically validate-and-delete a refresh token for single-use rotation. DELETE RETURNING fuses+ validate and delete into one statement so two concurrent refresh requests cannot both consume+ the same token. Returns ``(username, is_desktop, jwt_secret)``; the caller must mint the+ replacement tokens against that secret so a rotation landing mid-refresh cannot issue a+ post-rotation session from a pre-rotation token."""token_hash = _hash_token(token)now = datetime.now(timezone.utc).isoformat()conn = get_connection()@@ -875,12 +800,8 @@ def consume_refresh_token(token: str) -> Optional[Tuple[str, bool, str]]:def verify_refresh_token(token: str) -> Optional[Tuple[str, bool]]:- """- Verify a refresh token and return the username plus desktop marker.-- Returns the username and desktop marker if valid and not expired, None otherwise.- The token is NOT consumed — it stays valid until it expires.- """+ """Verify a refresh token and return the username plus desktop marker, or None when invalid or+ expired. The token is NOT consumed: it stays valid until it expires."""token_hash = _hash_token(token)conn = get_connection()try:@@ -920,7 +841,6 @@ def verify_refresh_token(token: str) -> Optional[Tuple[str, bool]]:def revoke_user_refresh_tokens(username: str) -> None:- """Revoke all refresh tokens for a user (e.g. on logout)."""conn = get_connection()try:conn.execute("DELETE FROM refresh_tokens WHERE username = ?", (username,))@@ -952,12 +872,10 @@ def create_desktop_secret() -> str:def validate_desktop_secret_with_credential(raw_secret: str) -> Optional[Tuple[str, str]]:- """Validate the desktop secret and return ``(username, jwt_secret)``.-- Both reads share one transaction so the returned secret is the credential- version the desktop secret was checked against; a reset landing mid-request- then invalidates the tokens minted from it rather than blessing them.- """+ """Validate the desktop secret and return ``(username, jwt_secret)``. Both reads share one+ transaction so the returned secret is the credential version the desktop secret was checked+ against; a reset landing mid-request then invalidates the tokens minted from it rather than+ blessing them."""if not raw_secret.startswith(DESKTOP_SECRET_PREFIX):return None@@ -981,13 +899,11 @@ def validate_desktop_secret_with_credential(raw_secret: str) -> Optional[Tuple[sdef validate_desktop_secret(raw_secret: str) -> Optional[str]:- """Return the real admin username when the desktop secret matches."""verified = validate_desktop_secret_with_credential(raw_secret)return verified[0] if verified else Nonedef clear_desktop_secret() -> None:- """Remove backend-side desktop auth state."""conn = get_connection()try:conn.execute(@@ -999,8 +915,6 @@ def clear_desktop_secret() -> None:conn.close()-# ----------------------------------------------------------------------------API_KEY_PREFIX = "sk-unsloth-"# The name is the only thing distinguishing internal keys by authority: Deep Research keys must@@ -1015,18 +929,12 @@ def create_api_key(internal: bool = False,expect_gen: Optional[str] = None,) -> Tuple[str, dict]:- """Create a new API key for *username*.-- Returns ``(raw_key, row_dict)`` where *raw_key* is shown to the user- exactly once. The database only stores the PBKDF2 hash.-- Pass ``internal=True`` for keys minted by workflows (e.g. data-recipe- runs) that should not appear in user-facing key listings.-- ``expect_gen`` ties the insert to the credential generation the request- authenticated under, so a session revoked by a concurrent password reset- cannot mint a key that outlives it. Raises ``CredentialRotated`` if it moved.- """+ """Create a new API key for *username*. Returns ``(raw_key, row_dict)`` where *raw_key* is shown to+ the user exactly once; the database only stores the PBKDF2 hash. Pass ``internal=True`` for keys+ minted by workflows that should not appear in user-facing listings. ``expect_gen`` ties the+ insert to the credential generation the request authenticated under, so a session revoked by a+ concurrent password reset cannot mint a key that outlives it. Raises ``CredentialRotated`` if it+ moved."""raw_key = API_KEY_PREFIX + secrets.token_hex(16)key_hash = _pbkdf2_api_key(raw_key)key_prefix = raw_key[len(API_KEY_PREFIX) : len(API_KEY_PREFIX) + 8]@@ -1110,11 +1018,8 @@ def revoke_api_key(username: str, key_id: int) -> bool:def revoke_internal_api_key(key_id: int) -> bool:- """Revoke an internal workflow-minted key without requiring a username.-- Used by the recipe runner to retire its sk-unsloth-* key once the job- terminates, shrinking the window a leaked key could be abused.- """+ """Revoke an internal workflow-minted key without requiring a username. Used by the recipe runner+ to retire its key once the job terminates, shrinking the window a leaked key could be abused."""conn = get_connection()try:cursor = conn.execute(@@ -1128,12 +1033,10 @@ def revoke_internal_api_key(key_id: int) -> bool:def is_internal_api_key(raw_key: str) -> bool:- """Whether *raw_key* is a workflow-minted internal key rather than a user's own.-- Lets request-scoped code (the API monitor) tell Unsloth's own background work from a- third party using Unsloth as an API server. The answer is memoized because this runs on- the event loop for every API-key request and a key's origin is fixed when it is minted.- """+ """Whether *raw_key* is a workflow-minted internal key rather than a user's own. Lets+ request-scoped code tell Unsloth's own background work from a third party using Unsloth as an+ API server. Memoized, because this runs on the event loop for every API-key request and a key's+ origin is fixed when it is minted."""if not raw_key.startswith(API_KEY_PREFIX):return Falsecache_id = _api_key_cache_id(raw_key)@@ -1163,19 +1066,13 @@ def is_internal_api_key(raw_key: str) -> bool:def internal_api_key_name(raw_key: str) -> Optional[str]:"""The workflow name *raw_key* was minted under, or ``None`` if it is not internal.-- ``is_internal_api_key`` answers "is this Unsloth's own key", which is the right- question for a monitor label but far too coarse for authorization: a- data-recipe key runs inside a recipe the user authored, so treating it as- equal to the Deep Research hop would let that recipe spend any saved cloud- credential. The name is fixed when the key is minted and is the only durable- thing that separates the two.-- Deliberately not memoized: this is read on the external-provider path only,- once per request that carries an API key, and a stale answer here would be a- stale authorization. The PBKDF2 derivation is taken from the shared hash- cache when it is warm, so the cost is one indexed lookup.- """+ ``is_internal_api_key`` answers "is this Unsloth's own key", which is far too coarse for+ authorization: a data-recipe key runs inside a recipe the user authored, so treating it as equal+ to the Deep Research hop would let that recipe spend any saved cloud credential. The name is+ fixed when the key is minted and is the only durable thing separating the two. Deliberately not+ memoized: this is read on the external-provider path once per request, and a stale answer would+ be a stale authorization. The PBKDF2 derivation comes from the shared hash cache when it is+ warm."""if not raw_key.startswith(API_KEY_PREFIX):return Nonecache_id = _api_key_cache_id(raw_key)@@ -1196,7 +1093,6 @@ def internal_api_key_name(raw_key: str) -> Optional[str]:def validate_api_key(raw_key: str) -> Optional[str]:- """Validate *raw_key* and return the owning username, or ``None``."""verified = validate_api_key_with_credential(raw_key)return verified[0] if verified else None@@ -1204,18 +1100,12 @@ def validate_api_key(raw_key: str) -> Optional[str]:def validate_api_key_with_credential(raw_key: str, *, touch: bool = True) -> Optional[Tuple[str, str]]:- """Validate *raw_key* and return ``(username, jwt_secret)``, or ``None``.-- Also updates ``last_used_at`` on success. The key check and the credential- read share one write transaction, so the returned version is the one the key- was actually valid under: a reset committing right after cannot have its new- generation handed to a request the key it revoked authenticated.-- ``touch=False`` drops that stamp, and with it the write transaction, for a caller- that only asks whether the key authenticates and never binds a write to the- generation. One request must not count as two uses, and on sqlite the write lock- is global, so an advisory check has no business taking it.- """+ """Validate *raw_key* and return ``(username, jwt_secret)``, or ``None``. Also updates+ ``last_used_at`` on success. The key check and the credential read share one write transaction,+ so the returned version is the one the key was actually valid under. ``touch=False`` drops that+ stamp, and with it the write transaction, for a caller that only asks whether the key+ authenticates: one request must not count as two uses, and on sqlite the write lock is global,+ so an advisory check has no business taking it."""cache_id = _api_key_cache_id(raw_key)cached_hash = _api_key_hash_cache.get(cache_id)key_hash = cached_hash if cached_hash is not None else _pbkdf2_api_key(raw_key)diff --git a/studio/backend/auth/terminal_prompt.py b/studio/backend/auth/terminal_prompt.pyindex f9b3c247919..85db81af567 100644--- a/studio/backend/auth/terminal_prompt.py+++ b/studio/backend/auth/terminal_prompt.py@@ -5,12 +5,10 @@Unsloth becomes reachable: a public Cloudflare URL (``--secure`` / ``--cloudflare``)or a raw non-loopback bind such as ``-H 0.0.0.0``.-Masked input echoes one ``*`` per keystroke (unlike ``getpass``). Works on-Windows (``msvcrt``) and Linux/macOS (``termios``). All output goes to stderr so-redirected stdout never swallows the prompt.--Mirrored for the CLI at ``unsloth_cli/commands/_password_prompt.py`` (the CLI-cannot import the Unsloth backend package); keep the two in sync.+Masked input echoes one ``*`` per keystroke (unlike ``getpass``). Works on Windows (``msvcrt``) and Linux/macOS+(``termios``). All output goes to stderr so redirected stdout never swallows the prompt. Mirrored for the CLI at+``unsloth_cli/commands/_password_prompt.py`` (the CLI cannot import the Unsloth backend package); keep the two+in sync."""from __future__ import annotations@@ -41,11 +39,9 @@ def _getch_windows() -> str: # pragma: no cover - exercised via fake on Linux Cclass _RestoreTtyOnSignals:- """Restore terminal attrs if SIGTERM/SIGHUP kills the prompt mid-read.-- A finally block can't run when a signal terminates the process, leaving the- shared terminal in cbreak/no-echo. Best-effort: no-op off the main thread or- where the signals are absent.+ """Restore terminal attrs if SIGTERM/SIGHUP kills the prompt mid-read. A finally block can't run when a+ signal terminates the process, leaving the shared terminal in cbreak/no-echo. Best-effort: no-op off the+ main thread or where the signals are absent."""def __init__(self, fd: int, old_attrs) -> None:@@ -356,13 +352,10 @@ def prompt_for_password_change(def resolve_supplied_password(cli_value: "str | None", out: "TextIO | None" = None) -> "str | None":- """Resolve a non-interactive initial admin password, or None if unset.-- Precedence: an explicit ``--password`` (literal ``-`` reads a line from- stdin), then the ``UNSLOTH_STUDIO_PASSWORD`` env var; empty/omitted means off.- A literal argv value is visible in the process list, so a note points at the- env var or stdin instead. Mirror of the CLI helper -- keep the two in sync.- """+ """Resolve a non-interactive initial admin password, or None if unset. Precedence: an explicit+ ``--password`` (literal ``-`` reads a line from stdin), then the ``UNSLOTH_STUDIO_PASSWORD`` env+ var; empty/omitted means off. A literal argv value is visible in the process list, so a note+ points at the env var or stdin instead. Mirror of the CLI helper -- keep the two in sync."""if out is None:out = sys.stderrif cli_value == "-":diff --git a/studio/backend/cloudflare_tunnel.py b/studio/backend/cloudflare_tunnel.pyindex 54778bb58a7..3aae0c44ae5 100644--- a/studio/backend/cloudflare_tunnel.py+++ b/studio/backend/cloudflare_tunnel.py@@ -3,12 +3,10 @@"""Free Cloudflare quick tunnel for Unsloth's 0.0.0.0 launches.-The raw http://<ip>:<port> is often unreachable (https-vs-http, blocked ports,-closed security groups); a cloudflared quick tunnel gives a free-https://*.trycloudflare.com URL that works anywhere, with no account or domain.--Best-effort throughout: any failure collapses to "no URL" and Unsloth keeps-running. Stdlib only (back-end imports are lazy) so it is safe to import early.+The raw http://<ip>:<port> is often unreachable (https-vs-http, blocked ports, closed security groups); a+cloudflared quick tunnel gives a free https://*.trycloudflare.com URL that works anywhere, with no account or+domain. Best-effort throughout: any failure collapses to "no URL" and Unsloth keeps running. Stdlib only+(back-end imports are lazy) so it is safe to import early."""from __future__ import annotations@@ -186,11 +184,8 @@ def _download(url: str, dest: Path) -> bool:def _extract_tgz_member(tgz_path: Path, dest: Path) -> bool:- """Extract just the `cloudflared` member from a darwin .tgz to dest.-- Rejects absolute paths and `..` traversal so a hostile archive cannot write- outside dest. Best-effort -> bool.- """+ """Extract just the `cloudflared` member from a darwin .tgz to dest. Rejects absolute paths and+ `..` traversal so a hostile archive cannot write outside dest. Best-effort -> bool."""import tarfiletry:with tarfile.open(tgz_path, "r:gz") as tar:@@ -323,11 +318,9 @@ def _probe_edge(def _verify_through_edge(host: str, deadline: float) -> bool:- """Verify at the edge, which selects the tunnel by SNI rather than by address.-- Error 1033 and an intercepting proxy's own page are both answers and are not- told apart here, so only the marker ends the wait. Nothing answering at all- is this path being blocked, which the hostname may still get through.+ """Verify at the edge, which selects the tunnel by SNI rather than by address. Error 1033 and an intercepting+ proxy's own page are both answers and are not told apart here, so only the marker ends the wait. Nothing+ answering at all is this path being blocked, which the hostname may still get through."""addresses = _edge_addresses()if not addresses:@@ -396,10 +389,8 @@ def _origin_url(host: str, port: int) -> str:class CloudflareTunnel:- """A cloudflared quick tunnel to a local Studio endpoint. Best-effort throughout.-- Use a loopback address for wildcard binds so cloudflared's upstream stays- local-only while matching Studio's active address family.+ """A cloudflared quick tunnel to a local Studio endpoint. Best-effort throughout. Use a loopback address for+ wildcard binds so cloudflared's upstream stays local-only while matching Studio's active address family."""def __init__(@@ -503,11 +494,9 @@ class CloudflareTunnel:callback(self)def wait_for_ready(self, timeout: float = _READY_TIMEOUT) -> Optional[str]:- """Block until the tunnel is actually serving -- the URL has been minted- *and* at least one edge connection has registered -- or until timeout.-- Returns the URL only when ready, so callers never advertise a URL that- would return Cloudflare error 1033 (HTTP 530)."""+ """Block until the tunnel is actually serving -- the URL has been minted *and* at least one edge connection+ has registered -- or until timeout. Returns the URL only when ready, so callers never advertise a URL+ that would return Cloudflare error 1033 (HTTP 530)."""self._ready_event.wait(timeout)return self.url if self.ready else None@@ -755,16 +744,12 @@ def start_studio_tunnel(admission: Optional[Tuple[int, int]] = None,origin_host: str = "localhost",) -> Optional[str]:- """Start a quick tunnel and return its public URL once it is actually- serving, or None (best-effort).-- Waits for cloudflared to both mint the URL and register an edge connection,- then fetches /api/health over the public URL, so the caller never advertises- a link that yields Cloudflare error 1033 (HTTP 530) or an unresolvable host.- If a URL is minted but no connection registers within the window (e.g. quic- is blocked on this network), retries once forcing the http2 protocol. On any- failure the tunnel is stopped and None is returned.- """+ """Start a quick tunnel and return its public URL once it is actually serving, or None+ (best-effort). Waits for cloudflared to both mint the URL and register an edge connection, then+ fetches /api/health over the public URL, so the caller never advertises a link that yields+ Cloudflare error 1033 (HTTP 530) or an unresolvable host. If a URL is minted but no connection+ registers within the window (e.g. quic is blocked on this network), retries once forcing the+ http2 protocol. On any failure the tunnel is stopped and None is returned."""global _active_tunnel, _shutdown_requested, _tunnel_generationglobal _tunnel_state, _tunnel_owner, _tunnel_url, _tunnel_error, _tunnel_portif managed_by not in _TUNNEL_OWNERS:diff --git a/studio/backend/colab.py b/studio/backend/colab.pyindex 81458d253b4..477786676ac 100644--- a/studio/backend/colab.py+++ b/studio/backend/colab.py@@ -20,10 +20,8 @@ logger = get_logger(__name__)def get_colab_url(port: int = 8888) -> str:- """Get the Colab proxy URL for a port.-- Retries 3x validating a real HTTPS Colab URL; falls back to localhost on failure.- """+ """Get the Colab proxy URL for a port. Retries 3x validating a real HTTPS Colab URL; falls back to+ localhost on failure."""import time as _timefallback = f"http://localhost:{port}"@@ -68,10 +66,8 @@ def _is_colab_proxy_url(url: str, port: int) -> bool:def _is_colab_runtime() -> bool:- """True on a hosted Colab notebook kernel.-- Reuses the backend's main Colab detector (``/content`` + Colab env / ``google.colab``)- instead of a single env var, which is not always present on hosted runtimes.+ """True on a hosted Colab notebook kernel. Reuses the backend's main Colab detector (``/content`` + Colab env+ / ``google.colab``) instead of a single env var, which is not always present on hosted runtimes."""try:from main import _IS_COLAB@@ -124,12 +120,9 @@ def _clear_colab_login_credentials() -> None:def _colab_credentials_still_valid(username: str, password: str) -> bool:- """True when *password* still matches the stored admin hash.-- Guards against redisplaying a cached first-run password after the user has- changed the admin password through the app, which would print credentials- that no longer authenticate to the current Cloudflare tunnel.- """+ """True when *password* still matches the stored admin hash. Guards against redisplaying a cached+ first-run password after the user has changed the admin password through the app, which would+ print credentials that no longer authenticate to the current Cloudflare tunnel."""try:from auth.storage import get_user_and_secretfrom auth.hashing import verify_password@@ -148,24 +141,18 @@ def _colab_credentials_still_valid(username: str, password: str) -> bool:def _colab_wants_cloudflare(cloudflare: "bool | None") -> bool:- """Resolve whether to open a Cloudflare tunnel.-- ``None`` auto-enables on real Colab (the in-cell proxy embed is often blank);- pass ``False`` to opt out.- """+ """Resolve whether to open a Cloudflare tunnel. ``None`` auto-enables on real Colab (the in-cell+ proxy embed is often blank); pass ``False`` to opt out."""if cloudflare is not None:return cloudflarereturn _is_colab_runtime()def _finalize_colab_admin_password() -> "tuple[str, str] | None":- """Clear the bootstrap-password gate on Colab so Cloudflare tunnels can start.-- Returns ``(username, password)`` for display in the notebook. On first run the- random admin password is finalized; on later runs (e.g. after interrupt) the- stored credentials are re-displayed so the Cloudflare link stays usable.- Anyone who can read this cell already controls the runtime.- """+ """Clear the bootstrap-password gate on Colab so Cloudflare tunnels can start. Returns ``(username,+ password)`` for display in the notebook. On first run the random admin password is finalized; on+ later runs (e.g. after interrupt) the stored credentials are re-displayed so the Cloudflare link+ stays usable. Anyone who can read this cell already controls the runtime."""if not _is_colab_runtime():return Nonetry:@@ -243,12 +230,10 @@ def _ready_card_html(has_cloudflare_link: bool = False,cloudflare_requested: bool = False,) -> str:- """Branded ready card for the in-notebook Unsloth view.-- Colab ``*.prod.colab.dev`` proxy URLs are session-scoped and 404 when opened as a- top-level tab or on another device, so never ``window.open`` them. On real Colab the- Cloudflare link is the supported entry point because in-cell proxy embeds often stay blank.- """+ """Branded ready card for the in-notebook Unsloth view. Colab ``*.prod.colab.dev`` proxy URLs are+ session-scoped and 404 when opened as a top-level tab or on another device, so never+ ``window.open`` them. On real Colab the Cloudflare link is the supported entry point because+ in-cell proxy embeds often stay blank."""short_url = _short_colab_url(url, port)if _is_colab_runtime() or _is_colab_proxy_url(url, port):if has_cloudflare_link:@@ -320,12 +305,9 @@ def show_link(has_cloudflare_link: bool = False,cloudflare_requested: bool = False,):- """Display a styled ready card for the UI.-- Colab proxy URLs are informational only (no new-tab open; they 404 outside the cell);- non-proxy URLs keep a clickable open button. *_url* is an optional pre-fetched proxy- URL to avoid a second eval_js round-trip.- """+ """Display a styled ready card for the UI. Colab proxy URLs are informational only (no new-tab+ open; they 404 outside the cell); non-proxy URLs keep a clickable open button. *_url* is an+ optional pre-fetched proxy URL to avoid a second eval_js round-trip."""from IPython.display import display, HTMLurl = _url if _url is not None else get_colab_url(port)@@ -353,11 +335,9 @@ def _warn_colab_cloudflare_missing(*, use_cloudflare: bool, cloudflare_url: "strdef _bootstrap_password_pending() -> bool:- """True while the default admin still owes a bootstrap-password change.-- While pending, a public tunnel GET (no Origin) reads as same-origin and gets the- injected password, so sharing the link would leak admin access. Fails safe to pending.- """+ """True while the default admin still owes a bootstrap-password change. While pending, a public+ tunnel GET (no Origin) reads as same-origin and gets the injected password, so sharing the link+ would leak admin access. Fails safe to pending."""try:from auth.storage import requires_password_change, DEFAULT_ADMIN_USERNAMEreturn bool(requires_password_change(DEFAULT_ADMIN_USERNAME))@@ -367,11 +347,9 @@ def _bootstrap_password_pending() -> bool:def start_cloudflare_tunnel(port: int) -> "str | None":- """Open a shareable Cloudflare quick tunnel to localhost:*port*, or None.-- run_server suppresses the tunnel on Colab, so we start it directly. Refused while the- bootstrap password is pending; any failure collapses to None (Colab proxy still works).- """+ """Open a shareable Cloudflare quick tunnel to localhost:*port*, or None. run_server suppresses the+ tunnel on Colab, so we start it directly. Refused while the bootstrap password is pending; any+ failure collapses to None (Colab proxy still works)."""if _bootstrap_password_pending():logger.warning("Cloudflare link not started: the admin account still has its temporary "@@ -415,10 +393,8 @@ def _stop_cloudflare_tunnel() -> None:def _is_studio_healthy(port: int, timeout: float = 2.0) -> bool:- """True only if Unsloth Studio (not some other app) answers /api/health on *port*.-- The service-marker check stops the reuse path reusing or tunneling a foreign process.- """+ """True only if Unsloth Studio (not some other app) answers /api/health on *port*. The+ service-marker check stops the reuse path reusing or tunneling a foreign process."""import json, urllib.requesttry:with urllib.request.urlopen(f"http://localhost:{port}/api/health", timeout = timeout) as r:@@ -432,11 +408,9 @@ def _shareable_link_html(password: "str | None" = None,username: "str | None" = None,) -> str:- """Branded card for the shareable Cloudflare link, styled like the show_link banner.-- *password* renders under the link so the credential sits in the card with the button- it unlocks. The username is always the default admin, so it reads inline.- """+ """Branded card for the shareable Cloudflare link, styled like the show_link banner. *password*+ renders under the link so the credential sits in the card with the button it unlocks. The+ username is always the default admin, so it reads inline."""login_block = ""if password:login_block = f"""@@ -482,12 +456,9 @@ _COLAB_IFRAME_HEIGHT = 900def _embed_kernel_port_iframe(port: int) -> bool:- """Embed Unsloth via Colab's native kernel-port iframe helper.-- Only trusted on a real Colab runtime: colabtools can import ``google.colab`` and- queue browser-side JS without appending an iframe, so callers outside Colab must use- the HTML iframe path instead.- """+ """Embed Unsloth via Colab's native kernel-port iframe helper. Only trusted on a real Colab+ runtime: colabtools can import ``google.colab`` and queue browser-side JS without appending an+ iframe, so callers outside Colab must use the HTML iframe path instead."""if not _is_colab_runtime():return Falsetry:@@ -548,10 +519,8 @@ def _show_and_embed(colab_login: "tuple[str, str] | None" = None,cloudflare_requested: bool = False,):- """Render the Unsloth ready card + iframe for *port*.-- Prefer Colab's ``serve_kernel_port_as_iframe`` on real Colab; raw HTML iframe is the- fallback. Cloudflare cards stay clickable.+ """Render the Unsloth ready card + iframe for *port*. Prefer Colab's ``serve_kernel_port_as_iframe`` on real+ Colab; raw HTML iframe is the fallback. Cloudflare cards stay clickable."""url = get_colab_url(port)logger.info(f"🌐 Unsloth Studio URL: {url}")@@ -607,19 +576,12 @@ def _show_and_embed(def start(port: int = 8888, *, cloudflare: "bool | None" = None):- """Start Unsloth Studio in Colab and display the URL.-- Args:- port: Port to bind/serve on.- cloudflare: Shareable Cloudflare HTTPS link. ``None`` (default) auto-enables on- real Colab because the in-cell proxy embed is often blank; pass ``False`` to- skip the tunnel or ``True`` to force it on other runtimes.-- Usage:- start() # Cloudflare link on Colab (auto); proxy iframe elsewhere- start(cloudflare=False) # Colab proxy iframe only (often blank on current Colab)- start(cloudflare=True) # force Cloudflare link on any runtime- """+ """Start Unsloth Studio in Colab and display the URL. Args: port: Port to bind/serve on.+ cloudflare: Shareable Cloudflare HTTPS link. ``None`` (default) auto-enables on real Colab+ because the in-cell proxy embed is often blank; pass ``False`` to skip the tunnel or ``True`` to+ force it on other runtimes. Usage: start() # Cloudflare link on Colab (auto); proxy iframe+ elsewhere start(cloudflare=False) # Colab proxy iframe only (often blank on current Colab)+ start(cloudflare=True) # force Cloudflare link on any runtime"""import timelogger.info("🦥 Starting Unsloth Studio...")diff --git a/studio/backend/lan_access.py b/studio/backend/lan_access.pyindex 8a0b0e6a5e5..ce62091a05c 100644--- a/studio/backend/lan_access.py+++ b/studio/backend/lan_access.py@@ -3,21 +3,18 @@"""Runtime LAN listener for Unsloth Studio.-Unsloth binds 127.0.0.1 by default, so a phone or laptop on the same network-cannot reach it without relaunching with ``-H 0.0.0.0``. This module adds a-second uvicorn listener over the already-running app, on the machine's own-network addresses and the same port, and takes it away again -- no restart, and-the loopback socket keeps serving the desktop app throughout.--The listener binds each detected address explicitly rather than the wildcard:-``0.0.0.0`` collides with the loopback socket that already holds the port. It-runs on the primary server's event loop with ``lifespan="off"``, so the app's-startup and shutdown handlers stay owned by the primary server and never fire-twice.--The settings-managed listener remains IPv4 only. Address discovery also serves-an existing IPv6 wildcard launch, while link-local IPv6 addresses are omitted-because another device cannot use them without the listener's interface scope.+Unsloth binds 127.0.0.1 by default, so a phone or laptop on the same network cannot reach it without+relaunching with ``-H 0.0.0.0``. This module adds a second uvicorn listener over the already-running app, on the+machine's own network addresses and the same port, and takes it away again -- no restart, and the loopback+socket keeps serving the desktop app throughout.++The listener binds each detected address explicitly rather than the wildcard: ``0.0.0.0`` collides with the+loopback socket that already holds the port. It runs on the primary server's event loop with ``lifespan="off"``,+so the app's startup and shutdown handlers stay owned by the primary server and never fire twice.++The settings-managed listener remains IPv4 only. Address discovery also serves an existing IPv6 wildcard launch,+while link-local IPv6 addresses are omitted because another device cannot use them without the listener's+interface scope."""from __future__ import annotations@@ -70,12 +67,10 @@ _bound_addresses: tuple[str, ...] = ()def detect_lan_addresses(ip_version: int = 4) -> list[str]:- """The machine's own reachable addresses for one IP version, default route first.-- Loopback, link-local (169.254/16) and multicast are dropped: none of them is- an address another device on the network can open. A public address is kept- -- a cloud VM binding its own public IP is the same operation as a laptop- binding its Wi-Fi address, and the caller decides whether that is wanted.+ """The machine's own reachable addresses for one IP version, default route first. Loopback, link-local+ (169.254/16) and multicast are dropped: none of them is an address another device on the network can open. A+ public address is kept -- a cloud VM binding its own public IP is the same operation as a laptop binding its+ Wi-Fi address, and the caller decides whether that is wanted."""# WSL's NAT-side address belongs to a private Hyper-V network a second device cannot open; mirrored# mode is different, since WSL joins the host's network@@ -129,12 +124,9 @@ def detect_lan_addresses(ip_version: int = 4) -> list[str]:def _wsl_networking_mode() -> Optional[str]:- """The active WSL networking mode, or ``None`` outside WSL.-- An older WSL without ``wslinfo`` is treated as unknown and therefore not- advertised. Older releases use NAT, so failing closed avoids handing a phone- an address that only the Windows host can route to.- """+ """The active WSL networking mode, or ``None`` outside WSL. An older WSL without ``wslinfo`` is+ treated as unknown and therefore not advertised. Older releases use NAT, so failing closed+ avoids handing a phone an address that only the Windows host can route to."""global _wsl_mode_cacheif sys.platform != "linux" or "microsoft" not in platform.release().casefold():@@ -174,12 +166,9 @@ def _is_host_only_interface(name: str) -> bool:def _interface_addresses(ip_version: int = 4) -> list[str]:- """Addresses for one IP version on every interface that is up.-- Falls back to resolving the hostname where psutil is unavailable. That- fallback is not an enumeration: a Linux host mapping its name to 127.0.1.1- reports nothing, which is why it is the last resort rather than the source.- """+ """Addresses for one IP version on every interface that is up. Falls back to resolving the hostname+ where psutil is unavailable. That fallback is not an enumeration: a Linux host mapping its name+ to 127.0.1.1 reports nothing, which is why it is the last resort rather than the source."""try:import psutilexcept ImportError:@@ -211,13 +200,10 @@ def _interface_addresses(ip_version: int = 4) -> list[str]:def is_public_address(address: str) -> bool:- """True when ``address`` is routable from the internet, not just this network.-- A VPS or dedicated box usually carries its public IPv4 straight on the NIC, so- the addresses this module binds are not always the LAN addresses the name- implies. Callers surface that rather than refusing it: a public-IP campus or- office network is a legitimate place to serve, and only the operator knows- which one they are on.+ """True when ``address`` is routable from the internet, not just this network. A VPS or dedicated box usually+ carries its public IPv4 straight on the NIC, so the addresses this module binds are not always the LAN+ addresses the name implies. Callers surface that rather than refusing it: a public-IP campus or office+ network is a legitimate place to serve, and only the operator knows which one they are on."""try:return ipaddress.ip_address(address).is_global@@ -348,12 +334,9 @@ def start_lan_listener(def _sync_lan_trust() -> None:- """Publish the beyond-loopback flag from the authoritative state.-- Derived rather than assigned by callers: a repeated stop, or a start racing a- stop in another worker thread, otherwise cleared a flag that a live listener- or a still-draining one owned. The caller holds ``_lock``.- """+ """Publish the beyond-loopback flag from the authoritative state. Derived rather than assigned by+ callers: a repeated stop, or a start racing a stop in another worker thread, otherwise cleared a+ flag that a live listener or a still-draining one owned. The caller holds ``_lock``."""set_lan_connector_active(_server is not None or _pending_drains > 0)@@ -391,12 +374,9 @@ def _arm_drain_watcher(server) -> None:def _clear_trust_after_drain(server) -> None:- """Hold the beyond-loopback flag until the stopped listener's requests finish.-- Closing the listening sockets stops new connections, but uvicorn then drains- the accepted ones, and a request that started on the LAN is still a remote- caller for its whole life.- """+ """Hold the beyond-loopback flag until the stopped listener's requests finish. Closing the+ listening sockets stops new connections, but uvicorn then drains the accepted ones, and a+ request that started on the LAN is still a remote caller for its whole life."""global _pending_drainsstate = getattr(server, "server_state", None)@@ -421,15 +401,11 @@ def _close_sockets(sockets) -> None:def stop_lan_listener() -> bool:- """Release the LAN sockets and take the listener down. Idempotent.-- Returns whether the port is confirmed released. A False means the sockets may- still be accepting, so the caller must keep treating the host as reachable.-- Waits for the sockets, not for ``serve()`` to return: uvicorn closes the- sockets passed to it at the top of its shutdown and only then drains- in-flight responses, so waiting on the serve task would make a Stop pressed- from a LAN device wait out its own response.+ """Release the LAN sockets and take the listener down. Idempotent. Returns whether the port is confirmed+ released; False means the sockets may still be accepting, so the caller must keep treating the host as+ reachable. Waits for the sockets, not for ``serve()`` to return: uvicorn closes the sockets passed to it at+ the top of its shutdown and only then drains in-flight responses, so waiting on the serve task would make a+ Stop pressed from a LAN device wait out its own response."""global _server, _serve_loop, _sockets, _bound_addresses, _port, _error@@ -450,9 +426,9 @@ def stop_lan_listener() -> bool:return Trueserver.should_exit = Trueif _running_on_event_loop():- # /api/shutdown tears down from a task on this very loop, so waiting would deadlock; ownership is- # kept because uvicorn cannot close the sockets until the loop is free again, and- # _graceful_shutdown blocks it for seconds stopping subprocesses+ # /api/shutdown tears down from a task on this very loop, so waiting would deadlock; ownership is kept+ # because uvicorn cannot close the sockets until the loop is free again, and _graceful_shutdown blocks it+ # for seconds stopping subprocesseslogger.info("LAN access stopping")return Trueif loop is None or loop.is_closed() or not loop.is_running():@@ -495,11 +471,9 @@ def clear_lan_listener_error() -> None:def request_on_lan_listener(scope) -> bool:- """True when this request arrived on a LAN listener socket, not on loopback.-- ``scope["server"]`` is the accepting socket's own address, so it identifies- the listener a connection came in on without trusting any client header.- """+ """True when this request arrived on a LAN listener socket, not on loopback. ``scope["server"]`` is+ the accepting socket's own address, so it identifies the listener a connection came in on+ without trusting any client header."""addresses = _bound_addressesif not addresses:return Falsediff --git a/studio/backend/loggers/config.py b/studio/backend/loggers/config.pyindex 1c29b0cb1f1..781fc6824c7 100644--- a/studio/backend/loggers/config.py+++ b/studio/backend/loggers/config.py@@ -3,8 +3,8 @@"""Structured logging configuration via structlog.-Environment-specific formats (JSON for prod, console for dev), ISO timestamps,-context-var integration, log-level filtering, and logger caching.+Environment-specific formats (JSON for prod, console for dev), ISO timestamps, context-var+integration, log-level filtering, and logger caching."""import logging@@ -43,12 +43,9 @@ _MAX_ERROR_CHARS = 2048def _truncate_middle(text: str, limit: int, tail: int) -> str:- """Keep the head and the tail of `text`, saying how much was dropped.-- The head holds the raising frame and the tail the exception type and message, so- both ends are worth keeping. `tail` is clamped so a cap smaller than the tail- cannot make the head negative and hand back nearly the whole string.- """+ """Keep the head and the tail of `text`, saying how much was dropped. The head holds the raising+ frame and the tail the exception type and message. `tail` is clamped so a cap smaller than the+ tail cannot make the head negative and hand back the whole string."""if limit <= 0 or len(text) <= limit:return texttail = max(1, min(tail, limit // 4))@@ -110,26 +107,24 @@ def _plain_tracebacks_enabled() -> bool:_TRACEBACK_ECHO_PREFIX = "| "-# Unicode's Bidi_Control set (PropList.txt), exactly what UAX #9 acts on and what UTR #36 /-# Trojan Source (CVE-2021-42574) name; json.dumps already escapes these (ensure_ascii), so only-# the echo would emit them raw. Deliberately NOT all of category Cf: U+200B-200D, U+00AD and-# U+FEFF occur in ordinary text (ZWNJ in Persian/Arabic, ZWJ in emoji) and reorder nothing.+# Unicode's Bidi_Control set (PropList.txt), exactly what UAX #9 acts on and what UTR #36 / Trojan+# Source (CVE-2021-42574) name; json.dumps already escapes these, so only the echo would emit them+# raw. Deliberately NOT all of category Cf: U+200B-200D, U+00AD and U+FEFF occur in ordinary text._BIDI_CONTROLS = frozenset("")def _escape_unprintable(text: str) -> str:- """Spell as ``\\uXXXX`` what a terminal would ACT on or stdout cannot encode, leaving- ordinary non-ASCII text readable. The JSON renderer used to cover all three for free:-- * **Lone surrogates** (reachable via ``json.loads('"\\ud800"')`` in a request body)- raise ``UnicodeEncodeError`` on a UTF-8 stdout, which inside an exception handler- loses the traceback AND replaces the original exception with the encoding error.- * **Terminal controls**: raw ESC lets request-derived text rewrite what the reader- sees, and a backspace run can rub out the prefix record forgery depends on.- * **Bidi controls** need no terminal -- any UAX #9 viewer reorders the line. Measured:- ``"| ValueError: rejected upload \\u202egnp.eliforp/sdaolpu/"`` DISPLAYS as- ``| ValueError: rejected upload /uploads/profile.png``. Escaped, not stripped, so- the record still says one was there.+ """Spell as ``\\uXXXX`` what a terminal would ACT on or stdout cannot encode, leaving ordinary+ non-ASCII text readable. The JSON renderer used to cover all three for free:++ * **Lone surrogates**, reachable through a request body, raise ``UnicodeEncodeError`` on a UTF-8+ stdout, which inside an exception handler loses the traceback AND replaces the original+ exception with the encoding error.+ * **Terminal controls**: raw ESC lets request-derived text rewrite what the reader sees, and a+ backspace run can rub out the prefix record forgery depends on.+ * **Bidi controls** need no terminal, since any UAX #9 viewer reorders the line: a measured+ "rejected upload" message DISPLAYS with its path reversed. Escaped, not stripped, so the+ record still says one was there.Tab is kept: it shifts alignment but cannot move the cursor back or erase."""@@ -153,14 +148,11 @@ def _escape_unprintable(text: str) -> str:def _echoable(exception: str) -> str:"""The traceback as lines that can never read as a log record, nor act on a terminal.-- ``splitlines`` also splits on \\r, \\x0b, \\x0c, \\x85 and U+2028/9, so rejoining on- \\n normalises every separator a message could smuggle in, including the \\r the export- worker's log reader treats as a line break.-- Capped AFTER escaping: the field arrives bounded by ``truncate_exception`` at- ``_MAX_EXC_CHARS``, but escaping costs six characters each, so an all-C0 payload turns- 16 KiB of bounded field into 98 KiB of echo. Capping the input keeps that multiplier."""+ ``splitlines`` also splits on the other Unicode line breaks, so rejoining on line feeds+ normalises every separator a message could smuggle in, including the CR the export worker's log+ reader treats as a line break. Capped AFTER escaping: the field arrives bounded by+ ``truncate_exception``, but escaping costs six characters each, so an all-C0 payload turns 16+ KiB of bounded field into 98 KiB of echo."""lines = [f"{_TRACEBACK_ECHO_PREFIX}{_escape_unprintable(part)}"for part in exception.rstrip().splitlines()@@ -169,12 +161,10 @@ def _echoable(exception: str) -> str:def _cap_echoed_lines(lines: list[str], limit: int) -> str:- """Join the echoed lines within `limit` characters, keeping the head and the tail.-- Whole lines where they fit, and the omission notice is prefixed too, so no emitted line- can begin a JSON value. A line too long for its budget is cut, not dropped: the cut can- land inside a ``\\uXXXX`` escape, but the tail holds the exception type and message and- a control-heavy message is exactly what makes that last line oversized."""+ """Join the echoed lines within `limit` characters, keeping the head and the tail. Whole lines+ where they fit, and the omission notice is prefixed too, so no emitted line can begin a JSON+ value. A line too long for its budget is cut, not dropped: the cut can land inside an escape,+ but the tail holds the exception type and message."""if limit <= 0:return "\n".join(lines)total = sum(len(line) + 1 for line in lines)@@ -215,26 +205,17 @@ def _cap_echoed_lines(lines: list[str], limit: int) -> str:def with_readable_traceback(renderer):- """Wrap the JSON renderer so an exception is ALSO echoed as a real multi-line traceback- on the lines after the record.-- ~/.unsloth/studio/logs is a tee of stdout and stdout is JSON, so every traceback- reached its reader as one enormous line with newlines escaped to ``\\n`` -- correct- JSON, unreadable prose. The reported Image Transform failure ("RuntimeError: Input type- (float) and bias type (c10::BFloat16)...") arrived that way, and so does every crash- anyone is asked to send in.-- The JSON record is emitted UNCHANGED, so record-by-record readers see what they always- saw, and every echoed line is prefixed so it cannot parse as a record. Non-JSON lines- in that file are already expected -- faulthandler dumps native stacks to the same- handle.-- Returned as part of the SAME string rather than written to another stream, so one- ``print`` under ``PrintLogger``'s lock keeps record and traceback adjacent and ordered:- a processor runs BEFORE that print, and the export worker reads stdout and stderr on- separate pipes.-- JSON only. ConsoleRenderer (development) already prints tracebacks as tracebacks."""+ """Wrap the JSON renderer so an exception is ALSO echoed as a real multi-line traceback on the+ lines after the record. ~/.unsloth/studio/logs is a tee of stdout and stdout is JSON, so every+ traceback reached its reader as one enormous line with escaped newlines: correct JSON,+ unreadable prose, and that is how every crash anyone is asked to send in arrives. The JSON+ record is emitted UNCHANGED, so record-by-record readers see what they always saw, and every+ echoed line is prefixed so it cannot parse as a record. Non-JSON lines in that file are already+ expected, since faulthandler dumps native stacks to the same handle. Returned as part of the+ SAME string rather than written to another stream, so one ``print`` under ``PrintLogger``'s lock+ keeps record and traceback adjacent and ordered: a processor runs BEFORE that print, and the+ export worker reads stdout and stderr on separate pipes. JSON only. ConsoleRenderer+ (development) already prints tracebacks as tracebacks."""def _render(logger, method_name, event_dict):exception = event_dict.get("exception")@@ -303,15 +284,11 @@ class _NullStream:def _silence_datasets_bar_output() -> None:- """Keep the datasets bar object, drop only what it writes.-- datasets exposes no env var, and its disable_progress_bar() works by forcing- tqdm(disable = True), which never registers the bar in tqdm._instances.- utils/datasets/chat_templates.py polls that set to publish- "Applying chat template ... 42%" to the UI, so disabling the bar outright would- freeze that status for the whole of a long format job. Pointing the bar at a null- stream keeps the counter (and the status) alive while the log stays clean.- """+ """Keep the datasets bar object, drop only what it writes. datasets exposes no env var, and its+ disable_progress_bar() works by forcing tqdm(disable = True), which never registers the bar in+ tqdm._instances. utils/datasets/chat_templates.py polls that set to publish "Applying chat+ template" progress to the UI, so disabling the bar outright would freeze that status for a whole+ long format job."""if "datasets" not in sys.modules:# Operator asked to keep them; leave every library alone.return@@ -333,11 +310,9 @@ def _silence_datasets_bar_output() -> None:def _redirect_every_bar_output() -> None:- """Point every tqdm bar at a null stream, disabling none of them.-- tqdm.std.tqdm.__init__ is the one funnel: huggingface_hub's, datasets' and- transformers' bar classes all subclass it and reach it through super().- """+ """Point every tqdm bar at a null stream, disabling none of them. tqdm.std.tqdm.__init__ is the one+ funnel: huggingface_hub's, datasets' and transformers' bar classes all subclass it and reach it+ through super()."""try:from tqdm.std import tqdm as bar_cls@@ -356,25 +331,15 @@ def _redirect_every_bar_output() -> None:def keep_progress_bars_countable() -> None:- """Keep the bar objects alive in a process that READS them, output dropped.-- core/training/worker.py runs a poller over tqdm._instances to turn the Hub- download bar and "Loading checkpoint shards" into the UI's status line, which is- the only progress a user sees between "Loading model..." and the first step. A- disabled bar is never registered in _instances (tqdm/std.py drops it), so the- inherited HF_HUB_DISABLE_PROGRESS_BARS default would leave that status frozen for- the whole of a multi-GB download. Same trade as datasets: keep the counter, drop- the writes, so nothing reaches the log either way.-- Only Unsloth's own default is undone; an operator who set the variable themselves- asked for no bars and keeps getting none. Afterwards- quiet_third_party_progress_bars() is a no-op in this process, so a later call- cannot re-disable what the poller reads.-- Call it BEFORE huggingface_hub is imported: hub reads the variable once, into a- module constant, and enable_progress_bars() then refuses to override it. The- training worker does, ahead of its setup_logging call.- """+ """Keep the bar objects alive in a process that READS them, output dropped. core/training/worker.py+ runs a poller over tqdm._instances to turn the Hub download bar and "Loading checkpoint shards"+ into the UI's status line, which is the only progress a user sees between "Loading model..." and+ the first step. A disabled bar is never registered in _instances, so the inherited+ HF_HUB_DISABLE_PROGRESS_BARS default would leave that status frozen for a whole multi-GB+ download. Only Unsloth's own default is undone; an operator who set the variable themselves+ keeps getting no bars, and afterwards quiet_third_party_progress_bars() is a no-op in this+ process. Call it BEFORE huggingface_hub is imported: hub reads the variable once into a module+ constant, and enable_progress_bars() then refuses to override it."""value = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")if value is None or not _env_is_true(value):return@@ -386,11 +351,9 @@ def keep_progress_bars_countable() -> None:def quiet_bar_kwargs() -> dict:- """tqdm kwargs that keep a bar counting but stop it writing to the log.-- For Unsloth's own explicit bars (the dataset conversion loops), which no library- switch reaches. Empty when the operator asked to keep bars, so nothing changes.- """+ """tqdm kwargs that keep a bar counting but stop it writing to the log. For Unsloth's own explicit+ bars (the dataset conversion loops), which no library switch reaches. Empty when the operator+ asked to keep bars, so nothing changes."""value = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")if value is None or not _env_is_true(value):return {}@@ -398,12 +361,10 @@ def quiet_bar_kwargs() -> dict:def allow_progress_bars() -> None:- """Undo an inherited Unsloth default so this process can draw progress bars.-- Called by the export worker, whose stdout is forwarded to the export dialog and- whose Hub upload bar is the only live byte progress a long push_to_hub has. An- operator-set HF_HUB_DISABLE_PROGRESS_BARS is left alone.- """+ """Undo an inherited Unsloth default so this process can draw progress bars. Called by the export+ worker, whose stdout is forwarded to the export dialog and whose Hub upload bar is the only live+ byte progress a long push_to_hub has. An operator-set HF_HUB_DISABLE_PROGRESS_BARS is left+ alone."""global _BARS_RESTORED_BARS_RESTORED = Trueif os.environ.pop(_PROGRESS_BARS_DEFAULTED, None):@@ -411,36 +372,18 @@ def allow_progress_bars() -> None:def quiet_third_party_progress_bars() -> None:- """Turn off the tqdm bars transformers / diffusers / huggingface_hub draw- during an in-process model load.-- A bar is written with carriage returns to a terminal, so in Unsloth's log it- lands as a burst of lines like-- Loading weights: 8%|> | 30/398 [00:00<00:01, 277.16it/s][A-- and, because tqdm writes to a different stream than the structlog JSON- writer with no line discipline between them, a bar can land mid-record:- ``Loading pipeline components...: 20%|...|{"timestamp": ...}``. That line- is no longer parseable JSON, so anything reading the log record-by-record- loses the record.-- Nothing is lost by dropping them: download and load progress already reach- the UI as real events (``hub_download_progress``, ``inference_load_progress``)- and via /api/inference/{images,video}/load-progress. Only the bars go; the- libraries' warnings and errors are untouched.-- The subprocess workers already do this by exporting- HF_HUB_DISABLE_PROGRESS_BARS (hub/services/download_lifecycle.py,- core/inference/stt_download_worker.py); the server process, which loads the- RAG embedder at boot and every diffusers pipeline in-process, did not.-- Respects an explicit operator override: if HF_HUB_DISABLE_PROGRESS_BARS is- already set, its value wins, parsed the way huggingface_hub parses it. Only- modules that are ALREADY imported get the API call, so this never forces a heavy- import at logging-setup time, and never caches a Hub copy that a subprocess is- about to replace with its transformers sidecar. `--verbose` skips it entirely.- """+ """Turn off the tqdm bars transformers / diffusers / huggingface_hub draw during an in-process+ model load. A bar is written with carriage returns to a terminal, so in Unsloth's log it lands+ as a burst of partial lines, and because tqdm writes to a different stream than the structlog+ JSON writer with no line discipline between them, a bar can land mid-record and leave a line+ that is no longer parseable JSON, losing the record for anything reading it record-by-record.+ Nothing is lost by dropping them: download and load progress already reach the UI as real events+ and via /api/inference/{images,video}/load-progress. The subprocess workers already do this by+ exporting HF_HUB_DISABLE_PROGRESS_BARS; the server process, which loads the RAG embedder at boot+ and every diffusers pipeline in-process, did not. Respects an explicit operator override, parsed+ the way huggingface_hub parses it. Only modules that are ALREADY imported get the API call, so+ this never forces a heavy import at logging-setup time, and never caches a Hub copy a subprocess+ is about to replace with its transformers sidecar. `--verbose` skips it entirely."""if _BARS_RESTORED:# This process took its bars back on purpose: the training worker reads them out of tqdm._instances,# where a disabled bar is never registered, and has already redirected their output.@@ -468,9 +411,8 @@ def quiet_third_party_progress_bars() -> None:pass# transformers derives its own _tqdm_active from the hub flag at import time, so a module imported- # BEFORE this ran still needs the explicit call.- # datasets is handled separately: the UI reads its bar counters, so only the output goes, and it is- # imported long after logging setup, which is why this function is safe to call again.+ # BEFORE this ran still needs the explicit call. datasets is handled separately: the UI reads its+ # bar counters, so only the output goes, and it is imported long after logging setup.for _mod in ("transformers", "diffusers"):module = sys.modules.get(_mod)if module is None:@@ -493,14 +435,10 @@ class LogConfig:env: Optional[str] = None,quiet_progress_bars: bool = True,) -> structlog.BoundLogger:- """Configure structured logging for the application.- Args:- service_name: Name of the service for logging identification- env: Environment (development/production), affects logging format- quiet_progress_bars: Turn third-party tqdm bars off. False for a process- whose stdout is a user-facing progress stream (the export worker).- """- # Log level from environment; fall back to INFO if invalid.+ """Configure structured logging for the application. Args: service_name: Name of the service+ for logging identification env: Environment (development/production), affects logging format+ quiet_progress_bars: Turn third-party tqdm bars off. False for a process whose stdout is a+ user-facing progress stream (the export worker)."""log_level_name = os.getenv("LOG_LEVEL", "INFO").upper()log_level = getattr(logging, log_level_name, logging.INFO)diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.pyindex e7e205ec2f4..8c7574bf1c6 100644--- a/studio/backend/loggers/handlers.py+++ b/studio/backend/loggers/handlers.py@@ -1,11 +1,8 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Structured logging handlers and middleware.--LoggingMiddleware (request/response logging with timing),-filter_sensitive_data (structlog processor for sanitization), and-get_logger (factory for structured loggers).+"""Structured logging handlers and middleware: LoggingMiddleware (request/response logging with timing),+filter_sensitive_data (structlog processor for sanitization), and get_logger (factory for structured loggers)."""from __future__ import annotations@@ -75,12 +72,11 @@ _QUIET_POLL_PATHS = {"/api/chat/threads/{id}","/api/chat/threads/{id}/forks",}-# The pure-liveness subset: the SPA fires them together in one burst, so they share a single bucket,-# the first logging with its real path and the rest of the window dropping.-# Only this group is shared: the other quiet paths each report on a different subsystem, so they-# keep their own heartbeat.-# Two paths are deliberately NOT here because their latency is worth seeing: /api/health waits on-# hardware detection, and /api/inference/status reads llama.cpp capabilities in an executor.+# The pure-liveness subset: the SPA fires them together in one burst, so they share a single bucket, the first+# logging with its real path and the rest of the window dropping. Only this group is shared: the other quiet paths+# each report on a different subsystem, so they keep their own heartbeat. Two paths are deliberately NOT here+# because their latency is worth seeing: /api/health waits on hardware detection, and /api/inference/status reads+# llama.cpp capabilities in an executor._LIVENESS_POLL_PATHS = frozenset({"/api/auth/status",@@ -137,10 +133,9 @@ _QUIET_SUCCESS_PATHS = {"/api/hub/datasets/download-progress","/api/hub/datasets/active-downloads","/api/hub/datasets/transport-status",- # Boot-burst catalog reads: the SPA refetches these on every auth change and dialog open, and each- # outcome is already visible in the UI.- # syncExternalProvidersFromBackend fetches the pair in one Promise.all, so they always arrive as two- # lines saying the same thing.+ # Boot-burst catalog reads: the SPA refetches these on every auth change and dialog open, and each outcome is+ # already visible in the UI. syncExternalProvidersFromBackend fetches the pair in one Promise.all, so they+ # always arrive as two lines saying the same thing."/api/providers/registry","/api/providers/",# Fetched in the same Promise.all as two routes that keep their access line, so the resync is still@@ -168,11 +163,9 @@ _CHAT_THREAD_PATH_RE = re.compile(r"^/api/chat/threads/(?!$)[^/]+(/forks)?$")def normalize_poll_path(path: str) -> str:- """Collapse a per-resource id so a templated path can join a suppression class.-- Used for classification and the de-duplication bucket only; the emitted line still- carries the real path. One bucket across ids is deliberate, as with the liveness- group: four tabs polling four threads are still one question.+ """Collapse a per-resource id so a templated path can join a suppression class. Used for classification and+ the de-duplication bucket only; the emitted line still carries the real path. One bucket across ids is+ deliberate, as with the liveness group: four tabs polling four threads are still one question."""m = _CHAT_THREAD_PATH_RE.match(path)if m is None:@@ -180,10 +173,9 @@ def normalize_poll_path(path: str) -> str:return _CHAT_THREAD_FORKS if m.group(1) else _CHAT_THREAD_DETAIL-# The log viewer polls these while reading the very file this middleware writes, so unsuppressed-# each poll appends a record the next reads back; _is_redundant_repeat cannot cover it.-# Separate from _QUIET_SUCCESS_PATHS because --verbose must NOT lift this one: the extra noise-# buries the failure the viewer was opened for.+# The log viewer polls these while reading the very file this middleware writes, so unsuppressed each poll+# appends a record the next reads back; _is_redundant_repeat cannot cover it. Separate from _QUIET_SUCCESS_PATHS+# because --verbose must NOT lift this one: the extra noise buries the failure the viewer was opened for._SELF_READ_PATHS = {"/api/settings/debug/logs","/api/settings/debug/logs/sources",@@ -191,11 +183,10 @@ _SELF_READ_PATHS = {def _is_quiet_success(method: str, path: str, status_code: int, pre_auth: bool) -> bool:- """GET-only. Suppress a 2xx poll line that carries no signal, plus a chat list- poll's transient pre-auth 401 (only in the bootstrap window before the first- successful token refresh). Mutations, real (post-refresh) auth failures, and- all other errors always log. --verbose disables the whole suppressor, except- for the log viewer's own reads."""+ """GET-only. Suppress a 2xx poll line that carries no signal, plus a chat list poll's transient pre-auth 401+ (only in the bootstrap window before the first successful token refresh). Mutations, real (post-refresh)+ auth failures, and all other errors always log. --verbose disables the whole suppressor, except for the log+ viewer's own reads."""if method != "GET":return Falseif 200 <= status_code < 300 and path in _SELF_READ_PATHS:@@ -207,14 +198,13 @@ def _is_quiet_success(method: str, path: str, status_code: int, pre_auth: bool)return pre_auth and status_code == 401 and path in _CHAT_LIST_PATHS-# An unhandled request exception is logged twice: here as a structured request_failed event whose-# "exception" field carries the whole traceback (format_exc_info renders it, see-# loggers/config.py), and again by uvicorn on stderr, which the desktop shell mirrors into-# tauri.log at ~90 lines per failure. Keep the structured copy.+# An unhandled request exception is logged twice: here as a structured request_failed event whose "exception"+# field carries the whole traceback (format_exc_info renders it, see loggers/config.py), and again by uvicorn on+# stderr, which the desktop shell mirrors into tauri.log at ~90 lines per failure. Keep the structured copy._UVICORN_ASGI_EXC_MSG = "Exception in ASGI application"-# Set on the exception instance itself rather than a side table: the object is what uvicorn hands-# us, so the match cannot go stale or collide with a recycled id, and an exception raised above-# this middleware (CORS, remote-access, the protocol layer) keeps uvicorn's traceback.+# Set on the exception instance itself rather than a side table: the object is what uvicorn hands us, so the+# match cannot go stale or collide with a recycled id, and an exception raised above this middleware (CORS,+# remote-access, the protocol layer) keeps uvicorn's traceback._LOGGED_EXC_ATTR = "_unsloth_request_failed_logged"@@ -228,9 +218,9 @@ def _mark_exception_logged(exc: BaseException) -> None:class _DropDuplicateAsgiException(logging.Filter):- """Drop uvicorn's "Exception in ASGI application" record when request_failed has- already logged that same exception. Anything else, including a failure that never- reached this middleware, passes through untouched. --verbose keeps both copies."""+ """Drop uvicorn's "Exception in ASGI application" record when request_failed has already logged that same+ exception. Anything else, including a failure that never reached this middleware, passes through untouched.+ --verbose keeps both copies."""def filter(self, record: logging.LogRecord) -> bool:if _VERBOSE_ACCESS_LOG:@@ -247,9 +237,9 @@ class _DropDuplicateAsgiException(logging.Filter):def install_uvicorn_duplicate_exception_filter() -> None:- """Attach the duplicate-traceback filter to uvicorn's error logger. Same- logger-level filter technique as run.py's startup-line rewrite; safe to call more- than once because a second identical install only re-checks the same records."""+ """Attach the duplicate-traceback filter to uvicorn's error logger. Same logger-level filter technique as+ run.py's startup-line rewrite; safe to call more than once because a second identical install only re-checks+ the same records."""logging.getLogger("uvicorn.error").addFilter(_DropDuplicateAsgiException())@@ -267,9 +257,8 @@ class LoggingMiddleware:def _is_redundant_repeat(self, method: str, path: str, query: bytes, status_code: int, now: float) -> bool:- """True if an identical GET/2xx log fired < window ago (query string is part- of the identity). Non-GET/non-2xx never dedup; quiet-poll paths use the longer- heartbeat. Stamps only on emit, so steady polls still log."""+ """True if an identical GET/2xx log fired < window ago (query string is part of the identity). Non-GET/non-2xx+ never dedup; quiet-poll paths use the longer heartbeat. Stamps only on emit, so steady polls still log."""if method != "GET" or not (200 <= status_code < 300):return False# A query makes the request something other than the background poll, so it keeps its own identitydiff --git a/studio/backend/main.py b/studio/backend/main.pyindex 6fc0ccec1ed..5bd36a2e823 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1,10 +1,6 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Main FastAPI application for Unsloth UI Backend-"""-import osimport sysimport threading@@ -17,10 +13,9 @@ from typing import Any, Optionalos.environ["PYTHONWARNINGS"] = "ignore"-# Pin GPU index ordering to PCI bus id before any torch import creates a CUDA context.-# Otherwise torch/CUDA default to FASTEST_FIRST while nvidia-smi (and Unsloth's VRAM-# probes) use PCI-bus order, so an index chosen from nvidia-smi can resolve to a different-# card. setdefault so an override wins; full rationale in utils/hardware/hardware.py.+# Pin GPU index ordering to PCI bus id before any torch import creates a CUDA context. Otherwise torch/CUDA+# default to FASTEST_FIRST while nvidia-smi (and Unsloth's VRAM probes) use PCI-bus order, so an index chosen+# from nvidia-smi can resolve to a different card. setdefault so an override wins; see utils/hardware/hardware.py.os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")# Windows terminals default to the active system code page. Reconfigure stdout/stderr@@ -38,16 +33,14 @@ _SYSTEM_GPU_CACHE_TTL_SECONDS = 10.0_system_gpu_cache_lock = threading.Lock()_system_gpu_cache: Optional[tuple[float, tuple[dict[str, Any], dict[str, Any]]]] = None-# ── Windows AMD ROCm DLL injection ──────────────────────────────────────────-# Python 3.8+ ignores PATH for extension modules; register ROCm bin dirs with-# os.add_dll_directory() so amdhip64.dll etc. are found before any torch import.+# Windows AMD ROCm DLL injection: Python 3.8+ ignores PATH for extension modules, so register ROCm bin+# dirs with os.add_dll_directory() to find amdhip64.dll etc. before any torch import.if sys.platform == "win32":# Module scope: the handle removes the search-path entry when garbage collected._ROCM_DLL_HANDLES: list = []def _add_rocm_dll_dirs() -> None:candidates = []- # 1. HIP_PATH / ROCM_PATH set by the AMD HIP SDK installerfor _var in ("HIP_PATH", "ROCM_PATH"):_val = os.environ.get(_var)if _val:@@ -85,12 +78,10 @@ if sys.platform == "win32":_add_rocm_dll_dirs()del _add_rocm_dll_dirs- # ── Windows AMD ROCm: make hipInfo.exe resolvable for subprocess probes ──- # bitsandbytes' get_rocm_gpu_arch() runs `hipinfo.exe` via PATH at import time; the AMD- # torch wheel ships it in the venv Scripts dir, which is on PATH only when the venv is- # activated -- Unsloth launches python directly. Without this every bitsandbytes import- # logs a scary (harmless) "Could not detect ROCm GPU architecture" error. Gated on the- # file existing, so non-AMD hosts are untouched; subprocess PATH ignores DLL dirs.+ # Windows AMD ROCm: make hipInfo.exe resolvable for subprocess probes. bitsandbytes' get_rocm_gpu_arch()+ # runs `hipinfo.exe` via PATH at import time; the AMD torch wheel ships it in the venv Scripts dir, which is+ # on PATH only when the venv is activated, and Unsloth launches python directly. Gated on the file existing,+ # so non-AMD hosts are untouched; subprocess PATH ignores DLL dirs._scripts_dir = os.path.dirname(sys.executable)if os.path.isfile(os.path.join(_scripts_dir, "hipInfo.exe")):import shutil as _shutil@@ -99,11 +90,10 @@ if sys.platform == "win32":del _shutildel _scripts_dir- # ── Windows AMD ROCm: set BNB_ROCM_VERSION before any bitsandbytes import ─- # bitsandbytes derives the rocm<ver>.dll name from torch.version.hip, but the wheel ships- # rocm72.dll, so the server crashes ("Configured ROCm binary not found") without this.- # Detect the shipped DLL (mirrors worker.py); gate on it rather than torch.version.hip to- # avoid importing torch. Installer-seeded values are defaults; caller values win.+ # Windows AMD ROCm: set BNB_ROCM_VERSION before any bitsandbytes import. bitsandbytes derives the+ # rocm<ver>.dll name from torch.version.hip, but the wheel ships rocm72.dll, so the server crashes+ # ("Configured ROCm binary not found") without this. Detect the shipped DLL (mirrors worker.py); gate on it+ # rather than torch.version.hip to avoid importing torch.if ("BNB_ROCM_VERSION" not in os.environor os.environ.get("UNSLOTH_BNB_ROCM_VERSION_SOURCE") == "sitecustomize"@@ -154,11 +144,9 @@ if sys.platform == "win32":lambda _r: "environment variable detected" not in _r.getMessage())-# ── WSL AMD Strix Halo (gfx1151): enable ROCDXG before any torch import ──────-# In WSL the AMD GPU is reached via the ROCDXG bridge (librocdxg.so over /dev/dxg), which-# HSA loads only when HSA_ENABLE_DXG_DETECTION=1 is set BEFORE torch touches the GPU. A-# worker launched outside a login shell misses the installer's persisted env and falls-# back to CPU. Gated on both /dev/dxg and librocdxg.so, so other platforms no-op.+# WSL AMD Strix Halo (gfx1151): in WSL the AMD GPU is reached via the ROCDXG bridge (librocdxg.so over+# /dev/dxg), which HSA loads only when HSA_ENABLE_DXG_DETECTION=1 is set BEFORE torch touches the GPU. A worker+# launched outside a login shell misses the installer's persisted env and falls back to CPU.elif sys.platform.startswith("linux") and "HSA_ENABLE_DXG_DETECTION" not in os.environ:try:if os.path.exists("/dev/dxg") and any(@@ -201,9 +189,8 @@ import _platform_compat # noqa: F401# unsloth-zoo import below, whose LLAMA_CPP_DEFAULT_DIR binding is import-time.from utils.paths.storage_roots import studio_root as _studio_root-# Same reason, same deadline: unsloth_zoo.compiler reads UNSLOTH_COMPILE_LOCATION-# at import time, and without this a direct start falls back to a CWD-relative-# unsloth_compiled_cache (on Windows that is the user profile).+# Same reason, same deadline: unsloth_zoo.compiler reads UNSLOTH_COMPILE_LOCATION at import time, and+# without this a direct start falls back to a CWD-relative unsloth_compiled_cache.from utils.paths.storage_roots import setup_cache_env as _setup_cache_envtry:@@ -260,11 +247,9 @@ _STUDIO_INSTALL_ID_RE = _re.compile(r"^[0-9a-f]{64}$")def _read_studio_install_id() -> str:- """Per-install opaque id at $STUDIO_HOME/share/studio_install_id.-- Returns "" when absent or not a 64-char lowercase-hex token; then- /api/health emits "" and the launcher accepts any healthy backend.- Carries no install-path info (matters when Unsloth runs -H 0.0.0.0)."""+ """Per-install opaque id at $STUDIO_HOME/share/studio_install_id. Returns "" when absent or not a 64-char+ lowercase-hex token; then /api/health emits "" and the launcher accepts any healthy backend. Carries no+ install-path info (matters when Unsloth runs -H 0.0.0.0)."""try:token = ((_STUDIO_ROOT_RESOLVED / "share" / "studio_install_id")@@ -280,10 +265,8 @@ _STUDIO_ROOT_ID_CACHE: str = _read_studio_install_id()def _studio_root_id() -> str:- """Same-install discriminator for /api/health (cached at import).-- Empty when no installer token is present; the launcher treats "" as- "accept any healthy backend"."""+ """Same-install discriminator for /api/health (cached at import). Empty when no installer token is+ present; the launcher treats "" as "accept any healthy backend"."""return _STUDIO_ROOT_ID_CACHE@@ -293,7 +276,6 @@ if sys.platform == "win32":mimetypes.add_type("application/javascript", ".js")mimetypes.add_type("text/css", ".css")-# Suppress dependency warnings in productionif os.getenv("ENVIRONMENT_TYPE", "production") == "production":warnings.filterwarnings("ignore")@@ -382,9 +364,8 @@ def get_unsloth_version() -> str:except PackageNotFoundError:pass- # Both files: the literal moved to _version.py, and models/_utils.py now holds only a- # re-export, which this prefix scan does not match. Trying both keeps a half-updated- # tree reporting a real version instead of falling through to "dev".+ # Both files: the literal moved to _version.py, and models/_utils.py now holds only a re-export, which+ # this prefix scan does not match. Trying both keeps a half-updated tree reporting a real version.root = _Path(__file__).resolve().parents[2] / "unsloth"for version_file in (root / "_version.py", root / "models" / "_utils.py"):try:@@ -413,9 +394,9 @@ def _load_desktop_owner() -> dict[str, str] | None:_DESKTOP_OWNER = _load_desktop_owner()-# The Tauri desktop app runs the backend locally, so stdio MCP servers are safe ("0" opts-# out). Tracked as an automatic loopback default so publishing a runtime tunnel can suspend-# it without overriding an explicit operator choice.+# The Tauri desktop app runs the backend locally, so stdio MCP servers are safe ("0" opts out). Tracked as an+# automatic loopback default so publishing a runtime tunnel can suspend it without overriding an explicit+# operator choice.if _DESKTOP_OWNER:from utils.host_policy import apply_stdio_mcp_loopback_default as _apply_desktop_stdio_default_apply_desktop_stdio_default("127.0.0.1")@@ -448,17 +429,11 @@ def _start_helper_precache_if_enabled() -> None:def _run_llama_cpp_startup_probes(app: FastAPI) -> None:- """llama.cpp capability (MTP support) + freshness (release age) probes.-- Runs OFF the startup critical path (see _start_llama_cpp_probes_if_enabled).- Both are cached and freshness has a 24h disk TTL, but on a cold/expired cache- the freshness check makes a blocking GitHub request, and on macOS the first- `llama-server --help` exec can stall on Gatekeeper verification -- neither must- ever gate `Application startup complete`. Writes app.state only; nothing reads- those values synchronously at startup (the status routes call- check_prebuilt_freshness directly at request time), so populating them late is- safe.- """+ """llama.cpp capability (MTP support) + freshness (release age) probes, run OFF the startup critical path.+ Both are cached and freshness has a 24h disk TTL, but on a cold/expired cache the freshness check makes+ a blocking GitHub request, and on macOS the first `llama-server --help` exec can stall on Gatekeeper+ verification, and neither must gate `Application startup complete`. Writes app.state only; nothing reads+ those values synchronously at startup."""try:from core.inference.llama_cpp import LlamaCppBackendfrom utils.llama_cpp_freshness import (@@ -497,10 +472,8 @@ def _run_llama_cpp_startup_probes(app: FastAPI) -> None:def _start_llama_cpp_probes_if_enabled(app: FastAPI) -> None:- """Run the llama.cpp startup probes on a daemon thread, off the startup- critical path so they never delay `Application startup complete`. Skipped- entirely when update checks are disabled, so a fully offline boot makes no- background network calls."""+ """Run the llama.cpp startup probes on a daemon thread, off the startup critical path. Skipped entirely+ when update checks are disabled, so a fully offline boot makes no background network calls."""if os.environ.get("UNSLOTH_DISABLE_UPDATE_CHECK") == "1":return@@ -525,13 +498,10 @@ def _post_warm_current_generation() -> int:def _start_post_warm_thread() -> bool:- """Put up a post-warm worker for this lifespan. True iff one was started.-- Starts one even while a previous worker is parked in the warm join. Declining there- left a restart with no worker at all: the old one was alive so this returned early,- then read the shutdown and exited. Generations make the overlap safe -- the stale- worker drops out by itself and a parked thread is free.- """+ """Put up a post-warm worker for this lifespan. True iff one was started. Starts one even while a previous+ worker is parked in the warm join: declining there left a restart with no worker at all, since the old+ one was alive so this returned early, then read the shutdown and exited. Generations make the overlap+ safe."""global _post_warm_thread, _post_warm_generationwith _post_warm_lock:_post_warm_generation += 1@@ -548,23 +518,17 @@ def _start_post_warm_thread() -> bool:def _stop_post_warm_thread() -> None:- """Retire whatever worker is current; never wait for it.-- Joining would hold shutdown for the rest of the ML stack import, the stall this path- exists to avoid. Bumping the generation suffices: the worker re-reads it after its join.- """+ """Retire whatever worker is current; never wait for it. Joining would hold shutdown for the rest of the ML+ stack import, the stall this path exists to avoid; bumping the generation suffices, since the worker+ re-reads it after its join."""global _post_warm_generationwith _post_warm_lock:_post_warm_generation += 1def _post_warm_retired(generation: Optional[int]) -> bool:- """True when this post-warm worker's lifespan has ended. Logs once when it has.-- A mismatch means the application that wanted this work has stopped. The remaining- work imports optional platform or RAG scheduling modules, so none of it may start for- a stopped lifespan.- """+ """True when this post-warm worker's lifespan has ended (logs once when it has). The remaining work imports+ optional platform or RAG scheduling modules, so none of it may start for a stopped lifespan."""if generation is None or _post_warm_current_generation() == generation:return Falseimport structlog as _structlog@@ -596,17 +560,15 @@ def _start_linked_folder_auto_sync(generation: Optional[int]) -> None:def _post_warm_background_work(generation: Optional[int] = None) -> None:- """Platform repair and linked-folder lifecycle work after the coordinated warm.-- MLX repair used to probe the runtime before the socket bound. Joining first keeps that- optional probe out of the login-screen critical path. Linked-folder startup only loads- embeddings when a queued sync has real ingestion work; an idle scheduler stays cold.- """+ """Platform repair and linked-folder lifecycle work after the coordinated warm. MLX repair used to probe the+ runtime before the socket bound; joining first keeps that optional probe out of the login-screen+ critical path. Linked-folder startup only loads embeddings when a queued sync has real ingestion+ work."""# No-op when the warm never started, so this is safe under the kill switch.join_background_warm()- # Shutdown routinely lands while parked in the join above, and everything below imports or- # loads part of the stack. Rechecked before every action; generation is None only in tests.+ # Shutdown routinely lands while parked in the join above, and everything below imports or loads part+ # of the stack. Rechecked before every action; generation is None only in tests.if _post_warm_retired(generation):return@@ -620,9 +582,9 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:except Exception as _mlx_exc:import structlog as _structlog- # Warning, not debug: this decides the MLX verdict on every healthy Apple Silicon- # boot, so a half-applied update (new mlx_repair.py over older hardware.py) arrives- # here and would silently leave Train/Export greyed out for the session.+ # Warning, not debug: this decides the MLX verdict on every healthy Apple Silicon boot, so a half-applied+ # update (new mlx_repair.py over older hardware.py) arrives here and would silently leave Train/Export+ # greyed out for the session._structlog.get_logger(__name__).warning("mlx autorepair skipped: %s", _mlx_exc)if _post_warm_retired(generation):@@ -631,12 +593,9 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:def clear_compiled_cache_unless_shared(app: FastAPI) -> None:- """Clear the compiled cache unless a sibling backend of this install is live.-- The decision lives in cache_cleanup, next to the paths it clears and the lock- that serializes it against a sibling's startup; run_server puts the probe on- app.state because main.py must not import run.py back.- """+ """Clear the compiled cache unless a sibling backend of this install is live. The decision lives in+ cache_cleanup, next to the paths it clears and the lock that serializes it against a sibling's startup;+ run_server puts the probe on app.state because main.py must not import run.py back."""_clear_compiled_cache_unless_shared(getattr(app.state, "live_sibling_backend", None))@@ -652,9 +611,9 @@ async def lifespan(app: FastAPI):_lifespan_log = _structlog.get_logger(__name__)clear_compiled_cache_unless_shared(app)- # Here because both launch paths reach it after the frontend decision: run.py calls- # setup_frontend(), and `uvicorn main:app` bypasses run.py entirely. With no- # catch-all the engine paths match on method alone and answer 405, read as "exists".+ # Here because both launch paths reach it after the frontend decision: run.py calls setup_frontend(), and+ # `uvicorn main:app` bypasses run.py entirely. With no catch-all the engine paths match on method alone and+ # answer 405, read as "exists".if not getattr(app.state, "frontend_mounted", False):try:from routes.llama_compat import add_get_denials@@ -662,17 +621,16 @@ async def lifespan(app: FastAPI):except Exception: # noqa: BLE001 -- never block startup over a discovery route_lifespan_log.warning("could not install API-only probe denials", exc_info = True)- # Move the legacy sandbox up here rather than from the first request: the- # copy can be minutes when the studio home is on another filesystem.+ # Move the legacy sandbox up here rather than from the first request: the copy can be minutes when the+ # studio home is on another filesystem.try:from core.inference.tools import (migrate_legacy_sandbox_in_background,start_sandbox_recovery,)migrate_legacy_sandbox_in_background()- # A tree renamed for deletion by a run that was killed, and the- # workspace deletes it left pending: both waited for the next Python or- # terminal call, which ordinary chat never makes.+ # A tree renamed for deletion by a run that was killed, and the workspace deletes it left pending:+ # both waited for the next Python or terminal call, which ordinary chat never makes.start_sandbox_recovery()except Exception: # noqa: BLE001pass@@ -711,9 +669,9 @@ async def lifespan(app: FastAPI):_lifespan_log.warning("chat generation orphan reconciliation failed: %s", exc)try:- # The boot pass above only settles runs orphaned by the previous process. A run- # that wedges while this one keeps serving needs the same reconciliation on an- # interval, bounded to runs whose progress lease has expired.+ # The boot pass above only settles runs orphaned by the previous process. A run that wedges while this one+ # keeps serving needs the same reconciliation on an interval, bounded to runs whose progress lease has+ # expired.from core.inference.chat_generation_runs import start_lease_sweeperstart_lease_sweeper(app)except Exception as exc:@@ -731,10 +689,9 @@ async def lifespan(app: FastAPI):except Exception as exc:_lifespan_log.warning("Hub manifest compatibility migration failed: %s", exc)- # llama.cpp probes: capability (MTP support) + freshness (release age). Inline they could- # block `Application startup complete` for tens of seconds on macOS (cold GitHub cache,- # Gatekeeper verifying the unsigned binary). Nothing reads them synchronously at startup,- # so run them on a daemon thread; app.state stays None until it populates them.+ # llama.cpp probes: capability (MTP support) + freshness (release age). Inline they could block `Application+ # startup complete` for tens of seconds on macOS (cold GitHub cache, Gatekeeper verifying the unsigned+ # binary). Nothing reads them synchronously at startup.app.state.llama_cpp_capabilities = Noneapp.state.llama_cpp_freshness = None_start_llama_cpp_probes_if_enabled(app)@@ -791,8 +748,8 @@ async def lifespan(app: FastAPI):None if _suppress_bootstrap else storage.get_bootstrap_password())- # Last, so it never contends for the GIL: the socket binds as soon as this returns, so the- # login screen is up while torch/transformers/datasets load.+ # Last, so it never contends for the GIL: the socket binds as soon as this returns, so the login+ # screen is up while torch/transformers/datasets load.start_background_warm()_start_post_warm_thread()@@ -800,9 +757,8 @@ async def lifespan(app: FastAPI):"lifespan startup completed in %.1fms",(_time.perf_counter() - _lifespan_started) * 1000,)- # Persist only terminal scalar usage from authenticated third-party API- # requests. The monitor itself stays storage-agnostic until the production- # lifespan is ready, which keeps imports and unit tests deterministic.+ # Persist only terminal scalar usage from authenticated third-party API requests. The monitor stays+ # storage-agnostic until the production lifespan is ready, which keeps imports and unit tests deterministic.from core.inference.api_monitor import api_monitor as _api_monitorfrom storage.api_usage_db import (acquire_api_usage_writer as _acquire_api_usage_writer,@@ -814,17 +770,16 @@ async def lifespan(app: FastAPI):_api_usage_callback_lease = _api_monitor.acquire_terminal_callback(_enqueue_api_usage)yield- # Remove only this lifespan's callback. A concurrently live sibling keeps- # both the monitor sink and the shared serialized writer. The final owner- # drains accepted receipts off the event loop before stopping the worker.+ # Remove only this lifespan's callback. A concurrently live sibling keeps both the monitor sink and the+ # shared serialized writer; the final owner drains accepted receipts off the event loop before stopping the+ # worker._api_monitor.release_terminal_callback(_api_usage_callback_lease)# Before any shutdown await: a warm finishing during one would still read the lifespan as current._stop_post_warm_thread()- # Retire the coordinated warm at shutdown entry too. run_lifespan_shutdown() repeats- # this after cleanup, but its awaits would otherwise let startup imports continue for- # a lifespan that has already stopped.+ # Retire the coordinated warm at shutdown entry too. run_lifespan_shutdown() repeats this after+ # cleanup, but its awaits would otherwise let startup imports continue for a stopped lifespan._invalidate_detection = getattr(_hw_module, "invalidate_detection", None)if _invalidate_detection is not None:_invalidate_detection()@@ -879,9 +834,8 @@ app = FastAPI(version = UNSLOTH_VERSION,description = "Backend API for Unsloth UI - Training and Model Management",lifespan = lifespan,- # Swagger UI and ReDoc are re-registered below on these same paths, against vendored- # assets instead of a CDN. FastAPI's built-ins point at cdn.jsdelivr.net, and this origin- # holds the auth tokens, so nothing third-party may execute here.+ # Swagger UI and ReDoc are re-registered below on these same paths, against vendored assets instead of+ # a CDN: FastAPI's built-ins point at cdn.jsdelivr.net, and this origin holds the auth tokens.docs_url = None,redoc_url = None,swagger_ui_oauth2_redirect_url = None,@@ -962,10 +916,9 @@ def _build_csp(script_nonce: "str | None" = None, *, docs: bool = False) -> str:worker_src = "worker-src 'self'"font_src = "font-src 'self' data:"if docs:- # script-src is deliberately untouched: the docs bundles are served from this origin- # and their inline init runs off the nonce. What is left cannot execute script, only- # style and lay out the page. ReDoc's Google Fonts sheet pulls faces from gstatic, and- # its search index runs in a worker it builds from a blob.+ # script-src is deliberately untouched: the docs bundles are served from this origin and their inline init+ # runs off the nonce. ReDoc's Google Fonts sheet pulls faces from gstatic, and its search index runs in a+ # worker it builds from a blob.style_src += f" {_DOCS_FONT_CSS}"font_src += f" {_DOCS_FONT_FILES}"worker_src += " blob:"@@ -1005,12 +958,8 @@ def _build_csp(script_nonce: "str | None" = None, *, docs: bool = False) -> str:class SecurityHeadersMiddleware:- """Set baseline security headers; splice per-response inline-script nonces into CSP.-- Pure ASGI (not BaseHTTPMiddleware) so streaming responses are not wrapped in- an anyio stream. Header logic mirrors the prior version exactly via- MutableHeaders on the response-start message.- """+ """Set baseline security headers; splice per-response inline-script nonces into CSP. Pure ASGI (not+ BaseHTTPMiddleware) so streaming responses are not wrapped in an anyio stream."""def __init__(self, app):self.app = app@@ -1055,13 +1004,11 @@ class SecurityHeadersMiddleware:app.add_middleware(SecurityHeadersMiddleware)-# Swagger UI and ReDoc, on FastAPI's own paths but served entirely from this origin.-# FastAPI's built-in pages load ~2.3 MB of JavaScript from cdn.jsdelivr.net and start it with-# an inline script. localStorage is origin-scoped, not path-scoped, so anything running on-# /docs can read the Unsloth tokens session.ts keeps there and call the API as that user. The-# bundles are vendored under assets/docs_ui (pinned + digest-checked by-# tests/test_docs_ui_assets.py) and the inline init runs off the same per-response nonce the-# bootstrap script uses, so script-src stays 'self' and works offline as a bonus.+# Swagger UI and ReDoc, on FastAPI's own paths but served entirely from this origin. FastAPI's built-in pages+# load ~2.3 MB of JavaScript from cdn.jsdelivr.net and start it with an inline script, and localStorage is+# origin-scoped, not path-scoped, so anything running on /docs can read the Unsloth tokens session.ts keeps+# there and call the API as that user. The bundles are vendored under assets/docs_ui (pinned + digest-checked by+# tests/test_docs_ui_assets.py) and the inline init runs off the same per-response nonce as the bootstrap script.import secrets as _secrets_for_docs # noqa: E402from fastapi.openapi.docs import ( # noqa: E402get_redoc_html,@@ -1093,11 +1040,9 @@ if _DOCS_ASSETS_DIR.is_dir():)def _docs_url(request: Request, path: str) -> str:- """Prefix with the mount point, as FastAPI's own docs routes do.-- Behind a path-stripping proxy (or `uvicorn --root-path`) the browser sees the prefix- the server never does, so an unprefixed URL escapes the mapping and 404s.- """+ """Prefix with the mount point, as FastAPI's own docs routes do. Behind a path-stripping proxy (or+ `uvicorn --root-path`) the browser sees the prefix the server never does, so an unprefixed URL+ escapes the mapping and 404s."""return f"{request.scope.get('root_path', '').rstrip('/')}{path}"@app.get("/docs", include_in_schema = False)@@ -1189,11 +1134,10 @@ _BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS = (*_STT_MULTIPART_UPLOAD_PATHS,*_VIDEO_MULTIPART_UPLOAD_PATHS,)-# Which of those may arrive with no Content-Length and be counted instead of refused.-# Deliberately NOT the whole set above: this middleware runs before authentication, and-# a counted body is a held body, so the dataset path (whose cap is the configurable-# upload limit, up to 8 GB) and the 25 MB stt paths keep their 411. The videos-# reference image is bounded at 32 MB, the same order as the default protected cap.+# Which of those may arrive with no Content-Length and be counted instead of refused. Deliberately NOT the+# whole set above: this middleware runs before authentication, and a counted body is a held body, so the dataset+# path (whose cap is the configurable upload limit, up to 8 GB) and the 25 MB stt paths keep their 411. The+# videos reference image is bounded at 32 MB._CHUNKED_UPLOAD_EXACT_PATHS = _VIDEO_MULTIPART_UPLOAD_PATHS@@ -1452,12 +1396,9 @@ app.add_middleware(# allow_headers is the REQUEST side; a response header is unreadable to JS unless# exposed, and Studio is cross-origin from tauri://localhost and tunnels.expose_headers = ["X-Unsloth-Conflict-Kind"],- # is_allowed_origin closes the moment the tunnel URL clears, but a preflight- # already cached by the browser does not. Measured in WebKit: with Starlette's- # 600s default, a state-changing request still REACHED the server after remote- # access was stopped (Chromium/Firefox/Edge re-preflighted). Keep the stale- # window short so revocation is nearly as immediate as every other trust- # signal here.+ # is_allowed_origin closes the moment the tunnel URL clears, but a preflight already cached by the browser+ # does not. Measured in WebKit: with Starlette's 600s default, a state-changing request still REACHED the+ # server after remote access was stopped. Keep the stale window short.max_age = 60,)@@ -1469,9 +1410,6 @@ from utils.remote_access_settings import RemoteAccessStopResponseMiddleware # napp.add_middleware(RemoteAccessStopResponseMiddleware)--# ============ Register API Routes ============-app.include_router(auth_router, prefix = "/api/auth", tags = ["auth"])app.include_router(training_router, prefix = "/api/train", tags = ["training"])app.include_router(models_router, prefix = "/api/models", tags = ["models"])@@ -1491,12 +1429,10 @@ app.include_router(video_router, prefix = "/api/inference", tags = ["inference"]app.include_router(video_openai_router, prefix = "/api/inference", tags = ["inference"])app.include_router(video_openai_router, prefix = "/v1", tags = ["openai-compat"])-# OpenAI-compatible: mount the inference router at /v1 for external tools.app.include_router(inference_router, prefix = "/v1", tags = ["openai-compat"])-# llama-server / Ollama discovery probes. Declares its own full paths (/props,-# /version, /api/tags, ...) so it needs no prefix, and must be registered here ---# ahead of the SPA catch-all in serve_frontend() -- or /props and /version go on-# resolving to index.html with a 200.+# llama-server / Ollama discovery probes. Declares its own full paths (/props, /version, /api/tags, ...) so it+# needs no prefix, and must be registered ahead of the SPA catch-all in serve_frontend() or /props and /version+# go on resolving to index.html with a 200.app.include_router(llama_compat_router, tags = ["openai-compat"])app.include_router(preview_router, prefix = "/p", tags = ["preview"])app.include_router(providers_router, prefix = "/api/providers", tags = ["providers"])@@ -1523,35 +1459,24 @@ app.include_router(youtube_router, prefix = "/api/youtube", tags = ["youtube"])# Re-wrap /v1/* client errors into OpenAI/Anthropic envelopes; non-/v1 keeps {"detail": ...}.install_api_error_handlers(app)--# ============ Health and System Endpoints ============--# /api/health has a hard deadline: preflight/backend.rs probes it with a 2s timeout right-# after TAURI_PORT is emitted, and a timeout is not retried -- it falls through to-# "desktop_owned_backend_starting", a dead end the user must clear by hand.-# A target, not a guarantee: the wait polls on the event loop and a C-extension import can-# hold the GIL past it. 1.5s measured a 1.742s worst case (0.26s margin); 1.0s buys one-# extra provisional reply, and only the web UI reads chat_only anyway.+# /api/health has a hard deadline: preflight/backend.rs probes it with a 2s timeout right after TAURI_PORT is+# emitted, and a timeout is not retried, falling through to "desktop_owned_backend_starting", a dead end the+# user must clear by hand. A target, not a guarantee: the wait polls on the event loop and a C-extension import+# can hold the GIL past it. 1.5s measured a 1.742s worst case; 1.0s buys one extra provisional reply._HEALTH_DETECT_BUDGET_S = 1.0async def _await_hardware_detection(budget: float) -> bool:- """Wait up to ``budget`` seconds for DEVICE to be set. True iff it is.-- Polls on the event loop instead of awaiting ensure_hardware_detected() in a thread:- asyncio.wait_for cannot cancel a to_thread, so a timed-out call holds the executor slot- for the rest of the import and a polled endpoint would drain the pool. Detection runs on- the warm thread, or the one start_background_detection() puts up.-- Returns False without kicking anything when the warm is switched off. Health is probed- automatically (desktop preflight, the frontend's first fetch), so kicking detection here- would import torch on every such host and the switch would buy nothing. The provisional- answer ships instead and the first hardware-dependent operation detects.- """+ """Wait up to ``budget`` seconds for DEVICE to be set. True iff it is. Polls on the event loop+ instead of awaiting ensure_hardware_detected() in a thread: asyncio.wait_for cannot cancel a+ to_thread, so a timed-out call holds the executor slot for the rest of the import and a polled+ endpoint would drain the pool. Returns False without kicking anything when the warm is switched+ off. Health is probed automatically, so kicking detection here would import torch on every such+ host and the switch would buy nothing."""if os.environ.get(DISABLE_ENV_VAR) == "1":return _hw_module.DETECTION_COMPLETE.is_set() and _hw_module.DEVICE is not None- # The event AND DEVICE: branches assign DEVICE and keep probing, and shutdown clears- # DEVICE then the event, so event-set-with-DEVICE-None would serve a torn-down verdict.+ # The event AND DEVICE: branches assign DEVICE and keep probing, and shutdown clears DEVICE then the+ # event, so event-set-with-DEVICE-None would serve a torn-down verdict.if _hw_module.DETECTION_COMPLETE.is_set() and _hw_module.DEVICE is not None:return Truestart_background_detection()@@ -1565,28 +1490,22 @@ async def _await_hardware_detection(budget: float) -> bool:def _hardware_snapshot() -> Optional[tuple[bool, Optional[str], Optional[str]]]:- """``(chat_only, chat_only_reason, chat_only_detail)`` if detection is settled, else ``None``.-- A seqlock read rather than ``_DETECT_LOCK``: that lock would park the endpoint for the- whole torch import, the stall this startup path removes. A forced re-detect clears the- event on the way in and bumps the generation before setting it again, so a read bracketed- by both lands wholly before or after one pass, never mid-pass where CHAT_ONLY is back to- True and the reason to None.-- That middle must not be published: config/env.ts caches the first reply carrying- `device_type` as authoritative, and the sidebar's recovery poll runs only while it reads- `chat_only_reason == "mlx_unavailable"`, so one such reply hides Train for the session.- """+ """``(chat_only, chat_only_reason, chat_only_detail)`` if detection is settled, else ``None``. A+ seqlock read rather than ``_DETECT_LOCK``: that lock would park the endpoint for the whole torch+ import. A forced re-detect clears the event on the way in and bumps the generation before+ setting it again, so a read bracketed by both lands wholly before or after one pass, never+ mid-pass where CHAT_ONLY is back to True and the reason to None. That middle must not be+ published: config/env.ts caches the first reply carrying `device_type` as authoritative, and the+ sidebar's recovery poll runs only while it reads `chat_only_reason == "mlx_unavailable"`."""for _ in range(3):if not _hw_module.DETECTION_COMPLETE.is_set():return Nonegeneration = _hw_module.DETECTION_GENERATIONdevice = _hw_module.DEVICEchat_only = bool(_hw_module.CHAT_ONLY)- # Refreshed, not the frozen global: the three inventory-sensitive verdicts can change- # after startup (an eGPU attached, a driver that finished restarting). Reason and detail- # come back together, or a forced re-detect starting in between would pair this reply's- # reason with a detail from a different pass.+ # Refreshed, not the frozen global: the three inventory-sensitive verdicts can change after startup (an eGPU+ # attached, a driver that finished restarting). Reason and detail come back together, or a forced re-detect+ # starting in between would pair this reply's reason with a detail from another pass.try:reason, detail = _hw_module.current_chat_only_verdict()except Exception:@@ -1601,33 +1520,21 @@ def _hardware_snapshot() -> Optional[tuple[bool, Optional[str], Optional[str]]]:return None-# How long a self-heal that has not started yet may keep holding a verdict back once the-# warm that schedules it is over. start_mlx_autorepair_if_needed() runs in-# _post_warm_background_work, immediately after join_background_warm(), so the handoff is-# the gap this covers; the warm itself is covered by _torch_warm_in_progress(), which is-# minutes on a cold Mac and cannot be replaced by any fixed number.+# How long a self-heal that has not started yet may keep holding a verdict back once the warm that schedules+# it is over. start_mlx_autorepair_if_needed() runs immediately after join_background_warm(), so the handoff is+# the gap this covers; the warm itself is covered by _torch_warm_in_progress()._MLX_PRESTART_GRACE_AFTER_WARM_S = 30.0-# Absolute backstop, measured from the first hold. _torch_warm_in_progress() goes false when-# the warm thread dies for any reason, but a warm parked forever inside an import never-# does, and "the scheduler is still coming" would then be a permanent answer: Train and-# Video would spin for the whole session instead of settling into the greyed state a broken-# MLX stack has genuinely earned. Well above the warm's own worst case, since firing this on-# a healthy boot would reintroduce the bug the hold exists to fix.+# Absolute backstop, measured from the first hold. _torch_warm_in_progress() goes false when the warm thread+# dies for any reason, but a warm parked forever inside an import never does, and "the scheduler is still+# coming" would then be a permanent answer. Well above the warm's own worst case._MLX_PRESTART_CEILING_S = 900.0_MLX_PRESTART_LOCK = threading.Lock()-# (detection generation, first hold, first tick the warm was seen STOPPED, None while it-# runs). Keyed by generation because detection is not once-per-process: a re-detect that-# republishes mlx_unavailable is a new verdict and gets its own window rather than-# inheriting a spent one. Guarded rather than atomic only because the three move together.-#-# The third field is when the warm was first seen stopped, not when it was last seen-# running, because nothing guarantees a health request lands near the end of the warm. The-# final stages are C-extension imports that hold the GIL for seconds at a time, so requests-# queue behind them and the next one served can be the first in a minute. Measuring the-# grace from the last observed poll would then start it in the past and expire it before-# the handoff it exists to cover, publishing the mlx_unavailable verdict the frontend-# stores as final -- the exact bug this hold prevents.+# (detection generation, first hold, first tick the warm was seen STOPPED, None while it runs). Keyed by+# generation because detection is not once-per-process: a re-detect that republishes mlx_unavailable is a new+# verdict and gets its own window. The third field is when the warm was first seen stopped, not when it was last+# seen running, because the final stages are C-extension imports that hold the GIL for seconds at a time, so+# measuring the grace from the last observed poll would start it in the past and expire it before the handoff._mlx_prestart_hold: Optional[tuple[int, float, Optional[float]]] = None# Indirected so tests can drive the windows without sleeping through them.@@ -1661,22 +1568,13 @@ def _mlx_prestart_hold_ok(generation: int) -> bool:def _superseded_by_mlx_repair(snapshot: Optional[tuple[bool, Optional[str]]]) -> bool:- """True when the MLX self-heal is about to replace this settled verdict.-- Scoped to /api/health rather than folded into ``_hardware_snapshot()``: the launcher's- watchdog reads /api/liveness and holds its startup grace open while hardware_detecting- is set, so a 15-minute reinstall must not stretch that grace. Only the UI reads- chat_only, and only the UI has a row to grey out on it.-- Bounded, never open-ended. A live worker holds the verdict for as long as its install- takes, capped by mlx_repair._WORKER_BUDGET_S: the repair's own subprocess timeout plus- an allowance for the post-install imports that verify it, which are not themselves- timed, so a worker parked in one cannot hold the verdict for the rest of the process.- A repair that has not started yet is only a promise, and this is where that promise- expires: the scheduler runs after the warm, so the hold lasts while the warm does and- a short handoff beyond it, under an absolute ceiling for the warm that never ends.- Past that the verdict settles exactly as it did before any of this existed.- """+ """True when the MLX self-heal is about to replace this settled verdict. Scoped to /api/health+ rather than folded into ``_hardware_snapshot()``: the launcher's watchdog reads /api/liveness+ and holds its startup grace open while hardware_detecting is set, so a 15-minute reinstall must+ not stretch that grace. Bounded, never open-ended. A live worker holds the verdict for as long+ as its install takes, capped by mlx_repair._WORKER_BUDGET_S. A repair that has not started yet+ is only a promise, and this is where that promise expires: the hold lasts while the warm does+ and a short handoff beyond it, under an absolute ceiling for the warm that never ends."""if snapshot is None:return Falseif not _hw_module.verdict_pending_mlx_repair(snapshot[0], snapshot[1]):@@ -1694,27 +1592,17 @@ def _superseded_by_mlx_repair(snapshot: Optional[tuple[bool, Optional[str]]]) ->def _torch_warm_in_progress() -> bool:- """True while the coordinated warm thread is still working through its stages.-- A separate field from ``hardware_detecting`` on purpose, rather than widening that one.- Hardware detection is only ``_STAGES[0]``; inference_backend, transformers, and datasets- run after it, and those C-extension imports can hold the GIL- for seconds at a time. A launcher ending its startup grace on ``hardware_detecting``- alone ends it with the expensive half of the warm still ahead of it, which is the window- the grace exists for. But that marker also means "this hardware verdict is provisional,- re-read it", and config/hardware-verdict.ts keeps the UI provisional and polling while it- is set, so keeping it lit through datasets would hide Train for the whole warm over a- verdict that settled seconds in. Two meanings, two fields.-- A snapshot read of module state, no lock and no wait, so /api/liveness stays cheap.-- False whenever no warm thread is running, which is what keeps the deferred case working:- with UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 the warm never starts, and one retired mid-stage- by a shutdown never finishes. Neither will ever set ``finished``, so deriving this from- "not finished" would report warming forever and hold the launcher's startup grace open- until it expired on its own. Absence therefore covers both "warm is over" and "no warm is- coming", and the field needs no deferred companion of its own.- """+ """True while the coordinated warm thread is still working through its stages. A separate field+ from ``hardware_detecting`` on purpose. Hardware detection is only ``_STAGES[0]``;+ inference_backend, transformers and datasets run after it, and those C-extension imports can+ hold the GIL for seconds at a time, so a launcher ending its startup grace on+ ``hardware_detecting`` alone ends it with the expensive half of the warm still ahead. But that+ marker also means "this hardware verdict is provisional, re-read it", and+ config/hardware-verdict.ts keeps the UI provisional and polling while it is set, so keeping it+ lit through datasets would hide Train for the whole warm. Two meanings, two fields. False+ whenever no warm thread is running, which keeps the deferred case working: with+ UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 the warm never starts, and one retired mid-stage by a+ shutdown never finishes, so deriving this from "not finished" would report warming forever."""status = warm_status()return bool(status["started"] and not status["finished"] and status["alive"])@@ -1744,16 +1632,10 @@ def _media_generation_active() -> bool:def _inference_active() -> bool:- """True while at least one generation is in flight.-- Published so the desktop health watchdog can tell a backend that is busy serving from- one that has died: a saturated host can stall the event loop past a probe budget, and- killing there ends a response the user is still waiting on.-- A len() under a threading.Lock held only for that read, plus a bool off each resident- media backend, so the route stays cheap. Failures report "not busy", the same answer as- before this field existed.- """+ """True while at least one generation is in flight, published so the desktop health watchdog can tell a+ backend that is busy serving from one that has died: a saturated host can stall the event loop past a+ probe budget, and killing there ends a response the user is still waiting on. Failures report "not+ busy"."""try:from state import active_generationsif active_generations.count() > 0:@@ -1778,20 +1660,16 @@ async def liveness_check():"studio_root_id": _studio_root_id(),**({"desktop_owner": owner} if (owner := _desktop_owner()) else {}),}- # Same unsettled markers /api/health publishes, and for the desktop health watchdog they- # are the point of the route: it probes liveness every 15s and holds its startup grace- # period open until a reply says the warm-up is over, because the warm thread's- # `import torch` holds the GIL and can stall the next probes on a healthy process.- # The watchdog reads torch_warm_in_progress for that, not hardware_detecting: later- # transformers and datasets stages can also hold the GIL after detection settles.- # Both are non-blocking reads of module-level state, so unlike health this neither starts- # detection nor waits on it and the route stays cheap.+ # Same unsettled markers /api/health publishes, and for the desktop health watchdog they are the point of the+ # route: it probes liveness every 15s and holds its startup grace open until a reply says the warm-up is+ # over, because the warm thread's `import torch` holds the GIL. The watchdog reads torch_warm_in_progress for+ # that, not hardware_detecting: later transformers and datasets stages can also hold the GIL after detection+ # settles. Both are non-blocking reads of module-level state.if _torch_warm_in_progress():alive["torch_warm_in_progress"] = True- # Startup is not the only window where a healthy backend can miss probes: an- # oversubscribed host generating on every slot stalls this loop the same way, long- # after the warm is over. The watchdog widens its failure budget on this marker- # rather than ending a stream that is still producing tokens.+ # Startup is not the only window where a healthy backend can miss probes: an oversubscribed host generating+ # on every slot stalls this loop the same way. The watchdog widens its failure budget on this marker rather+ # than ending a stream that is still producing tokens.if _inference_active():alive["inference_active"] = Trueif _hardware_snapshot() is None:@@ -1817,10 +1695,9 @@ async def health_check(request: Request):await _await_hardware_detection(_HEALTH_DETECT_BUDGET_S)# Snapshot, not a bare global read: a forced re-detect can start at any moment.snapshot = _hardware_snapshot()- # A chat-only verdict the MLX self-heal is about to overturn is not an answer yet. Hold it- # back and keep replying provisionally, or the Mac gets Train greyed out under a tooltip the- # reinstall makes wrong minutes later. Video does not wait on this: it runs on Metal without- # MLX, so it reads /api/system/hardware instead.+ # A chat-only verdict the MLX self-heal is about to overturn is not an answer yet. Hold it back and keep+ # replying provisionally, or the Mac gets Train greyed out under a tooltip the reinstall makes wrong minutes+ # later. Video does not wait on this: it runs on Metal without MLX.mlx_repairing = _superseded_by_mlx_repair(snapshot)if mlx_repairing:snapshot = None@@ -1884,10 +1761,9 @@ async def health_check(request: Request):platform_map = {"darwin": "mac", "win32": "windows", "linux": "linux"}device_type = platform_map.get(sys.platform, sys.platform)- # Alongside device_type, not folded into it: "mac" is every Darwin host, and an Intel- # Mac with a discrete GPU spills to system RAM like a PC while Apple Silicon has one- # pool and nowhere to spill. The UI words its memory warnings from this. Same gate the- # Metal context budget uses, and a pure platform check, so a health poll pays nothing.+ # Alongside device_type, not folded into it: "mac" is every Darwin host, and an Intel Mac with a discrete GPU+ # spills to system RAM like a PC while Apple Silicon has one pool and nowhere to spill. Same gate the Metal+ # context budget uses, and a pure platform check, so a health poll pays nothing.from utils.hardware import is_apple_siliconauthed = {@@ -1903,11 +1779,9 @@ async def health_check(request: Request):# Why chat_only is set; fingerprints the host, so keep it authed. One snapshot for all three.authed["chat_only"] = snapshot[0]authed["chat_only_reason"] = snapshot[1]- # What specifically blocked that reason, when detection recorded one. Only the MLX- # gate does today, and only because it is all-or-nothing: without it the greyed-out- # Train row can only say "run `unsloth studio update`", which is no help to someone- # whose update has already run and left one package behind. From the snapshot, so it- # cannot come from a different detection pass than the reason beside it.+ # What specifically blocked that reason, when detection recorded one. Only the MLX gate does today, and only+ # because it is all-or-nothing: without it the greyed-out Train row can only say "run `unsloth studio+ # update`". From the snapshot, so it cannot come from a different detection pass than the reason beside it.authed["chat_only_detail"] = snapshot[2]authed["device_type"] = device_typeauthed["apple_silicon"] = is_apple_silicon()@@ -1915,14 +1789,12 @@ async def health_check(request: Request):authed.pop("hardware_detecting", None)# Same for the deferred marker: the client reads it first and would keep the old reason.authed.pop("hardware_detection_deferred", None)- # torch_warm_in_progress deliberately survives. It does not qualify the verdict below;- # a settled verdict is exactly the state where the warm has finished stage one and is- # off importing transformers, and dropping it here would hand the watchdog the same- # too-early "startup is over" this field exists to replace.+ # torch_warm_in_progress deliberately survives: it does not qualify the verdict below, and dropping it+ # here would hand the watchdog the same too-early "startup is over" this field exists to replace.else:- # A re-detect started during the bearer await and base carries no chat_only_reason, so a- # client reading this as measured would store reason null and stop the sidebar's recovery- # poll. Mark provisional and omit device_type: env.ts treats it as authoritative.+ # A re-detect started during the bearer await and base carries no chat_only_reason, so a client reading this+ # as measured would store reason null and stop the sidebar's recovery poll. Mark provisional and omit+ # device_type: env.ts treats it as authoritative.authed["hardware_detecting"] = Trueif mlx_repairing:# base was built before the repair was noticed, so drop a marker that now@@ -2061,11 +1933,9 @@ def _get_cached_system_gpu_info()enriched_devices.append(enriched_dev)- # The tile divides the aggregate by the SUMMED per-device totals, so both must- # describe the same cards. The two probes enumerate independently: visibility- # drops a device whose mem_get_info raises, the aggregate side reads torch- # properties only and keeps it. A device in one and not the other inflates the- # percentage and floors free at 0, so identical index sets only (#7452).+ # The tile divides the aggregate by the SUMMED per-device totals, so both must describe the same cards. The+ # two probes enumerate independently: visibility drops a device whose mem_get_info raises, the aggregate+ # side keeps it, and a device in one and not the other inflates the percentage and floors free at 0 (#7452).aggregate_basis_matches = metrics_match and {d.get("index") for d in utilization_info.get("devices", [])} == {d.get("index") for d in enriched_devices}@@ -2089,9 +1959,8 @@ def _get_cached_system_gpu_info(logger.debug(f"Could not resolve gpu_ids support: {e}")llama_uses_vulkan = Falsegpu_ids_supported = True- # The spread also carries `physical_devices` and `mismatch`: GPUs the OS sees that this PyTorch- # cannot open (#8473). They stay their own fields, because `devices` below is the runtime-usable- # list that model fit budgets against and the training device picker pins from.+ # The spread also carries `physical_devices` and `mismatch`: GPUs the OS sees that this PyTorch cannot+ # open (#8473). They stay their own fields, because `devices` below is the runtime-usable list.gpu_info = {**visibility_info,"available": visibility_info.get("available", False),@@ -2105,9 +1974,9 @@ def _get_cached_system_gpu_info(else None,}- # Keep inference placement separate on train-capable hosts where a forced Vulkan llama.cpp- # bundle can enumerate a different device set. If Vulkan is installed but its probe fails,- # retain the unavailable Vulkan shape instead of budgeting GPUs llama.cpp cannot use.+ # Keep inference placement separate on train-capable hosts where a forced Vulkan llama.cpp bundle can+ # enumerate a different device set. If Vulkan is installed but its probe fails, retain the unavailable+ # Vulkan shape instead of budgeting GPUs llama.cpp cannot use.if visibility_info.get("backend") == "vulkan":gpu_info["gguf_gpu_ids_supported"] = bool(enriched_devices)inference_gpu_info = gpu_info@@ -2220,7 +2089,6 @@ def get_system_info("gpu": gpu_info,"inference_gpu": inference_gpu_info,"ml_packages": ml_packages,- # Export capability + torch-aware reason. See /api/system/hardware.**export_capability(),# Video capability + reason, same shape. Additive: older clients ignore the extra keys.**video_capability(),@@ -2265,9 +2133,9 @@ def get_hardware_info(if include_details:from utils.llama_cpp_update import get_installed_llama_version- # All backend-visible GPUs (respects CUDA_VISIBLE_DEVICES); get_gpu_summary reports only- # the primary. Sort by visible_ordinal: the nvidia-smi path returns physical order, so a- # reordering CUDA_VISIBLE_DEVICES (e.g. "5,3") would mislabel by array index.+ # All backend-visible GPUs (respects CUDA_VISIBLE_DEVICES); get_gpu_summary reports only the primary. Sort by+ # visible_ordinal: the nvidia-smi path returns physical order, so a reordering CUDA_VISIBLE_DEVICES (e.g.+ # "5,3") would mislabel by array index.devices = get_backend_visible_gpu_info().get("devices", [])body["gpus"] = [{"name": d.get("name"), "vram_total_gb": d.get("memory_total_gb")}@@ -2277,26 +2145,18 @@ def get_hardware_info(return body-# ============ Serve Frontend (Optional) ============--def _strip_crossorigin(html_bytes: bytes) -> bytes:- """Remove ``crossorigin`` attributes from script/link tags.-- Vite's default ``crossorigin`` forces CORS mode on font loads, which- Firefox HTTPS-Only Mode breaks over plain HTTP; stripping it makes them- same-origin fetches that work on any protocol.- """+ """Remove ``crossorigin`` attributes from script/link tags. Vite's default ``crossorigin`` forces+ CORS mode on font loads, which Firefox HTTPS-Only Mode breaks over plain HTTP."""html = html_bytes.decode("utf-8")html = _re.sub(r'\s+crossorigin(?:="[^"]*")?', "", html)return html.encode("utf-8")def _inject_bootstrap(html_bytes: bytes, app: FastAPI):- """Inject bootstrap credentials when password change is pending.- Returns ``(html_bytes, script_nonce_or_None)``; callers forward the nonce- via ``_CSP_SCRIPT_NONCE_HEADER`` so CSP allows the inline script.- """+ """Inject bootstrap credentials when password change is pending. Returns+ ``(html_bytes, script_nonce_or_None)``; callers forward the nonce via+ ``_CSP_SCRIPT_NONCE_HEADER`` so CSP allows the inline script."""import json as _jsonimport secrets as _secrets@@ -2324,12 +2184,10 @@ _DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}def _canonical_origin(scheme: str, netloc: str) -> Optional[tuple[str, str, int]]:- """Canonicalise an Origin to ``(scheme, host, port)`` for equality.- Browsers strip default ports (RFC 6454 sec 6.1) and scheme/host are- case-insensitive (RFC 3986), so a bare string compare misclassifies- same-origin requests as cross-origin. Returns ``None`` on unparseable input- so callers fall to the safer cross-origin default.- """+ """Canonicalise an Origin to ``(scheme, host, port)`` for equality. Browsers strip default ports (RFC 6454+ sec 6.1) and scheme/host are case-insensitive (RFC 3986), so a bare string compare misclassifies+ same-origin requests as cross-origin. Returns ``None`` on unparseable input so callers fall to the safer+ cross-origin default."""scheme = (scheme or "").strip().lower()if not scheme or not netloc:return None@@ -2376,9 +2234,8 @@ def _is_loopback_ip(host: Optional[str]) -> bool:return ip.is_loopback or (mapped is not None and mapped.is_loopback)-# A loopback peer carrying any of these is a proxy/tunnel relaying a remote client, so the-# peer is the proxy, not the caller: cloudflared sets cf-connecting-ip, reverse proxies set-# the rest (uvicorn only consumes x-forwarded-for, so the others survive to here).+# A loopback peer carrying any of these is a proxy/tunnel relaying a remote client, so the peer is the+# proxy, not the caller: cloudflared sets cf-connecting-ip, reverse proxies set the rest._PROXIED_CLIENT_HEADERS = ("cf-connecting-ip","forwarded",@@ -2389,11 +2246,8 @@ _PROXIED_CLIENT_HEADERS = (def _host_header_is_loopback(host_header: Optional[str]) -> bool:- """Loopback/localhost check on the raw Host header.-- Reads the header directly so a malformed or absent Host cannot fall back to- ``request.url.hostname``'s (loopback) ASGI server address.- """+ """Loopback/localhost check on the raw Host header, read directly so a malformed or absent Host+ cannot fall back to ``request.url.hostname``'s (loopback) ASGI server address."""if not host_header:return Falsehost = host_header.strip()@@ -2419,12 +2273,9 @@ def _is_local_bootstrap_request(request: Request) -> bool:def _is_same_origin_request(request: Request) -> bool:- """True when Origin is missing or matches request's scheme://host:port.-- Missing Origin counts as same-origin (top-level GETs omit it). Both sides- are canonicalised via :func:`_canonical_origin`; callers must emit- ``Vary: Origin``.- """+ """True when Origin is missing or matches request's scheme://host:port. Missing Origin counts as same-origin+ (top-level GETs omit it); both sides are canonicalised via :func:`_canonical_origin`, and callers must+ emit ``Vary: Origin``."""origin = request.headers.get("origin")if origin is None:# Missing header: top-level same-document GETs omit Origin.@@ -2504,12 +2355,9 @@ def _is_live_cloudflare_frontend_request(scope, app_state) -> bool:def _is_remote_frontend_request(scope, app_state) -> bool:- """True for a request the desktop backend may answer with its packaged web UI.-- Two ways in, both identified by the connection itself rather than a client- header the caller controls: Cloudflare's own edge, or one of the sockets the- runtime LAN listener bound (Settings > LAN access).- """+ """True for a request the desktop backend may answer with its packaged web UI: Cloudflare's own edge, or one+ of the sockets the runtime LAN listener bound, both identified by the connection itself rather than a+ client header the caller controls."""from lan_access import request_on_lan_listenerreturn _is_live_cloudflare_frontend_request(scope, app_state) or request_on_lan_listener(scope)@@ -2532,11 +2380,8 @@ def setup_frontend(*,tunnel_only: bool = False,):- """Mount frontend static files (optional).-- ``tunnel_only`` restricts the mount to remote callers: the Cloudflare edge, or- a socket the runtime LAN listener bound. See :func:`_is_remote_frontend_request`.- """+ """Mount frontend static files (optional). ``tunnel_only`` restricts the mount to remote callers:+ the Cloudflare edge, or a socket the runtime LAN listener bound."""if not build_path.exists():return False@@ -2592,24 +2437,22 @@ def setup_frontend(file_path = (build_path / full_path).resolve()- # Block path traversal - resolved path must stay inside build_pathif not file_path.is_relative_to(build_path.resolve()):return Response(status_code = 403)if file_path.is_file():return FileResponse(file_path)- # Last, so a real asset always wins: an engine endpoint Studio does not serve- # must 404 rather than render the app shell, which reads as "supported" to a- # client that checks the status before the body. Deliberately after the file- # lookup -- a build that ever ships one of these names still serves it.+ # Last, so a real asset always wins: an engine endpoint Studio does not serve must 404 rather than render the+ # app shell, which reads as "supported" to a client that checks the status before the body. Deliberately+ # after the file lookup, so a build that ever ships one of these names still serves it.if is_engine_probe_path(full_path):raise HTTPException(status_code = 404, detail = "API endpoint not found")# Serve index.html as bytes - avoids Content-Length mismatchreturn _build_index_response(request)- # The catch-all above is what 404s a GET probe. The lifespan reads this to decide- # whether the engine paths still need their own GET denial.+ # The catch-all above is what 404s a GET probe. The lifespan reads this to decide whether the engine+ # paths still need their own GET denial.app.state.frontend_mounted = Truereturn Truediff --git a/studio/backend/mcp_server.py b/studio/backend/mcp_server.pyindex 2a2c346ee95..20bac30bde4 100644--- a/studio/backend/mcp_server.py+++ b/studio/backend/mcp_server.py@@ -1,11 +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-"""Curated MCP tools for driving an Unsloth Studio instance.--The MCP surface deliberately wraps the existing Unsloth services instead of-duplicating training or export logic. It is opt-in because several tools can-start GPU work or write model artifacts.+"""Curated MCP tools for driving an Unsloth Studio instance. The MCP surface deliberately wraps the existing+Unsloth services instead of duplicating training or export logic. It is opt-in because several tools can start+GPU work or write model artifacts."""from __future__ import annotations@@ -75,10 +73,8 @@ def _dump(value: Any) -> Any:def _clamp(value: int, low: int, high: int) -> int:- """Clamp an MCP-supplied integer into an inclusive range.-- MCP tools call the Unsloth route functions directly, which skips FastAPI's- Query(ge=, le=) validation, so we re-apply the same bounds here.+ """Clamp an MCP-supplied integer into an inclusive range. MCP tools call the Unsloth route functions+ directly, which skips FastAPI's Query(ge=, le=) validation, so we re-apply the same bounds here."""return max(low, min(value, high))diff --git a/studio/backend/models/auth.py b/studio/backend/models/auth.pyindex e0251a6c0d8..9f255967eb2 100644--- a/studio/backend/models/auth.py+++ b/studio/backend/models/auth.py@@ -75,9 +75,6 @@ class ChangePasswordRequest(BaseModel):)-# -----------------------------------------------------------------------------class CreateApiKeyRequest(BaseModel):"""Request body to create a new API key."""diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 11f40a4e816..5193125c219 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -326,11 +326,10 @@ class LoadRequest(BaseModel):@field_validator("n_batch", "n_ubatch", "ctx_checkpoints", "cache_ram", mode = "before")@classmethoddef _no_booleans(cls, value: Any) -> Any:- # bool subclasses int and pydantic parses non-strictly, so `true` arrives as 1 and- # the load launches --batch-size 1, which llama-server aborts on: a 500 rather than- # a 422. Mirrors ModelOverrideRequest._no_booleans so /load and /settings agree.- # Kept off the annotation: an Annotated BeforeValidator stops the Field constraints- # folding into the int core schema, and they leak into OpenAPI as ge/le.+ # bool subclasses int and pydantic parses non-strictly, so `true` arrives as 1 and the load+ # launches --batch-size 1, which llama-server aborts on: a 500 rather than a 422. Mirrors+ # ModelOverrideRequest._no_booleans. Kept off the annotation: an Annotated BeforeValidator stops+ # the Field constraints folding into the int core schema, and they leak into OpenAPI as ge/le.if isinstance(value, bool):raise ValueError("Expected a number, got a boolean.")return value@@ -338,9 +337,8 @@ class LoadRequest(BaseModel):@field_validator("tensor_split")@classmethoddef _reject_degenerate_tensor_split(cls, value: Optional[List[float]]) -> Optional[List[float]]:- # A negative / non-finite / all-zero split is silently dropped at launch- # (stored as None) yet still compared raw in the reload dedupe, so an- # identical Apply reloads forever. Reject it up front; [] = no split.+ # A negative / non-finite / all-zero split is silently dropped at launch (stored as None) yet+ # still compared raw in the reload dedupe, so an identical Apply reloads forever. [] = no split.if not value:return valueimport math@@ -465,9 +463,8 @@ class ValidateModelRequest(BaseModel):load_in_4bit: bool = Field(True)cache_type_kv: Optional[str] = Field(None)tensor_parallel: bool = Field(False)- # Sized with, like the other intended load settings above: the follow-up /load- # opens no projector when this is set, so a preflight that charges for one would- # refuse a load that then fits.+ # Sized with, like the other intended load settings above: the follow-up /load opens no projector+ # when this is set, so a preflight that charges for one would refuse a load that then fits.disable_vision: bool = Field(False)gpu_ids: Optional[List[int]] = Field(None)# Sized with too: preflighting a CPU load would refuse one that takes no VRAM.@@ -611,9 +608,9 @@ class TransformersUpgradeCheckRequest(BaseModel):hf_token: Optional[str] = Field(None, description = "HuggingFace token, so gated repos resolve their config.json")- # Cache pin, in the same four fields /models/remote-code-scan takes and resolved by- # the same precedence: a cached model loads from its pinned snapshot, whose- # config.json can name a different architecture than the repo's current one.+ # Cache pin, in the same four fields /models/remote-code-scan takes and resolved by the same+ # precedence: a cached model loads from its pinned snapshot, whose config.json can name a+ # different architecture than the repo's current one.prefer_local_cache: bool = Field(False,description = "Inspect the cached snapshot rather than the Hub repo, when one is pinned.",@@ -740,7 +737,6 @@ class ValidateModelResponse(BaseModel):description = "Embedded GGUF chat template, read from the header when include_chat_template ""is set (native lease-backed picks); None for non-GGUF, over-cap, or not-read templates.",)- # Additive fields; the consuming consent dialog ships in a follow-up frontend PR.requires_transformers_upgrade: bool = Field(False,description = "True when the model's architecture is unknown to every installed "@@ -938,7 +934,6 @@ class MemoryEstimate(BaseModel):"'unsupported_source' or 'unsizable'.",)- # --- the two meanings that used to collide under `weights_bytes` ---quant_file_bytes: int = Field(0,description = "The selected GGUF quant file ALONE, as it sits on disk. This is "@@ -1677,14 +1672,6 @@ class InferenceStatusResponse(_InferenceRuntimeFields):)-# =====================================================================-# OpenAI-Compatible Chat Completions Models-# =====================================================================---# ── Multimodal content parts (OpenAI vision format) ──────────────--class TextContentPart(BaseModel):"""Text content part in a multimodal message."""@@ -1842,9 +1829,6 @@ ContentPart = Annotated["""Union type for multimodal content parts, discriminated by the 'type' field."""-# ── Messages ─────────────────────────────────────────────────────--class ChatMessage(BaseModel):"""Single message in a chat conversation.@@ -1890,9 +1874,8 @@ class ChatMessage(BaseModel):@field_validator("reasoning_content", mode = "before")@classmethoddef _ignore_non_string_reasoning(cls, value):- # This field used to be ignored as an unknown key. Some compatible- # gateways send structured reasoning, so declaring the string form must- # not turn those previously accepted requests into validation errors.+ # This field used to be ignored as an unknown key. Some compatible gateways send structured+ # reasoning, so declaring the string form must not turn those requests into validation errors.return value if isinstance(value, str) else None@model_validator(mode = "after")@@ -1905,9 +1888,8 @@ class ChatMessage(BaseModel):raise ValueError('"name" is only valid on role="tool" messages.')if self.role == "tool":- # tool_call_id resolution happens at ChatCompletionRequest scope.- # OpenAI accepts empty tool results (commands with no output);- # normalize to "" instead of a 400 agentic clients treat as fatal.+ # tool_call_id resolution happens at ChatCompletionRequest scope. OpenAI accepts empty tool+ # results (commands with no output); normalize to "" instead of a 400 agentic clients treat as fatal.if self.content is None or self.content == []:self.content = ""elif self.role == "assistant":@@ -1931,11 +1913,9 @@ class ThinkingConfig(BaseModel):def resolve_thinking_onto_enable_thinking(request):- """Map Anthropic-style ``thinking`` onto the internal ``enable_thinking``.-- ``enable_thinking`` wins when both are given. Shared with counting, which must resolve- the reasoning preamble exactly as the completion does.- """+ """Map Anthropic-style ``thinking`` onto the internal ``enable_thinking``. ``enable_thinking`` wins+ when both are given. Shared with counting, which must resolve the reasoning preamble exactly as+ the completion does."""if request.thinking is not None and request.enable_thinking is None:request.enable_thinking = request.thinking.type == "enabled"return request@@ -1974,12 +1954,11 @@ class ReasoningControlsRequest(BaseModel):return resolve_thinking_onto_enable_thinking(self)-# Recognized permission_mode values. The field accepts a plain string rather than-# a Literal so an unrecognized value from a newer UI/client degrades to the safest-# gate ("ask") instead of a 422. None stays unset at the request boundary: the tool-# loops normalize it to the product default "auto", while the route's confirm-gate-# derivation keeps an unset mode lenient (a non-streaming request cannot prompt, so-# it runs) to keep non-streaming clients and health checks working.+# Recognized permission_mode values. The field accepts a plain string rather than a Literal so an+# unrecognized value from a newer client degrades to the safest gate ("ask") instead of a 422.+# None stays unset at the request boundary: the tool loops normalize it to the product default+# "auto", while the route's confirm-gate derivation keeps an unset mode lenient (a non-streaming+# request cannot prompt, so it runs)._KNOWN_PERMISSION_MODES = ("ask", "auto", "off", "full")@@ -2018,10 +1997,8 @@ class ChatCompletionRequest(BaseModel):max_tokens: Optional[int] = Field(None, ge = 1, description = "Maximum tokens to generate (None = until EOS)")- # OpenAI's documented range is [-2, 2] on both penalties. Widening only- # admits requests that used to be rejected, so nothing that works today- # changes. A negative value boosts repetition wherever the backend applies- # the penalty at all.+ # OpenAI's documented range is [-2, 2] on both penalties. Widening only admits requests that used+ # to be rejected. A negative value boosts repetition wherever the backend applies the penalty.presence_penalty: float = Field(0.0,ge = -2.0,@@ -2111,7 +2088,6 @@ class ChatCompletionRequest(BaseModel):description = 'Streaming options, e.g. {"include_usage": true} to emit a final usage chunk.',)- # ── Unsloth extensions (ignored by standard OpenAI clients) ──top_k: int = Field(20, ge = -1, le = 100, description = "[x-unsloth] Top-k sampling")min_p: float = Field(0.01, ge = 0.0, le = 1.0, description = "[x-unsloth] Min-p sampling threshold")repetition_penalty: float = Field(@@ -2324,7 +2300,6 @@ class ChatCompletionRequest(BaseModel):description = "[x-unsloth] Per-request cancellation token. Frontend sends a fresh UUID per run so /inference/cancel matches one specific generation.",)- # ── External provider routing (x-unsloth extensions) ──────────provider_id: Optional[str] = Field(None,description = "[x-unsloth] Saved provider config ID. Its stored key is used when encrypted_api_key is omitted.",@@ -2452,16 +2427,13 @@ class ChatCompletionRequest(BaseModel):@model_validator(mode = "after")def _resolve_missing_tool_call_ids(self) -> "ChatCompletionRequest":- """Fill missing tool_call_id by walking back to the preceding assistant.-- OpenAI / Anthropic passthrough require the result id to match the- assistant's tool_calls[].id. Prefer function.name match, else first- unconsumed tool_call; synth a random id only if none exists. A user- turn breaks the lookup.- """- # Both passes below were a backwards rescan per tool result, O(n^2) for one assistant- # with n calls. Each is now one forward pass with an index -- the same search, since- # the backward walk never left the current user-delimited segment.+ """Fill missing tool_call_id by walking back to the preceding assistant. OpenAI / Anthropic+ passthrough require the result id to match the assistant's tool_calls[].id. Prefer+ function.name match, else first unconsumed tool_call; synth a random id only if none exists.+ A user turn breaks the lookup."""+ # Both passes below were a backwards rescan per tool result, O(n^2) for one assistant with n+ # calls. Each is now one forward pass with an index, the same search, since the backward walk+ # never left the current user-delimited segment.messages = self.messages# The first pass only feeds the second, so with every tool_call_id present there is# nothing to do (the common case).@@ -2474,9 +2446,8 @@ class ChatCompletionRequest(BaseModel):# Pre-mark explicit ids so a missing-id sibling can't steal a claimed one.consumed: set[tuple[int, int]] = set()- # Newest assistant call per explicit id in this segment; within one assistant the- # first index wins, matching the old first-match-nearest-assistant walk. Only- # ``str`` ids are indexed: ``tool_call_id`` is a ``str``, so nothing else matches.+ # Newest assistant call per explicit id in this segment; within one assistant the first index+ # wins, matching the old first-match-nearest-assistant walk. Only ``str`` ids are indexed.latest_by_id: dict = {}for asst_idx, msg in enumerate(messages):role = msg.role@@ -2498,11 +2469,10 @@ class ChatCompletionRequest(BaseModel):if claimed is not None:consumed.add(claimed)- # Assistants in this segment with an unclaimed call, oldest first, so the nearest is- # on top. A drained assistant never refills, so popping it is permanent and the walk- # past it happens once overall, not once per tool result. Each frame keeps its calls- # in order plus the same indexes bucketed by function name; one consumed out of turn- # is dropped when it reaches a queue front.+ # Assistants in this segment with an unclaimed call, oldest first, so the nearest is on top. A+ # drained assistant never refills, so popping it is permanent and the walk past it happens once+ # overall, not once per tool result. Each frame keeps its calls in order plus the same indexes+ # bucketed by function name; one consumed out of turn is dropped when it reaches a queue front.stack: list = []for asst_idx, msg in enumerate(messages):role = msg.role@@ -2588,15 +2558,11 @@ class ChatCompletionRequest(BaseModel):and self.confirm_tool_calls is Trueand not (self.provider_id or self.provider_type)):- # An explicit confirm_tool_calls=True with no mode opted into the- # pre-permission-mode contract of gating every call, so resolve it to- # "ask" rather than let the loop apply the "auto" default, which would- # silently weaken that opt-in to high-risk calls only. Unlike the "ask"- # branch below this only sets permission_mode, which is inert unless- # Unsloth's own tool loop runs, so it needs no enable_tools/mcp gate --- # deliberate, since a process-wide --enable-tools policy can force the- # loop when the request sets neither flag. A bare unset request- # (confirm_tool_calls is None) still defaults to auto.+ # An explicit confirm_tool_calls=True with no mode opted into the pre-permission-mode contract of+ # gating every call, so resolve it to "ask" rather than let the loop apply the "auto" default,+ # which would silently weaken that opt-in to high-risk calls only. Unlike the "ask" branch below+ # this only sets permission_mode, which is inert unless Unsloth's own tool loop runs, so it needs+ # no enable_tools/mcp gate. A bare unset request still defaults to auto.self.permission_mode = "ask"elif (self.permission_mode == "ask"@@ -2604,23 +2570,16 @@ class ChatCompletionRequest(BaseModel):and not (self.provider_id or self.provider_type)and (self.enable_tools is True or bool(self.mcp_enabled))):- # "Ask" gates every call, so a direct API caller that omits the legacy- # confirm flag must still hit the confirmation gate for Unsloth's own- # tool loop. An explicit confirm_tool_calls=False wins over the mode- # (mirrors _permission_mode_confirm and the Anthropic pre-switch guard),- # so only self-enable when the flag is unset. Only self-enable when that- # loop is actually requested- # (enable_tools / mcp_enabled) -- the router enters the loop on those- # signals, not on enabled_tools alone (which merely filters which tools- # run). A plain client-tool passthrough (client-supplied `tools` that- # Unsloth does not execute) must route verbatim, and external-provider+ # "Ask" gates every call, so a direct API caller that omits the legacy confirm flag must still hit+ # the confirmation gate for Unsloth's own tool loop. An explicit confirm_tool_calls=False wins over+ # the mode, so only self-enable when the flag is unset, and only when that loop is actually+ # requested (enable_tools / mcp_enabled): the router enters the loop on those signals, not on+ # enabled_tools alone. A plain client-tool passthrough must route verbatim, and external-provider# routing rejects confirm_tool_calls with tools, so skip the fold there.#- # "auto" is deliberately NOT folded: it only prompts for a call the- # classifier flags, so leaving confirm_tool_calls unset lets the route's- # _confirm_gate_needs_stream apply the safe-only exception (a safe-only- # auto selection needs no stream) instead of an explicit-confirm forcing- # stream=true. The mode still drives the loop's per-call gate.+ # "auto" is deliberately NOT folded: it only prompts for a call the classifier flags, so leaving+ # confirm_tool_calls unset lets _confirm_gate_needs_stream apply the safe-only exception instead of+ # an explicit confirm forcing stream=true. The mode still drives the loop's per-call gate.self.confirm_tool_calls = Truereturn self@@ -2732,9 +2691,8 @@ class ChatCountTokensRequest(ReasoningControlsRequest):elif self.bypass_permissions:self.permission_mode = "full"elif self.permission_mode is None and self.confirm_tool_calls is True:- # The same reading a completion gives it: gating every call is the- # pre-permission-mode way of asking for "ask", and the loop's retrieval- # gate turns on that. No provider clause -- this endpoint is local only.+ # The same reading a completion gives it: gating every call is the pre-permission-mode way of+ # asking for "ask", and the loop's retrieval gate turns on that. Local-only endpoint.self.permission_mode = "ask"return self@@ -2745,9 +2703,6 @@ class ToolConfirmRequest(BaseModel):decision: Literal["allow", "deny"] = "deny"-# ── OpenAI shell-tool container management ─────────────────────--class OpenAIContainerRequest(BaseModel):"""Shared body for the OpenAI container endpoints (list / create / delete).@@ -2810,9 +2765,6 @@ class ListOpenAIContainersResponse(BaseModel):containers: list[OpenAIContainerSummary]-# ── Streaming response chunks ────────────────────────────────────--class ChoiceDelta(BaseModel):"""Delta content for a streaming chunk."""@@ -2847,9 +2799,6 @@ class ChatCompletionChunk(BaseModel):context_truncated: Optional[dict] = None-# ── Non-streaming response ───────────────────────────────────────--class CompletionMessage(BaseModel):"""The assistant's complete response message."""@@ -2901,14 +2850,6 @@ class ChatCompletion(BaseModel):system_fingerprint: Optional[str] = None-# =====================================================================-# OpenAI Responses API Models (/v1/responses)-# =====================================================================---# ── Request models ──────────────────────────────────────────────--class ResponsesInputTextPart(BaseModel):"""Text content part in a Responses API message (type=input_text)."""@@ -3041,12 +2982,9 @@ class ResponsesUnknownInputItem(BaseModel):def _responses_input_item_discriminator(v: Any) -> str:- """Route a Responses input item to the correct tagged variant.-- Pydantic's smart-union matching misreports errors when a strict-``Literal``- variant doesn't match; an explicit discriminator makes routing deterministic- and falls through to the catch-all.- """+ """Route a Responses input item to the correct tagged variant. Pydantic's smart-union matching+ misreports errors when a strict-``Literal`` variant doesn't match; an explicit discriminator+ makes routing deterministic and falls through to the catch-all."""if isinstance(v, dict):t = v.get("type")r = v.get("role")@@ -3113,9 +3051,8 @@ class ResponsesRequest(BaseModel):max_output_tokens: Optional[int] = Field(None, ge = 1)stream: bool = Field(False, description = "Whether to stream the response via SSE")- # OpenAI function-calling fields, forwarded via the Chat Completions- # pass-through. Plain list so built-in tool shapes round-trip without- # validation errors; the translator forwards functions and Codex apply_patch.+ # OpenAI function-calling fields, forwarded via the Chat Completions pass-through. Plain list so+ # built-in tool shapes round-trip without validation errors.tools: Optional[list[dict]] = Field(None,description = (@@ -3147,9 +3084,6 @@ class ResponsesRequest(BaseModel):model_config = {"extra": "allow"}-# ── Response models ─────────────────────────────────────────────--class ResponsesOutputTextContent(BaseModel):"""A text content block inside an output message."""@@ -3250,14 +3184,6 @@ class ResponsesResponse(BaseModel):truncation: Optional[Any] = None-# =====================================================================-# Anthropic Messages API Models (/v1/messages)-# =====================================================================---# ── Request models ─────────────────────────────────────────────--class AnthropicTextBlock(BaseModel):type: Literal["text"]text: str@@ -3295,10 +3221,9 @@ class AnthropicToolResultBlock(BaseModel):return "" if v is None else v-# Block types the converter translates explicitly. Anything else (thinking /-# redacted_thinking, a provider block a resumed session replays, or a future type)-# is accepted as an unknown block and dropped by the converter, rather than 400-ing-# the whole request on strict validation.+# Block types the converter translates explicitly. Anything else (thinking / redacted_thinking, a+# provider block a resumed session replays, or a future type) is accepted as an unknown block and+# dropped by the converter, rather than 400-ing the whole request on strict validation._KNOWN_ANTHROPIC_BLOCK_TYPES = frozenset({"text", "image", "tool_use", "tool_result", "thinking", "redacted_thinking"})@@ -3322,9 +3247,8 @@ class AnthropicUnknownBlock(BaseModel):class AnthropicThinkingBlock(BaseModel):- # Clients replay thinking blocks with tool results (Anthropic's tool-use- # protocol requires it), so the request model must accept them; conversion- # drops them from the prompt.+ # Clients replay thinking blocks with tool results (Anthropic's tool-use protocol requires it), so+ # the request model must accept them; conversion drops them from the prompt.type: Literal["thinking"]thinking: str = ""signature: str = ""@@ -3393,15 +3317,13 @@ class AnthropicMessage(BaseModel):@classmethoddef _normalize_content(cls, data):# Role-aware leniency that never silently drops real user input:- # - assistant: a resumed tool-only turn's null content -> "" (str|list would- # 400 on null; "" keeps the converter's `for block in content` safe).- # Unknown blocks (thinking / future types) validate via+ # - assistant: a resumed tool-only turn's null content -> "" (str|list would 400 on null; ""+ # keeps the converter's `for block in content` safe). Unknown blocks validate via# AnthropicUnknownBlock and are dropped by the converter.- # - user: keep strict. Null user content stays None so str|list rejects it- # (400) rather than forwarding an empty prompt; and reject block types the- # converter cannot translate, since it silently skips unknown user blocks- # -- a user turn made only of them would validate yet send no content- # (silent data loss).+ # - user: keep strict. Null user content stays None so str|list rejects it (400) rather than+ # forwarding an empty prompt, and block types the converter cannot translate are rejected,+ # since it silently skips unknown user blocks: a user turn made only of them would validate+ # yet send no content.if not isinstance(data, dict):return datacontent = data.get("content")@@ -3416,9 +3338,8 @@ class AnthropicMessage(BaseModel):btype = (block.get("type") if isinstance(block, dict) else getattr(block, "type", None))- # Guard the value: a non-string type is unsupported too, and a- # membership test on an unhashable value would raise TypeError- # (escaping as a 500 instead of a clean 400).+ # Guard the value: a non-string type is unsupported too, and a membership test on an unhashable+ # value would raise TypeError, escaping as a 500 instead of a clean 400.if not isinstance(btype, str) or btype not in _USER_ANTHROPIC_BLOCK_TYPES:raise ValueError(f"unsupported content block type {btype!r} in a user message")return data@@ -3435,11 +3356,9 @@ class AnthropicTool(BaseModel):class AnthropicThinkingConfig(BaseModel):- # Deliberately `str`, not a Literal. Anthropic ships thinking types beyond- # enabled/disabled (adaptive tiers), and Claude Code sends them -- a strict- # Literal turns an unrecognized value into a hard 400, which is worse than- # the silent drop this replaced. Only "disabled" means off; treat anything- # else as a request to think.+ # Deliberately `str`, not a Literal. Anthropic ships thinking types beyond enabled/disabled+ # (adaptive tiers) and Claude Code sends them, and a strict Literal turns an unrecognized value+ # into a hard 400. Only "disabled" means off; treat anything else as a request to think.type: str = "enabled"# Accepted for wire compatibility; llama-server has no thinking budget.budget_tokens: Optional[int] = None@@ -3480,9 +3399,8 @@ class AnthropicMessagesRequest(BaseModel):)enable_tools: Optional[bool] = Noneenabled_tools: Optional[list[str]] = None- # Anthropic's native extended-thinking control. Only `type` is honored:- # llama-server has no thinking-token budget, so `budget_tokens` is accepted- # and ignored rather than 400'd (Claude Code always sends it alongside).+ # Anthropic's native extended-thinking control. Only `type` is honored: llama-server has no+ # thinking-token budget, so `budget_tokens` is accepted and ignored rather than 400'd.thinking: Optional[AnthropicThinkingConfig] = None# [x-unsloth] reasoning controls mirroring the OpenAI endpoint. These win# over `thinking` when both are present, matching enable_tools precedence.@@ -3522,11 +3440,9 @@ class AnthropicMessagesRequest(BaseModel):def _effort_from_output_config(self) -> "AnthropicMessagesRequest":if self.reasoning_effort is not None or not isinstance(self.output_config, dict):return self- # Only once thinking is already on. `reasoning_effort` is the x-unsloth- # override that deliberately outranks `thinking` (a named level means- # "think"), but Claude Code sends output_config.effort on EVERY request,- # including with thinking off -- adopting it there would re-enable- # thinking the caller switched off and pin the level the user never set.+ # Only once thinking is already on. `reasoning_effort` is the x-unsloth override that deliberately+ # outranks `thinking`, but Claude Code sends output_config.effort on EVERY request, including with+ # thinking off, and adopting it there would re-enable thinking the caller switched off.if self.resolved_enable_thinking() is not True:return selfeffort = self.output_config.get("effort")@@ -3595,9 +3511,6 @@ class AnthropicMessagesRequest(BaseModel):return self-# ── Response models ────────────────────────────────────────────--class AnthropicUsage(BaseModel):input_tokens: int = 0cache_creation_input_tokens: int = 0@@ -3620,9 +3533,8 @@ class AnthropicResponseToolUseBlock(BaseModel):class AnthropicResponseThinkingBlock(BaseModel):type: Literal["thinking"] = "thinking"thinking: str- # Anthropic signs thinking blocks so they can be replayed on a later turn.- # Nothing local can produce a valid signature, so it stays empty; clients- # that only render the trace do not check it.+ # Anthropic signs thinking blocks so they can be replayed on a later turn. Nothing local can+ # produce a valid signature, so it stays empty; clients that only render the trace do not check it.signature: str = ""@@ -3644,9 +3556,6 @@ class AnthropicMessagesResponse(BaseModel):usage: AnthropicUsage = Field(default_factory = AnthropicUsage)-# ── Diffusion (local text-to-image) ──--class DiffusionLoadRequest(BaseModel):"""Request to load a local diffusion (text-to-image) checkpoint."""@@ -3806,9 +3715,8 @@ class DiffusionLoadRequest(BaseModel):def _unique_lora_ids(cls, value: Optional[list["LoraSpec"]]) -> Optional[list["LoraSpec"]]:# Same guard DiffusionGenerateRequest carries, and it matters more here: _resolve_lora_set# suffixes colliding adapter names, so a repeated id resolves the SAME adapter twice and- # set_adapters stacks both copies past the per-adapter weight bound. On the generation path- # that is one bad image; on this path the adapters are baked into the quantized build- # before compilation, so the unintended combination rides every image until a reload.+ # set_adapters stacks both copies past the per-adapter weight bound. On the generation path that+ # is one bad image; here the adapters are baked into the quantized build before compilation.if value:seen: set[str] = set()for spec in value:@@ -4354,8 +4262,8 @@ class DiffusionInferenceInfoResponse(BaseModel):# ── OpenAI-compatible images API (POST /v1/images/generations) ──-# Shapes mirror OpenAI's CreateImageRequest / ImagesResponse. GPT-image-only knobs are accepted and ignored, like dall-e-2.-# The size string is parsed and `stream` rejected in the route; everything Pydantic can check declaratively is here.+# Shapes mirror OpenAI's CreateImageRequest / ImagesResponse. GPT-image-only knobs are accepted+# and ignored, like dall-e-2. The size string is parsed and `stream` rejected in the route.class ImageGenerationRequest(BaseModel):@@ -4411,9 +4319,6 @@ class ImageGenerationResponse(BaseModel):data: list[ImageGenerationData] = Field(..., description = "The generated images.")-# ── OpenAI-compatible audio API (POST /v1/audio/speech) ──--class AudioSpeechRequest(BaseModel):"""OpenAI ``CreateSpeechRequest`` for ``POST /v1/audio/speech``.@@ -4504,9 +4409,6 @@ class AudioGalleryListResponse(BaseModel):next_before_id: Optional[str] = None-# ── OpenAI-compatible videos API (/v1/videos) ──--class VideoJobCreateRequest(BaseModel):prompt: str = Field(..., min_length = 1)model: Optional[str] = None@@ -4560,9 +4462,6 @@ class VideoJobDeleteResponse(BaseModel):deleted: bool = True-# ── Video (local text-to-video) ──--class VideoLoadRequest(BaseModel):"""Request to load a local text-to-video checkpoint."""@@ -4733,11 +4632,10 @@ class VideoGenerateRequest(BaseModel):"where a downloaded model that is not the resident one is loaded first; omit to use ""whatever is loaded. The Video page never sends it.",)- # Width/height/num_frames/fps default per loaded family, so they are optional here. These bounds stay a COARSE outer- # guard only -- they are family-agnostic, and a request that clears them can still be one no checkpoint can render. The- # enforced rule is the LOADED family's own (its resolution presets and k * frame_step + frame_offset lattice), which the- # route checks with validate_video_request_shape and rejects with a 422 naming the supported shapes. Nothing tighter- # belongs here: with no model loaded there is no family to judge against, and that path must keep snapping as before.+ # Width/height/num_frames/fps default per loaded family, so they are optional here. These bounds+ # stay a COARSE family-agnostic outer guard: the enforced rule is the LOADED family's own+ # (resolution presets and the k * frame_step + frame_offset lattice), which the route checks with+ # validate_video_request_shape. With no model loaded there is no family to judge against.width: Optional[int] = Field(None,ge = 32,@@ -4871,14 +4769,12 @@ class VideoGenerateRequest(BaseModel):@model_validator(mode = "after")def _keyframe_canvas_needs_both_axes(self) -> "VideoGenerateRequest":- # Omit both axes for "match source", or provide both for an explicit canvas.- # KEYFRAME requests only. There a half-specified canvas is silently discarded:- # _resolve_keyframes matches the source aspect whenever either axis is missing, so the- # axis that was sent never reaches the render and the API would accept one recipe and- # draw another. Without a keyframe the backend deliberately resolves the missing axis- # from the family's default preset -- validate_video_request_shape and generate() both- # document and implement that -- so applying the rule to every request would reject- # half-specified LTX, Wan, Hunyuan and prompt-only H3 calls that have always been valid.+ # Omit both axes for "match source", or provide both for an explicit canvas. KEYFRAME requests+ # only: there a half-specified canvas is silently discarded, since _resolve_keyframes matches the+ # source aspect whenever either axis is missing, so the API would accept one recipe and draw+ # another. Without a keyframe the backend deliberately resolves the missing axis from the family's+ # default preset, so applying the rule everywhere would reject half-specified LTX, Wan, Hunyuan+ # and prompt-only H3 calls that have always been valid.if not (self.first_frame or self.last_frame):return selfif (self.width is None) != (self.height is None):@@ -4918,9 +4814,8 @@ class GalleryVideo(BaseModel):"clips saved before keyframes existed.",)model: Optional[str] = Field(None, description = "Model repo id that produced it")- # The load-time BUILD, mirroring GalleryImage: the repo id alone does not say which checkpoint- # ran or at what precision, so a clip could not be told apart from one rendered at another. All- # optional, so sidecars written before this existed still list.+ # The load-time BUILD, mirroring GalleryImage: the repo id alone does not say which checkpoint ran+ # or at what precision. All optional, so sidecars written before this existed still list.model_kind: Optional[str] = Field(None, description = "How the model was loaded: gguf, single_file or pipeline")diff --git a/studio/backend/models/models.py b/studio/backend/models/models.pyindex e0c9a81b2a1..ef6dca97e35 100644--- a/studio/backend/models/models.py+++ b/studio/backend/models/models.py@@ -153,9 +153,9 @@ class GgufVariantDetail(BaseModel):filename: str = Field(..., description = "GGUF filename (e.g., 'gemma-3-4b-it-Q4_K_M.gguf')")quant: str = Field(..., description = "Quantization label or internal GGUF variant key")- # Mirrors hub.schemas.inventory.GgufVariantDetail. The route builds THIS model, so a field that- # exists only on the hub twin is dropped by pydantic without a word and a qualified row falls back- # to rendering its whole relative path.+ # Mirrors hub.schemas.inventory.GgufVariantDetail. The route builds THIS model, so a field that exists only+ # on the hub twin is dropped by pydantic without a word and a qualified row falls back to rendering its whole+ # relative path.display_label: Optional[str] = Field(None, description = "Optional user-facing label when quant is an internal key")diff --git a/studio/backend/models/providers.py b/studio/backend/models/providers.pyindex 9db9c572ce5..689c81330c1 100644--- a/studio/backend/models/providers.py+++ b/studio/backend/models/providers.py@@ -10,9 +10,6 @@ from pydantic import BaseModel, FieldMAX_JSON_SAFE_INTEGER = 9_007_199_254_740_991-# ── Registry (static provider info) ───────────────────────────────--class ProviderRegistryEntry(BaseModel):"""A supported provider type with its default configuration."""@@ -51,9 +48,6 @@ class ProviderRegistryEntry(BaseModel):)-# ── Provider config CRUD ──────────────────────────────────────────--class ProviderCreate(BaseModel):"""Request to create a saved provider configuration."""@@ -153,9 +147,6 @@ class ProviderResponse(BaseModel):updated_at: str = Field(..., description = "ISO 8601 last-update timestamp")-# ── Model listing ─────────────────────────────────────────────────--class ProviderModelInfo(BaseModel):"""A model available from an external provider."""@@ -182,9 +173,6 @@ class ProviderModelsRequest(BaseModel):)-# ── Connection testing ────────────────────────────────────────────--class ProviderTestRequest(BaseModel):"""Request to test connectivity to an external provider."""diff --git a/studio/backend/models/responses.py b/studio/backend/models/responses.pyindex 862b70b402f..19148820986 100644--- a/studio/backend/models/responses.py+++ b/studio/backend/models/responses.py@@ -1,8 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Pydantic response models for training and model management routes-(previously returned as raw dicts)."""+"""Pydantic response models for training and model management routes (previously returned as raw dicts)."""from pydantic import BaseModel, Fieldfrom typing import Optional, Listdiff --git a/studio/backend/models/training.py b/studio/backend/models/training.pyindex ed66ce00afb..d2a1dc0b7da 100644--- a/studio/backend/models/training.py+++ b/studio/backend/models/training.py@@ -1,9 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Pydantic schemas for Training API-"""+"""Pydantic schemas for Training API"""import mathimport re@@ -942,7 +940,6 @@ class DiffusionTrainingStartRequest(BaseModel):"(auto for qwen-image, 1.0 otherwise)."),)- # ── resume ────────────────────────────────────────────────────────────────save_steps: int = Field(0,ge = 0,@@ -1103,11 +1100,8 @@ class DiffusionDatasetSummary(BaseModel):name: strpath: strimage_count: int- # Defaults to 0 so an older backend's payload, and every image-only caller, stays valid.- # Clips, for the families that train from video. Defaults to 0 so an older backend's payload (and every- # image-only caller) stays valid.- # Clips, for the families that train from video. Defaults to 0 so an older backend's payload (and every- # image-only caller) stays valid.+ # Clips, for the families that train from video. Defaults to 0 so an older backend's payload, and every+ # image-only caller, stays valid.clip_count: int = 0caption_count: int@@ -1126,15 +1120,14 @@ class DiffusionTrainableFamily(BaseModel):qlora_vram_gb: Optional[int] = Nonegated: bool = Falsenote: str = ""- # base_precision modes this machine supports for the family (empty = no selector, e.g. SDXL), the- # recommended pick, and whether regional torch.compile applies. Defaults keep older backends'- # payloads valid.+ # base_precision modes this machine supports for the family (empty = no selector, e.g. SDXL), the recommended+ # pick, and whether regional torch.compile applies. Defaults keep older backends' payloads valid.precision_modes: List[str] = Field(default_factory = list)recommended_precision: str = "nf4"supports_compile: bool = False- # Whether this family's loop writes checkpoint bundles. False makes the panel drop the "Checkpoint- # every" control: save_steps is refused, not ignored, for a checkpointless family, so offering the- # control means offering a value that rejects Start; defaults True so an older backend's payload keeps it.+ # Whether this family's loop writes checkpoint bundles. False makes the panel drop the "Checkpoint every"+ # control: save_steps is refused, not ignored, for a checkpointless family, so offering the control means+ # offering a value that rejects Start; defaults True so an older backend's payload keeps it.supports_checkpoints: bool = True# 1 for a family whose forward covers one packed sequence: a value above the cap is refused rather# than clamped, and declaring it here is what stops Pydantic dropping it from the response.diff --git a/studio/backend/routes/__init__.py b/studio/backend/routes/__init__.pyindex e4772c1b9d2..a8d648a245b 100644--- a/studio/backend/routes/__init__.py+++ b/studio/backend/routes/__init__.py@@ -1,9 +1,7 @@# 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 Routes-"""+"""API Routes"""from routes.training import router as training_routerfrom routes.models import router as models_routerdiff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.pyindex 3aa456ca0df..a7a7b422624 100644--- a/studio/backend/routes/auth.py+++ b/studio/backend/routes/auth.py@@ -46,11 +46,9 @@ router = APIRouter()def _require_a_credential_of_its_own(what: str):- """Refuse a caller that nothing but keyless API access let in.-- For effects that outlive the setting: turning keyless access back off does not- withdraw a key it handed out, restore one it destroyed, or undo a sign-out it- forced. Listing keys is refused with them because it names the key to revoke.+ """Refuse a caller that nothing but keyless API access let in. For effects that outlive the setting: turning+ keyless access back off does not withdraw a key it handed out, restore one it destroyed, or undo a sign-out+ it forced. Listing keys is refused with them because it names the key to revoke."""def dependency(no_credential: bool = Depends(authenticated_without_credential)) -> None:@@ -72,12 +70,9 @@ _CLI_BOOTSTRAP = (def _cli_is_inside(prefix: str) -> bool:- """Whether unsloth_cli lives under *prefix*, so -I would still find it.-- Located rather than imported: this runs in a request handler, and a spec- lookup answers the only question asked here, which is where the package is- on disk and not whether it starts.- """+ """Whether unsloth_cli lives under *prefix*, so -I would still find it. Located rather than+ imported: this runs in a request handler, and a spec lookup answers the only question asked+ here, which is where the package is on disk and not whether it starts."""try:spec = importlib.util.find_spec("unsloth_cli")origin = getattr(spec, "origin", None)@@ -92,29 +87,24 @@ def _cli_is_inside(prefix: str) -> bool:def _reset_password_command() -> str:"""Shell command shown in the 'incorrect password' hint.- Prefer the absolute path to this install's ``unsloth`` launcher (sibling of- the running interpreter) so the hint works even when its dir isn't on PATH.-- POSIX paths are shell-quoted. On Windows we use the bare absolute path only- when it has no spaces (a quoted path differs between cmd and PowerShell);- otherwise, or if the launcher can't be located, fall back to the PATH form.-- Windows never names unsloth.exe here, present or not. Existing is not the- same as runnable: an Application Control policy leaves the generated,- unsigned unsloth.exe on disk and denies it at CreateProcess (issue #8490),- and a bare `unsloth` resolves to that same file because PATHEXT puts .EXE- ahead of the .cmd shim. Whoever is locked out of Unsloth is exactly who needs- this command to work, so it must not be the one a policy refuses. Preference- order is therefore the interpreter's module entry, which needs no quoting in- cmd or PowerShell, then `unsloth.cmd` -- spelling the extension is what stops- PATHEXT reaching for the executable.-- -I only when the package is inside this interpreter's own prefix. -I implies- -s, so a ``pip install --user`` install would be told to run a command that- cannot find itself; unsloth_cli/__main__.py documents that exception and the- bootstrap to use instead, and this prints that bootstrap. It is safe to show- to either shell: the trampoline contains single quotes only, so one pair of- double quotes wraps it identically in cmd and in PowerShell.+ Prefer the absolute path to this install's ``unsloth`` launcher (sibling of the running interpreter) so the+ hint works even when its dir isn't on PATH. POSIX paths are shell-quoted. On Windows we use the bare+ absolute path only when it has no spaces (a quoted path differs between cmd and PowerShell); otherwise, or+ if the launcher can't be located, fall back to the PATH form.++ Windows never names unsloth.exe here, present or not. Existing is not the same as runnable: an Application+ Control policy leaves the generated, unsigned unsloth.exe on disk and denies it at CreateProcess (issue+ #8490), and a bare `unsloth` resolves to that same file because PATHEXT puts .EXE ahead of the .cmd shim.+ Whoever is locked out of Unsloth is exactly who needs this command to work, so it must not be the one a+ policy refuses. Preference order is therefore the interpreter's module entry, which needs no quoting in cmd+ or PowerShell, then `unsloth.cmd` -- spelling the extension is what stops PATHEXT reaching for the+ executable.++ -I only when the package is inside this interpreter's own prefix. -I implies -s, so a ``pip install --user``+ install would be told to run a command that cannot find itself; unsloth_cli/__main__.py documents that+ exception and the bootstrap to use instead, and this prints that bootstrap. It is safe to show to either+ shell: the trampoline contains single quotes only, so one pair of double quotes wraps it identically in cmd+ and in PowerShell."""try:bin_dir = os.path.dirname(os.path.abspath(sys.executable))@@ -137,9 +127,8 @@ def _reset_password_command() -> str:return "unsloth studio reset-password"-# Per-(ip, username) bucket + per-IP aggregate. Account bucket stops one user's-# typos from blocking others; the aggregate stops username-rotation spray.-# Single-process only; multi-worker deployments need a shared store.+# Per-(ip, username) bucket + per-IP aggregate. Account bucket stops one user's typos from blocking others; the+# aggregate stops username-rotation spray. Single-process only; multi-worker deployments need a shared store._LOGIN_BUCKETS: dict[tuple[str, str], deque] = {}_LOGIN_IP_BUCKETS: dict[str, deque] = {}_LOGIN_BUCKETS_LOCK = threading.Lock()@@ -152,9 +141,8 @@ _LOGIN_LOCKOUT_SECONDS = 60_LOGIN_MAX_BUCKETS = 4096# Last full stale-sweep time; rate-limits the O(n) sweep under a burst of new IPs._LAST_IP_PRUNE = 0.0-# Sharded overflow for per-IP failures that can't get their own bucket-# Each shard is a fixed-capacity dict ``ip -> [count, window_start]``; when full, a new IP evicts the lowest-count entry-# and starts clean.+# Sharded overflow for per-IP failures that can't get their own bucket. Each shard is a fixed-capacity dict+# ``ip -> [count, window_start]``; when full, a new IP evicts the lowest-count entry and starts clean._LOGIN_IP_OVERFLOW_SHARDS = 256_LOGIN_IP_OVERFLOW_MAX = 64_LOGIN_IP_OVERFLOW: list[dict] = [dict() for _ in range(_LOGIN_IP_OVERFLOW_SHARDS)]@@ -214,10 +202,8 @@ _UNKNOWN_LOGIN_USER = "\x00unknown-user"def _trust_forwarded_for() -> bool:- """Honour X-Forwarded-For only when UNSLOTH_STUDIO_TRUST_FORWARDED is set.-- Off by default so a direct caller can't spoof the header.- """+ """Honour X-Forwarded-For only when UNSLOTH_STUDIO_TRUST_FORWARDED is set. Off by default so a+ direct caller can't spoof the header."""return os.environ.get("UNSLOTH_STUDIO_TRUST_FORWARDED", "").lower() in ("1","true",@@ -301,10 +287,8 @@ def _prune_stale_buckets(now: float) -> None:def _prune_stale_ip_buckets(now: float) -> None:- """Drop empty / expired per-IP buckets to bound memory under spray.-- The dict is otherwise reclaimed only on a successful login, so a failure-only- spray from many (or spoofed) IPs would grow it without bound.+ """Drop empty / expired per-IP buckets to bound memory under spray. The dict is otherwise reclaimed only on a+ successful login, so a failure-only spray from many (or spoofed) IPs would grow it without bound."""stale: list[str] = []for bucket_ip, bucket in _LOGIN_IP_BUCKETS.items():@@ -320,25 +304,22 @@ def _record_login_failure(key: tuple[str, str]) -> int:now = time.monotonic()ip, _username = keywith _LOGIN_BUCKETS_LOCK:- # Keep the dict bounded without disabling throttling and without letting a- # spray reset a hot bucket: for a new IP at the cap, reclaim expired buckets- # (rate-limited) to make room.+ # Keep the dict bounded without disabling throttling and without letting a spray reset a hot bucket: for a new+ # IP at the cap, reclaim expired buckets (rate-limited) to make room.ip_bucket = _LOGIN_IP_BUCKETS.get(ip)if ip_bucket is None and len(_LOGIN_IP_BUCKETS) >= _LOGIN_MAX_BUCKETS:if now - _LAST_IP_PRUNE >= 1.0:_prune_stale_ip_buckets(now)_LAST_IP_PRUNE = nowif ip_bucket is None and len(_LOGIN_IP_BUCKETS) >= _LOGIN_MAX_BUCKETS:- # Still full -- every bucket is hot. Count this failure in the IP's- # bounded overflow shard instead of evicting a live one, so the spray- # stays throttled but can't push out (and reset) any IP's own counter.+ # Still full -- every bucket is hot. Count this failure in the IP's bounded overflow shard instead of+ # evicting a live one, so the spray stays throttled but can't push out (and reset) any IP's own counter.ip_fails = _overflow_record(ip, now)else:if ip_bucket is None:ip_bucket = _LOGIN_IP_BUCKETS[ip] = deque()- # Carry over any overflow failures this IP accrued while the dict- # was saturated, so straddling the overflow -> bucket transition- # can't double the effective per-IP limit.+ # Carry over any overflow failures this IP accrued while the dict was saturated, so straddling the+ # overflow -> bucket transition can't double the effective per-IP limit.carried, start = _overflow_take(ip, now)ip_bucket.extend([start] * carried)_prune_bucket(ip_bucket, now)@@ -383,9 +364,8 @@ def _clear_login_bucket(key: tuple[str, str]) -> None:with _LOGIN_BUCKETS_LOCK:_LOGIN_BUCKETS.pop(key, None)_LOGIN_IP_BUCKETS.pop(ip, None)- # A successful login resets the IP's throttle, including any overflow it- # accumulated during saturation (drop only this IP's entry, so a- # shard-mate's throttle is untouched).+ # A successful login resets the IP's throttle, including any overflow it accumulated during saturation (drop+ # only this IP's entry, so a shard-mate's throttle is untouched)._overflow_shard(ip).pop(ip, None)@@ -408,9 +388,8 @@ def identity(nonce: str, request: Request) -> dict:raise HTTPException(status_code = status.HTTP_400_BAD_REQUEST, detail = "nonce must decode to 16-128 bytes")- # The address + port the connection actually landed on.- # request.scope is getsockname, so this is the real local address even when bound to 0.0.0.0, never the client-- # controlled Host header.+ # The address + port the connection actually landed on. request.scope is getsockname, so this is the real local+ # address even when bound to 0.0.0.0, never the client-controlled Host header.server = request.scope.get("server") or ("", 0)host = server[0] or ""port = server[1] if server[1] is not None else 0@@ -645,9 +624,9 @@ async def change_password(detail = "New password must be different from the current password",)- # Single transaction: a separate refresh-token purge could fail after the password commit,- # leaving pre-change tokens able to mint access tokens. Conditional on the hash just- # verified, so a concurrent reset-password cannot be overwritten by it.+ # Single transaction: a separate refresh-token purge could fail after the password commit, leaving pre-change+ # tokens able to mint access tokens. Conditional on the hash just verified, so a concurrent reset-password+ # cannot be overwritten by it.new_secret = storage.update_password(current_subject,payload.new_password,@@ -678,10 +657,6 @@ async def change_password()-# API key management-# -----------------------------------------------------------------------------def _row_to_api_key_response(row: dict) -> ApiKeyResponse:return ApiKeyResponse(id = row["id"],diff --git a/studio/backend/routes/chat_generation_runs.py b/studio/backend/routes/chat_generation_runs.pyindex 56446294018..fedea1ecd61 100644--- a/studio/backend/routes/chat_generation_runs.py+++ b/studio/backend/routes/chat_generation_runs.py@@ -186,9 +186,9 @@ def _sanitize_request(payload: CreateChatGenerationRun) -> dict[str, Any]:status_code = 400,detail = "Media chat runs use the legacy streaming path",)- # Recovery currently rebuilds text and reasoning deltas, not server-side tool- # events. Keep any request whose effective policy can enter the local tool loop- # on the legacy subscriber-owned stream until those events are replayable.+ # Recovery currently rebuilds text and reasoning deltas, not server-side tool events. Keep any request whose+ # effective policy can enter the local tool loop on the legacy subscriber-owned stream until those events are+ # replayable.from routes.inference import _checkpoint_recall_may_enable_tools, _effective_enable_toolsrequest = request.model_copy(update = {"thread_id": payload.threadId})@@ -357,11 +357,10 @@ async def chat_generation_events(if await request.is_disconnected():returnif not events:- # Carries the run's progress stamp, which the lease renewals move.- # A bare keep-alive proves only that the CONNECTION is healthy, so a follower rearming its no-progress- # deadline on one could never settle a wedged run while the socket stayed up, the one case that fallback- # exists for.- # Comment framing, so _SSEDecoder still drops it and no client parsing it as an event is affected.+ # Carries the run's progress stamp, which the lease renewals move. A bare keep-alive proves only that the+ # CONNECTION is healthy, so a follower rearming its no-progress deadline on one could never settle a wedged+ # run while the socket stayed up, the one case that fallback exists for. Comment framing, so _SSEDecoder+ # still drops it and no client parsing it as an event is affected.yield f": keep-alive {int(snapshot['updatedAt'])}\n\n"return StreamingResponse(diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 752829b9c3d..231a4cfb9ee 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -1,11 +1,10 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Chat history API routes backed by studio.db.+"""Chat history API routes backed by studio.db.-SQLite-backed handlers are sync defs unless they also perform asynchronous cleanup. Those-mixed handlers explicitly send their database transaction through Starlette's threadpool.+SQLite-backed handlers are sync defs unless they also perform asynchronous cleanup; those mixed+handlers explicitly send their database transaction through Starlette's threadpool."""import asyncio@@ -181,33 +180,23 @@ class ChatThread(BaseModel):def _only_the_keys_the_snapshot_stored(self, settings: Optional[ChatThreadSettings]) -> Optional[dict]:- """Report a key the snapshot never held as absent rather than as null.-- `seed` is the one setting whose null is a value: it means this chat draws its own- rather than taking the pinned one. Spelling every unset field as null, which is- what the default dump does, would make a snapshot written before the field existed- read as a chat that had cleared it.- """+ """Report a key the snapshot never held as absent rather than as null. `seed` is the one+ setting whose null is a value: it means this chat draws its own rather than taking the+ pinned one. Spelling every unset field as null, which the default dump does, would make a+ snapshot written before the field existed read as a chat that cleared it."""if settings is None:return Nonereturn settings.model_dump(exclude_unset = True)def thread_from_row(row: dict) -> ChatThread:- """Build a ChatThread from a DATABASE row, tolerating a snapshot it cannot read.-- `settings` is the first strictly validated nested model Unsloth builds out of the- database rather than off the wire, and a stored snapshot outlives the build that- wrote it: a newer Unsloth adding a seventeenth setting, widening an enum or- raising a bound writes a blob this one rejects. Refusing it here 500s the chat on- open and takes the entire history export with it, since the export validates- every thread. `_json_loads` already shrugs off JSON that will not parse; JSON- that parses but postdates this build deserves the same treatment.-- Only the read is forgiving. The wire contract stays strict in both directions, so- a client still cannot invent a setting, and the row itself is left untouched,- which means upgrading again restores whatever this build had to drop.- """+ """Build a ChatThread from a DATABASE row, tolerating a snapshot it cannot read. `settings` is the+ first strictly validated nested model Unsloth builds out of the database rather than off the+ wire, and a stored snapshot outlives the build that wrote it: a newer Unsloth adding a setting,+ widening an enum or raising a bound writes a blob this one rejects. Refusing it here 500s the+ chat on open and takes the entire history export with it. Only the read is forgiving: the wire+ contract stays strict in both directions and the row is left untouched, so upgrading again+ restores whatever this build had to drop."""settings = row.get("settings")if isinstance(settings, dict):row = {**row, "settings": readable_thread_settings(settings)}@@ -234,27 +223,21 @@ def readable_thread_settings(settings: dict) -> Optional[dict]:def _unreadable_thread_settings(stored: dict) -> dict:- """The part of a stored snapshot this build cannot validate, and so must not delete.-- An older Unsloth opening a database a newer one wrote drops the fields it cannot read.- A blind replacement would make that loss permanent instead of temporary, so a write- carries forward everything the writer could not have known about: unknown keys, and- known keys holding values this build rejects.- """+ """The part of a stored snapshot this build cannot validate, and so must not delete. An older+ Unsloth opening a database a newer one wrote drops the fields it cannot read, and a blind+ replacement would make that loss permanent, so a write carries forward everything the writer+ could not have known about: unknown keys, and known keys holding rejected values."""readable = readable_thread_settings(stored) or {}return {k: v for k, v in stored.items() if k not in readable}def _settings_write_from_patch(patch: dict) -> Optional[dict]:- """Take `settings` / `settingsPatch` out of `patch` and describe the write they ask for.-- `settings` replaces the snapshot, `settingsPatch` applies only the fields it names,- for a client that knows what changed but not what else the row holds. The result is- handed to storage rather than executed here: the read, the merge and the guarded- metadata write all have to be one transaction, or two tabs each build a replacement- from the same stale row, or a rejected precondition returns 409 having already- committed the settings.- """+ """Take `settings` / `settingsPatch` out of `patch` and describe the write they ask for. `settings`+ replaces the snapshot, `settingsPatch` applies only the fields it names, for a client that knows+ what changed but not what else the row holds. The result is handed to storage rather than+ executed here: the read, the merge and the guarded metadata write have to be one transaction, or+ two tabs each build a replacement from the same stale row, or a rejected precondition returns+ 409 having already committed the settings."""replace = "settings" in patchmerge = "settingsPatch" in patchseq = patch.pop("settingsSeq", None)@@ -303,9 +286,8 @@ class ChatThreadPatch(BaseModel):# Applies just the fields it names. For the writer that knows what changed but not# what else the row holds, which is any write made before the row has been read.settingsPatch: Optional[ChatThreadSettings] = None- # Orders this writer's snapshot writes against its OWN earlier ones.- # So a keepalive sent on unload cannot be undone by a PATCH the server already had in hand. Never compared across- # writers: two browsers' counters mean nothing to each other.+ # Orders this writer's snapshot writes against its OWN earlier ones, so a keepalive sent on unload+ # cannot be undone by a PATCH the server already had in hand. Never compared across writers.settingsSeq: Optional[int] = NonesettingsWriter: Optional[str] = None@@ -372,9 +354,9 @@ class ChatDeleteRequest(BaseModel):class ChatClearRequest(BaseModel):- # The client fences every legacy Dexie thread it holds, so this bound has to sit above what- # a migrated install can legitimately collect: a 422 here fails the whole clear, and the- # identical retry fails with it, leaving backend history behind after Clear all.+ # The client fences every legacy Dexie thread it holds, so this bound has to sit above what a+ # migrated install can legitimately collect: a 422 here fails the whole clear, and the identical+ # retry fails with it, leaving backend history behind after Clear all.ids: list[str] = Field(default_factory = list, max_length = 200_000)operationId: Optional[str] = Field(default = None, min_length = 1, max_length = 128)@@ -393,9 +375,8 @@ class ChatExportResponse(BaseModel):class ChatInferenceSettings(BaseModel):- # allow_inf_nan: json.loads accepts bare NaN and Infinity.- # A bare NaN token in value_json reads back fine but renders as null, so refuse it at the door the way- # models/training.py does.+ # allow_inf_nan: json.loads accepts bare NaN and Infinity, and a bare NaN token in value_json reads+ # back fine but renders as null, so refuse it at the door the way models/training.py does.model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)temperature: Optional[float] = None@@ -487,9 +468,8 @@ class ChatSettingsPayload(BaseModel):maxToolCallsPerMessage: Optional[int] = Field(default = None, ge = 1)toolCallTimeout: Optional[int] = Field(default = None, ge = 1)- # Composer and RAG toggles. They describe the installation, not the browser- # that set them, so a second browser or a remote session reads them back here- # instead of falling back to defaults.+ # Composer and RAG toggles. They describe the installation, not the browser that set them, so a+ # second browser or a remote session reads them back here instead of falling back to defaults.reasoningEnabled: Optional[bool] = NonetoolsEnabled: Optional[bool] = NonecodeToolsEnabled: Optional[bool] = None@@ -767,9 +747,8 @@ def _cancel_research_runs(request: Request, run_ids: list[str]) -> None:returnsupervisor = getattr(request.app.state, "research_supervisor", None)for run_id in run_ids:- # The row is usually already gone here, which makes request_cancel raise:- # the supervisor is what actually stops the worker, so it is told first- # and the status update is the best-effort half.+ # The row is usually already gone here, which makes request_cancel raise: the supervisor is what+ # actually stops the worker, so it is told first and the status update is the best-effort half.if supervisor is not None:try:supervisor.cancel(run_id)@@ -782,13 +761,10 @@ def _cancel_research_runs(request: Request, run_ids: list[str]) -> None:def _cancel_active_generations(thread_ids: list[str]) -> None:- """Stop any generation still running for these threads.-- The sandbox goes with the thread, but a request that has not reached the- executor yet would dispatch its tool call afterwards, recreate the folder,- and write files no chat can reach. The in-flight guard only covers calls- already inside the executor. Best effort: this must never break a delete.- """+ """Stop any generation still running for these threads. The sandbox goes with the thread, but a+ request that has not reached the executor yet would dispatch its tool call afterwards, recreate+ the folder, and write files no chat can reach. The in-flight guard only covers calls already+ inside the executor. Best effort."""if not thread_ids:returntry:@@ -860,9 +836,9 @@ def _remove_conversation_archives(thread_ids, *, cutoff: "str | None" = None) ->except Exception:returnfor thread_id in thread_ids or []:- # Cut at the instant the delete was accepted, not on recreation: another tab can have recreated this id, and- # skipping the scope left the deleted conversation recallable.- # Everything archived before that instant belongs to the deleted conversation, everything after to the new one.+ # Cut at the instant the delete was accepted, not on recreation: another tab can have recreated this+ # id, and skipping the scope left the deleted conversation recallable. Everything archived before+ # that instant belongs to the deleted conversation, everything after to the new one.recreated = get_chat_thread(str(thread_id)) is not Noneif recreated and not cutoff:continue@@ -875,12 +851,9 @@ def _remove_conversation_archives(thread_ids, *, cutoff: "str | None" = None) ->async def _remove_sandboxes(thread_ids, delete_files: bool) -> "tuple[int, list[str]]":- """Drop each thread's sandbox off the event loop. Never raises.-- Returns how many went and which ids still have files. The chat is the only- way to those files, so a caller that never offered the choice can offer it- once it knows there was something to keep.- """+ """Drop each thread's sandbox off the event loop. Never raises. Returns how many went and which ids+ still have files. The chat is the only way to those files, so a caller that never offered the+ choice can offer it once it knows there was something to keep."""from starlette.concurrency import run_in_threadpooldef _remove() -> "tuple[int, list[str]]":@@ -894,9 +867,8 @@ async def _remove_sandboxes(thread_ids, delete_files: bool) -> "tuple[int, list[removed, kept = 0, []for thread_id in thread_ids:- # The row went first, and another tab can upsert the same id in the- # meantime. That chat is alive, with a tool call possibly running in- # here, so its folder is not this delete's to take.+ # The row went first, and another tab can upsert the same id in the meantime. That chat is alive,+ # with a tool call possibly running in here, so its folder is not this delete's to take.if get_chat_thread(thread_id) is not None:continue# A fork clones the message content, cards and all, so the source@@ -904,9 +876,8 @@ async def _remove_sandboxes(thread_ids, delete_files: bool) -> "tuple[int, list[if delete_files and sandbox_is_referenced_elsewhere(thread_id):if session_sandbox_has_files(thread_id):kept.append(thread_id)- # The user asked for these files and the chat is gone, so- # nothing comes back to that folder: written down, and the- # collection below takes it once the last fork goes too.+ # The user asked for these files and the chat is gone, so nothing comes back to that folder:+ # written down, and the collection below takes it once the last fork goes too.record_kept_sandbox(thread_id)continue# Again, next to the removal: the reference scan above reads@@ -915,9 +886,8 @@ async def _remove_sandboxes(thread_ids, delete_files: bool) -> "tuple[int, list[continueif remove_session_sandbox(thread_id, delete_files = delete_files):removed += 1- # A removal that had to wait for a running tool call is reported as- # kept: that call can still write a file, and this is the only- # answer the caller gets.+ # A removal that had to wait for a running tool call is reported as kept: that call can still write+ # a file, and this is the only answer the caller gets.elif sandbox_removal_deferred(thread_id) or session_sandbox_has_files(thread_id):kept.append(thread_id)return removed, kept@@ -927,9 +897,8 @@ async def _remove_sandboxes(thread_ids, delete_files: bool) -> "tuple[int, list[except Exception:logger.warning("chat_history.sandbox_cleanup_failed", exc_info = True)return 0, []- # Whatever this delete asked for: the last chat referencing a workspace the- # user already asked to delete can go through the plain path, and only the- # records marked pending are ever collected.+ # Whatever this delete asked for: the last chat referencing a workspace the user already asked to+ # delete can go through the plain path, and only the records marked pending are ever collected.from core.inference.tools import collect_orphaned_project_workspacesawait run_in_threadpool(collect_orphaned_project_workspaces)@@ -948,12 +917,9 @@ def list_attachments(def _decode_attachment_base64(payload: str) -> bytes:- """Strict base64 decode of a stored payload.-- Normalizes first: strips whitespace, fixes padding, accepts the URL-safe- alphabet. validate=False would silently drop bad characters and serve- corrupted bytes instead of failing, so raise 422 on anything else.- """+ """Strict base64 decode of a stored payload. Normalizes first: strips whitespace, fixes padding,+ accepts the URL-safe alphabet. validate=False would silently drop bad characters and serve+ corrupted bytes, so raise 422."""import base64normalized = "".join(payload.split())@@ -974,13 +940,10 @@ _AUDIO_FORMAT_MEDIA_TYPES = {def _safe_image_media_type(media_type: str) -> str:- """Clamp a data-URL media type to something inert to render.-- Imported chats store image parts verbatim, so the embedded type can be- text/html or image/svg+xml; echoing those would execute markup with the- app origin when opened. Anything not a plain raster type downloads as- bytes instead.- """+ """Clamp a data-URL media type to something inert to render. Imported chats store image parts+ verbatim, so the embedded type can be text/html or image/svg+xml; echoing those would execute+ markup with the app origin when opened. Anything not a plain raster type downloads as bytes+ instead."""lowered = media_type.strip().lower()if lowered.startswith("image/") and lowered != "image/svg+xml":return lowered@@ -1169,9 +1132,9 @@ async def delete_project():from starlette.concurrency import run_in_threadpool- # Rows first, files last: a member chat can still be running a tool in the- # workspace, and its cwd disappearing mid-call either kills the call or- # leaves what it writes next in a directory no project owns.+ # Rows first, files last: a member chat can still be running a tool in the workspace, and its cwd+ # disappearing mid-call either kills the call or leaves what it writes next in a directory no+ # project owns.cutoff = _archive_cutoff()try:project = await run_in_threadpool(@@ -1222,9 +1185,8 @@ async def delete_project(sandbox_is_referenced_elsewhere,)- # Cancelling only asks: a call already in the executor still has its- # cwd in there, and removing it strands what it writes next. The shared- # id first, since a call in a project runs as `project-<id>`.+ # Cancelling only asks: a call already in the executor still has its cwd in there, and removing it+ # strands what it writes next. The shared id first, since a call in a project runs as `project-<id>`.shared = project_session_id(project_id)idle = (await run_in_threadpool(wait_for_sessions_idle, [shared, *member_ids])@@ -1234,14 +1196,12 @@ async def delete_project(# A chat forked out of the project still shows cards for the shared# workspace, and the fork is not one of the ids deleted here.referenced = await run_in_threadpool(sandbox_is_referenced_elsewhere, shared, None)- # The row went first, so another client can create a project with this- # id in the window. It resolves to the same default path, and a tool- # call of its own may be writing in there right now.+ # The row went first, so another client can create a project with this id in the window. It resolves+ # to the same default path, and a tool call of its own may be writing in there right now.recreated = await run_in_threadpool(get_chat_project, project_id) is not Noneif not delete_files:- # The files stay, so the only job here is making them reachable: the- # row that held a custom path is gone, and a fork's cards still name- # this session.+ # The files stay, so the only job here is making them reachable: the row that held a custom path is+ # gone, and a fork's cards still name this session.await run_in_threadpool(record_orphaned_project,project_id,@@ -1255,9 +1215,8 @@ async def delete_project(project_id,)elif not idle:- # Still running after the wait. Removing a live tool call's working- # directory is worse than keeping files the user asked to delete,- # and the record below means the next delete can still collect them.+ # Still running after the wait. Removing a live tool call's working directory is worse than keeping+ # files the user asked to delete, and the record below means the next delete can still collect them.logger.warning("Kept project workspace %s: a tool call was still running in it",project_id,@@ -1268,9 +1227,8 @@ async def delete_project(project_id,)if delete_files and idle and not referenced and not recreated:- # Written down first: the delete can decline an unexpected path or- # stop at a locked file, and the row that knew where this workspace- # lives has already gone. The record is the only way back to it.+ # Written down first: the delete can decline an unexpected path or stop at a locked file, and the+ # row that knew where this workspace lives has already gone. The record is the only way back to it.await run_in_threadpool(record_orphaned_project,project_id,@@ -1278,17 +1236,15 @@ async def delete_project(True,project.get("rootPath"),)- # Once more, next to the delete itself: the record write above is- # an await, and a project created in that window resolves to this- # same path.+ # Once more, next to the delete itself: the record write above is an await, and a project created in+ # that window resolves to this same path.if await run_in_threadpool(get_chat_project, project_id) is not None:logger.warning("Kept project workspace %s: a project was created with that id",project_id,)- # Only when the new row is about these folders: the default- # root carries the project's name, so a project remade under- # this id can sit elsewhere and the old one would be stranded.+ # Only when the new row is about these folders: the default root carries the project's name, so a+ # project remade under this id can sit elsewhere and the old one would be stranded.if await run_in_threadpool(live_project_owns,project_id,@@ -1305,9 +1261,8 @@ async def delete_project(project.get("rootPath"),)elif delete_files and not recreated:- # Written down so it can be resolved and later collected: the row- # that knew where it lives is gone. The root too, since the deferred- # delete removes what the immediate one would; not for a live id.+ # Written down so it can be resolved and later collected: the row that knew where it lives is gone.+ # The root too, since the deferred delete removes what the immediate one would; not for a live id.await run_in_threadpool(record_orphaned_project,project_id,@@ -1480,21 +1435,15 @@ async def clear_history()def _clear_rows() -> tuple[list[str], list[str], list[str], bool, Optional[set]]:- """The clear, and the image snapshot the reap will be bounded to.-- Both in ONE threadpool call, so there is no await between them. Split across two,- the event loop can run another request in the gap: a chat created there survives- the transaction, but its images register before the snapshot and the reap takes- them, leaving its cards 404ing out of thumbnail_bytes.-- Narrowed, NOT closed, and the difference is worth stating. Another worker thread can- still register between the commit and the read a few instructions later, and only one- thing would truly close that: holding ``_registry_lock`` across the transaction. That- lock is what every image registration in the process takes, and this transaction is a- BEGIN IMMEDIATE that waits out contention for seconds, so paying for it means stalling- every search in every chat for the length of a clear. The window bought back is a few- instructions wide and its cost is one chat's thumbnails re-fetching. Not worth it.- """+ """The clear, and the image snapshot the reap will be bounded to. Both in ONE threadpool call,+ so there is no await between them. Split across two, the event loop can run another request+ in the gap: a chat created there survives the transaction, but its images register before+ the snapshot and the reap takes them. Narrowed, NOT closed: another worker thread can still+ register between the commit and the read, and only holding ``_registry_lock`` across the+ transaction would close that. Every image registration in the process takes that lock and+ this transaction is a BEGIN IMMEDIATE that waits out contention for seconds, so paying for+ it means stalling every search in every chat for the length of a clear, to buy back a window+ a few instructions wide."""from core.inference.search_images import snapshot_and_fence_registrationsif payload is None:@@ -1508,19 +1457,16 @@ async def clear_history(False,snapshot_and_fence_registrations(),)- # Answered by the transaction itself: read beforehand it is a guess, and a concurrent retry of the same- # operation id would replay while believing it cleared.- # The one BEGIN IMMEDIATE puts second replays while still believing it cleared; `replayed` is whichever the- # transaction actually did.+ # Answered by the transaction itself: read beforehand it is a guess, and the one BEGIN IMMEDIATE+ # puts second replays while still believing it cleared. `replayed` is whichever the transaction did.cleared, cleared_runs, cleared_chat_runs, replayed = clear_chat_history_with_replay_status(payload.ids,operation_id = payload.operationId,include_chat_generation_runs = True,)if replayed:- # A replay takes no snapshot of its own -- the chats created since the original- # clear are not its to reap. It may still have to FINISH that clear's reap,- # though, if the process died between the commit and the cleanup.+ # A replay takes no snapshot of its own: the chats created since the original clear are not its to+ # reap. It may still have to FINISH that clear's reap if the process died before the cleanup.return (cleared,cleared_runs,@@ -1559,9 +1505,8 @@ async def clear_history(# "Clear all chats" is the common bulk delete.# delete_files matches DELETE /threads: off by default, since the files are the user's.removed, kept = await _remove_sandboxes(list(dict.fromkeys(thread_ids + cleared)), delete_files)- # Search thumbnails are keyed by id, not thread.- # reapable_image_ids is the original clear's own snapshot off the ledger, so a replay's reap cannot reach a newer- # chat's images.+ # Search thumbnails are keyed by id, not thread. reapable_image_ids is the original clear's own+ # snapshot off the ledger, so a replay's reap cannot reach a newer chat's images.if not replayed or reapable_image_ids:from core.inference.search_images import clear_cacheawait run_in_threadpool(clear_cache, reapable_image_ids)@@ -1584,9 +1529,9 @@ def get_settings(current_subject: str = Depends(get_current_subject)):def compare_and_set_settings(payload: dict[str, Any], current_subject: str = Depends(get_current_subject)):- # A raw dict, as put_settings takes: automatic validation of a typed body- # renders the offending input back, and Starlette dumps with allow_nan =- # False, so a rejected NaN would 500 a request the validator refused.+ # A raw dict, as put_settings takes: automatic validation of a typed body renders the offending+ # input back, and Starlette dumps with allow_nan = False, so a rejected NaN would 500 a request the+ # validator refused.try:parsed = ConditionalChatSettingsPayload.model_validate(payload)except ValidationError as exc:diff --git a/studio/backend/routes/data_recipe/jobs.py b/studio/backend/routes/data_recipe/jobs.pyindex 355f402c9e1..c9bb9b90560 100644--- a/studio/backend/routes/data_recipe/jobs.py+++ b/studio/backend/routes/data_recipe/jobs.py@@ -45,16 +45,14 @@ router = APIRouter()# Keepalive cadence, well inside the ~100s a quick tunnel allows between body bytes._KEEPALIVE_EVERY_S = 15.0-# A stdio provider is a command this host would run, so only a UI session may-# supply one. Annotated, not a Depends default, so a direct call gets False.+# A stdio provider is a command this host would run, so only a UI session may supply one. Annotated, not a+# Depends default, so a direct call gets False.ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]def _resolve_local_v1_endpoint(request: Request) -> str:- """The /v1 URL of this process's own backend, at the address it is bound to.-- Port order: ``server_port`` (survives proxies/tunnels), the request scope, ``base_url``.- """+ """The /v1 URL of this process's own backend, at the address it is bound to. Port order:+ ``server_port`` (survives proxies/tunnels), the request scope, ``base_url``."""server = request.scope.get("server")port: Any = getattr(request.app.state, "server_port", None)if not isinstance(port, int) or port <= 0:@@ -87,12 +85,9 @@ def _request_has_desktop_access_token(request: Request) -> bool:def _used_llm_model_aliases(recipe: dict[str, Any]) -> set[str]:- """Return model_aliases actually referenced by an LLM column.-- Narrows the "Chat model loaded" gate so orphan model_config nodes don't- block unrelated runs. The ``llm-`` prefix matches- ``service.py::_recipe_has_llm_columns`` and covers all LLM column types.- """+ """Return model_aliases actually referenced by an LLM column. Narrows the "Chat model loaded" gate+ so orphan model_config nodes don't block unrelated runs. The ``llm-`` prefix matches+ ``service.py::_recipe_has_llm_columns`` and covers all LLM column types."""aliases: set[str] = set()for column in recipe.get("columns", []):if not isinstance(column, dict):@@ -188,14 +183,11 @@ def _ensure_selected_local_model_loaded(def _inject_local_structured_response_format(recipe: dict[str, Any], local_provider_names: set[str]) -> None:- """Inject an OpenAI ``response_format`` for each local llm-structured column.-- Clones the model_config and repoints the column at the clone so llm-text /- llm-judge columns sharing the alias keep free-form sampling. Without this,- data_designer only adds a prompt-level "return JSON" hint, which small GGUFs- often break. Forwarding ``response_format`` lets llama-server apply- grammar-constrained sampling, guaranteeing parseable output.- """+ """Inject an OpenAI ``response_format`` for each local llm-structured column. Clones the+ model_config and repoints the column at the clone so llm-text / llm-judge columns sharing the+ alias keep free-form sampling. Without this, data_designer only adds a prompt-level "return+ JSON" hint, which small GGUFs often break. Forwarding ``response_format`` lets llama-server+ apply grammar-constrained sampling, guaranteeing parseable output."""columns = recipe.get("columns")model_configs = recipe.get("model_configs")if not isinstance(columns, list) or not isinstance(model_configs, list):@@ -212,9 +204,8 @@ def _inject_local_structured_response_format(if not alias_to_local_mc:return- # Clone per (alias, column) so each llm-structured column gets its own- # schema without leaking response_format onto other columns sharing the- # base alias.+ # Clone per (alias, column) so each llm-structured column gets its own schema without leaking+ # response_format onto other columns sharing the base alias.seen_clone_aliases: set[str] = {mc.get("alias") for mc in model_configs if isinstance(mc.get("alias"), str)}@@ -247,9 +238,8 @@ def _inject_local_structured_response_format(params = {}clone["inference_parameters"] = params# BaseInferenceParams is extra="forbid", so response_format rides `extra_body`; llama-server reads the schema- # directly under it, not nested in a json_schema object.- # Per tools/server/README.md the schema sits directly under response_format and is converted to a GBNF grammar- # for sampling.+ # directly under it, not nested in a json_schema object. Per tools/server/README.md the schema sits directly+ # under response_format and is converted to a GBNF grammar for sampling.extra_body = params.get("extra_body")if not isinstance(extra_body, dict):extra_body = {}@@ -257,9 +247,9 @@ def _inject_local_structured_response_format("type": "json_schema","schema": output_format,}- # Internal opt-in that re-enables the ```json fence data_designer's structured-output parser expects, which the- # spec-compliant default now omits.- # The flag rides through the OpenAI SDK's extra_body passthrough alongside response_format.+ # Internal opt-in that re-enables the ```json fence data_designer's structured-output parser expects, which+ # the spec-compliant default now omits. The flag rides through the OpenAI SDK's extra_body passthrough+ # alongside response_format.extra_body["_unsloth_guided_fence"] = Trueparams["extra_body"] = extra_bodynew_configs.append(clone)@@ -274,12 +264,9 @@ def _inject_local_providers(request: Request,expect_gen: Optional[str] = None,) -> Optional[int]:- """Mutate recipe in-place: point is_local providers at this server and mint- a short-lived internal sk-unsloth-* key for workflow auth.-- Returns the minted key's row id (for the caller to revoke on completion), or- ``None`` when no local provider is reachable from an LLM column.- """+ """Mutate recipe in-place: point is_local providers at this server and mint a short-lived internal+ sk-unsloth-* key for workflow auth. Returns the minted key's row id (for the caller to revoke on+ completion), or ``None`` when no local provider is reachable from an LLM column."""providers = recipe.get("model_providers")if not providers:return None@@ -312,16 +299,14 @@ def _inject_local_providers(token = ""internal_key_id: Optional[int] = Noneif local_names & referenced_providers:- # Verify the selected local model is loaded before minting a key. Still- # a point-in-time check (TOCTOU); the /v1 endpoint returns a clear 400 if- # the model is unloaded or swapped before the subprocess calls it.+ # Verify the selected local model is loaded before minting a key. Still a point-in-time check (TOCTOU); the+ # /v1 endpoint returns a clear 400 if the model is unloaded or swapped before the subprocess calls it._ensure_selected_local_model_loaded(recipe, local_names)from auth import storage- # Mint an internal sk-unsloth-* key scoped to this run via the unified- # API-key path. Marked internal so it's hidden from the user's key list;- # the caller revokes it when the job terminates.+ # Mint an internal sk-unsloth-* key scoped to this run via the unified API-key path. Marked internal so it's+ # hidden from the user's key list; the caller revokes it when the job terminates.expires_at = (datetime.now(timezone.utc) + timedelta(hours = 24)).isoformat()token, row = storage.create_api_key(username = "unsloth",@@ -342,18 +327,18 @@ def _inject_local_providers(providers[i].pop("extra_headers", None)providers[i].pop("extra_body", None)- # llama-server's /v1/models can differ from the selected id (cache aliases, GGUF variants), and a loaded backend was- # already gated on, so the health check only mis-rejects.- # Force skip_health_check on local model_configs.+ # llama-server's /v1/models can differ from the selected id (cache aliases, GGUF variants), and a loaded+ # backend was already gated on, so the health check only mis-rejects. Force skip_health_check on local+ # model_configs.for mc in recipe.get("model_configs", []):if not isinstance(mc, dict):continueif mc.get("provider") in local_names:mc["skip_health_check"] = True# Disable thinking for local recipe inference: the <think> preamble roughly doubles tokens per row and- # pushes answers past data_designer's json-fence regex.- # Forwarded as chat_template_kwargs={enable_thinking: False} via extra_body so llama-server renders the- # template without it: llm-text columns get the latency cut, structured columns stop leaking think tags.+ # pushes answers past data_designer's json-fence regex. Forwarded as chat_template_kwargs={enable_thinking:+ # False} via extra_body so llama-server renders the template without it: llm-text columns get the latency+ # cut, structured columns stop leaking think tags.params = mc.get("inference_parameters")if not isinstance(params, dict):params = {}diff --git a/studio/backend/routes/data_recipe/mcp.py b/studio/backend/routes/data_recipe/mcp.pyindex e5822d4e743..ed9787fd059 100644--- a/studio/backend/routes/data_recipe/mcp.py+++ b/studio/backend/routes/data_recipe/mcp.py@@ -26,8 +26,8 @@ from utils.utils import safe_error_detaillogger = get_logger(__name__)router = APIRouter()-# A stdio provider is a command this host would run, so only a UI session may-# supply one. Annotated, not a Depends default, so a direct call gets False.+# A stdio provider is a command this host would run, so only a UI session may supply one. Annotated, not a+# Depends default, so a direct call gets False.ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]diff --git a/studio/backend/routes/data_recipe/seed.py b/studio/backend/routes/data_recipe/seed.pyindex f7feadb5985..ce238ab5cb8 100644--- a/studio/backend/routes/data_recipe/seed.py+++ b/studio/backend/routes/data_recipe/seed.py@@ -46,9 +46,9 @@ from utils.paths.path_utils import is_appledouble_metadatalogger = get_logger(__name__)router = APIRouter()-# Resolved on first use, not at module scope: the plugin package pulls the data-# designer engine, pandas and pyarrow, delaying uvicorn binding the port.-# False means "probed once, not installed", so callers still just see None.+# Resolved on first use, not at module scope: the plugin package pulls the data designer engine, pandas and+# pyarrow, delaying uvicorn binding the port. False means "probed once, not installed", so callers still just see+# None._CHUNKING: Any = None@@ -501,17 +501,12 @@ def _require_unstructured_ext(filename: str) -> str:def _read_native_drop(lease: str, budget: int) -> tuple[str, bytes]:- """Read a desktop drop; returns (filename, content).-- The webview never names a path directly: Rust signs what the OS handed it,- and this re-verifies and re-stats that grant before reading a byte. Same- contract as the RAG route's ``_save_native_path_upload``.-- ``budget`` is what is still allowed for this block. The path is a local file- of any size, so it is refused on its stat rather than after a multi-gigabyte- read, and the read itself stops one byte past the budget in case the file- grew between the two.- """+ """Read a desktop drop; returns (filename, content). The webview never names a path directly: Rust+ signs what the OS handed it, and this re-verifies and re-stats that grant before reading a byte.+ Same contract as the RAG route's ``_save_native_path_upload``. ``budget`` is what is still+ allowed for this block. The path is a local file of any size, so it is refused on its stat+ rather than after a multi-gigabyte read, and the read itself stops one byte past the budget in+ case the file grew between the two."""from utils.native_path_leases import NativePathLeaseError, verify_native_path_leasetry:@@ -554,9 +549,8 @@ async def upload_unstructured_file(# an upload that is about to be refused.budget = UNSTRUCTURED_RECIPE_UPLOAD_TOTAL_MAX_BYTES - _get_block_total_size(block_dir)- # Desktop drops arrive as a signed path.- # Tauri hands the webview a path, never a File (#9036); isinstance, not a truth test, since an unfilled Form param- # is still truthy.+ # Desktop drops arrive as a signed path: Tauri hands the webview a path, never a File (#9036); isinstance,+ # not a truth test, since an unfilled Form param is still truthy.lease = native_path_lease if isinstance(native_path_lease, str) else Noneif lease:original_filename, content = _read_native_drop(lease, budget)diff --git a/studio/backend/routes/data_recipe/validate.py b/studio/backend/routes/data_recipe/validate.pyindex df1a4a5103e..5a79b303840 100644--- a/studio/backend/routes/data_recipe/validate.py+++ b/studio/backend/routes/data_recipe/validate.py@@ -26,8 +26,8 @@ from utils.utils import safe_error_detail, safe_curated_detail, log_and_http_errlogger = get_logger(__name__)router = APIRouter()-# A stdio provider is a command this host would run, so only a UI session may-# supply one. Annotated, not a Depends default, so a direct call gets False.+# A stdio provider is a command this host would run, so only a UI session may supply one. Annotated, not a+# Depends default, so a direct call gets False.ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]_GITHUB_VALIDATE_NOTE = (@@ -128,11 +128,8 @@ def _collect_validation_errors(recipe: dict[str, Any]) -> list[ValidateError]:def _patch_local_providers(recipe: dict[str, Any]) -> None:- """Strip is_local and fill a dummy endpoint so validation doesn't choke.-- Strict `is True` matches _inject_local_providers: truthy non-boolean values- aren't treated as local.- """+ """Strip is_local and fill a dummy endpoint so validation doesn't choke. Strict `is True` matches+ _inject_local_providers: truthy non-boolean values aren't treated as local."""for provider in recipe.get("model_providers", []):if not isinstance(provider, dict):continuediff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.pyindex 2e991263a52..43b1ba040fa 100644--- a/studio/backend/routes/export.py+++ b/studio/backend/routes/export.py@@ -48,13 +48,11 @@ logger = get_logger(__name__)async def _ensure_export_supported() -> None:- """Reject a mutating export request up front (HTTP 400) when the host can't export.-- Keeps the backend authoritative even if a client bypasses the UI gate. Read-only endpoints+ """Reject a mutating export request up front (HTTP 400) when the host can't export. Keeps the+ backend authoritative even if a client bypasses the UI gate. Read-only endpoints(scan/status/logs) are intentionally NOT gated so the Export page can still render the reason.- Also refuses (409) while a latest-transformers install is swapping .venv_t5_latest: an- export worker spawned mid-swap could activate a half-replaced sidecar.- """+ Also refuses (409) while a latest-transformers install is swapping .venv_t5_latest: an export+ worker spawned mid-swap could activate a half-replaced sidecar."""from utils.transformers_latest import is_install_in_progressif is_install_in_progress():@@ -81,11 +79,9 @@ def _resolve_export_hf_token(push_to_hub: bool = False,allow_ambient: bool = True,) -> HfTokenArg:- """The credential this export runs under, as the anonymous-aware sentinel.-- ``None`` reads downstream as "go and find a credential" (``if token is None:- get_token()``), so a caller denied the ambient token is spelled ``False``.- """+ """The credential this export runs under, as the anonymous-aware sentinel. ``None`` reads+ downstream as "go and find a credential" (``if token is None: get_token()``), so a caller denied+ the ambient token is spelled ``False``."""token = raw_token.strip() if isinstance(raw_token, str) and raw_token.strip() else Noneif push_to_hub and token is None and not allow_ambient:raise HTTPException(@@ -248,9 +244,8 @@ async def get_export_logs("""try:backend = get_export_backend()- # No cursor on the first poll of a run: start from the run-start snapshot- # so the client gets every line since the run began (matches the SSE- # default), not the entire historical ring buffer.+ # No cursor on the first poll of a run: start from the run-start snapshot so the client gets every line since+ # the run began (matches the SSE default), not the entire historical ring buffer.if since is None:cursor = backend.get_run_start_seq()else:@@ -306,8 +301,7 @@ def _export_details(from utils.paths.storage_roots import exports_rootpath = Path(output_path)- # If it's outside exports_root, return the full absolute path- # so users can find their files on a different drive.+ # Outside exports_root, so return the full absolute path and users can find their files on another drive.if path.is_absolute():try:path.resolve().relative_to(exports_root().resolve())@@ -368,7 +362,6 @@ async def export_merged_model(from utils.transformers_version import SidecarSwapInProgressif isinstance(e, SidecarSwapInProgress):- # Expected loss of the race against a sidecar install: retryable 409.raise HTTPException(status_code = 409, detail = str(e))logger.error(f"Error exporting merged model: {e}", exc_info = True)raise HTTPException(@@ -418,7 +411,6 @@ async def export_base_model(from utils.transformers_version import SidecarSwapInProgressif isinstance(e, SidecarSwapInProgress):- # Expected loss of the race against a sidecar install: retryable 409.raise HTTPException(status_code = 409, detail = str(e))logger.error(f"Error exporting base model: {e}", exc_info = True)raise HTTPException(@@ -472,7 +464,6 @@ async def export_gguf(from utils.transformers_version import SidecarSwapInProgressif isinstance(e, SidecarSwapInProgress):- # Expected loss of the race against a sidecar install: retryable 409.raise HTTPException(status_code = 409, detail = str(e))logger.error(f"Error exporting GGUF model: {e}", exc_info = True)raise HTTPException(@@ -523,7 +514,6 @@ async def export_lora_adapter(from utils.transformers_version import SidecarSwapInProgressif isinstance(e, SidecarSwapInProgress):- # Expected loss of the race against a sidecar install: retryable 409.raise HTTPException(status_code = 409, detail = str(e))logger.error(f"Error exporting LoRA adapter: {e}", exc_info = True)raise HTTPException(@@ -532,10 +522,9 @@ async def export_lora_adapter()-# Live export log SSE. Same shape as stream_training_progress: id/event/data, a leading `retry:`, and Last-Event-ID-# honoured on reconnect.-# Worker stdout/stderr reaches the orchestrator as log entries (core/export/worker.py, orchestrator.py); shape follows-# routes/training.py.+# Live export log SSE. Same shape as stream_training_progress: id/event/data, a leading `retry:`, and+# Last-Event-ID honoured on reconnect. Worker stdout/stderr reaches the orchestrator as log entries+# (core/export/worker.py, orchestrator.py); shape follows routes/training.py.def _format_sse(data: str,event: str,@@ -579,9 +568,8 @@ async def stream_export_logs("""backend = get_export_backend()- # Starting cursor: explicit `since` wins, then Last-Event-ID on reconnect,- # else the run-start snapshot so the client sees every line since the run- # began even if the SSE connection opened after the export-kickoff POST.+ # Starting cursor: explicit `since` wins, then Last-Event-ID on reconnect, else the run-start snapshot so the+ # client sees every line since the run began even if the SSE connection opened after the export-kickoff POST.last_event_id = request.headers.get("last-event-id")if since is None and last_event_id is not None:try:diff --git a/studio/backend/routes/llama.py b/studio/backend/routes/llama.pyindex fa0487c2649..4367c37b974 100644--- a/studio/backend/routes/llama.py+++ b/studio/backend/routes/llama.py@@ -7,15 +7,13 @@ GET /api/llama/update-status -> is a newer prebuilt available + job stateGET /api/llama/update-changelog -> new carried changes since the installed buildPOST /api/llama/update -> download + atomically swap to the latest-Detection reuses utils.llama_cpp_freshness; the swap reuses-install_llama_prebuilt.py via utils.llama_cpp_update. Both fail open so the UI-never blocks on a missing marker / offline GitHub.--whisper.cpp updates piggyback here: the status payload carries a whisper-sub-status (update_available is the llama OR whisper union) and the apply job-chains a whisper phase after the llama phase when whisper is behind, with a-per-phase breakdown in job.phases. All pre-existing top-level fields keep-their shape, so older clients keep working unchanged.+Detection reuses utils.llama_cpp_freshness; the swap reuses install_llama_prebuilt.py via+utils.llama_cpp_update. Both fail open so the UI never blocks on a missing marker / offline GitHub.++whisper.cpp updates piggyback here: the status payload carries a whisper sub-status (update_available is the+llama OR whisper union) and the apply job chains a whisper phase after the llama phase when whisper is behind,+with a per-phase breakdown in job.phases. All pre-existing top-level fields keep their shape, so older clients+keep working unchanged."""from __future__ import annotationsdiff --git a/studio/backend/routes/llama_compat.py b/studio/backend/routes/llama_compat.pyindex aeebd884b92..95cb9844c47 100644--- a/studio/backend/routes/llama_compat.py+++ b/studio/backend/routes/llama_compat.py@@ -3,15 +3,14 @@"""Answer engine discovery probes with JSON, or with a 404, but never with the app.-Probes for engine endpoints used to land on main.py's SPA catch-all, so ``GET /props``-returned 200 and a page of HTML. That is worse than a 404: a probe reads the status-before the body. Served here: ``/props``, ``/v1/props``, ``/version``. Everything else-in llama-server's table gets an explicit 404, on its real method as well as GET.--Deliberately NOT served: Ollama's ``/api/tags`` and ``/api/show``. Answering them makes-a client select Ollama and then fail on ``/api/chat``, which Studio does not implement;-the reporting user's client instead fell back to the OpenAI surface and worked.-Advertising a protocol we do not have is the HTML 200 again, one layer up.+Probes for engine endpoints used to land on main.py's SPA catch-all, so ``GET /props`` returned 200 and a page+of HTML. That is worse than a 404: a probe reads the status before the body. Served here: ``/props``,+``/v1/props``, ``/version``. Everything else in llama-server's table gets an explicit 404, on its real method as+well as GET.++Deliberately NOT served: Ollama's ``/api/tags`` and ``/api/show``. Answering them makes a client select Ollama+and then fail on ``/api/chat``, which Studio does not implement; the reporting user's client instead fell back+to the OpenAI surface and worked. Advertising a protocol we do not have is the HTML 200 again, one layer up."""from __future__ import annotations@@ -139,9 +138,9 @@ def _server_props() -> dict:if public_id:props["model_path"] = public_id- # These describe the CHILD's route table and web UI, not ours: Studio launches with- # --metrics, so endpoint_metrics arrives true while public /metrics 404s here- # (tools/server/server-context.cpp puts all three flags in the payload).+ # These describe the CHILD's route table and web UI, not ours: Studio launches with --metrics, so+ # endpoint_metrics arrives true while public /metrics 404s here (tools/server/server-context.cpp puts all three+ # flags in the payload).for _child_only in ("ui", "ui_settings", "cors_proxy_enabled"):props.pop(_child_only, None)props["endpoint_slots"] = False@@ -169,8 +168,8 @@ def _server_props() -> dict:return props-# Slash forms too: FastAPI's redirect never fires.-# The catch-all fully matches "/props/" and returns index.html; routes/inference.py registers "/v1/models/" likewise.+# Slash forms too: FastAPI's redirect never fires. The catch-all fully matches "/props/" and returns+# index.html; routes/inference.py registers "/v1/models/" likewise.@router.get("/props", include_in_schema = False)@router.get("/props/", include_in_schema = False)@router.get("/v1/props", include_in_schema = False)@@ -193,9 +192,9 @@ async def _probe_not_found():raise HTTPException(status_code = 404, detail = "API endpoint not found")-# Without these a POST hit the GET-only catch-all and returned 405, reading as "exists, wrong method". HEAD is here-# because Starlette does not admit it on a GET route (measured, fastapi 0.141.1); GET stays with the catch-all so its-# asset lookup wins, and OPTIONS is untouched for CORS preflight.+# Without these a POST hit the GET-only catch-all and returned 405, reading as "exists, wrong method". HEAD is+# here because Starlette does not admit it on a GET route (measured, fastapi 0.141.1); GET stays with the catch-all+# so its asset lookup wins, and OPTIONS is untouched for CORS preflight._PROBE_DENIED_METHODS = ["HEAD", "POST", "PUT", "PATCH", "DELETE"]@@ -233,11 +232,9 @@ for _slots_form in _both_forms("/slots/{id_slot}"):def add_get_denials(app) -> None:- """404 the engine paths on GET as well, for an app with no frontend mounted.-- The GET denial normally comes from main.py's SPA catch-all, registered only when- setup_frontend() finds a build. In API-only mode there is none, so these paths- matched on method alone and answered 405, which a client reads as "endpoint exists".+ """404 the engine paths on GET as well, for an app with no frontend mounted. The GET denial normally comes+ from main.py's SPA catch-all, registered only when setup_frontend() finds a build. In API-only mode there is+ none, so these paths matched on method alone and answered 405, which a client reads as "endpoint exists"."""for path in sorted(_ENGINE_PROBE_PATHS) + sorted(_UNSERVED_V1_PROBE_PATHS):for form in _both_forms(f"/{path}"):diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.pyindex 10e3eebfbdc..f58f82a2f60 100644--- a/studio/backend/routes/mcp_servers.py+++ b/studio/backend/routes/mcp_servers.py@@ -57,17 +57,16 @@ logger = structlog.get_logger(__name__)router = APIRouter()-# Only a UI session may define a local command; API keys keep http(s) MCP.-# Annotated, not a Depends default: these routes are also called directly by the-# tests, where a Depends object is truthy and would read as "API key".+# Only a UI session may define a local command; API keys keep http(s) MCP. Annotated, not a Depends default:+# these routes are also called directly by the tests, where a Depends object is truthy and would read as "API key".ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]WithoutCredential = Annotated[bool, Depends(request_admitted_without_credential)]def _looks_like_command(value: str) -> bool:- """Whitespace is a one-way signal: a URL can't hold an unencoded space, so- a value with whitespace is definitely a command. No whitespace proves- nothing (a lone token may be a single-arg command or a scheme-less URL)."""+ """Whitespace is a one-way signal: a URL can't hold an unencoded space, so a value with whitespace is+ definitely a command. No whitespace proves nothing (a lone token may be a single-arg command or a+ scheme-less URL)."""return any(ch.isspace() for ch in value)@@ -306,9 +305,8 @@ def list_mcp_servers():rows = mcp_servers_db.list_servers()if via_api_key or no_credential:- # Drop the row, not just its fields: `url` is the argv (carries- # credentials), `headers` is the subprocess env, and a blanked url would- # round-trip into update as a bogus command.+ # Drop the row, not just its fields: `url` is the argv (carries credentials), `headers` is the subprocess+ # env, and a blanked url would round-trip into update as a bogus command.rows = [row for row in rows if not is_stdio(row["url"])]return [_row_to_response(row, include_headers = not no_credential) for row in rows]@@ -392,14 +390,13 @@ async def update_mcp_server()if not changes:raise HTTPException(status_code = 400, detail = "No fields to update")- # Both directions, so an API key can neither repoint an http row at a command- # nor edit a stdio row's env/name/enabled flag. Before every side effect, so a- # refusal leaves the row, its OAuth tokens, cache and sessions untouched.+ # Both directions, so an API key can neither repoint an http row at a command nor edit a stdio row's+ # env/name/enabled flag. Before every side effect, so a refusal leaves the row, its OAuth tokens, cache and+ # sessions untouched.if is_stdio(old["url"]) or is_stdio(changes.get("url", old["url"])):require_ui_session_for_local_commands(via_api_key)- # headers == HTTP headers (remote) or env vars (stdio). On a transport-type- # switch with no new headers, drop the old ones so env secrets aren't- # re-sent as HTTP headers (or vice versa).+ # headers == HTTP headers (remote) or env vars (stdio). On a transport-type switch with no new headers, drop+ # the old ones so env secrets aren't re-sent as HTTP headers (or vice versa).if ("url" in changesand is_stdio(changes["url"]) != is_stdio(old["url"])@@ -487,9 +484,9 @@ async def refresh_mcp_server_tools(if current is not None and not any(current.get(k) != server.get(k) for k in TOOL_CACHE_INVALIDATING_FIELDS):- # Start the cool-off so the next chat send does not re-hang on this server's timeout. If the row- # changed while the probe was awaiting, the FAILURE belongs to the old config and must not park- # the newly edited server.+ # Start the cool-off so the next chat send does not re-hang on this server's timeout. If the row changed+ # while the probe was awaiting, the FAILURE belongs to the old config and must not park the newly edited+ # server.record_probe_failure(server_id, use_oauth)return McpServerProbeResult(ok = False, error = safe_curated_detail(exc))diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex ecf536fac5c..770e5fd9b50 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -1,8 +1,6 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Model management API routes."""-import asyncioimport hashlibimport json@@ -37,9 +35,9 @@ from hub.services.models.catalog_classification import (_repo_is_diffusers,)-# Compatibility aliases: these moved to catalog_classification, but callers and tests still-# resolve them from routes.models. Assigned through the module rather than re-imported, since-# an import this module never loads reads as a botched hoist to verify_import_hoist.py.+# Compatibility aliases: these moved to catalog_classification, but callers and tests still resolve them+# from routes.models. Assigned through the module rather than re-imported, since an import this module never+# loads reads as a botched hoist to verify_import_hoist.py._AMBIGUOUS_DIFFUSION_GGUF_ARCHS = _catalog_classification._AMBIGUOUS_DIFFUSION_GGUF_ARCHS_DIFFUSION_GGUF_ARCHS = _catalog_classification._DIFFUSION_GGUF_ARCHS_TASK_CLASSIFY_WALK_SECONDS = _catalog_classification._TASK_CLASSIFY_WALK_SECONDS@@ -58,14 +56,12 @@ _local_family_needles = _catalog_classification._local_family_needles_local_is_diffusers = _catalog_classification._local_is_diffusers_local_model_can_chat = _catalog_classification._local_model_can_chat_task_classify_sort_key = _catalog_classification._task_classify_sort_key-# core.inference.llama_cpp imports this one. Without the alias that import raises, and the-# probe's `except Exception: return True` reads the raise as "the page can build it",-# promising an MoE or familyless GGUF a load that dies in llama-server.+# core.inference.llama_cpp imports this one. Without the alias that import raises, and the probe's+# `except Exception: return True` reads the raise as "the page can build it", promising an MoE or familyless+# GGUF a load that dies in llama-server._video_family_buildable = _catalog_classification._video_family_buildable-# The rest of what moved. Nothing in-repo reads these, which is why they went unnoticed ---# the one name that did have a caller surfaced as a wrong message, never an ImportError.-# All were importable from routes.models before and two are public, so a downstream fork or-# an older script may hold one, which this repo cannot see.+# The rest of what moved. Nothing in-repo reads these, but all were importable from routes.models+# before and two are public, so a downstream fork or an older script may hold one._H3_DENOISER_GGUF_PREFIXES = _catalog_classification._H3_DENOISER_GGUF_PREFIXES_LOADABLE_MEDIA_GGUF_TASKS = _catalog_classification._LOADABLE_MEDIA_GGUF_TASKS_MAX_TASK_CLASSIFY_GGUFS = _catalog_classification._MAX_TASK_CLASSIFY_GGUFS@@ -94,17 +90,17 @@ class CachedModelRepo(BaseModel):# Diffusion-tagged repo with NO top-level model_index.json: needs from_single_file + a filename.single_file: Optional[bool] = None# True for an sd.cpp companion mirror (VAE / text encoders, no denoiser). Declared here or- # response_model drops it and the flag never reaches the picker that has to filter on it.+ # response_model drops it before the picker that filters on it.companion: Optional[bool] = None- # Snapshot path for a copy its bare repo id cannot reach (legacy/default cache while- # another is active); undeclared, response_model drops it and the picker uses the active cache.+ # Snapshot path for a copy its bare repo id cannot reach (legacy/default cache while another is+ # active); undeclared, response_model drops it and the picker uses the active cache.load_id: Optional[str] = None# "adapter" for a cached LoRA/PEFT repo; pickers that offer whole models filter on it.model_format: Optional[str] = None# False for an encoder-only repo (embedding/CLIP/ViT); undeclared, response_model drops it.can_chat: Optional[bool] = None- # True for an image/video diffusion repo. Not the same question as task, which says only- # whether this backend can load it as a pipeline; an untrusted or unrecognised one has none.+ # True for an image/video diffusion repo. Not the same question as task, which says only whether this+ # backend can load it as a pipeline.diffusers: Optional[bool] = None@@ -124,13 +120,8 @@ def _normalize_hf_token(hf_token) -> Optional[str]:def _safe_is_dir(path) -> bool:- """``Path.is_dir()`` returning ``False`` instead of raising.-- Python >= 3.12 propagates ``PermissionError`` from ``is_dir()``;- folder-scan endpoints probe system locations (e.g. root-owned- ``/usr/share/ollama``) and must treat un-stat-able paths as "not a- directory", never 500.- """+ """``Path.is_dir()`` returning ``False`` instead of raising: Python >= 3.12 propagates+ ``PermissionError``, and folder-scan endpoints probe root-owned system locations."""try:return Path(path).is_dir()except OSError:@@ -155,13 +146,10 @@ from utils.hidden_models import (def hidden_model_matchers() -> tuple[list[str], list[str], list[str]]:- """Substring needles, exact repo ids, and exact resolved paths identifying- infra models (the RAG embedder and the llama.cpp install validation probe)- that pickers hide. Served by the ``/api/hub/hidden-models`` endpoint. A- configured HF-repo embedder is published as its exact lowercased repo id- (mirroring ``utils.hidden_models.is_hidden_model``) and a local-path- embedder as its exact resolved path only: a generic basename like "model"- must not substring-hide unrelated chat models."""+ """Substring needles, exact repo ids, and exact resolved paths identifying infra models (the RAG embedder+ and the llama.cpp install validation probe) that pickers hide. A configured HF-repo embedder is+ published as its exact lowercased repo id and a local-path embedder as its exact resolved path only: a+ generic basename like "model" must not substring-hide unrelated chat models."""from core.rag import config as rag_configneedles = [@@ -261,7 +249,6 @@ try:resolve_export_dir,)except ImportError:- # Fallback: import from parent directory.parent_backend = backend_path.parent / "backend"if str(parent_backend) not in sys.path:sys.path.insert(0, str(parent_backend))@@ -325,11 +312,9 @@ from utils.paths.path_utils import is_appledouble_metadatarouter = APIRouter()logger = get_logger(__name__)-# The shortest context worth pricing, used to separate the part of a footprint-# that shrinks with context from the part that does not. Not zero: zero means-# "the model's native length" to the planner, which is the opposite of what this-# asks. One llama.cpp KV stream pads to 256, so a smaller number would not make-# the cache any smaller and only invites a divide-by-zero somewhere downstream.+# The shortest context worth pricing, separating the part of a footprint that shrinks with context from the+# part that does not. Not zero: zero means "the model's native length" to the planner. One llama.cpp KV+# stream pads to 256, so a smaller number would not shrink the cache._MIN_PRICED_CONTEXT = 256@@ -338,7 +323,6 @@ def derive_model_type(audio_type: Optional[str],is_embedding: bool = False,) -> ModelType:- """Collapse individual capability flags into a single model modality string."""if is_embedding:return "embeddings"if audio_type is not None:@@ -349,19 +333,14 @@ def derive_model_type(def _resolve_hf_cache_dir() -> Path:- """Resolve local HF cache root used by hub downloads."""from utils.hf_cache_settings import get_hf_cache_pathsreturn get_hf_cache_paths().hub_cachedef _is_model_directory(d: Path) -> bool:- """Return ``True`` when *d* looks like a model directory.-- Requires both a config (``config.json``/``adapter_config.json``) and- weight files. Excludes ``mmproj`` GGUFs (vision projectors), calibration- imatrices and non-weight ``.bin`` files (``tokenizer.bin`` etc.) to avoid- false positives.- """+ """True when *d* looks like a model directory: both a config (``config.json`` /+ ``adapter_config.json``) and weight files, excluding ``mmproj`` GGUFs (vision projectors),+ calibration imatrices and non-weight ``.bin`` files (``tokenizer.bin`` etc.)."""def _is_weight_file(f: Path) -> bool:if is_appledouble_metadata(f):@@ -390,8 +369,8 @@ def _is_model_directory(d: Path) -> bool:return False-# Weight ``.bin`` files the local scanners accept, as opposed to companions like-# ``tokenizer.bin``. Mirrors ``_is_weight_file`` so every weight check agrees.+# Weight ``.bin`` files the local scanners accept, as opposed to companions like ``tokenizer.bin``.+# Mirrors ``_is_weight_file`` so every weight check agrees._WEIGHT_BIN_PREFIXES = ("pytorch_model", "model", "adapter_model", "consolidated")@@ -401,12 +380,12 @@ def _is_weight_bin(name: str) -> bool:def _has_non_gguf_weights(path: Path) -> bool:- """True if *path* holds non-GGUF weight files (``.safetensors`` or a weight- ``.bin``), ignoring companion ``.bin`` files such as ``tokenizer.bin`` so a- GGUF-only folder is not misread as a plain checkpoint."""+ """True if *path* holds non-GGUF weight files (``.safetensors`` or a weight ``.bin``), ignoring+ companion ``.bin`` files such as ``tokenizer.bin`` so a GGUF-only folder is not misread as a plain+ checkpoint."""try:- # Only the safetensors arm needs the check: a weight ".bin" is recognised by its name- # prefix, which a "._" already fails.+ # Only the safetensors arm needs the check: a weight ".bin" is recognised by its name prefix, which a+ # "._" already fails.if any(not is_appledouble_metadata(f) for f in path.glob("*.safetensors")):return Truereturn any(_is_weight_bin(f.name) for f in path.glob("*.bin"))@@ -420,12 +399,9 @@ def _local_pipeline_index(d: Path) -> bool:def _servable_gguf_names(directory: Path) -> list[str]:- """The ``.gguf`` names in *directory* that count as a model being present there.-- An imatrix is calibration data, not a model artifact, so it must not make an empty- folder look like one. mmproj and MTP drafters DO count: they are companions of a real- model, and presence is all they decide (format still asks _is_main_gguf_filename).- """+ """The ``.gguf`` names in *directory* that count as a model being present there. An imatrix is+ calibration data, not a model artifact; mmproj and MTP drafters DO count, since they are+ companions of a real model and presence is all they decide."""return [p.namefor p in directory.glob("*.gguf")@@ -434,14 +410,10 @@ def _servable_gguf_names(directory: Path) -> list[str]:def _is_gguf_companion_only_dir(path: Path) -> bool:- """True for a folder whose entire content is GGUF companions -- a lone mmproj adapter, an- MTP drafter, or both -- with nothing servable beside them.-- The scanners report ``model_format = None`` for such a folder, because neither companion is a- primary weight, and that is also what a plain checkpoint reports. The custom-folder scan below- validates GGUF rows through ``detect_gguf_model`` and waves the rest through, so without this- the folder is published as a model that no loader can start.- """+ """True for a folder whose entire content is GGUF companions (a lone mmproj adapter, an MTP drafter, or+ both) with nothing servable beside them. The scanners report ``model_format = None`` for such a folder,+ which is also what a plain checkpoint reports, and the custom-folder scan waves non-GGUF rows through,+ so without this the folder is published as a model no loader can start."""try:if not path.is_dir():return False@@ -495,7 +467,6 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Locahas_pipeline_index = _local_pipeline_index(child)has_model_files = has_gguf or has_non_gguf_weights or has_config or has_pipeline_indexexcept OSError:- # Skip unreadable children rather than failing the scan.continueif not has_model_files:continue@@ -629,22 +600,13 @@ def _scan_hf_cache(def _dir_model_format(path: Path, recursive: bool = False) -> Optional[str]:- """Return ``"gguf"`` for a directory whose only weights are ``.gguf`` files.-- LM Studio and custom GGUF folders frequently lack a ``-GGUF`` name suffix,- so the UI relies on this hint to route them through the GGUF load path- rather than treating them as plain local checkpoints. A directory whose only- ``.gguf`` is an mmproj vision adapter is not one: the variant selector drops- mmproj, so that path would find nothing to serve.-- ``recursive`` is for HF cache snapshots, which keep split quants in per-quant- subdirectories: a flat glob sees no ``.gguf`` there and would report the- snapshot as non-GGUF, hiding every sharded repo from the GGUF pickers. It looks- one level down rather than walking the tree, because that is where split quants- live and ``/api/models/local`` is async: an unbounded ``rglob`` per repo would- have to exhaust every non-GGUF snapshot before concluding there is no GGUF,- blocking the event loop on a large cache.- """+ """Return ``"gguf"`` for a directory whose only weights are ``.gguf`` files. LM Studio and custom+ GGUF folders frequently lack a ``-GGUF`` name suffix. A directory whose only ``.gguf`` is an+ mmproj vision adapter is not one: the variant selector drops mmproj, so that path would find+ nothing. ``recursive`` is for HF cache snapshots, which keep split quants in per-quant+ subdirectories: a flat glob would report the snapshot as non-GGUF and hide every sharded repo.+ One level down, not a walk: ``/api/models/local`` is async and an unbounded ``rglob`` per repo+ would block the event loop."""try:def _servable(p: Path) -> bool:@@ -661,11 +623,8 @@ def _dir_model_format(path: Path, recursive: bool = False) -> Optional[str]:def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:- """Scan an LM Studio models directory for model files.-- LM Studio uses a ``publisher/model-name`` folder structure with GGUF- files, or standalone GGUF files at the top level.- """+ """Scan an LM Studio models directory: ``publisher/model-name`` folders of GGUF files, or+ standalone GGUFs at the top level."""if not lm_dir.exists() or not lm_dir.is_dir():return []@@ -729,7 +688,6 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:)continue- # child is a publisher directory; scan its subdirectories.for model_dir in child.iterdir():try:if model_dir.is_dir():@@ -787,12 +745,9 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:def _ollama_links_dir(ollama_dir: Path) -> Optional[Path]:- """Return a writable directory for Ollama ``.gguf`` symlinks.-- Prefers ``<ollama_dir>/.studio_links/`` so links sit next to their- blobs; falls back to a per-ollama-dir namespace under Unsloth's cache- when the models dir is read-only (common for system installs).- """+ """A writable directory for Ollama ``.gguf`` symlinks. Prefers ``<ollama_dir>/.studio_links/`` so+ links sit next to their blobs; falls back to a per-ollama-dir namespace under Unsloth's cache when+ the models dir is read-only (common for system installs)."""from utils.paths.storage_roots import cache_rootprimary = ollama_dir / ".studio_links"@@ -825,22 +780,13 @@ def _ollama_links_dir(ollama_dir: Path) -> Optional[Path]:def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[LocalModelInfo]:- """Scan an Ollama models directory for downloaded models.-- Ollama uses a content-addressable layout- (``manifests/<host>/<namespace>/<model>/<tag>`` + ``blobs/sha256-...``);- we ``rglob`` all manifests so every layout depth is found. Each- manifest is JSON with a ``layers`` array: the- ``application/vnd.ollama.image.model`` layer holds the GGUF weights- and ``...image.projector`` is the vision adapter.-- Ollama blobs lack the ``.gguf`` extension the loading pipeline- requires, so we create ``.gguf``-named links to them (one subdir per- model, keyed by a short hash of the manifest path, so- ``detect_mmproj_file`` only sees that model's projector). Links are- symlinks when possible, else hardlinks; the link dir is- ``.studio_links/`` when writable, else Unsloth's cache.- """+ """Scan an Ollama models directory for downloaded models. Ollama uses a content-addressable layout+ (``manifests/<host>/<namespace>/<model>/<tag>`` + ``blobs/sha256-...``); ``rglob`` finds every+ layout depth. The ``application/vnd.ollama.image.model`` layer holds the GGUF weights and+ ``...image.projector`` is the vision adapter. Ollama blobs lack the ``.gguf`` extension the+ loading pipeline requires, so create ``.gguf``-named links to them, one subdir per model keyed+ by a short hash of the manifest path so ``detect_mmproj_file`` only sees that model's projector.+ Symlinks when possible, else hardlinks."""manifests_root = ollama_dir / "manifests"if not manifests_root.is_dir():return []@@ -856,12 +802,8 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Locareturn []def _make_link(link_dir: Path, link_name: str, target: Path) -> Optional[str]:- """Create a .gguf-named link to an Ollama blob.-- Tries symlink, then hardlink; skips the model if neither works- (a multi-GB copy in a sync request would block the backend).- Idempotent: skips recreation when a valid link already exists.- """+ """Create a .gguf-named link to an Ollama blob. Symlink, then hardlink; skips the model if neither+ works (a multi-GB copy in a sync request would block the backend). Idempotent."""link_dir.mkdir(parents = True, exist_ok = True)link_path = link_dir / link_nameresolved = target.resolve()@@ -939,12 +881,9 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Locae,)continue- # Parsed, but the shape is still whatever was on disk. rglob("*") hands us every- # file under manifests/, so a pruned pull, an editor backup, or any stray JSON can- # be a list or a string; .get() on one raises AttributeError, which neither this- # loop's `except OSError` nor the caller's catches, and one such file would 500- # the whole picker. Mirrors hub/services/models/ollama.py, which already validates- # each level of the same document.+ # rglob("*") hands us every file under manifests/, so a pruned pull, an editor backup, or any stray JSON can+ # be a list or a string; .get() on one raises AttributeError, which neither this loop's `except OSError`+ # nor the caller's catches, and one such file would 500 the whole picker.if not isinstance(manifest, dict):logger.debug("Skipping Ollama manifest %s: top level is not an object", tag_file)continue@@ -1021,9 +960,8 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Locamodel_id = f"ollama/{repo_name}:{tag}",display_name = display + suffix,path = gguf_link_path,- # The frontend groups and labels these rows by this value- # (local-model-options.ts, pickers.tsx); "custom" hid them- # in the generic folder section (#9986).+ # The frontend groups and labels these rows by this value (local-model-options.ts, pickers.tsx);+ # "custom" hid them in the generic folder section (#9986).source = "ollama",updated_at = updated_at,),@@ -1227,10 +1165,8 @@ def collect_local_models(record_scan_failure(str(folder.get("path", folder_path)), e)continuenote_scan_folder_scanned(str(folder.get("path", folder_path)), found = bool(custom_models))- # Keep an already-attributed source: a registered ~/.ollama/models (or a- # folder shadowing the HF cache) must not re-stamp its rows as generic- # custom entries. Mirrors _promote_to_custom_source() in- # hub/services/models/local_inventory.py.+ # Keep an already-attributed source: a registered ~/.ollama/models (or a folder shadowing the HF+ # cache) must not re-stamp its rows as generic custom entries.local_models += [mif m.source in ("hf_cache", "ollama", "hermes")@@ -1238,8 +1174,8 @@ def collect_local_models(for m in custom_models]- # Deduplicate, but always keep custom folder entries (keyed by (id, source)) so they show- # in the "Custom Folders" UI section even when the model is also in the HF cache.+ # Deduplicate, but always keep custom folder entries (keyed by (id, source)) so they show in the+ # "Custom Folders" UI section even when the model is also in the HF cache.deduped: dict[str, LocalModelInfo] = {}for model in local_models:semantic_id = model.model_id if model.source == "hf_cache" and model.model_id else model.id@@ -1299,7 +1235,6 @@ class _CompatLocalCacheChanged(RuntimeError):def _compat_inventory_path_identity(path: object) -> str:- """Canonical source identity for compatibility inventory flights."""raw = str(path)try:return os.path.normcase(os.path.realpath(os.path.expanduser(raw)))@@ -1316,9 +1251,8 @@ async def _shared_compat_local_inventory_scan(requested_sources = sourcesdef classify(models: List[LocalModelInfo]) -> List[LocalModelInfo]:- # Tag each model with its task and native-audio type for the model pickers.- # Inside the shared flight so overlapping callers reuse one classified result- # instead of each repeating the GGUF header reads.+ # Tag each model with its task and native-audio type for the pickers, inside the shared flight so+ # overlapping callers reuse one classified result instead of each repeating the GGUF header reads.classified = []for model in models:task, audio_type = _catalog_classification._local_model_classification_for_task(@@ -1354,10 +1288,9 @@ async def _shared_compat_local_inventory_scan(# Discard obsolete results and retry their waiters against the current cache epoch.superseded: Optional[List[LocalModelInfo]] = Nonefor _attempt in range(_COMPAT_LOCAL_INVENTORY_MAX_ATTEMPTS):- # Epoch first: the sources and folders below are read after it, so any- # change to them lands in a later epoch and the post-scan check sees it.- # A caller-supplied ``sources`` stays pinned - the /local route validated- # its models_dir against exactly those roots.+ # Epoch first: the sources and folders below are read after it, so any change to them lands in a later epoch+ # and the post-scan check sees it. A caller-supplied ``sources`` stays pinned, since the /local route+ # validated its models_dir against exactly those roots.epoch = hf_cache_scan.hf_cache_scans_epoch()scan_sources = requested_sources or _compat_local_inventory_sources()try:@@ -1384,25 +1317,19 @@ async def _shared_compat_local_inventory_scan(except _CompatLocalCacheChanged as changed:superseded = changed.modelscontinue- # Invalidations are outpacing the walk, so no scan will ever confirm as- # current. Answer with the freshest one (the loop only reaches here through- # the retry path, so there is always one) instead of rescanning forever.+ # Invalidations are outpacing the walk, so no scan will ever confirm as current. Answer with the+ # freshest one instead of rescanning forever.logger.warning("Compat local inventory kept racing cache invalidations; serving the last scan")return await asyncio.to_thread(classify, superseded)async def _invalidate_local_scans() -> None:- """Retire the cached local scans after something was deleted from disk.-- Every successful deletion branch has to call this. The /v1/models servability scan is- cached against the resolver generation, so a branch that returns without bumping it- keeps advertising what was just removed until the catalog TTL expires.-- Off the loop, like the other async invalidation sites in this file: invalidate_index- takes the resolver lock, and _index() holds that across a full multi-root filesystem- scan, so calling it inline from an async route would stall unrelated requests and- in-flight inference streams behind a rebuild.- """+ """Retire the cached local scans after something was deleted from disk. Every successful deletion+ branch has to call this: the /v1/models servability scan is cached against the resolver+ generation, so a branch that returns without bumping it keeps advertising what was just removed.+ Off the loop: invalidate_index takes the resolver lock, and _index() holds that across a full+ multi-root filesystem scan, so calling it inline would stall unrelated requests behind a+ rebuild."""from core.inference.local_model_resolver import invalidate_indexawait asyncio.to_thread(invalidate_index)@@ -1489,7 +1416,6 @@ async def add_scan_folder_endpoint(folder, inserted = await asyncio.to_thread(add_scan_folder_with_status, body.path)except ValueError as e:logger.warning("Scan folder rejected: %s (path=%s)", e, body.path)- # Forward the curated, path-free validation message.rejection_message = str(e)raise HTTPException(status_code = 400, detail = rejection_message)logger.info("Scan folder added: %s", folder.get("path"))@@ -1518,21 +1444,13 @@ async def remove_scan_folder_endpoint(def _dir_has_downloaded_model(directory: Path, max_entries: int = 4000) -> bool:- """True if *directory* actually holds a downloaded model.-- Recommended-folder chips should only appear once the well-known dir- has real weights, not just an empty LM Studio/Ollama scaffold. Two- layouts: a GGUF/safetensors/PyTorch-bin weight file anywhere in the- tree (LM Studio, plain dirs) or the Ollama content-addressable store- (a non-empty ``manifests/`` beside ``blobs/``, whose blobs carry no- extension). Weight detection mirrors the local scanner so a folder the- chip leads to is one the scanner would actually surface a model from.- Bounded by *max_entries* so a huge tree can't stall the request.- """- # Ollama layout: each manifest is JSON referencing content-addressable blobs. A manifest- # alone is not enough -- a failed or pruned pull leaves it behind with the model blob- # missing, so resolve the ``application/vnd.ollama.image.model`` layer to an on-disk blob- # before counting it (mirrors _scan_ollama_dir), else the chip leads to an empty picker.+ """True if *directory* actually holds a downloaded model, so a recommended-folder chip appears only once+ the well-known dir has real weights rather than an empty LM Studio/Ollama scaffold. Two layouts: a+ weight file anywhere in the tree, or the Ollama content-addressable store (a non-empty ``manifests/``+ beside ``blobs/``). Weight detection mirrors the local scanner, and *max_entries* bounds the walk."""+ # Ollama layout: a manifest alone is not enough, since a failed or pruned pull leaves it behind with the+ # model blob missing, so resolve the ``application/vnd.ollama.image.model`` layer to an on-disk blob before+ # counting it, else the chip leads to an empty picker.visited = 0manifests = directory / "manifests"blobs = directory / "blobs"@@ -1548,9 +1466,8 @@ def _dir_has_downloaded_model(directory: Path, max_entries: int = 4000) -> bool:manifest = json.loads(m.read_text(encoding = "utf-8-sig"))except (json.JSONDecodeError, OSError, ValueError):continue- # Same shape check as _scan_ollama_dir: a valid-JSON non-object under- # manifests/ must be skipped, not walked, or the chip probe raises- # AttributeError past the `except OSError` below.+ # Same shape check as _scan_ollama_dir: a valid-JSON non-object under manifests/ must be skipped, not+ # walked, or the chip probe raises AttributeError past the `except OSError` below.if not isinstance(manifest, dict):continuelayers = manifest.get("layers") or []@@ -1570,9 +1487,8 @@ def _dir_has_downloaded_model(directory: Path, max_entries: int = 4000) -> bool:return Trueexcept OSError:pass- # Generic weights: any GGUF/safetensors in a bounded BFS that skips hidden directories.- # ``rglob`` walks in arbitrary order and counts every entry, so a large hidden subtree- # could exhaust the budget before reaching real weights and falsely report "no model".+ # Bounded BFS that skips hidden directories: ``rglob`` walks in arbitrary order and counts every+ # entry, so a large hidden subtree could exhaust the budget before reaching real weights.queue = [directory]visited = 0while queue:@@ -1664,12 +1580,8 @@ _BROWSE_ENTRY_CAP = 2000def _count_model_files(directory: Path, cap: int = 200) -> int:- """Count GGUF/safetensors files immediately inside *directory*.-- Surfaces a count-hint so the UI can mark a weights-only leaf dir as a- valid "Use this folder" target. Bounded by *visited entries* (stops- after ``cap``), so the hint never costs more than a bounded walk.- """+ """Count GGUF/safetensors files immediately inside *directory* so the UI can mark a weights-only+ leaf dir as a valid "Use this folder" target. Bounded by visited entries."""n = 0visited = 0try:@@ -1694,9 +1606,8 @@ def _count_model_files(directory: Path, cap: int = 200) -> int:def _has_direct_model_signal(directory: Path) -> bool:- """Return True if an immediate child signals a model: a- GGUF/safetensors/config.json file or a ``models--*`` subdir (HF- cache). Bounded by ``_BROWSE_MODEL_HINT_PROBE``."""+ """True if an immediate child signals a model: a GGUF/safetensors/config.json file or a+ ``models--*`` subdir (HF cache). Bounded by ``_BROWSE_MODEL_HINT_PROBE``."""try:it = directory.iterdir()except OSError:@@ -1725,19 +1636,13 @@ def _has_direct_model_signal(directory: Path) -> bool:def _looks_like_model_dir(directory: Path) -> bool:- """Bounded heuristic to flag dirs worth exploring in the browser.-- False negatives are fine (the real scanner is authoritative). Three- signals, cheapest first: (1) name ``models--*`` (HF cache layout),- (2) an immediate child weight/config file, (3) a grandchild with a- direct signal (LM Studio / Ollama ``publisher/model`` layout, probing- the first ``_BROWSE_MODEL_HINT_PROBE`` child dirs).- """+ """Bounded heuristic to flag dirs worth exploring in the browser; false negatives are fine, the real scanner+ is authoritative. Three signals, cheapest first: name ``models--*`` (HF cache layout), an immediate child+ weight/config file, then a grandchild with a direct signal (LM Studio / Ollama ``publisher/model``)."""if directory.name.startswith("models--"):return Trueif _has_direct_model_signal(directory):return True- # Grandchild probe: LM Studio / Ollama publisher/model layout.try:it = directory.iterdir()except OSError:@@ -1763,18 +1668,11 @@ def _looks_like_model_dir(directory: Path) -> bool:def _build_browse_allowlist(media_roots: Optional[list[Path]] = None, drive_roots: Optional[list[Path]] = None) -> list[Path]:- """Return the root directories the folder browser may walk.-- The same list seeds the sidebar suggestion chips, so chip targets are- always reachable. Roots: HOME, resolved HF cache dirs, Unsloth's- outputs/exports/studio root, registered scan folders, and well-known- local-LLM dirs (LM Studio, Ollama, ``~/models``); each added only if- it resolves to a real directory.-- *media_roots* / *drive_roots* let the caller pass already-probed- removable-media and Windows drive roots so they aren't scanned again (a- disconnected mapped drive can make each probe slow); probed here when ``None``.- """+ """The root directories the folder browser may walk, which also seed the sidebar suggestion chips so chip+ targets are always reachable: HOME, resolved HF cache dirs, Unsloth's outputs/exports/studio root,+ registered scan folders, and well-known local-LLM dirs, each only if it resolves to a real directory.+ *media_roots* / *drive_roots* let the caller pass already-probed removable-media and Windows drive roots+ so they are not scanned again (a disconnected mapped drive makes each probe slow)."""from utils.paths import (hf_default_cache_dir,legacy_hf_cache_dir,@@ -1841,7 +1739,6 @@ def _build_browse_allowlist(except Exception as exc: # noqa: BLE001 -- best-effortlogger.debug("browse-folders: well-known dirs unavailable: %s", exc)- # Dedupe while preserving order.seen: set[str] = set()deduped: list[Path] = []for p in candidates:@@ -1854,16 +1751,12 @@ def _build_browse_allowlist(def _is_path_inside_allowlist(target: Path, allowed_roots: list[Path]) -> bool:- """True if *target* equals or descends from any allowed root.-- Uses ``os.path.realpath`` (symlinks can't escape the sandbox) and- ``os.path.commonpath`` for a component-wise containment test, so a string- prefix like ``/home/u`` never matches a sibling ``/home/user2`` while a- drive root ``D:\\`` still contains ``D:\\models``. A Windows drive root- authorizes its descendants, but a bare POSIX root ``/`` must NOT, else one- ``/`` allowlist entry would authorize every absolute path. ``normcase`` keeps- the drive-letter comparison case-insensitive, matching the hub browser.- """+ """True if *target* equals or descends from any allowed root. ``os.path.realpath`` (symlinks cannot+ escape the sandbox) plus ``os.path.commonpath`` for a component-wise test, so a string prefix+ like ``/home/u`` never matches a sibling ``/home/user2`` while a Windows drive root still+ contains its own subdirectories. A drive root authorizes its descendants, but a bare POSIX root+ ``/`` must NOT, else one entry would authorize every absolute path. ``normcase`` keeps the+ drive-letter comparison case-insensitive."""try:target_real = os.path.normcase(os.path.realpath(str(target)))except OSError:@@ -1895,7 +1788,6 @@ def _is_path_inside_allowlist(target: Path, allowed_roots: list[Path]) -> bool:def _normalize_browse_request_path(path: Optional[str]) -> str:- """Normalize the browse request path lexically, without touching the FS."""if path is None or not path.strip():return os.path.normpath(str(Path.home()))@@ -1906,7 +1798,6 @@ def _normalize_browse_request_path(path: Optional[str]) -> str:def _browse_relative_parts(requested_path: str, root: Path) -> Optional[list[str]]:- """Return validated relative path components under ``root``."""root_text = os.path.normpath(str(root))try:rel_text = os.path.relpath(requested_path, root_text)@@ -1927,7 +1818,6 @@ def _browse_relative_parts(requested_path: str, root: Path) -> Optional[list[strdef _match_browse_child(current: Path, name: str) -> Optional[Path]:- """Return the immediate child named ``name`` under ``current``."""try:for child in current.iterdir():if child.name == name:@@ -1947,7 +1837,6 @@ def _match_browse_child(current: Path, name: str) -> Optional[Path]:def _resolve_browse_target(path: Optional[str], allowed_roots: list[Path]) -> Path:- """Resolve a requested browse path by walking from trusted allowlist roots."""from storage.studio_db import (contains_sensitive_path_component,is_denied_system_path,@@ -2043,9 +1932,8 @@ def _resolve_browse_target(path: Optional[str], allowed_roots: list[Path]) -> Pa)-# Sync (def, not async) so FastAPI runs the blocking filesystem I/O in the threadpool: a-# disconnected mapped drive can make the probe wait out its timeout, which on the event-# loop would stall every other request. Matches the hub browse endpoint.+# Sync (def, not async) so FastAPI runs the blocking filesystem I/O in the threadpool: a disconnected mapped+# drive can make the probe wait out its timeout, which on the event loop would stall every other request.@router.get("/browse-folders", response_model = BrowseFoldersResponse)def browse_folders(path: Optional[str] = Query(@@ -2089,7 +1977,6 @@ def browse_folders(*external_media.macos_volume_roots(),]drive_roots = external_media.windows_drive_roots()- # Build once; the sandbox check and suggestion chips share it.allowed_roots = _build_browse_allowlist(media_roots, drive_roots)try:@@ -2162,7 +2049,6 @@ def browse_folders(exc,)except OSError as exc:- # Rare: iterdir succeeded but reading an entry failed.logger.warning("browse-folders: partial enumeration of %s: %s", target, exc)# Model-bearing first, then plain, then hidden; case-insensitive within each bucket.@@ -2180,7 +2066,6 @@ def browse_folders(else:parent = str(target.parent)- # Handy starting points for the quick-pick chips.suggestions: list[str] = []seen_sug: set[str] = set()@@ -2201,26 +2086,20 @@ def browse_folders(seen_sug.add(resolved)suggestions.append(resolved)- # Home first -- the safe fallback when everything else is cold._add_sug(Path.home())- # Reuse the roots probed for the allowlist above (no second drive scan).for p in media_roots:_add_sug(p)- # Windows drive roots so the user can hop between C:, D:, E: ...for p in drive_roots:_add_sug(p)- # The HF cache root the process is actually using.try:_add_sug(hf_default_cache_dir())except Exception:pass- # Already-registered scan folders (user-curated).try:for folder in list_scan_folders():_add_sug(Path(folder.get("path", "")))except Exception as exc:logger.debug("browse-folders: could not load scan folders: %s", exc)- # Dirs used by other local-LLM tools (LM Studio, Ollama, ~/models); existing paths only.try:for p in well_known_model_dirs():_add_sug(p)@@ -2272,8 +2151,8 @@ async def list_models(current_subject: str = Depends(get_current_subject)):)loaded_models.append(model_info)- # Active GGUF model (llama-server), labelled from the display id- # /api/inference/status publishes; the id stays raw for agents-tab's path filter.+ # Active GGUF model (llama-server), labelled from the display id /api/inference/status publishes; the+ # id stays raw for agents-tab's path filter.from routes.inference import _llama_status_model_ids, get_llama_cpp_backendllama_backend = get_llama_cpp_backend()@@ -2290,7 +2169,6 @@ async def list_models(current_subject: str = Depends(get_current_subject)):))- # Combine default and loaded; prefer loaded entries for duplicate ids so runtime flags survive.all_models = []seen_ids = set()loaded_by_id = {model_info.id: model_info for model_info in loaded_models}@@ -2324,11 +2202,9 @@ async def list_models(current_subject: str = Depends(get_current_subject)):def _get_max_position_embeddings(config) -> Optional[int]:- """The window this model was trained for, by the rule a load resolves it with.-- Reading one field name showed a dash for a model spelling it another way -- Kimi- Linear carries model_max_length alone -- and a number as soon as it loaded.- """+ """The window this model was trained for, by the rule a load resolves it with. Reading one field+ name showed a dash for a model spelling it another way (Kimi Linear carries model_max_length+ alone) and a number as soon as it loaded."""from types import SimpleNamespacefrom core.inference.mlx_inference import mlx_native_context_length@@ -2340,7 +2216,6 @@ _MODEL_WEIGHT_EXTENSIONS = (".safetensors", ".bin", ".pt", ".pth", ".gguf")def _get_model_size_bytes(model_name: str, hf_token: HfTokenArg = None) -> Optional[int]:- """Total size of model weight files from HF Hub."""try:from huggingface_hub import HfApi@@ -2458,9 +2333,8 @@ async def get_model_config(from utils.utils import pinned_hf_reachabilitydef _resolve(model_name: str) -> ModelDetails:- # Each probe below can reach the hub, so the guard wraps the whole handler: offline they- # must all resolve from the HF cache. Local paths stay on disk and skip the probe.- # One repo document between the probes, one verdict for a request that outlives the memo.+ # Each probe below can reach the hub, so the guard wraps the whole handler: offline they must all resolve+ # from the HF cache. One repo document between the probes, one verdict for a request that outlives the memo.with (pinned_hf_reachability(),_hf_offline_if_unreachable_for(model_name),@@ -2588,12 +2462,9 @@ def _consent_provider(scanned_targets: List[str],external_refs: Optional[List[str]] = None,) -> Optional[str]:- """HF org for the consent dialog's `from "<provider>"` tag, or None.-- Returns the owner only for a single, non-local, canonical ``owner/repo`` id; a LoRA's- extra base, a local path, or an external ``auto_map`` ref yields None so the dialog- never misattributes scanned code.- """+ """HF org for the consent dialog's `from "<provider>"` tag, or None. Only a single, non-local,+ canonical ``owner/repo`` id yields one; a LoRA's extra base, a local path, or an external+ ``auto_map`` ref yields None so the dialog never misattributes scanned code."""if len(scanned_targets) != 1 or external_refs or is_local_path(model_name):return Noneparts = model_name.split("/")@@ -2721,9 +2592,9 @@ async def scan_model_remote_code(from core.training.training import _resolve_model_snapshotlocal_path = normalize_path(model_local_path) if model_local_path else Nonescan_target = _resolve_model_snapshot(model_name, local_path) or model_name- # Scan the adapter AND the base together (a LoRA runs both repos' code), pinned by one- # combined fingerprint. Snapshot the primary's cache state BEFORE resolving the base: that- # resolve downloads adapter_config.json, which would hide the adapter from cleanup on decline.+ # Scan the adapter AND the base together (a LoRA runs both repos' code), pinned by one combined fingerprint.+ # Snapshot the primary's cache state BEFORE resolving the base: that resolve downloads adapter_config.json,+ # which would hide the adapter from cleanup on decline.primary_cache_target, _ = load_scan_target(scan_target, ())try:_primary_preexisting = is_local_path(primary_cache_target) or _repo_in_any_hf_cache(@@ -2773,9 +2644,9 @@ async def scan_model_remote_code(consent_load_subdirs[_target] = ()_subdirs = tuple(dict.fromkeys((*consent_load_subdirs[_target], *_subdirs)))consent_load_subdirs[_target] = _subdirs- # Record every repo OUR scan is first to pull into the cache (adapter, base, and external- # auto_map repos), so a decline purges exactly what was downloaded. Computed BEFORE the- # preflight downloads, against every cache the discard searches, so pre-existing repos stay.+ # Record every repo OUR scan is first to pull into the cache (adapter, base, and external auto_map repos), so+ # a decline purges exactly what was downloaded. Computed BEFORE the preflight downloads, against every+ # cache the discard searches, so pre-existing repos stay.from utils.security.remote_code_scan import external_auto_map_reposscan_created_repos: list = []@@ -2897,7 +2768,6 @@ async def discard_remote_code_download(if not _is_valid_repo_id(model_name):return {"deleted": False, "reason": "invalid"}- # Never delete a model that is loaded for inference.try:from hub.services.models.deletion import _loaded_id_matches_repofrom routes.inference import get_llama_cpp_backend@@ -2961,14 +2831,10 @@ async def discard_remote_code_download(def _audio_probe_target(inspection_target: str) -> str:- """Repo to ask about audio capability, resolving a registry alias first.-- A curated entry like "Spark-TTS-0.5B/LLM" names a load subdirectory, not a repo, so- the probe fetched a repo that does not exist, got a 404 on every path, and read that- as "definitely not an audio model" rather than "not a repo id". Spark-TTS then looked- like a text model, and picking it with an audio dataset hit the modality gate. Same- resolution routes/training.py already uses for the trainer's own preflight.- """+ """Repo to ask about audio capability, resolving a registry alias first. A curated entry like+ "Spark-TTS-0.5B/LLM" names a load subdirectory, not a repo, so the probe fetched a repo that does not+ exist, got a 404 on every path, and read that as "definitely not an audio model" rather than "not a+ repo id"."""if is_local_path(inspection_target):return inspection_targettry:@@ -2984,25 +2850,19 @@ def _audio_type_of_checkpoint(base_model: Optional[str],hf_token: Optional[str] = None,) -> Optional[str]:- """Codec a trained checkpoint speaks, or None for a text one.-- A scan row carries no modality, so without this every trained audio model reads- as text: the Audio page filters it out and chat routes it to the GGUF auto-switch,- which cannot resolve a local adapter directory. Detection reads the checkpoint- itself first (a merged export has its own tokenizer) and falls back to the base- repo an adapter names. Cached per model, so the scan stays one pass.- """+ """Codec a trained checkpoint speaks, or None for a text one. A scan row carries no modality, so without+ this every trained audio model reads as text: the Audio page filters it out and chat routes it to the+ GGUF auto-switch, which cannot resolve a local adapter directory. Detection reads the checkpoint itself+ first (a merged export has its own tokenizer) and falls back to the base repo an adapter names."""from utils.models.model_config import detect_audio_typefor candidate in (model_path, base_model):if not candidate:continuetry:- # local_files_only: this route was a filesystem scan. A trained checkpoint's- # base is already cached, and a non-definitive miss is deliberately not cached,- # so a gated or offline base would re-fetch on every poll.- # hf_token even under local_files_only: a gated base resolves through the same- # hub helpers, and the capability caches are keyed by token fingerprint, so a+ # local_files_only: this route was a filesystem scan, a trained checkpoint's base is already cached, and a+ # non-definitive miss is deliberately not cached, so a gated or offline base would re-fetch on every poll.+ # hf_token even under local_files_only: the capability caches are keyed by token fingerprint, so a# token-less probe would both misclassify and poison the cache for the rest.audio_type = detect_audio_type(candidate, hf_token = hf_token, local_files_only = True)except Exception as exc: # never let a scan row fail the whole listing@@ -3032,9 +2892,8 @@ async def scan_loras(try:resolved_outputs_dir = str(resolve_output_dir(outputs_dir))resolved_exports_dir = str(resolve_export_dir(exports_dir))- # Off the event loop: this is a directory walk plus, per checkpoint, a tokenizer- # read. It was already blocking before the audio probe was added; the probe made- # the block long enough to delay unrelated requests, streamed tokens included.+ # Off the event loop: this is a directory walk plus, per checkpoint, a tokenizer read, long enough to+ # delay unrelated requests, streamed tokens included.lora_list = await asyncio.to_thread(_scan_loras_sync, resolved_outputs_dir, resolved_exports_dir, hf_token)@@ -3054,7 +2913,6 @@ async def scan_loras(def _scan_loras_sync(resolved_outputs_dir: str, resolved_exports_dir: str, hf_token: Optional[str]) -> List[LoRAInfo]:- """The filesystem half of scan_loras, so it can run in a worker thread."""lora_list: List[LoRAInfo] = []trained_models = scan_trained_models(outputs_dir = resolved_outputs_dir)@@ -3071,7 +2929,6 @@ def _scan_loras_sync())- # Scan exported models (merged, LoRA, base - skips GGUF)exported = scan_exported_models(exports_dir = resolved_exports_dir)for display_name, model_path, export_type, base_model in exported:lora_list.append(@@ -3196,11 +3053,9 @@ def _loading_model_matches_deleted_path(loading_model: object, deleted_path: Patdef _active_diffusion_backend():- """The live Images engine, or None when this install has no diffusion stack.-- Fails OPEN on import: a chat-only install (no diffusers) must still be able to delete- its fine-tuned models. Reading the returned backend's state is what fails closed.- """+ """The live Images engine, or None when this install has no diffusion stack. Fails OPEN on import: a+ chat-only install (no diffusers) must still be able to delete its fine-tuned models. Reading the+ returned backend's state is what fails closed."""try:from core.inference.diffusion_engine_router import get_active_diffusion_enginereturn get_active_diffusion_engine()@@ -3210,7 +3065,6 @@ def _active_diffusion_backend():def _active_video_backend():- """The live Video backend, or None when this install has no video stack."""try:from core.inference.video import get_video_backendreturn get_video_backend()@@ -3220,11 +3074,8 @@ def _active_video_backend():def _prune_empty_parents(start: Path, stop_at: Path) -> None:- """Remove empty ancestors of ``start`` up to (not including) ``stop_at``.-- Used after deleting a checkpoint so the enclosing run dir doesn't- linger as an empty entry in scan results.- """+ """Remove empty ancestors of ``start`` up to (not including) ``stop_at``, so the enclosing run dir+ does not linger as an empty entry in scan results."""try:stop_resolved = stop_at.resolve()except OSError:@@ -3249,14 +3100,10 @@ def _prune_empty_parents(start: Path, stop_at: Path) -> None:def _variant_names_same_checkpoint(a: Optional[str], b: Optional[str]) -> bool:- """Whether two variant spellings can name the SAME checkpoint, for the load-state guard.-- Deletion accepts an unambiguous bare quant for a path-qualified key (the shared-container- layout, ``weights/model-Q4_K_M.gguf``), so a guard comparing the two spellings literally lets- a model loaded through a legacy bare pin be deleted through its advertised qualified row --- unlinking the resident model's snapshot and blob. Deliberately loose: a false match only- refuses a delete, a false miss loses weights.- """+ """Whether two variant spellings can name the SAME checkpoint, for the load-state guard. Deletion accepts+ an unambiguous bare quant for a path-qualified key (``weights/model-Q4_K_M.gguf``), so a guard comparing+ the two literally lets a model loaded through a legacy bare pin be deleted through its advertised+ qualified row. Deliberately loose: a false match only refuses a delete, a false miss loses weights."""from hub.utils.gguf import bare_quant_alias, is_qualified_gguf_variant_keyleft = (a or "").strip().lower()@@ -3283,9 +3130,8 @@ def _delete_gguf_variant_files(root: Path, variant: str) -> tuple[int, int]:for path in root.rglob("*"):if not path.is_file() or not _is_main_gguf_filename(path.name):continue- # Counted as a model if left in, so the reported count would follow the walk order; it- # still goes below, as metadata of the file it belongs to. Proven metadata only: anything- # else carrying this variant's key is a file the user asked to delete.+ # Counted as a model if left in, so the reported count would follow the walk order; it still goes+ # below, as metadata of the file it belongs to. Proven metadata only.if is_appledouble_metadata(path):continue# Keyed on the path, not the basename: a repo holding several checkpoints at@@ -3758,15 +3604,10 @@ def _settle_native_context(async def _read_native_context_length_bounded(model: str, is_local: bool) -> Optional[int]:- """``_read_native_context_length`` off the event loop, with a hard bound.-- Reporting None costs a pre-filled context field; waiting costs the whole variant- listing, which is what left the picker on "Loading variants…". Runs on a daemon- thread, not a pool: a stranded read must not join at interpreter exit, which would- hang shutdown for as long as the mount stays hung. Waiting for a slot is awaited- rather than skipped, so ordinary concurrent reads queue instead of losing their- length; the wait and the read share one budget.- """+ """``_read_native_context_length`` off the event loop, with a hard bound. Reporting None costs a pre-filled+ context field; waiting costs the whole variant listing. Runs on a daemon thread, not a pool: a stranded+ read must not join at interpreter exit and hang shutdown. The slot wait is awaited rather than skipped,+ so ordinary concurrent reads queue instead of losing their length; wait and read share one budget."""slots = _native_context_slots()began = time.monotonic()try:@@ -3806,16 +3647,11 @@ async def _read_native_context_length_bounded(model: str, is_local: bool) -> Optdef _read_native_context_length(repo_id: str, is_local: bool) -> Optional[int]:- """Native max context from a downloaded GGUF for this repo, or None.-- The value is identical across quants, so reading one non-mmproj shard's- header is enough. Only resolves once a file is on disk. Never raises.-- Bounded by ``_NATIVE_CONTEXT_READ_TIMEOUT_SECONDS``: this only pre-fills a- context field on an already selectable row, so a dragging walk reports None- rather than holding the variant listing open. Checked between files, and- files already read stay cached, so a later request resumes.- """+ """Native max context from a downloaded GGUF for this repo, or None. The value is identical across+ quants, so one non-mmproj shard's header is enough. Never raises. Bounded by+ ``_NATIVE_CONTEXT_READ_TIMEOUT_SECONDS``: this only pre-fills a context field on an already+ selectable row, so a dragging walk reports None rather than holding the variant listing open.+ Checked between files, and files already read stay cached, so a later request resumes."""try:from utils.models.gguf_metadata import read_gguf_context_lengthfrom utils.paths.path_utils import file_contents_available_locally@@ -3851,24 +3687,16 @@ def _read_native_context_length(repo_id: str, is_local: bool) -> Optional[int]:def _resolve_quant_gguf(repo_id: str, quant: str, is_local: bool) -> tuple[Optional[str], int]:- """Primary shard path and total weight bytes for a downloaded quant, or- (None, 0). Metadata lives in shard 1, so the lexicographically first file of- the matching quant is returned. Scoped to one snapshot to avoid summing the- same quant across revisions; when several snapshots hold the quant the most- complete one (largest total) wins so a partial revision can't shadow it.- Mirrors list_local_gguf_variants: quant labels are read from the snapshot-- relative path (so layouts like ``BF16/model.gguf`` resolve) and MTP drafter- files are skipped (so a ``...-Q8_0-MTP.gguf`` drafter can't be picked as the- Q8_0 weights). Never raises.- """+ """Primary shard path and total weight bytes for a downloaded quant, or (None, 0). Metadata lives in shard+ 1, so the lexicographically first file of the matching quant is returned. Scoped to one snapshot to+ avoid summing the same quant across revisions; when several hold it the most complete one wins. Mirrors+ list_local_gguf_variants: quant labels are read from the snapshot-relative path (so ``BF16/model.gguf``+ resolves) and MTP drafter files are skipped. Never raises."""try:if is_local:- # A direct file selection names the weights outright: custom, LM- # Studio and other local inventory entries whose path ends in .gguf- # never go through variant selection, so there is no quant label to- # match and nothing to scan for. Answer with the file itself, and- # with the whole split family's size rather than this shard's, the- # same way the quant scan below totals its shards.+ # A direct file selection names the weights outright: custom, LM Studio and other local inventory entries+ # whose path ends in .gguf never go through variant selection, so there is no quant label to match.+ # Answer with the file itself, and with the whole split family's size rather than this shard's.direct = Path(repo_id)if direct.is_file() and direct.suffix.lower() == ".gguf":from core.inference.llama_cpp import LlamaCppBackend@@ -3903,13 +3731,10 @@ def _resolve_quant_gguf(repo_id: str, quant: str, is_local: bool) -> tuple[Optioexcept OSError:continueranked[rank].append((rel, f, size))- # Exact keys alone when any exist: summing them with the label matches counts other- # checkpoints' bytes into this row's estimate and can reveal one of their files.- # ... and within those, ONE shard family, the same rule group_gguf_variant_files- # applies: a snapshot holding the same quant twice (QwQ-32B's two BF16 shard sets)- # would otherwise report double the weights the loader opens, which /kv-cache-estimate- # turns into a false exceeds-memory warning and which can make a snapshot look- # "more complete" purely for holding a redundant copy.+ # Exact keys alone when any exist: summing them with the label counts other checkpoints' bytes into this row+ # and can reveal one of their files. And within those, ONE shard family, the rule+ # group_gguf_variant_files applies: a snapshot holding the same quant twice (QwQ-32B's two BF16 shard+ # sets) would report double the weights the loader opens, a false exceeds-memory warning.chosen = _one_shard_family_of(ranked[0] or ranked[1])matches = [(rel, f) for rel, f, _size in chosen]total = sum(size for _rel, _f, size in chosen)@@ -3928,26 +3753,15 @@ def _resolve_quant_gguf(repo_id: str, quant: str, is_local: bool) -> tuple[Optiodef _resolve_mtp_drafter(main_gguf_path: str, search_root: Optional[str] = None) -> tuple[Optional[str], int]:- """Separate MTP drafter GGUF for a resolved main quant, or (None, 0).-- Some repos ship the drafter as its own file beside the weights (Gemma 4's- ``mtp-*.gguf``). The main GGUF has no ``nextn_predict_layers`` in that case,- so the estimator's embedded-head path returns None and the reserve reads as- zero unless we hand it the drafter.-- Delegates to the two resolvers the LOAD path already uses, rather than- scanning for a drafter itself: ``_companion_snapshot_sibling`` with the- loader's own ``_pick_mtp`` for an HF snapshot, and ``detect_mtp_file`` for a- local folder, which is what ``model_config`` calls when it builds the launch.- A bespoke scan here is how the estimate ends up pricing a different file from- the one llama-server opens: ``_pick_mtp`` is prefix-matched, so it cannot be- fooled by a directory that happens to be named ``mtp``, it finds- the snapshot-root companion when the weights sit in a quant subdirectory, it- sorts on relative strings rather than ``Path`` objects (whose ordering is- case-folded on Windows and not on POSIX, so two hosts really can disagree),- and it rejects an incomplete split set. Never raises: a drafter we cannot- find just costs a segment.- """+ """Separate MTP drafter GGUF for a resolved main quant, or (None, 0). Some repos ship the drafter+ as its own file beside the weights (Gemma 4's ``mtp-*.gguf``). The main GGUF has no+ ``nextn_predict_layers`` then, so the estimator's embedded-head path returns None and the+ reserve reads as zero unless we hand it the drafter. Delegates to the two resolvers the LOAD+ path uses rather than scanning itself: a bespoke scan is how the estimate ends up pricing a+ different file from the one llama-server opens. ``_pick_mtp`` is prefix-matched, finds the+ snapshot-root companion when the weights sit in a quant subdirectory, sorts on relative strings+ rather than ``Path`` objects (whose ordering is case-folded on Windows only), and rejects an+ incomplete split set. Never raises."""try:from utils.models.gguf_metadata import read_gguf_nextn_predict_layers@@ -3963,10 +3777,8 @@ def _resolve_mtp_drafter()if _snapshot_dir_of(main_gguf_path) is not None:- # An HF snapshot. ``_download_mtp`` takes the ``MTP/`` fallback only- # for qwen4exp with no head of its own, so the same gate applies here:- # pricing a nested copy for any other model reports a reserve for a- # drafter the load will not open.+ # ``_download_mtp`` takes the ``MTP/`` fallback only for qwen4exp with no head of its own, so the same gate+ # applies here: pricing a nested copy for any other model reports a reserve for a drafter never opened.pick = (_pick_mtpif LlamaCppBackend._gguf_path_wants_nested_mtp(main_gguf_path)@@ -3974,19 +3786,16 @@ def _resolve_mtp_drafter()drafter = _companion_snapshot_sibling(main_gguf_path, pick)else:- # A local folder, where the load path (model_config) pairs the drafter- # to the weight by name so a multi-model folder cannot attach a foreign- # one, and does accept the ``MTP/`` copy when no root drafter exists.- # No ``accept`` filter: the load path's one enforces a native-lease- # boundary, which a read-only estimate does not cross.+ # A local folder, where the load path pairs the drafter to the weight by name so a multi-model folder cannot+ # attach a foreign one, and does accept the ``MTP/`` copy when no root drafter exists. No ``accept``+ # filter: the load path's one enforces a native-lease boundary a read-only estimate does not cross.from utils.models.model_config import detect_mtp_filedrafter = detect_mtp_file(main_gguf_path, search_root = search_root)if not drafter:return None, 0- # The whole split family, not just the shard llama-server is handed:- # the load planner sizes the drafter with _get_gguf_size_bytes, and a- # split companion reserves every shard. Billing shard 1 alone reports a- # fit for a launch that allocates several times as much.+ # The whole split family, not just the shard llama-server is handed: the load planner sizes the drafter with+ # _get_gguf_size_bytes and a split companion reserves every shard, so billing shard 1 alone reports a fit+ # for a launch that allocates several times as much.return drafter, LlamaCppBackend._get_gguf_size_bytes(drafter)except Exception:return None, 0@@ -4066,13 +3875,9 @@ async def get_kv_cache_estimate(for models with no drafter -- the caller draws no segment either way."""- # The header read, the HF cache walk in _resolve_quant_gguf, the drafter- # lookup and the capability probe are all blocking disk work, and this- # route is called once per visible row. Run it in a worker so a long model- # list cannot stall the streamed tokens of a chat in the same process.- # n_ctx and n_parallel are bound as arguments rather than closed over: the- # body assigns to both (defaulting them), which would otherwise make them- # locals of this function and raise before either default could be applied.+ # The header read, the HF cache walk, the drafter lookup and the capability probe are all blocking disk work,+ # and this route is called once per visible row, so run it in a worker. n_ctx and n_parallel are bound as+ # arguments rather than closed over: the body assigns to both, which would make them locals and raise.def _estimate(n_ctx: Optional[int] = n_ctx, n_parallel: Optional[int] = n_parallel) -> dict:null = {"kv_bytes": None,@@ -4126,33 +3931,25 @@ async def get_kv_cache_estimate(be._model_identifier = "kv-estimate"be._read_gguf_metadata(path)- # With no pinned context a GGUF loads at its own native length, which- # only the metadata we just read knows. Defaulting here saves the caller- # a round trip spent discovering the number it then asks about.- # Mirror _resolve_parallel_slots: an omitted count means the server's- # standing slot count, not one slot. The KV estimator scales per-slot- # padding, so assuming 1 understates a default load.+ # With no pinned context a GGUF loads at its own native length, which only the metadata just read knows.+ # Mirror _resolve_parallel_slots too: an omitted count means the server's standing slot count, not one,+ # and the KV estimator scales per-slot padding, so assuming 1 understates a default load.if n_parallel is None:state = getattr(getattr(request, "app", None), "state", None)n_parallel = getattr(state, "llama_parallel_slots", 1) or 1- # What the launch will actually serve, not what was asked for. A build- # without --kv-unified splits the window per slot, so load_model falls- # back to one; pricing a four-slot default against such a build- # inflates the cache several times over and can warn OOM about a- # command that would never launch that way. Same resolution- # /estimate-memory applies, so the two cannot disagree.+ # What the launch will actually serve, not what was asked for. A build without --kv-unified splits the window+ # per slot, so load_model falls back to one; pricing a four-slot default against such a build inflates the+ # cache several times over. Same resolution /estimate-memory applies.try:from routes.inference import _effective_parallel_slotsn_parallel = _effective_parallel_slots(n_parallel, diffusion_kind = False)except Exception as e:logger.debug(f"slot clamp unavailable for '{repo_id}' {quant}: {e}")- # Whether the caller pinned a context, kept before the default below- # overwrites it. The planner reads the inherited LLAMA_ARG_CTX_SIZE- # only when its own n_ctx input is zero, so handing it the native- # length here priced the header's window for a child that will run at- # the environment's -- and an inherited context LARGER than native is- # then underpriced while still reading as auto-fitted.+ # Whether the caller pinned a context, kept before the default below overwrites it. The planner reads the+ # inherited LLAMA_ARG_CTX_SIZE only when its own n_ctx input is zero, so handing it the native length+ # priced the header's window for a child that will run at the environment's, and an inherited context+ # LARGER than native is then underpriced while still reading as auto-fitted._inherited_device_pin = Falsetry:_dev = (os.environ.get("LLAMA_ARG_DEVICE") or "").strip()@@ -4163,11 +3960,9 @@ async def get_kv_cache_estimate(logger.debug(f"inherited device pin unreadable: {e}")_ctx_was_omitted = not n_ctx- # Whether the launch will auto-fit at all. Only a context nobody- # pinned gets reduced to fit: load_model keeps a positive inherited- # LLAMA_ARG_CTX_SIZE rather than fitting it, so an inherited window- # over budget is a real overage the caller must be allowed to warn- # about. Resolved below once the inherited value is known.+ # Whether the launch will auto-fit at all. Only a context nobody pinned gets reduced to fit: load_model keeps+ # a positive inherited LLAMA_ARG_CTX_SIZE rather than fitting it, so an inherited window over budget is a+ # real overage the caller must be allowed to warn about._context_is_pinned = not _ctx_was_omitted# Same precedence the launch uses: an inherited positive context beats# the header, since load_model drops it only when it is zero.@@ -4184,11 +3979,9 @@ async def get_kv_cache_estimate(if not n_ctx or n_ctx < 1:return null- # The K/V types the launch will really open, including an inherited- # LLAMA_ARG_CACHE_TYPE_K/V that no structured setting overrode. The- # planner already resolves these for gpu_bytes; without the same- # resolution here kv_bytes stayed at f16 and the KV segment, the- # per-token rate and the readout all contradicted the total beside+ # The K/V types the launch will really open, including an inherited LLAMA_ARG_CACHE_TYPE_K/V that no+ # structured setting overrode. Without the same resolution the planner applies for gpu_bytes, kv_bytes+ # stayed at f16 and the KV segment, the per-token rate and the readout all contradicted the total beside# them. The heavier of the pair, matching the planner's own choice._effective_cache_type = cache_type_kvtry:@@ -4202,9 +3995,8 @@ async def get_kv_cache_estimate(except Exception as e:logger.debug(f"cache type resolution failed for '{repo_id}': {e}")- # ctx_checkpoints is not a rounding error: each saved checkpoint is an- # SWA snapshot per slot, so a 4-slot SWA model at 32k measures 5.82 GiB- # with none and 11.82 GiB at the llama.cpp default of 32.+ # ctx_checkpoints is not a rounding error: each saved checkpoint is an SWA snapshot per slot, so a+ # 4-slot SWA model at 32k measures 5.82 GiB with none and 11.82 GiB at the llama.cpp default of 32.kv = be._estimate_kv_cache_bytes(n_ctx,_effective_cache_type,@@ -4213,14 +4005,10 @@ async def get_kv_cache_estimate(n_ubatch = n_ubatch,)- # The checkpoint share of that cache, by difference rather than by- # re-deriving the SWA layer walk -- the snapshots are the only term that- # separates the two calls, so asking the same function twice cannot drift- # from it. This is the same derivation the load planner uses at- # routes/inference.py, and it is reported separately because llama.cpp- # keeps these snapshots in HOST heap: the planner's GPU figure is- # kv_bytes - kv_checkpoint_bytes. Folded into the bar's VRAM total they- # warn OOM over memory that never touches the card.+ # The checkpoint share of that cache, by difference rather than by re-deriving the SWA layer walk: the+ # snapshots are the only term separating the two calls. Reported separately because llama.cpp keeps these+ # snapshots in HOST heap (the planner's GPU figure is kv_bytes - kv_checkpoint_bytes); folded into the+ # bar's VRAM total they warn OOM over memory that never touches the card.kv_checkpoint = 0if ctx_checkpoints:_kv_without = be._estimate_kv_cache_bytes(@@ -4232,31 +4020,20 @@ async def get_kv_cache_estimate()kv_checkpoint = max(0, int(kv) - int(_kv_without))- # DSpark and DFlash attach a separate draft GGUF with its own weights- # and KV context, and Auto promotes to either ahead of MTP. Pricing- # them means reproducing the loader's whole sidecar precedence, which- # is how an estimate ends up charging a drafter the launch never- # opens. A DSpark sidecar alone runs to about 11 GB, so reporting a- # comfortable fit that omits it is the worst of the options: say the- # reserve is unpriced and let the caller draw nothing instead.+ # DSpark and DFlash attach a separate draft GGUF with its own weights and KV context, and Auto promotes to+ # either ahead of MTP. Pricing them means reproducing the loader's whole sidecar precedence, which is how+ # an estimate charges a drafter the launch never opens. A DSpark sidecar alone runs to about 11 GB, so say+ # the reserve is unpriced rather than report a comfortable fit that omits it._spec_mode = (speculative_type or "").lower()spec_unpriced = _spec_mode in ("dspark", "dflash")- # Auto is not a mode that declines a sidecar: the load planner promotes it- # to DSpark or DFlash whenever the repo ships one and the binary supports- # it, ahead of MTP. Reading the explicit modes alone left the largest- # single allocation this route can miss -- a DSpark sidecar is about 11 GB- # -- silently absent from an Auto row, which is the case that reports a- # comfortable fit and then fails to load. Gated on the binary's own- # capability for the same reason the planner gates on it: charging (or- # here, abstaining over) a sidecar the launch never opens would blank the- # bar on hosts whose llama-server cannot run one.+ # Auto is not a mode that declines a sidecar: the planner promotes it to DSpark or DFlash whenever the repo+ # ships one and the binary supports it, ahead of MTP. Reading the explicit modes alone left an ~11 GB+ # DSpark sidecar silently absent from an Auto row. Gated on the binary's own capability for the same+ # reason the planner gates on it: abstaining over a sidecar never opened would blank the bar.if not spec_unpriced and _spec_mode == "auto":try:- # Imported here, not borrowed from _resolve_mtp_drafter: these- # live in that function's local scope, so referencing them from- # this one raised NameError into the except below and left- # spec_unpriced false -- the silent no-op this guard exists to- # prevent, and invisible precisely because it failed quietly.+ # Imported here, not borrowed from _resolve_mtp_drafter: these live in that function's local scope, so+ # referencing them raised NameError into the except below and left spec_unpriced false.from core.inference.llama_cpp import (_companion_snapshot_sibling,_is_dflash_drafter_path,@@ -4273,11 +4050,9 @@ async def get_kv_cache_estimate(_has_dspark = bool(_companion_snapshot_sibling(path, _pick_dspark))_has_dflash = bool(_companion_snapshot_sibling(path, _pick_dflash))else:- # A plain local folder resolves its sidecars the way the load- # path does, through the same detectors that populate- # gguf_dspark_file / gguf_dflash_file. Restricting this to- # snapshots left every local model charting a total with the- # drafter missing.+ # A plain local folder resolves its sidecars the way the load path does, through the same detectors that+ # populate gguf_dspark_file / gguf_dflash_file. Restricting this to snapshots left every local model+ # charting a total with the drafter missing.from utils.models.drafters.dflash import detect_dflash_filefrom utils.models.model_config import detect_dspark_file@@ -4291,23 +4066,18 @@ async def get_kv_cache_estimate(except Exception as e:logger.debug(f"auto sidecar probe failed for '{repo_id}' {quant}: {e}")- # A vision GGUF launches with its mmproj resident unless the user- # turned vision off, and the projector is charged at a worst-case- # multiple of its file size (_MMPROJ_VRAM_SAFETY), not at it. Left- # out, a vision row shows a comfortable fit for a launch that has to- # find another gigabyte or push the projector to the CPU.+ # A vision GGUF launches with its mmproj resident unless vision is off, and the projector is charged at a+ # worst-case multiple of its file size (_MMPROJ_VRAM_SAFETY), not at it. Left out, a vision row shows a+ # comfortable fit for a launch that has to find another gigabyte.projector = Noneif not disable_vision:try:from core.inference.llama_cpp import LlamaCppBackend as _Befrom utils.models.model_config import detect_mmproj_file- # A cached HF layout puts the weights under a quant subdir- # (snapshot/Q4_K_M/model.gguf) and the projector at the- # snapshot ROOT, so scanning the weights' own directory finds- # nothing. Anchored the same way the drafter lookup is, and- # the same way the loader's _download_mmproj anchors on- # near_path.+ # A cached HF layout puts the weights under a quant subdir and the projector at the snapshot ROOT, so scanning+ # the weights' own directory finds nothing. Anchored the same way the drafter lookup is, and the same way+ # the loader's _download_mmproj anchors on near_path.from core.inference.llama_cpp import (_companion_snapshot_sibling,_pick_mmproj,@@ -4323,11 +4093,9 @@ async def get_kv_cache_estimate(except Exception as e:logger.debug(f"mmproj estimate failed for '{repo_id}' {quant}: {e}")- # Only the MTP modes reserve memory; ngram is free. "auto" may or may- # not resolve to MTP, and the estimator returns None when it doesn't.- # Guarded separately: the MTP path reads more metadata than the KV path,- # and a model it can't size should still get its KV bar rather than- # dropping the whole response to nulls.+ # Only the MTP modes reserve memory; ngram is free. "auto" may or may not resolve to MTP, and the estimator+ # returns None when it does not. Guarded separately: the MTP path reads more metadata than the KV path, and+ # a model it cannot size should still get its KV bar rather than dropping the response to nulls.spec = Nonespec_fixed = Noneif (speculative_type or "").lower() in ("mtp", "mtp+ngram", "auto"):@@ -4342,22 +4110,15 @@ async def get_kv_cache_estimate(drafter_path, drafter_bytes = _resolve_mtp_drafter(path, search_root = repo_id if is_local else None)- # Auto declines MTP on a sub-3B embedded head, where the- # per-token cost regresses; a separate drafter is exempt. Pricing- # a reserve the load will not take would overstate the bar and- # could warn OOM on a model that fits.+ # Auto declines MTP on a sub-3B embedded head, where the per-token cost regresses; a separate drafter+ # is exempt. Pricing a reserve the load will not take could warn OOM on a model that fits._mode = (speculative_type or "").lower()- # Same reason, one level down: llama-server only takes the MTP- # path when it advertises a --spec-type mtp token, and the loader- # declines on an inconclusive probe too. Both cover the- # separate-drafter path, which is emitted behind the same gate.- # Probes are cached on (path, mtime), so this stays cheap.+ # Same reason one level down: llama-server only takes the MTP path when it advertises a --spec-type+ # mtp token, and the loader declines on an inconclusive probe too. Probes are cached on (path, mtime)._binary_lacks_mtp = not (be.probe_server_capabilities() or {}).get("mtp_token")- # Auto also declines an MLA embedded head (GLM/DeepSeek/Kimi):- # that path keeps a duplicated full target-KV context and runs- # slower than no speculation, so it is off unless opted into.- # A separate drafter is unaffected, as is a non-MLA head.+ # Auto also declines an MLA embedded head (GLM/DeepSeek/Kimi): that path keeps a duplicated full target-KV+ # context and runs slower than no speculation. A separate drafter is unaffected, as is a non-MLA head._auto_drops_mla = (_mode == "auto"and be._kv_lora_rank is not None@@ -4365,16 +4126,11 @@ async def get_kv_cache_estimate(and not drafter_pathand not _mla_mtp_auto_enabled())- # The loader's own precondition (is_mtp_model): a model with no- # embedded head, no MTP name and no separate drafter cannot run- # MTP at all, so llama-server gets --spec-default and reserves- # nothing. Without this check _estimate_mtp_overhead_bytes still- # charges its target-side terms, and because- # mtp_keeps_target_ctx defaults to True -- deliberately, so an- # unsure caller over-reserves -- every MLA model was billed a- # second full f16 copy of its own KV. That is the whole cache- # again, which is the largest way this bar could be wrong, and it- # is wrong in the direction that warns OOM on a model that loads.+ # The loader's own precondition (is_mtp_model): a model with no embedded head, no MTP name and no separate+ # drafter cannot run MTP at all, so llama-server gets --spec-default and reserves nothing. Without this+ # check _estimate_mtp_overhead_bytes still charges its target-side terms, and because+ # mtp_keeps_target_ctx defaults to True every MLA model was billed a second full f16 copy of its own+ # KV: the whole cache again, in the direction that warns OOM on a model that loads._not_an_mtp_model = not (bool(be._nextn_predict_layers)or _is_mtp_model_name(repo_id, path)@@ -4392,11 +4148,9 @@ async def get_kv_cache_estimate():passelse:- # The drafter's own weights: resident for as long as the- # drafter is open and not reducible by shortening context.- # Reported separately so the caller's auto-fit softening,- # which exists for the context-linear part of the cache,- # cannot swallow a fixed overage no shorter context fixes.+ # The drafter's own weights: resident for as long as the drafter is open and not reducible by shortening+ # context. Reported separately so the caller's auto-fit softening, which exists for the context-linear+ # part of the cache, cannot swallow a fixed overage no shorter context fixes.spec_fixed = int(drafter_bytes or 0) or None_effective_draft_n_max = spec_draft_n_maxif _effective_draft_n_max is None:@@ -4424,47 +4178,28 @@ async def get_kv_cache_estimate(drafter_path = drafter_path,draft_weights_bytes = drafter_bytes,n_parallel = n_parallel,- # A Hybrid Mamba target keeps one recurrent rollback- # state per drafted token, which dominates everything- # else here: on a 4-slot model at 32k the reserve is- # 0.125 GiB at the zero default and 6.944 GiB at a- # depth of 16, so omitting it is a 55x understatement.- # Blank is not zero. _build_speculative_flags emits- # its own default when the field is unset (2 with a- # GPU, 3 without), and the rollback state is- # multiplied by it, so pricing zero dropped the- # dominant allocation on a Hybrid Mamba target- # outright. An explicit 0 is still honoured, since- # that is a real request to draft nothing.+ # A Hybrid Mamba target keeps one recurrent rollback state per drafted token, which dominates everything else+ # here: on a 4-slot model at 32k the reserve is 0.125 GiB at the zero default and 6.944 GiB at a depth of+ # 16. Blank is not zero: _build_speculative_flags emits its own default when the field is unset (2 with a+ # GPU, 3 without) and the rollback state is multiplied by it. An explicit 0 is still honoured.spec_draft_n_max = _effective_draft_n_max,)except Exception as e:logger.debug(f"mtp overhead estimate failed for '{repo_id}' {quant}: {e}")- # The load planner's own answer, alongside this route's field-by-field- # one. It is the authoritative figure: it applies the inherited- # environment (LLAMA_ARG_CACHE_TYPE_K/V, LLAMA_ARG_SWA_FULL,- # LLAMA_ARG_CTX_SIZE), derives the companion search roots the loader- # derives, and includes the compute buffers -- every term this route- # would otherwise have to reproduce, and has repeatedly reproduced- # incompletely. gpu_bytes is what lands on the card, with the host-heap- # checkpoint share already subtracted.- #- # Added beside the existing fields rather than replacing them: the- # planner defines weights_bytes as the weights PLUS whichever projector- # and drafter the launch opens, while this route's field shipped meaning- # the quant file alone. Redefining it would move a number an existing- # caller already reads.+ # The load planner's own answer, alongside this route's field-by-field one. It is the authoritative figure: it+ # applies the inherited environment (LLAMA_ARG_CACHE_TYPE_K/V, LLAMA_ARG_SWA_FULL, LLAMA_ARG_CTX_SIZE),+ # derives the companion search roots the loader derives, and includes the compute buffers. gpu_bytes is+ # what lands on the card, with the host-heap checkpoint share subtracted. Added beside the existing fields+ # rather than replacing them: the planner's weights_bytes includes the projector and drafter the launch+ # opens, while this route's field shipped meaning the quant file alone.planner_gpu = Noneplanner_compute = Noneplanner_total = Noneplanner_floor = Noneplanner_unsized = False- # Bound BEFORE the try, not inside it. Every statement below can- # raise into the surrounding `except`, and a name defined only on the- # success path then reads as a NameError from the projection after- # it -- which this same route has already been bitten by once, in a- # guard that silently never ran because of it.+ # Bound BEFORE the try, not inside it. Every statement below can raise into the surrounding `except`, and a+ # name defined only on the success path then reads as a NameError from the projection after it._b = Nonetry:from routes.inference import (@@ -4474,16 +4209,10 @@ async def get_kv_cache_estimate(_localized_estimate_config,)- # Tensor mode replicates its compute buffers on every device in- # the pool, so pricing one device understates the reserve by a- # factor of however many cards the launch would use. Only consulted- # in tensor mode: a layer split does not replicate them the same- # way, and this is the same count the load panel derives.- # The effective mode, not the request boolean: the planner turns- # tensor mode on for an inherited LLAMA_ARG_SPLIT_MODE=tensor even- # when the per-model toggle is off, and it replicates the compute- # buffers per device when it does. Reading the toggle alone left- # n_devices at one for exactly that launch.+ # Tensor mode replicates its compute buffers on every device in the pool, so pricing one device understates+ # the reserve by however many cards the launch would use. Only consulted in tensor mode: a layer split does+ # not replicate them the same way. The EFFECTIVE mode, not the request boolean: the planner turns tensor+ # mode on for an inherited LLAMA_ARG_SPLIT_MODE=tensor even when the per-model toggle is off._effective_tp = tensor_paralleltry:from core.inference.llama_server_args import _effective_tensor_parallel@@ -4522,30 +4251,17 @@ async def get_kv_cache_estimate(n_devices = _planner_devices,)if _b is not None:- # `or None` would fold a real zero into "no answer".- # Zero is a meaningful result: inherited placement such as- # LLAMA_ARG_DEVICE=none makes the launch entirely CPU- # resident, and discarding that sent the caller back to- # summing segments and drawing VRAM pressure for a load- # that touches no card at all.+ # `or None` would fold a real zero into "no answer". Zero is meaningful: inherited placement such as+ # LLAMA_ARG_DEVICE=none makes the launch entirely CPU resident, and discarding that sent the caller back+ # to summing segments and drawing VRAM pressure for a load that touches no card at all.planner_gpu = int(_b.gpu_bytes)planner_compute = int(_b.compute_bytes) or Noneplanner_total = int(_b.total_bytes) or Noneplanner_unsized = bool(_b.drafter_kv_unsized)- # The same plan priced at the shortest context worth- # asking for. Whatever is still there cannot be reduced by- # shortening context: the drafter's weights, the flat- # compute buffer, a Hybrid Mamba target's recurrent- # rollback state. Taken by difference against the real- # plan rather than by naming those terms, because naming- # them is how this route kept missing one; the planner- # decides what is fixed, and asking it twice cannot drift- # from itself.- #- # This is what an unpinned row's hard verdict must be- # drawn against. Auto-fit can shrink the cache, so a- # context-driven overage is not a failure, but nothing it- # can do touches this floor.+ # The same plan priced at the shortest context worth asking for. Whatever is still there cannot be reduced by+ # shortening context: the drafter's weights, the flat compute buffer, a Hybrid Mamba target's recurrent+ # rollback state. Taken by difference rather than by naming those terms, because naming them is how this+ # route kept missing one. An unpinned row's hard verdict must be drawn against this floor._floor = _gguf_memory_breakdown(_cfg,path,@@ -4567,18 +4283,11 @@ async def get_kv_cache_estimate(except Exception as e:logger.debug(f"planner breakdown failed for '{repo_id}' {quant}: {e}")- # Shaped through the canonical MemoryEstimate rather than assembled- # here, so this route and POST /inference/estimate-memory cannot drift- # apart in vocabulary the way they had. The projection is what keeps- # this route's own meaning of `weights_bytes` -- the quant file ALONE- # -- while the panel's projection keeps its aggregate meaning. The two- # sit side by side in core/inference/memory_contract.py, which is the- # only place either mapping is written down.- #- # The terms this route prices ITSELF (the target cache, the- # speculative split, the projector, the checkpoint share) are passed- # in rather than read off the estimate: the planner has its own- # figures for some of them and they are not interchangeable.+ # Shaped through the canonical MemoryEstimate rather than assembled here, so this route and POST+ # /inference/estimate-memory cannot drift apart in vocabulary. The projection keeps this route's own+ # meaning of `weights_bytes` (the quant file ALONE) while the panel's keeps its aggregate meaning; both+ # live in core/inference/memory_contract.py. The terms this route prices ITSELF are passed in rather than+ # read off the estimate: the planner has its own figures for some of them._estimate = build_memory_estimate(_b if _b is not None else EMPTY_BREAKDOWN,quant_file_bytes = weights_bytes or 0,@@ -4586,29 +4295,20 @@ async def get_kv_cache_estimate(# What remains on the card at the shortest context, so a caller# can tell a context-driven overage from one no context fixes.gpu_floor_bytes = planner_floor,- # False only when the loader is free to shrink the context. A- # caller that softens its verdict for an auto-fitted row has to- # stop softening here, or an inherited window over budget reads- # as a fit for a launch that will OOM.+ # False only when the loader is free to shrink the context. A caller that softens its verdict for an+ # auto-fitted row has to stop softening here, or an inherited window over budget reads as a fit for a+ # launch that will OOM.context_is_pinned = _context_is_pinned,- # An inherited LLAMA_ARG_DEVICE confines the child to the cards it- # names, and an automatic launch preserves it. The caller's budget- # is an aggregate over the whole visible inventory, which then- # describes a pool the launch will not open -- a 30 GiB model- # reads as fitting 2x24 GiB while the child has one card. The- # caller cannot see the environment, so it is reported here.- # Any pin at all is enough to say so: the route does not know the- # host's inventory, and abstaining is the safe direction.+ # An inherited LLAMA_ARG_DEVICE confines the child to the cards it names, and an automatic launch preserves+ # it. The caller's budget is an aggregate over the whole visible inventory, which then describes a pool the+ # launch will not open: a 30 GiB model reads as fitting 2x24 GiB while the child has one card.inherited_device_pin = _inherited_device_pin,# The planner saw a drafter whose cache it could not size, so its# own total is a floor.spec_unpriced = spec_unpriced or planner_unsized,- # The planner's own figures, kept exactly as this route computed- # them above: planner_gpu preserves a real zero, the other two do- # not. Passed in rather than assigned onto the model afterwards,- # because Pydantic does not validate assignment by default and a- # post-construction write puts whatever it is handed straight- # onto the wire.+ # The planner's own figures, kept exactly as computed above: planner_gpu preserves a real zero, the other two+ # do not. Passed in rather than assigned onto the model afterwards, because Pydantic does not validate+ # assignment by default and a post-construction write puts whatever it is handed on the wire.gpu_bytes = planner_gpu,compute_bytes = planner_compute,total_bytes = planner_total,@@ -4621,10 +4321,8 @@ async def get_kv_cache_estimate(# The part of spec_bytes a shorter context cannot reduce.spec_fixed_bytes = spec_fixed if spec else None,projector_bytes = projector or None,- # The part of kv_bytes that llama.cpp keeps in host heap rather- # than on the card, so a VRAM bar can subtract it. Included in- # kv_bytes, not beside it: the field shipped meaning the whole- # cache and an existing caller still reads it that way.+ # The part of kv_bytes llama.cpp keeps in host heap rather than on the card, so a VRAM bar can+ # subtract it. Included in kv_bytes, not beside it: the field shipped meaning the whole cache.kv_checkpoint_bytes = kv_checkpoint or None,)except Exception as e:@@ -4733,12 +4431,9 @@ async def get_gguf_download_progress(def _resolve_hf_cache_realpath(repo_dir: Path) -> Optional[str]:- """Most useful on-disk path for a HF cache repo.-- Delegates to the Hub scanner's function of the same name so this route and- ``/api/hub/local-models`` name one directory: the newest snapshot dir, ties broken by- ``snapshot_selection_key``.- """+ """Most useful on-disk path for a HF cache repo. Delegates to the Hub scanner's function of the same+ name so this route and ``/api/hub/local-models`` name one directory: the newest snapshot dir, ties+ broken by ``snapshot_selection_key``."""from hub.utils import inventory_scan as hf_cache_scanreturn hf_cache_scan.resolve_hf_cache_realpath(repo_dir)@@ -4755,15 +4450,10 @@ async def get_download_progress(def _repo_in_any_hf_cache(model_name: str) -> bool:- """Whether ``model_name`` already exists in ANY HF cache the discard searches- (active, legacy, default).-- ``created_by_scan`` must be True only when the scan itself first pulled the repo;- checking just the active cache (``get_cache_path``) would mark a repo the user- already had in a legacy/default cache as scan-created, so declining the consent- would delete a model they did not download via the scan. Mirrors the cache set in- ``_all_hf_cache_scans`` but only probes for the one repo dir (cheap, no full scan).- """+ """Whether ``model_name`` already exists in ANY HF cache the discard searches (active, legacy, default).+ ``created_by_scan`` must be True only when the scan itself first pulled the repo; checking just the+ active cache would mark a repo the user already had in a legacy/default cache as scan-created, so+ declining the consent would delete a model they did not download."""from utils.paths import resolve_cached_repo_id_casedirname = f"models--{resolve_cached_repo_id_case(model_name).replace('/', '--')}"@@ -4787,12 +4477,9 @@ def _repo_in_any_hf_cache(model_name: str) -> bool:def _all_hf_cache_scans():- """scan_cache_dir for the active, legacy, and default HF caches.-- Each probe is isolated: an unreadable auxiliary cache (permission denied,- broken symlink, OS-redirected ~/.cache) is skipped, not fatal, so the- Downloaded list never blanks out and downloads never leak into Recommended.- """+ """scan_cache_dir for the active, legacy, and default HF caches. Each probe is isolated: an+ unreadable auxiliary cache is skipped, not fatal, so the Downloaded list never blanks out and+ downloads never leak into Recommended."""from hub.utils.inventory_scan import all_hf_cache_scansreturn all_hf_cache_scans()@@ -4832,21 +4519,17 @@ def _repo_id_will_not_resolve(repo_cache_dir: Path) -> bool:def _default_ref_offers_no_whole_quant(repo_cache_dir: Path) -> bool:- """See hub.utils.inventory_scan; True when refs/main resolves onto a torn quant.-- _gguf_copy_is_usable asks the stronger question now, so this has no caller here. It stays- because it was importable before, and a name read only from outside looks unused inside.- """+ """See hub.utils.inventory_scan; True when refs/main resolves onto a torn quant. _gguf_copy_is_usable+ asks the stronger question now, so this has no caller here; it stays because it was importable+ before."""from hub.utils.inventory_scan import default_ref_offers_no_whole_quant as implreturn impl(repo_cache_dir)def _gguf_copy_is_usable(repo_info, load_id: Optional[str], active_root: Optional[Path]) -> bool:- """Whether this copy of the repo holds a quant a load can reach.-- A pinned copy names a complete snapshot. An unpinned copy must be in the active cache and have- an id that resolves onto a whole quant, which is exactly what withheld the pin.- """+ """Whether this copy of the repo holds a quant a load can reach. A pinned copy names a complete+ snapshot; an unpinned copy must be in the active cache and have an id that resolves onto a whole+ quant, which is exactly what withheld the pin."""if load_id:return Trueif active_root is None:@@ -4896,13 +4579,9 @@ def _main_variant_gguf_label(rel_path: str) -> Optional[str]:def _one_shard_family_of(entries: list) -> list:- """*entries* narrowed to the single shard family the loader would open.-- ``(rel, path, size)`` triples. Same rule as ``hub.utils.gguf.group_gguf_variant_files``:- every shard of one split GGUF shares a family, two files that do not are two checkpoints, and- the family kept is the one holding the lexicographically first file. A genuinely split GGUF is- one family and survives whole.- """+ """*entries* narrowed to the single shard family the loader would open, as ``(rel, path, size)`` triples.+ Same rule as ``hub.utils.gguf.group_gguf_variant_files``: every shard of one split GGUF shares a family,+ two files that do not are two checkpoints, and the family kept is the one holding the first file."""if len(entries) < 2:return list(entries)from hub.utils.gguf import gguf_variant_family@@ -4916,15 +4595,14 @@ def _one_shard_family_of(entries: list) -> list:def _main_variant_rank(rel_path: str, want: str) -> Optional[int]:- """How well *want* names this file's variant: 0 for its own key, 1 for the legacy- quant-label spelling, None for neither.-- *want* is the request VERBATIM: the bare-quant folding is applied per comparison, because- doing it once up front strips a qualified key's own path punctuation and folds ``exp-a/`` into- ``expa/``. Directory-qualified keys keep their legacy bare spelling, since stored pins predate- them. Root-level H3 stems do not: a bare quant names both FL2VA and Ref2VA, and picking the- first file would load a different task. Exact keys are used alone whenever any exist, and the- label is the fallback for rows with no root-stem identity.+ """How well *want* names this file's variant: 0 for its own key, 1 for the legacy quant-label spelling, None+ for neither.++ *want* is the request VERBATIM: the bare-quant folding is applied per comparison, because doing it once+ up front strips a qualified key's own path punctuation and folds ``exp-a/`` into ``expa/``.+ Directory-qualified keys keep their legacy bare spelling, since stored pins predate them. Root-level H3+ stems do not: a bare quant names both FL2VA and Ref2VA, and picking the first file would load a+ different task."""from hub.utils.gguf import is_qualified_gguf_variant_keyfrom utils.models.model_config import _gguf_variant_key@@ -4941,14 +4619,10 @@ def _main_variant_rank(rel_path: str, want: str) -> Optional[int]:def _variant_keys_match(key: str, want: str) -> bool:- """Whether *want* is *key*, for the exact-key test.-- ``_normalized_quant_label`` strips hyphens and underscores, which is right for a bare quant- (``UD-Q4_K_XL`` and ``udq4kxl`` are the same ask) and wrong for a path: it folds ``exp-a/`` and- ``expa/`` into one, so two advertised checkpoints both answered to the other's key. A qualified- key keeps its punctuation and compares case-insensitively; the legacy folding applies to the- bare aliases it was written for.- """+ """Whether *want* is *key*, for the exact-key test. ``_normalized_quant_label`` strips hyphens and+ underscores, which is right for a bare quant (``UD-Q4_K_XL`` and ``udq4kxl`` are the same ask) and wrong+ for a path: it folds ``exp-a/`` and ``expa/`` into one, so two advertised checkpoints both answered to+ the other's key."""from hub.utils.gguf import is_qualified_gguf_variant_keyif is_qualified_gguf_variant_key(key) or is_qualified_gguf_variant_key(want):@@ -4971,13 +4645,9 @@ def _repo_has_mmproj(repo_info) -> bool:def _cached_gguf_row_has_vision(repo_info, load_id: Optional[str]) -> bool:- """Whether the copy this row loads ships a projector.-- The loader opens the projector out of the snapshot it loads from, so one in a revision the- load never reaches is not vision support. A pinned row is judged on its snapshot, an unpinned- one on the first snapshot the load's own ordering finds a quant in. Judged per snapshot, not- per file: a split quant can sit in a subdirectory while the projector sits at the root.- """+ """Whether the copy this row loads ships a projector. The loader opens the projector out of the snapshot it+ loads from, so one in a revision the load never reaches is not vision support. Judged per snapshot, not+ per file: a split quant can sit in a subdirectory while the projector sits at the root."""if load_id:return _snapshot_has_gguf_projector(load_id)# No projector in any revision means none to reach, and saves a cache walk.@@ -5004,17 +4674,11 @@ def _iter_gguf_paths(root: Path, deadline: Optional[float] = None):def _repo_gguf_size_bytes(repo_info) -> int:- """Total on-disk size of primary GGUF weight files across all- revisions, excluding mmproj vision-adapter files.-- Hugging Face hardlinks blobs shared between revisions, so this- deduplicates by blob path (or revision commit hash + filename as a- fallback) to avoid double-counting. Unknown sizes (``size_on_disk is- None``, e.g. a partial download) count as zero. mmproj files are- excluded so repos whose only ``.gguf`` artifact is a vision adapter- aren't classed as GGUF repos: the variant selector filters mmproj- out and would otherwise show zero pickable variants.- """+ """Total on-disk size of primary GGUF weight files across all revisions, excluding mmproj. Hugging Face+ hardlinks blobs shared between revisions, so this deduplicates by blob path (or revision commit hash ++ filename) to avoid double-counting; unknown sizes count as zero. mmproj files are excluded so repos+ whose only ``.gguf`` artifact is a vision adapter are not classed as GGUF repos: the variant selector+ filters mmproj out and would otherwise show zero pickable variants."""unique_blobs: dict[str, int] = {}for revision in repo_info.revisions:rev_id = getattr(revision, "commit_hash", None) or str(id(revision))@@ -5032,18 +4696,14 @@ def _repo_gguf_size_bytes(repo_info) -> int:def _repo_has_gguf_files(repo_info) -> bool:- """True when any revision in a cached repo has a primary GGUF weight- file. Repos whose only ``.gguf`` artifact is an mmproj vision adapter- are not treated as GGUF here."""+ """True when any revision in a cached repo has a primary GGUF weight file; an mmproj-only repo is+ not one."""return _repo_gguf_size_bytes(repo_info) > 0def _blob_mtime(f) -> float:- """Blob modification time in epoch seconds (0.0 if unknown).-- Prefers HF metadata ``blob_last_modified``, falls back to stat(); uses- only mtimes (portable across Windows, macOS, Linux), never path parsing.- """+ """Blob modification time in epoch seconds (0.0 if unknown). Prefers HF metadata+ ``blob_last_modified``, falls back to stat(); only mtimes, never path parsing."""ts = getattr(f, "blob_last_modified", None)if isinstance(ts, (int, float)) and ts > 0:return float(ts)@@ -5057,11 +4717,8 @@ def _blob_mtime(f) -> float:def _repo_gguf_last_modified(repo_info) -> float:- """Newest mtime among a repo's primary (non-mmproj) GGUF blobs.-- Drives the Downloaded list's "last downloaded" ordering and groups a- multi-quant repo by its most recently downloaded quant.- """+ """Newest mtime among a repo's primary (non-mmproj) GGUF blobs, driving the Downloaded list's "last+ downloaded" ordering."""latest = 0.0for revision in repo_info.revisions:for f in cached_repo_files(revision):@@ -5083,10 +4740,9 @@ def snapshot_has_complete_variants(snapshot: str) -> bool:def _repo_gguf_load_id(repo_info, active_root: Optional[Path]) -> Optional[str]:- """Snapshot dir holding the newest primary GGUF, for a repo outside the active- hub cache that does not resolve by id. ``None`` when the id works or no- snapshot is recorded, since the repo dir itself is not loadable.- """+ """Snapshot dir holding the newest primary GGUF, for a repo outside the active hub cache that does+ not resolve by id. ``None`` when the id works or no snapshot is recorded, since the repo dir itself+ is not loadable."""from hub.utils.hf_cache_state import snapshot_selection_keyrepo_path = getattr(repo_info, "repo_path", None)@@ -5121,11 +4777,9 @@ def _repo_gguf_load_id(repo_info, active_root: Optional[Path]) -> Optional[str]:def _preferred_gguf_copy(rows: dict, ranks: dict, key: str, candidate: tuple[bool, bool], size: int) -> bool:- """Whether this copy should replace the one already kept for *key*.-- Same order the Hub inventory deduplicates by: a copy that cannot load loses to one that can,- whichever cache holds it, then the active cache wins, then the larger download.- """+ """Whether this copy should replace the one already kept for *key*, in the order the Hub inventory+ deduplicates by: a copy that cannot load loses to one that can, then the active cache wins, then+ the larger download."""existing = rows.get(key)if existing is None:return True@@ -5227,14 +4881,10 @@ def _cached_repo_partial(repo_cache_dir: Optional[Path] = None,snapshot_dir: Optional[Path] = None,) -> bool:- """Whether the cached model snapshot is incomplete (cancelled/partial download).- Reuses the hub inventory scan's snapshot-partial detector (cancel marker, legacy- .incomplete blob, manifest walk -- cheapest first). ``repo_cache_dir`` scopes the cache copy;- ``snapshot_dir`` attributes repo-wide signals to the selected revision. Without both, an- interrupted newer revision can flag a complete pinned revision as partial and hide it from the- picker.- Best-effort: a detection error reports not-partial so a scan glitch never hides a- genuinely usable repo."""+ """Whether the cached model snapshot is incomplete (cancelled/partial download), reusing the hub inventory+ scan's detector. ``repo_cache_dir`` scopes the cache copy and ``snapshot_dir`` attributes repo-wide+ signals to the selected revision; without both, an interrupted newer revision can flag a complete pinned+ revision as partial. Best-effort: a detection error reports not-partial so a glitch never hides a repo."""try:from hub.utils.inventory_scan import is_snapshot_partialreturn bool(is_snapshot_partial("model", repo_id, repo_cache_dir, snapshot_dir))@@ -5261,17 +4911,11 @@ _NON_GGUF_WEIGHT_EXTENSIONS = (".safetensors", ".bin")def _snapshot_can_serve_a_load(snapshot: Path) -> bool:- """Whether this snapshot has metadata and a complete weight payload.-- Transformers snapshots use the local scanners' config-plus-weight check. Diffusers- pipelines instead have a root ``model_index.json`` and component payloads in subdirs,- so use the same component-completeness check that guards local media loads.-- huggingface_hub keeps one snapshot per commit, so a partial fetch leaves an unloadable- dir with a newer mtime than the complete one beside it. Both halves happen: metadata- only (AutoConfig/AutoTokenizer at a newer revision) and weights only (Unsloth's base- model pre-warm fetches the shards plus index, no config.json).- """+ """Whether this snapshot has metadata and a complete weight payload. Transformers snapshots use the local+ scanners' config-plus-weight check; diffusers pipelines instead have a root ``model_index.json`` and+ component payloads in subdirs, so use the component-completeness check that guards local media loads.+ huggingface_hub keeps one snapshot per commit, so a partial fetch leaves an unloadable dir with a newer+ mtime than the complete one beside it, and both halves happen: metadata only, and weights only."""if _local_pipeline_index(snapshot):from core.inference.media_locality import _pipeline_components_presentfrom hub.utils.inventory_scan import snapshot_pipeline_missing_denoiser@@ -5307,14 +4951,10 @@ def _repo_model_snapshots(repo_info) -> list:def _repo_is_reachable_by_id(repo_path: Path, active_root: Path, loadable: Optional[Path]) -> bool:- """Whether loading this repo by its bare id lands somewhere that can serve it.-- Only the active cache makes the id a target, and there ``from_pretrained`` follows- ``refs/main``: ``repo_id_will_not_resolve`` catches a ref naming no directory, but a- ref naming an EXISTING half-fetched snapshot resolves fine and then fails. This is the- non-GGUF twin of ``default_ref_offers_no_whole_quant``. An unreadable ref, or a repo- with no better sibling, keeps the id it had.- """+ """Whether loading this repo by its bare id lands somewhere that can serve it. Only the active cache makes+ the id a target, and there ``from_pretrained`` follows ``refs/main``: ``repo_id_will_not_resolve``+ catches a ref naming no directory, but a ref naming an EXISTING half-fetched snapshot resolves fine and+ then fails. The non-GGUF twin of ``default_ref_offers_no_whole_quant``."""try:if repo_path.parent.resolve(strict = False) != active_root:return False@@ -5324,9 +4964,9 @@ def _repo_is_reachable_by_id(repo_path: Path, active_root: Path, loadable: Optioreturn Falseif loadable is None:return True- # No refs/main at all is not "fine", it is unresolvable: huggingface_hub writes- # refs/<revision> only when revision != commit_hash, so a commit-pinned fetch writes- # none and a tag-pinned one writes refs/<tag>. Offline the bare id then finds nothing.+ # No refs/main at all is not "fine", it is unresolvable: huggingface_hub writes refs/<revision> only when+ # revision != commit_hash, so a commit-pinned fetch writes none and a tag-pinned one writes refs/<tag>.+ # Offline the bare id then finds nothing.ref_snapshot = _default_ref_snapshot(repo_path)return ref_snapshot is not None and _snapshot_can_serve_a_load(ref_snapshot)@@ -5334,14 +4974,11 @@ def _repo_is_reachable_by_id(repo_path: Path, active_root: Path, loadable: Optiodef _repo_model_selection(repo_info, active_root: Optional[Path]) -> tuple[Optional[Path], Optional[str]]:- """The snapshot a load of this repo will read, and the load id pinning it.-- One choice of revision, so every field describing the pick answers for the SAME copy.- Scanning history instead lets an old revision speak for the row: a repo pushed first as- a LoRA and later merged into the same id (``push_to_hub_merged``) keeps its stale- ``adapter_config.json``, and a whole-model row read as an adapter is dropped from the- chat picker. ``load_id`` is ``None`` when the bare id already reaches a serving copy.- """+ """The snapshot a load of this repo will read, and the load id pinning it. One choice of revision, so every+ field describing the pick answers for the SAME copy. Scanning history instead lets an old revision speak+ for the row: a repo pushed first as a LoRA and later merged into the same id keeps its stale+ ``adapter_config.json``, and a whole-model row read as an adapter is dropped from the chat picker.+ ``load_id`` is ``None`` when the bare id already reaches a serving copy."""repo_path = getattr(repo_info, "repo_path", None)if repo_path is None or active_root is None:return None, None@@ -5365,22 +5002,17 @@ def _repo_model_selection(def _repo_model_load_id(repo_info, active_root: Optional[Path]) -> Optional[str]:- """Snapshot dir to load a non-GGUF repo by, or ``None`` when the bare id already works.-- The non-GGUF twin of ``_repo_gguf_load_id``: a repo cached only in the legacy or- default cache otherwise reads as its bare id, which ``ModelConfig`` resolves through- the active cache instead, so offline the pick cannot load and online it re-downloads.- """+ """Snapshot dir to load a non-GGUF repo by, or ``None`` when the bare id already works. The non-GGUF twin of+ ``_repo_gguf_load_id``: a repo cached only in the legacy or default cache otherwise reads as its bare+ id, which ``ModelConfig`` resolves through the active cache instead, so offline the pick cannot load and+ online it re-downloads."""return _repo_model_selection(repo_info, active_root)[1]def _repo_model_format(repo_info, selected: Optional[Path] = None) -> Optional[str]:- """``"adapter"`` for a cached LoRA/PEFT repo, else ``None``.-- ``cached_model_rows`` set no format, so every consumer filtering out adapters compared- against a key that never existed. An adapter ships ``adapter_config.json``; a merge does not.- Judged on the selected revision; only when none is determinable does history stand in.- """+ """``"adapter"`` for a cached LoRA/PEFT repo, else ``None``. ``cached_model_rows`` set no format, so+ every consumer filtering out adapters compared against a key that never existed. An adapter ships+ ``adapter_config.json``; a merge does not. Judged on the selected revision."""for snapshot in [selected] if selected is not None else _repo_model_snapshots(repo_info):try:if (snapshot / "adapter_config.json").is_file():@@ -5391,16 +5023,10 @@ def _repo_model_format(repo_info, selected: Optional[Path] = None) -> Optional[sdef _repo_model_can_chat(repo_info, selected: Optional[Path] = None) -> Optional[bool]:- """``False`` for a cached encoder-only repo (embedding, CLIP, ViT), else ``None``.-- The classification the hub inventory already applies to its own rows. ``task`` is- ``None`` for everything not diffusion, so a cached BERT or CLIP otherwise read as an- ordinary chat model. ``None`` when nothing is conclusive, so unknowns are never hidden.-- The selected revision answers first, so capability describes the copy the pin will- load rather than whichever snapshot sorts newest. Other snapshots stand in only when- the selection has no readable config, such as a weights-only snapshot.- """+ """``False`` for a cached encoder-only repo (embedding, CLIP, ViT), else ``None``: the classification the hub+ inventory already applies to its own rows. ``task`` is ``None`` for everything not diffusion, so a+ cached BERT or CLIP otherwise read as an ordinary chat model. ``None`` when nothing is conclusive, so+ unknowns are never hidden. The selected revision answers first."""from hub.services.models.common import _local_transformers_can_chat, _read_local_json_objectordered = _repo_model_snapshots(repo_info)@@ -5439,9 +5065,8 @@ def cached_model_rows(cache_scans = None) -> list[dict]:continueselected, model_load_id = _repo_model_selection(repo_info, active_root)if _recovered_repo_is_unusable_by_repo_id(repo_info):- # That guard withheld these because this schema could describe neither a- # partial nor a path; it now carries load_id, so a recovery holding a- # snapshot that serves a load is listed pinned to it instead of dropped.+ # That guard withheld these because this schema could describe neither a partial nor a path; it now+ # carries load_id, so a recovery holding a snapshot that serves a load is listed pinned to it.if not (model_load_id is not Noneand selected is not None@@ -5544,9 +5169,9 @@ async def delete_cached_model(def _resolve_cached_model_path(repo_id: str, variant: Optional[str]) -> Path:- """Absolute path of a cached repo (newest snapshot dir) or, with *variant*,- that quant's main GGUF file (first split of a sharded quant). Paths come- from the HF cache scan only, so callers can't probe arbitrary paths."""+ """Absolute path of a cached repo (newest snapshot dir) or, with *variant*, that quant's main GGUF file+ (first split of a sharded quant). Paths come from the HF cache scan only, so callers cannot probe+ arbitrary paths."""cache_scans = _all_hf_cache_scans()@@ -5722,13 +5347,9 @@ _EXPORT_SIZE_CACHE: dict[str, tuple[int, int, str]] = {}def _is_sizable_local_path(model: str) -> bool:- """True only for local paths under an Unsloth data root.-- Containment is decided lexically (no filesystem access) before the path is- touched, then the path is symlink-resolved and re-checked so a symlink- inside a root can't point the sizer outside it. A user-controlled path thus- can't trigger a scan of an arbitrary dir.- """+ """True only for local paths under an Unsloth data root. Containment is decided lexically (no filesystem+ access) before the path is touched, then the path is symlink-resolved and re-checked so a symlink inside+ a root cannot point the sizer outside it."""from utils.paths import outputs_root, exports_root, studio_rootfrom utils.paths.storage_roots import cache_root@@ -5769,11 +5390,9 @@ def _is_sizable_local_path(model: str) -> bool:def _export_size_cached(model: str, hf_token: Optional[str]) -> tuple[Optional[int], Optional[int], str]:- """Estimate a model's fp16/bf16-equivalent size in bytes (+ total params).-- Memoizes successful results by model id; never raises (failures return- (None, None, "unavailable") and are not cached). Blocking I/O; call off-thread.- """+ """Estimate a model's fp16/bf16-equivalent size in bytes (+ total params). Memoizes successful results by+ model id; never raises (failures return (None, None, "unavailable") and are not cached). Blocking I/O;+ call off-thread."""cached = _EXPORT_SIZE_CACHE.get(model)if cached is not None:return cacheddiff --git a/studio/backend/routes/openai_codex_auth.py b/studio/backend/routes/openai_codex_auth.pyindex cc06299acbb..a1fa659396c 100644--- a/studio/backend/routes/openai_codex_auth.py+++ b/studio/backend/routes/openai_codex_auth.py@@ -166,9 +166,8 @@ async def list_subscription_models(]status = codex_auth.auth_status(provider_id)if status == "reauthorization_required":- # Something already marked this bundle, possibly another worker, after the last- # provider sync the browser saw. Saying only "curated" here would leave the- # editor presenting a dead connection as healthy.+ # Something already marked this bundle, possibly another worker, after the last provider sync the browser+ # saw. Saying only "curated" here would leave the editor presenting a dead connection as healthy.return {"models": curated, "source": "reauthorization_required"}if status != "connected":return {"models": curated, "source": "curated"}@@ -178,10 +177,9 @@ async def list_subscription_models(provider_id, token, account_id, force = refresh)except (codex_auth.CodexAuthError, codex_client.CodexReauthorizationError) as exc:- # Say it in the answer rather than through a 401: the client's authFetch reads every 401 as an expired Unsloth- # session and retries, and the retry looks healthy.- # resolve_access has already marked the connection as needing reauthorization, so a source the picker does not- # treat as authoritative carries the signal instead.+ # Say it in the answer rather than through a 401: the client's authFetch reads every 401 as an expired+ # Unsloth session and retries, and the retry looks healthy. resolve_access has already marked the connection+ # as needing reauthorization, so a source the picker does not treat as authoritative carries the signal.logger.info("openai_codex.model_list_reauthorization_required",provider_id = provider_id,diff --git a/studio/backend/routes/preview.py b/studio/backend/routes/preview.pyindex 0faaba2c8c5..437b6472efe 100644--- a/studio/backend/routes/preview.py+++ b/studio/backend/routes/preview.py@@ -157,9 +157,8 @@ async def _serve_chat(if serializer_waiting:await resume_preview_after_serializer(scope)serializer_waiting = False- # The in-process coroutine, not the /load route: the route's padding returns a- # StreamingResponse while the checkpoint is still loading, so the chat below- # would run against the previous model (or none).+ # The in-process coroutine, not the /load route: the route's padding returns a StreamingResponse while the+ # checkpoint is still loading, so the chat below would run against the previous model (or none).await load_model_for_preview(LoadRequest(model_path = str(path)), request, DEFAULT_ADMIN_USERNAME)diff --git a/studio/backend/routes/profile_stats.py b/studio/backend/routes/profile_stats.pyindex c7fb370b420..c5b1c93bcb9 100644--- a/studio/backend/routes/profile_stats.py+++ b/studio/backend/routes/profile_stats.py@@ -1,10 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Usage numbers for the Profile settings tab.--Read-only aggregation over the local studio.db (see+"""Usage numbers for the Profile settings tab. Read-only aggregation over the local studio.db (see``storage.profile_stats_db``). Nothing is uploaded."""@@ -46,9 +43,8 @@ async def get_profile_stats(``Date.getTimezoneOffset()`` fallback for hosts with no tzdata."""try:- # A cold pass parses every message's metadata JSON: ~90 ms at 10k- # messages, ~1.2 s at 260k. Off the event loop so it cannot stall token- # streaming when Settings is opened mid-generation.+ # A cold pass parses every message's metadata JSON: ~90 ms at 10k messages, ~1.2 s at 260k. Off the event+ # loop so it cannot stall token streaming when Settings is opened mid-generation.return await asyncio.to_thread(compute_profile_stats,days = days,diff --git a/studio/backend/routes/prompts.py b/studio/backend/routes/prompts.pyindex df810087661..aa0b759da0f 100644--- a/studio/backend/routes/prompts.py+++ b/studio/backend/routes/prompts.py@@ -1,9 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Prompt storage API routes backed by studio.db.-"""+"""Prompt storage API routes backed by studio.db."""from fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import BaseModel, Fielddiff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.pyindex 815bb2abc61..eded18a6d81 100644--- a/studio/backend/routes/providers.py+++ b/studio/backend/routes/providers.py@@ -1,15 +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-"""-API routes for external LLM provider management.--Endpoints:- - Discover available provider types (registry)- - CRUD for saved provider configurations and API keys- - Fetch the RSA public key for API key encryption- - Test provider connectivity- - List models from a provider+"""API routes for external LLM provider management: the provider-type registry, CRUD for saved provider+configurations and their API keys, the RSA public key used to encrypt those keys, connectivity tests, and model+listing."""import uuid@@ -114,9 +108,9 @@ def _validate_provider_auth_contract(raise HTTPException(status_code = 400, detail = "ChatGPT subscription routing is fixed.")if models is None:return- # Same order of evidence the chat route uses, so a save cannot persist a model that- # every send would then refuse: the plan's catalog once it is known, otherwise the- # seed, plus what this row already carries unless it was left by another account.+ # Same order of evidence the chat route uses, so a save cannot persist a model that every send would then+ # refuse: the plan's catalog once it is known, otherwise the seed, plus what this row already carries unless it+ # was left by another account.if provider_id and openai_codex_client.subscription_catalog_known(provider_id):allowed = openai_codex_client.offered_subscription_model_ids(provider_id) | {slug@@ -145,16 +139,11 @@ def _validate_max_output_tokens_contract(field_was_set: bool,value: Optional[int] = None,) -> None:- """Reject a non-null override on a ChatGPT subscription.-- Codex routing, model list and output cap are all fixed, so an override stored there- would never be read. Every other type takes one: the frontend uses it to lower a- model's documented cap, or to replace the 32,768-token fallback for a model with no- documented cap.-- An explicit null is allowed everywhere, Codex included: a blank field serialises as- null rather than as an omission, and clearing an absent override is a no-op.- """+ """Reject a non-null override on a ChatGPT subscription. Codex routing, model list and output cap+ are all fixed, so an override stored there would never be read. Every other type takes one: the+ frontend uses it to lower a model's documented cap, or to replace the 32,768-token fallback for+ a model with no documented cap. An explicit null is allowed everywhere, Codex included: a blank+ field serialises as null rather than as an omission, and clearing an absent override is a no-op."""if field_was_set and value is not None and provider_type == "openai_codex":raise HTTPException(status_code = 400,@@ -162,9 +151,6 @@ def _validate_max_output_tokens_contract()-# ── Public key for API key encryption ─────────────────────────────--@router.get("/public-key")async def get_public_key(current_subject: str = Depends(get_current_subject)):"""Return the RSA public key PEM for client-side API key encryption.@@ -178,9 +164,6 @@ async def get_public_key(current_subject: str = Depends(get_current_subject)):}-# ── Provider registry (static) ───────────────────────────────────--@router.get("/registry", response_model = list[ProviderRegistryEntry])async def list_registry(include_hidden: bool = False, current_subject: str = Depends(get_current_subject)@@ -196,9 +179,6 @@ async def list_registry(return list_available_providers(include_hidden = include_hidden)-# ── Per-MTok pricing snapshot for client-side cost display ──────────--@router.get("/pricing")async def get_pricing_snapshot(current_subject: str = Depends(get_current_subject)):"""Static per-MTok pricing table the frontend uses to convert upstream@@ -206,9 +186,6 @@ async def get_pricing_snapshot(current_subject: str = Depends(get_current_subjecreturn pricing_snapshot()-# ── Provider config CRUD ──────────────────────────────────────────--# FastAPI offloads sync reads; mutations stay on-loop to preserve atomic sequences.@router.get("/", response_model = list[ProviderResponse])def list_provider_configs(_current_subject: str = Depends(get_current_subject)):@@ -306,15 +283,13 @@ async def update_provider_config(payload.max_output_tokens,)persisted_models = list(existing.get("models") or [])- # One reading of who owns this connection, used for every decision in this request:- # a second lookup later could name a different account than the one the selection was- # actually judged against.+ # One reading of who owns this connection, used for every decision in this request: a second lookup later could+ # name a different account than the one the selection was actually judged against.validated_account: str | None = Noneif existing_info.get("auth_kind") == "chatgpt_oauth":- # The OAuth bundle is shared through the installation DB while the catalog is per- # process, so another worker may have rebound this connection. The chat route- # makes the same check; without it here a save would persist exactly what every- # send then refuses.+ # The OAuth bundle is shared through the installation DB while the catalog is per process, so another worker+ # may have rebound this connection. The chat route makes the same check; without it here a save would persist+ # exactly what every send then refuses.current_bundle = openai_codex_auth.load_oauth_bundle(provider_id)validated_account = current_bundle.get("account_id") if current_bundle else Nonecurrent_account = validated_account@@ -324,10 +299,9 @@ async def update_provider_config(openai_codex_client.forget_subscription_models(provider_id)openai_codex_client.mark_subscription_catalog_stale(provider_id)if existing_info.get("auth_kind") == "chatgpt_oauth" and payload.models:- # Only a slug that is neither seeded nor already saved here needs the plan- # catalog. Reaching upstream for the others would make an ordinary save wait out- # the 20s connect / 120s read timeout whenever ChatGPT is unreachable, and would- # fail an unrelated edit to a connection whose selection was accepted long ago.+ # Only a slug that is neither seeded nor already saved here needs the plan catalog. Reaching upstream for the+ # others would make an ordinary save wait out the 20s connect / 120s read timeout whenever ChatGPT is+ # unreachable, and would fail an unrelated edit to a connection whose selection was accepted long ago.unproven = (set(payload.models) - set(existing_info["default_models"]) - set(persisted_models))@@ -367,9 +341,8 @@ async def update_provider_config(}metadata_requested = bool(payload.model_fields_set & metadata_fields)- # Only a *changed* base URL is validated. The dialog re-sends the stored value- # on every edit, so validating an unchanged legacy row would lock the user out- # of editing its models or API key. Outbound use is still checked.+ # Only a *changed* base URL is validated. The dialog re-sends the stored value on every edit, so validating an+ # unchanged legacy row would lock the user out of editing its models or API key. Outbound use is still checked.base_url = payload.base_urlif base_url and base_url != existing["base_url"]:try:@@ -416,17 +389,14 @@ async def update_provider_config(return current.get(field) == writtendef _restore_metadata() -> None:- """Undo this request's own metadata write, while it is still the row.-- update_provider commits and closes its own connection, so the row is already- durable by the time any later step fails; a compensating write is the only undo- there is. This handler suspends between that commit and the proof write, though- (remember_catalog_account awaits a 30s file lock, and the failure worth undoing is- exactly the one where that lock was contended), so a second save can land in- between. Restoring the whole pre-request snapshot would silently erase it. Put- back only the columns this request set, and only those the row still holds this- request's value for: a column a later save has since claimed belongs to that save.- """+ """Undo this request's own metadata write, while it is still the row. update_provider commits+ and closes its own connection, so the row is already durable by the time any later step+ fails; a compensating write is the only undo there is. This handler suspends between that+ commit and the proof write, though (remember_catalog_account awaits a 30s file lock, and the+ failure worth undoing is exactly the one where that lock was contended), so a second save+ can land in between. Restoring the whole pre-request snapshot would silently erase it. Put+ back only the columns this request set, and only those the row still holds this request's+ value for: a column a later save has since claimed belongs to that save."""if not metadata_requested:returncurrent = providers_db.get_provider(provider_id)@@ -436,9 +406,8 @@ async def update_provider_config(for field, written in metadata_updates.items():if field == "id":continue- # None means "not sent" for every column but max_output_tokens, which is only- # present here when it was explicitly requested. update_provider left the- # unsent ones alone, so there is nothing of this request's to take back.+ # None means "not sent" for every column but max_output_tokens, which is only present here when it was+ # explicitly requested. update_provider left the unsent ones alone, so there is nothing to take back.if written is None and field != "max_output_tokens":continueif not _current_matches(current, field, written):@@ -482,18 +451,15 @@ async def update_provider_config(row = providers_db.get_provider(provider_id)if existing_info.get("auth_kind") == "chatgpt_oauth" and payload.models is not None:- # Record the proof here rather than when a catalog is read: reading one only- # shows which account answered, while this is the point where the row's models- # were actually judged against it and stored.- # The account the selection was judged against, not whatever owns the connection- # by now. remember_catalog_account re-reads under the guard and declines to write- # when the bundle has moved on, so a rebind in between records nothing.- # Written after the row, never before: a proof recorded ahead of a commit that- # then failed would license models this connection never saved. Recording it is- # part of the save, so a failure here undoes the row too. Leaving the new models- # behind without the proof is the state saved_models_proven_for exists to catch,- # and it outlives the process: after a restart, with the plan catalog unreadable,- # the row's own slugs stop authorizing chat and the next save is refused as well.+ # Record the proof here rather than when a catalog is read: reading one only shows which account answered,+ # while this is the point where the row's models were actually judged against it and stored. The account the+ # selection was judged against, not whatever owns the connection by now: remember_catalog_account re-reads+ # under the guard and declines to write when the bundle has moved on, so a rebind in between records nothing.+ # Written after the row, never before: a proof recorded ahead of a commit that then failed would license+ # models this connection never saved. Recording it is part of the save, so a failure here undoes the row too.+ # Leaving the new models behind without the proof is the state saved_models_proven_for exists to catch, and it+ # outlives the process: after a restart, with the plan catalog unreadable, the row's own slugs stop+ # authorizing chat and the next save is refused as well.if validated_account:try:await openai_codex_auth.remember_catalog_account(provider_id, validated_account)@@ -579,14 +545,12 @@ async def delete_provider_config("provider.delete_credential_rollback_failed", provider_id = provider_id)raise- # The plan catalog is held per connection in this process and is only- # released by forget_subscription_models. Disconnecting the OAuth bundle- # calls it, deleting the whole connection did not, so every ChatGPT- # connection a user removed left its catalog, its account marker and its- # request ticket behind for the life of the process. Ids come from uuid4 and- # are never reused, so nothing stale could be consulted again; it simply- # accumulated. Released here, after the row is gone for good, so a rolled- # back delete keeps the catalog it is about to need again.+ # The plan catalog is held per connection in this process and is only released by+ # forget_subscription_models. Disconnecting the OAuth bundle calls it, deleting the whole connection did+ # not, so every ChatGPT connection a user removed left its catalog, its account marker and its request+ # ticket behind for the life of the process. Ids come from uuid4 and are never reused, so nothing stale+ # could be consulted again; it simply accumulated. Released here, after the row is gone for good, so a+ # rolled back delete keeps the catalog it is about to need again.openai_codex_client.forget_subscription_models(provider_id)@@ -613,14 +577,10 @@ def _bind_saved_provider_target(payload):)-# ── Test connectivity ─────────────────────────────────────────────--async def _test_custom_provider_connectivity(client, model_id: str) -> ProviderTestResult:- """Probe a custom OpenAI-compatible endpoint without assuming /chat/completions.-- TTS-only gateways such as Kokoro expose ``/models`` and ``/audio/speech`` but- not ``/chat/completions``. Try those first, then fall back to a chat probe."""+ """Probe a custom OpenAI-compatible endpoint without assuming /chat/completions. TTS-only gateways such as+ Kokoro expose ``/models`` and ``/audio/speech`` but not ``/chat/completions``. Try those first, then fall+ back to a chat probe."""model_id = (model_id or "").strip()models_error: Exception | None = Nonetry:@@ -767,9 +727,6 @@ async def test_provider(await client.close()-# ── List models from provider ─────────────────────────────────────--@router.post("/models", response_model = list[ProviderModelInfo])async def list_provider_models(payload: ProviderModelsRequest,@@ -822,12 +779,10 @@ async def list_provider_models(try:models = await client.list_models()- # Registry model-id filters describe one vendor's own catalog, so they- # only apply on that vendor's host. A Gemini OAI-compat proxy returns- # prefixed ids the allowlist strips, and an Azure or self-hosted OpenAI- # base returns operator-chosen deployment names that can carry any word- # the denylist reads as non-chat (`gpt-5.5-image-analysis`). Either way- # the picker empties out for a connection that works.+ # Registry model-id filters describe one vendor's own catalog, so they only apply on that vendor's host. A+ # Gemini OAI-compat proxy returns prefixed ids the allowlist strips, and an Azure or self-hosted OpenAI base+ # returns operator-chosen deployment names that can carry any word the denylist reads as non-chat+ # (`gpt-5.5-image-analysis`). Either way the picker empties out for a connection that works._NATIVE_HOSTS = {"gemini": ("generativelanguage.googleapis.com",),"openai": ("api.openai.com",),@@ -859,8 +814,8 @@ async def list_provider_models(denylist = info.get("model_id_denylist")if denylist is not None:models = [m for m in models if not denylist.search(m.get("id", ""))]- # Optional cap after filtering to keep large catalogs picker-sized.- # Unsorted, so "first N matches"; pair with default_models for flagships.+ # Optional cap after filtering to keep large catalogs picker-sized. Unsorted, so "first N matches"; pair with+ # default_models for flagships.limit = info.get("model_id_limit")if isinstance(limit, int) and limit > 0:models = models[:limit]diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.pyindex e6cc8cd6ff3..0a324275e69 100644--- a/studio/backend/routes/rag.py+++ b/studio/backend/routes/rag.py@@ -1,16 +1,13 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""HTTP API for the RAG engine: KB CRUD, uploads, SSE ingestion, search.+"""HTTP API for the RAG engine: KB CRUD, uploads, SSE ingestion, search. Single-tenant: the subject gates+access, not data.-Single-tenant: the subject gates access, not data.--Without a working sqlite-vec the router still mounts, and one contract covers every-endpoint. The KB list is polled, so it answers 200 with an empty list carrying an-availability marker, which is what lets a client tell an empty store from a machine-where RAG cannot run. Every other endpoint answers 503 stating the same reason.-Nothing logs a traceback for it: the condition is fixed for the session and rag_db-warns about it exactly once.+Without a working sqlite-vec the router still mounts, and one contract covers every endpoint. The KB list is+polled, so it answers 200 with an empty list carrying an availability marker, which is what lets a client tell+an empty store from a machine where RAG cannot run. Every other endpoint answers 503 stating the same reason.+Nothing logs a traceback for it: the condition is fixed for the session and rag_db warns about it exactly once."""from __future__ import annotations@@ -47,27 +44,21 @@ _UNAVAILABLE_DETAIL = "RAG is unavailable: the sqlite-vec extension could not bedef _require_rag() -> None:- """Gate an endpoint on RAG being runnable here.-- Covers both halves of unavailable: sqlite-vec never imported, and it imported but- its native library will not load. 503 with a stated reason rather than the 500 plus- traceback a raising connection would produce, and rag_db's warn-once keeps the log- quiet however often this fires.- """+ """Gate an endpoint on RAG being runnable here. Covers both halves of unavailable: sqlite-vec never+ imported, and it imported but its native library will not load. 503 with a stated reason rather+ than the 500 plus traceback a raising connection would produce, and rag_db's warn-once keeps the+ log quiet however often this fires."""if not rag_db.rag_available():raise HTTPException(status_code = 503, detail = _UNAVAILABLE_DETAIL)@contextmanagerdef _rag_unavailable_as_503(cleanup_path: str | None = None) -> Iterator[None]:- """Report RagExtensionUnavailable as the same 503, wherever it is raised.-- _require_rag() has normally answered for the session already; this closes the window- where the very first request is the one that discovers the missing library, and it- reaches the connections ingestion opens for itself. ``cleanup_path`` removes an- upload that was saved before the failure, so nothing is orphaned in the uploads- root. Real database errors are left alone.- """+ """Report RagExtensionUnavailable as the same 503, wherever it is raised. _require_rag() has+ normally answered for the session already; this closes the window where the very first request+ is the one that discovers the missing library, and it reaches the connections ingestion opens+ for itself. ``cleanup_path`` removes an upload that was saved before the failure, so nothing is+ orphaned in the uploads root. Real database errors are left alone."""try:yieldexcept rag_db.RagExtensionUnavailable as exc:@@ -82,12 +73,9 @@ def _rag_connection() -> sqlite3.Connection:def _availability(available: bool) -> dict:- """Availability marker carried by the KB list, the one response that degrades- rather than erroring.-- Additive: a client that only reads the list is unaffected, one that reads this can- say "RAG cannot run here" instead of showing an empty page that looks ready to use- and offering a Create that can only 503.+ """Availability marker carried by the KB list, the one response that degrades rather than erroring.+ Additive: a client that only reads the list is unaffected, one that reads this can say "RAG cannot run here"+ instead of showing an empty page that looks ready to use and offering a Create that can only 503."""return {"ragAvailable": available,@@ -358,10 +346,8 @@ def _require_scope_owner(scope_id: str,conn: sqlite3.Connection | None = None,) -> None:- """404 unless the scope's owner still exists.-- ``conn`` reuses a connection the caller already holds: sqlite-vec loads per- connection, so opening a second one to read a single row pays that twice.+ """404 unless the scope's owner still exists. ``conn`` reuses a connection the caller already holds:+ sqlite-vec loads per connection, so opening a second one to read a single row pays that twice."""if scope_type == "knowledge_base":if conn is not None:@@ -414,10 +400,10 @@ def list_knowledge_bases(subject: str = Depends(get_current_subject)) -> dict:try:conn = rag_db.get_connection()except rag_db.RagExtensionUnavailable:- # RAG_AVAILABLE only covers the import; the native library can still fail to load per connection (a missing vec0- # binary in the venv). The UI polls this list, so 500ing costs a traceback every few seconds for a condition- # that never changes in a session, and rag_db has warned once. The marker is the difference between "no- # knowledge bases yet" and "RAG cannot run here". Only the unavailable case degrades: a locked or corrupt+ # RAG_AVAILABLE only covers the import; the native library can still fail to load per connection (a missing+ # vec0 binary in the venv). The UI polls this list, so 500ing costs a traceback every few seconds for a+ # condition that never changes in a session, and rag_db has warned once. The marker is the difference between+ # "no knowledge bases yet" and "RAG cannot run here". Only the unavailable case degrades: a locked or corrupt# database still raises.return {"knowledgeBases": [], **_availability(False)}try:@@ -612,9 +598,9 @@ def _discard_document(document_id: str) -> None:store.delete_document(conn, document_id)finally:conn.close()- # Same uploads-root confinement as every other cleanup path, and best-effort for the same- # reason: on Windows commonpath raises across drives and os.remove raises while the ingestion- # worker still holds the file, neither of which should turn this into a 500.+ # Same uploads-root confinement as every other cleanup path, and best-effort for the same reason: on Windows+ # commonpath raises across drives and os.remove raises while the ingestion worker still holds the file, neither+ # of which should turn this into a 500._remove_stored_upload(document.get("stored_path"))diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.pyindex 9a113afe072..df7171e4ae6 100644--- a/studio/backend/routes/research_runs.py+++ b/studio/backend/routes/research_runs.py@@ -235,9 +235,8 @@ def _sanitize_config(value is not None for value in (provider_type, provider_id, external_model))if external_requested:- # A saved connection is still mandatory: the run is durable, so an- # inline key would have to be persisted, and _is_sensitive_key exists to- # stop exactly that. Only the provider-type allowlist is widened.+ # A saved connection is still mandatory: the run is durable, so an inline key would have to be persisted, and+ # _is_sensitive_key exists to stop exactly that. Only the provider-type allowlist is widened.if (not provider_runs_local_tools(provider_type)or not isinstance(provider_id, str)@@ -252,10 +251,9 @@ def _sanitize_config(provider = providers_db.get_provider(provider_id)if provider is None:raise HTTPException(status_code = 404, detail = "Provider config not found")- # The saved row is the source of truth for routing, so validate against it rather than the type the client sent:- # a self-hosted connection is stored under the backend "openai" type but surfaced as "custom" / "vllm" /- # "ollama" / "llama_cpp", so comparing the two for equality 400s exactly the connections this path exists to- # serve.+ # The saved row is the source of truth for routing, so validate against it rather than the type the client+ # sent: a self-hosted connection is stored under the backend "openai" type but surfaced as "custom" / "vllm" /+ # "ollama" / "llama_cpp", so comparing the two for equality 400s exactly the connections this path serves.saved_provider_type = provider["provider_type"]if not provider_runs_local_tools(saved_provider_type) or not provider["is_enabled"]:raise HTTPException(@@ -264,9 +262,9 @@ def _sanitize_config()request["providerType"] = saved_provider_type- # Mirrors the ragScope guard below. Every allowed field is a scalar, but "model" is- # stringified, so {"auth": "sk-..."} would slip past the sensitive-key scan (inner key- # unlisted) into the durable config as the model id.+ # Mirrors the ragScope guard below. Every allowed field is a scalar, but "model" is stringified, so+ # {"auth": "sk-..."} would slip past the sensitive-key scan (inner key unlisted) into the durable config as the+ # model id.if any(isinstance(value, (dict, list, tuple)) for value in request.values()):raise HTTPException(status_code = 400, detail = "Invalid inferenceRequest value")model = str(request.get("model") or thread.get("modelId") or "").strip()@@ -333,9 +331,9 @@ def _sanitize_config("whole_doc",}unknown_rag = set(rag_scope) - allowed_rag- # Every ragScope field is a scalar. A nested container evades the sensitive-key scan when- # its inner keys are unlisted (e.g. {"kb_id": {"auth": "sk-..."}}) and would reach- # retrieval code expecting a scalar scope id, so reject non-scalars outright.+ # Every ragScope field is a scalar. A nested container evades the sensitive-key scan when its inner keys+ # are unlisted (e.g. {"kb_id": {"auth": "sk-..."}}) and would reach retrieval code expecting a scalar scope+ # id, so reject non-scalars outright.non_scalar = any(isinstance(value, (dict, list, tuple)) for value in rag_scope.values())if unknown_rag or non_scalar or _contains_sensitive_key(rag_scope):raise HTTPException(status_code = 400, detail = "Unsupported or sensitive ragScope field")@@ -409,9 +407,9 @@ def create_research_run(raise HTTPException(status_code = 400, detail = "userMessageId must identify a user message in the thread")- # A handed-off question counts as the text. The worker researches config.question, so a multimodal turn that reads- # an image and calls deep_research passes the question it wrote, and refusing on the message's own empty text ends a- # complete handoff in a toast.+ # A handed-off question counts as the text. The worker researches config.question, so a multimodal turn that+ # reads an image and calls deep_research passes the question it wrote, and refusing on the message's own empty+ # text ends a complete handoff in a toast.if not message_text_with_pastes(user_message).strip() and not (payload.question or "").strip():raise HTTPException(status_code = 400,diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex ea906605bd0..71d48a61686 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -250,15 +250,13 @@ class VideoGenerationPresetState(MediaGenerationPresetState):class ImageGenerationPresetSettings(ImageGenerationPresetState):- # No cap on the read: upsert_media_generation_preset owns the limit, and refusing to- # report a store that somehow exceeds it would only turn a GET into a 500.+ # No cap on the read: upsert_media_generation_preset owns the limit, and refusing to report a store+ # that somehow exceeds it would only turn a GET into a 500.customPresets: list[ImageGenerationPreset] = Field(default_factory = list)saved: bool = Falseclass VideoGenerationPresetSettings(VideoGenerationPresetState):- # No cap on the read: upsert_media_generation_preset owns the limit, and refusing to- # report a store that somehow exceeds it would only turn a GET into a 500.customPresets: list[VideoGenerationPreset] = Field(default_factory = list)saved: bool = False@@ -271,12 +269,10 @@ def _nested_model(annotation: Any) -> Optional[type[BaseModel]]:def _readable(model: type[BaseModel], value: Any) -> Any:- """Drop what this build's schema does not define, keeping every field it does.-- `extra = "forbid"` is right for a submitted payload but wrong for reading storage back: a blob- holding one field from a newer build would otherwise fail validation, and a stored recipe the- user can no longer read is worse than one missing a field this build cannot render anyway.- """+ """Drop what this build's schema does not define, keeping every field it does. `extra = "forbid"` is right+ for a submitted payload but wrong for reading storage back: a blob holding one field from a newer build+ would otherwise fail validation, and a stored recipe the user can no longer read is worse than one+ missing a field this build cannot render anyway."""if isinstance(value, list):return [_readable(model, item) for item in value]if not isinstance(value, dict):@@ -310,11 +306,8 @@ def _without_field_at_location(value: Any, location: tuple[Any, ...]) -> tuple[Adef _validated_without_invalid_fields(schema: type[BaseModel], payload: dict) -> tuple[BaseModel, list[tuple[Any, ...]]]:- """Validate, dropping only the fields that fail.-- Resetting the whole recipe over one unreadable field would hand the client schema defaults,- which it then autosaves over the rest of a perfectly good stored recipe.- """+ """Validate, dropping only the fields that fail. Resetting the whole recipe over one unreadable field would+ hand the client schema defaults, which it then autosaves over the rest of a good stored recipe."""remaining = payloadremoved_locations = []while True:@@ -358,13 +351,10 @@ def _with_value_at_location(def _preserve_recovered_defaults(schema: type[BaseModel], stored: dict, submitted: dict) -> dict:- """Do not mistake a recovery default for an edit to an unreadable stored field.-- A downgraded GET omits known fields whose values this schema cannot validate, then Pydantic- supplies their defaults in the response. The client cannot tell those defaults from stored- values and echoes them in its next state write. Preserve the raw leaf only while the submitted- value is still the synthesized value; a real edit remains authoritative.- """+ """Do not mistake a recovery default for an edit to an unreadable stored field. A downgraded GET omits+ known fields whose values this schema cannot validate, then Pydantic supplies their defaults in the+ response; the client cannot tell those defaults from stored values and echoes them in its next state+ write. Preserve the raw leaf only while the submitted value is still the synthesized value."""recovered, locations = _validated_without_invalid_fields(schema, _readable(schema, stored))recovered_values = recovered.model_dump()merged = submitted@@ -394,15 +384,14 @@ def _get_generation_preset_settings(kind, schema):try:response = schema.model_validate(_readable(schema, stored))except ValidationError:- # A value this build cannot represent at all. Drop only what fails: one unreadable entry- # costs neither the rest of the list nor the state, which is validated on its own here.+ # A value this build cannot represent at all. Drop only what fails: one unreadable entry costs neither+ # the rest of the list nor the state.logger.warning("Dropping unreadable %s generation preset entries", kind)presets = schema.model_fields["customPresets"].annotationitem = _nested_model(get_args(presets)[0] if get_args(presets) else presets)readable = []- # Only a list is a preset collection. Recovery exists so a store this build cannot- # represent still reads; iterating a scalar here would answer 500 instead, which is the- # one outcome it is meant to prevent. _custom_presets takes the same view on the write.+ # Only a list is a preset collection. Recovery exists so a store this build cannot represent still+ # reads; iterating a scalar here would answer 500 instead. _custom_presets takes the same view on write.raw_presets = stored.get("customPresets")for raw in raw_presets if isinstance(raw_presets, list) else []:validated = _validated_readable_model(item, raw)@@ -608,15 +597,13 @@ class DownloadTransportResponse(BaseModel):mode: strxet_available: boolxet_unavailable_reason: Optional[str] = None- # What "auto" resolves to here right now, and why.auto_resolves_to: strauto_reason: Optional[str] = Noneclass XetNoticeReservePayload(BaseModel):- # A legacy localStorage count from a client that has not reported one before.- # Can only raise the stored count (see reserve_xet_notice), so a client cannot- # talk its own way back under the limit with it.+ # A legacy localStorage count from a client that has not reported one before. Can only raise the+ # stored count (see reserve_xet_notice), so a client cannot talk its own way back under the limit.seen_hint: int = 0@@ -663,16 +650,14 @@ class ModelMemoryResponse(BaseModel):# vetoes it; the UI surfaces that rather than failing silently.mlock_active: boolreload_required: bool- # Soft RLIMIT_MEMLOCK when finite. mlock cannot exceed it, so the UI warns- # that residency will not fully pin a model larger than this. None means- # unlimited (macOS) or not applicable (Windows).+ # Soft RLIMIT_MEMLOCK when finite. mlock cannot exceed it, so the UI warns that residency will not+ # fully pin a larger model. None means unlimited (macOS) or not applicable (Windows).memlock_limit_bytes: Optional[int] = Noneclass VramBudgetPayload(BaseModel):- # None clears the stored budget so env/default applies again; it cannot also mean "leave- # untouched", hence required rather than defaulted: with a default, a client that dropped the- # field would silently discard the stored budget.+ # None clears the stored budget so env/default applies again; it cannot also mean "leave untouched", hence+ # required rather than defaulted: with a default, a client that dropped the field would silently discard it.fraction: Optional[float] = Field(ge = VRAM_FRACTION_MIN, le = VRAM_FRACTION_MAX)@field_validator("fraction", mode = "before")@@ -735,7 +720,6 @@ class OpenAIAutoSwitchPayload(BaseModel):auto_unload_api_only: Optional[bool] = None# The image/video TTL is its own setting, not a share of the chat one.media_auto_unload_idle_seconds: Optional[int] = Field(default = None, ge = 0)- # And so is image/video auto-switch, for the same reason.media_auto_switch_model: Optional[bool] = None@@ -743,9 +727,8 @@ class OpenAIAutoSwitchResponse(BaseModel):enabled: boolauto_unload_idle_seconds: intdefault_enabled: bool = DEFAULT_OPENAI_AUTO_SWITCH_ENABLED- # True when the idle-unload loop will actually unload (effective TTL > 0). With- # UNSLOTH_MODEL_IDLE_TTL set and nothing stored, this is true even while enabled- # is false, so the UI can show idle-unload as active instead of "needs enable".+ # True when the idle-unload loop will actually unload (effective TTL > 0). With UNSLOTH_MODEL_IDLE_TTL set+ # and nothing stored this is true even while enabled is false, so the UI can show idle-unload as active.idle_unload_active: bool = Falseauto_unload_keep_kv: bool = DEFAULT_AUTO_UNLOAD_KEEP_KV# Stored, not effective: the UI must round-trip the saved value across an auto-switch toggle.@@ -810,10 +793,9 @@ class ModelOverridePayload(BaseModel):# meaningful values (none kept; cache disabled; no limit). Bounds mirror LoadRequest.ctx_checkpoints: Optional[int] = Field(default = None, ge = 0, le = CTX_CHECKPOINTS_MAX)cache_ram: Optional[int] = Field(default = None, ge = CACHE_RAM_MIN_MIB, le = CACHE_RAM_MAX_MIB)- # Does this client know the four above exist? A save REPLACES the entry, so an omission from a build that predates- # them is indistinguishable from a user clearing them. Only a client that sets this may clear by omission; default- # False, so an old payload is the safe case. Not a blanket carry-over: that would make clearing impossible for- # everyone.+ # Does this client know the four above exist? A save REPLACES the entry, so an omission from a build that+ # predates them is indistinguishable from a user clearing them. Only a client that sets this may clear by+ # omission; default False, so an old payload is the safe case.mirrors_server_tuning: bool = Falsetensor_parallel: bool = Falsedisable_vision: bool = False@@ -835,7 +817,6 @@ class ModelOverridePayload(BaseModel):@field_validator("chat_template_override")@classmethoddef _limit_chat_template_bytes(cls, value: Optional[str]) -> Optional[str]:- # Mirrors LoadRequest.normalize_blank_chat_template_override.if value is None:return Nonesize = chat_template_byte_length(value)@@ -872,8 +853,8 @@ class ModelOverridePayload(BaseModel):class ModelOverridesResponse(BaseModel):overrides: dict[str, dict]# Filled only when the caller named a model, resolved here rather than in the browser: the folding rules are- # Python's, so a client mirroring them can only approximate.- # casefold is not toLowerCase, and an ambiguous fold matches nothing on purpose.+ # Python's (casefold is not toLowerCase), so a client mirroring them can only approximate, and an ambiguous+ # fold matches nothing on purpose.resolved: Optional[dict] = Noneresolved_key: Optional[str] = None# What an explicit remove cleared; empty for a save.@@ -921,11 +902,9 @@ _NO_LAUNCH = object()def _active_launch_placement():- """``(state, policy_active, mlock_applicable)`` for the running child.-- ``state`` is ``_NO_LAUNCH`` when nothing is running or coming up, so the- caller can tell "no process" apart from "a process with no load-mode".- """+ """``(state, policy_active, mlock_applicable)`` for the running child. ``state`` is ``_NO_LAUNCH``+ when nothing is running or coming up, so the caller can tell "no process" from "a process with no+ load-mode"."""try:from routes.inference import get_llama_cpp_backend@@ -943,19 +922,12 @@ def _active_launch_placement():def _model_memory_reload_required() -> bool:- """True when the loaded process's memory placement contradicts the settings.-- Compares the state the child ACTUALLY launched with -- env defaults plus- last-wins argv, so a user-supplied --mlock / --no-mmap counts -- against- what the current settings would produce. The idle-unload veto applies- immediately (the loop re-reads each poll), so only placement can be stale.-- Keyed on is_active, not is_loaded: a save that lands while a load is still- passing its health check would otherwise report no reload while the child is- already committed to the pre-save flags. _memory_launch_pending covers the- same window before Popen, where the placement is decided but _process is- still None.- """+ """True when the loaded process's memory placement contradicts the settings. Compares the state the child+ ACTUALLY launched with (env defaults plus last-wins argv, so a user-supplied --mlock / --no-mmap counts)+ against what the current settings would produce. The idle-unload veto applies immediately, so only+ placement can be stale. Keyed on is_active, not is_loaded: a save that lands while a load is still+ passing its health check would otherwise report no reload while the child is already committed to the+ pre-save flags."""state, policy_active, mlock_applicable = _active_launch_placement()if state is _NO_LAUNCH:return False@@ -967,16 +939,11 @@ def _model_memory_reload_required() -> bool:def _model_memory_mlock_active(want_mlock: bool) -> bool:- """Whether page-locking is actually in force, not merely asked for.-- This drives the locked-memory cap warning, so taking it from the toggles- alone would tell a discrete-GPU user to raise a limit nothing consults.- With nothing running this is the intent, so the UI reflects the toggle. Once- a child exists it is what that child got: a full offload to a discrete GPU- skips the lock, and a diffusion runner has no load-mode at all, so claiming- otherwise would warn about ulimit -l for a lock nobody took. A user's own- --mlock counts, since the resolver reads the launched argv.- """+ """Whether page-locking is actually in force, not merely asked for. This drives the locked-memory cap+ warning, so taking it from the toggles alone would tell a discrete-GPU user to raise a limit nothing+ consults. With nothing running this is the intent; once a child exists it is what that child got, since+ a full offload to a discrete GPU skips the lock and a diffusion runner has no load-mode at all. A+ user's own --mlock counts, since the resolver reads the launched argv."""if not want_mlock:return Falsestate, _policy_active, _applicable = _active_launch_placement()@@ -998,20 +965,15 @@ def _model_memory_response() -> ModelMemoryResponse:def _vram_budget_reload_required(fraction: float) -> bool:- """True when a child is running that was sized against a different budget.-- Compares against the fraction the child actually launched with, not merely- "is something loaded", so re-saving the same value does not nag for a reload.- Exact equality is fine: both sides come from the same clamp, so a stored 0.97- and a launched 0.97 are the same float.- """+ """True when a child is running that was sized against a different budget. Compares against the fraction the+ child actually launched with, so re-saving the same value does not nag for a reload. Exact equality is+ fine: both sides come from the same clamp."""try:from routes.inference import get_llama_cpp_backendbackend = get_llama_cpp_backend()- # A planned-but-unspawned load has no _process, so is_active is False while- # the child is already committed to its captured fraction; answer from the- # pending value there, as _active_launch_placement does for Model Memory.+ # A planned-but-unspawned load has no _process, so is_active is False while the child is already+ # committed to its captured fraction; answer from the pending value there.pending = getattr(backend, "_vram_fraction_pending", None)if pending is not None:return float(pending) != float(fraction)@@ -1101,7 +1063,6 @@ def update_llama_cpp_path(raise log_and_http_error(exc,400,- # Validator messages are safe to expose to the UI.str(exc),event = "settings.update_llama_cpp_path_failed",log = logger,@@ -1322,9 +1283,8 @@ class LastLocalModelPayload(BaseModel):gguf_variant: Optional[str] = Field(default = None, max_length = MAX_GGUF_VARIANT_KEY_LEN)# Epoch ms of the load; orders writes from surfaces that keep their own local shadow.loaded_at: Optional[int] = Field(default = None, ge = 0)- # The client clock when the request was sent: the skew translates loaded_at into the server- # frame. Never persisted.- # The skew is server_now - client_now.+ # The client clock when the request was sent: the skew (server_now - client_now) translates loaded_at+ # into the server frame. Never persisted.client_now: Optional[int] = Field(default = None, ge = 0)@@ -1475,7 +1435,6 @@ def update_openai_auto_switch() from excidle_unload_active = get_auto_unload_idle_seconds() > 0if not keep_kv or not idle_unload_is_configured():- # Drop already-saved chat context too.from core.inference.llama_keepwarm import purge_kv_resumepurge_kv_resume()return OpenAIAutoSwitchResponse(@@ -1525,19 +1484,12 @@ def _bare_model_id(model_id: str) -> Optional[str]:def _fallback_supplies_extra_args(model_id: str, target_id: str) -> bool:- """Whether a load for this model would still pick flags off another entry.-- The carry-over copies a legacy bare ``repo`` row's flags onto the first- ``repo:QUANT`` save and leaves the bare row in place, and a load reads the- qualified key first and the bare one after it. So clearing the box for the quant- is only a clear while the quant keeps a row of its own: an all-default save- stores nothing, and the next load falls through to a row no page can show.-- Answered rather than repaired. Stripping the flags off the bare row was the first- fix and it is too broad: that row is the fallback for every quant that has no row,- so forgetting Q4's flags took Q6's with them, and it did nothing at all when a- sibling quant had a row of its own.- """+ """Whether a load for this model would still pick flags off another entry. The carry-over copies a legacy+ bare ``repo`` row's flags onto the first ``repo:QUANT`` save and leaves the bare row in place, and a+ load reads the qualified key first and the bare one after it, so clearing the box for the quant is only+ a clear while the quant keeps a row of its own. Answered rather than repaired: stripping the flags off+ the bare row was the first fix and it is too broad, since that row is the fallback for every quant that+ has no row."""from utils.openai_auto_switch_settings import get_model_overridefor candidate in (@@ -1554,12 +1506,9 @@ def _fallback_supplies_extra_args(model_id: str, target_id: str) -> bool:def _other_quants_remain(bare_id: str, removed_ids: list[str]) -> bool:- """Whether a quant of ``bare_id`` other than the ones being removed still has an entry.-- Such a quant has its own settings and never reads the bare fallback, so this is not- "is anyone inheriting" but "is this forget the last one for the model". If it is not,- the bare entry stays: an inheriting quant is exactly what it is there for.- """+ """Whether a quant of ``bare_id`` other than the ones being removed still has an entry. Such a quant has its+ own settings and never reads the bare fallback, so this is not "is anyone inheriting" but "is this+ forget the last one for the model"."""from utils.openai_auto_switch_settings import split_quant_suffixremoved = {key.strip().lower() for key in removed_ids}@@ -1574,16 +1523,10 @@ def _other_quants_remain(bare_id: str, removed_ids: list[str]) -> bool:def _legacy_standalone_gguf_key(model_id: str) -> Optional[str]:- """The stored ``<path>:LABEL`` entry for a bare standalone .gguf path, if any.-- A loose file has no quant to choose between, so it is keyed by the bare path,- but the label derived from its filename is never empty and that is how the- picker keyed the same file before, so an upgraded install carries entries- under it. The auto-switch loader reads that spelling after the bare path- misses; resolve_model_override_key does not, since folding a POSIX path only- touches an existing suffix. None for an id that already names a quant, for a- repo id, and when nothing is stored under the derived key.- """+ """The stored ``<path>:LABEL`` entry for a bare standalone .gguf path, if any. A loose file has no quant to+ choose between, so it is keyed by the bare path, but the label derived from its filename is never empty+ and that is how the picker keyed the same file before, so an upgraded install carries entries under it.+ The auto-switch loader reads that spelling after the bare path misses."""import osif not model_id.lower().endswith(".gguf"):@@ -1601,18 +1544,12 @@ def _legacy_standalone_gguf_key(model_id: str) -> Optional[str]:def _fill_target_id(target_id: str) -> str:- """Where a one-time backfill write for ``target_id`` has to land.-- A fill only adds, so unlike a save it cannot retire the other spelling of a cached- repo. Creating the snapshot-path key while the server already holds the repo id- would leave two entries for one quant, and the loader reads the load path before the- advertised id, so an upgraded browser's pre-upgrade copy would shadow the newer- server config on every API load. Fill into the entry already there instead: nothing- outranks it, and the fields it lacks still arrive.-- Only in that direction. A repo-id key never outranks an existing path entry, and two- snapshot paths name two caches, neither of which is knowably the one loaded here.- """+ """Where a one-time backfill write for ``target_id`` has to land. A fill only adds, so unlike a save it+ cannot retire the other spelling of a cached repo. Creating the snapshot-path key while the server+ already holds the repo id would leave two entries for one quant, and the loader reads the load path+ before the advertised id, so an upgraded browser's pre-upgrade copy would shadow the newer server+ config. Only in that direction: a repo-id key never outranks an existing path entry, and two snapshot+ paths name two caches."""from core.inference.model_ids import hf_cache_repo_idfrom utils.openai_auto_switch_settings import split_quant_suffix@@ -1630,22 +1567,17 @@ def _fill_target_id(target_id: str) -> str:return target_id-# One override write at a time. A save stores its target key and then reads the map back to retire the other spelling of-# the same cached repo, and a remove clears up to four keys, each its own transaction: atomic on their own, but not as a-# sequence. This route is a plain `def`, so FastAPI runs it in a threadpool, and two clients saving one quant under both-# spellings (the repo id the picker sends and the snapshot path an upgraded install still holds) could each write before-# either cleanup ran and then retire the other's row, leaving no override at all from two saves that both returned 200.-# Serialize the whole handler instead: overrides are written by a settings edit, never on a hot path, and the server-# runs one process.+# One override write at a time. A save stores its target key and then reads the map back to retire the other+# spelling of the same cached repo, and a remove clears up to four keys, each its own transaction: atomic on+# their own, but not as a sequence. This route is a plain `def`, so FastAPI runs it in a threadpool, and two+# clients saving one quant under both spellings could each write before either cleanup ran and then retire the+# other's row, leaving no override at all from two saves that both returned 200._override_write_lock = threading.Lock()def _serialized_override_write(func):- """Run ``func`` under _override_write_lock, keeping the handler body as it reads.-- functools.wraps carries __wrapped__, which inspect.signature follows, so FastAPI still- sees the endpoint's own parameters and dependencies.- """+ """Run ``func`` under _override_write_lock. functools.wraps carries __wrapped__, which+ inspect.signature follows, so FastAPI still sees the endpoint's own parameters and dependencies."""@functools.wraps(func)def wrapper(*args, **kwargs):@@ -1669,9 +1601,9 @@ def update_openai_auto_switch_override(raise ValueError("fill_absent_fields cannot be combined with remove.")# Only model_id is the documented "remove"; otherwise omitted flags carry over.requested_extra_args = payload.llama_extra_args- # fill_absent_fields and mirrors_server_tuning are write modes.- # Leaving either in would make every payload look non-empty (they are bools, so exclude_none does not drop them)- # and break the legacy "no fields means remove".+ # fill_absent_fields and mirrors_server_tuning are write modes. Leaving either in would make every payload+ # look non-empty (they are bools, so exclude_none does not drop them) and break the legacy "no fields+ # means remove".saved_fields = payload.model_dump(exclude = {"model_id",@@ -1685,7 +1617,6 @@ def update_openai_auto_switch_override(if payload.remove is not None:is_removal = payload.removeelse:- # Both booleans are carried.is_removal = (not payload.tensor_paralleland not payload.disable_vision@@ -1706,9 +1637,8 @@ def update_openai_auto_switch_override(if bare_id:requested_extra_args = get_model_override(bare_id).get("llama_extra_args")if requested_extra_args is None:- # And for a standalone .gguf upgraded from the build that keyed it by its- # filename label: the bare path written here is read before that key, so- # its flags would go dark with no page able to show or restore them.+ # And for a standalone .gguf upgraded from the build that keyed it by its filename label: the bare+ # path written here is read before that key, so its flags would go dark with no page able to show them.legacy_id = _legacy_standalone_gguf_key(payload.model_id)if legacy_id:requested_extra_args = get_model_override(legacy_id).get("llama_extra_args")@@ -1734,14 +1664,14 @@ def update_openai_auto_switch_override()else:extra_args = validate_extra_args(requested_extra_args)- # Same shape as the extra-args carry-over above, for the same reason: a save replaces the entry, so a field the- # caller never knew about must survive it. Gated on is_removal, not on payload.remove: the documented legacy- # contract is a payload carrying only model_id, which leaves remove None while is_removal is true.+ # Same shape as the extra-args carry-over above, for the same reason: a save replaces the entry, so a field+ # the caller never knew about must survive it. Gated on is_removal, not on payload.remove: the documented+ # legacy contract is a payload carrying only model_id, which leaves remove None._tuning_fields = ("load_mode", "spec_draft_cache_type", "ctx_checkpoints", "cache_ram")_kept_tuning = {name: getattr(payload, name) for name in _tuning_fields}if not payload.mirrors_server_tuning and not is_removal:- # The same spellings the extra-args carry-over walks: a cached repo is not an ordinary folded match, so a- # save under the repo id would find nothing and retire the alias with its tuning.+ # The same spellings the extra-args carry-over walks: a cached repo is not an ordinary folded match,+ # so a save under the repo id would find nothing and retire the alias with its tuning._alias_ids = [payload.model_id]for _candidate in (_bare_model_id(payload.model_id),@@ -1750,12 +1680,12 @@ def update_openai_auto_switch_override():if _candidate and _candidate not in _alias_ids:_alias_ids.append(_candidate)- # Load order, not collection order: a lookup reads the concrete load path before the advertised repo id, so- # reading the repo row first adopts tuning no load has used.+ # Load order, not collection order: a lookup reads the concrete load path before the advertised repo+ # id, so reading the repo row first adopts tuning no load has used._alias_ids.sort(key = lambda _key: not is_cache_load_path_key(_key))- # Taken as a unit from the first row that exists, not field by field down the list.- # A load stops at the first non-empty row (resolve_override_for_load) rather than merging, so filling a gap- # in the winner from a loser would switch dormant tuning on.+ # Taken as a unit from the first row that exists, not field by field down the list: a load stops at the+ # first non-empty row rather than merging, so filling a gap in the winner from a loser would switch+ # dormant tuning on.for _alias_id in _alias_ids:_stored_tuning = get_model_override(_alias_id)if not _stored_tuning:@@ -1766,9 +1696,9 @@ def update_openai_auto_switch_override(breakremoved_keys: list[str] = []if payload.remove is True:- # An explicit remove wins over any other field. Remove the key a load resolves to,- # not the literal one sent (the browser normalizes casing), and every spelling:- # clearing one of two leaves the survivor as the sole fold match.+ # An explicit remove wins over any other field. Remove the key a load resolves to, not the literal one sent+ # (the browser normalizes casing), and every spelling: clearing one of two leaves the survivor as the sole+ # fold match.target_ids = resolve_model_override_keys(payload.model_id) or [payload.model_id,]@@ -1780,9 +1710,8 @@ def update_openai_auto_switch_override(removed_keys.append(legacy_id)# The mirror image of the carry-over above: a save under repo:QUANT copies the flags off a legacy bare# `repo` entry and leaves it in place, and the loader falls back to it when the qualified key misses, so- # clearing only the qualified key hands the same flags straight back and the forget does nothing. Nothing in- # the UI can reach that bare entry. Only once it is nobody else's fallback, though: it backs every quant- # with no entry of its own, so forgetting Q4 must not strip Q8.+ # clearing only the qualified key hands the same flags straight back. Only once it is nobody else's+ # fallback, though: it backs every quant with no entry of its own, so forgetting Q4 must not strip Q8.bare_id = _bare_model_id(payload.model_id)if (bare_id@@ -1808,9 +1737,9 @@ def update_openai_auto_switch_override(# A fill retires nothing below, so it must not create the higher-priority spelling of a row# the server already holds.target_id = _fill_target_id(target_id)- # An explicit clear keeps a row even when nothing else is set, so long as a fallback would- # otherwise answer for this model: "no launch flags" and "nothing stored" are the same thing- # everywhere else, and different here. Written on the quant's own key, so no other quant moves.+ # An explicit clear keeps a row even when nothing else is set, so long as a fallback would otherwise answer+ # for this model: "no launch flags" and "nothing stored" are the same thing everywhere else, and different+ # here. Written on the quant's own key, so no other quant moves.keep_empty = (payload.llama_extra_args == []and not payload.fill_absent_fields@@ -1932,10 +1861,8 @@ def _model_names_gguf_repo(model: str) -> bool:def _llama_runtime_available() -> bool:- """Whether a llama-server binary this install can launch is present.-- Shares the embedder's own probe so the resolver and the loader cannot disagree- about whether the backend exists."""+ """Whether a llama-server binary this install can launch is present. Shares the embedder's own probe+ so the resolver and the loader cannot disagree about whether the backend exists."""from core.rag import embeddingstry:return embeddings._llama_server_runtime_available()@@ -1944,13 +1871,10 @@ def _llama_runtime_available() -> bool:def _llama_backend_active(model: str | None = None) -> bool:- """Whether llama serves the active model, or would serve ``model`` if supplied.-- Delegates to the embeddings module so a runtime fallback from- sentence-transformers to llama-server (after a torch/CUDA load or encode- failure) is honored: in that state the process loads only inert GGUF, so the- ST pickle gate below must not hard-block a repo whose GGUF companion is clean.- Before any backend is built this still reflects the resolver."""+ """Whether llama serves the active model, or would serve ``model`` if supplied. Delegates to the embeddings+ module so a runtime fallback from sentence-transformers to llama-server is honored: in that state the+ process loads only inert GGUF, so the ST pickle gate below must not hard-block a repo whose GGUF+ companion is clean. Before any backend is built this reflects the resolver."""from core.rag import embeddingstry:if model is not None:@@ -1961,9 +1885,8 @@ def _llama_backend_active(model: str | None = None) -> bool:def _resolves_as_local_gguf(model: str) -> bool:- """True when ``model`` is a local .gguf file or a directory holding one, so- a save on the llama-server backend needs no HF verification (the artifact- itself is the proof)."""+ """True when ``model`` is a local .gguf file or a directory holding one, so a save on the+ llama-server backend needs no HF verification: the artifact itself is the proof."""from core.rag.embed_llama_server import LlamaServerBackendtry:return LlamaServerBackend._resolve_local_gguf(model) is not None@@ -1972,10 +1895,9 @@ def _resolves_as_local_gguf(model: str) -> bool:def _local_gguf_backend_error(model: str) -> str | None:- """409 detail when ``model`` is a local dir without a .gguf but this install- embeds via llama-server (macOS/CPU default), which needs one. A- sentence-transformers-only folder would verify fine yet fail at first index.- None when not applicable. ``force`` skips this check like HF verification."""+ """409 detail when ``model`` is a local dir without a .gguf but this install embeds via llama-server+ (macOS/CPU default), which needs one: a sentence-transformers-only folder would verify fine yet fail at+ first index. ``force`` skips this check like HF verification."""from pathlib import Pathfrom utils.paths import normalize_path@@ -2002,10 +1924,9 @@ def _local_gguf_backend_error(model: str) -> str | None:def _hf_gguf_backend_error(model: str, hf_token: Optional[str]) -> str | None:- """409 detail when the llama-server backend would find no .gguf for an HF- repo: neither the derived companion repo nor the repo itself has one. Saves- that verify as embedding models would otherwise fail at first index.- None when not applicable; ``force`` skips this like HF verification."""+ """409 detail when the llama-server backend would find no .gguf for an HF repo: neither the derived+ companion repo nor the repo itself has one, so saves that verify as embedding models would fail at+ first index. ``force`` skips this like HF verification."""from pathlib import Pathif Path(model).expanduser().exists():@@ -2045,9 +1966,8 @@ def get_embedding_model(class EmbeddingModelResolveResponse(BaseModel):embedding_model: strbackend: Literal["llama", "sentence-transformers"]- # Repo the picker hands the download manager, and the files to take from it.- # Split GGUF plans contain every shard in the selected family.- # Both None when nothing needs fetching, or when ``error`` is set.+ # Repo the picker hands the download manager, and the files to take from it. Split GGUF plans contain+ # every shard in the selected family; both None when nothing needs fetching or when ``error`` is set.download_repo: Optional[str] = Nonefiles: Optional[list[str]] = Nonecached: bool = False@@ -2121,24 +2041,18 @@ def _list_repo_files_bounded(repo: str, hf_token: Optional[str]) -> list[str]:def _gguf_conversion_name_matches(hit_name: str, base: str) -> bool:- """Whether a search hit names a conversion of exactly ``base``.-- Prefix matching is unsafe (``foo`` must never resolve to ``foo-bar-GGUF``).- The Hub filter already requires GGUF; this check accepts only the common- conversion suffix spellings and the exact model name.- """+ """Whether a search hit names a conversion of exactly ``base``. Prefix matching is unsafe (``foo`` must+ never resolve to ``foo-bar-GGUF``); the Hub filter already requires GGUF, so this accepts only the+ common conversion suffix spellings and the exact model name."""name = hit_name.casefold()base = base.casefold()return name == base or name in {f"{base}-gguf", f"{base}_gguf", f"{base}.gguf"}def _gguf_files_for_pick(names: list[str], picked: str) -> Optional[list[str]]:- """The complete downloadable file family for a picked GGUF.-- llama-server opens split siblings implicitly, so a single selected shard is- not a usable plan. Incomplete published families are rejected. Deferred to the- loader so the plan offered here and the transfer it performs name one set.- """+ """The complete downloadable file family for a picked GGUF. llama-server opens split siblings implicitly,+ so a single selected shard is not a usable plan, and incomplete published families are rejected.+ Deferred to the loader so the plan offered here and the transfer name one set."""from core.rag.embed_llama_server import LlamaServerBackendreturn LlamaServerBackend._split_family(names, picked)@@ -2152,10 +2066,8 @@ def _pick_downloadable_gguf(names: list[str]) -> Optional[list[str]]:def _search_hub_for_gguf(model: str, hf_token: Optional[str]) -> Optional[tuple[str, list[str]]]:- """``(repo, files)`` for a GGUF conversion of ``model`` published by the same- owner under a name the -GGUF candidates do not cover.-- Same owner only: a third party's "Qwen3-Embedding-8B-GGUF" is an unverified+ """``(repo, files)`` for a GGUF conversion of ``model`` published by the same owner under a name the -GGUF+ candidates do not cover. Same owner only: a third party's "Qwen3-Embedding-8B-GGUF" is an unverifiedre-upload, and picking unsloth/X must download unsloth's own weights."""from core.rag import config as rag_config@@ -2272,21 +2184,17 @@ def _st_backend_available() -> bool:def _is_st_weight_name(basename: str) -> bool:- """Whether a filename is a checkpoint, not just something ending in a suffix.-- Shared with the loader so the plan and the cache check cannot disagree."""+ """Whether a filename is a checkpoint, not just something ending in a suffix. Shared with the loader+ so the plan and the cache check cannot disagree."""from utils.utils import is_st_weight_namereturn is_st_weight_name(basename)def _st_weight_source(model: str, hf_token: Optional[str]) -> Optional[tuple[str, list[str]]]:- """``(repo, weight files)`` for the repo an ST load of ``model`` would open.-- A slashless name such as ``all-MiniLM-L6-v2`` resolves under the- ``sentence-transformers/`` namespace, which is what the loader's own- ``st_repo_id_candidates`` encodes. Probing only the literal id refused the- alias outright and a forced save then pinned it cache-only.- """+ """``(repo, weight files)`` for the repo an ST load of ``model`` would open. A slashless name such as+ ``all-MiniLM-L6-v2`` resolves under the ``sentence-transformers/`` namespace, which is what the loader's+ own ``st_repo_id_candidates`` encodes; probing only the literal id refused the alias outright and a+ forced save then pinned it cache-only."""from utils.utils import st_repo_id_candidatesfor candidate in st_repo_id_candidates(model) or [model]:@@ -2315,11 +2223,9 @@ def _st_weight_files(model: str, hf_token: Optional[str]) -> Optional[list[str]]def _cached_snapshot_has_st_weights(model: str) -> bool:- """Whether the cached snapshot holds a checkpoint ST itself can open.-- ``hf_cache_snapshot_is_loadable`` counts ``.gguf``, which is right for the- llama backend and wrong here: a cached GGUF-only repo would come back ready- with no checkpoint ST can load. No network."""+ """Whether the cached snapshot holds a checkpoint ST itself can open. ``hf_cache_snapshot_is_loadable``+ counts ``.gguf``, which is right for the llama backend and wrong here: a cached GGUF-only repo would+ come back ready with no checkpoint ST can load. No network."""try:from utils.utils import snapshot_has_st_weightsreturn snapshot_has_st_weights(model)@@ -2328,11 +2234,10 @@ def _cached_snapshot_has_st_weights(model: str) -> bool:def _cached_st_source(model: str):- """``(repo id, snapshot dir)`` the cached ST weights for ``model`` came from.-- The same predicate as ``_cached_snapshot_has_st_weights``, keeping the repo it- matched under rather than reducing it to a yes: for a slashless alias that repo- is the ``sentence-transformers/`` one, and the PUT verifies and scans it."""+ """``(repo id, snapshot dir)`` the cached ST weights for ``model`` came from. Same predicate as+ ``_cached_snapshot_has_st_weights``, keeping the repo it matched under rather than reducing it to a yes:+ for a slashless alias that repo is the ``sentence-transformers/`` one, and the PUT verifies and scans+ it."""try:from utils.utils import cached_st_sourcereturn cached_st_source(model)@@ -2358,19 +2263,17 @@ def _cached_st_weight_names(model: str) -> list[str]:def _safetensors_plan(model: str, hf_token: Optional[str]) -> Optional[tuple[str, list[str]]]:- """``(repo, files)`` for running ``model`` on sentence-transformers instead.-- An embedder with no GGUF still works from its own safetensors, for about 1 GB- more memory, which beats refusing the model or pulling a stranger's conversion."""+ """``(repo, files)`` for running ``model`` on sentence-transformers instead. An embedder with no GGUF still+ works from its own safetensors, for about 1 GB more memory, which beats refusing the model or pulling a+ stranger's conversion."""if not _st_backend_available():return None# A complete local snapshot is the same proof the listing gives, and works# offline, where the listing fails and a downloaded model became unselectable.from utils.utils import cached_st_repo- # The repo the snapshot is actually filed under: a slashless name caches under- # sentence-transformers/, and naming the literal id sends the download manager- # at a repo that usually does not exist.+ # The repo the snapshot is actually filed under: a slashless name caches under sentence-transformers/, and+ # naming the literal id sends the download manager at a repo that usually does not exist.cached_repo = cached_st_repo(model)if cached_repo:return (cached_repo, _cached_st_weight_names(cached_repo))@@ -2387,8 +2290,7 @@ def _sentence_transformers_fallback_allowed(model: str) -> bool:def _hf_files_size(repo: str, files: list[str], hf_token: Optional[str]) -> Optional[int]:- """Total bytes of ``files`` in ``repo``, for the confirm dialog. None when the- hub does not say; the dialog has copy for that."""+ """Total bytes of ``files`` in ``repo``, for the confirm dialog. None when the hub does not say."""try:from huggingface_hub import model_info@@ -2524,9 +2426,8 @@ def _resolve_embedding_model_plan("The repository publishes no checkpoint this backend can load."),)- # The repo that actually publishes the weights, which for a slashless- # alias is the sentence-transformers/ one, not the literal name. Same- # question whether the answer came from the cache or from the Hub.+ # The repo that actually publishes the weights, which for a slashless alias is the+ # sentence-transformers/ one, not the literal name.if cached:download_repo = cached_source[0]elif source is None:@@ -2547,9 +2448,8 @@ def _resolve_embedding_model_plan(llama_only = (local_ggufor _model_names_gguf_repo(resolved)- # An explicit llama policy (or a runtime pin) refuses the safetensors- # fallback for every model, not only GGUF-named ones, so an ordinary repo- # id is just as unservable here without a binary.+ # An explicit llama policy (or a runtime pin) refuses the safetensors fallback for every model, not+ # only GGUF-named ones, so an ordinary repo id is just as unservable here without a binary.or not _sentence_transformers_fallback_allowed(resolved))if llama_only and not _llama_runtime_available():@@ -2617,7 +2517,6 @@ def _resolve_embedding_model_plan(return EmbeddingModelResolveResponse(embedding_model = resolved,backend = backend,- # Every remote/cache/fallback probe above has already failederror = _no_embedding_weights_error(candidates),)st_repo, _st_files = st_plan@@ -2725,34 +2624,33 @@ def update_embedding_model(detail = "The embedding download repository was not validated for this model.",)destination_is_llama = plan.backend == "llama"- # Verify and scan the repo the loader will actually open: a slashless alias resolves under sentence-transformers/,- # so the literal name scans a repo that usually does not exist.- # Only the ST path can diverge: a llama download_repo is the GGUF companion, which is not what is scanned here.+ # Verify and scan the repo the loader will actually open: a slashless alias resolves under+ # sentence-transformers/, so the literal name scans a repo that usually does not exist. Only the ST path can+ # diverge: a llama download_repo is the GGUF companion, which is not what is scanned here.verify_target = modelif not destination_is_llama and plan.download_repo and plan.download_repo != model:verify_target = plan.download_repo- # The env/default model needs no verification; saving it is a no-op override.- # A local GGUF on the llama-server backend is accepted as-is: it is exactly- # what the backend loads, and HF metadata cannot verify a local path.+ # The env/default model needs no verification; saving it is a no-op override. A local GGUF on the+ # llama-server backend is accepted as-is: it is exactly what the backend loads, and HF metadata cannot+ # verify a local path.is_local_gguf = destination_is_llama and _resolves_as_local_gguf(model)- # The pickle gate matters only for the sentence-transformers backend; on llama-server the embedder loads inert- # GGUFs, so scanning the ST pickle wrongly rejects a clean companion.- # On the llama-server backend the embedder loads GGUF files from effective_gguf_repo().+ # The pickle gate matters only for the sentence-transformers backend; on llama-server the embedder loads+ # inert GGUFs from effective_gguf_repo(), so scanning the ST pickle wrongly rejects a clean companion.scan_st_pickle = (model != default_embedding_model() and not is_local_gguf and not destination_is_llama)if scan_st_pickle:- # Malware/pickle gate before persisting a repo the embedder later loads; runs even under force, which only skips- # the is-embedding type check for repos HF cannot verify.- # Local paths and unreachable scans fail open inside evaluate_file_security.+ # Malware/pickle gate before persisting a repo the embedder later loads; runs even under force, which only+ # skips the is-embedding type check for repos HF cannot verify. Local paths and unreachable scans fail open+ # inside evaluate_file_security.from utils.security import evaluate_file_security, security_load_subdirsfrom core.rag.embeddings import _st_module_subdirs# Fall back to the loader's own token so a gated/private repo is actually scanned# (a token-less scan fails open for exactly the repo that would still load).scan_token = hf_token or _ambient_hf_token()- # Offline: subdir probes would hit the network and hang; the offline gate walks the whole cached snapshot, so no- # load-subdir hints are needed.+ # Offline: subdir probes would hit the network and hang; the offline gate walks the whole cached+ # snapshot, so no load-subdir hints are needed.if local_only_load:load_subdirs = ()else:@@ -2794,8 +2692,8 @@ def update_embedding_model(gguf_named = destination_is_llama and rag_config._names_gguf(model)if not gguf_named and not is_embedding_model(verify_target, hf_token = hf_token):# Offline, is_embedding_model can only confirm the ST layout, so a cached and loadable transformers-native- # embedder is accepted rather than 409'd where online would not.- # The unverifiable case is a transformers-native embedder such as gte-modernbert; uncached still 409s.+ # embedder (gte-modernbert and the like) is accepted rather than 409'd where online would not. Uncached+ # still 409s.from utils.utils import hf_cache_snapshot_is_loadable# Require a genuinely loadable cache (config + weights), not just a resolved refs/main,@@ -2825,9 +2723,9 @@ def update_embedding_model(trusted_download_pending = Falseif plan.error is None:trusted_backend = "llama-server" if destination_is_llama else "sentence-transformers"- # The exact family this transfer delivers.- # A repo publishing no RAG_EMBED_GGUF_VARIANT is served another quant on purpose, which the loader's variant- # lookup cannot recognize as what was downloaded, so the model would stay cache-only.+ # The exact family this transfer delivers. A repo publishing no RAG_EMBED_GGUF_VARIANT is served another+ # quant on purpose, which the loader's variant lookup cannot recognize as what was downloaded, so the model+ # would stay cache-only.trusted_gguf_files = plan.files if destination_is_llama else None# A sentence-transformers download repo is not a GGUF source. Keeping# it out also prevents a later runtime fallback from mislabelling it.@@ -2836,9 +2734,8 @@ def update_embedding_model(# cache-only until the transfer completes, or a close/cancel becomes an implicit download.trusted_download_pending = bool(plan.download_repo and not plan.cached)else:- # Save anyway, over a failed plan: nothing validated to record, but the- # marker still has to go on or both loaders take their uncached path and- # fetch invisibly at the first index, which this picker exists to replace.+ # Save anyway, over a failed plan: nothing validated to record, but the marker still has to go on or+ # both loaders take their uncached path and fetch invisibly at the first index.trusted_download_pending = Trueset_rag_embedding_model(model,@@ -3177,12 +3074,9 @@ def update_current_date_prompt(def _require_ui_session_for_keyless(via_api_key: bool = Depends(authenticated_via_api_key)) -> None:- """Only a signed-in UI session may change who needs a key.-- An sk-unsloth key must not be able to switch authentication off for the whole- install, and a keyless caller must not be able to widen its own scope; both are- ``authenticated_via_api_key``, so one check covers them.- """+ """Only a signed-in UI session may change who needs a key. An sk-unsloth key must not be able to switch+ authentication off for the whole install, and a keyless caller must not be able to widen its own scope;+ both are ``authenticated_via_api_key``, so one check covers them."""if via_api_key:raise HTTPException(status_code = 403,@@ -3277,14 +3171,13 @@ class PersonalizationCustomColorModes(BaseModel):MAX_IMPORTED_FONTS = 3# ~1.5 MB font file as base64; matches MAX_IMPORTED_FONT_DATA_URL_LENGTH in the frontend.MAX_FONT_DATA_URL_LENGTH = 2_200_000-# Aggregate cap across all imported fonts, matching the frontend so a synced payload always fits-# the browser's localStorage quota.-# Matches MAX_TOTAL_IMPORTED_FONT_DATA_URL_LENGTH in the frontend.+# Aggregate cap across all imported fonts, matching MAX_TOTAL_IMPORTED_FONT_DATA_URL_LENGTH in the+# frontend so a synced payload always fits the browser's localStorage quota.MAX_TOTAL_FONT_DATA_URL_LENGTH = 4_400_000-# Characters that could terminate a CSS declaration, escape the quoted font-family value or smuggle-# extra fallbacks/comments if a stored name reached a stylesheet. The server is the authoritative-# gate; the frontend strips the same set.+# Characters that could terminate a CSS declaration, escape the quoted font-family value or smuggle extra+# fallbacks/comments if a stored name reached a stylesheet. The server is the authoritative gate; the frontend+# strips the same set._FONT_NAME_FORBIDDEN = set(";{}()<>\"'\\/,`")@@ -3315,9 +3208,8 @@ class PersonalizationImportedFont(BaseModel):@field_validator("dataUrl")@classmethoddef _validate_font_data_url(cls, value: str) -> str:- # fullmatch, not match: re's ``$`` also matches just before a trailing- # newline, so ``match`` would accept "data:font/woff2;base64,AAAA\n",- # which the frontend's JS pattern (``$`` = end of string) rejects.+ # fullmatch, not match: re's ``$`` also matches just before a trailing newline, which the frontend's+ # JS pattern (``$`` = end of string) rejects.if not _FONT_DATA_URL_PATTERN.fullmatch(value):raise ValueError("dataUrl must be a base64 font data URL.")return value@@ -3336,12 +3228,10 @@ SIDEBAR_MENU_ITEM_DEFAULTS = {"connections": False,}-# Navigable sidebar rows the user can pin/reorder; the boolean is each id's default pin state.-# Order and pin state MUST match the frontend's shipped layout: the client sends every id on each save, so a missing id+# Navigable sidebar rows the user can pin/reorder; the boolean is each id's default pin state. Order and pin+# state MUST match the frontend's shipped layout (SIDEBAR_NAV_ITEM_IDS / SIDEBAR_NAV_DEFAULT_PINNED in+# features/settings/stores/appearance-custom-store.ts): the client sends every id on each save, so a missing id# 422s the whole personalization PUT.-# The frontend constants are SIDEBAR_NAV_ITEM_IDS / SIDEBAR_NAV_DEFAULT_PINNED in features/settings/stores/appearance--# custom-store.ts, and a legacy record predating sidebarNav is served this default as if it were an explicit remote-# choice.SIDEBAR_NAV_ITEM_DEFAULTS = {"hub": True,"projects": True,@@ -3522,9 +3412,8 @@ def get_personalization_settings(def _merge_personalization(base: dict, overlay: dict) -> dict:- # Recursively overlay only the request's set fields onto the stored record,- # so a stale client that omits newer keys (palette, customization) does not- # materialize their defaults and defeat the *Saved legacy detection.+ # Recursively overlay only the request's set fields onto the stored record, so a stale client that+ # omits newer keys does not materialize their defaults and defeat the *Saved legacy detection.merged = dict(base)for key, value in overlay.items():existing = merged.get(key)@@ -3558,13 +3447,8 @@ def update_personalization_settings(return PersonalizationPayload.model_validate(merged)-# Backs Settings > Logs: the session log always existed, but its path was only printed to a-# console the desktop user never sees.---# ── Logs: read the log files from inside the app ─────────────────────────────-# Backs the Settings > Logs tab. The session log always existed, but its-# path was only printed to a console the desktop user never sees.+# Backs Settings > Logs: the session log always existed, but its path was only printed to a console+# the desktop user never sees.class DebugLogSourceModel(BaseModel):id: strfamily: strdiff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex e210109a552..313d4098935 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -1,10 +1,6 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Training API routes-"""-import contextlibimport jsonimport os@@ -54,7 +50,6 @@ try:from utils.models.model_config import detect_gguf_model, load_model_defaultsfrom utils.paths import is_local_path, normalize_path, resolve_dataset_pathexcept ImportError:- # Fallback: parent directory.parent_backend = backend_path.parent / "backend"if str(parent_backend) not in sys.path:sys.path.insert(0, str(parent_backend))@@ -159,14 +154,11 @@ _TRAINING_START_ERROR_RESPONSES = {def _hub_unreachable() -> bool:- """Bounded, memoised Hub reachability check.-- hf_env_offline() only reads env vars, so a link that is merely dead burns the full- 5s + 10s metadata budget per leg -- once per resolved address, so 30s at best and- minutes on a multi-homed resolver -- before the cached fallbacks are consulted. The- training worker subprocess already guards itself this way (core/training/worker.py);- the route that spawns it did not. Fails open, so an online start is unchanged.- """+ """Bounded, memoised Hub reachability check. hf_env_offline() only reads env vars, so a merely dead+ link burns the full 5s + 10s metadata budget per leg, once per resolved address: 30s at best and+ minutes on a multi-homed resolver, before the cached fallbacks are consulted. The worker+ subprocess already guards itself this way (core/training/worker.py); the route that spawns it+ did not. Fails open."""memo = hf_reachability_memo()if memo is not None:return memo@@ -235,13 +227,10 @@ def _stop_training_if_active(def _is_finalizing(progress, msg_lower: str) -> bool:- """Worker alive past the last step, `complete` not yet drained.-- The save emits no step updates, so the bar sat at 100% labelled "training", which is- indistinguishable from a hang. Non-terminal by design: the last step means the optimizer- loop ended, not that the save succeeded, so completion still comes solely from- is_completed.- """+ """Worker alive past the last step, `complete` not yet drained. The save emits no step updates, so+ the bar sat at 100% labelled "training", indistinguishable from a hang. Non-terminal by design:+ the last step means the optimizer loop ended, not that the save succeeded, so completion still+ comes solely from is_completed."""if any(k in msg_lower for k in ("saving", "merging")):return Truetotal = getattr(progress, "total_steps", 0) or 0@@ -265,7 +254,6 @@ def _run_active(backend) -> bool:def _validate_local_dataset_paths(paths: list[str], label: str = "Local dataset") -> list[str]:- """Resolve and validate a list of local dataset paths. Returns validated absolute paths."""validated = []missing = []for dataset_path in paths:@@ -406,11 +394,9 @@ def _has_complete_indexed_weights(path: Path, index_name: str, expected_suffix:def _trainable_local_roots(path: Path, model_name: Optional[str] = None) -> list[Path]:- """The snapshot root plus any subdirectory a load reads from.-- Spark-TTS / BiCodec keep config.json and the weights under <snapshot>/LLM, so probing- only the root reports a perfectly good cached model as having no trainable weights.- """+ """The snapshot root plus any subdirectory a load reads from. Spark-TTS / BiCodec keep config.json+ and the weights under <snapshot>/LLM, so probing only the root reports a good cached model as+ having no trainable weights."""roots = [path]if not model_name:return roots@@ -1139,12 +1125,10 @@ async def cancel_training_start_request(def _background_video_generation_active() -> bool:- """Whether a video clip is generating on the video backend's worker thread.-- POST /video/generate returns at once and generates in the background, so an- in-flight clip is invisible to the keep-warm in-flight request count the- API-key training guards consult; ask the backend directly. Best-effort: a- probe failure must never block a training start."""+ """Whether a video clip is generating on the video backend's worker thread. POST /video/generate+ returns at once and generates in the background, so an in-flight clip is invisible to the+ keep-warm in-flight request count the API-key training guards consult; ask the backend directly.+ Best-effort: a probe failure must never block a training start."""try:from core.inference.video import get_video_backendreturn bool(get_video_backend().generate_progress().get("active"))@@ -1180,10 +1164,9 @@ async def start_training(if existing_record is not None:return _start_request_response(existing_record)- # Under API-key auth refuse to start training while a request is in flight, since training unloads the chat- # model. Checked BEFORE reserving the id, or every retry replays a stale rejection.- # Checked BEFORE reserving start_request_id, since a transient refusal resolved to "rejected" would make every- # retry replay it forever. Mixed UI+API is not special-cased.+ # Under API-key auth refuse to start training while a request is in flight, since training unloads+ # the chat model. Checked BEFORE reserving start_request_id, since a transient refusal resolved to+ # "rejected" would make every retry replay it forever. Mixed UI+API is not special-cased.if via_api_key is True:from core.inference.llama_keepwarm import other_inference_request_countif (@@ -2114,7 +2097,6 @@ async def stream_training_progress(and (getattr(backend, "current_job_id", "") or "") == job_id)- # ── Helpers ──────────────────────────────────────────────def run_active() -> bool:"""A run that reported terminal is done, even while its worker tears down."""return _run_active(backend)@@ -2165,7 +2147,6 @@ async def stream_training_progress(event: str = "progress",event_id: Optional[int] = None,) -> str:- """Format a single SSE message with id/event/data fields."""lines = []if event_id is not None:lines.append(f"id: {event_id}")@@ -2178,10 +2159,8 @@ async def stream_training_progress(if not is_current_job():return- # ── Retry directive ──────────────────────────────────────yield "retry: 3000\n\n"- # ── Replay missed steps on reconnect ─────────────────────if not is_current_job():returnif resume_from_step is not None and backend.step_history:@@ -2222,7 +2201,6 @@ async def stream_training_progress(if replayed:logger.info(f"SSE reconnect: replayed {replayed} missed steps")- # ── Initial status (only on fresh connections) ───────────if resume_from_step is None:if not is_current_job():return@@ -2282,7 +2260,6 @@ async def stream_training_progress()return- # ── Live polling loop ────────────────────────────────────last_step = resume_from_step if resume_from_step is not None else -1no_update_count = 0# The stall timeout applies only once the run is stepping@@ -2416,7 +2393,6 @@ async def stream_training_progress()return- # ── Final "complete" event ───────────────────────────────if not is_current_job():returnfinal_step = backend.step_history[-1] if backend.step_history else last_step@@ -2458,9 +2434,9 @@ async def stream_training_progress()-# ── Diffusion (SDXL) LoRA training ──────────────────────────────────────────── A separate, lightweight job path:-# diffusion runs use DiffusionTrainingService (its own subprocess + event pump), not the LLM TrainingBackend.# ── Diffusion (SDXL) LoRA training ────────────────────────────────────────────+# A separate, lightweight job path: diffusion runs use DiffusionTrainingService (its own+# subprocess + event pump), not the LLM TrainingBackend.def _diffusion_training_active() -> bool:"""Whether a diffusion (SDXL) LoRA job is currently running. Best-effort so theinterlock never blocks a start just because the service could not be imported."""@@ -2477,13 +2453,11 @@ class _DiffusionStartInFlight(RuntimeError):@contextlib.contextmanagerdef _diffusion_gpu_admission():- """Hold the diffusion service's GPU admission across the LLM spawn.-- Makes the cross-trainer admission atomic: entering re-tests the diffusion state under the- service's own lock and raises if a diffusion run is reserved or active, and while it is held- the diffusion ``reserve()`` refuses. So of two near-simultaneous starts of different types,- exactly one proceeds. Fails OPEN on an import/health failure, like every other guard here: a- chat-only install has no diffusion service and must still be able to train."""+ """Hold the diffusion service's GPU admission across the LLM spawn. Makes the cross-trainer+ admission atomic: entering re-tests the diffusion state under the service's own lock and raises+ if a diffusion run is reserved or active, and while it is held the diffusion ``reserve()``+ refuses, so of two near-simultaneous starts exactly one proceeds. Fails OPEN on an import/health+ failure: a chat-only install has no diffusion service and must still be able to train."""try:from core.training.diffusion_training_service import (TrainingActiveError,@@ -2512,11 +2486,10 @@ def _diffusion_gpu_admission():def _require_diffusion_dataset_mutable() -> None:- """Reject a dataset mutation while a diffusion run is active.-- The trainer re-opens dataset images during the loop, so mutating underneath it makes the run- nondeterministic or raises a FileNotFoundError mid-step. Fails open (a service-import failure- never blocks a mutation on an unknowable state), matching the start interlock."""+ """Reject a dataset mutation while a diffusion run is active. The trainer re-opens dataset images+ during the loop, so mutating underneath it makes the run nondeterministic or raises a+ FileNotFoundError mid-step. Fails open (a service-import failure never blocks a mutation on an+ unknowable state), matching the start interlock."""if _diffusion_training_active():raise HTTPException(status_code = 409,@@ -2528,13 +2501,11 @@ def _require_diffusion_dataset_mutable() -> None:def diffusion_dataset_interlock():- """Dependency holding the dataset interlock for a whole mutating request.-- The check above only covers the instant it runs: every one of these endpoints then hands its- filesystem work to a thread, and a ``/diffusion/start`` reserving in that gap would move- captions or images underneath the preflight or the running trainer. As a yield dependency the- registration spans the endpoint, so ``reserve()`` sees it and refuses instead. Fails open on an- import error, like the check it replaces."""+ """Dependency holding the dataset interlock for a whole mutating request. The check above only+ covers the instant it runs: every one of these endpoints then hands its filesystem work to a+ thread, and a ``/diffusion/start`` reserving in that gap would move captions or images+ underneath the preflight or the running trainer. As a yield dependency the registration spans+ the endpoint, so ``reserve()`` refuses instead. Fails open on an import error."""try:from core.training.diffusion_training_service import (TrainingActiveError,@@ -2552,12 +2523,10 @@ def diffusion_dataset_interlock():def _free_gpu_for_diffusion_training() -> None:- """Free GPU residents before the diffusion trainer spawns its own SDXL pipeline.-- The trainer subprocess loads a full SDXL pipeline; an export worker, a resident- Images pipeline, or loaded chat models would otherwise keep their VRAM allocated and- OOM the run. Mirrors the LLM start path's pre-spawn cleanup (export + diffusion- pipeline + chat). Best-effort: a failure to free one resident never blocks the start."""+ """Free GPU residents before the diffusion trainer spawns its own SDXL pipeline. The trainer+ subprocess loads a full SDXL pipeline; an export worker, a resident Images pipeline or loaded+ chat models would keep their VRAM and OOM the run. Mirrors the LLM start path's pre-spawn+ cleanup. Best-effort: failing to free one resident never blocks the start."""try:from core.export import get_export_backendexp_backend = get_export_backend()@@ -2651,15 +2620,12 @@ def _preflight_gated_base(base_model: str, hf_token: Optional[str]) -> None:def _resolve_diffusion_data_dir(raw: str) -> Path:- """Resolve a diffusion-training ``data_dir``. The upload/labeling routes create and- manage image datasets directly under ``datasets_root()`` and the UI passes the bare- folder name back as ``data_dir``, but the generic :func:`resolve_dataset_path`- searches the LLM uploads and recipe dataset roots FIRST -- so an unrelated upload- file or recipe folder sharing that name would shadow the just-uploaded image- dataset (preflight 400 "not a directory", or training the wrong data). Prefer the- image dataset root for a bare single-component name that exists there; everything- else (explicit "uploads/..." / "recipes/..." prefixes, absolute paths, missing- names) resolves exactly as before."""+ """Resolve a diffusion-training ``data_dir``. The upload/labeling routes manage image datasets+ directly under ``datasets_root()`` and the UI passes the bare folder name back as ``data_dir``,+ but :func:`resolve_dataset_path` searches the LLM uploads and recipe roots FIRST, so an+ unrelated upload or recipe folder of that name would shadow the just-uploaded image dataset.+ Prefer the image dataset root for a bare single-component name that exists there; everything+ else resolves exactly as before."""from utils.paths import datasets_rootvalue = str(raw or "").strip()@@ -2684,17 +2650,13 @@ def _preflight_diffusion_resume() -> None:"""Validate ``config["resume_from_checkpoint"]`` against ``identity``, optionally PINNING it.- Pinning rewrites the config's resume path to the exact ``checkpoint-<N>`` directory that was- accepted, so the trainer subprocess resumes the bundle this preflight approved rather than- re-picking "newest" from a directory that could have changed.-- Called twice -- once before the dataset is known, once with its fingerprint -- and both- times BEFORE the resident GPU models are freed. The FIRST pass does not pin: its identity- has no dataset fingerprint, so that comparison is skipped and it can accept the newest- bundle on the strength of a check it did not make. Rewriting the request to that bundle- left the dataset-aware pass with nothing to do but reject it, when scanning the original- directory would have found an older retained checkpoint matching the current images.- Raises ResumeError."""+ Pinning rewrites the config's resume path to the exact ``checkpoint-<N>`` directory accepted, so+ the trainer resumes the bundle this preflight approved rather than re-picking "newest" from a+ directory that could have changed. Called twice, once before the dataset is known and once with+ its fingerprint, both times BEFORE the resident GPU models are freed. The FIRST pass does not+ pin: its identity has no dataset fingerprint, so it can accept the newest bundle on the strength+ of a check it did not make, leaving the dataset-aware pass nothing to do but reject it when+ scanning the original directory would have found a matching older checkpoint. Raises ResumeError."""from core.training.diffusion_checkpoint import preflight_resumepath, _step = preflight_resume(@@ -2800,10 +2762,9 @@ async def start_diffusion_training(),)- # Same rule for the MiniMax-H3 trainer's own restrictions.- # Those config-only restrictions are a batch > 1, a non-bf16 precision, a weighting scheme, a compile request or a- # conditioning-cache directory, each of which used to reach the worker and 400 there with the user's models already- # evicted.+ # Same rule for the MiniMax-H3 trainer's own restrictions: a batch > 1, a non-bf16 precision, a+ # weighting scheme, a compile request or a conditioning-cache directory, each of which used to+ # reach the worker and 400 there with the user's models already evicted.from core.training.diffusion_train_common import h3_train_unsupported_reason_h3_reason = h3_train_unsupported_reason(normalized_cfg)@@ -2829,10 +2790,10 @@ async def start_diffusion_training(if _pipeline_reason:raise HTTPException(status_code = 400, detail = _pipeline_reason)- # Preflight a resume request in the same place and for the same reason: a checkpoint- # A checkpoint from a different family / base / LoRA shape / precision must 400 BEFORE the resident GPU model is- # evicted, not fail in the child. The dataset half of the identity needs the discovery pass, so it runs below, still- # before eviction.+ # Preflight a resume request in the same place and for the same reason: a checkpoint from a+ # different family / base / LoRA shape / precision must 400 BEFORE the resident GPU model is+ # evicted, not fail in the child. The dataset half of the identity needs the discovery pass, so it+ # runs below, still before eviction.from core.training.diffusion_checkpoint import (ResumeError,dataset_fingerprint,@@ -2846,9 +2807,8 @@ async def start_diffusion_training(resume_identity = identity_for_config(normalized_cfg) if resuming else Noneif resuming:try:- # Resolve + contain it here.- # Like data_dir / output_dir: the trainer subprocess would otherwise resolve a relative name against its own- # cwd.+ # Resolve and contain it here: the trainer subprocess would otherwise resolve a relative name+ # against its own cwd, as with data_dir / output_dir.config["resume_from_checkpoint"] = str(resolve_resume_dir(normalized_cfg.resume_from_checkpoint))@@ -2905,10 +2865,9 @@ async def start_diffusion_training(try:service.reserve()reserved = True- # Fail closed on clips BEFORE a discovery that cannot see them, but for the IMAGE-trained families only, or- # every valid MiniMax-H3 request is rejected by the refusal written to protect it.- # discover_training_pairs below already branches on the family, so this is the same question one step earlier;- # run in a worker thread because the scan stats every file and reads the caption sidecars.+ # Fail closed on clips BEFORE a discovery that cannot see them, but for the IMAGE-trained families+ # only, or every valid MiniMax-H3 request is rejected by the refusal written to protect it. In a+ # worker thread, since the scan stats every file and reads the caption sidecars.mixed_refusal = await asyncio.to_thread(_mixed_media_refusal, config["data_dir"], normalized_cfg.resolved_family)@@ -3051,9 +3010,9 @@ _DIFFUSION_DATASET_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}# shared definition so the trainer's discovery and this endpoint cannot drift apart._DIFFUSION_DATASET_CLIP_EXTS = set(_CLIP_EXTS)# The trainable unit of a dataset, whichever kind: only rules genuinely about pixels stay on-# _DIFFUSION_DATASET_IMAGE_EXTS. The two halves are disjoint with identical caption rules.-# The identical caption rules are a <stem>.txt / <stem>.caption sidecar, then a metadata.jsonl / captions.jsonl row,-# then the trigger prompt; test_diffusion_dataset_clips.py asserts both properties.+# _DIFFUSION_DATASET_IMAGE_EXTS. The two halves are disjoint with identical caption rules (a+# <stem>.txt / <stem>.caption sidecar, then a metadata.jsonl / captions.jsonl row, then the trigger+# prompt); test_diffusion_dataset_clips.py asserts both properties._DIFFUSION_DATASET_MEDIA_EXTS = _DIFFUSION_DATASET_IMAGE_EXTS | _DIFFUSION_DATASET_CLIP_EXTS_DIFFUSION_DATASET_TEXT_EXTS = {".txt", ".caption", ".jsonl"}@@ -3061,13 +3020,11 @@ _DIFFUSION_DATASET_TEXT_EXTS = {".txt", ".caption", ".jsonl"}def _resolve_dataset_caption(folder: Path, image_path: Path, meta_captions: dict[str, str]) -> Optional[str]:- """Resolve an item's caption using the same sidecar > metadata precedence the trainer- applies in ``discover_image_caption_pairs``. A per-item .txt/.caption sidecar wins and- is stripped, so an empty (tombstone) sidecar shadows metadata and yields "" -- the- trainer then skips that item (``if caption:``), so it must not count as captioned.-- Clips resolve through this same function unchanged: the clip discovery the video trainers- use applies the identical precedence, only over a different extension set."""+ """Resolve an item's caption using the same sidecar > metadata precedence the trainer applies in+ ``discover_image_caption_pairs``. A per-item .txt/.caption sidecar wins and is stripped, so an+ empty (tombstone) sidecar shadows metadata and yields "", which the trainer skips (``if+ caption:``) and so must not count as captioned. Clips resolve through this same function: the+ clip discovery applies the identical precedence over a different extension set."""caption: Optional[str] = Nonesidecar_present = Falsefor ext in (".txt", ".caption"):@@ -3097,11 +3054,10 @@ _DATASET_IMPORT_LOCKS_GUARD = threading.Lock()def _dataset_import_lock(folder: Path) -> "threading.Lock":- """One lock per dataset folder, so two imports cannot fill the same empty name at once.-- Keyed by the resolved path (the same folder can be reached by different names), and kept for- the process lifetime: there are a handful of dataset folders and a Lock is tiny, while- dropping one while another thread holds it would defeat the point."""+ """One lock per dataset folder, so two imports cannot fill the same empty name at once. Keyed by+ the resolved path (one folder can be reached by different names) and kept for the process+ lifetime: there are a handful of folders and a Lock is tiny, while dropping one while another+ thread holds it would defeat the point."""key = str(folder.resolve(strict = False))with _DATASET_IMPORT_LOCKS_GUARD:lock = _DATASET_IMPORT_LOCKS.get(key)@@ -3128,10 +3084,9 @@ def _import_response(def _diffusion_dataset_summary(folder: Path) -> DiffusionDatasetSummary:- # Count an item as captioned only when it resolves to a NON-EMPTY caption via the trainer's sidecar-over-metadata- # precedence: an empty tombstone makes the trainer skip the item. Images and clips are counted separately (the UI- # names them differently and only one family kind can read each), but captions are one folder total: the resolution- # rule is the same.+ # Count an item as captioned only when it resolves to a NON-EMPTY caption via the trainer's+ # sidecar-over-metadata precedence: an empty tombstone makes the trainer skip the item. Images and+ # clips are counted separately, but captions are one folder total, the resolution rule being the same.meta_captions = _load_metadata_captions(folder)images = clips = captions = 0for f in drop_appledouble_metadata(list(folder.iterdir())):@@ -3156,13 +3111,10 @@ def _diffusion_dataset_summary(folder: Path) -> DiffusionDatasetSummary:def _mixed_media_refusal(data_dir: str, resolved_family: str) -> Optional[str]:- """Why ``resolved_family`` cannot train on this folder as it stands, or None.-- Both discoveries read one medium and ignore the other, so a mixed folder trains on a- subset the picker counted as trainable and says nothing. The rule is the same in both- directions, only the medium that is out of place changes: refuse the folder rather than- quietly train part of it.- """+ """Why ``resolved_family`` cannot train on this folder as it stands, or None. Both discoveries read+ one medium and ignore the other, so a mixed folder trains on a subset the picker counted as+ trainable and says nothing. The rule is the same in both directions, only the medium that is out+ of place changes: refuse the folder rather than quietly train part of it."""from core.training.diffusion_train_common import CLIP_TRAINED_FAMILIESif str(resolved_family or "").strip().lower() in CLIP_TRAINED_FAMILIES:@@ -3172,10 +3124,8 @@ def _mixed_media_refusal(data_dir: str, resolved_family: str) -> Optional[str]:def _image_dataset_refusal(data_dir: str) -> Optional[str]:"""The converse of ``_clip_dataset_refusal``, for a family that trains from clips.-- ``discover_clip_caption_pairs`` enumerates video extensions only, so a still sitting in a- clip folder is dropped from the run while /diffusion/info and the picker both count it as- a training item. Same failure as the mixed case below, same answer."""+ ``discover_clip_caption_pairs`` enumerates video extensions only, so a still in a clip folder is+ dropped from the run while /diffusion/info and the picker both count it as a training item."""try:summary = _diffusion_dataset_summary(Path(data_dir).expanduser())except OSError:@@ -3191,17 +3141,13 @@ def _image_dataset_refusal(data_dir: str) -> Optional[str]:def _clip_dataset_refusal(data_dir: str) -> Optional[str]:- """Why a folder holding clips cannot be trained on yet, or None when it can.-- No trainer reads clips, and ``discover_image_caption_pairs`` scans stills only, so- without this a clip folder fails two different ways and neither says so. Clip-only, it- raises "No captioned images found. Provide ... per-image .txt captions", which is wrong- twice over on a folder where every clip has one. MIXED, it succeeds on the images and- the run trains on that subset in silence, while the picker counted the clips as- trainable items. So the rule is the folder, not the outcome: any clip present, refuse.-- The dataset layer still lists these folders, because uploading and captioning a clip set- is what lets one exist before the trainer does. Once discovery reads clips this check+ """Why a folder holding clips cannot be trained on yet, or None when it can. No trainer reads clips+ and ``discover_image_caption_pairs`` scans stills only, so without this a clip folder fails two+ ways and neither says so: clip-only it raises "No captioned images found", wrong twice over on a+ folder where every clip has one, and MIXED it trains on the image subset in silence while the+ picker counted the clips as trainable. So the rule is the folder, not the outcome: any clip+ present, refuse. The dataset layer still lists these folders, because uploading and captioning a+ clip set is what lets one exist before the trainer does. Once discovery reads clips this checkgoes with it."""try:summary = _diffusion_dataset_summary(Path(data_dir).expanduser())@@ -3218,13 +3164,10 @@ def _clip_dataset_refusal(data_dir: str) -> Optional[str]:def _listed_dataset_clip_count(summary: DiffusionDatasetSummary) -> int:- """How many trainable CLIPS a listed dataset folder holds, as the dataset layer reports it.-- Read off the summary with a 0 default rather than recounted here. Counting clips is the- dataset layer's job, and while that layer is still image-only the summary carries no clip- count at all, so every folder answers 0 -- which is precisely the state- ``_ui_trainable_families`` below has to detect. When the layer starts reporting clips this- starts returning them, with no edit here."""+ """How many trainable CLIPS a listed dataset folder holds, as the dataset layer reports it. Read+ off the summary with a 0 default rather than recounted here: counting clips is the dataset+ layer's job, and while that layer is image-only the summary carries no clip count at all, so+ every folder answers 0, which is precisely the state ``_ui_trainable_families`` has to detect."""try:return int(getattr(summary, "clip_count", 0) or 0)except (TypeError, ValueError):@@ -3232,12 +3175,10 @@ def _listed_dataset_clip_count(summary: DiffusionDatasetSummary) -> int:def _listed_dataset_trains_clips(summary: DiffusionDatasetSummary) -> bool:- """Whether a listed folder could actually start a clip run, not merely whether it holds clips.-- The same two conditions ``_image_dataset_refusal`` applies at Start, read off the summary the- listing already built: clips present, and no stills mixed in with them. Kept beside the count- helper above so the advertisement and the refusal cannot drift into disagreeing about which- folders a clip family can use."""+ """Whether a listed folder could actually start a clip run, not merely whether it holds clips. The+ same two conditions ``_image_dataset_refusal`` applies at Start, read off the summary the+ listing already built: clips present, and no stills mixed in. Kept beside the count helper so+ the advertisement and the refusal cannot drift apart."""if _listed_dataset_clip_count(summary) <= 0:return Falsetry:@@ -3247,28 +3188,16 @@ def _listed_dataset_trains_clips(summary: DiffusionDatasetSummary) -> bool:def _ui_trainable_families(datasets: list[DiffusionDatasetSummary]) -> list[dict]:- """The trainable families to ADVERTISE in the Train picker, given the datasets this same- response lists as selectable.-- ``family_train_infos()`` describes every family that has a trainer, which is the right- answer for the API: ``/diffusion/start`` accepts any of them and must keep doing so. It is- the wrong answer for the picker, because the picker offers a family and a dataset together.- The families in ``CLIP_TRAINED_FAMILIES`` train from captioned video clips and from nothing- else, so while every selectable dataset is stills, choosing one of them can only end in- Start failing with "No captioned video clips found" -- an option that cannot be completed- from the UI it is offered in.-- Gated on the LISTED datasets rather than on a family name or a feature flag, so this needs- no follow-up edit: the moment the dataset layer lists a folder of clips, the family that- trains on clips is advertised alongside it, and if the clip listing were ever withdrawn the- advertisement withdraws with it. Nothing here decides whether clips are listable; it only- reads what the listing already said.-- "Has clips" is not enough on its own. ``_image_dataset_refusal`` turns a MIXED folder away- from a clip family, so counting clips alone advertises the family on the strength of a- folder Start will then refuse -- an option that still cannot be completed, just one that- fails later and with a different message. The qualifying folder is one that would survive- that refusal: clips and no stills."""+ """The trainable families to ADVERTISE in the Train picker, given the datasets this same response+ lists as selectable. ``family_train_infos()`` describes every family that has a trainer, right+ for the API but wrong for the picker, which offers a family and a dataset together:+ ``CLIP_TRAINED_FAMILIES`` train from captioned clips and nothing else, so while every selectable+ dataset is stills, choosing one can only end in Start failing with "No captioned video clips+ found". Gated on the LISTED datasets rather than a family name or feature flag, so it needs no+ follow-up edit: the moment the dataset layer lists a folder of clips the family is advertised+ alongside it, and the advertisement is withdrawn with the listing. "Has clips" is not enough,+ since ``_image_dataset_refusal`` turns a MIXED folder away: the qualifying folder is one that+ would survive that refusal, clips and no stills."""from core.training.diffusion_train_common import CLIP_TRAINED_FAMILIES, family_train_infosinfos = family_train_infos()@@ -3342,13 +3271,11 @@ _DATASETS_CASE_INSENSITIVE: Optional[bool] = Nonedef _dataset_folder_is_case_insensitive(folder: Path) -> bool:- """True when ``folder`` cannot hold two names differing only by case.-- Probed once per process against the real filesystem rather than keyed off ``sys.platform``:- NTFS and the default APFS fold case, but macOS also ships case-SENSITIVE APFS volumes and a- Linux host can keep its Unsloth home on an exFAT/NTFS mount. A failed probe answers False,- which keeps the case-sensitive behaviour (two names, two files) unchanged.- """+ """True when ``folder`` cannot hold two names differing only by case. Probed once per process+ against the real filesystem rather than keyed off ``sys.platform``: NTFS and the default APFS+ fold case, but macOS also ships case-SENSITIVE APFS volumes and a Linux host can keep its+ Unsloth home on an exFAT/NTFS mount. A failed probe answers False, keeping the case-sensitive+ behaviour."""global _DATASETS_CASE_INSENSITIVEif _DATASETS_CASE_INSENSITIVE is None:import tempfile@@ -3362,13 +3289,11 @@ def _dataset_folder_is_case_insensitive(folder: Path) -> bool:def _clean_diffusion_dataset_name(name: str) -> str:- """Validate a dataset folder name: a single path component, no traversal, printable.-- Windows path rules are applied on EVERY platform, not just Windows: a dataset created on one- machine is opened on another, and both failures are silent or confusing. A reserved device name- dies in mkdir with an unhandled OSError, and a trailing period is stripped by Win32- normalization, so an upload to the "new" dataset 'photos.' would quietly write into the- existing 'photos'."""+ """Validate a dataset folder name: a single path component, no traversal, printable. Windows path+ rules are applied on EVERY platform: a dataset created on one machine is opened on another, and+ both failures are silent or confusing. A reserved device name dies in mkdir with an unhandled+ OSError, and Win32 strips a trailing period, so an upload to the "new" dataset 'photos.' would+ quietly write into the existing 'photos'."""import reglobal _DATASET_NAME_RE@@ -3514,10 +3439,9 @@ async def upload_diffusion_dataset(f"caption. Rename one before uploading."),)- # Reject a CASE variant already in this batch only where the filesystem folds case: there the commit- # replaces the first staged part with the second while `uploaded` counts both.- # There 'Cat.png' and 'cat.png' are ONE destination. The same-name exemption above is for a SEPARATE repeat- # upload; on a case-sensitive filesystem both stay allowed.+ # Reject a CASE variant already in this batch only where the filesystem folds case: there+ # 'Cat.png' and 'cat.png' are ONE destination and the commit replaces the first staged part with the+ # second while `uploaded` counts both. The same-name exemption above is for a SEPARATE repeat upload.clash_cf = first_name_by_casefold.get(fname_cf)if clash_cf is not None and _dataset_folder_is_case_insensitive(folder):raise HTTPException(@@ -3624,9 +3548,8 @@ async def upload_diffusion_dataset(_lock.release()-# Thumbnails live in a hidden subdir so they never appear in dataset listings or the trainer's-# image discovery.-# ── Dataset labeling (per-image caption editing) + one-click example imports ──+# ── Dataset labeling (per-image caption editing) + one-click example imports ── Thumbnails live in+# a hidden subdir so they never appear in dataset listings or the trainer's image discovery._THUMBS_DIRNAME = ".thumbs"_MAX_CAPTION_CHARS = 2000@@ -3663,11 +3586,10 @@ _MAX_TRAINING_IMAGE_SIDE = 4096def _validate_uploaded_training_image(path: Path, original_name: str) -> None:- """Reject an uploaded training image whose decoded dimensions exceed the per-side limit.-- Reads only the header (never img.load()), so a small-payload / huge-dimension file is caught- before it spikes memory. Bytes PIL cannot identify are left as-is (the upload contract accepts- arbitrary bytes under an image extension), so only oversized real images change behaviour."""+ """Reject an uploaded training image whose decoded dimensions exceed the per-side limit. Reads only+ the header (never img.load()), so a small-payload / huge-dimension file is caught before it+ spikes memory. Bytes PIL cannot identify are left as-is, so only oversized real images change+ behaviour."""from PIL import Image, UnidentifiedImageErrortry:@@ -3909,8 +3831,8 @@ async def set_diffusion_dataset_caption(sidecar.write_text(caption, encoding = "utf-8")image_path.with_suffix(".caption").unlink(missing_ok = True)return _image_record(folder, image_path, _load_metadata_captions(folder))- # Blank must actually clear. Unlinking alone would resurface this image's metadata caption- # Write an EMPTY sidecar: reader and trainer treat it as an authoritative tombstone.+ # Write an EMPTY sidecar: blank must actually clear, and unlinking alone would resurface this+ # image's metadata caption. Reader and trainer treat it as an authoritative tombstone.meta = _load_metadata_captions(folder)try:rel = image_path.relative_to(folder).as_posix()@@ -3944,10 +3866,9 @@ async def delete_diffusion_dataset_image(import glob as _globimage_path.unlink(missing_ok = True)- # Sidecars are keyed on the STEM, so fold stems only where the filesystem folds them: an exact compare would- # unlink a survivor's caption, and folding elsewhere strands cat.txt.- # cat.jpg and cat.png share cat.txt, and where the filesystem folds, CAT.mp4 reads the very file cat.png calls- # cat.txt. New collisions are refused at upload; legacy ones exist.+ # Sidecars are keyed on the STEM, so fold stems only where the filesystem folds them: an exact+ # compare would unlink a survivor's caption, and folding elsewhere strands cat.txt. cat.jpg and+ # cat.png share cat.txt; new collisions are refused at upload, legacy ones exist.folds_case = _dataset_folder_is_case_insensitive(folder)def same_stem(p: Path) -> bool:@@ -4076,7 +3997,6 @@ async def list_diffusion_dataset_examples(current_subject: str = Depends(get_curdef _detect_image_column(features) -> Optional[str]:- """Return the first datasets Image-feature column name, else None."""try:from datasets import Image as HFImageexcept Exception: # noqa: BLE001@@ -4318,10 +4238,9 @@ async def import_diffusion_dataset_example(status_code = 502,detail = f"No images found in '{entry['repo']}'.",)- # Promote the fully-materialized staging dir as a UNIT: a same-filesystem rename is atomic, so a hard- # process death leaves either the old folder or the finished import. rmdir needs an empty target, so- # fold any pre-existing files (a .thumbs cache, an older metadata.jsonl) INTO staging first and keep one- # atomic promotion.+ # Promote the fully-materialized staging dir as a UNIT: a same-filesystem rename is atomic, so a+ # hard process death leaves either the old folder or the finished import. rmdir needs an empty+ # target, so fold any pre-existing files INTO staging first and keep one atomic promotion.try:for p in sorted(folder.iterdir()):# Same name in both: the imported file wins, as the previous per-file move did. Park the old onediff --git a/studio/backend/routes/training_history.py b/studio/backend/routes/training_history.pyindex acb1adbef11..3327030a909 100644--- a/studio/backend/routes/training_history.py+++ b/studio/backend/routes/training_history.py@@ -1,9 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Training history API routes — browse, view, and delete past training runs.-"""+"""Training history API routes: browse, view, and delete past training runs."""import asyncioimport json@@ -67,12 +65,10 @@ def _canonical_output_dir(output_dir: Optional[str]) -> Optional[Path]:def _preview_fields(output_dir: Optional[str], sharing_on: bool) -> dict:- """Previewability + the signed `/p` share ref for a run's output dir.-- The signature is what makes the share link a capability: these routes are- authenticated, so only the run's owner ever receives it. When public sharing- is switched off, omit the signature so the UI hides the copy-link affordance- (and the link would 404 anyway). ``sharing_on`` is resolved once per request.+ """Previewability + the signed `/p` share ref for a run's output dir. The signature is what makes the share+ link a capability: these routes are authenticated, so only the run's owner ever receives it. When public+ sharing is switched off, omit the signature so the UI hides the copy-link affordance (and the link would 404+ anyway). ``sharing_on`` is resolved once per request."""ref = preview_ref(output_dir)return {@@ -83,12 +79,9 @@ def _preview_fields(output_dir: Optional[str], sharing_on: bool) -> dict:def _resume_blocked_reason(row: dict) -> Optional[str]:- """The provenance gate's own explanation, for runs it refuses.-- Only consulted for a row that is already known unresumable, so the extra work is- bounded to those. Returns None when the checkpoint is what is missing, leaving the- client's existing wording in place for that case.- """+ """The provenance gate's own explanation, for runs it refuses. Only consulted for a row that is+ already known unresumable, so the extra work is bounded to those. Returns None when the+ checkpoint is what is missing, leaving the client's existing wording in place for that case."""from core.training.provenance import resource_provenance_resume_blockerfrom core.training.resume import has_resume_state, training_run_config@@ -154,9 +147,9 @@ def _delete_run_output_dir(run_id: str, output_dir: str) -> Union[Path, bool]:staged = resolved.with_name(f".{resolved.name}.deleting-{uuid.uuid4().hex}")try:- # A same-parent rename, not an rmtree: the run is logically gone immediately but the bytes- # survive until the database row is committed, so a failed row delete can roll the whole- # operation back. _purge_staged_output_dir does the destructive half.+ # A same-parent rename, not an rmtree: the run is logically gone immediately but the bytes survive until the+ # database row is committed, so a failed row delete can roll the whole operation back.+ # _purge_staged_output_dir does the destructive half.resolved.rename(staged)return stagedexcept OSError:@@ -205,16 +198,12 @@ _ArtifactDeleteOutcome = Literal["deleted", "active", "shared", "failed"]def _delete_run_output_dir_guarded(run_id: str, output_dir: str) -> tuple[_ArtifactDeleteOutcome, Optional[Path], Optional[Path]]:- """Move the run's artifacts aside, reversibly, instead of destroying them.-- Deleting the directory outright and only then removing the database row leaves an- unrecoverable half-state if the row delete fails: the artifacts are gone and the row- survives with ``output_dir`` still populated, which is indistinguishable from the- legitimate "history kept, files kept" outcome. A same-parent rename is atomic and- costs nothing, so the destructive step can wait until the row is actually gone.-- Returns the outcome plus (original, staged) paths when there is something to purge.- """+ """Move the run's artifacts aside, reversibly, instead of destroying them. Deleting the directory+ outright and only then removing the database row leaves an unrecoverable half-state if the row+ delete fails: the artifacts are gone and the row survives with ``output_dir`` still populated,+ which is indistinguishable from the legitimate "history kept, files kept" outcome. A same-parent+ rename is atomic and costs nothing, so the destructive step can wait until the row is actually+ gone. Returns the outcome plus (original, staged) paths when there is something to purge."""from core.training.lifecycle import training_lifecycle_guardwith training_lifecycle_guard():if _output_dirs_overlap(output_dir, _active_training_output_dir()):@@ -259,12 +248,10 @@ def _restore_staged_output_dir(original: Path, staged: Path) -> bool:def _purge_staged_output_dir(run_id: str, original: Path, staged: Path) -> bool:- """Remove the staged copy once the row is gone. Returns whether the bytes are actually gone.-- The staged name is hidden and randomized and the row is already deleted, so reporting a failed- rmtree as success would strand every byte under a name nothing can find again. Put the- directory back under its own name instead and let the caller say the artifacts were kept.- """+ """Remove the staged copy once the row is gone. Returns whether the bytes are actually gone. The+ staged name is hidden and randomized and the row is already deleted, so reporting a failed+ rmtree as success would strand every byte under a name nothing can find again. Put the directory+ back under its own name instead and let the caller say the artifacts were kept."""try:shutil.rmtree(staged)logger.info("Deleted adapter directory for run %s: %s", run_id, staged)diff --git a/studio/backend/routes/training_vram.py b/studio/backend/routes/training_vram.pyindex bd4a43524bf..9580c96a804 100644--- a/studio/backend/routes/training_vram.py+++ b/studio/backend/routes/training_vram.py@@ -1,10 +1,8 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Memory coordination between inference and training.--Uses live free VRAM to keep resident chat and STT models when they fit. STT is-evicted before chat when training needs memory.+"""Memory coordination between inference and training. Uses live free VRAM to keep resident chat and STT+models when they fit. STT is evicted before chat when training needs memory."""from typing import Any, Callable, Dict, List, Optional, Tuple@@ -13,9 +11,9 @@ from loggers import get_loggerlogger = get_logger(__name__)-# keep iff usable_gb >= required_gb * SAFETY_MARGIN + KEEP_FLOOR_GB. Conservative:-# the probe sees only the chat model's current footprint, so reserve headroom for-# estimate error + KV-cache growth (KEEP_FLOOR_GB ~= 2 GB load buffer + 2 GB chat).+# keep iff usable_gb >= required_gb * SAFETY_MARGIN + KEEP_FLOOR_GB. Conservative: the probe sees only the chat+# model's current footprint, so reserve headroom for estimate error + KV-cache growth (KEEP_FLOOR_GB ~= 2 GB load+# buffer + 2 GB chat).SAFETY_MARGIN = 1.15KEEP_FLOOR_GB = 4.0@@ -85,10 +83,9 @@ def summarize_resident_stt() -> Dict[str, Any]:model = sidecar.loaded_modeldevice = sidecar.deviceloading = sidecar.is_loading()- # whisper.cpp holds GPU memory via its subprocess.- # Both engines can be live at once (engine switch or direct /audio/stt/load), so always fold the GGUF sidecar- # in: a resident Transformers model must not mask a GGUF server still binding its backend, or admission lets- # training launch into that startup and OOM.+ # whisper.cpp holds GPU memory via its subprocess. Both engines can be live at once (engine switch or direct+ # /audio/stt/load), so always fold the GGUF sidecar in: a resident Transformers model must not mask a GGUF+ # server still binding its backend, or admission lets training launch into that startup and OOM.ggml = get_ggml_stt_sidecar()if not model:model = ggml.loaded_model@@ -131,11 +128,9 @@ def can_keep_chat_during_training(optimizer: str,gpu_ids: Optional[List[int]],) -> Tuple[bool, Dict[str, Any]]:- """Decide if a resident chat model can coexist with training given free VRAM.-- Reuses training's own estimator/selector so the decision matches later- placement. Default-deny: anything we can't size returns False (unload).- """+ """Decide if a resident chat model can coexist with training given free VRAM. Reuses training's own+ estimator/selector so the decision matches later placement. Default-deny: anything we can't size+ returns False (unload)."""try:from utils.hardware import (DeviceType,@@ -241,16 +236,13 @@ def can_load_chat_during_training(single_device_gpu: Optional[str] = None,post_handoff_free_gpu_vram_gb: Optional[Dict[int, float]] = None,) -> Tuple[bool, Dict[str, Any]]:- """Decide if a NEW chat model can load without OOMing active training (inverse- of can_keep_chat_during_training: training is already resident, so size the- chat model against the free VRAM that remains). Sizes/places it the same way- the loader will: HF auto reuses auto_select_gpu_ids; HF explicit requires an- even-share per-GPU floor for device_map="balanced"; GGUF sizes from- required_override_gb over the visible pool. ``single_device_gpu`` is the- exact physical device token selected by a single-device runner.- `load_in_4bit` must be effective (LoRA can flip 4-bit -> 16-bit). CPU/MLX- allows the load; default-deny on any CUDA/XPU case it can't size, so a load- never OOMs training."""+ """Decide if a NEW chat model can load without OOMing active training (inverse of+ can_keep_chat_during_training: training is already resident, so size the chat model against the free VRAM+ that remains). Sizes/places it the same way the loader will: HF auto reuses auto_select_gpu_ids; HF explicit+ requires an even-share per-GPU floor for device_map="balanced"; GGUF sizes from required_override_gb over+ the visible pool. ``single_device_gpu`` is the exact physical device token selected by a single-device+ runner. `load_in_4bit` must be effective (LoRA can flip 4-bit -> 16-bit). CPU/MLX allows the load;+ default-deny on any CUDA/XPU case it can't size, so a load never OOMs training."""try:from utils.hardware import (DeviceType,@@ -348,18 +340,17 @@ def can_load_chat_during_training(elif single_device_gpu is not None:token = str(single_device_gpu).strip()if not token:- # Empty token = a CPU-only single-device runner- # For example a CPU diffusion GGUF: it uses no GPU VRAM, so it never threatens active training and can- # always load.+ # Empty token = a CPU-only single-device runner, for example a CPU diffusion GGUF: it uses no GPU VRAM, so it+ # never threatens active training and can always load.return True, {"mode": "single_device", "reason": "cpu_only"}try:selected_gpu = int(token)if selected_gpu < 0:raise ValueErrorexcept (TypeError, ValueError):- # A non-numeric device token (CUDA UUID / MIG handle) has no free-VRAM index, but the runner- # still drives ONE device: size against the worst-case visible device, never the aggregate- # pool, or a single-device load is OK'd on capacity it cannot use.+ # A non-numeric device token (CUDA UUID / MIG handle) has no free-VRAM index, but the runner still drives+ # ONE device: size against the worst-case visible device, never the aggregate pool, or a single-device load+ # is OK'd on capacity it cannot use.free_vals = [min(free_by_index.values())] if free_by_index else []else:free_vals = [free_by_index.get(selected_gpu, 0.0)]@@ -383,9 +374,8 @@ def can_load_chat_during_training(needed_gb = required_gb * SAFETY_MARGIN + KEEP_FLOOR_GBaggregate_fits = usable_gb >= needed_gb- # Explicit HF placement uses balanced sharding across a known number of- # GPUs. GGUF pins are candidate pools: llama.cpp may narrow an uneven- # pool to the smallest fitting subset, so only their aggregate matters.+ # Explicit HF placement uses balanced sharding across a known number of GPUs. GGUF pins are candidate pools:+ # llama.cpp may narrow an uneven pool to the smallest fitting subset, so only their aggregate matters.min_free_gb = min(free_vals)per_gpu_fits = Trueper_gpu_needed_gb = None@@ -418,10 +408,9 @@ def free_chat_models_for_training(reason: str) -> List[str]:try:from core.inference import get_inference_backendinf = get_inference_backend()- # No CPU exemption here, unlike the GGUF branch and the STT sidecars: it would- # key off a marker the orchestrator writes rather than the worker that masked,- # and a marker that disagreed is an OOM mid-training. Freeing a model that held- # no VRAM only costs a reload.+ # No CPU exemption here, unlike the GGUF branch and the STT sidecars: it would key off a marker the+ # orchestrator writes rather than the worker that masked, and a marker that disagreed is an OOM mid-training.+ # Freeing a model that held no VRAM only costs a reload.if inf.active_model_name or inf.loading_models:name = inf.active_model_name or next(iter(inf.loading_models), None)logger.info(@@ -457,22 +446,18 @@ def free_chat_models_for_training(reason: str) -> List[str]:def _stt_sidecar_holds_no_vram(sidecar) -> bool:- """True only when the resident dictation model is provably in CPU RAM.-- Conservative on purpose: anything unreadable answers False and the sidecar is- freed as before. Skipping one that does hold VRAM would starve the run this- is making room for, which is far worse than a needless reload.+ """True only when the resident dictation model is provably in CPU RAM. Conservative on purpose: anything+ unreadable answers False and the sidecar is freed as before. Skipping one that does hold VRAM would starve+ the run this is making room for, which is far worse than a needless reload."""try:device = getattr(sidecar, "device", None)if isinstance(device, str) and device.strip().lower() == "cpu":return True- # whisper.cpp and llama.cpp report a runtime name rather than a device, so read- # the flag each sets when it started without the GPU. Prefer the fact over the- # wish: mtmd's _gpu_disabled is what the live server was started with, while- # _forced_cpu is the standing preference, recorded even on the branch that does- # NOT restart a server with a request in flight, so reading it reports a server- # still at -ngl 99 as holding no VRAM.+ # whisper.cpp and llama.cpp report a runtime name rather than a device, so read the flag each sets when it+ # started without the GPU. Prefer the fact over the wish: mtmd's _gpu_disabled is what the live server was+ # started with, while _forced_cpu is the standing preference, recorded even on the branch that does NOT restart+ # a server with a request in flight, so reading it reports a server still at -ngl 99 as holding no VRAM.gpu_disabled = getattr(sidecar, "_gpu_disabled", None)if gpu_disabled is not None:return gpu_disabled is True@@ -484,12 +469,9 @@ def _stt_sidecar_holds_no_vram(sidecar) -> bool:def free_stt_model_for_training(reason: str) -> List[str]:- """Unload the dictation model(s) before training. Never raises.-- The Transformers and GGUF sidecars are freed under independent exception- boundaries so a failure unloading one backend never skips freeing the other- (both can hold accelerator memory at once after an engine switch).- """+ """Unload the dictation model(s) before training. Never raises. The Transformers and GGUF sidecars+ are freed under independent exception boundaries so a failure unloading one backend never skips+ freeing the other (both can hold accelerator memory at once after an engine switch)."""freed: List[str] = []try:from core.inference.stt_sidecar import get_stt_sidecar@@ -523,9 +505,8 @@ def free_stt_model_for_training(reason: str) -> List[str]:ggml = get_ggml_stt_sidecar()if ggml.is_loading() and ggml.cancel_pending_load():logger.info("Cancelling GGUF STT model load for training (%s)", reason)- # whisper-server may still be binding its backend; wait for the- # cancelled startup to be killed and reaped before training claims- # the memory (loaded_model stays unset until it is ready).+ # whisper-server may still be binding its backend; wait for the cancelled startup to be killed and+ # reaped before training claims the memory (loaded_model stays unset until it is ready).ggml.wait_for_load_to_settle()if ggml.loaded_model:ggml.unload()@@ -550,9 +531,8 @@ def free_stt_model_for_training(reason: str) -> List[str]:mtmd = get_mtmd_stt_sidecar()if mtmd.is_loading() and mtmd.cancel_pending_load():logger.info("Cancelling mtmd STT model load for training (%s)", reason)- # llama-server only becomes reachable through unload() once it is- # ready, so a startup has to be cancelled and reaped instead. Wait- # for that before training claims the memory it is allocating.+ # llama-server only becomes reachable through unload() once it is ready, so a startup has to be+ # cancelled and reaped instead. Wait for that before training claims the memory it is allocating.mtmd.wait_for_load_to_settle()if mtmd.loaded_model:mtmd.unload()diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex 9539cae0565..e41463b4ea3 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -3,16 +3,13 @@"""API routes for local text-to-video inference.-The video backend is a deliberate sibling of the diffusion (image) backend, so-these routes mirror the /images/* routes one-for-one: the same validate-before-evict-load ordering, the same GPU arbiter handoff (VIDEO owner in place of DIFFUSION),-the same error boundary mapping backend exceptions to HTTP, and the same gallery-CRUD shape. The backend runs in-process and is synchronous, so the blocking-calls are offloaded with asyncio.to_thread to keep the event loop free; the slow-operations (load AND generate) run as background jobs whose begin_* calls return-at once, with progress + terminal outcome polled from their *-progress routes.-This module is the single error boundary: backend methods raise, we map to HTTP-here.+The video backend is a deliberate sibling of the diffusion (image) backend, so these routes mirror the+/images/* routes one-for-one: the same validate-before-evict load ordering, the same GPU arbiter handoff (VIDEO+owner in place of DIFFUSION), the same error boundary mapping backend exceptions to HTTP, and the same gallery+CRUD shape. The backend runs in-process and is synchronous, so the blocking calls are offloaded with+asyncio.to_thread to keep the event loop free; the slow operations (load AND generate) run as background jobs+whose begin_* calls return at once, with progress + terminal outcome polled from their *-progress routes. This+module is the single error boundary: backend methods raise, we map to HTTP here."""from __future__ import annotations@@ -98,11 +95,10 @@ def _derived_h3_task(gguf_filename: Optional[str], kind: str) -> Optional[str]:def _guard_video_load_against_training() -> None:- """Refuse loading a video model while a training run is active. Unlike chat,- a video pipeline's VRAM can't be cheaply estimated before the load, so the- load is refused outright rather than fit-checked. No-op when training is- inactive or its state can't be read. Raises HTTP 409. Mirrors the image- load's _guard_diffusion_load_against_training."""+ """Refuse loading a video model while a training run is active. Unlike chat, a video pipeline's VRAM can't be+ cheaply estimated before the load, so the load is refused outright rather than fit-checked. No-op when+ training is inactive or its state can't be read. Raises HTTP 409. Mirrors the image load's+ _guard_diffusion_load_against_training."""from core.training import get_training_backendtry:@@ -160,17 +156,16 @@ async def video_download_plan(model_kind = kind,base_repo = request.base_repo,transformer_quant = request.transformer_quant,- # And the partition, because one of those quant-keyed refusals is task-keyed- # Without it here the plan below staged the 66 GB dense transformer_ref/ AND the incompatible fl2va quant- # first: the hosted pre-quantized H3 checkpoints are fl2va denoisers, so a quantized ref2va is rejected.+ # And the partition, because one of those quant-keyed refusals is task-keyed. Without it here the plan below+ # staged the 66 GB dense transformer_ref/ AND the incompatible fl2va quant first: the hosted pre-quantized+ # H3 checkpoints are fl2va denoisers, so a quantized ref2va is rejected.h3_task = request.h3_task,)- # BEFORE the plan is staged, as on the images side: /video/load refuses a precision this host cannot honour, but- # the UI plans and downloads first, so an explicit FP8 on an unsupported host paid for tens of GB of weights to- # be told afterwards. Network-free. Skipped while a trainer holds the GPU: an uncached scheme takes this into a- # quantise-and-matmul smoke probe that initialises CUDA. RANKING opens a CUDA context per candidate, so it waits- # until training is known idle, while validating and translating the ids happens either way. ONE resolution,- # reused by preflight and plan.+ # BEFORE the plan is staged, as on the images side: /video/load refuses a precision this host cannot honour,+ # but the UI plans and downloads first, so an explicit FP8 on an unsupported host paid for tens of GB of+ # weights to be told afterwards. Network-free. Skipped while a trainer holds the GPU: an uncached scheme takes+ # this into a quantise-and-matmul smoke probe that initialises CUDA. RANKING opens a CUDA context per+ # candidate, so it waits until training is known idle. ONE resolution, reused by preflight and plan.gpu_ordinal = Nonetraining = fam is not None and await asyncio.to_thread(_training_is_active)if fam is not None:@@ -198,13 +193,11 @@ async def video_download_plan(# The plan must see the encoder policy the load will use: an fp8 request takes a hosted pre-cast encoder, so# staging the dense one wastes ~49 GB on LTX-2.text_encoder_quant = request.text_encoder_quant,- # And the denoiser policy.- # A scheme with a hosted pre-quantized checkpoint replaces the dense DiT, so without this the plan stages- # 66.3 GB of shards the load never opens.+ # And the denoiser policy: a scheme with a hosted pre-quantized checkpoint replaces the dense DiT, so without+ # this the plan stages 66.3 GB of shards the load never opens.transformer_quant = request.transformer_quant,- # And the MiniMax-H3 partition.- # The two denoisers live in separate 66.28 GB subfolders: a ref2va load opens transformer_ref/, which the- # plan would otherwise miss entirely while staging the fl2va transformer/ it never opens.+ # And the MiniMax-H3 partition: the two denoisers live in separate 66.28 GB subfolders, so a ref2va load opens+ # transformer_ref/, which the plan would otherwise miss while staging the fl2va transformer/.h3_task = request.h3_task,)return DiffusionDownloadPlanResponse(**plan)@@ -229,10 +222,8 @@ async def load_video_model_gated(*,user_initiated: bool = False,):- """Everything ``POST /video/load`` does, plus who asked for it.-- Media auto-switch awaits this rather than the route so the idle unload can tell an- API-loaded pipeline from one the user picked on the Video page.+ """Everything ``POST /video/load`` does, plus who asked for it. Media auto-switch awaits this rather than the+ route so the idle unload can tell an API-loaded pipeline from one the user picked on the Video page."""from core.inference.diffusion import resolve_local_single_filefrom core.inference.diffusion_device import (@@ -292,10 +283,9 @@ async def load_video_model_gated(memory_mode = request.memory_mode,gpu_ordinal = gpu_ordinal,)- # Same bar again, for a speech GGUF picked out of a mixed video repo.- # The backend's own assertion runs on the load worker, INSIDE acquire_for, so a refusal there arrives having- # already evicted the chat model. Off-thread because the probe reads a header, and cache-only when the load is- # not user-initiated.+ # Same bar again, for a speech GGUF picked out of a mixed video repo. The backend's own assertion runs on the+ # load worker, INSIDE acquire_for, so a refusal there arrives having already evicted the chat model.+ # Off-thread because the probe reads a header, and cache-only when the load is not user-initiated.from core.inference.diffusion_compat import assert_pick_is_not_speechawait asyncio.to_thread(@@ -338,8 +328,8 @@ async def load_video_model_gated(if device != "cpu":# Register the in-flight load UNDER the arbiter lock: otherwise a competing acquire in that gap evicts VIDEO- # before the load is marked, finds nothing to cancel, and both allocate at once. The training admission- # wraps the same span.+ # before the load is marked, finds nothing to cancel, and both allocate at once. The training admission wraps+ # the same span.from routes.inference import _diffusion_training_admissiondef _acquire_and_begin():with _diffusion_training_admission():@@ -402,12 +392,10 @@ async def generate_video(def _refuse_unservable_request(pick) -> None:"""Judge the request against the family being switched TO, before it evicts anything.-- begin_generate judges it against the loaded family under the lock, which is what makes- the answer race-proof, but by then a request no model could have served has already cost- the resident pipeline and a multi-minute load. The same rules, applied to the target's- family and MiniMax-H3 partition, both of which the pick already determines.- """+ begin_generate judges it against the loaded family under the lock, which is what makes the+ answer race-proof, but by then a request no model could have served has already cost the+ resident pipeline and a multi-minute load. The same rules, applied to the target's family+ and MiniMax-H3 partition, both of which the pick already determines."""from core.inference.media_model_index import expected_partitionfrom core.inference.video import _detect_load_family, resolve_video_model_kindfrom core.inference.video_minimax_h3 import is_h3_native@@ -459,10 +447,10 @@ async def generate_video(raise HTTPException(status_code = 400, detail = str(exc))backend = get_video_backend()- # The real rule is the LOADED family's, applied by begin_generate under the same lock that reserves the state, so a- # concurrent load cannot leave the shape judged against one family and denoised by another.- # Unloaded still falls through to the not-loaded 409, and a family with no declared presets keeps the old SIZE- # snapping, though frame_step is declared regardless.+ # The real rule is the LOADED family's, applied by begin_generate under the same lock that reserves the state,+ # so a concurrent load cannot leave the shape judged against one family and denoised by another. Unloaded still+ # falls through to the not-loaded 409, and a family with no declared presets keeps the old SIZE snapping, though+ # frame_step is declared regardless.try:await asyncio.to_thread(backend.begin_generate,@@ -597,9 +585,9 @@ async def get_gallery_video_file()-# A clip is tens to hundreds of MB, so the gallery cannot fetch it into a blob like a PNG: that buffers the whole MP4,-# defeats seeking and pins the bytes in the webview. The /file route streams ranges but is bearer-gated, so mint a-# 12-hour HMAC link (<video> re-requests on seek).+# A clip is tens to hundreds of MB, so the gallery cannot fetch it into a blob like a PNG: that buffers the whole+# MP4, defeats seeking and pins the bytes in the webview. The /file route streams ranges but is bearer-gated, so+# mint a 12-hour HMAC link (<video> re-requests on seek)._VIDEO_LINK_TTL = 12 * 3600_VIDEO_LINK_SECRET = _secrets.token_bytes(32)@@ -717,9 +705,9 @@ async def export_gallery_video(def _forget_terminal_video(video_id: Optional[str]) -> None:- """Clear the backend's completed-job record for a clip that just left the gallery, so a page- reload does not merge it back as a card whose file is gone. Best-effort: an unavailable backend- only means the stale record survives, which is what happened before this call existed."""+ """Clear the backend's completed-job record for a clip that just left the gallery, so a page reload does not+ merge it back as a card whose file is gone. Best-effort: an unavailable backend only means the stale record+ survives, which is what happened before this call existed."""try:from core.inference.video import get_video_backendget_video_backend().forget_terminal_video(video_id)@@ -789,8 +777,6 @@ async def clear_gallery_videos(current_subject: str = Depends(get_current_subjecreturn {"removed": len(cleared)}-# ── OpenAI-compatible videos API (/v1/videos) ──-_VIDEO_SIZE_RE = _re.compile(r"^(\d{1,5})\s*x\s*(\d{1,5})$")_VIDEO_SECONDS_MAX = 120.0_VIDEO_JOB_ID_PREFIX = "video_"@@ -1120,13 +1106,10 @@ def _sync_jobs() -> None:def _await_generate_settled(video_id: str, timeout: float = _DELETE_SETTLE_TIMEOUT_S) -> bool:- """Block until the run started for ``video_id`` is no longer in flight.-- Bounded, so a wedged backend cannot hold the request open. Returns False when the- wait expired with the run still live: the caller must not report a deletion it- could not observe, or the worker commits its sidecar afterwards and the clip- reappears through retrieve/list.- """+ """Block until the run started for ``video_id`` is no longer in flight. Bounded, so a wedged+ backend cannot hold the request open. Returns False when the wait expired with the run still+ live: the caller must not report a deletion it could not observe, or the worker commits its+ sidecar afterwards and the clip reappears through retrieve/list."""from core.inference.video import get_video_backendbackend = get_video_backend()@@ -1356,9 +1339,9 @@ async def _create_openai_video(fam = _detect_load_family(pick.model_path, pick.gguf_filename, None)if fam is None:return- # Judge the duration against the family being switched TO, using its own lattice.- # Passing None here accepted any seconds and only refused it in begin_generate --- # after the resident pipeline had been evicted and the target fully loaded.+ # Judge the duration against the family being switched TO, using its own lattice. Passing None here accepted any+ # seconds and only refused it in begin_generate, after the resident pipeline had been evicted and the target+ # fully loaded.want_frames = (_frames_for_seconds(seconds,@@ -1464,9 +1447,9 @@ async def _create_openai_video(presets = defaults.get("resolution_presets") or []if size is None and presets:width, height = int(presets[0][0]), int(presets[0][1])- # Describe the job from what begin_generate reserved, falling back to the status() snapshot only- # where it said nothing: a load committing in between swaps the family, and the snapshot's fps- # would then date a frame count the new model never used.+ # Describe the job from what begin_generate reserved, falling back to the status() snapshot only where it said+ # nothing: a load committing in between swaps the family, and the snapshot's fps would then date a frame count+ # the new model never used.reserved = resolved if isinstance(resolved, dict) else {}run_frames = reserved.get("num_frames") or num_framesfps = reserved.get("fps") or defaults.get("fps")diff --git a/studio/backend/routes/whisper.py b/studio/backend/routes/whisper.pyindex 08a8f269ec7..b4a64e5c28a 100644--- a/studio/backend/routes/whisper.py+++ b/studio/backend/routes/whisper.py@@ -5,10 +5,9 @@GET /api/whisper/update-status -> is a newer prebuilt available + job state-Detection reuses utils.whisper_cpp_freshness and fails open so the UI never-blocks on a missing marker / offline GitHub. There is no whisper-only update-trigger: whisper updates piggyback on the single main update item-(POST /api/llama/update chains a whisper phase when whisper is behind).+Detection reuses utils.whisper_cpp_freshness and fails open so the UI never blocks on a missing marker /+offline GitHub. There is no whisper-only update trigger: whisper updates piggyback on the single main update+item (POST /api/llama/update chains a whisper phase when whisper is behind)."""from __future__ import annotationsdiff --git a/studio/backend/routes/youtube.py b/studio/backend/routes/youtube.pyindex 470e2b09044..43bb1db203a 100644--- a/studio/backend/routes/youtube.py+++ b/studio/backend/routes/youtube.py@@ -27,8 +27,8 @@ router = APIRouter()class TranscriptRequest(BaseModel):url: str = Field(max_length = 2048)- # Caption languages to prefer, best first. The UI forwards navigator.languages, so the- # per-tag cap has to clear a fully extended BCP 47 tag rather than reject the request.+ # Caption languages to prefer, best first. The UI forwards navigator.languages, so the per-tag cap has to+ # clear a fully extended BCP 47 tag rather than reject the request.languages: list[Annotated[str, Field(max_length = 64)]] = Field(default_factory = list,max_length = 8,diff --git a/studio/backend/run.py b/studio/backend/run.pyindex 695411430a8..c9a0e1f00a7 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -1,11 +1,6 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Run script for Unsloth UI Backend.--Self-contained; can be moved to any directory.-"""-import osimport sysimport time@@ -14,18 +9,11 @@ from typing import NoReturn, Optional, Sequence, Tupledef _normalize_standard_streams():- """Point missing std streams at the null device.-- sys.stdout/stderr/stdin are None in a process with no valid std handles (a- Windows pythonw or detached launch), so every .write() / .isatty() on them- raises AttributeError. A null-device stream answers like a real one, so- nothing downstream needs its own None check.-- MUST run before the `from loggers import ...` below: structlog binds- `from sys import stdout` at ITS import time and PrintLogger does- `self._file = file or stdout`, so a None stdout is captured permanently.- Normalizing inside run_server() is too late to undo that capture.- """+ """Point missing std streams at the null device: sys.stdout/stderr/stdin are None in a process with no+ valid std handles (a Windows pythonw or detached launch), so every .write() / .isatty() raises+ AttributeError. MUST run before the `from loggers import ...` below: structlog binds `from sys import+ stdout` at ITS import time and PrintLogger does ``self._file = file or stdout``, so a None stdout is+ captured permanently and normalizing inside run_server() is too late."""for name, mode in (("stdin", "r"), ("stdout", "w"), ("stderr", "w")):if getattr(sys, name, None) is not None:continue@@ -35,9 +23,8 @@ def _normalize_standard_streams():# Normalizing must never itself be what kills startup.continuesetattr(sys, name, stream)- # sys.__stdout__ & co are None here too, and readers of those (rich reads- # sys.__stdout__.fileno() at import) otherwise fall back to fds 0/1/2,- # which this process does not have. Point them at the real null fd.+ # sys.__stdout__ & co are None here too, and readers of those (rich reads sys.__stdout__.fileno() at+ # import) otherwise fall back to fds 0/1/2, which this process does not have.if getattr(sys, f"__{name}__", None) is None:setattr(sys, f"__{name}__", stream)@@ -46,17 +33,11 @@ _normalize_standard_streams()def _fix_torch_cuda_ld_path():- """Prepend torch's bundled CUDA libs to LD_LIBRARY_PATH.-- PyTorch wheels ship their own CUDA runtime (libcudart, libcublas, ...) in- ``site-packages/nvidia/*/lib``. On Linux the dynamic linker reads- LD_LIBRARY_PATH before the RUNPATH baked into torch's .so files, so a- pre-existing LD_LIBRARY_PATH pointing at a different system CUDA (e.g.- /usr/local/cuda-13/lib64 from conda or a Docker base image) shadows torch's- libs and triggers "undefined symbol" errors when torch is imported. Detect- torch's lib dirs (without importing torch) and prepend them. Returns True if- LD_LIBRARY_PATH was changed.- """+ """Prepend torch's bundled CUDA libs to LD_LIBRARY_PATH, returning True if it was changed. PyTorch wheels+ ship their own CUDA runtime in ``site-packages/nvidia/*/lib``; on Linux the dynamic linker reads+ LD_LIBRARY_PATH before the RUNPATH baked into torch's .so files, so a pre-existing LD_LIBRARY_PATH+ pointing at a different system CUDA (conda, a Docker base image) shadows torch's libs and triggers+ "undefined symbol" on import. Detected without importing torch."""if sys.platform != "linux":return Falseld_path = os.environ.get("LD_LIBRARY_PATH", "")@@ -100,14 +81,10 @@ _LD_FIXED_SENTINEL = "_UNSLOTH_STUDIO_LD_FIXED"def _maybe_reexec_for_cuda_ld_path():- """Re-exec once so the dynamic linker sees the corrected LD_LIBRARY_PATH.-- LD_LIBRARY_PATH is read at process start, so editing os.environ in-process- cannot fix the running interpreter; a single re-exec is required. Call only- from a true entry point (the ``if __name__ == "__main__"`` block), never at- import time, because os.execv replaces the whole process (an embedder such- as Colab that does ``from run import run_server`` must not be re-exec'd).- """+ """Re-exec once so the dynamic linker sees the corrected LD_LIBRARY_PATH: it is read at process start, so+ editing os.environ in-process cannot fix the running interpreter. Call only from a true entry point,+ never at import time, because os.execv replaces the whole process (an embedder such as Colab that does+ ``from run import run_server`` must not be re-exec'd)."""if _LD_FIXED_SENTINEL in os.environ:returnif not _fix_torch_cuda_ld_path():@@ -120,7 +97,6 @@ def _maybe_reexec_for_cuda_ld_path():# Suppress C-level dependency warnings globally (e.g. SwigPyPacked).os.environ["PYTHONWARNINGS"] = "ignore"-# Add the backend dir to sys.path early so local modules import.backend_dir = Path(__file__).parentif str(backend_dir) not in sys.path:sys.path.insert(0, str(backend_dir))@@ -135,8 +111,8 @@ except ValueError as exc:raise SystemExit(f"Error: Invalid UNSLOTH_CPU_THREADS value {configured!r}: {exc}") from None# Windows ROCm ships no distributed backend, so torchao and the CUDA-only xformers both die on import,-# taking diffusers/transformers with them. A stub only seeds a name nothing has imported yet, so both-# must precede the first import below. No-op on other runtimes.+# taking diffusers/transformers with them. A stub only seeds a name nothing has imported yet, so both must+# precede the first import below.from core._torchao_stub import (install_torchao_windows_rocm_stub,install_xformers_windows_rocm_stub,@@ -145,9 +121,8 @@ from core._torchao_stub import (install_xformers_windows_rocm_stub()install_torchao_windows_rocm_stub()-# Anaconda/conda-forge Python: seed platform._sys_version_cache before imports-# that trigger attrs -> rich -> structlog -> platform crash.-# See: https://github.com/python/cpython/issues/102396+# Anaconda/conda-forge Python: seed platform._sys_version_cache before imports that trigger attrs ->+# rich -> structlog -> platform crash (https://github.com/python/cpython/issues/102396).import _platform_compat # noqa: F401from loggers import get_logger, install_uvicorn_duplicate_exception_filter@@ -167,22 +142,16 @@ DISABLE_PUBLIC_CHECK_ENV = "UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK"def public_check_disabled() -> bool:- """True when the operator has turned off the third-party startup lookups.-- On a wildcard bind Unsloth asks ifconfig.me for the public IP and check-host.net- whether the port is reachable. Both are useful for sharing an Unsloth but both tell- an outside service this machine is running one, which lab and privacy-sensitive- deployments do not want (#7307 Problem 8). Set the var to opt out.- """+ """True when the operator has turned off the third-party startup lookups. On a wildcard bind Unsloth+ asks ifconfig.me for the public IP and check-host.net whether the port is reachable; both tell an+ outside service this machine is running one, which lab and privacy-sensitive deployments do not+ want (#7307 Problem 8)."""return os.environ.get(DISABLE_PUBLIC_CHECK_ENV, "").strip().lower() in {"1", "true", "yes"}def _resolve_lan_ip(ip_version: int = 4) -> str:- """This machine's own LAN-facing address. No third-party network call.-- Discovery is a UDP route lookup plus the active interfaces; the lookup only- fixes the local end of the socket and sends no packet.- """+ """This machine's own LAN-facing address, with no third-party network call: a UDP route lookup plus+ the active interfaces, and the lookup only fixes the local end of the socket."""from lan_access import detect_lan_addressestry:@@ -195,21 +164,13 @@ def _resolve_lan_ip(ip_version: int = 4) -> str:def _resolve_external_ip() -> str:- """Resolve the machine's external IP address.-- Tries, in order:- 1. GCE metadata server (instant on Google Cloud VMs)- 2. ifconfig.me (anywhere with internet, skipped by UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK)- 3. The default route's own source address (fallback)-- This is the machine's INTERNET-facing address, used for the reachability- probe and the Cloudflare messaging -- not for "another device on your- network," which _network_share_host_for_bind answers instead. Step 3 stays- a raw route lookup rather than _resolve_lan_ip: that one filters out every- address a LAN peer cannot open (WSL's NAT side, link-local), which is the- right policy for an address we advertise and the wrong one for a last-resort- answer to "where am I".- """+ """Resolve the machine's external IP address: GCE metadata server, then ifconfig.me (skipped by+ UNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK), then the default route's own source address. This is the+ INTERNET-facing address, used for the reachability probe and the Cloudflare messaging, not for+ "another device on your network", which _network_share_host_for_bind answers. The fallback stays+ a raw route lookup rather than _resolve_lan_ip, which filters out every address a LAN peer+ cannot open (WSL's NAT side, link-local): right for an address we advertise, wrong for a last+ resort."""import socketimport urllib.request@@ -249,15 +210,10 @@ def _resolve_external_ip() -> str:def _install_uvicorn_startup_log_rewrite(bind_host: str) -> None:- """Rewrite Uvicorn's startup log line: swap a wildcard bind for the address- this machine answers on, use our Mac-aware stop hint, and rename the prefix- to "Unsloth Studio running on".-- The line is a claim about where the server is reachable, so the address is- _network_share_host_for_bind's, resolved here rather than passed in so no- caller can hand it the internet-facing one (#8868). With no LAN address to- name, the guard below leaves uvicorn's raw wildcard.- """+ """Rewrite Uvicorn's startup log line: swap a wildcard bind for the address this machine answers on, use+ our Mac-aware stop hint, and rename the prefix to "Unsloth Studio running on". The line is a claim+ about where the server is reachable, so the address is _network_share_host_for_bind's, resolved here+ rather than passed in so no caller can hand it the internet-facing one (#8868)."""import loggingimport re@@ -307,7 +263,6 @@ def _local_port_open(port: int,timeout: float = 1.0,) -> bool:- """True iff a TCP connection to (host, port) succeeds within timeout."""import sockettry:with socket.create_connection((host, port), timeout = timeout):@@ -327,12 +282,9 @@ def _working_local_url(port: int) -> "str | None":def _localhost_ipv6_mismatch_url(bind_host: str, port: int) -> "str | None":- """Return the IPv4 loopback URL when localhost won't reach 127.0.0.1.-- Local Unsloth binds to 127.0.0.1. Where localhost resolves to IPv6 only (::1),- http://localhost:<port> fails (or hits a different process on ::1) even though- http://127.0.0.1:<port> works. Return the IPv4 URL for the caller to surface.- """+ """The IPv4 loopback URL when localhost will not reach 127.0.0.1. Local Unsloth binds to 127.0.0.1,+ and where localhost resolves to IPv6 only (::1), http://localhost:<port> fails or hits a different+ process even though the IPv4 URL works."""import socketif bind_host != "127.0.0.1" or not port or port <= 0:@@ -362,17 +314,15 @@ def _localhost_ipv6_mismatch_url(bind_host: str, port: int) -> "str | None":if host == "::1":has_ipv6_loopback = True- # A connection to ::1 is NOT evidence Unsloth is reachable there: Unsloth binds- # 127.0.0.1 only, so anything on ::1 is a different process. Dual-stack- # localhost is fine (browsers fall back to 127.0.0.1), so only the IPv6-only- # case strands the user.+ # A connection to ::1 is NOT evidence Unsloth is reachable there: Unsloth binds 127.0.0.1 only, so+ # anything on ::1 is a different process. Dual-stack localhost is fine (browsers fall back to+ # 127.0.0.1), so only the IPv6-only case strands the user.if has_ipv6_loopback and not has_ipv4_loopback:return ipv4_urlreturn Nonedef _stdout_color_ok() -> bool:- """Whether to emit ANSI color codes on stdout. Mirrors startup_banner."""if os.environ.get("NO_COLOR", "").strip():return Falseif os.environ.get("FORCE_COLOR", "").strip():@@ -384,7 +334,6 @@ def _stdout_color_ok() -> bool:def _print_localhost_ipv6_mismatch_warning(local_url: str, port: int) -> None:- """Warn that localhost points at ::1 while Unsloth is bound to 127.0.0.1."""use_color = _stdout_color_ok()warn_c = "\033[38;5;215;1m" if use_color else ""reset = "\033[0m" if use_color else ""@@ -398,10 +347,9 @@ def _print_localhost_ipv6_mismatch_warning(local_url: str, port: int) -> None:def _verify_global_reachability(display_host: str, port: int) -> None:- """Probe check-host.net to confirm display_host:port is reachable from the- public internet. Synchronous so output lands between the banner URLs and the- stop hint. Bounded at ~15s; failures swallowed (verifier failing != Unsloth- failing). Only meaningful for a wildcard bind, and skipped entirely by+ """Probe check-host.net to confirm display_host:port is reachable from the public internet. Synchronous so+ output lands between the banner URLs and the stop hint. Bounded at ~15s; failures swallowed (verifier+ failing is not Unsloth failing). Only meaningful for a wildcard bind, and skipped entirely byUNSLOTH_STUDIO_DISABLE_PUBLIC_CHECK."""global _public_reachable# Reset to "unknown" each run; set True/False only when the probe decides.@@ -421,7 +369,7 @@ def _verify_global_reachability(display_host: str, port: int) -> None:ok_c = "\033[38;5;120;1m" if use_color else ""err_c = "\033[38;5;203;1m" if use_color else ""warn_c = "\033[38;5;215;1m" if use_color else ""- local_url_c = "\033[38;5;108;1m" if use_color else "" # matches banner's URL color+ local_url_c = "\033[38;5;108;1m" if use_color else ""reset = "\033[0m" if use_color else ""url = f"http://{_url_host(display_host)}:{port}"@@ -439,7 +387,6 @@ def _verify_global_reachability(display_host: str, port: int) -> None:)returnexcept ValueError:- # Not an IP literal; probe by hostname.pass# The probe hands display_host:port to a third party and asks it to connect.@@ -480,7 +427,6 @@ def _verify_global_reachability(display_host: str, port: int) -> None:continueif results and all(v is not None for v in results.values()):break- # Two decisive nodes is enough; stop early.decisive = [vfor v in results.values()@@ -536,7 +482,6 @@ def _verify_global_reachability(display_host: str, port: int) -> None:f"{dim} then open http://localhost:{port}/ in your browser.{reset}",flush = True,)- # Only offer the local URL if loopback answers.local_url = _working_local_url(port)if local_url:print(@@ -551,7 +496,6 @@ def _verify_global_reachability(display_host: str, port: int) -> None:flush = True,)except urllib.error.URLError:- # Outbound HTTPS blocked; skip.passexcept Exception:pass@@ -575,15 +519,11 @@ def _display_host_for_bind(host: str) -> str:def _network_share_host_for_bind(host: str) -> str:- """The address to hand another device on this LAN, or to build the API- panel's direct base URL from.-- Deliberately not _display_host_for_bind: that answers "what is this- machine's internet-facing address" (right for the reachability probe and the- Cloudflare line), and for a wildcard bind that can be a public WAN IP a LAN- peer cannot route to (#8868). Only a family the wildcard actually binds is- resolved, so an IPv6-only launch is never advertised at an IPv4 address.- """+ """The address to hand another device on this LAN, or to build the API panel's direct base URL from.+ Deliberately not _display_host_for_bind: that answers "what is this machine's internet-facing address",+ and for a wildcard bind that can be a public WAN IP a LAN peer cannot route to (#8868). Only a family+ the wildcard actually binds is resolved, so an IPv6-only launch is never advertised at an IPv4+ address."""wildcard_versions = wildcard_ip_versions(host)if not wildcard_versions:return host@@ -599,14 +539,10 @@ def _loopback_bind_host_for(host: str) -> str:def _direct_server_url(host: str, port: int) -> "Optional[str]":- """The API panel's direct (non-tunnel) base, or None when this launch has no- address worth publishing.-- The frontend prefers any non-null server_url over the origin the client- reached, so publishing ``http://0.0.0.0:<port>`` (a wildcard bind with no LAN- address: WSL behind NAT, loopback-only) would put an unroutable address in- the API examples, the desktop agent command and a copied preview link.- """+ """The API panel's direct (non-tunnel) base, or None when this launch has no address worth publishing. The+ frontend prefers any non-null server_url over the origin the client reached, so publishing+ ``http://0.0.0.0:<port>`` (a wildcard bind with no LAN address: WSL behind NAT, loopback-only) would+ put an unroutable address in the API examples, the desktop agent command and a copied preview link."""if not port or port <= 0:return Noneshare_host = _network_share_host_for_bind(host)@@ -621,8 +557,6 @@ def _tool_policy_notice(host: str, secure: bool, enable_tools: "Optional[bool]")if enable_tools is False:return "Server-side tools are DISABLED (--disable-tools)."if enable_tools is None:- # This launcher installs no tools-on default (that is `unsloth studio- # run`), so the request decides and the Unsloth UI sends its pills.return ("Server-side tools follow each request's enable_tools; the Unsloth UI's ""tool toggles decide. Pass --enable-tools to force them on for every "@@ -670,12 +604,10 @@ def _emit_startup_output(enable_tools: "Optional[bool]" = None,lan_addresses: "tuple[str, ...]" = (),) -> None:- """Print the access banner, post-startup warnings, the tool-policy notice,- then a single stop hint. Extracted from ``_run`` so the wiring is testable.-- ``lan_addresses`` are the addresses a persisted Settings > LAN access- auto-start has already bound. A loopback launch carrying them is network- reachable, so both the banner and the tool-policy notice must say so."""+ """Print the access banner, post-startup warnings, the tool-policy notice, then a single stop hint.+ ``lan_addresses`` are the addresses a persisted Settings > LAN access auto-start has already bound. A+ loopback launch carrying them is network reachable, so both the banner and the tool-policy notice must+ say so."""if secure:_emit_secure_startup_output(port, enable_tools)return@@ -701,7 +633,6 @@ def _emit_startup_output(def _print_cloudflare_line(secure: bool = False, loopback_host: str = "127.0.0.1") -> None:- """Print Cloudflare tunnel state for startup banners."""from startup_banner import stdout_supports_coloraccent = "\033[38;5;150;1m"@@ -804,11 +735,8 @@ def _print_cloudflare_line(secure: bool = False, loopback_host: str = "127.0.0.1def _get_pid_on_port(port: int) -> "tuple[int, str] | None":- """Return (pid, process_name) listening on *port*, or None.-- Uses psutil when available, else None so callers can still report the conflict- without process details.- """+ """(pid, process_name) listening on *port*, or None. Uses psutil when available, else None so+ callers can still report the conflict without process details."""try:import psutilexcept ImportError:@@ -842,11 +770,9 @@ def _bind_addresses(host: str, port: int) -> "set[str]":def _addresses_collide(recorded: "str | None", host: str, port: int) -> bool:- """Would a server bound to *recorded* block a bind to *host*?-- *recorded* may list several addresses. Unknown or wildcard on either side- collides: refusing with a clear message beats silently starting a duplicate.- """+ """Would a server bound to *recorded* block a bind to *host*? *recorded* may list several addresses;+ unknown or wildcard on either side collides, since refusing with a clear message beats silently+ starting a duplicate."""if not recorded or is_wildcard_host(host):return Truelisted = {a.strip() for a in recorded.split(",") if a.strip()}@@ -856,16 +782,11 @@ def _addresses_collide(recorded: "str | None", host: str, port: int) -> bool:def _is_port_free(host: str, port: int) -> bool:- """Check if a port is available for binding.-- For a ``0.0.0.0`` wildcard host, also check whether anything is listening on- ``127.0.0.1`` (and ``::1`` when IPv6 exists): an SSH tunnel may hold loopback- while the wildcard bind succeeds, making Unsloth unreachable via ``localhost``.- """+ """Check if a port is available for binding. For a ``0.0.0.0`` wildcard host, also check whether anything+ is listening on ``127.0.0.1`` (and ``::1`` when IPv6 exists): an SSH tunnel may hold loopback while the+ wildcard bind succeeds, making Unsloth unreachable via ``localhost``."""import socket- # 1. Can we bind to the requested address? getaddrinfo resolves both- # IPv4 and IPv6 to the right address family.sockets = []try:addr_info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)@@ -896,8 +817,8 @@ def _is_port_free(host: str, port: int) -> bool:for probe in sockets:probe.close()- # 2. On a wildcard bind, verify localhost isn't already claimed by another- # process (e.g. an SSH -L tunnel); a successful connect means it is.+ # On a wildcard bind, verify localhost is not already claimed by another process (e.g. an SSH -L+ # tunnel); a successful connect means it is.if is_wildcard_host(host):for loopback, family in [("127.0.0.1", socket.AF_INET),@@ -907,10 +828,8 @@ def _is_port_free(host: str, port: int) -> bool:with socket.socket(family, socket.SOCK_STREAM) as s:s.settimeout(1)if s.connect_ex((loopback, port)) == 0:- # Port is taken on loopback.return Falseexcept OSError:- # IPv6 disabled or other OS-level restriction -- skip.continuereturn True@@ -922,11 +841,8 @@ def _find_free_port(max_attempts: int = 20,avoid_own_studio: bool = False,) -> int:- """Find a free port from `start`, trying up to max_attempts ports.-- ``avoid_own_studio`` aborts rather than skipping past one of our own servers- in the fallback range, which would start a duplicate on a later port.- """+ """Find a free port from `start`, trying up to max_attempts ports. ``avoid_own_studio`` aborts rather+ than skipping past one of our own servers in the fallback range, which would start a duplicate."""for offset in range(max_attempts):candidate = start + offsetif _is_port_free(host, candidate):@@ -943,9 +859,8 @@ from utils.paths.storage_roots import studio_root as _studio_root# Legacy single-instance file; still read so `stop` finds an older build's server._PID_FILE = _studio_root() / "studio.pid"PID_FILE_GLOB = "studio-*.pid"-# Deliberately not a .pid: everything that globs PID_FILE_GLOB expects a bound-# server with a port in the name, and a process that has not bound yet is not-# one. Only the sibling probe reads these.+# Deliberately not a .pid: everything that globs PID_FILE_GLOB expects a bound server with a port in+# the name, and a process that has not bound yet is not one.STARTUP_MARKER_GLOB = "studio-starting-*.marker"_OWN_STARTUP_MARKERS: "list[Path]" = []_STARTUP_MARKER_HOOK_REGISTERED = False@@ -977,10 +892,9 @@ def _pid_alive(pid: int) -> bool:timeout = 10,).stdoutexcept Exception:- # Unconfirmed means keep, matching the CLI's _pid_alive. Pruning a- # live server's record is what lets the next launch fall back past it- # and strand it, which is the bug this file exists to fix. A stale- # record instead costs one clear "already running" message.+ # Unconfirmed means keep, matching the CLI's _pid_alive. Pruning a live server's record is what lets the+ # next launch fall back past it and strand it; a stale record instead costs one clear "already running"+ # message.return Truereturn f'"{int(pid)}"' in outtry:@@ -1001,7 +915,6 @@ def _process_create_time(pid: int) -> "float | None":def _read_pid_record(path: Path) -> "tuple[int, float | None, str | None] | None":- """Parse ``pid`` / optional ``create_time`` / optional bind address."""try:lines = path.read_text(encoding = "utf-8").splitlines()except (OSError, UnicodeDecodeError):@@ -1027,13 +940,10 @@ def _read_pid_record(path: Path) -> "tuple[int, float | None, str | None] | Nonedef _pid_is_studio_backend(pid: int, created_times: "Sequence[float | None]" = ()) -> bool:- """False only when a recorded start time proves this PID is a different process.-- Any recorded time matching is enough -- a stale record must not veto a live- server that reused the PID. Untimed records cannot be checked at all, so they- are trusted: a legacy `python run.py` has no telltale argv, and guessing from- the command line rejected real servers.- """+ """False only when a recorded start time proves this PID is a different process. Any recorded time matching+ is enough: a stale record must not veto a live server that reused the PID. Untimed records cannot be+ checked at all, so they are trusted, since a legacy `python run.py` has no telltale argv and guessing+ from the command line rejected real servers."""known = [c for c in created_times if c is not None]if not known:return True@@ -1044,11 +954,9 @@ def _pid_is_studio_backend(pid: int, created_times: "Sequence[float | None]" = (def _own_studio_on_port(port: int, host: str) -> "int | None":- """PID of one of our own servers already bound to *port* for *host*.-- Reads our own records rather than enumerating listeners: psutil is optional,- and without it a listener scan finds nothing and we silently start a duplicate.- """+ """PID of one of our own servers already bound to *port* for *host*. Reads our own records rather than+ enumerating listeners: psutil is optional, and without it a listener scan finds nothing and we silently+ start a duplicate."""try:paths = list(_studio_root().glob(f"studio-{port}-*.pid"))except OSError:@@ -1073,20 +981,17 @@ def _own_studio_on_port(port: int, host: str) -> "int | None":def _legacy_studio_on_port(port: int) -> "int | None":- """A pre-upgrade server recorded only its PID, so match it to the listener.-- Falling back past one leaves it running while `_write_pid_file` overwrites the- only record of it. When the listener is unknowable, assume it is ours.- """+ """A pre-upgrade server recorded only its PID, so match it to the listener. Falling back past one leaves it+ running while `_write_pid_file` overwrites the only record of it. When the listener is unknowable,+ assume it is ours."""record = _read_pid_record(_PID_FILE)if record is None:return Nonepid, created, _address = recordif not _pid_alive(pid):return None- # A current build writes a per-port file too, so its port is already known --- # and this port's records were just checked. Only count a record that still- # matches the live process: a stale one may just share a reused PID.+ # A current build writes a per-port file too, so its port is already known, and this port's records were+ # just checked. Only count a record that still matches the live process: a stale one may share a reused PID.for other in _per_port_records():if other and other[0] == pid and _pid_is_studio_backend(pid, [other[1]]):return None@@ -1099,21 +1004,11 @@ def _legacy_studio_on_port(port: int) -> "int | None":def write_startup_marker() -> None:- """Record that this process is coming up, before uvicorn starts.-- The per-port record cannot be written until uvicorn reports the bound port,- and lifespan startup runs well before that. Two overlapping launches would- otherwise each find no sibling and each clear the shared compiled cache, the- exact race this is meant to prevent, so a sibling has to be discoverable- from the moment it could do any clearing.-- Published under the same lock the clear takes, so the marker cannot appear in- the gap between a sibling's probe and its rmtree; that ordering is the whole- point of the marker.-- Best effort, like the records themselves: a studio home we cannot write to- is not a reason to refuse to start.- """+ """Record that this process is coming up, before uvicorn starts. The per-port record cannot be written+ until uvicorn reports the bound port, and lifespan startup runs well before that. Two overlapping+ launches would otherwise each find no sibling and each clear the shared compiled cache, so a sibling+ has to be discoverable from the moment it could do any clearing. Published under the same lock the+ clear takes, so the marker cannot appear in the gap between a sibling's probe and its rmtree."""me = os.getpid()created = _process_create_time(me)body = f"{me}\n{created if created is not None else ''}\n"@@ -1126,10 +1021,9 @@ def write_startup_marker() -> None:# did before the lock existed. Startup still has to happen.compiled_cache_lock = contextlib.nullcontextLOCK_BUSY = None- # A longer budget than a clear takes: publishing behind a holder that is- # mid-rmtree is the case worth waiting out. Publishing anyway if the wait- # runs out is still right, because a marker that never appears makes this- # backend invisible, which is the failure the marker exists to prevent.+ # A longer budget than a clear takes: publishing behind a holder that is mid-rmtree is the case worth+ # waiting out. Publishing anyway if the wait runs out is still right, because a marker that never appears+ # makes this backend invisible.with compiled_cache_lock(timeout = 30.0) as lock_state:published_unlocked = lock_state == LOCK_BUSYif published_unlocked:@@ -1144,10 +1038,8 @@ def write_startup_marker() -> None:# Same layout as a per-port record, so _read_pid_record parses both.# An unknown start time is a blank line, read back as None.path.write_text(body, encoding = "utf-8")- # Not appended twice. The path is the same file every time (this- # PID names it), so a second publish rewrites identical bytes, but- # a duplicate entry would be popped and retried twice on the way- # out for no reason.+ # Not appended twice: the path is the same file every time (this PID names it), and a duplicate entry+ # would be popped and retried twice on the way out for no reason.if path not in _OWN_STARTUP_MARKERS:_OWN_STARTUP_MARKERS.append(path)except OSError:@@ -1156,11 +1048,8 @@ def write_startup_marker() -> None:returnimport atexit- # Registered here rather than beside the pid-file hook: startup can fail- # between these two points, and the marker has to go either way. Before the- # wait below, so an interrupt during it still takes the marker back. Once- # per process: the hook drains the whole list, so a second registration- # only runs it again on an empty one.+ # Registered here rather than beside the pid-file hook: startup can fail between these two points, and the+ # marker has to go either way. Before the wait below, so an interrupt during it still takes the marker back.global _STARTUP_MARKER_HOOK_REGISTEREDif not _STARTUP_MARKER_HOOK_REGISTERED:atexit.register(_remove_startup_marker)@@ -1169,25 +1058,17 @@ def write_startup_marker() -> None:_wait_out_a_running_cache_clear(compiled_cache_lock, LOCK_BUSY)-# A clear is an rmtree of one directory. Five minutes is not how long that takes-# even on network storage; it is how long to keep waiting before deciding that-# refusing to start is worse for the user than starting on a cache that may lose-# files underneath it.+# A clear is an rmtree of one directory. Five minutes is not how long that takes even on network storage; it+# is how long to keep waiting before deciding that refusing to start is worse than starting on a cache that+# may lose files underneath it._CACHE_CLEAR_WAIT_SECONDS = 300.0def _wait_out_a_running_cache_clear(compiled_cache_lock, lock_busy) -> None:- """Block until whoever is clearing the compiled cache has finished.-- The marker is already published, so this backend is visible to every sibling- probe from here on, which is what publishing unlocked bought. What it must- not do is return to a caller that immediately imports and compiles into a- cache another backend is still deleting: that is the cross-backend race the- lock exists to close. Taking the lock and dropping it again is the wait.-- The lock is an OS file lock, released when its holder exits, so a crashed- backend cannot hold this here.- """+ """Block until whoever is clearing the compiled cache has finished. What this must not do is return to a+ caller that immediately imports and compiles into a cache another backend is still deleting; taking the+ lock and dropping it again is the wait. The lock is an OS file lock, released when its holder exits, so+ a crashed backend cannot hold this here."""with compiled_cache_lock(timeout = _CACHE_CLEAR_WAIT_SECONDS) as state:if state == lock_busy:logger.warning(@@ -1205,18 +1086,11 @@ _MARKER_REMOVAL_BACKOFF_SECONDS = 0.2def _remove_startup_marker() -> None:- """Delete this process's startup markers, retrying a failure a few times.-- A path is dropped from the list only once it is actually gone. A transient- unlink failure would otherwise lose the only reference to it, leaving a- marker on disk that no later cleanup can retry: its recorded start time- still matches this process, so an embedded host that keeps running would go- on answering as a live backend and pin the compiled cache.-- Retrying here rather than only keeping the path is what makes that recovery- real. The one guaranteed later call is the atexit hook, which an embedded- host that outlives its backend does not reach for a long time, if ever.- """+ """Delete this process's startup markers, retrying a failure a few times. A path is dropped from the list+ only once it is actually gone: a transient unlink failure would otherwise lose the only reference to+ it, leaving a marker whose recorded start time still matches this process, so an embedded host that+ keeps running would go on answering as a live backend and pin the compiled cache. The one guaranteed+ later call is the atexit hook, which such a host may not reach for a long time."""import timeremaining = []@@ -1237,11 +1111,8 @@ def _remove_startup_marker() -> None:def _record_written_at(path: Path) -> float:- """When *path* was last written, or 0.0 when the filesystem will not say.-- 0.0 makes an unreadable time the oldest possible, so it never wins the- "which statement about this PID came last" comparison below.- """+ """When *path* was last written, or 0.0 when the filesystem will not say. 0.0 makes an unreadable time the+ oldest possible, so it never wins the "which statement about this PID came last" comparison below."""try:return path.stat().st_mtimeexcept OSError:@@ -1275,20 +1146,14 @@ def _legacy_record() -> "tuple[tuple[int, float | None, str | None], float] | Nodef _sibling_is_running(pid: int) -> bool:- """Alive, and not an exited process nobody waited on.-- A zombie answers kill(0) and keeps its start time, so on its own liveness- reads it as a serving backend. Under a non-reaping parent (PID 1 in some- containers) it can stay that way indefinitely, and a record pointing at one- would pin the compiled cache on every later startup.- """+ """Alive, and not an exited process nobody waited on. A zombie answers kill(0) and keeps its start time,+ and under a non-reaping parent (PID 1 in some containers) it can stay that way indefinitely, so a+ record pointing at one would pin the compiled cache on every later startup."""if not _pid_alive(pid):return Falsetry:from utils.process_lifetime import _pid_is_zombieexcept Exception: # noqa: BLE001- # The check is an exclusion, so without it this behaves as it did- # before: alive is alive.return Truereturn not _pid_is_zombie(pid)@@ -1301,19 +1166,13 @@ def _live_sibling(records: "list", me: int, timed: "list") -> "int | None":pid, created, _address = recordif pid == me or not _sibling_is_running(pid):continue- # Corroborate against other records for this PID, the way- # _legacy_studio_on_port does. studio.pid holds a bare PID with no start- # time, and an untimed record is trusted unconditionally, so on its own- # it would resurrect a server that died and had its PID reused -- and- # keep the compiled cache forever on the strength of it. A timestamped- # record for the same PID that fails the check is evidence it is gone.- #- # Only a record written no earlier than this one counts as that- # evidence. A pre-upgrade backend writes a bare studio.pid and nothing- # else, so if it starts on a PID a crashed current-version backend left- # a timestamped record for, the older timestamp is a statement about a- # process that is gone, not about this one. Letting it veto would clear- # the compiled cache under a serving legacy backend.+ # Corroborate against other records for this PID, the way _legacy_studio_on_port does. studio.pid holds a+ # bare PID with no start time, and an untimed record is trusted unconditionally, so on its own it would+ # resurrect a server that died and had its PID reused. A timestamped record for the same PID that fails+ # the check is evidence it is gone. Only a record written no earlier than this one counts: a pre-upgrade+ # backend writes a bare studio.pid and nothing else, so if it starts on a PID a crashed current-version+ # backend left a record for, the older timestamp describes a process that is gone, and letting it veto+ # would clear the compiled cache under a serving legacy backend.corroborating = [other[1]for other, other_written in timed@@ -1325,21 +1184,13 @@ def _live_sibling(records: "list", me: int, timed: "list") -> "int | None":def live_sibling_backend() -> "int | None":- """PID of another live Unsloth backend of this install, or None.-- Two of ours at once is a supported configuration: `_resolve_port` refuses- only the port one of ours already holds, and `_abort_already_running` tells- the user to pick another. They share an install-tree compiled cache, so the- second one must not wipe it out from under the first.-- All three records are read, because a sibling can be in a state where only- one of them exists: a startup marker while it is still binding, a per-port- record once it has bound, and `studio.pid` alone for a pre-upgrade server or- one whose best-effort per-port write failed.-- Called before `_write_pid_file`, so our own record is not there yet; the- explicit pid check keeps it correct for the marker, which is.- """+ """PID of another live Unsloth backend of this install, or None. Two of ours at once is a supported+ configuration, and they share an install-tree compiled cache, so the second must not wipe it out from+ under the first. All three records are read, because a sibling can be in a state where only one exists:+ a startup marker while it is still binding, a per-port record once it has bound, and `studio.pid` alone+ for a pre-upgrade server or one whose best-effort per-port write failed. Called before+ `_write_pid_file`, so our own record is not there yet; the explicit pid check keeps it correct for the+ marker, which is."""me = os.getpid()timed = _timed_records()return _live_sibling(timed + [_legacy_record()], me, timed)@@ -1357,13 +1208,9 @@ def _resolve_port(port: int,avoid_own_studio: bool = True,) -> int:- """The requested port, or the next free one.-- With ``avoid_own_studio`` this aborts rather than falling back past one of our- own servers, on *port* itself or anywhere in the fallback range: skipping one- is what strands it. Callers that read the bound port back pass False and keep- the plain fallback.- """+ """The requested port, or the next free one. With ``avoid_own_studio`` this aborts rather than falling back+ past one of our own servers, on *port* itself or anywhere in the fallback range, since skipping one is+ what strands it."""if _is_port_free(host, port):return portif avoid_own_studio:@@ -1383,9 +1230,8 @@ def _abort_already_running(pid: int, port: int) -> "NoReturn":sys.exit(1)-# Direct backend launches bypass the CLI's env re-export; do it here for-# real custom roots so unsloth-zoo's import-time LLAMA_CPP_DEFAULT_DIR-# picks up the custom build. Skip legacy-default to avoid flipping+# Direct backend launches bypass the CLI's env re-export; do it here for real custom roots so unsloth-zoo's+# import-time LLAMA_CPP_DEFAULT_DIR picks up the custom build. Skip legacy-default to avoid flipping# default-mode installs into env-override.try:_LEGACY_STUDIO_ROOT = (Path.home() / ".unsloth" / "studio").resolve()@@ -1407,9 +1253,8 @@ if _STUDIO_ROOT_RESOLVED != _LEGACY_STUDIO_ROOT:mark_managed_llama_cpp_path(_MANAGED_LLAMA_CPP_PATH)-# The studio bundles unsloth_zoo; declare unsloth present (as `import unsloth`-# does) so its lazy submodule imports (export, hardware, mlx) and the-# DiffusionGemma runner never trip the install guard on a clean install.+# The studio bundles unsloth_zoo; declare unsloth present (as `import unsloth` does) so its lazy+# submodule imports and the DiffusionGemma runner never trip the install guard on a clean install.os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")@@ -1444,13 +1289,11 @@ def _write_pid_file(port: int, host: str = ""):passelse:_OWN_PID_FILE = path- # An older CLI's `stop` only reads this one, and expects a bare PID. Written- # independently of the per-port record: if that one failed, this is the only- # thing keeping the server stoppable at all.+ # An older CLI's `stop` only reads this one, and expects a bare PID. Written independently of the+ # per-port record: if that one failed, this is the only thing keeping the server stoppable at all.try:- # Never take it from a server that is still running. A pre-upgrade server- # is recorded here and nowhere else, so overwriting its entry is exactly- # what strands it -- the orphan this file exists to prevent.+ # Never take it from a server that is still running. A pre-upgrade server is recorded here and nowhere+ # else, so overwriting its entry is exactly what strands it.prior = _read_pid_record(_PID_FILE) if _PID_FILE.is_file() else Noneif prior is None or prior[0] == os.getpid() or not _pid_alive(prior[0]):_PID_FILE.write_text(str(os.getpid()), encoding = "utf-8")@@ -1459,12 +1302,8 @@ def _write_pid_file(port: int, host: str = ""):def _legacy_heir() -> "int | None":- """Another live server's PID, to hand the legacy studio.pid over to.-- Only one server owns studio.pid at a time, so its exit would otherwise drop- the single record an older CLI can read, stranding any sibling that is still- serving.- """+ """Another live server's PID, to hand the legacy studio.pid over to. Only one server owns studio.pid+ at a time, so its exit would otherwise drop the single record an older CLI can read."""try:paths = sorted(_studio_root().glob(PID_FILE_GLOB))except OSError:@@ -1481,21 +1320,14 @@ def _legacy_heir() -> "int | None":def _remove_pid_file():- """Remove the records that belong to this process.-- _PID_FILE is checked even when the per-port record was never written, since- _write_pid_file writes the two independently.-- The startup marker is deliberately NOT dropped here. _graceful_shutdown- calls this before the server thread is joined, and a backend that is still- finishing an in-flight request or a background warm is still importing from- the cache; going invisible there would let a replacement clear it underneath.- The marker goes when the server thread actually ends, and from the atexit- hook if the process exits first.- """- # Nothing here may raise: _graceful_shutdown calls this at the end, and an- # unreadable or undeletable record must not abandon the rest of the exit- # path. _read_pid_record already swallows OSError/UnicodeDecodeError.+ """Remove the records that belong to this process. _PID_FILE is checked even when the per-port+ record was never written, since _write_pid_file writes the two independently. The startup marker+ is deliberately NOT dropped here: _graceful_shutdown calls this before the server thread is+ joined, and a backend still finishing an in-flight request is still importing from the cache, so+ going invisible there would let a replacement clear it underneath. The marker goes when the+ server thread actually ends, and from the atexit hook if the process exits first."""+ # Nothing here may raise: _graceful_shutdown calls this at the end, and an unreadable or undeletable+ # record must not abandon the rest of the exit path.if _OWN_PID_FILE is not None:try:record = _read_pid_record(_OWN_PID_FILE) if _OWN_PID_FILE.is_file() else None@@ -1506,9 +1338,8 @@ def _remove_pid_file():try:record = _read_pid_record(_PID_FILE) if _PID_FILE.is_file() else Noneif record is not None and record[0] == os.getpid():- # Hand the pointer to a live sibling rather than deleting it. An- # older CLI reads only this file, so dropping it while another- # server is still up leaves that server unstoppable.+ # Hand the pointer to a live sibling rather than deleting it: an older CLI reads only this file, so+ # dropping it while another server is still up leaves that server unstoppable.heir = _legacy_heir()if heir is None:_PID_FILE.unlink(missing_ok = True)@@ -1539,15 +1370,10 @@ def _run_console_shutdown(shutdown) -> None:def _install_windows_console_handler(shutdown) -> bool:- """Run the graceful shutdown when the console window is closed.-- Closing the window raises CTRL_CLOSE_EVENT, which Python never turns into a- signal, so neither a signal handler nor atexit runs and cleanup is skipped.- ``shutdown`` takes no arguments and must not touch signal.signal: Windows- runs this on a thread it creates for the event, and Windows kills the- process about five seconds later, so the work is bounded to fit. No-op off- Windows.- """+ """Run the graceful shutdown when the console window is closed. Closing the window raises+ CTRL_CLOSE_EVENT, which Python never turns into a signal, so neither a signal handler nor atexit runs.+ ``shutdown`` takes no arguments and must not touch signal.signal: Windows runs this on a thread it+ creates for the event and kills the process about five seconds later, so the work is bounded to fit."""if sys.platform != "win32":return Falsetry:@@ -1581,8 +1407,7 @@ def _install_windows_console_handler(shutdown) -> bool:ctypes.get_last_error(),)return False- # Hold a reference: a collected callback leaves Windows calling into- # freed memory.+ # Hold a reference: a collected callback leaves Windows calling into freed memory.globals()["_WINDOWS_CONSOLE_HANDLER"] = callbacklogger.info("Console-close handler installed")return True@@ -1592,11 +1417,8 @@ def _install_windows_console_handler(shutdown) -> bool:def _graceful_shutdown(server = None):- """Shut down all subprocess backends and the uvicorn server.-- Called from signal handlers to clean up children before exit. Critical on- Windows where atexit handlers are unreliable after Ctrl+C.- """+ """Shut down all subprocess backends and the uvicorn server. Called from signal handlers to clean up+ children before exit; critical on Windows where atexit handlers are unreliable after Ctrl+C."""logger.info("Graceful shutdown initiated -- cleaning up subprocesses...")# 0a. Latch "quitting" before any subsystem is torn down. Each step below refuses to@@ -1617,11 +1439,9 @@ def _graceful_shutdown(server = None):except Exception as e:logger.warning("Error stopping the LAN listener: %s", e)- # 1. Shut down uvicorn (releases the listening socket).if server is not None:server.should_exit = True- # 2. Clean up inference subprocess (if instantiated).try:from core.inference.orchestrator import _inference_backendif _inference_backend is not None:@@ -1629,7 +1449,6 @@ def _graceful_shutdown(server = None):except Exception as e:logger.warning("Error shutting down inference subprocess: %s", e)- # 3. Clean up export subprocess (if instantiated).try:from core.export.orchestrator import _export_backendif _export_backend is not None:@@ -1637,7 +1456,6 @@ def _graceful_shutdown(server = None):except Exception as e:logger.warning("Error shutting down export subprocess: %s", e)- # 4. Clean up training subprocess (if active).try:from core.training.training import _training_backendif _training_backend is not None:@@ -1645,7 +1463,6 @@ def _graceful_shutdown(server = None):except Exception as e:logger.warning("Error shutting down training subprocess: %s", e)- # 5. Kill llama-server subprocess (if loaded).try:from routes.inference import _llama_cpp_backend, cancel_pending_loads@@ -1665,14 +1482,12 @@ def _graceful_shutdown(server = None):except Exception as e:logger.warning("Error shutting down llama-server: %s", e)- # 6. Stop the Cloudflare tunnel (if started).try:from cloudflare_tunnel import close_studio_tunnel_lifecycleclose_studio_tunnel_lifecycle()except Exception as e:logger.warning("Error stopping Cloudflare tunnel: %s", e)- # 7. Backstop sweep for any adopted child the steps above missed.try:from utils.process_lifetime import clear_breadcrumb, terminate_allterminate_all()@@ -1680,8 +1495,8 @@ def _graceful_shutdown(server = None):except Exception as e:logger.warning("Error in process-lifetime sweep: %s", e)- # Last: while cleanup runs the server is still alive, and dropping the record- # early leaves a retried `stop` or a new launch unable to find it.+ # Last: while cleanup runs the server is still alive, and dropping the record early leaves a retried+ # `stop` or a new launch unable to find it._remove_pid_file()logger.info("All subprocesses cleaned up")@@ -1699,8 +1514,8 @@ def _flush_standard_streams() -> None:def _wait_for_server_shutdown(timeout: Optional[float] = _SERVER_SHUTDOWN_JOIN_TIMEOUT) -> None:- """Join the uvicorn thread so the prompt returns only after its shutdown logs- flush. Skip the self-join when called from the server thread."""+ """Join the uvicorn thread so the prompt returns only after its shutdown logs flush. Skip the+ self-join when called from the server thread."""import threadingthread = _server_thread@@ -1713,12 +1528,9 @@ def _wait_for_server_shutdown(timeout: Optional[float] = _SERVER_SHUTDOWN_JOIN_T_flush_standard_streams()-# The uvicorn server instance -- set by run_server(), used by callers-# that tell the server to exit (e.g. signal handlers)._server = None_server_thread = None-# Shutdown event -- wakes the main loop on signal._shutdown_event = None# trycloudflare.com URL for wildcard binds (set by run_server, read by the banner);@@ -1732,15 +1544,13 @@ def _publish_cloudflare_url(app_state, cloudflare_url: "Optional[str]") -> None:app_state.cloudflare_url = cloudflare_url-# Public reachability from the last _verify_global_reachability run, read by the-# Cloudflare banner line. True when the public ip:port probe confirmed reachable,-# False when it confirmed NOT reachable, None when the probe did not run or could-# not decide (timeout, blocked, private address).+# Public reachability from the last _verify_global_reachability run: True when the probe confirmed+# reachable, False when it confirmed NOT reachable, None when it did not run or could not decide._public_reachable = None_cloudflare_requested = False-# Opt-in tri-state (mirrors the CLI): None = off by default, True = on,-# False = explicit --no-cloudflare. run_server overwrites it before the banner.+# Opt-in tri-state (mirrors the CLI): None = off by default, True = on, False = explicit+# --no-cloudflare._cloudflare_flag = None@@ -1748,11 +1558,9 @@ _DEFAULT_FRONTEND_PATH = Path(__file__).resolve().parent.parent / "frontend" / "def _iter_frontend_fallback_candidates() -> "list[Path]":- """Yield `studio/frontend/dist` paths to try when the default is missing.-- Covers PATH-shadowed binaries whose __file__ resolves into a site-packages- tree with no vite build (e.g. plain `pip install unsloth`).- """+ """Yield `studio/frontend/dist` paths to try when the default is missing, covering PATH-shadowed binaries+ whose __file__ resolves into a site-packages tree with no vite build (e.g. plain `pip install+ unsloth`)."""import astimport re@@ -1777,8 +1585,8 @@ def _iter_frontend_fallback_candidates() -> "list[Path]":src = finder.read_text(encoding = "utf-8")except (OSError, UnicodeDecodeError):continue- # Tolerate single/multi-line dict literals; [^}]* rejects nested- # dicts, which the setuptools editable template never emits.+ # Tolerate single/multi-line dict literals; [^}]* rejects nested dicts, which the setuptools editable+ # template never emits.m = re.search(r"^MAPPING\s*(?::[^=]*)?=\s*(\{[^}]*\})", src, re.M | re.S)if not m:continue@@ -1796,11 +1604,8 @@ def _iter_frontend_fallback_candidates() -> "list[Path]":def _resolve_frontend_path(frontend_path: Path) -> tuple[Optional[Path], list[Path]]:- """Pick a frontend dir that contains `index.html`.-- Returns (chosen, attempted). `chosen` is None if nothing servable was found;- `attempted` is the ordered list for diagnostics.- """+ """Pick a frontend dir that contains `index.html`. Returns (chosen, attempted); `chosen` is None if+ nothing servable was found."""attempted: list[Path] = []seen: set[Path] = set()@@ -1829,36 +1634,27 @@ def _frontend_serving_mode(*, api_only: bool, desktop_owned: bool) -> tuple[booldef _missing_frontend_is_fatal(*, tunnel_only: bool) -> bool:- """Whether an unresolvable SPA build must abort startup.-- It must when the web UI is this launch's own surface: a 404 on / is worse- than a loud error. It must not for the desktop, which passes --api-only with- no --frontend and whose installer skips the frontend build outright; there- the SPA only backs the optional remote web UI, so aborting would kill the- local API before TAURI_PORT is ever emitted. Degrade to API-only instead."""+ """Whether an unresolvable SPA build must abort startup. It must when the web UI is this launch's own+ surface: a 404 on / is worse than a loud error. It must not for the desktop, which passes --api-only+ with no --frontend and whose installer skips the frontend build; there the SPA only backs the optional+ remote web UI, so aborting would kill the local API before TAURI_PORT is emitted."""return not tunnel_onlyclass _TeeStream:- """Mirror writes to the original stream and a session log file.-- Console behavior is unchanged (writes/returns delegate to the original- stream; Tauri's structured-stdout protocol and isatty probes see exactly- what they saw before). The file copy is best-effort: a full disk or a- closed handle must never break the console.-- The file copy also collapses carriage-return progress frames: a tqdm bar redraws- "\\r<frame>" hundreds of times and a file keeps every one (5 KB for one "Loading- weights" bar). Only frames are ever withheld -- a partial line with no "\\r" (a- prompt, a traceback torn by a hang) is written on arrival, and a held frame is- closed off on its own line before the next record, never prefixed onto it.-- Frames are picked exactly as the desktop reader picks them, so the session log and- tauri.log stay interchangeable: strip the terminator (trim_line_endings), then take- the last non-blank "\\r"-separated frame (collapse_progress_frames), both in- src-tauri/src/process.rs. Reading the "\\r" of a CRLF as a redraw instead keeps the- empty text after it and drops the line, which on Windows is every relayed child- line there is."""+ """Mirror writes to the original stream and a session log file. Console behavior is unchanged, and+ the file copy is best-effort: a full disk or a closed handle must never break the console.++ The file copy collapses carriage-return progress frames: a tqdm bar redraws "\\r<frame>" hundreds+ of times and a file keeps every one. Only frames are ever withheld: a partial line with no "\\r" (a+ prompt, a traceback torn by a hang) is written on arrival, and a held frame is closed off on its+ own line before the next record.++ Frames are picked exactly as the desktop reader picks them, so the session log and tauri.log stay+ interchangeable: strip the terminator (trim_line_endings), then take the last non-blank+ "\\r"-separated frame (collapse_progress_frames), both in src-tauri/src/process.rs. Reading the+ "\\r" of a CRLF as a redraw instead keeps the empty text after it and drops the line, which on+ Windows is every relayed child line there is."""def __init__(self, stream, log_fh):self._stream = stream@@ -1869,21 +1665,21 @@ class _TeeStream:@staticmethoddef _last_frame(line):- # A trailing "\r" terminates the line (CRLF, or tqdm's own sign-off); it does not- # open an empty redraw. Strip it first, as trim_line_endings does on the desktop side.+ # A trailing "\r" terminates the line (CRLF, or tqdm's own sign-off); it does not open an empty+ # redraw. Strip it first, as trim_line_endings does on the desktop side.line = line.rstrip("\r")if "\r" not in line:return linefor frame in reversed(line.split("\r")):if frame.strip():return frame- # All frames blank, so the line is blank. Return a frame, not the whole text: a- # "\r" reaching the file lands as "\r\r\n" once the handle adds its own terminator.+ # All frames blank, so the line is blank. Return a frame, not the whole text: a bare CR reaching the+ # file lands as CR CR LF once the handle adds its own terminator.return line.rsplit("\r", 1)[-1]def _write_file(self, data):- # Not a continuation of a held frame: that would flush it unterminated and glue- # the next record on. print("", end = "") is enough to get here.+ # Not a continuation of a held frame: that would flush it unterminated and glue the next record on.+ # print("", end = "") is enough to get here.if not data:return# Overwhelmingly the common case, and the one that must stay cheap.@@ -1892,8 +1688,8 @@ class _TeeStream:returnif self._pending_frame and data[:1] not in ("\r", "\n"):- # Not a redraw of the held frame nor its terminator, so it is the next record.- # Close the frame off on its own line; concatenating costs a reader the JSON.+ # Not a redraw of the held frame nor its terminator, so it is the next record. Close the frame off on+ # its own line; concatenating costs a reader the JSON.self._log_fh.write(self._pending_frame + "\n")self._pending_frame = ""@@ -1904,8 +1700,8 @@ class _TeeStream:complete = head + newlineself._log_fh.write("\n".join(self._last_frame(line) for line in complete.split("\n")))if tail:- # Unterminated remainder: hold it only if it is a redraw, else write it now- # so a hang cannot swallow real output.+ # Unterminated remainder: hold it only if it is a redraw, else write it now so a hang cannot swallow+ # real output.if "\r" in tail:self._pending_frame = self._last_frame(tail)else:@@ -1933,12 +1729,10 @@ class _TeeStream:passdef close(self):- # We do NOT own the console stream (it is the terminal / Jupyter kernel- # stream we wrapped), so closing the tee must never take the server down.- # Flush the log copy, then forward close() to the wrapped stream- # best-effort: on Colab that stream is an ipykernel OutStream whose- # close() can raise (see _harden_console_close / ipython/ipykernel#867).- # A frame still held here has nothing left to supersede it, so land it.+ # We do NOT own the console stream (it is the terminal / Jupyter kernel stream we wrapped), so closing+ # the tee must never take the server down. Forward close() best-effort: on Colab that stream is an+ # ipykernel OutStream whose close() can raise (ipython/ipykernel#867). A frame still held here has+ # nothing left to supersede it, so land it.try:if self._pending_frame:self._log_fh.write(self._pending_frame + "\n")@@ -1963,12 +1757,9 @@ _WATCH_FD_THREAD_ATTR = "watch_fd_thread"def _is_missing_watch_fd_thread(exc):- """True only for ipython/ipykernel#867's missing-``watch_fd_thread`` error.-- ``AttributeError.name`` exists from Python 3.10; the message carries the- attribute name on every version (possibly with a "Did you mean" tail), so- check both and let every other AttributeError through.- """+ """True only for ipython/ipykernel#867's missing-``watch_fd_thread`` error. ``AttributeError.name`` exists+ from Python 3.10; the message carries the attribute name on every version (possibly with a "Did you+ mean" tail), so check both and let every other AttributeError through."""if getattr(exc, "name", None) == _WATCH_FD_THREAD_ATTR:return Truereturn _WATCH_FD_THREAD_ATTR in str(exc)@@ -1976,29 +1767,16 @@ def _is_missing_watch_fd_thread(exc):def _harden_console_close(stream):"""Stop a displaced console stream's close() from aborting Unsloth startup.-- ``_setup_server_disk_logging`` replaces ``sys.stdout``/``sys.stderr`` with a- tee. That changes the object identity of the console stream, so a third-party- logging handler that captured the ORIGINAL stream (notably Colab's ``absl``- logging handler, whose ``close()`` skips ``sys.stdout``/``sys.stderr`` but not- a stream that is no longer either) treats it as an ordinary stream and calls- ``close()`` on it during logging teardown -- ``uvicorn.Config()`` ->- ``logging.config.dictConfig()`` -> ``logging.shutdown()``.-- A Jupyter/Colab ``ipykernel`` ``OutStream`` created with ``watchfd=False``- (the Colab default, and every in-process kernel) never gains a- ``watch_fd_thread``, yet the ``OutStream.close()`` shipped in the affected- ipykernel versions joins that thread unconditionally and raises- ``AttributeError: 'OutStream' object has no attribute 'watch_fd_thread'``- (ipython/ipykernel#867). That AttributeError propagates out of- ``uvicorn.Config(...)`` and aborts startup ("Unsloth Studio failed to start").-- Wrap the stream's ``close()`` in a transparent pass-through that swallows- ONLY that specific teardown AttributeError. A healthy close() (a real console- stream, or an OutStream with fd-watching on) runs to completion exactly as- before and any other error still propagates, so nothing changes off Colab. A- stream whose ``close`` cannot be reassigned keeps its original close().- """+ ``_setup_server_disk_logging`` replaces ``sys.stdout``/``sys.stderr`` with a tee, changing the+ object identity of the console stream, so a third-party logging handler that captured the+ ORIGINAL stream (notably Colab's ``absl`` handler, whose ``close()`` skips+ ``sys.stdout``/``sys.stderr`` but not a stream that is no longer either) calls ``close()`` on it+ during logging teardown, via ``uvicorn.Config()`` -> ``dictConfig()`` -> ``logging.shutdown()``.+ An ipykernel ``OutStream`` created with ``watchfd=False`` (the Colab default) never gains a+ ``watch_fd_thread``, yet the affected ipykernel versions join that thread unconditionally in+ ``close()`` and raise ``AttributeError`` (ipython/ipykernel#867), which aborts startup. So wrap+ ``close()`` in a pass-through that swallows ONLY that AttributeError; a healthy close() runs+ exactly as before and any other error still propagates."""if stream is None:returntry:@@ -2013,8 +1791,7 @@ def _harden_console_close(stream):if not _is_missing_watch_fd_thread(exc):# A real teardown failure; never hide it.raise- # ipython/ipykernel#867: watchfd=False OutStream.close() joins a- # thread that was never created. Nothing to clean up; keep going.+ # ipython/ipykernel#867: watchfd=False OutStream.close() joins a thread that was never created.return Nonetry:@@ -2025,15 +1802,10 @@ def _harden_console_close(stream):def _setup_server_disk_logging():- """Tee stdout/stderr to ~/.unsloth/studio/logs/server/ and aim- faulthandler at the same file so hard crashes (access violations /- SIGSEGV in the GPU runtime) leave a stack trace on disk.-- Also exports PYTHONFAULTHANDLER=1 so child Python processes (training- workers) dump native-crash stacks to their captured stderr. Keeps the- newest 20 session logs. Opt out with UNSLOTH_STUDIO_NO_FILE_LOG=1.- Returns the log path, or None when disabled/unavailable.- """+ """Tee stdout/stderr to ~/.unsloth/studio/logs/server/ and aim faulthandler at the same file so hard+ crashes (access violations / SIGSEGV in the GPU runtime) leave a stack trace on disk. Also exports+ PYTHONFAULTHANDLER=1 so child Python processes dump native-crash stacks to their captured stderr. Keeps+ the newest 20 session logs; opt out with UNSLOTH_STUDIO_NO_FILE_LOG=1."""if os.environ.get("UNSLOTH_STUDIO_NO_FILE_LOG") == "1":return Nonetry:@@ -2050,8 +1822,8 @@ def _setup_server_disk_logging():log_dir.mkdir(parents = True, exist_ok = True)stamp = time.strftime("%Y%m%d-%H%M%S")log_path = log_dir / f"server-{stamp}-pid{os.getpid()}.log"- # Line-buffered so the tail survives a hard kill; errors="replace"- # so a console encoding quirk can never take the server down.+ # Line-buffered so the tail survives a hard kill; errors="replace" so a console encoding quirk can+ # never take the server down.log_fh = open(log_path, "w", encoding = "utf-8", errors = "replace", buffering = 1)except Exception:return None@@ -2062,23 +1834,22 @@ def _setup_server_disk_logging():faulthandler.enable(file = log_fh, all_threads = True)except Exception:pass- # Children (training workers) inherit: their native-crash stacks land on- # the stderr the server already captures.+ # Children (training workers) inherit: their native-crash stacks land on the stderr the server already+ # captures.os.environ.setdefault("PYTHONFAULTHANDLER", "1")- # Replacing the console streams orphans them from third-party "is this the- # live console?" checks, so guard their close() first (ipython/ipykernel#867).+ # Replacing the console streams orphans them from third-party "is this the live console?" checks, so+ # guard their close() first (ipython/ipykernel#867)._harden_console_close(sys.stdout)_harden_console_close(sys.stderr)- # _normalize_standard_streams() ran at import, so these are never None; the- # tee's own None guards are defence-in-depth for _TeeStream(None, ...).+ # _normalize_standard_streams() ran at import, so these are never None; the tee's own None guards are+ # defence-in-depth.sys.stdout = _TeeStream(sys.stdout, log_fh)sys.stderr = _TeeStream(sys.stderr, log_fh)- # Best-effort retention: keep the newest 20 session logs. `protect` says so explicitly- # rather than trusting the new file to sort newest, which two starts in the same- # second do not guarantee.+ # Best-effort retention: keep the newest 20 session logs. `protect` says so explicitly rather than+ # trusting the new file to sort newest, which two starts in the same second do not guarantee.try:from utils.log_retention import prune_log_dirprune_log_dir(log_dir, "server-*.log", protect = log_path)@@ -2090,9 +1861,8 @@ def _setup_server_disk_logging():def _cloudflare_tunnel_should_start(*, cloudflare: bool, host: str, secure: bool, api_only: bool, is_colab: bool) -> bool:- """Whether to start the Cloudflare tunnel. --secure exposes only the tunnel- (loopback bind), so it tunnels even api-only (headless secure API serving);- otherwise tunnel wildcard binds, never api-only (Tauri) or Colab."""+ """Whether to start the Cloudflare tunnel. --secure exposes only the tunnel (loopback bind), so it+ tunnels even api-only; otherwise tunnel wildcard binds, never api-only (Tauri) or Colab."""if is_colab or not cloudflare:return Falseif secure:@@ -2133,12 +1903,9 @@ _CLOUDFLARE_INTENT_ENV = "_UNSLOTH_CLOUDFLARE_INTENT"def _consume_cloudflare_intent(cloudflare: "Optional[bool]", secure: bool) -> str:- """Resolve user intent without confusing a compatibility flag with opt-out.-- An explicit choice on THIS invocation wins: letting the inherited marker- override it would let a stale export, Docker ENV or systemd Environment=- re-enable a tunnel the user opted out of.- """+ """Resolve user intent without confusing a compatibility flag with opt-out. An explicit choice on THIS+ invocation wins: letting the inherited marker override it would let a stale export, Docker ENV or+ systemd Environment= re-enable a tunnel the user opted out of."""inherited = os.environ.pop(_CLOUDFLARE_INTENT_ENV, None)if secure or cloudflare is True:return "enabled"@@ -2151,12 +1918,9 @@ def _consume_cloudflare_intent(cloudflare: "Optional[bool]", secure: bool) -> stdef _stream_isatty(stream) -> bool:- """isatty() that treats broken streams as non-interactive.-- isatty() can raise under service wrappers (closed stdin -> ValueError;- sys.stdin None in Windows GUI -> AttributeError); such a stream can't host a- prompt, which is a fallback, not an error.- """+ """isatty() that treats broken streams as non-interactive: it can raise under service wrappers (closed+ stdin gives ValueError; sys.stdin None in a Windows GUI gives AttributeError), and such a stream cannot+ host a prompt."""try:return stream.isatty()except (AttributeError, ValueError):@@ -2325,9 +2089,8 @@ def _terminal_password_gate(flush = True,)return False, False- # The public page won't auto-fill the bootstrap credential (suppressed- # below) and the seeded file may already be gone, so point recovery at a- # terminal-attached run / reset-password instead of reading it from disk.+ # The public page will not auto-fill the bootstrap credential and the seeded file may already be gone,+ # so point recovery at a terminal-attached run / reset-password instead of reading it from disk.print(" WARNING: the default admin password is still active while ""Unsloth is about to be published on a public Cloudflare URL, and "@@ -2351,8 +2114,8 @@ def _terminal_password_gate(return _auth_hashing.verify_password(candidate, salt, pwd_hash)def _apply_change(new_password: str) -> None:- # Same effects as routes/auth.py change_password: rehash, rotate the JWT- # secret, revoke refresh tokens in the SAME transaction.+ # Same effects as routes/auth.py change_password: rehash, rotate the JWT secret, revoke refresh tokens+ # in the SAME transaction._auth_storage.update_password(_admin, new_password, revoke_refresh_tokens = True)changed = prompt_for_password_change(@@ -2423,22 +2186,18 @@ def _terminal_password_gate(def _apply_supplied_password(password_value: "Optional[str]") -> None:- """Non-interactively set the INITIAL admin password before the socket binds,- for a direct ``python run.py`` launch (the CLI does this in its own parent).- Value comes from --password / UNSLOTH_STUDIO_PASSWORD / stdin.-- Only ever sets the FIRST password: an already-set one is a hard error, an- invalid value fails closed. NOT wrapped in a broad try/except: an auth- storage failure must abort rather than expose the default credential.- """+ """Non-interactively set the INITIAL admin password before the socket binds, for a direct ``python run.py``+ launch. Only ever sets the FIRST password: an already-set one is a hard error, an invalid value fails+ closed. NOT wrapped in a broad try/except: an auth storage failure must abort rather than expose the+ default credential."""from auth import hashing as _auth_hashingfrom auth import storage as _auth_storagefrom auth.terminal_prompt import SUPPLIED_PASSWORD_ENV, resolve_supplied_passwordsupplied = resolve_supplied_password(password_value)- # Strip the env var once read so child subprocesses (cloudflared, llama-server,- # code-exec tools) can't inherit the plaintext via /proc/PID/environ. Mirrors- # the CLI. Unconditional: strips a leftover value even when a literal --password won.+ # Strip the env var once read so child subprocesses (cloudflared, llama-server, code-exec tools) cannot+ # inherit the plaintext via /proc/PID/environ. Unconditional: strips a leftover value even when a literal+ # --password won.os.environ.pop(SUPPLIED_PASSWORD_ENV, None)if not supplied:return@@ -2490,16 +2249,11 @@ def _apply_supplied_password(password_value: "Optional[str]") -> None:def _apply_cli_tool_policy(enable_tools: "Optional[bool]") -> None:- """Honor an explicit --enable-tools/--disable-tools; None leaves the policy- unset, so each request's own enable_tools decides. Host is never inspected- here.-- The tools-on default for an omitted `enable_tools` belongs to `unsloth studio- run`, which installs it itself (that is the launcher that has always forced- tools on). Installing it here too would extend it to `unsloth studio`, the- desktop app and Colab, where paths built around "omitted means off" -- n > 1,- max_tool_calls_per_message: 0, the pre-switch passthrough guard -- would- start seeing it."""+ """Honor an explicit --enable-tools/--disable-tools; None leaves the policy unset, so each request's own+ enable_tools decides. The tools-on default for an omitted `enable_tools` belongs to `unsloth studio+ run`, which installs it itself. Installing it here too would extend it to `unsloth studio`, the desktop+ app and Colab, where paths built around "omitted means off" (n > 1, max_tool_calls_per_message: 0, the+ pre-switch passthrough guard) would start seeing it."""if enable_tools is None:returnfrom state.tool_policy import set_tool_policy@@ -2507,26 +2261,20 @@ def _apply_cli_tool_policy(enable_tools: "Optional[bool]") -> None:set_tool_policy(enable_tools)-# Mirror unsloth_cli/commands/studio.py's _PARALLEL_*: the admission queue caps concurrent-# chats at the slot count, so a direct launch matches the CLI (VRAM fit may still cut it-# back). Defined above run_server() so embedders that omit it do not serialise every chat.+# Mirror unsloth_cli/commands/studio.py's _PARALLEL_*: the admission queue caps concurrent chats at the slot+# count, so a direct launch matches the CLI. Defined above run_server() so embedders that omit it do not+# serialise every chat._PARALLEL_MIN = 1_PARALLEL_MAX = 64_PARALLEL_DEFAULT_PLAIN = 4def _drops_its_marker_on_failure(start):- """Take the startup marker back if the server never starts.-- An embedded caller keeps its process alive across a failure -- colab.py- catches SystemExit and Exception around run_server -- and no exit hook runs- then. A marker left behind would answer every later sibling probe as a live- backend, so no backend of this install would clear the compiled cache again.-- A decorator rather than a renamed inner function: run_server's signature is- a contract here, read both by inspect.signature and by tests that parse the- def out of this file, and functools.wraps keeps both intact.- """+ """Take the startup marker back if the server never starts. An embedded caller keeps its process alive+ across a failure (colab.py catches SystemExit and Exception around run_server) and no exit hook runs+ then, so a marker left behind would answer every later sibling probe as a live backend. A decorator+ rather than a renamed inner function: run_server's signature is a contract here, read both by+ inspect.signature and by tests that parse the def out of this file."""import functools@functools.wraps(start)@@ -2534,13 +2282,9 @@ def _drops_its_marker_on_failure(start):try:return start(*args, **kwargs)except BaseException:- # Only when no server thread is left running. A KeyboardInterrupt- # during the readiness wait asks uvicorn to stop and re-raises- # without joining, so the thread may still be finishing lifespan- # startup or shutdown. Taking the marker back there makes a backend- # that is still up invisible to a sibling, which would then clear- # the compiled cache under it. That thread's own finally removes- # the marker at the point it has genuinely stopped serving.+ # Only when no server thread is left running. A KeyboardInterrupt during the readiness wait asks uvicorn+ # to stop and re-raises without joining, so the thread may still be finishing lifespan; taking the marker+ # back there makes a backend that is still up invisible to a sibling, which would then clear the cache.thread = _server_threadif thread is None or not thread.is_alive():_remove_startup_marker()@@ -2564,30 +2308,18 @@ def run_server(emit_tauri_port: bool = True,abort_if_own_studio: "Optional[bool]" = None,):- """- Start the FastAPI server.-- Args:- host: Host to bind to- port: Port to bind to (auto-increments if in use)- frontend_path: Path to frontend build directory (optional)- silent: Suppress startup messages- api_only: API server only, except that a Tauri-owned backend serves its- packaged frontend exclusively through a live Cloudflare tunnel- llama_parallel_slots: parallel slots for llama-server (default- _PARALLEL_DEFAULT_PLAIN, matching the CLI entry points)- cloudflare: opt in to the public Cloudflare HTTPS tunnel for a wildcard- bind. Tri-state: None (unset) and False both mean off; True enables it.- --secure implies it (True) and rejects an explicit False.- enable_tools: explicit --enable-tools/--disable-tools policy; None leaves- the default (tools on, a request's own enable_tools: false honored)- emit_tauri_port: print the machine-readable TAURI_PORT line the desktop- app parses from stdout; the headless `run --api-only` path turns it- off so it does not pollute the documented URL/API-key banner-- Note:- Signal handlers are NOT registered here so embedders (e.g. Colab) keep- their own interrupt semantics; standalone callers register them after.+ """Start the FastAPI server. Public entry point: colab.py and other embedders import it.++ ``port`` auto-increments when the given one is in use. ``cloudflare`` is tri-state: None and+ False both mean off, True opts the public HTTPS tunnel in for a wildcard bind, and ``secure``+ implies True and rejects an explicit False. ``api_only`` still serves the packaged frontend+ when a Tauri-owned backend has a live tunnel. ``emit_tauri_port`` prints the machine-readable+ TAURI_PORT line the desktop app parses; ``run --api-only`` turns it off so it does not pollute+ the URL and API-key banner. ``enable_tools`` of None leaves the default on, honouring a+ request's own ``enable_tools: false``.++ Signal handlers are NOT registered here, so embedders keep their own interrupt semantics;+ standalone callers register them afterwards."""global _server, _server_thread, _shutdown_event@@ -2596,10 +2328,9 @@ def run_server(boot_started = time.perf_counter()- # --secure exposes ONLY the Cloudflare link, so --secure --no-cloudflare contradicts- # itself. Reject it before anything below touches a process global: the tee further- # down replaces sys.stdout/sys.stderr, and an embedder that catches this SystemExit- # would keep it, the log handle open, and nest another tee on its next call.+ # --secure exposes ONLY the Cloudflare link, so --secure --no-cloudflare contradicts itself. Reject it+ # before anything below touches a process global: the tee further down replaces sys.stdout/sys.stderr, and+ # an embedder that catches this SystemExit would keep it, the log handle open, and nest another tee.if secure and cloudflare is False:raise SystemExit("--secure requires the Cloudflare tunnel; do not combine it with --no-cloudflare."@@ -2615,36 +2346,28 @@ def run_server("choose an explicit port.")- # Windows cp1252 can't encode emoji; reconfigure stdout to UTF-8. Before the tee, so- # it reaches the console stream rather than the wrapper.+ # Windows cp1252 cannot encode emoji; reconfigure stdout to UTF-8. Before the tee, so it reaches the+ # console stream rather than the wrapper.if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"):try:sys.stdout.reconfigure(encoding = "utf-8", errors = "replace")except Exception:pass- # Persist a session log + native-crash stacks BEFORE anything else, so even- # import-time failures leave evidence on disk. Field report: Unsloth "terminates- # without a warning" -- a native crash in the GPU runtime kills the process with no- # traceback, and a desktop-shortcut console closes before anything can be read.+ # Persist a session log + native-crash stacks BEFORE anything else, so even import-time failures leave+ # evidence on disk: a native crash in the GPU runtime kills the process with no traceback, and a+ # desktop-shortcut console closes before anything can be read._session_log = _setup_server_disk_logging()if _session_log is not None and not silent:print(f"Session log: {_session_log}")- # Configure structlog only now, after the tee: PrintLoggerFactory captures sys.stdout- # at configure() time and cache_logger_on_first_use freezes it into any logger that- # has already emitted, so configuring first pins this module's logger to the console- # and keeps its lines out of the file just opened above.- #- # main.py configures too, but on import, which lands seconds later -- after the- # "startup begin" line below. That line used to render through structlog's defaults- # (ConsoleRenderer, local time) and everything after it as JSON in UTC, so the clock- # appeared to jump hours between line one and line two. Repeating configure() is safe;- # main.py's call still wins for its own service name.- #- # Imported here, not at module scope: `loggers` must be a real package to resolve- # `loggers.config`, and run.py is loaded by tests that stand a bare ModuleType in for- # it (tests/studio/install/test_selection_logic.py:84), which never reach this call.+ # Configure structlog only now, after the tee: PrintLoggerFactory captures sys.stdout at configure() time+ # and cache_logger_on_first_use freezes it into any logger that has already emitted, so configuring first+ # pins this module's logger to the console and keeps its lines out of the file just opened above. main.py+ # configures too, but on import, which lands after the "startup begin" line below, so the clock appeared to+ # jump hours between line one and line two; repeating configure() is safe and main.py's call still wins for+ # its own service name. Imported here, not at module scope: `loggers` must be a real package to resolve+ # `loggers.config`, and run.py is loaded by tests that stand a bare ModuleType in for it.from loggers.config import LogConfigLogConfig.setup_logging(@@ -2655,14 +2378,13 @@ def run_server(logger.info("run_server startup begin api_only=%s host=%s port=%s", api_only, host, port)cloudflare_intent = _consume_cloudflare_intent(cloudflare, secure)- # Reap every child if the parent dies abnormally (terminal close, Task- # Manager kill, SIGKILL); must run before any child can spawn.+ # Reap every child if the parent dies abnormally (terminal close, Task Manager kill, SIGKILL); must+ # run before any child can spawn.from utils.process_lifetime import initialize_parent_lifetime, reap_recorded_childreninitialize_parent_lifetime()- # macOS has neither PR_SET_PDEATHSIG nor job objects, so an Unsloth that- # crashed left its sidecars running. Sweep before spawning anything: a- # leftover holds VRAM, a port, and the files an update has to replace.+ # macOS has neither PR_SET_PDEATHSIG nor job objects, so an Unsloth that crashed left its sidecars running.+ # Sweep before spawning anything: a leftover holds VRAM, a port, and the files an update has to replace.try:reaped = reap_recorded_children()if reaped:@@ -2670,10 +2392,8 @@ def run_server(except Exception as e:logger.warning("Could not sweep orphans from a previous run: %s", e)- # --secure exposes ONLY the Cloudflare link, so force a loopback bind and the raw- # port is never public (even -H 0.0.0.0). The --no-cloudflare contradiction was- # already rejected at the top of this function, before the tee went in. Otherwise- # keep the tri-state so the banner distinguishes "off by default" from an explicit+ # --secure exposes ONLY the Cloudflare link, so force a loopback bind and the raw port is never public (even+ # -H 0.0.0.0). Otherwise keep the tri-state so the banner distinguishes "off by default" from an explicit# --no-cloudflare.if secure:cloudflare = True@@ -2682,9 +2402,8 @@ def run_server(# `unsloth studio run` installs its own resolved policy and passes None here._apply_cli_tool_policy(enable_tools)- # Set env vars BEFORE importing main so CORS middleware picks them up.- # secure api-only is a remote server behind Cloudflare, so it keeps the- # any-origin CORS profile; plain api-only stays locked to the Tauri app.+ # Set env vars BEFORE importing main so CORS middleware picks them up. secure api-only is a remote server+ # behind Cloudflare, so it keeps the any-origin CORS profile; plain api-only stays locked to the Tauri app.if api_only:os.environ["UNSLOTH_API_ONLY"] = "1"if secure:@@ -2692,12 +2411,10 @@ def run_server(import asyncio- # nest_asyncio is for Colab/IPython, where the main thread already runs a loop- # the blocking waits below would collide with. Apply it only with a loop running- # (a plain CLI start has nothing to nest) and only on Python <= 3.13: on 3.14+- # its global Task patch leaves asyncio.current_task() None (tracking moved into- # C), which also breaks the background uvicorn loop and 500s every request. It- # is archived upstream, so no 3.14 fix is coming; skip it there.+ # nest_asyncio is for Colab/IPython, where the main thread already runs a loop the blocking waits below+ # would collide with. Apply it only with a loop running and only on Python <= 3.13: on 3.14+ its global Task+ # patch leaves asyncio.current_task() None (tracking moved into C), which breaks the background uvicorn loop+ # and 500s every request. It is archived upstream, so no 3.14 fix is coming.if sys.version_info < (3, 14):try:asyncio.get_running_loop()@@ -2710,8 +2427,8 @@ def run_server(from threading import Thread, Eventimport uvicorn- # `from main import app` below loads torch/unsloth/transformers (~2 min cold,- # silent), so print a flushed heads-up (piped stdout is block-buffered).+ # `from main import app` below loads torch/unsloth/transformers (~2 min cold, silent), so print a+ # flushed heads-up (piped stdout is block-buffered).if not silent:print("Loading Unsloth Studio, please wait... (this can take a few minutes)",@@ -2721,14 +2438,10 @@ def run_server(import_started = time.perf_counter()- # Before the import, not just before uvicorn: this is what makes us visible- # to a sibling's own probe, and the earlier it lands the smaller the window- # in which two launches can each believe they are alone.- #- # The cache env has to be seeded first. main.py pins UNSLOTH_COMPILE_LOCATION- # at import time, which is after this point, and that variable is part of the- # coordination key: publishing before it is set would key the marker and the- # lock differently from the clear that follows, and serialize nothing.+ # Before the import, not just before uvicorn: this is what makes us visible to a sibling's own probe, and+ # the earlier it lands the smaller the window in which two launches can each believe they are alone. The+ # cache env has to be seeded first: main.py pins UNSLOTH_COMPILE_LOCATION at import time, which is after+ # this point, and that variable is part of the coordination key.try:from utils.paths.storage_roots import setup_cache_envsetup_cache_env()@@ -2739,9 +2452,8 @@ def run_server(from main import app, setup_frontend, _desktop_owner, _IS_COLAB- # Handed to lifespan as a callable, not a value: it is asked again at- # shutdown, when a sibling may have started since. On app.state rather than- # imported, because main.py must not import this module back.+ # Handed to lifespan as a callable, not a value: it is asked again at shutdown, when a sibling may have+ # started since. On app.state rather than imported, because main.py must not import this module back.app.state.live_sibling_backend = live_sibling_backendlogger.info(@@ -2752,14 +2464,13 @@ def run_server(print(" - Starting server...", flush = True)from utils.paths import ensure_studio_directories- # Allow local stdio MCP servers on a loopback bind (the user's own machine),- # but never on Colab, which is a hosted VM reachable through its proxy. The- # gate reads the env var at request time, so this need not precede the import.+ # Allow local stdio MCP servers on a loopback bind (the user's own machine), but never on Colab, which is a+ # hosted VM reachable through its proxy. The gate reads the env var at request time, so this need not+ # precede the import.from utils.host_policy import apply_stdio_mcp_loopback_defaultapply_stdio_mcp_loopback_default(host, is_colab = _IS_COLAB)- # Create all standard directories on startup.ensure_studio_directories()logger.info(@@ -2767,12 +2478,10 @@ def run_server((time.perf_counter() - boot_started) * 1000,)- # Auto-find a free port if the requested one is in use.original_port = port- # Refusing rather than falling back is for callers that cannot follow us to- # the new port. `studio run` reads app.state.server_port back and the desktop- # app reads TAURI_PORT, so both should keep the plain fallback; only the- # bare launch, which has nothing but the banner, benefits from the refusal.+ # Refusing rather than falling back is for callers that cannot follow us to the new port. `studio run` reads+ # app.state.server_port back and the desktop app reads TAURI_PORT, so both keep the plain fallback; only+ # the bare launch benefits from the refusal.if abort_if_own_studio is None:abort_if_own_studio = not api_onlyport = _resolve_port(host, port, avoid_own_studio = abort_if_own_studio)@@ -2810,8 +2519,8 @@ def run_server(display = chosenprint(f"[OK] Frontend loaded from {display}")elif not _missing_frontend_is_fatal(tunnel_only = _tunnel_only_frontend):- # Remote access serves nothing; the local API the desktop asked for- # still comes up. The tunnel gate already 404s every other request.+ # Remote access serves nothing; the local API the desktop asked for still comes up. The tunnel gate+ # already 404s every other request.logger.warning("No frontend build found, so Remote and LAN access will not serve the web UI. ""Tried: %s",@@ -2842,9 +2551,8 @@ def run_server("Fix one of:\n"f" - run the installer's binary directly: {installer_bin} studio\n"+ (- # An Application Control policy can block the generated- # unsloth.exe while the signed interpreter beside it still- # runs, so name a route that does not go through it.+ # An Application Control policy can block the generated unsloth.exe while the signed interpreter beside+ # it still runs, so name a route that does not go through it.f" - or through the interpreter: {sys.executable} -I -m unsloth_cli studio\n"if sys.platform == "win32"else ""@@ -2854,13 +2562,12 @@ def run_server(" - reinstall: curl -fsSL https://unsloth.ai/install.sh | sh")- # For the banner and the reachability probe; the startup log line resolves- # its own, LAN-only, answer.+ # For the banner and the reachability probe; the startup log line resolves its own, LAN-only, answer.display_host = _display_host_for_bind(host)_install_uvicorn_startup_log_rewrite(host)- # LoggingMiddleware already logs every unhandled request exception with its full- # traceback as a structured event; without this uvicorn prints the same traceback- # again on stderr and the desktop shell copies it into tauri.log line by line.+ # LoggingMiddleware already logs every unhandled request exception with its full traceback as a structured+ # event; without this uvicorn prints the same traceback again on stderr and the desktop shell copies it+ # into tauri.log line by line.install_uvicorn_duplicate_exception_filter()logger.info(@@ -2883,10 +2590,10 @@ def run_server(ready_event.set()# server_header=False suppresses uvicorn's "Server: uvicorn"; SecurityHeadersMiddleware sets its own.- # http=... is uvicorn's own h11 protocol unless we are on the plain-h11 path, where it- # becomes a subclass that ignores socket reads delivered after the connection was already- # closed. Without it every clean shutdown on Windows ends in an h11 LocalProtocolError- # traceback that reads as a crash; see utils/uvicorn_h11_shutdown.py for the full sequence.+ # http=... is uvicorn's own h11 protocol unless we are on the plain-h11 path, where it becomes a subclass+ # that ignores socket reads delivered after the connection was already closed. Without it every clean+ # shutdown on Windows ends in an h11 LocalProtocolError traceback that reads as a crash; see+ # utils/uvicorn_h11_shutdown.py.from utils.uvicorn_h11_shutdown import uvicorn_http_protocolconfig_kwargs = dict(@@ -2897,10 +2604,8 @@ def run_server(server_header = False,http = uvicorn_http_protocol(),)- # Colab only: trust X-Forwarded-* from Colab's reverse proxy so the app sees- # the real https origin. forwarded_allow_ips="*" is safe in Colab's- # single-user sandbox but too lax for local/standalone, so leave uvicorn's- # loopback-only default elsewhere.+ # Colab only: trust X-Forwarded-* from Colab's reverse proxy so the app sees the real https origin.+ # forwarded_allow_ips="*" is safe in Colab's single-user sandbox but too lax for local/standalone.if _IS_COLAB:config_kwargs["proxy_headers"] = Trueconfig_kwargs["forwarded_allow_ips"] = "*"@@ -2908,12 +2613,11 @@ def run_server(_server = _ReadyServer(config)_shutdown_event = Event()- # Expose the actual bound port so handlers build loopback URLs at the real- # backend, not whatever a proxy/tunnel exposed. For ephemeral binds (port==0)- # leave it unset so handlers fall back to the request scope / base_url.+ # Expose the actual bound port so handlers build loopback URLs at the real backend, not whatever a+ # proxy/tunnel exposed. For ephemeral binds (port==0) leave it unset so handlers fall back to the request+ # scope / base_url.app.state.server_port = port if port and port > 0 else Noneapp.state.server_request_host = None- # Direct (non-tunnel) base for the API panel; resolve wildcard binds to the LAN IP.app.state.server_url = _direct_server_url(host, port)# raw bind address: the keyless exposure warning must tell loopback from a wildcard bindapp.state.bind_host = host@@ -2952,8 +2656,8 @@ def run_server(frontend_served = _serve_frontend and _frontend_mounted,)- # Expose a shutdown callable before the server accepts requests so- # /api/shutdown is ready as soon as readiness publishes.+ # Expose a shutdown callable before the server accepts requests so /api/shutdown is ready as soon as+ # readiness publishes.def _trigger_shutdown():_graceful_shutdown(_server)if _shutdown_event is not None:@@ -2961,14 +2665,13 @@ def run_server(app.state.trigger_shutdown = _trigger_shutdown- # A supplied --password / UNSLOTH_STUDIO_PASSWORD / stdin sets the initial- # admin password before the gate and socket bind (direct `python run.py`;- # the CLI applies it in its own parent).+ # A supplied --password / UNSLOTH_STUDIO_PASSWORD / stdin sets the initial admin password before the+ # gate and socket bind (direct `python run.py`; the CLI applies it in its own parent)._apply_supplied_password(password)- # Never publish with the seeded default password active: prompt first (or- # warn / fail closed headless; see _terminal_password_gate). Runs BEFORE the- # socket binds so a pre-gate listener can't hand out the injected credential.+ # Never publish with the seeded default password active: prompt first (or warn / fail closed headless; see+ # _terminal_password_gate). Runs BEFORE the socket binds so a pre-gate listener cannot hand out the+ # injected credential._pw_proceed, _pw_drop_bootstrap = _terminal_password_gate(tunnel_will_start = _launch_tunnel_managed,host = host,@@ -2986,9 +2689,8 @@ def run_server()sys.exit(1)if _pw_drop_bootstrap:- # Password just changed (stale) or a public URL is about to serve the- # default credential: don't leak it in the HTML. Lifespan runs AFTER this- # and re-reads the bootstrap password, so the flag (not a plain None)+ # Password just changed (stale) or a public URL is about to serve the default credential: do not leak it in+ # the HTML. Lifespan runs AFTER this and re-reads the bootstrap password, so the flag (not a plain None)# makes it skip that re-read.app.state.suppress_bootstrap_injection = Trueapp.state.bootstrap_password = None@@ -2997,9 +2699,8 @@ def run_server(open_studio_tunnel_lifecycle()- # Run server in a daemon thread with explicit new_event_loop() +- # run_until_complete() (not asyncio.run) so nest_asyncio's patches don't- # interfere when Colab/IPython already runs a loop on the main thread.+ # Run server in a daemon thread with explicit new_event_loop() + run_until_complete() (not asyncio.run) so+ # nest_asyncio's patches do not interfere when Colab/IPython already runs a loop on the main thread.def _run():loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)@@ -3014,16 +2715,14 @@ def run_server(loop.close()if not ready_event.is_set():startup_failed.set()- # An embedded host stays alive after the server thread ends, and a- # post-readiness failure in here never reaches run_server's caller,- # so nothing else takes these back. They would keep validating- # against the still-live host PID with no backend serving. This is- # also the point at which the backend has genuinely stopped serving,- # which is why the marker goes here rather than in _remove_pid_file.+ # An embedded host stays alive after the server thread ends, and a post-readiness failure in here never+ # reaches run_server's caller, so nothing else takes these back: they would keep validating against the+ # still-live host PID with no backend serving. This is also the point at which the backend has genuinely+ # stopped serving, which is why the marker goes here rather than in _remove_pid_file._remove_startup_marker()_remove_pid_file()- # the loop is closed above, so this is what an embedded host that calls- # run_server again needs to stop seeing the previous listener as live+ # The loop is closed above, so this is what an embedded host that calls run_server again needs to stop+ # seeing the previous listener as live.from lan_access import close_lan_listener_lifecycle as _close_lan_listener_close_lan_listener()@@ -3049,8 +2748,8 @@ def run_server(_server_thread = threadthread.start()- # Wait until uvicorn finishes lifespan startup and binds sockets, or until it- # exits/fails first. No deadline: a slow but live startup stays in progress.+ # Wait until uvicorn finishes lifespan startup and binds sockets, or until it exits/fails first. No+ # deadline: a slow but live startup stays in progress.try:while not ready_event.is_set():if startup_failed.is_set() or not thread.is_alive():@@ -3093,14 +2792,13 @@ def run_server(# check and adopts a child the sweep has already gone past.atexit.register(mark_process_shutting_down)- # Output port for Tauri (api-only), only after sockets bind and startup done.- # The headless `run --api-only` path opts out so it does not leak this line.+ # Output port for Tauri (api-only), only after sockets bind and startup is done. The headless+ # `run --api-only` path opts out so it does not leak this line.if api_only and emit_tauri_port:print(f"TAURI_PORT={port}", flush = True)- # Desktop-owned backends only (the owner env handshake): a headless- # `unsloth studio --api-only` has no app to bind its lifetime to and- # must survive its terminal (e.g. nohup). If the app dies without- # running its cleanup, exit instead of orphaning on the port.+ # Desktop-owned backends only (the owner env handshake): a headless `unsloth studio --api-only` has no app+ # to bind its lifetime to and must survive its terminal (e.g. nohup). If the app dies without running its+ # cleanup, exit instead of orphaning on the port.from main import _desktop_ownerif _desktop_owner() is not None:from utils.parent_watchdog import start_parent_watchdog@@ -3121,9 +2819,9 @@ def run_server(app.state.remote_access_ready = Trueapp.state.lan_access_ready = True- # Free trycloudflare.com tunnel for wildcard binds (the raw ip:port is often- # unreachable). Started pre-banner and even when silent so the CLI banner can- # read app.state.cloudflare_url; torn down by _graceful_shutdown.+ # Free trycloudflare.com tunnel for wildcard binds (the raw ip:port is often unreachable). Started+ # pre-banner and even when silent so the CLI banner can read app.state.cloudflare_url; torn down by+ # _graceful_shutdown._cloudflare_enabled = _launch_tunnel_managed_cloudflare_requested = _cloudflare_enabled@@ -3143,8 +2841,8 @@ def run_server(atexit.register(close_studio_tunnel_lifecycle)- # --secure fails closed: no tunnel means no public link, so exit rather than- # silently fall back to a raw port.+ # --secure fails closed: no tunnel means no public link, so exit rather than silently fall back to a+ # raw port.if secure and not _cloudflare_url:print("A secure Cloudflare link is not allowed, use --no-secure which provides a 0.0.0.0 link",@@ -3154,10 +2852,9 @@ def run_server(_graceful_shutdown(_server)sys.exit(1)- # Time-box a freshly-exposed web UI: if nobody changes the seeded admin- # password within the deadline (default 1h), shut down rather than leave an- # unsecured public instance running. No-op for loopback, --api-only, Colab,- # an already-changed password, or UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0.+ # Time-box a freshly-exposed web UI: if nobody changes the seeded admin password within the deadline+ # (default 1h), shut down rather than leave an unsecured public instance running. No-op for loopback,+ # --api-only, Colab, an already-changed password, or UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0.try:from auth import storage as _auth_storagefrom auth.bootstrap_timeout import (@@ -3217,11 +2914,8 @@ def run_server(def _build_arg_parser():- """Build the backend CLI argument parser.-- Extracted from the __main__ block so the flag wiring (notably the- --secure/--no-secure polarity and its --not-secure alias) stays unit-testable.- """+ """Build the backend CLI argument parser, extracted from the __main__ block so the flag wiring+ (notably the --secure/--no-secure polarity and its --not-secure alias) stays unit-testable."""import argparseparser = argparse.ArgumentParser(description = "Run Unsloth UI Backend server")@@ -3282,9 +2976,8 @@ def _build_arg_parser():default = argparse.SUPPRESS,help = argparse.SUPPRESS,)- # Tri-state tool policy: no flag -> None (tools default on, a request's own- # enable_tools: false honored);- # --enable-tools/--disable-tools force on/off.+ # Tri-state tool policy: no flag means None (tools default on, a request's own enable_tools: false+ # honored); --enable-tools/--disable-tools force on/off.parser.add_argument("--enable-tools",dest = "enable_tools",@@ -3327,10 +3020,8 @@ def _build_arg_parser():# For direct execution (also invoked by CLI via os.execvp / subprocess).if __name__ == "__main__":- # Correct a conflicting system CUDA on LD_LIBRARY_PATH before torch is- # imported (below, via run_server). Re-execs once on Linux so the dynamic- # linker uses torch's bundled CUDA libs; no-op on other platforms, when- # LD_LIBRARY_PATH is unset or already correct, or after the single re-exec.+ # Correct a conflicting system CUDA on LD_LIBRARY_PATH before torch is imported (below, via run_server).+ # Re-execs once on Linux so the dynamic linker uses torch's bundled CUDA libs._maybe_reexec_for_cuda_ld_path()import signal@@ -3383,7 +3074,6 @@ if __name__ == "__main__":sys.stderr.flush()sys.exit(1)- # Signal handler -- ensures subprocess cleanup on Ctrl+C.def _signal_handler(signum, frame):# Restore defaults so a second signal force-quits if shutdown stalls.signal.signal(signal.SIGINT, signal.SIG_DFL)@@ -3400,18 +3090,16 @@ if __name__ == "__main__":if hasattr(signal, "SIGBREAK"):signal.signal(signal.SIGBREAK, _signal_handler)- # NOT _signal_handler: Windows runs this on a thread it creates, and- # signal.signal() off the main thread raises, which would leave the window- # close doing no cleanup at all.+ # NOT _signal_handler: Windows runs this on a thread it creates, and signal.signal() off the main thread+ # raises, which would leave the window close doing no cleanup at all.def _console_shutdown():_graceful_shutdown(_server)_shutdown_event.set()_install_windows_console_handler(_console_shutdown)- # Keep running until shutdown signal. Event.wait() without a timeout blocks at- # the C level on Linux, preventing SIGINT delivery; a short timeout in a loop- # lets the interpreter process pending signals.+ # Keep running until shutdown signal. Event.wait() without a timeout blocks at the C level on Linux,+ # preventing SIGINT delivery; a short timeout in a loop lets the interpreter process pending signals.while not _shutdown_event.is_set():_shutdown_event.wait(timeout = 1)_wait_for_server_shutdown()diff --git a/studio/backend/startup_banner.py b/studio/backend/startup_banner.pyindex a6c6bc47bdc..45339fc84ce 100644--- a/studio/backend/startup_banner.py+++ b/studio/backend/startup_banner.py@@ -1,10 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Terminal banner for Unsloth startup.--Stdlib only -- safe to import without the rest of the backend.-"""+"""Terminal banner for Unsloth startup. Stdlib only -- safe to import without the rest of the backend."""from __future__ import annotations@@ -83,19 +80,14 @@ def print_studio_access_banner(include_stop_hint: bool = True,lan_addresses: "tuple[str, ...]" = (),) -> None:- """Pretty-print URLs once the server is listening. Set- ``include_stop_hint=False`` to omit the trailing stop block; pair with- :func:`print_studio_stop_hint` after inserting your own content.-- ``lan_addresses`` are the addresses a runtime LAN listener (Settings > LAN- access) is already serving on. A loopback launch that carries one is not- reachable on this machine only, so the banner must say where else it answers.-- ``network_host`` is the address printed under "another device on your- network", defaulting to ``display_host``. A wildcard-bind caller passes both:- ``display_host`` can be a public WAN IP, which is the reachability probe's- business and not what a LAN peer can open (#8868).- """+ """Pretty-print URLs once the server is listening. Set ``include_stop_hint=False`` to omit the+ trailing stop block; pair with :func:`print_studio_stop_hint` after inserting your own content.+ ``lan_addresses`` are the addresses a runtime LAN listener (Settings > LAN access) is already+ serving on. A loopback launch that carries one is not reachable on this machine only, so the+ banner must say where else it answers. ``network_host`` is the address printed under "another+ device on your network", defaulting to ``display_host``. A wildcard-bind caller passes both:+ ``display_host`` can be a public WAN IP, which is the reachability probe's business and not what+ a LAN peer can open (#8868)."""use_color = stdout_supports_color()dim = "\033[38;5;245m"title = "\033[38;5;150m"diff --git a/studio/backend/storage/api_usage_db.py b/studio/backend/storage/api_usage_db.pyindex 4d8777ba8f1..60304f9b0b8 100644--- a/studio/backend/storage/api_usage_db.py+++ b/studio/backend/storage/api_usage_db.py@@ -138,11 +138,9 @@ def _insert_api_usage(receipt: ApiUsageReceipt) -> bool:def record_api_usage(receipt: ApiUsageReceipt) -> bool:- """Insert one external request receipt, returning whether a row was added.-- The monitor id is the idempotency key, so repeated completion notification- cannot inflate profile totals. Invalid or zero-usage receipts are ignored.- """+ """Insert one external request receipt, returning whether a row was added. The monitor id is the+ idempotency key, so repeated completion notification cannot inflate profile totals. Invalid or+ zero-usage receipts are ignored."""if receipt.kind != "request" or receipt.via_api_key is not True:return Falsecounts = (receipt.prompt_tokens, receipt.completion_tokens, receipt.total_tokens)@@ -201,12 +199,9 @@ class ApiUsageWriter:return Truedef stop(self, timeout: float = _WORKER_DRAIN_TIMEOUT_SECONDS) -> bool:- """Stop accepting receipts and wait boundedly for the queue to drain.-- Returns ``True`` once the daemon consumed the stop sentinel. On timeout,- the daemon keeps retrying the already accepted head receipt and exits- after it succeeds and drains the remaining queue.- """+ """Stop accepting receipts and wait boundedly for the queue to drain. Returns ``True`` once the+ daemon consumed the stop sentinel. On timeout, the daemon keeps retrying the already+ accepted head receipt and exits after it succeeds and drains the remaining queue."""with self._state_lock:if not self._stopped:self._stopped = True@@ -239,10 +234,9 @@ class ApiUsageWriter:if not _is_busy_error(exc):logger.warning("api usage receipt persistence failed", exc_info = True)break- # record_api_usage already made its bounded fast retries: retain this accepted item at- # the head of- # the single writer until a long transaction releases SQLite, with the stop sentinel behind it- # so final shutdown drains rather than silently dropping usage.+ # record_api_usage already made its bounded fast retries: retain this accepted item at the head of+ # the single writer until a long transaction releases SQLite, with the stop sentinel behind it so+ # final shutdown drains rather than silently dropping usage.busy_failures += 1if busy_failures == 1 or busy_failures % 20 == 0:logger.warning(@@ -283,10 +277,8 @@ def enqueue_api_usage(receipt: ApiUsageReceipt) -> None:def release_api_usage_writer(lease: str) -> None:- """Release one lifespan and boundedly drain after the last owner exits.-- A timed-out daemon retains its accepted queue, but the global gate is always- cleared so a successor lifespan can start a fresh writer.+ """Release one lifespan and boundedly drain after the last owner exits. A timed-out daemon retains its+ accepted queue, but the global gate is always cleared so a successor lifespan can start a fresh writer."""global _writer, _writer_stoppingwriter = Nonediff --git a/studio/backend/storage/chat_generation_runs_db.py b/studio/backend/storage/chat_generation_runs_db.pyindex fcb097d30bd..e7dd4edd2f4 100644--- a/studio/backend/storage/chat_generation_runs_db.py+++ b/studio/backend/storage/chat_generation_runs_db.py@@ -167,12 +167,10 @@ def _append_events_locked(def _missing_lease_columns(exc: sqlite3.OperationalError) -> bool:- """Whether `exc` is this database still waiting on the progress-lease migration.-- _connect lets a call through when contention blocks the ALTER, so every statement- naming progress_at or progress_tokens can meet a table that predates them. Degrading- to the pre-migration behaviour keeps that window harmless: without it a blocked- migration would abort a generation with `no such column` the moment the writer let go.+ """Whether `exc` is this database still waiting on the progress-lease migration. _connect lets a call through+ when contention blocks the ALTER, so every statement naming progress_at or progress_tokens can meet a table+ that predates them. Degrading to the pre-migration behaviour keeps that window harmless: without it a+ blocked migration would abort a generation with `no such column` the moment the writer let go."""message = str(exc).lower()return "no such column" in message and (@@ -181,20 +179,15 @@ def _missing_lease_columns(exc: sqlite3.OperationalError) -> bool:def _touch_progress_locked(conn: sqlite3.Connection, run_id: str, tokens: int) -> None:- """Stamp the progress lease for one flush of streamed output.-- Monotonic in both fields, the same rule studio_db._safe_generation_assistant_update- applies to the assistant row this run owns: the token counter only ever accumulates,- and progress_at takes MAX(stored, now) so a wall-clock step backwards (NTP, suspend)- cannot age a live run into the sweep below. One chunk carries at most one token- delta, so the count of chunk events is the token count.-- updated_at moves with it, as it already does on every event append. That is what the- follower's snapshot poll compares, so a client watching a run through a long model- preparation or an admission wait, neither of which emits events, sees the server is- alive and rearms its own no-progress deadline instead of reporting an interruption- over healthy work.- """+ """Stamp the progress lease for one flush of streamed output. Monotonic in both fields, the same+ rule studio_db._safe_generation_assistant_update applies to the assistant row this run owns: the+ token counter only ever accumulates, and progress_at takes MAX(stored, now) so a wall-clock step+ backwards (NTP, suspend) cannot age a live run into the sweep below. One chunk carries at most+ one token delta, so the count of chunk events is the token count. updated_at moves with it, as+ it already does on every event append. That is what the follower's snapshot poll compares, so a+ client watching a run through a long model preparation or an admission wait, neither of which+ emits events, sees the server is alive and rearms its own no-progress deadline instead of+ reporting an interruption over healthy work."""now = now_ms()try:conn.execute(@@ -469,13 +462,10 @@ def get_worker_run(def touch_progress(run_id: str) -> None:- """Renew one run's progress lease without recording any streamed output.-- For work the lease cannot see. Automatic model loading, idle reload and auto-download- all happen between mark_running and the first token, and the engine's own first-token- budget does not start until after them, so ageing a run from mark_running could reap a- legitimate load followed by a legitimate prefill.- """+ """Renew one run's progress lease without recording any streamed output. For work the lease cannot+ see: automatic model loading, idle reload and auto-download all happen between mark_running and+ the first token, and the engine's own first-token budget does not start until after them, so+ ageing a run from mark_running could reap a legitimate load followed by a legitimate prefill."""conn = _connect()try:_touch_progress_locked(conn, run_id, 0)@@ -748,16 +738,12 @@ def wait_for_events(def reconcile_runs(*, error: str = "Studio restarted during generation", stale_after_ms: int | None = None) -> list[str]:- """Settle active runs, returning the ids settled.-- ``stale_after_ms`` is what makes this safe to run while Studio is serving: with it,- only runs whose progress lease has not moved for that long are settled, so a slow- but advancing generation is never touched. Without it (process boot) every active- run is orphaned by definition and all of them are settled.-- Partial output survives either way: only the run row and the assistant message's- status metadata are rewritten, never the streamed content or the event log.- """+ """Settle active runs, returning the ids settled. ``stale_after_ms`` is what makes this safe to run+ while Studio is serving: with it, only runs whose progress lease has not moved for that long are+ settled, so a slow but advancing generation is never touched. Without it (process boot) every+ active run is orphaned by definition and all of them are settled. Partial output survives either+ way: only the run row and the assistant message's status metadata are rewritten, never the+ streamed content or the event log."""conn = _connect()settled: list[str] = []try:@@ -777,8 +763,8 @@ def reconcile_runs(if not _missing_lease_columns(exc):raise# Contention blocked the migration, so falling back to started_at/created_at is the opposite of- # conservative: those stamps are older by the whole life of the run, so one that streamed moments- # ago is reaped once its total AGE passes the timeout. Boot reconcile passes no stale_after_ms.+ # conservative: those stamps are older by the whole life of the run, so one that streamed moments ago is+ # reaped once its total AGE passes the timeout. Boot reconcile passes no stale_after_ms.if stale_after_ms is not None:conn.rollback()return []diff --git a/studio/backend/storage/credential_secrets.py b/studio/backend/storage/credential_secrets.pyindex 77d5eac57a2..fc45fff247f 100644--- a/studio/backend/storage/credential_secrets.py+++ b/studio/backend/storage/credential_secrets.py@@ -1,11 +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-"""Encrypted installation-wide credential persistence in ``studio.db``.--Unsloth is a single-user local application. Credentials belong to the installation,-not to an authenticated subject. The AES key lives separately in auth.db and the-credential kind/scope are authenticated so ciphertext rows cannot be swapped.+"""Encrypted installation-wide credential persistence in ``studio.db``. Unsloth is a single-user local+application, so credentials belong to the installation, not to an authenticated subject. The AES key lives+separately in auth.db and the credential kind/scope are authenticated so ciphertext rows cannot be swapped."""from __future__ import annotationsdiff --git a/studio/backend/storage/profile_stats_db.py b/studio/backend/storage/profile_stats_db.pyindex bed1101034f..d8819293852 100644--- a/studio/backend/storage/profile_stats_db.py+++ b/studio/backend/storage/profile_stats_db.py@@ -1,22 +1,17 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""-Profile usage statistics derived from studio.db.--Read-only aggregation over chat threads/messages (with their per-message-``metadata_json``), content-free API usage receipts, and training runs/metrics.-The numbers are only as complete as the local history retained after each-feature was introduced.+"""Profile usage statistics derived from studio.db.-Chat and training tables predate authenticated subjects and therefore remain-install-wide. API usage receipts are filtered to the requesting subject.+Read-only aggregation over chat threads/messages (with their per-message ``metadata_json``), content-free API+usage receipts, and training runs/metrics. The numbers are only as complete as the local history retained after+each feature was introduced. Chat and training tables predate authenticated subjects and therefore remain+install-wide; API usage receipts are filtered to the requesting subject.-Token counts live inside each message's metadata blob, so they cannot be summed-in SQL portably (JSON1 is not guaranteed on every bundled SQLite). Rows are-streamed once in (thread, time) order and every metric is folded in that single-pass, then memoised against per-source count/timestamp fingerprints so reopening-the Profile tab is free until history changes.+Token counts live inside each message's metadata blob, so they cannot be summed in SQL portably (JSON1 is not+guaranteed on every bundled SQLite). Rows are streamed once in (thread, time) order and every metric is folded+in that single pass, then memoised against per-source count/timestamp fingerprints so reopening the Profile tab+is free until history changes."""import json@@ -52,10 +47,8 @@ _cache: dict[str, Any] = {"fingerprint": None, "expires_at": 0.0, "payload": Nondef _as_float(value: Any) -> Optional[float]:- """Coerce JSON numbers defensively; metadata is written by the client.-- json accepts integers of any width, and float() raises OverflowError past- ~1e308, so one oversized counter would 500 the whole panel.+ """Coerce JSON numbers defensively; metadata is written by the client. json accepts integers of any width,+ and float() raises OverflowError past ~1e308, so one oversized counter would 500 the whole panel."""if isinstance(value, bool) or value is None:return None@@ -84,13 +77,10 @@ def _clean_str(value: Any) -> str:def _resolve_zone(tz_name: str, tz_offset_minutes: int):- """The caller's zone, preferring an IANA name over a single offset.-- A fixed offset is only correct for the half of the year the caller happens- to be in, so a winter message read during summer lands an hour out and can- cross midnight. An IANA name carries each date's own offset. The offset- stays as the fallback for callers that send no name, or hosts with no tzdata.- """+ """The caller's zone, preferring an IANA name over a single offset. A fixed offset is only correct+ for the half of the year the caller happens to be in, so a winter message read during summer+ lands an hour out and can cross midnight. An IANA name carries each date's own offset. The+ offset stays as the fallback for callers that send no name, or hosts with no tzdata."""if tz_name:try:return ZoneInfo(tz_name)@@ -100,12 +90,9 @@ def _resolve_zone(tz_name: str, tz_offset_minutes: int):def _local_stamp(created_at_ms: int, zone) -> Optional[datetime]:- """Wall-clock time in the caller's timezone, not the server's.-- created_at is a client-supplied integer that SQLite stores unchecked, so a- value outside datetime's range is possible. Drop that row rather than let- one bad import take down the whole panel.- """+ """Wall-clock time in the caller's timezone, not the server's. created_at is a client-supplied+ integer that SQLite stores unchecked, so a value outside datetime's range is possible. Drop that+ row rather than let one bad import take down the whole panel."""if created_at_ms <= 0:return Nonetry:@@ -115,15 +102,10 @@ def _local_stamp(created_at_ms: int, zone) -> Optional[datetime]:def _streaks(days: set[date], today: date) -> dict[str, Any]:- """Current and longest run of consecutive active days.-- The current streak survives a day that has not been used yet: a streak that- ended yesterday is still "live" until today is over.-- Imported history or a skewed client clock can date rows in the future.- Those are dropped up front so they cannot pad the longest streak or be- reported as the last active day either.- """+ """Current and longest run of consecutive active days. The current streak survives a day that has+ not been used yet: a streak that ended yesterday is still "live" until today is over. Imported+ history or a skewed client clock can date rows in the future; those are dropped up front so they+ cannot pad the longest streak or be reported as the last active day either."""days = {day for day in days if day <= today}if not days:return {"current": 0, "longest": 0, "lastActiveDay": None}@@ -262,18 +244,13 @@ def _merge_api_activity(chat: _MessageFold, api: _ApiUsageFold) -> None:def _fork_keepers(conn) -> dict[tuple[str, int, str], str]:- """For each original message, the one clone elected to stand in for it.-- A clone is normally ignored because the original is counted instead. Once- the original is gone, whether its thread was deleted or just that row was- pruned, the clones become the only record. Letting every sibling count them- would multiply the usage, so exactly one may.-- Electing per message rather than per fork matters because fork_chat_thread- copies one parent_id branch, not the whole thread: sibling forks taken from- a retry and a regeneration hold different rows, and a per-fork winner would- silently drop whatever only the loser carries.- """+ """For each original message, the one clone elected to stand in for it. A clone is normally ignored+ because the original is counted instead. Once the original is gone, whether its thread was+ deleted or just that row was pruned, the clones become the only record. Letting every sibling+ count them would multiply the usage, so exactly one may. Electing per message rather than per+ fork matters because fork_chat_thread copies one parent_id branch, not the whole thread: sibling+ forks taken from a retry and a regeneration hold different rows, and a per-fork winner would+ silently drop whatever only the loser carries."""rows = conn.execute("""SELECT m.thread_id, m.created_at, m.role,@@ -297,11 +274,9 @@ def _fork_keepers(conn) -> dict[tuple[str, int, str], str]:def _surviving_original_keys(conn) -> set[tuple[str, int, str]]:- """Identity of every message still living in a thread that has been forked.-- Clones get fresh ids, so there is nothing to join on. Within one thread the- timestamp and role are enough to recognise the row a clone was taken from.- """+ """Identity of every message still living in a thread that has been forked. Clones get fresh ids,+ so there is nothing to join on. Within one thread the timestamp and role are enough to recognise+ the row a clone was taken from."""rows = conn.execute("""SELECT m.thread_id, m.created_at, m.role@@ -489,28 +464,18 @@ def _daily_series(fold: _MessageFold, today: date, days: int) -> list[dict[str,def _superseded(prefix: str = "r.") -> str:- """SQL for "a later run resumed from this one, so its counters live there".-- ``prefix`` must qualify the outer row: the EXISTS subquery selects from the- same table, so a bare column name would bind to the subquery instead.-- ``create_run``'s resume claim sets ``resume_blocked`` and leaves- ``output_dir`` alone. Cancelling clears ``output_dir`` while setting the- same flag, so the flag alone cannot tell the two apart.-- ``delete_run`` never clears the flag, so the continuation has to still be- there. Otherwise deleting it would strand the source at zero while its row- and metrics stay visible in history.-- The continuation also has to have reached the source's step. ``create_run``- claims the source the moment a resume starts, but ``final_step`` is only- written on the first metric flush, so a continuation that fails before then- would take the source's completed work down with it.-- ``resumed_from_run_id`` records the lineage outright. Runs written before- that column existed fall back to matching ``output_dir``, which is weaker:- cancelling a continuation nulls its ``output_dir`` and breaks the match.- """+ """SQL for "a later run resumed from this one, so its counters live there". ``prefix`` must qualify+ the outer row: the EXISTS subquery selects from the same table, so a bare column name would bind+ to the subquery instead. ``create_run``'s resume claim sets ``resume_blocked`` and leaves+ ``output_dir`` alone. Cancelling clears ``output_dir`` while setting the same flag, so the flag+ alone cannot tell the two apart. ``delete_run`` never clears the flag, so the continuation has+ to still be there; otherwise deleting it would strand the source at zero while its row and+ metrics stay visible in history. The continuation also has to have reached the source's step.+ ``create_run`` claims the source the moment a resume starts, but ``final_step`` is only written+ on the first metric flush, so a continuation that fails before then would take the source's+ completed work down with it. ``resumed_from_run_id`` records the lineage outright. Runs written+ before that column existed fall back to matching ``output_dir``, which is weaker: cancelling a+ continuation nulls its ``output_dir`` and breaks the match."""return f"""{prefix}resume_blocked = 1AND EXISTS (@@ -544,16 +509,15 @@ def _training_stats(conn) -> dict[str, Any]:""").fetchone()- # A resumed run continues its source's counters, so only a run superseded by a resume is dropped:- # create_run's claim sets resume_blocked while leaving output_dir intact, whereas cancelling- # clears it, so a cancelled run keeps the work it did do.+ # A resumed run continues its source's counters, so only a run superseded by a resume is dropped: create_run's+ # claim sets resume_blocked while leaving output_dir intact, whereas cancelling clears it, so a cancelled run+ # keeps the work it did do.steps = conn.execute(f"SELECT COALESCE(SUM(r.final_step), 0) FROM training_runs r WHERE NOT ({_superseded()})").fetchone()[0]- # num_tokens is state.num_input_tokens_seen, a running total logged at each step, so summing the- # samples multiplies the real figure; take each run's final counter, the value get_run_metrics- # reports.+ # num_tokens is state.num_input_tokens_seen, a running total logged at each step, so summing the samples+ # multiplies the real figure; take each run's final counter, the value get_run_metrics reports.tokens = conn.execute(f"""SELECT COALESCE(SUM(run_tokens), 0) FROM (@@ -638,12 +602,9 @@ def compute_profile_stats(*,subject: str = "",) -> dict[str, Any]:- """Aggregate profile statistics, subject-scoping only external API usage.-- Legacy Unsloth chat and training history is install-wide because those rows- have no authenticated owner. An empty subject intentionally sees no API- receipts, keeping non-route callers fail-closed.- """+ """Aggregate profile statistics, subject-scoping only external API usage. Legacy Unsloth chat and+ training history is install-wide because those rows have no authenticated owner. An empty+ subject intentionally sees no API receipts, keeping non-route callers fail-closed."""days = max(1, min(int(days), MAX_DAILY_DAYS))tz_offset_minutes = max(-MAX_TZ_OFFSET_MINUTES, min(int(tz_offset_minutes), MAX_TZ_OFFSET_MINUTES)diff --git a/studio/backend/storage/providers_db.py b/studio/backend/storage/providers_db.pyindex 55cb9a25461..a24c8da6b47 100644--- a/studio/backend/storage/providers_db.py+++ b/studio/backend/storage/providers_db.py@@ -3,12 +3,10 @@"""SQLite storage for external LLM provider configurations.-Same pattern as studio_db.py (module-level functions, raw sqlite3, WAL,-per-function connections). API keys are NOT stored here: they live only in-the browser (localStorage) and are sent encrypted per-request.--Enabled model selections and discovered catalog IDs are stored server-side so-remote Unsloth clients see the same connection state (#7281).+Same pattern as studio_db.py (module-level functions, raw sqlite3, WAL, per-function connections). API keys are+NOT stored here: they live only in the browser (localStorage) and are sent encrypted per-request. Enabled model+selections and discovered catalog IDs are stored server-side so remote Unsloth clients see the same connection+state (#7281)."""from __future__ import annotations@@ -106,12 +104,9 @@ def get_connection() -> sqlite3.Connection:@contextmanagerdef provider_bundle_transaction() -> Iterator[sqlite3.Connection]:- """Atomically mutate a provider row and its saved credentials.-- Provider metadata and encrypted credentials share ``studio.db``. A single- SQLite write transaction therefore prevents other processes from observing- a new endpoint with the previous key (or the inverse) while a provider edit- is in progress.+ """Atomically mutate a provider row and its saved credentials. Provider metadata and encrypted credentials+ share ``studio.db``, so a single SQLite write transaction prevents other processes from observing a new+ endpoint with the previous key (or the inverse) while a provider edit is in progress."""# Ensure both tables exist before opening the transaction. The credential module commits schema# initialization on its own connection.diff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.pyindex 1e53fda315f..956582131b6 100644--- a/studio/backend/storage/rag_db.py+++ b/studio/backend/storage/rag_db.py@@ -3,16 +3,14 @@"""SQLite storage for the RAG engine.-Same pattern as providers_db.py / studio_db.py (module functions, raw sqlite3,-WAL, per-call connections, lazy schema), but every connection also loads-sqlite-vec (vec0 needs it per-connection). If it cannot load, get_connection()-raises RagExtensionUnavailable rather than failing import, and rag_available()-reports the machine as one where RAG cannot run.--One rag.db holds the ``documents`` / ``chunks`` model, the FTS5 lexical index-(``chunks_fts``) and the sqlite-vec dense index (``chunks_vec``, created lazily-by ensure_vec once the embedding dim is known, since vec0 bakes the dim into the-column type).+Same pattern as providers_db.py / studio_db.py (module functions, raw sqlite3, WAL, per-call connections, lazy+schema), but every connection also loads sqlite-vec (vec0 needs it per-connection). If it cannot load,+get_connection() raises RagExtensionUnavailable rather than failing import, and rag_available() reports the+machine as one where RAG cannot run.++One rag.db holds the ``documents`` / ``chunks`` model, the FTS5 lexical index (``chunks_fts``) and the+sqlite-vec dense index (``chunks_vec``, created lazily by ensure_vec once the embedding dim is known, since vec0+bakes the dim into the column type)."""import logging@@ -38,11 +36,10 @@ _RAG_UNAVAILABLE_MSG = "RAG unavailable: sqlite-vec extension could not be loadeclass RagExtensionUnavailable(RuntimeError):- """sqlite-vec is installed but its native library will not load (a missing- vec0 binary in the venv is the common macOS case). Subclasses RuntimeError so- existing ``except RuntimeError`` callers are unaffected; it exists so a caller- can tell "RAG is switched off on this machine" from a real database error and- degrade instead of returning 500 on every poll."""+ """sqlite-vec is installed but its native library will not load (a missing vec0 binary in the venv is the+ common macOS case). Subclasses RuntimeError so existing ``except RuntimeError`` callers are unaffected; it+ exists so a caller can tell "RAG is switched off on this machine" from a real database error and degrade+ instead of returning 500 on every poll."""_schema_lock = threading.Lock()@@ -71,18 +68,14 @@ def _warn_unavailable_once(exc: BaseException | None = None) -> None:def rag_available() -> bool:- """Whether RAG can actually run in this process.-- RAG_AVAILABLE only records that ``import sqlite_vec`` worked. The vec0 native- library it loads is a separate file, and a venv can have the package without it- (the common macOS case), which nothing finds out until a connection tries. So try,- unless one already got through: a machine where RAG works answers from the flag- instead of opening a second connection per request, and a machine where it does not- pays the same failed connect it paid before, quietly.-- A genuine database error (locked, corrupt, bad schema) is not an answer to this- question, so it propagates instead of being reported as "RAG is off here".- """+ """Whether RAG can actually run in this process. RAG_AVAILABLE only records that ``import+ sqlite_vec`` worked. The vec0 native library it loads is a separate file, and a venv can have+ the package without it (the common macOS case), which nothing finds out until a connection+ tries. So try, unless one already got through: a machine where RAG works answers from the flag+ instead of opening a second connection per request, and a machine where it does not pays the+ same failed connect it paid before, quietly. A genuine database error (locked, corrupt, bad+ schema) is not an answer to this question, so it propagates instead of being reported as "RAG is+ off here"."""if not RAG_AVAILABLE:return Falseif _extension_loaded:@@ -96,9 +89,8 @@ def rag_available() -> bool:def _ensure_schema(conn: sqlite3.Connection) -> None:- """Create the RAG tables if absent (once per process). ``chunks_vec`` is- skipped: its column type needs the embedding dim, so ensure_vec() makes it- lazily at first ingest."""+ """Create the RAG tables if absent (once per process). ``chunks_vec`` is skipped: its column type needs the+ embedding dim, so ensure_vec() makes it lazily at first ingest."""conn.execute("PRAGMA journal_mode=WAL")conn.executescript("""@@ -265,9 +257,8 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:"CREATE INDEX IF NOT EXISTS idx_documents_archive_ordinal ""ON documents(scope, archive_ordinal) WHERE archive_ordinal IS NOT NULL")- # After the ALTER that adds the column on an older database. Partial, so it holds only- # folder-owned rows and is empty with nothing linked, which keeps the lexical fast-path gate an- # index probe rather than a scan.+ # After the ALTER that adds the column on an older database. Partial, so it holds only folder-owned rows and+ # is empty with nothing linked, which keeps the lexical fast-path gate an index probe rather than a scan.conn.execute("CREATE INDEX IF NOT EXISTS idx_documents_linked_folder ""ON documents(linked_folder_id) WHERE linked_folder_id IS NOT NULL"@@ -277,11 +268,9 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:def ensure_linked_folder_columns(conn: sqlite3.Connection) -> None:- """Add the linked-folder columns a database created by an earlier build is missing.-- Also called for the metadata connection, which skips _ensure_schema so that scope- retirement keeps working when the vector extension cannot load.- """+ """Add the linked-folder columns a database created by an earlier build is missing. Also called for+ the metadata connection, which skips _ensure_schema so that scope retirement keeps working when+ the vector extension cannot load."""job_cols = {r[1] for r in conn.execute("PRAGMA table_info(linked_folder_sync_jobs)").fetchall()}# the queued follow-up request; it replaced a flag that only recorded rebuildsif job_cols and "successor_kind" not in job_cols:@@ -335,12 +324,9 @@ def get_connection() -> sqlite3.Connection:def get_metadata_connection() -> sqlite3.Connection:- """Open rag.db without loading sqlite-vec.-- This connection is only for ordinary SQLite metadata tables. It lets lifecycle- tombstones remain writable when the optional native vector extension is temporarily- unavailable. Callers must not query or mutate the vec0 virtual table.- """+ """Open rag.db without loading sqlite-vec. This connection is only for ordinary SQLite metadata+ tables. It lets lifecycle tombstones remain writable when the optional native vector extension+ is temporarily unavailable. Callers must not query or mutate the vec0 virtual table."""db_path = rag_db_path()ensure_dir(db_path.parent)conn = sqlite3.connect(str(db_path))@@ -361,11 +347,10 @@ def vec_table_dim(conn: sqlite3.Connection) -> int | None:def ensure_vec(conn: sqlite3.Connection, dim: int) -> None:- """Create the dense ``chunks_vec`` table once the embedding dim is known- (vec0 bakes it into the column type). A width change (embedding model- switched in Settings) drops the table: the old vectors live in a foreign- space and would only block inserts, while lexical search keeps serving old- chunks until they are re-uploaded."""+ """Create the dense ``chunks_vec`` table once the embedding dim is known (vec0 bakes it into the column+ type). A width change (embedding model switched in Settings) drops the table: the old vectors live in a+ foreign space and would only block inserts, while lexical search keeps serving old chunks until they are+ re-uploaded."""existing = vec_table_dim(conn)if existing is not None and existing != int(dim):logger.warning(@@ -392,9 +377,9 @@ def vec_table_exists(conn: sqlite3.Connection) -> bool:def _delete_document_chunks(conn, document_id: str) -> None:- """Delete a document's chunk rows (chunks/chunks_fts/chunks_vec), keeping the- documents row. Used when reconciling a half-ingested doc to failed: retrieval- filters by scope not status, so leftover chunks would stay citable."""+ """Delete a document's chunk rows (chunks/chunks_fts/chunks_vec), keeping the documents row. Used when+ reconciling a half-ingested doc to failed: retrieval filters by scope not status, so leftover chunks would+ stay citable."""chunk_ids = [r["id"]for r in conn.execute(@@ -412,11 +397,9 @@ def _delete_document_chunks(conn, document_id: str) -> None:def reconcile_orphaned_ingestion_jobs() -> int:- """Fail ingestion jobs/documents left mid-flight by a crash so they stop- showing as stuck "processing" and become re-ingestible. Work owned by another- live backend is left alone until its lease expires. No-op without RAG. Returns- the number of jobs reset.- """+ """Fail ingestion jobs/documents left mid-flight by a crash so they stop showing as stuck+ "processing" and become re-ingestible. Work owned by another live backend is left alone until+ its lease expires. No-op without RAG. Returns the number of jobs reset."""# rag_available(), not RAG_AVAILABLE: a venv with the package but no vec0 binary would raise out of# startup and be logged as a reconcile failure when there is nothing to reconcile.if not rag_available():diff --git a/studio/backend/storage/research_runs_db.py b/studio/backend/storage/research_runs_db.pyindex 6f029541e89..ae4139345bc 100644--- a/studio/backend/storage/research_runs_db.py+++ b/studio/backend/storage/research_runs_db.py@@ -267,11 +267,9 @@ def create_run(def _unbind_assistant_locked(conn: sqlite3.Connection, previous_id: str | None, next_id: str | None) -> None:- """Drop the research binding from the reply the run is leaving behind.-- Both replies would otherwise carry the same run id, and each renders whatever that run is- doing now -- so the new question's live card would appear twice.- """+ """Drop the research binding from the reply the run is leaving behind. Both replies would otherwise+ carry the same run id, and each renders whatever that run is doing now, so the new question's+ live card would appear twice."""if not previous_id or previous_id == next_id:returnrow = conn.execute(@@ -308,11 +306,9 @@ def _stopped_run_locked(conn: sqlite3.Connection, thread_id: str) -> sqlite3.Rowdef research_spent(thread_id: str) -> bool:- """Whether the thread's research is used up, which is what the composer greys out on.-- The claim itself outlives a stopped run so the same run can be re-pointed, so a held- claim alone must not read as spent: after a Stop, research is still on offer.- """+ """Whether the thread's research is used up, which is what the composer greys out on. The claim+ itself outlives a stopped run so the same run can be re-pointed, so a held claim alone must not+ read as spent: after a Stop, research is still on offer."""conn = get_connection()try:claim = conn.execute(@@ -330,12 +326,10 @@ def rebind_cancelled(assistant_message_id: str | None,config: dict[str, Any],) -> dict | None:- """Re-point the thread's stopped run at a newer message, or return None.-- A thread holds one Deep Research run for its lifetime, so a run the user stopped would- otherwise refuse every later question in that chat. Stopping kept nothing, so the same- run is reset and pointed at the new message instead of a second one being created.- """+ """Re-point the thread's stopped run at a newer message, or return None. A thread holds one Deep+ Research run for its lifetime, so a run the user stopped would otherwise refuse every later+ question in that chat. Stopping kept nothing, so the same run is reset and pointed at the new+ message instead of a second one being created."""conn = get_connection()try:conn.execute("BEGIN IMMEDIATE")@@ -362,10 +356,10 @@ def rebind_cancelled(plan_revision = revision,created = now,)- # retry_count is the attempt epoch every event is stamped with, and a new question is a new- # attempt: without the bump its report would carry the stopped question's reasoning, since- # get_reasoning_text joins every event at the run's current attempt. The retry BUDGET is counted- # per question, so spending an epoch here spends no retry.+ # retry_count is the attempt epoch every event is stamped with, and a new question is a new attempt: without+ # the bump its report would carry the stopped question's reasoning, since get_reasoning_text joins every event+ # at the run's current attempt. The retry BUDGET is counted per question, so spending an epoch here spends no+ # retry.conn.execute("UPDATE research_runs SET user_message_id=?, assistant_message_id=?, ""status='planning', cancel_requested=0, plan_json=NULL, plan_hash=NULL, "@@ -786,8 +780,8 @@ def retry(run_id: str, max_retries: int = 3) -> str:if row["status"] not in {"failed", "cancelled"}:raise ResearchConflictError("Only failed or cancelled runs can be retried")# Counted per question, not per run row: a thread re-points one run at each new question, so a raw- # retry_count would hand a fresh question whatever the stopped one left over, and nothing at all- # once the budget was spent.+ # retry_count would hand a fresh question whatever the stopped one left over, and nothing at all once the+ # budget was spent.spent = conn.execute("SELECT COUNT(*) FROM research_events WHERE run_id=? AND event_type='run.retried' ""AND seq > COALESCE((SELECT MAX(seq) FROM research_events "@@ -855,11 +849,9 @@ _CLAIMABLE_SQL = """SELECT r.id FROM research_runs rdef _has_claimable(now: int) -> bool:- """Read-only probe for claimable work, taking no write lock.-- The supervisor polls twice a second forever and almost every poll finds nothing, so- opening BEGIN IMMEDIATE first meant an idle Studio held the writer lock 2x/second and- any slow writer elsewhere became a stream of "database is locked" here.+ """Read-only probe for claimable work, taking no write lock. The supervisor polls twice a second forever and+ almost every poll finds nothing, so opening BEGIN IMMEDIATE first meant an idle Studio held the writer lock+ 2x/second and any slow writer elsewhere became a stream of "database is locked" here."""conn = get_connection()try:diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex be5d0ef95ce..7b161ac1195 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -3,8 +3,8 @@"""SQLite storage for training run history and metrics.-Like auth/storage.py (module-level functions, raw sqlite3, per-function-connections) plus WAL mode and PRAGMA foreign_keys = ON for CASCADE deletes.+Like auth/storage.py (module-level functions, raw sqlite3, per-function connections) plus WAL mode+and PRAGMA foreign_keys = ON for CASCADE deletes."""import hashlib@@ -46,7 +46,6 @@ def _extract_project_name_from_config_json(config_json: Optional[str]) -> Optiondef _denied_path_prefixes() -> list[str]:- """Platform-aware denylist of system directories."""system = platform.system()if system == "Linux":return ["/proc", "/sys", "/dev", "/etc", "/boot", "/run"]@@ -74,11 +73,10 @@ def _denied_path_prefixes() -> list[str]:def is_denied_system_path(path: str) -> bool:"""True if *path* is, or descends from, a denied system directory.- Mirrors the denylist add_scan_folder() enforces at registration so the- browser refuses /etc, /proc, C:\\Windows, etc. even when the allowlist holds- a broad root (a Windows drive root C:\\ or a legacy-registered / root). The- /run carve-out keeps Linux removable-media mounts browseable. Expects an- already-resolved (realpath) path so symlinks cannot escape into a denied subtree.+ Mirrors the denylist add_scan_folder() enforces at registration, so the browser refuses /etc,+ /proc, C:\\Windows and the like even when the allowlist holds a broad root. The /run carve-out+ keeps Linux removable-media mounts browseable. Expects an already-resolved (realpath) path so+ symlinks cannot escape into a denied subtree."""is_win = platform.system() == "Windows"check = os.path.normcase(path) if is_win else path@@ -120,9 +118,8 @@ def _default_project_root(project: dict) -> str:class ProjectWorkspaceError(OSError):"""Raised when a project's workspace folder cannot be created.- Tagged, and carrying the folder, so a caller can name it. The same upsert- also touches the database directory, and that is a different path with a- different fix.+ Tagged, and carrying the folder, so a caller can name it: the same upsert also touches the+ database directory, which is a different path with a different fix."""def __init__(self, path: str, cause: OSError):@@ -144,12 +141,9 @@ def _ensure_project_workspace(root_path: str) -> str:def sandbox_is_referenced_elsewhere(session_id: str, exclude_thread_id: "str | None" = None) -> bool:- """Whether a surviving chat still shows file cards for this sandbox.-- Forking clones the message content verbatim, so the fork's cards keep the- source chat's session id. Deleting the source's files would leave those- cards downloading nothing, in a chat the user did not delete.- """+ """Whether a surviving chat still shows file cards for this sandbox. Forking clones the message+ content verbatim, so the fork's cards keep the source chat's session id, and deleting the+ source's files would leave those cards downloading nothing."""if not session_id:return Falseconn = get_connection()@@ -180,7 +174,6 @@ def sandbox_is_referenced_elsewhere(def _mentions_session(content_json: str, session_id: str) -> bool:- """Whether this message's content names *session_id* as a sandbox."""try:content = json.loads(content_json)except (TypeError, ValueError):@@ -204,12 +197,9 @@ def _like_escape(value: str) -> str:def delete_project_workspace(project: dict) -> None:- """Remove a deleted project's workspace directory.-- Separate from the row delete so the caller can stop the tool calls running- in there first: pulling the working directory out from under a live- subprocess is how a half-written file ends up outside any project.- """+ """Remove a deleted project's workspace directory. Separate from the row delete so the caller can+ stop the tool calls running in there first: pulling the working directory out from under a live+ subprocess is how a half-written file ends up outside any project."""_delete_project_workspace(project)@@ -281,13 +271,11 @@ _INVENTORY_UPDATE_TRIGGER_SQL = f"""def _replace_inventory_update_trigger(conn: sqlite3.Connection) -> None:- """Swap the unscoped trigger for the scoped one, safely for concurrent openers.-- DDL does not open a transaction under sqlite3's legacy transaction control, only DML- does, so a bare DROP + CREATE pair can interleave across processes as- drop/drop/create/create and the second CREATE raises out of `get_connection`. Hence:- skip when already scoped, hold the writer lock across the pair, IF NOT EXISTS on top.- """+ """Swap the unscoped trigger for the scoped one, safely for concurrent openers. DDL does not open a+ transaction under sqlite3's legacy transaction control, only DML does, so a bare DROP + CREATE+ pair can interleave across processes as drop/drop/create/create and the second CREATE raises out+ of `get_connection`. Hence: skip when already scoped, hold the writer lock across the pair, IF+ NOT EXISTS on top."""row = conn.execute("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?",(_INVENTORY_UPDATE_TRIGGER,),@@ -446,14 +434,12 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:conn.execute("ALTER TABLE chat_threads ADD COLUMN settings_json TEXT")if "model_gguf_variant" not in chat_thread_cols:conn.execute("ALTER TABLE chat_threads ADD COLUMN model_gguf_variant TEXT")- # Orders one writer's snapshot writes against its own earlier ones. A tab closing- # sends its last edit keepalive, which can overtake a PATCH already accepted by the- # server, and no client-side cancel reaches a handler that is already running: the- # older write has to be refused here. Scoped to the writer that sent it, so two- # browsers are never ordered against each other; see write_chat_thread_settings.- # {writer id: highest seq seen from it}. One writer and one seq is not enough: a- # write from another tab overwrites them, and the delayed request the ordering exists- # to refuse is then compared against a watermark that is no longer its own.+ # Orders one writer's snapshot writes against its own earlier ones. A tab closing sends its last+ # edit keepalive, which can overtake a PATCH already accepted by the server, and no client-side+ # cancel reaches a handler that is already running. Scoped to the writer that sent it, so two+ # browsers are never ordered against each other. {writer id: highest seq seen from it}: one writer+ # and one seq is not enough, since a write from another tab overwrites them and the delayed+ # request is then compared against a watermark that is no longer its own.if "settings_seqs" not in chat_thread_cols:conn.execute("ALTER TABLE chat_threads ADD COLUMN settings_seqs TEXT")if "project_id" not in chat_thread_cols:@@ -510,13 +496,12 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:conn.execute("ALTER TABLE chat_clear_operations ADD COLUMN deleted_thread_ids_json TEXT NOT NULL DEFAULT '[]'")- # The thumbnail reap happens AFTER this transaction commits, behind seconds of archive and- # sandbox cleanup. A crash in that window leaves the operation recorded and the cache- # unreaped, and the retry that follows replays -- skipping the one cleanup that had not- # run. These two columns let the replay finish it: the ids the original clear was- # responsible for, and whether the reap has since completed. NULL in either means the- # answer is unknown (a row written by an older build), which is treated as done, since a- # replay must never reap on a guess.+ # The thumbnail reap happens AFTER this transaction commits, behind seconds of archive and sandbox+ # cleanup, so a crash in that window leaves the operation recorded and the cache unreaped and the+ # retry replays, skipping the one cleanup that had not run. These two columns let the replay finish+ # it: the ids the original clear was responsible for, and whether the reap has since completed.+ # NULL in either is unknown (an older build) and treated as done, since a replay must never reap+ # on a guess.if "reapable_image_ids_json" not in chat_clear_operation_cols:conn.execute("ALTER TABLE chat_clear_operations ADD COLUMN reapable_image_ids_json TEXT")if "caches_cleared_at" not in chat_clear_operation_cols:@@ -1192,12 +1177,9 @@ def bulk_upsert_prompt_lists(lists: list[dict]) -> int:def is_sqlite_busy_error(exc: sqlite3.OperationalError) -> bool:- """Is this the writer lock being held elsewhere, rather than a real fault?-- sqlite reports it as plain OperationalError, so the message is the only signal.- Lives here because studio.db is the contended file and several modules need the- same answer; storage.api_usage_db delegates to it.- """+ """Is this the writer lock being held elsewhere, rather than a real fault? sqlite reports it as+ plain OperationalError, so the message is the only signal. Lives here because studio.db is the+ contended file and several modules need the same answer; storage.api_usage_db delegates to it."""message = str(exc).lower()return "locked" in message or "busy" in message@@ -1211,23 +1193,16 @@ _CONTENDED_BUSY_TIMEOUT_SECONDS = 30.0def _apply_wal_synchronous(conn: sqlite3.Connection) -> None:- """Drop to synchronous=NORMAL, but only while the file is really in WAL mode.-- Under WAL, sqlite still defaults to synchronous=FULL, which fsyncs on every commit- while holding the writer lock. On a machine whose disk is busy -- a Colab session- pulling a multi-GB GGUF, say -- one commit blocked for 37s, and every other writer- (notably the research supervisor's claim_next) spent that whole window timing out- with "database is locked". NORMAL is sqlite's own recommended pairing for WAL: it- can lose the last transactions to a host power loss, but the database is never- corrupted, and commits stay durable across an application crash either way.-- The WAL check is not decoration. `PRAGMA journal_mode=WAL` silently declines on- filesystems without proper shared-memory support (network shares, some FUSE and- container-mounted paths, which Windows users hit most often), leaving the file on a- rollback journal where NORMAL drops the very fsync that keeps it consistent. Those- installs keep FULL and simply do not get the speedup. journal_mode is persistent in- the file, so this reads what is actually in force rather than what was requested.- """+ """Drop to synchronous=NORMAL, but only while the file is really in WAL mode. Under WAL, sqlite+ still defaults to synchronous=FULL, which fsyncs on every commit while holding the writer lock:+ on a machine whose disk is busy one commit blocked for 37s, and every other writer spent that+ window timing out with "database is locked". NORMAL is sqlite's own recommended pairing for WAL:+ it can lose the last transactions to a host power loss, but the database is never corrupted and+ commits stay durable across an application crash. The WAL check is not decoration. `PRAGMA+ journal_mode=WAL` silently declines on filesystems without proper shared-memory support (network+ shares, some FUSE and container-mounted paths), leaving the file on a rollback journal where+ NORMAL drops the very fsync that keeps it consistent. Those installs keep FULL. journal_mode is+ persistent in the file, so this reads what is in force rather than what was requested."""try:mode = conn.execute("PRAGMA journal_mode").fetchone()[0]except (sqlite3.Error, TypeError, IndexError):@@ -1375,7 +1350,6 @@ def update_run_total_steps(id: str, total_steps: int) -> None:def update_run_progress(id: str, step: int, loss: Optional[float], duration_seconds: Optional[float]) -> None:- """Update current progress on a running training run (called on each metric flush)."""conn = get_connection()try:conn.execute(@@ -1525,7 +1499,6 @@ def update_run_config_json(id: str, config_json: str) -> bool:def mark_run_cancel_requested(id: str) -> bool:- """Clear resume/export state only while the exact run is still active."""conn = get_connection()try:cursor = conn.execute(@@ -1663,7 +1636,6 @@ def get_resumable_run_by_output_dir(output_dir: str) -> Optional[dict]:def get_run_metrics(id: str) -> dict:- """Return metric arrays for a run, using paired step arrays per metric."""conn = get_connection()try:rows = conn.execute(@@ -1801,12 +1773,10 @@ def list_scan_folders() -> list[dict]:def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:- """Add a custom scan folder and return its row plus whether it was inserted."""if not path or not path.strip():raise ValueError("Path cannot be empty")normalized = os.path.realpath(os.path.expanduser(path.strip()))- # Validate the path is an existing, readable directory before persisting.if not os.path.exists(normalized):raise ValueError("Path does not exist")if not os.path.isdir(normalized):@@ -1828,9 +1798,8 @@ def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:continueraise ValueError(f"Path under {prefix} is not allowed")- # Last, so a denied path is never opened: os.access alone passes on folders- # macOS TCC or a Windows ACL still refuses at scan time, which is how a- # registered folder ends up looking empty instead of blocked.+ # Last, so a denied path is never opened: os.access alone passes on folders macOS TCC or a Windows+ # ACL still refuses at scan time, which is how a registered folder looks empty instead of blocked.if not is_readable_dir(normalized):raise ValueError("Path is not readable")@@ -1875,7 +1844,6 @@ def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:def add_scan_folder(path: str) -> dict:- """Add a directory to the custom scan folder list. Returns the row."""row, _ = add_scan_folder_with_status(path)return row@@ -2051,10 +2019,9 @@ def update_chat_thread(expected_opening_message_id: Optional[str] = None,settings_write: Optional[dict] = None,) -> Optional[dict]:- """Patch a thread. With expected_title, the write only lands while the row- still holds that title, so a concurrent rename wins instead of being lost.- expected_opening_message_id guards a title derived from that message: if it- is gone, the write is rejected rather than expanding deleted text."""+ """Patch a thread. With expected_title, the write only lands while the row still holds that title,+ so a concurrent rename wins instead of being lost. expected_opening_message_id guards a title+ derived from that message: if it is gone, the write is rejected rather than expanding deleted text."""allowed = {"title": ("title", patch.get("title")),"modelType": ("model_type", patch.get("modelType")),@@ -2146,18 +2113,13 @@ def _write_chat_thread_settings_in_conn(writer: Optional[str] = None,keep_unreadable = None,) -> Optional[bool]:- """The snapshot write itself, on a connection whose transaction the caller owns.-- None when the row is gone. True when it wrote, False when an older write from the- same writer was refused; both leave the caller's transaction usable.-- The all-or-nothing the caller wants is about FAILURE: a rejected metadata- precondition must not leave the settings committed, and a missing row must write- nothing. A refusal is not a failure. It means this writer has already landed a newer- snapshot, so the row holds what the writer wanted either way, and rolling the- metadata back with it would drop a rename the client sent in the same PATCH and got- a 200 for.- """+ """The snapshot write itself, on a connection whose transaction the caller owns. None when the row+ is gone. True when it wrote, False when an older write from the same writer was refused; both+ leave the caller's transaction usable. The all-or-nothing the caller wants is about FAILURE: a+ rejected metadata precondition must not leave the settings committed, and a missing row must+ write nothing. A refusal is not a failure: this writer has already landed a newer snapshot, so+ the row holds what it wanted either way, and rolling the metadata back would drop a rename the+ client sent in the same PATCH and got a 200 for."""row = conn.execute("SELECT settings_json, settings_seqs FROM chat_threads WHERE id = ?",(id,),@@ -2177,10 +2139,9 @@ def _write_chat_thread_settings_in_conn(# stays in least-recently-used order.seqs.pop(writer, None)seqs[writer] = seq- # One entry per tab that has ever written, so bound it. Evicted by last use and- # never by counter: every session starts its own counter at 1, so comparing them- # across writers would throw out the newest tab and keep long-dead ones, leaving- # the active writer with no watermark for its own stragglers to be refused by.+ # One entry per tab that has ever written, so bound it. Evicted by last use and never by counter:+ # every session starts its own counter at 1, so comparing them across writers would throw out the+ # newest tab and keep long-dead ones, leaving the active writer with no watermark.while len(seqs) > _MAX_SETTINGS_WRITERS:seqs.pop(next(iter(seqs)))stored = _json_loads(row["settings_json"], None)@@ -2212,25 +2173,17 @@ def write_chat_thread_settings(writer: Optional[str] = None,keep_unreadable = None,) -> Optional[dict]:- """Write a thread's settings snapshot, reading and merging in one transaction.-- Doing the read in the route and the write here lets two requests on the same thread,- two tabs or a tab closing behind an open one, both turn a partial patch into a full- replacement built from the same stale snapshot, and the second one lands on top. The- read, the merge and the write have to be one transaction, so they are.-- `writer` and `seq` order the writes, and only ever against the same writer's own- earlier ones: a write is dropped when it comes from the writer whose snapshot is- already stored and carries a seq no newer than it. Two browsers are never compared,- because their clocks and counters have nothing to do with each other and the one that- happened to be behind would have every edit silently refused. Within one writer the- ordering is real, which is the case that needs it: an aborted fetch does not stop a- handler the server has already started.-- `keep_unreadable(stored) -> dict` names the part of the stored snapshot the caller- could not read, which a replacement carries forward rather than deleting. Passed in- rather than imported so this module stays free of the wire models.- """+ """Write a thread's settings snapshot, reading and merging in one transaction. Doing the read in+ the route and the write here lets two requests on the same thread both turn a partial patch into+ a full replacement built from the same stale snapshot, and the second one lands on top. `writer`+ and `seq` order the writes, and only ever against the same writer's own earlier ones: a write is+ dropped when it comes from the writer whose snapshot is already stored and carries a seq no+ newer than it. Two browsers are never compared, since their counters have nothing to do with+ each other and the one behind would have every edit silently refused. Within one writer the+ ordering is real: an aborted fetch does not stop a handler already started.+ `keep_unreadable(stored) -> dict` names the part of the stored snapshot the caller could not+ read, which a replacement carries forward rather than deleting. Passed in rather than imported+ so this module stays free of the wire models."""conn = get_connection()try:# IMMEDIATE takes the write lock up front, so the read below cannot be overtaken.@@ -2298,7 +2251,6 @@ def list_chat_threads(def build_chat_history_export() -> tuple[list[dict], list[dict], list[dict]]:- """Read projects, threads, and messages from one SQLite snapshot."""conn = get_connection()try:conn.execute("BEGIN")@@ -2465,24 +2417,18 @@ def delete_chat_threads_with_active_research_runs(ids: list[str]) -> list[str]:def delete_chat_threads(ids: list[str]) -> list[str]:- """Delete threads and return the active research runs removed with them."""return delete_chat_threads_with_active_research_runs(ids)def unreaped_clear_operation_image_ids(operation_id: Optional[str]) -> Optional[set]:- """The ids a recorded clear was responsible for but never reaped, or None.-- None means there is nothing for a replay to finish: no such operation, a row from a build- that did not record the snapshot, or a reap that already completed. A replay must never- reap on a guess -- the whole point of bounding it is that the images of chats created- since the original clear are NOT its to take -- so anything unknown answers None.-- Exists because the reap runs after the clear's transaction commits, behind seconds of- archive and sandbox cleanup. Killed in that window, the operation is recorded and the- thumbnails of every deleted chat are still on disk; the retry that follows replays and,- without this, skips the one cleanup that had not run. Those files say what was searched- for, so leaving them is the worse of the two failures this module weighs.- """+ """The ids a recorded clear was responsible for but never reaped, or None. None means there is+ nothing for a replay to finish: no such operation, a row from a build that did not record the+ snapshot, or a reap that already completed. A replay must never reap on a guess, since the+ images of chats created since the original clear are NOT its to take. Exists because the reap+ runs after the clear's transaction commits, behind seconds of archive and sandbox cleanup.+ Killed in that window, the operation is recorded and the thumbnails of every deleted chat are+ still on disk, and the retry that follows would skip the one cleanup that had not run. Those+ files say what was searched for, so leaving them is the worse failure."""if operation_id is None:return Nonetry:@@ -2510,14 +2456,11 @@ def unreaped_clear_operation_image_ids(operation_id: Optional[str]) -> Optional[def record_clear_operation_reap_scope(operation_id: Optional[str], image_ids: Optional[set]) -> None:- """Persist what this clear's reap is responsible for, before it runs.-- Written as its own statement rather than in the clear's INSERT: the snapshot is taken- immediately after that transaction commits, and moving the commit later to include it- would widen the window where a concurrent retry sees no ledger row at all.-- A None snapshot means "clear everything", which no replay may repeat blindly, so it is- stored as an explicit absence and read back as nothing to finish."""+ """Persist what this clear's reap is responsible for, before it runs. Written as its own statement+ rather than in the clear's INSERT: the snapshot is taken immediately after that transaction+ commits, and moving the commit later to include it would widen the window where a concurrent+ retry sees no ledger row at all. A None snapshot means "clear everything", which no replay may+ repeat blindly, so it is stored as an explicit absence."""if operation_id is None:returntry:@@ -2567,8 +2510,6 @@ def clear_chat_history(operation_id: Optional[str] = None,include_chat_generation_runs: bool = False,) -> "tuple[list[str], list[str]] | tuple[list[str], list[str], list[str]]":- """Delete every chat thread. Returns (thread ids removed, research runs cascaded)."""-result = clear_chat_history_with_replay_status(additional_thread_ids,operation_id = operation_id,@@ -2586,26 +2527,19 @@ def clear_chat_history_with_replay_status(operation_id: Optional[str] = None,include_chat_generation_runs: bool = False,) -> "tuple[list[str], list[str], bool] | tuple[list[str], list[str], list[str], bool]":- """`clear_chat_history`, plus whether this call replayed a recorded outcome.-- Returns (thread ids removed, research runs cascaded, replayed), optionally- including active chat generation run ids before the replay flag.-- The first two are taken inside the same transaction: another process can add a- thread between a listing and this call, its sandbox has to be cleaned up too, and- after the cascade nothing can tell the supervisor which runs to stop.-- `replayed` comes from that same transaction because it cannot be established- outside one. Two requests carrying the same operation id can both read an- unrecorded ledger before either commits, so both would conclude they performed- the clear; BEGIN IMMEDIATE then serialises them and the loser silently replays.- A caller trusting the outside read would run the second request's cleanup of- global, non-id-keyed state -- the thumbnail cache -- against threads created- since the winner committed, which this call deliberately kept. That is exactly- the retry the operation id exists to make safe: the frontend reissues the same- id when its first attempt times out, and Starlette does not cancel the handler- the client hung up on, so both really are in flight at once.- """+ """`clear_chat_history`, plus whether this call replayed a recorded outcome. Returns (thread ids+ removed, research runs cascaded, replayed), optionally including active chat generation run ids+ before the replay flag. The first two are taken inside the same transaction: another process can+ add a thread between a listing and this call, its sandbox has to be cleaned up too, and after+ the cascade nothing can tell the supervisor which runs to stop. `replayed` comes from that same+ transaction because it cannot be established outside one. Two requests carrying the same+ operation id can both read an unrecorded ledger before either commits, so both would conclude+ they performed the clear; BEGIN IMMEDIATE then serialises them and the loser silently replays. A+ caller trusting the outside read would run the second request's cleanup of global, non-id-keyed+ state (the thumbnail cache) against threads created since the winner committed. That is exactly+ the retry the operation id exists to make safe: the frontend reissues the same id when its first+ attempt times out, and Starlette does not cancel the handler the client hung up on, so both+ really are in flight at once."""conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)try:conn.execute("BEGIN IMMEDIATE")@@ -2746,11 +2680,10 @@ def ensure_chat_project_workspace(id: str) -> Optional[dict]:return Noneroot_path = project.get("rootPath") or _default_project_root(project)root_path = _ensure_project_workspace(root_path)- # a delete running in another threadpool worker can drop the row at any point before the- # directory is created, so confirm the project outlived the create rather than trusting a- # pre-create snapshot. Removing the directory here is not this function's call: only the- # delete path knows whether the user asked to keep the files, and the row may have had a- # populated workspace already. An empty directory left behind is the cheaper outcome.+ # A delete running in another threadpool worker can drop the row at any point before the directory+ # is created, so confirm the project outlived the create rather than trusting a pre-create+ # snapshot. Removing the directory here is not this function's call: only the delete path knows+ # whether the user asked to keep the files. An empty directory left behind is the cheaper outcome.project = get_chat_project(id)if project is None:return None@@ -2806,9 +2739,8 @@ def delete_chat_project(id: str, delete_files: bool = False) -> Optional[dict]:(id,),)}- # Read before the cascade removes them: afterwards nothing can tell the- # supervisor which runs to stop, and a worker keeps doing model, web and- # RAG work for a project that is gone.+ # Read before the cascade removes them: afterwards nothing can tell the supervisor which+ # runs to stop, and a worker keeps doing model, web and RAG work for a project that is gone.active_runs = ([row["id"]@@ -2948,11 +2880,8 @@ def _bump_chat_thread_updated_at(def _recompute_chat_thread_updated_at(conn: sqlite3.Connection, thread_id: str) -> None:- """Set updated_at from the remaining messages, floored at created_at.-- Unlike the ratchet-only bump, this can lower updated_at -- needed after- pruning, which may delete the thread's newest message.- """+ """Set updated_at from the remaining messages, floored at created_at. Unlike the ratchet-only bump,+ this can lower updated_at -- needed after pruning, which may delete the thread's newest message."""conn.execute("""UPDATE chat_threads@@ -3046,12 +2975,10 @@ def _server_managed_message_ids(conn: sqlite3.Connection, thread_id: str) -> setdef _surviving_parent_id(conn: sqlite3.Connection, thread_id: str, message_id: str, pruned: set) -> "str | None":- """The stored ancestor a message relinks to once `pruned` is deleted, or None at the root.-- Walking the stored chain server side is what makes the relink allowance safe: the expected- parent is derived from rows the server already holds, so a client cannot smuggle an arbitrary- link past the guard by claiming its old parent went away.- """+ """The stored ancestor a message relinks to once `pruned` is deleted, or None at the root. Walking+ the stored chain server side is what makes the relink allowance safe: the expected parent is+ derived from rows the server already holds, so a client cannot smuggle an arbitrary link past+ the guard by claiming its old parent went away."""seen = {message_id}row = conn.execute("SELECT parent_id FROM chat_messages WHERE thread_id = ? AND id = ?",@@ -3298,7 +3225,6 @@ def _is_locally_stored_blob(value: str) -> bool:def _managed_content_part_payload(part: dict) -> Optional[tuple[str, Any]]:- """Return the locally stored blob payload used to identify a content part."""image = part.get("image")if isinstance(image, str) and image[:5].lower() == "data:":return "image", image@@ -3433,7 +3359,6 @@ def _chat_attachment_inventory_entries(def count_chat_message_attachments(attachments_json: Optional[str], content_json: Optional[str]) -> int:- """Count distinct user-visible uploads represented by a chat message."""return len(_chat_attachment_inventory_entries(attachments_json, content_json))@@ -3682,10 +3607,9 @@ def sync_chat_messages(if _references_tombstoned_generation(conn, message)}messages = [message for message in messages if str(message["id"]) not in tombstoned_ids]- # Generation-linked messages are server-managed: keep the record rather than reject the- # batch on client drift. No _guard_research_messages call here as a result -- these ids- # never reach it. upsert_chat_message still guards, so the single-message route keeps- # rejecting edits.+ # Generation-linked messages are server-managed: keep the record rather than reject the batch on+ # client drift. No _guard_research_messages call as a result, since these ids never reach it;+ # upsert_chat_message still guards, so the single-message route keeps rejecting edits.research_ids = _research_message_ids(conn, thread_id)generation_ids = _generation_message_ids(conn, thread_id)managed_ids = research_ids | generation_ids@@ -3701,10 +3625,9 @@ def sync_chat_messages(| (generation_ids - explicitly_deleted_terminal_ids)| (tombstoned_ids - explicitly_deleted_ids))- # The rows this sync will delete, computed before the upsert so a relink forced by- # that deletion can be told apart from an edit. Research ids are subtracted because- # the delete below exempts them: counting one as pruned would walk the reseat past a- # parent that actually survives, detaching a research turn from its own prompt.+ # The rows this sync will delete, computed before the upsert so a relink forced by that deletion+ # can be told apart from an edit. Research ids are subtracted because the delete exempts them:+ # counting one as pruned would walk the reseat past a parent that actually survives.pruned: set = set()if prune_missing:pruned = (@@ -3728,14 +3651,11 @@ def sync_chat_messages(and _safe_generation_assistant_update(conn, thread_id, m))]- # Content is dropped, structure is not: the prune below can delete a research- # message's parent, and a dangling parent makes the whole thread unimportable. The- # replacement is walked from the stored chain, never taken from the client.- #- # Candidates come from managed_ids rather than `protected` because the delete exempts- # research rows whatever allow_research_update says, so a narrower set would leave one- # dangling. Ids the batch itself writes are excluded: an authorized caller reparenting- # a research row must not have that overwritten by the repair.+ # Content is dropped, structure is not: the prune below can delete a research message's parent, and+ # a dangling parent makes the whole thread unimportable. The replacement is walked from the stored+ # chain, never taken from the client. Candidates come from managed_ids rather than `protected`+ # because the delete exempts research rows whatever allow_research_update says. Ids the batch+ # itself writes are excluded: an authorized reparent must not be overwritten by the repair.reseat_candidates = managed_ids - {str(m["id"]) for m in messages}reseat_parents = {message_id: _surviving_parent_id(conn, thread_id, message_id, pruned)@@ -3839,7 +3759,6 @@ def sync_chat_messages(def _parents_of(conn, thread_id: str, message_ids: set) -> dict:- """Stored parent of each id in *message_ids*, for rows that exist."""if not message_ids:return {}return {@@ -3853,11 +3772,9 @@ def _parents_of(conn, thread_id: str, message_ids: set) -> dict:def _reseat_protected_messages(conn, thread_id: str, reseat_parents: dict) -> None:- """Point protected messages at the ancestor that survived the prune.-- Their own rows survive it, the parents they pointed at need not, and a dangling parent- makes the whole thread unimportable on the next load rather than just that turn.- """+ """Point protected messages at the ancestor that survived the prune. Their own rows survive it, the+ parents they pointed at need not, and a dangling parent makes the whole thread unimportable on+ the next load rather than just that turn."""for message_id, parent_id in reseat_parents.items():conn.execute("UPDATE chat_messages SET parent_id = ? WHERE thread_id = ? AND id = ?",@@ -3930,15 +3847,10 @@ def fork_chat_thread(created_at: int,id_factory,) -> Optional[dict]:- """Atomically clone thread + ancestor msgs `[root..branch_message_id]`- into a new thread. Returns the new thread dict (with messages copied)- or None if source missing.-- Reset both code-exec container ids -- per-provider snapshot is handled- by the route layer (best-effort, OpenAI only).-- `id_factory()` produces fresh message uuids; injected for testability.- """+ """Atomically clone thread + ancestor msgs `[root..branch_message_id]` into a new thread. Returns+ the new thread dict (with messages copied) or None if source missing. Reset both code-exec+ container ids; the per-provider snapshot is handled by the route layer. `id_factory()` produces+ fresh message uuids, injected for testability."""conn = get_connection()try:conn.execute("BEGIN IMMEDIATE")@@ -4057,11 +3969,9 @@ def count_forks_for_message(thread_id: str, message_id: str) -> int:def chat_thread_has_messages(thread_id: str) -> bool:- """Whether this thread has any saved message. Existence only, no rows hydrated.-- A temporary (incognito) chat is never written here, so this is what tells a thread- whose turns can be archived from one whose turns must not be.- """+ """Whether this thread has any saved message. Existence only, no rows hydrated. A temporary+ (incognito) chat is never written here, so this is what tells a thread whose turns can be+ archived from one whose turns must not be."""conn = get_connection()try:row = conn.execute(@@ -4073,7 +3983,6 @@ def chat_thread_has_messages(thread_id: str) -> bool:def fork_counts_for_thread(thread_id: str) -> dict[str, int]:- """Fork counts for every message of one thread, keyed by message id."""conn = get_connection()try:rows = conn.execute(@@ -4121,7 +4030,6 @@ def get_chat_message(thread_id: str, message_id: str) -> Optional[dict]:def _blob_part_base64_len(part: dict) -> int:- """Base64 payload length of an image or audio content part, or 0."""image = part.get("image")if isinstance(image, str) and image[:5].lower() == "data:":return len(image.rsplit(",", 1)[-1])@@ -4143,12 +4051,9 @@ def _attachment_content_parts(attachment: dict) -> list[dict]:def _chat_attachment_size_bytes(attachment: dict) -> Optional[int]:- """Approximate stored size of one attachment's content parts.-- Image and audio parts hold base64 payloads (decoded bytes ~= 3/4 of the- encoded length); text parts count their character length. None when there- is no sizable content (e.g. a stripped/legacy attachment).- """+ """Approximate stored size of one attachment's content parts. Image and audio parts hold base64+ payloads (decoded bytes ~= 3/4 of the encoded length); text parts count their character length.+ None when there is no sizable content."""total = 0found = Falsefor part in _attachment_content_parts(attachment):@@ -4165,11 +4070,9 @@ def _chat_attachment_size_bytes(attachment: dict) -> Optional[int]:def _content_part_attachments(content_json: Optional[str]) -> list[dict]:- """Managed local blobs stored in content_json, with stable payload ids.-- Exact duplicate blobs intentionally share one inventory id. Deleting that- id removes every identical copy, avoiding ambiguous index-based addressing.- """+ """Managed local blobs stored in content_json, with stable payload ids. Exact duplicate blobs+ intentionally share one inventory id: deleting it removes every identical copy, avoiding+ ambiguous index-based addressing."""content = _json_loads(content_json, None)if not isinstance(content, list):return []@@ -4205,7 +4108,6 @@ def _content_part_attachments(content_json: Optional[str]) -> list[dict]:def list_chat_attachments_page(limit: int = 50, offset: int = 0) -> tuple[list[dict], Optional[int]]:- """One bounded page from the normalized attachment inventory."""if not 1 <= limit <= 100:raise ValueError("limit must be between 1 and 100")if offset < 0:@@ -4263,7 +4165,6 @@ def list_chat_attachments() -> list[dict]:def get_chat_attachment(message_id: str, attachment_id: str) -> Optional[dict]:- """One attachment record (full content) from a message, or None."""conn = get_connection()try:row = conn.execute(@@ -4317,13 +4218,9 @@ def _record_chat_attachment_tombstone(def delete_chat_attachment(message_id: str, attachment_id: str) -> bool:- """Remove one stored upload from a message.-- The tombstone is retained while the thread exists, so pruning and later- recreating the same message id cannot restore the deleted upload. If an- ordinary attachment id collides with a content-blob id, both are deleted as- one managed item.- """+ """Remove one stored upload from a message. The tombstone is retained while the thread exists, so+ pruning and later recreating the same message id cannot restore the deleted upload. If an+ ordinary attachment id collides with a content-blob id, both are deleted as one managed item."""conn = get_connection()try:conn.execute("BEGIN IMMEDIATE")@@ -4448,13 +4345,9 @@ def get_app_setting(key: str, fallback = None):def get_app_settings(keys: list[str]) -> dict[str, Any]:- """Read a set of settings from one SQLite snapshot.-- Values that form one logical record must not be fetched through separate- connections: a concurrent multi-key upsert could otherwise leave a reader- pairing one save's first field with another save's remaining fields.- Missing keys are omitted from the result.- """+ """Read a set of settings from one SQLite snapshot. Values that form one logical record must not be+ fetched through separate connections: a concurrent multi-key upsert could leave a reader pairing+ one save's first field with another save's remaining fields. Missing keys are omitted."""unique = list(dict.fromkeys(keys))if not unique:return {}@@ -4471,13 +4364,10 @@ def get_app_settings(keys: list[str]) -> dict[str, Any]:def compare_and_set_app_setting(key: str, expected: Any, value: Any) -> bool:- """Write ``value`` to ``key`` only while it still holds ``expected``.-- A read-then-upsert cannot express "clear this flag": another save committing- in the gap is silently reverted by the write that follows it. Comparing inside- one immediate transaction makes a losing update a no-op instead. Returns- whether the write happened.- """+ """Write ``value`` to ``key`` only while it still holds ``expected``. A read-then-upsert cannot+ express "clear this flag": another save committing in the gap is silently reverted by the write+ that follows it. Comparing inside one immediate transaction makes a losing update a no-op+ instead. Returns whether the write happened."""conn = get_connection()try:conn.execute("BEGIN IMMEDIATE")@@ -4541,25 +4431,19 @@ def upsert_app_setting_map_entry(fill_absent_fields: bool = False,coupled_fields: tuple[tuple[str, ...], ...] = (),) -> dict[str, Any]:- """Set (or delete, when entry_value is falsy) one sub-entry of a dict-valued- app setting, atomically under BEGIN IMMEDIATE so concurrent writers to other- sub-entries cannot drop each other's updates.-- ``fill_absent_fields`` writes only what is missing: the entry is created when- it is not there, and otherwise gains the fields it does not already hold while- every stored value is left exactly as it is. Nothing is ever deleted. The read- and the write share this transaction, so a caller that read the map earlier- cannot replace a value written since. Used by the one-time localStorage- backfill, whose contract is that the server copy is the newer authority: an- upgraded install can hold an entry with only the fields an older release knew,- while this browser holds the rest, and entry-level skipping would strand them.-- ``coupled_fields`` names groups that only mean anything together. Field-by-field- filling would otherwise take a qualifier from this browser and leave the value it- qualifies as the server wrote it: a stored ``gpu_ids`` in one index space, relabelled- with the other space's ``gpu_index_kind``, points at a different GPU while looking- stored. A group any part of which is already held is skipped whole.- """+ """Set (or delete, when entry_value is falsy) one sub-entry of a dict-valued app setting,+ atomically under BEGIN IMMEDIATE so concurrent writers to other sub-entries cannot drop each+ other's updates. ``fill_absent_fields`` writes only what is missing: the entry is created when+ absent, and otherwise gains the fields it does not hold while every stored value is left as it+ is. The read and the write share this transaction, so a caller that read the map earlier cannot+ replace a value written since. Used by the one-time localStorage backfill, whose contract is+ that the server copy is the newer authority: an upgraded install can hold an entry with only the+ fields an older release knew while this browser holds the rest, and entry-level skipping would+ strand them. ``coupled_fields`` names groups that only mean anything together. Field-by-field+ filling would take a qualifier from this browser and leave the value it qualifies as the server+ wrote it: a stored ``gpu_ids`` in one index space, relabelled with the other space's+ ``gpu_index_kind``, points at a different GPU while looking stored. A group any part of which is+ held is skipped whole."""conn = get_connection()try:conn.execute("BEGIN IMMEDIATE")@@ -4736,16 +4620,12 @@ def upsert_chat_settings_merge_if_current(expected_absent: Iterable[str] = (),expected_absent_paths: Iterable[Iterable[str]] = (),) -> tuple[dict[str, Any], bool]:- """Atomically merge ``updates`` only if ``expected`` still matches.-- Expected is a recursive subset so legacy keys omitted by the current client- do not prevent a guarded migration. Any field the client did read is fenced- against a newer tab write in the same BEGIN IMMEDIATE transaction.- """- # Contended timeout, not the default: this fires during hydration alongside- # the ordinary settings writer, and takes a write lock before knowing if it- # will write. Where WAL declined both share one writer, and the 5s default- # surfaces as a bare "database is locked" the route cannot map.+ """Atomically merge ``updates`` only if ``expected`` still matches. Expected is a recursive subset+ so legacy keys omitted by the current client do not prevent a guarded migration. Any field the+ client did read is fenced against a newer tab write in the same BEGIN IMMEDIATE transaction."""+ # Contended timeout, not the default: this fires during hydration alongside the ordinary settings+ # writer and takes a write lock before knowing if it will write. Where WAL declined both share one+ # writer, and the 5s default surfaces as a bare "database is locked" the route cannot map.conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)try:conn.execute("BEGIN IMMEDIATE")@@ -4798,11 +4678,7 @@ def upsert_chat_settings_merge_if_current(conn.close()-# --- Legacy Dexie import ledger (recovery rationale in _ensure_schema's schema comment) -----def list_chat_legacy_imports() -> list[str]:- """Return the legacy_thread_id of every thread already imported."""conn = get_connection()try:rows = conn.execute("SELECT legacy_thread_id FROM chat_legacy_imports").fetchall()@@ -4812,12 +4688,9 @@ def list_chat_legacy_imports() -> list[str]:def upsert_chat_legacy_imports(legacy_thread_ids: list[str]) -> tuple[int, int]:- """Mark each given legacy thread id as imported. Idempotent.-- Returns (accepted, inserted): count of deduped non-empty input ids, and- count of rows actually new. RETURNING lets callers tell first-time imports- from idempotent re-runs without an extra SELECT.- """+ """Mark each given legacy thread id as imported. Idempotent. Returns (accepted, inserted): count of+ deduped non-empty input ids, and count of rows actually new. RETURNING lets callers tell+ first-time imports from idempotent re-runs without an extra SELECT."""ids = list(dict.fromkeys(tid for tid in legacy_thread_ids if tid))if not ids:return 0, 0diff --git a/studio/frontend/public/reload-snapshot.js b/studio/frontend/public/reload-snapshot.jsindex cd5bec3d58c..06f66967ec9 100644--- a/studio/frontend/public/reload-snapshot.js+++ b/studio/frontend/public/reload-snapshot.js@@ -18,11 +18,10 @@var overlay = null;var retainedSnapshot = null;var removalTimer = null;- // Appearance is inline custom properties on <html> plus these gate- // attributes, written by theme-boot.js (mode and palette) and- // applyCustomizationToDocument in- // src/features/settings/stores/appearance-custom-store.ts (the rest).- // Uncarried, the copy paints in stock colors until React restyles it.+ // Appearance is inline custom properties on <html> plus these gate attributes, written by+ // theme-boot.js (mode and palette) and applyCustomizationToDocument in+ // src/features/settings/stores/appearance-custom-store.ts (the rest). Uncarried, the copy paints+ // in stock colors until React restyles it.var appearanceAttributes = ["data-chat-font","data-code-font-size",@@ -110,10 +109,9 @@return styles;}- // Design tokens the app defines through `:root` do not reach a shadow tree:- // `:root` matches only a document's root element, and Tailwind's `:host`- // block redeclares some of them on the host. Freeze the computed set and put- // it on the copy's own root instead.+ // Design tokens the app defines through `:root` do not reach a shadow tree: `:root` matches only+ // a document's root element, and Tailwind's `:host` block redeclares some of them on the host.+ // Freeze the computed set and put it on the copy's own root instead.function readTokens() {var style = getComputedStyle(document.documentElement);var tokens = {};@@ -701,10 +699,9 @@continue;}var style = getComputedStyle(original);- // Two shapes with empty rectangles that are nonetheless visible: a- // `display: contents` wrapper generates no box however much its- // children fill, and a closed select still paints its selected- // option's label. Judging either by its rectangle drops what it shows.+ // Two shapes with empty rectangles that are nonetheless visible: a `display: contents`+ // wrapper generates no box however much its children fill, and a closed select still paints+ // its selected option's label. Judging either by its rectangle drops what it shows.var paintsThroughSelect =(original.tagName === "OPTION" ||original.tagName === "OPTGROUP") &&@@ -843,12 +840,11 @@saveSnapshot();}});- // Firefox, WebKitGTK and Safari before 18.2 do not expose pageswap, but- // still deliver pagehide on reload. Do not register both: Chromium fires- // pagehide after pageswap and a second full-DOM capture during unload is- // both expensive and lower fidelity. pagehide cannot tell a reload from any- // other unload, so on those engines a snapshot is also written when the user- // navigates away; the restore side discards it (navigationType below).+ // Firefox, WebKitGTK and Safari before 18.2 do not expose pageswap, but still deliver pagehide on+ // reload. Do not register both: Chromium fires pagehide after pageswap and a second full-DOM+ // capture during unload is both expensive and lower fidelity. pagehide cannot tell a reload from+ // any other unload, so on those engines a snapshot is also written when the user navigates away;+ // the restore side discards it (navigationType below).if (!("onpageswap" in window)) {window.addEventListener("pagehide", function (event) {if (!event.persisted) saveSnapshot();diff --git a/studio/frontend/public/theme-boot.js b/studio/frontend/public/theme-boot.jsindex 70bd93e0e19..6ea6cce29a0 100644--- a/studio/frontend/public/theme-boot.js+++ b/studio/frontend/public/theme-boot.js@@ -1,10 +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-// Apply the stored theme and palette before the bundle loads so the first-// paint is never the wrong mode. Loaded as an external classic script (it-// blocks parsing, like an inline script) because the backend CSP only-// allows script-src 'self'.+// Apply the stored theme and palette before the bundle loads so the first paint is never the wrong+// mode. Loaded as an external classic script (it blocks parsing, like an inline script) because the+// backend CSP only allows script-src 'self'.try {// Storage reads get their own guards so a blocked localStorage (private// browsing) still resolves a mode from the OS preference.diff --git a/studio/frontend/scripts/build-fast-copy-bundle.mjs b/studio/frontend/scripts/build-fast-copy-bundle.mjsindex dc2f8977417..15b9ad72f2d 100644--- a/studio/frontend/scripts/build-fast-copy-bundle.mjs+++ b/studio/frontend/scripts/build-fast-copy-bundle.mjs@@ -4,17 +4,14 @@// Compile the SHIPPED module into a browser script, so the byte-for-byte proof runs against the// TypeScript that is actually in the tree rather than against a hand-kept copy of it. Proving a// reference implementation proves the reference implementation; what reaches a user is-// studio/frontend/src/components/assistant-ui/thread-fast-copy.ts, so that is what is built.-//-// Usage: node scripts/build-fast-copy-bundle.mjs <out-dir>, from studio/frontend.-// It lives here rather than beside its caller in tests/studio because node resolves a bare-// `import ... from "vite"` against the IMPORTING FILE's directory, and vite is installed-// under studio/frontend/node_modules.+// studio/frontend/src/components/assistant-ui/thread-fast-copy.ts, so that is what is built. Usage:+// node scripts/build-fast-copy-bundle.mjs <out-dir>, from studio/frontend. It lives here rather+// than beside its caller in tests/studio because node resolves a bare `import ... from "vite"`+// against the IMPORTING FILE's directory, and vite is installed under studio/frontend/node_modules.// Writes <out-dir>/fastcopy.js, an IIFE bundle exposing the module's exports as `SBFastCopy`.-//// `configFile: false` so studio/frontend/vite.config.ts (the app build: react plugin, chunking,-// asset pipeline) is not applied to a one-module library build. `copyPublicDir: false` because-// the app's public/ is tens of megabytes of images the proof never loads.+// asset pipeline) is not applied to a one-module library build. `copyPublicDir: false` because the+// app's public/ is tens of megabytes of images the proof never loads.import path from "node:path";import { fileURLToPath } from "node:url";diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex d87cc7dc61f..06e776b3814 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -2,24 +2,20 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0/**- * Budget for the JavaScript Unsloth must download, parse and execute before the- * first screen exists.+ * Budget for the JavaScript Unsloth must download, parse and execute before the first screen exists.*- * Two PRs (#8623, #8624) moved 1.5 MB of decoded resources off this path by hand,- * each measuring it with a throwaway Chromium harness. Nothing then stopped the- * next static import from putting it back, and nothing noticed when one did: a- * single `import` of a dialog that is closed on load was carrying 2.4 MB.+ * Two PRs (#8623, #8624) moved 1.5 MB of decoded resources off this path by hand, each measuring it with a+ * throwaway Chromium harness. Nothing then stopped the next static import from putting it back, and nothing+ * noticed when one did: a single `import` of a dialog that is closed on load was carrying 2.4 MB.*- * The eager set is not inferred here. Vite already computes it and writes it into- * index.html: the entry `<script type="module">` plus one `<link rel="modulepreload">`- * per chunk in the entry's STATIC import closure. That is exactly what the browser- * fetches before the app boots. Chunks reachable only through `import()` carry no- * preload link and are correctly not counted. A parser-blocking classic- * `<script src>` (public/theme-boot.js) is added to that: it is not Vite's, but it- * runs before the module graph and so is part of the same wait.+ * The eager set is not inferred here. Vite already computes it and writes it into index.html: the entry+ * `<script type="module">` plus one `<link rel="modulepreload">` per chunk in the entry's STATIC import closure.+ * That is exactly what the browser fetches before the app boots. Chunks reachable only through `import()` carry+ * no preload link and are correctly not counted. A parser-blocking classic `<script src>`+ * (public/theme-boot.js) is added to that: it is not Vite's, but it runs before the module graph and so is part+ * of the same wait.*- * Raising a budget is a normal thing to do. Doing it in the same diff as the import- * that needed it is the point.+ * Raising a budget is a normal thing to do. Doing it in the same diff as the import that needed it is the point.*/import { readFileSync, realpathSync } from "node:fs";@@ -31,15 +27,13 @@ const HERE = dirname(fileURLToPath(import.meta.url));const DIST = resolve(HERE, "..", "dist");/**- * Measured on the build these were set from, plus a little headroom.- *- * Transfer is what crosses the wire. Raw is what the main thread has to parse and- * execute, which is the part that shows up as a slow launch on a weak machine.+ * Measured on the build these were set from, plus a little headroom. Transfer is what crosses the wire. Raw is+ * what the main thread has to parse and execute, which is the part that shows up as a slow launch on a weak+ * machine.*/export const BUDGET = {- // Measured 1,496.2 KB transfer / 5,207.2 KB raw at 17363f8a2.- // Raised for the audio placement control: same build both sides, merge base- // 1,560.9 KB transfer against branch 1,562.6 KB, so it crossed the old 1,562.5 KB+ // Measured 1,496.2 KB transfer / 5,207.2 KB raw at 17363f8a2. Raised for the audio placement control: same+ // build both sides, merge base 1,560.9 KB transfer against branch 1,562.6 KB, so it crossed the old 1,562.5 KB// ceiling by a tenth of a kilobyte.//// Raised again because main crossed 1,582.0 KB and stayed there. Four builds on@@ -62,22 +56,17 @@ export const BUDGET = {rawBytes: 5_500_000,};-// The chunk count is reported but not budgeted. Splitting a page out of the entry-// raises it while lowering the bytes, which is the behaviour this is trying to-// reward; capping it would penalise the fix.+// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the+// bytes, which is the behaviour this is trying to reward; capping it would penalise the fix.-/**- * A start tag: lowercased name, and its attributes by lowercased name. A valueless- * attribute like `defer` is present with an empty-string value, as HTML defines it.- */+/** A start tag: lowercased name, and its attributes by lowercased name. A valueless attribute like `defer` is+ * present with an empty-string value, as HTML defines it. */type StartTag = { name: string; attrs: Map<string, string> };/**- * ASCII whitespace, which is what separates one attribute from the next.- *- * CR is in here for safety only: the parser's input preprocessor turns every CR- * into an LF before the tokenizer sees it, so a CRLF file cannot behave- * differently. https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream+ * ASCII whitespace, which is what separates one attribute from the next. CR is in here for safety only: the+ * parser's input preprocessor turns every CR into an LF before the tokenizer sees it, so a CRLF file cannot+ * behave differently. https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream*/const WHITESPACE = new Set(["\t", "\n", "\f", "\r", " "]);@@ -121,27 +110,22 @@ function readValue(}/**- * Reads the attributes of one start tag, beginning just past its name, and returns- * where the tag ends.+ * Reads the attributes of one start tag, beginning just past its name, and returns where the tag ends.*- * This is the tokenizer's attribute states, narrowed to what a build artefact can- * contain. The two rules that matter, and that no regex over the tag text can- * express:+ * This is the tokenizer's attribute states, narrowed to what a build artefact can contain. The two rules that+ * matter, and that no regex over the tag text can express:*- * - `>` ends the tag only OUTSIDE a quoted value. Inside one it is ordinary text- * ("anything else: append the current input character to the current- * attribute's value"), so `data-note="a > b"` is one attribute and the tag does- * not end there.+ * - `>` ends the tag only OUTSIDE a quoted value. Inside one it is ordinary text ("anything else: append the+ * current input character to the current attribute's value"), so `data-note="a > b"` is one attribute and+ * the tag does not end there.* https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state- * - An attribute begins only after whitespace, `/` or a previous value, so a NAME- * is the only place `async` or `type` can be read from. A value is arbitrary- * text: `data-mode="load async later"` contains no `async` attribute.- * https://html.spec.whatwg.org/multipage/parsing.html#before-attribute-name-state+ * - An attribute begins only after whitespace, `/` or a previous value, so a NAME is the only place `async`+ * or `type` can be read from. A value is arbitrary text: `data-mode="load async later"` contains no `async`+ * attribute. https://html.spec.whatwg.org/multipage/parsing.html#before-attribute-name-state*- * Both were live bugs while this searched the tag text instead: the first dropped- * the entry chunk, the second dropped the parser-blocking script, and in each case- * enough of the build survived to satisfy the shape guard below, so the gate- * reported a comfortable pass on a startup path it had not measured.+ * Both were live bugs while this searched the tag text instead: the first dropped the entry chunk, the second+ * dropped the parser-blocking script, and in each case enough of the build survived to satisfy the shape guard+ * below, so the gate reported a comfortable pass on a startup path it had not measured.*/function readAttributes(html: string,@@ -177,11 +161,9 @@ function readAttributes(}/**- * End of a comment, from just past its `<!--`.- *- * `<!-->` and `<!--->` close there rather than running on: the comment start and- * comment start dash states both end the comment on `>`. Read as unterminated, the- * rest of the file disappears along with the tags in it.+ * End of a comment, from just past its `<!--`. `<!-->` and `<!--->` close there rather than running on: the+ * comment start and comment start dash states both end the comment on `>`. Read as unterminated, the rest of the+ * file disappears along with the tags in it.* https://html.spec.whatwg.org/multipage/parsing.html#comment-start-state*/const COMMENT_END = /^-?>|--!?>/;@@ -203,17 +185,15 @@ const TAG_NAME_START = /[a-z]/i;/*** Every start tag in the document, in order.*- * Comments and script bodies are skipped rather than scanned, for the same reason- * the attribute parser exists: a tag is only a tag where the browser sees one. A- * `<script src>` commented out during debugging is not downloaded and must not be- * charged, and a tag written inside a string in an inline script is text.+ * Comments and script bodies are skipped rather than scanned, for the same reason the attribute parser exists: a+ * tag is only a tag where the browser sees one. A `<script src>` commented out during debugging is not+ * downloaded and must not be charged, and a tag written inside a string in an inline script is text.* https://html.spec.whatwg.org/multipage/parsing.html#script-data-state*- * A script body ends at the first `</script`, which is the tokenizer's answer- * unless the body itself contains `<!-- <script`: those escaped states let a- * `</script>` be text. Erring there reads a bit of script body as markup, so the- * mistake is to charge a chunk that is not there rather than to miss one. Checked- * against parse5 over 40,000 generated documents, that is the only case left.+ * A script body ends at the first `</script`, which is the tokenizer's answer unless the body itself contains+ * `<!-- <script`: those escaped states let a `</script>` be text. Erring there reads a bit of script body as+ * markup, so the mistake is to charge a chunk that is not there rather than to miss one. Checked against parse5+ * over 40,000 generated documents, that is the only case left.*/function* startTags(html: string): Generator<StartTag> {let i = 0;@@ -258,23 +238,21 @@ function relTokens(tag: StartTag): string[] {}/**- * True when the tag carries `blocking="render"`, which holds the FIRST RENDER back- * until the resource has been fetched and evaluated.+ * True when the tag carries `blocking="render"`, which holds the FIRST RENDER back until the resource has been+ * fetched and evaluated.*- * The spec's own reading: "Let value be the value of el's blocking attribute...- * converted to ASCII lowercase... split on ASCII whitespace", then "An element is- * potentially render-blocking if its blocking tokens set contains 'render'", and in- * prepare the script element, "If el is potentially render-blocking, then block- * rendering on el" -- which is reached for any external script, `async` or not. The- * async/defer carve-out applies only to what is IMPLICITLY render-blocking.+ * The spec's own reading: "Let value be the value of el's blocking attribute... converted to ASCII lowercase...+ * split on ASCII whitespace", then "An element is potentially render-blocking if its blocking tokens set+ * contains 'render'", and in prepare the script element, "If el is potentially render-blocking, then block+ * rendering on el", which is reached for any external script, `async` or not. The async/defer carve-out applies+ * only to what is IMPLICITLY render-blocking.* https://html.spec.whatwg.org/multipage/urls-and-fetching.html#blocking-attributes* https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element*- * Measured, not assumed: a `<script async blocking="render" src>` held back for two- * seconds moved first contentful paint from 20 ms to 2,020 ms in Chromium 151 and- * from 11 ms to 2,009 ms in WebKit 26.5, with Chromium reporting the request's- * renderBlockingStatus as "blocking". Firefox has not shipped it (bugzil.la/1751383)- * and simply treats the script as async.+ * Measured, not assumed: a `<script async blocking="render" src>` held back for two seconds moved first+ * contentful paint from 20 ms to 2,020 ms in Chromium 151 and from 11 ms to 2,009 ms in WebKit 26.5, with+ * Chromium reporting the request's renderBlockingStatus as "blocking". Firefox has not shipped it+ * (bugzil.la/1751383) and simply treats the script as async.*/function blocksRender(tag: StartTag): boolean {return (attr(tag, "blocking") ?? "")@@ -284,16 +262,12 @@ function blocksRender(tag: StartTag): boolean {}/**- * The eager set, in three buckets, as paths relative to `dist/`.- *- * `entry` and `preloads` are Vite's output and stay apart so the caller can tell- * "Vite stopped emitting preload links" from "this page really does load one- * chunk": flattened, a build with no preloads reads as a very small app.- *- * `blocking` is the classic `<script src>` in `<head>`, which is not Vite's and- * carries no preload link, but is parser-blocking: it is downloaded and run before- * the module graph starts. `public/theme-boot.js` is one, and left out it could- * grow without limit inside a gate whose whole subject is startup JavaScript.+ * The eager set, in three buckets, as paths relative to `dist/`. `entry` and `preloads` are Vite's output and+ * stay apart so the caller can tell "Vite stopped emitting preload links" from "this page really does load one+ * chunk": flattened, a build with no preloads reads as a very small app. `blocking` is the classic `<script+ * src>` in `<head>`, which is not Vite's and carries no preload link, but is parser-blocking: it is downloaded+ * and run before the module graph starts. `public/theme-boot.js` is one, and left out it could grow without+ * limit inside a gate whose whole subject is startup JavaScript.*/export type EagerSet = {entry: string[];@@ -302,22 +276,18 @@ export type EagerSet = {};/**- * A `type` the browser still runs as a classic script. An absent type is the same- * thing; anything else (`importmap`, `application/json`, a template) is not code- * that runs, and `module` is handled on its own.+ * A `type` the browser still runs as a classic script. An absent type is the same thing; anything else+ * (`importmap`, `application/json`, a template) is not code that runs, and `module` is handled on its own.*- * Exact strings, deliberately. The spec matches this attribute on JavaScript MIME- * type ESSENCE, so a parameter makes it match nothing: `text/javascript;- * charset=utf-8` is not evaluated, and Chromium, Firefox and WebKit do not even- * fetch such a script. Bytes the browser never requests are not startup cost.+ * Exact strings, deliberately. The spec matches this attribute on JavaScript MIME type ESSENCE, so a parameter+ * makes it match nothing: `text/javascript; charset=utf-8` is not evaluated, and Chromium, Firefox and WebKit do+ * not even fetch such a script. Bytes the browser never requests are not startup cost.*- * The whole essence list, not the four anyone would write today. The legacy- * spellings are not historical trivia: every one of them still executes. Measured- * in Chromium 151, a script tagged `application/x-javascript`, `text/jscript`,- * `text/javascript1.5`, `text/livescript`, `application/x-ecmascript` or- * `text/x-javascript` runs, while `text/javascript; charset=utf-8` and- * `application/json` do not. The list is frozen, so this does not grow.- * https://mimesniff.spec.whatwg.org/#javascript-mime-type+ * The whole essence list, not the four anyone would write today. The legacy spellings are not historical+ * trivia: every one of them still executes. Measured in Chromium 151, a script tagged+ * `application/x-javascript`, `text/jscript`, `text/javascript1.5`, `text/livescript`, `application/x-ecmascript`+ * or `text/x-javascript` runs, while `text/javascript; charset=utf-8` and `application/json` do not. The list is+ * frozen, so this does not grow. https://mimesniff.spec.whatwg.org/#javascript-mime-type*/const CLASSIC_TYPES = new Set(["application/ecmascript",@@ -367,19 +337,15 @@ export function eagerSetFromHtml(html: string): EagerSet {// Vite's entry, always one of its own hashed assets.add(set.entry, attr(tag, "src"), "assets/");} else if (!type || CLASSIC_TYPES.has(type)) {- // Counts from anywhere in the build, not just assets/. `defer` is included:- // a deferred script runs after parsing but BEFORE DOMContentLoaded, in- // document order with the module entry, which is itself deferred -- so it is- // on exactly the timeline this budgets. Only `async` is out, having no- // ordering relationship to the first screen at all. `async` also wins when- // both are present, which is why it is the one tested.- //- // Unless it is asked to block rendering, which restores the relationship the- // exclusion assumes is absent: `blocking="render"` is the documented way to- // keep a boot script off the parser without letting the unthemed page paint,- // and it delays the first screen by the whole fetch and evaluation. Not- // counting it would leave the one thing this gate exists to bound -- bytes- // between the navigation and the first screen -- unbounded.+ // Counts from anywhere in the build, not just assets/. `defer` is included: a deferred script runs after+ // parsing but BEFORE DOMContentLoaded, in document order with the module entry, which is itself deferred, so+ // it is on exactly the timeline this budgets. Only `async` is out, having no ordering relationship to the+ // first screen at all. `async` also wins when both are present, which is why it is the one tested. Unless it+ // is asked to block rendering, which restores the relationship the exclusion assumes is absent:+ // `blocking="render"` is the documented way to keep a boot script off the parser without letting the+ // unthemed page paint, and it delays the first screen by the whole fetch and evaluation. Not counting it+ // would leave the one thing this gate exists to bound, bytes between the navigation and the first screen,+ // unbounded.if (!hasAttr(tag, "async") || blocksRender(tag)) {add(set.blocking, attr(tag, "src"));}@@ -402,9 +368,9 @@ export function eagerChunksFromHtml(html: string): string[] {type Measured = { name: string; raw: number; transfer: number };/**- * What the browser actually downloads. The backend gzips the `/assets` mount only- * (studio/backend/main.py mounts `_AssetGZipMiddleware` there); everything else- * goes out through a plain FileResponse, so its raw size IS its transfer size.+ * What the browser actually downloads. The backend gzips the `/assets` mount only (studio/backend/main.py mounts+ * `_AssetGZipMiddleware` there); everything else goes out through a plain FileResponse, so its raw size IS its+ * transfer size.*/function transferBytes(name: string, bytes: Buffer): number {return name.startsWith("assets/")@@ -419,9 +385,8 @@ function measure(names: string[]): Measured[] | string {try {bytes = readFileSync(join(DIST, name));} catch {- // index.html names a file the build did not emit. Reporting it rather than- // a stack trace, because the alternative reading -- that the budget is fine- // -- is the one that must never be reachable.+ // index.html names a file the build did not emit. Reporting it rather than a stack trace, because the+ // alternative reading, that the budget is fine, is the one that must never be reachable.return `dist/index.html references ${name}, which is not in the build`;}out.push({@@ -449,28 +414,21 @@ function main(): number {const { entry, preloads, blocking } = eagerSetFromHtml(html);const names = [...blocking, ...entry, ...preloads];- // Counting Vite's own output only: a parser-blocking classic script is not- // evidence that the module graph was read correctly, so it cannot stand in for- // the entry when deciding whether this still understands the build.- //- // A code-split build of this app is dozens of chunks. One or none means the- // shape this reads has changed and the number below would be fiction: with- // `build.modulePreload: false` the links disappear and the entry alone measured- // 424 KB of a 5,207 KB startup path, reporting 4.8 MB to spare. A comfortable- // pass is the one answer this must never give by accident.- //- // Counting scripts and links together rather than requiring both: when the entry- // module is nothing but imports, Vite inlines it into one `<script>` per imported- // chunk and emits no preload links at all, which is a complete measurement. So- // the total is what decides whether this is a code-split build.- //- // But at least one entry is required on top of that total, because preloads- // without one is not a build shape Vite emits: a modulepreload link exists to- // announce the entry's static import closure, so links surviving while the entry- // does not means the entry was read wrong, not that it is absent. Left to the- // total alone, the app's 48 links carry the guard while the largest single chunk- // in the startup path silently leaves the measurement -- which is exactly how- // two mis-parses of this file's own making stayed invisible.+ // Counting Vite's own output only: a parser-blocking classic script is not evidence that the+ // module graph was read correctly, so it cannot stand in for the entry when deciding whether this+ // still understands the build. A code-split build of this app is dozens of chunks. One or none+ // means the shape this reads has changed and the number below would be fiction: with+ // `build.modulePreload: false` the links disappear and the entry alone measured 424 KB of a 5,207+ // KB startup path, reporting 4.8 MB to spare. A comfortable pass is the one answer this must+ // never give by accident. Counting scripts and links together rather than requiring both: when+ // the entry module is nothing but imports, Vite inlines it into one `<script>` per imported chunk+ // and emits no preload links at all, which is a complete measurement. So the total is what+ // decides whether this is a code-split build. But at least one entry is required on top of that+ // total, because preloads without one is not a build shape Vite emits: a modulepreload link+ // exists to announce the entry's static import closure, so links surviving while the entry does+ // not means the entry was read wrong, not that it is absent. Left to the total alone, the app's+ // 48 links carry the guard while the largest single chunk in the startup path silently leaves the+ // measurement, which is exactly how two mis-parses of this file's own making stayed invisible.const fromVite = entry.length + preloads.length;if (entry.length === 0 || fromVite < 2) {console.error(@@ -528,12 +486,10 @@ function main(): number {}/**- * True when this file was run, rather than imported by the tests.- *- * Compared through realpath on both sides. `import.meta.url` is already the real- * path (node resolves modules through symlinks), while `process.argv[1]` is the- * path as typed, so a checkout reached through a symlinked directory made the two- * disagree and the whole check became a silent no-op that exited 0.+ * True when this file was run, rather than imported by the tests. Compared through realpath on both sides.+ * `import.meta.url` is already the real path (node resolves modules through symlinks), while `process.argv[1]`+ * is the path as typed, so a checkout reached through a symlinked directory made the two disagree and the whole+ * check became a silent no-op that exited 0.*/function invokedDirectly(): boolean {const argv = process.argv[1];diff --git a/studio/frontend/smoke-code-block-flicker-main.tsx b/studio/frontend/smoke-code-block-flicker-main.tsxindex 69f7ead203c..ea7cfe29a43 100644--- a/studio/frontend/smoke-code-block-flicker-main.tsx+++ b/studio/frontend/smoke-code-block-flicker-main.tsx@@ -2,20 +2,16 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0// Harness page for tests/studio/playwright_code_block_flicker.py: the real Thread, streaming a-// reply that ends in code fences, sampling every code block's rendered HEIGHT per frame.-//-// The mechanism it catches: streamdown sets `content-visibility: auto` with-// `contain-intrinsic-size: auto 200px` inline on every code-block wrapper. Such an element has no-// LAST REMEMBERED SIZE until it has rendered once, so it lays out at the 200px fallback. The-// re-render at the end of a stream REPLACES the node, and a replaced node is new, so it can lay-// out at 200px for a frame before snapping back. That is the "reload" flicker src/index.css-// describes. So the measurement is not a timing: did a TALL block go SHORT and back, and did the-// thread's scrollHeight dip with it -- per frame, the resolution a flicker is visible at.-//-// Same shape as smoke-heavy-thread.html: vite entry, no backend, auth, GPU or model. Thread is-// real because `.aui-thread-root` is where the override lives; a bare ThreadPrimitive.Root lacks-// that class and would report no flicker on every tree.-//+// reply that ends in code fences, sampling every code block's rendered HEIGHT per frame. The+// mechanism it catches: streamdown sets `content-visibility: auto` with `contain-intrinsic-size:+// auto 200px` inline on every code-block wrapper. Such an element has no LAST REMEMBERED SIZE until+// it has rendered once, so it lays out at the 200px fallback. The re-render at the end of a stream+// REPLACES the node, and a replaced node is new, so it can lay out at 200px for a frame before+// snapping back. That is the "reload" flicker src/index.css describes. So the measurement is not a+// timing: did a TALL block go SHORT and back, and did the thread's scrollHeight dip with it -- per+// frame, the resolution a flicker is visible at. Same shape as smoke-heavy-thread.html: vite entry,+// no backend, auth, GPU or model. Thread is real because `.aui-thread-root` is where the override+// lives; a bare ThreadPrimitive.Root lacks that class and would report no flicker on every tree.// useLocalRuntime with a generator adapter, not a seeded import: the flicker is at stream// FINALIZATION, and `thread.import` never passes through the running -> complete transition.@@ -65,16 +61,13 @@ window.fetch = (input, init) => {return realFetch(input, init);};-// ── CSS variants ────────────────────────────────────────────────────-//-// Each variant is a stylesheet appended AFTER src/index.css, not an edit to the tree. `?css=tree`-// is the pass/fail run; the others exist so "no flicker" can be shown to be a property of the-// tree rather than of the fixture.-//-// The prefix is deliberately OVERSPECIFIC. The tree's rules are scoped-// (`.aui-thread-root[data-status="running"] ...`), so a variant at the obvious specificity loses-// to them exactly where it matters and measures the tree under another name -- that once made-// the pre-override variant report zero flickers, reading as "nothing to fix".+// ── CSS variants ──────────────────────────────────────────────────── Each variant is a stylesheet+// appended AFTER src/index.css, not an edit to the tree. `?css=tree` is the pass/fail run; the+// others exist so "no flicker" can be shown to be a property of the tree rather than of the+// fixture. The prefix is deliberately OVERSPECIFIC. The tree's rules are scoped+// (`.aui-thread-root[data-status="running"] ...`), so a variant at the obvious specificity loses to+// them exactly where it matters and measures the tree under another name -- that once made the+// pre-override variant report zero flickers, reading as "nothing to fix".const HERE = ".aui-thread-root.aui-thread-root.aui-thread-root";const BLOCK = '[data-streamdown="code-block"]';@@ -139,8 +132,6 @@ if (variantCss) {document.head.append(style);}-// ── content ─────────────────────────────────────────────────────────-const PROSE = ["The reception of a long thread is decided by what the renderer does on every interaction rather than by what it did once at load.","A reply that arrives quickly can still leave a thread that answers a keystroke slowly, because the two costs are paid in different places.",@@ -209,8 +200,6 @@ function reply(fences: number, linesPerFence: number): string {return parts.join("\n\n");}-// ── sampling ────────────────────────────────────────────────────────-type Frame = {t: number;/** Height of every [data-streamdown="code-block"] in DOM order. */diff --git a/studio/frontend/smoke-collapse-layout-main.tsx b/studio/frontend/smoke-collapse-layout-main.tsxindex 666c0b221bc..71c41a8086b 100644--- a/studio/frontend/smoke-collapse-layout-main.tsx+++ b/studio/frontend/smoke-collapse-layout-main.tsx@@ -2,17 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0// Harness page for tests/studio/playwright_collapse_layout.py.-//// It answers one question: when a collapsible toggles, does the browser lay out the WHOLE document,// and does that cost scale with how big the document is?-//// The design point that makes the answer readable is that the COLLAPSIBLE'S OWN CONTENT IS// IDENTICAL IN EVERY RUN. Only the filler around it changes size. So if a toggle gets more// expensive as `fillers` grows, the extra cost cannot be the pane's own content -- it is the rest// of the document being laid out because of a toggle that has nothing to do with it.-//// Four arms, selected with `?arm=`:-//// radix-height Radix `CollapsibleContent` + the `animate-collapsible-*` height keyframes.// Today's mechanism.// radix-grid Radix `CollapsibleContent` + a `grid-template-rows: 0fr -> 1fr` transition,@@ -26,7 +22,6 @@// reasoning The real `ReasoningRoot` / `ReasoningTrigger` / `ReasoningContent` /// `ReasoningText`, which follow GRID_COLLAPSE_REASONING_ENABLED. Run the page// once per flag value to get the real before/after rather than a model of it.-//// No backend, no runtime: the reasoning primitives are plain components, and giving them a// synthetic runtime would only add nodes that are not part of what is being measured.@@ -99,17 +94,15 @@ function PaneBody({ extra }: { extra: number }) {// `animate-collapsible-down` / `animate-collapsible-up`, and tailwind-merge does not know those as// members of its `animate` group, so a wrapper-based grid arm would silently keep the height// keyframes and the comparison would be between two things that both animate height.-//-// `heightContentClass` is `reasoning.tsx`'s own list with the duration inlined.-//-// The two grid arms do NOT share a class string, and the first attempt at this got it wrong in a-// way worth recording. Radix has no "presence separate from state", so its arm has to drive the-// row size off `data-state`. `UnmeasuredCollapsibleContent` drives it off its own staged-// `expanded`, which lags `data-state` by two frames precisely so the `0fr` start value exists.-// Giving the unmeasured arm the `data-[state=open]:grid-rows-[1fr]` variant as well let the-// attribute selector -- higher specificity than the plain class -- win at mount, and the pane-// snapped open with no transition while still reporting a clean layout count. A cheap-looking-// number for an animation that was not running.+// `heightContentClass` is `reasoning.tsx`'s own list with the duration inlined. The two grid arms+// do NOT share a class string, and the first attempt at this got it wrong in a way worth recording.+// Radix has no "presence separate from state", so its arm has to drive the row size off+// `data-state`. `UnmeasuredCollapsibleContent` drives it off its own staged `expanded`, which lags+// `data-state` by two frames precisely so the `0fr` start value exists. Giving the unmeasured arm+// the `data-[state=open]:grid-rows-[1fr]` variant as well let the attribute selector -- higher+// specificity than the plain class -- win at mount, and the pane snapped open with no transition+// while still reporting a clean layout count. A cheap-looking number for an animation that was not+// running.const heightContentClass ="overflow-hidden ease-out data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down data-[state=closed]:fill-mode-forwards data-[state=open]:duration-200 data-[state=closed]:duration-200";diff --git a/studio/frontend/smoke-find-in-page-main.tsx b/studio/frontend/smoke-find-in-page-main.tsxindex 28f27b1e1d7..0d5a96e76af 100644--- a/studio/frontend/smoke-find-in-page-main.tsx+++ b/studio/frontend/smoke-find-in-page-main.tsx@@ -2,11 +2,10 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0// Harness for the find bar: a vite entry with no backend, driving the real bar, the real index and-// the real CSS Custom Highlight API against a real browser.-//-// The node suite reaches everything pure. What a highlight looks like painted, whether the walk-// scrolls only when a match is off screen, whether an `inert` panel stays out of the count, and-// what a streaming reply costs an open bar are only answerable here.+// the real CSS Custom Highlight API against a real browser. The node suite reaches everything pure.+// What a highlight looks like painted, whether the walk scrolls only when a match is off screen,+// whether an `inert` panel stays out of the count, and what a streaming reply costs an open bar are+// only answerable here./* eslint-disable no-restricted-imports -- a harness entry point, not app code. */import {diff --git a/studio/frontend/smoke-heavy-thread-main.tsx b/studio/frontend/smoke-heavy-thread-main.tsxindex 4e9288c11e7..e73e3199ad9 100644--- a/studio/frontend/smoke-heavy-thread-main.tsx+++ b/studio/frontend/smoke-heavy-thread-main.tsx@@ -1,19 +1,15 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Harness page for tests/studio/playwright_heavy_thread.py: the real Thread holding a HEAVY-// thread, so the measured cost of typing, scrolling, opening a menu, deleting and re-opening is-// the app's own and grows the way a long session's does.-//-// The axis is CHARACTERS OF THREAD CONTENT, not messages. Users report the slowdown after "long-// generations with any code cells and/or text", which is a statement about volume, so a fixture-// of N short paragraphs would measure the wrong variable.-//-// The content mix is the one the report names, and every kind of it is present at every size-// because the fixture is built in whole CYCLES of one message per kind (~26K characters a-// cycle). Building "until the budget runs out" instead would give the smallest size only the-// first few kinds, and the curve would then be reporting a change of fixture, not of size.-//+// Harness page for tests/studio/playwright_heavy_thread.py: the real Thread holding a HEAVY thread, so the+// measured cost of typing, scrolling, opening a menu, deleting and re-opening is the app's own and grows the way+// a long session's does.+// The axis is CHARACTERS OF THREAD CONTENT, not messages. Users report the slowdown after "long generations with+// any code cells and/or text", which is a statement about volume, so a fixture of N short paragraphs would+// measure the wrong variable. The content mix is the one the report names, and every kind of it is present at+// every size because the fixture is built in whole CYCLES of one message per kind (~26K characters a cycle).+// Building "until the budget runs out" instead would give the smallest size only the first few kinds, and the+// curve would then be reporting a change of fixture, not of size.// prose long multi-paragraph answers// python fence a large highlighted code fence// typescript fence a second language, so one grammar is not the whole Shiki story@@ -24,23 +20,17 @@// svg fence a highlighted fence that also renders an inline <img> preview// image parts a raster PNG data URL and a unique SVG data URL, as image content parts// json fence one very long line, the shape that behaves worst in a highlighter-//-// Two honest limits, both of which the harness's own docstring repeats:-//-// * The HTML artifact renders as an artifact CARD here, not as a live preview. The <iframe>-// lives in ArtifactSurface on the chat page, and it loads its content from the backend-// (/api/inference/artifact-preview-frame), so it cannot exist on a backend-free smoke page.-// What is measured is the in-thread cost of an artifact, which is what a scroll pays.-// * `python` results carry `images: []`. A non-empty list makes the card fetch each image from-// the backend, which would put a network round trip inside a timed region.-//-// Same shape as smoke-autoscroll.html and smoke-thread-weight.html: a vite entry, no backend, no-// auth. Thread itself and the message bodies are real on purpose; mocking either deletes the-// measurement. The runtime is synthetic -- a local runtime whose model adapter never runs,-// seeded through `thread.import`.-//-// useLocalRuntime rather than useExternalStoreRuntime: the delete path under measurement is-// `thread.export()` -> MessageRepository -> `thread.import()`, which only the local runtime backs.+// Two honest limits, both of which the harness's own docstring repeats. The HTML artifact renders as an artifact+// CARD here, not as a live preview: the <iframe> lives in ArtifactSurface on the chat page and loads its content+// from the backend (/api/inference/artifact-preview-frame), so it cannot exist on a backend-free smoke page. What+// is measured is the in-thread cost of an artifact, which is what a scroll pays. And `python` results carry+// `images: []`, since a non-empty list makes the card fetch each image from the backend, which would put a+// network round trip inside a timed region.+// Same shape as smoke-autoscroll.html and smoke-thread-weight.html: a vite entry, no backend, no auth. Thread+// itself and the message bodies are real on purpose; mocking either deletes the measurement. The runtime is+// synthetic, a local runtime whose model adapter never runs, seeded through `thread.import`. useLocalRuntime+// rather than useExternalStoreRuntime: the delete path under measurement is `thread.export()` ->+// MessageRepository -> `thread.import()`, which only the local runtime backs.import { Thread } from "@/components/assistant-ui/thread";import { TooltipProvider } from "@/components/ui/tooltip";@@ -62,44 +52,36 @@ import { type ReactElement, useEffect, useRef, useState } from "react";import { createRoot } from "react-dom/client";import "./src/index.css";-// The local runtime's thread list item reports a synthetic `__LOCALID_...` remoteId, which is-// truthy, so the fork-count badges really do ask the backend. Answering them here, before anything-// mounts, keeps that off the wire entirely; answering them from the Playwright side instead would-// put a round trip to another process inside a timed region.-// An explicit allowlist, never a blanket `/api/` match. A blanket match resolves EVERY request the-// measured interactions make before Playwright emits it, so `stray_api_requests` stays at zero and-// the fan-out this harness exists to detect becomes invisible to it. Narrowing it is what made the-// two entries below visible in the first place.-//-// Each entry answers a request the harness itself provokes, with the body that endpoint really-// returns, so no round trip lands inside a timed region. Anything NOT listed here goes to the-// network and trips the stray counter, which is the point.+// The local runtime's thread list item reports a synthetic `__LOCALID_...` remoteId, which is truthy, so the+// fork-count badges really do ask the backend. Answering them here, before anything mounts, keeps that off the+// wire entirely; answering them from the Playwright side instead would put a round trip to another process inside+// a timed region. An explicit allowlist, never a blanket `/api/` match: a blanket match resolves EVERY request the+// measured interactions make before Playwright emits it, so `stray_api_requests` stays at zero and the fan-out+// this harness exists to detect becomes invisible to it. Narrowing it is what made the two entries below visible+// in the first place. Each entry answers a request the harness itself provokes, with the body that endpoint+// really returns, so no round trip lands inside a timed region. Anything NOT listed here goes to the network and+// trips the stray counter, which is the point.const STUBBED_API: ReadonlyArray<readonly [RegExp, string]> = [- // The fork-count badges. One GET per THREAD, not per message: fork-count-store subscribes once- // per rendered thread and refreshes on CHAT_HISTORY_UPDATED_EVENT, which the delete action- // fires, so the harness provokes it during seeding and again inside the measured actions.- //- // The endpoint used to be per message, `/threads/{id}/messages/{id}/forks` answering- // `{"count":n}`, and that is the shape this allowlist was written against. The per-thread- // endpoint replaced it and this entry was not moved with it, so every one of these went to the- // dev server and the run failed its own stray-request check. Match the shape the app actually- // requests, and answer with the body it actually returns: `getThreadForkCounts` reads- // `data.counts` and builds a Map from it, so `{"counts":{}}` is "no message has forks" and- // renders no badge on any message. An empty `{}` body would leave the same empty Map today, but- // it is not what the endpoint returns, and a stub that answers a shape the endpoint never sends- // is how this drifted in the first place.+ // The fork-count badges. One GET per THREAD, not per message: fork-count-store subscribes once per rendered+ // thread and refreshes on CHAT_HISTORY_UPDATED_EVENT, which the delete action fires, so the harness provokes it+ // during seeding and again inside the measured actions. The endpoint used to be per message,+ // `/threads/{id}/messages/{id}/forks` answering `{"count":n}`, and that is the shape this allowlist was written+ // against. The per-thread endpoint replaced it and this entry was not moved with it, so every one of these went+ // to the dev server and the run failed its own stray-request check. Match the shape the app actually requests,+ // and answer with the body it actually returns: `getThreadForkCounts` reads `data.counts` and builds a Map from+ // it, so `{"counts":{}}` is "no message has forks" and renders no badge on any message. An empty `{}` body would+ // leave the same empty Map today, but it is not what the endpoint returns, and a stub that answers a shape the+ // endpoint never sends is how this drifted in the first place.[/\/api\/chat\/threads\/[^/]+\/forks$/, '{"counts":{}}'],- // The delete action's own persistence. deleteThreadMessage syncs the exported repository- // whenever remoteId is truthy, which the synthetic id always is, so this is the fixture- // maintaining itself rather than app fan-out. Left on the wire it is 3 round trips inside the- // delete measurement, and it fails the run's own stray check.+ // The delete action's own persistence. deleteThreadMessage syncs the exported repository whenever remoteId is+ // truthy, which the synthetic id always is, so this is the fixture maintaining itself rather than app fan-out.+ // Left on the wire it is 3 round trips inside the delete measurement, and it fails the run's own stray check.[/\/api\/chat\/threads\/[^/]+\/messages$/, '{"messages":[]}'],[/\/api\/chat\/threads\/[^/]+$/, "{}"],- // App fan-out, NOT fixture upkeep: re-opening a thread asks for the project list and the- // knowledge bases. Stubbed so a dev-server round trip does not land inside the reopen window,- // which would be measuring the network rather than the render. They are recorded in- // `__stubbedApi` and printed as "stubbed api requests" rather than being silently swallowed,- // because two whole-endpoint GETs per reopen is a real cost and should stay visible.+ // App fan-out, NOT fixture upkeep: re-opening a thread asks for the project list and the knowledge bases.+ // Stubbed so a dev-server round trip does not land inside the reopen window, which would be measuring the+ // network rather than the render. They are recorded in `__stubbedApi` and printed as "stubbed api requests"+ // rather than being silently swallowed, because two whole-endpoint GETs per reopen is a real cost.[/\/api\/chat\/projects(\?|$)/, '{"projects":[]}'],[/\/api\/rag\/knowledge-bases(\?|$)/, '{"knowledge_bases":[]}'],];@@ -126,12 +108,10 @@ window.fetch = (input, init) => {return realFetch(input, init);};-// ── content generators ──────────────────────────────────────────────-//-// Every generator takes the block index and produces content that is UNIQUE to it. That is not-// decoration: code-plugin.ts caches highlighted tokens keyed on the exact source string, so a-// fixture that repeats one fence would highlight it once and hand back the cached result for-// every other copy, and the Shiki cost would vanish from the curve.+// Content generators. Every generator takes the block index and produces content that is UNIQUE to it. That is+// not decoration: code-plugin.ts caches highlighted tokens keyed on the exact source string, so a fixture that+// repeats one fence would highlight it once and hand back the cached result for every other copy, and the Shiki+// cost would vanish from the curve.const PROSE_SENTENCES = ["The reception of a long thread is decided by what the renderer does on every interaction, not by what it did once at load.",@@ -265,10 +245,9 @@ function htmlArtifact(index: number, targetChars: number): string {}function svgFence(index: number, targetChars: number): string {- // Unsloth renders a highlighted fence AND an inline <img> preview for an svg fence, so this one- // block buys both a Shiki pass and an image decode. No <script>, no on*= handlers, no- // <foreignObject>: any of those make the preview refuse to render and the block silently- // becomes an ordinary code fence.+ // Unsloth renders a highlighted fence AND an inline <img> preview for an svg fence, so this one block buys both+ // a Shiki pass and an image decode. No <script>, no on*= handlers, no <foreignObject>: any of those make the+ // preview refuse to render and the block silently becomes an ordinary code fence.const open = [`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 160" width="320" height="160">`];const close = ["</svg>"];const body: string[] = [];@@ -327,13 +306,10 @@ const PNG_DATA_URL =const pngCache = new Map<number, string>();/**- * A PNG that is unique to this block, so each one is a separate decode rather than a cache hit- * on the last.- *+ * A PNG that is unique to this block, so each one is a separate decode rather than a cache hit on the last.* Drawn and exported here rather than embedded as a literal because assistant-ui only accepts- * `data:image/(png|jpeg|jpg|gif|webp);base64,` for an image part and drops anything else with a- * console warning -- an SVG data URL, which would have been the easy way to vary the bytes, is- * silently discarded.+ * `data:image/(png|jpeg|jpg|gif|webp);base64,` for an image part and drops anything else with a console warning:+ * an SVG data URL, which would have been the easy way to vary the bytes, is silently discarded.*/function pngDataUrl(index: number): string {const cached = pngCache.get(index);@@ -363,8 +339,6 @@ function pngDataUrl(index: number): string {return url;}-// ── the cycle ───────────────────────────────────────────────────────-type Part = NonNullable<Exclude<ThreadMessageLike["content"], string>>[number];/** One block: the user's prompt and the assistant messages it produced. */@@ -566,13 +540,11 @@ type Plan = {};/**- * What one cycle must put on screen. The Python side multiplies these by the cycle count and- * fails the run if the DOM holds fewer.- *- * This is not belt and braces. assistant-ui drops an image part whose data URL is not- * `data:image/(png|jpeg|jpg|gif|webp);base64,` with nothing but a console.warn, and a fixture- * that quietly loses its images still renders 300K characters of prose and code and still- * produces a rising curve -- of the wrong thing.+ * What one cycle must put on screen. The Python side multiplies these by the cycle count and fails the run if the+ * DOM holds fewer. This is not belt and braces: assistant-ui drops an image part whose data URL is not+ * `data:image/(png|jpeg|jpg|gif|webp);base64,` with nothing but a console.warn, and a fixture that quietly loses+ * its images still renders 300K characters of prose and code and still produces a rising curve, of the wrong+ * thing.*/const EXPECTED_PER_CYCLE: Record<string, number> = {// Two image parts in the image block, plus the inline preview the svg fence renders.@@ -586,27 +558,23 @@ const EXPECTED_PER_CYCLE: Record<string, number> = {// python, typescript, json, svg, the html document, and the two tool result panes.codeBlocks: 7,/*- * THE CODE ITSELF, in characters: the one size measure deferral cannot move.- *- * This was a floor of 2,500 highlighted tokens, doing two jobs at once. Off-screen fences now- * render as a plain shell, so tokens partly measure where the viewport is: the same fixture- * renders 1,322 per cycle where it rendered 3,216. Characters do not move, because the shell- * carries the same text node: 12,660 for one cycle and 51,081 for four (2 of 5 and 15 of 20- * fences deferred), and Chromium, Firefox and WebKit each report 12,660 to the character.- *- * Floor 12,000 against 12,660; a cycle is seven blocks averaging ~1,800 chars, so losing any one- * block still fails. The other job, telling a settled thread from one still building itself, is- * now `unhighlightedMountedFences`, asked per block.- */+ * THE CODE ITSELF, in characters: the one size measure deferral cannot move.+ * This was a floor of 2,500 highlighted tokens, doing two jobs at once. Off-screen fences now render as a plain+ * shell, so tokens partly measure where the viewport is: the same fixture renders 1,322 per cycle where it+ * rendered 3,216. Characters do not move, because the shell carries the same text node: 12,660 for one cycle+ * and 51,081 for four (2 of 5 and 15 of 20 fences deferred), and Chromium, Firefox and WebKit each report+ * 12,660 to the character.+ * Floor 12,000 against 12,660; a cycle is seven blocks averaging ~1,800 chars, so losing any one block still+ * fails. The other job, telling a settled thread from one still building itself, is now+ * `unhighlightedMountedFences`, asked per block.+ */codeChars: 12000,};/**- * Whole cycles of one block per kind until `targetChars` is reached, never fewer than one.- *- * Whole cycles, not "blocks until the budget runs out": a partial cycle would give the smallest- * size only the first few kinds of content, so the curve across sizes would be reporting a change- * of fixture as well as a change of size.+ * Whole cycles of one block per kind until `targetChars` is reached, never fewer than one. Whole cycles, not+ * "blocks until the budget runs out": a partial cycle would give the smallest size only the first few kinds of+ * content, so the curve across sizes would be reporting a change of fixture as well as a change of size.*/function buildThread(targetChars: number): { messages: ThreadMessageLike[]; plan: Plan } {const messages: ThreadMessageLike[] = [];@@ -671,14 +639,12 @@ function HeavyThreadApi({return built.plan;},/**- * Like seed(), then N one-word messages after it. Used by the viewport-gap measurement in- * #9058: the tail makes the first mount commit land entirely on compact rows, which is the- * worst case for a fixed-size initial window.- *- * It REPLACES rather than appends, and the heavy part is the same buildThread() call seed()- * makes, so every census count for `targetChars` is identical to seed(targetChars). The only- * difference is the tail, which is text parts only: no fences, images or tool calls.- */+ * Like seed(), then N one-word messages after it. Used by the viewport-gap measurement in #9058: the tail+ * makes the first mount commit land entirely on compact rows, which is the worst case for a fixed-size+ * initial window. It REPLACES rather than appends, and the heavy part is the same buildThread() call seed()+ * makes, so every census count for `targetChars` is identical to seed(targetChars). The only difference is+ * the tail, which is text parts only: no fences, images or tool calls.+ */seedCompactTail(targetChars: number, tailMessages: number): Plan {const built = buildThread(targetChars);const messages = built.messages.slice();@@ -694,13 +660,11 @@ function HeavyThreadApi({return { ...built.plan, messages: messages.length };},/**- * The empty band below the last mounted row, in px.- *- * gapBottom is measured against the viewport's BOTTOM EDGE, not against scrollHeight, so the- * viewport's own bottom spacer counts as the gap it always was and the caller subtracts- * spacerHeight to get the part the mount window is responsible for. Computed any other way- * the numbers stop being comparable across sizes.- */+ * The empty band below the last mounted row, in px. gapBottom is measured against the viewport's BOTTOM+ * EDGE, not against scrollHeight, so the viewport's own bottom spacer counts as the gap it always was and+ * the caller subtracts spacerHeight to get the part the mount window is responsible for. Computed any other+ * way the numbers stop being comparable across sizes.+ */gapMetrics(): Record<string, number> {const element = api.viewport();if (!element) return { ok: 0 };@@ -728,23 +692,20 @@ function HeavyThreadApi({};},/**- * Put the seeded thread back, and answer with how many messages that is.- *- * Deleting a message is destructive to the repository, not to the view, so re-opening does- * not undo it. Restoring is the same import seed() does: cheap on the harness side, and it- * is untimed, but every timed repetition then runs on the same fixture rather than on a- * thread that is one message shorter each time round.- */+ * Put the seeded thread back, and answer with how many messages that is. Deleting a message is destructive+ * to the repository, not to the view, so re-opening does not undo it. Restoring is the same import seed()+ * does: cheap on the harness side, and it is untimed, but every timed repetition then runs on the same+ * fixture rather than on a thread that is one message shorter each time round.+ */restore(): number {aui.thread().import(ExportedMessageRepository.fromArray(seeded.current));return seeded.current.length;},/**- * Open every tool card. Radix unmounts collapsed content, so a thread of closed cards- * carries no result panes at all and the "tool calls with collapsible output" half of the- * fixture would be a row of buttons. A user who has just watched those tools run is- * looking at them open, which is the state worth measuring.- */+ * Open every tool card. Radix unmounts collapsed content, so a thread of closed cards carries no result+ * panes at all and the "tool calls with collapsible output" half of the fixture would be a row of buttons. A+ * user who has just watched those tools run is looking at them open, which is the state worth measuring.+ */expandTools(): number {const triggers = Array.from(document.querySelectorAll<HTMLElement>('[data-slot="tool-fallback-trigger"]'),@@ -766,10 +727,10 @@ function HeavyThreadApi({return mounted;},/**- * One selector pass. Polling for a deletion has to read this, not counts(): counts() is a- * dozen document-wide queries including a walk of every element, so at 300K characters a- * poll loop built on it would spend more time measuring than the delete itself takes.- */+ * One selector pass. Polling for a deletion has to read this, not counts(): counts() is a dozen+ * document-wide queries including a walk of every element, so at 300K characters a poll loop built on it+ * would spend more time measuring than the delete itself takes.+ */messageCount(): number {return document.querySelectorAll("[data-role]").length;},@@ -778,10 +739,10 @@ function HeavyThreadApi({return document.querySelectorAll("pre code span").length;},/**- * Everything a caller might use to prove the fixture landed. A harness that asks for 300K- * characters of mixed content and silently renders 200K of prose measures the wrong thing,- * so the Python side prints every one of these and fails on any that is zero.- */+ * Everything a caller might use to prove the fixture landed. A harness that asks for 300K characters of+ * mixed content and silently renders 200K of prose measures the wrong thing, so the Python side prints+ * every one of these and fails on any that is zero.+ */counts(): Record<string, number> {return {messages: document.querySelectorAll("[data-role]").length,@@ -791,12 +752,12 @@ function HeavyThreadApi({codeBlocks: document.querySelectorAll("pre").length,highlightedTokens: document.querySelectorAll("pre code span").length,/*- * HOW MUCH CODE IS ON THE PAGE. `highlightedTokens` cannot answer that any more: a- * deferred fence renders as a plain shell, so tokens measure where the reader is- * looking. The shell holds the same text node the highlighted block holds (which is- * also why selection, clipboard and find-in-page are identical across the two states),- * so characters read the same either way and still drop if the fixture loses code.- */+ * HOW MUCH CODE IS ON THE PAGE. `highlightedTokens` cannot answer that any more: a deferred fence+ * renders as a plain shell, so tokens measure where the reader is looking. The shell holds the same text+ * node the highlighted block holds (which is also why selection, clipboard and find-in-page are+ * identical across the two states), so characters read the same either way and still drop if the fixture+ * loses code.+ */codeChars: Array.from(document.querySelectorAll("pre code")).reduce((total, node) => total + (node.textContent?.length ?? 0),0,@@ -804,12 +765,12 @@ function HeavyThreadApi({fenceBlocks: document.querySelectorAll('[data-streamdown="code-block"]').length,deferredFences: document.querySelectorAll("[data-unsloth-fence-deferred]").length,/*- * A fence that is NEITHER deferred NOR highlighted, at rest: the settlement half of the- * old token floor, asked per block. Streamdown mounts a code block on its own- * unhighlighted fallback and colours it from a passive effect, so this state exists for- * a frame on any build and a settled thread must hold none. Stronger than a floor on- * the total, which one stuck block passes as long as the others make up the count.- */+ * A fence that is NEITHER deferred NOR highlighted, at rest: the settlement half of the old token floor,+ * asked per block. Streamdown mounts a code block on its own unhighlighted fallback and colours it from+ * a passive effect, so this state exists for a frame on any build and a settled thread must hold none.+ * Stronger than a floor on the total, which one stuck block passes as long as the others make up the+ * count.+ */unhighlightedMountedFences: Array.from(document.querySelectorAll('[data-streamdown="code-block"]'),).filter(@@ -818,11 +779,10 @@ function HeavyThreadApi({block.querySelector("pre code span") === null,).length,toolParts: document.querySelectorAll(".aui-tool-fallback-root").length,- // The collapsible CONTENT ELEMENT, which Radix keeps in the tree for its collapse- // animation. It is present whether the card is open or shut, so it counts cards, not- // visible panes: measured at 25000 chars it reads 2 with every card closed and 2 again- // after expandTools(). Do NOT gate a wait on this; such a gate is satisfied by a thread- // of closed cards and cannot fail. Use codeExecutionPanes, which is 0 then 2.+ // The collapsible CONTENT ELEMENT, which Radix keeps in the tree for its collapse animation. It is present+ // whether the card is open or shut, so it counts cards, not visible panes: measured at 25000 chars it reads+ // 2 with every card closed and 2 again after expandTools(). Do NOT gate a wait on this; such a gate is+ // satisfied by a thread of closed cards and cannot fail. Use codeExecutionPanes, which is 0 then 2.collapsibleOutputs: document.querySelectorAll('[data-slot="tool-fallback-content"]',).length,@@ -853,10 +813,9 @@ function HeavyThreadApi({return document.querySelector<HTMLTextAreaElement>(".aui-composer-input");},/**- * What the RUNTIME thinks the composer holds. Reading the textarea back instead would only- * echo the value the caller just wrote, so a keystroke that never reached React would still- * look like it landed.- */+ * What the RUNTIME thinks the composer holds. Reading the textarea back instead would only echo the value+ * the caller just wrote, so a keystroke that never reached React would still look like it landed.+ */composerText(): string {return aui.composer().getState().text;},@@ -869,10 +828,10 @@ function HeavyThreadApi({return messages[messages.length - 1] ?? null;},/**- * The last assistant message's action-bar button with accessible name `label`.- * TooltipIconButton puts that name in an `sr-only` span rather than an aria-label, so this- * matches on text and stays correct if the styling classes are renamed.- */+ * The last assistant message's action-bar button with accessible name `label`. TooltipIconButton puts that+ * name in an `sr-only` span rather than an aria-label, so this matches on text and stays correct if the+ * styling classes are renamed.+ */actionButton(label: string): HTMLButtonElement | null {const last = api.lastAssistantMessage();if (!last) return null;@@ -907,10 +866,10 @@ function Harness(): ReactElement {);}-// Thread reaches useNavigate (the fork action, the composer tools menu). Without a router in-// context tanstack's useRouter still works, but console.warns on every render of every action-// bar, which scales with the thread and is serialised over the debugging channel. A memory router-// with one route removes that without pulling in the app shell.+// Thread reaches useNavigate (the fork action, the composer tools menu). Without a router in context tanstack's+// useRouter still works, but console.warns on every render of every action bar, which scales with the thread and+// is serialised over the debugging channel. A memory router with one route removes that without pulling in the+// app shell.const rootRoute = createRootRoute({ component: Harness });const router = createRouter({routeTree: rootRoute,diff --git a/studio/frontend/smoke-shortcuts-main.tsx b/studio/frontend/smoke-shortcuts-main.tsxindex f711569072d..38425e90ea9 100644--- a/studio/frontend/smoke-shortcuts-main.tsx+++ b/studio/frontend/smoke-shortcuts-main.tsx@@ -1,11 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Harness for tests/studio/playwright_keyboard_shortcuts.py: a vite entry with no-// backend, driving the real registry, the real store and the real useShortcut-// against a real browser's keyboard. The node suite can reach the pure functions-// but not the listener, so what a chord does to a focused button, to a text-// field, on auto-repeat, or under AltGr is only answerable here.+// Harness for tests/studio/playwright_keyboard_shortcuts.py: a vite entry with no backend, driving+// the real registry, the real store and the real useShortcut against a real browser's keyboard. The+// node suite can reach the pure functions but not the listener, so what a chord does to a focused+// button, to a text field, on auto-repeat, or under AltGr is only answerable here./* eslint-disable no-restricted-imports -- a harness entry point, not app code. */import { useChatNavigationStore } from "@/features/chat/stores/chat-navigation-store";diff --git a/studio/frontend/smoke-stream-pacing-main.tsx b/studio/frontend/smoke-stream-pacing-main.tsxindex e94eea6d4b4..71880277934 100644--- a/studio/frontend/smoke-stream-pacing-main.tsx+++ b/studio/frontend/smoke-stream-pacing-main.tsx@@ -5,17 +5,14 @@// assistant-ui runtime, fed a fixed reply at a fixed rate, so the measured main-thread cost// is the chat renderer's own. Same shape as smoke-autoscroll.html and smoke-research.html:// a vite entry, no backend, no auth, no model.-//// Four merged PRs moved this path (#7892 transition starvation, #8750 incremental Markdown,// #8845 publish coalescing, #8935 incremental fence tokenization) and each rebuilt a// throwaway harness to prove it. The number they all reported is `longestStallMs`: the// longest the bubble stops growing while text is still arriving.-//// A local runtime rather than a bare component: MarkdownText reads its message part from// assistant-ui context and its BlockComponent reads `useAuiState`, so mounting it outside a// provider throws. The real runtime also puts assistant-ui's own update scheduling inside// the measurement, which is where #7892's starvation lived.-//// The reply is a fixed string, not a model's output. #8845's first measurement attempts// failed because free-form sampling gave the two sides different essays, and the renderer's// cost is superlinear in length, so comparing across different text says nothing.@@ -203,11 +200,10 @@ function Harness(): ReactElement {state.paintedChars = painted;lastGrowthAt = now;} else {- // Measure the stall in progress: a stall closed only by a LATER paint misses a- // freeze that runs to the end of the stream, whose lost tail can hide inside the- // 90% floor. stallInProgress caps it at stream end, so a freeze spanning that- // moment is still recorded in full while the settle check's own quiet frames are- // not counted as one.+ // Measure the stall in progress: a stall closed only by a LATER paint misses a freeze+ // that runs to the end of the stream, whose lost tail can hide inside the 90% floor.+ // stallInProgress caps it at stream end, so a freeze spanning that moment is still+ // recorded in full while the settle check's own quiet frames are not counted as one.const stall = stallInProgress(lastGrowthAt,now,@@ -218,12 +214,11 @@ function Harness(): ReactElement {state.longestStallMs = stall;}}- // Settled is counted in FRAMES without growth, not wall clock: #8845's last- // failed attempt used a 1.5s quiet window and called a reply finished mid- // freeze. A freeze blocks the frame loop too, so a frame counter cannot tick- // through one. Rendered length is compared against itself, not the bytes sent,- // because Markdown syntax (fences, list markers, math delimiters) never- // reaches textContent.+ // Settled is counted in FRAMES without growth, not wall clock: #8845's last failed attempt+ // used a 1.5s quiet window and called a reply finished mid freeze. A freeze blocks the+ // frame loop too, so a frame counter cannot tick through one. Rendered length is compared+ // against itself, not the bytes sent, because Markdown syntax (fences, list markers, math+ // delimiters) never reaches textContent.if (state.streamEndedAtMs !== null && state.timeToFullyPaintedMs === null) {if (painted > settledChars) {settledChars = painted;@@ -245,13 +240,12 @@ function Harness(): ReactElement {handle = requestAnimationFrame(watch);});- // `observe({type})` aborts silently on an unsupported entry type instead of throwing,- // so a try/catch never fires and the long-task total stays 0, a perfect score on the- // budget that matters most. Only supportedEntryTypes answers the question, and the- // answer is recorded so the driver can fail the run instead of reporting the zero.- // Chromium alone ships longtask (Gecko bug 1348405 open, WebKit never shipped it).- // run() moves measureFrom to the moment the stream is asked for, so nothing the page- // did while loading lands in the budget.+ // `observe({type})` aborts silently on an unsupported entry type instead of throwing, so a+ // try/catch never fires and the long-task total stays 0, a perfect score on the budget that+ // matters most. Only supportedEntryTypes answers the question, and the answer is recorded so+ // the driver can fail the run instead of reporting the zero. Chromium alone ships longtask+ // (Gecko bug 1348405 open, WebKit never shipped it). run() moves measureFrom to the moment the+ // stream is asked for, so nothing the page did while loading lands in the budget.let measureFrom = Number.POSITIVE_INFINITY;let observer: PerformanceObserver | null = null;state.longTaskSupported =diff --git a/studio/frontend/smoke-thread-weight-main.tsx b/studio/frontend/smoke-thread-weight-main.tsxindex f487d8a2646..6a0f501b928 100644--- a/studio/frontend/smoke-thread-weight-main.tsx+++ b/studio/frontend/smoke-thread-weight-main.tsx@@ -5,7 +5,6 @@// measured cost of a keystroke, a scroll, a menu and a delete is the app's own and grows with the// thread the way a user's does (#8977).// Same shape as smoke-autoscroll.html and smoke-research.html: a vite entry, no backend, no auth.-//// Two things are real on purpose and cannot be mocked away without deleting the measurement:// - Thread itself, from src/components/assistant-ui/thread.tsx, with its per-message action// bars, tooltips and markdown blocks.@@ -13,7 +12,6 @@// Streamdown, Shiki and KaTeX all pay their per-message price.// The runtime is synthetic: a local runtime whose model adapter never runs, seeded through// `thread.import`.-//// useLocalRuntime rather than useExternalStoreRuntime: the delete path under measurement is// `thread.export()` -> MessageRepository -> `thread.import()`, which only the local runtime backs.diff --git a/studio/frontend/smoke-tool-activity-main.tsx b/studio/frontend/smoke-tool-activity-main.tsxindex 47a49edbfc0..cdf592d98a3 100644--- a/studio/frontend/smoke-tool-activity-main.tsx+++ b/studio/frontend/smoke-tool-activity-main.tsx@@ -2,18 +2,15 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0// Harness page for tests/studio/playwright_tool_activity.py.-//// The node suite reaches the open-state reducers and the store, but not a// rendered Radix Collapsible, so aria-expanded, whether closed content is in// the DOM, and scroll movement are only answerable here.-//// Four disclosure paths reach the same primitive by different routes, and a fix// landing in one can miss the others:// controlled useToolActivityOpen -- web search, knowledge base, code exec// uncontrolled <ToolFallbackRoot defaultOpen> -- terminal, generic/MCP// approval the same card with awaitingApproval, which must stay open// group <ToolGroupRoot>, whose open state is its own-//// The explicit `overflow-y: auto` ancestor exists because that is what// useCollapseScrollLock walks up to find.@@ -40,10 +37,9 @@ const params = new URLSearchParams(window.location.search);const fillers = Number.parseInt(params.get("fillers") ?? "60", 10);const strict = params.get("strict") === "1";const rtl = params.get("rtl") === "1";-// `?only=uncontrolled` renders a single card. The scroll scene needs it: the-// preference closes every card at once and a chevron closes one, so measuring-// them against each other on the full page compares different amounts of-// content collapsing, not different code paths.+// `?only=uncontrolled` renders a single card. The scroll scene needs it: the preference closes+// every card at once and a chevron closes one, so measuring them against each other on the full+// page compares different amounts of content collapsing, not different code paths.const only = params.get("only") ?? "";const shows = (name: string) => only === "" || only === name;diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex e9ea92e5da8..4905942c8b2 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -97,9 +97,8 @@ function ReloadSnapshotReady() {return null;}-// reload-snapshot.js runs outside React during pageswap. Mirror the in-memory-// privacy state onto the document so Temporary Chat is never serialized even-// briefly into sessionStorage.+// reload-snapshot.js runs outside React during pageswap. Mirror the in-memory privacy state onto+// the document so Temporary Chat is never serialized even briefly into sessionStorage.function ReloadSnapshotPrivacy() {const incognito = useChatRuntimeStore((state) => state.incognito);@@ -310,9 +309,8 @@ function RootLayout() {(s) => s.isChatOnly() && !s.capabilitiesUnknown(),);const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);- // Video is the other row the sidebar grays out, on the two verdicts its- // pipelines cannot run on at all. Same hint the row reads, so the two cannot- // disagree about which hosts they are.+ // Video is the other row the sidebar grays out, on the two verdicts its pipelines cannot run on+ // at all. Same hint the row reads, so the two cannot disagree about which hosts they are.const videoDisabled =videoNavHint(chatOnlyMeasured, chatOnlyReason) !== undefined;// Exact match: a prefix would treat /chatty as chat, hiding its not-found UI.@@ -342,12 +340,11 @@ function RootLayout() {}),[rawThread, rawCompare, rawNew, rawProject],);- // Freeze the last /chat search and latch "mounted" via render-phase setState- // (React's "adjust state during render" pattern), avoiding effects/refs.- // Empty until /chat is visited: location.search is the raw URL's, not the- // matched route's, so seeding it would let another route's ?project= stand- // in for a chat the user has never opened. The adjustment below fills it on- // the first /chat render, so landing straight on /chat loses nothing.+ // Freeze the last /chat search and latch "mounted" via render-phase setState (React's "adjust+ // state during render" pattern), avoiding effects/refs. Empty until /chat is visited:+ // location.search is the raw URL's, not the matched route's, so seeding it would let another+ // route's ?project= stand in for a chat the user has never opened. The adjustment below fills it+ // on the first /chat render, so landing straight on /chat loses nothing.const [frozenChatSearch, setFrozenChatSearch] = useState<ChatSearch>({});const [chatMounted, setChatMounted] = useState(isChatRoute);if (isChatRoute && frozenChatSearch !== liveChatSearch) {@@ -450,13 +447,12 @@ function RootLayout() {}) => {clearNewChatDraft(); // fresh chat starts empty, no bleed from the last oneconst chatRuntime = useChatRuntimeStore.getState();- // The project on screen, which on Chat is the runtime's. The page keeps- // that in step with the route, the inferred ones included: a thread or a- // compare pair opened without ?project= still belongs to its project, and- // the page's own New chat button starts the next chat there. Reading the- // search param instead would leave that project without being asked to.- // Off Chat the page is hidden rather than unmounted, so its project is one- // the user cannot see and a new chat belongs to none.+ // The project on screen, which on Chat is the runtime's. The page keeps that in step with the+ // route, the inferred ones included: a thread or a compare pair opened without ?project= still+ // belongs to its project, and the page's own New chat button starts the next chat there.+ // Reading the search param instead would leave that project without being asked to. Off Chat+ // the page is hidden rather than unmounted, so its project is one the user cannot see and a new+ // chat belongs to none.const openProjectId = isChatRoute ? chatRuntime.activeProjectId : null;const projectId = options?.standalone ? null : openProjectId;chatRuntime.setActiveThreadId(null);@@ -498,11 +494,10 @@ function RootLayout() {useShortcut("switchToHub", goTo("/hub"), {enabled: routeShortcutEnabled,});- // Train is the one workspace the chat-only guard turns away, so its chord is- // the one that has to ask first: firing it on a host without the hardware- // would bounce off /studio and land the user on /chat, away from whatever- // they had open. The sidebar disables the row on the same measured check,- // and only once measured, since the guess is what the row waits out too.+ // Train is the one workspace the chat-only guard turns away, so its chord is the one that has to+ // ask first: firing it on a host without the hardware would bounce off /studio and land the user+ // on /chat, away from whatever they had open. The sidebar disables the row on the same measured+ // check, and only once measured, since the guess is what the row waits out too.useShortcut("switchToTrain", goTo("/studio"), {enabled: routeShortcutEnabled && !chatOnlyMeasured,});diff --git a/studio/frontend/src/app/routes/settings.tsx b/studio/frontend/src/app/routes/settings.tsxindex 84650bdb8b4..8dda0575254 100644--- a/studio/frontend/src/app/routes/settings.tsx+++ b/studio/frontend/src/app/routes/settings.tsx@@ -7,10 +7,9 @@ import { useSettingsDialogStore } from "@/features/settings";import { requireAuth } from "../auth-guards";import { Route as rootRoute } from "./__root";-// /settings deep-links the modal: open it, then redirect home. Tab title is-// driven by useSettingsDialogStore in __root.tsx since the redirect means-// /settings never stays matched; staticData is a safety net if beforeLoad-// ever stops throwing.+// /settings deep-links the modal: open it, then redirect home. Tab title is driven by+// useSettingsDialogStore in __root.tsx since the redirect means /settings never stays matched;+// staticData is a safety net if beforeLoad ever stops throwing.export const Route = createRoute({getParentRoute: () => rootRoute,path: "/settings",diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex c5e20492e56..f48bff576a3 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -231,7 +231,6 @@ import { toast } from "@/lib/toast";import { ShutdownDialog } from "@/components/shutdown-dialog";import { translate, useT, type TranslationKey } from "@/i18n";-/** The ⌥⌘1-6 Recents slots, as a constant so the list below is fixed-length. */const RECENT_SLOT_NUMBERS = [1, 2, 3, 4, 5, 6] as const;const EMPHASIS_MARKER = "__UNSLOTH_I18N_EMPHASIS_MARKER__";@@ -312,10 +311,9 @@ const SIDEBAR_PROJECT_LIMIT = 5;const menuRadioItemClass ="pl-9 pr-3 [&>[data-slot=dropdown-menu-radio-item-indicator]]:right-auto [&>[data-slot=dropdown-menu-radio-item-indicator]]:left-3";-// Whether cmd or ctrl adds a row to the selection. This is the user's own-// keyboard, not the host Unsloth runs on, so it reads the browser rather than-// the platform store: a Mac browser on a Linux host still uses cmd. Ctrl is-// left alone on macOS, where ctrl click is the right click chord.+// Whether cmd or ctrl adds a row to the selection. This is the user's own keyboard, not the host+// Unsloth runs on, so it reads the browser rather than the platform store: a Mac browser on a Linux+// host still uses cmd. Ctrl is left alone on macOS, where ctrl click is the right click chord.const SELECT_WITH_META =typeof navigator !== "undefined" &&/mac/i.test(navigator.platform || navigator.userAgent);@@ -431,18 +429,13 @@ function preloadSilently(request: Promise<unknown>): void {void request.catch(() => undefined);}-// "New" pill for recent tabs. Same recipe as the brand "beta" badge./**- * "Open chat folder" for a browser session, where the backend's file manager is- * not the user's. Radix's `disabled` takes the row's pointer events away and a- * tooltip is blocked while the menu owns the screen, so the row stays enabled,- * refuses the select itself, and drives a controlled tooltip off a- * pointer-events-none anchor (as the MCP rows do).- *- * The reason is carried twice: the tooltip hangs off an aria-hidden anchor and- * opens on hover, which a screen reader never reaches and a touch device does- * not have, so `title` describes the row itself and selecting it (tap or Enter)- * opens the hint rather than doing nothing.+ * "Open chat folder" for a browser session, where the backend's file manager is not the user's.+ * Radix's `disabled` takes the row's pointer events away and a tooltip is blocked while the menu+ * owns the screen, so the row stays enabled, refuses the select itself, and drives a controlled+ * tooltip off a pointer-events-none anchor (as the MCP rows do). The reason is carried twice: that+ * tooltip opens on hover, which a screen reader never reaches and a touch device does not have, so+ * `title` describes the row and selecting it opens the hint rather than doing nothing.*/function OpenChatFolderUnavailableItem() {const [hintOpen, setHintOpen] = useState(false);@@ -529,7 +522,6 @@ function NavItem({// Show that tooltip on the expanded row too, not just the collapsed rail where it// stands in for the hidden label.alwaysTooltip?: boolean;- // Trailing "New" pill text.badge?: string;// Absolutely-positioned extras over the row, e.g. a disclosure chevron.overlay?: ReactNode;@@ -580,11 +572,9 @@ function getSidebarItemThreadIds(item: SidebarItem) {const WORKFLOW_UNAVAILABLE = "The loaded model cannot do this";-// Re-read cadences for the hardware verdict below. An unmeasured verdict holds Train and Video-// on a spinner, so it is re-read sooner than the background MLX self-heal check, which only-// pays off after the user has repaired an install. A re-read outstanding longer than the stall-// window is given up on rather than latching the poll off: the backend it is waiting on is the-// one case this has to recover from.+// Re-read cadences for the hardware verdict below. An unmeasured verdict holds Train and Video on+// a spinner, so it is re-read sooner than the background MLX self-heal check. A re-read outstanding+// longer than the stall window is given up on rather than latching the poll off./** How long a selection chord keeps a repeat press off the open chat. */const SELECTION_ACTION_GRACE_MS = 750;/** The sidebar's own element, present on desktop and inside the mobile drawer. */@@ -596,11 +586,10 @@ const VERDICT_POLL_STALL_MS = 30000;// CPU-torch machine and no_gpu becomes torch_cpu_build. Nothing else re-reads the verdict.// Matched to that TTL, since polling faster than the answer can change is pure traffic.const INVENTORY_POLL_MS = 60000;-// The health path reads those snapshots non-blocking: the first read past expiry SCHEDULES-// the refresh and returns the stale entry, so the new answer lands a moment later. On the-// TTL alone the read that triggers the refresh is a whole interval from the read that-// consumes it, leaving an attached eGPU invisible for close to two minutes. One short-// follow-up read collects it instead.+// The health path reads those snapshots non-blocking: the first read past expiry SCHEDULES the+// refresh and returns the stale entry. On the TTL alone the read that triggers the refresh is a+// whole interval from the read that consumes it, leaving an attached eGPU invisible for close to+// two minutes. One short follow-up read collects it instead.const INVENTORY_FOLLOW_UP_MS = 4000;// The verdicts the inventory can still move. Everything else describes something a probe// cannot change (an Intel Mac stays an Intel Mac).@@ -608,11 +597,10 @@ const INVENTORY_SENSITIVE_REASONS = new Set(["no_gpu","torch_cpu_build","torch_cuda_unavailable",- // A torch that will not import is classified from its wheel on disk, so the backend can- // replace this with torch_cpu_build or torch_cuda_unavailable once the OS probe recovers.- // Leaving it out treated that first answer as settled and stopped the only forced health- // re-read, so the sidebar and navigation stayed on the failure for the rest of the session- // while /api/system already reported the mismatch.+ // A torch that will not import is classified from its wheel on disk, so the backend can replace+ // this with torch_cpu_build or torch_cuda_unavailable once the OS probe recovers. Leaving it out+ // treated that first answer as settled and stopped the only forced health re-read, so the sidebar+ // stayed on the failure while /api/system already reported the mismatch."detection_failed",]);@@ -772,9 +760,8 @@ export function AppSidebar() {);const [usesCustomTitlebar] = useState(shouldUseCustomWindowTitlebar);const [usesNativeMacTitlebar] = useState(shouldUseNativeMacWindowTitlebar);- // Read from the shortcuts store, not the shipped default: a rebound or- // cleared action must not leave the hint advertising a dead chord. Both- // already render in the platform's own notation.+ // Read from the shortcuts store, not the shipped default: a rebound or cleared action must not+ // leave the hint advertising a dead chord. Both already render in the platform's own notation.const searchShortcutLabel = useShortcutLabel("searchChats");const settingsShortcutLabel = useShortcutLabel("openSettings");const { pathname, search, href } = useRouterState({@@ -806,10 +793,9 @@ export function AppSidebar() {const closeMobileIfOpen = () => {if (isMobile) setOpenMobile(false);};- // SidebarProvider is mounted at the route root and outlives the navigation,- // and the workspace chords register up there too, above it, so they cannot- // call what every row below calls by hand. Closing on the route covers both,- // and anything else that navigates from outside this file.+ // SidebarProvider is mounted at the route root and outlives the navigation, and the workspace+ // chords register above it, so they cannot call what every row below calls by hand. Closing on the+ // route covers both, and anything else that navigates from outside this file.useEffect(() => {if (isMobile) setOpenMobile(false);}, [href, isMobile, setOpenMobile]);@@ -854,34 +840,30 @@ export function AppSidebar() {const videoDisabledHint = videoNavHint(chatOnlyMeasured, chatOnlyReason);const videoDisabled = videoDisabledHint !== undefined;- // Two things can change the verdict after the first /api/health. The backend MLX self-heal- // (utils/mlx_repair) can reinstall MLX and flip chat_only false without a restart, and- // detection can land after fetchDeviceType gave up waiting for it. The platform store cached- // that first reply, so re-poll for both; the guard below stops it once neither applies.+ // Two things can change the verdict after the first /api/health: the backend MLX self-heal+ // (utils/mlx_repair) can reinstall MLX and flip chat_only false without a restart, and detection+ // can land after fetchDeviceType gave up waiting. The platform store cached that first reply, so+ // re-poll for both; the guard below stops it once neither applies.useEffect(() => {// Also while deferred: under the kill switch health settles nothing, so a GPU host would stay chat-only.const selfHealSettled =!chatOnly || (chatOnlyReason !== "mlx_unavailable" && !detectionDeferred);- // And on any platform while the verdict itself is out. fetchDeviceType spends its bounded- // wait at most once per page load, so a host that detects slower than that keeps the- // provisional reply, and nothing else is scheduled to re-read it: the rows above would spin- // and /studio would hold its loading panel for the rest of the session. This is the only- // recovery poll in the app, and the sidebar is mounted on every route that gates on the- // verdict (studio-page reads the same store, so it recovers with it; video-page reads the- // backend's video verdict instead and needs nothing from here).+ // And on any platform while the verdict itself is out. fetchDeviceType spends its bounded wait at+ // most once per page load, so a host that detects slower keeps the provisional reply and nothing+ // else re-reads it: the rows above would spin and /studio would hold its loading panel for the rest+ // of the session. This is the only recovery poll in the app, and the sidebar is mounted on every+ // route that gates on the verdict.const inventorySensitive =chatOnly && INVENTORY_SENSITIVE_REASONS.has(chatOnlyReason ?? "");if (selfHealSettled && !capabilitiesUnknown && !inventorySensitive) return;let pollingSince = 0;- // Which read currently owns the guard. A read that outlived the stall window is replaced,- // and the replacement takes the guard with it; without an owner the abandoned read's- // `finally` would clear a guard it no longer holds and let the next tick stack another- // forced read onto the slow backend, every interval, which is the pile-up this prevents.+ // Which read currently owns the guard. A read that outlived the stall window is replaced, and the+ // replacement takes the guard with it; without an owner the abandoned read's `finally` would clear+ // a guard it no longer holds and stack another forced read onto the slow backend every interval.let pollOwner = 0;- // Cleared on unmount with the interval: a follow-up outliving the effect would read- // against a verdict this effect no longer describes. Through `window`, like the- // interval beside it, and 0 for "none" because that is what window.setTimeout never- // returns.+ // Cleared on unmount with the interval: a follow-up outliving the effect would read against a+ // verdict this effect no longer describes. Through `window`, and 0 for "none" because that is what+ // window.setTimeout never returns.let followUp = 0;const id = window.setInterval(() => {// A backend still importing torch answers slowly, so skip while a re-read is outstanding@@ -970,10 +952,9 @@ export function AppSidebar() {const [scrolled, setScrolled] = useState(false);// Bottom fade hides at the very bottom / for short lists so the last row isn't washed out.const [canScrollDown, setCanScrollDown] = useState(false);- // Rail width: 0 where scrollbars overlay (macOS default) or the list fits,- // the platform's thin rail where they are classic. Only rows inside the- // scroller lose it, so the rows outside pad by it to keep one edge. Written- // to the DOM, and only on a change: state here would loop (React #185).+ // Rail width: 0 where scrollbars overlay (macOS default) or the list fits, the platform's thin rail+ // where they are classic. Only rows inside the scroller lose it, so the rows outside pad by it to+ // keep one edge. Written to the DOM, and only on a change: state here would loop (React #185).const railWidthRef = useRef<number | null>(null);const measureScrollRail = useCallback((el: HTMLDivElement) => {const rail = el.offsetWidth - el.clientWidth;@@ -982,10 +963,9 @@ export function AppSidebar() {el.parentElement?.style.setProperty("--sidebar-rail", `${rail}px`);}, []);- // A callback ref, not an effect: the mobile Sheet unmounts its subtree on- // close and the breakpoint swaps it for the desktop one, so the scroller is a- // new node each time and an effect keyed on a stable callback never re-runs.- // Still runs before paint.+ // A callback ref, not an effect: the mobile Sheet unmounts its subtree on close and the breakpoint+ // swaps it for the desktop one, so the scroller is a new node each time and an effect keyed on a+ // stable callback never re-runs. Still runs before paint.const railObserverRef = useRef<ResizeObserver | null>(null);const attachScroller = useCallback((el: HTMLDivElement | null) => {@@ -997,11 +977,9 @@ export function AppSidebar() {railWidthRef.current = null;if (!el) return;measureScrollRail(el);- // Watch the box, not renders: the Images disclosure and the project- // toggles change the row count without rendering this component, and a- // scrollbar appearing shrinks the content box by its own width. Safe- // where the earlier observer was not: it writes a variable, never state,- // so there is no render to feed back (React #185).+ // Watch the box, not renders: the Images disclosure and the project toggles change the row count+ // without rendering this component, and a scrollbar appearing shrinks the content box. Safe where+ // the earlier observer was not: it writes a variable, never state, so nothing feeds back.const observer = new ResizeObserver(() => measureScrollRail(el));observer.observe(el);railObserverRef.current = observer;@@ -1075,11 +1053,9 @@ export function AppSidebar() {const setChatSort = useSidebarOrganizationStore((s) => s.setChatSort);const setPinnedSort = useSidebarOrganizationStore((s) => s.setPinnedSort);const setManualOrder = useSidebarOrganizationStore((s) => s.setManualOrder);- // With the Projects section on, a project chat lives in its folder and- // repeating it here would be noise. With it off there are no folders, so- // Recents is where those chats go, and a new project chat still lands- // somewhere visible. Pinned chats are held back either way: the Pinned- // section renders those.+ // With the Projects section on, a project chat lives in its folder and repeating it here would be+ // noise. With it off there are no folders, so Recents is where those chats go. Pinned chats are+ // held back either way: the Pinned section renders those.const recentChatItems = useMemo(() =>allChatItems.filter(@@ -1119,10 +1095,9 @@ export function AppSidebar() {list.sort((a, b) => b.updatedAt - a.updatedAt);return map;}, [allChatItems]);- // Every project gets a folder: pinned first in pin order, then by activity,- // then whatever the user dragged, which outranks both. Activity comes from- // the member chats, since a project's own updatedAt only moves when its name,- // instructions or archived flag are edited.+ // Every project gets a folder: pinned first in pin order, then by activity, then whatever the user+ // dragged, which outranks both. Activity comes from the member chats, since a project's own+ // updatedAt only moves when its name, instructions or archived flag are edited.const sidebarProjectRecords = useMemo(() => {const lastActivityAt = (project: ProjectRecord) => {let latest = project.updatedAt ?? project.createdAt;@@ -1150,10 +1125,9 @@ export function AppSidebar() {manualOrder,chatsByProjectId,]);- // Memoised for its identity, not for the slice. It feeds the rendered-row set- // the selection guard depends on, and that effect sets state: React re-renders- // once to find the bail-out, which would rebuild this array and schedule the- // effect again, without end.+ // Memoised for its identity, not for the slice. It feeds the rendered-row set the selection guard+ // depends on, and that effect sets state: React re-renders once to find the bail-out, which would+ // rebuild this array and schedule the effect again, without end.const visibleProjectRecords = useMemo(() =>showAllProjects@@ -1229,8 +1203,7 @@ export function AppSidebar() {undefined: undefined;const queueByThreadId = usePromptQueueUI((s) => s.byThreadId);- // In the navigation store, not local state: the unread chords register- // outside this tree.+ // In the navigation store, not local state: the unread chords register outside this tree.const unreadThreadIds = useChatNavigationStore((s) => s.unreadThreadIds);const markThreadsUnread = useChatNavigationStore((s) => s.markThreadsUnread);const clearThreadsUnread = useChatNavigationStore(@@ -1334,24 +1307,19 @@ export function AppSidebar() {() => sortedPinnedChatItems.map((item) => item.id),[sortedPinnedChatItems],);- // Whole lists, not the visible slices, so a drop cannot lose what a- // collapsed "Show more" is hiding.- // The project chats actually on screen. Grouping by project keeps them out of- // Recents, so without these the chords cannot see them at all. Same rule the- // Projects section renders by, collapsed folders and per-folder limit included.- // All three chat groups leave the tree on Train/Recipes/Export and are hidden- // on the icon rail, so a chord must not reach what they hold. Same rule a- // collapsed section follows, read off the sidebar as a whole. The mobile- // sheet is not part of it: it carries no collapsible state, and gating on it- // would strand the chords on any window narrow enough to count as mobile.+ // Whole lists, not the visible slices, so a drop cannot lose what a collapsed "Show more" is+ // hiding, plus the project chats actually on screen: grouping by project keeps them out of Recents,+ // so without those the chords cannot see them at all. All three chat groups leave the tree on+ // Train/Recipes/Export and are hidden on the icon rail, so a chord must not reach what they hold;+ // read off the sidebar as a whole. The mobile sheet is not part of it, since it carries no+ // collapsible state and gating on it would strand the chords on any narrow window.const chatListsOnScreen =!isStudioRoute &&!showTrainingRecents &&(isMobile || sidebarState !== "collapsed");- // Selecting needs the rows, not just the lists. A closed mobile sheet unmounts- // them as the icon rail does, so Select All would build a selection with- // nothing on screen and Archive, Pin and Mark unread would take it over the- // open chat. Navigation is deliberately exempt: it moves the chat the user IS+ // Selecting needs the rows, not just the lists. A closed mobile sheet unmounts them as the icon+ // rail does, so Select All would build a selection with nothing on screen and Archive, Pin and Mark+ // unread would take it over the open chat. Navigation is exempt: it moves the chat the user IS// looking at, and the sheet is closed for most of its life on a narrow window.const chatRowsOnScreen = chatListsOnScreen && (!isMobile || openMobile);const renderedProjectChatItems = useMemo(() => {@@ -1397,10 +1365,9 @@ export function AppSidebar() {for (const item of visibleRecentItems) ids.add(item.id);return ids;}, [visiblePinnedItems, renderedProjectChatItems, visibleRecentItems]);- // The folder rows, selectable in their own right and leaving the screen on- // their own terms: the section closes, the sidebar organizes by date, or a- // "show less" takes back the overflow. The chat sets above say nothing about- // that, since a folder with no chats in view is still a row.+ // The folder rows, selectable in their own right and leaving the screen on their own terms: the+ // section closes, the sidebar organizes by date, or a "show less" takes back the overflow. The chat+ // sets above say nothing about that, since a folder with no chats in view is still a row.const renderedProjectIds = useMemo(() => {if (!chatListsOnScreen || organizeBy !== "project" || !projectsOpen) {return new Set<string>();@@ -1522,14 +1489,11 @@ export function AppSidebar() {dropProjectSelection();}, [dropChatSelection, dropProjectSelection]);- // Emptying the published lists is not enough: Archive, Pin, Mark unread and- // Delete all prefer the selection over the open chat, and a selection shows- // nowhere but the rows, its count living in their context menus. Carried onto- // Train or behind the icon rail it would be invisible and still be what the- // chords hit. Same reason opening a row drops it.- // Sections close one at a time, though, and a "show less" takes back only- // its own overflow, so the rest of the selection is still on screen and- // still worth acting on. Drop what went and keep what stayed.+ // Emptying the published lists is not enough: Archive, Pin, Mark unread and Delete all prefer the+ // selection over the open chat, and a selection shows nowhere but the rows. Carried onto Train or+ // behind the icon rail it would be invisible and still be what the chords hit. Sections close one+ // at a time, though, and a "show less" takes back only its own overflow, so drop what went and keep+ // what stayed.useEffect(() => {if (!chatRowsOnScreen) {clearSelection();@@ -1547,10 +1511,9 @@ export function AppSidebar() {}return kept.size === prev.size ? prev : kept;});- // Folder rows go the same way. Left behind, a project whose section the- // user closed keeps the selection alive with nothing on screen, and the- // tool card's Escape steps aside for it: the press that should have- // declined a call clears a selection instead.+ // Folder rows go the same way. Left behind, a project whose section the user closed keeps the+ // selection alive with nothing on screen, and the tool card's Escape steps aside for it: the press+ // that should have declined a call clears a selection instead.const projectAnchor = projectAnchorRef.current;if (projectAnchor && !renderedProjectIds.has(projectAnchor)) {projectAnchorRef.current = null;@@ -1586,19 +1549,16 @@ export function AppSidebar() {dropProjectSelection,]);- // Escape leaves a selection, as it does the menus. A passive listener rather- // than one that consumes the key: dictation's Escape reads defaultPrevented- // first, and a stale selection must not outrank a live recording. Declining a- // tool call is the Escape that must not double up, and it steps aside on- // `selectionActive` below.+ // Escape leaves a selection, as it does the menus. A passive listener rather than one that consumes+ // the key: dictation's Escape reads defaultPrevented first, and a stale selection must not outrank+ // a live recording. Declining a tool call steps aside on `selectionActive` below.const selectionActive = selectionCount > 0 || projectSelectionCount > 0;useEffect(() => {if (!selectionActive) return;const onKeyDown = (event: KeyboardEvent) => {- // Bare, and only bare. Escape with a modifier is somebody else's chord,- // ⇧Esc for Clear all unreads among them, and dropping the selection under- // one would leave Archive or Pin pointing elsewhere. defaultPrevented for- // the same reason: a menu closing on Escape is not a request to lose it.+ // Bare, and only bare. Escape with a modifier is somebody else's chord, Clear all unreads among+ // them, and dropping the selection under one would leave Archive or Pin pointing elsewhere.+ // defaultPrevented likewise: a menu closing on Escape is not a request to lose it.if (event.key !== "Escape" || event.defaultPrevented) return;if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) {return;@@ -1783,7 +1743,6 @@ export function AppSidebar() {const manualDragEnabled = chatSort === "manual";const pinnedDragEnabled = pinnedSort === "manual";- /** The cue class for this row, or undefined when it is not the drop target. */function dropCueClass(scope: string | undefined,orderedIds: string[] | undefined,@@ -1802,11 +1761,8 @@ export function AppSidebar() {: DROP_CUE_TOP;}- /**- * Menu path to the same reorder dragging does. Touch browsers never fire- * dragstart and a keyboard cannot drag, so a manually ordered list is- * unreorderable without this.- */+ /** Menu path to the same reorder dragging does. Touch browsers never fire dragstart and a keyboard+ * cannot drag, so a manually ordered list is unreorderable without this. */function renderMoveRowItems(scope: string,orderedIds: string[],@@ -1835,7 +1791,6 @@ export function AppSidebar() {);}- /** Drag handlers for one row of a reorderable list. */function rowDragProps(scope: string, orderedIds: string[], rowId: string) {return {draggable: true,@@ -1966,17 +1921,15 @@ export function AppSidebar() {const chatDisabled = trainingInProgress;const usesDesktopTitlebar = usesCustomTitlebar || usesNativeMacTitlebar;- // Navigation rows share one box, so a hover pill has the same edges wherever- // it lands. Rows outside the list scroller add the rail width it does not- // lose, so both end on the same edge whether or not the scrollbar takes- // space. Logical sides, since the rail moves under rtl.+ // Navigation rows share one box, so a hover pill has the same edges wherever it lands. Rows outside+ // the list scroller add the rail width it does not lose, so both end on the same edge whether or+ // not the scrollbar takes space. Logical sides, since the rail moves under rtl.const rowPadding = usesDesktopTitlebar? "ps-[5px] pe-[calc(var(--sidebar-rail,0px)+5px)]": "ps-1.5 pe-[calc(var(--sidebar-rail,0px)+6px)]";- // Inside the scroller the rail already occupies that space. The profile- // footer also uses this padding deliberately: its width is independent of- // whether the unrelated recent-chat list currently has a scrollbar.+ // Inside the scroller the rail already occupies that space. The profile footer also uses this+ // padding deliberately: its width is independent of whether the recent-chat list has a scrollbar.const unrailedRowPadding = usesDesktopTitlebar ? "px-[5px]" : "px-1.5";// Header actions end where a hovered row's "…" does: unrailedRowPadding + the@@ -2566,9 +2519,8 @@ export function AppSidebar() {} else if (empty.value) {toast.info("No exportable content.");} else {- // Denied permission, an unfocused document, a failed history read: the- // payload was fine and the write was not, and a chord has no cursor to- // show that with.+ // Denied permission, an unfocused document, a failed history read: the payload was fine and+ // the write was not, and a chord has no cursor to show that with.toast.error("Could not copy this chat.");}}@@ -2576,11 +2528,9 @@ export function AppSidebar() {/** The sandbox sessions this chat's stored tool results name, if any. */async function recordedSandboxSessionIds(ids: string[]): Promise<string[]> {const recorded: string[] = [];- // Every id a thread names, not just its latest: one chat that ran a tool,- // moved between projects and ran another wrote to two folders on its own,- // and the newest would answer for both.- // One at a time, not Promise.all: this file's export contract forbids a- // concurrent await here, and two panes win nothing.+ // Every id a thread names, not just its latest: one chat that ran a tool, moved between projects+ // and ran another wrote to two folders on its own, and the newest would answer for both. One at a+ // time, not Promise.all: this file's export contract forbids a concurrent await here.for (const threadId of ids) {recorded.push(...allRecordedSandboxSessionIds(await listStoredChatMessages(threadId)),@@ -2590,34 +2540,23 @@ export function AppSidebar() {}/**- * The folders this chat's files are actually in: what its tool results name,- * or, for a chat old enough that they name nothing, what is on disk.- *- * Chats stored before results carried a session recorded nothing, so one that- * ran loose and has since joined a project would be answered with the project- * workspace. Its thread sandbox is the only other candidate, and files there- * are this chat's, which is what makes them worth probing: a chat can join a- * project, record that session, and move back out, and current membership- * says nothing about where its older files went. The project workspace is- * not probed, because it belongs to every chat in the project alike.- *- * A union rather than a fallback. One recorded id is not evidence that the- * others are recorded too: a chat can have run a tool before recording- * existed, moved into a project, and run another one since, and taking the- * recorded id alone would answer for both folders while hiding the older.- *- * Shared by "Open chat folder" and "Copy session id", which drifted apart- * once: the copy path skipped the probe and reported success on a folder the- * chat had never written to.- */+ * The folders this chat's files are actually in: what its tool results name, or, for a chat old+ * enough that they name nothing, what is on disk. Chats stored before results carried a session+ * recorded nothing, so one that ran loose and has since joined a project would be answered with+ * the project workspace; its thread sandbox is the only other candidate, and files there are this+ * chat's. The project workspace is not probed, because it belongs to every chat alike.+ *+ * A union rather than a fallback: one recorded id is not evidence that the others are recorded+ * too, and taking it alone would answer for both folders while hiding the older. Shared by "Open+ * chat folder" and "Copy session id", which drifted apart once, the copy path skipping the probe+ * and reporting success on a folder the chat had never written to.+ */async function sandboxSessionIdsHolding(ids: string[]): Promise<string[]> {const recorded = await recordedSandboxSessionIds(ids);- // Thread folders only. A project sandbox is shared by every chat in the- // project, so files there are no evidence that THIS chat wrote them, and- // counting one would report a second folder for any chat that joined a- // project someone else had already used. Both callers already fall back to- // the folder membership gives them when nothing here names one, which is- // the honest answer where there is no evidence either way.+ // Thread folders only. A project sandbox is shared by every chat in the project, so files there are+ // no evidence that THIS chat wrote them, and counting one would report a second folder for any chat+ // that joined a project someone else had used. Both callers already fall back to the folder+ // membership gives them when nothing here names one.const held: string[] = [];for (const candidate of ids) {// Already named, so there is nothing a probe could add.@@ -2631,10 +2570,9 @@ export function AppSidebar() {async function copyChatSessionId(item: SidebarItem) {const threadIds = getSidebarItemThreadIds(item);const ids = threadIds.length > 0 ? threadIds : [item.id];- // The chat's own history names the folder it wrote to, which is not where- // current membership points once it has moved between projects. Same read- // as "Open chat folder", and the same answer when it names two, whether- // that is a compare row's two panes or one thread that outlived a move.+ // The chat's own history names the folder it wrote to, which is not where current membership points+ // once it has moved between projects. Same read as "Open chat folder", and the same answer when it+ // names two, whether that is a compare row's two panes or one thread that outlived a move.const refusal: { value: { title: string; description?: string } | null } = {value: null,};@@ -2712,9 +2650,9 @@ export function AppSidebar() {useEffect(() => {openChatItemRef.current = openChatItem;});- // The sidebar is unmounted on the auth routes, so this is where a sign-out- // reaches: the store outlives the component that filled it, and the unread- // set and the walk belong to the account that just left.+ // The sidebar is unmounted on the auth routes, so this is where a sign-out reaches: the store+ // outlives the component that filled it, and the unread set and the walk belong to the account+ // that just left.useEffect(() => () => useChatNavigationStore.getState().resetAccountState(),[],@@ -2725,9 +2663,8 @@ export function AppSidebar() {return () => setOpenChatItem(null);}, []);- // --- Chat shortcuts ----------------------------------------------------- // The sidebar is on every shell route and holds the list, the handlers and- // the router, so the chat chords register here.+ // --- Chat shortcuts ---+ // The sidebar is on every shell route and holds the list, the handlers and the router.const activeChatItem = useMemo(() => allChatItems.find((item) => item.id === activeThreadId) ?? null,[allChatItems, activeThreadId],@@ -2743,12 +2680,10 @@ export function AppSidebar() {const goToChat = (pick: (state: ChatNavigationState) => SidebarItem | null) =>openChatItemById(pick(useChatNavigationStore.getState()));- // With rows selected these act on the selection, matching the context menu;- // otherwise on the open chat. Acting on a selection clears it, so without- // this latch a second press would land on the open chat, which the user- // never selected.- // Keyed by action: the press to hold back is a repeat of the one that just- // took the selection, not a different command the user chose deliberately.+ // With rows selected these act on the selection, matching the context menu; otherwise on the open+ // chat. Acting on a selection clears it, so without this latch a second press would land on the+ // open chat, which the user never selected. Keyed by action: the press to hold back is a repeat of+ // the one that just took the selection, not a different command chosen deliberately.const selectionActedRef = useRef<{ id: ShortcutId; at: number } | null>(null);const actOnSelection = (id: ShortcutId, fn: () => void) => {selectionActedRef.current = { id, at: Date.now() };@@ -2765,18 +2700,15 @@ export function AppSidebar() {// than falling through to the open chat. Delete already behaves this way.const projectsOnlySelected = () =>selectionCount === 0 && projectSelectionCount > 0;- // A dialog leaves the sidebar mounted and inert behind it, and these chords- // are window-level, so Settings over Chat would archive or rename the chat- // behind it. Asked at press time, since `enabled` is read at render.- //- // Backgrounded, not "not in the foreground": reading a missing element as- // covered would kill these chords on the mobile drawer, which unmounts.+ // A dialog leaves the sidebar mounted and inert behind it, and these chords are window-level, so+ // Settings over Chat would archive or rename the chat behind it. Asked at press time, since+ // `enabled` is read at render. Backgrounded, not "not in the foreground": reading a missing element+ // as covered would kill these chords on the mobile drawer, which unmounts.const sidebarCovered = () => {if (isSurfaceBackgrounded(SIDEBAR_SELECTOR)) return true;- // With the mobile drawer closed the sidebar is unmounted, so the check- // above has nothing to read. The app root is always mounted and Radix- // aria-hides it for a modal's life. A fallback only: an open drawer is- // itself a dialog hiding the root, and the sidebar in it is the foreground.+ // With the mobile drawer closed the sidebar is unmounted, so the check above has nothing to read.+ // The app root is always mounted and Radix aria-hides it for a modal's life. A fallback only: an+ // open drawer is itself a dialog hiding the root, and the sidebar in it is the foreground.return (typeof document !== "undefined" &&document.querySelector(SIDEBAR_SELECTOR) === null &&@@ -2815,9 +2747,8 @@ export function AppSidebar() {if (followsSelectionAction("togglePinChat")) return;withActiveChat((item) => togglePinnedChat(item.id));});- // A selection made behind a dialog is invisible and still what the mutating- // chords hit once the dialog closes, which is the thing those chords being- // guarded was meant to prevent.+ // A selection made behind a dialog is invisible and still what the mutating chords hit once the+ // dialog closes, which is the thing those chords being guarded was meant to prevent.useShortcut("selectAllChats", () => {if (sidebarCovered()) return;selectAllChats();@@ -2827,17 +2758,15 @@ export function AppSidebar() {if (sidebarCovered()) return;if (selectionCount > 0) deleteSelected();});- // Through the dialog: the row's inline pill is rendered by the row, and the- // open chat may be behind a collapsed section, past a folder's "show more",- // or on a route with no chat list at all, where the chord would look dead and- // leave a rename waiting to appear the moment the row came back.+ // Through the dialog: the row's inline pill is rendered by the row, and the open chat may be behind+ // a collapsed section, past a folder's "show more", or on a route with no chat list at all, where+ // the chord would look dead and leave a rename waiting to appear when the row came back.useShortcut("renameChat", () => {if (sidebarCovered()) return;withActiveChat((item) => openRenameChat(item, false));});- // The clipboard is outside the app, so writing a hidden chat's contents into- // it from behind a dialog is not something the user can take back by closing- // the dialog.+ // The clipboard is outside the app, so writing a hidden chat's contents into it from behind a+ // dialog is not something the user can take back by closing the dialog.useShortcut("copyChatAsMarkdown", () => {if (sidebarCovered()) return;withActiveChat((item) => void copyChatItemAsMarkdown(item));@@ -2855,9 +2784,8 @@ export function AppSidebar() {useShortcut("previousChat", () => goToChat((s) => adjacentChatItem(s, -1)), {repeats: true,});- // The walk holds the stack still while it runs, so a modifier held down- // reaches the third chat back and beyond; releasing it ends the walk and- // puts the chat it landed on at the top.+ // The walk holds the stack still while it runs, so a modifier held down reaches the third chat+ // back and beyond; releasing it ends the walk and puts the chat it landed on at the top.const walkRecentlyViewed = (delta: number) =>openChatItemById(useChatNavigationStore.getState().stepRecentlyViewed(delta));useShortcut("nextRecentlyViewedChat", () => walkRecentlyViewed(1), {@@ -2882,8 +2810,7 @@ export function AppSidebar() {toast.success(`Cleared ${cleared} unread ${cleared === 1 ? "chat" : "chats"}`);});- // The six slots register as <Shortcut> elements: a loop of hooks would- // break the rules of hooks.+ // The six slots register as <Shortcut> elements: a loop of hooks would break the rules of hooks.const slotShortcuts = (<>{RECENT_SLOT_NUMBERS.map((slot) => (@@ -3296,12 +3223,9 @@ export function AppSidebar() {onSelect={() => {void (async () => {try {- // A chat moved between projects keeps the sandbox it- // wrote to, so its own history names the folder, not- // current membership. A failed read is reported- // below rather than caught per pane, which would- // read as "never ran a tool" and fall back to- // membership, the answer the recorded id overrides.+ // A chat moved between projects keeps the sandbox it wrote to, so its own+ // history names the folder, not current membership. A failed read is+ // reported below rather than caught per pane.const ids =threadIds.length > 0 ? threadIds : [item.id];const distinct = await sandboxSessionIdsHolding(ids);@@ -4327,9 +4251,8 @@ export function AppSidebar() {// The profile is outside the recent-chat scroller and keeps its full// width when that scroller gains or loses a scrollbar.unrailedRowPadding,- // pt-[3px] cancels the profile button's -3px margin, so the 8px- // above it is whatever sits over the footer edge (the fade plateau,- // or the list's pb-2 once the fade is hidden) and 8px sits below.+ // pt-[3px] cancels the profile button's -3px margin, so the 8px above it is whatever sits over the+ // footer edge (the fade plateau, or the list's pb-2 once the fade is hidden) and 8px sits below.showUpdateCard ? "pt-1" : "pt-[3px]",)}>@@ -4340,9 +4263,8 @@ export function AppSidebar() {<divaria-hidden="true"className={cn(- // The scroll area hard-clips at the fade's bottom edge, so a plain- // ramp is still part-transparent there and slices the last row- // mid-glyph. from-[8px] holds it opaque just across the clip, and+ // The scroll area hard-clips at the fade's bottom edge, so a plain ramp is still part-transparent+ // there and slices the last row mid-glyph. from-[8px] holds it opaque just across the clip, and// matches the list's pb-2 so the gap is the same once it hides."pointer-events-none absolute start-0 end-[var(--sidebar-rail,0px)] bottom-full bg-gradient-to-t from-[var(--sidebar-surface)] from-[8px] to-[rgb(from_var(--sidebar-surface)_r_g_b/0)] transition-opacity duration-200",// Shorter fade with the update card so the list reads closer todiff --git a/studio/frontend/src/components/assistant-ui/attachment.tsx b/studio/frontend/src/components/assistant-ui/attachment.tsxindex 5388bb5a60c..f35d32cd254 100644--- a/studio/frontend/src/components/assistant-ui/attachment.tsx+++ b/studio/frontend/src/components/assistant-ui/attachment.tsx@@ -92,9 +92,8 @@ type PastedTextAttachment = {readonly sentBytes?: number;};-// Long pastes arrive as a synthetic .txt and render as a chip, not a tile.-// The selector only passes references along: the text can be megabytes, so-// nothing here may copy or scan it.+// Long pastes arrive as a synthetic .txt and render as a chip, not a tile. The selector only passes+// references along: the text can be megabytes, so nothing here may copy or scan it.const usePastedTextAttachment = (): PastedTextAttachment | null => {return useAuiState(useShallow(({ attachment }): PastedTextAttachment | null => {diff --git a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsxindex 8d0d46e5cc2..864034cbbdb 100644--- a/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx+++ b/studio/frontend/src/components/assistant-ui/code-fence-defer.tsx@@ -18,54 +18,28 @@ import { type FenceMode, resolveFenceMode } from "./code-fence-mode";import { normalizeLanguage } from "./code-plugin";/*- * MONOTONIC fence highlighting: a fence is rendered as a plain shell until the- * first time it comes near the viewport, and from that moment it is highlighted- * for the rest of its mount. There is no reverse edge.- *- * WHY THE DIRECTION MATTERS. The previous attempt at this gated on viewport- * entry AND on viewport EXIT, so scrolling away from a fence, or collapsing the- * pane holding it, tore the highlighted subtree down and scrolling back built- * it again. That makes the gate BIDIRECTIONAL: a user gesture that ought to- * cost nothing instead schedules a full re-tokenize and a re-mount of every- * span in the block. It was predicted to save 55% and measured slower.- *- * Here the only transition is cheap -> expensive, taken at most once per mount.- * Scrolling away costs nothing, because there is nothing to undo; the observer- * has already been disconnected and the component has no effect left running.- * The worst case is therefore exactly today's cost (every fence looked at), and- * every fence the reader never reaches is saved outright.- *- * WHAT THE SHELL IS. The same text, in the same elements streamdown's own- * unhighlighted fallback would use, carrying the same `data-streamdown`- * attributes so every rule in index.css that sizes a code block applies to it- * unchanged. The text is present in the DOM and selectable, which is the- * property `content-visibility: auto` does not have: skipped content has to be- * rendered before it can be selected, and that was measured at +28.8% on- * `select_all_copy.select_all_ms`. Selection, clipboard and native find-in-page- * see the same characters here whether the fence has upgraded or not.- *- * A STREAMING fence never defers. The block being written is by definition the- * one the reader is looking at, and deferring it would change what streaming- * renders rather than what a settled thread costs.+ * MONOTONIC fence highlighting: a fence renders as a plain shell until the first time it comes near+ * the viewport, and is highlighted for the rest of its mount. There is no reverse edge.+ * An earlier attempt gated on viewport entry AND exit, so scrolling away tore the highlighted+ * subtree down and scrolling back rebuilt it: a gesture that ought to cost nothing scheduled a full+ * re-tokenize, and it measured slower. Here the only transition is cheap -> expensive, at most once+ * per mount, so the worst case is exactly today's cost and every fence never reached is saved.+ * The shell is the same text in the same elements streamdown's own unhighlighted fallback would+ * use, carrying the same `data-streamdown` attributes so index.css sizes it unchanged. The text is+ * in the DOM and selectable, which `content-visibility: auto` is not (skipped content has to be+ * rendered before it can be selected, +28.8% on select_all_ms).+ * A STREAMING fence never defers: the block being written is the one the reader is looking at.*//** How far outside the viewport a fence counts as "reached": one viewport of slack each way, so the- * upgrade lands a frame or two before the block is on screen and the reader never sees the swap.- *- * THE PERCENTAGE RESOLVES AGAINST THE ROOT'S HEIGHT, and the spec says otherwise. Intersection- * Observer 2.2 says percentages "are resolved relative to the width of the undilated rectangle"- * for all four sides; no engine does that for top and bottom, and w3c/IntersectionObserver#391 is- * open on exactly that. Measured on a synthetic scroller, with `0px 0px` and `300px 0px` alongside- * as controls that must come back 0 and 300:- *- * root 300x800 -> 800 px root 1600x600 -> 600 px root 600x1400 -> 1400 px- *- * on Chromium, Firefox and WebKit alike, nine rows, every control reproduced. So it is the HEIGHT,- * which `inBand` and the jump test below both assume. That is today's engines against a spec that- * reads otherwise, so it is guarded rather than trusted: `pf9462_parity.py` re-measures two- * geometries every run and fails if the observer's lookahead and the pre-paint band stop agreeing,- * which is what an engine moving to the spec's reading would look like.+ * upgrade lands a frame or two before the block is on screen.+ * THE PERCENTAGE RESOLVES AGAINST THE ROOT'S HEIGHT, and the spec says otherwise: Intersection+ * Observer 2.2 resolves percentages against the undilated rectangle's WIDTH for all four sides, no+ * engine does that for top and bottom, and w3c/IntersectionObserver#391 is open on it. Measured as+ * the height on Chromium, Firefox and WebKit alike, which `inBand` and the jump test both assume.+ * Guarded rather than trusted: `pf9462_parity.py` re-measures two geometries every run and fails if+ * the observer's lookahead and the pre-paint band stop agreeing.*/const REACH_MARGIN = "100% 0px";@@ -89,11 +63,10 @@ const readBuildFlag = (): string => {}};-// Streamdown trims trailing newlines off a fence body before rendering it, so-// the shell has to as well or the two differ by a blank line of height.-//-// The length is split out because `warmGrammars` needs the size of what a warm WOULD tokenize on-// every render, and slicing a 20,000 character fence to measure it is a copy per render.+// Streamdown trims trailing newlines off a fence body before rendering it, so the shell has to as+// well or the two differ by a blank line of height. The length is split out because `warmGrammars`+// needs the size of what a warm WOULD tokenize, and slicing a 20,000 character fence to measure it+// is a copy per render.export const trimmedLength = (text: string): number => {let end = text.length;while (end > 0 && text[end - 1] === "\n") end -= 1;@@ -104,17 +77,11 @@ export const trimTrailingNewlines = (text: string): string =>text.slice(0, trimmedLength(text));/*- * AN EMPTY FENCE IS ONE LINE TALL, not nothing.- *- * Streamdown renders a code block as one span per token line, and it special-cases the empty line:- *- * children: c.length === 0 || (c.length === 1 && c[0].content === "") ? `\n` : c.map(...)- *- * It also trims trailing newlines off the source first, exactly as `trimTrailingNewlines` does- * here, so a fence whose body is empty or is nothing but newlines tokenizes to a single empty line- * and renders as one newline: one line box of height. A `<code>` holding an empty text node has no- * line box at all, so without this the shell is one line shorter than the block it stands in for- * and the fence grows by a line when it upgrades, moving everything below it.+ * AN EMPTY FENCE IS ONE LINE TALL, not nothing. Streamdown renders one span per token line and+ * special-cases the empty line to a single newline, having trimmed trailing newlines first exactly as+ * `trimTrailingNewlines` does here, so an empty body renders as one line box of height. A `<code>`+ * holding an empty text node has no line box at all, so without this the shell is one line shorter+ * than the block it stands in for and everything below it moves when the fence upgrades.*/const shellBody = (source: string): string => {const trimmed = trimTrailingNewlines(source);@@ -158,28 +125,26 @@ function FenceShell({/*** Has this fence been reached yet? Latches true and never returns false again.*- * Takes a ref to an element the CALLER already renders rather than mounting a- * wrapper of its own. An extra div here would sit between a list item and its- * code block and break `[data-streamdown="list-item"] > [data-streamdown=- * "code-block"]`, and would push the block one level deeper than the- * `:last-child` margin chain in index.css walks -- a layout change smuggled in- * by a performance change, which is the one thing an A/B must not carry.+ * Takes a ref to an element the CALLER already renders rather than mounting a wrapper: an extra div+ * would sit between a list item and its code block, breaking+ * `[data-streamdown="list-item"] > [data-streamdown="code-block"]`, and would push the block one+ * level deeper than index.css's `:last-child` margin chain walks. That is a layout change smuggled+ * in by a performance change, which is the one thing an A/B must not carry.*/-// No IntersectionObserver, no gate. Read once at module scope so the decision-// is part of the rendered value rather than a state write from inside an-// effect, which would cost a cascading render on every fence in the thread.+// No IntersectionObserver, no gate. Read once at module scope so the decision is part of the+// rendered value rather than a state write from inside an effect, which would cost a cascading+// render on every fence in the thread.const CAN_OBSERVE =typeof IntersectionObserver !== "undefined" &&typeof globalThis !== "undefined";/*- * THE REGISTER OF FENCES THAT HAVE NOT BEEN REACHED YET, for the two things that must reach across- * all of them at once without waiting for a React render: a discontinuous scroll, and a print,- * which puts the WHOLE document on the page. Both go through `latchNow` below.- *- * A gate carries the two elements its observers were built against, resolved at the same moment- * and rebuilt with them, so nothing here re-walks the ancestor chain or re-reads a computed style.- * `warm` comes from the caller because the highlighter instance lives with the block's component.+ * THE REGISTER OF FENCES NOT YET REACHED, for the two things that must reach across all of them at+ * once without waiting for a React render: a discontinuous scroll, and a print, which puts the+ * WHOLE document on the page. Both go through `latchNow`. A gate carries the two elements its+ * observers were built against, resolved at the same moment and rebuilt with them, so nothing here+ * re-walks the ancestor chain or re-reads a computed style. `warm` comes from the caller because+ * the highlighter instance lives with the block's component.*/type FenceGate = {node: HTMLElement;@@ -203,31 +168,21 @@ const gateOpen = (gate: FenceGate): boolean =>&& (gate.near === gate.outer || inBand(gate.near as HTMLElement, gate.outer));/*- * UPGRADE THESE FENCES INSIDE THIS TASK, so the browser paints them highlighted instead of- * painting the plain shell and correcting it a few frames later. Dropping any of the three steps- * was measured to put a painted plain frame back:- *- * 1. `warm(true)`. Streamdown's highlighted body renders its own plain fallback whenever the- * plugin answers `null`, which it does only while a grammar is loading; with the grammar in- * hand it tokenizes in the same call. Warming makes the render below a cache hit.- * 2. The inner `flushSync(latch)`. A normally scheduled update lands after the next paint, which- * is the whole defect. This commits the shell-to-block swap in this task.+ * UPGRADE THESE FENCES INSIDE THIS TASK, so the browser paints them highlighted rather than+ * painting the plain shell and correcting it frames later. Dropping any of the three steps was+ * measured to put a painted plain frame back:+ * 1. `warm(true)`. Streamdown's highlighted body falls back to plain whenever the plugin answers+ * `null`, which it does only while a grammar loads; with the grammar in hand it tokenizes in+ * the same call, so the render below is a cache hit.+ * 2. The inner `flushSync(latch)`, since a normally scheduled update lands after the next paint.* 3. The inner `flushSync(poke)`, INSIDE an outer `flushSync`. Step 2 does not produce the* COLOURED commit: `HighlightedCodeBlockBody` starts at `useState(raw)` and asks for tokens- * from a PASSIVE effect, so every newly mounted block renders unhighlighted once. Off screen- * at thread mount that is invisible; deferred, it is a plain frame on the reader's screen.- *- * WHY THE POKE AND THE NESTING, since an empty `flushSync(() => {})` does neither:- *- * - React runs pending passive effects from `performSyncWorkOnRoot`, reached only when sync work- * is waiting, so a flush with nothing to do never runs the effect that colours the block.- * `poke` is that work: a state write on an already-latched fence whose own effects all- * early-return.- * - `flushSync` restores React's update priority BEFORE performing the flush, so the passive- * effect's update resolves against the ambient priority, and a scroll is continuous rather- * than discrete, so it is not flushed and lands next frame after all. The outer call holds the- * priority discrete across its whole body, so the inner flushes carry the effect's update too.- *+ * from a PASSIVE effect, so every newly mounted block renders unhighlighted once.+ * Why the poke and the nesting, since an empty `flushSync(() => {})` does neither: React runs+ * pending passive effects from `performSyncWorkOnRoot`, reached only when sync work is waiting, and+ * `poke` is that work. And `flushSync` restores update priority BEFORE performing the flush, so the+ * passive effect's update would resolve against the ambient priority (a scroll is continuous, so+ * not flushed); the outer call holds the priority discrete across its whole body.* One way only. Nothing here can clear a latch.*/const latchNow = (arrived: readonly FenceGate[]): void => {@@ -248,26 +203,19 @@ const latchNow = (arrived: readonly FenceGate[]): void => {/** A DISCONTINUOUS SCROLL: a scrollbar drag, Ctrl+End, an anchor jump, a restored position.- ** Neither the observers' one root height of lookahead (`REACH_MARGIN`) nor the render-time* pre-paint gate covers a jump: the viewport can move further than the lookahead in one step with* no React render in between, and an IntersectionObserver record is delivered one or more frames- * AFTER the paint. Chromium at the 100K rung, 16 seeded jumps: 8 painted 3 to 4 frames of plain- * code, 50 to 190 ms.- *- * A SCROLL LISTENER IS ENOUGH AND IS IN TIME: scroll events are dispatched in the "run the scroll+ * AFTER the paint (measured: 8 of 16 seeded jumps painted 3 to 4 frames of plain code).+ * A scroll listener is enough and is in time: scroll events are dispatched in the "run the scroll* steps" of the same update-the-rendering pass that will paint the new position, before* animation-frame callbacks and before style, layout and paint, so a `flushSync` from here is part- * of the frame the reader is about to see. `scrollTo`, wheel, drag and keyboard all arrive here.- *- * THE THRESHOLD IS DERIVED, NOT TUNED. The band is one root height `h` bigger each way, so after a+ * of the frame the reader is about to see.+ * The threshold is derived, not tuned: the band is one root height `h` bigger each way, so after a* scroll of `d` the newly visible strip `[d, d + h]` is inside the old band exactly when `d <= h`.- * The pass therefore runs only when the lookahead provably did not cover the movement, and a- * continuous scroll pays one subtraction per event.- *- * ONE LISTENER, NOT ONE PER FENCE. Scroll does not bubble but does capture, so one capturing+ * One listener, not one per fence: scroll does not bubble but does capture, so one capturing* document listener sees every element including nested reasoning panes. Attached when the first- * fence registers and removed when the last latches, so nothing left to defer costs nothing.+ * fence registers and removed when the last latches.*/const lastScrollTop = new WeakMap<EventTarget, number>();let scrollWatched = false;@@ -305,35 +253,23 @@ const unwatchScrolling = (): void => {/** PRINT, the one gesture that puts every deferred fence on the page at once.- *- * Colour is all deferral costs a printed page -- the shell holds a live text node, so it prints- * complete, in order and in the right font -- but a page that lost the colour on fences the reader- * never scrolled past is a defect they can see and keep. Nor does the printed window match the- * reader's: a print lays out at PAPER width while the scroll offset carries across as raw pixels,- * so the page lands several fences away. Letter against a 1280 px window: 1 to 2 deferred fences- * on every sampled page, 6.6% pixel difference against the same page with the flag off; matching- * paper to window removes it, which identifies the cause and is why chasing the window is the- * wrong fix. The whole document is on the page, so the whole document has to be highlighted.- *- * WHY AN EARLIER ATTEMPT FAILED and was reported as impossible: it latched every fence from- * `beforeprint` with `flushSync`, the blocks swapped, and 53 of 56 still printed on streamdown's- * raw fallback, because the swap alone renders UNHIGHLIGHTED while the passive effect waits on a- * grammar. `latchNow` closes both halves (warm, then flush the colouring render as well as the- * swap) and `warmGrammars` below keeps a loading grammar from being what is missing at snapshot.- *+ * Colour is all deferral costs a printed page, since the shell holds a live text node, but a page+ * that lost the colour on fences the reader never scrolled past is a defect they keep. Nor does the+ * printed window match the reader's: a print lays out at PAPER width while the scroll offset+ * carries across as raw pixels, so the page lands several fences away (matching paper to window+ * removes the difference, which is why chasing the window is the wrong fix). The whole document is+ * on the page, so the whole document has to be highlighted.+ * An earlier attempt latched every fence from `beforeprint` with `flushSync` and 53 of 56 still+ * printed on streamdown's raw fallback, because the swap alone renders UNHIGHLIGHTED while the+ * passive effect waits on a grammar. `latchNow` closes both halves and `warmGrammars` keeps a+ * loading grammar from being what is missing at snapshot.* BOTH DOORS: `beforeprint` covers Ctrl+P and the print menu; headless `page.pdf()` and DevTools- * print emulation change the media query without firing it, and a PDF export is how a reader keeps- * a copy.- *+ * print emulation change the media query without firing it.* A PRINT UPGRADES THE DOCUMENT THAT WAS PRINTED, AND NOTHING ELSE. This was a module-global- * `printed` folded into every future fence's `reached`, a session-wide latch rather than a- * monotonic one: at the 100K rung a thread with 53 of 56 fences deferred, 2,458 spans and 22,794- * elements printed once, then after navigating away inside the app and back remounted with 0- * deferred, 41,410 spans and 61,747 elements. One Ctrl+P turned the default off for the tab's- * life, including threads never on the printed page. So a print latches what is on the page WHEN- * IT HAPPENS and a fence mounted afterwards defers again; every print does it again, so print,- * scroll, print gives a second page as complete as the first. Still one way only: `latchNow` can- * only latch, and reverting on `afterprint` would be the bidirectional edge this design avoids.+ * `printed` folded into every future fence's `reached`, so one Ctrl+P turned the default off for+ * the tab's life, including threads never on the printed page. So a print latches what is on the+ * page WHEN IT HAPPENS and a fence mounted afterwards defers again. Still one way only: reverting+ * on `afterprint` would be the bidirectional edge this design avoids.*/const upgradeEverythingForPrint = (): void => {latchNow([...unreached]);@@ -341,55 +277,30 @@ const upgradeEverythingForPrint = (): void => {/** GRAMMARS, WARMED AT IDLE, ON REAL TEXT, ONE TOKENIZATION PER TASK.- ** One fence per language, so `latchNow`'s synchronous path cannot be defeated by a still-loading* grammar: on a jump into a language the reader has not met, and on a print, where there is no* later frame to correct in. Nothing runs when nothing is deferred. "Per language" means per- * GRAMMAR, `normalizeLanguage`, not per fence tag: ```py and ```python are one grammar to the- * highlighter, and two keys here would warm it twice, on two different fences.- *- * IT USED TO WARM ON AN EMPTY STRING. Loading a grammar is the cheap half; running it over text- * the first time is not, and `""` never does the second. So the first REAL tokenization still paid- * the whole one-off cost, and with deferral on that landed in one frame, during a scroll, on the- * fence the reader had just reached. Three arms out of ONE build at the 100K rung on WebKitGTK- * 2.50.4, two reps each, so a difference between arms cannot be a build difference:- *- * worst scroll frame warm callbacks, ms- * warm on "" 1200, 1085 ms 1 and 1- * warm on real text 183, 190 ms 1 and 2- * this: split, eager loads 187, 183 ms 1/64/21/32/1016 and 2/68/36/52/1104- *- * The 1,016 ms is ONE tokenize call, typescript's first, which nothing here can subdivide; the- * split only keeps the other four off it. Every arm pays that call: unsplit at t=6.5 s inside a- * grammar-load callback, which is why its warm reads 1 ms, and on the `""` arm at t=36.5 s, inside- * the scroll, where it IS the worst frame. Moved, not skipped, and the totals say so: tokenize time- * RISES, 1607-1746 ms to 1917-2039 ms, because a warmed fence is tokenized once and read from cache- * later. Mount is unaffected, worst idle frame is best here (25 and 32 ms against 46/37 unsplit and- * 38/43 on `""`), idle is 62.5 fps and 7.1 to 7.4% busy on every arm, the three arms render the- * same document (7,259 spans, 27,045 elements, 56 code blocks), and the rig is jam-controlled: a- * 200 ms/250 ms hog reads 81% busy.- *+ * GRAMMAR, `normalizeLanguage`, not per fence tag: ```py and ```python are one grammar, and two+ * keys here would warm it twice on two different fences.+ * IT USED TO WARM ON AN EMPTY STRING. Loading a grammar is the cheap half; running it over text the+ * first time is not, and `""` never does the second, so the first REAL tokenization still paid the+ * whole one-off cost, landing in one frame during a scroll (worst scroll frame 1200 ms against+ * 185 ms warming on real text, three arms out of one build). Moved, not skipped: total tokenize+ * time RISES, because a warmed fence is tokenized once and read from cache later.* WHY THE TOKENIZATIONS YIELD AND THE LOADS DO NOT. An idle callback only chooses when it STARTS:* nothing yields once it runs, its 2,000 ms timeout can start it on a busy thread, and WebKitGTK- * has no `requestIdleCallback` at all, so this venue takes the `setTimeout` fallback and cannot- * even pick a quiet moment. With a grammar already loaded `code.highlight` tokenizes INLINE and N- * languages concatenate -- driving shiki with this component's configuration, the five languages- * here (c, python, go, typescript, rust) cost 746 ms back to back. But `highlight` answers `null`- * WHILE a grammar loads, so yielding the loads too would put the fifth grammar 500 ms x N away and- * a jump or a print inside that window would get streamdown's plain fallback out of `latchNow`'s- * flush -- the defect this whole pre-warm exists to prevent. So every load starts in the first- * pass and only the tokenizing is spread out.- *- * NOTHING BOUNDED THE SIZE OF A WARM, and this comment used to claim `MAX_HIGHLIGHT_CHARS` did.- * It does not reach here: `markdownPluginNeeds` applies it in `markdown-preview.tsx` and- * `model-readme.tsx`, `tool-code-cell.tsx` and `attachment-preview.tsx` apply it to their own- * source, but `markdown-text.tsx` supplies the code plugin unconditionally and `FenceBlock` warms- * the whole body -- and `code-plugin.ts`'s `evict` keeps the last fence whatever its size. A LATCH- * is demanded work and stays uncapped; a warm is SPECULATIVE, on a fence the reader may never- * reach, so it is capped at the same 20,000 characters. Over the cap, and for a fence that is- * EMPTY or nothing but newlines, the grammar loads and nothing is tokenized; neither marks the- * language warmed, so a later fence that can warm it still does. The cap costs the measurement- * nothing: the largest fence at this rung is 2,817 characters.+ * has no `requestIdleCallback` at all. With a grammar already loaded `code.highlight` tokenizes+ * INLINE and N languages concatenate. But `highlight` answers `null` WHILE a grammar loads, so+ * yielding the loads too would put the fifth grammar 500 ms x N away and a jump or print inside+ * that window would get the plain fallback out of `latchNow`'s flush, the defect this pre-warm+ * exists to prevent. So every load starts in the first pass and only the tokenizing is spread out.+ * NOTHING BOUNDED THE SIZE OF A WARM, and this comment used to claim `MAX_HIGHLIGHT_CHARS` did. It+ * does not reach here: `markdown-text.tsx` supplies the code plugin unconditionally, `FenceBlock`+ * warms the whole body, and `code-plugin.ts`'s `evict` keeps the last fence whatever its size. A+ * LATCH is demanded work and stays uncapped; a warm is SPECULATIVE, so it is capped at the same+ * 20,000 characters. Over the cap, and for a fence that is empty or nothing but newlines, the+ * grammar loads and nothing is tokenized; neither marks the language warmed, so a later fence that+ * can warm it still does.*/const grammarsWarmed = new Set<string>();const grammarsLoaded = new Set<string>();@@ -445,26 +356,19 @@ if (typeof window !== "undefined" && typeof window.addEventListener === "functio/** THE NEAREST SCROLLING ANCESTOR, found rather than named.- *- * This used to match two known selectors, `[data-slot='thread-viewport']` and- * `.aui-thread-viewport`, and `closest()` walks straight past anything that matches neither. The- * one that matters is the reasoning pane: while a reply streams, `reasoning.tsx` gives its trace- * `overflow-y-auto` and `max-h-64` and pins it to the bottom, so the reader is looking at an+ * This used to match two known selectors and `closest()` walks straight past anything matching+ * neither. The one that matters is the reasoning pane: while a reply streams, `reasoning.tsx` gives+ * its trace `overflow-y-auto` and `max-h-64` and pins it to the bottom, so the reader looks at an* arbitrarily long trace through a 256 px window nested inside the thread scroller.- *- * What this is NOT. It is not a correctness fix. Intermediate scrollers clip, so intersection was- * always computed correctly and fences inside that pane were always deferred properly; measured in- * Chromium with ten fences in a 256 px inner scroller inside a 400 px outer one, 3 of 10 reported- * intersecting either way. It is a LOOKAHEAD fix. `rootMargin` expands the ROOT's rectangle, so- * rooting at the thread viewport expanded a rectangle the reader is not looking through and the- * one-viewport warning was worth nothing inside the pane: the "100% 0px" column and the no-margin- * column were identical at 3 of 10, while rooting at the inner scroller gave 5 of 10. The- * user-visible consequence of getting it wrong is narrow and real: a fence scrolling into the- * 256 px window gets no pre-warm and shows the plain shell for the frames the upgrade takes.- *- * `null` is deliberately still possible and is deliberately NOT the default: a fence with no- * scrolling ancestor really is clipped by the document viewport, but assuming that when a scroller- * exists is the bug the review caught.+ * Not a correctness fix: intermediate scrollers clip, so intersection was always computed+ * correctly. It is a LOOKAHEAD fix. `rootMargin` expands the ROOT's rectangle, so rooting at the+ * thread viewport expanded a rectangle the reader is not looking through and the one-viewport+ * warning was worth nothing inside the pane (3 of 10 with and without the margin, against 5 of 10+ * rooted at the inner scroller). Getting it wrong shows the plain shell for the frames the upgrade+ * takes.+ * `null` is deliberately still possible and deliberately NOT the default: a fence with no scrolling+ * ancestor really is clipped by the document viewport, but assuming that when a scroller exists is+ * the bug the review caught.*/const isScrollable = (el: HTMLElement): boolean => {const overflowY = getComputedStyle(el).overflowY;@@ -483,48 +387,27 @@ const scrollerOf = (node: HTMLElement): HTMLElement | null => {/** THE OUTERMOST ONE TOO, and why the nearest is not enough on its own.- ** An explicit root is clipped by the ancestors BETWEEN the target and the root, and by NOTHING- * above it. Rooting at the reasoning pane therefore asks "is this fence inside the pane's own- * window" and never "is the pane itself anywhere near the reader". Two ways that goes wrong, and- * the second one undoes the whole change on the pane most likely to hold the spans:- *- * 1. A pane scrolled far out of the thread still reports the two or three fences inside its- * 256 px window as intersecting, so they upgrade where nobody can see them.- * 2. `reasoning.tsx` drops `max-h-64` when the stream ends but KEEPS `overflow-y-auto`, so the- * pane stops being scrollable and its box becomes the whole trace. An observer still rooted- * at it from the streaming frames then reports EVERY fence in that trace as intersecting at- * once.- *- * Rooting at the outermost scroller instead would fix both and cost the lookahead that rooting at- * the nearest one bought: measured in Chromium with ten fences in a 256 px inner scroller inside a- * 400 px outer one, the inner root reports 5 of 10 with a one-window margin against 3 of 10 for- * the outer root, and the difference is exactly the pre-warm that keeps a fence from showing its- * plain shell as it scrolls into the pane.- *- * So when the two differ there are two gates, watching two different elements, and the latch needs- * both: the FENCE against the nearest scroller answers "the reader is about to reach it inside the- * pane", and the PANE against the outermost scroller answers "the pane is somewhere the reader can- * see". Watching the fence through the outer root instead would clip it at the pane on the way and- * go false exactly where the inner lookahead was doing its work -- 2 of 10 against 4, measured with- * the pane fully in view. When the two scrollers are the same element, which is every fence outside- * a nested scroller, there is exactly one observer and this costs nothing.- *- * THE CONJUNCTION IS NOT ENOUGH ON ITS OWN, which took a measurement to see. A stale inner root- * is too permissive, and the outer gate only covers that while the pane is out of view. Scroll the- * expanded pane so much as partly on screen and the outer gate is true, so the stale inner root- * decides alone and reports the WHOLE trace: 10 of 10 in both engines, on a 4,080 px trace against- * a 900 px viewport where the right answer is about 3. So the inner root is re-resolved when the- * pane stops scrolling, which collapses the fence back to the single-gate case where the outermost- * scroller is the root and nothing can be stale.- *- * Watched with a ResizeObserver on the pane rather than by re-resolving on every frame, and only- * for fences that actually have a nested scroller. The callback reads one `overflow-y` on one- * element, so a streaming pane resizing every frame costs one computed-style read per fence per- * frame and rebinds nothing until the cap actually comes off.- *- * Still one-way. Nothing here can clear a latch; the extra gate and the rebind can only withhold- * one.+ * above it, so rooting at the reasoning pane asks "is this fence inside the pane's window" and+ * never "is the pane anywhere near the reader". A pane scrolled far out of the thread still reports+ * the fences inside its 256 px window as intersecting, and `reasoning.tsx` drops `max-h-64` when+ * the stream ends but KEEPS `overflow-y-auto`, so the pane stops being scrollable, its box becomes+ * the whole trace, and an observer still rooted at it reports EVERY fence at once.+ * Rooting at the outermost scroller instead would fix both and cost the lookahead the nearest one+ * bought (5 of 10 inner against 3 of 10 outer, measured). So when the two differ there are two+ * gates and the latch needs both: the FENCE against the nearest scroller answers "the reader is+ * about to reach it inside the pane", and the PANE against the outermost answers "the pane is+ * somewhere the reader can see". Watching the fence through the outer root instead would clip it at+ * the pane on the way and go false exactly where the inner lookahead works. When the two scrollers+ * are the same element there is one observer and this costs nothing.+ * THE CONJUNCTION IS NOT ENOUGH ON ITS OWN. A stale inner root is too permissive and the outer gate+ * only covers that while the pane is out of view: scroll the expanded pane partly on screen and the+ * stale inner root decides alone and reports the WHOLE trace (10 of 10 in both engines where the+ * right answer is about 3). So the inner root is re-resolved when the pane stops scrolling, which+ * collapses the fence back to the single-gate case.+ * Watched with a ResizeObserver on the pane rather than by re-resolving every frame, and only for+ * fences that have a nested scroller: the callback reads one `overflow-y` on one element.+ * Still one-way. The extra gate and the rebind can only withhold a latch.*/const outermostScrollerOf = (node: HTMLElement): HTMLElement | null => {let found: HTMLElement | null = null;@@ -544,17 +427,17 @@ const inBand = (node: HTMLElement, scroller: HTMLElement | null): boolean => {};/**- * @param enabled false on the shipped default, where this hook must cost nothing at all: no- * state is ever written, no observer is built and no layout is read.+ * @param enabled false on the shipped default, where this hook must cost nothing at all: no state+ * is written, no observer is built and no layout is read.* @param streaming the fence is still being written. It is highlighted while it streams AND it* latches, so that finishing cannot take the highlighting back.* @param language used only to load one grammar per language rather than one per fence; `null`* warms plain text.- * @param chars this fence's source length, read only by `warmGrammars` to keep a SPECULATIVE- * warm inside `MAX_HIGHLIGHT_CHARS`. A latch is demanded work and is not capped.+ * @param chars this fence's source length, read only by `warmGrammars` to keep a SPECULATIVE warm+ * inside `MAX_HIGHLIGHT_CHARS`. A latch is demanded work and is not capped.* @param warm drive the highlighter over this fence: `true` for tokens, `false` for the grammar- * alone. See `latchNow`. Held in a ref, not an effect dependency, so an- * unmemoized caller cannot rebuild every observer in the thread on every render.+ * alone. Held in a ref, not an effect dependency, so an unmemoized caller cannot+ * rebuild every observer in the thread on every render.*/export function useFenceReached(host: RefObject<HTMLElement | null>,@@ -575,16 +458,11 @@ export function useFenceReached(}, [warm]);/*- * A COMPLETING STREAM MUST NOT DOWNGRADE.- *- * `streaming` goes true -> FALSE when streamdown recognises the closing delimiter. Deriving- * `reached` from it alone therefore takes a fence that was highlighted all through its stream- * and hands it back the plain shell the moment it finishes: highlighted -> plain, on a block the- * reader is watching, which is precisely the reverse edge this design exists to remove. The- * fence was reached; that has to be recorded, not recomputed.- *- * In a layout effect so the downgrade is never painted even for one frame.- */+ * A COMPLETING STREAM MUST NOT DOWNGRADE. `streaming` goes true -> FALSE when streamdown+ * recognises the closing delimiter, so deriving `reached` from it alone hands a fence that was+ * highlighted all through its stream back the plain shell the moment it finishes: the reverse+ * edge this design exists to remove. In a layout effect so it is never painted.+ */useLayoutEffect(() => {if (!enabled || latched || !streaming) return;// eslint-disable-next-line react-hooks/set-state-in-effect@@ -592,28 +470,18 @@ export function useFenceReached(}, [enabled, latched, streaming]);/*- * THE FIRST FRAME, which the observer cannot cover.- *- * An IntersectionObserver delivers its first record asynchronously, one or more frames after- * `observe()`. For a fence that is ALREADY on screen when the thread mounts, those frames are- * plain code inside the viewport: measured at 2 to 3 frames, 30 to 190 ms. That is a visible- * difference, not an off-screen one, so it is closed here rather than argued about.- *- * `useLayoutEffect` runs after mutation and BEFORE paint, so a fence that is on screen latches- * and re-renders within the same frame and the plain shell is never painted. One- * `getBoundingClientRect` per unreached fence, all of them inside a single commit with no DOM- * mutation in between, so the layout is forced once for the whole thread rather than once per- * fence.- *- * RE-RUN ON A REBIND. `generation` is a dependency because the ResizeObserver below bumps it- * when the reasoning pane stops scrolling, and expanding that pane can bring a fence inside the- * outer viewport for the first time. Without it the rebind's own render leaves the plain shell- * in place, and the replacement observer is built in a passive effect and delivers- * asynchronously, so the shell is PAINTED. That is an on-screen difference, which is the one- * kind this change is not allowed to have.- *- * Still one-way: this can only ever latch true.- */+ * THE FIRST FRAME, which the observer cannot cover.+ * An IntersectionObserver delivers its first record asynchronously, one or more frames after+ * `observe()`, so a fence ALREADY on screen at mount shows plain code inside the viewport for 2+ * to 3 frames. `useLayoutEffect` runs after mutation and BEFORE paint, so it latches and+ * re-renders within the same frame. One `getBoundingClientRect` per unreached fence, all inside a+ * single commit with no DOM mutation between, so layout is forced once for the whole thread.+ * RE-RUN ON A REBIND. `generation` is a dependency because the ResizeObserver below bumps it when+ * the reasoning pane stops scrolling, and expanding that pane can bring a fence inside the outer+ * viewport for the first time; without it the replacement observer is built in a passive effect+ * and delivers asynchronously, so the shell is PAINTED.+ * Still one-way: this can only ever latch true.+ */useLayoutEffect(() => {if (reached) return;const node = host.current;@@ -623,43 +491,31 @@ export function useFenceReached(const near = scrollerOf(node);const outer = outermostScrollerOf(node);if (inBand(node, near) && (near === outer || inBand(near as HTMLElement, outer))) {- // The cascading render this warns about is the POINT: it is what keeps the plain shell off- // the screen. It happens at most once per fence, only for the one or two fences that are- // already on screen at mount, and the alternative is the 2 to 3 painted frames of- // unhighlighted code this replaced.+ // The cascading render this warns about is the POINT: it keeps the plain shell off the screen. It+ // happens at most once per fence, only for the one or two already on screen at mount, and the+ // alternative is 2 to 3 painted frames of unhighlighted code.// eslint-disable-next-line react-hooks/set-state-in-effectsetLatched(true);}}, [reached, host, generation]);- // The one-way edge. Once `reached` is true this effect re-runs, takes the- // early return, and never observes anything again, so a fence that has been- // read carries no residual per-scroll cost at all.+ // The one-way edge. Once `reached` is true this effect re-runs, takes the early return, and never+ // observes anything again, so a fence that has been read carries no residual per-scroll cost.useEffect(() => {if (reached) return;const node = host.current;if (!node) return;- // ROOTED AT THE THREAD'S SCROLLER, not at the document.- //- // The chat scrolls inside a nested overflow container. With `root` unset the root is the- // document viewport, and `rootMargin` expands THAT rectangle -- while the intersection is- // still clipped by the scroller's own edges, which no margin can widen. The lookahead would- // then be worth nothing: a fence would report intersecting only once it was already inside- // the visible band, and the reader would get the plain shell for the frames it takes the- // observer to deliver and the upgrade to render. Rooting at the scroller is what makes the- // margin mean one viewport of warning.- //- // See `outermostScrollerOf`: when a nested scroller is in the way, the outermost one is+ // ROOTED AT THE THREAD'S SCROLLER, not at the document. The chat scrolls inside a nested overflow+ // container; with `root` unset the root is the document viewport and `rootMargin` expands THAT+ // rectangle, while the intersection is still clipped by the scroller's edges, which no margin can+ // widen. See `outermostScrollerOf`: when a nested scroller is in the way, the outermost one is// observed as well and the latch needs both. One observer, not two, whenever they agree.const near = scrollerOf(node);const outer = outermostScrollerOf(node);- // WHAT EACH GATE WATCHES, which is not the same element.- //- // Observing the FENCE against the outer root clips it at the pane on the way, so the outer- // gate goes false exactly where the inner lookahead was supposed to be doing its work: 2 of 10- // against the inner root's 4, measured, with the pane fully in view. Observing the PANE- // against the outer root asks the question the outer gate is for -- is the pane anywhere the- // reader can see -- and the inner gate keeps its lookahead untouched at 4 of 10.+ // WHAT EACH GATE WATCHES, which is not the same element. Observing the FENCE against the outer root+ // clips it at the pane on the way, so the outer gate goes false exactly where the inner lookahead+ // should be working (2 of 10 against 4). Observing the PANE against the outer root asks the+ // question the outer gate is for, and the inner gate keeps its lookahead untouched.const gates: [Element, Element | null][] = near === outer? [[node, near]]: [[node, near], [near as HTMLElement, outer]];diff --git a/studio/frontend/src/components/assistant-ui/code-fence-mode.ts b/studio/frontend/src/components/assistant-ui/code-fence-mode.tsindex 8ed68027d5e..4b23e1c6596 100644--- a/studio/frontend/src/components/assistant-ui/code-fence-mode.ts+++ b/studio/frontend/src/components/assistant-ui/code-fence-mode.ts@@ -3,16 +3,13 @@/** WHICH FENCE MODE IS IN FORCE, decided in one pure function.- ** Kept out of `code-fence-defer.tsx` because that is a `.tsx` and the frontend's tests run under* `node --experimental-strip-types`, which cannot load JSX. Every row below is RUN by* `tests/code-fence-mode.test.ts` rather than checked by regexes over the source.- ** "off" every fence is highlighted at mount. What shipped before `defer` became default.* "defer" SHIP DEFAULT. An unreached fence is a plain shell and is never tokenized.* "tokenize" MEASUREMENT ONLY. Same plain shell, but the highlighter is still driven over the* source and the result thrown away.- ** `tokenize` is not a shipping mode. `defer` removes the spans AND the tokenizer work that makes* them, so an improvement under `defer` alone cannot say which paid for it; `tokenize` holds the* DOM at `defer`'s size with only the tokenizer work back, so tokenize-minus-defer is thediff --git a/studio/frontend/src/components/assistant-ui/code-plugin.ts b/studio/frontend/src/components/assistant-ui/code-plugin.tsindex 786e90f33a0..dc53cf81d78 100644--- a/studio/frontend/src/components/assistant-ui/code-plugin.ts+++ b/studio/frontend/src/components/assistant-ui/code-plugin.ts@@ -72,23 +72,20 @@ export const normalizeLanguage = (language: string): BundledLanguage => {return alias ?? (key as BundledLanguage);};-// A streaming fence re-enters highlight() every frame with the whole block, so-// Shiki re-tokenizes it in full ~60x/sec. Past MIN_INCREMENTAL_CHARS, cache the-// completed lines and their grammar state so each refresh tokenizes only new-// text, keeping the 250 ms plain-tail cadence.+// A streaming fence re-enters highlight() every frame with the whole block, so Shiki re-tokenizes+// it in full ~60x/sec. Past MIN_INCREMENTAL_CHARS, cache the completed lines and their grammar+// state so each refresh tokenizes only new text, keeping the 250 ms plain-tail cadence.export const MIN_INCREMENTAL_CHARS = 2000;const REFRESH_MS = 250;-// Shiki's own tokenizer guard is a wall clock: a line that takes longer than-// `tokenizeTimeLimit` (default 500 ms) is abandoned part-way and the rest of it-// is emitted as one uncoloured token. Dual themes are two passes with two-// separate budgets, and only the first pays to compile the grammar's regexes,-// so a loaded machine drops the light theme to plain and keeps the dark one-// correct -- for the same line, in the same result. Committed lines are never-// re-tokenized, so that half-plain line is then cached for the life of the-// fence. Bound the work by line length instead: same protection against a-// minified blob (~120 ms at this length, growing quadratically past it, which-// is VS Code's `editor.maxTokenizationLineLength` default for the same reason),-// but the output depends on the source rather than on the host.+// Shiki's own tokenizer guard is a wall clock: a line that takes longer than `tokenizeTimeLimit`+// (default 500 ms) is abandoned part-way and the rest of it is emitted as one uncoloured token.+// Dual themes are two passes with two separate budgets, and only the first pays to compile the+// grammar's regexes, so a loaded machine drops the light theme to plain and keeps the dark one+// correct -- for the same line, in the same result. Committed lines are never re-tokenized, so that+// half-plain line is then cached for the life of the fence. Bound the work by line length instead:+// same protection against a minified blob (~120 ms at this length, growing quadratically past it,+// which is VS Code's `editor.maxTokenizationLineLength` default for the same reason), but the+// output depends on the source rather than on the host.export const TOKENIZE_LIMITS = {tokenizeTimeLimit: 0,tokenizeMaxLineLength: 20_000,@@ -169,37 +166,31 @@ const shiftLine = (line: TokenLine, offset: number): TokenLine =>: line.map((token) => ({ ...token, offset: token.offset + offset }));// ADJACENT-TOKEN COALESCING: TRIED, MEASURED AT ZERO, REMOVED.-//// The renderer emits one <span> per themed token, so a fence's span census is// its token census, and Shiki splits on GRAMMAR boundaries rather than on// rendered appearance. Merging runs of adjacent tokens whose rendered style is// byte-identical looked like a pure reduction with no gating at all: no// viewport state machine, nothing a reader could do to push a fence back into a// more expensive shape.-//// It buys exactly nothing. Running the whole studiobench corpus, 728 fences and// 1,335,897 code characters, through this component's own Shiki configuration:-//// dual tokens 537013 -> merged 537013 0.0% fewer// darkonly tokens 535981 -> merged 535981 0.0% fewer-//// and the 100K rung's 99 assembled fences, 180,902 characters, 72550 -> 72550// dual, 72408 -> 72408 dark only, 62098 -> 62098 light only. Not one adjacent// pair in half a million shares a rendered style, in any theme mode. Shiki// already emits maximally coalesced tokens. No timing was run on it, because a// mechanism that removes no spans cannot make anything faster.-//// The implementation is not kept. Carrying a runtime-flippable flag through the// fence cache for a measured-zero benefit only adds a way for a cached result// to disagree with the flag that produced it. Run// `node scripts/coal-span-census.mjs <markdown>` from studio/frontend to check// the census on any thread rather than taking these numbers on trust.-// Markdown reports a closing fence as body until it recognizes it, so that-// line is all a fence can lose: up to three spaces, one run of backticks or-// tildes, then spaces. It also starts a line, so the body it leaves behind ends-// at a newline. The run can be short, because the cached code is the last text-// tokenized and the run may still have been arriving then.+// Markdown reports a closing fence as body until it recognizes it, so that line is all a fence can+// lose: up to three spaces, one run of backticks or tildes, then spaces. It also starts a line, so+// the body it leaves behind ends at a newline. The run can be short, because the cached code is the+// last text tokenized and the run may still have been arriving then.const CLOSING_FENCE = /^ {0,3}(?:`+|~+)[ \t]*$/;/** Whether `longer` is one fence's body, `shorter`, plus its closing line. */diff --git a/studio/frontend/src/components/assistant-ui/code-themes.ts b/studio/frontend/src/components/assistant-ui/code-themes.tsindex 67db02b9b4d..46a131a03c1 100644--- a/studio/frontend/src/components/assistant-ui/code-themes.ts+++ b/studio/frontend/src/components/assistant-ui/code-themes.ts@@ -5,10 +5,9 @@ import oneDarkPro from "@shikijs/themes/one-dark-pro";import oneLight from "@shikijs/themes/one-light";import type { ThemeRegistrationAny } from "shiki";-// Canonical Atom One Dark / One Light themes from `@shikijs/themes`. Only the-// background is overridden so the code block blends into the app's `--code-block`-// surface; all token colors/scopes are kept intact for consistent multi-language-// highlighting out of the box.+// Canonical Atom One Dark / One Light themes from `@shikijs/themes`. Only the background is+// overridden so the code block blends into the app's `--code-block` surface; all token+// colors/scopes are kept intact for consistent multi-language highlighting out of the box.const withTransparentBg = (theme: ThemeRegistrationAny): ThemeRegistrationAny => ({...theme,bg: "transparent",diff --git a/studio/frontend/src/components/assistant-ui/image.tsx b/studio/frontend/src/components/assistant-ui/image.tsxindex 5bb9a6c2a0c..1070045f33a 100644--- a/studio/frontend/src/components/assistant-ui/image.tsx+++ b/studio/frontend/src/components/assistant-ui/image.tsx@@ -1,6 +1,5 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-//// Portions adapted from assistant-ui packages/ui/src/components/assistant-ui/image.tsx// MIT License, Copyright (c) 2025 AgentbaseAI Inc.// Source: https://github.com/assistant-ui/assistant-ui/blob/main/packages/ui/src/components/assistant-ui/image.tsxdiff --git a/studio/frontend/src/components/assistant-ui/markdown-block-fallback.ts b/studio/frontend/src/components/assistant-ui/markdown-block-fallback.tsindex 83a45e4df07..01990b89c6b 100644--- a/studio/frontend/src/components/assistant-ui/markdown-block-fallback.ts+++ b/studio/frontend/src/components/assistant-ui/markdown-block-fallback.ts@@ -4,23 +4,15 @@/*** What one Markdown block should show when it cannot be RENDERED.*- * Streamdown loads two parts of a reply through `React.lazy`: the syntax- * highlighted code body and the Mermaid renderer. Both are fetched at the- * moment a reply first contains that construct, and a lazy import that rejects- * rethrows during render. Nothing between the thread and the router catches- * that today, so one chunk that will not load replaces the whole application- * with the router's error page and takes the reply that was already on screen- * with it.+ * Streamdown loads the syntax highlighted code body and the Mermaid renderer through `React.lazy`,+ * and a lazy import that rejects rethrows during render. Nothing between the thread and the router+ * catches that today, so one chunk that will not load replaces the whole application with the+ * router's error page and takes the reply that was already on screen with it.*- * The answer is to keep the CONTENT. A fence whose highlighter is missing is- * still perfectly readable as text: it is the same characters in the same- * order, which is what the model actually said. So the degraded form of a block- * is its own source, with the Markdown fence scaffolding removed so a reader- * sees code rather than backticks.- *- * Deliberately NOT an error card and deliberately not blank. A reader who asked- * a model for a shell command needs the command, not an apology, and least of- * all an empty box where their answer used to be.+ * The answer is to keep the CONTENT: a fence whose highlighter is missing is still readable as+ * text, so the degraded form of a block is its own source with the Markdown fence scaffolding+ * removed. Deliberately NOT an error card and deliberately not blank. A reader who asked a model+ * for a shell command needs the command, not an apology, and least of all an empty box.*/export type MarkdownBlockFallback = {@@ -44,12 +36,10 @@ type OpeningFence = {};/**- * Scanned rather than matched.- *- * The regex this replaces put `[^\r\n]*` straight after `` `{3,} ``, and the two- * compete for the same backticks, so an opening run with no line break after it- * backtracks quadratically. Scanning takes the run greedily once and never- * reconsiders, which is linear by construction on any input.+ * Scanned rather than matched. The regex this replaces put a line-tail match straight after the+ * backtick run, and the two compete for the same backticks, so an opening run with no line break+ * after it backtracks quadratically. Scanning takes the run greedily once and never reconsiders,+ * which is linear by construction on any input.*/function openingFence(content: string): OpeningFence | null {let i = 0;@@ -66,11 +56,10 @@ function openingFence(content: string): OpeningFence | null {// the delimiter and the language tag as prose instead.const rest = lineEnd === -1 ? content.length : lineEnd;const info = content.slice(i + run, rest).replace(/\r$/, "");- // "If the info string comes after a backtick fence, it may not contain any- // backtick characters" (CommonMark 0.31.2). Such a line is a PARAGRAPH, so- // the block is not a whole-block fence and belongs to the caller unchanged;- // treating it as one drops the opening line and the reader loses that text.- // Tilde fences carry no such restriction. `CODE_FENCE_RE` in+ // "If the info string comes after a backtick fence, it may not contain any backtick characters"+ // (CommonMark 0.31.2). Such a line is a PARAGRAPH, so the block is not a whole-block fence and+ // belongs to the caller unchanged; treating it as one drops the opening line and the reader loses+ // that text. Tilde fences carry no such restriction, and `CODE_FENCE_RE` in// `features/chat/artifacts/html-fences` already spells the same rule.if (char === "`" && info.includes("`")) return null;const body = lineEnd === -1 ? "" : content.slice(lineEnd + 1);@@ -80,16 +69,12 @@ function openingFence(content: string): OpeningFence | null {/*** The body with the opener's indentation taken off each line.*- * "If the leading code fence is indented N spaces, then up to N spaces of- * indentation are removed from each line of the content" (CommonMark 0.31.2).- * UP TO: a line indented less than the opener loses only what it has, and a line- * indented more keeps the remainder, which is the code's own structure.- *- * Recognising the indent when opening the fence and then not removing it is the- * half of the rule that shows. The rendered block reads `x = 1`, the degraded- * one reads ` x = 1`, and a reader who copies that into a file gets an- * IndentationError from text their model never wrote. `extractHtmlFences`- * already applies the same rule to the same construct.+ * "If the leading code fence is indented N spaces, then up to N spaces of indentation are removed+ * from each line of the content" (CommonMark 0.31.2). UP TO: a line indented less than the opener+ * loses only what it has, and one indented more keeps the remainder, which is the code's own+ * structure. Recognising the indent when opening the fence and then not removing it is the half of+ * the rule that shows: the reader copies the degraded block into a file and gets an+ * IndentationError from text their model never wrote. `extractHtmlFences` applies the same rule.*/function stripIndent(body: string, indent: number): string {if (indent === 0 || body === "") return body;@@ -105,16 +90,14 @@ function stripIndent(body: string, indent: number): string {/*** Whether the line `[from, to)` of `text` closes a fence opened with `marker`.*- * CommonMark 0.31.2 requires the closing fence to use the same character and- * "at least as many" of it, so the opening length is a MINIMUM and not a match:- * a four-backtick close is how a model closes a fence whose body contains a- * three-backtick one. The previous back-reference demanded the exact same run- * and left the close on screen as if it were code.+ * CommonMark 0.31.2 requires the closing fence to use the same character and "at least as many" of+ * it, so the opening length is a MINIMUM and not a match: a four-backtick close is how a model+ * closes a fence whose body contains a three-backtick one. The previous back-reference demanded+ * the exact same run and left the close on screen as if it were code.*- * Bounds rather than a line STRING because the caller has thousands of lines and- * the only thing most of them need is a look at their first character. Slicing- * each one, and testing each one against a regex, cost more than everything else- * in the scan put together.+ * Bounds rather than a line STRING because the caller has thousands of lines and most need only a+ * look at their first character. Slicing each one and testing it against a regex cost more than+ * everything else in the scan put together.*/function closesFenceAt(text: string,@@ -140,16 +123,11 @@ function closesFenceAt(}/**- * The readable form of a block that failed to render.- *- * Falls back to the block's own source unchanged for anything that is not a- * whole-block fence: a paragraph, a list or a table is already readable as- * Markdown, and inventing a renderer here would be a second thing to go wrong.- *- * This runs only once rendering has ALREADY failed, so it is the last thing- * between the reader and a lost block. Getting the fence wrong here does not- * cost a nicety, it puts stray backticks in the only view of the answer that- * still exists.+ * The readable form of a block that failed to render. Falls back to the block's own source for+ * anything that is not a whole-block fence: a paragraph, a list or a table is already readable as+ * Markdown, and inventing a renderer here would be a second thing to go wrong. This runs only once+ * rendering has ALREADY failed, so getting the fence wrong does not cost a nicety, it puts stray+ * backticks in the only view of the answer that still exists.*/export function markdownBlockFallback(content: string): MarkdownBlockFallback {const open = openingFence(content);@@ -169,27 +147,20 @@ export function markdownBlockFallback(content: string): MarkdownBlockFallback {/*** The fence's content, or null when the fence does not own the whole block.*- * One block is usually one construct, but not always: Streamdown 2.5's- * `parseMarkdownIntoBlocks` returns an ENTIRE reply as a single block once it- * contains a footnote (measured: the same reply splits into 5 blocks without one- * and 1 with). A fence at the top of such a block is followed by its own close- * and then by prose, and reading the whole thing as the fence's body put the- * closing delimiter, the prose and the footnote on screen as if the model had- * written them as Python.+ * One block is usually one construct, but not always: Streamdown 2.5's `parseMarkdownIntoBlocks`+ * returns an ENTIRE reply as a single block once it contains a footnote (measured: the same reply+ * splits into 5 blocks without one and 1 with). A fence at the top of such a block is followed by+ * its own close and then by prose, and reading the whole thing as the fence's body put the closing+ * delimiter, the prose and the footnote on screen as if the model had written them as Python.*- * So the close is looked for from the TOP, and where it falls decides:- * last line the fence is the block. Its content is everything above.- * earlier the block continues past the fence, so it is not a whole-block- * fence and belongs to the caller unchanged.- * never still streaming. All of it is content, which is the case the- * reader needs most: the failure happens mid-fence, long before it- * closes.+ * So the close is looked for from the TOP, and where it falls decides. On the last line the fence+ * is the block and its content is everything above; earlier, the block continues past the fence,+ * so it belongs to the caller unchanged; never, it is still streaming and all of it is content,+ * which is the case the reader needs most since the failure happens mid-fence.*- * Driven by `indexOf` on the delimiter rather than walked line by line. A close- * has to carry at least three of the opening character, so the only lines worth- * looking at are the ones holding such a run, and an ordinary code block has- * exactly one: its own. Walking every line instead cost ~50ns per LINE, which a- * long block pays in full every time it re-renders.+ * Driven by `indexOf` on the delimiter rather than walked line by line: a close carries at least+ * three of the opening character, and an ordinary code block holds exactly one such run. Walking+ * every line cost ~50ns per LINE, which a long block pays in full every time it re-renders.*/function fenceBody(body: string, marker: string): string | null {// The line break before the closing fence belongs to the fence's line, and adiff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex e8a256aca2b..c35a8ae364b 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -95,10 +95,10 @@ import {} from "./streaming-render-schedule";const baseMath = createMathPlugin({ singleDollarTextMath: true });-// Mark the block that holds each inline maths root, on the way past, so `index.css` has something-// that can take containment. Composed onto the maths plugin's own rehype pass because that is the-// only hook here that runs after Streamdown's sanitizer, which strips class names it does not-// recognise. See `math-block-marker.ts` for why neither plugin prop works.+// Mark the block that holds each inline maths root, on the way past, so `index.css` has something that can take+// containment. Composed onto the maths plugin's own rehype pass because that is the only hook here that runs after+// Streamdown's sanitizer, which strips class names it does not recognise. See `math-block-marker.ts` for why+// neither plugin prop works.const math = {...baseMath,rehypePlugin: withMathBlockMarker(baseMath.rehypePlugin),@@ -124,24 +124,22 @@ const STREAMDOWN_SHIKI_THEME = [] satisfies NonNullable<StreamdownProps["shikiTheme"]>;const { withSmoothContextProvider } = INTERNAL;-// Streamdown 2.5 schedules ordinary streaming blocks in an interruptible React-// transition. A continuous token stream can starve that transition for seconds.-// Its animated path commits every block update directly. StreamdownBlock removes-// the animation transformer while retaining this direct scheduling path.+// Streamdown 2.5 schedules ordinary streaming blocks in an interruptible React transition, and a continuous token+// stream can starve that transition for seconds. Its animated path commits every block update directly.+// StreamdownBlock removes the animation transformer while retaining this direct scheduling path.const STREAMDOWN_IMMEDIATE_UPDATES = {duration: 0,stagger: 0,} satisfies NonNullable<StreamdownProps["animated"]>;/*- * Registering `img` replaces Streamdown's own renderer WHOLESALE (its `Components` map is keyed by- * tag, so the default `img` is only a default), so everything that renderer did for a `data:` image- * is restated here: wrapper, hidden-when-failed, fallback text, hover download. What it could not do- * is the reason this exists -- an on-disk answer image arrives as- * ``, survives sanitize() because it carries no scheme,- * and then reaches the DOM as a plain same-origin <img src>, with no Authorization header, 401s, and- * renders as "Image not available". That case is rewritten into an authed fetch -> object URL first- * (see `use-sandbox-image`); a `data:` URI keeps going straight through, untouched.+ * Registering `img` replaces Streamdown's own renderer WHOLESALE (its `Components` map is keyed by tag, so the+ * default `img` is only a default), so everything that renderer did for a `data:` image is restated here: wrapper,+ * hidden-when-failed, fallback text, hover download. What it could not do is the reason this exists: an on-disk+ * answer image arrives as ``, survives sanitize() because it carries+ * no scheme, and then reaches the DOM as a plain same-origin <img src>, with no Authorization header, 401s, and+ * renders as "Image not available". That case is rewritten into an authed fetch -> object URL first (see+ * `use-sandbox-image`); a `data:` URI keeps going straight through, untouched.*/const MarkdownImage = memo(function MarkdownImage(props: ComponentProps<"img">) {// `node` is Streamdown's ExtraProps; it must not reach the DOM.@@ -154,9 +152,9 @@ const MarkdownImage = memo(function MarkdownImage(props: ComponentProps<"img">)node: _node,...dom} = props as ComponentProps<"img"> & { node?: unknown };- // The fallback scope, for a src that records no session of its own (a bare `plot.png`): the same- // pair the adapter resolves a run's session from (`unstable_threadId ?? activeThreadId`). A src- // that DOES record one keeps it -- the folder its files were written to is where they still are.+ // The fallback scope, for a src that records no session of its own (a bare `plot.png`): the same pair the adapter+ // resolves a run's session from (`unstable_threadId ?? activeThreadId`). A src that DOES record one keeps it: the+ // folder its files were written to is where they still are.const remoteId = useAuiState(({ threadListItem }) => threadListItem.remoteId);const activeThreadId = useChatRuntimeStore((state) => state.activeThreadId);const projectId = useChatProjectScope();@@ -181,11 +179,10 @@ const MarkdownImage = memo(function MarkdownImage(props: ComponentProps<"img">)(file !== null && sandbox.state.status === "failed");// Hidden when it failed and has no intrinsic size to fall back on, as Streamdown's own renderer does.const sized = dom.width != null || dom.height != null;- // Download naming follows the replaced renderer: a real extension on the path wins whole (alt must- // never override a real filename); otherwise any extension in alt is STRIPPED and one inferred from the- // blob's type is appended -- so alt="plot" downloads "plot.png", not "plot". Split before DECODING,- // so a raw `#`/`?` keeps its delimiter meaning, then decode: `loss curve #1.png` must save under its- // real name, not as `loss%20curve%20%231.png`.+ // Download naming follows the replaced renderer: a real extension on the path wins whole (alt must never override+ // a real filename); otherwise any extension in alt is STRIPPED and one inferred from the blob's type is appended,+ // so alt="plot" downloads "plot.png", not "plot". Split before DECODING, so a raw `#`/`?` keeps its delimiter+ // meaning, then decode: `loss curve #1.png` must save under its real name, not as `loss%20curve%20%231.png`.const downloadName = (blobType: string): string => {const tail =decodeSegment((file ?? src ?? "").split(/[?#]/)[0].split("/").pop() ?? "") || "";@@ -465,11 +462,10 @@ function CodeBlockActions({}function useAnimationFreeBlockProps(props: BlockProps): BlockProps {- // `animated` is needed only to bypass Streamdown's starvable React transition.- // Its rehype plugin still wraps every word even with duration and stagger set- // to zero. Remove that one plugin before parsing so long streams do not create- // thousands of animation spans. Keep the filtered array stable so completed- // blocks remain memoised while the final block continues streaming.+ // `animated` is needed only to bypass Streamdown's starvable React transition. Its rehype plugin still wraps every+ // word even with duration and stagger set to zero. Remove that one plugin before parsing so long streams do not+ // create thousands of animation spans. Keep the filtered array stable so completed blocks remain memoised while+ // the final block continues streaming.const rehypePlugins = useMemo(() =>withoutStreamdownAnimationPlugin(@@ -486,17 +482,15 @@ function useAnimationFreeBlockProps(props: BlockProps): BlockProps {}/**- * Whether this message carries a renderable render_html tool part, asked once per message part- * instead of once per markdown block.+ * Whether this message carries a renderable render_html tool part, asked once per message part instead of once per+ * markdown block.*- * The value belongs to the MESSAGE, but the block component is mounted per block, so subscribing- * there minted a subscription per block (800 of 10,193 on the 300K-character heavy thread), each- * re-scanning `message.parts` on every store update -- and every keystroke is a store update.- * One subscription in MarkdownTextImpl plus a context read gives the same blocks the same answer.- *- * `false` is the right default for a block rendered outside a message part (nothing does today):- * no render_html part is visible, which is what the artifact collapse below assumes absent- * evidence.+ * The value belongs to the MESSAGE, but the block component is mounted per block, so subscribing there minted a+ * subscription per block (800 of 10,193 on the 300K-character heavy thread), each re-scanning `message.parts` on+ * every store update, and every keystroke is a store update. One subscription in MarkdownTextImpl plus a context+ * read gives the same blocks the same answer. `false` is the right default for a block rendered outside a message+ * part (nothing does today): no render_html part is visible, which is what the artifact collapse below assumes+ * absent evidence.*/const RenderHtmlToolPresenceContext = createContext(false);@@ -607,21 +601,15 @@ function StreamdownBlockContent(props: BlockProps) {}/*- * THE STREAMING ROUTE, and the one that actually fires.- *- * `getCodeFence` needs the CLOSING fence, so a fence that is still arriving- * has no `codeFence` and falls all the way through to here rather than to- * `FenceBlock`. This bare `Block` is therefore what first asks for the- * highlighter chunk on a streamed reply, which is exactly when it fails.- *- * Left unguarded, the whole-block boundary catches that and latches with no- * reset, so the block never re-enters `FenceBlock` when its closing fence- * finally lands and the copy and download bar never mounts at all. Measured:- * with this unguarded, a streamed abort produced an identical document to the- * commit before the inner boundary existed, 0 copy and 0 download buttons on- * both. Guarding it keeps the failure inside the renderer boundary, so the- * completed block mounts `FenceBlock` normally and keeps its controls.- */+ * THE STREAMING ROUTE, and the one that actually fires. `getCodeFence` needs the CLOSING fence, so a fence that+ * is still arriving has no `codeFence` and falls all the way through to here rather than to `FenceBlock`. This+ * bare `Block` is therefore what first asks for the highlighter chunk on a streamed reply, which is exactly when+ * it fails. Left unguarded, the whole-block boundary catches that and latches with no reset, so the block never+ * re-enters `FenceBlock` when its closing fence finally lands and the copy and download bar never mounts at all.+ * Measured: with this unguarded, a streamed abort produced an identical document to the commit before the inner+ * boundary existed, 0 copy and 0 download buttons on both. Guarding it keeps the failure inside the renderer+ * boundary, so the completed block mounts `FenceBlock` normally and keeps its controls.+ */return (<MarkdownRendererBoundaryfallback={<MarkdownBlockFallbackView content={props.content} />}@@ -632,13 +620,10 @@ function StreamdownBlockContent(props: BlockProps) {}/*- * The fence branch, extracted so the reach latch can be a hook.- *- * With the flag off this renders exactly what the branch rendered before: the- * same `relative isolate` wrapper, the same `<Block>`, the same action bar. The- * wrapper is reused as the intersection target rather than a new one being- * introduced, so the DOM the off arm produces is byte-for-byte what main- * produces and the on arm differs only in what is INSIDE the wrapper.+ * The fence branch, extracted so the reach latch can be a hook. With the flag off this renders exactly what the+ * branch rendered before: the same `relative isolate` wrapper, the same `<Block>`, the same action bar. The+ * wrapper is reused as the intersection target rather than a new one being introduced, so the DOM the off arm+ * produces is byte-for-byte what main produces and the on arm differs only in what is INSIDE the wrapper.*/function FenceBlock({blockProps,@@ -655,41 +640,32 @@ function FenceBlock({const mode = fenceMode();/*- * WHICH FENCES THIS COVERS, and which it does not.- *- * `CODE_FENCE_RE` accepts exactly three backticks, unindented. CommonMark also allows tildes,- * four or more backticks (which is how a model writes a fence whose body contains one), and up- * to three spaces of indent. Those forms never reach here, so they render exactly as they do- * today and get no deferral: unrealised benefit, not a wrong result.- *- * Left alone deliberately rather than overlooked. `getCodeFence` is also what decides whether a- * block is an SVG or a full HTML document to be shown as an artifact, and a fence that does not- * match it renders a bare `<Block>` with no `relative isolate` wrapper and no copy button.- * Widening the regex would therefore add an artifact path and a copy overlay to blocks that do- * not have them today, which is a rendering change, and a performance PR is the wrong place to- * smuggle one in.- *- * It also does not move any number here: over the frozen corpus, 2,467,069 characters, all- * 1,456 fence delimiters are unindented triple backticks. Not one tilde, not one four-backtick- * fence, not one indented one.- */- // `getCodeFence` hands back the WHOLE info string, so a fence opened with metadata such as- // ```python startLine=10 arrives here as "python startLine=10". Markdown treats everything- // after the first word as metadata and Streamdown highlights it as `python`, so passing the- // raw string on would label the shell with the metadata attached and, in the measurement arm,- // tokenize an unknown language as plain text -- which is exactly the grammar work the arm- // exists to put back.+ * WHICH FENCES THIS COVERS, and which it does not. `CODE_FENCE_RE` accepts exactly three backticks, unindented.+ * CommonMark also allows tildes, four or more backticks (which is how a model writes a fence whose body contains+ * one), and up to three spaces of indent. Those forms never reach here, so they render exactly as they do today+ * and get no deferral: unrealised benefit, not a wrong result.+ * Left alone deliberately rather than overlooked. `getCodeFence` is also what decides whether a block is an SVG+ * or a full HTML document to be shown as an artifact, and a fence that does not match it renders a bare+ * `<Block>` with no `relative isolate` wrapper and no copy button. Widening the regex would therefore add an+ * artifact path and a copy overlay to blocks that do not have them today, which is a rendering change, and a+ * performance PR is the wrong place to smuggle one in. It also does not move any number here: over the frozen+ * corpus, 2,467,069 characters, all 1,456 fence delimiters are unindented triple backticks. Not one tilde, not+ * one four-backtick fence, not one indented one.+ */+ // `getCodeFence` hands back the WHOLE info string, so a fence opened with metadata such as ```python startLine=10+ // arrives here as "python startLine=10". Markdown treats everything after the first word as metadata and+ // Streamdown highlights it as `python`, so passing the raw string on would label the shell with the metadata+ // attached and, in the measurement arm, tokenize an unknown language as plain text, which is exactly the grammar+ // work the arm exists to put back.const languageToken = language?.trim().split(/\s+/)[0] || null;/*- * DRIVE THE HIGHLIGHTER OVER THIS FENCE ON DEMAND. The latch owns WHEN; this owns WHAT, because- * the plugin instance lives here with the component that renders the block.- *- * `tokens: true`: `code.highlight` returns synchronously once the grammar is loaded and caches- * on the source string, so this is the same object the block's own render is about to ask for,- * which is what lets a jump or a print swap straight to a COLOURED block rather than to- * streamdown's plain fallback. `tokens: false` highlights "", loading the grammar only.- */+ * DRIVE THE HIGHLIGHTER OVER THIS FENCE ON DEMAND. The latch owns WHEN; this owns WHAT, because the plugin+ * instance lives here with the component that renders the block. `tokens: true`: `code.highlight` returns+ * synchronously once the grammar is loaded and caches on the source string, so this is the same object the+ * block's own render is about to ask for, which is what lets a jump or a print swap straight to a COLOURED block+ * rather than to streamdown's plain fallback. `tokens: false` highlights "", loading the grammar only.+ */const warm = useCallback((tokens: boolean) => {code.highlight({@@ -712,10 +688,9 @@ function FenceBlock({warm,);- // MEASUREMENT ARM ONLY. See `FenceMode`: this puts the tokenizer work back while leaving the- // document at the deferred size, so the two costs can be told apart. `code.highlight` caches- // on the source string, so the work happens exactly once and the discarded result is the same- // object the real path would have used.+ // MEASUREMENT ARM ONLY. See `FenceMode`: this puts the tokenizer work back while leaving the document at the+ // deferred size, so the two costs can be told apart. `code.highlight` caches on the source string, so the work+ // happens exactly once and the discarded result is the same object the real path would have used.const pretokenize = mode === "tokenize" && !reached;useEffect(() => {if (!pretokenize) return;@@ -760,12 +735,10 @@ function FenceBlock({);}/**- * Every block is rendered inside a boundary. Streamdown fetches the code- * highlighter and the Mermaid renderer with `React.lazy` the first time a reply- * needs them, and a rejected import rethrows during render; without this the- * nearest catcher is the ROUTER's, which replaces all of Unsloth and takes the- * reply and its runtime with it. Per block, so one fence losing its colours- * costs only that fence.+ * Every block is rendered inside a boundary. Streamdown fetches the code highlighter and the Mermaid renderer with+ * `React.lazy` the first time a reply needs them, and a rejected import rethrows during render; without this the+ * nearest catcher is the ROUTER's, which replaces all of Unsloth and takes the reply and its runtime with it. Per+ * block, so one fence losing its colours costs only that fence.*/const StreamdownBlock = memo((props: BlockProps) => (<MarkdownBlockBoundary content={props.content}>@@ -820,11 +793,10 @@ function useCoalescedStreamingText(return cancelScheduledRender;}, [cancelScheduledRender]);- // Holding the last painted text is only correct while the reply is being- // appended to. A running message can also be replaced, as the audio path does- // when it swaps its placeholder for the player, and that must show at once.- // The length check rejects most of those before the prefix scan runs; the- // scan itself costs about 59 ms across a 175,000 character stream.+ // Holding the last painted text is only correct while the reply is being appended to. A running message can also+ // be replaced, as the audio path does when it swaps its placeholder for the player, and that must show at once.+ // The length check rejects most of those before the prefix scan runs; the scan itself costs about 59 ms across a+ // 175,000 character stream.if (isStreaming &&displayed.messageId === messageId &&@@ -849,10 +821,9 @@ const MarkdownTextImpl = () => {aui.part.source === "message" && aui.part.query.type === "index"? aui.part.query.index: 0;- // Parts are keyed by index, so switching conversations hands this instance a- // different message, and Streamdown only extends its parsed blocks: key it per- // message. The cache generation joins the key for the case the Markdown string- // cannot express, an edit that drops retained blocks without changing the tail.+ // Parts are keyed by index, so switching conversations hands this instance a different message, and Streamdown+ // only extends its parsed blocks: key it per message. The cache generation joins the key for the case the+ // Markdown string cannot express, an edit that drops retained blocks without changing the tail.const messageId = useAuiState(({ message }) => message.id);// Read once here for every block below: see RenderHtmlToolPresenceContext.const messageHasRenderableRenderHtmlTool = useAuiState(({ message }) =>diff --git a/studio/frontend/src/components/assistant-ui/math-block-containment.ts b/studio/frontend/src/components/assistant-ui/math-block-containment.tsindex a7766494037..73a65f95c8d 100644--- a/studio/frontend/src/components/assistant-ui/math-block-containment.ts+++ b/studio/frontend/src/components/assistant-ui/math-block-containment.ts@@ -3,7 +3,6 @@/** READING THE FLAG, AND PUTTING IT WHERE THE STYLESHEET CAN SEE IT.- ** Split from `math-block-mode.ts` for the same reason `code-fence-defer.tsx` is split from* `code-fence-mode.ts`: this file touches `import.meta.env` and `document`, neither of which the* frontend's `node --experimental-strip-types` test runner can evaluate, and the decision itselfdiff --git a/studio/frontend/src/components/assistant-ui/math-block-marker.ts b/studio/frontend/src/components/assistant-ui/math-block-marker.tsindex 885517fc6ce..bce35839ec1 100644--- a/studio/frontend/src/components/assistant-ui/math-block-marker.ts+++ b/studio/frontend/src/components/assistant-ui/math-block-marker.ts@@ -3,71 +3,57 @@/** MARK THE BLOCK THAT HOLDS INLINE MATHS, so a stylesheet has something it can contain.- ** WHY THIS EXISTS. On WebKitGTK, which is what Studio and Desktop render through on Linux,- * `RenderLayerScrollableArea::scrollTo` reaches- * `RenderLayer::recursiveUpdateLayerPositionsAfterScroll`, which recurses over every descendant- * RenderLayer once per scroll EVENT with no dirty-bit pruning and exactly one early out,- * `!m_hasVisibleDescendant && !m_hasVisibleContent`. `RenderBoxModelObject::requiresLayer()` is- * true for `isPositioned()`, and `isPositioned()` is `position != static`, so `position: relative`- * alone buys a layer. KaTeX sets `position: relative` on `.katex`, `.base` and `.vlist`, and- * `position: absolute` on `.katex-mathml` and `.vlist > span`. A 500K-character maths-bearing- * thread measures 21,713 positioned boxes, about 20,700 of them under KaTeX, and 287.6 ms of- * blocked main thread to move that scroller by ONE PIXEL.- *- * `content-visibility: auto` reaches that same early out for content the user cannot see: a- * skipped subtree is `isSkippedContent()` and `RenderLayer::computeHasVisibleContent()` returns- * false for it, so the walk stops at the skipped root instead of descending.- *- * WHY THE MATHS ROOT ITSELF IS NOT THE PLACE TO PUT IT. `content-visibility` needs SIZE- * CONTAINMENT to take effect, and size containment does not apply to a non-atomic inline-level box- * (css-contain-2 #containment-size; WebKit implements the check in- * `Style::ContainmentChecker::shouldApplySizeContainment`). Shipped `katex.css` gives `.katex` no- * `display`, so inline maths computes to `display: inline` and the declaration is silently inert- * on it. That was measured rather than reasoned about: a rule naming `.katex` had the engine act- * on 0 of 146 sampled inline roots. In the same corpus only about 4,919 of the positioned boxes- * under maths sit under DISPLAY maths against about 15,291 under INLINE maths, so a rule that can- * only reach display maths leaves three quarters of the cost behind, and measured as such: minus- * 27 percent on the mean and plus 13 percent on p50, under the bar either way.- *- * SO THE DECLARATION IS HOISTED TO THE BLOCK THAT CONTAINS THE MATHS. For inline maths that block- * is the paragraph, list item or heading it sits in, and nothing in CSS can select "an element- * that contains maths" except `:has()`, which is itself the measured owner of the 500K scroll cost- * on Chromium. So the renderer marks it, here.- *- * DISPLAY MATHS NEEDS NO MARKER and deliberately gets none. `remark-math` emits it as- * `<pre><code class="language-math math-display">`, `rehype-katex` replaces that whole `pre` with- * `<span class="katex-display">`, and `katex.css` gives that span `display: block`. It is already- * a block-level element with a stable class, so `index.css` names it directly. Marking it here- * would put a class on a node that is about to be thrown away.- *- * WHERE THIS RUNS, AND WHY IT IS NOT A `remarkPlugins` OR `rehypePlugins` PROP. Both were tried- * and both are wrong here:- *- * - Passing `rehypePlugins` to `<Streamdown>` replaces its default list, and Streamdown only- * installs the `allowedTags` sanitizer schema when that list is still the default one- * (`rehypePlugins === defaultRehypePlugins`). A pipeline that does not carry the merge silently- * drops the sanitize pass this renderer depends on -- a security regression to buy a class name;- * the one now passed for data images carries it (`lib/markdown-data-images.ts`).- * - Marking on the mdast side, through `data.hProperties`, lands the class BEFORE- * `rehype-sanitize`, whose `defaultSchema` permits `className` on `a`, `code`, `h2`, `li`,- * `ol`, `section` and `ul` and NOWHERE ELSE. A class on a `<p>` would be stripped, and- * stripped silently, which is exactly the shape of a change that measures as doing nothing.- *- * So the marker is composed onto the MATHS plugin's own rehype pass, which Streamdown appends- * after `raw`, `sanitize` and `harden`. It is the only hook in this pipeline that runs on hast,- * after the sanitizer, without displacing anything.- *- * WHAT IT SEES THERE. The sanitizer strips `math-inline` and `math-display` for the same reason it- * would strip ours: `defaultSchema` allows only `['className', /^language-./]` on `code`. So by- * this point both kinds of maths carry `language-math` and nothing else, and inline is told from- * display exactly the way `rehype-katex` itself tells them apart one plugin later: display maths- * is a `code` whose parent is a `pre`.- *- * THE CLASS IS EMITTED WHETHER OR NOT THE FEATURE IS ON. It is inert without the stylesheet rule,- * and emitting it unconditionally is what lets a measurement compare a window with the feature on- * against a window with it off WITHOUT the two windows holding different DOM. An arm that mutates- * the DOM inside its own measured window is billing itself for someone else's work.+ * `RenderLayerScrollableArea::scrollTo` reaches `RenderLayer::recursiveUpdateLayerPositionsAfterScroll`, which+ * recurses over every descendant RenderLayer once per scroll EVENT with no dirty-bit pruning and exactly one early+ * out, `!m_hasVisibleDescendant && !m_hasVisibleContent`. `RenderBoxModelObject::requiresLayer()` is true for+ * `isPositioned()`, and `isPositioned()` is `position != static`, so `position: relative` alone buys a layer.+ * KaTeX sets `position: relative` on `.katex`, `.base` and `.vlist`, and `position: absolute` on `.katex-mathml`+ * and `.vlist > span`. A 500K-character maths-bearing thread measures 21,713 positioned boxes, about 20,700 of+ * them under KaTeX, and 287.6 ms of blocked main thread to move that scroller by ONE PIXEL. `content-visibility:+ * auto` reaches that same early out for content the user cannot see: a skipped subtree is `isSkippedContent()` and+ * `RenderLayer::computeHasVisibleContent()` returns false for it, so the walk stops at the skipped root instead of+ * descending.+ * WHY THE MATHS ROOT ITSELF IS NOT THE PLACE TO PUT IT. `content-visibility` needs SIZE CONTAINMENT to take+ * effect, and size containment does not apply to a non-atomic inline-level box (css-contain-2 #containment-size;+ * WebKit implements the check in `Style::ContainmentChecker::shouldApplySizeContainment`). Shipped `katex.css`+ * gives `.katex` no `display`, so inline maths computes to `display: inline` and the declaration is silently inert+ * on it. That was measured rather than reasoned about: a rule naming `.katex` had the engine act on 0 of 146+ * sampled inline roots. In the same corpus only about 4,919 of the positioned boxes under maths sit under DISPLAY+ * maths against about 15,291 under INLINE maths, so a rule that can only reach display maths leaves three quarters+ * of the cost behind, and measured as such: minus 27 percent on the mean and plus 13 percent on p50, under the bar+ * either way.+ * SO THE DECLARATION IS HOISTED TO THE BLOCK THAT CONTAINS THE MATHS. For inline maths that block is the+ * paragraph, list item or heading it sits in, and nothing in CSS can select "an element that contains maths"+ * except `:has()`, which is itself the measured owner of the 500K scroll cost on Chromium. So the renderer marks+ * it, here.+ * DISPLAY MATHS NEEDS NO MARKER and deliberately gets none. `remark-math` emits it as `<pre><code+ * class="language-math math-display">`, `rehype-katex` replaces that whole `pre` with `<span+ * class="katex-display">`, and `katex.css` gives that span `display: block`. It is already a block-level element+ * with a stable class, so `index.css` names it directly. Marking it here would put a class on a node that is about+ * to be thrown away.+ * WHERE THIS RUNS, AND WHY IT IS NOT A `remarkPlugins` OR `rehypePlugins` PROP. Both were tried and both are wrong+ * here:+ * - Passing `rehypePlugins` to `<Streamdown>` replaces its default list, and Streamdown only installs the+ * `allowedTags` sanitizer schema when that list is still the default one (`rehypePlugins ===+ * defaultRehypePlugins`). A pipeline that does not carry the merge silently drops the sanitize pass this+ * renderer depends on: a security regression to buy a class name; the one now passed for data images carries+ * it (`lib/markdown-data-images.ts`).+ * - Marking on the mdast side, through `data.hProperties`, lands the class BEFORE `rehype-sanitize`, whose+ * `defaultSchema` permits `className` on `a`, `code`, `h2`, `li`, `ol`, `section` and `ul` and NOWHERE ELSE. A+ * class on a `<p>` would be stripped, and stripped silently, which is exactly the shape of a change that+ * measures as doing nothing.+ * So the marker is composed onto the MATHS plugin's own rehype pass, which Streamdown appends after `raw`,+ * `sanitize` and `harden`. It is the only hook in this pipeline that runs on hast, after the sanitizer, without+ * displacing anything.+ * WHAT IT SEES THERE. The sanitizer strips `math-inline` and `math-display` for the same reason it would strip+ * ours: `defaultSchema` allows only `['className', /^language-./]` on `code`. So by this point both kinds of maths+ * carry `language-math` and nothing else, and inline is told from display exactly the way `rehype-katex` itself+ * tells them apart one plugin later: display maths is a `code` whose parent is a `pre`.+ * THE CLASS IS EMITTED WHETHER OR NOT THE FEATURE IS ON. It is inert without the stylesheet rule, and emitting it+ * unconditionally is what lets a measurement compare a window with the feature on against a window with it off+ * WITHOUT the two windows holding different DOM. An arm that mutates the DOM inside its own measured window is+ * billing itself for someone else's work.*/interface HastProperties {@@ -86,17 +72,14 @@ interface HastNode {export const MATH_BLOCK_CLASS = "aui-math-block";/*- * The class the stylesheet contains DISPLAY maths by, added AFTER KaTeX has run and only to- * displays that carry no equation number. `katex.css` resets `katexEqnNo` on `body` and increments- * it in `.katex .eqn-num::before`, and style containment, which `content-visibility: auto` applies- * unconditionally, scopes that increment to each contained display. Measured on Chromium: three- * numbered displays read (1) (2) (3) with the feature off and (1) (1) (1) with it on. The same- * fixture on WebKitGTK 2.50.4 does NOT reproduce it, 0 differing pixels, so this is engine- * dependent and Chromium is the engine most of the web UI runs in.- *- * A `:has()` rule would express this in CSS alone and is exactly what must not be used: two- * `:has()` rules were the measured owner of the whole 500K scroll cost on Chromium, fixed in #9669.- * So the renderer decides, and the stylesheet names a plain class.+ * The class the stylesheet contains DISPLAY maths by, added AFTER KaTeX has run and only to displays that carry no+ * equation number. `katex.css` resets `katexEqnNo` on `body` and increments it in `.katex .eqn-num::before`, and+ * style containment, which `content-visibility: auto` applies unconditionally, scopes that increment to each+ * contained display. Measured on Chromium: three numbered displays read (1) (2) (3) with the feature off and (1)+ * (1) (1) with it on. The same fixture on WebKitGTK 2.50.4 does NOT reproduce it, 0 differing pixels, so this is+ * engine dependent and Chromium is the engine most of the web UI runs in. A `:has()` rule would express this in+ * CSS alone and is exactly what must not be used: two `:has()` rules were the measured owner of the whole 500K+ * scroll cost on Chromium, fixed in #9669. So the renderer decides, and the stylesheet names a plain class.*/export const MATH_DISPLAY_CLASS = "aui-math-display";@@ -106,11 +89,8 @@ const EQN_NUM_CLASSES = new Set(["eqn-num", "mml-eqn-num"]);/** What survives `rehype-sanitize` on a maths `code` element. See the header. */const MATH_CLASS = "language-math";-/*- * Elements that can take size containment AND that a run of prose carrying inline maths can be- * sitting in. `pre` is absent because a `code.language-math` inside one is DISPLAY maths, which- * this module does not touch.- */+/* Elements that can take size containment AND that a run of prose carrying inline maths can be sitting in. `pre`+ * is absent because a `code.language-math` inside one is DISPLAY maths, which this module does not touch. */const BLOCK_TAGS = new Set(["p","div",@@ -126,30 +106,24 @@ const BLOCK_TAGS = new Set([]);/*- * Size containment does NOT apply to internal table elements (css-contain-2 #containment-size), so- * a `td` or `th` cannot be the target, and neither can anything above it short of the whole table,- * which would be far too coarse a thing to collapse. Maths inside a table cell is therefore- * ABANDONED rather than hoisted past. Recorded as a known limit rather than hidden: the corpus- * this was measured on has no maths in tables.- *- * LIST ITEMS ARE HERE FOR A DIFFERENT AND MEASURED REASON. `content-visibility: auto` applies- * STYLE containment, which scopes the automatic `list-item` counter, and a contained `li` can then- * no longer resolve `counter(list-item)` for its own `::marker`. The observed result is not a- * renumbering, it is that the number DISAPPEARS: photographed on WebKitGTK 2.50.4 with a five item- * ordered list where only items 2 and 4 carried the class, the marker column differed by 61 and 59- * pixels at full channel swing on exactly those two items and by 0 pixels on the other three, so- * the list read 1, nothing, 3, nothing, 5. Siblings still observe the increment; what breaks is the- * contained item's own marker.- *- * An earlier revision marked the `li` DELIBERATELY, because Streamdown gives a list item's- * paragraph `[&>p]:inline` and an inline box cannot take size containment, which leaves the `li` as- * the only containable ancestor. There is no third option there, so maths inside a list item is- * abandoned like maths inside a table cell. `ol` and `ul` are listed too, so the walk cannot hoist- * PAST an item and contain the whole list, which would lose every marker in it instead of one.- *- * The cost of this exemption was censused rather than assumed: of the 595 marked blocks in the 500K- * corpus, 595 are `p` and 0 are `li`, so it gives up nothing that the +92% measurement was- * counting. A thread that does put maths in lists loses the optimisation for those items and keeps+ * Size containment does NOT apply to internal table elements (css-contain-2 #containment-size), so a `td` or `th`+ * cannot be the target, and neither can anything above it short of the whole table, which would be far too coarse+ * a thing to collapse. Maths inside a table cell is therefore ABANDONED rather than hoisted past. Recorded as a+ * known limit rather than hidden: the corpus this was measured on has no maths in tables.+ * LIST ITEMS ARE HERE FOR A DIFFERENT AND MEASURED REASON. `content-visibility: auto` applies STYLE containment,+ * which scopes the automatic `list-item` counter, and a contained `li` can then no longer resolve+ * `counter(list-item)` for its own `::marker`. The observed result is not a renumbering, it is that the number+ * DISAPPEARS: photographed on WebKitGTK 2.50.4 with a five item ordered list where only items 2 and 4 carried the+ * class, the marker column differed by 61 and 59 pixels at full channel swing on exactly those two items and by 0+ * pixels on the other three, so the list read 1, nothing, 3, nothing, 5. Siblings still observe the increment;+ * what breaks is the contained item's own marker.+ * An earlier revision marked the `li` DELIBERATELY, because Streamdown gives a list item's paragraph+ * `[&>p]:inline` and an inline box cannot take size containment, which leaves the `li` as the only containable+ * ancestor. There is no third option there, so maths inside a list item is abandoned like maths inside a table+ * cell. `ol` and `ul` are listed too, so the walk cannot hoist PAST an item and contain the whole list, which+ * would lose every marker in it instead of one. The cost of this exemption was censused rather than assumed: of+ * the 595 marked blocks in the 500K corpus, 595 are `p` and 0 are `li`, so it gives up nothing that the +92%+ * measurement was counting. A thread that does put maths in lists loses the optimisation for those items and keeps* its numbering, which is the right way round.*/const UNCONTAINABLE_TAGS = new Set([@@ -165,11 +139,9 @@ const UNCONTAINABLE_TAGS = new Set(["tr",]);-/*- * The same bound the measurement harness used when it walked the rendered DOM for the equivalent- * arm. Maths buried more than twelve elements deep inside inline wrappers is not a shape this- * renderer produces, and an unbounded walk over a malformed tree is worse than marking nothing.- */+/* The same bound the measurement harness used when it walked the rendered DOM for the equivalent arm. Maths+ * buried more than twelve elements deep inside inline wrappers is not a shape this renderer produces, and an+ * unbounded walk over a malformed tree is worse than marking nothing. */const MAX_HOPS = 12;const classListOf = (node: HastNode): string[] => {@@ -195,11 +167,9 @@ const isInlineMath = (node: HastNode, parent: HastNode | undefined): boolean =>parent?.tagName !== "pre";/**- * Walk up `stack` (outermost first) and mark the nearest element that can take containment.- *- * Returns the element marked, or `null` when there is nothing markable, which happens for maths- * inside a table cell, maths deeper than `MAX_HOPS` inside inline wrappers, and maths with no- * block ancestor at all.+ * Walk up `stack` (outermost first) and mark the nearest element that can take containment. Returns the element+ * marked, or `null` when there is nothing markable, which happens for maths inside a table cell, maths deeper than+ * `MAX_HOPS` inside inline wrappers, and maths with no block ancestor at all.*/export const markNearestBlock = (stack: HastNode[]): HastNode | null => {let hops = 0;@@ -209,14 +179,13 @@ export const markNearestBlock = (stack: HastNode[]): HastNode | null => {if (UNCONTAINABLE_TAGS.has(tagName)) return null;if (!BLOCK_TAGS.has(tagName)) continue;/*- * Streamdown renders a list item with `[&>p]:inline`, so the paragraph a list item wraps its- * text in computes to `display: inline` and cannot take size containment. Neither can the list- * item, for the counter reason recorded on `UNCONTAINABLE_TAGS`, so there is nothing markable- * here and the maths is abandoned rather than hoisted to something that would break numbering.- * `tests/math-block-marker.test.ts` reads the `[&>p]:inline` class out of the installed- * Streamdown build, so the day Streamdown stops doing it this stops being justified loudly- * rather than quietly.- */+ * Streamdown renders a list item with `[&>p]:inline`, so the paragraph a list item wraps its text in computes+ * to `display: inline` and cannot take size containment. Neither can the list item, for the counter reason+ * recorded on `UNCONTAINABLE_TAGS`, so there is nothing markable here and the maths is abandoned rather than+ * hoisted to something that would break numbering. `tests/math-block-marker.test.ts` reads the `[&>p]:inline`+ * class out of the installed Streamdown build, so the day Streamdown stops doing it this stops being justified+ * loudly rather than quietly.+ */if (tagName === "p" && i > 0 && stack[i - 1].tagName === "li") return null;addClass(candidate);return candidate;@@ -224,10 +193,8 @@ export const markNearestBlock = (stack: HastNode[]): HastNode | null => {return null;};-/**- * Mark every block that holds inline maths. Returns how many blocks were marked, which is what- * makes the transform testable without a DOM and without a browser.- */+/** Mark every block that holds inline maths. Returns how many blocks were marked, which is what makes the+ * transform testable without a DOM and without a browser. */export const markMathBlocks = (tree: HastNode): number => {const stack: HastNode[] = [];let marked = 0;@@ -257,13 +224,11 @@ type Attacher = () => Transformer | undefined;/**- * Compose the marker in front of the maths renderer, preserving whatever options the maths plugin- * was configured with.- *- * Takes the `rehypePlugin` off a Streamdown maths plugin, which is either an attacher or an- * `[attacher, options]` tuple, and returns a single attacher that marks the tree and then hands it- * to the original. Returning ONE attacher matters: Streamdown appends this value to its rehype- * list as a single entry, where an array would be read as an `[attacher, options]` tuple.+ * Compose the marker in front of the maths renderer, preserving whatever options the maths plugin was configured+ * with. Takes the `rehypePlugin` off a Streamdown maths plugin, which is either an attacher or an `[attacher,+ * options]` tuple, and returns a single attacher that marks the tree and then hands it to the original. Returning+ * ONE attacher matters: Streamdown appends this value to its rehype list as a single entry, where an array would+ * be read as an `[attacher, options]` tuple.*//** Does this subtree carry a KaTeX equation number? */const hasEquationNumber = (node: HastNode): boolean => {@@ -279,16 +244,15 @@ const hasEquationNumber = (node: HastNode): boolean => {/*** Run AFTER KaTeX. Two jobs, both about the equation counter:*- * 1. Give every `.katex-display` WITHOUT an equation number the class the stylesheet contains by.- * A numbered one is left alone and simply does not take containment.- * 2. Take `MATH_BLOCK_CLASS` back off any block that turned out to contain a numbered display.- * `markMathBlocks` runs before KaTeX, when a display is still- * `<pre><code class="language-math">` and no `.eqn-num` exists to see, so a blockquote or div- * holding both inline maths and a numbered display would otherwise scope the counter from- * above and break the numbering just as effectively.+ * 1. Give every `.katex-display` WITHOUT an equation number the class the stylesheet contains by. A numbered one+ * is left alone and simply does not take containment.+ * 2. Take `MATH_BLOCK_CLASS` back off any block that turned out to contain a numbered display. `markMathBlocks`+ * runs before KaTeX, when a display is still `<pre><code class="language-math">` and no `.eqn-num` exists to+ * see, so a blockquote or div holding both inline maths and a numbered display would otherwise scope the+ * counter from above and break the numbering just as effectively.*- * Returns how many displays were marked and how many blocks were unmarked, which is what makes- * this testable without a browser.+ * Returns how many displays were marked and how many blocks were unmarked, which is what makes this testable+ * without a browser.*/export const guardEquationNumbers = (tree: HastNode): { marked: number; unmarked: number } => {let marked = 0;diff --git a/studio/frontend/src/components/assistant-ui/math-block-mode.ts b/studio/frontend/src/components/assistant-ui/math-block-mode.tsindex 9f930418ac7..1a4df1a5da9 100644--- a/studio/frontend/src/components/assistant-ui/math-block-mode.ts+++ b/studio/frontend/src/components/assistant-ui/math-block-mode.ts@@ -2,96 +2,58 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0/*- * WHETHER MATHS-BEARING BLOCKS TAKE CONTAINMENT, decided in one pure function.- *- * Kept out of any `.tsx` and free of `import.meta`, exactly as `code-fence-mode.ts` is, because- * the frontend's tests run under `node --experimental-strip-types` and can neither load JSX nor- * evaluate `import.meta.env`. Every row below is RUN by `tests/math-block-mode.test.ts` rather- * than checked by regexes over the source.- *- * "off" The marker class is still emitted, the stylesheet rule that reads it is not armed,- * and nothing about rendering changes.- * "contain" SHIP DEFAULT, subject to the engine gate below. `content-visibility: auto` applies+ * Whether maths-bearing blocks take containment, decided in one pure function.+ * Kept out of any `.tsx` and free of `import.meta`, as `code-fence-mode.ts` is: the frontend tests+ * run under `node --experimental-strip-types` and can neither load JSX nor evaluate+ * `import.meta.env`. Every row below is RUN by `tests/math-block-mode.test.ts`.+ * "off" the marker class is still emitted, the stylesheet rule that reads it is not armed.+ * "contain" ship default, subject to the engine gate below: `content-visibility: auto` applies* to maths-bearing blocks, so off-screen maths generates no boxes and no RenderLayers- * until it is scrolled to. See the comment on `SHIP_DEFAULT` for what that buys and- * for the two costs that are accepted rather than solved.- *- * TWO STATES, NOT THREE. `code-fence-mode.ts` distinguishes an unset flag from a mistyped one; this- * file does not, and the reason has CHANGED now that the default is "contain". It used to be that- * unset and unrecognised both resolved to "off" and there was no distinction to draw. They no- * longer land in the same place: unset resolves to the ship default, which is ON, while an- * unrecognised value resolves to "off". That asymmetry is deliberate and is the safe direction. An- * operator who mistypes `VITE_UNSLOTH_MATH_BLOCK_CONTAINMENT=conatin` was reaching for the flag,- * and the only reason to reach for a flag that is already on is to turn it off, so a typo turning- * it off does what they were trying to do. The opposite rule, resolving a typo to the default,- * would ignore them.+ * until it is scrolled to.+ * Two states, not three: unset resolves to the ship default, which is ON, while an UNRECOGNISED+ * value resolves to "off". The asymmetry is deliberate and is the safe direction. An operator who+ * mistypes the flag was reaching for it, and the only reason to reach for a flag already on is to+ * turn it off, so a typo turning it off does what they were trying to do.*/export type MathBlockMode = "off" | "contain";/*- * SHIP DEFAULT, and the evidence for it.- *- * WHAT IT BUYS. At the 500K rung on a real GPU (AMD gfx1151, production bundle, two repetitions per- * rung, each arm scored against its own two neighbouring baselines, runs 32902943628 and- * 32906688232) a one pixel scroll costs 285 ms of blocked main thread and the interface runs at- * 3.2 fps. With this on it costs 18 to 19.5 ms and runs at 35.6 to 38.2 fps: +92% on the mean and- * +88% on the median rAF gap, in all four sessions. At 100K it is +80 to +85% at 62 fps. At 0K the- * selector matches nothing, so the rule cannot cost anything there for a structural reason rather- * than a statistical one.- *- * RENDERING IS UNCHANGED. Two production bundles, feature off against on, photographed at seven- * maths blocks after one full walk of the thread: 10 differing pixels over seven frames, four of- * them bit-identical, `scrollHeight` matching exactly at 307,915.- *- * THE THREE THINGS THAT COULD HAVE STOPPED IT, each measured rather than argued.- *- * 1. FIND-IN-PAGE. Handled by `gateOnEngine` below, not by this constant: an engine that cannot- * find skipped content does not get containment at all. Verified once by driving the real- * `WebKitFindController` over four states on WebKitGTK 2.50.4 (plain 1 match, contained 1,- * `visibility: hidden` 0, absent 0; the two controls are what make the middle row mean- * something). Studio Desktop wires no find-in-page on any platform, so the exposed surface is- * the web UI in a browser older than Safari 26, which is exactly what the gate switches off.- * 2. LIST NUMBERING. Fixed by making `li`, `ol` and `ul` uncontainable; see- * `math-block-marker.ts`. Censused at zero cost: 595 of 595 marked blocks in the 500K corpus- * are paragraphs.- * 3. A REMEMBERED HEIGHT GOING STALE ACROSS A RESIZE. Accepted, at a measured size. Narrowing the- * window from 1440 to 1008 px on the 500K corpus leaves `scrollHeight` 6,350 px short of the- * truth, 2.0%, against 0.0% for the same thread with the feature off. It converges as blocks- * are scrolled past. A synthetic fixture in which EVERY block is contained reads 100%, which- * is an upper bound and not what a real thread does.- *- * WHAT IS ACCEPTED RATHER THAN SOLVED. The 2.0% above, and clipping: paint containment clips an- * inline formula wider than the chat column instead of letting it overflow, confirmed by hit- * testing. Zero blocks overflow in the 500K corpus. `overflow-x: auto` is NOT the remedy, because- * it would make 595 marked blocks into 595 scroll containers, which is the RenderLayer population- * this whole change exists to remove.- *+ * Ship default, and the evidence for it.+ * WHAT IT BUYS. At the 500K rung on a real GPU (AMD gfx1151, production bundle, two repetitions+ * per rung, runs 32902943628 and 32906688232) a one pixel scroll costs 285 ms of blocked main+ * thread and the interface runs at 3.2 fps; with this on it costs 18 to 19.5 ms at 35.6 to 38.2+ * fps, +92% on the mean rAF gap in all four sessions. At 100K it is +80 to +85% at 62 fps. At 0K+ * the selector matches nothing, so the rule cannot cost anything there for a structural reason+ * rather than a statistical one. RENDERING IS UNCHANGED: two production bundles, off against on,+ * differ by 10 pixels over seven frames with `scrollHeight` matching exactly at 307,915.+ * The three things that could have stopped it, each measured rather than argued. FIND-IN-PAGE is+ * handled by `gateOnEngine` below, not by this constant: an engine that cannot find skipped+ * content does not get containment at all, verified by driving the real `WebKitFindController` on+ * WebKitGTK 2.50.4. LIST NUMBERING is fixed by making `li`, `ol` and `ul` uncontainable; see+ * `math-block-marker.ts`. A REMEMBERED HEIGHT GOING STALE ACROSS A RESIZE is accepted at a+ * measured size: narrowing 1440 to 1008 px on the 500K corpus leaves `scrollHeight` 2.0% short,+ * converging as blocks are scrolled past.+ * Also accepted rather than solved: paint containment CLIPS an inline formula wider than the chat+ * column instead of letting it overflow, though zero blocks overflow in the 500K corpus.+ * `overflow-x: auto` is NOT the remedy, because it would make 595 marked blocks into 595 scroll+ * containers, which is the RenderLayer population this whole change exists to remove.* Moving this line is the whole of "turn block containment off again".*/export const SHIP_DEFAULT: MathBlockMode = "contain";/*- * THE FIND-IN-PAGE GATE, and why it is a proxy rather than a direct test.- *+ * The find-in-page gate, and why it is a proxy rather than a direct test.* WebKit below Safari 26 cannot find SKIPPED `content-visibility` content with native find-in-page- * (webkit.org/b/283846). `index.css` already refuses to use `content-visibility: auto` on code- * blocks for exactly this reason and says so in a comment, noting that Studio has no in-thread- * search to fall back on. Containment on maths-bearing blocks reintroduces the same hazard, and it- * reaches further: the marked element is a whole paragraph or heading, so ordinary PROSE in a- * maths-bearing block would stop being findable too, not just the formula.- *- * Nothing on the platform exposes "can find-in-page reach skipped content", so this gates on a CSS- * feature that shipped in the SAME release as the fix and is therefore absent on exactly the builds- * that are affected. Anchor positioning is that feature. This is a PROXY: it asserts a release- * train, not the bug, and if some engine ever ships one without the other this gate is wrong in- * whichever direction that engine chose. That is a deliberate trade against the alternative, which- * is parsing a user-agent string that WebKitGTK freezes at `AppleWebKit/605.1.15` on every version- * it has ever shipped.- *- * Measured on the venue the performance numbers came from, WebKitGTK 2.50.4: `anchor-name` is- * supported, and that build does find skipped content. The point of the gate is the builds that are- * not that one, which Studio absolutely ships against, since Linux uses whatever WebKitGTK the host- * provides and macOS uses whatever the OS provides.+ * (webkit.org/b/283846); `index.css` already refuses `content-visibility: auto` on code blocks for+ * exactly this reason. Here the marked element is a whole paragraph or heading, so ordinary PROSE+ * in a maths-bearing block would stop being findable too, not just the formula.+ * Nothing on the platform exposes "can find-in-page reach skipped content", so this gates on+ * anchor positioning, a CSS feature that shipped in the SAME release as the fix and is therefore+ * absent on exactly the builds that are affected. It asserts a release train, not the bug, and if+ * some engine ever ships one without the other this gate is wrong in whichever direction that+ * engine chose. The alternative is parsing a user-agent string that WebKitGTK freezes at+ * `AppleWebKit/605.1.15` on every version it has ever shipped. Studio ships against whatever+ * WebKitGTK the host provides, which is the case the gate exists for.*/export const FIND_IN_PAGE_PROBE = "anchor-name: --unsloth-probe";@@ -100,8 +62,8 @@ export const FIND_IN_PAGE_PROBE = "anchor-name: --unsloth-probe";** An EXPLICIT RUNTIME override wins, because that global exists so a measurement or a bug report* can force an arm from the devtools console, and a gate that silently refused would make the- * console flip look like it had worked while measuring the other arm. A build flag does NOT win:- * a build is shipped to machines whose engines the builder cannot see.+ * console flip look like it had worked while measuring the other arm. A build flag does NOT win: a+ * build is shipped to machines whose engines the builder cannot see.*/export const gateOnEngine = (mode: MathBlockMode,@@ -141,31 +103,23 @@ export const resolveMathBlockMode = (/*** The attribute the stylesheet reads, on `document.documentElement`, following the- * `html[data-panel-resizing]` precedent already in `index.css`. An attribute rather than a class- * on the thread root because it has to be reachable before any thread has mounted, and because a- * measurement can flip it without provoking a React render, which keeps the DOM identical between- * a measured window with the feature on and one with it off.+ * `html[data-panel-resizing]` precedent already in `index.css`. An attribute rather than a class on+ * the thread root because it has to be reachable before any thread has mounted, and because a+ * measurement can flip it without provoking a React render.*/export const MATH_BLOCK_CONTAINMENT_ATTRIBUTE = "data-math-block-containment";export const MATH_BLOCK_CONTAINMENT_ON = "on";/*- * REAPPLY WHEN THE CONSOLE FLIPS THE GLOBAL.- *+ * Reapply when the console flips the global.* `applyMathBlockContainment()` is called once, before the first render. Without this, a tester who- * set `__UNSLOTH_MATH_BLOCK_CONTAINMENT__` from devtools AFTER load changed nothing: the attribute- * kept its old value and the session went on measuring the arm it was already in, silently. That is- * the worst failure mode an escape hatch can have, because the number it produces looks like an- * answer.- *- * The global is redefined as an accessor so that ASSIGNING it reapplies. The value is held in a- * closure rather than on the scope object, so reading the property still returns what was written- * and nothing else on the page sees a different shape than before.- *- * It lives HERE, in the module with no `import.meta` and no `document`, for the reason this file's- * header gives: the frontend's `node --experimental-strip-types` runner cannot load the other one,- * and an escape hatch whose failure mode is silence is exactly the thing that needs rows run- * against it rather than a comment.+ * set `__UNSLOTH_MATH_BLOCK_CONTAINMENT__` from devtools AFTER load changed nothing: the session+ * went on measuring the arm it was already in, silently, which is the worst failure mode an escape+ * hatch can have, because the number it produces looks like an answer.+ * The global is redefined as an accessor so that ASSIGNING it reapplies, with the value held in a+ * closure so reading the property still returns what was written. It lives here, in the module with+ * no `import.meta` and no `document`, because the `node --experimental-strip-types` runner cannot+ * load the other one.*/export const installOverrideWatcher = (scope: Record<string, unknown>,diff --git a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx b/studio/frontend/src/components/assistant-ui/progressive-messages.tsxindex 177616d82f6..a43449ff2dd 100644--- a/studio/frontend/src/components/assistant-ui/progressive-messages.tsx+++ b/studio/frontend/src/components/assistant-ui/progressive-messages.tsx@@ -1,23 +1,18 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// React glue for the widen-only mount window. The state machine, and why this is not a virtualizer,-// are in progressive-mount-controller.ts.-//-// This replaces `<ThreadPrimitive.Messages>{renderThreadMessage}</ThreadPrimitive.Messages>` with-// an equivalent map over a bounded index range: upstream renders `MessageByIndexProvider ->-// RenderChildrenWithAccessor -> children({ message })`, this renders `MessageByIndexProvider ->-// children`, dropping an accessor wrapper the thread's slot does not use and that emits no DOM.-//-// The replacement is permanent, not a mode the thread leaves once the window closes: swapping trees-// would change the element type at that position, so React would unmount and rebuild every message-// on the convergence commit, which is the cost being avoided.-//-// It takes the SAME propless slot #9042 gave `ThreadPrimitive.Messages`, for the same reason.-// `renderMessage()` returns one shared element object, so a commit that changes the row count hands-// React an identical element for every pre-existing row and React skips those subtrees. A-// `components` object would allocate fresh props per row per commit, so every delete would-// re-render every body, action bar and tooltip: the regression #9042 removed.+// React glue for the widen-only mount window. The state machine, and why this is not a virtualizer, are in+// progressive-mount-controller.ts.+// This replaces `<ThreadPrimitive.Messages>{renderThreadMessage}</ThreadPrimitive.Messages>` with an equivalent+// map over a bounded index range: upstream renders `MessageByIndexProvider -> RenderChildrenWithAccessor ->+// children({ message })`, this renders `MessageByIndexProvider -> children`, dropping an accessor wrapper the+// thread's slot does not use and that emits no DOM. The replacement is permanent, not a mode the thread leaves+// once the window closes: swapping trees would change the element type at that position, so React would unmount+// and rebuild every message on the convergence commit, which is the cost being avoided.+// It takes the SAME propless slot #9042 gave `ThreadPrimitive.Messages`, for the same reason. `renderMessage()`+// returns one shared element object, so a commit that changes the row count hands React an identical element for+// every pre-existing row and React skips those subtrees. A `components` object would allocate fresh props per row+// per commit, so every delete would re-render every body, action bar and tooltip: the regression #9042 removed.import {MessageByIndexProvider,@@ -52,9 +47,9 @@ import {import { useAdjustForContentInsertedAbove } from "@/components/assistant-ui/use-intent-aware-autoscroll";/**- * Every mount window currently withholding rows. Module-level rather than context: the consumers are- * imperative DOM readers (screenshot capture, the #9016 harness census) not necessarily in the React- * tree, and a thread can be mounted twice at once (the Compare panes).+ * Every mount window currently withholding rows. Module-level rather than context: the consumers are imperative+ * DOM readers (screenshot capture, the #9016 harness census) not necessarily in the React tree, and a thread can+ * be mounted twice at once (the Compare panes).*/interface ActiveCompleter {complete: () => Promise<void>;@@ -65,39 +60,33 @@ interface ActiveCompleter {const activeCompleters = new Set<ActiveCompleter>();/**- * Force every in-flight progressive mount to completion, resolving once the commit has painted.- *- * Anything reading the thread out of the DOM rather than the runtime store must await this, or a- * read during the few frames a long thread takes to converge silently sees a short conversation.- * Store readers need nothing: the window gated rendering, never the store.+ * Force every in-flight progressive mount to completion, resolving once the commit has painted. Anything reading+ * the thread out of the DOM rather than the runtime store must await this, or a read during the few frames a long+ * thread takes to converge silently sees a short conversation. Store readers need nothing: the window gated+ * rendering, never the store.*/export const PROGRESSIVE_MOUNT_SEARCH_MS = 400;export async function completeProgressiveMounts(/**- * Force only the threads whose viewport this accepts. Every one of them by default. Find-in-page- * passes one: the shell keeps each workspace mounted and marks the off-route ones `inert`, and- * mounting a retained conversation's withheld rows serves nobody looking at another route.- */+ * Force only the threads whose viewport this accepts. Every one of them by default. Find-in-page passes one:+ * the shell keeps each workspace mounted and marks the off-route ones `inert`, and mounting a retained+ * conversation's withheld rows serves nobody looking at another route.+ */wants?: (viewport: HTMLElement | null) => boolean,): Promise<void> {const wanted = () =>wants === undefined? [...activeCompleters]: [...activeCompleters].filter((entry) => wants(entry.viewportRef.current));- // Two waits, failing in opposite directions.- //- // Draining is easy: ask every completer that exists to finish. Reading the set ONCE is not enough,- // since completers register from a layout effect and a caller in the same task as the thread- // opening finds it empty (measured: returned in 0.1ms, 16 of 220 rows two frames later).- //- // The hard half is that "empty" is ambiguous: a settled thread and a thread still loading history- // (about 160ms on a cold open) look alike, so returning at the first empty reading resolves before- // any row exists. An empty set is therefore only believed after SEARCH_MS of looking; a set that- // was non-empty and has drained is believed immediately.- //- // So a caller on a settled thread pays SEARCH_MS, the deliberate direction to be wrong in: the- // alternative is a screenshot or export of a conversation that is not there yet.+ // Two waits, failing in opposite directions. Draining is easy: ask every completer that exists to finish.+ // Reading the set ONCE is not enough, since completers register from a layout effect and a caller in the same+ // task as the thread opening finds it empty (measured: returned in 0.1ms, 16 of 220 rows two frames later).+ // The hard half is that "empty" is ambiguous: a settled thread and a thread still loading history (about 160ms+ // on a cold open) look alike, so returning at the first empty reading resolves before any row exists. An empty+ // set is therefore only believed after SEARCH_MS of looking; a set that was non-empty and has drained is+ // believed immediately. So a caller on a settled thread pays SEARCH_MS, the deliberate direction to be wrong+ // in: the alternative is a screenshot or export of a conversation that is not there yet.const deadline = Date.now() + PROGRESSIVE_MOUNT_SEARCH_MS;let observed = false;for (;;) {@@ -123,15 +112,12 @@ export function hasPendingProgressiveMounts(): boolean {}/**- * Hand native scroll anchoring back, leaving no trace of having taken it.- *- * `removeProperty` empties the inline declaration but keeps the attribute, so the settled viewport- * carried `style=""` where the shipping one carries no `style` at all. That is inert, but it was the- * ONLY difference a whole-document structural digest could find between this branch and its merge- * base at 100K and 300K (45,014 lines, one changed line, on a null scoring exactly zero), and a- * byte-identical converged document is a claim worth being able to make rather than footnote.- *- * Only an empty declaration is cleared, so any other inline style a caller has set survives.+ * Hand native scroll anchoring back, leaving no trace of having taken it. `removeProperty` empties the inline+ * declaration but keeps the attribute, so the settled viewport carried `style=""` where the shipping one carries+ * no `style` at all. That is inert, but it was the ONLY difference a whole-document structural digest could find+ * between this branch and its merge base at 100K and 300K (45,014 lines, one changed line, on a null scoring+ * exactly zero), and a byte-identical converged document is a claim worth being able to make rather than+ * footnote. Only an empty declaration is cleared, so any other inline style a caller has set survives.*/function restoreScrollAnchoring(viewport: HTMLElement | null): void {if (!viewport) return;@@ -140,12 +126,11 @@ function restoreScrollAnchoring(viewport: HTMLElement | null): void {}/**- * The row to hold still: the first one the reader can actually SEE, not the first in the list.- *- * Widening prepends above everything, so for a widening any row will do. A RELAYOUT will not: a row- * growing between the topmost row and the fold moves the reader while leaving the topmost row where- * it was. Measured with a 600px height change injected into one row above a detached reader with the- * window open: 600px of movement, reported as 0 by a topmost-row anchor.+ * The row to hold still: the first one the reader can actually SEE, not the first in the list. Widening prepends+ * above everything, so for a widening any row will do. A RELAYOUT will not: a row growing between the topmost row+ * and the fold moves the reader while leaving the topmost row where it was. Measured with a 600px height change+ * injected into one row above a detached reader with the window open: 600px of movement, reported as 0 by a+ * topmost-row anchor.*/function pickAnchorRow(viewport: HTMLElement): Element | null {const fold = viewport.getBoundingClientRect().top;@@ -158,17 +143,15 @@ function pickAnchorRow(viewport: HTMLElement): Element | null {}}if (!anchor) return null;- // Then descend to the fold. A row can be taller than the viewport (a long answer with images and- // code usually is), so a reader partway through one has the row's top ABOVE them: a block earlier- // in that message growing moves everything they see while the row's top stays put, and a whole-row- // anchor reports zero. The first descendant reaching the fold does not. Bounded because that block- // is a few levels down, and this runs once per re-pick, not per frame.- //- // Known residual: if the fold lands inside a tall LEAF block (a paragraph with no element- // children) the descent stops with its top above the reader, so lines reflowing inside it move- // what they see without moving the block. Closing that needs a caret point at the fold, spelled- // differently on all three engines, costing a Range and a rect every frame, and not itself stable- // across the reflow it would measure.+ // Then descend to the fold. A row can be taller than the viewport (a long answer with images and code usually+ // is), so a reader partway through one has the row's top ABOVE them: a block earlier in that message growing+ // moves everything they see while the row's top stays put, and a whole-row anchor reports zero. The first+ // descendant reaching the fold does not. Bounded because that block is a few levels down, and this runs once+ // per re-pick, not per frame.+ // Known residual: if the fold lands inside a tall LEAF block (a paragraph with no element children) the descent+ // stops with its top above the reader, so lines reflowing inside it move what they see without moving the+ // block. Closing that needs a caret point at the fold, spelled differently on all three engines, costing a+ // Range and a rect every frame, and not itself stable across the reflow it would measure.for (let depth = 0; depth < 8; depth += 1) {if (anchor.getBoundingClientRect().top >= fold) break;let next: Element | null = null;@@ -195,15 +178,13 @@ function sampleAnchor(viewport: HTMLElement, element: Element): AnchorSample {}/**- * An anchor plus the row it sits in, sampled together. The row is the fallback: pickAnchorRow- * descends to the fold, so the anchor is often the `<pre>` Streamdown replaces when Shiki finishes,- * and a replaced node takes its baseline with it. A `[data-role]` row is never replaced in place.- *- * Being an ANCESTOR, the row does not move when the replacement changes height inside it, so that- * height change goes uncorrected. That is the better of the two available errors: an anchor BELOW- * the replaced block would also see it grow DOWNWARD past the fold, which moves nothing the reader- * sees, trading an error in a rare case for one in the common case. Either way the residual is one- * code block's height change, for a detached reader, while a window is open.+ * An anchor plus the row it sits in, sampled together. The row is the fallback: pickAnchorRow descends to the+ * fold, so the anchor is often the `<pre>` Streamdown replaces when Shiki finishes, and a replaced node takes its+ * baseline with it. A `[data-role]` row is never replaced in place. Being an ANCESTOR, the row does not move when+ * the replacement changes height inside it, so that height change goes uncorrected. That is the better of the two+ * available errors: an anchor BELOW the replaced block would also see it grow DOWNWARD past the fold, which moves+ * nothing the reader sees, trading an error in a rare case for one in the common case. Either way the residual is+ * one code block's height change, for a detached reader, while a window is open.*/function holdAnchor(viewport: HTMLElement, element: Element): HeldAnchor {const row = element.closest("[data-role]");@@ -244,12 +225,11 @@ function useProgressiveMountWindow([aui],);- // Which indices actually paint, read IMPERATIVELY off the store for the same reason isRunning is:- // a `useAuiState` selector touching the messages array runs on every store write, and the- // composer is controlled off store state, so that would walk the thread once per keystroke and- // once per streamed token. This is called only where a window is armed -- mount, thread switch,- // and the commit that first brings messages in -- so it costs one snapshot each time, not one- // per render. See thread-research-presence.ts for the same hazard.+ // Which indices actually paint, read IMPERATIVELY off the store for the same reason isRunning is: a+ // `useAuiState` selector touching the messages array runs on every store write, and the composer is controlled+ // off store state, so that would walk the thread once per keystroke and once per streamed token. This is called+ // only where a window is armed (mount, thread switch, and the commit that first brings messages in), so it+ // costs one snapshot each time, not one per render. See thread-research-presence.ts for the same hazard.const renderableAt = useCallback(() => {const messages = aui.thread().getState().messages as ReadonlyArray<{role?: ThreadMessageRole;@@ -268,33 +248,28 @@ function useProgressiveMountWindow(initialWindow(count, isRunningNow(), renderableAt()),);- // Re-arm per thread, adjusting state during render as React documents, so the previous thread's- // window can never gate the new one for a frame.- //- // UNEXERCISED today: `<GeneratedImageOverlayProvider key={runtimeThreadId}>` in thread.tsx wraps- // this subtree, so a thread switch rebuilds this component and the useState initialiser above- // re-arms instead (measured across in-app switches: zero arm records from this branch). Kept- // because it is what makes this component correct on its own terms; remove that ancestor key and- // it is the only thing between a thread switch and the previous window gating the next thread.+ // Re-arm per thread, adjusting state during render as React documents, so the previous thread's window can+ // never gate the new one for a frame. UNEXERCISED today: `<GeneratedImageOverlayProvider key={runtimeThreadId}>`+ // in thread.tsx wraps this subtree, so a thread switch rebuilds this component and the useState initialiser+ // above re-arms instead (measured across in-app switches: zero arm records from this branch). Kept because it is+ // what makes this component correct on its own terms; remove that ancestor key and it is the only thing between+ // a thread switch and the previous window gating the next thread.const [previousKey, setPreviousKey] = useState(resetKey);if (previousKey !== resetKey) {setPreviousKey(resetKey);setMountWindow(initialWindow(count, isRunningNow(), renderableAt()));}- // The commit that puts the FIRST rows into an empty tree.- //- // Mounting is not when the app learns the thread length. `threadListItem.id` flips as soon as- // switchToThread resolves and that remounts this subtree, but the messages arrive only when the- // history adapter settles, a Dexie read plus two HTTP calls later. So on a cold open the useState- // above runs at `count === 0` and declines, and without this the whole thread lands in one- // unbounded commit: the stall this file exists to remove. Measured opening a 220-message thread:- // mount at count 0, count 220 about 160ms later, same resetKey, first paint carrying all 220.- //- // Gated on the PREVIOUS count being zero rather than on crossing MIN_PROGRESSIVE_MESSAGES: a tree- // that never rendered a row has no scroll position to lose, so arming here cannot move a reader.- // Appending a 40th message to a 39-message thread crosses the threshold too, and would window a- // conversation the reader is in the middle of.+ // The commit that puts the FIRST rows into an empty tree. Mounting is not when the app learns the+ // thread length: `threadListItem.id` flips as soon as switchToThread resolves and that remounts+ // this subtree, but the messages arrive only when the history adapter settles, a Dexie read plus+ // two HTTP calls later. So on a cold open the useState above runs at `count === 0` and declines,+ // and without this the whole thread lands in one unbounded commit: the stall this file exists to+ // remove. Measured opening a 220-message thread: mount at count 0, count 220 about 160ms later,+ // same resetKey, first paint carrying all 220. Gated on the PREVIOUS count being zero rather than+ // on crossing MIN_PROGRESSIVE_MESSAGES: a tree that never rendered a row has no scroll position+ // to lose, so arming here cannot move a reader. Appending a 40th message to a 39-message thread+ // crosses the threshold too, and would window a conversation the reader is in the middle of.const [previousCount, setPreviousCount] = useState(count);if (previousCount !== count) {setPreviousCount(count);@@ -304,11 +279,10 @@ function useProgressiveMountWindow(}}- // A thread that shrank at or past the live window's start is reconciled HERE, during render, not- // at the next widening. Rendering every row (below) is only half: the STATE still says start 204,- // and a widen against a 100-message thread would produce start 68 and unmount the 68 rows this- // render just mounted. Before this existed the stale state painted an empty column for 2 to 8- // frames.+ // A thread that shrank at or past the live window's start is reconciled HERE, during render, not at the next+ // widening. Rendering every row (below) is only half: the STATE still says start 204, and a widen against a+ // 100-message thread would produce start 68 and unmount the 68 rows this render just mounted. Before this+ // existed the stale state painted an empty column for 2 to 8 frames.if (mountWindow != null && mountWindow.start >= count) {setMountWindow(null);}@@ -321,10 +295,10 @@ function useProgressiveMountWindow(if (threadIsRunning && mountWindow != null) setMountWindow(null);}, [threadIsRunning, mountWindow]);- // The row held still across a widening commit, plus the scroll state it was held against, both- // captured against the SCROLL CONTAINER rather than the window (see AnchorSample).- // anchorCorrection turns the pair into a scrollTop delta in document space, assuming nothing else- // moved scrollTop, which is what disarming native anchoring below is for.+ // The row held still across a widening commit, plus the scroll state it was held against, both captured against+ // the SCROLL CONTAINER rather than the window (see AnchorSample). anchorCorrection turns the pair into a+ // scrollTop delta in document space, assuming nothing else moved scrollTop, which is what disarming native+ // anchoring below is for.const anchorRef = useRef<| ({element: Element;@@ -338,17 +312,14 @@ function useProgressiveMountWindow(const captureAnchor = useCallback(() => {const viewport = viewportRef.current;- // Disarm native scroll anchoring HERE, immediately before the capture it would invalidate. The- // correction is document space and only holds while nothing else moves scrollTop, so the- // browser must be out of the loop before the first sample, not merely soon.- //- // A layout effect is too early: this component is a DESCENDANT of the viewport, so on the- // mounting commit React runs this subtree's layout effects before the viewport's ref callback,- // `viewportRef.current` is null and the style is silently skipped. Measured on that version,- // computed `overflow-anchor` stayed `auto` until the FIRST widening at +803ms, so that widening- // applied the document-space correction on top of the browser's: a reader who scrolled 4000px- // was left 776px short. This callback runs from a requestAnimationFrame, after a paint, so the- // ref is populated.+ // Disarm native scroll anchoring HERE, immediately before the capture it would invalidate. The correction is+ // document space and only holds while nothing else moves scrollTop, so the browser must be out of the loop+ // before the first sample, not merely soon. A layout effect is too early: this component is a DESCENDANT of the+ // viewport, so on the mounting commit React runs this subtree's layout effects before the viewport's ref+ // callback, `viewportRef.current` is null and the style is silently skipped. Measured on that version, computed+ // `overflow-anchor` stayed `auto` until the FIRST widening at +803ms, so that widening applied the+ // document-space correction on top of the browser's: a reader who scrolled 4000px was left 776px short. This+ // callback runs from a requestAnimationFrame, after a paint, so the ref is populated.if (viewport) viewport.style.setProperty("overflow-anchor", "none");const anchor = viewport ? pickAnchorRow(viewport) : null;// The enclosing row is a fallback: the anchor is often the `<pre>` Streamdown replaces when@@ -408,28 +379,22 @@ function useProgressiveMountWindow(idleRef.current = holdAnchor(viewport, element);}, [mountWindow, adjustForContentInsertedAbove, viewportRef]);- // Content above the reader also moves for reasons that are not a widening, and nothing else- // watches for it while the window is open: Streamdown replaces a `<pre>` when Shiki finishes,- // KaTeX resizes a formula, an image lands. Native anchoring absorbs those and is disabled for the- // duration, so compensation has to cover the whole interval, not just widening commits. The- // autoscroll hook's mutation path pins a FOLLOWING reader and leaves a detached one alone.- //- // Measured when written, injecting a 600px height change into one row above a detached reader with- // the window open: without this the reader moved the full 600px, against 0px on the merge base.- //- // RE-MEASURED SINCE, AND IT NO LONGER REPRODUCES ITS OWN MEASUREMENT: ablating this whole effect- // leaves grow 600, grow 3600 and shrink 1200 identical to head within noise. The cause is- // declaration ORDER, not the logic: the widening capture effect above registers its rAF first, so- // `anchorRef.current` is non-null on every frame the window is open and this body returns at its- // first line. Instrumented, 0 of 1110 frames across chromium, firefox and webkit got past it, and- // the widening layout effect absorbs the reflow instead. Confirmed causally by swapping only the- // two effect declarations, after which this body runs about 5 times per repetition. Anyone+ // Content above the reader also moves for reasons that are not a widening, and nothing else watches for it+ // while the window is open: Streamdown replaces a `<pre>` when Shiki finishes, KaTeX resizes a formula, an image+ // lands. Native anchoring absorbs those and is disabled for the duration, so compensation has to cover the whole+ // interval, not just widening commits. The autoscroll hook's mutation path pins a FOLLOWING reader and leaves a+ // detached one alone. Measured when written, injecting a 600px height change into one row above a detached+ // reader with the window open: without this the reader moved the full 600px, against 0px on the merge base.+ // RE-MEASURED SINCE, AND IT NO LONGER REPRODUCES ITS OWN MEASUREMENT: ablating this whole effect leaves grow+ // 600, grow 3600 and shrink 1200 identical to head within noise. The cause is declaration ORDER, not the logic:+ // the widening capture effect above registers its rAF first, so `anchorRef.current` is non-null on every frame+ // the window is open and this body returns at its first line. Instrumented, 0 of 1110 frames across chromium,+ // firefox and webkit got past it, and the widening layout effect absorbs the reflow instead. Confirmed causally+ // by swapping only the two effect declarations, after which this body runs about 5 times per repetition. Anyone// reordering these two effects is switching this on.- //- // Kept because the widening path it defers to has no visibility test, so this is the only thing- // that would catch a reflow on a frame with no widening pending. The anchor is the first row the- // reader can SEE, re-picked only when gone or scrolled out of view, so per frame this costs one- // rect and one scrollTop read.+ // Kept because the widening path it defers to has no visibility test, so this is the only thing that would+ // catch a reflow on a frame with no widening pending. The anchor is the first row the reader can SEE, re-picked+ // only when gone or scrolled out of view, so per frame this costs one rect and one scrollTop read.useEffect(() => {if (mountWindow == null) {idleRef.current = null;@@ -485,14 +450,12 @@ function useProgressiveMountWindow(return () => cancelAnimationFrame(frame);}, [mountWindow, adjustForContentInsertedAbove, viewportRef]);- // Native scroll anchoring goes back on the moment the window closes, and on unmount, so a settled- // thread is exactly the thread that shipped before this change. Turning it OFF happens at capture- // time instead, for the ordering reason in captureAnchor.- //- // Why it must be off: left on, the browser moves scrollTop by the inserted height on some frames- // and not others (never on any shipping Safari, and suppressed per frame elsewhere after a- // programmatic scroll), and no in-frame measurement can tell which kind of frame it is in. Off,- // scrollTop moves only when the reader or this code moves it, which anchorCorrection assumes.+ // Native scroll anchoring goes back on the moment the window closes, and on unmount, so a settled thread is+ // exactly the thread that shipped before this change. Turning it OFF happens at capture time instead, for the+ // ordering reason in captureAnchor. Why it must be off: left on, the browser moves scrollTop by the inserted+ // height on some frames and not others (never on any shipping Safari, and suppressed per frame elsewhere after a+ // programmatic scroll), and no in-frame measurement can tell which kind of frame it is in. Off, scrollTop moves+ // only when the reader or this code moves it, which anchorCorrection assumes.useLayoutEffect(() => {if (mountWindow != null) return;restoreScrollAnchoring(viewportRef.current);@@ -553,9 +516,9 @@ function useProgressiveMountWindow(}/**- * The thread's message list. Drop-in for `ThreadPrimitive.Messages`, with a long thread's first- * commit bounded to the tail and the rest arriving over the following frames. Memoized on component- * identity exactly as upstream is, so a `Thread` re-render does not rebuild the row array.+ * The thread's message list. Drop-in for `ThreadPrimitive.Messages`, with a long thread's first commit bounded to+ * the tail and the rest arriving over the following frames. Memoized on component identity exactly as upstream+ * is, so a `Thread` re-render does not rebuild the row array.*/export const ProgressiveMessages: FC<{/** The thread's propless message slot. See thread-message-slot.ts. */@@ -571,12 +534,11 @@ export const ProgressiveMessages: FC<{return useMemo(() => {if (count === 0) return null;- // `start >= count` means the thread shrank under a live window (a bulk delete, or a switch to- // a shorter thread), and clamping `start` to `count` would make this loop emit NOTHING.- // Measured before this line: dropping a 220-message thread to 10 with the window at start=204- // painted an empty column for 2 to 8 frames (37 to 146ms) on all three engines. `widen` heals- // it a frame later but runs inside startTransition, so the blank persists. Drop the- // restriction in the same commit: it can withhold nothing now.+ // `start >= count` means the thread shrank under a live window (a bulk delete, or a switch to a shorter+ // thread), and clamping `start` to `count` would make this loop emit NOTHING. Measured before this line:+ // dropping a 220-message thread to 10 with the window at start=204 painted an empty column for 2 to 8 frames+ // (37 to 146ms) on all three engines. `widen` heals it a frame later but runs inside startTransition, so the+ // blank persists. Drop the restriction in the same commit: it can withhold nothing now.const first =mountWindow == null || mountWindow.start >= count? 0diff --git a/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts b/studio/frontend/src/components/assistant-ui/progressive-mount-controller.tsindex 5e09525ff56..dc3b54820a7 100644--- a/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts+++ b/studio/frontend/src/components/assistant-ui/progressive-mount-controller.ts@@ -1,68 +1,55 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Widen-only mount window for the chat thread.-//-// Re-opening a 300K thread costs 3175ms on Chromium (#9016), nearly all of it mounting messages-// from nothing. Mounting only the last 20 of 220 re-opens in 438ms and is FLAT in thread length-// (441ms at 25K, 470ms at 100K, 438ms at 300K, medians of 8 paired rounds): cost follows mounted-// nodes, not thread length.-//-// Not a virtualizer: unmounting what scrolls away breaks find-in-page, cross-message selection,-// copy-all, screen readers, print and export. Open WebUI shipped that in 02690339 and reverted it-// ten days later in d56d74b3 as "catastrophic mount/destroy thrashing" (open-webui#23990).-//-// So the window only ever GROWS: first commit mounts the tail, each frame adds a chunk, and once it-// covers the thread the restriction is dropped for good. Nothing is ever unmounted, so the document-// converges to exactly the pre-change tree a few frames later; consumers that cannot wait have-// `completeProgressiveMounts` (see use-progressive-mount).-//-// The thread is always bottom-anchored, so the window is a single `start` index. That is the one-// simplification over LibreChat#14901, which also has to support a top anchor.+// Widen-only mount window for the chat thread. Re-opening a 300K thread costs 3175ms on Chromium+// (#9016), nearly all of it mounting messages from nothing. Mounting only the last 20 of 220+// re-opens in 438ms and is FLAT in thread length (441ms at 25K, 470ms at 100K, 438ms at 300K,+// medians of 8 paired rounds): cost follows mounted nodes, not thread length. Not a virtualizer:+// unmounting what scrolls away breaks find-in-page, cross-message selection, copy-all, screen+// readers, print and export. Open WebUI shipped that in 02690339 and reverted it ten days later in+// d56d74b3 as "catastrophic mount/destroy thrashing" (open-webui#23990). So the window only ever+// GROWS: first commit mounts the tail, each frame adds a chunk, and once it covers the thread the+// restriction is dropped for good. Nothing is ever unmounted, so the document converges to exactly+// the pre-change tree a few frames later; consumers that cannot wait have+// `completeProgressiveMounts` (see use-progressive-mount). The thread is always bottom-anchored, so+// the window is a single `start` index. That is the one simplification over LibreChat#14901, which+// also has to support a top anchor.-/**- * Indices `[start, count)` may mount. `null` means no restriction: where a settled thread rests,- * and the only state a short thread is ever in.- */+/** Indices `[start, count)` may mount. `null` means no restriction: where a settled thread rests, and the only+ * state a short thread is ever in. */export type MountWindow = { start: number } | null;-/**- * Below this many messages the whole thread mounts in one commit, as before. Chunking a thread that- * was never slow only adds frames: at 20 messages, 446ms against a 438ms floor.- */+/** Below this many messages the whole thread mounts in one commit, as before. Chunking a thread that was never+ * slow only adds frames: at 20 messages, 446ms against a 438ms floor. */export const MIN_PROGRESSIVE_MESSAGES = 40;/*** Messages in the first commit.*- * A window that undershoots what the user can see paints a gap, so what matters is how tall 16 of- * the SHORTEST rows this app can produce are. One-word rows alternate 126px (user) and 80px- * (assistant) because the roles carry different padding; sixteen of them measure 1643px, and with- * the viewport's 48px top inset and 165px bottom spacer that fills every clientHeight up to 1890px.- * Quote the pair, not their 103px mean: the mean only reproduces the total for an EVEN row count,- * drifting up to 23px otherwise, which is why INITIAL_MESSAGES is even.+ * A window that undershoots what the user can see paints a gap, so what matters is how tall 16 of the SHORTEST+ * rows this app can produce are. One-word rows alternate 126px (user) and 80px (assistant) because the roles+ * carry different padding; sixteen of them measure 1643px, and with the viewport's 48px top inset and 165px+ * bottom spacer that fills every clientHeight up to 1890px. Quote the pair, not their 103px mean: the mean only+ * reproduces the total for an EVEN row count, drifting up to 23px otherwise, which is why INITIAL_MESSAGES is+ * even.*- * Measured, not derived, on a 144-message thread whose last 24 messages are one-word replies, three- * rounds a point, Chromium 151 / Firefox / WebKit: at 900, 1080, 1440, 1800, 1840 and 1860px of- * clientHeight the empty band below the last row on the first painted commit is exactly the band a- * settled thread has, so 0px of it is this window's. First row on screen at 133 to 315ms by engine.+ * Measured, not derived, on a 144-message thread whose last 24 messages are one-word replies, three rounds a+ * point, Chromium 151 / Firefox / WebKit: at 900, 1080, 1440, 1800, 1840 and 1860px of clientHeight the empty+ * band below the last row on the first painted commit is exactly the band a settled thread has, so 0px of it is+ * this window's. First row on screen at 133 to 315ms by engine.*- * Above 1890px it undershoots, left unfixed: 10px of band at 1900px, 110px at 2000px, 270px at- * 2160px, closed by the first chunk and nothing unreachable meanwhile. Deriving the window from- * clientHeight would have to guess how many rows fill it before mounting any, and the merge base it- * is compared against paints NOTHING for 1318ms at 2160px and then the whole thread at once. 270px- * of white for a third of a second, at a height needing a 4K panel in portrait, beats 1.3s of empty- * screen at every height. 16 is also what LibreChat#14901 ships for the same job.- *- * Probe: tests/studio/probe_compact_tail_gap.py.+ * Above 1890px it undershoots, left unfixed: 10px of band at 1900px, 110px at 2000px, 270px at 2160px, closed by+ * the first chunk and nothing unreachable meanwhile. Deriving the window from clientHeight would have to guess+ * how many rows fill it before mounting any, and the merge base it is compared against paints NOTHING for 1318ms+ * at 2160px and then the whole thread at once. 270px of white for a third of a second, at a height needing a 4K+ * panel in portrait, beats 1.3s of empty screen at every height. 16 is also what LibreChat#14901 ships for the+ * same job. Probe: tests/studio/probe_compact_tail_gap.py.*/export const INITIAL_MESSAGES = 16;/**- * Messages added per widening frame until the window covers the thread.- *- * Measured, not inherited. One build at three chunk sizes through #9016's 300K fixture, three- * rounds of three repetitions each:+ * Messages added per widening frame until the window covers the thread. Measured, not inherited: one build at+ * three chunk sizes through #9016's 300K fixture, three rounds of three repetitions each:** | chunk | first row | converged | worst frame | frames over 33ms |* |---|---|---|---|---|@@ -70,49 +57,42 @@ export const INITIAL_MESSAGES = 16;* | 32 | 236ms | 3186ms | 437ms | 9 |* | 64 | 222ms | 3170ms | 703ms | 6 |*- * Chunk size cannot affect the first commit (always INITIAL_MESSAGES wide) nor the total work; it- * only trades build-in height against length. 32 is the midpoint and what LibreChat#14901 uses.- * Changing it chooses a shape, not a speedup.+ * Chunk size cannot affect the first commit (always INITIAL_MESSAGES wide) nor the total work; it only trades+ * build-in height against length. 32 is the midpoint and what LibreChat#14901 uses. Changing it chooses a shape,+ * not a speedup.*/export const CHUNK_MESSAGES = 32;/**- * The most messages the first commit may span, however few of them render.+ * The most messages the first commit may span, however few of them render. Sizing the tail on renderable rows+ * means walking back across every non-rendering message in between, and that walk is unbounded on its own:+ * sixteen visible messages followed by two hundred system entries walks to zero and the first commit rebuilds+ * every provider in the thread, which is the bound this file exists to create.*- * Sizing the tail on renderable rows means walking back across every non-rendering message in- * between, and that walk is unbounded on its own: sixteen visible messages followed by two hundred- * system entries walks to zero and the first commit rebuilds every provider in the thread, which is- * the bound this file exists to create.- *- * Four tails. A thread has to be three quarters non-rendering across its whole tail before this- * binds at all, which no thread the importers produce comes close to; below that it costs nothing- * and the window is exactly the renderable-row one. When it does bind the first commit shows fewer- * than INITIAL_MESSAGES rows, possibly none, and widening reaches the rest within a few frames --- * bounded work either way, against the 1318ms of empty screen the merge base pays for the same- * thread.+ * Four tails. A thread has to be three quarters non-rendering across its whole tail before this binds at all,+ * which no thread the importers produce comes close to; below that it costs nothing and the window is exactly the+ * renderable-row one. When it does bind the first commit shows fewer than INITIAL_MESSAGES rows, possibly none,+ * and widening reaches the rest within a few frames: bounded work either way, against the 1318ms of empty screen+ * the merge base pays for the same thread.*/export const MAX_INITIAL_SPAN = INITIAL_MESSAGES * 4;-/**- * The window a thread opens with. A running thread opens unrestricted: widening and streaming write- * the same scroll position, and a run starting under a short window would commit its reply into a- * tree that has not reached it. A mid-run thread was mounted a moment ago anyway.- */+/** The window a thread opens with. A running thread opens unrestricted: widening and streaming write the same+ * scroll position, and a run starting under a short window would commit its reply into a tree that has not+ * reached it. A mid-run thread was mounted a moment ago anyway. */export function initialWindow(count: number,isRunning: boolean,isRenderable?: (index: number) => boolean,): MountWindow {if (isRunning || count < MIN_PROGRESSIVE_MESSAGES) return null;- // Sized on rows that RENDER, not on messages. A message whose role the thread supplies no- // component for paints nothing at all -- `threadMessageKind` returns "none" and `ThreadMessage`- // returns null -- so it has no height. Counting those into the tail opens an imported- // conversation ending in system messages on sixteen zero-height rows and no conversation, until- // a later widening frame rescues it: the exact stall this window exists to remove. Both- // importers preserve "system" (chat-import.ts, openwebui-import.ts).- //- // Optional so the arithmetic stays testable on its own and `stepsToCover` keeps a pure form; a- // caller that cannot say what renders gets the old count-based window.+ // Sized on rows that RENDER, not on messages. A message whose role the thread supplies no component for paints+ // nothing at all (`threadMessageKind` returns "none" and `ThreadMessage` returns null), so it has no height.+ // Counting those into the tail opens an imported conversation ending in system messages on sixteen zero-height+ // rows and no conversation, until a later widening frame rescues it: the exact stall this window exists to+ // remove. Both importers preserve "system" (chat-import.ts, openwebui-import.ts). Optional so the arithmetic+ // stays testable on its own and `stepsToCover` keeps a pure form; a caller that cannot say what renders gets the+ // old count-based window.if (!isRenderable) return { start: Math.max(0, count - INITIAL_MESSAGES) };// Walk back from the end until the window holds a full tail of renderable rows, but never past// MAX_INITIAL_SPAN messages: the walk crosses non-rendering messages too, and without the cap a@@ -125,10 +105,9 @@ export function initialWindow(renderable += 1;if (renderable >= INITIAL_MESSAGES) return { start: index };}- // The cap bound before a full tail was found. Take the cap: the first commit shows whatever- // renders inside it, which may be nothing, and widening reaches the rest within a few frames.- // Bounded and converging beats both alternatives -- mounting the whole thread, and withholding- // on a thread this short.+ // The cap bound before a full tail was found. Take the cap: the first commit shows whatever renders inside it,+ // which may be nothing, and widening reaches the rest within a few frames. Bounded and converging beats both+ // alternatives, mounting the whole thread and withholding on a thread this short.if (floor > 0) return { start: floor };// The whole thread fits inside the cap and still holds fewer renderable rows than one tail:// there is nothing to withhold, and withholding anyway would hide part of the little there is.@@ -140,13 +119,10 @@ export function isCovered(current: MountWindow): boolean {return current == null || current.start <= 0;}-/**- * The next window. Returns `null` once it would cover the thread, so the restriction drops in the- * same commit that mounts the last chunk rather than a frame later.- *- * `count` is re-read every step because messages arrive between frames. `start` only ever moves- * down, so a thread growing under a live window cannot un-mount anything.- */+/** The next window. Returns `null` once it would cover the thread, so the restriction drops in the same commit+ * that mounts the last chunk rather than a frame later. `count` is re-read every step because messages arrive+ * between frames. `start` only ever moves down, so a thread growing under a live window cannot un-mount+ * anything. */export function widen(current: MountWindow, count: number): MountWindow {if (current == null) return null;// A start at or past the end withholds nothing. Clamping to `count` then subtracting a chunk@@ -158,10 +134,8 @@ export function widen(current: MountWindow, count: number): MountWindow {return { start };}-/**- * Whether `index` may mount. Out-of-window indices are not rendered at all rather than hidden: the- * cost avoided is mounting, so hiding would collect nothing.- */+/** Whether `index` may mount. Out-of-window indices are not rendered at all rather than hidden: the cost avoided+ * is mounting, so hiding would collect nothing. */export function admits(current: MountWindow, index: number): boolean {return current == null || index >= current.start;}@@ -169,71 +143,64 @@ export function admits(current: MountWindow, index: number): boolean {/** One end of a widening, as the correction below needs to see it. */export type AnchorSample = {/**- * The anchor row's offset from the top of the SCROLL CONTAINER, not of the window.- *- * `getBoundingClientRect().top` is window-relative, so it also moves when the container moves- * for reasons unrelated to the thread: the composer grows a line, mobile chrome slides away, a- * parent relayouts, the window resizes. Any of those landing between capture and the widening- * commit would read as content inserted above and be corrected away, moving a detached reader- * for nothing. Subtracting the container's own top at both ends removes it.- */+ * The anchor row's offset from the top of the SCROLL CONTAINER, not of the window.+ * `getBoundingClientRect().top` is window-relative, so it also moves when the container moves for reasons+ * unrelated to the thread: the composer grows a line, mobile chrome slides away, a parent relayouts, the window+ * resizes. Any of those landing between capture and the widening commit would read as content inserted above+ * and be corrected away, moving a detached reader for nothing. Subtracting the container's own top at both ends+ * removes it.+ */viewportOffset: number;/** The scroll container's scrollTop at the same instant. */scrollTop: number;/**- * The largest scrollTop possible at the same instant (`scrollHeight - clientHeight`).- *- * Only for the one case where the browser moves scrollTop with anchoring off: content above a- * reader near the bottom SHRINKING forces a clamp, since the old offset no longer exists. The- * document-space delta reports the whole shrink anyway, so applying it on top of the clamp would- * move the viewport twice by the clamped part. See anchorCorrection.- */+ * The largest scrollTop possible at the same instant (`scrollHeight - clientHeight`). Only for the one case+ * where the browser moves scrollTop with anchoring off: content above a reader near the bottom SHRINKING forces+ * a clamp, since the old offset no longer exists. The document-space delta reports the whole shrink anyway, so+ * applying it on top of the clamp would move the viewport twice by the clamped part. See anchorCorrection.+ */maxScrollTop: number;};/**- * How far to move scrollTop so a widening commit leaves the reader looking at the same content,- * or null for "do nothing". Pure, so it can be tested as arithmetic rather than as a substring.+ * How far to move scrollTop so a widening commit leaves the reader looking at the same content, or null for "do+ * nothing". Pure, so it can be tested as arithmetic rather than as a substring.*- * DOCUMENT space, correct only because the viewport turns CSS scroll anchoring OFF while the window- * is open (see progressive-messages). With native anchoring live the browser moves scrollTop by the- * inserted height and a document-space delta reports that insertion too, so applying it doubles the- * browser's correction: that was v1, and it walked a parked reader's scrollTop 22,897 to 117,104.+ * DOCUMENT space, correct only because the viewport turns CSS scroll anchoring OFF while the window is open (see+ * progressive-messages). With native anchoring live the browser moves scrollTop by the inserted height and a+ * document-space delta reports that insertion too, so applying it doubles the browser's correction: that was v1,+ * and it walked a parked reader's scrollTop 22,897 to 117,104.*- * v2 kept anchoring on, measured the residual in viewport space, and dropped any frame the reader- * scrolled through, since in viewport space a gesture and a layout shift are the same number. That- * holds only while the browser compensates, and it is not in charge of whether it does. Measured at- * 150K characters:+ * v2 kept anchoring on, measured the residual in viewport space, and dropped any frame the reader scrolled+ * through, since in viewport space a gesture and a layout shift are the same number. That holds only while the+ * browser compensates, and it is not in charge of whether it does. Measured at 150K characters:*- * - Every shipping Safari and iOS browser has no scroll anchoring at all today; WebKit implemented- * it in February 2026 and Playwright's WebKit 26.5 has it, which hid this on this machine. With- * `overflow-anchor: none` standing in for those builds, one dropped frame walked a parked reader- * 19,259px and dropping every frame walked them 45,873px, on all three engines.- * - Anchoring is also suppressed PER FRAME on engines that have it, including after a programmatic- * scroll, which is what scrollbar drag, PageUp and middle-click autoscroll all become. Chromium- * 151 with a reader scrolling that way through the build-in: 45,161px of drift.+ * - Every shipping Safari and iOS browser has no scroll anchoring at all today; WebKit implemented it in+ * February 2026 and Playwright's WebKit 26.5 has it, which hid this on this machine. With `overflow-anchor:+ * none` standing in for those builds, one dropped frame walked a parked reader 19,259px and dropping every+ * frame walked them 45,873px, on all three engines.+ * - Anchoring is also suppressed PER FRAME on engines that have it, including after a programmatic scroll, which+ * is what scrollbar drag, PageUp and middle-click autoscroll all become. Chromium 151 with a reader scrolling+ * that way through the build-in: 45,161px of drift.*- * So the browser is taken out of the loop rather than trusted in it. With anchoring off scrollTop- * moves only when the reader or this code moves it, and document space subtracts the reader's own- * movement arithmetically: no frame skipped, nothing to feature-probe. Same fixture, same reader:- * 12px.+ * So the browser is taken out of the loop rather than trusted in it. With anchoring off scrollTop moves only when+ * the reader or this code moves it, and document space subtracts the reader's own movement arithmetically: no+ * frame skipped, nothing to feature-probe. Same fixture, same reader: 12px.*/export function anchorCorrection(captured: AnchorSample,now: AnchorSample,): number | null {- // What the browser was forced to absorb. With anchoring off it moves scrollTop for exactly one- // reason: the reader's offset stopped existing because the document got shorter above them. That- // part already happened, so only the remainder is applied.- //- // The clamp is estimated from the captured scrollTop, so it is exact only for a reader who did- // not scroll during the frame, and that bound cannot be closed here: the two orderings (clamp- // then gesture, gesture then clamp) produce the SAME pair of samples while wanting different- // answers, so gating on "scrollTop did not end at maxScrollTop" just moves the error to the other- // ordering. This picks clamp-first and is wrong by at most `captured.scrollTop -- // now.maxScrollTop`, the height of the shrink the reader was hanging over, never by their- // gesture. It needs a DETACHED reader parked inside that overhang, content above them shrinking,- // and a scroll in that one frame, with a window open. Everything else has this term at zero.+ // What the browser was forced to absorb. With anchoring off it moves scrollTop for exactly one reason: the+ // reader's offset stopped existing because the document got shorter above them. That part already happened, so+ // only the remainder is applied.+ // The clamp is estimated from the captured scrollTop, so it is exact only for a reader who did not scroll during+ // the frame, and that bound cannot be closed here: the two orderings (clamp then gesture, gesture then clamp)+ // produce the SAME pair of samples while wanting different answers, so gating on "scrollTop did not end at+ // maxScrollTop" just moves the error to the other ordering. This picks clamp-first and is wrong by at most+ // `captured.scrollTop - now.maxScrollTop`, the height of the shrink the reader was hanging over, never by their+ // gesture. It needs a DETACHED reader parked inside that overhang, content above them shrinking, and a scroll in+ // that one frame, with a window open. Everything else has this term at zero.const clamped = Math.max(0, captured.scrollTop - now.maxScrollTop);const shift =now.viewportOffset +@@ -244,10 +211,8 @@ export function anchorCorrection(return Math.abs(shift) >= 1 ? shift : null;}-/**- * Widening frames a thread of `count` messages takes to converge. Tests assert on this so the- * constants above cannot drift into a thread that never finishes.- */+/** Widening frames a thread of `count` messages takes to converge. Tests assert on this so the constants above+ * cannot drift into a thread that never finishes. */export function stepsToCover(count: number): number {let steps = 0;let current = initialWindow(count, false);diff --git a/studio/frontend/src/components/assistant-ui/python-tool-image-path.ts b/studio/frontend/src/components/assistant-ui/python-tool-image-path.tsindex cd92b01e286..9bcdf6c48b0 100644--- a/studio/frontend/src/components/assistant-ui/python-tool-image-path.ts+++ b/studio/frontend/src/components/assistant-ui/python-tool-image-path.ts@@ -7,8 +7,7 @@ export function pythonToolImagePath(sessionId: string,filename: string,): string {- // Segment by segment, like the file cards: a chart written to outputs/ keeps- // a real "/" in the URL, and an encoded one is refused by proxies before the- // route ever sees it.+ // Segment by segment, like the file cards: a chart written to outputs/ keeps a real "/" in the+ // URL, and an encoded one is refused by proxies before the route ever sees it.return sandboxFilePath(sessionId, filename);}diff --git a/studio/frontend/src/components/assistant-ui/reasoning.tsx b/studio/frontend/src/components/assistant-ui/reasoning.tsxindex 456cc299a27..95b21a07b04 100644--- a/studio/frontend/src/components/assistant-ui/reasoning.tsx+++ b/studio/frontend/src/components/assistant-ui/reasoning.tsx@@ -202,16 +202,15 @@ function ReasoningContent({closeDurationMs={ANIMATION_DURATION}className={cn(shared,- // No `animate-collapsible-*`, so nothing consumes- // `--radix-collapsible-content-height` and nothing needs to know the content's height.- // `1fr` resolves against the content on every frame, which is also what makes this- // correct while reasoning is still streaming into an open pane: the row simply tracks- // the growing content instead of holding a height captured at toggle time.- //- // The duration is unconditional here. The height keyframes needed a per-state duration- // because they were two different animations; this is one transition run in both- // directions. `prefers-reduced-motion` still reaches it: index.css forces- // `transition-duration: 0.01ms !important` on every element, and this is a transition.+ // No `animate-collapsible-*`, so nothing consumes `--radix-collapsible-content-height`+ // and nothing needs to know the content's height. `1fr` resolves against the content on+ // every frame, which is also what makes this correct while reasoning is still streaming+ // into an open pane: the row simply tracks the growing content instead of holding a+ // height captured at toggle time. The duration is unconditional here. The height+ // keyframes needed a per-state duration because they were two different animations; this+ // is one transition run in both directions. `prefers-reduced-motion` still reaches it:+ // index.css forces `transition-duration: 0.01ms !important` on every element, and this is+ // a transition."duration-(--animation-duration)",className,)}@@ -433,10 +432,9 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({}}, [isReasoningStreaming]);- // Reset per-round open state. manualOpen is sticky and regenerate reuses this- // instance, so a hand-opened block would stay pinned open and never collapse.- // Adjusted during render, not in an effect: React re-runs this component- // before committing, so a stale open never reaches the DOM.+ // Reset per-round open state. manualOpen is sticky and regenerate reuses this instance, so a+ // hand-opened block would stay pinned open and never collapse. Adjusted during render, not in an+ // effect: React re-runs this component before committing, so a stale open never reaches the DOM.const [wasStreaming, setWasStreaming] = useState(isReasoningStreaming);if (wasStreaming !== isReasoningStreaming) {setWasStreaming(isReasoningStreaming);@@ -446,17 +444,14 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({}}- // Keep the streaming height cap until the automatic close finishes. Removing- // it on the completion frame expands long reasoning to its full height before- // the collapsible can close, which makes the entire chat jump.- //- // The grid path needs the same margin the collapsible's own backstop uses. The- // height keyframes animate from a height captured at toggle time, so releasing- // the cap mid-animation cannot change what they animate; `1fr` instead resolves- // against the live content every frame, so an early release grows the row in the- // middle of the collapse and produces exactly the jump this timer prevents. The- // transition also starts a render after this timer is armed, so an exact- // ANIMATION_DURATION lands inside it.+ // Keep the streaming height cap until the automatic close finishes. Removing it on the completion+ // frame expands long reasoning to its full height before the collapsible can close, which makes+ // the entire chat jump. The grid path needs the same margin the collapsible's own backstop uses.+ // The height keyframes animate from a height captured at toggle time, so releasing the cap+ // mid-animation cannot change what they animate; `1fr` instead resolves against the live content+ // every frame, so an early release grows the row in the middle of the collapse and produces+ // exactly the jump this timer prevents. The transition also starts a render after this timer is+ // armed, so an exact ANIMATION_DURATION lands inside it.useEffect(() => {const closeDelay = GRID_COLLAPSE_REASONING_ENABLED? ANIMATION_DURATION + CLOSE_FALLBACK_MARGIN_MSdiff --git a/studio/frontend/src/components/assistant-ui/research-reply-owners.ts b/studio/frontend/src/components/assistant-ui/research-reply-owners.tsindex 8c7b2f80fd4..615f3ae0a29 100644--- a/studio/frontend/src/components/assistant-ui/research-reply-owners.ts+++ b/studio/frontend/src/components/assistant-ui/research-reply-owners.ts@@ -19,9 +19,8 @@ export type ExportedReplyItem = {message: { metadata?: unknown };};-// Keyed on the revision object, not a counter, so a stale entry is unreachable: a current-// revision is the same object, a stale one has been replaced. Weak, so a dead thread's entry goes-// with it.+// Keyed on the revision object, not a counter, so a stale entry is unreachable: a current revision+// is the same object, a stale one has been replaced. Weak, so a dead thread's entry goes with it.const ownersByRevision = new WeakMap<object, ReadonlySet<string>>();/**diff --git a/studio/frontend/src/components/assistant-ui/sandbox-files.ts b/studio/frontend/src/components/assistant-ui/sandbox-files.tsindex 0913f5068b9..54f877c3110 100644--- a/studio/frontend/src/components/assistant-ui/sandbox-files.ts+++ b/studio/frontend/src/components/assistant-ui/sandbox-files.ts@@ -85,9 +85,8 @@ export function isSandboxToolResult(images?: unknown;files?: unknown;};- // images too: it is always in Unsloth's own wrapper, and a tool result that- // merely has text and sessionId is someone else's, whose other fields would- // be dropped on export.+ // images too: it is always in Unsloth's own wrapper, and a tool result that merely has text and+ // sessionId is someone else's, whose other fields would be dropped on export.return (typeof v.text === "string" &&typeof v.sessionId === "string" &&diff --git a/studio/frontend/src/components/assistant-ui/sources.tsx b/studio/frontend/src/components/assistant-ui/sources.tsxindex d2e9901be5c..330a7962c59 100644--- a/studio/frontend/src/components/assistant-ui/sources.tsx+++ b/studio/frontend/src/components/assistant-ui/sources.tsx@@ -19,8 +19,6 @@ import {HoverCardContent,} from "@/components/ui/hover-card";-// ── Helpers ──────────────────────────────────────────────────-const extractDomain = (url: string): string => {try {return new URL(url).hostname.replace(/^www\./, "");@@ -34,8 +32,6 @@ const getDomainInitial = (url: string): string => {return domain.charAt(0).toUpperCase();};-// ── Sub-components ───────────────────────────────────────────-function SourceIcon({url,className,@@ -126,8 +122,6 @@ function Source({);}-// ── Source badge with hover card ─────────────────────────────-export interface SourceData {/*** Stable per-citation key. Two Anthropic citations into different spans of@@ -186,8 +180,6 @@ const SourceBadge: FC<{ source: SourceData; allowRemoteIcons?: boolean }> = ({);};-// ── Grouped sources with 2-row collapse ─────────────────────-const SourcesGroup: FC<{ sources?: SourceData[]; allowRemoteIcons?: boolean }> = ({sources: suppliedSources,allowRemoteIcons = true,@@ -333,12 +325,8 @@ const SourcesGroup: FC<{ sources?: SourceData[]; allowRemoteIcons?: boolean }> =);};-// ── Individual source (renders null — SourcesGroup handles all) ──-const SourcesNoop: FC<Record<string, unknown>> = () => null;-// ── Exports ──────────────────────────────────────────────────-const Sources = memo(SourcesNoop) as unknown as FC<Record<string, unknown>> & {Root: typeof Source;Icon: typeof SourceIcon;diff --git a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.tsindex 9a290d6aaee..1a83a2e3952 100644--- a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts+++ b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts@@ -8,37 +8,26 @@ import { type BlockProps, parseMarkdownIntoBlocks } from "streamdown";// The block list interleaves "\n\n" separators, so this is about four// paragraphs of slack for a construct that a later line can still reinterpret.const ROLLBACK_BLOCKS = 8;-// A marker the reply never closes leaves the tail growing with nothing to-// retain, and the boundary scan is then paid on top of the full repair it was-// meant to replace. Give up at a character budget, since characters are what-// that scan costs, and a transient imbalance closes far below this. The budget-// is spent before giving up and that spending grows with the square of the tail,-// so the value matters. Measured on an emphasis marker that only closes 40,000-// characters later, 420 updates, five repetitions: the median cost against the-// full-document path is +73% at 32,768 and +1.6% at 8,192. 8,192 characters is-// still around 1,300 words of slack, well beyond a marker a later line closes.+// A marker the reply never closes leaves the tail growing with nothing to retain, and the boundary+// scan is then paid on top of the full repair it was meant to replace. Give up at a character+// budget, since characters are what that scan costs, and the spending grows with the square of the+// tail. Measured on a marker that closes 40,000 characters later: median cost against the+// full-document path is +73% at 32,768 and +1.6% at 8,192, which is still ~1,300 words of slack.const STALLED_TAIL_CHARACTERS = 8_192;-// remend repairs the trailing incomplete construct, but it reaches that-// decision with whole-string passes: one walks the text once per `[` looking-// for an unterminated link, another escapes comparison operators line by line.-// Inside an unterminated fence every such character is literal and every pass-// declines, so those walks cost the length of the fence and change nothing. The-// fence also lexes into a single block, so `candidateCount` in update() is 0,-// nothing is ever retained, and the tail grows with the fence: appending one-// chunk then costs O(fence) and a reply costs the square of it. Repair the head-// plus a window of the fence body instead, and splice the untouched middle back-// in. The window carries the last line and the line before it, which is all the-// trailing repairs read.+// remend repairs the trailing incomplete construct, but reaches that decision with whole-string+// passes: one walks the text once per `[` looking for an unterminated link, another escapes+// comparison operators line by line. Inside an unterminated fence every such character is literal+// and every pass declines, so those walks cost the length of the fence and change nothing. The+// fence also lexes into a single block, so nothing is ever retained and a reply costs the square of+// it. Repair the head plus a window of the fence body instead and splice the untouched middle back+// in; the window carries the last line and the one before it, which is all the trailing repairs read.const OPEN_FENCE_REPAIR_WINDOW = 4_096;-// A plain two-line probe. When remend leaves the head alone with ordinary text-// after it, no marker is pending for it to close, so it cannot append anything-// beyond the window either. Without it a marker left open before the fence gets-// its closer at the wrong offset.-//-// Its verdict is a property of the HEAD, while remend decides from the whole-// string, so on its own it is not enough: text later in the body can flip a-// global parity the probe assumed and revive a marker it cleared. The body-// marker refusal below is what closes that gap, and the two only work together.+// A plain two-line probe. When remend leaves the head alone with ordinary text after it, no marker+// is pending for it to close, so it cannot append anything beyond the window either; without it a+// marker left open before the fence gets its closer at the wrong offset. Its verdict is a property+// of the HEAD while remend decides from the whole string, so on its own it is not enough: text+// later in the body can flip a global parity the probe assumed. The body marker refusal below is+// what closes that gap.const OPEN_FENCE_PROBE = "\nq\n";// An index can only be resolved once the two characters after it are known, so// the scan keeps that many back from the live edge and re-reads them.@@ -51,20 +40,13 @@ const SINGLE_ASTERISK_CONTEXT = "*x*\n\n";const SINGLE_UNDERSCORE_CONTEXT = "_x_\n\n";const INLINE_CODE_ASTERISK_CONTEXT = "`a *b* c`\n\n";const INLINE_CODE_UNDERSCORE_CONTEXT = "`a _b_ c`\n\n";-// The one context that is deliberately UNBALANCED, because the fact it carries-// is an open region rather than a marker that exists somewhere behind the-// boundary. remend has no other way to enter the state: `\(` is the only-// transition into inline LaTeX, so standing in for a region the retained prefix-// opened means writing an opener and nothing else. The blank line after it is-// load bearing twice over. It keeps the opener off the tail's first line, which-// every line-oriented repair (comparison operators, setext headings, the list-// item scan) would otherwise read as part of that line, and it puts a newline-// between the tail and the `(`, which is where remend's backwards scan for a-// link destination stops. The region itself survives the blank line: remend's-// math scan has no newline rule, so `\(` stays open until a `\)` closes it,-// which is exactly the behaviour being reproduced.-//-// There is deliberately no `\[` twin. See `hasUncarriableMath`.+// The one context that is deliberately UNBALANCED, because the fact it carries is an open region+// rather than a marker behind the boundary. remend has no other way to enter the state: `\(` is the+// only transition into inline LaTeX. The blank line after it is load bearing twice over: it keeps+// the opener off the tail's first line, which every line-oriented repair would otherwise read as+// part of that line, and it puts a newline between the tail and the `(`, which is where remend's+// backwards scan for a link destination stops. The region survives it, since remend's math scan has+// no newline rule. There is deliberately no `\[` twin; see `hasUncarriableMath`.const INLINE_LATEX_CONTEXT = "\\(\n\n";const FOOTNOTE_REFERENCE_RE = /\[\^[\w-]{1,200}\](?!:)/;const FOOTNOTE_DEFINITION_RE = /\[\^[\w-]{1,200}\]:/;@@ -165,21 +147,13 @@ export function parseMarkdownIntoRenderableBlocks(markdown: string): string[] {// Where remend believes the emphasis scan sits with respect to math.//-// remend 1.3.0 kept two booleans here, one for `$...$` and one for `$$...$$`,-// and knew nothing about the LaTeX bracket delimiters. That is the bug the-// 1.3.1 bump fixes: on `where \( \delta_{r} = 1 \) holds.` the `_` of the-// subscript was counted as an unmatched emphasis marker and "completed" with a-// second `_` appended to a document that was already finished, so the reply-// showed a stray underscore. 1.3.1 replaced the pair with the five state-// machine below (`inlineLatex`, `blockLatex`, `inlineDollar`, `blockDollar`,-// `none`), and every marker inside any of the four open states is skipped.-//-// The dollar half is unchanged between the two versions, so the two booleans-// map onto `inlineDollar` and `blockDollar` exactly; only the LaTeX half is-// new. Unsloth has to mirror it because `RepairParity` is a hand written copy of-// remend's marker rules, and a copy that still counts the subscript would show-// the stray `_` for as long as the reply is streaming and drop it the moment-// the message settles and the whole body is repaired in one pass.+// remend 1.3.0 kept two booleans here, one for `$...$` and one for `$$...$$`, and knew nothing+// about the LaTeX bracket delimiters. That is the bug the 1.3.1 bump fixes: on+// `where \( \delta_{r} = 1 \) holds.` the subscript `_` was counted as an unmatched emphasis+// marker and "completed" with a second `_` appended to a finished document. 1.3.1 replaced the pair+// with the five-state machine below and skips every marker inside any of the four open states. The+// dollar half is unchanged, so the two booleans map onto `inlineDollar` and `blockDollar` exactly.+// Unsloth mirrors it because `RepairParity` is a hand-written copy of remend's marker rules.type EmphasisMathState =| "none"| "inlineLatex"@@ -252,12 +226,10 @@ const createRepairParity = (inlineMath: false,});-// Marked keeps link reference definitions in one document-wide map and emits-// no token for a label it has already seen, so a definition that is retained-// while its twin is still live would be lexed apart and shown as a literal-// line. Keeping every definition in the live tail makes the two lexes agree.-// Marked reads a fenced block as code, so those do not count; anything else-// that merely looks like a definition costs retention, never correctness.+// Marked keeps link reference definitions in one document-wide map and emits no token for a label+// it has already seen, so a definition retained while its twin is still live would be lexed apart+// and shown as a literal line. Keeping every definition in the live tail makes the two lexes agree.+// Marked reads a fenced block as code, so those do not count.function updateLinkDefinitionParity(parity: RepairParity, text: string): void {if (!FENCED_CODE_BLOCK_RE.test(text) && LINK_DEFINITION_RE.test(text)) {parity.linkDefinition = true;@@ -316,12 +288,10 @@ function isWithinHtmlTag(text: string, index: number): boolean {return false;}-// A `\` opens or closes a LaTeX region when the character after it is the-// matching bracket, and does nothing otherwise. Both regions only open from-// `none` and only close from their own state, so a `\]` in the middle of a-// `\(...\)` span is inert and the opener stands until its own closer arrives.-// Returns null when this backslash is not a delimiter, which is remend's signal-// to leave the state alone and read the escaped character normally.+// A `\` opens or closes a LaTeX region when the character after it is the matching bracket, and+// does nothing otherwise. Both regions only open from `none` and only close from their own state,+// so a `\]` inside a `\(...\)` span is inert. Returns null when this backslash is not a delimiter,+// which is remend's signal to read the escaped character normally.function latexMathTransition(state: EmphasisMathState,next: string | undefined,@@ -341,11 +311,9 @@ function latexMathTransition(return null;}-// `$$` toggles the block state from wherever it was, which is how an unclosed-// `$...$` is swallowed by a following display block. A lone `$` cannot close a-// block one and cannot open anything inside one, so `blockDollar` absorbs it.-// This half is byte for byte the rule remend 1.3.0 already had, written as a-// transition rather than as two booleans.+// `$$` toggles the block state from wherever it was, which is how an unclosed `$...$` is swallowed+// by a following display block. A lone `$` cannot close a block one and cannot open anything inside+// one, so `blockDollar` absorbs it. This half is byte for byte remend 1.3.0's rule.function dollarMathTransition(state: EmphasisMathState,isDouble: boolean,@@ -362,14 +330,10 @@ function dollarMathTransition(const isLatexMathState = (state: EmphasisMathState): boolean =>state === "inlineLatex" || state === "blockLatex";-// remend recomputes this from the start of the document for every marker it-// looks at; this runs once, in step with the emphasis scan, and reaches the-// same state at every offset. It deliberately runs before the fence handling-// below, because remend's math scan is a separate pass that knows nothing about-// fenced code: a `$` inside a fence moves the math state there too.-//-// Returns the index to resume from, which is one past a delimiter that spans-// two characters so the second half is not read again.+// remend recomputes this from the start of the document for every marker it looks at; this runs+// once, in step with the emphasis scan, and reaches the same state at every offset. It runs before+// the fence handling below because remend's math scan is a separate pass that knows nothing about+// fenced code. Returns the index to resume from, one past a two-character delimiter.function updateEmphasisMathParity(parity: RepairParity,text: string,@@ -412,11 +376,9 @@ const isBoundaryCharacter = (character: string | undefined): boolean =>character === "\t" ||character === "\n";-// remend's skip list for the single asterisk counter. 1.3.1 dropped ONE clause-// from it, the one that skipped an asterisk with a word character on each side,-// and moved that case into `countsAsSingleAsterisk` below, where it is now-// counted under a condition rather than dropped outright. Everything else here-// is byte for byte what 1.3.0 had.+// remend's skip list for the single asterisk counter. 1.3.1 dropped ONE clause, the one skipping an+// asterisk with a word character on each side, and moved that case into `countsAsSingleAsterisk`+// below. Everything else here is byte for byte what 1.3.0 had.function shouldSkipAsterisk(parity: RepairParity,text: string,@@ -438,20 +400,13 @@ function shouldSkipAsterisk(return isBoundaryCharacter(previous) && isBoundaryCharacter(next);}-// Does this asterisk move the single asterisk parity?-//-// This is remend 1.3.1's rule and it is NOT 1.3.0's. 1.3.0 dropped every-// asterisk with a word character on both sides, so `*foo*bar` counted one-// marker, came out odd, and the repair closed it. 1.3.1 counts the in-word one-// as soon as the count is already odd or an in-word chain is running, so the-// same text counts two, comes out even, and nothing is appended. Verified-// against the two packages directly: `remend("*foo*bar\n\n~~s")` returns-// `"*foo*bar\n\n~~s*~~"` under 1.3.0 and `"*foo*bar\n\n~~s~~"` under 1.3.1,-// the inserted `*` being the pending marker the strikethrough repair flushes.-//-// `inWordAsteriskChain` is what lets a run like `*foo*bar*baz` keep counting-// after the second marker has been taken: the chain is set by an in-word marker-// that counted, and any non word character outside a fence clears it again.+// Does this asterisk move the single asterisk parity? This is remend 1.3.1's rule and NOT 1.3.0's.+// 1.3.0 dropped every asterisk with a word character on both sides, so `*foo*bar` counted one+// marker, came out odd, and the repair closed it. 1.3.1 counts the in-word one as soon as the count+// is already odd or an in-word chain is running, so the same text counts two and nothing is+// appended: remend of `*foo*bar` followed by `~~s` appends a stray `*` under 1.3.0 and nothing+// under 1.3.1. `inWordAsteriskChain` is what lets `*foo*bar*baz` keep counting after the second+// marker; any non word character outside a fence clears it.function countsAsSingleAsterisk(parity: RepairParity,text: string,@@ -460,9 +415,8 @@ function countsAsSingleAsterisk(const previous = text[index - 1];const next = text[index + 1];const inWord = isWordCharacter(previous) && isWordCharacter(next);- // "Text" here means present and not whitespace, which is remend's test for- // whether a marker has something on that side to attach to. It is weaker than- // "word character": punctuation counts.+ // "Text" here means present and not whitespace, which is remend's test for whether a marker has+ // something on that side to attach to. It is weaker than "word character": punctuation counts.const previousIsText = !isBoundaryCharacter(previous);const nextIsText = !isBoundaryCharacter(next);if (inWord && !parity.singleAsterisk && !parity.inWordAsteriskChain) {@@ -644,11 +598,10 @@ function clearInWordAsteriskChain(function updateEmphasisParity(parity: RepairParity, text: string): void {for (let index = 0; index < text.length; index += 1) {- // The chain is cleared at the top of the loop, before any of the multi- // character skips below, because every one of those skips starts on a- // backslash, a dollar or a backtick, and all three are non word characters- // that clear the chain in remend as well. Reading only the first character- // of a skipped pair therefore reaches the same state remend does.+ // The chain is cleared at the top of the loop, before any of the multi character skips below,+ // because every one of those skips starts on a backslash, a dollar or a backtick, and all three+ // are non word characters that clear the chain in remend as well. Reading only the first+ // character of a skipped pair therefore reaches the same state remend does.clearInWordAsteriskChain(parity, text[index]);index = updateEmphasisMathParity(parity, text, index);const skipped = skipEscapeOrFence(parity, text, index);@@ -770,28 +723,21 @@ function updateRepairParity(parity: RepairParity, text: string): void {updateInlineMathParity(parity, text);}-// An open math region a boundary may NOT sit inside, because the tail repair-// cannot be told about it. Only `inlineLatex` is missing from this list, and the-// asymmetry is a property of the openers rather than of the regions:+// An open math region a boundary may NOT sit inside, because the tail repair cannot be told about+// it. Only `inlineLatex` is missing, and the asymmetry is a property of the openers://-// `$` and `$$` are counted by the katex and inlineKatex repairs as well as by-// the emphasis scan, so a bare dollar in the context prefix would also make-// those two close a delimiter the retained prefix already holds. This is the-// refusal the two booleans 1.3.0 kept here always had, unchanged.+// `$` and `$$` are counted by the katex and inlineKatex repairs as well as by the emphasis scan,+// so a bare dollar in the context prefix would make those two close a delimiter the retained+// prefix already holds. This is the refusal 1.3.0's two booleans always had.//-// `\[` is the only way into `blockLatex`, and it carries a `[` that remend's-// link repair reads. That repair walks backwards over every `[` outside code-// and completes the first one whose `]` is missing, so an opener standing in-// for a `\[` several blocks back turns a tail with no bracket of its own into-// one ending `](streamdown:incomplete-link)`, while the whole document is left-// alone because the real `\[` does have a `]` after it somewhere in the-// retained prefix. Found by differential fuzzing against a full remend() of-// the same text, on a body holding an unclosed `\[` and a later stray `]`.-// There is no opener without the bracket, so the boundary is refused instead.+// `\[` is the only way into `blockLatex` and carries a `[` that remend's link repair reads: that+// repair walks backwards over every `[` outside code and completes the first one whose `]` is+// missing, so an opener standing in for a `\[` several blocks back turns a tail with no bracket+// of its own into one ending `](streamdown:incomplete-link)`, while the whole document is left+// alone. Found by differential fuzzing against a full remend() of the same text.//-// `inlineLatex` has neither problem: `(` is read only by the backwards scan for-// a link destination, which stops at the first newline, and the context prefix-// ends with a blank line.+// `inlineLatex` has neither problem: `(` is read only by the backwards scan for a link destination,+// which stops at the first newline, and the context prefix ends with a blank line.const hasUncarriableMath = (parity: RepairParity): boolean =>parity.emphasisMath !== "none" && parity.emphasisMath !== "inlineLatex";@@ -872,15 +818,12 @@ const emphasisContext = (context: RetainedContext): string => {const latexContext = (context: RetainedContext): string =>context.latex === "inlineLatex" ? INLINE_LATEX_CONTEXT : "";-// Taking the context as a value lets a candidate commit be priced before it is-// applied, which the repeated-Markdown check in update() needs.-//-// The LaTeX opener goes LAST, immediately before the tail, and the ordering is-// not cosmetic: everything after it is inside the region it opens, so a-// `_x_\n\n` written after it would be a pair of underscores remend declines to-// count and the emphasis context would silently carry nothing. Putting it last-// is also what the document itself looks like, since a marker that reached the-// boundary as a candidate was counted, which means it sat outside the region.+// Taking the context as a value lets a candidate commit be priced before it is applied, which the+// repeated-Markdown check in update() needs. The LaTeX opener goes LAST, immediately before the+// tail, and the ordering is not cosmetic: everything after it is inside the region it opens, so a+// `_x_` written after it would be a pair of underscores remend declines to count and the emphasis+// context would carry nothing. It is also what the document looks like, since a marker that reached+// the boundary as a candidate was counted, which means it sat outside the region.function repairContextPrefix(context: RetainedContext): string {return (emphasisContext(context) +@@ -898,29 +841,21 @@ function repairTail(tail: string, context: RetainedContext): string {return remend(prefix + tail).slice(prefix.length);}-// Where remend believes a fence is open. It toggles on any ``` run, wherever on-// the line that run sits, and a backslash escapes the backtick after it, so this-// deliberately mirrors remend rather than CommonMark: a mid-line ``` closes the-// fence for remend and must close it here too.+// Where remend believes a fence is open. It toggles on any ``` run, wherever on the line that run+// sits, and a backslash escapes the backtick after it, so this deliberately mirrors remend rather+// than CommonMark: a mid-line ``` closes the fence for remend and must close it here too.type OpenFenceState = {index: number;fenceOpen: boolean;bodyStart: number;- // The FIRST ` $ or ~ in the current fence body, or -1. Its mere presence- // disqualifies the splice, so only whether one exists ever matters; the index- // is kept because it reads better in a test than a bare boolean.- //- // remend does not have one notion of "inside a fence"; it has at least three,- // and they disagree. `isWithinCodeBlock` walks the text and honours a- // backslash before a backtick, the emphasis counters toggle on ``` without- // honouring it, and the inline-code repair just counts /```/g. An escaped- // \``` or a ```` run flips the last of those and not the first. The opener- // that stands in for the elided text can only reproduce all three when the- // elided part holds none of the characters any of them counts.- //- // The first such character, not the last: a marker sitting in the window- // would otherwise mask an earlier one sitting in the elided middle, which is- // the half that matters. First is also monotone, so it costs nothing to keep.+ // The FIRST ` $ or ~ in the current fence body, or -1. Its mere presence disqualifies the splice,+ // so only whether one exists ever matters; the index reads better in a test than a bare boolean.+ // remend does not have one notion of "inside a fence"; it has at least three, and they disagree.+ // `isWithinCodeBlock` honours a backslash before a backtick, the emphasis counters toggle on ```+ // without honouring it, and the inline-code repair just counts /```/g. The opener standing in for+ // the elided text can only reproduce all three when the elided part holds none of the characters+ // any of them counts. The first such character, not the last: a marker in the window would+ // otherwise mask an earlier one in the elided middle, and first is monotone.firstBodyMarker: number;};@@ -1002,36 +937,26 @@ class OpenFenceTracker {}}-// A head the probe found inert contributes nothing but "a fence is open", which-// one opener reproduces. Standing in for it keeps the repair off the head as-// well as off the elided body.+// A head the probe found inert contributes nothing but "a fence is open", which one opener+// reproduces. Standing in for it keeps the repair off the head as well as off the elided body.const OPEN_FENCE_SYNTHETIC_HEAD = "```\n";-// The spliced repair, or null when it cannot be shown to match repairTail. All-// four refusals fall back to repairing the whole tail:-//+// The spliced repair, or null when it cannot be shown to match repairTail. All four refusals fall+// back to repairing the whole tail:// a body still shorter than the window has nothing to elide;-// a final line longer than the window leaves no line boundary to cut on,-// which is the only place the splice can start without changing what the-// trailing repairs read;-// a PRECEDING line longer than the window puts the cut on the newline that-// ends it, so the window holds the final line alone. remend's setext repair-// reads exactly one line back, and the synthetic opener standing in for it-// is never blank, so a whitespace-only line elided that way turns a tail-// ending in `-`, `--`, `=` or `==` into one carrying a zero-width space-// that repairing the whole tail does not add, and that the copy button-// would then put on the clipboard;-// a ` $ or ~ ANYWHERE in the body, elided or retained, is a character one of-// remend's fence notions counts, and the opener cannot stand in for it.-//-// The last one deliberately covers the retained window and not just the elided-// middle, because the probe that licenses the opener reads the head ALONE while-// remend decides from the whole string. An escaped \``` in the window flips the-// global triple-run parity, so the whole-tail repair closes an unmatched inline-// backtick that sits before the opener and the spliced output does not; a `$$`-// there moves the math parity the other way. Neither is reachable from a-// refusal on the cut, since the probe runs before the cut is chosen. Keeping-// the body free of all three characters is what makes the probe's verdict a+// a final line longer than the window leaves no line boundary to cut on, the only place the+// splice can start without changing what the trailing repairs read;+// a PRECEDING line longer than the window puts the cut on the newline that ends it, so the window+// holds the final line alone. remend's setext repair reads exactly one line back, and the+// synthetic opener is never blank, so a whitespace-only line elided that way turns a tail+// ending in `-`, `--`, `=` or `==` into one carrying a zero-width space that repairing the+// whole tail does not add, and that the copy button would put on the clipboard;+// a ` $ or ~ ANYWHERE in the body, elided or retained, is a character one of remend's fence+// notions counts, and the opener cannot stand in for it.+// The last one covers the retained window and not just the elided middle, because the probe that+// licenses the opener reads the head ALONE while remend decides from the whole string: an escaped+// backtick fence in the window flips the global triple-run parity, and a `$$` there moves the math+// parity. Keeping the body free of all three characters is what makes the probe's verdict a// property of the whole tail rather than of the head it was handed.function repairOpenFenceTail(tail: string,@@ -1056,11 +981,10 @@ function repairOpenFenceTail();}-// Every field but `latex` records that something EXISTS behind the boundary and-// so can only ever be turned on. `latex` is a position rather than a fact: the-// region the prefix opened can be closed by a later commit, so this one is-// taken from the parity outright instead of being or-ed in. That is why each-// commit point stores its own context, which a rewind then restores.+// Every field but `latex` records that something EXISTS behind the boundary and so can only be+// turned on. `latex` is a position rather than a fact: the region the prefix opened can be closed by+// a later commit, so it is taken from the parity outright. That is why each commit point stores its+// own context, which a rewind then restores.const retainedLatexState = (parity: RepairParity): RetainedLatexState =>parity.emphasisMath === "inlineLatex" ? "inlineLatex" : "none";@@ -1091,21 +1015,18 @@ type CommitBoundary = {repairBroke: boolean;};-// Where one commit left the retained prefix. `advanceContext` only ever adds-// facts and cannot be undone, so each commit's context is stored to allow a-// rewind to an earlier boundary.+// Where one commit left the retained prefix. `advanceContext` only ever adds facts and cannot be+// undone, so each commit's context is stored to allow a rewind to an earlier boundary.type CommitPoint = {blockCount: number;length: number;context: RetainedContext;};-// CommonMark counts a line feed, a lone carriage return, and a carriage return-// followed by a line feed as the same line ending, and reference parsers-// normalise to LF before parsing, so this cannot change what is rendered. The-// scan runs per frame and costs nothing next to the repair and lex it protects-// (0.4 us on an 88,000 character reply); the replace only runs for a reply that-// actually carries a carriage return.+// CommonMark counts a line feed, a lone carriage return, and CRLF as the same line ending, and+// reference parsers normalise to LF before parsing, so this cannot change what is rendered. The+// scan runs per frame and costs nothing next to the repair and lex it protects (0.4 us on an 88,000+// character reply); the replace only runs for a reply that carries a carriage return.function normalizeLineEndings(text: string): string {return text.includes("\r") ? text.replace(/\r\n?/g, "\n") : text;}@@ -1113,18 +1034,13 @@ function normalizeLineEndings(text: string): string {/*** `a` begins with `b`.*- * `String.prototype.startsWith` is the obvious spelling and is far slower here,- * because it scans where slicing to the prefix length and comparing lets the- * engine reject on length and then compare natively.- *- * The win is in the PREFIX length, not in how the strings are represented. Swept- * on V8: at an 8 character prefix `startsWith` is FASTER (0.4x), at 1,024 it is- * 105x slower and at 60,000 it is 250x slower, and a cons receiver behaves the- * same as a flat one (250x against 254x). So do not reach for this helper for- * short prefixes; it earns its place on a reply-length one.+ * `String.prototype.startsWith` is the obvious spelling and is far slower here, because it scans+ * where slicing to the prefix length and comparing lets the engine reject on length and then+ * compare natively. The win is in the PREFIX length, not in how the strings are represented: swept+ * on V8, at an 8 character prefix `startsWith` is FASTER (0.4x), at 1,024 it is 105x slower and at+ * 60,000 it is 250x slower. So do not reach for this helper for short prefixes.*- * Semantically identical: `slice` clamps to the string length, so a `b` longer- * than `a` yields a short slice that cannot equal it.+ * Semantically identical: `slice` clamps to the string length.*/export const hasPrefix = (a: string, b: string): boolean =>a.length >= b.length && a.slice(0, b.length) === b;@@ -1138,12 +1054,10 @@ function sharedPrefixLength(left: string, right: string): number {return index;}-// Does `text` end at a blank line, counting the start of the document as one?-// Unchanged characters alone cannot keep a block across a rewrite: Marked reads-// `paragraph\n` plus new text as a lazy continuation, so an edit that closes up-// a blank line re-segments the paragraph before it even though that paragraph's-// characters never moved. `\r` counts as line-ending whitespace, so CRLF reads-// the same as LF.+// Does `text` end at a blank line, counting the start of the document as one? Unchanged characters+// alone cannot keep a block across a rewrite: Marked reads `paragraph` plus new text as a lazy+// continuation, so an edit that closes up a blank line re-segments the paragraph before it even+// though that paragraph's characters never moved. `\r` counts as line-ending whitespace.function endsAtBlankLine(text: string, end: number): boolean {if (end === 0) {return true;@@ -1163,11 +1077,9 @@ function endsAtBlankLine(text: string, end: number): boolean {return true;}-// The last blank line at or before `limit`, or 0 for none. An untouched blank-// line between the boundary and the rewrite carries most of the insulation, so-// the boundary need not land on the blank line itself. Not all of it: see-// `rewindToRewrite`, which also keeps a rollback window of blocks between the-// boundary and the first changed character.+// The last blank line at or before `limit`, or 0 for none. An untouched blank line between the+// boundary and the rewrite carries most of the insulation, so the boundary need not land on the+// blank line itself. Not all of it: see `rewindToRewrite`, which also keeps a rollback window.function lastBlankLineEnd(text: string, limit: number): number {for (let end = limit; end > 0; end -= 1) {if (endsAtBlankLine(text, end)) {@@ -1186,10 +1098,9 @@ function findCommitBoundary(candidateCount: number,latex: RetainedLatexState,): CommitBoundary {- // The tail does not start at the top of the document, so the scan starts- // where the retained prefix left remend's math scan. Only the LaTeX state can- // be anything but neutral there, and it is the one state whose markers the- // tail repair would otherwise start counting again.+ // The tail does not start at the top of the document, so the scan starts where the retained+ // prefix left remend's math scan. Only the LaTeX state can be anything but neutral there, and it+ // is the one state whose markers the tail repair would otherwise start counting again.const parity = createRepairParity(latex);const commit: CommitBoundary = {count: 0,@@ -1234,10 +1145,9 @@ export class IncrementalMarkdownCache {private fullDocumentMode = false;private lastMarkdown: string | null = null;private droppedRetainedBlocks = false;- // How often a rewrite discarded the whole retained prefix, and how many- // characters a rewind handed back to the live tail. Both redo work with an- // identical result, so time is the only other evidence they happened. Tests- // read these to hold the rewind path in place.+ // How often a rewrite discarded the whole retained prefix, and how many characters a rewind+ // handed back to the live tail. Both redo work with an identical result, so time is the only+ // other evidence they happened. Tests read these to hold the rewind path in place.private retainedPrefixRebuilds = 0;private rewoundCharacters = 0;// Bumped only when the Markdown string alone cannot signal a changed render.@@ -1261,11 +1171,10 @@ export class IncrementalMarkdownCache {return { markdown, parseMarkdownIntoBlocks: this.parseMarkdownIntoBlocks };}- // The repair of a tail sitting inside an open fence, or null to repair the- // whole tail as before. The head is everything the repair would have to keep:- // once the probe shows remend leaves it alone, it holds nothing that could- // change the repair of the body, and it stays fixed until the fence closes,- // so the probe is paid once per fence rather than once per chunk.+ // The repair of a tail sitting inside an open fence, or null to repair the whole tail as before.+ // The head is everything the repair would have to keep: once the probe shows remend leaves it+ // alone, it holds nothing that could change the repair of the body, and it stays fixed until the+ // fence closes, so the probe is paid once per fence rather than once per chunk.private repairOpenFence(): string | null {const bounds = this.fenceTracker.spliceBounds(this.tail);if (bounds === null) {@@ -1299,25 +1208,20 @@ export class IncrementalMarkdownCache {return this.render(remend(markdown));}- // The text handed to the cache is not always an extension of the last one:- // `preprocessLaTeX` rewrites an already emitted span when a `\(...\)` closes,- // a `\[...\]` becomes a `$$` block or a currency `$` turns out not to open- // math, and a closing fence rewrites its own body. Each edits one span, so- // rewind to the last commit the rewrite can neither reach nor re-segment- // rather than discarding the whole prefix. Returns false when nothing- // survives and the caller has to start over; mutates nothing before then, so- // the reset fallback never sees a half-rewound cache. `fullDocumentMode`- // cannot be set here: only `renderFullDocument` raises it, and it clears- // `commitPoints` first, so the guard below has already returned.+ // The text handed to the cache is not always an extension of the last one: `preprocessLaTeX`+ // rewrites an already emitted span when a `\(...\)` closes, a `\[...\]` becomes a `$$` block or a+ // currency `$` turns out not to open math, and a closing fence rewrites its own body. Each edits+ // one span, so rewind to the last commit the rewrite can neither reach nor re-segment rather than+ // discarding the whole prefix. Returns false when nothing survives; mutates nothing before then, so+ // the reset fallback never sees a half-rewound cache.private rewindToRewrite(markdown: string): boolean {if (this.commitPoints.length === 0) {return false;}- // Characters the rewrite left alone. Usually the rewrite is inside the live- // tail, and `slice` shares the original's characters, so that case costs- // one native comparison plus a scan of the tail (about to be re-lexed- // anyway) rather than a scan of the whole reply.+ // Characters the rewrite left alone. Usually the rewrite is inside the live tail, and `slice`+ // shares the original's characters, so that case costs one native comparison plus a scan of the+ // tail (about to be re-lexed anyway) rather than a scan of the whole reply.const committedPrefix = this.source.slice(0, this.committedLength);const shared = hasPrefix(markdown, committedPrefix)? this.committedLength +@@ -1328,13 +1232,10 @@ export class IncrementalMarkdownCache {// at the last blank line the rewrite left intact.const safeLimit = lastBlankLineEnd(this.source, shared);- // A blank line is not a wall either: Marked merges a run of them into one- // separator block, so inserting a newline (as `\[...\]` -> `\n$$\n` does)- // re-segments the separator in front of it, and a list or indented code- // block reopens across one. So demand the same margin the append path- // requires -- ROLLBACK_BLOCKS blocks behind the boundary -- measured from- // the first changed character. Counting backwards costs only the blocks- // near the rewrite.+ // A blank line is not a wall either: Marked merges a run of them into one separator block, so+ // inserting a newline re-segments the separator in front of it, and a list or indented code block+ // reopens across one. So demand the same margin the append path requires, ROLLBACK_BLOCKS blocks+ // behind the boundary, measured from the first changed character.let blocksBeforeLimit = this.committedBlocks.length;let scanned = this.committedLength;while (blocksBeforeLimit > 0 && scanned > safeLimit) {@@ -1386,12 +1287,10 @@ export class IncrementalMarkdownCache {}update(rawMarkdown: string): IncrementalMarkdownRender {- // Every boundary this class finds is a byte offset into the text it was- // handed, but the blocks it compares against come back from Streamdown with- // their line endings already normalised. On a CRLF reply the two disagree- // one block in, `findCommitBoundary` sees `"para"` where the source holds- // `"para\r"`, nothing is ever committed, and the whole reply re-repairs and- // re-lexes on every frame. Normalise first so both sides speak LF.+ // Every boundary this class finds is a byte offset into the text it was handed, but the blocks it+ // compares against come back from Streamdown with their line endings already normalised. On a CRLF+ // reply the two disagree one block in, nothing is ever committed, and the whole reply re-repairs+ // and re-lexes on every frame. Normalise first so both sides speak LF.const markdown = normalizeLineEndings(rawMarkdown);// Tokens arrive faster than frames, so the coalescer hands the same text todiff --git a/studio/frontend/src/components/assistant-ui/thread-fast-copy.ts b/studio/frontend/src/components/assistant-ui/thread-fast-copy.tsindex 6381e5a6c57..8eb2995a773 100644--- a/studio/frontend/src/components/assistant-ui/thread-fast-copy.ts+++ b/studio/frontend/src/components/assistant-ui/thread-fast-copy.ts@@ -4,71 +4,46 @@/*** Copying a selection out of the thread, without paying for the styled clipboard flavour.*- * WHERE THE TIME GOES. Almost all of the cost of a copy on a long thread is the browser building- * the annotated `text/html` flavour, not extracting text. Measured on smoke-heavy-thread.html at- * the 100K rung -- the real Thread, 14,137 elements in the viewport, Chromium, five repetitions- * with the selection re-established before each -- a 40,626-character selection costs 347.0ms to- * copy, and producing the identical string ourselves costs 11.9ms. So: take the event, write the- * plain text ourselves, and the styled flavour is never built.+ * Almost all of the cost of a copy on a long thread is the browser building the annotated+ * `text/html` flavour, not extracting text: on smoke-heavy-thread.html at the 100K rung a+ * 40,626-character selection costs 347.0ms to copy and 11.9ms to produce ourselves. So take the+ * event, write the plain text ourselves, and the styled flavour is never built.** `Selection.toString()` IS NOT THE SAME STRING AS THE CLIPBOARD'S `text/plain`, and this file- * exists because of that. Blink builds the two with different `TextIteratorBehavior` flags:- *- * DOMSelection::toString() ForSelectionToString, SkipsUnselectableContent- * FrameSelection::SelectedTextForClipboard() SkipsUnselectableContent, EntersTextControls,- * IgnoresCssTextTransforms, EmitsImageAltText- *- * and `WebViewImpl::ApplyWebPreferences` turns `SetSelectionIncludesAltImageText(true)` on for- * every web view, so the alt-text one is not conditional in practice. The thirty-one constructs- * in tests/studio/_thread_fast_copy_constructs.py were copied one at a time on Playwright's- * Chromium and WebKit and pasted back, and the clipboard differs from `toString()` in exactly- * four places:- *- * construct chromium webkit what is done here- * img[alt] emits the alt text emits the alt text REPRODUCED- * U+00A0 becomes a space becomes a space REPRODUCED- * text-transform ignored (source text) applied (rendered) REPRODUCED (chromium)- * input/textarea/ value emitted, as its value omitted REFUSED- * select own block- *- * Everything else -- block boundaries, whitespace collapsing, `user-select: none`, generated- * content, tables, lists, `<pre>`, `<br>`, entities, emoji -- is identical, because it is the- * same iterator. So this does NOT reimplement the iterator. It patches the enumerated deltas- * into the live DOM inside one synchronous turn of the copy event, asks the engine for its own- * `toString()`, and puts everything back. Every semantic not on that list stays right by+ * exists because of that: Blink builds them with different `TextIteratorBehavior` flags, and+ * `WebViewImpl::ApplyWebPreferences` turns `SetSelectionIncludesAltImageText(true)` on for every+ * web view. Copying the thirty-one constructs in tests/studio/_thread_fast_copy_constructs.py one+ * at a time on Chromium and WebKit found exactly four divergences: img[alt] emits alt text (both,+ * REPRODUCED), U+00A0 becomes a space (both, REPRODUCED), text-transform is ignored on chromium+ * and applied on webkit (REPRODUCED for chromium), and a form control's value is emitted as its+ * own block on chromium and omitted on webkit (REFUSED). Everything else is identical because it+ * is the same iterator, so this does NOT reimplement the iterator: it patches the enumerated+ * deltas into the live DOM inside one synchronous turn of the copy event, asks the engine for its+ * own `toString()`, and puts everything back. Every semantic not on that list stays right by* construction, which a hand-written walker could not promise.*- * WHY THIS RUNS ON ONE ENGINE FAMILY. WebKit's `toString()` appends trailing block breaks its- * clipboard does not carry, and the count depends on what the selection ends with: +2 after a- * paragraph or a heading, +1 after a div, list, `<pre>` or blockquote, +0 after a table or an- * inline. That is the iterator's block-boundary emission, which is exactly the open-ended part- * this avoids. Chromium's delta is +0 in all eleven endings measured. A clipboard that is- * silently wrong is worse than a clipboard that is slow, so an engine whose mapping has not been- * proven gets the browser's own copy. The check is a BEHAVIOURAL probe of `toString()`, not a- * version test; the user agent narrows it further and is never allowed to decide what bytes are- * produced.+ * ONE ENGINE FAMILY ONLY. WebKit's `toString()` appends trailing block breaks its clipboard does+ * not carry, and the count depends on what the selection ends with (+2 after a paragraph or+ * heading, +1 after a div, list, `<pre>` or blockquote, +0 after a table or an inline). Chromium's+ * delta is +0 in all eleven endings measured. A silently wrong clipboard is worse than a slow one,+ * so an unproven engine gets the browser's own copy. The check is a BEHAVIOURAL probe of+ * `toString()`, not a version test; the user agent narrows it further and never decides bytes.*- * WHY A FORM CONTROL IS REFUSED rather than reproduced. Chromium emits a control's value AND- * treats it as its own block, and the break depends on the control: a text input lands as- * "value\n", a select as "\nvalue\n". That is the same block-boundary problem. Measured on the- * real thread at the 100K rung, the viewport contains ZERO form controls, so the refusal costs- * nothing that exists -- and a password field would copy as its mask, where guessing the glyph- * wrong would put a real password on the clipboard.+ * A FORM CONTROL IS REFUSED rather than reproduced, because chromium's emission carries a+ * control-dependent block break ("value" then a break for a text input, breaks on both sides for a+ * select). The 100K-rung viewport contains ZERO form controls, so the refusal costs nothing that+ * exists, and a password field would copy as its mask, where guessing the glyph wrong would put a+ * real password on the clipboard.*- * WHAT THIS DOES NOT COVER. A document-wide Ctrl+A does not route through here, and moving the- * listener to the document would not change that. The copy event targets the node the selection- * starts in, which for a whole-document selection is the first row of the sidebar, so a viewport- * listener never sees it (measured in both engines) -- but a document listener that did see it- * would refuse anyway, because that selection spans the composer's textarea. What is fixed here- * is the case that dominates a session: dragging a selection across a long stretch of the- * conversation.+ * NOT COVERED: a document-wide Ctrl+A, which targets the first sidebar row rather than the+ * viewport (measured in both engines) and would be refused anyway for spanning the composer's+ * textarea. Moving the listener to the document changes neither.*- * WHY NOT SERIALISE THE MESSAGE STORE. Building the text from the store is faster still, because- * nothing is read out of the DOM at all. It also changes what lands on the clipboard: role- * headings, thinking markers and tool lines the DOM selection never contained. That trade is- * worth making on a virtualized list, where the DOM physically cannot select an unmounted- * message. On the shipped, fully mounted list it buys only speed, at the cost of handing the- * user a different document than the one they highlighted.+ * NOT SERIALISED FROM THE MESSAGE STORE, which would be faster still but puts role headings,+ * thinking markers and tool lines on the clipboard that the DOM selection never contained. That+ * trade is worth making on a virtualized list, where the DOM cannot select an unmounted message;+ * on the shipped fully mounted list it only hands the user a different document than they+ * highlighted.*//** Why a copy was left to the browser. Named so a test can assert the reason, not just the miss. */@@ -87,11 +62,9 @@ export type ThreadCopyDecision =/*** A copy event, structurally. The GATE needs no DOM, so its branches can be unit tested against- * plain objects. The SERIALISER below is the part that must be proven in a browser against a- * real clipboard, and is, by tests/studio/playwright_thread_fast_copy.py, which builds THIS- * module and, per construct, sets what it produces against what the engine's own copy puts on- * the clipboard: Chromium must match byte for byte, WebKit must refuse, and its refusal must be- * backed by a divergence the same run measures.+ * plain objects. The SERIALISER below must be proven in a browser against a real clipboard, and is,+ * by tests/studio/playwright_thread_fast_copy.py: per construct, Chromium must match byte for byte+ * and WebKit must refuse with a divergence the same run measures.*/export type CopyEventLike = {readonly defaultPrevented: boolean;@@ -134,16 +107,12 @@ function matchesAncestor(target: unknown, selectors: string): boolean {}/**- * The smallest subtree the checks have to be right about.- *- * The range's common ancestor, not the viewport, and the difference is what makes this worth- * shipping: a thread with one `<textarea>` open anywhere would otherwise never take the fast- * path again, however far from it the user selected. The common ancestor is by definition a- * superset of the selected content, so scanning it is an over-approximation -- it can only ever- * refuse a copy the fast path could have taken, never accept one it could not.- *- * A range that ends in a text node has no `querySelector` of its own, hence the parent. Anything- * unrecognisable falls back to the viewport, which is the conservative direction.+ * The smallest subtree the checks have to be right about: the range's common ancestor, not the+ * viewport. That difference is what makes this worth shipping, since one open `<textarea>`+ * anywhere would otherwise cost the fast path for the whole thread. The common ancestor is a+ * superset of the selected content, so scanning it can only refuse a copy the fast path could have+ * taken, never accept one it could not. A range ending in a text node has no `querySelector`, hence+ * the parent; anything unrecognisable falls back to the viewport, the conservative direction.*/function scopeOf(selection: SelectionLike,@@ -169,17 +138,13 @@ function scopeOf(/*** Does this engine's clipboard agree with its own `toString()` about trailing block breaks?+ * A hidden paragraph is selected and `toString()` asked whether it appends one: Chromium says "a",+ * WebKit says "a" plus two breaks. Cached, since the answer cannot change within a document.*- * A hidden paragraph is selected and `toString()` asked whether it appends one. Chromium says- * "a"; WebKit says "a\n\n". Cached, because the answer cannot change within a document, and run- * with the user's own selection saved and restored around it.- *- * The restore goes through `restoreSelection`, the serialiser's, and for the same reason: this- * path also takes the selection away and rebuilds it, so rebuilding from ranges alone would flip- * a selection the user dragged upwards. The text copied would still be right and their highlight- * would silently reverse, which is the more annoying half of the bug -- the next Shift+Arrow then- * moves the far end. Reached on a plain drag right-to-left, and on the FIRST copy of a document,- * since the answer is cached afterwards.+ * The restore goes through the serialiser's `restoreSelection` for the same reason it does there:+ * rebuilding from ranges alone flips a selection the user dragged upwards, so the text would be+ * right while their highlight silently reversed and the next Shift+Arrow moved the far end.+ * Reached on a plain right-to-left drag, and on the FIRST copy of a document.*/export function engineClipboardIsMapped(view: Window & typeof globalThis,@@ -225,23 +190,20 @@ export function engineClipboardIsMapped(/*** The two deltas that are reproduced, patched into the live DOM and taken straight back out.- *- * Returns the undo list rather than doing its own cleanup, so the caller can guarantee the- * restore runs even if `toString()` throws. Nothing here paints: the whole sequence is one- * synchronous turn of the copy event, so the user never sees the patched document.+ * Returns the undo list rather than cleaning up itself, so the caller can guarantee the restore+ * runs even if `toString()` throws. Nothing here paints: the whole sequence is one synchronous+ * turn of the copy event.*//*** Put an element's `style` attribute back exactly as it was found, including not being there.- ** `style.removeProperty` is not the inverse of `style.setProperty` at the serialisation level,* which is the level a DOM comparison works at.*//**- * Would the clipboard's own iterator emit this image's alt text?- *- * `SkipsUnselectableContent` and ordinary rendering rules mean an image that is not displayed,- * not visible or not selectable contributes nothing. `visibility` and `user-select` inherit, so- * the computed style already answers for an ancestor that set them.+ * Would the clipboard's own iterator emit this image's alt text? `SkipsUnselectableContent` and+ * ordinary rendering rules mean an image that is not displayed, not visible or not selectable+ * contributes nothing. `visibility` and `user-select` inherit, so the computed style already+ * answers for an ancestor that set them.*/function nativeWouldEmitAlt(image: HTMLImageElement): boolean {const computed = getComputedStyle(image);@@ -258,11 +220,10 @@ function restoreStyleAttribute(element: Element, had: string | null): void {return;}// `removeAttribute("style")` DOES NOT REMOVE IT once the inline declaration has been touched.- // Measured in Chromium: setProperty then removeAttribute leaves `style=""` on the element and- // in its serialisation, and calling removeAttribute twice does not help, nor does clearing- // `cssText` first. Removing the attribute NODE does work. The residue is invisible to a user- // and visible to every DOM comparison, and it is permanent: it survives the copy that caused- // it, so a thread accumulates one per element the fast path ever touched.+ // Measured in Chromium: setProperty then removeAttribute leaves `style=""` on the element and in+ // its serialisation, twice does not help, nor does clearing `cssText` first. Removing the+ // attribute NODE does work. The residue is invisible to a user, visible to every DOM comparison,+ // and permanent, so a thread accumulates one per element the fast path ever touched.try {element.attributes.removeNamedItem("style");} catch {@@ -273,54 +234,43 @@ function restoreStyleAttribute(element: Element, had: string | null): void {function patchClipboardDeltas(root: Element): Array<() => void> {const undo: Array<() => void> = [];- // IgnoresCssTextTransforms: the clipboard carries the SOURCE text.- //- // ROOT ITSELF, not only its descendants. A selection lying entirely inside- // `<span class="uppercase">text</span>` has that span as its common ancestor, and- // `querySelectorAll("*")` does not include the element it is called on, so the transform was- // missed and the TRANSFORMED text was written where the clipboard carries the source text.- // Raised in review and reproduced against the real clipboard before it was fixed: the three- // cases now in tests/studio/_thread_fast_copy_constructs.py under INSIDE_SCOPE all failed.- // `text-transform` inherits, so `getComputedStyle(root)` already reports a transform set on- // any ancestor above the scope, and no walk upwards is needed.+ // IgnoresCssTextTransforms: the clipboard carries the SOURCE text. ROOT ITSELF, not only its+ // descendants. A selection lying entirely inside `<span class="uppercase">text</span>` has that+ // span as its common ancestor and `querySelectorAll("*")` excludes the element it is called on,+ // so the TRANSFORMED text was written where the clipboard carries the source (the INSIDE_SCOPE+ // cases in tests/studio/_thread_fast_copy_constructs.py all failed). `text-transform` inherits,+ // so `getComputedStyle(root)` already reports a transform set on any ancestor above the scope.const scoped: HTMLElement[] = [];if (root instanceof HTMLElement) scoped.push(root);scoped.push(...Array.from(root.querySelectorAll<HTMLElement>("*")));for (const element of scoped) {const transform = getComputedStyle(element).textTransform;if (!TRANSFORMED.has(transform)) continue;- // THE RAW ATTRIBUTE, not the property. Going through `style.removeProperty` restores the- // computed value and does NOT restore the serialisation: an element that had no `style`- // attribute is left carrying `style=""`, and one that had `style="text-transform:uppercase"`- // gets it rewritten as `style="text-transform: uppercase;"`. Neither is visible to a user- // and both are visible to any DOM comparison, so every copy silently rewrote the document.- // Caught by the structural parity digest, which reported six actions differing against a- // null that matched fifteen of sixteen.+ // THE RAW ATTRIBUTE, not the property. `style.removeProperty` restores the computed value and NOT+ // the serialisation: an element that had no `style` attribute is left carrying `style=""`, and one+ // that had `style="text-transform:uppercase"` gets it rewritten with a space and a semicolon.+ // Invisible to a user, visible to any DOM comparison, so every copy silently rewrote the document.const had = element.getAttribute("style");element.style.setProperty("text-transform", "none", "important");undo.push(() => restoreStyleAttribute(element, had));}- // EmitsImageAltText: the clipboard carries the alt text, which is not in the DOM as text.- //- // THE HOLDER MUST NOT HAVE A BOX. Unsloth's message images are display:block, so an inline- // holder placed beside one sits between two blocks, the engine wraps it in an anonymous block,- // and the alt text arrives with a leading newline the real clipboard does not have. That was- // measured on the real thread as 40,650 characters against the clipboard's 40,648, two images- // each contributing one extra break. Taking the image out of the flow removes the box the- // break came from, and an image contributes no text of its own, so hiding it changes nothing- // else.+ // EmitsImageAltText: the clipboard carries the alt text, which is not in the DOM as text. THE+ // HOLDER MUST NOT HAVE A BOX. Unsloth's message images are display:block, so an inline holder+ // beside one sits between two blocks, the engine wraps it in an anonymous block, and the alt text+ // arrives with a leading newline the real clipboard does not have (measured on the real thread as+ // 40,650 characters against 40,648, two images each contributing one extra break). Taking the+ // image out of the flow removes the box the break came from, and an image contributes no text of+ // its own, so hiding it changes nothing else.for (const image of Array.from(root.querySelectorAll<HTMLImageElement>("img[alt]"),)) {const alt = image.getAttribute("alt");if (!alt) continue;- // ONLY AN IMAGE THE NATIVE ITERATOR WOULD EMIT. Chromium skips an image that is not- // rendered or not selectable, so inserting its alt text unconditionally ADDS text the- // clipboard never carried. Measured against the real clipboard: `display: none`,- // `visibility: hidden` and `user-select: none` all diverge, and so does Unsloth's own- // `ImagePreview`, which carries an `invisible` class until the image loads -- so copying- // across a message whose image had not finished loading gained an alt string.+ // ONLY AN IMAGE THE NATIVE ITERATOR WOULD EMIT. Chromium skips an image that is not rendered or+ // not selectable, so inserting alt text unconditionally ADDS text the clipboard never carried:+ // `display: none`, `visibility: hidden`, `user-select: none` and Unsloth's own `ImagePreview`,+ // which carries an `invisible` class until the image loads, all diverge.if (!nativeWouldEmitAlt(image)) continue;const had = image.getAttribute("style");image.style.setProperty("display", "none", "important");@@ -338,26 +288,20 @@ function patchClipboardDeltas(root: Element): Array<() => void> {/*** The string the browser would have put on the clipboard, produced without building the styled- * flavour. Proven byte-for-byte against Chromium's real clipboard over 31 selections -- the 23- * of the 31 constructs it answers, the other 8 being refused or copying nothing, plus two- * element-offset endpoints, three selections scoped to a transformed element and three partials- * -- and on the real thread at 40,648 characters.- *- * The selection is restored whatever happens, because a copy that quietly moved the user's- * highlight would be a worse bug than the one being fixed.+ * flavour. Proven byte-for-byte against Chromium's real clipboard over 31 selections (the 23+ * constructs it answers, two element-offset endpoints, three scoped to a transformed element and+ * three partials) and on the real thread at 40,648 characters. The selection is restored whatever+ * happens, because a copy that quietly moved the user's highlight would be the worse bug.*//*** A selection's DIRECTION, and only its direction.*- * Deliberately not the endpoints. Capturing raw offsets and restoring them was wrong: the alt- * holders are inserted BEFORE their images, so an endpoint expressed as an element/child offset- * in the same parent points at a different child afterwards. Measured, with two images and a- * trailing text node selected by parent offsets 0..3: the clipboard carried- * `first catsecond cattail text` and we produced `first catsecond cat`, silently dropping the- * tail -- and because that is non-empty, the listener took the copy rather than handing it back.- *- * A cloned `Range` is live and its boundaries move with the DOM, so the ranges already hold the- * correct positions. All that is missing from them is which end the user dragged from.+ * Deliberately not the endpoints: the alt holders are inserted BEFORE their images, so an endpoint+ * expressed as an element/child offset in the same parent points at a different child afterwards.+ * Measured with two images and a trailing text node selected by parent offsets 0..3, the tail was+ * silently dropped, and because the result is non-empty the listener took the copy anyway. A+ * cloned `Range` is live and its boundaries move with the DOM, so the ranges already hold the+ * correct positions; only which end the user dragged from is missing from them.*/type SelectionDirection = { readonly backward: boolean };@@ -380,14 +324,12 @@ function captureDirection(selection: Selection): SelectionDirection {/*** Put the selection back the way it was, INCLUDING ITS DIRECTION.*- * A `Range` carries ordered boundaries and nothing else, so rebuilding with `addRange` always- * produces a forward selection. Measured: a selection dragged upwards came back with its anchor- * and focus swapped, so the user's next Shift+Arrow would move the opposite edge of it. Only the- * patched path ever rebuilds the selection, which is why this never showed on ordinary prose.- *- * `setBaseAndExtent` preserves direction and takes one anchor/focus pair, so a multi-range- * selection still falls back to `addRange`. Firefox is the only engine that produces those, and- * it is not an engine this fast path runs on.+ * A `Range` carries ordered boundaries and nothing else, so `addRange` always produces a forward+ * selection: a selection dragged upwards came back with anchor and focus swapped, so the user's+ * next Shift+Arrow moved the opposite edge. Only the patched path rebuilds the selection, which is+ * why this never showed on ordinary prose. `setBaseAndExtent` preserves direction but takes one+ * anchor/focus pair, so a multi-range selection still falls back to `addRange`; only Firefox+ * produces those, and this fast path does not run there.*/function restoreSelection(selection: Selection,@@ -446,10 +388,9 @@ export function faithfulSelectionText(}/**- * Should this copy be answered by us instead of the browser, and if not, why not?- *- * Pure, and every rejection carries its reason, because each branch is a distinct way of getting- * somebody's copy wrong and "the fast path did not run" is not enough to tell them apart.+ * Should this copy be answered by us instead of the browser, and if not, why not? Pure, and every+ * rejection carries its reason, because each branch is a distinct way of getting somebody's copy+ * wrong and "the fast path did not run" cannot tell them apart.*/export function decideThreadCopy(event: CopyEventLike,@@ -467,11 +408,10 @@ export function decideThreadCopy(return { kind: "native", reason: "no-clipboard-data" };}- // A copy out of a text control is that control's own selection, and `window.getSelection()` is- // not it: the document selection is usually collapsed or stale while a textarea has focus, so- // substituting it would replace the copied field with unrelated text. The thread viewport- // contains these -- a message being edited mounts a textarea -- so this cannot be left to the- // listener's placement.+ // A copy out of a text control is that control's own selection, and `window.getSelection()` is not+ // it: the document selection is usually collapsed or stale while a textarea has focus, so+ // substituting it replaces the copied field with unrelated text. The thread viewport contains these+ // (a message being edited mounts a textarea), so this cannot be left to the listener's placement.if (matchesAncestor(event.target, EDITABLE_ORIGIN)) {return { kind: "native", reason: "editable-origin" };}@@ -481,9 +421,8 @@ export function decideThreadCopy(return { kind: "native", reason: "empty-selection" };}- // A selection that starts inside the thread and runs out of it -- into the composer, the- // sidebar, the header -- has a common ancestor above the viewport. Its text is no longer- // something this file has proven, so it is not something this file should be rewriting.+ // A selection that starts inside the thread and runs out of it has a common ancestor above the+ // viewport. Its text is no longer something this file has proven.for (let index = 0; index < selection.rangeCount; index += 1) {if (!viewport.contains(selection.getRangeAt(index).commonAncestorContainer)@@ -506,11 +445,9 @@ export function decideThreadCopy(}/**- * Wire the decision to a live viewport. Returns the detach function.- *- * Only `copy` is listened for. A `cut` also has to mutate the document it cut from, and the- * thread is not editable, so a cut inside it is already a no-op and one inside a message being- * edited belongs to that textarea.+ * Wire the decision to a live viewport. Returns the detach function. Only `copy` is listened for:+ * a `cut` must also mutate the document it cut from, the thread is not editable, and one inside a+ * message being edited belongs to that textarea.*/export function attachThreadFastCopy(viewport: HTMLElement): () => void {const onCopy = (event: ClipboardEvent) => {diff --git a/studio/frontend/src/components/assistant-ui/thread-feature-flags.ts b/studio/frontend/src/components/assistant-ui/thread-feature-flags.tsindex f37e9b98610..a9677328f08 100644--- a/studio/frontend/src/components/assistant-ui/thread-feature-flags.ts+++ b/studio/frontend/src/components/assistant-ui/thread-feature-flags.ts@@ -8,7 +8,6 @@// `grid-template-rows` from `0fr` to `1fr` instead of animating `height` from `0` to// `--radix-collapsible-content-height`, and it uses a local collapsible primitive that never calls// `getBoundingClientRect`.-//// Both halves are required. The CSS variable is supplied by Radix's `CollapsibleContentImpl`,// whose `useLayoutEffect` writes `transitionDuration: 0s` / `animationName: none`, reads// `getBoundingClientRect()`, then writes the styles back -- on every `open` change,@@ -16,13 +15,11 @@// synchronous full-document layout, and Blink's layout is O(total layout objects) rather than// O(dirty objects), so it is charged the whole thread. Swapping only the keyframes leaves the// measurement exactly where it was; see `unmeasured-collapsible.tsx`.-//// Scoped to the reasoning pane. `tool-group.tsx`, `tool-fallback.tsx` and the shared// `components/ui/collapsible.tsx` default still animate height: `app-sidebar.tsx` keys its scroll// fade off `onAnimationEnd` with `animationName === "collapsible-down" | "collapsible-up"`, which a// transition does not fire, and changing three collapsibles at once would make an A/B on the// reasoning toggle unattributable.-//// ON. The A/B this comment was waiting for has run, on the standard tier at the 100K rung, four// repetitions across two independent waves, each wave carrying its own null control measured in// band under the same load. `reasoning_toggle.open_ms` cleared all three gates in BOTH waves:@@ -30,14 +27,12 @@// and the jank index cleared in the first wave and fell under its floor in the second, so the claim// here is narrow: opening a reasoning pane on a long thread gets meaningfully cheaper, and nothing// else was shown to move.-//// The screenshots this comment asked for were taken, on two production builds of the same commit// differing only in this boolean. Collapsed, the two panes are byte-identical PNGs. Expanded, they// differ in 25 pixels along one text baseline at a maximum channel delta of 2/255, which is// antialiasing. `textContent` is byte-identical in both states, 23,965 characters expanded.// Geometry matches to the sub-pixel: root 744x5937.38 and content 718x5896.25 on both arms, the// grid row resolving `1fr` to exactly the height Radix measures.-//// The parity digest does report a difference, and it is real rather than noise: the per-message// structural signature is 209 characters shorter, entirely within `[data-slot="reasoning-root"]`.// It is accounted for to the byte: -242 from the class list (Radix's eight animation and durationdiff --git a/studio/frontend/src/components/assistant-ui/tool-arg-text.ts b/studio/frontend/src/components/assistant-ui/tool-arg-text.tsindex 2752da558d1..aff620d42c2 100644--- a/studio/frontend/src/components/assistant-ui/tool-arg-text.ts+++ b/studio/frontend/src/components/assistant-ui/tool-arg-text.ts@@ -29,10 +29,9 @@ export const toolArgText = (value: unknown): string => {if (typeof value === "string") return value;try {if (typeof value === "object") {- // SERIALISED, not coerced: `String({"toString":null})` throws "Cannot- // convert object to primitive value", the exact crash this stops. JSON- // also shows what arrived, which "[object Object]" never did.- // `?? ""` because a `toJSON` returning undefined makes stringify do so.+ // SERIALISED, not coerced: `String({"toString":null})` throws "Cannot convert object to+ // primitive value", the exact crash this stops. JSON also shows what arrived, which "[object+ // Object]" never did. `?? ""` because a `toJSON` returning undefined makes stringify do so.const json = JSON.stringify(value) ?? "";return json.length > MAX_SERIALISED_LENGTH? `${json.slice(0, MAX_SERIALISED_LENGTH)}…`@@ -42,10 +41,9 @@ export const toolArgText = (value: unknown): string => {// (ECMA-262 22.1.1.1), `${sym}` throws.return String(value);} catch {- // Load-bearing, not defensive. All three engines parse 4,000,000 levels of- // nesting; Firefox then throws "InternalError: too much recursion" and- // Safari a RangeError out of JSON.stringify where Chrome succeeds. Keep the- // binding bare: Firefox's is not a RangeError.+ // Load-bearing, not defensive. All three engines parse 4,000,000 levels of nesting; Firefox+ // then throws "InternalError: too much recursion" and Safari a RangeError out of JSON.stringify+ // where Chrome succeeds. Keep the binding bare: Firefox's is not a RangeError.return "";}};diff --git a/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx b/studio/frontend/src/components/assistant-ui/tool-code-cell.tsxindex fc5f04b3dfa..1b148d68d27 100644--- a/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx@@ -62,9 +62,8 @@ export function CopyBtn({ text }: { text: string }) {}function DownloadBtn({ code, name }: { code: string; name: string }) {- // Route through the shared boundary: browsers keep the normal download,- // Tauri gets the native save chooser. A bare blob anchor is silently- // dropped by the desktop WebView2.+ // Route through the shared boundary: browsers keep the normal download, Tauri gets the native+ // save chooser. A bare blob anchor is silently dropped by the desktop WebView2.const download = useCallback(() => {void downloadFile(code, name, "text/plain;charset=utf-8").catch((error) => {if (!isDownloadCancelled(error)) {diff --git a/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx b/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsxindex 3b43bc55cbd..30a5053cf28 100644--- a/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx@@ -80,9 +80,8 @@ export function ToolConfirmationControls({decision,);if (ok) {- // Only hide the controls once the backend confirms it matched the- // pending call -- otherwise the generation would stay blocked with- // no way to retry.+ // Only hide the controls once the backend confirms it matched the pending call --+ // otherwise the generation would stay blocked with no way to retry.setDecided(true);clearToolConfirmation(toolCallId);} else {@@ -104,22 +103,20 @@ export function ToolConfirmationControls({}}, [showControls, autoAllowed, pending, failed, resolve]);- // ⏎ / Esc, only while this card is asking: an auto-approved one answers- // itself. Off route the chat pane is hidden rather than unmounted, so- // without the active check a bare key would decide a request nobody can- // see. With a second request parked, in the other Compare pane or further- // up the thread, the chord has no way to say which one it means, so both- // cards fall back to their buttons.+ // ⏎ / Esc, only while this card is asking: an auto-approved one answers itself. Off route the+ // chat pane is hidden rather than unmounted, so without the active check a bare key would decide+ // a request nobody can see. With a second request parked, in the other Compare pane or further up+ // the thread, the chord has no way to say which one it means, so both cards fall back to their+ // buttons.const chatActive = useChatActive();const soleRequest = useChatRuntimeStore((s) => Object.keys(s.toolConfirmations).length === 1,);- // A sidebar selection answers Escape already, and that listener does not- // consume the key, so both would run off one press and deny a call the user- // was only dismissing a selection with. Escape there costs nothing to undo- // and this does not, so this is the one that waits. Enter goes with it: the- // buttons are still there, and a card that takes half its keys is worse to- // explain than one that takes none.+ // A sidebar selection answers Escape already, and that listener does not consume the key, so both+ // would run off one press and deny a call the user was only dismissing a selection with. Escape+ // there costs nothing to undo and this does not, so this is the one that waits. Enter goes with+ // it: the buttons are still there, and a card that takes half its keys is worse to explain than+ // one that takes none.const selectionActive = useChatNavigationStore((s) => s.selectionActive);const keyboardReady =chatActive &&@@ -153,11 +150,10 @@ export function ToolConfirmationControls({{enabled: keyboardReady,skipInTextFields: true,- // A request usually arrives with the composer still focused from the- // prompt that caused it, and Escape types nothing there, so the gate- // would hold the decline back at the one moment it is most wanted. Enter- // above gets no such pass: that key sends. Every other field keeps its- // Escape, the queued-prompt editor and the settings search included.+ // A request usually arrives with the composer still focused from the prompt that caused it,+ // and Escape types nothing there, so the gate would hold the decline back at the one moment+ // it is most wanted. Enter above gets no such pass: that key sends. Every other field keeps+ // its Escape, the queued-prompt editor and the settings search included.textFieldException: COMPOSER_INPUT_SELECTOR,},);diff --git a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx b/studio/frontend/src/components/assistant-ui/tool-fallback.tsxindex aa649e2125b..84131d9e5a8 100644--- a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx@@ -333,9 +333,8 @@ function ToolFallbackResult({}const imageResult = isMcpImageResult(result) ? result : null;- // Colourised CLIs (ls --color, grep --color, npm, cargo, pytest) emit SGR- // escapes that a plain <pre> cannot style; strip them so the pane stays- // readable (#7962).+ // Colourised CLIs (ls --color, grep --color, npm, cargo, pytest) emit SGR escapes that a plain+ // <pre> cannot style; strip them so the pane stays readable (#7962).const resultText = imageResult ? null : stringifyToolResult(result);return (diff --git a/studio/frontend/src/components/assistant-ui/tool-group.tsx b/studio/frontend/src/components/assistant-ui/tool-group.tsxindex fe809caf9e2..ad37967852b 100644--- a/studio/frontend/src/components/assistant-ui/tool-group.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-group.tsx@@ -64,10 +64,9 @@ function ToolGroupRoot({...props}: ToolGroupRootProps) {const collapsibleRef = useRef<HTMLDivElement>(null);- // Same treatment as ToolFallbackRoot. ToolGroupImpl passes `undefined`- // whenever it is not forcing the group open, so this uncontrolled state is- // what is on screen for most of a group's life -- without the sync, a group- // expanded by hand stays open while every card inside it closes.+ // Same treatment as ToolFallbackRoot. ToolGroupImpl passes `undefined` whenever it is not forcing+ // the group open, so this uncontrolled state is what is on screen for most of a group's life --+ // without the sync, a group expanded by hand stays open while every card inside it closes.const collapseByDefault = useChatPreferencesStore((state) => state.collapseToolActivityByDefault,);diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsxindex ba98f72c45d..439ef52e98d 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx@@ -101,8 +101,7 @@ const formatGeneratedImageLabel = (prompt: string): string => {: `Generated image: ${prompt}`;};-// Takes text: `size?.match` guards nullish only, so `"size": 1024` reached-// `.match` on a number.+// Takes text: `size?.match` guards nullish only, so `"size": 1024` reached `.match` on a number.const parseImageSize = (size: string,): { width: number; height: number } | null => {diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsxindex 2a6d506c3c9..35361dfc0df 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx@@ -135,12 +135,11 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({) : null;return (- // Status, output and images collapse from history; the executed script- // renders outside ToolFallbackContent so it stays visible on reopen- // (#7165) -- a script is an artifact, a one-line command is not.- // That holds only while collapseToolActivity is off; with it on the script- // moves inside the collapsible, behind one click. awaitingApproval is the- // exception: a decision about a script needs the script on screen.+ // Status, output and images collapse from history; the executed script renders outside+ // ToolFallbackContent so it stays visible on reopen (#7165) -- a script is an artifact, a+ // one-line command is not. That holds only while collapseToolActivity is off; with it on the+ // script moves inside the collapsible, behind one click. awaitingApproval is the exception: a+ // decision about a script needs the script on screen.<ToolFallbackRootdefaultOpen={isRunning}awaitingApproval={awaitingApproval}diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsxindex 3ca82ec95d9..653f7acb751 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx@@ -40,10 +40,9 @@ const TerminalToolUIImpl: ToolCallMessagePartComponent = ({// Args still streaming = the model is WRITING the command, not running it yet.const { propStatus } = useToolArgsStatus();const isWritingCommand = isRunning && propStatus.command === "streaming";- // A command that wrote files arrives as the python tool's structured shape;- // a plain string means it wrote none.- // The same test the adapter applies: a foreign result that merely has text- // would otherwise be rendered as that field alone.+ // A command that wrote files arrives as the python tool's structured shape; a plain string means+ // it wrote none. The same test the adapter applies: a foreign result that merely has text would+ // otherwise be rendered as that field alone.const structured = isSandboxToolResult(result)? (result as unknown as { text: string; sessionId?: string; files?: SandboxFile[] }): null;diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsxindex 9d8aee16f2a..00ccdab0035 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx@@ -102,9 +102,8 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({// object here, and .trim() on one crashes the card that was meant to show the call.const query = toolArgText((args as { query?: unknown })?.query);const url = toolArgText((args as { url?: unknown })?.url).trim();- // gpt-5.x agentic search: `open_page` carries a url, `find_in_page` a url and- // a pattern. Older streams send neither, so a url with a pattern is the same- // call by shape.+ // gpt-5.x agentic search: `open_page` carries a url, `find_in_page` a url and a pattern. Older+ // streams send neither, so a url with a pattern is the same call by shape.const pattern = toolArgText((args as { pattern?: unknown })?.pattern);const actionType = toolArgText((args as { action_type?: unknown })?.action_type,diff --git a/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx b/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsxindex be09f01bde6..eb905b6625e 100644--- a/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx+++ b/studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx@@ -45,21 +45,18 @@ const TOUCH_MOVE_THRESHOLD_PX = 4;// per-event) so slow 1px-per-event sources (middle-click autoscroll,// scrollbar drags, some trackpads) accumulate instead of slipping under.const UPWARD_DETACH_THRESHOLD_PX = 2;-// Window the viewport stays pinned through layout/content races. Extends-// on every resize/mutation, so streaming keeps it pinned; settles this-// long after the last change.+// Window the viewport stays pinned through layout/content races. Extends on every resize/mutation,+// so streaming keeps it pinned; settles this long after the last change.const FOLLOW_SETTLE_MS = 600;-// How often a quiet pinned frame re-checks layout for the rest of the follow-// window. Content can grow with no mutation record and no border-box resize-// (image decode, font-display: swap, a late KaTeX pass), and the-// MutationObserver below excludes style, so only a frame that reads layout-// notices. 100ms not every frame: six times fewer forced layouts, and the view-// is back on the bottom in ~115ms measured (timer plus the frame it schedules).+// How often a quiet pinned frame re-checks layout for the rest of the follow window. Content can+// grow with no mutation record and no border-box resize (image decode, font-display: swap, a late+// KaTeX pass), and the MutationObserver below excludes style, so only a frame that reads layout+// notices. 100ms not every frame: six times fewer forced layouts, and the view is back on the+// bottom in ~115ms measured (timer plus the frame it schedules).const SETTLE_CHECK_MS = 100;-// Max stabilizer compensation. Absorbs sub-frame transients (~5-15px shiki-// re-renders, ~8px action-bar drift). Larger shrinks are intentional-// content removals (delete, regenerate clear, reasoning collapse); padding-// those over leaves empty space, so above this we release and let+// Max stabilizer compensation. Absorbs sub-frame transients (~5-15px shiki re-renders, ~8px+// action-bar drift). Larger shrinks are intentional content removals (delete, regenerate clear,+// reasoning collapse); padding those over leaves empty space, so above this we release and let// autoscroll re-pin to the new height.const STABILIZER_MAX_PX = 64;@@ -210,18 +207,15 @@ export function useIntentAwareAutoScroll(): {const atBottomStrict = (): boolean =>distanceFromBottom() <= AT_BOTTOM_THRESHOLD_PX;- // Room to scroll upward. Guards wheel/touch detach: a gesture on a- // viewport with nothing above can't express intent to leave the- // bottom and must not flip userDetachedRef, else later streaming- // skips extendFollow and auto-follow stays dead for the session.+ // Room to scroll upward. Guards wheel/touch detach: a gesture on a viewport with nothing+ // above can't express intent to leave the bottom and must not flip userDetachedRef, else+ // later streaming skips extendFollow and auto-follow stays dead for the session.const canScrollUp = (): boolean => el.scrollTop > 0;- // True when a nested scrollable ancestor of the target (reasoning- // panel, tool output) has room above and will consume the upward- // delta before it reaches the viewport. Walk stops at the viewport,- // so only intermediate inner scrollers count. Without this, wheel/- // touchmove bubbling would falsely detach while reading a long- // reasoning pane mid-stream.+ // True when a nested scrollable ancestor of the target (reasoning panel, tool output) has+ // room above and will consume the upward delta before it reaches the viewport. Walk stops at+ // the viewport, so only intermediate inner scrollers count. Without this, wheel/ touchmove+ // bubbling would falsely detach while reading a long reasoning pane mid-stream.const innerScrollWillConsumeUpward = (target: EventTarget | null,): boolean => {@@ -277,10 +271,9 @@ export function useIntentAwareAutoScroll(): {// Hygiene, not correctness: `following` checks userDetached before `settling`, so a// queued check cannot re-pin anyway; it just should not sit on a timer.clearSettleCheck();- // The stabilizer only matters while pinning. Once the user- // scrolls up, drop residual padding so the bottom stays flush on- // return. Safe mid-content: shrinking scrollHeight can't cap their- // scrollTop.+ // The stabilizer only matters while pinning. Once the user scrolls up, drop residual+ // padding so the bottom stays flush on return. Safe mid-content: shrinking scrollHeight+ // can't cap their scrollTop.releaseStabilizer();maxContentHeight = el.scrollHeight;};@@ -359,25 +352,19 @@ export function useIntentAwareAutoScroll(): {requestTick();};- // Content inserted above the viewport by a progressive-mount widening.- // THIS HOOK OWNS scrollTop; the progressive mount only reports the height- // it put above the fold, so the two never both write.- //- // While the user is FOLLOWING there is deliberately nothing to do: the- // MutationObserver below already runs onLayoutChange -> pinIfFollowing in- // the same frame before paint, and since widening only prepends, "pin to- // the bottom" and "shift by the height inserted above" are the same pixel.- // Correcting here too would double the forced layouts per frame and its- // scroll event could re-attach a user who deliberately detached within- // RE_ATTACH_THRESHOLD_PX of the bottom.- //- // While the user is DETACHED nothing else moves the viewport: extendFollow- // early-returns, stabilize only rebases its high-water mark, and- // pinIfFollowing returns without scrolling. So this is the only actor, and- // without it the page slides down under the reader every widening frame.- //- // `behavior: "instant"` is required: the viewport carries `scroll-smooth`,- // so an animated write would still be in flight at the next frame's write.+ // Content inserted above the viewport by a progressive-mount widening. THIS HOOK OWNS+ // scrollTop; the progressive mount only reports the height it put above the fold, so the two+ // never both write. While the user is FOLLOWING there is deliberately nothing to do: the+ // MutationObserver below already runs onLayoutChange -> pinIfFollowing in the same frame+ // before paint, and since widening only prepends, "pin to the bottom" and "shift by the+ // height inserted above" are the same pixel. Correcting here too would double the forced+ // layouts per frame and its scroll event could re-attach a user who deliberately detached+ // within RE_ATTACH_THRESHOLD_PX of the bottom. While the user is DETACHED nothing else moves+ // the viewport: extendFollow early-returns, stabilize only rebases its high-water mark, and+ // pinIfFollowing returns without scrolling. So this is the only actor, and without it the+ // page slides down under the reader every widening frame. `behavior: "instant"` is required:+ // the viewport carries `scroll-smooth`, so an animated write would still be in flight at the+ // next frame's write.adjustImplRef.current = (deltaPx: number) => {if (!userDetachedRef.current) {return;@@ -386,12 +373,10 @@ export function useIntentAwareAutoScroll(): {el.scrollTo({ top: el.scrollTop + deltaPx, behavior: "instant" });}// Advance the intent bookkeeping whether or not anything was written.- //// With a write, this stops the scroll event it provokes from reading as// reader movement: the `delta > 0` branch below would re-attach a user// parked near the bottom and the next widening frame would yank them// down.- //// WITHOUT a write it matters just as much. When native scroll anchoring// absorbs a widening in full the correction is zero, but the browser// still moved scrollTop by the whole inserted height and still fires a@@ -455,12 +440,11 @@ export function useIntentAwareAutoScroll(): {extendFollow();}} else if (delta < 0 && !userDetachedRef.current) {- // Upward: sum across events to catch 1px-per-event sources- // (middle-click autoscroll, some trackpads) that slip under a- // per-event threshold. Count distance-from-bottom growth, not- // raw scrollTop delta: when content above collapses, browsers- // scroll-anchor so scrollTop and scrollHeight drop together and- // distance is unchanged. Those layout deltas must not flip intent.+ // Upward: sum across events to catch 1px-per-event sources (middle-click autoscroll, some+ // trackpads) that slip under a per-event threshold. Count distance-from-bottom growth,+ // not raw scrollTop delta: when content above collapses, browsers scroll-anchor so+ // scrollTop and scrollHeight drop together and distance is unchanged. Those layout deltas+ // must not flip intent.const distanceDelta = distanceNow - lastDistanceFromBottom;if (distanceDelta > 0) {upwardAccumulator += distanceDelta;@@ -478,27 +462,18 @@ export function useIntentAwareAutoScroll(): {requestTick();};- // Scroll stabilizer.- //- // Problem: when a trailing code block finalizes (shiki re-renders the- // <pre> with highlight spans), its height briefly dips then recovers.- // The dip shrinks `scrollHeight`, so the browser synchronously caps- // `scrollTop` to the new max — a one-frame upward jump, then a- // "snap back". Re-scrolling can't help: once scrollHeight drops the- // cap has happened and scrollTop can't exceed the new max.- //- // Fix: keep `scrollHeight` monotonic across the follow window. Track- // max content height (scrollHeight minus our padding) and write any- // shortfall into CSS var `--aui-scroll-stabilizer`, read by the- // viewport's padding-bottom. A 5px shrink grows padding 5px so the- // browser sees no scrollHeight change. Padding shrinks back to zero- // as content grows past its prior high-water mark.- //- // Self-contained: lives on the viewport element via a CSS variable,- // touching no other UI.- //- // Returns the post-adjustment scrollHeight so one layout read per- // observer callback feeds both stabilization and pinning.+ // Scroll stabilizer. Problem: when a trailing code block finalizes (shiki re-renders the+ // <pre> with highlight spans), its height briefly dips then recovers. The dip shrinks+ // `scrollHeight`, so the browser synchronously caps `scrollTop` to the new max — a one-frame+ // upward jump, then a "snap back". Re-scrolling can't help: once scrollHeight drops the cap+ // has happened and scrollTop can't exceed the new max. Fix: keep `scrollHeight` monotonic+ // across the follow window. Track max content height (scrollHeight minus our padding) and+ // write any shortfall into CSS var `--aui-scroll-stabilizer`, read by the viewport's+ // padding-bottom. A 5px shrink grows padding 5px so the browser sees no scrollHeight change.+ // Padding shrinks back to zero as content grows past its prior high-water mark.+ // Self-contained: lives on the viewport element via a CSS variable, touching no other UI.+ // Returns the post-adjustment scrollHeight so one layout read per observer callback feeds+ // both stabilization and pinning.const stabilize = (): number => {const sh = el.scrollHeight;const currentContent = sh - stabilizerPx;@@ -515,10 +490,9 @@ export function useIntentAwareAutoScroll(): {maxContentHeight = currentContent;}const shrink = maxContentHeight - currentContent;- // Large shrinks (over STABILIZER_MAX_PX) are intentional removals- // (delete, regenerate clear, reasoning collapse). Compensating- // would leave an empty gap, so release the stabilizer and rebase- // the high-water mark; the pinIfFollowing call below re-anchors to+ // Large shrinks (over STABILIZER_MAX_PX) are intentional removals (delete, regenerate+ // clear, reasoning collapse). Compensating would leave an empty gap, so release the+ // stabilizer and rebase the high-water mark; the pinIfFollowing call below re-anchors to// the new bottom.if (shrink > STABILIZER_MAX_PX) {maxContentHeight = currentContent;@@ -536,9 +510,8 @@ export function useIntentAwareAutoScroll(): {return currentContent + stabilizerPx;};- // Synchronous pin-to-bottom. Observer callbacks run after layout,- // before paint, so this scrollTo composites in the same frame as the- // triggering mutation.+ // Synchronous pin-to-bottom. Observer callbacks run after layout, before paint, so this+ // scrollTo composites in the same frame as the triggering mutation.const pinIfFollowing = (scrollHeight: number): void => {if (userDetachedRef.current) {return;@@ -567,17 +540,14 @@ export function useIntentAwareAutoScroll(): {const mutationObserver = new MutationObserver(onLayoutChange);const onViewportResize = onLayoutChange;- // Fresh attach always starts pinned. Rebinds to the SAME element must- // not pin or reset detach state: the Viewport's composed ref identity- // changes on re-render, so React re-runs the ref (null, then same- // element) on unrelated renders (composer resizes); pinning would- // yank the chat to bottom each time. Observers are re-installed either- // way.+ // Fresh attach always starts pinned. Rebinds to the SAME element must not pin or reset detach+ // state: the Viewport's composed ref identity changes on re-render, so React re-runs the ref+ // (null, then same element) on unrelated renders (composer resizes); pinning would yank the+ // chat to bottom each time. Observers are re-installed either way.if (!isRebind) {userDetachedRef.current = false;- // Pin on first attach, covering thread.initialize firing before the- // ref is bound.+ // Pin on first attach, covering thread.initialize firing before the ref is bound.extendFollow();if (el.scrollHeight > el.clientHeight) {el.scrollTo({ top: el.scrollHeight, behavior: "instant" });@@ -595,10 +565,9 @@ export function useIntentAwareAutoScroll(): {childList: true,subtree: true,characterData: true,- // Layout-affecting attributes only. Excludes `style` (elements may- // mutate it in response to viewport state → feedback loop). `class`- // catches Tailwind show/hide; the rest catch Radix/native- // collapsibles that change scrollHeight without a viewport resize.+ // Layout-affecting attributes only. Excludes `style` (elements may mutate it in response to+ // viewport state → feedback loop). `class` catches Tailwind show/hide; the rest catch+ // Radix/native collapsibles that change scrollHeight without a viewport resize.attributes: true,attributeFilter: ["class",diff --git a/studio/frontend/src/components/floating-monitor.tsx b/studio/frontend/src/components/floating-monitor.tsxindex 83103397582..ae1db35d8db 100644--- a/studio/frontend/src/components/floating-monitor.tsx+++ b/studio/frontend/src/components/floating-monitor.tsx@@ -162,9 +162,8 @@ function useMonitorLayout(constraintsElement: HTMLDivElement | null) {}const width = Math.min(desiredWidth, constraintsBox.width);- // Clamp position against the height actually rendered. A hand-resized- // panel keeps its own height and scrolls, so growing content must not- // drag it upwards and leave a gap below.+ // Clamp position against the height actually rendered. A hand-resized panel keeps its own+ // height and scrolls, so growing content must not drag it upwards and leave a gap below.const height = Math.min(monitor.style.height ? monitorBox.height : desiredHeight,constraintsBox.height,@@ -195,9 +194,8 @@ function useMonitorLayout(constraintsElement: HTMLDivElement | null) {});setLayout((current) => {- // Mid-drag the offset lives in a transform, and the measured box- // already includes it, so committing left/top here would apply it- // twice. finishDrag lands the position instead.+ // Mid-drag the offset lives in a transform, and the measured box already includes it, so+ // committing left/top here would apply it twice. finishDrag lands the position instead.const held = session && current ? current : null;const restLeft = held?.left ?? left;const restTop = held?.top ?? top;@@ -236,12 +234,11 @@ function useMonitorLayout(constraintsElement: HTMLDivElement | null) {};}, [constraintsElement, publisher]);- // ResizeObserver never fires for a position-only change, so dragging alone- // would leave the published frame at the monitor's old corner and the overlay- // stack dodging where it used to be. Re-publish once each layout is committed,- // which after a drag is on release: the frames in between are a transform, and- // republishing through them would re-render every overlay in the stack for- // each one, which is most of what made dragging feel heavy.+ // ResizeObserver never fires for a position-only change, so dragging alone would leave the+ // published frame at the monitor's old corner and the overlay stack dodging where it used to be.+ // Re-publish once each layout is committed, which after a drag is on release: the frames in+ // between are a transform, and republishing through them would re-render every overlay in the+ // stack for each one, which is most of what made dragging feel heavy.useLayoutEffect(() => {void layout;const monitor = monitorRef.current;@@ -304,10 +301,9 @@ function useMonitorLayout(constraintsElement: HTMLDivElement | null) {event.currentTarget.setPointerCapture(event.pointerId);}- // One paint per frame, and through a transform rather than left/top. The- // panel is backdrop-blurred, so every layout-driven move re-sampled what is- // behind it; a trackpad also reports moves faster than the display refreshes,- // so most of those renders were never shown.+ // One paint per frame, and through a transform rather than left/top. The panel is+ // backdrop-blurred, so every layout-driven move re-sampled what is behind it; a trackpad also+ // reports moves faster than the display refreshes, so most of those renders were never shown.function paintDrag() {dragFrameRef.current = 0;const session = dragSessionRef.current;@@ -483,14 +479,12 @@ function FloatingMonitorPanel({const hasGpu = (displayedGpu?.available ?? false) && devices.length > 0;- // The container sits on the floating panel layer, above the bottom-right- // overlay stack. The stack is anchored to that same corner and does not move- // for this monitor, so the two can overlap. The stack is passive status; this- // is a window being dragged, resized and closed, so it wins. Still below the- // startup screen and tooltips. See lib/z-layers.- //- // The API monitor panel shares this layer rather than sitting under it, and- // whichever of the two the user touched last is the one in front.+ // The container sits on the floating panel layer, above the bottom-right overlay stack. The stack+ // is anchored to that same corner and does not move for this monitor, so the two can overlap. The+ // stack is passive status; this is a window being dragged, resized and closed, so it wins. Still+ // below the startup screen and tooltips. See lib/z-layers. The API monitor panel shares this+ // layer rather than sitting under it, and whichever of the two the user touched last is the one+ // in front.return (<divref={setConstraintsElement}diff --git a/studio/frontend/src/components/model-memory-bar.tsx b/studio/frontend/src/components/model-memory-bar.tsxindex 2773e26cdbf..86715cb140d 100644--- a/studio/frontend/src/components/model-memory-bar.tsx+++ b/studio/frontend/src/components/model-memory-bar.tsx@@ -124,10 +124,9 @@ export function ModelMemoryBar({pressure,} = segments;const colors = SEGMENT_COLORS[pressure];- // Two failures, two fixes: oversized weights need a smaller quant, while a- // total that only overflows with context needs a shorter context or a- // quantized KV cache. Both get said -- staying silent on the first reads as- // "this is fine" on a model that can't load at all.+ // Two failures, two fixes: oversized weights need a smaller quant, while a total that only+ // overflows with context needs a shorter context or a quantized KV cache. Both get said --+ // staying silent on the first reads as "this is fine" on a model that can't load at all.const warning =segments.status === "model-exceeds"? t("modelMemory.tooLarge")diff --git a/studio/frontend/src/components/tauri/window-titlebar.tsx b/studio/frontend/src/components/tauri/window-titlebar.tsxindex 157c46eac7d..6915ca10b6c 100644--- a/studio/frontend/src/components/tauri/window-titlebar.tsx+++ b/studio/frontend/src/components/tauri/window-titlebar.tsx@@ -351,10 +351,9 @@ export function WindowTitlebar({{showSidebarSurface && (<divdata-slot="window-titlebar-decoration"- // Marks a consumer of --studio-sidebar-live-width. Only this and the- // header below read it, so PANEL_RESIZE_SCOPED_VARS_ENABLED writes- // the live width here instead of on the document element, where it- // would restyle the whole document once per drag frame.+ // Marks a consumer of --studio-sidebar-live-width. Only this and the header below read+ // it, so PANEL_RESIZE_SCOPED_VARS_ENABLED writes the live width here instead of on the+ // document element, where it would restyle the whole document once per drag frame.data-titlebar-live-width-scope=""aria-hidden="true"className="pointer-events-none absolute inset-x-0 top-[var(--studio-custom-titlebar-height)] z-[45] h-3"diff --git a/studio/frontend/src/components/ui/combobox.tsx b/studio/frontend/src/components/ui/combobox.tsxindex 07202d30aee..0e3d4ab34d9 100644--- a/studio/frontend/src/components/ui/combobox.tsx+++ b/studio/frontend/src/components/ui/combobox.tsx@@ -171,9 +171,8 @@ function ComboboxContent({data-chips={!!anchor}onWheel={(event) => {onWheel?.(event);- // Dialog scroll locks cancel native wheel scrolling on this- // body-portaled popup, so scroll the list by hand while one is- // active.+ // Dialog scroll locks cancel native wheel scrolling on this body-portaled popup, so+ // scroll the list by hand while one is active.if (!document.body.hasAttribute("data-scroll-locked")) return;const list = event.currentTarget.querySelector<HTMLElement>('[data-slot="combobox-list"]',diff --git a/studio/frontend/src/components/ui/copyable-error-chip.tsx b/studio/frontend/src/components/ui/copyable-error-chip.tsxindex b9759f111c2..62b6d62f2dc 100644--- a/studio/frontend/src/components/ui/copyable-error-chip.tsx+++ b/studio/frontend/src/components/ui/copyable-error-chip.tsx@@ -27,8 +27,7 @@ export function CopyableErrorChip({const [copied, setCopied] = useState(false);const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);- // Clear any pending reset on unmount to avoid a setState on an- // unmounted component.+ // Clear any pending reset on unmount to avoid a setState on an unmounted component.useEffect(() => () => {if (resetTimer.current) clearTimeout(resetTimer.current);}, []);diff --git a/studio/frontend/src/components/ui/input.tsx b/studio/frontend/src/components/ui/input.tsxindex 152c177e938..e8f1464d732 100644--- a/studio/frontend/src/components/ui/input.tsx+++ b/studio/frontend/src/components/ui/input.tsx@@ -6,8 +6,7 @@ import type * as React from "react";import { cn } from "@/lib/utils";const BASE_CLASSES =- // White fill with a subtle border,- // fully-rounded pill for single-row controls.+ // White fill with a subtle border, fully-rounded pill for single-row controls."bg-background border-border dark:border-transparent dark:bg-white/[0.06] focus-visible:border-ring dark:focus-visible:border-transparent dark:focus-visible:bg-white/[0.12] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 h-9 rounded-full border px-3.5 py-1 text-base transition-colors file:h-7 file:text-sm file:font-medium aria-invalid:ring-[3px] md:text-sm file:text-foreground placeholder:text-muted-foreground w-full min-w-0 outline-none file:inline-flex file:border-0 file:bg-transparent disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50";function stepNumberInput(input: HTMLInputElement, direction: 1 | -1): void {@@ -36,8 +35,7 @@ function stepNumberInput(input: HTMLInputElement, direction: 1 | -1): void {: Math.floor(pos);next = base + nextPos * step;} else {- // Stepping an empty, non-numeric field starts from the minimum, matching- // the native spinner.+ // Stepping an empty, non-numeric field starts from the minimum, matching the native spinner.next = min ?? direction * step;}if (min !== null) {diff --git a/studio/frontend/src/components/ui/panel-resize-handle.tsx b/studio/frontend/src/components/ui/panel-resize-handle.tsxindex 1f8648f4ec3..6a4bb6fa3de 100644--- a/studio/frontend/src/components/ui/panel-resize-handle.tsx+++ b/studio/frontend/src/components/ui/panel-resize-handle.tsx@@ -22,25 +22,19 @@ const CLICK_COMPAT_WINDOW_MS = 300/** Arrow-key resize step for keyboard users. */const RESIZE_STEP = 16-// A drag needs one cursor over the whole viewport, because the pointer travels-// across buttons and text that would otherwise claim their own. That used to be-// `html[data-panel-resizing] *` plus `cursor`/`user-select` on <body>. Both-// reach every element in the document: the universal selector matches all of-// them, and `cursor` and `user-select` are inherited, so writing them on <body>-// marks inherited style dirty for everything below it. The cost is therefore-// proportional to the STANDING DOM rather than to the one thing that changed,-// which is the same shape as the sidebar-width writes scoped in #9400/#9441.-//-// The same is true of the rule that blanked pointer events on the sidebar and-// on [data-slot="sidebar-inset"], the <main> holding the whole app including-// the thread: `pointer-events` is inherited too, so that write dirtied the-// thread's subtree on both flips as well.-//-// A single fixed element on top of the viewport does both jobs with an-// invalidation set of one element. It carries the cursor, and by being the hit-// test target for the whole viewport it keeps hover and click off the content-// underneath. It is transparent and it is removed the instant the drag ends, so-// nothing about what the user sees changes.+// A drag needs one cursor over the whole viewport, because the pointer travels across buttons and+// text that would otherwise claim their own. That used to be `html[data-panel-resizing] *` plus+// `cursor`/`user-select` on <body>. Both reach every element in the document: the universal+// selector matches all of them, and `cursor` and `user-select` are inherited, so writing them on+// <body> marks inherited style dirty for everything below it. The cost is therefore proportional to+// the STANDING DOM rather than to the one thing that changed, which is the same shape as the+// sidebar-width writes scoped in #9400/#9441. The same is true of the rule that blanked pointer+// events on the sidebar and on [data-slot="sidebar-inset"], the <main> holding the whole app+// including the thread: `pointer-events` is inherited too, so that write dirtied the thread's+// subtree on both flips as well. A single fixed element on top of the viewport does both jobs with+// an invalidation set of one element. It carries the cursor, and by being the hit test target for+// the whole viewport it keeps hover and click off the content underneath. It is transparent and it+// is removed the instant the drag ends, so nothing about what the user sees changes.const DRAG_OVERLAY_SLOT = "panel-resize-drag-overlay"/** Nested drags cannot happen through pointer capture, but a stuck overlay would* swallow the whole UI, so ownership is explicit rather than assumed. */@@ -57,9 +51,8 @@ function acquireDragOverlay(): void {const s = el.styles.position = "fixed"s.inset = "0"- // Top of the named scale, not a hand-picked large number: the rules it- // replaces were `!important` and blanked whole subtrees, so anything it did- // not out-rank it would only partly stand in for.+ // Top of the named scale, not a hand-picked large number: the rules it replaces were `!important`+ // and blanked whole subtrees, so anything it did not out-rank it would only partly stand in for.s.zIndex = String(Z_LAYER.DRAG_CURSOR_OVERLAY)s.background = "transparent"// Explicit, because it is load-bearing rather than incidental. Being the hitdiff --git a/studio/frontend/src/components/ui/panel-resize-recalc-flags.ts b/studio/frontend/src/components/ui/panel-resize-recalc-flags.tsindex 95a42671977..410baf142b8 100644--- a/studio/frontend/src/components/ui/panel-resize-recalc-flags.ts+++ b/studio/frontend/src/components/ui/panel-resize-recalc-flags.ts@@ -3,14 +3,12 @@// Panel-resize style-recalc flags, for staged rollout. The wiring stays in// place, so flipping a flag here is the only edit needed.-//// WHY. An unregistered CSS custom property inherits, so writing one marks// inherited style dirty for every descendant. `PanelResizeHandle` writes two of// them on every animation frame of a sidebar drag -- `--sidebar-width` on// `[data-slot="sidebar-wrapper"]` and `--studio-sidebar-live-width` on// `document.documentElement` -- and both are ancestors of the chat thread, so// each one restyles the whole document.-//// Measured on the heavy-thread harness (Chromium, `UpdateLayoutTree.elementCount`// from a devtools trace, median of 10 writes): the unscoped write is linear in// thread size, 4,286 elements / 67.9 ms at a 4,000-element thread up to 37,811 /@@ -20,33 +18,27 @@// 1,088.25 ms total become 12 per frame and 3.76 ms, with identical rendered// geometry at all 8 positions and --sidebar-width resolving the same at every// consumer.-//// Read those milliseconds as roughly 2.7x high: they come off the vite DEV// server, and the built production stylesheet costs 49.1 ms against 133.3 ms// over the same DOM. The mechanism is not a dev artefact -- unregistered// against `inherits: false` is 1333x on dev and 982x on prod, and elementCount// is a DOM property, identical on both.-//// CONFIRMED ON THE REAL APP before the flag was turned on, because the numbers// above come off a harness whose sidebar is nearly empty and whose document is// a third the size of a real one. Two production builds of the same commit// differing only in this boolean, served by the backend, 100K rung, 42,885// elements, five drags of eight frames each:-//// flag off 44,141 elements restyled per frame, 1,934.87 ms per drag// flag on 770 elements restyled per frame, 37.35 ms per drag-//// 57x fewer elements and 52x less recalc, or 241.9 ms per frame down to 4.67 --// the difference between roughly 4 fps and inside the 60 fps budget. Both arms// were checked for potency first (40/40 samples in the expected regime: off on// the wrapper and <html>, on at [data-slot="sidebar"] with no <html> write), so// neither reading is two identical builds wearing two labels. Geometry and// every computed width were identical across all 40 drag positions.-//// The harness's "12 elements" does NOT transfer: [data-slot="sidebar"] really// holds ~770 elements once the thread list is populated. The ratio is 57x, not// 1000x. Still worth having, but quote the 57x.-//// WHAT DOES NOT MEASURE THIS. studiobench cannot see this change at all: none of// its actions performs a pointer drag, so the per-frame write path is never// entered and every timing it reports for this flag is null by construction.@@ -55,7 +47,6 @@// path should. That null is not evidence the flag is inert; the drag measurement// above is the evidence, and UI parity over 64 action pairs against the same// concurrent null found 0 stable actions rendering differently.-//// WHY NOT `@property { inherits: false }`. That is right only for a property// whose sole consumer is the element written to (`--aui-scroll-stabilizer`).// Here it would silently break both: `--sidebar-width` is read by@@ -69,7 +60,6 @@// every consumer and not the thread, and `--studio-sidebar-live-width` to the// titlebar roots, which do not exist on a build without a custom titlebar,// where the write is skipped entirely.-//// NOT ADDRESSED BY THIS FLAG, measured so the next person need not:// `html[data-panel-resizing] *` (index.css:1604-1605) is a universal descendant// selector on `<html>` and restyles the whole document too, 37,818 elements /diff --git a/studio/frontend/src/components/ui/sidebar.tsx b/studio/frontend/src/components/ui/sidebar.tsxindex 7d8e095a691..175c095800f 100644--- a/studio/frontend/src/components/ui/sidebar.tsx+++ b/studio/frontend/src/components/ui/sidebar.tsx@@ -149,8 +149,7 @@ function SidebarProvider({return setOpen((open) => !open)}, [isMobile, setOpen, setOpenMobile, hasPinMode, togglePinnedProp])- // Chord comes from the shortcuts store, so Settings -> Shortcuts can rebind- // or clear it.+ // Chord comes from the shortcuts store, so Settings -> Shortcuts can rebind or clear it.useShortcut("toggleSidebar", toggleSidebar)// We add a state so that we can do data-state="expanded" or "collapsed".@@ -189,12 +188,11 @@ function SidebarProvider({data-slot="sidebar-wrapper"style={{- // The drag handle writes this same property live while resizing.- // Under PANEL_RESIZE_SCOPED_VARS_ENABLED it moves DOWN to- // [data-slot="sidebar"], which holds every consumer, and cannot- // also stay here: this wrapper is an ancestor of the chat thread,- // so a declaration left behind would keep restyling the thread on- // every render even once the drag-time write had moved.+ // The drag handle writes this same property live while resizing. Under+ // PANEL_RESIZE_SCOPED_VARS_ENABLED it moves DOWN to [data-slot="sidebar"], which holds+ // every consumer, and cannot also stay here: this wrapper is an ancestor of the chat+ // thread, so a declaration left behind would keep restyling the thread on every render+ // even once the drag-time write had moved....(PANEL_RESIZE_SCOPED_VARS_ENABLED? null: { "--sidebar-width": `${width}px` }),@@ -204,14 +202,12 @@ function SidebarProvider({}className={cn(// `has-[>...]`, not `has-[...]`, and the combinator is the whole point.- //// This wrapper is an ancestor of the chat thread, as the note on// --sidebar-width above already says. A `:has()` whose argument is a// DESCENDANT selector has to be re-checked whenever anything is// inserted or removed anywhere in the subject's subtree, and// answering it means WALKING that subtree. On an ancestor of the// thread that walk is the whole thread, on every mutation.- //// It is a traversal, NOT a restyle, and the difference matters// because it is why containment does not help. Blink's own// `UpdateLayoutTree.elementCount` for one inserted span is 1 with@@ -223,7 +219,6 @@ function SidebarProvider({// help. `content-visibility: auto` on the message roots does not// help either, measured at -7%: the argument re-check walks skipped// content too.- //// Measured at the 500K rung, corpus 23cd2464, on a 357,843-element// thread: appending one EMPTY span inside a message cost 17.5 and// 18.6 ms in two concurrent arms with this rule in place, 8.7 ms with@@ -231,7 +226,6 @@ function SidebarProvider({// chat-page.tsx deleted. Deleting the other eleven `:has()` rules// that survived the bisect changed nothing (17.2 / 19.2 ms), and the// same span appended to <body> costs 0.10 ms either way.- //// CHROMIUM ONLY. On a synthetic thread carrying this same ancestor// chain and the built Unsloth stylesheet, at 300,464 elements, one// inserted span costs 1.20 ms plain / 1.29 ms child / 5.63 ms one@@ -240,7 +234,6 @@ function SidebarProvider({// Firefox: flat in both, within noise of each other. So this change// is free where it does not help and it does not regress the engine// Unsloth uses on Linux.- //// The child combinator is not a weakening. `data-variant` is rendered// on the root element of `Sidebar` below, and `Sidebar` is a direct// child of this wrapper (AppSidebar returns it inside a Fragment,diff --git a/studio/frontend/src/components/ui/slider.tsx b/studio/frontend/src/components/ui/slider.tsxindex d3d39188efc..d5969694540 100644--- a/studio/frontend/src/components/ui/slider.tsx+++ b/studio/frontend/src/components/ui/slider.tsx@@ -116,11 +116,10 @@ function Slider({<SliderPrimitive.Thumbdata-slot="slider-thumb"key={index}- // The thumb is the element carrying role="slider", so the name and the- // spoken value belong here. Everything else spreads onto Root, which is- // a plain div: an aria-label passed to this component reached that div- // and left the actual control unnamed, and Radix only fills in a label- // of its own for multi-thumb ranges.+ // The thumb is the element carrying role="slider", so the name and the spoken value+ // belong here. Everything else spreads onto Root, which is a plain div: an aria-label+ // passed to this component reached that div and left the actual control unnamed, and+ // Radix only fills in a label of its own for multi-thumb ranges.aria-label={props["aria-label"]}aria-labelledby={props["aria-labelledby"]}aria-valuetext={thumbValueText?.(values[index] ?? min, index)}diff --git a/studio/frontend/src/components/ui/sonner.tsx b/studio/frontend/src/components/ui/sonner.tsxindex 4c65edc4b74..ca5f81cdd22 100644--- a/studio/frontend/src/components/ui/sonner.tsx+++ b/studio/frontend/src/components/ui/sonner.tsx@@ -12,10 +12,9 @@ import { useTheme } from "@/features/settings/stores/theme-store";import { createLoadingToastIcon } from "@/lib/toast";import { Toaster as Sonner, type ToasterProps } from "sonner";-// Make toast text selectable. Sonner's onPointerDown calls setPointerCapture(),-// which steals the drag and blocks text selection. dismissible:false would stop-// it but also kills the close button. So we swallow pointerdown on toast text-// (never on its buttons) before sonner sees it.+// Make toast text selectable. Sonner's onPointerDown calls setPointerCapture(), which steals the+// drag and blocks text selection. dismissible:false would stop it but also kills the close button.+// So we swallow pointerdown on toast text (never on its buttons) before sonner sees it.const handleToastPointerDownCapture = (event: React.PointerEvent<HTMLDivElement>,) => {diff --git a/studio/frontend/src/components/ui/tooltip-modal-layer.ts b/studio/frontend/src/components/ui/tooltip-modal-layer.tsindex f16e506ba04..f285027f808 100644--- a/studio/frontend/src/components/ui/tooltip-modal-layer.ts+++ b/studio/frontend/src/components/ui/tooltip-modal-layer.ts@@ -22,11 +22,10 @@ export function isBlockedByActiveModal(element: HTMLElement): boolean {}// Whether a modal layer is up at all, shared by every tooltip. Radix sets body pointer-events to-// none while one is, which is also when a hovered trigger stops receiving pointerleave, so an-// open tooltip hangs over the dialog with nothing able to close it.-//-// Two observers, because the questions cost differently: "is a modal up" is one attribute on one-// node; "which layer owns a trigger" needs the whole subtree, and only matters while one is up.+// none while one is, which is also when a hovered trigger stops receiving pointerleave, so an open+// tooltip hangs over the dialog with nothing able to close it. Two observers, because the questions+// cost differently: "is a modal up" is one attribute on one node; "which layer owns a trigger"+// needs the whole subtree, and only matters while one is up.let modalLayerUp = false;const modalLayerListeners = new Set<() => void>();let bodyLayerObserver: MutationObserver | null = null;diff --git a/studio/frontend/src/components/ui/tooltip.tsx b/studio/frontend/src/components/ui/tooltip.tsxindex 324450383df..ae56db7c9b5 100644--- a/studio/frontend/src/components/ui/tooltip.tsx+++ b/studio/frontend/src/components/ui/tooltip.tsx@@ -174,10 +174,9 @@ function Tooltip({if (!clickOpen) return;const release = (event: Event) => {const target = event.target as Node | null;- // The trigger is matched by element, not by data-slot: an `asChild` child- // can drop the attribute (a component that does not spread props), and- // then a press on this very trigger read as outside, cleared the pin, and- // the click handler toggled it straight back on.+ // The trigger is matched by element, not by data-slot: an `asChild` child can drop the+ // attribute (a component that does not spread props), and then a press on this very trigger+ // read as outside, cleared the pin, and the click handler toggled it straight back on.if (target && modalBlockStore.getTriggerElement()?.contains(target)) {return;}@@ -275,9 +274,8 @@ function TooltipTrigger({type TooltipVariant = "default" | "rich" | "none";-// `default` applies the compact black-pill styling shared with the-// sidebar/chat icon labels. `rich` opts into the larger multi-row-// popover surface used for timing/context breakdowns. `none` is an+// `default` applies the compact black-pill styling shared with the sidebar/chat icon labels. `rich`+// opts into the larger multi-row popover surface used for timing/context breakdowns. `none` is an// escape hatch for tooltips that need to bring their own surface.function TooltipContent({variant = "default",@@ -289,10 +287,9 @@ function TooltipContent({}: React.ComponentProps<typeof TooltipPrimitive.Content> & {variant?: TooltipVariant;}) {- // Single-line compact tooltips render as a full pill; wrapped ones keep- // the squarer corners so tall pills do not look like capsules. A ref- // callback measures on mount: Radix mounts the portal content without- // re-rendering this wrapper, so an effect here would never see the node.+ // Single-line compact tooltips render as a full pill; wrapped ones keep the squarer corners so+ // tall pills do not look like capsules. A ref callback measures on mount: Radix mounts the portal+ // content without re-rendering this wrapper, so an effect here would never see the node.const contentRef = useCallback((el: React.ComponentRef<typeof TooltipPrimitive.Content> | null) => {assignRef(ref, el);diff --git a/studio/frontend/src/components/ui/unmeasured-collapsible.tsx b/studio/frontend/src/components/ui/unmeasured-collapsible.tsxindex 17e9db903f3..2584ecc6dbb 100644--- a/studio/frontend/src/components/ui/unmeasured-collapsible.tsx+++ b/studio/frontend/src/components/ui/unmeasured-collapsible.tsx@@ -2,12 +2,9 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0// A collapsible that never measures its content.-//// WHY THIS EXISTS, and why swapping the keyframes alone would not have worked.-//// Radix's `CollapsibleContentImpl` runs this on every `open` change (react-collapsible 1.1.12,// dist/index.mjs, verbatim shape):-//// useLayoutEffect(() => {// const node = ref.current;// if (node) {@@ -19,7 +16,6 @@// ... // write back// }// }, [context.open, present]);-//// It publishes the result as `--radix-collapsible-content-height`, which the// `animate-collapsible-down` / `animate-collapsible-up` keyframes consume. The read is// UNCONDITIONAL: it does not check whether any stylesheet references the variable. So replacing the@@ -27,13 +23,11 @@// measurement and leaves the measurement itself untouched. The forced layout stays, and with it the// full-document relayout that Blink charges for it, because Blink's layout is O(total layout// objects) and not O(dirty objects).-//// Hence a local primitive. It keeps Radix's public shape -- `data-state`, `data-disabled`,// `aria-expanded`, `aria-controls`, the generated content id, `hidden` when closed, and children// unmounted while closed -- and drops only the measurement, because with `0fr -> 1fr` there is// nothing left to measure: `1fr` resolves against the content on its own, every frame, including// while the content is still streaming in.-//// Two things the grid technique requires, and it silently does not collapse without them:// * the animating child must be `min-height: 0`, or its automatic minimum size floors the row at// the content's height and `0fr` never reaches zero;diff --git a/studio/frontend/src/components/web/update-banner.tsx b/studio/frontend/src/components/web/update-banner.tsxindex f0b4cc8f8cb..4b36753ad8e 100644--- a/studio/frontend/src/components/web/update-banner.tsx+++ b/studio/frontend/src/components/web/update-banner.tsx@@ -12,9 +12,8 @@ import { Download } from "lucide-react";import { AnimatePresence, motion } from "motion/react";import { type ReactElement, useEffect, useRef, useState } from "react";-// macOS, Linux and WSL update via the POSIX installer; only native Windows-// (PowerShell) needs the irm one-liner. Any non-windows device_type (incl. wsl)-// resolves to the curl command below.+// macOS, Linux and WSL update via the POSIX installer; only native Windows (PowerShell) needs the+// irm one-liner. Any non-windows device_type (incl. wsl) resolves to the curl command below.const STUDIO_INSTALL_UNIX_CMD = "curl -fsSL https://unsloth.ai/install.sh | sh";const STUDIO_INSTALL_WINDOWS_CMD = "irm https://unsloth.ai/install.ps1 | iex";const RELEASE_NOTES_URL = "https://unsloth.ai/docs/new/changelog";diff --git a/studio/frontend/src/config/env.ts b/studio/frontend/src/config/env.tsindex ef77b7e1a98..5ed4259e7ff 100644--- a/studio/frontend/src/config/env.ts+++ b/studio/frontend/src/config/env.ts@@ -90,13 +90,12 @@ export const usePlatformStore = create<PlatformState>()((_, get) => ({},}));-// Once an authoritative (server-reported) platform has been fetched, a-// non-forced response must not overwrite it. The post-render fetchDeviceType()-// in main.tsx runs before auth is ready and can resolve after the authed-// root-route/provider fetches; such a late write would reset deviceType,-// cloudflareUrl/serverUrl/secure, and fetched, whether it is a browser fallback-// (unauthenticated) or an earlier authenticated request that landed after a-// later forced refresh. Forced refreshes are explicit re-reads, so they still write.+// Once an authoritative (server-reported) platform has been fetched, a non-forced response must not+// overwrite it. The post-render fetchDeviceType() in main.tsx runs before auth is ready and can+// resolve after the authed root-route/provider fetches; such a late write would reset deviceType,+// cloudflareUrl/serverUrl/secure, and fetched, whether it is a browser fallback (unauthenticated)+// or an earlier authenticated request that landed after a later forced refresh. Forced refreshes+// are explicit re-reads, so they still write.function shouldKeepAuthoritativePlatform(force?: boolean): boolean {return !force && usePlatformStore.getState().fetched;}@@ -167,12 +166,11 @@ export async function fetchDeviceType(options?: {server_url?: string | null;secure?: boolean;};- // Once the store holds an authoritative (server-reported) platform, a- // non-forced response must not overwrite it. It may be an unauthenticated- // fallback, or an earlier authenticated request that resolved after a- // later forced refresh already picked up device_type and the tunnel- // fields; writing either would reset device type or null the tunnel- // fields. Forced refreshes are explicit re-reads, so they still write.+ // Once the store holds an authoritative (server-reported) platform, a non-forced response+ // must not overwrite it. It may be an unauthenticated fallback, or an earlier authenticated+ // request that resolved after a later forced refresh already picked up device_type and the+ // tunnel fields; writing either would reset device type or null the tunnel fields. Forced+ // refreshes are explicit re-reads, so they still write.if (shouldKeepAuthoritativePlatform(options?.force)) {return usePlatformStore.getState().deviceType;}@@ -212,10 +210,9 @@ export async function fetchDeviceType(options?: {return deviceType;}} catch {- // Backend not ready: use client-side detection so chat-only guard works- // on initial load (important for macOS). Keep fetched=false so a later- // call retries against the backend. But a late non-forced failure must not- // wipe an authoritative platform that already resolved.+ // Backend not ready: use client-side detection so chat-only guard works on initial load+ // (important for macOS). Keep fetched=false so a later call retries against the backend. But a+ // late non-forced failure must not wipe an authoritative platform that already resolved.if (shouldKeepAuthoritativePlatform(options?.force)) {return usePlatformStore.getState().deviceType;}diff --git a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsxindex b7783e9a5c9..b16eb53779d 100644--- a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx+++ b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx@@ -245,19 +245,17 @@ export function ApiMonitorOverlay(): ReactElement | null {// that it stays where it was put, even if that is on top of the monitor.const [panelElement, setPanelElement] = useState<HTMLDivElement | null>(null);const [placedByUser, setPlacedByUser] = useState(false);- // Bumped when the panel has moved without its anchor changing: the entry- // animation is a transform, and the box the stack keeps clear of has to be- // the one on screen.+ // Bumped when the panel has moved without its anchor changing: the entry animation is a+ // transform, and the box the stack keeps clear of has to be the one on screen.const [settledAt, setSettledAt] = useState(0);const { anchor, covered, place } = usePanelAnchor(panelElement,placedByUser,settledAt,);- // The drag offset, owned here rather than left to motion, so it can be folded- // back into the anchor on release. Left as a transform it would be applied on- // top of every later clamp, and the published box would stay at the corner- // the panel was dragged away from.+ // The drag offset, owned here rather than left to motion, so it can be folded back into the+ // anchor on release. Left as a transform it would be applied on top of every later clamp, and the+ // published box would stay at the corner the panel was dragged away from.const dragX = useMotionValue(0);const dragY = useMotionValue(0);@@ -292,10 +290,9 @@ export function ApiMonitorOverlay(): ReactElement | null {const visible = isOpen && !onFullPage;const serverStatus = data?.status ?? "idle";- // A panel that has just opened is the one the user is being shown, so it- // comes to the front. Touching either panel afterwards brings that one- // forward instead, which is the only way out of a resource monitor resized- // over the whole viewport.+ // A panel that has just opened is the one the user is being shown, so it comes to the front.+ // Touching either panel afterwards brings that one forward instead, which is the only way out of+ // a resource monitor resized over the whole viewport.useEffect(() => {if (visible) {raisePanel("api-monitor");diff --git a/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsxindex e897a04cbaa..ad4a2ff4203 100644--- a/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx+++ b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx@@ -62,9 +62,8 @@ function describeOverride(override: ApiModelOverride): string[] {if (override.spec_draft_cache_type) {parts.push(`draft KV ${override.spec_draft_cache_type}`);}- // Both compared against undefined rather than tested for truth: 0 is a value the- // user can pick for either (no checkpoints, no host cache) and would otherwise- // be listed as unset.+ // Both compared against undefined rather than tested for truth: 0 is a value the user can pick+ // for either (no checkpoints, no host cache) and would otherwise be listed as unset.if (override.ctx_checkpoints !== undefined) {parts.push(plural(override.ctx_checkpoints, "checkpoint"));}diff --git a/studio/frontend/src/features/api-monitor/panel-placement.ts b/studio/frontend/src/features/api-monitor/panel-placement.tsindex fb54228551a..a59bed159d7 100644--- a/studio/frontend/src/features/api-monitor/panel-placement.ts+++ b/studio/frontend/src/features/api-monitor/panel-placement.ts@@ -127,12 +127,11 @@ function candidates(const steps = [...obstacles].sort((a, b) => b.top - a.top).map((box) => ({ left: right, top: box.top - PANEL_GAP - size.height }));- // The corner each candidate came from, kept rather than inferred back out of- // its coordinates. A 400px panel in a 768px window is anchored right at- // left=352, which is left of the midpoint, so reading the side off `left`- // ranked the right-hand corner as a left-hand refuge. Being first, it then- // won the tie and the panel stayed exactly where it was, over the Close- // button and the resize grip this fallback exists to keep reachable.+ // The corner each candidate came from, kept rather than inferred back out of its coordinates. A+ // 400px panel in a 768px window is anchored right at left=352, which is left of the midpoint, so+ // reading the side off `left` ranked the right-hand corner as a left-hand refuge. Being first, it+ // then won the tie and the panel stayed exactly where it was, over the Close button and the+ // resize grip this fallback exists to keep reachable.const ordered: Array<PanelAnchor & { rightSide: boolean }> = [{ left: right, top: bottom, rightSide: true },...steps.map((step) => ({ ...step, rightSide: true })),@@ -145,9 +144,8 @@ function candidates(return {anchor: placed,clearRank: index,- // Left half first, and within a half the bottom first: this panel and- // the stack both live along the bottom edge, so a refuge up top is the- // bigger surprise.+ // Left half first, and within a half the bottom first: this panel and the stack both live+ // along the bottom edge, so a refuge up top is the bigger surprise.refugeRank:(anchor.rightSide ? 2 : 0) +(placed.top > viewport.height / 2 ? 0 : 1),diff --git a/studio/frontend/src/features/api-monitor/use-panel-anchor.ts b/studio/frontend/src/features/api-monitor/use-panel-anchor.tsindex f3cc8fcadde..43d4b7176f0 100644--- a/studio/frontend/src/features/api-monitor/use-panel-anchor.ts+++ b/studio/frontend/src/features/api-monitor/use-panel-anchor.ts@@ -80,10 +80,9 @@ export function usePanelAnchor(setSize(null);return;}- // offsetWidth/offsetHeight, not the bounding rect: the panel animates in- // from scale 0.94, and a rect measured through that transform is 6% short.- // Placed against it, the panel then overhangs the right edge of the screen- // once the animation lands.+ // offsetWidth/offsetHeight, not the bounding rect: the panel animates in from scale 0.94, and a+ // rect measured through that transform is 6% short. Placed against it, the panel then overhangs+ // the right edge of the screen once the animation lands.const measure = () => {const width = element.offsetWidth;const height = element.offsetHeight;@@ -136,10 +135,9 @@ export function usePanelAnchor([commit, size, viewport],);- // Publish where it actually landed, so the notification stack steps over this- // panel the same way it steps over the resource monitor. Measured rather than- // derived from the anchor, because before the first anchor is committed the- // panel is still sitting on its CSS corner.+ // Publish where it actually landed, so the notification stack steps over this panel the same way+ // it steps over the resource monitor. Measured rather than derived from the anchor, because+ // before the first anchor is committed the panel is still sitting on its CSS corner.useLayoutEffect(() => {const { setFrame, clearFrame } = useMonitorFrameStore.getState();if (!element) {diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsxindex 503c82dc823..2d112316dc8 100644--- a/studio/frontend/src/features/audio/audio-page.tsx+++ b/studio/frontend/src/features/audio/audio-page.tsx@@ -1,9 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// The Audio page: Generate (TTS via the main inference slot) and Transcribe (STT via the-// dictation sidecar). The page stays mounted across tab switches (see __root.tsx), so `active`-// gates polling, popovers and the recorder rather than lifecycle.+// The Audio page: Generate (TTS via the main inference slot) and Transcribe (STT via the dictation sidecar).+// The page stays mounted across tab switches (see __root.tsx), so `active` gates polling, popovers and the+// recorder rather than lifecycle.import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";import {@@ -346,10 +346,9 @@ export function AudioPage({const [audioInstructions, setAudioInstructions] = useState("");const [audioLanguage, setAudioLanguage] = useState("");const [temperature, setTemperature] = useState(0.6);- // Sending temperature unconditionally puts it in the request's model_fields_set, which the- // backend reads as an explicit client override that beats the per-model recommendation, so- // only send it once the user has moved the slider.- // Spark-TTS wants 0.8, OuteTTS 0.4, so only send it once the user has moved the slider.+ // Sending temperature unconditionally puts it in the request's model_fields_set, which the backend reads as an+ // explicit client override that beats the per-model recommendation (Spark-TTS wants 0.8, OuteTTS 0.4), so only+ // send it once the user has moved the slider.const [temperatureEdited, setTemperatureEdited] = useState(false);const handleTemperatureChange = useCallback((value: number) => {setTemperatureEdited(true);@@ -434,11 +433,10 @@ export function AudioPage({const sttStatusRefreshGeneration = useRef(0);const sttLoadGeneration = useRef(0);const sttLoadingGeneration = useRef<number | null>(null);- // Residency is not ownership: the activation resync adopts whatever a sidecar already holds,- // including a model chat dictation loaded. The identity, not a boolean, since another- // surface can replace the sidecar's model while Audio is inactive and a bare flag would claim- // that too. Keyed on the model alone, since a "gguf" pick without whisper-server comes back- // resident under the Transformers fallback.+ // Residency is not ownership: the activation resync adopts whatever a sidecar already holds, including a model+ // chat dictation loaded. The identity, not a boolean, since another surface can replace the sidecar's model+ // while Audio is inactive and a bare flag would claim that too. Keyed on the model alone, since a "gguf" pick+ // without whisper-server comes back resident under the Transformers fallback.const sttLoadedByThisPage = useRef<string | null>(null);const sttLoadAbort = useRef<AbortController | null>(null);const deferredSttLoad = useRef<{@@ -643,9 +641,9 @@ export function AudioPage({forget();return;}- // Forget only once the sidecar is actually released: clearing first left a failed unload with the- // model in VRAM and no Eject to retry with. Scoped to the model this page claimed, since- // another surface can switch the same engine before the request lands.+ // Forget only once the sidecar is actually released: clearing first left a failed unload with the model in+ // VRAM and no Eject to retry with. Scoped to the model this page claimed, since another surface can switch the+ // same engine before the request lands.await unloadSttModel(sttEngineForRepoId(selected), claim);forget();await refreshSttStatus();@@ -853,7 +851,6 @@ export function AudioPage({};}, [active, refreshGallery]);- // The selected clip needs its bytes before the player can play it.useEffect(() => {const clip = clips.find((c) => c.id === selectedId);if (clip) void ensureClipSrc(clip);@@ -878,10 +875,9 @@ export function AudioPage({async (repoId: string,ggufFilename?: string | null,- // Where the weights actually are: a row cached in a NON-ACTIVE HF cache is loadable only by its- // snapshot path, which the picker supplies as meta.loadId, and sending the display repo id- // instead failed offline or re-downloaded into the active cache. Chat threads the same field- // (chat-page.tsx).+ // Where the weights actually are: a row cached in a NON-ACTIVE HF cache is loadable only by its snapshot path,+ // which the picker supplies as meta.loadId, and sending the display repo id instead failed offline or+ // re-downloaded into the active cache. Chat threads the same field (chat-page.tsx).loadId?: string | null,audioType?: string | null,remoteCodeApproval?: RemoteCodeApproval,@@ -901,9 +897,8 @@ export function AudioPage({};return;}- // A load stops every chat on the shared llama-server, so ask the way Chat does instead of- // dead-ending on the backend's 409. Claimed before the await: a routed pick arriving while- // the dialog is open must queue.+ // A load stops every chat on the shared llama-server, so ask the way Chat does instead of dead-ending on the+ // backend's 409. Claimed before the await: a routed pick arriving while the dialog is open must queue.ttsLoadInFlight.current = true;// Chat's gate, held across the question and the load. Without it a queue can materialize while// the dialog is open, outside the snapshot the answer was given for.@@ -945,9 +940,9 @@ export function AudioPage({const pending = {generation,repoId,- // What the request actually sent. Cancelling under the display id works only when the load target- // is a standard HF cache snapshot; a pinned directory elsewhere does not match and- // _cancel_scoped_load_attempt then refuses.+ // What the request actually sent. Cancelling under the display id works only when the load target is a+ // standard HF cache snapshot; a pinned directory elsewhere does not match and _cancel_scoped_load_attempt then+ // refuses.loadTarget: loadId || repoId,loadRequestId,controller,@@ -999,9 +994,8 @@ export function AudioPage({trust_remote_code: trustRemoteCode,approved_remote_code_fingerprint: approvedRemoteCodeFingerprint,audio_device: wantsCpu ? "cpu" : "auto",- // GGUF ignores audio_device: llama.cpp offloads unless told not to.- // An absent speculative_type resolves to "auto", which may attach a GPU- // drafter, and the backend then evicts image/video for a CPU load.+ // GGUF ignores audio_device: llama.cpp offloads unless told not to. An absent speculative_type resolves to+ // "auto", which may attach a GPU drafter, and the backend then evicts image/video for a CPU load....(wantsCpu && isGgufLoad? // biome-ignore lint/style/useNamingConvention: API schema{@@ -1016,9 +1010,9 @@ export function AudioPage({runtime: "tts",onRequestStart: () => {pending.requestStarted = true;- // Queued prompts would otherwise start on the model this load replaces. Only once /load is- // actually going out: loadModel returns without sending when a stored token is invalid, and- // cancelling earlier threw away accepted sends for a swap that never happened.+ // Queued prompts would otherwise start on the model this load replaces. Only once /load is actually going+ // out: loadModel returns without sending when a stored token is invalid, and cancelling earlier threw away+ // accepted sends for a swap that never happened.cancelPreStreamRunReservations(stopDecision.preStreamRunTokens);requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds);},@@ -1063,9 +1057,8 @@ export function AudioPage({releaseLifecycle();busyRef.current = null;setBusy(null);- // Only while Audio is visible: replaying unconditionally started a load with activeRef already- // false, which the deactivation effect never saw to cancel, so a hidden page could replace- // the model Chat had loaded.+ // Only while Audio is visible: replaying unconditionally started a load with activeRef already false, which+ // the deactivation effect never saw to cancel, so a hidden page could replace the model Chat had loaded.if (activeRef.current) replayQueuedTtsPick();}},@@ -1262,9 +1255,9 @@ export function AudioPage({}}- // Hub TTS picks use the same managed path as Chat. Native models can also depend on a second- // codec repository, so the selected repo's downloaded badge is not enough: the cache-aware- // backend plan owns every missing file.+ // Hub TTS picks use the same managed path as Chat. Native models can also depend on a second codec+ // repository, so the selected repo's downloaded badge is not enough: the cache-aware backend plan owns every+ // missing file.if (meta.source === "hub" && !ggufFilename) {let plan;try {@@ -1372,9 +1365,9 @@ export function AudioPage({selectedSttRepoRef.current === repoId;setBusy("loading");- // Ownership is claimed only once the requested model is actually resident: claiming it up front- // meant a cancelled download left the flag set while the backend kept the previous model, so- // leaving Transcribe unloaded another surface's model.+ // Ownership is claimed only once the requested model is actually resident: claiming it up front meant a+ // cancelled download left the flag set while the backend kept the previous model, so leaving Transcribe+ // unloaded another surface's model.const toastId = toast.loading(`Preparing ${sidecarKey}…`);try {try {@@ -1576,11 +1569,10 @@ export function AudioPage({if (!transitionMode("speak")) return;// Serialize against a Transcribe release started by that transition.const releaseInFlight = pendingTranscribeRelease.current;- // A release that failed leaves the sidecar resident, so do not stack a speech model on top of- // it. Back to Transcribe, where Eject can retry.- // Claimed before the await below, not after: the button only disables on `busy`, so a slow release- // let several clicks through, each resuming into its own generateAudio while generateAbort- // tracked only the last.+ // A release that failed leaves the sidecar resident, so do not stack a speech model on top of it: back to+ // Transcribe, where Eject can retry. Claimed before the await below, not after: the button only disables on+ // `busy`, so a slow release let several clicks through, each resuming into its own generateAudio while+ // generateAbort tracked only the last.if (releaseInFlight && !(await releaseInFlight)) {setMode("transcribe");return;@@ -1809,9 +1801,8 @@ export function AudioPage({setBusy("unloading");void (async () => {try {- // Ejecting stops every chat on the shared llama-server, and unforced the backend refused with a- // 409 the user could only read. Nothing is torn down until the answer is in, so declining- // leaves the page as it was.+ // Ejecting stops every chat on the shared llama-server, and unforced the backend refused with a 409 the+ // user could only read. Nothing is torn down until the answer is in, so declining leaves the page as it was.const stopDecision = await confirmStopRunningChatsIfNeeded("Unloading the model","unload",@@ -1866,11 +1857,10 @@ export function AudioPage({const handleGenerate = useCallback(async () => {const text = prompt.trim();if (!text) return;- // Same gate the TTS load path uses: switching straight from Transcribe with a speech model- // already resident needs no load, so nothing else waits for the sidecar teardown, and- // generating beside a dictation model OOMs a device that fits either alone. Claimed before- // the await below, since the button only disables on `busy` and a slow release let several- // clicks each resume into their own generateAudio.+ // Same gate the TTS load path uses: switching straight from Transcribe with a speech model already resident+ // needs no load, so nothing else waits for the sidecar teardown, and generating beside a dictation model OOMs a+ // device that fits either alone. Claimed before the await below, since the button only disables on `busy` and a+ // slow release let several clicks each resume into their own generateAudio.if (busyRef.current) return;busyRef.current = "generating";setBusy("generating");@@ -1921,9 +1911,9 @@ export function AudioPage({setFallbackClip(null);selectClip(generatedClip.id);} else if (generated.clip_id) {- // The server did persist it; only this refresh missed it. Select the id so a later refresh shows- // the real record, but keep the response audio too: selectedClip resolves against `clips`,- // so an id that is not there yet would render the empty state.+ // The server did persist it; only this refresh missed it. Select the id so a later refresh shows the real+ // record, but keep the response audio too: selectedClip resolves against `clips`, so an id that is not there+ // yet would render the empty state.setFallbackClip({url: `data:audio/wav;base64,${generated.audio.data}`,prompt: text,@@ -2239,9 +2229,8 @@ export function AudioPage({[dropClip, refreshGallery],);- // This page stays mounted across route changes, so a restore from the Settings archive would not- // reach History until a reload. Refresh the loaded window, not just the first page: a clip- // re-enters at its own age.+ // This page stays mounted across route changes, so a restore from the Settings archive would not reach+ // History until a reload. Refresh the loaded window, not just the first page: a clip re-enters at its own age.useEffect(() =>subscribeGalleryChanged("audio", () => {diff --git a/studio/frontend/src/features/auth/components/auth-form.tsx b/studio/frontend/src/features/auth/components/auth-form.tsxindex 989732ea5bd..f4829680249 100644--- a/studio/frontend/src/features/auth/components/auth-form.tsx+++ b/studio/frontend/src/features/auth/components/auth-form.tsx@@ -112,9 +112,8 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {let canceled = false;async function initializeAuthForm(): Promise<void> {- // Always check the server first; localStorage flags can be stale (e.g.- // tokens from a previous install). /api/auth/status is the source of- // truth for requires_password_change.+ // Always check the server first; localStorage flags can be stale (e.g. tokens from a previous+ // install). /api/auth/status is the source of truth for requires_password_change.try {const response = await fetch(apiUrl("/api/auth/status"));if (!response.ok) throw new Error("Failed to load auth status.");@@ -146,8 +145,7 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {return;}- // On login, skip to the app if a valid session exists and no- // password change is required.+ // On login, skip to the app if a valid session exists and no password change is required.if (isLoginMode && !result.requires_password_change) {if (hasRefreshToken()) {const refreshed = await refreshSession();diff --git a/studio/frontend/src/features/chat/adapters/pcm-recorder.ts b/studio/frontend/src/features/chat/adapters/pcm-recorder.tsindex db9d5b31185..c78c73fa548 100644--- a/studio/frontend/src/features/chat/adapters/pcm-recorder.ts+++ b/studio/frontend/src/features/chat/adapters/pcm-recorder.ts@@ -109,8 +109,7 @@ function createAudioContext(): AudioContext {return new Ctx({ sampleRate: TARGET_SAMPLE_RATE });} catch {// Some engines only open a context at the device rate. The backend resamples whatever it is- // given, so that is still correct, just larger on the wire, which secondsWithin() accounts- // for.+ // given, so that is still correct, just larger on the wire, which secondsWithin() accounts for.return new Ctx();}}diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 27693be2288..4a46dc5b1af 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -108,10 +108,10 @@ export class StreamInterruptedError extends Error {/** Thrown when a reasoning model consumes its output budget before emitting any standard content,* so the chat UI can explain a completed stream holding only a thinking panel. */export class GenerationLengthError extends Error {- /** @param maxTokensWasSet whether the user actually configured a Max Tokens value. With Max Tokens- * on "Max" the backend already requests the whole context length, so generation stops at the- * context wall and "Increase Max Tokens" cannot be followed. The false branch also covers a- * finite cap the prompt left no room for, hence the wording about raising the cap. */+ /** @param maxTokensWasSet whether the user actually configured a Max Tokens value. With Max Tokens on "Max"+ * the backend already requests the whole context length, so generation stops at the context wall and+ * "Increase Max Tokens" cannot be followed. The false branch also covers a finite cap the prompt left no room+ * for, hence the wording about raising the cap. */constructor(maxTokensWasSet = true) {super(maxTokensWasSet@@ -828,10 +828,10 @@ export async function getChatThread(threadId: string,options: { bounded?: boolean; timeoutMs?: number; signal?: AbortSignal } = {},): Promise<ThreadRecord | null> {- // Bounded for the delete reconciliation: an unbounded read there would hang the delete the write- // timeout exists to keep moving. `timeoutMs` is for a caller with a deadline of its own,- // since the settings pairing gives up long before the write timeout and each retry otherwise- // left the previous attempt running. `signal` ends it earlier still.+ // Bounded for the delete reconciliation: an unbounded read there would hang the delete the write timeout+ // exists to keep moving. `timeoutMs` is for a caller with a deadline of its own, since the settings pairing+ // gives up long before the write timeout and each retry otherwise left the previous attempt running. `signal`+ // ends it earlier still.const timeout =options.bounded || options.timeoutMs !== undefined? disposableTimeoutSignal(options.timeoutMs ?? THREAD_WRITE_TIMEOUT_MS)@@ -883,9 +883,9 @@ export interface UpdateChatThreadOptions {expectedTitle?: string;/** And only while this is still the thread's opening user message. */expectedOpeningMessageId?: string;- /** Off for one update inside a bulk action, which announces itself once at the end. Every- * notification is a synchronous localStorage write that wakes the other tabs, so Archive All- * would otherwise send one per thread. */+ /** Off for one update inside a bulk action, which announces itself once at the end. Every notification is a+ * synchronous localStorage write that wakes the other tabs, so Archive All would otherwise send one per+ * thread. */notify?: boolean;/** Give up on the write; used to stand a superseded settings PATCH down. */signal?: AbortSignal;@@ -1107,9 +1107,9 @@ export async function getChatMessage(return parseJsonOrThrow<MessageRecord>(response);}-/** The server owns this message and will reject every save of it. Distinct from a transient- * failure: retrying can never succeed, so callers must stop rather than back off. Without- * this the per-chunk autosave re-sent on every chunk for the whole generation. */+/** The server owns this message and will reject every save of it. Distinct from a transient failure: retrying+ * can never succeed, so callers must stop rather than back off. Without this the per-chunk autosave re-sent on+ * every chunk for the whole generation. *//** Set by routes/chat_history.py; exposed through the CORS middleware in main.py. */const CONFLICT_KIND_HEADER = "X-Unsloth-Conflict-Kind";const CONFLICT_KIND_PROTECTED = "protected";@@ -1563,9 +1563,8 @@ export async function* streamChatCompletions(sawReasoningContent &&!sawAssistantContent) {- // The backend substitutes the full context length when the user left Max Tokens on "Max", so a- // payload value equal to it is indistinguishable from unset, and both mean the setting is- // not the lever.+ // The backend substitutes the full context length when the user left Max Tokens on "Max", so a payload value+ // equal to it is indistinguishable from unset, and both mean the setting is not the lever.throw new GenerationLengthError(maxTokensIsTheLimit({cap: payload.max_tokens ?? null,@@ -1698,9 +1697,8 @@ export async function* streamChatCompletions(}}} finally {- // Only abort on an early/abnormal exit: after a natural [DONE] the request is logically complete- // and the backend finalizes its api-monitor entry, so cancelling here can mark a successful- // request as cancelled.+ // Only abort on an early/abnormal exit: after a natural [DONE] the request is logically complete and the+ // backend finalizes its api-monitor entry, so cancelling here can mark a successful request as cancelled.if (!completed) {try {await reader.cancel();diff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.tsindex 0418f3f740d..0facb575ec5 100644--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts@@ -176,10 +176,9 @@ export async function saveChatSettingsPatchIfCurrent(patch,}),});- // A backend without this route answers 404 (--api-only) or 405 (the browser- // build's GET-only SPA catch-all). The desktop app adopts any backend above a- // version floor, so that pairing is supported, not a bug. Report "not- // applied" so the caller leaves the server alone.+ // A backend without this route answers 404 (--api-only) or 405 (the browser build's GET-only SPA+ // catch-all). The desktop app adopts any backend above a version floor, so that pairing is+ // supported, not a bug. Report "not applied" so the caller leaves the server alone.if (response.status === 404 || response.status === 405) {return { settings: expected, applied: false };}diff --git a/studio/frontend/src/features/chat/artifacts/html-frame.tsx b/studio/frontend/src/features/chat/artifacts/html-frame.tsxindex c15e6b1eaac..0f1070dc658 100644--- a/studio/frontend/src/features/chat/artifacts/html-frame.tsx+++ b/studio/frontend/src/features/chat/artifacts/html-frame.tsx@@ -70,9 +70,8 @@ function appendBlocked(};}-// A non-HTTP(S) violation reports a bare token ("eval", "blob"), which the permissive CSP-// widens too. Dropping those left the canvas blank with no prompt, so label them with the-// token itself.+// A non-HTTP(S) violation reports a bare token ("eval", "blob"), which the permissive CSP widens+// too. Dropping those left the canvas blank with no prompt, so label them with the token itself.const BLOCKED_KEYWORD = /^[a-z-]+$/;function blockedHost(uri: string): string | null {diff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.tsindex 25892db3e8a..0d52dcf16a8 100644--- a/studio/frontend/src/features/chat/attachment-content.ts+++ b/studio/frontend/src/features/chat/attachment-content.ts@@ -835,12 +835,11 @@ async function readBoundedText(): Promise<{ text: string; truncated: boolean }> {const truncated = file.size > MAX_PREVIEW_TEXT_BYTES;const slice = truncated ? file.slice(0, MAX_PREVIEW_TEXT_BYTES) : file;- // Strict decoding belongs to the files the text adapter owns, where refusing- // is better than sending mojibake to the model. A preview of someone else's- // file may not be stricter than the adapter that accepted it: .html goes to- // the HTML adapter, which sends a windows-1252 page happily, and reading the- // preview through the strict path meant opening one threw where it used to- // render.+ // Strict decoding belongs to the files the text adapter owns, where refusing is better than+ // sending mojibake to the model. A preview of someone else's file may not be stricter than the+ // adapter that accepted it: .html goes to the HTML adapter, which sends a windows-1252 page+ // happily, and reading the preview through the strict path meant opening one threw where it used+ // to render.if (!isTextAttachmentName(file.name)) {return { text: await slice.text(), truncated };}diff --git a/studio/frontend/src/features/chat/audio-attachment-adapter.ts b/studio/frontend/src/features/chat/audio-attachment-adapter.tsindex 65ca7579d2e..e593e237571 100644--- a/studio/frontend/src/features/chat/audio-attachment-adapter.ts+++ b/studio/frontend/src/features/chat/audio-attachment-adapter.ts@@ -27,12 +27,10 @@ function newAttachmentId(): string {// Audio shares the "Add photos & files" picker. Like VisionImageAdapter, unsupported models are// rejected at add() time with a toast.export class AudioAttachmentAdapter implements AttachmentAdapter {- // MIME is unreliable for some containers (m4a), so also match by- // extension. No .webm extension: it would claim video/webm files; real- // audio webm (MediaRecorder) always reports the audio/webm MIME. .mp4 and- // .m4v stay off for the same reason; only .m4a is audio-only. Not the picker- // list: this decides routing, and .3gp is in that list only so a dialog can- // offer a recording.+ // MIME is unreliable for some containers (m4a), so also match by extension. No .webm extension:+ // it would claim video/webm files; real audio webm (MediaRecorder) always reports the audio/webm+ // MIME. .mp4 and .m4v stay off for the same reason; only .m4a is audio-only. Not the picker list:+ // this decides routing, and .3gp is in that list only so a dialog can offer a recording.accept = AUDIO_ATTACHMENT_ACCEPT;private readonly attachmentIds = new Set<string>();diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex ae20438ecff..dff5f0eb149 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -696,9 +696,9 @@ const CompareContent = memo(function CompareContent({);});-/** One column in the compare layout: a ChatRuntimeProvider and a Thread with hideComposer. Each- * pane is `flex-1 basis-0 min-h-0 min-w-0` so panes share space equally and the inner- * viewport scrolls instead of spilling. */+/** One column in the compare layout: a ChatRuntimeProvider and a Thread with hideComposer. Each pane is+ * `flex-1 basis-0 min-h-0 min-w-0` so panes share space equally and the inner viewport scrolls instead of+ * spilling. */function ComparePane({modelType,pairId,@@ -777,9 +777,9 @@ function useCompareReloadReadiness(pairId: string): (pane: string) => void {);}-/** Shared shell for both compare variants: a flex column with the two panes as siblings and the- * shared composer docked at the bottom. Flex, not grid: grid rows with 1fr triggered resize- * thrash in assistant-ui's autoscroll on breakpoint crossings. */+/** Shared shell for both compare variants: a flex column with the two panes as siblings and the shared composer+ * docked at the bottom. Flex, not grid: grid rows with 1fr triggered resize thrash in assistant-ui's autoscroll+ * on breakpoint crossings. */function CompareShell({handlesRef,children,@@ -834,15 +834,15 @@ const LoraCompareContent = memo(function LoraCompareContent({const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);const checkpointIsLora = useIsLoraCompare();- // Global on purpose: a first compare run starts before either thread exists, so there is no pair- // id to scope BY. The gate exists at all because these ids feed ComparePane's- // `initialThreadId`, so learning them mid-run points ThreadAutoSwitch at a live thread.+ // Global on purpose: a first compare run starts before either thread exists, so there is no pair id to scope+ // BY. The gate exists at all because these ids feed ComparePane's `initialThreadId`, so learning them mid-run+ // points ThreadAutoSwitch at a live thread.const anyRunning = useChatRuntimeStore((s) => Object.keys(s.localRunByThreadId).length > 0,);- // ...but only RE-lists wait. The shared provider (#8908) keeps a base chat's run alive across- // the switch into compare, so `anyRunning` is true on arrival for an unrelated reason, and- // gating the FIRST list on it left an existing compare on blank runtimes.+ // ...but only RE-lists wait. The shared provider (#8908) keeps a base chat's run alive across the switch into+ // compare, so `anyRunning` is true on arrival for an unrelated reason, and gating the FIRST list on it left an+ // existing compare on blank runtimes.const listedPairRef = useRef<string | null>(null);useEffect(() => {@@ -1598,9 +1598,9 @@ function ProjectLanding({}if (!activeThreadId) {if (resumed && pendingNewThreadId) {- // ...unless it was deleted while another view held the screen. Nothing else clears this id, so- // restoring a tombstoned thread would put a conversation storage no longer has back on- // screen. Fall through to the rotate below.+ // ...unless it was deleted while another view held the screen. Nothing else clears this id, so restoring a+ // tombstoned thread would put a conversation storage no longer has back on screen. Fall through to the+ // rotate below.if (!isChatThreadDeleted(pendingNewThreadId)) {useChatRuntimeStore.getState().setActiveThreadId(pendingNewThreadId);return;@@ -1620,9 +1620,9 @@ function ProjectLanding({) {return;}- // Hand the composer's attach choice to the chat it just created: setting this swaps- // ProjectComposer for Thread, so the bar holding the choice unmounts and its cleanup drops- // it. Its own choice only, or a later send would consume another composer's pick.+ // Hand the composer's attach choice to the chat it just created: setting this swaps ProjectComposer for+ // Thread, so the bar holding the choice unmounts and its cleanup drops it. Its own choice only, or a later+ // send would consume another composer's pick.const captured = pendingTargetClaimRef.current;useChatRuntimeStore.getState()@@ -1838,9 +1838,9 @@ function ProjectLanding({setRenameDraft(event.target.value)}onKeyDown={(event) => {- // Ignore keydowns fired mid-IME-composition (CJK) so a candidate-confirming- // Enter does not commit the rename. Guarded before the key branch so Escape- // is covered too (isComposing on WebKit, 229 on Chromium).+ // Ignore keydowns fired mid-IME-composition (CJK) so a candidate-confirming Enter does not commit+ // the rename. Guarded before the key branch so Escape is covered too (isComposing on+ // WebKit, 229 on Chromium).if (event.nativeEvent.isComposing ||event.keyCode === 229@@ -2171,9 +2171,8 @@ type PendingHubAutoLoad = {originGgufVariant: string | null;};-// `search` comes from RootLayout (not useSearch) so ChatPage stays mounted off-route, frozen to-// the last /chat search. `active` is false off-route: close portaled surfaces and stop-// route-specific listeners.+// `search` comes from RootLayout (not useSearch) so ChatPage stays mounted off-route, frozen to the last /chat+// search. `active` is false off-route: close portaled surfaces and stop route-specific listeners.export function ChatPage({search,active,@@ -2191,9 +2190,9 @@ export function ChatPage({const store = useChatRuntimeStore.getState();const wasIncognito = store.incognito;store.setIncognito(!store.incognito);- // On an empty scratch chat there is nothing to abandon, so flip in place: navigating would- // remount the thread and bounce the composer. Otherwise start a clean chat so the temporary- // session cannot inherit or leave behind a persisted thread.+ // On an empty scratch chat there is nothing to abandon, so flip in place: navigating would remount the thread+ // and bounce the composer. Otherwise start a clean chat so the temporary session cannot inherit or leave+ // behind a persisted thread.const onEmptyScratchChat =!search.thread &&!search.compare &&@@ -2373,9 +2372,9 @@ export function ChatPage({const persistedActiveThreadId = isAssistantLocalThreadId(activeThreadId)? null: activeThreadId;- // A ?new=<nonce> chat has no thread in the URL before or after its first send, and for the first- // render the store still holds the PREVIOUS chat's id until ThreadNewChatSwitch blanks it,- // so latch on having seen it blanked for this nonce.+ // A ?new=<nonce> chat has no thread in the URL before or after its first send, and for the first render the+ // store still holds the PREVIOUS chat's id until ThreadNewChatSwitch blanks it, so latch on having seen it+ // blanked for this nonce.const newChatBlankedRef = useRef<string | null>(null);if (search.new &&@@ -2578,9 +2577,8 @@ export function ChatPage({const supportsBuiltinWebFetch = providerSupportsBuiltinWebFetch(provider?.providerType,);- // Kimi's k2.6/k2.5 default to thinking enabled server-side, so the Think pill comes up clicked.- // Search stays off; the composer's mutual-exclusion handlers flip the two.- // Per https://platform.kimi.ai/docs/models.+ // Kimi's k2.6/k2.5 default to thinking enabled server-side, so the Think pill comes up clicked. Search stays+ // off; the composer's mutual-exclusion handlers flip the two. Per https://platform.kimi.ai/docs/models.const isKimi = provider?.providerType === "kimi";// Web search on by default only for Anthropic and OpenAI, both with structured citations.// OpenRouter and Kimi work on opt-in but are less reliable.@@ -2601,10 +2599,9 @@ export function ChatPage({const storedWebFetchToolsEnabled =threadScopedOverride("webFetchToolsEnabled") ??loadOptionalBool(CHAT_WEB_FETCH_TOOLS_ENABLED_KEY);- // Unsloth runs Search and Code itself for any provider that advertises the capability, so a- // self-hosted connection has no hosted builtin to key off. Keying the pill state on the- // hosted flags alone discarded the saved preference on every reload and sent- // enable_tools: false.+ // Unsloth runs Search and Code itself for any provider that advertises the capability, so a self-hosted+ // connection has no hosted builtin to key off. Keying the pill state on the hosted flags alone discarded the+ // saved preference on every reload and sent enable_tools: false.const supportsStudioToolsHere =providerModelSupportsStudioTools(provider?.providerType,@@ -2783,9 +2780,9 @@ export function ChatPage({? "single:implicit": artifactViewKey;- // Compare replaces the shared provider on screen, so the base view is kept mounted behind it:- // unmounting runs useLocalRuntime's detach(), the backend cancels on the disconnect, and a- // project chat's run would die. Frozen to the last non-compare view.+ // Compare replaces the shared provider on screen, so the base view is kept mounted behind it: unmounting runs+ // useLocalRuntime's detach(), the backend cancels on the disconnect, and a project chat's run would die. Frozen+ // to the last non-compare view.const keptBaseViewRef = useRef<{view: Exclude<ChatView, { mode: "compare" }>;attachmentTargetKey: string;@@ -2798,9 +2795,9 @@ export function ChatPage({keptBaseViewRef.current?.attachmentTargetKey ?? artifactViewKey;const baseBackgrounded = view.mode === "compare";- // #9251's reload signal, taken here because the provider is hoisted. Stored as the project it- // belongs to, not a boolean: the hoisted provider is not remounted when the project changes,- // so a flag would release the next landing's shell early.+ // #9251's reload signal, taken here because the provider is hoisted. Stored as the project it belongs to, not+ // a boolean: the hoisted provider is not remounted when the project changes, so a flag would release the next+ // landing's shell early.const projectLandingId =baseView?.mode === "project" ? baseView.projectId : null;const [projectRuntimeReadyFor, setProjectRuntimeReadyFor] = useState<@@ -3426,9 +3423,9 @@ export function ChatPage({// Both controls are the header's, and the header drops them in Compare, where each pane carries// its own picker. Without the check the chord would toggle state nothing renders.const headerPickersShown = active && view.mode !== "compare";- // This page stays mounted under a dialog, so `enabled` still says yes while the header is inert;- // without a press-time check the chord opens a popover on the covered surface.- // Backgrounded, not "not in the foreground": an unrendered layout is not a covered one.+ // This page stays mounted under a dialog, so `enabled` still says yes while the header is inert; without a+ // press-time check the chord opens a popover on the covered surface. Backgrounded, not "not in the foreground":+ // an unrendered layout is not a covered one.const chatCovered = () => isSurfaceBackgrounded(COMPOSER_INPUT_SELECTOR);useShortcut("openModelPicker",@@ -3448,9 +3445,9 @@ export function ChatPage({},{ enabled: projectSwitcherShown },);- // A picker left open would come back on the next visit as a ghost. Off-route is one way to leave- // it (this page stays mounted), and so is entering Compare or a standalone chat taking the- // project away. Adjusted during render, as React prescribes for derived state.+ // A picker left open would come back on the next visit as a ghost. Off-route is one way to leave it (this page+ // stays mounted), and so is entering Compare or a standalone chat taking the project away. Adjusted during+ // render, as React prescribes for derived state.if (!projectSwitcherShown && projectPickerOpen) {setProjectPickerOpen(false);}@@ -3577,12 +3574,10 @@ export function ChatPage({return;}}- // For local turns, also require the restored count to fit in- // the active window. Skip when unknown (external provider).- //- // llama.cpp only: it stops at the window, so a count past it is stale by- // definition. MLX generates straight past instead, where an over-window count- // is the true one and the bar has a state for it.+ // For local turns, also require the restored count to fit in the active window. Skip when unknown+ // (external provider). llama.cpp only: it stops at the window, so a count past it is stale by definition.+ // MLX generates straight past instead, where an over-window count is the true one and the bar has a state+ // for it.const limit = store.loadedIsGguf ? store.loadedContextLength : null;if (typeof limit === "number" &&@@ -3629,10 +3624,10 @@ export function ChatPage({).flatMap((provider) =>provider.models.map((model) => {- // For OpenRouter's free router the chosen underlying model is latched from `chunk.model`, so- // render the chip as `openrouter:<short-chosen>`, dropping the redundant `/free` and the- // chosen id's org prefix: inclusionai/ring-2.6-1t-20260508:free becomes- // ring-2.6-1t-20260508:free. The `:free` suffix already conveys "free model".+ // For OpenRouter's free router the chosen underlying model is latched from `chunk.model`, so render the+ // chip as `openrouter:<short-chosen>`, dropping the redundant `/free` and the chosen id's org prefix:+ // inclusionai/ring-2.6-1t-20260508:free becomes ring-2.6-1t-20260508:free. The `:free` suffix already+ // conveys "free model".let displayName = model;if (provider.providerType === "openrouter" &&@@ -3657,10 +3652,10 @@ export function ChatPage({),[externalProvidersForChat, lastOpenRouterChosenModel],);- // `externalModels` is flat-mapped from `provider.models`, the ids the user ticked, so a model- // unticked in the connection dialog looks exactly like one the provider withdrew; the- // connection's cached catalogue tells the two apart. Depends on the store value and the gate- // rather than on `externalProvidersForChat`, which is a fresh array each render.+ // `externalModels` is flat-mapped from `provider.models`, the ids the user ticked, so a model unticked in the+ // connection dialog looks exactly like one the provider withdrew; the connection's cached catalogue tells the+ // two apart. Depends on the store value and the gate rather than on `externalProvidersForChat`, which is a+ // fresh array each render.const externalConnections = useMemo<ExternalConnectionRef[]>(() =>connectionsEnabled@@ -3729,9 +3724,9 @@ export function ChatPage({[models, loraModels, externalModels],);- // The picker's own handler, reached the way the picker reaches it: with the row's metadata, not- // the bare id. A local or fine-tuned row is in neither `/api/models/list` nor the external- // ids, so without it the switch loads on different arguments.+ // The picker's own handler, reached the way the picker reaches it: with the row's metadata, not the bare id. A+ // local or fine-tuned row is in neither `/api/models/list` nor the external ids, so without it the switch loads+ // on different arguments.const handleSwitchBackToChatModel = useCallback((target: ChatModelSwitchTarget) => {handleCheckpointChange(diff --git a/studio/frontend/src/features/chat/external-providers.ts b/studio/frontend/src/features/chat/external-providers.tsindex d56915bd3dd..25edf84bd31 100644--- a/studio/frontend/src/features/chat/external-providers.ts+++ b/studio/frontend/src/features/chat/external-providers.ts@@ -412,9 +412,8 @@ export function toExternalBackendProviderType(providerType: string | null | undefined,): string | undefined {if (!providerType) return undefined;- // vLLM's /v1/responses applies the loaded model's chat template, which 400s on- // strict-alternation templates. Pass the type through so the backend routes vLLM to- // /v1/chat/completions instead.+ // vLLM's /v1/responses applies the loaded model's chat template, which 400s on strict-alternation+ // templates. Pass the type through so the backend routes vLLM to /v1/chat/completions instead.if (providerType === "vllm") return "vllm";if (providerType === "ollama") return "ollama";if (providerType === "llama_cpp") return "llama_cpp";diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsindex c80e90e61f3..04a2ec3905c 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts@@ -435,12 +435,10 @@ function getTransformersUpgradeRequiredMessage(modelName: string): string {}/**- * Reconcile the chat runtime store against `/api/inference/status`: refresh the- * models/loras catalogs and either re-pin the active checkpoint or clear the- * loaded-model flags when nothing is loaded. Module-level so it can run outside- * a React render (e.g. the imperative resync below); `useChatModelRuntime.refresh`- * is a thin wrapper over it. External selections are left untouched since they- * have no backend mirror.+ * Reconcile the chat runtime store against `/api/inference/status`: refresh the models/loras+ * catalogs and either re-pin the active checkpoint or clear the loaded-model flags when nothing is+ * loaded. Module-level so it can run outside a React render; `useChatModelRuntime.refresh` is a thin+ * wrapper. External selections are left untouched since they have no backend mirror.*/// Prevent older concurrent status reads from overwriting newer results.let syncGeneration = 0;@@ -515,10 +513,9 @@ async function syncInferenceStatusToStore(options?: {const selectedCheckpoint = useChatRuntimeStore.getState().params.checkpoint;const isExternalSelectionActive = isExternalModelId(selectedCheckpoint);const selectionChanged = selectedCheckpoint !== selectedAtStart;- // The local selection is re-derived from this status on every mount, so adopting a- // TTS model made it the chat model without the user picking it. Read the slot as- // empty and the eviction branch below clears the stale pick, as it does for an- // image or video load.+ // The local selection is re-derived from this status on every mount, so adopting a TTS model made+ // it the chat model without the user picking it. Read the slot as empty and the eviction branch+ // below clears the stale pick, as it does for an image or video load.const chatActiveModel =statusRes.active_model &&!isSpeechOnlyStatus(statusRes) &&@@ -544,9 +541,8 @@ async function syncInferenceStatusToStore(options?: {applyActiveModelStatusToStore(statusRes, {previousCheckpoint: selectedCheckpoint,previousGgufVariant,- // With no prior selection this is Studio discovering the server's- // resident model, so its global-only snapshot belongs to this- // checkpoint and is safe to migrate.+ // With no prior selection this is Studio discovering the server's resident model, so its+ // global-only snapshot belongs to this checkpoint and is safe to migrate.adoptingExistingServerModel: selectedCheckpoint === "",});// setModels(listRes...) above used catalog data, which omits audio capability. Re-apply live@@ -621,10 +617,9 @@ async function syncInferenceStatusToStore(options?: {}/**- * The mount handoff: hydrate from status, then observe until the server settles.- *- * The gate is up before the sync is issued, since a refresh issued later can answer first- * and adopt the outgoing model.+ * The mount handoff: hydrate from status, then observe until the server settles. The gate is up+ * before the sync is issued, since a refresh issued later can answer first and adopt the outgoing+ * model.*/async function refreshAndWaitForServerModel(options?: {signal?: AbortSignal;@@ -643,16 +638,12 @@ async function refreshAndWaitForServerModel(options?: {}/**- * Reconcile the UI after the SERVER unloaded the active model out from under it- * (e.g. a llama.cpp update unloads the running model to swap the binary): the- * model selector drops to "select model" instead of pointing at a model that now- * 400s on send. Imperative so the global llama-update banner (which has no- * chat-runtime handle) can call it.- *- * Only a LOCAL selection points at the unloaded model. An external-provider- * selection has no llama.cpp mirror and still works, so clearing it (which also- * wipes its persisted id) would drop a valid, unrelated model; skip the clear so- * the refresh below leaves it intact.+ * Reconcile the UI after the SERVER unloaded the active model out from under it (e.g. a llama.cpp+ * update unloads the running model to swap the binary): the model selector drops to "select model"+ * instead of pointing at a model that now 400s on send. Imperative so the global llama-update+ * banner, which has no chat-runtime handle, can call it. Only a LOCAL selection points at the+ * unloaded model: an external-provider selection has no llama.cpp mirror and still works, so+ * clearing it would drop a valid, unrelated model.*/export async function resyncInferenceStatusAfterServerModelChange(): Promise<void> {// Both llama.cpp update paths land here, and an update replaces the binary whose --help the flag catalogue describes.@@ -774,10 +765,9 @@ export function useChatModelRuntime() {// Dictation is a sidecar and evicts nothing; chat's own loads reconcile themselves. A "tts" load// does neither: it is the Audio page taking this very slot.if (runtime === "chat" || runtime === "stt") return;- // Both edges, not only the settle. The arbiter evicts chat inside the- // image or video load POST, before the download starts, so waiting for- // the load to finish left the picker and the header naming a model that- // had already gone and that 400s on send, for the whole download.+ // Both edges, not only the settle. The arbiter evicts chat inside the image or video load POST,+ // before the download starts, so waiting for the load to finish left the picker and the header+ // naming a model that had already gone and that 400s on send, for the whole download.void refresh({includeLoras: false,externalChatSlotLoad: runtime === "tts",@@ -874,12 +864,10 @@ export function useChatModelRuntime() {}dismissStartToastsForModelSelection();- // A load is already in flight. If it's this exact pick (id + variant + token),- // ignore the duplicate click. If it's a DIFFERENT model (including a different- // GGUF variant of the same repo, which the old id+token guard wrongly treated- // as a duplicate), don't start a second concurrent load and don't swallow the- // request: surface it so the user waits or cancels. Centralized here so every- // entry point is covered, not just the staged Load button.+ // A load is already in flight. If it is this exact pick (id + variant + token), ignore the+ // duplicate click. If it is a DIFFERENT model, including a different GGUF variant of the same repo,+ // do not start a second concurrent load and do not swallow the request: surface it so the user+ // waits or cancels. Centralized here so every entry point is covered.const bailIfLoadInFlight = (): boolean => {const inFlightLoad =loadingModelRef.current ??@@ -921,11 +909,10 @@ export function useChatModelRuntime() {await ensureGpuDeviceCache().catch(() => {});}// What /load would carry for a pick with no saved config, which is not always the live runtime:- // performLoad treats a different checkpoint or variant as a switch and clears the per-model- // fields first, so comparing the outgoing model's settings would both prompt for a load that- // dedupes and adopt one that does not. gpuMemoryMode and the dtypes still come from the store.- // gpuMemoryMode is standing, and kvCacheDtype and tensorParallel are not reset, so those three- // still come from the store.+ // performLoad treats a different checkpoint or variant as a switch and clears the per-model fields+ // first, so comparing the outgoing model's settings would both prompt for a load that dedupes and+ // adopt one that does not. gpuMemoryMode is standing, and kvCacheDtype and tensorParallel are not+ // reset, so those three still come from the store.const live = useChatRuntimeStore.getState();const resetsPerModelSettings = Boolean(live.params.checkpoint &&@@ -972,11 +959,10 @@ export function useChatModelRuntime() {// guarded on its absence.(loadPath ?? modelId).toLowerCase().endsWith(".gguf"),) &&- // The id names the weights, not how the server was invoked: a remembered context length,- // drafter, placement or extra arg the resident load does not run is a real reload. Not- // `pendingConfig`: with no saved record the caller has already run- // applyModelLoadConfigToRuntime(null), which resets the store to DEFAULT_PER_MODEL_CONFIG,- // and performLoad reads the store for every field the config does not carry.+ // The id names the weights, not how the server was invoked: a remembered context length, drafter,+ // placement or extra arg the resident load does not run is a real reload. Not `pendingConfig`: with+ // no saved record the caller has already run applyModelLoadConfigToRuntime(null), which resets the+ // store to DEFAULT_PER_MODEL_CONFIG, and performLoad reads the store for the rest.residentRuntimeMatchesConfig(status, comparedConfig, {// What the applier fills an unset field with, so the comparison is against what /load would send// rather than against silence.@@ -1049,11 +1035,10 @@ export function useChatModelRuntime() {// Roll back the config pre-applied for the load that is not happening, before hydrating, so the// resident status wins over the staged snapshot. The helper carries the diffusion flag.restorePreviousConfig();- // ...except for maxSeqLength, which the rollback has the last word on: it is a client-side cap- // no status field echoes, so leaving it rolled back would hand this model the OUTGOING one's- // cap, and applyActiveModelStatus below cannot correct it. An absent cap is not silence- // either: applyPerModelConfigToRuntime resolves it to defaultInferenceParams.maxSeqLength,- // so leaving it unset kept the outgoing cap.+ // ...except for maxSeqLength, which the rollback has the last word on: it is a client-side cap no+ // status field echoes, so leaving it rolled back would hand this model the OUTGOING one's cap and+ // applyActiveModelStatus cannot correct it. An absent cap is not silence either:+ // applyPerModelConfigToRuntime resolves it to defaultInferenceParams.maxSeqLength.const pickedMaxSeqLength =normalizeMaxSeqLength(pendingConfig?.maxSeqLength) ??defaultInferenceParams.maxSeqLength;@@ -1231,12 +1216,10 @@ export function useChatModelRuntime() {let cpuFallbackReason: CpuFallbackReason | null = null;let mmprojFallbackReason: MmprojFallbackReason | null = null;try {- // Hoisted out of performLoad's GGUF branch for the progress pollers, but kept off- // loads that never reach the Hub: it validates over the network and can block on a- // dialog, and a stale Settings token must not gate a local or cached-LoRA load.- // An Ollama row's id is an opaque `ollama-manifest:` reference rather than a- // path, so isLocalModelPath does not recognise it even though the backend- // materialises the load entirely from the local Ollama store.+ // Hoisted out of performLoad's GGUF branch for the progress pollers, but kept off loads that never+ // reach the Hub: it validates over the network and can block on a dialog, and a stale Settings+ // token must not gate a local or cached-LoRA load. An Ollama row's id is an opaque+ // `ollama-manifest:` reference rather than a path, so isLocalModelPath does not recognise it.const mayReachHub =!isLocal && !isOllamaLinkPath(modelId) && nativePathToken == null;if (mayReachHub) {@@ -1254,13 +1237,12 @@ export function useChatModelRuntime() {let previousWasUnloaded = false;const pendingLoadConfig =typeof selection !== "string" ? selection.config : undefined;- // The outgoing model's slot INTENT (blank = follow the server default), which the resolved- // baseline cannot express. previousConfig is the snapshot taken before pre-applying the- // target's config. Read before the staged-metadata await so a change cannot perturb it.- // Unlike tensorParallel, vision does NOT survive a model switch: it is per-model config defaulting- // to vision on, so a target that saved none gets that default, not the outgoing model's setting.- // The dedupe above builds its own view of an unconfigured switch from DEFAULT_PER_MODEL_CONFIG,- // and resetsPerModelSettings cannot repair it, since this constant is captured before that block.+ // The outgoing model's slot INTENT (blank = follow the server default), which the resolved baseline+ // cannot express. previousConfig is the snapshot taken before pre-applying the target's config,+ // read before the staged-metadata await so a change cannot perturb it. Unlike tensorParallel,+ // vision does NOT survive a model switch: it is per-model config defaulting to vision on, so a+ // target that saved none gets that default. The dedupe above builds its own view of an+ // unconfigured switch from DEFAULT_PER_MODEL_CONFIG, and resetsPerModelSettings cannot repair it.const previousNParallel =typeof selection !== "string" && selection.previousConfig? (selection.previousConfig.nParallel ?? null)@@ -1285,11 +1267,9 @@ export function useChatModelRuntime() {? (selection.previousConfig.mlxKvBits ?? null): useChatRuntimeStore.getState().mlxKvBits;if (isGguf && isDiffusion === undefined) {- // Prepare the token exactly as validateModel/loadModel do (and as- // the compare path does): the Hub rejects an invalid Authorization- // header with 401 even for a public repo, so sending the raw stored- // token here would abort the load before the existing "continue- // anonymously / replace token" recovery flow could run.+ // Prepare the token exactly as validateModel/loadModel do: the Hub rejects an invalid+ // Authorization header with 401 even for a public repo, so sending the raw stored token here would+ // abort the load before the "continue anonymously / replace token" recovery flow could run.isDiffusion = (await fetchGgufStagedMetadata({model_path: loadPath,@@ -1334,9 +1314,8 @@ export function useChatModelRuntime() {(typeof selection !== "string"? selection.previousConfig?.maxSeqLength: null) ?? maxSeqLength;- // The intent the model had, not the length it ended up at: sending the- // resolved length would pin a model nobody pinned.- // The resident backend's own answer, so a native-audio checkpoint the worker+ // The intent the model had, not the length it ended up at: sending the resolved length would pin a+ // model nobody pinned. The resident backend's own answer, so a native-audio checkpoint the worker// served off the MLX path does not roll back at the sentinel.const previousIsMlx = residentIsServedByMlx(previousIsGguf,@@ -1359,10 +1338,9 @@ export function useChatModelRuntime() {): (previousPin ??unpinnedLoadContext(false, previousIsMlx, previousMaxSeqLength));- // main's `const hfToken = stateBeforeUnload.hfToken` is deliberately not- // carried over: this branch prepares the credential once in the enclosing- // scope, and re-reading the raw stored token here would shadow it and undo- // the preparation for every load below.+ // main's `const hfToken = stateBeforeUnload.hfToken` is deliberately not carried over: this branch+ // prepares the credential once in the enclosing scope, and re-reading the raw stored token here+ // would shadow it and undo the preparation for every load below.const previousModelRequiresTrustRemoteCode =stateBeforeUnload.modelRequiresTrustRemoteCode;const previousActiveNativePathExpiresAtMs =@@ -1380,10 +1358,9 @@ export function useChatModelRuntime() {let loadMlxKvBits =pendingLoadConfig?.mlxKvBits ?? stateBeforeUnload.mlxKvBits;// gpuMemoryMode is a standing preference; the rest are per-model knobs the reset below clears, so- // they are re-baselined there in lock-step with the store.- // A GGUF native context can exceed maxSeqLength, so sizing on raw maxSeqLength could pass, unload,- // then have /load refuse it. Uses the click-time snapshot, so the two agree. A same-repo quant- // switch (different gguf_variant) is a different model for per-model knobs, so re-baseline them.+ // they are re-baselined there in lock-step with the store. A GGUF native context can exceed+ // maxSeqLength, so sizing on raw maxSeqLength could pass, unload, then have /load refuse it. A+ // same-repo quant switch is a different model for per-model knobs, so re-baseline them.let loadCustomContextLength =pendingLoadConfig?.customContextLength ??stateBeforeUnload.customContextLength;@@ -1393,10 +1370,9 @@ export function useChatModelRuntime() {: (pendingLoadConfig?.tensorParallel ??stateBeforeUnload.tensorParallel);// The diffusion runner has no projector to skip, so the toggle is inert there. Unlike- // tensorParallel this does NOT survive a model switch: it is per-model config defaulting to- // vision on, and carrying it over loaded the new model text-only and silently, because the- // dedupe comparison builds its own view of an unconfigured switch. resetsPerModelSettings- // cannot repair it, since this constant is captured before that block runs.+ // tensorParallel this does NOT survive a model switch: it is per-model config defaulting to vision+ // on, and carrying it over loaded the new model text-only and silently, because the dedupe+ // comparison builds its own view of an unconfigured switch.const loadSwitchesModelOrVariant = Boolean(currentCheckpoint &&(currentCheckpoint !== modelId ||@@ -1473,9 +1449,8 @@ export function useChatModelRuntime() {? (await consumeNativePathToken(nativePathToken, "validate-model")).nativePathLease: undefined;// Validate with the same effective context /load uses: a GGUF native context can exceed- // maxSeqLength, so sizing on raw maxSeqLength could pass, unload, then have /load refuse it.- // Mirror /load on a cross-model switch, and treat a same-repo quant switch as a different- // model for the per-model knobs.+ // maxSeqLength, so sizing on raw maxSeqLength could pass, unload, then have /load refuse it. Mirror+ // /load on a cross-model switch, treating a same-repo quant switch as a different model.const switchingModelOrVariant =currentCheckpoint !== modelId ||(loadActiveGgufVariant ?? null) !== (ggufVariant ?? null);@@ -1641,8 +1616,8 @@ export function useChatModelRuntime() {// On a model switch, fall back to the persisted standing preference rather than null so a// per-session forced MTP mode cannot follow the user onto a model without an MTP head.- // spec_draft_n_max is MTP-only and always resets, and the loaded shadow is seeded to prevent- // a transient dirty Apply. keepSpeculative skips this for a staged Load.+ // spec_draft_n_max is MTP-only and always resets, and the loaded shadow is seeded to prevent a+ // transient dirty Apply. keepSpeculative skips this for a staged Load.if (resetsPerModelSettings) {const persistedSpeculativeType = readPersistedSpeculativeType();useChatRuntimeStore.setState({@@ -1708,11 +1683,9 @@ export function useChatModelRuntime() {loadSplitRatio = null;}- // The Context Length the USER set for this load, captured before the- // clamp below can stand in for it. This, not the n_ctx that goes on- // the wire, is what the completed load pins: several send rules put a- // positive n_ctx on the wire with the control on Auto, and a pin read- // back out of one of those is a number the user never chose.+ // The Context Length the USER set for this load, captured before the clamp below can stand in for+ // it. This, not the n_ctx that goes on the wire, is what the completed load pins: several send+ // rules put a positive n_ctx on the wire with the control on Auto.const targetIsMlx = isServedByMlx(isGguf,platform.deviceType,@@ -1723,13 +1696,10 @@ export function useChatModelRuntime() {targetIsMlx,pinnedMaxSeqLength,);- // Pinning layers on the SAME model keeps the currently resolved- // context: with no explicit pin, a manual+pinned reload would send 0,- // which the backend's --fit off branch treats as the NATIVE context --- // far larger than the sheet shows when the load was fit-sized (Default- // or Manual + Auto layers may auto-reduce context to fit VRAM), a- // likely OOM. loadedContextLength is that resolved value; a model already- // at native reloads unchanged, so this is safe for any prior mode.+ // Pinning layers on the SAME model keeps the currently resolved context: with no explicit pin, a+ // manual+pinned reload would send 0, which the backend's --fit off branch treats as the NATIVE+ // context, far larger than the sheet shows when the load was fit-sized, a likely OOM.+ // loadedContextLength is that resolved value; a model already at native reloads unchanged.if (isGguf &&!switchingModelOrVariant &&@@ -1817,11 +1787,9 @@ export function useChatModelRuntime() {// If cancelled while loading, do not show the model as active: it is being unloaded.if (abortCtrl.signal.aborted) throw new Error("Cancelled");- // The load applied this spec mode, so persist the user's standing preference now (the requested- // intent, not the resolved echo). Skipped for a per-model config, whose choice must not- // overwrite the global default.- // The requested intent, not the resolved echo: saveSpeculativeType keeps only the universal- // auto/ngram/off. Skip for a per-model config (keepSpeculative).+ // The load applied this spec mode, so persist the user's standing preference now: the requested+ // intent, not the resolved echo, since saveSpeculativeType keeps only the universal auto/ngram/off.+ // Skipped for a per-model config (keepSpeculative), whose choice must not overwrite the global.if (!keepSpeculative) {saveSpeculativeType(loadSpeculativeType);}@@ -1830,9 +1798,8 @@ export function useChatModelRuntime() {const currentParams = useChatRuntimeStore.getState().params;const loadedFields = loadedContextFields(loadResponse);- // The reported window, or where nothing sized one the requested length.- // The request answers only for a backend that sizes nothing: a self-sizing- // one was sent the sentinel, which as a budget is zero.+ // The reported window, or where nothing sized one the requested length: the request answers only+ // for a backend that sizes nothing, a self-sizing one having been sent the sentinel.const loadedContextCap = replayMaxTokensCap(loadedFields.loadedContextLength ??(!loadResponse.is_gguf && effectiveMaxSeqLength > 0@@ -1931,8 +1898,8 @@ export function useChatModelRuntime() {const supportsPreserveThinking =loadResponse.supports_preserve_thinking ?? false;const supportsTools = loadResponse.supports_tools ?? false;- // GLM-5.2-style models report their own effort levels; everything else keeps the default low/medium/high.- // They report high|max.+ // GLM-5.2-style models report their own effort levels (high|max); everything else keeps the+ // default low/medium/high.const reasoningEffortLevels =loadResponse.reasoning_effort_levels &&loadResponse.reasoning_effort_levels.length > 0@@ -2004,12 +1971,9 @@ export function useChatModelRuntime() {loadedNBatch: committedNBatch,...committedServerTuning,// What this model is running, for the rollback below: an omitted field inherited the resident- // process's list, so the last thing we knew still holds unless this was a different model.- // An explicit empty list is recorded as empty, not null, since omitting the field is what- // makes /load inherit. The server's echo comes first, as the only account of what the launch- // carried: a reload that omits the field but sets max_seq_length is stripped of its- // inherited --ctx-size, and the status refresh that would notice runs while- // modelLoading is still true and reseeds nothing.+ // process's list, so the last thing we knew still holds unless this was a different model. An+ // explicit empty list is recorded as empty, not null, since omitting the field is what makes /load+ // inherit. The server's echo comes first, as the only account of what the launch carried.loadedLlamaExtraArgs:loadResponse.requested_llama_extra_args !== undefined? (loadResponse.requested_llama_extra_args ?? [])@@ -2086,7 +2050,6 @@ export function useChatModelRuntime() {} catch (error) {// Skip rollback if the user cancelled: the model is already being unloaded.if (abortCtrl.signal.aborted) throw error;- // If we unloaded a previous model and the new load failed, attempt a rollback.if (previousWasUnloaded && previousCheckpoint) {let rollbackNativePathLease: string | undefined;if (previousActiveNativePathToken) {@@ -2147,8 +2110,7 @@ export function useChatModelRuntime() {tensor_parallel: stateBeforeUnload.loadedTensorParallel ?? false,// What the PREVIOUS server was loaded with. Not the control field, which// applyPerModelConfigToRuntime has already overwritten with the TARGET's setting, and not- // loadedVisionDisabledByUser, which is narrowed to models that can do images. Same- // separately tracked baseline tensor_parallel uses.+ // loadedVisionDisabledByUser, which is narrowed to models that can do images.disable_vision: stateBeforeUnload.loadedDisableVision ?? false,// Restore the previous model's GPU Memory placement, not backend defaults.gpu_memory_mode: stateBeforeUnload.loadedGpuMemoryMode ?? "auto",@@ -2215,8 +2177,7 @@ export function useChatModelRuntime() {loadedDisableVision:rollbackResponse.disable_vision ?? false,// The rolled-back model's own loaded value, matching the request above field for field. Not- // stateBeforeUnload.disableVision, which holds the TARGET's value by now, and not the echo- // either, since the replayed request is gated on the model having a projector.+ // stateBeforeUnload.disableVision, which holds the TARGET's value by now, and not the echo either.disableVision: stateBeforeUnload.loadedDisableVision ?? false,loadedVisionDisabledByUser:rollbackResponse.vision_disabled_by_user ?? false,@@ -2348,8 +2309,7 @@ export function useChatModelRuntime() {dlSamples,);// loadProgress state is only read by the dismissed-toast inline status, and writing it while the- // toast is visible re-renders the whole chat page every poll (janky in WebView2). Feed the- // toast directly instead.+ // toast is visible re-renders the whole chat page every poll. Feed the toast directly instead.if (loadToastDismissedRef.current) {setLoadProgress({percent: pct,diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.tsindex 1135d0db7d4..c08f95ec381 100644--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts@@ -190,8 +190,7 @@ export function applyActiveModelStatusToStore(const reasoningAlwaysOn = status.reasoning_always_on ?? false;const reasoningStyle = status.reasoning_style ?? "enable_thinking";// GLM-5.2-style models report their own effort levels; everything else keeps the default- // low/medium/high.- // They report high|max.+ // low/medium/high. They report high|max.const reasoningEffortLevels =status.reasoning_effort_levels && status.reasoning_effort_levels.length > 0? (status.reasoning_effort_levels as ReasoningEffort[])@@ -217,18 +216,16 @@ export function applyActiveModelStatusToStore(// While a load is in flight, performLoad owns the load params. Seeding them// from a stale poll here would clobber the values the load dialog just set.const seedLoadParams = options.seedLoadParams ?? !prevState.modelLoading;- // A model/variant change underneath this tab. The controls in the store belong- // to the model that just left, so they are reseeded here the way every other- // load param at this site already is: the echo cannot stand in, since a new- // model can report the old count.+ // A model/variant change underneath this tab. The controls in the store belong to the model that+ // just left, so they are reseeded here the way every other load param at this site already is:+ // the echo cannot stand in, since a new model can report the old count.const slotsModelChanged = hydratingExistingModel;- // This model's remembered override, read only on a fresh store or a model- // change, so a steady poll cannot re-pin a control the user just blanked. A- // self-sizing backend has no slot fields, so an unseeded store says nothing- // about it and it goes by the checkpoint alone.- // Through the resident resolver, not the raw id: an API-driven load reports the- // snapshot path a cached repo loaded from, while its settings are keyed by the- // repo id, and the plain lookup misses that record.+ // This model's remembered override, read only on a fresh store or a model change, so a steady+ // poll cannot re-pin a control the user just blanked. A self-sizing backend has no slot fields,+ // so an unseeded store says nothing about it and it goes by the checkpoint alone. Through the+ // resident resolver, not the raw id: an API-driven load reports the snapshot path a cached repo+ // loaded from, while its settings are keyed by the repo id, and the plain lookup misses that+ // record.const slotsUnseeded =prevState.loadedNParallel === null && prevState.nParallel === null;// same rule for the batch-size pair@@ -317,8 +314,7 @@ export function applyActiveModelStatusToStore(isMlx: status.is_mlx ?? false,seedLoadParams,modelChanged: slotsModelChanged,- // Both fields: a record written before the MLX pin moved still carries it- // in maxSeqLength.+ // Both fields: a record written before the MLX pin moved still carries it in maxSeqLength.remembered: remembered?.remembered ? savedContextPin(remembered.config) : null,// Raw, not the normalised incomingGpuMode/incomingGpuLayers below: the rule// needs "Manual with AUTO layers", and those normalise layers to null off@@ -637,9 +633,8 @@ export function applyActiveModelStatusToStore(hydratingExistingModel &&storedReasoningEnabled === null) {- // Anchored regex: first "Xb"/"X.Xb" after start or [-_/.] so the version literal in- // "qwen3.5" / "qwen3.6" does not match first, and "Qwen3.5-35B-A3B" yields 35 (total), not 3- // (active).+ // Anchored regex: first "Xb"/"X.Xb" after start or [-_/.] so the version literal in "qwen3.5" /+ // "qwen3.6" does not match first, and "Qwen3.5-35B-A3B" yields 35 (total), not 3 (active).// Mirrors use-chat-model-runtime.ts and the inline regex in llama_cpp.py.let reasoningDefault = true;const mid = checkpointId.toLowerCase();@@ -668,11 +663,10 @@ export function applyActiveModelStatusToStore(reasoningAlwaysOn || useChatRuntimeStore.getState().reasoningEnabled,);- // Every status merge carries the base family recommendation, including the- // refresh immediately after performLoad. Layer the active Qwen mode over it- // so that refresh cannot undo performLoad's thinking table. This also covers- // startup/CLI/external adoption, while model memory still wins because this- // remains a defaults update.+ // Every status merge carries the base family recommendation, including the refresh immediately+ // after performLoad. Layer the active Qwen mode over it so that refresh cannot undo performLoad's+ // thinking table. This also covers startup/CLI/external adoption, while model memory still wins+ // because this remains a defaults update.if (status.inference && supportsReasoning) {const current = useChatRuntimeStore.getState();const qwenParams = resolveQwenThinkingParams(diff --git a/studio/frontend/src/features/chat/lib/resident-config-match.ts b/studio/frontend/src/features/chat/lib/resident-config-match.tsindex f078ba59716..387f4d91b93 100644--- a/studio/frontend/src/features/chat/lib/resident-config-match.ts+++ b/studio/frontend/src/features/chat/lib/resident-config-match.ts@@ -307,11 +307,10 @@ const SETTING_CHECKS: SettingCheck[] = [},{chatOnly: true,- // Always pinned: the status echoes what the load requested, so a resident server- // that asked for nothing reports null and a blank control agrees with it. Reading- // blank as "no opinion" instead would mean clearing the dtype back to the f16- // default never relaunched, leaving the server on the quantized draft cache the- // panel no longer shows.+ // Always pinned: the status echoes what the load requested, so a resident server that asked for+ // nothing reports null and a blank control agrees with it. Reading blank as "no opinion"+ // instead would mean clearing the dtype back to the f16 default never relaunched, leaving the+ // server on the quantized draft cache the panel no longer shows.pinned: () => true,agrees: (c, s) =>(c.specDraftCacheDtype ?? null) ===diff --git a/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.ts b/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.tsindex 071ba822f4d..782e6963557 100644--- a/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.ts+++ b/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.ts@@ -78,13 +78,12 @@ export function resolveCtxPinSeed(options: {if (isMlx) {return { customContextLength: incoming, loadedCustomContextLength: incoming };}- // One placement mode has no ambiguity to reason around: under Manual memory- // with Auto layers the load sends its pin as max_seq_length through- // resolveFitMaxSeqLength, which answers `customContextLength > 0 ? it : 0`.- // Auto there is 0 on the wire, always, so a POSITIVE echo in this mode is- // proof of an explicit pin rather than evidence of nothing. Read before the- // branches below because it outranks both of them: it is better evidence than- // a saved config, and on a model change it describes the model that arrived.+ // One placement mode has no ambiguity to reason around: under Manual memory with Auto layers the+ // load sends its pin as max_seq_length through resolveFitMaxSeqLength, which answers+ // `customContextLength > 0 ? it : 0`. Auto there is 0 on the wire, always, so a POSITIVE echo in+ // this mode is proof of an explicit pin rather than evidence of nothing. Read before the branches+ // below because it outranks both of them: it is better evidence than a saved config, and on a+ // model change it describes the model that arrived.if (gpuMemoryMode === "manual" && gpuLayers != null && gpuLayers < 0) {return { customContextLength: incoming, loadedCustomContextLength: incoming };}diff --git a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsxindex b2686b6e7a9..f4ab5a97592 100644--- a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx+++ b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx@@ -205,8 +205,7 @@ function contentBlocksToText(content: unknown): string {parts.push("[thinking]\n" + thinkText + "\n[/thinking]");}} else if (p.type === "tool-call") {- // Keep base64 image payloads and sandbox card metadata out of every export format: use the- // model-visible text, matching chat replay.+ // Keep base64 image payloads and sandbox card metadata out of every export format: use the model-visible text, matching chat replay.const result = toolResultModelText(p.result,typeof p.toolName === "string" ? p.toolName : undefined,@@ -243,8 +242,7 @@ async function loadConversationMessages(toast.info(emptyMessage);return null;}- // No parentId = legacy flat thread (already DB createdAt-sorted); walking the chain would invert- // order, so keep raw order.+ // No parentId = legacy flat thread (already DB createdAt-sorted); walking the chain would invert order.const hasParentIds = raw.some((m) => (m as { parentId?: unknown }).parentId != null);if (!hasParentIds) return raw;return orderByParentChain(raw, { includeSiblings }) as typeof raw;@@ -262,8 +260,7 @@ function messageToText(msg: { content: unknown; attachments?: unknown }): stringif (Array.isArray(msg.attachments)) {for (const attachment of msg.attachments as Array<{ content?: unknown }>) {if (!attachment?.content) continue;- // A paste carries a wrapper the same text never had when it fitted inline, so strip it rather- // than exporting the marker.+ // A paste carries a wrapper the same text never had when it fitted inline, so strip it rather than exporting the marker.const attText = unwrapPastedTextContent(contentBlocksToText(attachment.content),);@@ -273,8 +270,7 @@ function messageToText(msg: { content: unknown; attachments?: unknown }): stringreturn parts.join("\n\n");}-// Markdown counterpart to messageToText: same content and attachments, but each part keeps its-// shape so the renderer can fence tool calls and collapse thinking.+// Markdown counterpart to messageToText: same content and attachments, but each part keeps its shape so the renderer can fence tool calls and collapse thinking.function messageToMarkdown(msg: { content: unknown; attachments?: unknown }): string {const normalizeToolResult = toolResultModelText;const blocks = contentBlocksToMarkdownBlocks(msg.content, normalizeToolResult);@@ -296,9 +292,7 @@ function messageToMarkdown(msg: { content: unknown; attachments?: unknown }): streturn renderConversationBlocks(blocks);}-// OpenAI messages array (tool-calling + multimodal fine-tuning): tool calls to "tool_calls" plus-// separate "role":"tool" messages; images to "image_url" parts; audio dropped; thinking kept-// as a text part.+// OpenAI messages array (tool-calling + multimodal fine-tuning): tool calls to "tool_calls" plus separate "role":"tool" messages; images to "image_url" parts; audio dropped; thinking kept as a text part.type OAIContentPart =| { type: "text"; text: string }@@ -356,8 +350,7 @@ function messageToOpenAI(msg: { role: unknown; content: unknown; attachments?: u);toolCalls.push({ id, type: "function", function: { name, arguments: argsStr } });if (p.result !== undefined && p.result !== null) {- // Keep base64 image payloads out of exports: MCP image results carry their model-visible text- // alongside the data, so serialize the text instead of the full object.+ // Keep base64 image payloads out of exports: MCP image results carry their model-visible text alongside the data, so serialize the text instead of the full object.const modelText = toolResultModelText(p.result, name);const resultStr =typeof modelText === "string" ? modelText : JSON.stringify(modelText);@@ -416,8 +409,7 @@ export async function exportConversationShareGPT(threadId: string): Promise<void);}-// OpenAI/ChatML JSONL: {"messages": [{"role","content"}, ...]} per conversation; Unsloth reads-// this as a ChatML dataset.+// OpenAI/ChatML JSONL: {"messages": [{"role","content"}, ...]} per conversation; Unsloth reads this as a ChatML dataset.export async function exportConversationRawJsonl(threadId: string): Promise<void> {return exportConversationJsonl(threadId, "training");}@@ -480,8 +472,7 @@ export const exportConversationMarkdown = createConversationMarkdownExporter({notifyNoContent: () => toast.info("No exportable content."),});-// "skipped" is an empty conversation, which has already said so and must not stop the rest of a-// pair; "failed" has toasted a reason, so stop there rather than stack a second one.+// "skipped" is an empty conversation, which has already said so and must not stop the rest of a pair; "failed" has toasted a reason, so stop there rather than stack a second one.type SaveSourceOutcome = "saved" | "skipped" | "failed";async function saveConversationAsProjectSource(@@ -496,8 +487,7 @@ async function saveConversationAsProjectSource(const markdown = buildConversationMarkdown(messages.map((msg) => ({role: String(msg.role ?? ""),- // As the markdown exporter does: a project source is retrieved back into context, so the- // renderer's tokens must not be saved as prose.+ // As the markdown exporter does: a project source is retrieved back into context, so the renderer's tokens must not be saved as prose.content: stripSearchImageTokens(messageToMarkdown(msg)),})),);@@ -536,9 +526,7 @@ export async function saveChatItemAsProjectSource(}}-/** A sidebar row as one markdown document. The halves of a compare pair are named after their- * models, as saving them to project sources does: the two arrive in whichever order they- * last answered in, so position alone would label them wrong. */+/** A sidebar row as one markdown document. The halves of a compare pair are named after their models, as saving to project sources does: the two arrive in whichever order they last answered in, so position alone would label them wrong. */export async function buildChatItemMarkdown(item: {id: string;title: string;@@ -678,8 +666,7 @@ export async function exportBulkConversationsSeparate(await downloadBlob(zipped, `${basename}.zip`, "application/zip");}-// Scope-level bulk export shared by the sidebar Recents menu and Settings > Chat > Data.-// "recents" = chats outside projects; "all" adds project chats.+// Scope-level bulk export shared by the sidebar Recents menu and Settings > Chat > Data. "recents" = chats outside projects; "all" adds project chats.export async function bulkExportConversationsByScope(scope: "recents" | "all",format: ConvExportFormat,@@ -722,9 +709,7 @@ export async function exportProjectConversations();}-// One JSONL line per conversation, string-only content in system/user/assistant turns: Unsloth's-// training tab detects this as ChatML natively and it works with train-on-completions-// masking. Reasoning, tool calls and images are dropped for clean SFT targets.+// One JSONL line per conversation, string-only content in system/user/assistant turns: the training tab detects this as ChatML natively and it works with train-on-completions masking. Reasoning, tool calls and images are dropped for clean SFT targets.export type FineTuneMessage = {role: "system" | "user" | "assistant";@@ -739,13 +724,11 @@ function messageToPlainText(msg: {attachments?: unknown;}): string {const parts: string[] = [];- // Only attachment text is unwrapped: a message body is verbatim, and may legitimately quote the- // wrapper syntax in a code sample.+ // Only attachment text is unwrapped: a message body is verbatim, and may legitimately quote the wrapper syntax in a code sample.const collect = (blocks: unknown, fromAttachment = false) => {const normalize = fromAttachment? unwrapPastedTextContent: (text: string) => text;- // Legacy and imported histories can store content as a plain string.if (typeof blocks === "string") {if (blocks.trim()) parts.push(normalize(blocks));return;@@ -784,9 +767,7 @@ function mergeSameRoleTurns(turns: FineTuneMessage[]): FineTuneMessage[] {return merged;}-/** Conversation turns for fine-tuning, or null when the thread has no usable user + assistant- * exchange. Consecutive same-role turns merge, assistant turns before the first user turn- * drop (a target with no prompt teaches nothing), and trailing non-assistant turns drop. */+/** Conversation turns for fine-tuning, or null when the thread has no usable user + assistant exchange. Consecutive same-role turns merge, assistant turns before the first user turn drop (a target with no prompt teaches nothing), and trailing non-assistant turns drop. */function messagesToFineTuneTurns(messages: Array<{ role: unknown; content: unknown; attachments?: unknown }>,): FineTuneMessage[] | null {@@ -826,9 +807,7 @@ const SHAREGPT_FROM: Record<FineTuneMessage["role"], string> = {assistant: "gpt",};-/** JSONL lines for one conversation in the chosen format. Alpaca is single-turn, so each user to- * assistant pair becomes its own record with the system prompt and earlier exchange in the- * input field. */+/** JSONL lines for one conversation in the chosen format. Alpaca is single-turn, so each user to assistant pair becomes its own record with the system prompt and earlier exchange in the input field. */function turnsToFineTuneLines(turns: FineTuneMessage[],format: FineTuneFormat,@@ -890,8 +869,7 @@ export async function buildFineTuneJsonl(const hasParentIds = raw.some((m) => (m as { parentId?: unknown }).parentId != null,);- // Chain only: retries/regenerations leave sibling branches, and mixing alternate replies into one- // conversation corrupts the training targets.+ // Chain only: retries/regenerations leave sibling branches, and mixing alternate replies into one conversation corrupts the training targets.const ordered = hasParentIds? (orderByParentChain(raw, { includeSiblings: false }) as typeof raw): raw;@@ -930,8 +908,7 @@ export async function exportFineTuneJsonl(return conversations;}-// ShareGPT training exports: prompt to one record (human turn + empty gpt slot); list to one-// multi-turn record, each item a human turn.+// ShareGPT training exports: prompt to one record (human turn + empty gpt slot); list to one multi-turn record, each item a human turn.function exportPromptTrainingJsonl(entry: PromptEntry): Promise<void> {const record = {conversations: [@@ -1334,21 +1311,15 @@ function ExportModal({);}-// Unsaved edits live in the parent keyed by entry id, so switching rows in the rail never-// silently throws away what you typed.+// Unsaved edits live in the parent keyed by entry id, so switching rows in the rail never silently throws away what you typed.type PromptDraft = { name: string; text: string };type ListDraft = { name: string; items: string[] };-// Factories, not shared constants: every reset would otherwise hand back the same `items` array,-// one in-place edit from corrupting it for good.+// Factories, not shared constants: every reset would otherwise hand back the same `items` array, one in-place edit from corrupting it for good.const emptyPromptDraft = (): PromptDraft => ({ name: "", text: "" });const emptyListDraft = (): ListDraft => ({ name: "", items: ["", ""] });-// Selecting the Lists tab auto-selects its first row, and one controlled textarea per item makes-// that cost grow faster than the item count: in Chromium 100 items settle in 247ms, 200 in 568ms,-// 500 in 2.5s and 2000 in 36s, against a flat 80ms on the collapsed card this replaced. The backend-// accepts 10000 items in one list (routes/prompts.py), which an import can produce, so past this-// many the editor waits to be asked for; save, run and export all still read the full items.+// Selecting the Lists tab auto-selects its first row, and one controlled textarea per item makes that cost grow faster than the item count: in Chromium 100 items settle in 247ms, 500 in 2.5s and 2000 in 36s, against a flat 80ms on the collapsed card this replaced. The backend accepts 10000 items in one list (routes/prompts.py), so past this many the editor waits to be asked for; save, run and export still read the full items.const EDITOR_ROW_LIMIT = 100;function relativeTime(ts: number): string {@@ -1363,8 +1334,7 @@ function relativeTime(ts: number): string {return new Date(ts).toLocaleDateString();}-// `current` drives the roving tabindex and stays true while a New form covers the pane: without-// it every row is tabbable, so reaching the editor means tabbing through the library.+// `current` drives the roving tabindex and stays true while a New form covers the pane: without it every row is tabbable, so reaching the editor means tabbing through the library.function RailRow({title,preview,@@ -1443,8 +1413,7 @@ function EmptyDetail({);}-// Deleting a dirty entry destroys the stored copy and the only copy of the unsaved draft at once,-// so that case asks first.+// Deleting a dirty entry destroys the stored copy and the only copy of the unsaved draft at once, so that case asks first.function UnsavedDeleteConfirm({open,onOpenChange,@@ -1524,14 +1493,11 @@ function PromptDetail({[name, text, entry.name, entry.text, onDraftChange],);- // One mutation at a time, and the lock lives in the parent: this pane is keyed by row id, so- // selecting another row unmounts it and a local lock would come back false. PUT is an- // unconditional upsert, so a Save still in flight can land after a DELETE.+ // One mutation at a time, and the lock lives in the parent: this pane is keyed by row id, so selecting another row unmounts it and a local lock would come back false. PUT is an unconditional upsert, so a Save still in flight can land after a DELETE.const handleSave = useCallback(async () => {const trimText = text.trim();if (!trimText) return;- // Snapshot what is going to the server: the editor stays usable while the request is in flight,- // so the draft can move on before it resolves.+ // Snapshot what is going to the server: the editor stays usable while the request is in flight, so the draft can move on before it resolves.const submitted: PromptDraft = { name, text };await runMutation(lockKey("prompt", entry.id), async () => {try {@@ -1541,8 +1507,7 @@ function PromptDetail({text: trimText,updatedAt: now(),});- // Refresh before dropping the draft. Dropping it first uncovers the pre-save copy this pane still- // holds, so the editor flashes the old text until the fetch lands.+ // Refresh before dropping the draft, or the pre-save copy this pane still holds flashes the old text until the fetch lands.await onRefresh();onSaved(submitted);} catch (err) {@@ -1564,17 +1529,14 @@ function PromptDetail({return;}onDraftChange(undefined);- // Refresh before clearing, or the keep-a-row-selected pass runs against a list that still holds- // this row and can select the deleted entry back.+ // Refresh before clearing, or the keep-a-row-selected pass runs against a list that still holds this row and can select the deleted entry back.await onRefresh();- // Id goes up so the parent only clears if this row is still selected: the delete is awaited, and- // a click elsewhere meanwhile would be undone.+ // Id goes up so the parent only clears if this row is still selected: the delete is awaited, and a click elsewhere meanwhile would be undone.onDeleted(entry.id);});}, [entry.id, onDraftChange, onDeleted, onRefresh, runMutation]);- // Export what the pane shows, normalised as saving would, or a dirty entry writes a file that does- // not match the screen.+ // Export what the pane shows, normalised as saving would, or a dirty entry writes a file that does not match the screen.const exportValue: PromptEntry = dirty? { ...entry, name: name.trim() || "Untitled Prompt", text: text.trim() }: entry;@@ -1678,10 +1640,7 @@ function PromptDetail({);}-// A create has no row id yet, so it cannot use the by-id mutation lock above. The ref is the-// authority because React state is not readable straight after scheduling it. Call this above-// the New forms, never inside one: selecting a rail row unmounts the form, and a guard that-// dies with it comes back false while its request is still out.+// A create has no row id yet, so it cannot use the by-id mutation lock above. The ref is the authority because React state is not readable straight after scheduling it. Call this above the New forms, never inside one: selecting a rail row unmounts the form, and a guard that dies with it comes back false while its request is still out.function useCreateGuard(): {creating: boolean;create: (fn: () => Promise<void>) => Promise<void>;@@ -1702,8 +1661,7 @@ function useCreateGuard(): {return { creating, create };}-// Draft lives in the parent, like the edit drafts: selecting a row hides this form, and local-// state would be discarded with it.+// Draft lives in the parent, like the edit drafts: selecting a row hides this form, and local state would be discarded with it.function NewPromptForm({draft,onDraftChange,@@ -1724,9 +1682,7 @@ function NewPromptForm({const { name, text } = draft;const setName = (value: string) => onDraftChange({ ...draft, name: value });const setText = (value: string) => onDraftChange({ ...draft, text: value });- // A create outlives the form that started it, so this answers "is the form the user is looking at- // still mine". Set in setup, not just at the ref: StrictMode replays setup, cleanup, setup,- // and the flag would stay false from that first cleanup for the pane's whole life.+ // A create outlives the form that started it, so this answers "is the form the user is looking at still mine". Set in setup, not just at the ref: StrictMode replays setup, cleanup, setup, and the flag would stay false from that first cleanup for the pane's whole life.const mounted = useRef(true);useEffect(() => {mounted.current = true;@@ -1742,8 +1698,7 @@ function NewPromptForm({if (!trimText) return;const ts = now();const id = newId();- // What the request carries: the fields stay editable while it is out, so the draft can move on- // before it resolves.+ // What the request carries: the fields stay editable while it is out, so the draft can move on before it resolves.const submitted: PromptDraft = { name, text };try {await savePromptEntry({@@ -1754,18 +1709,15 @@ function NewPromptForm({updatedAt: ts,});} catch (err) {- // Without this the rejection is unhandled and the form just sits there, so the prompt looks saved- // until the dialog is reopened.+ // Without this the rejection is unhandled and the form just sits there, so the prompt looks saved until the dialog is reopened.toast.error("Could not create prompt", {description: err instanceof Error ? err.message : "Please try again.",});return;}- // Await the refresh first, or the keep-a-row-selected effect runs against a list without the new- // id and bounces the selection off it.+ // Await the refresh first, or the keep-a-row-selected effect runs against a list without the new id and bounces the selection off it.await onRefresh();- // The parent resets the draft if it still holds what was sent, and moves the view to the new row- // only while this form is still on screen.+ // The parent resets the draft if it still holds what was sent, and moves the view to the new row only while this form is still on screen.onCreated(id, submitted, mounted.current);}),[name, text, create, onRefresh, onCreated],@@ -1827,8 +1779,7 @@ function PromptListDetail({const name = draft?.name ?? entry.name;const items = draft?.items ?? entry.items;- // Decided once per list and latched: this pane is keyed by row id, so selecting another list- // re-decides it, but Add prompt taking a 100-item list to 101 must not unmount the editor.+ // Decided once per list and latched: this pane is keyed by row id, so selecting another list re-decides it, but Add prompt taking a 100-item list to 101 must not unmount the editor.const [editorMounted, setEditorMounted] = useState(() => items.length <= EDITOR_ROW_LIMIT,);@@ -1848,12 +1799,10 @@ function PromptListDetail({[name, items, entry.name, entry.items, onDraftChange],);- // See PromptDetail: a Save landing after a DELETE would upsert the row back, and the lock is the- // parent's because this pane unmounts on a row switch.+ // See PromptDetail: a Save landing after a DELETE would upsert the row back, and the lock is the parent's because this pane unmounts on a row switch.const handleSave = useCallback(async () => {const filtered = items.filter((t) => t.trim());if (filtered.length === 0) return;- // See PromptDetail: the editor stays usable while the request is in flight.const submitted: ListDraft = { name, items };await runMutation(lockKey("list", entry.id), async () => {try {@@ -1863,7 +1812,6 @@ function PromptListDetail({items: filtered,updatedAt: now(),});- // See PromptDetail: the draft is what covers the pre-save entry.await onRefresh();onSaved(submitted);} catch (err) {@@ -1885,15 +1833,12 @@ function PromptListDetail({return;}onDraftChange(undefined);- // See PromptDetail: clearing first can reselect the row being deleted.await onRefresh();- // See PromptDetail: only the parent knows whether this row is still current.onDeleted(entry.id);});}, [entry.id, onDraftChange, onDeleted, onRefresh, runMutation]);- // Run what the editor shows. Off entry.items, deleting every draft item left the button enabled- // on the stored length and ran the old list.+ // Run what the editor shows. Off entry.items, deleting every draft item left the button enabled on the stored length and ran the old list.const runnableItems = items.filter((t) => t.trim());// See PromptDetail: export the visible draft, not the last saved copy.@@ -2028,8 +1973,7 @@ function PromptListDetail({);}-// See NewPromptForm: the in-progress list lives in the parent so clicking a row in the rail-// cannot silently discard a partially authored list.+// See NewPromptForm: the in-progress list lives in the parent so clicking a row in the rail cannot silently discard a partially authored list.function NewPromptListForm({draft,onDraftChange,@@ -2050,7 +1994,6 @@ function NewPromptListForm({const { name, items } = draft;const setName = (value: string) => onDraftChange({ ...draft, name: value });const setItems = (value: string[]) => onDraftChange({ ...draft, items: value });- // See NewPromptForm, including why the flag is set in setup.const mounted = useRef(true);useEffect(() => {mounted.current = true;@@ -2066,7 +2009,6 @@ function NewPromptListForm({if (filtered.length === 0) return;const ts = now();const id = newId();- // See NewPromptForm: the editor stays usable while the request is out.const submitted: ListDraft = { name, items };try {await savePromptList({@@ -2077,13 +2019,11 @@ function NewPromptListForm({updatedAt: ts,});} catch (err) {- // See NewPromptForm: an unhandled rejection reads as a saved list.toast.error("Could not create list", {description: err instanceof Error ? err.message : "Please try again.",});return;}- // See NewPromptForm: select only once the refreshed list contains the id.await onRefresh();onCreated(id, submitted, mounted.current);}),@@ -2157,8 +2097,7 @@ export function PromptStorageDialog({const [promptLists, setPromptLists] = useState<PromptListEntry[]>([]);const [selectedPromptId, setSelectedPromptId] = useState<string | null>(null);const [selectedListId, setSelectedListId] = useState<string | null>(null);- // Maps, not plain objects: ids are arbitrary strings, so one named "constructor" would resolve to- // an inherited prototype member.+ // Maps, not plain objects: ids are arbitrary strings, so one named "constructor" would resolve to an inherited prototype member.const [promptDrafts, setPromptDrafts] = useState<Map<string, PromptDraft>>(() => new Map(),);@@ -2166,7 +2105,7 @@ export function PromptStorageDialog({() => new Map(),);- // In-progress new entries, held here rather than inside the forms so that hiding a form does not destroy the work.+ // In-progress new entries, held here rather than inside the forms so hiding a form does not destroy the work.const [newPromptDraft, setNewPromptDraft] = useState<PromptDraft>(emptyPromptDraft);const [newListDraft, setNewListDraft] = useState<ListDraft>(emptyListDraft);const newPromptStarted =@@ -2198,21 +2137,16 @@ export function PromptStorageDialog({});}, []);- // Mutation locks live here rather than in the detail panes, which are keyed by row id and unmount- // the moment another row is selected. Held by id until the request settles, or a Save in- // flight during a row switch comes back unlocked and its PUT can land after a DELETE.+ // Mutation locks live here rather than in the detail panes, which are keyed by row id and unmount the moment another row is selected. Held by id until the request settles, or a Save in flight during a row switch comes back unlocked and its PUT can land after a DELETE.const [mutatingIds, setMutatingIds] = useState<ReadonlySet<string>>(() => new Set<string>(),);- // The ref is the authority, not the state: a functional updater is not guaranteed to run during- // setState, so reading the outcome straight after scheduling one can see a stale answer, skip- // the request, and still acquire the id later during render with nothing to release it.+ // The ref is the authority, not the state: a functional updater is not guaranteed to run during setState, so reading the outcome straight after scheduling one can see a stale answer, skip the request, and still acquire the id later during render with nothing to release it.const mutatingRef = useRef<ReadonlySet<string>>(new Set<string>());const runMutation = useCallback(async (id: string, fn: () => Promise<void>) => {const [held, started] = acquire(mutatingRef.current, id);- // The buttons are disabled while locked, but a second caller reaching here anyway must not run and- // must not clear the first one's lock.+ // The buttons are disabled while locked, but a second caller reaching here anyway must not run and must not clear the first one's lock.if (!started) return;mutatingRef.current = held;setMutatingIds(held);@@ -2226,13 +2160,11 @@ export function PromptStorageDialog({[],);- // Above the New forms, not inside them: selecting a rail row unmounts the form while its create is- // still out, and a guard mounted with it would let reopening New mint a second id.+ // Above the New forms, not inside them: selecting a rail row unmounts the form while its create is still out, and a guard mounted with it would let reopening New mint a second id.const promptCreate = useCreateGuard();const listCreate = useCreateGuard();- // Only drop the draft if it still holds what the request carried: anything typed while the save- // was in flight is the user's most recent intent.+ // Only drop the draft if it still holds what the request carried: anything typed while the save was in flight is the user's most recent intent.const clearPromptDraftIfSaved = useCallback((id: string, submitted: PromptDraft) => {setPromptDrafts((prev) => {@@ -2272,9 +2204,7 @@ export function PromptStorageDialog({}}, [open, refreshEntries, refreshLists]);- // In the handler, not an effect keyed to activeTab: an effect leaves one render of the new tab- // still holding the old query, and the keep-a-row-selected pass runs in it and drops the row- // that tab had selected.+ // In the handler, not an effect keyed to activeTab: an effect leaves one render of the new tab still holding the old query, and the keep-a-row-selected pass runs in it and drops that tab's row.const selectTab = useCallback((tab: Tab) => {setActiveTab(tab);setSearchQuery("");@@ -2283,16 +2213,13 @@ export function PromptStorageDialog({setShowNewList(false);}, []);- // Clear the search too: an active one the new entry does not match keeps it out of the filtered- // rail. The draft resets only when it still holds what was sent, since the fields stay- // editable while the create is out.+ // Clear the search too: an active one the new entry does not match keeps it out of the filtered rail. The draft resets only when it still holds what was sent, since the fields stay editable while the create is out.const selectCreatedPrompt = useCallback((id: string, submitted: PromptDraft, fromOpenForm: boolean) => {setNewPromptDraft((prev) =>samePromptDraft(prev, submitted) ? emptyPromptDraft() : prev,);- // The user left the form while the request was out, so they are looking at something else on- // purpose. Take the refresh, leave the view alone.+ // The user left the form while the request was out, so they are looking at something else on purpose. Take the refresh, leave the view alone.if (!fromOpenForm) return;setSearchQuery("");setSelectedPromptId(id);@@ -2330,9 +2257,7 @@ export function PromptStorageDialog({return all.filter((e) => e.name.toLowerCase().includes(q));}, [promptLists, searchQuery]);- // Keep a row selected whenever the filtered rail is non-empty. During render, not in an effect:- // an effect paints the blank pane once before correcting it. The visible tab only, since- // searchQuery is shared and correcting against the hidden one dropped the row selected there.+ // Keep a row selected whenever the filtered rail is non-empty. During render, not in an effect: an effect paints the blank pane once before correcting it. The visible tab only, since searchQuery is shared and correcting against the hidden one dropped the row selected there.if (activeTab === "prompts") {if (filteredPrompts.length === 0) {if (selectedPromptId !== null) setSelectedPromptId(null);@@ -2373,8 +2298,7 @@ export function PromptStorageDialog({[onUse, onOpenChange],);- // The rail is one tab stop; arrows move within it. Clicking rather than setting the id keeps the- // two tabs on one handler.+ // The rail is one tab stop; arrows move within it. Clicking rather than setting the id keeps the two tabs on one handler.const handleRailKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;const rows = Array.from(diff --git a/studio/frontend/src/features/chat/provider-capabilities.ts b/studio/frontend/src/features/chat/provider-capabilities.tsindex 7ef5a16a90c..b31642fda2c 100644--- a/studio/frontend/src/features/chat/provider-capabilities.ts+++ b/studio/frontend/src/features/chat/provider-capabilities.ts@@ -111,12 +111,10 @@ const EXTERNAL_MAX_OUTPUT_TOKENS_BY_MODEL: Array<{prefixes: readonly string[];cap: number;}> = [- // OpenAI. The Responses API rejects an over-limit max_output_tokens rather- // than clamping it, so an overstated cap is a failed request and an- // understated one only a shorter answer. First match wins: a bare family- // prefix (`gpt-5`, `gpt-4`) goes last or it swallows its own minors, and the- // `-chat-latest` aliases go first because they cap at 16,384 whatever their- // family does.+ // OpenAI. The Responses API rejects an over-limit max_output_tokens rather than clamping it, so+ // an overstated cap is a failed request and an understated one only a shorter answer. First match+ // wins: a bare family prefix (`gpt-5`, `gpt-4`) goes last or it swallows its own minors, and the+ // `-chat-latest` aliases go first because they cap at 16,384 whatever their family does.{providerType: "openai",prefixes: [@@ -146,7 +144,6 @@ const EXTERNAL_MAX_OUTPUT_TOKENS_BY_MODEL: Array<{cap: 4096,},{ providerType: "openai", prefixes: ["gpt-4"], cap: 8192 },- // Anthropic{providerType: "anthropic",prefixes: [@@ -178,7 +175,6 @@ const EXTERNAL_MAX_OUTPUT_TOKENS_BY_MODEL: Array<{prefixes: ["claude-opus-4-1", "claude-opus-4-20250514"],cap: 32000,},- // Gemini{providerType: "gemini",prefixes: ["gemini-3", "gemini-pro", "gemini-flash"],@@ -901,10 +897,9 @@ function resolveGeminiReasoningCapabilities(// Image generation; no thinking knob.return withEnableThinkingStyle();}- // Gemini 2.5 Flash-Lite: thinkingBudget 0 = off, positive from 512. Must be checked- // BEFORE the broader `gemini-2.5-flash` prefix.- // The backend maps "minimal" to that 512 floor in _stream_gemini.- // https://ai.google.dev/gemini-api/docs/thinking+ // Gemini 2.5 Flash-Lite: thinkingBudget 0 = off, positive from 512. Must be checked BEFORE the+ // broader `gemini-2.5-flash` prefix. The backend maps "minimal" to that 512 floor in+ // _stream_gemini. https://ai.google.dev/gemini-api/docs/thinkingif (m.startsWith("gemini-2.5-flash-lite")) {return withReasoningEffortStyle({supportsReasoning: true,diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 7e1f51c3b9c..89ca5735795 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -227,10 +227,9 @@ class PreStreamAwareAttachmentAdapter implements AttachmentAdapter {}add(state: { file: File }) {- // A composite picks its adapter synchronously from the name and MIME type,- // and both say "video" for an audio-only 3GP recording, so settle that from- // the container's own tracks first, as the native readers do. Every other- // file goes straight through, keeping the delegate's own return.+ // A composite picks its adapter synchronously from the name and MIME type, and both say "video"+ // for an audio-only 3GP recording, so settle that from the container's own tracks first, as the+ // native readers do. Every other file goes straight through, keeping the delegate's own return.if (!needsAttachmentTrackInspection(state.file)) {return this.delegate.add(state);}@@ -367,10 +366,9 @@ class VisionImageAdapter implements AttachmentAdapter {class PDFAttachmentAdapter implements AttachmentAdapter {accept = "application/pdf";- // Refused here, not at send: the composer empties itself before it awaits send(), so a ceiling- // that only fires there discards the typed message too. The throw is invisible: nothing- // subscribes to attachmentAddError and the picker never awaits addAttachment, so the toast is- // the only thing telling the user why no file appeared.+ // Refused here, not at send: the composer empties itself before it awaits send(), so a ceiling that+ // only fires there discards the typed message too. The throw is invisible (nothing subscribes to+ // attachmentAddError and the picker never awaits addAttachment), so the toast is the only reason given.add({ file }: { file: File }): Promise<PendingAttachment> {const sizeError = getDocumentAttachmentSizeError(file, "PDF");if (sizeError) {@@ -806,10 +804,9 @@ function toThreadMessage(m: MessageRecord): ThreadMessage {generationStatus === "completed" &&custom.generationSettled !== true;// Persisted metadata alone must never restore a running message: a run that never terminalised- // still says "running" on every later load, and `{type:"running"}` unmounts Send. Ask- // whether the run is corroborated live, else show the partial as interrupted, which keeps- // every character and offers Continue. Unfinished runs only: a completed-but-unsettled run- // has a terminal status and is replayed by the follow instead.+ // still says "running" on every later load, and `{type:"running"}` unmounts Send. Ask whether the+ // run is corroborated live, else show the partial as interrupted, which keeps every character and+ // offers Continue. Unfinished runs only: a completed-but-unsettled run is replayed by the follow.const needsGenerationRecovery =generationUnsettled ||(generationUnfinished && generationIsCorroboratedLive(custom, m.threadId));@@ -1431,7 +1428,6 @@ function createStudioDbAdapter(return streamTitle(thread.title || defaultTitle);}- // Compare: wait until both threads done.if (pairId) {const paired = (await listStoredChatThreads({ pairId })).find((t) => t.id !== remoteId,@@ -1886,17 +1882,16 @@ function useStudioRuntimeAdapters(activeGenerationRuns = [];activeGenerationRunsLoaded = false;}- // The endpoint is named for active runs but returns rows, so a run that terminalised between- // the write and this read comes back with it, and force-writing `generationSettled: false`- // over a finished reply revives it. Take the still-live rows only; a failed read is silence.- // Publish the still-live rows as the corroboration toThreadMessage restores a running status from.+ // The endpoint is named for active runs but returns rows, so a run that terminalised between the+ // write and this read comes back with it, and force-writing `generationSettled: false` over a+ // finished reply revives it. Publish the still-live rows only; a failed read is silence.activeGenerationRuns = activeGenerationRuns.filter((run) => !isTerminalChatGenerationRun(run),);- // And drop any run the message snapshot already shows as finished: the runs read happens first,- // so a run that completed in between is still listed. Filtering the LIST rather than- // skipping at the overlay matters, since a stale mapping keeps the thread reading as durable- // and a later subscriber-owned stream would be capped.+ // And drop any run the message snapshot already shows as finished: the runs read happens first, so+ // a run that completed in between is still listed. Filtering the LIST rather than skipping at the+ // overlay matters, since a stale mapping keeps the thread reading as durable and a later+ // subscriber-owned stream would be capped.const terminalMessageRuns = new Set(msgs.filter((message) => {@@ -2041,11 +2036,9 @@ function useStudioRuntimeAdapters(}| undefined;const store = useChatRuntimeStore.getState();- // Window check applies only when a local GGUF window is known; external- // providers have loadedContextLength === null. llama.cpp stops at the window, so- // a saved count past it is stale; MLX runs past it by design, and a thread whose- // recount is unsupported -- a VLM, or one carrying tool history -- would never- // get another count to replace the one rejected here.+ // Window check applies only when a local GGUF window is known; external providers have+ // loadedContextLength === null. llama.cpp stops at the window, so a saved count past it is stale;+ // MLX runs past it by design, and a thread whose recount is unsupported would never get another.const localLimit = store.loadedIsGguf ? store.loadedContextLength : null;const withinLocalLimit =!localLimit || (savedUsage?.totalTokens ?? 0) <= localLimit;@@ -2068,10 +2061,9 @@ function useStudioRuntimeAdapters(}}// Only when nothing was restored: saved usage is the last completion's exact totals, and- // refreshContextUsage does NOT stand down for usage already there, so it would overwrite- // them with an estimate whose completionTokens is 0. A thread opened after a model switch- // fails modelMatches and still gets priced (#7450). Primary pane only: a compare pane- // never owns the global bar.+ // refreshContextUsage does NOT stand down for usage already there, so it would overwrite them with+ // an estimate whose completionTokens is 0. A thread opened after a model switch fails modelMatches+ // and still gets priced (#7450). Primary pane only: a compare pane never owns the global bar.if (!restoredUsage && modelType === "base" && !pairId) {void refreshContextUsage({ threadId: remoteId });}@@ -2130,14 +2122,11 @@ function useStudioRuntimeAdapters(await deleteStoredChatThreads([remoteId]);return;}- // Published before the reads below: a temporary chat has no row to confirm, and a read that- // fails must not leave the runtime pointing at the previously open chat. Not while this pane- // is only mounted to keep its run attached, since a hidden pane naming itself active makes- // Export pull the unrelated base chat. Nor mid-switch: switchToNewThread() is async, so- // mainThreadId is still the OUTGOING thread for that gap, which the attempt check catches.- // Nor mid-switch: switchToNewThread() is async, so mainThreadId is still the OUTGOING thread for- // the whole gap, and a write landing there republishes the chat the user just left.- // attempt !== landedAttempt is that gap.+ // Published before the reads below: a temporary chat has no row to confirm, and a read that fails+ // must not leave the runtime pointing at the previously open chat. Not while this pane is only+ // mounted to keep its run attached, since a hidden pane naming itself active makes Export pull the+ // unrelated base chat. Nor mid-switch: switchToNewThread() is async, so mainThreadId is still the+ // OUTGOING thread for that gap, and attempt !== landedAttempt is that gap.const switchState = newThreadSwitchStateRef?.current;const switchInFlight = Boolean(switchState &&@@ -2204,12 +2193,10 @@ function useStudioRuntimeAdapters(sameResearchRun ||!incomingMetadata?.serverManaged ||existingRevision > incomingRevision);- // The backend owns this message and refuses client edits, and every field the save would send- // was just read back from it, so the request is answered 409 every time: one measured 43.6 s- // generation cost 265 PUTs, 256 rejected. `parentId` is the one field not echoed back, and- // it is dropped either way, since the server rejects the whole request.- // One measured 43.6 s generation: 265 PUTs, 256 rejected, plus 353 whole-thread GETs from the- // ensureStoredChatThread inside saveStoredChatMessage. Returning here drops both.+ // The backend owns this message and refuses client edits, and every field the save would send was+ // just read back from it, so the request is answered 409 every time: one measured 43.6 s generation+ // cost 265 PUTs, 256 rejected, plus 353 whole-thread GETs from the ensureStoredChatThread inside+ // saveStoredChatMessage. `parentId` is the one field not echoed back, and it is dropped either way.if (preserveServerManaged) {await throwIfHistoryWasCleared(remoteId);return;@@ -2616,10 +2603,9 @@ function ThreadNewChatSwitch({useChatRuntimeStore.getState().setActiveThreadId(null);}, [aui, isLoading, newThreadSwitchStateRef, nonce, paused]);- // Reassert this view's thread when a switch started before it lands anyway. Leaving a landing- // for a saved chat and coming back before switchToThread resolves used to end with- // assistant-ui assigning that saved thread as the main one, since the promise does not know- // the route moved. Recognised by the exact id that switch asked for.+ // Reassert this view's thread when a switch started before it lands anyway. Leaving a landing for a+ // saved chat and coming back before switchToThread resolves used to end with assistant-ui assigning+ // that saved thread as the main one. Recognised by the exact id that switch asked for.useEffect(() => {if (isLoading || paused) {return;@@ -2780,11 +2766,9 @@ function ThreadScopedSettingsSync({return;}if (!enabled) {- // Compare panes share one composer between two threads, so no single chat's snapshot could- // apply: compare runs on the installation defaults and its edits move them. Said here rather- // than leaving the module pointing at the last single chat.- // Otherwise the module still points at the last single chat, whose stored pills a model load would- // read back through threadScopedOverride.+ // Compare panes share one composer between two threads, so no single chat's snapshot could apply:+ // compare runs on the installation defaults and its edits move them. Said here rather than leaving+ // the module pointing at the last single chat, whose stored pills a model load would read back.applyThreadScopedSettings(null, null);return;}@@ -2823,12 +2807,10 @@ function ThreadScopedSettingsSync({const sync = () => {if (cancelled || paired) return;- // The composer is live while this read is out, so hold any edit made meanwhile rather than- // writing it to the installation defaults. Drop to those defaults for the duration: until- // the read lands the store still holds the OUTGOING chat's values, and a send in that window- // would carry the previous chat's permission level and pills.- // A send in that window is captured by snapshotQueuedChatRunSettings and carries the previous- // chat's permission level and pills, so a chat stored as "ask" could run tools without asking.+ // The composer is live while this read is out, so hold any edit made meanwhile rather than writing+ // it to the installation defaults. Drop to those defaults for the duration: until the read lands+ // the store still holds the OUTGOING chat's values, and a send in that window is captured by+ // snapshotQueuedChatRunSettings, so a chat stored as "ask" could run tools without asking.if (!defaulted) {defaulted = true;applyThreadScopedSettings(null, null);@@ -2839,11 +2821,9 @@ function ThreadScopedSettingsSync({const read = new AbortController();reads.add(read);// The deadline covers the WAITS as well as the read, neither of which is bounded on its own; in- // front of it their time went uncounted and the chain could outlast THREAD_PAIRING_WAIT_MS- // with the gate shut. Inside it, a stall is one failed attempt.- // The settings chain is a PATCH, and awaitStoredChatThreadWrites settles a row write opening with- // an unbounded getStoredChatThread. Inside the deadline a stall is one failed attempt, which- // retryThreadRead handles.+ // front of it their time went uncounted and the chain could outlast THREAD_PAIRING_WAIT_MS with the+ // gate shut. The settings chain is a PATCH, and awaitStoredChatThreadWrites opens with an unbounded+ // getStoredChatThread. Inside the deadline a stall is one failed attempt, which retryThreadRead handles.void Promise.race([Promise.all([// This chat's own PATCH first: a read that overtakes it returns the pre-edit snapshot.diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 32c2aaed924..3a5e98a0307 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -668,7 +668,6 @@ export function SharedComposer({const setMcpEnabledForChat = useChatRuntimeStore((s) => s.setMcpEnabledForChat,);- // Three most recently updated projects for the quick-access submenuconst { projects } = useChatProjects();const recentProjects = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)@@ -714,9 +713,8 @@ export function SharedComposer({mmprojFallbackReason,});const isCompareMode = Boolean(model1?.id || model2?.id);- // Attach-time gate. Compare mode defers to send: the catalog can lag a model's real capabilities,- // and models[] only syncs after ensureModelLoaded at send time. Single mode uses the loaded- // model's runtime capability.+ // Attach-time gate. Compare defers to send: the catalog can lag a model's real capabilities and+ // models[] only syncs after ensureModelLoaded. Single mode uses the loaded model's capability.const attachUnavailableReason = isCompareMode ? null : imageUnavailableReason;const effectiveExternalModelId =selectedExternalProvider?.providerType === "openrouter" &&@@ -775,13 +773,10 @@ export function SharedComposer({const thinkingActiveLook = isEffort? reasoningLockedOn || (effectiveReasoningVisualEnabled && !reasoningDisabled): reasoningLockedOn || (effectiveReasoningEnabled && !reasoningDisabled);- // Two-pill gating: Search lights up on a local tool runtime OR a provider-run server-side- // web_search; Code on the local runtime OR Anthropic with a model accepting- // code_execution_20250825, the only external code-execution tool today.- // Search: supportsTools (Code/python plus local web_search) OR supportsBuiltinWebSearch- // (OpenAI/Anthropic/OpenRouter/Kimi). Code: the local runtime OR Anthropic with a model taking- // code_execution_20250825, per providerSupportsBuiltinCodeExecution. Anthropic is the only- // external provider shipping a code-execution tool today.+ // Two-pill gating. Search: supportsTools (Code/python plus local web_search) OR+ // supportsBuiltinWebSearch (OpenAI/Anthropic/OpenRouter/Kimi). Code: the local runtime OR+ // Anthropic with a model taking code_execution_20250825, the only external code-execution tool+ // today, per providerSupportsBuiltinCodeExecution.const supportsBuiltinCodeExecution = providerSupportsBuiltinCodeExecution(selectedExternalProvider?.providerType,effectiveExternalModelId,@@ -795,16 +790,15 @@ export function SharedComposer({const supportsBuiltinWebFetch = providerSupportsBuiltinWebFetch(selectedExternalProvider?.providerType,);- // Gemini rejects codeExecution alongside image modalities. Search is blocked on older Gemini- // image ids but allowed on Gemini 3 image models, so only Code is disabled unconditionally- // in Gemini image mode.+ // Gemini rejects codeExecution alongside image modalities. Search is blocked on older Gemini image+ // ids but allowed on Gemini 3 image models, so only Code is disabled unconditionally there.const isExternalGemini = selectedExternalProvider?.providerType === "gemini";const imageDisabled = !modelLoaded || !supportsBuiltinImageGeneration;const imageModeDisablesCode =isExternalGemini && imageToolsEnabled && !imageDisabled;- // Image-tier Gemini models always reject codeExecution and reject web_search on older ids, so do- // not let local `supportsTools` re-enable a pill the Gemini backend silently drops: gate- // strictly on provider builtin support.+ // Image-tier Gemini models always reject codeExecution and reject web_search on older ids, so gate+ // strictly on provider builtin support: local `supportsTools` must not re-enable a pill the+ // Gemini backend silently drops.const isGeminiImageTier =isExternalGemini && supportsBuiltinImageGeneration;// Disable only when a loaded model lacks the capability; with no model the tool can still be@@ -954,7 +948,6 @@ export function SharedComposer({for (let i = 0; i < files.length; i++) {const file = files[i];if (!file) continue;- // Handle audio filesif (isAudioAttachmentFile(file)) {const sizeError = getAudioSizeError(file.size);if (sizeError) {@@ -1092,8 +1085,8 @@ export function SharedComposer({? useChatRuntimeStore.getState().params.checkpoint: undefined;- // Generalized compare requires both panes to have a model: a half-selected send either races to- // an empty bubble with bogus tok/s (#5569) or leaves the empty pane with a dangling prompt.+ // Generalized compare requires both panes to have a model: a half-selected send either races to an+ // empty bubble with bogus tok/s (#5569) or leaves the empty pane with a dangling prompt.// hasCompareHandles is true only in GeneralCompareContent.if (hasCompareHandles && !isGeneralizedCompare) {toast.error("Pick a model in each pane to compare", {@@ -1109,9 +1102,8 @@ export function SharedComposer({!isGeneralizedCompare &&imageUnavailableReason) {- // Single mode: the loaded model's runtime capability is known here. Compare mode defers: each- // ensureModelLoaded sets loadedIsMultimodal for its side, and the adapter's pre-stream gate- // runs per side.+ // Single mode knows the loaded model's capability here. Compare defers: each ensureModelLoaded+ // sets loadedIsMultimodal for its side, and the adapter's pre-stream gate runs per side.toast.error(imageUnavailableReason);resetPromptQueue();return;@@ -1123,7 +1115,6 @@ export function SharedComposer({const image = await fileToBase64DataURL(file);content.push({ type: "image", image });} catch {- // skip failed image}}if (submittedAudio) {@@ -1219,7 +1210,6 @@ export function SharedComposer({return;}- // Generalized compare: load each model before dispatching to its sideif (isGeneralizedCompare) {const store = useChatRuntimeStore.getState();const trustRemoteCode = store.params.trustRemoteCode ?? false;@@ -1244,10 +1234,9 @@ export function SharedComposer({return;}// The GPU/offload knobs both compare loads must use, snapshotted at Send: ensureModelLoaded runs- // sequentially and the first load's response echo rewrites the live store, so reading the- // store per load would hand model 2 the first model's echoed defaults.- // The first load's echo (loadedGpuMemoryFields) rewrites the live store, resetting- // gpuLayers/nCpuMoe/split/pick to defaults on a non-GGUF or Auto first model.+ // sequentially and the first load's echo (loadedGpuMemoryFields) rewrites the live store,+ // resetting gpuLayers/nCpuMoe/split/pick to defaults on a non-GGUF or Auto first model, so+ // reading the store per load would hand model 2 the first model's echoed defaults.const compareLoadKnobs = {gpuMemoryMode: store.gpuMemoryMode,gpuLayers: store.gpuLayers,@@ -1322,8 +1311,8 @@ export function SharedComposer({diffusionUnknown = staged.diffusionUnknown;}// Pass-through arguments can live only in the server's override map while this config comes from- // local storage, and /load's omission path inherits them from a RESIDENT instance, which a- // cold compare pane does not have, so the experiment would run a different command.+ // local storage, and /load's omission path inherits them from a RESIDENT instance, which a cold+ // compare pane does not have, so the experiment would run a different command.if (targetIsGguf &&// Not for the diffusion runner, which appends none of them.@@ -1332,9 +1321,8 @@ export function SharedComposer({try {// Sanitised for the same reason the panel sanitises what it hydrates: either list becomes an// EXPLICIT /load argument, validated strictly rather than going through the carry-over paths- // that drop a newly denied flag quietly.- // A pane on an install upgraded across a denylist change would otherwise answer 400 on a- // comparison that ran the day before.+ // that drop a newly denied flag quietly, so a pane on an install upgraded across a denylist+ // change would otherwise answer 400 on a comparison that ran the day before.const managed = await loadManagedLlamaFlags();const clean = (tokens: readonly string[]) =>sanitizeStoredExtraArgs(@@ -1370,12 +1358,10 @@ export function SharedComposer({// The load still works; a real overrides outage surfaces there.}}- // Mirror single-view resolveLoadMaxSeqLength: a pane with no explicit context- // hands sizing to whichever local backend serves it, not the session- // maxSeqLength, which would silently shrink the shown context. One no local- // backend serves falls back to the app default rather than the active model's- // runtime snapshot, else comparing a saved 128K model against an unconfigured- // one loads the latter at 128K and OOMs.+ // Mirror single-view resolveLoadMaxSeqLength: a pane with no explicit context hands sizing to+ // whichever local backend serves it, not the session maxSeqLength, which would silently shrink+ // the shown context. With no local backend it falls back to the app default rather than the+ // active model's runtime snapshot, else an unconfigured model loads at a saved 128K and OOMs.const effectiveMaxSeqLength =savedContextPin(ownConfig) ??unpinnedLoadContext(@@ -1399,9 +1385,9 @@ export function SharedComposer({: ownRemembered? ownConfig.tensorParallel: fallbackTensorParallel;- // The diffusion runner has no projector to skip, so the toggle is inert there. A pane with no- // saved config gets the per-model DEFAULT, not the store's current value: unlike- // tensorParallel, which stands across models, an unconfigured model is one with vision on.+ // The diffusion runner has no projector to skip, so the toggle is inert there. A pane with no saved+ // config gets the per-model DEFAULT, not the store's current value: unlike tensorParallel, an+ // unconfigured model is one with vision on.const effectiveDisableVision = resolvedIsDiffusion? false: ownRemembered@@ -1412,8 +1398,7 @@ export function SharedComposer({}// A pane's OWN saved split is sent instead of being forced to Auto (#7574); the shared Send-time// snapshot is not, since its layer count is bounded by another GGUF. Knobs the runner has no- // equivalent for (MoE offload, tensor parallel) stay hard-forced, and an UNCLASSIFIED GGUF- // is pinned too: see lib/gpu-placement.ts.+ // equivalent for (MoE offload, tensor parallel) stay hard-forced, as does an UNCLASSIFIED GGUF.const {gpuMemoryMode: effectiveGpuMemoryMode,gpuLayers: effectiveGpuLayers,@@ -1443,10 +1428,8 @@ export function SharedComposer({resolvedIsDiffusion === true,);// A pane's context comes from its own config only: a saved pin, or null. It must not inherit the- // active model's shared snapshot, which resolveFitMaxSeqLength would treat as a pin and load- // this pane at the other model's context.- // A GGUF pane with no explicit context loads at native (0 -> n_ctx_train), not the session- // maxSeqLength, which would silently shrink the shown context.+ // active model's shared snapshot, which resolveFitMaxSeqLength would treat as a pin. A GGUF pane+ // with no explicit context loads at native (0 -> n_ctx_train), not the session maxSeqLength.const effectiveCustomContextLength = ownConfig.customContextLength;let loadTrustRemoteCode = trustRemoteCode;let approvedRemoteCodeFingerprint: string | null = null;@@ -1605,9 +1588,9 @@ export function SharedComposer({// Same cap as the interactive load: this replays the model's remembered settings, and a budget// kept from a larger context does not fit the one it just loaded with.{- // The reported window leads and the request stands in only for a backend- // that sizes nothing, as on the interactive load: an unpinned pane sends- // the auto-size sentinel, and capping a budget at 0 asks for no output.+ // The reported window leads and the request stands in only for a backend that sizes nothing, as on+ // the interactive load: an unpinned pane sends the auto-size sentinel, and capping a budget at 0+ // asks for no output.maxTokensCap: replayMaxTokensCap(loadedContextFields(resp).loadedContextLength ??(!resp.is_gguf && effectiveMaxSeqLength > 0@@ -1619,10 +1602,9 @@ export function SharedComposer({store.setModelRequiresTrustRemoteCode(resp.requires_trust_remote_code ?? false,);- // This pane's own saved Context Length, not compareMaxSeqLength: the wire- // value is Auto-resolved for a same-model reload, so pinning it would- // convert Auto into a number the user never set (see resolveExplicitCtxPin).- // A non-GGUF pane keeps an MLX pin instead of clearing its baseline.+ // This pane's own saved Context Length, not compareMaxSeqLength: the wire value is Auto-resolved+ // for a same-model reload, so pinning it would convert Auto into a number the user never set+ // (see resolveExplicitCtxPin). A non-GGUF pane keeps an MLX pin instead of clearing its baseline.const keepCustomCtx = targetIsGguf? resolveExplicitCtxPin(effectiveCustomContextLength): retainedContextPin({@@ -1686,9 +1668,8 @@ export function SharedComposer({// The context baseline this pane loaded with (see keepCustomCtx above), so a// later Apply/Reset can't silently revert the pin it was serving.loadedCustomContextLength: keepCustomCtx,- // Adopt the load response's GPU-memory fields (mode/layers/MoE/split/pick- // plus loaded baselines) so the GPU controls round-trip. (The context group,- // customContextLength and native-path token/expiry clear in the tail below.)+ // Adopt the load response's GPU-memory fields (mode/layers/MoE/split/pick plus loaded baselines)+ // so the GPU controls round-trip. The context group and native-path token/expiry clear below....loadedGpuMemoryFields(resp),// Drives the GPU Memory controls' diffusion gate; set alongside the GPU fields on every load path// so the gate cannot read stale.@@ -1702,9 +1683,8 @@ export function SharedComposer({// reload use the context it actually loaded with.customContextLength: keepCustomCtx,...loadedContextFields(resp),- // Compare selections load by repo/variant, never from the file picker,- // so they carry no native lease. Clear any prior picked file's- // token/expiry so the reload path never sends a stale lease.+ // Compare selections load by repo/variant, never from the file picker, so they carry no native+ // lease. Clear any prior picked file's token/expiry so the reload path never sends a stale one.activeNativePathToken: null,activeNativePathExpiresAtMs: null,...resolveLoadedSpeculativeSettings(resp),@@ -1756,7 +1736,6 @@ export function SharedComposer({const handle1 = handlesRef.current["model1"];const handle2 = handlesRef.current["model2"];- // Show user messages immediately on both sidesif (handle1) handle1.appendMessage(content);if (handle2) handle2.appendMessage(content);@@ -1766,7 +1745,6 @@ export function SharedComposer({setComparing(true);try {- // Side 1: load, generate, waitif (handle1 && model1?.id) {toast("Loading Model 1…", {id: toastId,@@ -1785,7 +1763,6 @@ export function SharedComposer({await done;}- // Side 2: load, generate, waitif (handle2 && model2?.id) {acquireCompareModelLifecycle();const needsLoad = compareSelectionNeedsLoad(model2);@@ -1837,7 +1814,6 @@ export function SharedComposer({setComparing(false);}} else {- // Original behavior: fire all handles simultaneouslyconst liveRuntime = useChatRuntimeStore.getState();if (requireStableCheckpoint &&@@ -1893,9 +1869,8 @@ export function SharedComposer({function onKeyDown(e: KeyboardEvent) {// IME composition (JP/CN/KR): Enter commits the candidate, so do not hijack it (#5318). Re-pin- // composingRef in case the stuck watchdog (#5546) cleared it during a long candidate-window- // pause, and re-arm the watchdog on the same path, or the WSL+Chrome no-compositionend case- // pins composingRef forever.+ // composingRef in case the stuck watchdog (#5546) cleared it during a long candidate-window pause,+ // and re-arm the watchdog on the same path, or the WSL+Chrome no-compositionend case pins it forever.if (e.nativeEvent.isComposing || e.keyCode === 229) {composingRef.current = true;refreshStuckImeTimer();@@ -1931,16 +1906,15 @@ export function SharedComposer({!isDictating &&!sendUnavailableReason;- // Compare mode swaps this composer in for the single-chat one and only one is ever on screen, so- // the chords register in both. Both gate on the chat tab being visible: off-route the pane is- // hidden, not unmounted.+ // Compare mode swaps this composer in for the single-chat one and only one is ever on screen, so the+ // chords register in both. Both gate on the chat tab being visible: off-route the pane is hidden.const chatActive = useChatActive();useShortcut("startDictation",() => {- // As in the single-chat composer: a dialog over Chat leaves this registered, and a microphone- // opened behind one is neither visible nor stoppable. Stopping first and ungated, so a- // recording stays stoppable wherever the gate would say no.+ // As in the single-chat composer: a dialog over Chat leaves this registered, and a microphone opened+ // behind one is neither visible nor stoppable. Stopping first and ungated, so a recording stays+ // stoppable wherever the gate would say no.if (isDictating) {stopDictation();return;@@ -2238,9 +2212,9 @@ export function SharedComposer({ref={textareaRef}value={text}onChange={(e) => {- // ALWAYS mirror the DOM value into React state, even during IME composition: the controlled- // `value` must match the DOM at all times, else an unrelated parent re-render reconciles the- // textarea back to the stored value mid-composition, wiping the preedit (#5318).+ // ALWAYS mirror the DOM value into React state, even during IME composition: the controlled `value`+ // must match the DOM at all times, else an unrelated parent re-render reconciles the textarea back+ // to the stored value mid-composition, wiping the preedit (#5318).setCompositionState(isNativeComposing(e.nativeEvent));setText(e.target.value);}}@@ -2452,10 +2426,8 @@ export function SharedComposer({onClick={() => {const next = !toolsEnabled;setToolsEnabled(next);- // Kimi's $web_search builtin requires thinking=disabled, so toggle the Think pill off when Search- // is on, mirroring the backend.- // Per https://platform.kimi.ai/docs/guide/use-web-search.- // Per https://platform.kimi.ai/docs/guide/use-web-search.+ // Kimi's $web_search builtin requires thinking=disabled, so toggle the Think pill off when Search is+ // on, mirroring the backend. Per https://platform.kimi.ai/docs/guide/use-web-search.if (isKimiExternal) {setReasoningEnabled(!next, { persist: false });applyQwenThinkingParams(!next);diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 7f2bc7e6eee..706b2301f2b 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -143,8 +143,8 @@ export const MODELS_FIT_ON_DEVICE_ONLY_KEY =export const CHAT_BYPASS_PERMISSIONS_KEY = "unsloth_chat_bypass_permissions";export const CHAT_PERMISSION_MODE_KEY = "unsloth_chat_permission_mode";-/** Local tool-call gate: "ask" every call, "auto" only high-risk ones, "off" never but keeps- * the sandbox, "full" drops both and is session-only. */+/** Local tool-call gate: "ask" every call, "auto" only high-risk ones, "off" never but keeps the+ * sandbox, "full" drops both and is session-only. */export type PermissionMode = "ask" | "auto" | "off" | "full";export const CHAT_WEB_FETCH_TOOLS_ENABLED_KEY ="unsloth_chat_web_fetch_tools_enabled";@@ -156,10 +156,9 @@ export const CHAT_RAG_AUTOINJECT_MIN_SCORE_KEY ="unsloth_chat_rag_autoinject_min_score";export const CHAT_RAG_OCR_KEY = "unsloth_chat_rag_ocr_scanned";export const CHAT_RAG_CAPTION_KEY = "unsloth_chat_rag_caption_figures";-// Only the model-agnostic intents (auto/ngram/off) persist: a saved drafter mode no-ops on a-// model with no MTP head or DSpark sidecar.-// The model-specific drafter modes (mtp/mtp+ngram/dspark/dflash) and spec_draft_n_max stay-// session-only. Unknown -> auto.+// Only the model-agnostic intents (auto/ngram/off) persist: a saved drafter mode no-ops on a model+// with no MTP head or DSpark sidecar, so the model-specific modes and spec_draft_n_max stay+// session-only. Unknown maps to auto.const PERSISTED_SPEC_MODES = new Set(["auto", "ngram", "off"]);export type RagSource = { type: "thread" } | { type: "kb"; kbId: string };@@ -314,7 +313,7 @@ function loadRagNumber(}// External picks ride in `params.checkpoint` as `external::<providerId>::<modelId>`.-// PersistedChatSettings omits `checkpoint`: only the local side is mirrored by the backend's+// PersistedChatSettings omits `checkpoint`: only the local side is mirrored by// /api/inference/status.active_model.const LAST_EXTERNAL_CHECKPOINT_KEY = "unsloth_chat_last_external_checkpoint";@@ -329,10 +328,8 @@ function loadLastExternalCheckpoint(): string | null {}/**- * Two checkpoints naming the same model.- *- * normalizeModelIdentity, not toLowerCase: it folds case for repository ids and- * the case-insensitive path forms while preserving it for POSIX paths, where+ * Two checkpoints naming the same model. normalizeModelIdentity, not toLowerCase: it folds case for+ * repository ids and the case-insensitive path forms while preserving it for POSIX paths, where* /home/u/Models/qwen3.8 and /home/u/models/qwen3.8 are two different files.*/function isOpaqueModelRef(modelId: string): boolean {@@ -354,10 +351,9 @@ function sameCheckpointIdentity(return normalizeModelIdentity(left) === normalizeModelIdentity(right);}-// A checkpoint that arrived without any adoption signal: restored from-// localStorage at startup, or picked by the user while the settings GET was-// still in flight. Chat settings are installation-wide, so neither may claim a-// global snapshot another browser wrote for a different model.+// A checkpoint that arrived without any adoption signal: restored from localStorage at startup, or+// picked by the user while the settings GET was still in flight. Chat settings are+// installation-wide, so neither may claim a global snapshot another browser wrote.let unownedCheckpointBeforeHydration: string | null = null;function saveLastExternalCheckpoint(value: string | null): void {@@ -799,14 +795,12 @@ function mirrorSettingToBackend(key: string, raw: string): void {saveSettingsPatch(patch);}-/** Move any held startup edits onto the outgoing patch. */function drainPreHydrationPatch(): void {if (!preHydrationPatch) return;mergePatch(pendingPatch, preHydrationPatch);preHydrationPatch = null;}-/** Replay the edits made while the initial GET was still in flight. */function flushPreHydrationSettings(): void {if (!preHydrationPatch) return;const patch = preHydrationPatch;@@ -905,7 +899,6 @@ function noteConstraintSuppressedThreadField(constraintSuppressedThreadFields.add(field);}-/** Is the stored value the one to keep, rather than the constraint-derived live one? */function keepsStoredValueUnderConstraint(key: (typeof CONSTRAINT_SUPPRESSIBLE_KEYS)[number],threadId: string,@@ -1465,9 +1458,9 @@ function scheduleThreadScopedSettingsWrite(}, THREAD_SETTINGS_DEBOUNCE_MS);}-// The chat whose snapshot is in flight, plus edits made before it landed: only the read can-// say whether they are the chat's or the defaults'. Writing them globally moved every-// other chat's default and was then overwritten by the arriving snapshot.+// The chat whose snapshot is in flight, plus edits made before it landed: only the read can say+// whether they are the chat's or the defaults'. Writing them globally moved every other chat's+// default and was then overwritten by the arriving snapshot.let pendingPairingThreadId: string | null = null;/** The store's thread-scoped values as they stood when the current pairing began. */let pairingWindowDefaults: ThreadScopedSettings | null = null;@@ -1534,9 +1527,9 @@ const pairingSettledByThreadId = new Map<{ promise: Promise<void>; resolve: () => void }>();-/** Resolves once `threadId`'s own settings are known; the adapter awaits it so a run cannot- * start on the installation defaults (a chat stored "ask" would run "off"). False means- * the wait ran out and the store now describes some other chat, so callers must stop. */+/** Resolves once `threadId`'s own settings are known; the adapter awaits it so a run cannot start on+ * the installation defaults (a chat stored "ask" would run "off"). False means the wait ran out and+ * the store now describes some other chat, so callers must stop. */export function awaitThreadScopedPairing(threadId: string | null | undefined,): Promise<boolean> {@@ -1551,10 +1544,9 @@ export function awaitThreadScopedPairing(]);}-// Longer than the read can take (retries, timeouts, and a give-up that opens the gate), so-// a run is only refused for a chat whose pairing was genuinely abandoned.-// THREAD_READ_RETRIES retries, each bounded by THREAD_READ_TIMEOUT_MS and spaced-// THREAD_READ_RETRY_MS apart.+// Longer than the read can take (THREAD_READ_RETRIES retries, each bounded by THREAD_READ_TIMEOUT_MS+// and spaced THREAD_READ_RETRY_MS apart, plus a give-up that opens the gate), so a run is only+// refused for a chat whose pairing was genuinely abandoned.const THREAD_PAIRING_WAIT_MS = 30_000;/** The chat turned out to own no snapshot: send the held edits to the defaults, as before. */@@ -1582,9 +1574,8 @@ export function commitHeldThreadScopedEditsToTheirThread(const held = heldThreadScopedEdits;heldThreadScopedEdits = [];pendingPairingThreadId = null;- // pairingWindowDefaultsThreadId is deliberately NOT cleared: a failed read re-pairs the same- // chat with the edit in the store, and resampling would take it for a default. The gate- // stays shut too, since the store now shows the chat the user moved to.+ // pairingWindowDefaultsThreadId is deliberately NOT cleared: a failed read re-pairs the same chat+ // with the edit in the store, and resampling would take it for a default. The gate stays shut too.closeThreadScopedPairingGate(null);if (threadId === null || held.length === 0) return Promise.resolve();const changes = heldThreadScopedChanges(held);@@ -1599,9 +1590,9 @@ export function commitHeldThreadScopedEditsToTheirThread(return mergeThreadScopedSettingsIntoRow(threadId, changes);}-/** Put the installation values back over the edits just written to the chat being left, or- * the next chat takes its temperature and prompt. Only on a real leave: a retried read- * or a fork commits the same way while the chat stays open. */+/** Put the installation values back over the edits just written to the chat being left, or the next+ * chat takes its temperature and prompt. Only on a real leave: a retried read or a fork commits the+ * same way while the chat stays open. */function restoreDefaultsOverCommittedEdits(threadId: string,held: { field: string }[],@@ -1666,8 +1657,6 @@ async function mergeThreadScopedSettingsIntoRow(const previous = threadSettingsWriteChains.get(threadId) ?? Promise.resolve();const next = previous.catch(() => undefined)- // Last session's unconfirmed writes go first: one carries a different writer id, so nothing- // on the server orders it against this edit..then(() => threadSettingsReplaySettled).catch(() => undefined).then(async () => {@@ -1701,9 +1690,9 @@ async function mergeThreadScopedSettingsIntoRow(return next;}-/** What the server called an installation default, for fields hydration skipped because the- * user had just set them inside a chat whose read was out. When the pairing window closes- * the default returns to this rather than the browser's pre-hydration copy. */+/** What the server called an installation default, for fields hydration skipped because the user had+ * just set them inside a chat whose read was out. When the pairing window closes the default returns+ * to this rather than the browser's pre-hydration copy. */const hydratedDefaultsByHeldField = new Map<string, unknown>();/** Is this field an edit waiting on its chat's read, and so not the installation's to set? */@@ -1735,9 +1724,9 @@ function captureThreadScopedEdit(return false;}-/** Persist a value a model load applied rather than one the user picked: before hydration- * such a write only reflects this browser's cache. `stillCurrent` says it matches the live- * store, so a load spanning hydration cannot write its stale capture over the answer. */+/** Persist a value a model load applied rather than one the user picked: before hydration such a+ * write only reflects this browser's cache. `stillCurrent` says it matches the live store, so a load+ * spanning hydration cannot write its stale capture over the answer. */function persistLoadDerivedSetting(key: string,raw: string,@@ -1790,14 +1779,13 @@ function saveBool(key: string, value: boolean): void {// given one. Only hydration and the composer toggle write it.let storedPreserveThinking: boolean | null = null;-/** Record the preference a stored value or a toggle just expressed. */function notePreserveThinkingPreference(value: boolean): void {storedPreserveThinking = value;}-/** The backend's family default is a DEFAULT: it seeds the switch where the installation- * never answered and never replaces an answer, as resolveToolsEnabledOnLoad does. That is- * what makes a cold boot deterministic when the settings GET and the status race. */+/** The backend's family default is a DEFAULT: it seeds the switch where the installation never+ * answered and never replaces an answer, as resolveToolsEnabledOnLoad does, which is what makes a+ * cold boot deterministic when the settings GET and the status race. */export function resolvePreserveThinkingOnLoad(resp: {supports_preserve_thinking?: boolean | null;preserve_thinking_default?: boolean | null;@@ -1855,10 +1843,9 @@ export function normalizeSpeculativeType(const s = String(v).trim().toLowerCase();if (!s) return null;if (s === "auto" || s === "default") return "auto";- // The same four spellings _LEGACY_SPEC_MODE_MAP reads as "off". A stored override- // reaches here raw (model-overrides.ts binds speculative_type unnormalized), so- // falling through to Auto would compare Auto against a status the backend already- // canonicalised to "off" and re-send /load on every pick.+ // The same four spellings _LEGACY_SPEC_MODE_MAP reads as "off". A stored override reaches here raw+ // (model-overrides.ts binds speculative_type unnormalized), so falling through to Auto would compare+ // Auto against a status the backend already canonicalised to "off" and re-send /load on every pick.if (s === "off" || s === "none" || s === "disable" || s === "disabled") {return "off";}@@ -2000,9 +1987,9 @@ export function rebalanceSplit(return out;}-// Validate a persisted gpu_ids pick against the GPUs present now, returning null (automatic)-// when stale, so a saved [1] on a 1-GPU host is not sent and rejected unclearably. A cold-// device cache leaves it alone; an absent namespace is a legacy physical-ID pick.+// Validate a persisted gpu_ids pick against the GPUs present now, returning null (automatic) when+// stale, so a saved [1] on a 1-GPU host is not sent and rejected unclearably. A cold device cache+// leaves it alone; an absent namespace is a legacy physical-ID pick.export function reconcilePersistedGpuIds(ids: number[] | null,savedIndexKind?: GpuIndexKind | null,@@ -2051,10 +2038,9 @@ export function loadedGpuMemoryFields(resp: {// Meaningful only for a GGUF chat load, and a non-GGUF response still serializes// gpu_memory_mode "auto", so gate on is_gguf or a transformers load resets the preference.if (!resp.is_gguf) {- // Clear the GPU pick / offload baseline a prior GGUF load left, else a stale loadedGpuIds- // reads as dirty. gpuMemoryMode stays but its baseline clears, so Reset keeps the mode.- // gpuIdsDirty is ungated, so Reset would restore it while the picker is hidden. gpuMemoryMode is- // kept as the standing preference, but its loaded baseline clears to null.+ // Clear the GPU pick / offload baseline a prior GGUF load left, else a stale loadedGpuIds reads as+ // dirty. gpuIdsDirty is ungated, so Reset would restore it while the picker is hidden. gpuMemoryMode+ // is kept as the standing preference, but its loaded baseline clears to null.return {selectedGpuIds: null,selectedGpuIndexKind: null,@@ -2082,9 +2068,9 @@ export function loadedGpuMemoryFields(resp: {reportedGpuIds == null? null: cachedPinnableGpuIndexKind(resp.is_diffusion === true);- // A numeric id is unsafe to adopt once discovery says it is not a physical CUDA/ROCm id or- // Vulkan ordinal. While discovery is cold the namespace is merely deferred, so keep the- // pin, or a reload in that window lets llama.cpp fall back to every device.+ // A numeric id is unsafe to adopt once discovery says it is not a physical CUDA/ROCm id or Vulkan+ // ordinal. While discovery is cold the namespace is merely deferred, so keep the pin, or a reload in+ // that window lets llama.cpp fall back to every device.const gpuIds =reportedGpuIds != null && gpuIndexKind !== null ? reportedGpuIds : null;// A shim without --ngl reports Auto while the backend still holds the ask, so recover it:@@ -2114,10 +2100,9 @@ export function loadedGpuMemoryFields(resp: {loadedGpuLayers: null,loadedNCpuMoe: null,loadedSplitRatio: null,- // Auto ignores these, so reset the editable knobs or a switch back to Manual sends a previous- // model's values. Diffusion excepted: an "auto" response may be an older shim that dropped- // a manual split, so restore the ask when the response carries it. Resetting the slider- // would turn it into manual/-1, unapplyable even after the unsloth_zoo upgrade adds --ngl.+ // Auto ignores these, so reset the editable knobs or a switch back to Manual sends a previous model's+ // values. Diffusion excepted: an "auto" response may be an older shim that dropped a manual split, so+ // restore the ask when the response carries it....(resp.is_diffusion? droppedSplit != null? { gpuLayers: droppedSplit }@@ -2218,7 +2203,6 @@ type ChatRuntimeStore = {/** What /api/inference/status says is resident, as opposed to what the picker selected.* undefined until the first read, so the header does not flash "not loaded". */residentCheckpoint: string | null | undefined;- /** Whether the backend loaded the active model from a filesystem path. */activeModelIsLocal: boolean;loadedContextLength: number | null;maxContextLength: number | null;@@ -2274,7 +2258,6 @@ type ChatRuntimeStore = {mcpEnabledForChat: boolean;ragEnabled: boolean;ragSource: RagSource;- /** Default composer attachment scope for chats inside a project. */projectAttachmentTarget: ProjectAttachmentTarget;/** Per-chat override of that default, so a pick in one chat does not redirect the rest. Session-only. */projectAttachmentTargetByThread: Record<string, ProjectAttachmentTarget>;@@ -2358,35 +2341,28 @@ type ChatRuntimeStore = {loadedNParallel: number | null;/** user --batch-size override for gguf loads (null = llama.cpp default 2048) */nBatch: number | null;- /** batch size the last successful load sent (null = default) */loadedNBatch: number | null;/** Pass-through args the resident model is running, as far as this client knows. A rollback* resends them: by then the target load has replaced the backend's inheritance source. */loadedLlamaExtraArgs: string[] | null;/** user --ubatch-size override for gguf loads (null = llama.cpp default 512) */nUbatch: number | null;- /** micro-batch size the last successful load sent (null = default) */loadedNUbatch: number | null;/** --spec-draft-type-k/-v override, the DRAFT context's KV dtype (null = f16). Separate from* kvCacheDtype, which is the target model's. */specDraftCacheDtype: string | null;- /** draft cache dtype the last successful load sent (null = default) */loadedSpecDraftCacheDtype: string | null;/** user --load-mode override (null = llama.cpp's own `auto`) */loadMode: string | null;- /** load mode the last successful load sent (null = default) */loadedLoadMode: string | null;/** user --ctx-checkpoints override (null = llama.cpp default 32) */ctxCheckpoints: number | null;- /** checkpoint count the last successful load sent (null = default) */loadedCtxCheckpoints: number | null;/** user --cache-ram override in MiB (null = llama.cpp default 8192) */cacheRam: number | null;- /** host prompt cache size the last successful load sent (null = default) */loadedCacheRam: number | null;/** Tensor-parallel split (--split-mode tensor) toggle, GGUF multi-GPU only. */tensorParallel: boolean;- /** Backend-reported tensor-parallel state; null until first hydrated. */loadedTensorParallel: boolean | null;/** What the RUNNING server was loaded with, as opposed to what the control shows: a pending* per-model config reaches disableVision before a switch captures its baseline. */@@ -2398,7 +2374,6 @@ type ChatRuntimeStore = {/** GPU memory strategy for GGUF loads. "auto" fits GPUs and context for you; "manual" owns* the offload (gpuLayers < 0 = Auto/--fit, >= 0 pins layers + nCpuMoe). */gpuMemoryMode: "auto" | "manual";- /** Backend-reported gpu memory mode; null until first hydrated. */loadedGpuMemoryMode: "auto" | "manual" | null;/** The active model must use the staged CPU-only runtime when it is reloaded. */loadedCpuFallback: boolean;@@ -2410,7 +2385,6 @@ type ChatRuntimeStore = {loadedNCpuMoe: number | null;/** Manual mode: per-GPU layer counts (--tensor-split), in GPU-in-use order; null = unset. */splitRatio: number[] | null;- /** Backend-reported per-GPU split ratio (--tensor-split); null = unset. */loadedSplitRatio: number[] | null;/** Model layer count (GGUF block_count); the manual ceiling is this + 1, the output layer too. */ggufLayerCount: number | null;@@ -2421,7 +2395,6 @@ type ChatRuntimeStore = {/** Namespace used by selectedGpuIds; kept with deferred persisted picks. */selectedGpuIndexKind: GpuIndexKind | null;loadedGpuIds: number[] | null;- /** Backend-reported namespace paired with loadedGpuIds. */loadedGpuIndexKind: GpuIndexKind | null;/** Persisted: expand every On Device GGUF repo's quantizations by default. */expandQuantizations: boolean;@@ -2524,7 +2497,6 @@ type ChatRuntimeStore = {/** False when the switch only puts back what was on screen before a hidden load, so the model* it steps off was never the user's. */persist?: boolean;- /** The context the model just loaded with, when the caller knows it. */maxTokensCap?: number;},) => void;@@ -2587,7 +2559,6 @@ type ChatRuntimeStore = {* readPendingAttachmentTargetClaim gave; a newer one means another composer owns it. */adoptPendingProjectAttachmentTarget: (threadId: string, claim?: number) =>void;- /** Drop a choice made in a composer that never became a chat. */clearPendingProjectAttachmentTarget: () => void;setRagMode: (mode: RagMode) => void;setRagTopK: (topK: number) => void;@@ -2603,9 +2574,7 @@ type ChatRuntimeStore = {owner?: () => void,) => void;appendToolLiveOutput: (toolCallId: string, text: string) => void;- /** Clear one tool's live output, or all when no id is given. */clearToolLiveOutput: (toolCallId?: string) => void;- /** Preserve a finished tool's full live-streamed output for display. */setToolFullOutput: (toolCallId: string, text: string) => void;/** Drop a stale preserved full output (a new run is reusing the id). */clearToolFullOutput: (toolCallId: string) => void;@@ -2768,13 +2737,10 @@ let loadedModelReasoningMode: {} | null = null;/**- * Record the mode a load/status response put the active model in. Persisted- * settings can describe the previous model, so they cannot pick the migration- * table after a family default changed on load.- *- * `fromLoad` marks a model this browser actually loaded. A status refresh only- * echoes the reasoningEnabled already in the store, which before hydration is- * this browser's local default, so it must not outrank the persisted toggle.+ * Record the mode a load/status response put the active model in. Persisted settings can describe the+ * previous model, so they cannot pick the migration table after a family default changed on load.+ * `fromLoad` marks a model this browser actually loaded: a status refresh only echoes the+ * reasoningEnabled already in the store, which before hydration is this browser's local default.*/export function noteLoadedModelReasoningMode(checkpoint: string,@@ -2822,7 +2788,6 @@ function getSettingsHydrationVersions(): SettingsHydrationVersions {};}-/** Refresh the localStorage cache from the values hydration just applied. */function cacheHydratedSettings(settings: PersistedChatSettings,versions: SettingsHydrationVersions,@@ -2994,7 +2959,6 @@ function rememberOutgoingModel(return next;}-/** Write an edit to the global set, and to the selected model's own set. */function persistParamEdit(changedParams: PersistedInferenceParams,paramsByModel: Record<string, PersistedInferenceParams> | null,@@ -3077,10 +3041,9 @@ function pickLocallyEditedParams(return edited;}-/** The context the last load or status published for the model on screen.- * loadedContextLength covers only a backend that sizes a window, so without this- * a safetensors model has nothing to clamp the hydration replay against. Keyed- * by checkpoint. */+/** The context the last load or status published for the model on screen. loadedContextLength covers+ * only a backend that sizes a window, so without this a safetensors model has nothing to clamp the+ * hydration replay against. Keyed by checkpoint. */let loadedContext: { checkpoint: string; cap: number } | null = null;function noteLoadedContext(checkpoint: string, cap: number | undefined): void {@@ -3118,9 +3081,8 @@ function noteModelDefaultsBeforeHydration(checkpoint: string,ownsPersistedGlobal: boolean,): void {- // A model the user selected while settings were in flight does not own the- // previous session's global snapshot, even as this tab's first checkpoint.- // Server-resident startup adoption is the one exception.+ // A model the user selected while settings were in flight does not own the previous session's global+ // snapshot, even as this tab's first checkpoint. Server-resident startup adoption is the exception.if (!ownsPersistedGlobal) {modelLoadedBeforeHydration = checkpoint;return;@@ -3298,11 +3260,9 @@ function getHydratedSettingsState() {continue;}- // Same reason, the other direction: a load that landed while this response- // was in flight already chose the mode for the running model and advances- // no mutation version, so the stored toggle describes the previous one. Let- // the load win, as its sampling table does. Only an actual load, though: a- // status refresh echoes local state and must not outrank the installation.+ // Same reason, the other direction: a load that landed while this response was in flight already+ // chose the mode for the running model and advances no mutation version, so the stored toggle+ // describes the previous one. Only an actual load, though: a status refresh echoes local state.if (key === "reasoningEnabled" &&loadEstablishedReasoningMode(state, true)@@ -3416,13 +3376,10 @@ function installationReasoningEnabled(state: ChatRuntimeStore): boolean {}/**- * Whether a load or status response established the reasoning mode for the- * active model, with no user toggle since.- *- * A load writes reasoningEnabled without advancing its mutation version, so- * hydration would otherwise replay a toggle describing the previous model. The- * migration table and the hydrated pill both read this, so they cannot disagree- * and show a thinking pill above non-thinking sampling.+ * Whether a load or status response established the reasoning mode for the active model, with no user+ * toggle since. A load writes reasoningEnabled without advancing its mutation version, so hydration+ * would otherwise replay a toggle describing the previous model. The migration table and the hydrated+ * pill both read this, so they cannot disagree and show a thinking pill above non-thinking sampling.*/function loadEstablishedReasoningMode(state: ChatRuntimeStore,@@ -3449,10 +3406,9 @@ function qwenMigrationThinkingOn(if (state.reasoningAlwaysOn) {return true;}- // Ahead of the established mode: a model that cannot reason never had the- // thinking table applied at load, so its recorded mode is just this browser's- // toggle. Only once status reported this checkpoint, though, since- // supportsReasoning starts false and "not asked yet" is not "cannot".+ // Ahead of the established mode: a model that cannot reason never had the thinking table applied at+ // load, so its recorded mode is just this browser's toggle. Only once status reported this+ // checkpoint, since supportsReasoning starts false and "not asked yet" is not "cannot".const statusSeen = sameCheckpointIdentity(loadedModelReasoningMode?.checkpoint,state.params.checkpoint,@@ -3496,11 +3452,10 @@ const QWEN_MIGRATION_DECISION_FIELDS = [// Raw, not sanitized: the server tests `key in current` against what is stored,// so asserting absence from the sanitized copy would fence a key the row has./**- * True when a decision field is stored but sanitizes away, such as an explicit- * null or an empty inferenceParamsByModel map: the compare-and-set can assert a- * value or an absence and neither fits, and `expected` matches by recursive- * subset, so an empty map matches a populated one. Decline rather than migrate- * unfenced. An absent key is different, and stays fenced by expectedAbsent.+ * True when a decision field is stored but sanitizes away, such as an explicit null or an empty+ * inferenceParamsByModel map: the compare-and-set can assert a value or an absence and neither fits,+ * and `expected` matches by recursive subset, so an empty map matches a populated one. Decline rather+ * than migrate unfenced. An absent key is different, and stays fenced by expectedAbsent.*/function qwenMigrationHasUnfenceableField(rawSettings: unknown,@@ -3548,9 +3503,9 @@ function qwenMigrationExpectedAbsentPaths(}}}- // Normalizing a differently-cased key writes a new exact-key row. Unfenced,- // the subset compare only checks the old spelling, so an exact-key row- // another tab added after the confirming read would be overwritten whole.+ // Normalizing a differently-cased key writes a new exact-key row. Unfenced, the subset compare only+ // checks the old spelling, so an exact-key row another tab added after the confirming read would be+ // overwritten whole.const stored = nested("inferenceParamsByModel");for (const modelId of Object.keys(patch.inferenceParamsByModel ?? {})) {if (!Object.hasOwn(stored, modelId)) {@@ -3593,9 +3548,8 @@ function applyLegacyQwenDefaultsAfterPresetChange(? migration.patch.inferenceParamsByModel?.[activeModelId]: migration.patch.inferenceParams;if (activePatch) {- // The open chat may pin one of these, but a later snapshot-less chat- // falls back to the installation copy captured when pairing began. Move- // it with the migrated defaults before restoring the thread's params.+ // The open chat may pin one of these, but a later snapshot-less chat falls back to the installation+ // copy captured when pairing began, so move it with the migrated defaults.noteThreadScopedDefaults(activePatch);}return {@@ -3618,13 +3572,10 @@ function applyLegacyQwenDefaultsAfterPresetChange(}/**- * Bring local params back in line after a migration the server accepted while a- * local edit was in flight.- *- * The edit flips provenance to "modified", so the ordinary apply refuses and- * the tab keeps generating from values the server no longer holds. Only the- * fields the user did not touch are adopted, which is what the per-field- * mutation versions captured before the write identify.+ * Bring local params back in line after a migration the server accepted while a local edit was in+ * flight. The edit flips provenance to "modified", so the ordinary apply refuses and the tab keeps+ * generating from values the server no longer holds. Only the fields the user did not touch are+ * adopted, which is what the per-field mutation versions captured before the write identify.*/function adoptMigratedFieldsAfterLocalEdit(patch: PersistedChatSettings,@@ -3676,17 +3627,14 @@ async function retryLegacyQwenDefaultsAfterPresetChange(migrateOwnedGlobalAlongsideModelMemory: boolean,): Promise<void> {try {- // Land the preset selection first so the confirming GET can recognize the- // legacy snapshot; a newer edit in another tab fails the fingerprint- // safely.+ // Land the preset selection first so the confirming GET can recognize the legacy snapshot; a newer+ // edit in another tab fails the fingerprint safely.await flushPendingChatSettings();- // A write outstanding past the flush timeout would reach the backend merge- // after this CAS and restore the legacy row. Rearm on its settlement rather- // than wait: an external selection gets no later status callback.+ // A write outstanding past the flush timeout would reach the backend merge after this CAS and restore+ // the legacy row. Rearm on its settlement rather than wait: an external selection gets no callback.if (!settingsWritesAreDrained()) {- // Bounded: a refused patch is retained and reflushed by each pass, so an- // unbounded rearm loops on an unreachable backend. Cleared once writes- // drain, so a healthy install never spends it.+ // Bounded: a refused patch is retained and reflushed by each pass, so an unbounded rearm loops on an+ // unreachable backend. Cleared once writes drain, so a healthy install never spends it.if (qwenMigrationRearmsWhileBlocked < QWEN_MIGRATION_MAX_REARMS) {qwenMigrationRearmsWhileBlocked += 1;void inflightFlush.catch(() => undefined).then(() => {@@ -3745,10 +3693,9 @@ async function retryLegacyQwenDefaultsAfterPresetChange(qwenMigrationExpectedAbsent(confirmedRaw),qwenMigrationExpectedAbsentPaths(confirmedRaw, migration.patch),);- // Only now touch local state: applying before persisting would leave this- // tab generating with values the server rejected. Revalidated after the- // await too, since the checkpoint can move while the response is in flight,- // and an external pick gets no callback to schedule another retry.+ // Only now touch local state: applying before persisting would leave this tab generating with values+ // the server rejected. Revalidated after the await too, since the checkpoint can move while the+ // response is in flight, and an external pick gets no callback to schedule another retry.if (persisted.applied &&sameCheckpointIdentity(@@ -3788,9 +3735,9 @@ const QWEN_MIGRATION_MAX_REARMS = 3;let qwenMigrationRearmsWhileBlocked = 0;/**- * Settles once a scheduled migration has decided and persisted, so a prompt sent- * right after picking a Qwen with a dormant legacy row does not generate from- * the values getReplayedParams just put on screen.+ * Settles once a scheduled migration has decided and persisted, so a prompt sent right after picking+ * a Qwen with a dormant legacy row does not generate from the values getReplayedParams just put on+ * screen.*/export async function awaitPendingQwenDefaultsMigration(): Promise<void> {if (qwenMigrationInFlight === null) return;@@ -3893,9 +3840,8 @@ function scheduleLegacyQwenDefaultsRetry(includeOwnedGlobal,migrateScheduledOwnedGlobalAlongsideModelMemory,).patch !== null;- // A status refresh needs a confirming GET only when the local store still- // holds a legacy row. Adoption is the exception: it owns a server snapshot- // model defaults already replaced locally, so only the server still has it.+ // A status refresh needs a confirming GET only when the local store still holds a legacy row.+ // Adoption is the exception: it owns a server snapshot model defaults already replaced locally.const hasOwnedGlobalCandidate =includeOwnedGlobal && isPresenceBumpQwen(state.params.checkpoint);if (!hasLocalCandidate && !hasOwnedGlobalCandidate) {@@ -4113,9 +4059,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({// Assigned by the confirming read below, so the failure path can prefer// it over the older hydration response.let confirmed: PersistedChatSettings | undefined;- // What to hydrate when nothing was migrated. The confirming read is the- // newer server truth, but a legacy merge that failed to save exists- // only here, and re-reading the server would discard it.+ // What to hydrate when nothing was migrated. The confirming read is the newer server truth, but a+ // legacy merge that failed to save exists only here, and re-reading the server would discard it.const unmigrated = (snapshot: PersistedChatSettings,): QwenDefaultsMigration => ({@@ -4129,9 +4074,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({get(),hydrationVersions.scalarSettings.reasoningEnabled,);- // A model loaded during the settings GET replaced the one whose global- // fallback was saved. Only the model resident at startup can own a- // global-only legacy snapshot.+ // A model loaded during the settings GET replaced the one whose global fallback was saved. Only the+ // model resident at startup can own a global-only legacy snapshot.const globalBelongsToActiveCheckpoint =!sameCheckpointIdentity(modelLoadedBeforeHydration, checkpoint) &&modelLeftBeforeHydration === null &&@@ -4153,19 +4097,16 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({let checkpointMovedDuringConfirm = false;if (fromServer && migration.patch) {try {- // Re-read immediately before the write, so the patch derives from- // this confirmation rather than the earlier hydration response and- // a newer edit from another tab is left untouched.+ // Re-read immediately before the write, so the patch derives from this confirmation rather than the+ // earlier hydration response and a newer edit from another tab is left untouched.const confirmedRaw = await getChatSettings();confirmed = sanitizeChatSettings(confirmedRaw);const confirmedState = get();- // A model switch during the confirming GET invalidates the- // checkpoint and mode this migration would persist; the new model- // schedules its own retry. The preset can move too: a slider- // touched now sets the local source to "modified" but queues its- // write behind the debounce, so the server still reads- // "builtin-default". Migrating on that stale read would rewrite a- // preset the user already modified, so trust the local version.+ // A model switch during the confirming GET invalidates the checkpoint and mode this migration would+ // persist; the new model schedules its own retry. The preset can move too: a slider touched now sets+ // the local source to "modified" but queues its write behind the debounce, so the server still reads+ // "builtin-default", and migrating on that stale read would rewrite a preset the user already+ // modified.const presetSourceUnchanged =activePresetSourceMutationVersion ===hydrationVersions.presets.activePresetSource &&@@ -4193,9 +4134,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({),): unmigrated(confirmed);- // migrateLegacyQwenDefaults returns its own input when nothing- // migrates, so a read finding no candidate would otherwise replace- // an unsaved legacy merge with server-only settings.+ // migrateLegacyQwenDefaults returns its own input when nothing migrates, so a read finding no+ // candidate would otherwise replace an unsaved legacy merge with server-only settings.if (migration.patch === null ||qwenMigrationHasUnfenceableField(confirmedRaw, confirmed)@@ -4222,12 +4162,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({};}} catch {- // Best effort, but that cannot mean hydrating values the server- // never accepted: the sheet and every request would show migrated- // sampling while storage still held the old row, on each start.- // Fall back to what was actually read, preferring the confirming- // snapshot when it landed, since the first read may already be- // stale and backfill would then push this browser's copy over it.+ // Best effort, but that cannot mean hydrating values the server never accepted: the sheet and every+ // request would show migrated sampling while storage still held the old row, on each start. Fall back+ // to what was actually read, preferring the confirming snapshot when it landed, since the first read+ // may already be stale.migration = unmigrated(confirmed ?? settings);}}@@ -4256,9 +4194,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({if (applied) {cacheHydratedSettings(hydratedSettings, hydrationVersions);mirroredSettingsHydrated = true;- // Only an authoritative read says a mirrored field is unset on the- // server. A GET that fell back to legacy storage knows nothing about- // it, and backfilling then pushes this browser's stale values over+ // Only an authoritative read says a mirrored field is unset on the server. A GET that fell back to+ // legacy storage knows nothing about it, and backfilling then pushes this browser's stale values over// whatever another browser wrote.if (fromServer) backfillMirroredSettings(hydratedSettings);// After the backfill, so a startup edit wins over the stored value.@@ -4267,9 +4204,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({if (checkpointMovedDuringConfirm) {scheduleLegacyQwenDefaultsRetry(null);}- // The previous session's tab-close writes, for the rows that did not exist- // yet when it sent them. A replay of one that did land is refused by its own- // seq, so this cannot revert anything newer.+ // The previous session's tab-close writes, for the rows that did not exist yet when it sent them. A+ // replay of one that did land is refused by its own seq, so this cannot revert anything newer.replayUnconfirmedThreadSettings();}} catch {@@ -4326,9 +4262,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({const outgoing = checkpointChanged? rememberOutgoingModel(state, state.params): null;- // An interactive local load arrives with the destination checkpoint and recommended params,- // reaching setCheckpoint only later, so replay here or the switch never restores the- // model's own settings. fromModelDefaults marks the updates memory goes back over.+ // An interactive local load arrives with the destination checkpoint and recommended params, reaching+ // setCheckpoint only later, so replay here or the switch never restores the model's own settings.noteLoadedContext(params.checkpoint, options?.maxTokensCap);const replayed = checkpointChanged || fromModelDefaults;const nextParams = getReplayedParams(@@ -4358,10 +4293,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({);const persistingGlobally =options?.persist !== false && state.settingsHydrated;- // A sampling key moved with a chat open belongs to that chat, so it reaches neither the- // defaults nor the model's memory. NOT gated on hydration, unlike the global write: the- // composer is live while the initial /api/chat/settings request is out, and an uncaptured- // edit leaked.+ // A sampling key moved with a chat open belongs to that chat, so it reaches neither the defaults nor+ // the model's memory. NOT gated on hydration, unlike the global write: the composer is live while the+ // initial /api/chat/settings request is out, and an uncaptured edit leaked.const sharedParams =options?.persist !== false? withoutCapturedThreadEdits(changedParams, fromModelDefaults)@@ -4403,9 +4337,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({: {}),};});- // Startup can hydrate before the server's active model is adopted. Once- // status applies its defaults the checkpoint and reasoning mode are known,- // so the deferred active-row migration can run.+ // Startup can hydrate before the server's active model is adopted. Once status applies its defaults+ // the checkpoint and reasoning mode are known, so the deferred active-row migration can run.if (options?.fromModelDefaults === true) {const retryState = get();const ownsPersistedGlobal =@@ -4439,9 +4372,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({return { activePresetSource };});if (returnedToBuiltInDefault) {- // The sheet updates provenance before applying the parameter edit. Defer- // a microtask so a final slider move restoring built-in Default has- // landed before the migration inspects and flushes it.+ // The sheet updates provenance before applying the parameter edit. Defer a microtask so a final+ // slider move restoring built-in Default has landed before the migration inspects and flushes it.scheduleLegacyQwenDefaultsRetry(useChatRuntimeStore.getState().params.checkpoint,);@@ -4499,9 +4431,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({set((state) => {const key = "__default";if (!threadId || threadId === key) return state;- // Two first turns can share "__default" with nothing linking a run to the thread being- // persisted, so moving the arrays wholesale handed over a sibling's stop handle. Adopt- // only when the key holds a single run.+ // Two first turns can share "__default" with nothing linking a run to the thread being persisted, so+ // moving the arrays wholesale handed over a sibling's stop handle.if ((state.runOwnerByThreadId[key]?.length ?? 0) > 1) return state;// Only the transient run maps move; anything filed under the real id is better identified.const moved: Partial<ChatRuntimeStore> = {};@@ -4582,9 +4513,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({setCheckpoint: (modelId, ggufVariant, options) => {let scheduleQwenMigration = false;set((state) => {- // Persist external selections so they survive a refresh. Local ids are re-derived on mount,- // and a stale persisted one would race the freshly-loaded model. See- // LAST_EXTERNAL_CHECKPOINT_KEY notes.+ // Persist external selections so they survive a refresh. Local ids are re-derived on mount, and a+ // stale persisted one would race the freshly-loaded model.saveLastExternalCheckpoint(isExternalModelId(modelId) ? modelId : null);// Only disarm research for a connection that cannot drive it: the id prefix alone switched// it off for capable providers, and saveBool would write that off for every browser.@@ -4601,9 +4531,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({unownedCheckpointBeforeHydration = modelId;}scheduleQwenMigration = checkpointChanged && state.settingsHydrated;- // Remember what the outgoing model was running with before replacing it.- // Not for a restore: the model it steps off is the one a background load- // put there, and its load defaults are not settings the user chose.+ // Remember what the outgoing model was running with. Not for a restore: the model it steps off is the+ // one a background load put there, and its load defaults are not settings the user chose.const outgoing =checkpointChanged && options?.persist !== false? rememberOutgoingModel(state, state.params)@@ -4663,10 +4592,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({checkpoint: modelId,maxTokens: nextMaxTokens,};- // The chat outranks the model it switches to, so its pinned sampling and prompt go back over- // the replay; an external switch has no load to do it. Live store only.- // Live store only: getReplayStatePatch still persists from the unrestored object, so the model's- // own values reach the installation defaults.+ // The chat outranks the model it switches to, so its pinned sampling and prompt go back over the+ // replay; an external switch has no load to do it. Live store only: getReplayStatePatch still persists+ // from the unrestored object, so the model's own values reach the installation defaults.const restoredParams = checkpointChanged? restoreThreadScopedParams(nextParams): nextParams;@@ -4694,19 +4622,16 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({...(clampsDeepResearch ? { deepResearchEnabled: false } : {}),};});- // An external pick is the whole story for that model: no load and no status- // follows it, so nothing else would ever schedule the migration and the- // replayed legacy row would keep being sent until a reload. Never with- // ownership, since selecting a model says nothing about whose global the- // installation's snapshot is. The scheduler's own dry run makes this cheap- // when there is no legacy row to repair.+ // An external pick is the whole story for that model: no load and no status follows it, so nothing+ // else would ever schedule the migration and the replayed legacy row would keep being sent until a+ // reload. Never with ownership, since selecting a model says nothing about whose global the+ // installation's snapshot is.if (scheduleQwenMigration) {scheduleLegacyQwenDefaultsRetry(null);}},- // Re-apply the incoming thread's own usage rather than blanking the bar: a run that finished- // in the background never wrote the visible value, and a still-mounted runtime skips the- // history loader on the way back.+ // Re-apply the incoming thread's own usage rather than blanking the bar: a run that finished in the+ // background never wrote the visible value, and a still-mounted runtime skips the history loader.setActiveThreadId: (activeThreadId) =>set((state) => ({activeThreadId,@@ -4749,9 +4674,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({: { ...state, threadScopedSettingsPending: pending };}if (threadScopedSettingsThreadId === null) {- // A held edit is in the store but belongs to its chat, so capturing it here would promote it- // to the default every snapshot-less chat follows; take the pre-window value. Deleting the- // key leaves no fallback and leaks the edited value into the next chat.+ // A held edit is in the store but belongs to its chat, so capturing it here would promote it to the+ // default every snapshot-less chat follows; take the pre-window value. Deleting the key leaves no+ // fallback and leaks the edited value into the next chat.const captured = readThreadScopedSettings(state) as Record<string,unknowndiff --git a/studio/frontend/src/features/chat/sync-external-providers.ts b/studio/frontend/src/features/chat/sync-external-providers.tsindex 8b25f304348..32037f3fb70 100644--- a/studio/frontend/src/features/chat/sync-external-providers.ts+++ b/studio/frontend/src/features/chat/sync-external-providers.ts@@ -116,10 +116,9 @@ export function pruneProviderModelIds(providerType: string,modelIds: string[],): string[] {- // Anthropic has no entry: a `-YYYYMMDD` id is the canonical name for the- // whole pre-4.6 generation, not a snapshot. This mirrored the backend- // denylist and outlived it, stripping those ids from the server catalog,- // the seeds and saved selections alike.+ // Anthropic has no entry: a `-YYYYMMDD` id is the canonical name for the whole pre-4.6+ // generation, not a snapshot. This mirrored the backend denylist and outlived it, stripping those+ // ids from the server catalog, the seeds and saved selections alike.if (providerType === "openai") {return modelIds.filter((id) => !OPENAI_DEPRECATED_MODELS.has(id));}diff --git a/studio/frontend/src/features/chat/text-attachment-accept.ts b/studio/frontend/src/features/chat/text-attachment-accept.tsindex fc695780341..68b2007d595 100644--- a/studio/frontend/src/features/chat/text-attachment-accept.ts+++ b/studio/frontend/src/features/chat/text-attachment-accept.ts@@ -4,11 +4,10 @@/*** Extensions `TextAttachmentAdapter` reads inline; shared with the drop path.*- * Read as UTF-8 (or BOM-marked UTF-16) and sent as text, so anything an editor- * opens belongs here.- * Extensions another adapter claims stay off: the composite adapter takes the- * first match, so .html, .pdf, .ods/.odt and the media containers are theirs.- * .ts and .mts are TypeScript here, so video cannot take them for MPEG-TS.+ * Read as UTF-8 (or BOM-marked UTF-16) and sent as text, so anything an editor opens belongs here.+ * Extensions another adapter claims stay off, since the composite adapter takes the first match:+ * .html, .pdf, .ods/.odt and the media containers are theirs. .ts and .mts are TypeScript here, so+ * video cannot take them for MPEG-TS.*/export const TEXT_ATTACHMENT_EXTENSIONS = [// Prose and documentation@@ -115,7 +114,6 @@ export const TEXT_ATTACHMENT_EXTENSIONS = [".jsp",".tpl",".qml",- // JavaScript and TypeScript".js",".jsx",".mjs",@@ -124,13 +122,11 @@ export const TEXT_ATTACHMENT_EXTENSIONS = [".tsx",".mts",".cts",- // Python".py",".pyi",".pyx",".pxd",".ipynb",- // JVM".java",".kt",".kts",@@ -170,7 +166,6 @@ export const TEXT_ATTACHMENT_EXTENSIONS = [".vhdl",".asm",".s",- // .NET".cs",".vb",".vbs",@@ -183,7 +178,6 @@ export const TEXT_ATTACHMENT_EXTENSIONS = [".sln",".props",".targets",- // Apple platforms".m",".mm",".swift",@@ -239,7 +233,6 @@ export const TEXT_ATTACHMENT_EXTENSIONS = [".cairo",".mojo",".gd",- // Shells".sh",".bash",".zsh",@@ -290,7 +283,6 @@ export const TEXT_ATTACHMENT_EXTENSIONS = [".pri",".cabal",".opam",- // Shaders".glsl",".frag",".vert",@@ -310,7 +302,6 @@ export const TEXT_ATTACHMENT_EXTENSIONS = [".robot",".http",".rest",- // Diffs".diff",".patch",];@@ -383,10 +374,9 @@ export async function isBinaryVobSubSubtitle(file: File): Promise<boolean> {const TRACKER_MOD_MAGICS = new Set(["M.K.","M!K!",- // ProTracker's other 4-channel marker. file(1) lists it at offset 1080- // alongside M.K., and the 31-sample layout puts byte 470 inside a sample name- // rather than the order table, so the Soundtracker fallback does not catch- // one either: without this the module is read as UTF-8 text.+ // ProTracker's other 4-channel marker. file(1) lists it at offset 1080 alongside M.K., and the+ // 31-sample layout puts byte 470 inside a sample name rather than the order table, so the+ // Soundtracker fallback does not catch one either."!PM!","PATT","NSMS",@@ -596,12 +586,10 @@ const GETTEXT_CHARSET_RE =/*** The charset a gettext catalog's header entry declares.*- * The entry is the first one in the file by convention, so the prefix settles- * it without decoding a catalog that can run to megabytes. A cutoff can still- * miss it, though: a project with more than 64 KiB of translator comments above- * the entry pushes it past the prefix, and the catalog was then refused for- * carrying exactly the bytes its header describes. So when the prefix holds no- * entry, read the rest, which the attachment cap already bounds.+ * The entry is the first one in the file by convention, so the prefix settles it without decoding a+ * catalog that can run to megabytes. A cutoff can still miss it: more than 64 KiB of translator+ * comments above the entry pushes it past the prefix, and the catalog was then refused for carrying+ * exactly the bytes its header describes. So when the prefix holds no entry, read the rest.*/function declaredGettextCharset(bytes: Uint8Array,@@ -619,9 +607,8 @@ function declaredGettextCharset(if (fromPrefix || !cut) {return fromPrefix;}- // A cutoff can also split the entry itself, leaving a match that holds the- // first continuation lines but not the Content-Type one, so retry on the- // charset rather than on the entry.+ // A cutoff can also split the entry itself, leaving a match that holds the first continuation+ // lines but not the Content-Type one, so retry on the charset rather than on the entry.return gettextHeaderCharset(decoder.decode(bytes));}@@ -640,10 +627,9 @@ const GETTEXT_ESCAPES: Record<string, string> = {/*** A gettext string's value: its adjacent literals joined, escapes resolved.*- * PO wraps a long string across quoted pieces and concatenates them, so the- * header is not the source text. Matching the raw entry instead read a charset- * split across two pieces (`charset=windows-` then `1252\n`) as the truncated- * label, and a catalog was refused for declaring a charset it does not.+ * PO wraps a long string across quoted pieces and concatenates them, so the header is not the+ * source text. Matching the raw entry instead read a charset split across two pieces+ * (`charset=windows-` then `1252`) as the truncated label, and refused the catalog.*/function gettextStringValue(raw: string): string {let out = "";@@ -667,8 +653,7 @@ function gettextStringValue(raw: string): string {return out;}-// A line that opens with anything but another quoted piece, which is where a-// header entry ends.+// A line that opens with anything but another quoted piece, which is where a header entry ends.const GETTEXT_ENTRY_ENDED_RE = /\r?\n[ \t]*[^ \t"\r\n]/;/**@@ -691,11 +676,10 @@ function gettextHeaderCharset(text: string, truncated = false): string | null {return charset && charset.toUpperCase() !== "CHARSET" ? charset : null;}-// Header block only: a body part can declare its own, but the message-level-// charset is what an 8-bit single-part mail is written in.-// Every Content-Type in the file, not just the first: a multipart message keeps-// the charset on its parts, and an mbox holds one per message, which can sit-// anywhere in the archive. Folded continuation lines start with space or tab.+// Header block only: a body part can declare its own, but the message-level charset is what an+// 8-bit single-part mail is written in. Every Content-Type in the file, not just the first: a+// multipart message keeps the charset on its parts, and an mbox holds one per message. Folded+// continuation lines start with space or tab.const EMAIL_CONTENT_TYPE_RE =/(?:^|\r?\n)Content-Type:((?:[^\r\n]*)(?:\r?\n[ \t][^\r\n]*)*)/gi;const CHARSET_LABEL_RE = /^[A-Za-z0-9._-]+/;@@ -724,9 +708,9 @@ function headerParameters(value: string): string[] {* A header value's parameter by name, and nothing that merely looks like one.** An unanchored search took the first match anywhere in the value, so- * `text/plain; name="charset=windows-1251.txt"; charset=windows-1252` read the- * filename and stopped, and a `filename="report; boundary=fake"` on any header- * at all registered a multipart delimiter that does not exist.+ * `text/plain; name="charset=windows-1251.txt"; charset=windows-1252` read the filename and+ * stopped, and a `filename="report; boundary=fake"` registered a multipart delimiter that does not+ * exist.*/function headerParameter(value: string, name: string): string | undefined {for (const parameter of headerParameters(value)) {@@ -743,9 +727,8 @@ function headerParameter(value: string, name: string): string | undefined {/*** A quoted-string parameter value, escapes resolved.*- * `\X` stands for `X`, so a value carrying a quote reads to its real closing- * one rather than stopping at the escaped one, and the text it yields is what a- * delimiter line actually holds. The splitter above already honours escapes;+ * An escape stands for the character it escapes, so a value carrying a quote reads to its real+ * closing one rather than stopping at the escaped one. The splitter above already honours escapes;* this is the other half of that.*/function unquoteHeaderValue(raw: string): string {@@ -782,30 +765,26 @@ const HEADER_FOLD_RE = /\r?\n[ \t]+/g;/*** The header regions of a message or archive, body text excluded.*- * One forward pass over the lines, slicing only the header regions themselves.- * Restarting a search from each candidate boundary instead is quadratic, and a- * body of diff hunks is all candidate boundaries: 1 MB of them took 14 seconds.+ * One forward pass over the lines, slicing only the header regions themselves. Restarting a search+ * from each candidate boundary is quadratic, and a body of diff hunks is all candidate boundaries:+ * 1 MB of them took 14 seconds.*- * Only a delimiter a header actually declared reopens the headers. Any line- * starting with `--` reopened them before, so a signature marker or a quoted- * diff put the body back into header mode, and the next body line shaped like- * `Content-Type: ... charset=...` became a second declaration that refused the- * file. A closing delimiter, `--boundary--`, ends its part instead of starting- * one.+ * Only a delimiter a header actually declared reopens the headers. Any line starting with `--`+ * reopened them before, so a signature marker or a quoted diff put the body back into header mode+ * and the next body line shaped like a Content-Type became a second declaration. A closing+ * delimiter ends its part instead of starting one.*- * @param mbox Whether the file is an archive of messages. A `From ` line only- * separates messages there, and an archive escapes the one a body starts with.- * A single `.eml` has no separator at all, so an ordinary sentence opening with- * "From " is body text and must not reopen the headers.+ * @param mbox Whether the file is an archive of messages. A `From ` line only separates messages+ * there, and an archive escapes the one a body starts with; a single `.eml` has no separator, so an+ * ordinary sentence opening with "From " is body text.*/function emailHeaderBlocks(text: string, mbox: boolean): string[] {const blocks: string[] = [];const boundaries = new Set<string>();const closeBlock = (block: string) => {- // Unfolded first: a header may wrap anywhere folding whitespace is allowed,- // and `multipart/mixed;\r\n boundary="part"` is a common wrap. Reading the- // raw block missed that boundary, so the part headers below it were never- // scanned and the charset they declare went with them.+ // Unfolded first: a header may wrap anywhere folding whitespace is allowed, and+ // `multipart/mixed;` wrapping before its boundary is common. Reading the raw block missed that+ // boundary, so the part headers below it were never scanned.const unfolded = block.replace(HEADER_FOLD_RE, " ");blocks.push(unfolded);for (const header of unfolded.matchAll(EMAIL_CONTENT_TYPE_RE)) {@@ -838,9 +817,8 @@ function emailHeaderBlocks(text: string, mbox: boolean): string[] {// An mbox separator, or a delimiter one of the headers above declared.let resumes = mbox && text.startsWith("From ", position);if (resumes) {- // A boundary belongs to the message that named it. Carrying one into- // the next message lets a body line that happens to repeat it reopen- // the headers there.+ // A boundary belongs to the message that named it. Carrying one into the next message lets+ // a body line that happens to repeat it reopen the headers there.boundaries.clear();} else if (boundaries.size > 0 && text.startsWith("--", position)) {// Trailing whitespace is allowed on a delimiter line and is not part of@@ -874,10 +852,9 @@ function emailHeaderBlocks(text: string, mbox: boolean): string[] {/*** The property-parameter sections of a vCard, values excluded.*- * `FN;CHARSET=windows-1252:name` declares a charset; `NOTE:see \;CHARSET=x`- * does not, because that text is the value. The section therefore ends at the- * property's value delimiter: the first colon outside a quoted parameter value.- * Folded lines, which begin with a space or tab, continue the line above.+ * `FN;CHARSET=windows-1252:name` declares a charset; the same text after a value delimiter does+ * not, because it is the value. The section therefore ends at the first colon outside a quoted+ * parameter value. Folded lines, which begin with a space or tab, continue the line above.*/function vCardParameterSections(text: string): string[] {const sections: string[] = [];@@ -923,12 +900,10 @@ function vCardParameterSections(text: string): string[] {return sections;}-// An XML prolog names the document's encoding and must be the first thing in it.-// Read from the bytes rather than the extension, so every XML dialect here-// (.resx, .xliff, .svg, a text .plist, the project files) is covered at once.-// The whitespace after the target is what tells a declaration from a processing-// instruction: `xml-stylesheet` and `xml-model` open with the same five bytes,-// and neither states what the document is written in.+// An XML prolog names the document's encoding and must be the first thing in it. Read from the+// bytes rather than the extension, so every XML dialect here is covered at once. The whitespace+// after the target is what tells a declaration from a processing instruction: `xml-stylesheet` and+// `xml-model` open with the same five bytes.const XML_PROLOG_ENCODING_RE =/^<\?xml[ \t\r\n][^>]*?[ \t\r\n]encoding[ \t]*=[ \t]*["\']([A-Za-z0-9._-]+)["\']/i;// XML's own S production. `\s` would also take a form feed or a no-break space,@@ -938,11 +913,9 @@ const XML_WHITESPACE_BYTES = new Set([0x20, 0x09, 0x0d, 0x0a]);/*** The encoding an XML declaration names, if the document opens with one.*- * The declaration has to be the first thing in the document, so five bytes- * settle whether there is one to read; everything else costs nothing. It then- * runs to its own ">", and its grammar puts no bound on the whitespace between- * the parts, so a fixed prefix could cut `encoding` off and leave a document- * that states its encoding refused for holding it.+ * The declaration has to be the first thing in the document, so five bytes settle whether there is+ * one to read. It then runs to its own ">", and its grammar puts no bound on the whitespace between+ * the parts, so a fixed prefix could cut `encoding` off and refuse a document that states it.*/function declaredXmlEncoding(bytes: Uint8Array): string | null {const decoder = new TextDecoder("windows-1252");@@ -964,13 +937,11 @@ function declaredXmlEncoding(bytes: Uint8Array): string | null {}/**- * The encoding a declared label names, or the label itself when nothing decodes- * it.+ * The encoding a declared label names, or the label itself when nothing decodes it.*- * `windows-1252`, `CP1252` and `latin1` are three spellings of one encoding, so- * comparing the spellings called an archive multi-charset when a single decoder- * reads every message in it. TextDecoder already knows the equivalences, and- * reports the canonical name it settled on.+ * `windows-1252`, `CP1252` and `latin1` are three spellings of one encoding, so comparing the+ * spellings called an archive multi-charset when a single decoder reads every message in it.+ * TextDecoder already knows the equivalences and reports the canonical name.*/function canonicalCharset(charset: string): string {const label = GETTEXT_CHARSET_ALIASES[charset.toUpperCase()] ?? charset;@@ -998,10 +969,9 @@ function charsetCollector(): { found: string[]; add: (c?: string) => void } {};}-// Headers and property parameters are ASCII, so these scans cannot fail on the-// body's own encoding. They read the whole file rather than a prefix: a-// declaration further in is the one a cutoff would miss, leaving those messages-// decoded as the first. The attachment cap already bounds the work.+// Headers and property parameters are ASCII, so these scans cannot fail on the body's own encoding.+// They read the whole file rather than a prefix: a declaration further in is the one a cutoff would+// miss, leaving those messages decoded as the first. The attachment cap already bounds the work./** Charsets a `.vcf` declares, one per property parameter. */function declaredVCardCharsets(bytes: Uint8Array, fileName: string): string[] {@@ -1036,14 +1006,11 @@ function declaredEmailCharsets(bytes: Uint8Array, fileName: string): string[] {/** A charset this browser has no decoder for.*- * An UndecodableTextError rather than a plain one, because that is the type- * the composer recognises: every other refusal in TextAttachmentAdapter.add- * toasts before it throws, and this one went out as a bare Error, failed the- * `instanceof` there, and left the attachment silently missing. The labels- * that land here are not exotic. Six of them are standard: the Encoding- * Standard maps iso-2022-kr, hz-gb-2312 and the iso-2022-cn family to- * "replacement", which TextDecoder is required to refuse, so a Korean or- * Chinese .eml declaring its own charset disappeared with no message at all.+ * An UndecodableTextError rather than a plain one, because that is the type the composer+ * recognises: every other refusal in TextAttachmentAdapter.add toasts before it throws, and this+ * one went out as a bare Error, failed the `instanceof`, and left the attachment silently missing.+ * Six of the labels that land here are standard: the Encoding Standard maps iso-2022-kr,+ * hz-gb-2312 and the iso-2022-cn family to "replacement", which TextDecoder must refuse.*/function unsupportedCharsetError(fileName: string,@@ -1110,24 +1077,19 @@ const ASCII_DECODER_LABEL = "windows-1252";/*** A vCard decoded one property at a time, or null if it cannot be.*- * `CHARSET` is a property parameter, so a 2.1 card may legitimately put- * windows-1252 on `FN` and windows-1251 on `NOTE`. Reading the file as one unit- * corrupts every property but one, which is why more than one declaration is- * refused there; this honours each of them instead.+ * `CHARSET` is a property parameter, so a 2.1 card may legitimately put windows-1252 on `FN` and+ * windows-1251 on `NOTE`. Reading the file as one unit corrupts every property but one, which is+ * why more than one declaration is refused there; this honours each of them instead.*- * Only the value is decoded under the property's own charset. The name and- * parameters ahead of the delimiter are ASCII by the grammar, and a folded line,- * which begins with a space or tab, continues the property above under the same- * charset. A property that declares nothing is UTF-8, strictly: this is not the- * place to guess a code page for it.+ * Only the value is decoded under the property's own charset: the name and parameters ahead of the+ * delimiter are ASCII by the grammar, and a folded line continues the property above under the same+ * charset. A property that declares nothing is UTF-8, strictly.*- * Anything it cannot account for comes back as a reading with no text, so the- * caller falls back to the whole-file one rather than emitting a partly guessed- * one. `failure` is set when a declaration itself is the obstacle, which no- * other reading of the file can resolve.+ * Anything it cannot account for comes back as a reading with no text, so the caller falls back to+ * the whole-file one rather than emitting a partly guessed one. `failure` is set when a declaration+ * itself is the obstacle, which no other reading can resolve.*- * @param truncated Whether `bytes` is a prefix. Only its last line can end- * mid-character, so only that one is read leniently.+ * @param truncated Whether `bytes` is a prefix. Only its last line can end mid-character.*/function decodeVCardPerProperty(bytes: Uint8Array,@@ -1262,15 +1224,11 @@ export function decodeTextAttachmentBytes(if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {return decodeWithCharset(bytes.subarray(2), "utf-16be", fileName, truncated);}- // A document that states its own encoding decides before UTF-8 is tried:- // bytes that happen to be valid UTF-8 would otherwise decode into different- // characters than the file says it holds. An XML prolog is that statement by- // specification, a gettext header and a vCard property parameter by format,- // and all three are written by the exporter rather than typed by a person.- //- // A mail Content-Type is the exception and stays a fallback below: clients- // mislabel 8-bit mail constantly, so the bytes being valid UTF-8 is the- // better evidence there.+ // A document that states its own encoding decides before UTF-8 is tried: bytes that happen to be+ // valid UTF-8 would otherwise decode into different characters than the file says it holds. An XML+ // prolog is that statement by specification, a gettext header and a vCard property parameter by+ // format, and all three are written by the exporter rather than typed by a person. A mail+ // Content-Type is the exception and stays a fallback below: clients mislabel 8-bit mail constantly.const xmlEncoding = declaredXmlEncoding(whole);if (xmlEncoding) {return decodeWithCharset(bytes, xmlEncoding, fileName, truncated);@@ -1281,21 +1239,17 @@ export function decodeTextAttachmentBytes(}const vCardCharsets = declaredVCardCharsets(whole, fileName);if (vCardCharsets.length > 0) {- // CHARSET is a property parameter whatever the count, so one declaration- // speaks for its own property and not for the file: an export holding a 2.1- // card beside a 3.0 one, which cannot declare anything, read the whole- // bundle in the 2.1 card's charset and turned the other into mojibake.- // A preview reads the same way, so what it shows is what gets sent.+ // CHARSET is a property parameter whatever the count, so one declaration speaks for its own+ // property and not for the file: an export holding a 2.1 card beside a 3.0 one read the whole+ // bundle in the 2.1 card's charset. A preview reads the same way, so what it shows is what is sent.const perProperty = decodeVCardPerProperty(bytes, truncated, fileName);if ("text" in perProperty) {return perProperty.text;}- // A declaration the reading could not honour has to be reported, not read- // past. Falling through to UTF-8 accepted the card whenever its other- // properties happened to be ASCII, so one unsupported charset was refused- // on a card that declared it alone and ignored on a card that declared a- // second one beside it. The single-declaration case reports the same- // obstacle through the whole-unit reading below.+ // A declaration the reading could not honour has to be reported, not read past. Falling through to+ // UTF-8 accepted the card whenever its other properties happened to be ASCII, so one unsupported+ // charset was refused on a card that declared it alone and ignored on a card that declared a second+ // one beside it. The single-declaration case reports the same obstacle through the reading below.if (perProperty.failure && vCardCharsets.length > 1) {throw perProperty.failure;}@@ -1306,17 +1260,15 @@ export function decodeTextAttachmentBytes(return decodeWithCharset(bytes, vCardCharsets[0]!, fileName, truncated);}try {- // A truncated read decodes with stream:true so the character the slice cut- // in half is dropped rather than raising. A whole file gets no such licence:- // there, a dangling lead byte is a bad encoding and has to be reported.+ // A truncated read decodes with stream:true so the character the slice cut in half is dropped+ // rather than raising. A whole file gets no such licence: a dangling lead byte is a bad encoding.return new TextDecoder("utf-8", { fatal: true }).decode(bytes, {stream: truncated,});} catch {- // An 8-bit mail says which charset it is, so honour it rather than refusing- // a standards-valid message. Tried only here, so a modern one is never- // remapped by a stale declaration. A vCard was tried above and only reaches- // this line when it named more than one charset.+ // An 8-bit mail says which charset it is, so honour it rather than refusing a standards-valid+ // message. Tried only here, so a modern one is never remapped by a stale declaration. A vCard was+ // tried above and only reaches this line when it named more than one charset.const declared = vCardCharsets.length? vCardCharsets: declaredEmailCharsets(whole, fileName);@@ -1331,9 +1283,8 @@ export function decodeTextAttachmentBytes(`It declares more than one charset (${declared.join(", ")}), and is read as one unit.`,);}- // Otherwise a legacy code page, but which one is not knowable from the- // bytes: the same byte is a different letter in windows-1252, windows-1251- // and Shift-JIS. Guessing sends confident mojibake, so say so instead.+ // Otherwise a legacy code page, but which one is not knowable from the bytes: the same byte is a+ // different letter in windows-1252, windows-1251 and Shift-JIS. Guessing sends confident mojibake.throw new UndecodableTextError(fileName);}}diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex a91c5c9e471..89f520d44fd 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -148,7 +148,6 @@ export interface ValidateModelResponse {chat_template?: string | null;/** Architecture only shipped by a newer transformers; UI pauses on the upgrade dialog. */requires_transformers_upgrade?: boolean;- /** Set only when requires_transformers_upgrade. */transformers_upgrade?: TransformersUpgradeInfo | null;}diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.tsindex dba970f3ec0..10ea4956077 100644--- a/studio/frontend/src/features/chat/utils/continuation.ts+++ b/studio/frontend/src/features/chat/utils/continuation.ts@@ -1,9 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-/** Resuming a response that stopped early (`length`, `cancelled`, `interrupted`): the conversation- * is re-sent with the partial as the final assistant turn plus `continue_final_message`, so- * the prompt ends mid-sentence and the new text is appended to the partial. */+/** Resuming a response that stopped early (`length`, `cancelled`, `interrupted`): the conversation is re-sent+ * with the partial as the final assistant turn plus `continue_final_message`, so the prompt ends mid-sentence+ * and the new text is appended to the partial. *//** Why a turn ended before the model was done. `context_window` is a `length` cut the same* request can never fit into, hence its own reason. */diff --git a/studio/frontend/src/features/chat/utils/openwebui-import.ts b/studio/frontend/src/features/chat/utils/openwebui-import.tsindex a27925853a3..cbaa5d8df94 100644--- a/studio/frontend/src/features/chat/utils/openwebui-import.ts+++ b/studio/frontend/src/features/chat/utils/openwebui-import.ts@@ -89,8 +89,6 @@ export function isOpenWebUIRecord(value: unknown): boolean {return blob.messages.some(looksLikeOpenWebUIMessage);}-// Content-// A closed fence first, then an opener that never closed: an answer cut off inside a code// block still quotes code. The unclosed form is anchored to line start, where markdown// requires a fence; unanchored, a stray ``` swallowed the rest of the message.@@ -454,8 +452,6 @@ function messageParts(return { content: parts, attachments };}-// Message graph-/** Message ids from `currentId` back to the root: the branch the user had open. */function activePath(byId: Map<string, Node>, currentId: unknown): Set<string> {const path = new Set<string>();diff --git a/studio/frontend/src/features/chat/utils/qwen-defaults-migration.ts b/studio/frontend/src/features/chat/utils/qwen-defaults-migration.tsindex cca7fe819a0..47f77d7600d 100644--- a/studio/frontend/src/features/chat/utils/qwen-defaults-migration.ts+++ b/studio/frontend/src/features/chat/utils/qwen-defaults-migration.ts@@ -135,11 +135,10 @@ function migrateStoredModelDefaults(const migratedByModel: Record<string, PersistedInferenceParams> = {};const patchByModel: Record<string, PersistedInferenceParams> = {};const storedEntries = Object.entries(stored ?? {});- // Prefer an exact key when legacy storage holds two spellings; otherwise- // normalize the sole case-insensitive match to the checkpoint spelling, which- // is how replay indexes the map. normalizeModelIdentity, not toLowerCase: it- // preserves case for POSIX paths, which can name two different files. Opaque- // ids compare exactly and have no legacy spellings to reconcile.+ // Prefer an exact key when legacy storage holds two spellings; otherwise normalize the sole+ // case-insensitive match to the checkpoint spelling, which is how replay indexes the map.+ // normalizeModelIdentity, not toLowerCase: it preserves case for POSIX paths, which can name two+ // different files. Opaque ids compare exactly and have no legacy spellings to reconcile.const activeIdentity = normalizeModelIdentity(activeCheckpoint);const activeIsOpaque = isOpaqueModelRef(activeCheckpoint);// Only the sole alias, checked rather than assumed: with two spellings one@@ -230,8 +229,7 @@ export function migrateLegacyQwenDefaults(const globalChanges = migrateGlobal? changedDefaults(settings.inferenceParams ?? {}, currentGlobalDefaults): null;- // An already-current global produces {}, which is truthy and would be sent as- // an empty patch.+ // An already-current global produces {}, which is truthy and would be sent as an empty patch.const globalPatch =globalChanges && Object.keys(globalChanges).length > 0? globalChangesdiff --git a/studio/frontend/src/features/chat/utils/settings-retry.ts b/studio/frontend/src/features/chat/utils/settings-retry.tsindex 960c45d587d..a269a3295ca 100644--- a/studio/frontend/src/features/chat/utils/settings-retry.ts+++ b/studio/frontend/src/features/chat/utils/settings-retry.ts@@ -1,15 +1,14 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Which failed settings writes are worth keeping, and which have to be let go. The settings-// queue coalesces every change into one patch and requeues it when the PUT fails, which is-// right for a server that is down and wrong for one that refuses this patch.-// /api/chat/settings is extra="forbid" and rejects the WHOLE body on one bad field, so a-// permanently-rejected value requeued forever takes every later save down with it: after one-// 400 no chat setting can persist again for the life of the tab. Reachable without a bug on-// either side whenever the two versions differ.-// A new bundle against a rolled-back backend has every mirrored field rejected as extra_forbidden,-// which is exactly the shape below.+// Which failed settings writes are worth keeping, and which have to be let go. The settings queue+// coalesces every change into one patch and requeues it when the PUT fails, which is right for a+// server that is down and wrong for one that refuses this patch. /api/chat/settings is+// extra="forbid" and rejects the WHOLE body on one bad field, so a permanently-rejected value+// requeued forever takes every later save down with it: after one 400 no chat setting can persist+// again for the life of the tab. Reachable without a bug on either side whenever the two versions+// differ. A new bundle against a rolled-back backend has every mirrored field rejected as+// extra_forbidden, which is exactly the shape below./** A non-2xx answer from the settings endpoint, carrying what the server said. */export class ChatSettingsRequestError extends Error {diff --git a/studio/frontend/src/features/chat/utils/update-thread-message.ts b/studio/frontend/src/features/chat/utils/update-thread-message.tsindex 7425115a47d..8e4422a95fd 100644--- a/studio/frontend/src/features/chat/utils/update-thread-message.ts+++ b/studio/frontend/src/features/chat/utils/update-thread-message.ts@@ -85,8 +85,7 @@ export function extractTaggedText(content: any): string {const text = part.text || part.content || "";if (!text) return "";- // Trim the text first so we don't accumulate newlines- // around the tags on every save.+ // Trim the text first so we don't accumulate newlines around the tags on every save.if (part.type === 'reasoning') {return `${open}THINK${close}\n${escapeMarkers(text.trim())}\n${open}/THINK${close}`;}diff --git a/studio/frontend/src/features/export/api/export-api.ts b/studio/frontend/src/features/export/api/export-api.tsindex eee9d6eb472..eb238159b6a 100644--- a/studio/frontend/src/features/export/api/export-api.ts+++ b/studio/frontend/src/features/export/api/export-api.ts@@ -240,9 +240,8 @@ export async function getExportStatus(): Promise<ExportStatus> {return parseJson<ExportStatus>(response);}-// ─────────────────────────────────────────────────────────────────────-// Live export log stream (Server-Sent Events)-// ─────────────────────────────────────────────────────────────────────+// ───────────────────────────────────────────────────────────────────── Live export log stream+// (Server-Sent Events) ─────────────────────────────────────────────────────────────────────export type ExportLogStream = "stdout" | "stderr" | "status";diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsxindex 91e2d3c2833..88972be1730 100644--- a/studio/frontend/src/features/export/export-page.tsx+++ b/studio/frontend/src/features/export/export-page.tsx@@ -178,7 +178,6 @@ export function ExportPage() {})),);- // ---- API-driven checkpoint state ----const [models, setModels] = useState<ModelCheckpoints[]>(() => getCachedCheckpoints() ?? [],);@@ -302,7 +301,6 @@ export function ExportPage() {steps: exportTourSteps,});- // ---- Fetch checkpoints on mount ----useEffect(() => {let cancelled = false;const hadCache = getCachedCheckpoints() !== null;@@ -347,7 +345,6 @@ export function ExportPage() {setExportMethod("gguf");}, [preselectRun, models]);- // ---- Fetch local models for direct export ----useEffect(() => {let cancelled = false;const hadCache = getCachedLocalModels() !== null;@@ -386,7 +383,6 @@ export function ExportPage() {signalReady();}, [isLoadingLocalModels, loadingCheckpoints, signalReady]);- // ---- Derived state ----const selectedModelData = useMemo(() =>selectedModelIdx != null@@ -905,7 +901,6 @@ export function ExportPage() {return () => obs.disconnect();}, [showPanel]);- // ---- Render ----return (<div className="min-h-[calc(100dvh-var(--studio-titlebar-height,0px))] bg-background"><main className="mx-auto max-w-7xl px-5 py-8 sm:px-9">diff --git a/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts b/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.tsindex a55988bc702..565c0b71cb2 100644--- a/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts+++ b/studio/frontend/src/features/export/hooks/use-export-runtime-lifecycle.ts@@ -56,12 +56,11 @@ export function useExportRuntimeLifecycle(): void {store.getState().setConnected(false);};- // ── JSON log polling (tunnel-safe fallback) ──────────────────────────- // Runs for the whole active run, in parallel with the SSE stream. On- // localhost the SSE delivers first and these polls are de-duped away by- // seq; over a Cloudflare tunnel the SSE is buffered and these polls are- // what actually fill the log panel. A successful poll marks the stream- // "connected" so the panel shows "streaming" rather than "connecting...".+ // ── JSON log polling (tunnel-safe fallback) ────────────────────────── Runs for the whole+ // active run, in parallel with the SSE stream. On localhost the SSE delivers first and these+ // polls are de-duped away by seq; over a Cloudflare tunnel the SSE is buffered and these polls+ // are what actually fill the log panel. A successful poll marks the stream "connected" so the+ // panel shows "streaming" rather than "connecting...".const pollLogsOnce = async () => {if (disposed || !store.getState().isExporting) return;try {@@ -134,11 +133,10 @@ export function useExportRuntimeLifecycle(): void {if (streamController === controller) {streamController = null;}- // Do NOT clear `connected` here: over a Cloudflare tunnel the SSE drops- // and reconnects repeatedly (buffered / premature complete), which used- // to flap the indicator back to "connecting...". The log poll owns the- // connected flag for the duration of the run; stopStream clears it when- // the run actually ends.+ // Do NOT clear `connected` here: over a Cloudflare tunnel the SSE drops and reconnects+ // repeatedly (buffered / premature complete), which used to flap the indicator back to+ // "connecting...". The log poll owns the connected flag for the duration of the run;+ // stopStream clears it when the run actually ends.if (!disposed &&diff --git a/studio/frontend/src/features/export/stores/export-runtime-store.ts b/studio/frontend/src/features/export/stores/export-runtime-store.tsindex 53a4e22c989..77f518ebbec 100644--- a/studio/frontend/src/features/export/stores/export-runtime-store.ts+++ b/studio/frontend/src/features/export/stores/export-runtime-store.ts@@ -308,9 +308,8 @@ export const useExportRuntimeStore = create<ExportRuntimeStore>()((set, get) =>startedAt: state.startedAt ?? Date.now(),};}- // A recovered (not store-owned) run finished on the backend. Settle from- // the last-op record when present (accurate success/error/output path),- // else fall back to the optimistic guess.+ // A recovered (not store-owned) run finished on the backend. Settle from the last-op record+ // when present (accurate success/error/output path), else fall back to the optimistic guess.if (!status.is_export_active && state.isExporting && !state.ownsRun) {// A standalone load_checkpoint (or no recorded op) is not an export and// must never settle as a finished export. A completed export ends on itsdiff --git a/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts b/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.tsindex 0d8abd20dbd..440791f4573 100644--- a/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts+++ b/studio/frontend/src/features/find-in-page/hooks/use-find-in-page.ts@@ -193,15 +193,11 @@ export function useFindInPage(const index = indexRef.current;// One past the cap: a count equal to the cap cannot say whether it is the total or a floor,// and the counter would read "5000+" for a page holding exactly 5000. Only its existence is- // kept.- //- // The anchor decides WHICH matches survive the cap, keeping the ones nearest the reader. It- // is a thunk because `viewportOffset` reads layout and an argument is evaluated whether or- // not the callee wants it, so inline it ran on every keystroke however few matches there- // were.- //- // Remembered as the thunk resolves it, so the trim below can ask where the reader was- // without a second layout read, and without one at all under the cap.+ // kept. The anchor decides WHICH matches survive the cap, keeping the ones nearest the+ // reader. It is a thunk because `viewportOffset` reads layout and an argument is evaluated+ // whether or not the callee wants it, so inline it ran on every keystroke however few matches+ // there were. Remembered as the thunk resolves it, so the trim below can ask where the reader+ // was without a second layout read, and without one at all under the cap.let anchoredAt: number | null = null;const matches = findMatches(index,@@ -266,11 +262,10 @@ export function useFindInPage(// A fresh open always starts from the reader, whatever the index says.search(false, true);- // The thread mounts its tail first and widens over the next few frames, so a search against- // the document as found would miss everything above the fold. The bar stays usable throughout.- //- // Only the threads this search can read: asking globally would make an off-route conversation- // mount every row it withheld, to be skipped by the very walk that asked for it.+ // The thread mounts its tail first and widens over the next few frames, so a search against the+ // document as found would miss everything above the fold. The bar stays usable throughout. Only+ // the threads this search can read: asking globally would make an off-route conversation mount+ // every row it withheld, to be skipped by the very walk that asked for it.let live = true;void completeProgressiveMounts((viewport) =>indexReaches(scope, viewport),diff --git a/studio/frontend/src/features/find-in-page/lib/find-dom.ts b/studio/frontend/src/features/find-in-page/lib/find-dom.tsindex 2e9eb9d1122..a700363642c 100644--- a/studio/frontend/src/features/find-in-page/lib/find-dom.ts+++ b/studio/frontend/src/features/find-in-page/lib/find-dom.ts@@ -441,7 +441,6 @@ function revealWithin(scroller: Element, rect: DOMRect): boolean {return true;}-/** The element a range starts in, which is where both walks below begin. */function elementFor(range: Range): Element | null {const start = range.startContainer;return start.nodeType === 1@@ -491,7 +490,6 @@ export function scrollViewportTop(range: Range): number {export function scrollRangeIntoView(range: Range): boolean {let element = elementFor(range);let moved = false;- // Bounded by DOM depth, and each step is one rect read plus at most one scroll write.while (element) {if (scrollsAxis(element, "y") || scrollsAxis(element, "x")) {// Re-read each time: scrolling the inner container decides what the outer one still owes.diff --git a/studio/frontend/src/features/find-in-page/lib/find-text-index.ts b/studio/frontend/src/features/find-in-page/lib/find-text-index.tsindex 39665f8e6f2..cfc2e6eee82 100644--- a/studio/frontend/src/features/find-in-page/lib/find-text-index.ts+++ b/studio/frontend/src/features/find-in-page/lib/find-text-index.ts@@ -188,9 +188,9 @@ function skipsByMarkup(element: FindElementLike): boolean {if (SKIP_TAGS.has(element.tagName.toUpperCase())) return true;if (hasClassToken(element, "katex-mathml")) return true;if (element.getAttribute(FIND_SKIP_ATTRIBUTE) !== null) return true;- // Boolean attributes, so presence is the whole signal. The shell parks an off-route workspace- // under `inert`; Radix marks the page `aria-hidden` behind a modal. KaTeX is the narrow exception:- // its painted HTML tree is deliberately aria-hidden because a clipped MathML mirror speaks it.+ // Boolean attributes, so presence is the whole signal. The shell parks an off-route workspace under `inert`;+ // Radix marks the page `aria-hidden` behind a modal. KaTeX is the narrow exception: its painted HTML tree is+ // deliberately aria-hidden because a clipped MathML mirror speaks it.if (element.getAttribute("hidden") !== null) return true;if (element.getAttribute("inert") !== null) return true;return (@@ -204,10 +204,10 @@ export function skipsSubtree(style: ResolvedStyle | null = computedStyle(element),): boolean {if (skipsByMarkup(element)) return true;- // `contentVisibilityAuto` off, since such a subtree is skipped rather than hidden and nothing- // would put it back (scrolling renders without mutating, so the observer never fires); opacity- // off, so a message fading in stays findable. Both spellings of each option, since an engine- // reads only the name it knows: the modern one alone is a no-op on Chrome 105-120, Firefox 106-121.+ // `contentVisibilityAuto` off, since such a subtree is skipped rather than hidden and nothing would put it back+ // (scrolling renders without mutating, so the observer never fires); opacity off, so a message fading in stays+ // findable. Both spellings of each option, since an engine reads only the name it knows: the modern one alone+ // is a no-op on Chrome 105-120, Firefox 106-121.const painted = element.checkVisibility?.({contentVisibilityAuto: false,opacityProperty: false,@@ -362,9 +362,9 @@ export function buildTextIndex(}// A share, not all: one huge node given the rest leaves out everything after it.let take = Math.min(ceiling - length, MAX_NODE_CHARS);- // Never between the halves of a pair: keeping the leading one leaves a code unit that is- // not a character, which reads as a grapheme of its own and lets a match end against it,- // inside what the page draws as one. Dropping it instead makes the cut a real boundary.+ // Never between the halves of a pair: keeping the leading one leaves a code unit that is not a character,+ // which reads as a grapheme of its own and lets a match end against it, inside what the page draws as one.+ // Dropping it instead makes the cut a real boundary.if (take > 0 && take < data.length && isPairedHalf(data, take))take -= 1;if (take <= 0) {@@ -439,16 +439,14 @@ export function buildTextIndex(/*** True when a rebuild renumbers the match list, so the search has to re-anchor to the viewport.*- * The index is the workspace followed by the surfaces portaled in front of it, joined at- * `rootLength`. A monitor stays searchable while it is up and rewrites its reading on a timer, so- * judged as one string every poll reads as a renumbered document and throws the reader out of the- * conversation behind it. What decides is whether text moved AHEAD of the reader's offset.+ * The index is the workspace followed by the surfaces portaled in front of it, joined at `rootLength`. A monitor+ * stays searchable while it is up and rewrites its reading on a timer, so judged as one string every poll reads+ * as a renumbered document and throws the reader out of the conversation behind it. What decides is whether text+ * moved AHEAD of the reader's offset.*- * This is the cheap half of the answer. `search` asks the exact question afterwards, by looking for- * a match still starting at that offset, so this only has to turn down the rebuilds where the- * offset would be meaningless.- *- * Here rather than beside its caller: the hook imports React and cannot run under `node --test`.+ * This is the cheap half of the answer. `search` asks the exact question afterwards, by looking for a match+ * still starting at that offset, so this only has to turn down the rebuilds where the offset would be+ * meaningless. Here rather than beside its caller: the hook imports React and cannot run under `node --test`.*/export function renumbersMatches(before: FindTextIndex,@@ -519,10 +517,8 @@ function canonicalVariants(needle: string, dotted: boolean): string[] {return variants;}-/**- * One canonical cluster. Hangul conjoining sequences can contain repeated leading, vowel, and- * trailing Jamo, so the whole L*V*T* run has to win before the generic character alternative.- */+/** One canonical cluster. Hangul conjoining sequences can contain repeated leading, vowel, and trailing Jamo,+ * so the whole L*V*T* run has to win before the generic character alternative. */const CLUSTER_PATTERN =// biome-ignore lint/suspicious/noMisleadingCharacterClass: Jamo and combining marks intentionally form canonical clusters./(?:[ᄀ-ᅟꥠ-]+[ᅠ-ᆧힰ-ퟆ]+[ᆨ-ᇿퟋ-ퟻ]*|[\s\S])[̀-ͯ҃-҉᪰-᷀-᷿⃐-⃰︠-︯]*/gu;@@ -539,11 +535,10 @@ const TRAILING_HANGUL_JAMO_SOURCE = "[\\u11a8-\\u11ff\\ud7cb-\\ud7fb]";const HANGUL_HINT_PATTERN = /[ᄀ-ᇿꥠ-가-ퟻ]/u;/**- * True when a cluster needs the trailing-jamo boundary, which only the pattern path writes.- *- * Extended and Old Hangul jamo have no precomposed form, so NFC and NFD spell them the same way and- * the single-spelling query would take the literal scan, where an open syllable prefix-matches a- * closed one. Modern Hangul always has two spellings and reaches the pattern anyway.+ * True when a cluster needs the trailing-jamo boundary, which only the pattern path writes. Extended and Old+ * Hangul jamo have no precomposed form, so NFC and NFD spell them the same way and the single-spelling query+ * would take the literal scan, where an open syllable prefix-matches a closed one. Modern Hangul always has two+ * spellings and reaches the pattern anyway.*/function needsHangulBoundary(needle: string): boolean {if (!HANGUL_HINT_PATTERN.test(needle)) return false;@@ -561,10 +556,8 @@ function needsHangulBoundary(needle: string): boolean {const HANGUL_LVT_PATTERN =/^([\u1100-\u115f\ua960-\ua97f][\u1160-\u11a7\ud7b0-\ud7c6])([\u11a8-\u11ff\ud7cb-\ud7fb][\s\S]*)$/u;-/**- * The half-composed spelling of a closed syllable: the L+V pair precomposed, the trailing jamo left- * as it is. Neither NFC nor NFD writes it, so a document holding one is invisible to both.- */+/** The half-composed spelling of a closed syllable: the L+V pair precomposed, the trailing jamo left as it is.+ * Neither NFC nor NFD writes it, so a document holding one is invisible to both. */function partiallyComposedHangul(cluster: string): string | null {const parts = HANGUL_LVT_PATTERN.exec(cluster);if (!parts) return null;@@ -584,9 +577,9 @@ function isPairedHalf(text: string, at: number): boolean {/*** Per cluster, because alternating whole spellings of the WHOLE query reaches only all-composed or- * all-decomposed text, and one occurrence can be neither: joining two text nodes joins two sources,- * so `café` in one and `café` in the next make one visible word with a spelling the- * query cannot be written in. Every engine's own find matches it.+ * all-decomposed text, and one occurrence can be neither: joining two text nodes joins two sources, so `café` in+ * one and `café` in the next make one visible word with a spelling the query cannot be written in. Every+ * engine's own find matches it.*/function canonicalSource(needle: string, dotted: boolean): string {let out = "";@@ -610,10 +603,10 @@ function canonicalSource(needle: string, dotted: boolean): string {// A decomposed dotted I folds to `i` plus a combining dot, which has no precomposed form, so// NFC cannot put it back and the plain query would miss a word plainly on screen.if (dotted && cluster === "i") spellings.push(`i${COMBINING_DOT}`);- // Longest first, as `canonicalVariants` is: alternation takes the first that fits, so a short- // spelling that is a prefix of a long one wins and the rest of the cluster is left outside the- // match: `i` before `i` plus its combining dot ended the match inside the grapheme, and the- // boundary check threw the occurrence away rather than reaching for the longer spelling.+ // Longest first, as `canonicalVariants` is: alternation takes the first that fits, so a short spelling that is+ // a prefix of a long one wins and the rest of the cluster is left outside the match: `i` before `i` plus its+ // combining dot ended the match inside the grapheme, and the boundary check threw the occurrence away rather+ // than reaching for the longer spelling.if (spellings.length > 1) spellings.sort((a, b) => b.length - a.length);const spellingSource =spellings.length === 1@@ -634,13 +627,12 @@ function canonicalSource(needle: string, dotted: boolean): string {* index costs 4ms once and a fraction of a microsecond a question. */const segmentsCache = new WeakMap<FindTextIndex, GraphemeSegments>();-/** Every boundary in the index, once seeking for them has cost more than walking the lot would.- *- * In time, not in seeks: a seek is 0.2us into a page of Hangul and 1236us into a page of flags,- * so any count is far too small for one and far too large for the other, and the large end cost- * a first search twenty seconds. The budget is what a scan of this index would itself cost, so- * the total stays within twice the better of the two and no constant is left to be wrong about.- * The rate is the slower of the two measured, 1.3M characters scanned in 82ms. */+/** Every boundary in the index, once seeking for them has cost more than walking the lot would. In time, not+ * in seeks: a seek is 0.2us into a page of Hangul and 1236us into a page of flags, so any count is far too+ * small for one and far too large for the other, and the large end cost a first search twenty seconds. The+ * budget is what a scan of this index would itself cost, so the total stays within twice the better of the two+ * and no constant is left to be wrong about. The rate is the slower of the two measured, 1.3M characters+ * scanned in 82ms. */const boundaryCache = new WeakMap<FindTextIndex, Uint8Array>();const seekCosts = new WeakMap<FindTextIndex,@@ -693,11 +685,10 @@ function graphemeSegmenter() {}/**- * Whether this engine's `containing` agrees with its own iterator about where a segment starts.- *- * WebKit's answers the segment that ENDS at the offset: over `x` and a thumbs up it reads 0, 0, 1- * where Chromium and Firefox read 0, 1, 1, so every interior boundary comes back "not a boundary".- * Where it is wrong the boundaries are tabulated instead, which is the same answer more slowly.+ * Whether this engine's `containing` agrees with its own iterator about where a segment starts. WebKit's answers+ * the segment that ENDS at the offset: over `x` and a thumbs up it reads 0, 0, 1 where Chromium and Firefox read+ * 0, 1, 1, so every interior boundary comes back "not a boundary". Where it is wrong the boundaries are+ * tabulated instead, which is the same answer more slowly.*/let seeksBoundaries: boolean | undefined;function segmenterSeeksBoundaries(platform: {@@ -756,12 +747,11 @@ function joinsAcross(before: string, point: string): boolean {}/**- * True when `[start, end)` begins and ends where a grapheme does.- *- * Asked of the platform, which knows the whole of UAX 29 and is kept current with it; enumerating- * the ranges here kept missing one more way to land inside a cluster every round. Asked one offset- * at a time, so neither the size of the index nor where the match landed in it costs anything:- * tabulating a block's boundaries instead paid 250ms per block, and paid it again on every reindex.+ * True when `[start, end)` begins and ends where a grapheme does. Asked of the platform, which knows the whole+ * of UAX 29 and is kept current with it; enumerating the ranges here kept missing one more way to land inside a+ * cluster every round. Asked one offset at a time, so neither the size of the index nor where the match landed+ * in it costs anything: tabulating a block's boundaries instead paid 250ms per block, and paid it again on every+ * reindex.*/function alignsToGraphemes(index: FindTextIndex,@@ -776,10 +766,10 @@ function alignsToGraphemes() {return false;}- // Almost every match is in text that cannot join at either edge, and asking the segmenter costs- // far more than looking. Nothing below U+0300 joins: the lowest combining mark is U+0300, the- // lowest spacing mark U+0903, Prepend starts at U+0600, Hangul Jamo at U+1100, and everything- // astral arrives as a surrogate. Both sides of each edge, since the query can end with one.+ // Almost every match is in text that cannot join at either edge, and asking the segmenter costs far more than+ // looking. Nothing below U+0300 joins: the lowest combining mark is U+0300, the lowest spacing mark U+0903,+ // Prepend starts at U+0600, Hangul Jamo at U+1100, and everything astral arrives as a surrogate. Both sides of+ // each edge, since the query can end with one.if (!splitsCrlf(text, start) &&!splitsCrlf(text, end) &&diff --git a/studio/frontend/src/features/hf-auth/api.ts b/studio/frontend/src/features/hf-auth/api.tsindex ab4b0495669..5f41bb73e35 100644--- a/studio/frontend/src/features/hf-auth/api.ts+++ b/studio/frontend/src/features/hf-auth/api.ts@@ -2,8 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { authFetch } from "@/features/auth";-// This header helper is API-layer-only and is not part of the feature's-// React-facing public barrel.+// This header helper is API-layer-only and is not part of the feature's React-facing public barrel.// eslint-disable-next-line no-restricted-importsimport { hubTokenHeader } from "@/features/hub/lib/hub-token-header";diff --git a/studio/frontend/src/features/hub/catalog/download-card.tsx b/studio/frontend/src/features/hub/catalog/download-card.tsxindex 4ba98dfac66..17d5ee9bd40 100644--- a/studio/frontend/src/features/hub/catalog/download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/download-card.tsx@@ -62,9 +62,8 @@ export function DownloadCard({<div className="hub-download-card"><div className="group/dl flex items-center">{children}</div>{progress && (- // Match the row's inner text bounds: the trigger and the action- // button both inset 12px, so the bar lines up with the quant label- // on the left and the percentage on the right.+ // Match the row's inner text bounds: the trigger and the action button both inset 12px,+ // so the bar lines up with the quant label on the left and the percentage on the right.<div className="px-3"><DownloadProgressBarprogress={progress}diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsxindex ffde621fad7..42e38e9d952 100644--- a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx@@ -853,13 +853,12 @@ export function GgufDownloadCard({const updateTargetLabel = updateTargetVariant? ggufVariantDisplayLabel(updateTargetVariant): updateTarget;- // Confirm → close the dialog and run the re-download as a MANAGED download, so- // it surfaces in the "Downloading N items" panel with correct manifest-based- // progress and a working Cancel — the same UX as any other download — instead- // of a bespoke modal/toast. The worker re-resolves `main` and pulls only the- // changed blobs, so the cached version stays intact (and runnable) until the- // new revision lands. Completion refreshes the variant list, whose metadata- // carries the "Update available" cue.+ // Confirm → close the dialog and run the re-download as a MANAGED download, so it surfaces in the+ // "Downloading N items" panel with correct manifest-based progress and a working Cancel — the+ // same UX as any other download — instead of a bespoke modal/toast. The worker re-resolves `main`+ // and pulls only the changed blobs, so the cached version stays intact (and runnable) until the+ // new revision lands. Completion refreshes the variant list, whose metadata carries the "Update+ // available" cue.const handleConfirmUpdate = useCallback(() => {if (!updateTarget) return;const variant = updateTarget;diff --git a/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.ts b/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.tsindex 3887225266b..13a88a97ad5 100644--- a/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.ts+++ b/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.ts@@ -87,25 +87,19 @@ export function applyLiveGgufVariantStates(variant.download_size_bytes ?? 0,variant.size_bytes,);- // The row says "N left", so N has to follow the transfer of a running job,- // and the backend's measured remainder covers every other case.- //- // Both terms come from the job and only from the job. snapshot_progress nets- // completed_baseline_bytes -- files a previous quant already fetched, an- // mmproj most often -- out of expected_bytes AND downloaded_bytes alike, so- // the pair is self-consistent while the catalog totals above are not.- // Subtracting the transfer from `expectedBytes`, the larger of the two- // scopes, adds that baseline back: 1 GB reused and 1 GB fetched of a 5 GB- // plan would read 4 GB left rather than 3 GB.- //- // Only while running: `transferredBytes` is progress, not bytes a resume can- // reuse. From huggingface_hub 1.18 the partial is process-unique and unlinked- // in a finally, so an interrupted transfer is refetched whole, which is how- // `existing_blob_bytes` already prices it. Subtracting a dead job's progress- // read "1.0 GB left" for a cancelled 18 GB download with all 18 GB to fetch.- //- // And only off a MEASURED reading: a held one is priced against the previous,- // larger total, so mixing it with the current one read "0 B left".+ // The row says "N left", so N has to follow the transfer of a running job, and the backend's+ // measured remainder covers every other case. Both terms come from the job and only from the+ // job. snapshot_progress nets completed_baseline_bytes -- files a previous quant already+ // fetched, an mmproj most often -- out of expected_bytes AND downloaded_bytes alike, so the+ // pair is self-consistent while the catalog totals above are not. Subtracting the transfer from+ // `expectedBytes`, the larger of the two scopes, adds that baseline back: 1 GB reused and 1 GB+ // fetched of a 5 GB plan would read 4 GB left rather than 3 GB. Only while running:+ // `transferredBytes` is progress, not bytes a resume can reuse. From huggingface_hub 1.18 the+ // partial is process-unique and unlinked in a finally, so an interrupted transfer is refetched+ // whole, which is how `existing_blob_bytes` already prices it. Subtracting a dead job's+ // progress read "1.0 GB left" for a cancelled 18 GB download with all 18 GB to fetch. And only+ // off a MEASURED reading: a held one is priced against the previous, larger total, so mixing it+ // with the current one read "0 B left".const liveRemaining =activeDownloadState(live.state) &&live.measuredTransfer &&diff --git a/studio/frontend/src/features/hub/catalog/hub-detail-view.tsx b/studio/frontend/src/features/hub/catalog/hub-detail-view.tsxindex 3d7ab7b8a67..dd43c105398 100644--- a/studio/frontend/src/features/hub/catalog/hub-detail-view.tsx+++ b/studio/frontend/src/features/hub/catalog/hub-detail-view.tsx@@ -46,10 +46,9 @@ export function HubDetailView({<divref={scrollRef}data-hub-scroll="true"- // Mirror the catalog's gutter strategy so the centered column lines up- // with the top bar: the full overlay reserves an equal both-edges gutter- // to stay symmetric; split pins a narrow pane so it nudges the scrollbar- // in from the edge with a right gutter only.+ // Mirror the catalog's gutter strategy so the centered column lines up with the top bar:+ // the full overlay reserves an equal both-edges gutter to stay symmetric; split pins a+ // narrow pane so it nudges the scrollbar in from the edge with a right gutter only.className={cn("min-h-0 flex-1 overflow-x-hidden overflow-y-auto [overflow-anchor:none] [scrollbar-width:thin]",compactdiff --git a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsxindex 28da3bd5408..b725de9e3df 100644--- a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx+++ b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx@@ -323,10 +323,9 @@ export function LocalOnDeviceCard({};});}, [currentVariantState.variants, remoteVariantState.variants]);- // The same live VRAM Budget the memory bar on this card reads. Without it the- // quant menu ranked against the 0.97 default while the bar beside it used the- // saved fraction, so an over-budget variant could sit above a smaller one that- // actually fits.+ // The same live VRAM Budget the memory bar on this card reads. Without it the quant menu ranked+ // against the 0.97 default while the bar beside it used the saved fraction, so an over-budget+ // variant could sit above a smaller one that actually fits.const budgetFraction = useVramBudgetFraction() ?? undefined;const sortedVariants = useMemo(() =>@@ -398,10 +397,9 @@ export function LocalOnDeviceCard({!runPending &&!updateJobActive &&updateAvailable;- // Update runs as a MANAGED download (same path as a normal download) so it- // shows in the Downloads panel with manifest-based progress and a working- // Cancel. The worker re-resolves `main` and pulls changed blobs while the old- // cached copy stays runnable until the new revision verifies.+ // Update runs as a MANAGED download (same path as a normal download) so it shows in the Downloads+ // panel with manifest-based progress and a working Cancel. The worker re-resolves `main` and+ // pulls changed blobs while the old cached copy stays runnable until the new revision verifies.const handleConfirmUpdate = () => {if (!repoId || !updateTargetVariant) return;setUpdateOpen(false);diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsxindex 2219e5daf7e..bef264a803c 100644--- a/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx+++ b/studio/frontend/src/features/hub/catalog/models-catalog-lists.tsx@@ -482,17 +482,15 @@ export function DownloadedList({>{pinnedItems.map((item) => {const rowKey = `${item.variant}-${item.row.id}`;- // movePinned can only move a key that is in the pinned list, and- // pins also exist as `repoId::quant` (written by the GGUF quant- // menus). Deriving the key without checking membership would let- // a row advertise a drag that every movePinned call silently- // found nothing to do. pinnedCount selects this slice on the same- // predicate today, so the check holds the two in lockstep rather- // than trusting them to stay identical. Datasets are excluded- // outright: pin keys carry no repo type, so a dataset whose- // repoId also names a pinned model reaches this grid, and the row- // menu offers datasets no pin action, so a drag here must not- // reorder the user's model pins from the dataset list.+ // movePinned can only move a key that is in the pinned list, and pins also exist as+ // `repoId::quant` (written by the GGUF quant menus). Deriving the key without+ // checking membership would let a row advertise a drag that every movePinned call+ // silently found nothing to do. pinnedCount selects this slice on the same predicate+ // today, so the check holds the two in lockstep rather than trusting them to stay+ // identical. Datasets are excluded outright: pin keys carry no repo type, so a+ // dataset whose repoId also names a pinned model reaches this grid, and the row menu+ // offers datasets no pin action, so a drag here must not reorder the user's model+ // pins from the dataset list.const itemPinKey =!isDataset &&item.row.repoId &&@@ -522,9 +520,8 @@ export function DownloadedList({onDragEnd={() => {dragPinKeyRef.current = null;setDragRowKey(null);- // Escape, or a release outside any cell, reaches dragend- // without a drop. A drop already committed and cleared the- // session, so this call is then a no-op.+ // Escape, or a release outside any cell, reaches dragend without a drop. A drop+ // already committed and cleared the session, so this call is then a no-op.endPinnedDrag(false);}}onDragOver={(event) => {diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsxindex 7ae5b1c319d..715cc62344b 100644--- a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx+++ b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx@@ -59,11 +59,10 @@ const COARSE_POINTER =typeof window.matchMedia === "function" &&window.matchMedia("(pointer: coarse)").matches;-// Defer the cached-size chip (Radix Tooltip + two store subscriptions) until a-// row is first hovered/focused so scrolling the virtualized list doesn't pay-// that cost per row; an identical StatChip placeholder makes the swap invisible.-// Coarse pointers have no hover, so they arm immediately. Default true so any-// out-of-row usage stays functional.+// Defer the cached-size chip (Radix Tooltip + two store subscriptions) until a row is first+// hovered/focused so scrolling the virtualized list doesn't pay that cost per row; an identical+// StatChip placeholder makes the swap invisible. Coarse pointers have no hover, so they arm+// immediately. Default true so any out-of-row usage stays functional.const CatalogRowInteractiveContext = createContext(true);function CachedSizeChip(props: {@@ -951,9 +950,8 @@ export function VirtualRows<T>({left: 0,width: "100%",transform: `translateY(${virtualRow.start - scrollMargin}px)`,- // Fixed height matching estimateSize (no measureElement ref):- // dynamic per-row measurement churns virtualizer state and causes- // visible jumps as new rows arrive.+ // Fixed height matching estimateSize (no measureElement ref): dynamic per-row+ // measurement churns virtualizer state and causes visible jumps as new rows arrive.height: `${rowHeight}px`,contain: "layout",}}diff --git a/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsx b/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsxindex a4f09b7bac6..a2ebb39d7f4 100644--- a/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsx+++ b/studio/frontend/src/features/hub/catalog/on-device-folders-dialog.tsx@@ -153,10 +153,9 @@ export function OnDeviceFoldersDialog({onInventoryChange?.();}, [onInventoryChange]);- // Relocating the cache changes which repos are on disk, but- // updateHuggingFaceCacheSettings already bumps the inventory version, which- // re-fetches every source. Refreshing here too would scan twice, since the- // two rounds carry different version keys and cannot be deduplicated.+ // Relocating the cache changes which repos are on disk, but updateHuggingFaceCacheSettings+ // already bumps the inventory version, which re-fetches every source. Refreshing here too would+ // scan twice, since the two rounds carry different version keys and cannot be deduplicated.const saveDownloadLocation = useCallback(async (nextPath: string | null) => {setDownloadSaving(true);try {diff --git a/studio/frontend/src/features/hub/catalog/use-download-card-state.ts b/studio/frontend/src/features/hub/catalog/use-download-card-state.tsindex 5be9dc29491..b10998da8b3 100644--- a/studio/frontend/src/features/hub/catalog/use-download-card-state.ts+++ b/studio/frontend/src/features/hub/catalog/use-download-card-state.ts@@ -42,9 +42,8 @@ export function downloadStopMode(cancelTransport?: string | null,partialsResumable = false,): DownloadStopMode {- // The cancel marker wins where there is one: a Xet run that fell back to- // HTTP still cancels into a restart-only partial, so Pause would promise a- // resume the marker does not allow.+ // The cancel marker wins where there is one: a Xet run that fell back to HTTP still cancels into+ // a restart-only partial, so Pause would promise a resume the marker does not allow.const transport = cancelTransport ?? activeTransport ?? partialTransport;// Capability, not a row verdict: the partial being written right now is this// machine's own, so the installed writer decides whether stopping keeps it.diff --git a/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts b/studio/frontend/src/features/hub/download-manager/progress-reconcile.tsindex 8ff02916d5d..b2e97236779 100644--- a/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts+++ b/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts@@ -1,10 +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-// One backend progress reading reconciled against the job's current figures.-// Split out of poll-loop so it can be exercised on its own: poll-loop reaches-// the store, the toaster and the API client, and this is the part that decides-// what a card shows and when a download counts as finished.+// One backend progress reading reconciled against the job's current figures. Split out of poll-loop+// so it can be exercised on its own: poll-loop reaches the store, the toaster and the API client,+// and this is the part that decides what a card shows and when a download counts as finished.import { DOWNLOAD_KIND } from "./constants";import { MAX_PROGRESS_FRACTION } from "./download-manager-config";@@ -20,13 +19,11 @@ export function hasObservedExpectedBytes(job: ManagedDownload): boolean {);}-// A number off the wire (a byte count or a fraction), or 0 when it is not a usable-// one. The payload is-// cast from raw JSON with no runtime validation (apiGetProgress -> ProgressLike),-// and a NaN or an Infinity survives every comparison below to reach the store as-// a width of "NaN%" on the progress bar. 0 reads as "not measured", which is the-// conservative answer here: it holds the card's last figure rather than-// publishing a garbage one, and never manufactures a completion.+// A number off the wire (a byte count or a fraction), or 0 when it is not a usable one. The payload+// is cast from raw JSON with no runtime validation (apiGetProgress -> ProgressLike), and a NaN or+// an Infinity survives every comparison below to reach the store as a width of "NaN%" on the+// progress bar. 0 reads as "not measured", which is the conservative answer here: it holds the+// card's last figure rather than publishing a garbage one, and never manufactures a completion.function finiteReading(value: number | null | undefined): number {return typeof value === "number" && Number.isFinite(value) ? value : 0;}@@ -72,29 +69,24 @@ export function resolveProgressUpdate(: Math.max(reported > 0 ? reported : job.expectedBytes, job.expectedBytes);const previousDownloadedBytes = job.downloadedBytes;const reportedCompleted = finiteReading(progressResp.completed_bytes);- // Hold the last reading through a poll that found nothing, rather than- // publishing the "I could not measure this" answer as a measurement. The- // backend recomputes both counters from the shared per-repo blobs/ dir every- // poll, and when it cannot resolve a variant's expected files it returns an- // all-zero reading against the caller's catalog-hinted total; the failure- // behind that is negatively cached, so every poll for the whole TTL says the- // same thing and a finished card reads "0 B of 33 GB" until the app restarts.- //- // Deliberately NOT a high-water mark, which is what the fraction below uses.- // Bytes have legitimate reasons to fall inside one generation and the- // fraction does not: an XET run that falls back to HTTP re-claims with the- // same generation and a freshly computed completed_baseline_bytes, and- // resuming in XET mode purges the partial outright. A floor would pin the- // card near full for the whole retry and starve the rolling-window rate of- // the movement it needs to publish a speed or an ETA. Only a zero is ignored,- // so every real change -- up or down -- still lands on the next poll.+ // Hold the last reading through a poll that found nothing, rather than publishing the "I could+ // not measure this" answer as a measurement. The backend recomputes both counters from the shared+ // per-repo blobs/ dir every poll, and when it cannot resolve a variant's expected files it+ // returns an all-zero reading against the caller's catalog-hinted total; the failure behind that+ // is negatively cached, so every poll for the whole TTL says the same thing and a finished card+ // reads "0 B of 33 GB" until the app restarts. Deliberately NOT a high-water mark, which is what+ // the fraction below uses. Bytes have legitimate reasons to fall inside one generation and the+ // fraction does not: an XET run that falls back to HTTP re-claims with the same generation and a+ // freshly computed completed_baseline_bytes, and resuming in XET mode purges the partial+ // outright. A floor would pin the card near full for the whole retry and starve the+ // rolling-window rate of the movement it needs to publish a speed or an ETA. Only a zero is+ // ignored, so every real change -- up or down -- still lands on the next poll.const reportedDownloaded = finiteReading(progressResp.downloaded_bytes);- // Whether this poll MEASURED the transfer counter or merely held the last- // one. A held figure is fine to draw a bar with, but it is priced against the- // PREVIOUS total, so a caller subtracting it from the current expectedBytes- // gets a remainder for a plan that no longer exists. The XET fallback reclaim- // is exactly that pairing: the retry's first reading is a legitimate 0 against- // a shrunken total, and the 3 GB held behind it wipe out a 0.5 GB remainder.+ // Whether this poll MEASURED the transfer counter or merely held the last one. A held figure is+ // fine to draw a bar with, but it is priced against the PREVIOUS total, so a caller subtracting+ // it from the current expectedBytes gets a remainder for a plan that no longer exists. The XET+ // fallback reclaim is exactly that pairing: the retry's first reading is a legitimate 0 against a+ // shrunken total, and the 3 GB held behind it wipe out a 0.5 GB remainder.const measuredTransfer = resetMonotonic || reportedDownloaded > 0;const downloadedBytes = measuredTransfer? Math.max(0, reportedDownloaded)@@ -106,15 +98,14 @@ export function resolveProgressUpdate(: measuredCompleted? reportedCompleted: Math.max(job.completedBytes, 0);- // ...and the completion flag is only honoured on a poll that measured the- // counter it is a statement about. Holding the bytes over made a new pairing- // reachable that the plain reading never was: LAST poll's completed_bytes- // beside THIS poll's complete_on_disk, a completion neither reading showed on- // its own. The backend does hold the invariant that would rule that out- // (complete_on_disk is only set once completed_bytes clears the total), but a- // false "complete" retires the card and drops the download, and that is not an- // outcome to leave resting on a cross-tier promise no code here checks. Both- // halves of hasObservedExpectedBytes now provably come from the same reading.+ // ...and the completion flag is only honoured on a poll that measured the counter it is a+ // statement about. Holding the bytes over made a new pairing reachable that the plain reading+ // never was: LAST poll's completed_bytes beside THIS poll's complete_on_disk, a completion+ // neither reading showed on its own. The backend does hold the invariant that would rule that out+ // (complete_on_disk is only set once completed_bytes clears the total), but a false "complete"+ // retires the card and drops the download, and that is not an outcome to leave resting on a+ // cross-tier promise no code here checks. Both halves of hasObservedExpectedBytes now provably+ // come from the same reading.const completeOnDisk = progressResp.complete_on_disk === true && measuredCompleted;const madeProgress =resetMonotonic ||@@ -134,14 +125,13 @@ export function resolveProgressUpdate(? downloadedBytes / expected: 0;const cappedFraction = Math.min(rawFraction, MAX_PROGRESS_FRACTION);- // Keep the GGUF variant bar monotonic: backend progress is recomputed from the- // shared per-repo blobs/ dir, so a sibling quant, generation bump, or- // no-metadata poll can dip one reading. Resets via startJob's seed fraction.- //- // NOT across a generation change, though. `resetMonotonic` is the caller saying another- // client restarted this job, and it already clears the byte counters -- carrying the old- // generation's high-water mark over pinned a retry that starts at 0 B to the previous run's- // 99% for its entire life, which is the stale card this whole path exists to remove.+ // Keep the GGUF variant bar monotonic: backend progress is recomputed from the shared per-repo+ // blobs/ dir, so a sibling quant, generation bump, or no-metadata poll can dip one reading.+ // Resets via startJob's seed fraction. NOT across a generation change, though. `resetMonotonic`+ // is the caller saying another client restarted this job, and it already clears the byte counters+ // -- carrying the old generation's high-water mark over pinned a retry that starts at 0 B to the+ // previous run's 99% for its entire life, which is the stale card this whole path exists to+ // remove.const fraction =isGgufVariantJob && !resetMonotonic? Math.max(cappedFraction, job.fraction)diff --git a/studio/frontend/src/features/hub/download-manager/start-toast.ts b/studio/frontend/src/features/hub/download-manager/start-toast.tsindex dc9d4fbe0d0..6a9fcf103d9 100644--- a/studio/frontend/src/features/hub/download-manager/start-toast.ts+++ b/studio/frontend/src/features/hub/download-manager/start-toast.ts@@ -1,12 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// The one toast announcing a download start, and the one place it is dismissed.-//-// Chat used to raise its own alongside the Xet notice, so one download produced two-// stacked toasts; callers now hand their message over instead. The 8s duration says-// nothing about the transfer, so the id is derived from the job key and finalize()-// dismisses it (nothing can be stored: teardownRuntime runs first).+// The one toast announcing a download start, and the one place it is dismissed. Chat used to raise+// its own alongside the Xet notice, so one download produced two stacked toasts; callers now hand+// their message over instead. The 8s duration says nothing about the transfer, so the id is derived+// from the job key and finalize() dismisses it (nothing can be stored: teardownRuntime runs first).import { toast } from "@/lib/toast";diff --git a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts b/studio/frontend/src/features/hub/download-manager/transport-conflict.tsindex 1ece48bb3be..d855ca9510b 100644--- a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts+++ b/studio/frontend/src/features/hub/download-manager/transport-conflict.ts@@ -93,19 +93,17 @@ async function activeSiblingTransport(return null;}-// Outcome of a start request so callers can tell whether a transfer for this-// exact request is actually live before telling the user it began. "started"-// means a running/cancelling job exists for this key (a fresh start or an-// already-active one). "conflict" means a transport partial conflict was-// recorded and must be resolved from the Hub download card; "busy" means the-// repo is occupied by a sibling variant/snapshot/pending start that is not this-// transfer; "error" means the start failed or was refused.+// Outcome of a start request so callers can tell whether a transfer for this exact request is+// actually live before telling the user it began. "started" means a running/cancelling job exists+// for this key (a fresh start or an already-active one). "conflict" means a transport partial+// conflict was recorded and must be resolved from the Hub download card; "busy" means the repo is+// occupied by a sibling variant/snapshot/pending start that is not this transfer; "error" means the+// start failed or was refused.export type DownloadStartOutcome = "started" | "conflict" | "busy" | "error";-// A start can no-op without throwing: the backend can refuse it (startJob-// finalizes "error"), startJob's peer guard can skip it, or-// hasActiveOrPendingStart can trip on a snapshot/peer/pending that is not this-// request. Derive the outcome from the actual job state of this exact key so+// A start can no-op without throwing: the backend can refuse it (startJob finalizes "error"),+// startJob's peer guard can skip it, or hasActiveOrPendingStart can trip on a snapshot/peer/pending+// that is not this request. Derive the outcome from the actual job state of this exact key so// callers never claim a download began when it did not.function isJobActiveFor(req: DownloadRequest): boolean {const job = getState().jobs[jobKeyOf(req.kind, req.repoId, req.variant)];@@ -237,11 +235,10 @@ export async function requestStart("Transport status check failed; starting without partial-conflict preflight.",err,);- // Fail safe: Xet purges any partial unconditionally, so when the partial- // can't be verified we downgrade this one start to HTTP (resumes an HTTP- // partial, harmless for a fresh download); the Xet preference is kept for- // next time. Only downgrade once we confirmed no sibling variant is- // downloading, since a live sibling may be mid-transfer on Xet.+ // Fail safe: Xet purges any partial unconditionally, so when the partial can't be verified we+ // downgrade this one start to HTTP (resumes an HTTP partial, harmless for a fresh download);+ // the Xet preference is kept for next time. Only downgrade once we confirmed no sibling+ // variant is downloading, since a live sibling may be mid-transfer on Xet.if (mode === TRANSPORT.XET && siblingProbed && !siblingTransport) {toast.warning("Couldn't verify existing partial download", {description:diff --git a/studio/frontend/src/features/hub/download-manager/xet-progress-notice.ts b/studio/frontend/src/features/hub/download-manager/xet-progress-notice.tsindex 38df6d44871..eb17ad2ccc5 100644--- a/studio/frontend/src/features/hub/download-manager/xet-progress-notice.ts+++ b/studio/frontend/src/features/hub/download-manager/xet-progress-notice.ts@@ -28,9 +28,8 @@ export const XET_NOTICE_TITLE = "Download is running";export const XET_NOTICE_DESCRIPTION ="Xet sends the file in small pieces, so the bar can sit at 0% and then jump to done. Nothing is stuck.";export const XET_NOTICE_DESCRIPTION_CLASS = "!text-muted-foreground";-// A restart is also a start disclosure. Keeping its copy here lets poll-loop-// combine it with the Xet explanation instead of creating an unrelated toast-// that can outlive its download.+// A restart is also a start disclosure. Keeping its copy here lets poll-loop combine it with the+// Xet explanation instead of creating an unrelated toast that can outlive its download.export const RESTART_NOTICE_TITLE = "Restarting this download";export const RESTART_NOTICE_DESCRIPTION ="The earlier partial can't be resumed, so this download is starting over.";diff --git a/studio/frontend/src/features/hub/hooks/use-discover-search.ts b/studio/frontend/src/features/hub/hooks/use-discover-search.tsindex ffd2662435c..7ebbab4860b 100644--- a/studio/frontend/src/features/hub/hooks/use-discover-search.ts+++ b/studio/frontend/src/features/hub/hooks/use-discover-search.ts@@ -115,11 +115,10 @@ export function useDiscoverSearch({// stale window can no longer announce "Back online" without a working request.const online = phase === "available";- // Gated on the live backoff only, never on "probing". Gating on availability- // is what discarded the error and made every cause render the same, and that- // is now safe because the disabled path preserves it; but leaving it ungated- // let a user typing through an outage issue a request per debounce tick, each- // one re-arming the window it was meant to be waiting out.+ // Gated on the live backoff only, never on "probing". Gating on availability is what discarded+ // the error and made every cause render the same, and that is now safe because the disabled path+ // preserves it; but leaving it ungated let a user typing through an outage issue a request per+ // debounce tick, each one re-arming the window it was meant to be waiting out.const modelSearch = useHubModelSearch(debouncedQuery, {accessToken,sortBy,diff --git a/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts b/studio/frontend/src/features/hub/hooks/use-hub-model-search.tsindex 3085b24052c..ec7b2a53594 100644--- a/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts+++ b/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts@@ -786,12 +786,11 @@ export function useHubModelSearch();const search = useHubPaginatedSearch(createIter, mapModel, { enabled });- // Secondary sort only with no user query (the merged iterator already floats unsloth results)- // and outside channel scoping.- //- // STABLE-APPEND CONTRACT: when a later page lands, keep the sorted prefix verbatim and append- // only the new tail, else a late unsloth/* repo jumps earlier and bumps the viewport. Sort only- // when the listing resets (length shrinks or zeros), where re-ordering is safe.+ // Secondary sort only with no user query (the merged iterator already floats unsloth results) and+ // outside channel scoping. STABLE-APPEND CONTRACT: when a later page lands, keep the sorted+ // prefix verbatim and append only the new tail, else a late unsloth/* repo jumps earlier and+ // bumps the viewport. Sort only when the listing resets (length shrinks or zeros), where+ // re-ordering is safe.const [stableCache, setStableCache] = useState<{source: HfModelResult[] | null;length: number;diff --git a/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.ts b/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.tsindex 4ea42357b00..6d623b4d98e 100644--- a/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.ts+++ b/studio/frontend/src/features/hub/hooks/use-hub-paginated-search.ts@@ -39,9 +39,8 @@ type BusyKind = "initial" | "more";*/const MIN_FETCH_INTERVAL_MS = 350;-// Preserved results older than this refetch on re-enable so the feed can't lag-// the Hub. Reset by every successful pull (idle time only). Mirrors the-// modelInfo TTL in hf-cache.ts.+// Preserved results older than this refetch on re-enable so the feed can't lag the Hub. Reset by+// every successful pull (idle time only). Mirrors the modelInfo TTL in hf-cache.ts.const STALE_AFTER_MS = 5 * 60 * 1000;export async function pullBatch<T>(@@ -57,10 +56,9 @@ export async function pullBatch<T>(return { items, done: true, scanned };}scanned += 1;- // mapItem already returns null to mean "skip", so a throw is the same- // answer arriving the hard way. Letting it out marked the generator dead- // over an item next() had already handed us, and every restart then hit- // the same row at the same position.+ // mapItem already returns null to mean "skip", so a throw is the same answer arriving the hard+ // way. Letting it out marked the generator dead over an item next() had already handed us, and+ // every restart then hit the same row at the same position.let mapped: T | null = null;try {mapped = mapItem(result.value);@@ -119,9 +117,8 @@ export function useHubPaginatedSearch<T>(const iterRef = useRef<AsyncGenerator<unknown> | null>(null);const versionRef = useRef(0);- // Aborts the live iterator's in-flight fetches; the prior one is aborted and- // replaced when a new query supersedes the feed so the abandoned listing stops- // fetching and priming the cache.+ // Aborts the live iterator's in-flight fetches; the prior one is aborted and replaced when a new+ // query supersedes the feed so the abandoned listing stops fetching and priming the cache.const abortRef = useRef<AbortController | null>(null);// Identity of the last-fetched query. A fetch (re)starts only when one of these@@ -131,9 +128,8 @@ export function useHubPaginatedSearch<T>(const loadedNonceRef = useRef(-1);const loadedAtRef = useRef(0);- // Synchronous in-flight guard. Set before any setState so back-to-back- // fetchMore() calls can't both pass the gate while React batches the commit.- // Cleared in finally() of the matching pull.+ // Synchronous in-flight guard. Set before any setState so back-to-back fetchMore() calls can't+ // both pass the gate while React batches the commit. Cleared in finally() of the matching pull.const busyRef = useRef(false);const busyKindRef = useRef<BusyKind | null>(null);const busyTokenRef = useRef(0);diff --git a/studio/frontend/src/features/hub/lib/abort-signals.ts b/studio/frontend/src/features/hub/lib/abort-signals.tsindex e320f70ff29..2938467417c 100644--- a/studio/frontend/src/features/hub/lib/abort-signals.ts+++ b/studio/frontend/src/features/hub/lib/abort-signals.ts@@ -1,10 +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-// WebView-compatibility shims. AbortSignal.timeout (WebKitGTK < 2.38) and-// AbortSignal.any (WebKitGTK < 2.44) are missing on older engines Tauri embeds-// and throw synchronously if called. These ponyfills delegate to the native-// impl when present, else fall back to an AbortController.+// WebView-compatibility shims. AbortSignal.timeout (WebKitGTK < 2.38) and AbortSignal.any+// (WebKitGTK < 2.44) are missing on older engines Tauri embeds and throw synchronously if called.+// These ponyfills delegate to the native impl when present, else fall back to an AbortController.export interface PollSignal {signal: AbortSignal;diff --git a/studio/frontend/src/features/hub/lib/dataset-size.ts b/studio/frontend/src/features/hub/lib/dataset-size.tsindex 76ac12d2d67..dbfe3206912 100644--- a/studio/frontend/src/features/hub/lib/dataset-size.ts+++ b/studio/frontend/src/features/hub/lib/dataset-size.ts@@ -23,10 +23,9 @@ interface DatasetSizeApiResponse {};}-// Transient (429/5xx/network) misses cache briefly so a rate-limited burst-// doesn't pin the size to "unknown" until reload. "longlived" covers stable-ish-// answers like datasets-server 404 ("not processed yet"); "permanent" is a-// genuinely missing repo (HF models API 404).+// Transient (429/5xx/network) misses cache briefly so a rate-limited burst doesn't pin the size to+// "unknown" until reload. "longlived" covers stable-ish answers like datasets-server 404 ("not+// processed yet"); "permanent" is a genuinely missing repo (HF models API 404).const TRANSIENT_MISS_TTL_MS = 60_000;const LONGLIVED_MISS_TTL_MS = 24 * 60 * 60 * 1000;const FETCH_TIMEOUT_MS = 10_000;diff --git a/studio/frontend/src/features/hub/lib/hidden-models.ts b/studio/frontend/src/features/hub/lib/hidden-models.tsindex f13c38cb3f1..0ccff9efc7a 100644--- a/studio/frontend/src/features/hub/lib/hidden-models.ts+++ b/studio/frontend/src/features/hub/lib/hidden-models.ts@@ -4,16 +4,14 @@import { authFetch } from "@/features/auth";import { getInventoryVersion } from "../stores/inventory-events";-// Infra models hidden from browse/preview lists (Hub Discover, the chat model-// selector, and local on-device rows). Mirrors the backend-// `utils.hidden_models`: the RAG embedding model, STT dictation models, and the-// llama.cpp validation probe are not usable chat models. Server-confirmed cache-// rows are trusted because the backend applies variant-aware filtering.-// Optimistic cache rows still use these needles until the server confirms them.-// The dynamic matchers fetched from `/api/hub/hidden-models` add the user's-// configured embedder as exact repo ids and exact resolved paths, never-// substring needles. Per-repo views are not filtered, so reinstall flows still-// show downloaded files.+// Infra models hidden from browse/preview lists (Hub Discover, the chat model selector, and local+// on-device rows). Mirrors the backend `utils.hidden_models`: the RAG embedding model, STT+// dictation models, and the llama.cpp validation probe are not usable chat models. Server-confirmed+// cache rows are trusted because the backend applies variant-aware filtering. Optimistic cache rows+// still use these needles until the server confirms them. The dynamic matchers fetched from+// `/api/hub/hidden-models` add the user's configured embedder as exact repo ids and exact resolved+// paths, never substring needles. Per-repo views are not filtered, so reinstall flows still show+// downloaded files.const HIDDEN_NEEDLES = ["bge-small-en-v1.5", // RAG embedder: unsloth/bge-small-en-v1.5[-GGUF]"ggml-org/models", // llama.cpp validation probe repo@@ -21,9 +19,8 @@ const HIDDEN_NEEDLES = [];const HIDDEN_STT_REPOS = new Set([// Transformers safetensors repos and their whisper.cpp GGUF companions- // (unslothai/whisper-*-GGUF): STT-only, never chat models. The Qwen3-ASR- // GGUFs are here for the same reason: llama.cpp will load one as a chat- // model, where it only answers with transcripts.+ // (unslothai/whisper-*-GGUF): STT-only, never chat models. The Qwen3-ASR GGUFs are here for the+ // same reason: llama.cpp will load one as a chat model, where it only answers with transcripts."unsloth/whisper-tiny","unsloth/whisper-base","unsloth/whisper-small",diff --git a/studio/frontend/src/features/hub/lib/network.ts b/studio/frontend/src/features/hub/lib/network.tsindex 10a03f8bdd2..9c3cec6244e 100644--- a/studio/frontend/src/features/hub/lib/network.ts+++ b/studio/frontend/src/features/hub/lib/network.ts@@ -117,10 +117,9 @@ export function isRemoteNetworkOffline(}export function isHuggingFaceOffline(): boolean {- // navigator.onLine is advisory only (false-reports offline on WSL2 / some- // WebKitGTK/Tauri webviews). The authoritative signal is the empirical- // remote-offline TTL, set when a real fetch fails and cleared on next success;- // navigator's online/offline events still drive re-evaluation.+ // navigator.onLine is advisory only (false-reports offline on WSL2 / some WebKitGTK/Tauri+ // webviews). The authoritative signal is the empirical remote-offline TTL, set when a real fetch+ // fails and cleared on next success; navigator's online/offline events still drive re-evaluation.return isRemoteNetworkOffline(HUGGING_FACE_ORIGIN);}@@ -175,10 +174,9 @@ export function markRemoteNetworkOffline(const ttl = typeof originOrTtl === "number" ? originOrTtl : ttlMs;const nextUntil = Date.now() + ttl;const previousUntil = remoteOfflineUntilByOrigin.get(origin) ?? 0;- // The cause has to describe the window in force: recording a newer cause while- // keeping a longer window left the panel naming a spent failure while a- // different, still-live one held it unavailable. A first cause is always- // taken, so nothing the user sees goes unexplained.+ // The cause has to describe the window in force: recording a newer cause while keeping a longer+ // window left the panel naming a spent failure while a different, still-live one held it+ // unavailable. A first cause is always taken, so nothing the user sees goes unexplained.const takesWindow = nextUntil > previousUntil;const records =failure !== undefined && (takesWindow || !lastFailureByOrigin.has(origin));diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 04bed68b58a..5d5c73353f6 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -5,10 +5,9 @@ import { withBackgroundLoadNotice } from "@/lib/model-lifecycle-events";import { authFetch } from "@/features/auth";import { readFastApiError } from "@/lib/format-fastapi-error";-// One Advanced control's resolved value and provenance, for the Advanced-panel badges. `value` is-// the engaged value (null when off), `requested` is what the caller asked for (null = left to-// the backend), `source` is "auto" or "explicit", `status` says whether the ask survived, and-// `reason` is the tooltip why.+// One Advanced control's resolved value and provenance, for the Advanced-panel badges. `value` is the engaged+// value (null when off), `requested` is what the caller asked for (null = left to the backend), `source` is "auto"+// or "explicit", `status` says whether the ask survived, and `reason` is the tooltip why.export interface DiffusionResolvedControl {value: string | boolean | null;// Absent on backends predating the requested/actual split.@@ -31,9 +30,9 @@ export interface DiffusionStatus {// Selected GGUF quant. Newer backends report this separately from the compute dtype.gguf_variant?: string | null;cpu_offload: boolean;- // The ENGAGED runtime build. The backend has always sent these; declaring them is what lets the UI- // report what actually ran instead of echoing the load request back. Transformer quant- // engaged on the dense fast path ("int8" / "fp8" / ...), null = the GGUF ran as-is.+ // The ENGAGED runtime build. The backend has always sent these; declaring them is what lets the UI report what+ // actually ran instead of echoing the load request back. Transformer quant engaged on the dense fast path+ // ("int8" / "fp8" / ...), null = the GGUF ran as-is.transformer_quant?: string | null;// Text-encoder quant engaged ("fp8" | "fp8_dynamic" | "int8" | "nvfp4"), null = dense bf16.text_encoder_quant?: string | null;@@ -108,9 +107,9 @@ export interface DiffusionLoadRequest {// checkpoint, so several cards resolve to the one with the most free VRAM.gpu_ids?: number[];transformer_cache?: "off" | "fbcache";- // LoRA adapters to BAKE into a torchao int8/fp8 build: they can only attach to the dense- // transformer BEFORE quantisation and compile, so a quantized load that omits them rejects- // every generation. Ignored by bf16 / bnb-4bit, which apply at generate time.+ // LoRA adapters to BAKE into a torchao int8/fp8 build: they can only attach to the dense transformer BEFORE+ // quantisation and compile, so a quantized load that omits them rejects every generation. Ignored by bf16 /+ // bnb-4bit, which apply at generate time.loras?: LoraSpecInput[];}@@ -270,9 +269,8 @@ export async function getGenerateProgress(): Promise<DiffusionGenerateProgress>}export async function loadDiffusionModel(body: DiffusionLoadRequest): Promise<DiffusionStatus> {- // Announced so the loaded models indicator shows the load for as long as the toast does, rather- // than up to one 5s poll later. This POST only starts the load, so the notice settles from- // load-progress, not from the response.+ // Announced so the loaded models indicator shows the load for as long as the toast does, rather than up to one 5s+ // poll later. This POST only starts the load, so the notice settles from load-progress, not from the response.return withBackgroundLoadNotice("image",body.model_path,@@ -303,10 +301,10 @@ export interface DiffusionDownloadPlan {required_bytes?: number;/** Selected checkpoint's contribution to required_bytes. */checkpoint_bytes?: number;- /** Why this pick cannot load as selected (a FLUX.2 GGUF paired with a different-size base), or- * null when nothing is known to be wrong. The backend reads metadata only, so it stays silent- * rather than guessing; when it does speak, refuse the pick here, since the alternative is- * the loader saying the same thing after a ~19 GB download. */+ /** Why this pick cannot load as selected (a FLUX.2 GGUF paired with a different-size base), or null when nothing+ * is known to be wrong. The backend reads metadata only, so it stays silent rather than guessing; when it does+ * speak, refuse the pick here, since the alternative is the loader saying the same thing after a ~19 GB+ * download. */incompatible_reason?: string | null;}@@ -357,9 +355,9 @@ export async function generateDiffusionImage(}if (!response.ok && RESPONSE_LOST_STATUSES.has(response.status)) {const detail = await readFastApiError(response);- // A proxy answers with HTML (or nothing); the app answers with JSON. Only the former means the- // request may still be running: settling an application error would poll for a generation- // that never started and hide the reason the backend gave.+ // A proxy answers with HTML (or nothing); the app answers with JSON. Only the former means the request may still+ // be running: settling an application error would poll for a generation that never started and hide the reason+ // the backend gave.if (response.status === 503 &&(response.headers.get("content-type") || "").toLowerCase().includes("application/json")@@ -378,9 +376,9 @@ export async function cancelDiffusionGeneration(signal?: AbortSignal,): Promise<{ cancelled: boolean }> {return parseJson(- // No network retry, and abortable. The endpoint always targets whichever generation is active NOW,- // so a retry or a 401 refresh-and-replay firing after the stopped run settled can land on a- // run the user started meanwhile. The signal lets the caller drop a pending one.+ // No network retry, and abortable. The endpoint always targets whichever generation is active NOW, so a retry or+ // a 401 refresh-and-replay firing after the stopped run settled can land on a run the user started meanwhile.+ // The signal lets the caller drop a pending one.await authFetch("/api/inference/images/generate/cancel",{ method: "POST", signal },@@ -510,9 +508,8 @@ export interface DiffusionTrainingStartRequest {// stop-and-save always writes one, so Resume stays available either way.save_steps?: number;save_total_limit?: number;- // Continue a previous run: its output_dir, or one explicit checkpoint-<N> directory inside it.- // train_steps then means the TARGET TOTAL, so a checkpoint at 11 with train_steps 500 runs- // 12..500.+ // Continue a previous run: its output_dir, or one explicit checkpoint-<N> directory inside it. train_steps then+ // means the TARGET TOTAL, so a checkpoint at 11 with train_steps 500 runs 12..500.resume_from_checkpoint?: string | null;// The run being continued. Recorded in the history for lineage only.resumed_from_job_id?: string | null;@@ -750,9 +747,9 @@ export async function uploadDiffusionDataset();}-// One item in a training dataset folder, with its resolved caption. `caption_source` records where-// it came from, so the labeling grid can highlight uncaptioned items. `kind` is absent on-// older backends, which listed images only; treat a missing value as "image".+// One item in a training dataset folder, with its resolved caption. `caption_source` records where it came from,+// so the labeling grid can highlight uncaptioned items. `kind` is absent on older backends, which listed images+// only; treat a missing value as "image".export interface DiffusionDatasetImageRecord {filename: string;caption: string | null;diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 60cbe0b5703..565e1561cbd 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -203,7 +203,6 @@ const ASPECT_RATIOS: Record<string, [number, number]> = {"21:9": [21, 9],};const ASPECT_OPTIONS = ["custom", ...Object.keys(ASPECT_RATIOS)];-// Names read faster than bare ratios; Flip covers the portrait side of each.const ASPECT_LABELS: Record<string, string> = {"1:1": "Square","3:2": "Photo",@@ -228,7 +227,6 @@ const DIM_OPTIONS = [1408, 1536, 1664, 1792, 1920, 2048,];-/** Compact size control: type a value, or pick one of the usual sizes from the menu. */function DimensionSelect({icon,label,@@ -313,8 +311,8 @@ function matchAspect(width: number, height: number): { key: string; portrait: bo}// Module cache of the backend-persisted gallery, so a tab switch re-renders instantly; object-// URLs are revoked only on delete. The 192 MB blob budget never evicts a visible image.-// 192 MB is ~100-200 images, far more than a viewport holds.+// URLs are revoked only on delete. The 192 MB blob budget (~100-200 images) never evicts a+// visible image.const IMAGE_BLOB_BUDGET_BYTES = 192 * 1024 * 1024;const galleryCache: {@@ -442,7 +440,6 @@ function formatTimestamp(epochSeconds: number): string {return new Date(epochSeconds * 1000).toLocaleString();}-// Bar label for an in-flight generation: step count plus an ETA once known.function genStepLabel(p: DiffusionGenerateProgress): string {// Text encoding happens before the first scheduler tick, so step 0 means "working, not denoising yet".if (p.step === 0) return "Preparing (text encoding + warmup)…";@@ -570,7 +567,8 @@ const IDLE_PROGRESS: DiffusionLoadProgress = {error: null,};-// One row: label, track, value. The Images sliders are Chat ParamSlider, so both pages share one control.+// One row: label, track, value. The Images sliders are Chat ParamSlider, so both pages share one+// control.function SliderField({label,hint,@@ -658,7 +656,6 @@ function ResolvedBadge({);}-// A compact labeled Select row for the Advanced Options panel.function AdvancedSelect({label,hint,@@ -670,9 +667,7 @@ function AdvancedSelect({}: {label: string;hint?: ReactNode;- // An optional inline badge next to the label (e.g. the "Auto: X" resolved-value pill).badge?: ReactNode;- // A short always-visible description under the row.desc?: string;value: string;onValueChange: (v: string) => void;@@ -944,7 +939,6 @@ async function buildOutpaint(return { image: ic.toDataURL("image/png"), mask: mc.toDataURL("image/png") };}-// One labeled row in the recipe popover.function RecipeRow({label,value,@@ -972,7 +966,6 @@ function RecipeRow({);}-// The full generation recipe for an image, with a one-click "restore to inputs".function RecipePopover({image,onRestore,@@ -1047,7 +1040,6 @@ function RecipePopover({);}-// One "what actually ran" line in the loaded-build summary below.function BuildRow({ label, value, badge }: { label: string; value: string; badge?: ReactNode }) {return (<div className="flex items-center justify-between gap-2">@@ -1302,9 +1294,7 @@ export function ImagesPage({const seededResident = useRef<string | null>(null);const [busy, setBusy] = useState<Busy>(null);- // {done, total} while a multi-run generation is in flight (null = idle).const [genDone, setGenDone] = useState<number | null>(null);- // Live per-step progress (step / total + ETA) polled during generation.const [genStep, setGenStep] = useState<DiffusionGenerateProgress | null>(null);const genPollTimer = useRef<ReturnType<typeof setInterval> | null>(null);// visibilitychange handler active while a generation poll runs: background tabs clamp@@ -1332,10 +1322,9 @@ export function ImagesPage({// Set by Stop for one handleGenerate call: the backend cancel only reaches the denoise running// RIGHT NOW, so a count > 1 request would start its next run straight after.const cancelRequested = useRef(false);- // True only once the backend answered {cancelled: true}. Anything else means the run was NOT- // stopped, so an error it raises afterwards is a real failure.- // Anything else -- a POST that never landed, or {cancelled: false} because the run was already past- // its last cancellation check -- means it was NOT stopped.+ // True only once the backend answered {cancelled: true}. Anything else, a POST that never landed+ // or {cancelled: false} because the run was already past its last cancellation check, means it was+ // NOT stopped, so an error raised afterwards is a real failure.const cancelAcked = useRef(false);// Bumped once per handleGenerate call, so a cancel can tell its own run from a later one.const runToken = useRef(0);@@ -1944,7 +1933,6 @@ export function ImagesPage({[dropFromStrip],);- // Load an image's recipe back into the form inputs.const restoreSettings = useCallback((image: GalleryImage) => {setPrompt(image.prompt);// Negative prompt only applies when guidance>0; do not restore a hidden value.@@ -2094,9 +2082,9 @@ export function ImagesPage({() =>subscribeModelEjected("image", () => {dropResidentState();- // That eject cancelled the replacement load, and its progress poll is the only thing that- // clears `busy`, which dropResidentState just stopped; leaving it set locks the page.- // Narrowed to "loading" so a generation is left alone, and held until the start settles.+ // That eject cancelled the replacement load, and its progress poll is the only thing that clears+ // `busy`, which dropResidentState just stopped; leaving it set locks the page. Narrowed to+ // "loading" so a generation is left alone, and held until the start settles.const pending = pendingStart.current;if (pending) {setBusy((prev) => (prev === "loading" ? "unloading" : prev));@@ -2522,9 +2510,9 @@ export function ImagesPage({// Set when a staged download finished while this page was hidden: both diffusion pages stay// mounted and a load evicts whatever holds the GPU. The pick fires on return.const stagedLoadDeferred = useRef(false);- // Both deferred paths run the load minutes after the pick was reported started, so both need- // the same rollback: a deferred load can still be REFUSED, and staging polls nothing.- // `owned` is read BEFORE the call, so a newer pick's label is left alone.+ // Both deferred paths run the load minutes after the pick was reported started, so both need the+ // same rollback: a deferred load can still be REFUSED, and staging polls nothing. `owned` is read+ // BEFORE the call, so a newer pick's label is left alone.const runStagedLoad = useCallback((pending: NonNullable<typeof pendingStagedLoad.current>) => {if (pendingStagedLoad.current === pending) pendingStagedLoad.current = null;@@ -2611,11 +2599,9 @@ export function ImagesPage({source: ModelSelectorChangeMeta["source"] = "hub",token?: number,): Promise<boolean> => {- // Staging never sets `busy`, so a second pick passes the guard while this plan is in flight,- // and plans resolve in response order rather than pick order. Bumped before the non-hub- // return too, so a local pick invalidates an in-flight hub plan.- // Plans resolve in response order, not pick order. Bumped before the non-hub return too: a local- // pick must invalidate an in-flight hub plan.+ // Staging never sets `busy`, so a second pick passes the guard while this plan is in flight, and+ // plans resolve in response order rather than pick order. Bumped before the non-hub return too, so+ // a local pick invalidates an in-flight hub plan.const pick = ++pickSeq.current;// The previous pick's staged intent dies with it: a pick that stages nothing never calls// stage(), so the queue keeps the older job and its onReady loads the abandoned model.@@ -2653,10 +2639,9 @@ export function ImagesPage({bytes: e.bytes,ggufFilename: e.gguf_filename,// The entry carrying the picked checkpoint file, so the panel can label it without guessing:- // filenames cannot tell the two apart, and repo identity is not enough when a checkpoint- // shares its repo with cached companions. The backend's answer wins, since a gated pipeline- // is staged from an ungated MIRROR. Nullish coalescing, not `or`: a planner- // answering false is still an answer.+ // filenames cannot tell the two apart, and repo identity is not enough when a checkpoint shares+ // its repo with cached companions. The backend's answer wins, since a gated pipeline is staged+ // from an ungated MIRROR. Nullish coalescing, not `or`: a planner answering false is still an answer.checkpoint:e.checkpoint ??(opts.filename@@ -3040,11 +3025,11 @@ export function ImagesPage({try {setStatusIfNewest(++statusTicket.current, await unloadDiffusionModel());setQuant(null);- // Hold the page until any load start still in flight has run to its END, compensating unload- // and all. Without the fence an eject landing before the start registered returned success- // and cleared busy, so the next pick was refused while the older load carried on.- // That older handler, seeing the newer loadSeq, skips its compensating unload and returns without- // restarting its poll, leaving a multi-gigabyte load running with no toast and no cancel control.+ // Hold the page until any load start still in flight has run to its END, compensating unload and+ // all. Without the fence an eject landing before the start registered returned success and cleared+ // busy, so the next pick was refused while the older load carried on: that older handler, seeing+ // the newer loadSeq, skips its compensating unload and leaves a multi-gigabyte load running with+ // no toast and no cancel control.const pending = pendingStart.current;if (pending) {try {@@ -3345,10 +3330,10 @@ export function ImagesPage({genVisibilityListener.current = null;}cancelRequested.current = false;- // Refresh on EVERY exit, not just the successful one, and AWAIT it before Generate comes back:- // a generation can change server-side status and a cancelled native run can leave no model- // at all, so re-enabling first would offer a button that 409s.- // Speed=Auto compiles on the 3rd LoRA-free run and supports_lora flips false.+ // Refresh on EVERY exit, not just the successful one, and AWAIT it before Generate comes back: a+ // generation can change server-side status (Speed=Auto compiles on the 3rd LoRA-free run and+ // supports_lora flips false) and a cancelled native run can leave no model at all, so re-enabling+ // first would offer a button that 409s.if (isMounted.current) await refreshStatus();setBusy(null);setGenDone(null);@@ -3411,7 +3396,6 @@ export function ImagesPage({const activeWorkflowTab =WORKFLOW_TABS.find((t) => t.id === workflow) ?? WORKFLOW_TABS[0];- // The Advanced (load-time) tuning controls, rendered in the right-docked panel below.const advancedControls = (<><AdvancedSelectdiff --git a/studio/frontend/src/features/images/train/dataset-files.ts b/studio/frontend/src/features/images/train/dataset-files.tsindex 8a19b866bd1..5478a09482e 100644--- a/studio/frontend/src/features/images/train/dataset-files.ts+++ b/studio/frontend/src/features/images/train/dataset-files.ts@@ -1,8 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Mirrors _DIFFUSION_DATASET_IMAGE_EXTS, _CLIP_EXTS and _TEXT_EXTS in-// backend/routes/training.py.+// Mirrors _DIFFUSION_DATASET_IMAGE_EXTS, _CLIP_EXTS and _TEXT_EXTS in backend/routes/training.py.export const DATASET_IMAGE_EXTS = [".png", ".jpg", ".jpeg", ".webp", ".bmp"];// video containers, for the families that train from clips rather than stills.export const DATASET_CLIP_EXTS = [".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi"];diff --git a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx b/studio/frontend/src/features/images/train/diffusion-train-panel.tsxindex c6303966cfc..ee73ce7a4ee 100644--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx@@ -207,9 +207,9 @@ function datasetItemLabel(d: { image_count: number; clip_count?: number }): stri// and push into its neighbour.const selectClass ="h-8 w-full min-w-0 text-xs *:data-[slot=select-value]:min-w-0 *:data-[slot=select-value]:truncate";-// Every settings cell is a grid item, so it needs min-w-0 to shrink; grid-cols-1 carries that-// shrink to the contents, since a bare `grid` froze the implicit track at its widest child's-// min-content (150px) and painted over the next column.+// Every settings cell is a grid item, so it needs min-w-0 to shrink; grid-cols-1 carries that shrink to the+// contents, since a bare `grid` froze the implicit track at its widest child's min-content (150px) and painted+// over the next column.const fieldClass = "grid grid-cols-1 min-w-0 gap-2";/** opens the folder picker; icon-only because the 416px rail already holds the select and the file-pick button. */@@ -417,9 +417,9 @@ export function DiffusionTrainPanel({// sdxl trains the U-Net in mixed precision, so it uses mixed_precision instead of base_precision.// Everything else is a DiT family.const isDiT = familyName !== "sdxl";- // An EMPTY precision_modes list on a DiT family means this host cannot train it at all (the- // reason rides in vram_note); only an ABSENT field means an older backend. SDXL reports []- // too but is not precision-gated, hence the isDiT scope.+ // An EMPTY precision_modes list on a DiT family means this host cannot train it at all (the reason rides in+ // vram_note); only an ABSENT field means an older backend. SDXL reports [] too but is not precision-gated,+ // hence the isDiT scope.const familyUntrainable =isDiT &&reportedFamily?.precision_modes != null &&@@ -442,9 +442,9 @@ export function DiffusionTrainPanel({// Same for checkpoints: MiniMax-H3's loop writes no resume bundle and its validation REFUSES a// nonzero save_steps, so offering the field meant a rejected Start with nothing saying why.const supportsCheckpoints = reportedFamily?.supports_checkpoints ?? true;- // Same for the batch axis: MiniMax-H3's forward covers ONE packed sequence and its validation- // REFUSES a batch above 1 rather than clamping, so a value carried over from another family- // rejected Start with nothing saying why. Hidden when the family caps it at 1.+ // Same for the batch axis: MiniMax-H3's forward covers ONE packed sequence and its validation REFUSES a batch+ // above 1 rather than clamping, so a value carried over from another family rejected Start with nothing saying+ // why. Hidden when the family caps it at 1.const maxBatchSize = reportedFamily?.max_train_batch_size ?? null;const batchIsFixed = maxBatchSize != null && maxBatchSize <= 1;@@ -506,9 +506,9 @@ export function DiffusionTrainPanel({// Track whether the user hand-edited the numeric settings; if not, a family change re-seeds them// from that family's defaults.const settingsDirty = useRef(false);- // The LR schedule pair tracks its own edits rather than riding on settingsDirty: it is the one- // setting whose control DISAPPEARS ("Warmup steps" is hidden under plain "constant"), so a- // value carried past a family change is invisible rather than merely stale.+ // The LR schedule pair tracks its own edits rather than riding on settingsDirty: it is the one setting whose+ // control DISAPPEARS ("Warmup steps" is hidden under plain "constant"), so a value carried past a family change+ // is invisible rather than merely stale.const lrScheduleDirty = useRef(false);// Track whether the user hand-picked a base precision; if not, a family change re-seeds it from// recommended_precision.@@ -628,10 +628,10 @@ export function DiffusionTrainPanel({seededBaseFamily.current = family.name;baseDirty.current = false;}- // An already-valid base wins: the top bar sets family and base together. A loaded checkpoint may- // be the DISTILLED half of a pair, which is never in base_repos, so fall back to the paired- // training base before base_repos[0], or opening Train with the 9B model loaded seeds the 4B- // base. reportedFamily, since deploy_bases is backend-only.+ // An already-valid base wins: the top bar sets family and base together. A loaded checkpoint may be the+ // DISTILLED half of a pair, which is never in base_repos, so fall back to the paired training base before+ // base_repos[0], or opening Train with the 9B model loaded seeds the 4B base. reportedFamily, since+ // deploy_bases is backend-only.const pairedTrainingBase = loadedBaseRepo? resolveDiffusionTrainingBase(reportedFamily, loadedBaseRepo): null;@@ -670,9 +670,8 @@ export function DiffusionTrainPanel({if (isDiT) setPrecision("bf16");}, [isDiT]);- // The base actually used everywhere. baseChoice can briefly hold another family's repo, where a- // raw <select value> would DISPLAY the first option while the request carried the stale repo,- // so clamp to the current family.+ // The base actually used everywhere. baseChoice can briefly hold another family's repo, where a raw <select+ // value> would DISPLAY the first option while the request carried the stale repo, so clamp to the current family.const effectiveBase =baseChoice === CUSTOM_BASE || (family?.base_repos ?? []).includes(baseChoice)? baseChoice@@ -683,9 +682,8 @@ export function DiffusionTrainPanel({const resolvedBase = (effectiveBase === CUSTOM_BASE ? customBase : effectiveBase).trim();const basePrequantized = isDiT && repoIsPrequantized(resolvedBase);- // A prequantized base cannot serve the dense precisions; auto-flip a dense selection back to- // "auto" (nf4) so the run does not fail at the backend validator. Reuses precisionDirty so a- // later family change still re-seeds.+ // A prequantized base cannot serve the dense precisions; auto-flip a dense selection back to "auto" (nf4) so+ // the run does not fail at the backend validator. Reuses precisionDirty so a later family change still re-seeds.useEffect(() => {if (basePrequantized && DENSE_PRECISIONS.has(basePrecision)) {precisionDirty.current = false;@@ -701,7 +699,6 @@ export function DiffusionTrainPanel({}}, []);- // Poll status while the panel is active.useEffect(() => {if (!active) return;void poll();@@ -774,7 +771,6 @@ export function DiffusionTrainPanel({selectedDataset.caption_count >= selectedItemCount,);- // Map the backend's paired history arrays into the chart component's {step,value} series.const lossHistory: TrainingSeriesPoint[] = useMemo(() => {const h = status?.metric_history;if (!h) return [];@@ -821,7 +817,6 @@ export function DiffusionTrainPanel({}}, []);- // Chart series for a selected previous run (from its persisted metric logs).const viewLossHistory: TrainingSeriesPoint[] = useMemo(() => {const h = viewRun?.metric_history;if (!h) return [];@@ -880,9 +875,9 @@ export function DiffusionTrainPanel({setUploading(true);try {const misKeyed = await metadataKeyedOnSubfolders(files);- // the endpoint accumulates into the same folder, so a tree past the multipart part or byte cap- // goes up in slices. The cap decides where the slices fall, so it is forced past the cache,- // and a cap that cannot be read stops the upload.+ // the endpoint accumulates into the same folder, so a tree past the multipart part or byte cap goes up in+ // slices. The cap decides where the slices fall, so it is forced past the cache, and a cap that cannot be+ // read stops the upload.let maxBytes: number;try {maxBytes = (await loadUploadLimitSettings({ force: true })).maxUploadSizeBytes;@@ -1254,9 +1249,9 @@ export function DiffusionTrainPanel({value: number,set: (n: number) => void,fallback: number,- // markDirty overrides which dirty flag an edit claims. Only "Warmup steps" passes one: it is- // seeded from the family like rank/LR/resolution but tracked by lrScheduleDirty, so charging- // it to the shared flag would freeze the other three at the previous family's values.+ // markDirty overrides which dirty flag an edit claims. Only "Warmup steps" passes one: it is seeded from the+ // family like rank/LR/resolution but tracked by lrScheduleDirty, so charging it to the shared flag would+ // freeze the other three at the previous family's values.extra?: { min?: number; step?: number; hint?: ReactNode; markDirty?: () => void },) => (<div className={fieldClass}>@@ -1340,10 +1335,9 @@ export function DiffusionTrainPanel({return "fp8 (experimental)";};- // The training settings, the run area's MAIN content before a run starts. Columns key off this- // pane's OWN width, not the window's, or a viewport breakpoint put three columns in a ~280px- // pane. A cell needs 150px (66px number field + 6px gap + 78px unit select), hence 324px for- // two columns and 498px for three.+ // The training settings, the run area's MAIN content before a run starts. Columns key off this pane's OWN+ // width, not the window's, or a viewport breakpoint put three columns in a ~280px pane. A cell needs 150px+ // (66px number field + 6px gap + 78px unit select), hence 324px for two columns and 498px for three.const trainingSettings = (<div className="@container flex flex-col gap-6"><div className="grid grid-cols-1 gap-x-6 gap-y-5 @min-[324px]:grid-cols-2 @min-[498px]:grid-cols-3">diff --git a/studio/frontend/src/features/loaded-models/eject-chat-model.ts b/studio/frontend/src/features/loaded-models/eject-chat-model.tsindex 94492025743..be7906c0cf8 100644--- a/studio/frontend/src/features/loaded-models/eject-chat-model.ts+++ b/studio/frontend/src/features/loaded-models/eject-chat-model.ts@@ -72,14 +72,13 @@ export async function ejectChatModel(if (unloadedAliases.length > 0) {return { unloadedAliases, stillResident, replacedBy: null };}- // A row that was already cached, or an active one that has become cached- // since the card last polled. A model replaced inside the five-second poll- // window is not gone: the Transformers backend only moves- // `active_model_name` and leaves the previous model in `backend.models`- // (core/inference/inference.py:620), which /status still reports under- // `loaded` (routes/inference.py:8112), still holding its weights. Either way- // the scoped read above cannot match it, so ask what the runtime is really- // holding before reporting the row as somebody else's.+ // A row that was already cached, or an active one that has become cached since the card last+ // polled. A model replaced inside the five-second poll window is not gone: the Transformers+ // backend only moves `active_model_name` and leaves the previous model in `backend.models`+ // (core/inference/inference.py:620), which /status still reports under `loaded`+ // (routes/inference.py:8112), still holding its weights. Either way the scoped read above cannot+ // match it, so ask what the runtime is really holding before reporting the row as somebody+ // else's.const holdsTarget = (names: string[] | undefined) =>names?.some((name) => deps.matches(target, name)) ?? false;if (deps.cachedRow || holdsTarget(await deps.readCached?.())) {diff --git a/studio/frontend/src/features/loaded-models/index.ts b/studio/frontend/src/features/loaded-models/index.tsindex 9dbeed2ed83..ab1120aa7f8 100644--- a/studio/frontend/src/features/loaded-models/index.ts+++ b/studio/frontend/src/features/loaded-models/index.ts@@ -1,16 +1,14 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// The preference module comes FIRST, and the order is load-bearing. The-// indicator imports the settings barrel, which eagerly evaluates SettingsDialog-// and so general-tab, whose top-level reset list dereferences-// LOADED_MODELS_PREFERENCE_KEYS through this same barrel. Export the indicator-// first and an app that reaches this barrel before the settings one enters-// general-tab while this module is still initialising, and startup dies with-// "Cannot access 'LOADED_MODELS_PREFERENCE_KEYS' before initialization".-// Evaluating the constant first makes the cycle harmless whichever side is-// entered first. Verified in Vite dev, which serves native ESM and so has no-// bundler to reorder this.+// The preference module comes FIRST, and the order is load-bearing. The indicator imports the+// settings barrel, which eagerly evaluates SettingsDialog and so general-tab, whose top-level reset+// list dereferences LOADED_MODELS_PREFERENCE_KEYS through this same barrel. Export the indicator+// first and an app that reaches this barrel before the settings one enters general-tab while this+// module is still initialising, and startup dies with "Cannot access+// 'LOADED_MODELS_PREFERENCE_KEYS' before initialization". Evaluating the constant first makes the+// cycle harmless whichever side is entered first. Verified in Vite dev, which serves native ESM and+// so has no bundler to reorder this.export {LOADED_MODELS_PREFERENCE_KEYS,getLoadedModelsDismissed,diff --git a/studio/frontend/src/features/loaded-models/loaded-models-api.ts b/studio/frontend/src/features/loaded-models/loaded-models-api.tsindex 69b3d5d5269..f0bfd391d12 100644--- a/studio/frontend/src/features/loaded-models/loaded-models-api.ts+++ b/studio/frontend/src/features/loaded-models/loaded-models-api.ts@@ -61,10 +61,9 @@ async function readSttStatus(return (await response.json()) as SttStatusResponse;}-// A runtime that accepts the connection and never answers would leave the whole-// batch pending forever, and with it the in-flight guard gating every later-// refresh. Well past a cold status probe, so a slow-but-healthy read still lands-// and only a real hang trips it.+// A runtime that accepts the connection and never answers would leave the whole batch pending+// forever, and with it the in-flight guard gating every later refresh. Well past a cold status+// probe, so a slow-but-healthy read still lands and only a real hang trips it.const READ_TIMEOUT_MS = 10_000;/** null on failure or timeout: one stalled runtime must not empty the list. */@@ -207,10 +206,9 @@ export type EjectOutcome =| { status: "alreadyFree" }| { status: "replaced"; resident: string }| { status: "stillResident"; model: string }- // The unload was accepted but the read that confirms it did not answer, so- // neither "done" nor "failed" is true. Reported as its own outcome rather- // than collapsed into either, since the whole point of the confirming read is- // that a 200 from this endpoint is not evidence.+ // The unload was accepted but the read that confirms it did not answer, so neither "done" nor+ // "failed" is true. Reported as its own outcome rather than collapsed into either, since the+ // whole point of the confirming read is that a 200 from this endpoint is not evidence.| { status: "unverified" };/** `unload` could not confirm what the runtime holds, which is not the same as@@ -298,10 +296,9 @@ export async function ejectLoadedModel({ method: "POST" },);if (!response.ok) throw new Error(await readErrorDetail(response));- // The unload response body is a fixed {loaded_model: null}, and the- // backend silently serves `gguf` from the transformers engine when- // whisper-server is absent, so a 200 is not evidence this engine let- // go. Re-read and report what it actually holds.+ // The unload response body is a fixed {loaded_model: null}, and the backend silently+ // serves `gguf` from the transformers engine when whisper-server is absent, so a 200 is+ // not evidence this engine let go. Re-read and report what it actually holds.const after = await bounded(readSttStatus);// A non-2xx read is null too, and reading that as "nothing left"// would toast success and drop the row for a model still holdingdiff --git a/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsx b/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsxindex 1da35bcbad9..f19ec76c84f 100644--- a/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsx+++ b/studio/frontend/src/features/loaded-models/loaded-models-indicator.tsx@@ -202,11 +202,10 @@ export function LoadedModelsIndicator({const { position, panelRef, startDrag, dragging, justDragged } =useDragPosition(LOADED_MODELS_PREFERENCE_KEYS.position);- // A new load brings a closed card back: closing it means "not now", not "stop- // telling me", which is what the Settings toggle is for. Subscribed above the- // early return, so a dismissed card is still listening for the load that- // reopens it. On the start of the load, not the end, so it is up for the whole- // time the toast is.+ // A new load brings a closed card back: closing it means "not now", not "stop telling me", which+ // is what the Settings toggle is for. Subscribed above the early return, so a dismissed card is+ // still listening for the load that reopens it. On the start of the load, not the end, so it is+ // up for the whole time the toast is.useEffect(() =>subscribeModelLifecycle(({ loading }) => {@@ -217,14 +216,12 @@ export function LoadedModelsIndicator({[],);- // A load started outside this tab raises no lifecycle event at all: the- // OpenAI-compatible API and auto-switch go nowhere near the frontend wrappers- // that announce one. The poll is the only witness, so a row appearing while- // the card is closed reopens it too, which is what the tooltip promises.- //- // The first poll after closing is the baseline, never a reopen: the ids are- // read fresh on mount, and a dismissal survives a reload, so treating what is- // already resident as new would make the card impossible to close.+ // A load started outside this tab raises no lifecycle event at all: the OpenAI-compatible API and+ // auto-switch go nowhere near the frontend wrappers that announce one. The poll is the only+ // witness, so a row appearing while the card is closed reopens it too, which is what the tooltip+ // promises. The first poll after closing is the baseline, never a reopen: the ids are read fresh+ // on mount, and a dismissal survives a reload, so treating what is already resident as new would+ // make the card impossible to close.const idsWhileClosedRef = useRef<Set<string> | null>(null);useEffect(() => {if (!dismissed) {@@ -307,9 +304,8 @@ export function LoadedModelsIndicator({<TooltipTrigger asChild={true}><divaria-label="Drag to move"- // Not a button, so no click follows to consume the drag- // sentinel: say so, or the collapsed pill's next click reads- // this drag as its own and refuses to expand.+ // Not a button, so no click follows to consume the drag sentinel: say so, or the+ // collapsed pill's next click reads this drag as its own and refuses to expand.onPointerDown={startDrag}className="flex size-6 shrink-0 cursor-grab touch-none items-center justify-center rounded-full text-muted-foreground/60 transition-colors hover:bg-foreground/[0.07] hover:text-foreground active:cursor-grabbing">diff --git a/studio/frontend/src/features/loaded-models/loaded-models-sources.ts b/studio/frontend/src/features/loaded-models/loaded-models-sources.tsindex 0f76ddf54a8..acaee621db4 100644--- a/studio/frontend/src/features/loaded-models/loaded-models-sources.ts+++ b/studio/frontend/src/features/loaded-models/loaded-models-sources.ts@@ -126,11 +126,10 @@ export function describeInferenceStatus(const active = status.active_model;if (active) {const audioType = status.audio_type ?? null;- // is_audio means TTS here, as mlx_inference documents ("audio_vlm (omni- // audio input; is_audio stays False -- it means TTS and redirects in the- // chat route)"). So the audio types split three ways, not two: whisper is- // the ASR sidecar, audio_vlm is a chat model that happens to listen, and- // the rest speak. Only the third kind belongs under Speech.+ // is_audio means TTS here, as mlx_inference documents ("audio_vlm (omni audio input; is_audio+ // stays False -- it means TTS and redirects in the chat route)"). So the audio types split+ // three ways, not two: whisper is the ASR sidecar, audio_vlm is a chat model that happens to+ // listen, and the rest speak. Only the third kind belongs under Speech.const isTts =Boolean(status.is_audio) &&audioType !== "whisper" &&@@ -351,13 +350,12 @@ export function withPendingLoads(if (pending.size === 0) return rows;const extra: LoadedModelEntry[] = [];for (const [source, model] of pending) {- // A status row wins only when it describes the same load. Images and video- // keep the OLD pipeline resident while the replacement downloads, freeing it- // only at the commit, so a source-only test hid the incoming model for the- // whole pull: the card showed the model being replaced and no sign of the- // one arriving. A row that is itself loading always wins, which is what- // keeps chat and dictation from announcing the same load twice when the- // backend spells its name differently.+ // A status row wins only when it describes the same load. Images and video keep the OLD+ // pipeline resident while the replacement downloads, freeing it only at the commit, so a+ // source-only test hid the incoming model for the whole pull: the card showed the model being+ // replaced and no sign of the one arriving. A row that is itself loading always wins, which is+ // what keeps chat and dictation from announcing the same load twice when the backend spells its+ // name differently.if (rows.some((row) =>diff --git a/studio/frontend/src/features/loaded-models/show-loaded-models-pref.ts b/studio/frontend/src/features/loaded-models/show-loaded-models-pref.tsindex 44f5255c982..aa64ee07bf9 100644--- a/studio/frontend/src/features/loaded-models/show-loaded-models-pref.ts+++ b/studio/frontend/src/features/loaded-models/show-loaded-models-pref.ts@@ -1,10 +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-// Whether the corner indicator may appear. Off by default; only an explicit-// "true" (Settings -> General -> Notifications) enables it. An older explicit-// "false" still reads as off, so anyone who already turned it down stays that-// way. Tri-state on purpose: see setShowLoadedModels.+// Whether the corner indicator may appear. Off by default; only an explicit "true" (Settings ->+// General -> Notifications) enables it. An older explicit "false" still reads as off, so anyone who+// already turned it down stays that way. Tri-state on purpose: see setShowLoadedModels.import { useSyncExternalStore } from "react";@@ -38,10 +37,9 @@ export function getShowLoadedModels(): boolean {export function setShowLoadedModels(show: boolean): void {try {- // Both values written, never removed: "false" is the one an older reader- // also treats as off, so a pre-update tab does not flip the card back on- // through the storage event. Absent still means off here, so the default- // is unaffected.+ // Both values written, never removed: "false" is the one an older reader also treats as off, so+ // a pre-update tab does not flip the card back on through the storage event. Absent still means+ // off here, so the default is unaffected.localStorage.setItem(STORAGE_KEY, show ? "true" : "false");} catch {// storage unavailable@@ -83,9 +81,8 @@ export function getLoadedModelsDismissed(): boolean {}export function setLoadedModelsDismissed(dismissed: boolean): void {- // Nothing to announce when it already reads that way, and the reopen path- // runs on every load start, so this would otherwise re-render the app's whole- // overlay stack for each one.+ // Nothing to announce when it already reads that way, and the reopen path runs on every load+ // start, so this would otherwise re-render the app's whole overlay stack for each one.if (getLoadedModelsDismissed() === dismissed) {return;}diff --git a/studio/frontend/src/features/loaded-models/use-drag-position.ts b/studio/frontend/src/features/loaded-models/use-drag-position.tsindex 4b92a81c2a3..0334c1dd852 100644--- a/studio/frontend/src/features/loaded-models/use-drag-position.ts+++ b/studio/frontend/src/features/loaded-models/use-drag-position.ts@@ -1,10 +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-// Pointer drag for the indicator, in the Live monitor's idiom: anchored to its-// corner until the user moves it, then kept where they left it. Absolute-// viewport coordinates rather than a transform, so the position survives a-// reload and can be clamped when the window changes size.+// Pointer drag for the indicator, in the Live monitor's idiom: anchored to its corner until the+// user moves it, then kept where they left it. Absolute viewport coordinates rather than a+// transform, so the position survives a reload and can be clamped when the window changes size.import { useCallback, useEffect, useRef, useState } from "react";@@ -97,10 +96,9 @@ export function useDragPosition(storageKey: string): UseDragPosition {const [position, setPosition] = useState<DragPosition | null>(() => {if (typeof window === "undefined") return null;const stored = readStored(storageKey);- // Clamp on read as well as on resize. The observer below cannot fire until- // after the first paint, so a position saved on a wider screen would flash- // off screen once; zero width/height keeps at least the top-left corner in- // view, and the first measurement refines it.+ // Clamp on read as well as on resize. The observer below cannot fire until after the first+ // paint, so a position saved on a wider screen would flash off screen once; zero width/height+ // keeps at least the top-left corner in view, and the first measurement refines it.return stored ? clampToViewport(stored, 0, 0, viewport()) : null;});// Held from pointerdown to pointerup; dragging only once past the threshold.@@ -108,9 +106,8 @@ export function useDragPosition(storageKey: string): UseDragPosition {const [dragging, setDragging] = useState(false);const movedRef = useRef(false);const panelRef = useRef<HTMLDivElement | null>(null);- // Mirrored into state because the reclamp effect must re-subscribe when the- // node mounts: the card renders nothing until the first poll returns a row,- // so the effect's first run sees a null ref.+ // Mirrored into state because the reclamp effect must re-subscribe when the node mounts: the card+ // renders nothing until the first poll returns a row, so the effect's first run sees a null ref.const [panelEl, setPanelEl] = useState<HTMLDivElement | null>(null);const attachPanel = useCallback((node: HTMLDivElement | null) => {panelRef.current = node;@@ -128,9 +125,8 @@ export function useDragPosition(storageKey: string): UseDragPosition {lastLeft: number;lastTop: number;} | null>(null);- // The drag paints through the DOM rather than through state, so a frame costs- // no render at all. Held here so pointermove only ever records the latest- // offset and the frame reads it.+ // The drag paints through the DOM rather than through state, so a frame costs no render at all.+ // Held here so pointermove only ever records the latest offset and the frame reads it.const frameRef = useRef(0);const pendingRef = useRef<{ dx: number; dy: number } | null>(null);@@ -146,13 +142,11 @@ export function useDragPosition(storageKey: string): UseDragPosition {});}, []);- // A window that shrank, or a panel that grew when expanded, would otherwise- // strand it off screen with nothing able to bring it back.- //- // Deliberately not keyed on `position`: it used to be, so every frame of a- // drag tore the observer down and built a new one, and observing re-measures,- // which forced a synchronous layout each time. reclamp is a no-op until the- // panel has a position, so attaching on mount costs nothing.+ // A window that shrank, or a panel that grew when expanded, would otherwise strand it off screen+ // with nothing able to bring it back. Deliberately not keyed on `position`: it used to be, so+ // every frame of a drag tore the observer down and built a new one, and observing re-measures,+ // which forced a synchronous layout each time. reclamp is a no-op until the panel has a position,+ // so attaching on mount costs nothing.useEffect(() => {if (!panelEl) return;const measure = () => {@@ -257,10 +251,9 @@ export function useDragPosition(storageKey: string): UseDragPosition {if (moved && session) {const landed = { left: session.lastLeft, top: session.lastTop };setPosition(landed);- // Stored here rather than from an effect on `position`, so only a place- // the user chose is kept. A reclamp is the window adapting at display- // time, and persisting one let a small window permanently overwrite a- // position saved on a large one; the read path clamps anyway.+ // Stored here rather than from an effect on `position`, so only a place the user chose is+ // kept. A reclamp is the window adapting at display time, and persisting one let a small+ // window permanently overwrite a position saved on a large one; the read path clamps anyway.store(storageKey, landed);}sessionRef.current = null;@@ -268,9 +261,8 @@ export function useDragPosition(storageKey: string): UseDragPosition {setDragging(false);}, [applyPending, storageKey]);- // The press turned into a drag. Pin the panel where it already sits, so the- // transform offsets from the spot the anchor had it in and the first move- // does not jump.+ // The press turned into a drag. Pin the panel where it already sits, so the transform offsets+ // from the spot the anchor had it in and the first move does not jump.const beginDrag = useCallback((left: number, top: number) => {movedRef.current = true;setDragging(true);diff --git a/studio/frontend/src/features/loaded-models/use-loaded-models.ts b/studio/frontend/src/features/loaded-models/use-loaded-models.tsindex 384330a6aa7..cdb9d1b8183 100644--- a/studio/frontend/src/features/loaded-models/use-loaded-models.ts+++ b/studio/frontend/src/features/loaded-models/use-loaded-models.ts@@ -57,10 +57,9 @@ export function useLoadedModels(// Mirrored for the read below, which needs the last rows without taking a// dependency that would rebuild `refresh` on every poll.const polledRef = useRef<LoadedModelEntry[]>(NO_ENTRIES);- // Reported empty rather than cleared: clearing would be a setState in an- // effect, and the last read is right again the moment the pref returns.- // Loads announced by the API call itself, so a row appears with the toast- // rather than up to one poll later.+ // Reported empty rather than cleared: clearing would be a setState in an effect, and the last+ // read is right again the moment the pref returns. Loads announced by the API call itself, so a+ // row appears with the toast rather than up to one poll later.const [pending, setPending] = useState<Map<LoadedModelSource, string | null>>(() => new Map(),);@@ -114,9 +113,8 @@ export function useLoadedModels(const refreshRef = useRef<() => void>(() => {});const refresh = useCallback(() => {- // Keyed on recording, not showing: a closed card keeps polling so a load- // started outside this tab, which raises no lifecycle event at all, still- // brings it back.+ // Keyed on recording, not showing: a closed card keeps polling so a load started outside this+ // tab, which raises no lifecycle event at all, still brings it back.if (!track) return;if (inFlightRef.current) {// Remember the ask instead of dropping it: the refresh an eject queues@@ -147,9 +145,8 @@ export function useLoadedModels(refreshRef.current();return;}- // This read is the one that supersedes them, so retire only once no- // further read is already queued, and only for the sources it could- // actually see.+ // This read is the one that supersedes them, so retire only once no further read is already+ // queued, and only for the sources it could actually see.if (mountedRef.current) retireSettled(unreadable);});}, [track, retireSettled]);@@ -160,17 +157,14 @@ export function useLoadedModels(refreshRef.current = refresh;}, [refresh]);- // Nothing is listening once recording stops, so the terminal event for a load- // in flight is missed and its optimistic row would come back as one no poll- // can retire: `withPendingLoads` only yields to a status row for the same- // runtime, and a failed or since-unloaded load has none. Drop them and let the- // poll say what is really resident. Keyed on `track`, not `enabled`: a closed- // card is still recording, and clearing there would throw away the very load- // that is about to reopen it.- //- // Adjusted during render rather than in an effect: React re-runs this render- // before committing, so the stale rows never reach the DOM, and the guard- // makes it run once per transition.+ // Nothing is listening once recording stops, so the terminal event for a load in flight is missed+ // and its optimistic row would come back as one no poll can retire: `withPendingLoads` only+ // yields to a status row for the same runtime, and a failed or since-unloaded load has none. Drop+ // them and let the poll say what is really resident. Keyed on `track`, not `enabled`: a closed+ // card is still recording, and clearing there would throw away the very load that is about to+ // reopen it. Adjusted during render rather than in an effect: React re-runs this render before+ // committing, so the stale rows never reach the DOM, and the guard makes it run once per+ // transition.const [wasTracking, setWasTracking] = useState(track);if (wasTracking !== track) {setWasTracking(track);@@ -248,9 +242,8 @@ export function useLoadedModels();} else {toast.success(`Ejected ${label}`);- // Drop the row now, rather than offering to eject it again until the- // next poll. Any read already in flight predates this and would put- // the row back, so retire it.+ // Drop the row now, rather than offering to eject it again until the next poll. Any read+ // already in flight predates this and would put the row back, so retire it.generationRef.current += 1;if (mountedRef.current) {setEntries((prev) => prev.filter((row) => row.id !== entry.id));diff --git a/studio/frontend/src/features/model-picker/api/model-overrides.ts b/studio/frontend/src/features/model-picker/api/model-overrides.tsindex d7847e28d65..645f7ce37d5 100644--- a/studio/frontend/src/features/model-picker/api/model-overrides.ts+++ b/studio/frontend/src/features/model-picker/api/model-overrides.ts@@ -115,9 +115,8 @@ export function foldOverrideKey(key: string): string {return path;}// splitQuantSuffix, not the last colon: a colon is legal in a POSIX filename, so- // "/models/foo:Bar.gguf" is a whole path and reading "Bar.gguf" as a quant would fold it- // onto the real, different file "/models/foo:bar.gguf". Mirrors the backend's- // split_quant_suffix.+ // "/models/foo:Bar.gguf" is a whole path and reading "Bar.gguf" as a quant would fold it onto the+ // real, different file "/models/foo:bar.gguf". Mirrors the backend's split_quant_suffix.const split = splitQuantSuffix(key);const id = split ? split[0] : key;const quant = split ? `:${split[1].toLowerCase()}` : "";@@ -486,11 +485,10 @@ async function sendModelOverride(body: JSON.stringify({// biome-ignore lint/style/useNamingConvention: API schemamodel_id: modelOverrideKey(modelId, ggufVariant),- // This build mirrors the llama-server tuning group, so an omission here is the- // user clearing it rather than a client that predates the fields. Without this- // the backend preserves the stored values, which is what stops a cached older- // bundle from deleting settings it never knew to send. An older backend ignores- // the key.+ // This build mirrors the llama-server tuning group, so an omission here is the user clearing+ // it rather than a client that predates the fields. Without this the backend preserves the+ // stored values, which is what stops a cached older bundle from deleting settings it never+ // knew to send. An older backend ignores the key.// biome-ignore lint/style/useNamingConvention: API schemamirrors_server_tuning: true,// Only sent when set, so an older backend is not handed an unknown key every save.diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.tsindex 1cf8575d706..ab32248175a 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts@@ -1,10 +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-// Assertions over the model catalog: keys, aliases, integrity, quant ladders, search.-// `--network` adds an OPT-IN Hub reachability/gated-flag pass, kept out of-// `npm run catalog:check` so a Hub hiccup cannot fail an unrelated PR.-// Run it on a schedule (.github/workflows/model-catalog-network-check.yml) or by hand with+// Assertions over the model catalog: keys, aliases, integrity, quant ladders, search. `--network` adds an OPT-IN+// Hub reachability/gated-flag pass, kept out of `npm run catalog:check` so a Hub hiccup cannot fail an unrelated+// PR. Run it on a schedule (.github/workflows/model-catalog-network-check.yml) or by hand with// `npm run catalog:check:network`.import assert from "node:assert/strict";@@ -371,9 +370,8 @@ for (const catalog of [IMAGE_CATALOG, VIDEO_CATALOG]) {}}-// A non-GGUF artifact stating a parameter count must state its size, or the VRAM badge-// falls back to the QLoRA estimator, which reads a pipeline as a language model-// (5B says 5.9 GB where Wan 2.2 TI2V is 30).+// A non-GGUF artifact stating a parameter count must state its size, or the VRAM badge falls back to the QLoRA+// estimator, which reads a pipeline as a language model (5B says 5.9 GB where Wan 2.2 TI2V is 30).for (const catalog of [IMAGE_CATALOG, VIDEO_CATALOG, AUDIO_CATALOG]) {for (const group of catalog) {for (const artifact of group.artifacts) {@@ -392,9 +390,8 @@ const H3 = "MiniMaxAI/MiniMax-H3"; // 145 GB, tiers at 74/140 and 123/80const fitsCurated = (id: string, gpuGb: number, systemRamGb: number) =>curatedArtifactFitsDevice(id, VIDEO_CATALOG, { gpuGb, systemRamGb });-// The resident 70% rule on the card alone. RAM is not a discrete GPU's budget: a pipeline-// with no measured tier is placed wholly on the card.-// 64 GB of RAM does not rescue a 12 GB card.+// The resident 70% rule on the card alone. RAM is not a discrete GPU's budget: a pipeline with no measured tier+// is placed wholly on the card, so 64 GB of RAM does not rescue a 12 GB card.assert.equal(fitsCurated(WAN, 48, 0), true);assert.equal(fitsCurated(WAN, 40, 0), false);assert.equal(fitsCurated(WAN, 12, 64), false);@@ -410,9 +407,9 @@ assert.equal(fitsCurated(H3, 74, 100), false);// A GGUF ladder self-fits via pickDefaultQuant, and an unknown id is not ours to judge.assert.equal(fitsCurated("unsloth/MiniMax-H3-GGUF", 12, 64), undefined);assert.equal(fitsCurated("someone/not-in-the-catalog", 12, 64), undefined);-// Transcription retries a failed device load on CPU (stt_sidecar.py), so RAM is a real-// budget for stt: Whisper Large runs on a card too small to hold it. A tts load rejects CPU-// offload (inference.py raise_if_offloaded), so Orpheus is judged on the card.+// Transcription retries a failed device load on CPU (stt_sidecar.py), so RAM is a real budget for stt: Whisper+// Large runs on a card too small to hold it. A tts load rejects CPU offload (inference.py raise_if_offloaded), so+// Orpheus is judged on the card.assert.equal(curatedArtifactFitsDevice("unsloth/whisper-large-v3", AUDIO_CATALOG, {gpuGb: 4,@@ -453,9 +450,8 @@ assert.equal(const GB = 1024 ** 3;-// Delegated to lib/gguf-fit, the Hub badge formula: 0.97 of the card (or saved VRAM budget)-// against weights + KV, then RAM offload at 0.5. The old 0.7-of-each rule on raw file-// size matched neither the Hub nor the loader.+// Delegated to lib/gguf-fit, the Hub badge formula: 0.97 of the card (or saved VRAM budget) against weights ++// KV, then RAM offload at 0.5. The old 0.7-of-each rule on raw file size matched neither the Hub nor the loader.assert.equal(classifyGgufFit(10 * GB, { gpuGb: 24, systemRamGb: 64 }), "fits");// 20 GiB needs 24.0: past the 23.28 budget, still inside the 24 GiB card.assert.equal(classifyGgufFit(20 * GB, { gpuGb: 24, systemRamGb: 64 }), "marginal");@@ -516,10 +512,9 @@ for (const gpuCount of [1, 2, 4]) {);}-// Images / Video place a GGUF through the diffusion backend, whose 64 GiB unified budget is-// (total - 20%) * 0.85 = 43.5 GiB. This rule allows 44.8; the llama.cpp one allows 62.1-// and would promise loads the planner refuses.-// classifyMediaGgufFit. The 43.5 GiB figure is (total - 20% reserve) * 0.85, per diffusion_memory.py.+// Images / Video place a GGUF through the diffusion backend, whose 64 GiB unified budget is (total - 20%) * 0.85+// = 43.5 GiB, per diffusion_memory.py. This rule allows 44.8; the llama.cpp one allows 62.1 and would promise+// loads the planner refuses.assert.equal(classifyMediaGgufFit(40 * GB, 64, 0), "fits"); // 40 <= 44.8assert.equal(classifyMediaGgufFit(50 * GB, 64, 0), "oom"); // past 44.8, no RAM tier// The same 50 GiB file reads as fitting under the llama.cpp rule, the regression this guard@@ -591,9 +586,8 @@ assert.equal(.format,"bnb-4bit",);-// 48 GB: still bnb-4bit. fp8 is family-denied for qwen-image (renders black) and the -FP8-// repo ships prequant .pt rather than single-file safetensors, so the old winner-// auto-routed to a download that 404s.+// 48 GB: still bnb-4bit. fp8 is family-denied for qwen-image (renders black) and the -FP8 repo ships prequant+// .pt rather than single-file safetensors, so the old winner auto-routed to a download that 404s.assert.equal(pickDefaultArtifact(qwenGroup, { gpuGb: 48, systemRamGb: 64, isDownloaded: notDownloaded }).format,@@ -678,9 +672,8 @@ const hyimage = groupForRepoId(IMAGE_CATALOG,);assert.ok(hyimage);-// bf16 at both ends now: the QuantStack GGUF was unpublished, so the group has no quant-// ladder left. 50 GB still fits a 24 GB card's 61.6 GB budget, so this asserts the-// group did not vanish with its GGUF.+// bf16 at both ends now: the QuantStack GGUF was unpublished, so the group has no quant ladder left. 50 GB still+// fits a 24 GB card's 61.6 GB budget, so this asserts the group did not vanish with its GGUF.assert.equal(pickDefaultArtifact(hyimage, { gpuGb: 24, systemRamGb: 64, isDownloaded: notDownloaded }).repoId,@@ -762,9 +755,9 @@ assert.equal(.format,"bf16",);-// The upper tier in the picker's units: 132 GiB VRAM is 141.7 decimal GB, past the 132 GB-// where the estimator drops its host-RAM floor to 85 GB, and 85 GiB RAM is 91.3 GB.-// A decimal-GB tier table would wrongly send this host to GGUF.+// The upper tier in the picker's units: 132 GiB VRAM is 141.7 decimal GB, past the 132 GB where the estimator+// drops its host-RAM floor to 85 GB, and 85 GiB RAM is 91.3 GB. A decimal-GB tier table would wrongly send this+// host to GGUF.assert.equal(pickDefaultArtifact(h3, { gpuGb: 132, systemRamGb: 85, isDownloaded: notDownloaded }).format,@@ -819,10 +812,9 @@ assert.equal(.format,"gguf",);-// LTX-2.3 video carries the official BF16 single file (no FP8: the loader refuses its-// scaled-fp8 one), keeping the ~50 GB Gemma3 encoder resident, so B200-class only.-// Looked up by the retired unsloth/LTX-2.3 id on purpose: a pasted or persisted copy-// must still land on this group through the GGUF artifact's suffix-stripped key.+// LTX-2.3 video carries the official BF16 single file (no FP8: the loader refuses its scaled-fp8 one), keeping+// the ~50 GB Gemma3 encoder resident, so B200-class only. Looked up by the retired unsloth/LTX-2.3 id on purpose:+// a pasted or persisted copy must still land on this group through the GGUF artifact's suffix-stripped key.const ltxGroup = groupForRepoId("unsloth/LTX-2.3", VIDEO_CATALOG);assert.ok(ltxGroup);assert.equal(ltxGroup.canonicalId, "Lightricks/LTX-2.3");@@ -955,19 +947,18 @@ assert.ok(groupMatchesQuery(ltx23, "lightricks/ltx-2.3"));console.log("model-catalog check: all assertions passed");-// Opt-in `--network` pass: every failure it catches was reported by hand, a link that 401s-// on an undeclared gated repo or 404s after a rename. Anonymous on purpose, since that-// is what a fresh install sees; only a definitive verdict fails the run.+// Opt-in `--network` pass: every failure it catches was reported by hand, a link that 401s on an undeclared+// gated repo or 404s after a rename. Anonymous on purpose, since that is what a fresh install sees; only a+// definitive verdict fails the run.const HF_API = "https://huggingface.co/api/models";const HF_RESOLVE = "https://huggingface.co";const NETWORK_ATTEMPTS = 3;/** Per-attempt wall clock, headers and body together. */const NETWORK_TIMEOUT_MS = 20_000;-/** Wall clock for the whole network pass, under the workflow's 10-minute timeout. Bounding- * each attempt is not enough: ~53 repos at NETWORK_BATCH 4 is 14 serial batches, so a- * stalling peer would be killed at 10 as a red run. Past the deadline requests- * short-circuit to "no opinion" and the check exits 0. */+/** Wall clock for the whole network pass, under the workflow's 10-minute timeout. Bounding each attempt is not+ * enough: ~53 repos at NETWORK_BATCH 4 is 14 serial batches, so a stalling peer would be killed at 10 as a red+ * run. Past the deadline requests short-circuit to "no opinion" and the check exits 0. */const NETWORK_DEADLINE_MS = 7 * 60 * 1000;/** Set when the network pass starts; Infinity keeps the offline assertions unbounded. */let networkDeadlineAt = Number.POSITIVE_INFINITY;diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.tsindex 0dedd80f456..6411384a638 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts@@ -1,9 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// One canonical name per diffusion model, its published artifacts (GGUF quants, prequant FP8 /-// bnb-4bit repos, official BF16 pipelines), and a deterministic router picking the best-// artifact for the device. Pure helpers, no React/DOM deps. See model-catalog.check.ts.+// One canonical name per diffusion model, its published artifacts (GGUF quants, prequant FP8 / bnb-4bit repos,+// official BF16 pipelines), and a deterministic router picking the best artifact for the device. Pure helpers, no+// React/DOM deps. See model-catalog.check.ts.import {type GgufFitClass,@@ -61,10 +61,9 @@ export interface CatalogGroup {artifacts: ModelArtifact[];/** Cross-owner ids that resolve to this group. Suffix stripping never merges two owners on its own. */aliases?: readonly string[];- /** What the model can do, for the row's capability glyphs. Same fallback rule as- * `ModelArtifact.totalParams`: the Hub listing's tags win where it returns the row, since- * `detectCapabilities` reads tags then repo-name keywords and a name like "MiniMax-H3-GGUF"- * says nothing about the audio track the model emits. */+ /** What the model can do, for the row's capability glyphs. Same fallback rule as `ModelArtifact.totalParams`:+ * the Hub listing's tags win where it returns the row, since `detectCapabilities` reads tags then repo-name+ * keywords and a name like "MiniMax-H3-GGUF" says nothing about the audio track the model emits. */capabilities?: Partial<ModelCapabilities>;}@@ -171,8 +170,8 @@ export const IMAGE_CATALOG: CatalogGroup[] = [artifacts: [bf16Pipeline("Qwen/Qwen-Image-2512", 54, { totalParams: 20430401088 }),// No FP8 row: unsloth/Qwen-Image-2512-FP8 holds torch prequant .pt checkpoints, not a single-file- // .safetensors, and fp8 is denied for this family anyway (_FAMILY_SCHEME_DENY: qwen-image- // renders every frame black under fp8).+ // .safetensors, and fp8 is denied for this family anyway (_FAMILY_SCHEME_DENY: qwen-image renders every frame+ // black under fp8).bnb4bit("unsloth/Qwen-Image-2512-unsloth-bnb-4bit", 14, { totalParams: 10850871408 }),gguf("unsloth/Qwen-Image-2512-GGUF"),],@@ -277,15 +276,13 @@ export const IMAGE_CATALOG: CatalogGroup[] = [},{// 17B dual-stream 2K-native DiT with a Qwen2.5-VL encoder. bf16 only: this used to carry- // gguf("QuantStack/HunyuanImage-2.1-GGUF") as the consumer route, and that repo was- // unpublished. An entry the Hub cannot serve renders as a one-click download that fails- // partway through, the exact case model-catalog-network-check exists to find. No vetted- // replacement: unsloth has an FP8 mirror but no GGUF, and the third-party GGUF repos are a- // different lineage. At 24 GB the bf16 still fits the 61.6 GB budget, so the group stays- // visible; the quant ladder is what is gone.- // The mirror guider components load natively on diffusers 0.39. The retired GGUF repo 404s to an- // authed request and 401s anonymously; QuantStack itself is alive and still ships its other GGUF- // repos, so this is one model withdrawn rather than a publisher going away.+ // gguf("QuantStack/HunyuanImage-2.1-GGUF") as the consumer route, and that repo was unpublished. An entry the+ // Hub cannot serve renders as a one-click download that fails partway through, the exact case+ // model-catalog-network-check exists to find. No vetted replacement: unsloth has an FP8 mirror but no GGUF, and+ // the third-party GGUF repos are a different lineage. At 24 GB the bf16 still fits the 61.6 GB budget, so the+ // group stays visible; the quant ladder is what is gone. The mirror guider components load natively on+ // diffusers 0.39. The retired GGUF repo 404s to an authed request and 401s anonymously; QuantStack itself is+ // alive and still ships its other GGUF repos, so this is one model withdrawn rather than a publisher going away.canonicalId: "hunyuanvideo-community/HunyuanImage-2.1-Diffusers",displayName: "HunyuanImage 2.1",description: "Text-to-image",@@ -295,9 +292,9 @@ export const IMAGE_CATALOG: CatalogGroup[] = [],},{- // 17B MoE DiT + four text encoders. The MIT repos ship no Llama text_encoder_4, so the backend- // assembles it from the open unsloth mirror at load time (+16 GB): ~63 GB bf16-resident, a- // datacenter pick. Full is the undistilled base, Dev and Fast its distillations.+ // 17B MoE DiT + four text encoders. The MIT repos ship no Llama text_encoder_4, so the backend assembles it+ // from the open unsloth mirror at load time (+16 GB): ~63 GB bf16-resident, a datacenter pick. Full is the+ // undistilled base, Dev and Fast its distillations.canonicalId: "HiDream-ai/HiDream-I1-Full",displayName: "HiDream I1",description: "Text-to-image",@@ -361,13 +358,12 @@ export const VIDEO_CATALOG: CatalogGroup[] = [capabilities: { audio: true },artifacts: [bf16Pipeline("MiniMaxAI/MiniMax-H3", 145, {- // Cluster measurements at the default 1344x768, 124-frame preset: the lower-GPU tier holds one- // 66 GB component at a time and keeps the full model in RAM. THESE ARE GiB and the backend- // estimators they mirror are decimal GB, so the two sets must never be copied across:- // nvidia.py memory_total_gb and main.py available_gb divide by 1024, while video.py divides- // runtime bytes by 1_000_000_000. Converted, these are 79.5 / 150.3 and 132.1 / 85.9 GB,- // matching the estimators' 78.74 / 150 and 132 / 85. Copying the decimal figures across- // applies the conversion twice and sends capable hosts to GGUF.+ // Cluster measurements at the default 1344x768, 124-frame preset: the lower-GPU tier holds one 66 GB+ // component at a time and keeps the full model in RAM. THESE ARE GiB and the backend estimators they mirror+ // are decimal GB, so the two sets must never be copied across: nvidia.py memory_total_gb and main.py+ // available_gb divide by 1024, while video.py divides runtime bytes by 1_000_000_000. Converted, these are+ // 79.5 / 150.3 and 132.1 / 85.9 GB, matching the estimators' 78.74 / 150 and 132 / 85. Copying the decimal+ // figures across applies the conversion twice and sends capable hosts to GGUF.offloadFitTiers: [{ gpuGb: 74, systemRamGb: 140 },{ gpuGb: 123, systemRamGb: 80 },@@ -390,13 +386,12 @@ export const VIDEO_CATALOG: CatalogGroup[] = [],},{- // The distilled 2.3 release: Lightricks' own bf16/fp8 single-file DiT checkpoints (loaded against- // the already-trusted LTX-2 base for the VAE / Gemma3 encoder) plus the GGUF quants. The- // single-file ones keep the ~50 GB encoder in bf16, so consumer GPUs route to GGUF.- // Keyed on the artifact that exists: unsloth/LTX-2.3 was never published (404), and an- // `unsloth/*` id that is not an artifact clears both the picker's owner guard and the- // backend's, so a pick that reached the fall-through was loaded as a pipeline and only died- // at the Hub. Lightricks/LTX-2.3 IS an artifact below, so that fall-through cannot fire.+ // The distilled 2.3 release: Lightricks' own bf16/fp8 single-file DiT checkpoints (loaded against the+ // already-trusted LTX-2 base for the VAE / Gemma3 encoder) plus the GGUF quants. The single-file ones keep the+ // ~50 GB encoder in bf16, so consumer GPUs route to GGUF. Keyed on the artifact that exists: unsloth/LTX-2.3+ // was never published (404), and an `unsloth/*` id that is not an artifact clears both the picker's owner guard+ // and the backend's, so a pick that reached the fall-through was loaded as a pipeline and only died at the Hub.+ // Lightricks/LTX-2.3 IS an artifact below, so that fall-through cannot fire.canonicalId: "Lightricks/LTX-2.3",displayName: "LTX 2.3 distilled",description: "Text-to-video with audio",@@ -409,8 +404,8 @@ export const VIDEO_CATALOG: CatalogGroup[] = [90,),// No FP8 artifact: the LTX-2.3 loader refuses the official scaled-FP8 single file (it carries- // .weight_scale/.input_scale), so a click would start a ~76 GB download that always fails.- // 21.0B is what the Hub reports, and carrying it keeps the row identical when offline.+ // .weight_scale/.input_scale), so a click would start a ~76 GB download that always fails. 21.0B is what the+ // Hub reports, and carrying it keeps the row identical when offline.gguf("unsloth/LTX-2.3-GGUF", { totalParams: 21_005_004_544 }),],},@@ -442,9 +437,9 @@ export const VIDEO_CATALOG: CatalogGroup[] = [description: "Text-to-video",scope: "video",artifacts: [- // Highest-quality first: pickDefaultArtifact sorts only by FORMAT, so these two bf16 artifacts- // keep catalog order and the fit loop returns the first that fits. 720p (52 GB) precedes- // 480p (40 GB), so an 80 GB card picks 720p.+ // Highest-quality first: pickDefaultArtifact sorts only by FORMAT, so these two bf16 artifacts keep catalog+ // order and the fit loop returns the first that fits. 720p (52 GB) precedes 480p (40 GB), so an 80 GB card+ // picks 720p.bf16Pipeline("hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-720p_t2v", 52, {label: "BF16 - 720p",keywords: ["bf16", "720p"],@@ -459,10 +454,10 @@ export const VIDEO_CATALOG: CatalogGroup[] = [},];-// The Audio page's curated list. tts groups load into the main slot via /api/inference/load-// (Orpheus is the only family the llama.cpp TTS path also serves as GGUF); native TTS-// families use their official Transformers/Diffusers interfaces. stt groups map to the-// dictation sidecar models in stt-model-catalog.ts, so their sizes are informational only.+// The Audio page's curated list. tts groups load into the main slot via /api/inference/load (Orpheus is the only+// family the llama.cpp TTS path also serves as GGUF); native TTS families use their official+// Transformers/Diffusers interfaces. stt groups map to the dictation sidecar models in stt-model-catalog.ts, so+// their sizes are informational only.export const AUDIO_CATALOG: CatalogGroup[] = [{canonicalId: "unsloth/orpheus-3b-0.1-ft",@@ -566,9 +561,9 @@ export const AUDIO_CATALOG: CatalogGroup[] = [],},// Llasa is deliberately absent: it speaks XCodec2 (65,536 <|s_N|> tokens), which is in neither- // _AUDIO_TOKEN_PATTERNS nor AudioCodecManager, so a curated row loaded and then failed at- // generation. Unsloth can still TRAIN Llasa (unsloth_Llasa-3B.yaml); this catalog only feeds the- // Generate picker. Re-add both rows together with an xcodec2 decoder.+ // _AUDIO_TOKEN_PATTERNS nor AudioCodecManager, so a curated row loaded and then failed at generation. Unsloth+ // can still TRAIN Llasa (unsloth_Llasa-3B.yaml); this catalog only feeds the Generate picker. Re-add both rows+ // together with an xcodec2 decoder.{canonicalId: "unslothai/Qwen3-ASR-0.6B-GGUF",displayName: "Qwen3-ASR 0.6B",@@ -782,8 +777,8 @@ export function curatedTotalParamsFor(}/** Curated capabilities for any id belonging to a group that declares them. Same fallback rule as- * `curatedTotalParamsFor`: the listing's tags win. Group-level, since every artifact of a- * model can do what the model can do. */+ * `curatedTotalParamsFor`: the listing's tags win. Group-level, since every artifact of a model can do what the+ * model can do. */export function curatedCapabilitiesFor(repoId: string,catalog: CatalogGroup[],@@ -795,9 +790,8 @@ export function curatedCapabilitiesFor(vision: declared?.vision ?? false,reasoning: declared?.reasoning ?? false,audio: declared?.audio ?? false,- // From the group's scope rather than a declaration: every catalog entry is a generator of one or- // the other, and the scope already says which. Beats the name heuristic, which has to guess- // a family from a repo id.+ // From the group's scope rather than a declaration: every catalog entry is a generator of one or the other, and+ // the scope already says which. Beats the name heuristic, which has to guess a family from a repo id.imageGen: declared?.imageGen ?? group.scope === "image",videoGen: declared?.videoGen ?? group.scope === "video",};@@ -812,9 +806,8 @@ export function curatedDisplayNameFor(): string | null {const hit = artifactForRepoId(repoId, catalog);if (!hit) return null;- // A row that earns a speed qualifier must read the same closed as open: this helper names the- // trigger and curatedRowLabelFor names the row, so a divergence would rename the model as- // the popover opens.+ // A row that earns a speed qualifier must read the same closed as open: this helper names the trigger and+ // curatedRowLabelFor names the row, so a divergence would rename the model as the popover opens.if (h3PerfSuffix(repoId, host)) {return curatedRowLabelFor(repoId, catalog, host)?.name ?? hit.group.displayName;}@@ -823,17 +816,16 @@ export function curatedDisplayNameFor(: hit.group.displayName;}-// Artifact labels are written as "FORMAT" or "FORMAT - QUALIFIER". The format head and a-// resolution qualifier are chips; anything else stays in the name, since it is the only thing-// telling two rows of one group apart.+// Artifact labels are written as "FORMAT" or "FORMAT - QUALIFIER". The format head and a resolution qualifier are+// chips; anything else stays in the name, since it is the only thing telling two rows of one group apart.const LABEL_PART_SEPARATOR = " - ";const OFFICIAL_SUFFIX_RE = /\s*\(official\)$/i;const GGUF_SUFFIX_RE = /-gguf$/i;const RESOLUTION_RE = /^\d{3,4}p$/i;-/** A curated row as name plus chips. The name used to carry the artifact inside brackets ("MiniMax- * H3 (BF16 (official))"), which pushed the part a user scans for behind the part they do- * not. Null for ids outside the catalog. */+/** A curated row as name plus chips. The name used to carry the artifact inside brackets ("MiniMax H3 (BF16+ * (official))"), which pushed the part a user scans for behind the part they do not. Null for ids outside the+ * catalog. */export function curatedRowLabelFor(repoId: string,catalog: CatalogGroup[],@@ -874,9 +866,9 @@ export function catalogToModelOptions(const options: ModelOption[] = [];for (const group of catalog) {for (const artifact of group.artifacts) {- // A host that can only run the native engine is not offered the pipeline rows it would be refused- // at load. This is the one place the `models` prop is built, so filtering here covers the- // trigger name and the picker's seed ids together.+ // A host that can only run the native engine is not offered the pipeline rows it would be refused at load.+ // This is the one place the `models` prop is built, so filtering here covers the trigger name and the picker's+ // seed ids together.if (!curatedArtifactIsOfferable(artifact.repoId, host)) continue;options.push({id: artifact.repoId,@@ -953,9 +945,9 @@ export interface DeviceBudget {gpuCount?: number;}-/** GGUF fit, delegated to the one formula the Hub badge already uses. This used to carry its own- * rule (0.7 * GPU + 0.7 * RAM, raw file size) whose comment claimed to match `_select_gpus`;- * it did not, so chat hid quants the loader would have taken and ignored the VRAM Budget. */+/** GGUF fit, delegated to the one formula the Hub badge already uses. This used to carry its own rule (0.7 * GPU+ * + 0.7 * RAM, raw file size) whose comment claimed to match `_select_gpus`; it did not, so chat hid quants the+ * loader would have taken and ignored the VRAM Budget. */export function classifyGgufFit(sizeBytes: number,budget: DeviceBudget,@@ -967,11 +959,11 @@ export function classifyGgufFit(return classifyGgufFitForDevice(sizeBytes, budget);}-/** Fit rule for a GGUF the IMAGES / VIDEO / AUDIO pickers offer, the one case the shared llama.cpp- * formula must not judge: those loads go through the diffusion backend, whose budget is free- * memory minus a reserve at a 0.85 margin (`diffusion_memory.py`) and which cannot offload.- * On a 64 GiB Mac that planner allows about 43.5 GiB where llama.cpp allows 62.1; this rule- * allows 44.8. It is not the diffusion planner either, only the closer of the two. */+/** Fit rule for a GGUF the IMAGES / VIDEO / AUDIO pickers offer, the one case the shared llama.cpp formula must+ * not judge: those loads go through the diffusion backend, whose budget is free memory minus a reserve at a 0.85+ * margin (`diffusion_memory.py`) and which cannot offload. On a 64 GiB Mac that planner allows about 43.5 GiB+ * where llama.cpp allows 62.1; this rule allows 44.8. It is not the diffusion planner either, only the closer of+ * the two. */export function classifyMediaGgufFit(sizeBytes: number,gpuGb: number,@@ -1091,12 +1083,11 @@ export function pickDefaultArtifact()[0];}-/** Whether ONE curated artifact loads on this device, by the rule `pickDefaultArtifact` routes- * with, since a row click loads that exact artifact. System RAM is not part of a- * discrete-GPU budget: a pipeline goes wholly on the card unless the catalog states a- * measured offload tier or the loader falls back to CPU, which only transcription does. A- * unified-memory host reports RAM and no GPU, and there the RAM is the card. Undefined where- * nothing can be judged, so the caller shows no verdict rather than a wrong one. */+/** Whether ONE curated artifact loads on this device, by the rule `pickDefaultArtifact` routes with, since a row+ * click loads that exact artifact. System RAM is not part of a discrete-GPU budget: a pipeline goes wholly on the+ * card unless the catalog states a measured offload tier or the loader falls back to CPU, which only+ * transcription does. A unified-memory host reports RAM and no GPU, and there the RAM is the card. Undefined+ * where nothing can be judged, so the caller shows no verdict rather than a wrong one. */export function curatedArtifactFitsDevice(repoId: string,catalog: CatalogGroup[],@@ -1108,9 +1099,9 @@ export function curatedArtifactFitsDevice(if (budget.gpuGb <= 0 && budget.systemRamGb <= 0) return undefined;if (artifact.offloadFitTiers?.length) return fitsArtifactBudget(artifact, budget);if (artifact.approxSizeGb === undefined) return undefined;- // Transcription retries a failed device load on CPU (stt_sidecar.py), so RAM is a real budget- // there, but the WHOLE model goes to whichever device it lands on, so it is the larger of- // the two and not their sum. An image, video or TTS load rejects CPU offload.+ // Transcription retries a failed device load on CPU (stt_sidecar.py), so RAM is a real budget there, but the+ // WHOLE model goes to whichever device it lands on, so it is the larger of the two and not their sum. An image,+ // video or TTS load rejects CPU offload.const deviceGb =group.task === "stt"? Math.max(budget.gpuGb, budget.systemRamGb)diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex 1f48fb128cd..3170cd9b91a 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -241,7 +241,6 @@ function isUnslothPublisherRepoId(repoId: string): boolean {return isUnslothOwner(splitRepoLabel(repoId).owner);}-/** Lowercase and strip separators for fuzzy search. */function normalizeForSearch(s: string): string {return s.toLowerCase().replace(/[\s_.-]/g, "");}@@ -415,7 +414,6 @@ function ListLabel({action?: ReactNode;collapsed?: boolean;onToggle?: () => void;- /** Draw a divider line above to separate it from the section above (omit on the first section). */divider?: boolean;}) {return (@@ -452,14 +450,12 @@ function ListLabel({);}-/** Format bytes to a human-readable size string. */function formatBytes(bytes: number): string {// Guard non-positive / non-finite sizes so we never render "NaN undefined".if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";// Decimal (base-1000) units to match Hugging Face's reported sizes; the GPU-fit math stays- // base-1024. Divide iteratively, not via Math.log, which is off at exact powers of 1000.- // Divide iteratively rather than via Math.log, which has float error at exact powers of 1000- // (mislabeling 1 TB as "1000 GB") and could run off the end of units.+ // base-1024. Divide iteratively, not via Math.log, which is off at exact powers of 1000 and could+ // run off the end of units.const units = ["B", "KB", "MB", "GB", "TB"];let i = 0;let value = bytes;@@ -560,14 +556,11 @@ function VisionBadge() {);}-/** Parameter count chip ("27B"). */function ParamChip({ label }: { label: string }) {return (- // h-[18px], the height every other chip in the row band already pins (quant, vision, the disk- // mark, the Loaded tag). py-px left this one sized by its line box instead, which is the only- // height here that scales with --ui-font-scale: at 1.0 it stood 1px PROUDER than the quant and- // vision chips beside it and at 0.8125 it sat 1.8px shorter, so the row only looked level at- // the one scale where the two happened to cross. A shared height is level at every scale.+ // h-[18px], the height every other chip in the row band pins (quant, vision, the disk mark, the+ // Loaded tag). py-px sized this one by its line box instead, the one height here that scales with+ // --ui-font-scale, so the row only looked level at the scale where the two happened to cross.<span className="inline-flex h-[18px] shrink-0 items-center whitespace-nowrap rounded-md border border-border/60 px-1.5 text-ui-10 font-medium text-muted-foreground tabular-nums">{label}</span>@@ -665,8 +658,6 @@ interface FitVerdict {const AMBER = "!text-yellow-600 dark:!text-yellow-400";const ORANGE = "!text-orange-600 dark:!text-orange-300";-/** Over budget but still card-sized. `_select_gpus` scores against FREE VRAM, so whether this- * lands on the GPU depends on what else is resident; missing it costs speed, not the load. *//** Over the VRAM Budget, still smaller than the card. Not conditional: `_vram_usable_mib`* gives `free - reserve`, which on an idle card IS the budget this tier passed, so* `_select_gpus` hands it to --fit every time. Raising the budget is the lever. */@@ -792,7 +783,6 @@ function VramBadge({const SIZE_PARTS_RE = /^(~?)([\d.]+)\s*([A-Za-z]+)$/;-/** A size in mono: the dot pulled in, a hair of air before the unit. */function SizeText({ value }: { value: string }) {const parts = SIZE_PARTS_RE.exec(value);if (!parts) {@@ -868,7 +858,6 @@ export function GgufDownloadFootprintExplanation({);}-/** The one quant a row loads, as a compact mono chip. */function QuantChip({ label }: { label: string }) {return (<span className="inline-flex h-[18px] max-w-full items-center overflow-hidden rounded-md bg-black/[0.06] px-1 font-mono text-ui-9 text-muted-foreground dark:bg-white/[0.1]">@@ -907,10 +896,9 @@ function artifactBudget(gpu: {const META_COLUMN = {// Fits "UD-Q4_K_XL"; a hard cap, so longer quants clip.quant: "min-[560px]:w-[7.2em]",- // Each width below is the widest set its scope can draw: anything wider makes min-w-min expand- // the slot and shift every column after it.- // The slot holds capability glyphs (18px), the vision badge (24px) and the "on disk" mark (14px),- // gap-1 between them. Scope draws no glyph: the vision badge alone, or the disk mark alone.+ // Each width below is the widest set its scope can draw: anything wider makes min-w-min expand the+ // slot and shift every column after it. This slot holds capability glyphs (18px), the vision badge+ // (24px) and the "on disk" mark (14px), gap-1 between them; scope draws no glyph.badge: "min-w-min min-[560px]:w-[24px]",// One glyph plus the disk mark (18 + 4 + 14).badgeMid: "min-w-min min-[560px]:w-[36px]",@@ -922,13 +910,10 @@ const META_COLUMN = {badgeWide: "min-w-min min-[560px]:w-[36px]",// The fit mark (Hub rows), one 18px glyph.vram: "min-w-min min-[560px]:w-[18px]",- // Device rows reserve the slot rather than hug the chip. This is the last variable column on the- // right, so hugging it let each row's meta cluster set its own width: a "1B" row, and more so a- // row with no param at all, gave its name group the leftover and carried its quant chip that much- // further right, leaving the quant column ragged down the list. 4.4em is the widest these lists- // draw, measured at text-ui-10 -- "235B" is 38.4px, a 5-char "0.35B" 40.9px -- so nothing routine- // trips min-w-min and shifts the row back out of line. The slack now sits in front of the chip,- // as its gap to the modality mark. Hub keeps its own width for "2779.5B".+ // Device rows reserve the slot rather than hug the chip. This is the last variable column, so+ // hugging it let each row's meta cluster set its own width and left the quant column ragged. 4.4em+ // is the widest these lists draw at text-ui-10 ("235B" 38.4px, "0.35B" 40.9px), so nothing routine+ // trips min-w-min. Hub keeps its own width for "2779.5B".param: "min-w-min min-[560px]:w-[4.4em]",paramWide: "min-w-min min-[560px]:w-[5.2em]",// formatBytes writes no space ("536MB"), so the widest this holds is 29.5px, not the ~40px a spaced "536 MB" needs.@@ -942,11 +927,9 @@ const META_COLUMN = {const ROW_ACTIONS_CLASS ="mr-0.5 flex w-[38px] shrink-0 items-center justify-end -space-x-0.5 opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100 has-[[data-state=open]]:opacity-100 [@media(hover:none)]:opacity-100";-// Partial rows keep their buttons on screen. Everywhere else the gutter hides until the row is-// hovered because the row itself is the action -- click it and the model loads, so the menu is a-// secondary path. A partial cannot be loaded at all: the menu IS the row's only affordance, and-// hiding the one control that reaches a stalled multi-GB download behind a hover reads as the-// download having no controls at all.+// Partial rows keep their buttons on screen. Everywhere else the gutter hides until hover because+// the row itself is the action, but a partial cannot be loaded at all: the menu IS its only+// affordance, and hiding it reads as the stalled download having no controls.const ROW_ACTIONS_PINNED_CLASS = cn(ROW_ACTIONS_CLASS, "opacity-100");function ModelRow({@@ -1215,12 +1198,10 @@ function ModelRow({{aligned ? (<spanclassName={cn(- // Device leads the chip, Hub trails it. Both columns are fixed, so the choice is- // only where the column's slack falls: trailing it put the slack in FRONT of the- // chip, where it read as part of the gap to the modality mark and grew or shrank- // with the label -- 6.9px after a "217B", 19px after a "1B". Leading the chip- // leaves that gap as the cluster's own gap-1, the same 4px the quant chip keeps- // to the same mark, and the slack falls back toward the size instead.+ // Device leads the chip, Hub trails it. Both columns are fixed, so the choice is only where the+ // slack falls: trailing put it in FRONT of the chip, where it read as part of the gap to the+ // modality mark and grew with the label (6.9px after "217B", 19px after "1B"). Leading leaves that+ // gap as the cluster's own gap-1."flex shrink-0 items-center text-ui-10",alignMeta === "hub"? cn("justify-end", META_COLUMN.paramWide)@@ -1887,10 +1868,9 @@ function GgufVariantExpander({}).then((footprint) => {if (cancelled || !footprint) return;- // A checkpoint already on disk is not part of required_bytes, so nothing may be subtracted for- // it: subtracting drove the total to zero and hid a multi-GB companion set. Only a hub pick- // carries its checkpoint inside the total.- // expectedBytes stands in when the planner could not size it.+ // A checkpoint already on disk is not part of required_bytes, so nothing may be subtracted for it:+ // subtracting drove the total to zero and hid a multi-GB companion set. Only a hub pick carries+ // its checkpoint inside the total; expectedBytes stands in when the planner could not size it.const checkpoint = checkpointIsLocal? 0: footprint.checkpointBytes > 0@@ -2228,9 +2208,8 @@ function GgufVariantExpander({if (pinnedKeys.includes(pinKey(repoId, v.quant))) {togglePinnedQuant(repoId, v.quant);}- // Re-fetch this expander's variants so the deleted quant stops showing as- // downloaded while other cached quants remain.- // repo still has other cached quants.+ // Re-fetch this expander's variants so the deleted quant stops showing as downloaded while the+ // repo's other cached quants remain.setRefreshKey((key) => key + 1);},}@@ -2376,14 +2355,10 @@ let _localDirCache: LocalModelInfo[] = [];let _customFolderCache: LocalModelInfo[] = [];let _scanFoldersCache: ScanFolderInfo[] = [];-/** True when any on-device model (downloaded GGUF, cached repo, LM Studio, or- * custom-folder model) is known. Reads the module caches, which persist across- * popover mounts, so the selector can default to the On Device tab.- *- * Partials do not count. The cached lists carry them so they can be seen and- * removed, but a machine whose only cached row is a cancelled download has- * nothing to load, and opening on that tab shows one unusable row instead of- * the list that would get the user a model. */+/** True when any on-device model (downloaded GGUF, cached repo, LM Studio, or custom-folder model)+ * is known. Reads the module caches, which persist across popover mounts, so the selector can+ * default to the On Device tab. Partials do not count: a machine whose only cached row is a+ * cancelled download has nothing to load. */export function hasDownloadedModels(): boolean {return (_cachedGgufCache.some((c) => !c.partial) ||@@ -2616,14 +2591,12 @@ export function HubModelPicker({onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;resolveDownloadFootprint?: ModelDownloadFootprintResolver;onFoldersChange?: () => void;- /** Open the full Hub page to browse more models. */onBrowseHub?: () => void;onModelsChange?: (deletedModel?: DeletedModelRef) => void;onConfigure?: (id: string, meta: ModelSelectorChangeMeta) => void;deleteDisabled?: boolean;/** Section shown when not searching. Search spans all sections. */section?: "downloaded" | "recommended" | "connected";- /** Section toggle rendered under the search bar. */sectionToggle?: ReactNode;onEject?: () => void;/** Restrict results to a pipeline task; undefined = all tasks (the chat default). */@@ -3109,12 +3082,9 @@ export function HubModelPicker({void refreshInventoryIfOlderThan(INVENTORY_FRESHNESS_WINDOW_MS);}, [refreshInventoryIfOlderThan]);- // Hide downloaded models from the recommended list. Case-insensitive- // since the HF cache lowercases repo IDs.- // Complete downloads only. This set answers "can this id load right now": it decides- // isDownloaded on a search pick, which is what skips download staging, and it paints the- // on-disk dot. A partial is on disk but not loadable, so admitting one here would send a- // torn snapshot straight to the loader from the Hub and Recommended lists.+ // Hide downloaded models from the recommended list, case-insensitively since the HF cache+ // lowercases repo ids. Complete downloads only: this set answers "can this id load right now", so+ // admitting a partial would send a torn snapshot straight to the loader.const downloadedSet = useMemo(() =>new Set(@@ -4164,10 +4134,8 @@ export function HubModelPicker({);}, [sortedCachedModels, showHfSection, debouncedQuery, formatFilter]);- // Non-GGUF cached rows are not shown in chat-only mode, so the empty-state logic must use this- // or the picker can go blank. A task-scoped picker is exempt.- // Not visibleCachedModels, or the picker can go blank. A task-scoped picker (Images) is exempt:- // the image backend loads local diffusers/safetensors pipelines even on chat-only hosts.+ // Non-GGUF cached rows are hidden in chat-only mode, so the empty-state logic must use this or the+ // picker can go blank. A task-scoped picker is exempt: the image backend loads local pipelines.const visibleCachedModelRows = chatOnly && !task ? [] : visibleCachedModels;const visibleAdditionalOnDeviceModels = useMemo(() => {@@ -4432,7 +4400,6 @@ export function HubModelPicker({],);- // Recommended models that match the current search query.const filteredRecommendedIds = useMemo(() => {if (!showHfSection) return [];const q = normalizeForSearch(debouncedQuery.trim());@@ -4826,7 +4793,6 @@ export function HubModelPicker({},);- // Recompute the top/bottom edge fades from the scroll position.const updateListFades = useCallback((el: HTMLDivElement) => {const scrolled = el.scrollTop > 0;setListScrolled((prev) => (prev === scrolled ? prev : scrolled));@@ -4834,7 +4800,6 @@ export function HubModelPicker({setListMoreBelow((prev) => (prev === moreBelow ? prev : moreBelow));}, []);- // Keep the fades in sync when rows are added, removed, or filtered.useEffect(() => {const el = scrollRef.current;if (!el) return;@@ -4894,7 +4859,7 @@ export function HubModelPicker({scrollRef,]);- /** Handle clicking a model row — GGUF repos expand, others load directly. */+ /** Handle clicking a model row: GGUF repos expand, others load directly. */const handleModelClick = useCallback((id: string) => {if (isKnownGgufRepo(id)) {@@ -4961,7 +4926,6 @@ export function HubModelPicker({</TooltipContent></Tooltip>);- // Sort icon + selected label inside the trigger pill.const sortTriggerContent = (label: ReactNode) => (<span className="flex items-center gap-1"><HugeiconsIcon@@ -5019,7 +4983,6 @@ export function HubModelPicker({/>);- // Connected models grouped by provider, filtered by the shared search query.const connectedGroups = useMemo(() => {const needle = normalizeForSearch(debouncedQuery.trim());const byProvider = new Map<@@ -5249,18 +5212,11 @@ export function HubModelPicker({meta={`GGUF · ${formatBytes(variant.size_bytes)}`}quantChip={ggufQuantChipLabel(variant.quant)}partial={isPartial}- // No verdict to pass, so the mark takes its cautious wording:- // /api/models/gguf-variants builds models.models.GgufVariantDetail, which carries no- // partial_resumable. A sole-quant row is never partial anyway -- readSoleQuant only- // picks a clean quant -- so this mark is defensive to begin with.- // Only for models the llama.cpp path actually loads. The Images and- // Video pickers deliberately keep diffusion GGUFs listed, and those- // run on the diffusion planner with different runtime buffers, on a- // single torch device rather than the aggregate inference pool. The- // KV estimator has nothing to say about them, and when it returns- // unsized the bar falls back to the file size and draws a- // weights-only verdict anyway -- a confident number about the wrong- // runtime, which is the failure this bar exists to avoid.+ // No verdict to pass, so the mark takes its cautious wording: /api/models/gguf-variants carries no+ // partial_resumable, and a sole-quant row is never partial anyway. Only for models the llama.cpp+ // path loads: Images and Video keep diffusion GGUFs listed, and those run on the diffusion planner+ // with different runtime buffers on a single torch device, so the KV estimator falls back to the+ // file size and draws a confident number about the wrong runtime.memory={mediaPageForTask(c.task)? undefined@@ -6757,9 +6713,8 @@ export function HubModelPicker({id.toLowerCase(),)}capabilities={capsById.get(id)}- // Same meta the unfiltered Recommended row shows, so a model keeps its size- // chip when reached by typing.- // because it was reached by typing.+ // Same meta the unfiltered Recommended row shows, so a model keeps its size chip when reached by+ // typing.meta={isKnownGgufRepo(id)? (recommendedMeta.get(id)?.meta ?? "GGUF")diff --git a/studio/frontend/src/features/model-picker/components/numeric-value-input.tsx b/studio/frontend/src/features/model-picker/components/numeric-value-input.tsxindex 94067340fb4..4dc22d6ddb9 100644--- a/studio/frontend/src/features/model-picker/components/numeric-value-input.tsx+++ b/studio/frontend/src/features/model-picker/components/numeric-value-input.tsx@@ -185,13 +185,12 @@ export const NumericValueInput = forwardRef<lastBlurCommittedRef.current = null;} else {draftRef.current = String(final);- // Only bridge the still-stale parent value when the blur actually- // dispatched onChange. Otherwise the parent is already current and- // there is nothing to bridge; caching here would leave a stale pin- // that a later Reset or external edit (which doesn't change the- // displayed value) can never clear, so a following Load/Save would- // recreate the override Reset removed. Same test as the dispatch, so- // a click in the same turn as the blur cannot see them disagree.+ // Only bridge the still-stale parent value when the blur actually dispatched onChange.+ // Otherwise the parent is already current and there is nothing to bridge; caching here+ // would leave a stale pin that a later Reset or external edit (which doesn't change the+ // displayed value) can never clear, so a following Load/Save would recreate the+ // override Reset removed. Same test as the dispatch, so a click in the same turn as the+ // blur cannot see them disagree.lastBlurCommittedRef.current = isEdit(final) ? final : null;}}diff --git a/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts b/studio/frontend/src/features/model-picker/model-config/llama-extra-args.tsindex eae0ed79ecc..a1b99b3c2ac 100644--- a/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts+++ b/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts@@ -174,7 +174,6 @@ export function sanitizeStoredExtraArgs(kept.length > 0 &&extraArgFlagName(kept[kept.length - 1]) !== null) {- // The flag this value belonged to.kept.pop();}continue;@@ -372,7 +371,6 @@ export function parseExtraArgs(input: string): ExtraArgsParse {const quotedIndices = new Set<number>();let current = "";let started = false;- // Whether any part of the token being built came from inside quotes.let currentQuoted = false;let quote: '"' | "'" | null = null;@@ -786,7 +784,6 @@ export function diagnoseExtraArgs(// validate_extra_args refuses it outright, so saying so here is the difference between a red// line and a failed load. Two-value flags are allowed for.let pendingValues = 0;- // The flag those values are owed to, for the checks below.let pendingOwner: string | null = null;// A flag left waiting for its value. Reported only when the arity is known: the catalogue read// this build's own help, or it is the two-value flag whose arity needs no probe. Andiff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.tsindex 00fdf5294fe..9d0fc124bc0 100644--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts@@ -41,10 +41,10 @@ export interface PerModelConfig {/** Load a vision GGUF without its mmproj, freeing the projector's VRAM. */disableVision: boolean;chatTemplateOverride: string | null;- /** Pass-through llama-server argv tokens, appended after Unsloth's own flags. Three states:- * `undefined` means this copy never read the stored value, so a save leaves the server's- * alone (this is what kept CLI-set flags alive); `null` means the user cleared the box and- * must be sent as an explicit `[]`; a non-empty list is what to launch with. */+ /** Pass-through llama-server argv tokens, appended after Unsloth's own flags. Three states: `undefined` means+ * this copy never read the stored value, so a save leaves the server's alone (this is what kept CLI-set flags+ * alive); `null` means the user cleared the box and must be sent as an explicit `[]`; a non-empty list is what+ * to launch with. */llamaExtraArgs?: string[] | null;// GPU Memory controls (per-model, GGUF-only), optional so older blobs parse. Absent or null// selectedGpuIds means automatic. --tensor-split is not remembered: it follows the GPU set.@@ -78,9 +78,8 @@ export const DEFAULT_PER_MODEL_CONFIG: PerModelConfig = {export const N_PARALLEL_MIN = 1;export const N_PARALLEL_MAX = 64;-// Mirrors vram_budget_settings.py VRAM_FRACTION_MIN/MAX/DEFAULT as whole percent (the slider is-// integer). Server-wide, so these only bound the control; the value lives in-// /api/settings/vram-budget.+// Mirrors vram_budget_settings.py VRAM_FRACTION_MIN/MAX/DEFAULT as whole percent (the slider is integer).+// Server-wide, so these only bound the control; the value lives in /api/settings/vram-budget.export const VRAM_BUDGET_PERCENT_MIN = 80;export const VRAM_BUDGET_PERCENT_MAX = 100;export const VRAM_BUDGET_PERCENT_DEFAULT = 97;@@ -122,9 +121,8 @@ const NO_MLX_REASONS = new Set(["detection_failed",]);-/** Whether MLX will serve this model, and so whether MLX-only settings apply. Every non-GGUF- * model loads through MLX on a working Mac stack, so `!isGguf` alone would show these- * controls to CUDA users. */+/** Whether MLX will serve this model, and so whether MLX-only settings apply. Every non-GGUF model loads through+ * MLX on a working Mac stack, so `!isGguf` alone would show these controls to CUDA users. */export function isServedByMlx(isGguf: boolean,deviceType: string | null | undefined,@@ -137,13 +135,10 @@ export function isServedByMlx();}-/** Whether MLX serves the RESIDENT model.- *- * The platform cannot answer it alone: the worker picks NativeAudioBackend for a- * native-audio checkpoint before the MLX fast-path, so those load on Apple Silicon- * without MLX serving them. `loadedIsMlx` is the backend's own answer, and null there- * means nothing is loaded yet, where the platform is still the best available one.- */+/** Whether MLX serves the RESIDENT model. The platform cannot answer it alone: the worker picks+ * NativeAudioBackend for a native-audio checkpoint before the MLX fast-path, so those load on Apple Silicon+ * without MLX serving them. `loadedIsMlx` is the backend's own answer, and null there means nothing is loaded+ * yet, where the platform is still the best available one. */export function residentIsServedByMlx(isGguf: boolean,deviceType: string | null | undefined,@@ -166,13 +161,10 @@ export function presetLoadSettingNames(: "max seq length";}-/** Whether llama.cpp serves the active model.- *- * `loadedIsGguf` is the backend's own answer; the rest identify a GGUF that has not- * reported one yet. A context length is not among them -- MLX reports one too, so it- * says a model is loaded, not which backend loaded it. An external provider is excluded- * because its id keeps a `.gguf` suffix while the flag describes a local load.- */+/** Whether llama.cpp serves the active model. `loadedIsGguf` is the backend's own answer; the rest identify a+ * GGUF that has not reported one yet. A context length is not among them, since MLX reports one too, so it says+ * a model is loaded, not which backend loaded it. An external provider is excluded because its id keeps a+ * `.gguf` suffix while the flag describes a local load. */export function isServedByLlamaCpp(x: {loadedIsGguf?: boolean | null;activeGgufVariant?: string | null;@@ -193,13 +185,10 @@ export function isServedByLlamaCpp(x: {/** The store's record of the context window a load left behind.*- * A window counts when the backend that reported it sized one. MLX always does, so its- * `context_length` stands alone even with no trained window in the config. Transformers- * sizes nothing and echoes the requested max_seq_length, so without a native length it- * contributes no window.- *- * One constructor because the four move together: a window without the backend that- * produced it is what made a context length read as proof of a GGUF.+ * A window counts when the backend that reported it sized one. MLX always does, so its `context_length` stands+ * alone even with no trained window in the config. Transformers sizes nothing and echoes the requested+ * max_seq_length, so without a native length it contributes no window. One constructor because the four move+ * together: a window without the backend that produced it is what made a context length read as proof of a GGUF.*/export function loadedContextFields(resp: {is_gguf?: boolean;@@ -269,9 +258,8 @@ export const KV_CACHE_DTYPES = [export const MLX_KV_BITS: readonly number[] = [8, 6, 5, 4, 3, 2];const VALID_KV_CACHE_DTYPES = new Set<string>(KV_CACHE_DTYPES);-// llama-server's --load-mode enum in --help order. "auto" is the default: the UI shows it,-// storage keeps null and the backend emits no flag. Never sent verbatim; builds like-// b10360 reject "auto" as a value.+// llama-server's --load-mode enum in --help order. "auto" is the default: the UI shows it, storage keeps null and+// the backend emits no flag. Never sent verbatim; builds like b10360 reject "auto" as a value.export const LOAD_MODES = ["auto","none",@@ -350,9 +338,9 @@ const STORED_CONFIG_FIELDS = new Set(["selectedGpuIndexKind",]);-/** Keep only a list of strings, preserving the three states above. Anything that is not an- * array is "not loaded" (`undefined`), never "cleared": the flags a wipe would throw- * away are invisible in this panel until the row reads them. */+/** Keep only a list of strings, preserving the three states above. Anything that is not an array is "not loaded"+ * (`undefined`), never "cleared": the flags a wipe would throw away are invisible in this panel until the row+ * reads them. */function normalizeLlamaExtraArgs(value: unknown): string[] | null | undefined {if (value === null) {return null;@@ -491,14 +479,11 @@ export function normalizeMaxSeqLength(value: unknown): number | null {/** The context a saved record pins, whichever field it was written in.*- * MLX's pin moved into `customContextLength` beside llama.cpp's, while transformers- * keeps its own in `maxSeqLength` and a record written before the move still carries an- * MLX pin there. The same record is read on a host that serves it with a different- * backend, so every read has to honour both.- *- * A *saved* record only. `currentRuntimePerModelConfig` builds the same shape from the- * live store, where `maxSeqLength` is the length the model resolved to rather than one- * anybody chose; read that through `customContextLength` alone.+ * MLX's pin moved into `customContextLength` beside llama.cpp's, while transformers keeps its own in+ * `maxSeqLength` and a record written before the move still carries an MLX pin there. The same record is read on+ * a host that serves it with a different backend, so every read has to honour both. A *saved* record only:+ * `currentRuntimePerModelConfig` builds the same shape from the live store, where `maxSeqLength` is the length+ * the model resolved to rather than one anybody chose; read that through `customContextLength` alone.*/export function savedContextPin(config: {customContextLength?: number | null;@@ -507,12 +492,10 @@ export function savedContextPin(config: {return config.customContextLength ?? normalizeMaxSeqLength(config.maxSeqLength ?? null);}-/** The patch that pins a context for a non-GGUF target, on the backend serving it.- *- * An edit leaves a pin in exactly one field, clearing whichever the record arrived with:- * a record holding both loads at a different length depending on who asked -- the picker- * resolves `customContextLength` first, the API's auto-switch load `maxSeqLength`.- */+/** The patch that pins a context for a non-GGUF target, on the backend serving it. An edit leaves a pin in+ * exactly one field, clearing whichever the record arrived with: a record holding both loads at a different+ * length depending on who asked, since the picker resolves `customContextLength` first and the API's+ * auto-switch load `maxSeqLength`. */export function contextPinPatch(value: number, isMlx: boolean): Partial<PerModelConfig> {// Held to what a load may ask for, but not rounded to the control's step: a pin taken// from a resolved window need not sit on that grid.@@ -560,15 +543,15 @@ function loadAdvancedSettingsOpen(): boolean | null {}}-// Set only when a write is refused, so the switch keeps working with storage disabled or-// full. Cleared by the next write that sticks. `stored` is what storage held then, the-// one signal that tells a later write by someone else apart.+// Set only when a write is refused, so the switch keeps working with storage disabled or full. Cleared by the+// next write that sticks. `stored` is what storage held then, the one signal that tells a later write by someone+// else apart.let unpersisted: { open: boolean; stored: boolean | null } | null = null;const advancedOpenListeners = new Set<() => void>();-/** Null until the switch is used, so an untouched panel may open the section for a model with- * non-default advanced values. Read straight from storage, not cached: a write from- * another tab while every panel was unmounted has no listener and no replayed event. */+/** Null until the switch is used, so an untouched panel may open the section for a model with non-default+ * advanced values. Read straight from storage, not cached: a write from another tab while every panel was+ * unmounted has no listener and no replayed event. */export function readAdvancedSettingsOpen(): boolean | null {const stored = loadAdvancedSettingsOpen();if (!unpersisted) {@@ -997,10 +980,10 @@ function normalize(raw: unknown): PerModelConfig {function toStoredConfig(config: PerModelConfig): StoredPerModelConfig {const normalized = normalize(config);- // Stamped with the OLDEST version that still understands every field present, so a record an- // older client can safely rewrite stays in its reach. Only a TRUE disableVision needs v4:- // false is what a pre-vision client reconstructs anyway, and stamping every record v4- // would put the whole store out of reach. The tuning group follows the same rule.+ // Stamped with the OLDEST version that still understands every field present, so a record an older client can+ // safely rewrite stays in its reach. Only a TRUE disableVision needs v4: false is what a pre-vision client+ // reconstructs anyway, and stamping every record v4 would put the whole store out of reach. The tuning group+ // follows the same rule.const hasServerTuning =normalized.loadMode != null ||normalized.specDraftCacheDtype != null ||@@ -1165,9 +1148,9 @@ export function isDefaultConfig(config: PerModelConfig): boolean {config.nParallel == null &&config.nBatch == null &&config.nUbatch == null &&- // The tuning group, for the same reason as the arguments below: savePerModelConfig deletes- // an entry it judges default, so a config changing only these was dropped on the way to- // storage. Compared against null, not truth: 0 checkpoints and a 0 or -1 cache are values.+ // The tuning group, for the same reason as the arguments below: savePerModelConfig deletes an entry it judges+ // default, so a config changing only these was dropped on the way to storage. Compared against null, not truth:+ // 0 checkpoints and a 0 or -1 cache are values.(config.specDraftCacheDtype ?? null) === null &&(config.loadMode ?? null) === null &&config.ctxCheckpoints == null &&@@ -1199,9 +1182,8 @@ export function savePerModelConfig(modelId: string,ggufVariant: string | null | undefined,config: PerModelConfig,- /** Receives models dropped to stay inside the storage budget. Eviction is silent and still- * reports success, so without this their server overrides would keep applying with- * nothing in the UI able to forget them. */+ /** Receives models dropped to stay inside the storage budget. Eviction is silent and still reports success, so+ * without this their server overrides would keep applying with nothing in the UI able to forget them. */evicted?: { modelId: string; ggufVariant: string | null }[],): boolean {if (@@ -1289,10 +1271,8 @@ export function deletePerModelConfig(return writeMap(map);}-/**- * Every stored record an override key names. Matched, not split: a colon is legal in- * a path, and two records can spell one key.- */+/** Every stored record an override key names. Matched, not split: a colon is legal in a path, and two records+ * can spell one key. */function findModelOverrideKeyOwners(overrideKey: string,): { modelId: string; ggufVariant: string | null }[] {@@ -1346,13 +1326,12 @@ export function deletePerModelConfigsForOverrideKeys(/*** Move a saved config from an id an older release keyed it by onto the current one.*-* A repo cached outside the active HF cache is now keyed by its repo id (what the picker and-* auto-switch index use); it used to be keyed by the snapshot path it loads from. Nothing else-* migrates that, so without this the model reads as never remembered after an upgrade.-*-* The key is renamed in one write rather than saved then deleted: holding both copies puts an-* already-full map over budget, and the save then silently evicts an unrelated model whose-* server override outlives anything the UI could forget. A rename cannot grow the entry count.+* A repo cached outside the active HF cache is now keyed by its repo id (what the picker and auto-switch index+* use); it used to be keyed by the snapshot path it loads from. Nothing else migrates that, so without this the+* model reads as never remembered after an upgrade. The key is renamed in one write rather than saved then+* deleted: holding both copies puts an already-full map over budget, and the save then silently evicts an+* unrelated model whose server override outlives anything the UI could forget. A rename cannot grow the entry+* count.*/export function adoptLegacyConfigKey(modelId: string,@@ -1390,9 +1369,8 @@ export function adoptLegacyConfigKey(const [key] = storageKeysForModelVariant(modelId, ggufVariant);map[key] = toStoredConfig(legacy);}- // Only the key strings change length, and a repo id is normally shorter than the snapshot- // path. If it is not and that tips the map past its byte cap, leave storage as it was:- // eviction is not undoable.+ // Only the key strings change length, and a repo id is normally shorter than the snapshot path. If it is not and+ // that tips the map past its byte cap, leave storage as it was: eviction is not undoable.const bytesAfter = serializedMapSize(map);if (bytesAfter > bytesBefore &&@@ -1430,11 +1408,10 @@ export function resolveInitialConfig(return { config: { ...DEFAULT_PER_MODEL_CONFIG }, remembered: false };}-/** Remembered settings for the identifier /api/inference/status reports as loaded. An API- * auto-switch hands the loader a concrete snapshot path while settings are keyed by repo- * id, so reading the raw identifier reports the resident model as unremembered and blanks- * a control it is running with. Only a namespaced collapse is adopted, per- * residentModelIdMatches. */+/** Remembered settings for the identifier /api/inference/status reports as loaded. An API auto-switch hands the+ * loader a concrete snapshot path while settings are keyed by repo id, so reading the raw identifier reports the+ * resident model as unremembered and blanks a control it is running with. Only a namespaced collapse is adopted,+ * per residentModelIdMatches. */export function resolveResidentInitialConfig(modelId: string,ggufVariant?: string | null,diff --git a/studio/frontend/src/features/native-intents/store.ts b/studio/frontend/src/features/native-intents/store.tsindex 1f4332716a1..cdc5b9b5945 100644--- a/studio/frontend/src/features/native-intents/store.ts+++ b/studio/frontend/src/features/native-intents/store.ts@@ -38,11 +38,9 @@ interface NativeIntentState {// keyed: until the intents land there is no settled target, and the OS drop// went to the window, which has one composer to send from.registeringImageDrops: number;- // Same for audio: cover the register-and-read window or a fast submit- // goes out without the clip.+ // Same for audio: cover the register-and-read window or a fast submit goes out without the clip.registeringAudioDrops: number;- // Same for video: one clip is a long read, and a submit in that window would- // go out without it.+ // Same for video: one clip is a long read, and a submit in that window would go out without it.registeringVideoDrops: number;// Bumped, per chat, when a drop fails before it reaches a queue. The composer// watches its own key so a failure elsewhere cannot cancel its parked send.@@ -52,8 +50,7 @@ interface NativeIntentState {// Owner of queued composer-file batches, by composer identity. A remount means// the outgoing instance cannot hand the batches over itself, so it leaves a note.imageDropOwners: Record<string, string>;- // Same for audio: a new chat re-keys mid-read, so the clip needs a note- // to follow the composer.+ // Same for audio: a new chat re-keys mid-read, so the clip needs a note to follow the composer.audioDropOwners: Record<string, string>;videoDropOwners: Record<string, string>;addIntent: (intent: NativeIntent) => void;diff --git a/studio/frontend/src/features/native-intents/use-native-readiness.ts b/studio/frontend/src/features/native-intents/use-native-readiness.tsindex 9debb055d7e..d3a10a1ce00 100644--- a/studio/frontend/src/features/native-intents/use-native-readiness.ts+++ b/studio/frontend/src/features/native-intents/use-native-readiness.ts@@ -26,10 +26,9 @@ export function useNativePathLeasesSupported(): boolean {check(5000);return;}- // The health bit says the backend holds a key, not that it holds- // OURS. A survivor adopted from a dead previous app has one of its- // own, so the grant would fail on the signature instead. Only the- // app knows which backend it spawned.+ // The health bit says the backend holds a key, not that it holds OURS. A survivor+ // adopted from a dead previous app has one of its own, so the grant would fail on the+ // signature instead. Only the app knows which backend it spawned.const { invoke } = await import("@tauri-apps/api/core");const usable = await invoke<boolean>("native_path_leases_usable");if (disposed) return;diff --git a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts b/studio/frontend/src/features/profile/hooks/use-personalization-sync.tsindex bdbc0873e37..55ccfaf111d 100644--- a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts+++ b/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts@@ -35,12 +35,11 @@ import type { AvatarShape } from "../stores/user-profile-store";const PUSH_DEBOUNCE_MS = 800;-// Version 2 payloads store the language preference ("auto" or a pinned-// locale). Version 1 always serialized the resolved locale, so its "en" is-// usually the old default rather than an explicit pick.-// Version 3 migrates untouched sidebar layouts to keep Video under More.-// Version 4 pins Video under Images. Without this bump a synced profile-// rehydrates its stored layout over the local migration.+// Version 2 payloads store the language preference ("auto" or a pinned locale). Version 1 always+// serialized the resolved locale, so its "en" is usually the old default rather than an explicit+// pick. Version 3 migrates untouched sidebar layouts to keep Video under More. Version 4 pins Video+// under Images. Without this bump a synced profile rehydrates its stored layout over the local+// migration.const PERSONALIZATION_VERSION = 4;type ProfileSnapshot = {@@ -146,10 +145,9 @@ function serialized(data: PersonalizationWrite): string {return JSON.stringify(data);}-// Version 1 clients wrote language on every save, so a legacy "en" usually-// means the user never picked a language. Map it to auto; explicit picks of-// other locales (the old default was English) are kept. Version 2 payloads-// are trusted verbatim, so a deliberate English pick stays pinned.+// Version 1 clients wrote language on every save, so a legacy "en" usually means the user never+// picked a language. Map it to auto; explicit picks of other locales (the old default was English)+// are kept. Version 2 payloads are trusted verbatim, so a deliberate English pick stays pinned.export function remoteLanguagePreference(version: unknown,language: unknown,@@ -239,11 +237,10 @@ export function usePersonalizationSync(enabled: boolean): void {const remote = await loadPersonalization();if (cancelled) return;if (remote.saved) {- // Legacy records predating a field come back server-defaulted. Keep- // the local value and re-push it (lastSaved below records the remote- // default so the push detects the diff) rather than treating the- // default as an explicit remote choice. A record that actually stored- // the field reports <field>Saved=true and still wins.+ // Legacy records predating a field come back server-defaulted. Keep the local value and+ // re-push it (lastSaved below records the remote default so the push detects the diff)+ // rather than treating the default as an explicit remote choice. A record that actually+ // stored the field reports <field>Saved=true and still wins.const localGreeting =useUserProfileStore.getState().showGreetingSloth;const remoteGreeting = remote.profile.showGreetingSloth !== false;@@ -302,11 +299,10 @@ export function usePersonalizationSync(enabled: boolean): void {if (nextLanguage !== latestLanguageRef.current) {const localeResult = await setLocale(nextLanguage, {signal: localeHydrationController.signal,- // A catalog that will not load must not decide whether the rest of- // personalization syncs. Adopting the preference and rendering- // English keeps the local preference equal to the server's, so the- // baseline below is honest and the debounced push cannot overwrite- // the remote language with a stale local one.+ // A catalog that will not load must not decide whether the rest of personalization+ // syncs. Adopting the preference and rendering English keeps the local preference+ // equal to the server's, so the baseline below is honest and the debounced push+ // cannot overwrite the remote language with a stale local one.adoptOnFailure: true,// And a catalog request that is accepted but never completes// must not hold hydration, and with it every save for the rest@@ -314,12 +310,11 @@ export function usePersonalizationSync(enabled: boolean): void {timeoutMs: LOCALE_INITIALIZATION_TIMEOUT_MS,});if (cancelled) return;- // "superseded" means a newer request took over, so this language is- // no longer the one in effect and must not be recorded as the- // synchronized baseline: the newer request may itself have failed,- // leaving the local preference on neither value. Hydration still has- // to finish, or every later save stays paused for the session; an- // empty baseline makes the next push send whatever is in effect.+ // "superseded" means a newer request took over, so this language is no longer the one+ // in effect and must not be recorded as the synchronized baseline: the newer request+ // may itself have failed, leaving the local preference on neither value. Hydration+ // still has to finish, or every later save stays paused for the session; an empty+ // baseline makes the next push send whatever is in effect.if (localeResult === "cancelled") return;if (localeResult === "superseded") {if (authGenerationRef.current === generation) {@@ -329,9 +324,8 @@ export function usePersonalizationSync(enabled: boolean): void {return;}}- // lastSaved records what the server actually has (server-side defaults- // for legacy fields) so the debounced push re-uploads preserved local- // values.+ // lastSaved records what the server actually has (server-side defaults for legacy fields)+ // so the debounced push re-uploads preserved local values.lastSavedRef.current = serialized({...payload({ ...nextProfile, showGreetingSloth: remoteGreeting },diff --git a/studio/frontend/src/features/profile/sloth-avatars.ts b/studio/frontend/src/features/profile/sloth-avatars.tsindex b6ac132377e..47531957ccc 100644--- a/studio/frontend/src/features/profile/sloth-avatars.ts+++ b/studio/frontend/src/features/profile/sloth-avatars.ts@@ -1,16 +1,13 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Curated list of sloth emoji stickers offered as profile pictures.-//-// The full `public/Sloth emojis` folder has ~38 PNGs, but many are non-square-// or carry heavy whitespace on one or more edges, which crops badly inside the-// round avatar frame. This list is the subset that is (a) effectively square-// (aspect ratio within ~10% of 1:1) and (b) low-whitespace on every edge, so-// each one fills the avatar circle cleanly. Exact duplicates are de-duped.-//-// Paths are relative to the public folder; resolve with `publicAssetUrl(...)`-// before using as an <img> src so spaces and subpath deploys are handled.+// Curated list of sloth emoji stickers offered as profile pictures. The full `public/Sloth emojis`+// folder has ~38 PNGs, but many are non-square or carry heavy whitespace on one or more edges,+// which crops badly inside the round avatar frame. This list is the subset that is (a) effectively+// square (aspect ratio within ~10% of 1:1) and (b) low-whitespace on every edge, so each one fills+// the avatar circle cleanly. Exact duplicates are de-duped. Paths are relative to the public+// folder; resolve with `publicAssetUrl(...)` before using as an <img> src so spaces and subpath+// deploys are handled.export const SLOTH_AVATARS: readonly string[] = ["Sloth emojis/large sloth yay.png","Sloth emojis/large sloth heart.png",diff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.tsindex 672a4911a22..fa43f948599 100644--- a/studio/frontend/src/features/rag/api/rag-api.ts+++ b/studio/frontend/src/features/rag/api/rag-api.ts@@ -211,9 +211,8 @@ export function uploadProjectDocument();}-// Cached "does this project have indexed sources?" probe so the chat adapter can-// auto-scope project chats without a round trip per message. The sources panel-// invalidates on upload/delete.+// Cached "does this project have indexed sources?" probe so the chat adapter can auto-scope project+// chats without a round trip per message. The sources panel invalidates on upload/delete.const projectSourcesCache = new Map<string, { has: boolean; at: number }>();const PROJECT_SOURCES_TTL_MS = 30_000;@@ -799,9 +798,8 @@ export function getPreviewTarget();}-// Signed URL (no bearer) so pdf.js can issue Range requests. Absolute because-// consumers bypass authFetch, and a relative path under Tauri resolves against-// the webview origin.+// Signed URL (no bearer) so pdf.js can issue Range requests. Absolute because consumers bypass+// authFetch, and a relative path under Tauri resolves against the webview origin.export async function getDocumentFileUrl(documentId: string): Promise<string> {const data = await ragRequest<{ url: string }>(`/documents/${encodeURIComponent(documentId)}/file-url`,diff --git a/studio/frontend/src/features/rag/api/rag-availability.ts b/studio/frontend/src/features/rag/api/rag-availability.tsindex 01ad1c751f5..a70de0348e6 100644--- a/studio/frontend/src/features/rag/api/rag-availability.ts+++ b/studio/frontend/src/features/rag/api/rag-availability.ts@@ -5,19 +5,16 @@ import { create } from "zustand";import { formatFastApiDetail } from "@/lib/format-fastapi-error";-// Whether RAG can run on this host at all, as reported by the backend.-//-// A machine where sqlite-vec imports but its native library will not load has a working-// server and a dead RAG engine. The router says so rather than raising: GET-// /api/rag/knowledge-bases answers 200 with an availability marker beside the (empty)-// list, and every other RAG endpoint answers 503 with the same reason. Without this-// store both readings are dropped on the floor and the Knowledge bases dialog looks-// like an empty store, offering a Create button that can only 503.-//-// Read it the way the platform store in config/env.ts is read: `isUnavailable()`, never-// `available` on its own. Everything here is optimistic until the backend has actually-// answered, because graying a feature out on a guess is indistinguishable from a-// measured "unsupported", and a backend that predates the marker never answers at all.+// Whether RAG can run on this host at all, as reported by the backend. A machine where sqlite-vec+// imports but its native library will not load has a working server and a dead RAG engine. The+// router says so rather than raising: GET /api/rag/knowledge-bases answers 200 with an availability+// marker beside the (empty) list, and every other RAG endpoint answers 503 with the same reason.+// Without this store both readings are dropped on the floor and the Knowledge bases dialog looks+// like an empty store, offering a Create button that can only 503. Read it the way the platform+// store in config/env.ts is read: `isUnavailable()`, never `available` on its own. Everything here+// is optimistic until the backend has actually answered, because graying a feature out on a guess+// is indistinguishable from a measured "unsupported", and a backend that predates the marker never+// answers at all./** The shape the KB list carries; older backends send neither field. */interface RagAvailabilityMarker {@@ -29,16 +26,14 @@ interface RagAvailabilityMarker {const DEFAULT_UNAVAILABLE_REASON ="RAG is unavailable on this machine: the sqlite-vec extension could not be loaded.";-// What routes/rag.py sends with its 503 ("RAG is unavailable: the sqlite-vec extension-// could not be loaded."). Matched on the extension name rather than the whole sentence,-// so a reworded detail still reads as the backend's verdict while a proxy's "Service-// Temporarily Unavailable" does not.-//-// Deliberately NOT "rag is unavailable" as well. That phrase is the loose half of the-// pair: anything RAG-aware in front of the backend could emit it without meaning the-// extension, and matching either fragment would then persist a capability verdict from a-// transient outage. "sqlite-vec" is a package name, so nothing upstream says it by-// accident, and the whole capability being gated here is exactly that extension.+// What routes/rag.py sends with its 503 ("RAG is unavailable: the sqlite-vec extension could not be+// loaded."). Matched on the extension name rather than the whole sentence, so a reworded detail+// still reads as the backend's verdict while a proxy's "Service Temporarily Unavailable" does not.+// Deliberately NOT "rag is unavailable" as well. That phrase is the loose half of the pair:+// anything RAG-aware in front of the backend could emit it without meaning the extension, and+// matching either fragment would then persist a capability verdict from a transient outage.+// "sqlite-vec" is a package name, so nothing upstream says it by accident, and the whole capability+// being gated here is exactly that extension.const RAG_UNAVAILABLE_MARKERS = ["sqlite-vec"];/** True only for a 503 body the RAG router itself produced. */diff --git a/studio/frontend/src/features/rag/api/save-markdown-source.ts b/studio/frontend/src/features/rag/api/save-markdown-source.tsindex e9381c3afa9..243f97557bf 100644--- a/studio/frontend/src/features/rag/api/save-markdown-source.ts+++ b/studio/frontend/src/features/rag/api/save-markdown-source.ts@@ -56,9 +56,8 @@ export function projectSourceFileName(title: string): string {)// Windows drops a trailing period or space, so never send one..replace(/[\s.]+$/, "");- // The backend collapses everything outside [A-Za-z0-9._-] to "_", so a title- // with no ASCII word character at all would be listed as "_.md". A generic- // name at least reads as one.+ // The backend collapses everything outside [A-Za-z0-9._-] to "_", so a title with no ASCII word+ // character at all would be listed as "_.md". A generic name at least reads as one.if (!/[A-Za-z0-9]/.test(stem)) return "chat.md";// A device name stays reserved through any extension, and Windows reads it as// the part before the *first* dot, so break the name there.@@ -114,9 +113,8 @@ export async function saveMarkdownAsProjectSource(): Promise<boolean> {const filename = projectSourceFileName(title);const file = new File([markdown], filename, { type: "text/markdown" });- // Invalidate the sources probe before the upload as well as after it (the- // announce below): a chat sent mid-upload must not cache "no sources" for the- // probe's TTL.+ // Invalidate the sources probe before the upload as well as after it (the announce below): a chat+ // sent mid-upload must not cache "no sources" for the probe's TTL.invalidateProjectSources(projectId);try {const result = await uploadProjectDocument(projectId, file);diff --git a/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx b/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsxindex 6e93a113f80..5b8df08b1bc 100644--- a/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx+++ b/studio/frontend/src/features/rag/components/knowledge-base-composer-button.tsx@@ -25,9 +25,8 @@ import { listKnowledgeBases } from "../api/rag-api";import type { KnowledgeBase } from "../types/rag";import { KnowledgeBaseDialog } from "./knowledge-base-dialog";-// Matches the Thinking/MCP pill chevron.-// Picks the retrieval source. Shown whenever retrieval is on; dims but stays-// interactive (so it can be turned off) while the loaded model can't run it.+// Matches the Thinking/MCP pill chevron. Picks the retrieval source. Shown whenever retrieval is+// on; dims but stays interactive (so it can be turned off) while the loaded model can't run it.export function KnowledgeBaseComposerButton({side = "bottom",}: {diff --git a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx b/studio/frontend/src/features/rag/components/project-source-dropzone.tsxindex 5935b847b15..0f2c06d0de0 100644--- a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx+++ b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx@@ -318,9 +318,8 @@ export function ProjectSourceDropzone({rows can carry their own remove buttons. */}<divref={nativeDropRef}- // preventDefault runs even while disabled: nothing else on the page- // cancels a file drop, so the browser would navigate to the file and- // kill the uploads in flight.+ // preventDefault runs even while disabled: nothing else on the page cancels a file drop, so+ // the browser would navigate to the file and kill the uploads in flight.onDragEnter={(e) => {e.preventDefault();if (disabled) return;diff --git a/studio/frontend/src/features/rag/components/project-sources-panel.tsx b/studio/frontend/src/features/rag/components/project-sources-panel.tsxindex 02ed603f909..912e1873dfd 100644--- a/studio/frontend/src/features/rag/components/project-sources-panel.tsx+++ b/studio/frontend/src/features/rag/components/project-sources-panel.tsx@@ -82,10 +82,9 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {void refresh({ quiet: true });}, [projectId, refresh]);- // External mutators (sidebar/thread saves, deletes elsewhere) announce when- // they are done; refresh the mounted list so a source saved from a chat shows- // up here without a remount. The list only polls while a row it already knows- // is indexing, so nothing else would ever fetch it.+ // External mutators (sidebar/thread saves, deletes elsewhere) announce when they are done;+ // refresh the mounted list so a source saved from a chat shows up here without a remount. The+ // list only polls while a row it already knows is indexing, so nothing else would ever fetch it.useEffect(() =>subscribeProjectSourcesUpdated(projectId, () => {diff --git a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx b/studio/frontend/src/features/rag/components/thread-documents-bar.tsxindex 984bb40bf5f..b4c2d2b19c1 100644--- a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx+++ b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx@@ -374,9 +374,8 @@ export function ThreadDocumentsBar({initPromiseRef.current = null;}, [threadId]);- // An abandoned composer leaves its choice under the pending key, where the- // next new chat would claim it. Adoption removes the key, so this drops only- // what nobody claimed.+ // An abandoned composer leaves its choice under the pending key, where the next new chat would+ // claim it. Adoption removes the key, so this drops only what nobody claimed.useEffect(() => () =>useChatRuntimeStore.getState().clearPendingProjectAttachmentTarget(),@@ -444,14 +443,13 @@ export function ThreadDocumentsBar({projectLister,);- // Tell the composer whether any doc is still indexing, so it can hold a queued- // send until retrieval covers them (Composer.enqueueSend). For KB / RAG-off scope- // is null, so both lists are empty and this reads false.- // From the hooks, not the rows: work started in the Sources panel is in flight- // before either instance has a row for it, and a job already running on a- // reopened project arrives with the first list, so hold until that lands.- // Both scopes hold on their first list, for the same reason: reopening a chat- // whose own attachment was still indexing lists nothing until it lands either.+ // Tell the composer whether any doc is still indexing, so it can hold a queued send until+ // retrieval covers them (Composer.enqueueSend). For KB / RAG-off scope is null, so both lists are+ // empty and this reads false. From the hooks, not the rows: work started in the Sources panel is+ // in flight before either instance has a row for it, and a job already running on a reopened+ // project arrives with the first list, so hold until that lands. Both scopes hold on their first+ // list, for the same reason: reopening a chat whose own attachment was still indexing lists+ // nothing until it lands either.const hasIndexing =threadIndexing || threadListLoading || projectIndexing || projectListLoading;useEffect(() => {@@ -607,10 +605,9 @@ export function ThreadDocumentsBar({if (ragEnabled && ragSource.type === "kb") {return <KnowledgeBaseSourceChip kbId={ragSource.kbId} />;}- // Project sources retrieve whether the Docs pill is on or not (chat-adapter's- // projectRagEnabled), so list them either way rather than letting the model- // answer from files the user cannot see. The attach controls stay behind the- // pill: with it off, thread scope is inert.+ // Project sources retrieve whether the Docs pill is on or not (chat-adapter's projectRagEnabled),+ // so list them either way rather than letting the model answer from files the user cannot see.+ // The attach controls stay behind the pill: with it off, thread scope is inert.if (!ragEnabled) {return projectDocuments.length > 0 ? (<InheritedProjectSources documents={projectDocuments} />diff --git a/studio/frontend/src/features/rag/components/use-linked-folders.ts b/studio/frontend/src/features/rag/components/use-linked-folders.tsindex 5cc70884e9c..cb8b9293e16 100644--- a/studio/frontend/src/features/rag/components/use-linked-folders.ts+++ b/studio/frontend/src/features/rag/components/use-linked-folders.ts@@ -309,10 +309,9 @@ export function useLinkedFolders(async (folderId: string, mode: "sync" | "rebuild") => {const operationScopeKey = scopeKey;try {- // Inside the request's lease and before the scope guard: the job runs on- // the project it started for whatever this hook shows, and returning- // without a watcher drops that count to zero mid-sync. Deduped, so- // trackJob's own call is a no-op.+ // Inside the request's lease and before the scope guard: the job runs on the project it+ // started for whatever this hook shows, and returning without a watcher drops that count to+ // zero mid-sync. Deduped, so trackJob's own call is a no-op.const { job } = await withProjectWork(async () => {const started =mode === "rebuild"diff --git a/studio/frontend/src/features/rag/components/use-rag-documents.ts b/studio/frontend/src/features/rag/components/use-rag-documents.tsindex e2c10cbb7a4..89a0338278c 100644--- a/studio/frontend/src/features/rag/components/use-rag-documents.ts+++ b/studio/frontend/src/features/rag/components/use-rag-documents.ts@@ -341,8 +341,7 @@ export function useRagDocuments(try {for (let attempt = 0; attempt < REFRESH_RETRIES; attempt += 1) {const last = attempt === REFRESH_RETRIES - 1;- // True for a request that published, and for one a newer request has- // already outranked.+ // True for a request that published, and for one a newer request has already outranked.if (await refresh({ quiet: opts?.quiet, silentErrors: !last })) return;if (last) break;await new Promise((resolve) =>@@ -389,10 +388,9 @@ export function useRagDocuments(? loadProjectSources(scope.projectId): refresh());} else {- // Nothing is coming for the scope just dropped, and the request that- // was is now behind the sequence, so it will not clear these itself.- // Left set, the composer reads the list as still unknown and holds- // every send.+ // Nothing is coming for the scope just dropped, and the request that was is now behind the+ // sequence, so it will not clear these itself. Left set, the composer reads the list as+ // still unknown and holds every send.refreshInFlight.current = false;// eslint-disable-next-line react-hooks/set-state-in-effectsetLoading(false);@@ -412,12 +410,11 @@ export function useRagDocuments(// eslint-disable-next-line react-hooks/exhaustive-deps}, [scopeKey]);- // Safety net: a big upload opens one SSE stream per doc, but HTTP/1.1 caps- // concurrent connections, so streams past the cap may never deliver a terminal- // frame and leave a chip spinning. While anything is indexing, reconcile against- // the document list (one request covers every doc) so chips always resolve.- // Work on this project running elsewhere: an upload from the other instance,- // or a folder sync. Neither has a row here until it lands.+ // Safety net: a big upload opens one SSE stream per doc, but HTTP/1.1 caps concurrent+ // connections, so streams past the cap may never deliver a terminal frame and leave a chip+ // spinning. While anything is indexing, reconcile against the document list (one request covers+ // every doc) so chips always resolve. Work on this project running elsewhere: an upload from the+ // other instance, or a folder sync. Neither has a row here until it lands.const [workElsewhere, setWorkElsewhere] = useState(0);const workScopeId = scope?.type === "project" ? scope.projectId : null;useEffect(() => {@@ -453,10 +450,9 @@ export function useRagDocuments(documents.some((d) => d.status === "pending" || d.status === "running");useEffect(() => {if (!scopeKey || !hasIndexing) return;- // Skip a tick while one is still out. Starting another would retire it- // through the sequence gate, and a list slower than the interval would- // then never publish: the row this is watching never reaches completed and- // a queued send waits forever.+ // Skip a tick while one is still out. Starting another would retire it through the sequence+ // gate, and a list slower than the interval would then never publish: the row this is watching+ // never reaches completed and a queued send waits forever.const id = setInterval(() => {if (!refreshInFlight.current) {void refresh({ quiet: true });@@ -558,9 +554,8 @@ export function useRagDocuments([trackJob],);- // `overrideScope` lets a caller pass a freshly-resolved scope (or a promise of- // one), since the thread bar's id is still null on the first click; falls back to- // the hook scope.+ // `overrideScope` lets a caller pass a freshly-resolved scope (or a promise of one), since the+ // thread bar's id is still null on the first click; falls back to the hook scope.const upload = useCallback(async (files: FileList | File[] | RagUploadItem[],@@ -577,10 +572,9 @@ export function useRagDocuments(// job tracking and optimistic chips alone.uploadInFlightRef.current = true;setUploading(true);- // Published before the first await so the other instance gates from the- // moment the upload starts, not once the bytes are in.- // The composer passes its project scope explicitly, since the hook's own- // can still be null on the render that starts the upload.+ // Published before the first await so the other instance gates from the moment the upload+ // starts, not once the bytes are in. The composer passes its project scope explicitly, since+ // the hook's own can still be null on the render that starts the upload.const knownScope =overrideScope instanceof Promise || typeof overrideScope === "function"? nulldiff --git a/studio/frontend/src/features/rag/components/vision-overrides.ts b/studio/frontend/src/features/rag/components/vision-overrides.tsindex f2f1f36b6de..3fa0fc7cc89 100644--- a/studio/frontend/src/features/rag/components/vision-overrides.ts+++ b/studio/frontend/src/features/rag/components/vision-overrides.ts@@ -7,12 +7,11 @@ import {useChatRuntimeStore,} from "@/features/chat";-// Hydration is a network round trip with no deadline of its own: authFetch sets-// no AbortSignal, so a wedged or unreachable server leaves the promise pending-// for as long as the socket does. Uploads used to read these overrides-// synchronously, so waiting forever would be a new way for a drop to hang with-// nothing on screen. Bound it and take the local values, the way a blocked-// localStorage already falls through to the backend defaults.+// Hydration is a network round trip with no deadline of its own: authFetch sets no AbortSignal, so+// a wedged or unreachable server leaves the promise pending for as long as the socket does. Uploads+// used to read these overrides synchronously, so waiting forever would be a new way for a drop to+// hang with nothing on screen. Bound it and take the local values, the way a blocked localStorage+// already falls through to the backend defaults.const HYDRATION_WAIT_MS = 8_000;function wait(ms: number): Promise<void> {@@ -24,9 +23,8 @@ function hasLocal(key: string): boolean {try {return window.localStorage.getItem(key) !== null;} catch {- // Storage can be blocked outright (sandboxed context). These overrides are- // optional, so fall back to the backend defaults rather than failing the- // upload that asked for them.+ // Storage can be blocked outright (sandboxed context). These overrides are optional, so fall+ // back to the backend defaults rather than failing the upload that asked for them.return false;}}diff --git a/studio/frontend/src/features/recipe-studio/components/inline/inline-model.tsx b/studio/frontend/src/features/recipe-studio/components/inline/inline-model.tsxindex a678dad9a83..7b47a4ad53d 100644--- a/studio/frontend/src/features/recipe-studio/components/inline/inline-model.tsx+++ b/studio/frontend/src/features/recipe-studio/components/inline/inline-model.tsx@@ -56,9 +56,8 @@ export function InlineModel(props: InlineModelProps): ReactElement {);}- // model_config branch: mirror the dialog path's local-aware provider sync so- // inline edits clear stale local-only metadata without synthesizing the- // legacy "local" placeholder.+ // model_config branch: mirror the dialog path's local-aware provider sync so inline edits clear+ // stale local-only metadata without synthesizing the legacy "local" placeholder.const localNames = props.localProviderNames ?? new Set<string>();const modelConfig = props.config;const isLinkedToLocal = localNames.has(modelConfig.provider);diff --git a/studio/frontend/src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx b/studio/frontend/src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsxindex 702b9491fe6..fcaf3d33a0e 100644--- a/studio/frontend/src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx+++ b/studio/frontend/src/features/recipe-studio/dialogs/seed/unstructured-drop-zone.tsx@@ -181,8 +181,7 @@ export function UnstructuredDropZone({// Skip if the drop zone unmounted or its block changed: the id no// longer belongs here and restoring would leak it into another block.if (!mountedRef.current || blockIdRef.current !== blockId) return;- // Still exists server-side (counts toward quota); restore it at its- // original position.+ // Still exists server-side (counts toward quota); restore it at its original position.deletedIdsRef.current.delete(entry.id);onFilesChange((prev) => {const next = [...prev];diff --git a/studio/frontend/src/features/recipe-studio/easy/github-crawler-easy-view.tsx b/studio/frontend/src/features/recipe-studio/easy/github-crawler-easy-view.tsxindex 77a86e481ca..68d7bc14a66 100644--- a/studio/frontend/src/features/recipe-studio/easy/github-crawler-easy-view.tsx+++ b/studio/frontend/src/features/recipe-studio/easy/github-crawler-easy-view.tsx@@ -61,11 +61,10 @@ export function GithubCrawlerEasyView({const localModelValue =modelValue.trim().toLowerCase() === "local" ? "" : modelValue;- // Local buffer for the Rows input so the user can hold transient invalid- // state (empty while backspacing, partial digits, etc.) without the parent- // snapping them back to 1 on every keystroke. The canonical ``rows`` value- // only advances when the buffer parses to a valid positive integer; on- // blur we clamp back to a sane default if the user left it empty.+ // Local buffer for the Rows input so the user can hold transient invalid state (empty while+ // backspacing, partial digits, etc.) without the parent snapping them back to 1 on every+ // keystroke. The canonical ``rows`` value only advances when the buffer parses to a valid+ // positive integer; on blur we clamp back to a sane default if the user left it empty.const [rowsText, setRowsText] = useState(String(rows));useEffect(() => {// eslint-disable-next-line react-hooks/set-state-in-effect -- keep the draft input in sync when the parent resets rows.diff --git a/studio/frontend/src/features/recipe-studio/hooks/use-recipe-executions.ts b/studio/frontend/src/features/recipe-studio/hooks/use-recipe-executions.tsindex 92a2973f9f8..f397f368334 100644--- a/studio/frontend/src/features/recipe-studio/hooks/use-recipe-executions.ts+++ b/studio/frontend/src/features/recipe-studio/hooks/use-recipe-executions.ts@@ -880,11 +880,10 @@ export function useRecipeExecutions({return false;}- // Recipe and Chat share one singleton local inference backend. This direct- // load is a point-in-time handoff to job creation, not a lease: if Chat- // swaps models after this succeeds, the backend runs against current state.- // A future generation token should be validated across this load and the- // `/jobs` loaded-model gate.+ // Recipe and Chat share one singleton local inference backend. This direct load is a+ // point-in-time handoff to job creation, not a lease: if Chat swaps models after this+ // succeeds, the backend runs against current state. A future generation token should be+ // validated across this load and the `/jobs` loaded-model gate.const restorePrevious = await prepareLocalModelForExecution(payload);if (restorePrevious === false) {return false;diff --git a/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts b/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.tsindex 2d912724698..4cb612f44c1 100644--- a/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts+++ b/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts@@ -315,12 +315,11 @@ export function useRecipePersistence({return () => window.clearTimeout(timeoutId);}, [isDirty, persistRecipe, saveLoading]);- // Drain queued cleanups even when autosave is skipped: a net-zero edit (add- // then remove an unstructured seed before the 800ms debounce) keeps isDirty- // false, so the autosave effect never drains and the queued uid leaks its- // upload dir. Not-dirty means currentPayload equals the saved recipe, and- // drain skips the uid it still references, so only dirs no saved recipe- // points at are deleted (keeps the save-first invariant).+ // Drain queued cleanups even when autosave is skipped: a net-zero edit (add then remove an+ // unstructured seed before the 800ms debounce) keeps isDirty false, so the autosave effect never+ // drains and the queued uid leaks its upload dir. Not-dirty means currentPayload equals the saved+ // recipe, and drain skips the uid it still references, so only dirs no saved recipe points at are+ // deleted (keeps the save-first invariant).useEffect(() => {if (!initialRecipeReady || isDirty || saveLoading) {return;diff --git a/studio/frontend/src/features/recipe-studio/recipe-studio-page.tsx b/studio/frontend/src/features/recipe-studio/recipe-studio-page.tsxindex f1f5e0958e5..fa50bb28194 100644--- a/studio/frontend/src/features/recipe-studio/recipe-studio-page.tsx+++ b/studio/frontend/src/features/recipe-studio/recipe-studio-page.tsx@@ -226,10 +226,9 @@ export function RecipeStudioPage({},[viewModeStorageKey],);- // Easy mode has no canvas overlay/progress island, so a started run would- // leave the Run button stuck on "Running..." with nothing else changing.- // Flip to the Runs pane where progress is rendered. Advanced (editor) keeps- // its island and stays put.+ // Easy mode has no canvas overlay/progress island, so a started run would leave the Run button+ // stuck on "Running..." with nothing else changing. Flip to the Runs pane where progress is+ // rendered. Advanced (editor) keeps its island and stays put.const handleExecutionStart = useCallback(() => {setActiveView((currentView) =>currentView === "easy" ? "executions" : currentView,@@ -571,10 +570,9 @@ export function RecipeStudioPage({);const toggleMaximize = useCallback(() => {- // The maximized surface is a fixed z-50 overlay that already covers the- // app sidebar (z-10/z-20), so we don't touch the sidebar's own state — that- // state is persisted in pin mode and mutating it here would leak the- // temporary collapse into the next page/session.+ // The maximized surface is a fixed z-50 overlay that already covers the app sidebar+ // (z-10/z-20), so we don't touch the sidebar's own state — that state is persisted in pin mode+ // and mutating it here would leak the temporary collapse into the next page/session.setMaximized((prev) => !prev);// Container size changes; refit once the layout settles.scheduleFitView({ delayMs: TAB_SWITCH_FIT_DELAY_MS });@@ -598,9 +596,8 @@ export function RecipeStudioPage({}}, [activeView, reactFlowInstance]);- // The "Exit full view" control lives inside the editor canvas, which unmounts- // on other tabs. Drop full-view mode when leaving the editor so Easy/Runs- // aren't left under the fixed overlay.+ // The "Exit full view" control lives inside the editor canvas, which unmounts on other tabs. Drop+ // full-view mode when leaving the editor so Easy/Runs aren't left under the fixed overlay.useEffect(() => {if (activeView !== "editor" && maximized) {setMaximized(false);@@ -841,10 +838,9 @@ export function RecipeStudioPage({setRows={setFullRows}updateConfig={updateConfig}onRun={() => {- // Easy mode is a full run (artifact persisted, tracked in- // Runs) capped at the user's row count. runFull requires a- // non-empty fullRunName; the effect above populates one on- // mount so runFull's closure is current by click time.+ // Easy mode is a full run (artifact persisted, tracked in Runs) capped at the+ // user's row count. runFull requires a non-empty fullRunName; the effect above+ // populates one on mount so runFull's closure is current by click time.void runFull();}}runLoading={fullLoading || executionLocked}diff --git a/studio/frontend/src/features/recipe-studio/stores/recipe-studio.ts b/studio/frontend/src/features/recipe-studio/stores/recipe-studio.tsindex a1ff72ee9b7..4ba704d21c3 100644--- a/studio/frontend/src/features/recipe-studio/stores/recipe-studio.ts+++ b/studio/frontend/src/features/recipe-studio/stores/recipe-studio.ts@@ -77,10 +77,9 @@ type RecipeStudioState = {nextId: number;nextY: number;fitViewTick: number;- // Upload-uid directories whose owning block dropped them; server-side- // deletion is deferred until a save no longer references them, so a- // reload before autosave cannot leave a saved recipe pointing at- // deleted files.+ // Upload-uid directories whose owning block dropped them; server-side deletion is deferred until+ // a save no longer references them, so a reload before autosave cannot leave a saved recipe+ // pointing at deleted files.pendingUploadCleanups: string[];queueUploadCleanup: (uid: string) => void;setSheetOpen: (open: boolean) => void;diff --git a/studio/frontend/src/features/recipe-studio/utils/graph/recipe-graph-connection.ts b/studio/frontend/src/features/recipe-studio/utils/graph/recipe-graph-connection.tsindex 25e4d848c2e..db4d2379ef0 100644--- a/studio/frontend/src/features/recipe-studio/utils/graph/recipe-graph-connection.ts+++ b/studio/frontend/src/features/recipe-studio/utils/graph/recipe-graph-connection.ts@@ -387,10 +387,9 @@ export function applyRecipeConnection(nextBaseEdges,);if (source.kind === "model_provider" && target.kind === "model_config") {- // Keep model_config.provider in sync when a drag changes the link.- // Local providers need an explicit load id; don't synthesize the legacy- // "local" placeholder. External relinks clear local-only GGUF metadata;- // legacy placeholders normalize back to empty.+ // Keep model_config.provider in sync when a drag changes the link. Local providers need an+ // explicit load id; don't synthesize the legacy "local" placeholder. External relinks clear+ // local-only GGUF metadata; legacy placeholders normalize back to empty.const isSourceLocal = source.is_local === true;const isLegacyLocalPlaceholder =target.model.trim().toLowerCase() === "local";diff --git a/studio/frontend/src/features/recipe-studio/utils/import/parsers/sampler-parser.ts b/studio/frontend/src/features/recipe-studio/utils/import/parsers/sampler-parser.tsindex 651b5fb50c9..f125e497fc5 100644--- a/studio/frontend/src/features/recipe-studio/utils/import/parsers/sampler-parser.ts+++ b/studio/frontend/src/features/recipe-studio/utils/import/parsers/sampler-parser.ts@@ -62,11 +62,10 @@ function parseCategoryConditionalParams(// The words buildSamplerParams reads as a mode rather than as a prefix.const UUID_RESERVED_FORMATS = new Set(["uuid4", "short", "short_form", "upper", "uppercase"]);-// buildSamplerParams spreads a uuid format over the three fields data_designer-// defines, so rebuild the single UI string from those rather than from a-// `format` key nothing writes. A prefix whose own value is one of the reserved-// words comes back in the builder's `prefix:` escaped form, so re-saving writes-// the prefix again instead of turning it into a flag.+// buildSamplerParams spreads a uuid format over the three fields data_designer defines, so rebuild+// the single UI string from those rather than from a `format` key nothing writes. A prefix whose+// own value is one of the reserved words comes back in the builder's `prefix:` escaped form, so+// re-saving writes the prefix again instead of turning it into a flag.function readUuidFormat(params: Record<string, unknown>): string {const prefix = readString(params.prefix)?.trim();if (prefix) {diff --git a/studio/frontend/src/features/settings/api/coding-agents.ts b/studio/frontend/src/features/settings/api/coding-agents.tsindex fe964b53480..9fae9250fbe 100644--- a/studio/frontend/src/features/settings/api/coding-agents.ts+++ b/studio/frontend/src/features/settings/api/coding-agents.ts@@ -20,11 +20,10 @@ type ApiCodingAgentsInfo = {// every consumer of this endpoint sees the same set.const HIDDEN_AGENTS = new Set(["pi"]);-// Which CLIs are on PATH is environment state, not a persisted setting -- it-// can change any time the user installs something new, so this only-// de-duplicates concurrent in-flight calls (e.g. React strict-mode's double-// mount) rather than caching the result across the module's lifetime. Every-// fresh call (each time a settings panel mounts) re-checks PATH for real.+// Which CLIs are on PATH is environment state, not a persisted setting -- it can change any time+// the user installs something new, so this only de-duplicates concurrent in-flight calls (e.g.+// React strict-mode's double mount) rather than caching the result across the module's lifetime.+// Every fresh call (each time a settings panel mounts) re-checks PATH for real.let inFlightInfo: Promise<CodingAgentsInfo> | null = null;function fromApi(info: ApiCodingAgentsInfo): CodingAgentsInfo {diff --git a/studio/frontend/src/features/settings/api/openai-auto-switch.ts b/studio/frontend/src/features/settings/api/openai-auto-switch.tsindex 1b03ba9fbaa..3d19498705a 100644--- a/studio/frontend/src/features/settings/api/openai-auto-switch.ts+++ b/studio/frontend/src/features/settings/api/openai-auto-switch.ts@@ -84,9 +84,8 @@ async function fetchOpenAIAutoSwitchSettings(): Promise<OpenAIAutoSwitchSettingsreturn fromApi(await res.json());}-// Bumped on every invalidation. A response that was already in flight when the-// cache was cleared must not refill it, or the pre-toggle value would be served-// indefinitely.+// Bumped on every invalidation. A response that was already in flight when the cache was cleared+// must not refill it, or the pre-toggle value would be served indefinitely.let cacheGeneration = 0;function cacheSettings(settings: OpenAIAutoSwitchSettings, generation: number) {@@ -174,9 +173,8 @@ export async function updateOpenAIAutoSwitchSettings(body[key] = value;}}- // Read BEFORE the request: idleUnloadActive depends on the Model Memory- // setting, so a residency write landing mid-flight makes this response stale- // even though it is our own write's reply.+ // Read BEFORE the request: idleUnloadActive depends on the Model Memory setting, so a residency+ // write landing mid-flight makes this response stale even though it is our own write's reply.const generation = cacheGeneration;const res = await authFetch("/api/settings/openai-auto-switch", {method: "PUT",diff --git a/studio/frontend/src/features/settings/api/remote-access-state.ts b/studio/frontend/src/features/settings/api/remote-access-state.tsindex c97cdc99ff4..dea741e3018 100644--- a/studio/frontend/src/features/settings/api/remote-access-state.ts+++ b/studio/frontend/src/features/settings/api/remote-access-state.ts@@ -102,11 +102,10 @@ export function remoteAccessStopDisconnectsOrigin();}-// A Stop sent from the tunnel's own origin is answered with a terminal off, then-// that origin dies. Polls landing during teardown still report "stopping", a state-// this origin can never see resolve, so they must not overwrite the terminal off.-// One that can still stop the connector proves teardown was abandoned, so the-// origin is staying up and polls lead again.+// A Stop sent from the tunnel's own origin is answered with a terminal off, then that origin dies.+// Polls landing during teardown still report "stopping", a state this origin can never see resolve,+// so they must not overwrite the terminal off. One that can still stop the connector proves+// teardown was abandoned, so the origin is staying up and polls lead again.export function remoteAccessSelfStopPoll(next: RemoteAccessStatus,expectingDisconnect: boolean,diff --git a/studio/frontend/src/features/settings/api/vram-budget.ts b/studio/frontend/src/features/settings/api/vram-budget.tsindex 84a2f22285b..5fbb2dca52d 100644--- a/studio/frontend/src/features/settings/api/vram-budget.ts+++ b/studio/frontend/src/features/settings/api/vram-budget.ts@@ -80,21 +80,19 @@ export function flushVramBudgetSave(): Promise<VramBudgetSettings> | null {* that request replaces. The chain swallows rejections the debounced save reported.*/export function settleVramBudgetSave(): Promise<unknown> | null {- // The newest write, not the chain: the chain swallows rejections so one failed- // save cannot strand those behind it, and a caller waiting on it would be told- // the save succeeded. Only the newest can have re-staged a retry, and writes- // settle in order, so it still covers every open write.+ // The newest write, not the chain: the chain swallows rejections so one failed save cannot strand+ // those behind it, and a caller waiting on it would be told the save succeeded. Only the newest+ // can have re-staged a retry, and writes settle in order, so it still covers every open write.return (flushVramBudgetSave() ??(vramBudgetWritesOpen > 0 ? vramBudgetNewestWrite : null));}-// A load waits on the budget it is about to launch against, so an edit made in-// that window is flushed by the teardown alongside the load request and either-// fraction could size the child. Settling in a loop only shrinks that window;-// closing the control closes it. Held here because the row unmounts and the load-// does not.+// A load waits on the budget it is about to launch against, so an edit made in that window is+// flushed by the teardown alongside the load request and either fraction could size the child.+// Settling in a loop only shrinks that window; closing the control closes it. Held here because the+// row unmounts and the load does not.let vramBudgetLocked = false;export function setVramBudgetLocked(locked: boolean) {@@ -165,10 +163,9 @@ async function fetchVramBudgetSettings(): Promise<VramBudgetSettings> {export async function loadVramBudgetSettings(options: { force?: boolean; rethrow?: boolean } = {},): Promise<VramBudgetSettings | null> {- // Read behind any open write: a row remounting right after a flushed drag can- // otherwise GET the old fraction before the PUT commits and answer after it,- // repainting the control with the value the server just replaced. The- // subscription cannot untangle that, since only the order is wrong.+ // Read behind any open write: a row remounting right after a flushed drag can otherwise GET the+ // old fraction before the PUT commits and answer after it, repainting the control with the value+ // the server just replaced. The subscription cannot untangle that, since only the order is wrong.const pendingWrites =vramBudgetWritesOpen > 0 ? vramBudgetWriteChain : Promise.resolve();// Waiting behind the writes open now says nothing about a save issued while thediff --git a/studio/frontend/src/features/settings/components/embedding-model-picker.tsx b/studio/frontend/src/features/settings/components/embedding-model-picker.tsxindex 02ccbf37117..2c5a452f116 100644--- a/studio/frontend/src/features/settings/components/embedding-model-picker.tsx+++ b/studio/frontend/src/features/settings/components/embedding-model-picker.tsx@@ -113,9 +113,8 @@ export function EmbeddingModelPicker({if (selected && !rows.some((row) => row.id === selected)) {rows.push({ id: selected, sizeBytes: null });}- // The configured default the same way: the empty search is scoped to- // `unsloth`, so a private, other-owner or local default had no row, and the- // old "Reset to default" button is gone.+ // The configured default the same way: the empty search is scoped to `unsloth`, so a private,+ // other-owner or local default had no row, and the old "Reset to default" button is gone.const fallback = defaultModel?.trim();if (fallback && !rows.some((row) => row.id === fallback)) {rows.push({ id: fallback, sizeBytes: null });diff --git a/studio/frontend/src/features/settings/components/language-select.tsx b/studio/frontend/src/features/settings/components/language-select.tsxindex fbf892f793c..e07062282bc 100644--- a/studio/frontend/src/features/settings/components/language-select.tsx+++ b/studio/frontend/src/features/settings/components/language-select.tsx@@ -27,18 +27,16 @@ export function LanguageSelect() {const preference = useLocalePreference();const pendingPreference = usePendingLocalePreference();const catalogFailed = useLocaleCatalogFailed();- // Name no entry at all whenever the preference's own catalog failed and a- // fallback was adopted. A controlled Select never fires onValueChange for the- // value it already holds, so whichever entry it names is the one entry the- // user cannot pick, and after a failure both of them are needed: the failed- // preference is the retry, and the fallback in effect is how English becomes- // a real preference instead of something the app is doing temporarily. The- // empty string is Radix's "no selection", so every entry stays pickable and- // the trigger shows the language actually in effect as the placeholder.- // Whether the catalog failed has to come from the store rather than a- // `preference !== locale` comparison, because a failed `auto` still reads as- // `auto`, and its fallback locale is indistinguishable from a successful- // detection that landed on the same language.+ // Name no entry at all whenever the preference's own catalog failed and a fallback was adopted. A+ // controlled Select never fires onValueChange for the value it already holds, so whichever entry+ // it names is the one entry the user cannot pick, and after a failure both of them are needed:+ // the failed preference is the retry, and the fallback in effect is how English becomes a real+ // preference instead of something the app is doing temporarily. The empty string is Radix's "no+ // selection", so every entry stays pickable and the trigger shows the language actually in effect+ // as the placeholder. Whether the catalog failed has to come from the store rather than a+ // `preference !== locale` comparison, because a failed `auto` still reads as `auto`, and its+ // fallback locale is indistinguishable from a successful detection that landed on the same+ // language.const fallbackLabel = catalogFailed ? LOCALES[locale].nativeLabel : "";return (diff --git a/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx b/studio/frontend/src/features/settings/components/model-auto-switch-section.tsxindex 0bb3b78687e..dc53380e527 100644--- a/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx+++ b/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx@@ -166,11 +166,10 @@ export function ModelAutoSwitchSection() {}};- // Idle-unload is tied to auto-switch (the freed model reloads via the swap).- // Toggling off preserves the saved seconds rather than zeroing them — the- // backend gates unloading on the enabled flag, so it never unloads while off.- // Enabling commits the drafted value, falling back to the last saved one so- // it can never get stuck.+ // Idle-unload is tied to auto-switch (the freed model reloads via the swap). Toggling off+ // preserves the saved seconds rather than zeroing them — the backend gates unloading on the+ // enabled flag, so it never unloads while off. Enabling commits the drafted value, falling back+ // to the last saved one so it can never get stuck.const handleToggle = (enabled: boolean) => {const savedIdleSeconds = settings?.autoUnloadIdleSeconds ?? 0;if (!enabled) {diff --git a/studio/frontend/src/features/settings/components/model-memory-section.tsx b/studio/frontend/src/features/settings/components/model-memory-section.tsxindex 31e10f717ca..dd54ca5d710 100644--- a/studio/frontend/src/features/settings/components/model-memory-section.tsx+++ b/studio/frontend/src/features/settings/components/model-memory-section.tsx@@ -58,10 +58,9 @@ export function ModelMemorySection() {}};- // Both on suppresses --mlock. Say so, rather than looking like a no-op.- // Keyed on the toggles, not mlockActive: that now also reads false when the- // running model simply had nothing in host RAM to lock, which is a different- // reason than the one this line gives.+ // Both on suppresses --mlock. Say so, rather than looking like a no-op. Keyed on the toggles, not+ // mlockActive: that now also reads false when the running model simply had nothing in host RAM to+ // lock, which is a different reason than the one this line gives.const mlockVetoed =settings?.keepResident === true && settings.noRamReserve === true;// A finite locked-memory cap means llama.cpp logs "failed to mlock" anddiff --git a/studio/frontend/src/features/settings/components/palette-cards.tsx b/studio/frontend/src/features/settings/components/palette-cards.tsxindex e6b920574be..d42e041bf08 100644--- a/studio/frontend/src/features/settings/components/palette-cards.tsx+++ b/studio/frontend/src/features/settings/components/palette-cards.tsx@@ -127,10 +127,9 @@ export function PaletteCards() {onClick={() => setPalette(opt.value)}aria-pressed={active}data-palette-value={opt.value}- // The active ring is CSS-driven off html[data-palette] (see- // .palette-card in index.css) so it moves in the same style- // pass that swaps the tokens; keying it off React state leaves- // the ring on the old card until the app finishes re-rendering.+ // The active ring is CSS-driven off html[data-palette] (see .palette-card in index.css)+ // so it moves in the same style pass that swaps the tokens; keying it off React state+ // leaves the ring on the old card until the app finishes re-rendering.className="palette-card flex flex-col gap-2 rounded-xl border border-border p-2.5 text-left transition-colors focus-visible:border-ring focus-visible:outline-none"><PalettePreview colors={PREVIEWS[opt.value][resolved]} />diff --git a/studio/frontend/src/features/settings/components/settings-row.tsx b/studio/frontend/src/features/settings/components/settings-row.tsxindex 68fadf2764b..5935512b0c7 100644--- a/studio/frontend/src/features/settings/components/settings-row.tsx+++ b/studio/frontend/src/features/settings/components/settings-row.tsx@@ -39,9 +39,8 @@ export function SettingsRow({<divdata-settings-label={label}className={cn(- // Controls are fixed-width and shrink-0, so an unwrapped row starves the- // label. justify-end right-aligns a wrapped control without breaking- // items-stretch for flex-col callers.+ // Controls are fixed-width and shrink-0, so an unwrapped row starves the label. justify-end+ // right-aligns a wrapped control without breaking items-stretch for flex-col callers."flex flex-wrap justify-end gap-x-6 gap-y-2 py-3",alignTop ? "items-start" : "items-center",destructive && "border-t border-border/60 mt-2 pt-4",diff --git a/studio/frontend/src/features/settings/components/stt-download-prompt.tsx b/studio/frontend/src/features/settings/components/stt-download-prompt.tsxindex 7bee7c37d09..4a6b9019b88 100644--- a/studio/frontend/src/features/settings/components/stt-download-prompt.tsx+++ b/studio/frontend/src/features/settings/components/stt-download-prompt.tsx@@ -59,8 +59,7 @@ export function SttDownloadPrompt() {}try {await startSttDownload(request.model, hfApiToken(hfToken));- // Progress goes to the shared download panel; the model loads itself- // when it lands.+ // Progress goes to the shared download panel; the model loads itself when it lands.trackSttDownload(request.model);} catch (error) {toast.error(t("settings.voice.dictation.sttDownloadFailed"), {diff --git a/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsx b/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsxindex 4e063ff9bb4..1253df665fe 100644--- a/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsx+++ b/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsx@@ -189,10 +189,9 @@ function toSortTime(value: string | number | null | undefined): number {return Number.isNaN(parsed) ? 0 : parsed;}-// Safari and Firefox block window.open after an await (the user gesture is-// gone), so open a blank tab synchronously and point it at the URL once-// resolved. A blocked synchronous open is surfaced instead of silently losing-// the file after the asynchronous URL lookup. The Tauri webview has no+// Safari and Firefox block window.open after an await (the user gesture is gone), so open a blank+// tab synchronously and point it at the URL once resolved. A blocked synchronous open is surfaced+// instead of silently losing the file after the asynchronous URL lookup. The Tauri webview has no// window.open at all, so it goes through the OS opener.async function openResolvedUrl(resolve: () => Promise<string>): Promise<void> {if (isTauri) {@@ -258,13 +257,11 @@ const EXT_BY_MIME: Record<string, string> = {"audio/flac": "flac",};-// Name the save after the bytes the route actually returns. Uploaded documents-// come back as extracted text (TextAttachmentAdapter also wraps it in-// <attachment name=...>), so text/plain is .txt whatever the upload was called.-// Managed content parts arrive named "Chat image"/"Chat audio" with no-// extension at all, which the OS cannot recognise.-// A dot at index 0 is a dotfile (.env), not an extension: treating it as one-// would strip the whole name and save a bare ".txt".+// Name the save after the bytes the route actually returns. Uploaded documents come back as+// extracted text (TextAttachmentAdapter also wraps it in <attachment name=...>), so text/plain is+// .txt whatever the upload was called. Managed content parts arrive named "Chat image"/"Chat audio"+// with no extension at all, which the OS cannot recognise. A dot at index 0 is a dotfile (.env),+// not an extension: treating it as one would strip the whole name and save a bare ".txt".function extensionStart(name: string): number {const dot = name.lastIndexOf(".");return dot > 0 ? dot : -1;diff --git a/studio/frontend/src/features/settings/components/usage-examples.tsx b/studio/frontend/src/features/settings/components/usage-examples.tsxindex 66d6bc34c4b..cb2b1489d7b 100644--- a/studio/frontend/src/features/settings/components/usage-examples.tsx+++ b/studio/frontend/src/features/settings/components/usage-examples.tsx@@ -140,9 +140,8 @@ const DOC_LINKS = [},];-// Fallback until the backend's installed-CLI check resolves. Mirrors-// CODING_AGENTS in studio/backend/utils/coding_agents.py, minus HIDDEN_AGENTS-// (see ../api/coding-agents.ts).+// Fallback until the backend's installed-CLI check resolves. Mirrors CODING_AGENTS in+// studio/backend/utils/coding_agents.py, minus HIDDEN_AGENTS (see ../api/coding-agents.ts).const DEFAULT_AGENTS = ["claude", "codex", "openclaw", "opencode", "hermes", "dsh"];// The agent selection resets to this whenever an auto-pick is no longer// trustworthy (leaving loopback, or the only compatible detected agent@@ -174,9 +173,8 @@ function bodyExtraLines(variant: Variant, indent: string): string[] {if (variant !== "plain") {lines.push(`${indent}"enable_tools": true,`);lines.push(`${indent}"enabled_tools": [${toolsJson}],`);- // The gate only asks over the X-Unsloth-Events frames these snippets deliberately do- // not take, so say the tools run unprompted rather than hand out a request the server- // refuses.+ // The gate only asks over the X-Unsloth-Events frames these snippets deliberately do not take,+ // so say the tools run unprompted rather than hand out a request the server refuses.lines.push(`${indent}"permission_mode": "off",`);}return lines;@@ -714,19 +712,17 @@ export function UsageExamples({void fetchDeviceType({ force: true });}, []);- // Fetching is the only job of this effect: populate availableAgents/- // detectedAgents (or clear them). Which agent gets auto-picked from that- // list is derived separately below, so it can react to the loaded model- // changing too, not just a fresh fetch.+ // Fetching is the only job of this effect: populate availableAgents/ detectedAgents (or clear+ // them). Which agent gets auto-picked from that list is derived separately below, so it can react+ // to the loaded model changing too, not just a fresh fetch.useEffect(() => {// Browser loopback URLs can be SSH/local forwards, so only the desktop app// may use backend PATH checks to mark or auto-pick local agents.if (!localAgentDetection) {setDetectedAgents([]);- // A previously auto-picked agent was only ever verified against the- // Unsloth backend's PATH, which is meaningless now that this panel no- // longer targets a loopback base -- don't leave it selected, but- // never touch a choice the user made by hand.+ // A previously auto-picked agent was only ever verified against the Unsloth backend's PATH,+ // which is meaningless now that this panel no longer targets a loopback base -- don't leave+ // it selected, but never touch a choice the user made by hand.if (!agentPickedByUserRef.current) {// The effect below corrects this; isGguf read here would be a stale closure.setAgent(DEFAULT_AGENT);diff --git a/studio/frontend/src/features/settings/hooks/use-published-frame.ts b/studio/frontend/src/features/settings/hooks/use-published-frame.tsindex 5c9049f506e..8f75a66017e 100644--- a/studio/frontend/src/features/settings/hooks/use-published-frame.ts+++ b/studio/frontend/src/features/settings/hooks/use-published-frame.ts@@ -1,9 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Publish an element's box to the overlay-frame store, so the API monitor-// panel opens somewhere it is not. The Live monitor does this by hand inside-// its own layout effect; anything else uses this.+// Publish an element's box to the overlay-frame store, so the API monitor panel opens somewhere it+// is not. The Live monitor does this by hand inside its own layout effect; anything else uses this.import { useEffect, useMemo } from "react";diff --git a/studio/frontend/src/features/settings/hooks/use-shortcut.ts b/studio/frontend/src/features/settings/hooks/use-shortcut.tsindex 6fc01a3a57c..4bef4be4054 100644--- a/studio/frontend/src/features/settings/hooks/use-shortcut.ts+++ b/studio/frontend/src/features/settings/hooks/use-shortcut.ts@@ -50,10 +50,9 @@ export function isImeComposing(event: KeyboardEvent): boolean {*/export function isSurfaceInForeground(selector: string): boolean {if (typeof document === "undefined") return false;- // Every match, not the first: Compare keeps the base view mounted and inert- // behind the panes, so the first composer found is the hidden one. Radix- // marks the rest of the page aria-hidden (older React: inert) for a modal's- // life, which is the general signal, not a per-dialog store.+ // Every match, not the first: Compare keeps the base view mounted and inert behind the panes, so+ // the first composer found is the hidden one. Radix marks the rest of the page aria-hidden (older+ // React: inert) for a modal's life, which is the general signal, not a per-dialog store.return [...document.querySelectorAll(selector)].some((el) => !el.closest('[aria-hidden="true"], [inert]'),);@@ -175,9 +174,8 @@ export function useShortcut(if (isImeComposing(event)) return;const hit = bindings.find((binding) => matchesBinding(binding, event));if (!hit) return;- // The exception is for a chord that types nothing there. Decline ships- // on Escape; rebound to Enter or a letter, the same pass would deny the- // request as the user edits the prompt.+ // The exception is for a chord that types nothing there. Decline ships on Escape; rebound to+ // Enter or a letter, the same pass would deny the request as the user edits the prompt.const exception = typesInTextField(hit) ? undefined : textFieldException;if (skipInTextFields && isTextEntryFocused(exception)) return;// The focused control keeps its own Enter or Space.@@ -191,9 +189,8 @@ export function useShortcut(// to reach the browser untouched.if (latestRef.current.claims?.() === false) return;event.preventDefault();- // Held past the OS repeat delay the chord arrives again and again. It- // stays consumed either way, but only an action that asked for repeats- // runs on them.+ // Held past the OS repeat delay the chord arrives again and again. It stays consumed either+ // way, but only an action that asked for repeats runs on them.if (event.repeat && !repeats) return;latestRef.current.handler(event);};diff --git a/studio/frontend/src/features/settings/lib/debug-log-buffer.ts b/studio/frontend/src/features/settings/lib/debug-log-buffer.tsindex 733fe1fce50..98b1d3b5b00 100644--- a/studio/frontend/src/features/settings/lib/debug-log-buffer.ts+++ b/studio/frontend/src/features/settings/lib/debug-log-buffer.ts@@ -113,10 +113,9 @@ export async function withRequestTimeout<T>(running.catch(() => {});const deadline = new Promise<never>((_, reject) => {timer = setTimeout(() => {- // Reject BEFORE aborting. `local.abort()` settles an abort-aware task- // synchronously, and that rejection would then win the race and arrive- // as an ordinary AbortError, which the poll loop drops in silence: the- // deadline would announce itself only for work that ignores the signal.+ // Reject BEFORE aborting. `local.abort()` settles an abort-aware task synchronously, and that+ // rejection would then win the race and arrive as an ordinary AbortError, which the poll loop+ // drops in silence: the deadline would announce itself only for work that ignores the signal.reject(new DebugLogTimeoutError(timeoutMs));local.abort();}, timeoutMs);@@ -124,10 +123,9 @@ export async function withRequestTimeout<T>(try {return await Promise.race([running, deadline]);} catch (error) {- // The caller's own abort wins the tie: an unmount or a source switch is- // silent by design, and it can race the timer on a request that was- // already doomed. Only a backstop with no caller abort behind it is a- // fault the user needs told about.+ // The caller's own abort wins the tie: an unmount or a source switch is silent by design, and+ // it can race the timer on a request that was already doomed. Only a backstop with no caller+ // abort behind it is a fault the user needs told about.if (signal?.aborted && isRequestTimeout(error)) throw abortError();throw error;} finally {@@ -151,8 +149,7 @@ export function isPageStale(page: {pageSourceId: string | null;}): boolean {if (page.requestSelection !== page.currentSelection) return true;- // The server answers an unset source with its default, so only disagree when- // both ends named one.+ // The server answers an unset source with its default, so only disagree when both ends named one.return Boolean(page.requestSourceId &&page.pageSourceId &&diff --git a/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts b/studio/frontend/src/features/settings/lib/keyboard-shortcuts.tsindex 6bda9679990..91a2fc1587c 100644--- a/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts+++ b/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts@@ -4,16 +4,12 @@import type { TranslationKey } from "@/i18n";/**- * Every rebindable action. To add one: an entry in SHORTCUT_DEFS, its two i18n- * keys in all twelve locales, its label in settings-search.ts, and a- * `useShortcut(id, ...)` where the action runs.- *- * Order is the render order and decides who owns a contested chord, so the- * most reached-for actions come first. An action only earns a row when Unsloth- * has the feature behind it.+ * Every rebindable action. To add one: an entry in SHORTCUT_DEFS, its two i18n keys in all+ * twelve locales, its label in settings-search.ts, and a `useShortcut(id, ...)` where the action+ * runs. Order is the render order and decides who owns a contested chord, so the most+ * reached-for actions come first.*/export type ShortcutId =- // Chat navigation, first because it is what the list is mostly for.| "newChat"| "newTemporaryChat"| "archiveChat"@@ -34,7 +30,6 @@ export type ShortcutId =| "goToRecentChat4"| "goToRecentChat5"| "goToRecentChat6"- // Workspaces| "switchToChat"| "switchToProjects"| "switchToHub"@@ -44,7 +39,6 @@ export type ShortcutId =| "switchToVideo"| "switchToAudio"| "switchToExport"- // Panels and app-level actions| "findInPage"| "toggleApiMonitor"| "toggleSidebar"@@ -54,7 +48,6 @@ export type ShortcutId =| "openSettings"| "approveToolRequest"| "declineToolRequest"- // Composer| "attachFiles"| "cycleReasoningEffort"| "decreaseReasoningEffort"@@ -64,7 +57,6 @@ export type ShortcutId =| "startDictation"| "sendMessage"| "toggleFastMode"- // Chat actions| "copyChatAsMarkdown"| "copySessionId"| "forkChat"@@ -72,7 +64,6 @@ export type ShortcutId =| "renameChat"| "openKeyboardShortcuts";-/** Which of an action's two chords a value belongs to. */export type ShortcutSlot = "primary" | "alternate";export const SHORTCUT_SLOTS: ShortcutSlot[] = ["primary", "alternate"];@@ -90,10 +81,7 @@ export interface ShortcutDef {nonMacDefaultAlternateBinding?: string | null;/** Allow a chord with no modifier. Only for prompt-gated actions. */allowBareKey?: boolean;- /**- * Hide the row on the desktop build. The handler returns there, so offering- * the row offers a key that does nothing.- */+ /** Hide the row on the desktop build. The handler returns there, so offering the row offers a key that does nothing. */webOnly?: boolean;}@@ -155,18 +143,16 @@ const WORKSPACE_DEFS: ShortcutDef[] = WORKSPACE_IDS.map((id, i) =>/** Most-used first: the list renders in this order, and it settles which* action owns a chord two of them claim, rather than mount order. */export const SHORTCUT_DEFS: ShortcutDef[] = [- // -- Chat navigation ----------------------------------------------------- // ⌘N opens a browser window and cannot be prevented, and ⇧⌘O already- // shipped, so ⌘N rides along as the alternate for the desktop build.+ // ⌘N opens a browser window and cannot be prevented, and ⇧⌘O already shipped, so ⌘N rides+ // along as the alternate for the desktop build.def("newChat", "Mod+Shift+KeyO", { defaultAlternateBinding: "Mod+KeyN" }),def("newTemporaryChat", "Mod+Shift+KeyN"),// ⇧⌘A is Chrome's tab search and Firefox's add-ons manager, so E, the archive// key every mail client uses, on the ⌥ run the rest of these chat chords sit on.def("archiveChat", "Mod+Alt+KeyE"),def("newStandaloneChat", "Mod+Alt+KeyO"),- // ⌃⇧U off macOS is GTK's hex entry, hard-coded in GtkIMContextSimple and- // bound again by IBus, so a focused composer is where it would be fought- // over. U stays the mnemonic on the ⌥ run, beside Clear all unreads.+ // ⌃⇧U off macOS is GTK's hex entry, hard-coded in GtkIMContextSimple and bound again by IBus,+ // so a focused composer is where it would be fought over. U stays the mnemonic on the ⌥ run.def("markChatUnread", "Mod+Shift+KeyU", {nonMacDefaultBinding: "Mod+Alt+KeyU",}),@@ -186,9 +172,8 @@ export const SHORTCUT_DEFS: ShortcutDef[] = [def("nextRecentlyViewedChat", "Ctrl+Tab", {nonMacDefaultBinding: "Mod+Tab",}),- // No arrow alternate: ⌥⌘→ is Chrome's next tab, and off macOS the same chord- // reads as Ctrl+Alt+→, desktop switching on GNOME and KDE and screen rotation- // on Intel graphics. Taken everywhere, so the bracket pair carries these.+ // No arrow alternate: ⌥⌘→ is Chrome's next tab, and off macOS the same chord reads as+ // Ctrl+Alt+→, desktop switching on GNOME and KDE and screen rotation on Intel graphics.def("nextChat", "Mod+Shift+BracketRight"),def("nextChatNeedingAttention", "Mod+Alt+KeyA"),def("previousRecentlyViewedChat", "Ctrl+Shift+Tab", {@@ -197,20 +182,16 @@ export const SHORTCUT_DEFS: ShortcutDef[] = [def("previousChat", "Mod+Shift+BracketLeft"),...RECENT_SLOT_DEFS,- // -- Workspaces ---------------------------------------------------------...WORKSPACE_DEFS,- // -- Panels and app-level actions ---------------------------------------// The one default that deliberately takes a chord the browser owns, because the browser's own// find is what it replaces: that one cannot reach a message the mount window has not committed,- // counts the sidebar and composer as page, and does not exist on the desktop build. The chord is- // cancellable in every engine this ships on, so the handler wins it; Settings still flags it.+ // counts the sidebar and composer as page, and does not exist on the desktop build. Cancellable+ // in every engine this ships on, so the handler wins it; Settings still flags it.def("findInPage", "Mod+KeyF"),- // ⌥⌘U is view source on macOS, so U keeps its mnemonic on ⌃⇧ there instead,- // the same swap the composer pair below makes. Off macOS it gives U up- // altogether: three actions wanted that letter and only two chords carry it- // safely there, so the two that mean "unread" have them and this one, whose- // U was never a mnemonic, takes M for monitor.+ // ⌥⌘U is view source on macOS, so U keeps its mnemonic on ⌃⇧ there instead. Off macOS it gives+ // U up altogether: three actions wanted that letter and only two chords carry it safely there,+ // so the two that mean "unread" have them and this one takes M for monitor.def("toggleApiMonitor", "Ctrl+Shift+KeyU", {nonMacDefaultBinding: "Mod+Alt+Shift+KeyM",}),@@ -228,7 +209,6 @@ export const SHORTCUT_DEFS: ShortcutDef[] = [def("approveToolRequest", "Enter", { allowBareKey: true }),def("declineToolRequest", "Escape", { allowBareKey: true }),- // -- Composer -----------------------------------------------------------def("attachFiles", null),def("cycleReasoningEffort", null),def("decreaseReasoningEffort", null),@@ -245,10 +225,8 @@ export const SHORTCUT_DEFS: ShortcutDef[] = [def("sendMessage", null),def("toggleFastMode", null),- // -- Chat actions -------------------------------------------------------def("copyChatAsMarkdown", null),- // ⌥⌘C is Firefox's element picker and Safari's console, so C moves the same- // way U did above.+ // ⌥⌘C is Firefox's element picker and Safari's console, so C moves the same way U did above.def("copySessionId", "Ctrl+Shift+KeyC", {nonMacDefaultBinding: "Mod+Alt+KeyC",}),@@ -295,21 +273,16 @@ export function defaultBindingFor(}/**- * Chords the browser owns. Tab and window management never reaches the page at- * all; the rest is cancellable, but taking it breaks the browser's own action.- * Both work in the desktop build, so they still ship as defaults and the tab- * flags them on the web.+ * Chords the browser owns. Tab and window management never reaches the page at all; the rest is+ * cancellable, but taking it breaks the browser's own action. Both work in the desktop build, so+ * they still ship as defaults and the tab flags them on the web.*- * What gets in, here and in the two platform sets below: a chord the browser- * takes from every user out of the box. These sets drive a warning the user- * reads and a test no default may fail, and both are only worth anything if- * the chord really is gone on the machine in front of them. A chord that only- * binds once a hidden developer menu is switched on does not qualify -- Safari- * puts Empty Caches on ⌥⌘E and reloads from origin on ⌥⌘R, but only for- * someone who went and enabled the Develop menu, so warning every macOS user- * about them would be telling almost all of them something untrue. Where a- * default and an opt-in chord do collide, the tab that raised the menu is also- * the tab that rebinds.+ * What gets in, here and in the two platform sets below: a chord the browser takes from every+ * user out of the box. These sets drive a warning the user reads and a test no default may fail,+ * and both are only worth anything if the chord really is gone on the machine in front of them. A+ * chord that only binds once a hidden developer menu is switched on does not qualify -- Safari+ * puts Empty Caches on ⌥⌘E only for someone who enabled the Develop menu, so warning every macOS+ * user about it would be telling almost all of them something untrue.*/const BROWSER_RESERVED_VALUES = new Set<string>(["Mod+KeyN",@@ -338,11 +311,10 @@ const BROWSER_RESERVED_VALUES = new Set<string>([]);/**- * Owned on macOS only, where ⌥⌘ is the browsers' own run. From Chrome's- * shortcut list: U view source, I dev tools, J console, B bookmarks, N split- * view, F search, and the arrows for tabs and toolbar focus. Firefox adds C,- * its element picker, and K, its console. Off macOS the same values read as- * Ctrl+Alt, which none of them claim.+ * Owned on macOS only, where ⌥⌘ is the browsers' own run. From Chrome's shortcut list: U view+ * source, I dev tools, J console, B bookmarks, N split view, F search, and the arrows for tabs+ * and toolbar focus. Firefox adds C, its element picker, and K, its console. Off macOS the same+ * values read as Ctrl+Alt, which none of them claim.*/const MAC_RESERVED_VALUES = new Set<string>(["Mod+Alt+KeyU",@@ -355,11 +327,9 @@ const MAC_RESERVED_VALUES = new Set<string>(["Mod+Alt+KeyK",// Page Setup, which Chrome lists beside ⌘P on its own shortcuts page."Mod+Alt+KeyP",- // Safari's Show Next Tab and Show Previous Tab, per Apple's own shortcut- // list, and Chrome carries the same pair on macOS. Off macOS they read as- // Ctrl+Shift+bracket, which no browser claims. The chat walk ships on them- // for the desktop build, where nothing intercepts them; reserving them is- // what puts the warning in front of a web user who is about to rebind.+ // Safari's Show Next Tab and Show Previous Tab, per Apple's own shortcut list, and Chrome+ // carries the same pair on macOS. Off macOS they read as Ctrl+Shift+bracket, which no browser+ // claims. The chat walk ships on them for the desktop build; reserving them warns a web user."Mod+Shift+BracketLeft","Mod+Shift+BracketRight","Mod+Alt+ArrowLeft",@@ -390,10 +360,9 @@ export function isBrowserReservedBinding(}/**- * Keys the browser turns into a click on whatever control has focus. A chord- * built from one of these with no modifier has to leave that click alone, or- * pressing Enter on a focused Deny button would run the shortcut instead and- * preventDefault would cancel the button's own activation.+ * Keys the browser turns into a click on whatever control has focus. A chord built from one of+ * these with no modifier has to leave that click alone, or pressing Enter on a focused Deny+ * button would run the shortcut and preventDefault would cancel the button's own activation.*/const ACTIVATION_CODES = new Set(["Enter", "NumpadEnter", "Space"]);@@ -506,11 +475,9 @@ export function bindingFromEvent(): ShortcutBinding | null {const code = event.code || keyToCode(event.key ?? "");if (!code || isModifierCode(code)) return null;- // Off macOS there is nowhere to put Meta: matchesBinding rejects an event- // carrying it, so recording Super+Alt+K would drop the Super and persist plain- // Alt+K -- a chord the user did not choose, which then fires on Alt+K alone- // while the one they pressed never matches. Record nothing instead, the same- // answer the recorder already gets while only modifiers are held.+ // Off macOS there is nowhere to put Meta: matchesBinding rejects an event carrying it, so+ // recording Super+Alt+K would persist plain Alt+K -- a chord the user did not choose, which then+ // fires on Alt+K alone while the one they pressed never matches. Record nothing instead.if (!mac && event.metaKey) return null;// matchesBinding will not fire an AltGr chord, so do not record one.if (!mac && isAltGraphEvent(event)) return null;@@ -526,9 +493,9 @@ export function bindingFromEvent(}/**- * AltGr rather than a real Ctrl+Alt. AltGr reports both, so typing ą or € would- * otherwise fire every Ctrl+Alt chord and eat the character. Callers gate this- * on being off macOS: Option reports AltGraph too, and it is a plain Alt.+ * AltGr rather than a real Ctrl+Alt. AltGr reports both, so typing ą or € would otherwise fire+ * every Ctrl+Alt chord and eat the character. Callers gate this on being off macOS: Option+ * reports AltGraph too, and it is a plain Alt.*/function isAltGraphEvent(event: {getModifierState?: (key: string) => boolean;@@ -619,10 +586,8 @@ export function formatCode(code: string): string {return named[code] ?? code;}-/**- * Display string, in the platform's own modifier order: macOS renders- * ⌃⌥⇧⌘ then the key, everything else spells the modifiers out.- */+/** Display string, in the platform's own modifier order: macOS renders ⌃⌥⇧⌘ then the key,+ * everything else spells the modifiers out. */export function formatBindingLabel(binding: ShortcutBinding,mac = isMacPlatform(),@@ -644,7 +609,6 @@ export function formatBindingLabel(return parts.join("+");}-/** Convenience for rendering a stored value straight to a chip. */export function formatBindingValueLabel(value: string | null,mac = isMacPlatform(),@@ -654,24 +618,21 @@ export function formatBindingValueLabel(}/**- * A binding with no modifier at all would swallow plain typing, so the- * recorder refuses it. Function keys are self-contained, and an action gated on- * an on-screen prompt (`allowBareKey`) may take any key.+ * A binding with no modifier at all would swallow plain typing, so the recorder refuses it.+ * Function keys are self-contained, and an action gated on an on-screen prompt (`allowBareKey`)+ * may take any key.*/export function isAcceptableBinding(binding: ShortcutBinding,allowBareKey = false,): boolean {if (binding.mod || binding.ctrl || binding.alt) return true;- // Tab moves focus, and a chord consumes the key it answers to. Bound bare,- // even on a prompt-gated action, it makes that prompt's own buttons- // unreachable by keyboard. Held with a modifier it is a chord like any- // other, which is where the recently-viewed walk sits.+ // Tab moves focus, and a chord consumes the key it answers to. Bound bare, even on a+ // prompt-gated action, it makes that prompt's own buttons unreachable by keyboard.if (binding.code === "Tab") return false;if (allowBareKey) return true;if (/^F\d{1,2}$/.test(binding.code)) return true;- // Escape is self-contained too, but bare it belongs to declining a tool call- // and is the way out of the recorder. Held with Shift it is free, which is- // where clearAllUnreads sits. Anything else has to say so with allowBareKey.+ // Escape is self-contained too, but bare it belongs to declining a tool call and is the way out+ // of the recorder. Held with Shift it is free, which is where clearAllUnreads sits.return binding.code === "Escape" && binding.shift;}diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsxindex 5a98bf9f305..3bf2f717e0d 100644--- a/studio/frontend/src/features/settings/settings-dialog.tsx+++ b/studio/frontend/src/features/settings/settings-dialog.tsx@@ -261,9 +261,8 @@ export function SettingsDialog() {const opener = useSettingsDialogStore((s) => s.opener);const openerFallback = useSettingsDialogStore((s) => s.openerFallback);const reduced = useReducedMotion();- // Mounting a heavy tab panel (System, Connections) in the same commit as- // the nav highlight makes the highlight lag the click. Render the panel- // from a deferred value so the nav updates first.+ // Mounting a heavy tab panel (System, Connections) in the same commit as the nav highlight makes+ // the highlight lag the click. Render the panel from a deferred value so the nav updates first.const panelTab = useDeferredValue(activeTab);const [query, setQuery] = useState("");diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex 08103523dfe..411c13d63d6 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -40,9 +40,8 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {"settings.profile.description","settings.profile.displayName","settings.profile.nickname",- // avatarShape lives inside the avatar edit popover, so it has no- // always-rendered label for search to scroll to.- // The stats heading and highlight tiles render for every profile; the+ // avatarShape lives inside the avatar edit popover, so it has no always-rendered label for+ // search to scroll to. The stats heading and highlight tiles render for every profile; the// insight and training cards are conditional, so they stay out."settings.profile.stats.title","settings.profile.stats.lifetimeTokens",diff --git a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts b/studio/frontend/src/features/settings/stores/appearance-custom-store.tsindex 1ef6916125c..ec44ea3a0ac 100644--- a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts+++ b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts@@ -356,8 +356,7 @@ function sanitizeSidebarMenu(value: unknown): SidebarMenuItemPref[] {seen.add(source.id);items.push({ id: source.id, visible: source.visible !== false });}- // Ids added after the payload was written land at the end with their- // default visibility.+ // Ids added after the payload was written land at the end with their default visibility.for (const id of SIDEBAR_MENU_ITEM_IDS) {if (!seen.has(id))items.push({ id, visible: SIDEBAR_MENU_DEFAULT_VISIBLE[id] });@@ -703,9 +702,8 @@ function syncImportedFonts(fonts: ImportedFont[]): void {const wanted = new Map((Array.isArray(fonts) ? fonts : []).map((f) => [f.name, f.dataUrl]),);- // Drop faces whose name is gone OR whose bytes changed: document.fonts is a- // set of FontFace objects, not keyed by family, so a stale face must be- // deleted before the new bytes are added.+ // Drop faces whose name is gone OR whose bytes changed: document.fonts is a set of FontFace+ // objects, not keyed by family, so a stale face must be deleted before the new bytes are added.for (const [name, entry] of registeredFontFaces) {if (wanted.get(name) !== entry.dataUrl) {document.fonts.delete(entry.face);@@ -823,10 +821,9 @@ export function applyCustomizationToDocument(setVar("--custom-chat-font", null);}- // The UI font size drives a typography scale factor, never the root font- // size: rem-based layout geometry must not move with the preference. The- // scale reaches text through the --text-* / --text-ui-* / --leading-*- // tokens in index.css.+ // The UI font size drives a typography scale factor, never the root font size: rem-based layout+ // geometry must not move with the preference. The scale reaches text through the --text-* /+ // --text-ui-* / --leading-* tokens in index.css.const effectiveUiFontSize = c.uiFontSize ?? UI_FONT_SIZE_RANGE.default;if (effectiveUiFontSize !== UI_FONT_SIZE_RANGE.default) {setVar(diff --git a/studio/frontend/src/features/settings/stores/embedding-model-store.ts b/studio/frontend/src/features/settings/stores/embedding-model-store.tsindex a495644c469..40cba88a33c 100644--- a/studio/frontend/src/features/settings/stores/embedding-model-store.ts+++ b/studio/frontend/src/features/settings/stores/embedding-model-store.ts@@ -47,11 +47,10 @@ interface EmbeddingModelState {// and shows an error, or an older model, over what the newer one just read.let latestLoad = 0;-// Each surface keeps its own pending flag, so the one the user switches to can-// write while the first write is still out. Request order is the best guess at-// which one the user meant, but not proof of what the backend ended on: the-// later one can fail verification, or persist first. So the newest answer wins-// the moment it lands, and once every overlapping write has settled the store+// Each surface keeps its own pending flag, so the one the user switches to can write while the+// first write is still out. Request order is the best guess at which one the user meant, but not+// proof of what the backend ended on: the later one can fail verification, or persist first. So the+// newest answer wins the moment it lands, and once every overlapping write has settled the store// re-reads instead of trusting the guess.let latestSave = 0;let savesInFlight = 0;diff --git a/studio/frontend/src/features/settings/stores/keyboard-shortcuts-store.ts b/studio/frontend/src/features/settings/stores/keyboard-shortcuts-store.tsindex 85196e5d2c5..0c1cd6ec131 100644--- a/studio/frontend/src/features/settings/stores/keyboard-shortcuts-store.ts+++ b/studio/frontend/src/features/settings/stores/keyboard-shortcuts-store.ts@@ -37,10 +37,9 @@ export type ShortcutOverrides = Partial</** Builds before alternates stored `id -> string | null`. Read that as the* primary slot, or every existing customization reverts to defaults. */function normalizeEntry(value: unknown): ShortcutOverrideEntry | null {- // A null back then cleared the action, which had one chord, so it has to- // clear both now. Left to the primary alone it would pick up whatever- // alternate has shipped since and start answering again, which is the- // opposite of what the user asked for.+ // A null back then cleared the action, which had one chord, so it has to clear both now. Left to+ // the primary alone it would pick up whatever alternate has shipped since and start answering+ // again, which is the opposite of what the user asked for.if (value === null) return { primary: null, alternate: null };// A rebind is different: the user chose a primary and never saw an// alternate, so that slot is untouched and takes the shipped default, thediff --git a/studio/frontend/src/features/settings/stores/monitor-frame-store.ts b/studio/frontend/src/features/settings/stores/monitor-frame-store.tsindex 95d3acb511b..65b33f0f6d7 100644--- a/studio/frontend/src/features/settings/stores/monitor-frame-store.ts+++ b/studio/frontend/src/features/settings/stores/monitor-frame-store.ts@@ -1,14 +1,11 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Where the floating panels are, in viewport coordinates. The Live monitor,-// the chat composer and the API monitor panel each publish their box here-// while mounted.-//-// Read only by api-monitor/panel-placement, which opens the API panel clear of-// the others. The notification rail is not a reader: it is anchored in CSS.-// Placing it from these boxes is what moved it out of its corner, since every-// input to that placement (composer height, download rows, release notes)+// Where the floating panels are, in viewport coordinates. The Live monitor, the chat composer and+// the API monitor panel each publish their box here while mounted. Read only by+// api-monitor/panel-placement, which opens the API panel clear of the others. The notification rail+// is not a reader: it is anchored in CSS. Placing it from these boxes is what moved it out of its+// corner, since every input to that placement (composer height, download rows, release notes)// changes on its own.import { create } from "zustand";diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.tsindex 776b76907f8..62f098524b0 100644--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts@@ -43,10 +43,9 @@ interface SettingsDialogState {open: boolean;activeTab: SettingsTab;scrollTarget: SettingsScrollTarget | null;- // Element focused when openDialog() ran. Radix's FocusScope normally tracks- // this, but the rAF-scheduled focus() in settings-dialog.tsx races its- // previous-focus capture, leaving focus on <body> after close. We restore- // explicitly via onCloseAutoFocus.+ // Element focused when openDialog() ran. Radix's FocusScope normally tracks this, but the+ // rAF-scheduled focus() in settings-dialog.tsx races its previous-focus capture, leaving focus on+ // <body> after close. We restore explicitly via onCloseAutoFocus.opener: HTMLElement | null;openerFallback: HTMLElement | null;// Set when something asks to jump straight to an archive listing (the archivediff --git a/studio/frontend/src/features/settings/stores/theme-store.ts b/studio/frontend/src/features/settings/stores/theme-store.tsindex 603467969f1..15beaaa7bd1 100644--- a/studio/frontend/src/features/settings/stores/theme-store.ts+++ b/studio/frontend/src/features/settings/stores/theme-store.ts@@ -54,10 +54,9 @@ function readStoredPalette(): Palette {return isPalette(stored) ? stored : "standard";}-// In-memory source of truth so a selected value survives even when-// localStorage is blocked (private browsing). Without it the snapshots would-// re-read empty storage and revert React state to the default while the DOM-// already changed.+// In-memory source of truth so a selected value survives even when localStorage is blocked (private+// browsing). Without it the snapshots would re-read empty storage and revert React state to the+// default while the DOM already changed.let currentTheme: Theme = readStoredTheme();let currentPalette: Palette = readStoredPalette();diff --git a/studio/frontend/src/features/settings/tabs/agents-tab.tsx b/studio/frontend/src/features/settings/tabs/agents-tab.tsxindex e239f1de712..14a25a07f6e 100644--- a/studio/frontend/src/features/settings/tabs/agents-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/agents-tab.tsx@@ -308,10 +308,9 @@ function discoverGgufModels(models.push(model);};for (const model of items) {- // /api/models/list reports the backend's raw identifier, which for a native- // grant is the host path that status deliberately withholds. The resident- // model reaches the picker through status instead, so drop path-shaped ids- // rather than leak one into the list and into the copied command.+ // /api/models/list reports the backend's raw identifier, which for a native grant is+ // the host path status deliberately withholds. The resident model reaches the picker+ // through status instead, so drop path-shaped ids rather than leak one into the command.if (!model.is_gguf || looksLikePath(model.id)) {continue;}@@ -330,17 +329,14 @@ function discoverGgufModels(return { models, variants };}-// Scanned local GGUFs (./models, LM Studio, custom folders) that the caches above-// miss. The id is the load id, i.e. the on-disk path for anything outside the active-// cache, so label the row by repo id when there is one but keep the path to load by.-// model_format is only set by the scanners that compute it: _scan_hf_cache leaves it-// unset, so a custom scan folder holding an HF cache layout would vanish from the-// picker on an exclusive check. Treat unset as unknown and fall back to the name.+// Scanned local GGUFs (./models, LM Studio, custom folders) the caches above miss. The id is+// the load id, i.e. the on-disk path outside the active cache, so label by repo id when there+// is one but keep the path to load by. model_format is set only by the scanners that compute+// it (_scan_hf_cache leaves it unset), so treat unset as unknown and fall back to the name.function isLocalGguf(model: LocalModelInfo): boolean {- // The scanners set this only for a directory holding a primary, non-mmproj GGUF- // and no other weights, so an unset format means "not GGUF", not "unknown". Do not- // guess from the name: a safetensors folder called Foo-GGUF would load the- // transformers backend and then fail the GGUF-only agents.+ // The scanners set this only for a directory holding a primary, non-mmproj GGUF and no other+ // weights, so an unset format means "not GGUF", not "unknown". Do not guess from the name: a+ // safetensors folder called Foo-GGUF would load transformers and then fail the GGUF-only agents.return (model.model_format ?? "").toLowerCase() === "gguf";}@@ -349,9 +345,8 @@ function localGgufEntries(): { id: string; label: string }[] {const entries: { id: string; label: string }[] = [];for (const model of models) {- // partial marks an interrupted sharded download: variant discovery would treat- // the shards it has as complete and build a command that fails on load. The- // cached repo row still offers it, and _repo_gguf_load_id withholds the path.+ // partial marks an interrupted sharded download: variant discovery would treat the shards it+ // has as complete and build a command that fails on load. The cached repo row still offers it.if (model.partial || !(model.id && isLocalGguf(model))) {continue;}@@ -408,7 +403,6 @@ function activeGgufSelection(};}-/** Official provider or agent logo when available, else a monogram tile. */function AgentIcon({logo,icon,@@ -659,11 +653,10 @@ export function AgentsTab() {return p.startsWith("win") || p.includes("windows");});const origin = typeof window !== "undefined" ? window.location.origin : "";- // Browser commands target the viewed origin; a desktop window origin is a Tauri URL- // the CLI cannot reach, so use the backend URL from /api/health (getApiBase until it- // lands). The command then runs wherever that CLI is: a loopback base is this Unsloth's- // own host, so deviceType decides, and it reports wsl where the browser would claim- // Windows. For any other base the client platform is only the initial guess.+ // Browser commands target the viewed origin; a desktop window origin is a Tauri URL the CLI+ // cannot reach, so use the backend URL from /api/health (getApiBase until it lands). A loopback+ // base is this Unsloth's own host, so deviceType decides and reports wsl where the browser would+ // claim Windows. For any other base the client platform is only the initial guess.const studioBase = isTauri ? (serverUrl ?? getApiBase()) : origin;const inferredCommandOs: ExampleOs = (isLoopbackBase(studioBase)@@ -706,7 +699,6 @@ export function AgentsTab() {const [cachedLoadIds, setCachedLoadIds] = useState<Record<string, string>>({},);- // Display names for scanned models, keyed by the path that identifies them.const [modelLabels, setModelLabels] = useState<Record<string, string>>({});// The model /api/inference/status reports as resident, so the command attaches to it// rather than remapping to another cached copy.@@ -812,10 +804,9 @@ export function AgentsTab() {const visibleModels = matchingModels.slice(0, MODEL_RESULT_LIMIT);const preferredVariant = knownVariants[selectedModel] ?? null;const selectedAgentDetails = detailsFor(selectedAgent);- // A GGUF outside the active cache does not resolve by repo id, so name its- // snapshot path; `unsloth start` now also matches a path by the basename- // /v1/models advertises for it. The resident model is exempt: it already- // loaded by id, and cached-gguf keeps the largest copy across caches, whose+ // A GGUF outside the active cache does not resolve by repo id, so name its snapshot path;+ // `unsloth start` also matches a path by the basename /v1/models advertises. The resident model+ // is exempt: it loaded by id, and cached-gguf keeps the largest copy across caches, whose// snapshot could switch cache or quant under it.const selectedModelIsActive =activeStatusModel != null &&@@ -986,7 +977,6 @@ export function AgentsTab() {}));}).catch(() => {- // The example model keeps the builder useful if discovery fails.});return () => {cancelled = true;@@ -1042,10 +1032,9 @@ export function AgentsTab() {});}, []);- // The resident GGUF went away (unloaded, or replaced by a transformer model).- // Following it means letting go too, or the command would name a stale model and- // switch the shared server back. A native-grant label is not even loadable, so it- // leaves the list entirely. An explicit pick still wins.+ // The resident GGUF went away (unloaded, or replaced by a transformer model). Following it means+ // letting go too, or the command would name a stale model and switch the shared server back. A+ // native-grant label is not even loadable, so it leaves the list entirely. An explicit pick wins.const dropActiveModel = useCallback((attachOnly: string | null, wasActive: string | null) => {if (attachOnly) {@@ -1096,10 +1085,9 @@ export function AgentsTab() {],);- // Another client, or a load that finishes after this tab opens, can change what- // is resident on a shared server. Keep tracking it rather than pinning the model- // seen at mount, or the command would name a stale one and switch the server- // back, unloading it for every attached session. An explicit pick still wins.+ // Another client, or a load finishing after this tab opens, can change what is resident on a+ // shared server. Keep tracking it rather than pinning the model seen at mount, or the command+ // would switch the server back, unloading it for every attached session. An explicit pick wins.useEffect(() => {let cancelled = false;const sync = () => {@@ -1133,11 +1121,9 @@ export function AgentsTab() {if (!(restored && discoveredKeys && statusSettled)) return;const active = activeModelRef.current;restoredModel.current = null;- // modelKey both sides: discovery folds repo-id case, so an exact match- // would retire a valid pick just for a different spelling.- // A path is never in discoveredKeys (the catalog drops path ids and a scan- // root may not cover it), but `unsloth start --model <path>` is valid, so- // absence there is not evidence.+ // modelKey both sides: discovery folds repo-id case, so an exact match would retire a valid pick+ // for a different spelling. A path is never in discoveredKeys (the catalog drops path ids and a+ // scan root may not cover it), but `unsloth start --model <path>` is valid, so absence is not evidence.if (looksLikePath(restored) ||isHuggingFaceRepo(restored) ||@@ -1150,9 +1136,8 @@ export function AgentsTab() {modelSelectionChanged.current = false;chosenVariant.current = null;setStoredModel(null, null);- // adopt straight away rather than parking on the example model: the next- // poll is STATUS_POLL_MS away, and a command copied meanwhile would switch- // a shared server off whatever is loaded.+ // adopt straight away rather than parking on the example model: the next poll is STATUS_POLL_MS+ // away, and a command copied meanwhile would switch a shared server off whatever is loaded.if (active) {adoptActiveModel(active);return;@@ -1164,9 +1149,8 @@ export function AgentsTab() {useEffect(() => {let cancelled = false;- // A scanned directory is not repo-shaped but still has a path to enumerate, and- // after discovery that path IS the identity. Only a standalone .gguf file, which- // is one quant by definition, is genuinely variantless.+ // A scanned directory is not repo-shaped but still has a path to enumerate, and after discovery+ // that path IS the identity. Only a standalone .gguf file is genuinely variantless.const localDir =cachedLoadId ??(looksLikePath(selectedModel) &&@@ -1174,9 +1158,8 @@ export function AgentsTab() {? selectedModel: null);if (!(isHuggingFaceRepo(selectedModel) || localDir)) {- // A loose .gguf is one quant already. Status can record a quant parsed from its- // filename, and restoring that would add --gguf-variant, which a bare file path- // cannot resolve, so it stays null here.+ // A loose .gguf is one quant already. Status can record a quant parsed from its filename, and+ // restoring that would add --gguf-variant, which a bare file path cannot resolve.const standaloneFile = selectedModel.toLowerCase().endsWith(".gguf");queueMicrotask(() => {if (cancelled) {@@ -1207,9 +1190,8 @@ export function AgentsTab() {}// Clear a prior failure once a later request (e.g. after adding a token) succeeds.setVariantsFailed(false);- // Drop partial quants: an interrupted split download still lists a quant, and- // naming it builds a command that resolves the shards it has and then fails on- // the missing ones.+ // Drop partial quants: an interrupted split download still lists a quant, and naming it builds+ // a command that resolves the shards it has and then fails on the missing ones.const uniqueVariants = Array.from(new Map(info.variants@@ -1221,12 +1203,9 @@ export function AgentsTab() {const available = new Set(uniqueVariants.map((variant) => variant.quant),);- // Authoritative for this repo: drop a remembered quant it no longer- // offers, or adoptActiveModel re-imposes it on the next poll.- // Stop adoptActiveModel re-imposing a quant this repo will not serve.- // In-memory only: `partial` here means "still downloading", and an- // offline reply lists just the cache, so neither is grounds to delete- // the user's saved quant. Dropping the ref re-runs this next mount.+ // Authoritative for this repo: drop a remembered quant it no longer offers, or adoptActiveModel+ // re-imposes it on the next poll. In-memory only: `partial` here means "still downloading", and+ // an offline reply lists just the cache, so neither is grounds to delete the user's saved quant.const remembered = rememberedVariant(selectedModel);if (remembered && !available.has(remembered)) {chosenVariant.current = null;diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsxindex fbf6e6c93d1..ec1fe77fc68 100644--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx@@ -130,9 +130,8 @@ export function DataTab() {const [fineTuneExporting, setFineTuneExporting] = useState(false);const [openingRecipe, setOpeningRecipe] = useState(false);const [loadingTraining, setLoadingTraining] = useState(false);- // Chat-only hosts redirect /studio back to /chat, so loading a dataset in- // the Train tab would upload it and then strand the user; gate the action- // the same way the sidebar gates Train.+ // Chat-only hosts redirect /studio back to /chat, so loading a dataset in the Train tab would+ // upload it and then strand the user; gate the action the same way the sidebar gates Train.const chatOnly = usePlatformStore((s) => s.isChatOnly());const ragUnavailable = useRagAvailabilityStore((s) => s.isUnavailable());const ragAvailabilityUnknown = useRagAvailabilityStore((s) =>@@ -393,10 +392,9 @@ export function DataTab() {const handleUseInTraining = async () => {setLoadingTraining(true);try {- // Same deferred module as above. The training store and datasets-api it also- // pulls stay eager either way, since __root.tsx imports the @/features/training- // barrel that re-exports both; Recipe Studio is what actually leaves the- // startup bundle.+ // Same deferred module as above. The training store and datasets-api it also pulls stay eager+ // either way, since __root.tsx imports the @/features/training barrel that re-exports both;+ // Recipe Studio is what actually leaves the startup bundle.const { loadFineTuneDatasetInTrainTab } = await import("../components/finetune-recipe");diff --git a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx b/studio/frontend/src/features/settings/tabs/debugging-tab.tsxindex 28f65d61470..472e3b75e86 100644--- a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx@@ -61,9 +61,8 @@ export function DebuggingTab() {// A burst larger than one response continues on the next poll, which in// manual mode never comes unless the user knows to ask for it.const [morePending, setMorePending] = useState(false);- // File logging is off and an older session's log is still on disk, so the- // pane shows real content that will never grow. Unsaid, a stale log is- // indistinguishable from a live one.+ // File logging is off and an older session's log is still on disk, so the pane shows real content+ // that will never grow. Unsaid, a stale log is indistinguishable from a live one.const [staleSession, setStaleSession] = useState(false);const { copied, copy } = useCopyFeedback();@@ -126,11 +125,10 @@ export function DebuggingTab() {return;}if (isLogSourceGone(error)) {- // The id we hold is no longer enumerated (file removed, or pushed out of- // the per-family window). The backend sends 404 so the picker rebuilds;- // without this the loop re-polls a dead id forever. Reselecting the- // server's default terminates: it comes from the same walk, and- // "nothing at all" is a 200 with a status, not another 404.+ // The id we hold is no longer enumerated (file removed, or pushed out of the per-family+ // window). The backend sends 404 so the picker rebuilds; without this the loop re-polls a+ // dead id forever. Reselecting the server's default terminates: it comes from the same+ // walk, and "nothing at all" is a 200 with a status, not another 404.cursorRef.current = null;await refreshSources({ signal, reselect: true });return;@@ -140,9 +138,8 @@ export function DebuggingTab() {[refreshSources, t],);- // The llama runner writes a NEW file per load attempt, so a list fetched at- // mount goes stale exactly when it matters: fail a load with the tab open and- // that failure's log is not offered.+ // The llama runner writes a NEW file per load attempt, so a list fetched at mount goes stale+ // exactly when it matters: fail a load with the tab open and that failure's log is not offered.const rescanSourcesIfStale = useCallback(async (signal?: AbortSignal) => {if (Date.now() - lastSourceScanRef.current < SOURCE_RESCAN_MS) return;@@ -216,10 +213,9 @@ export function DebuggingTab() {cursorRef.current = null;setBuffer(EMPTY_BUFFER);setRealpath(null);- // Every notice below describes the file being left, so all of them go with- // it. Clearing only `dropped` let a failed first read on the new source keep- // claiming the OLD one's state, and in manual mode nothing retries: the pane- // sat there calling a live log a frozen session.+ // Every notice below describes the file being left, so all of them go with it. Clearing only+ // `dropped` let a failed first read on the new source keep claiming the OLD one's state, and in+ // manual mode nothing retries: the pane sat there calling a live log a frozen session.setDropped(false);setMorePending(false);setStaleSession(false);diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex a26c760edc5..217af8bbacd 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -94,9 +94,8 @@ const PREFS_KEYS: string[] = [SIDEBAR_ORGANIZATION_STORAGE_KEY,"unsloth_settings_active_tab",SETTINGS_PANEL_PREFS_STORAGE_KEY,- // Rebound chords. Without this a reset leaves the user on shortcuts they- // asked to throw away, and a chord bound to something unusable has no- // escape hatch from this button.+ // Rebound chords. Without this a reset leaves the user on shortcuts they asked to throw away, and+ // a chord bound to something unusable has no escape hatch from this button.KEYBOARD_SHORTCUTS_STORAGE_KEY,// Outranks the install-wide setting, so a reset that left it behind would keep ignoring// transport changes made elsewhere.@@ -123,15 +122,13 @@ const PREFS_KEYS: string[] = [// Model selector settings ("Select model settings" group)"unsloth_chat_expand_quantizations","unsloth_chat_show_all_quantizations",- // The memory bar's opt-in. Reset All advertises restoring defaults and this- // feature's default is off, so leaving the key out left it switched on across- // a reset that said it had turned everything back.- //- // Spelled out rather than imported as CHAT_SHOW_MEMORY_BAR_KEY, for the same- // reason the note above gives: it lives in chat-runtime-store, which is in an- // import cycle with this file, so the constant would still be in its temporal- // dead zone when this module-scope list is built. A test pins this literal- // against the store's constant so the two cannot drift apart silently.+ // The memory bar's opt-in. Reset All advertises restoring defaults and this feature's default is+ // off, so leaving the key out left it switched on across a reset that said it had turned+ // everything back. Spelled out rather than imported as CHAT_SHOW_MEMORY_BAR_KEY, for the same+ // reason the note above gives: it lives in chat-runtime-store, which is in an import cycle with+ // this file, so the constant would still be in its temporal dead zone when this module-scope list+ // is built. A test pins this literal against the store's constant so the two cannot drift apart+ // silently."unsloth_chat_show_memory_bar","unsloth_models_fit_on_device_only",// Chat presetsdiff --git a/studio/frontend/src/features/settings/tabs/keyboard-shortcuts-tab.tsx b/studio/frontend/src/features/settings/tabs/keyboard-shortcuts-tab.tsxindex 6d86b4c2426..029b8aefd0b 100644--- a/studio/frontend/src/features/settings/tabs/keyboard-shortcuts-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/keyboard-shortcuts-tab.tsx@@ -140,11 +140,10 @@ export function KeyboardShortcutsTab() {if (!recording) return;const def = SHORTCUT_DEFS.find((entry) => entry.id === recording.id);const onKeyDown = (event: KeyboardEvent) => {- // Tab held bare is never an acceptable binding, so it is still what it- // was: the way out. Left swallowed with the rest, a row that records- // bare keys had no keyboard exit at all, since Escape is a chord there- // and Enter or Space on the focused pencil records instead of pressing- // it. Not prevented, so focus moves on as it would have.+ // Tab held bare is never an acceptable binding, so it is still what it was: the way out. Left+ // swallowed with the rest, a row that records bare keys had no keyboard exit at all, since+ // Escape is a chord there and Enter or Space on the focused pencil records instead of+ // pressing it. Not prevented, so focus moves on as it would have.if (event.code === "Tab" &&!event.metaKey &&@@ -157,10 +156,9 @@ export function KeyboardShortcutsTab() {}event.preventDefault();event.stopPropagation();- // Every keydown is swallowed above, so bare Escape is the only way out of- // recording. The exception is a row that takes bare keys: Escape is the- // chord it ships, so recording it has to be possible, and the pencil- // cancels there instead.+ // Every keydown is swallowed above, so bare Escape is the only way out of recording. The+ // exception is a row that takes bare keys: Escape is the chord it ships, so recording it has+ // to be possible, and the pencil cancels there instead.if (event.code === "Escape" &&!event.metaKey &&@@ -291,9 +289,8 @@ export function KeyboardShortcutsTab() {const value = resolveBinding(overrides, def.id, slot);return !value || shortcutOwningBinding(overrides, value) !== def.id;});- // Anything this action ships an alternate for keeps its line, cleared or- // not: hiding a cleared slot would take its restore control with it, and- // Reset all is not a way back from one edit.+ // Anything this action ships an alternate for keeps its line, cleared or not: hiding a cleared+ // slot would take its restore control with it, and Reset all is not a way back from one edit.const hasAlternate =defaultBindingFor(def, "alternate", mac) !== null ||resolveBinding(overrides, def.id, "alternate") !== null ||diff --git a/studio/frontend/src/features/settings/tabs/voice-tab.tsx b/studio/frontend/src/features/settings/tabs/voice-tab.tsxindex ce93f44cba7..daaebfafd85 100644--- a/studio/frontend/src/features/settings/tabs/voice-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/voice-tab.tsx@@ -560,11 +560,10 @@ export function VoiceTab() {try {const status = await fetchSttStatus(statusNonce, sttModel);if (cancelled) return;- // A curated model prefers the GGUF (whisper.cpp) engine, but without- // whisper-server the backend serves it through Transformers instead of- // failing. Fall back to the Transformers status here too, or the model- // shows as unavailable and download is blocked even though it works.- // mtmd models run nowhere else, so they never fall back.+ // A curated model prefers the GGUF (whisper.cpp) engine, but without whisper-server the+ // backend serves it through Transformers instead of failing. Fall back to the Transformers+ // status here too, or the model shows as unavailable and download is blocked even though it+ // works. mtmd models run nowhere else, so they never fall back.const engineStatus = isMtmdModel? status.mtmd: isGgufModel && status.gguf?.available@@ -715,10 +714,9 @@ export function VoiceTab() {try {await startSttDownload(sttModel, hfApiToken(hfToken));trackSttDownload(sttModel);- // The status effect only re-polls while it can see a download. Its last- // read was before this one existed, and the on-demand branch schedules- // nothing, so without a nudge the tab shows Download for the whole- // transfer.+ // The status effect only re-polls while it can see a download. Its last read was before this+ // one existed, and the on-demand branch schedules nothing, so without a nudge the tab shows+ // Download for the whole transfer.setStatusNonce((nonce) => nonce + 1);} catch (error) {toast.error(t("settings.voice.dictation.sttDownloadFailed"), {diff --git a/studio/frontend/src/features/studio/sections/dataset-preview-dialog.tsx b/studio/frontend/src/features/studio/sections/dataset-preview-dialog.tsxindex c6de29841f5..be09e97f467 100644--- a/studio/frontend/src/features/studio/sections/dataset-preview-dialog.tsx+++ b/studio/frontend/src/features/studio/sections/dataset-preview-dialog.tsx@@ -223,7 +223,6 @@ export function DatasetPreviewDialog({? `Detected ${data.detected_format} format. No manual column mapping needed.`: null;- // ── AI Assist ──────────────────────────────────────────────────────const [isAiLoading, setIsAiLoading] = useState(false);const [aiError, setAiError] = useState<string | null>(null);const aiAssistControllerRef = useRef<AbortController | null>(null);diff --git a/studio/frontend/src/features/training/api/datasets-api.ts b/studio/frontend/src/features/training/api/datasets-api.tsindex 597b12bfe6d..08c81d3c588 100644--- a/studio/frontend/src/features/training/api/datasets-api.ts+++ b/studio/frontend/src/features/training/api/datasets-api.ts@@ -132,8 +132,6 @@ async function uploadTrainingDatasetForm(return res.json();}-// ── AI Assist ──-type AiAssistMappingArgs = {columns: string[];samples: Record<string, unknown>[];diff --git a/studio/frontend/src/features/training/hooks/use-training-transformers-upgrade-notice.ts b/studio/frontend/src/features/training/hooks/use-training-transformers-upgrade-notice.tsindex 3bae3925081..a6239d034c7 100644--- a/studio/frontend/src/features/training/hooks/use-training-transformers-upgrade-notice.ts+++ b/studio/frontend/src/features/training/hooks/use-training-transformers-upgrade-notice.ts@@ -59,10 +59,9 @@ export function useTrainingTransformersUpgradeNotice(): TrainingTransformersUpgr// the flag travels on its own rather than being read off the path.const preferLocalCache = Boolean(modelKnownCached);const localPath = (preferLocalCache && modelLocalPath) || null;- // The cache is the state; this counter only re-renders once an answer lands in it,- // keeping setState out of the effect body. Reading the map during render already- // answers for a model asked about before, and switching models needs no reset because- // the key changes with it.+ // The cache is the state; this counter only re-renders once an answer lands in it, keeping+ // setState out of the effect body. Reading the map during render already answers for a model+ // asked about before, and switching models needs no reset because the key changes with it.const [, markAnswered] = useState(0);const key = selectedModel? upgradeNoticeCacheKey(diff --git a/studio/frontend/src/features/training/lib/model-defaults.ts b/studio/frontend/src/features/training/lib/model-defaults.tsindex 1bcc0901a8c..0463ac94f99 100644--- a/studio/frontend/src/features/training/lib/model-defaults.ts+++ b/studio/frontend/src/features/training/lib/model-defaults.ts@@ -38,10 +38,9 @@ function toStringArray(value: unknown): string[] | undefined {return result.length > 0 ? result : undefined;}-// The spellings studio/backend/core/training/trainer.py accepts, so a file means-// the same thing to the picker as it does to the trainer. A quoted "false" read-// as "leave it at the default" is how a config asking for no checkpointing ended-// up training with Unsloth GC.+// The spellings studio/backend/core/training/trainer.py accepts, so a file means the same thing to+// the picker as it does to the trainer. A quoted "false" read as "leave it at the default" is how a+// config asking for no checkpointing ended up training with Unsloth GC.const GRADIENT_CHECKPOINTING_ALIASES = new Map<string,TrainingConfigState["gradientCheckpointing"]@@ -130,11 +129,10 @@ export function mapBackendModelConfigToTrainingPatch(if (warmupSteps !== undefined) {patch.warmupSteps = warmupSteps;} else {- // Ten shipped model_defaults express warmup as a ratio and set no- // warmup_steps, default.yaml among them, so reading only warmup_steps left- // every one of them on the generic UI default. Materialize with ceil, the- // way TrainingArguments.get_warmup_steps does, so a small ratio such as an- // imported 0.03 over 10 steps asks for warmup and gets it instead of zero.+ // Ten shipped model_defaults express warmup as a ratio and set no warmup_steps, default.yaml+ // among them, so reading only warmup_steps left every one of them on the generic UI default.+ // Materialize with ceil, the way TrainingArguments.get_warmup_steps does, so a small ratio such+ // as an imported 0.03 over 10 steps asks for warmup and gets it instead of zero.const warmupRatio = toNumber(training?.warmup_ratio);if (warmupRatio !== undefined && maxSteps !== undefined && maxSteps > 0) {patch.warmupSteps = Math.ceil(warmupRatio * maxSteps);diff --git a/studio/frontend/src/features/training/lib/training-upgrade-notice-cache.ts b/studio/frontend/src/features/training/lib/training-upgrade-notice-cache.tsindex 02a7c2d14be..e73426eb27e 100644--- a/studio/frontend/src/features/training/lib/training-upgrade-notice-cache.ts+++ b/studio/frontend/src/features/training/lib/training-upgrade-notice-cache.ts@@ -3,13 +3,11 @@import type { TransformersUpgradeCheck } from "@/features/transformers-upgrade";-// One answer per (sidecar generation, model, cached copy, token) for the Configure-// preview. The config.json read behind the check is a network round trip and the notice-// hook runs on every Configure render, so without this, scrubbing a slider would re-ask.-//-// The generation is in the key because an install invalidates every answer here: the-// release offered is now installed, and the sidecar it activated flips forces16Bit on-// for models that reported 4-bit before.+// One answer per (sidecar generation, model, cached copy, token) for the Configure preview. The+// config.json read behind the check is a network round trip and the notice hook runs on every+// Configure render, so without this, scrubbing a slider would re-ask. The generation is in the key+// because an install invalidates every answer here: the release offered is now installed, and the+// sidecar it activated flips forces16Bit on for models that reported 4-bit before.const cache = new Map<string, TransformersUpgradeCheck>();// Separator no field can contain: a model id, a cache path and a token are all printable.@@ -36,15 +34,13 @@ export function upgradeNoticeCacheKey(].join(KEY_SEPARATOR);}-// Entries from a superseded generation can never be read again, so drop them rather than-// let an install-per-session leak the whole map.-//-// The generation only counts up, so an older one is always a straggler: a check fired-// before an install can still be in flight when it lands, resolving after the-// post-install check answered. Letting that write rewind the generation would clear the-// fresh entry and store the stale answer in its place, and since its effect was already-// cleaned up nothing re-asks, so the preview would show no notice for the rest of the-// session. Superseded reads and writes are ignored: null, never the whole map.+// Entries from a superseded generation can never be read again, so drop them rather than let an+// install-per-session leak the whole map. The generation only counts up, so an older one is always+// a straggler: a check fired before an install can still be in flight when it lands, resolving+// after the post-install check answered. Letting that write rewind the generation would clear the+// fresh entry and store the stale answer in its place, and since its effect was already cleaned up+// nothing re-asks, so the preview would show no notice for the rest of the session. Superseded+// reads and writes are ignored: null, never the whole map.function activeCache(sidecarGeneration: number): typeof cache | null {if (sidecarGeneration < cachedGeneration) {return null;diff --git a/studio/frontend/src/features/training/lib/yaml-config.ts b/studio/frontend/src/features/training/lib/yaml-config.tsindex 3be434330d9..02c2b67b3ca 100644--- a/studio/frontend/src/features/training/lib/yaml-config.ts+++ b/studio/frontend/src/features/training/lib/yaml-config.ts@@ -27,10 +27,9 @@ export function parseYamlConfig(text: string): BackendModelConfig {console.warn("Ignored unknown YAML keys:", unknownKeys.join(", "));}- // File import is authoritative: force vision_image_size = null when the- // training section is missing/malformed/lacks the key, so a stale store- // value can't survive an import. (Same-model defaults reloads preserve- // user choice via Object.hasOwn in model-defaults.ts.)+ // File import is authoritative: force vision_image_size = null when the training section is+ // missing/malformed/lacks the key, so a stale store value can't survive an import. (Same-model+ // defaults reloads preserve user choice via Object.hasOwn in model-defaults.ts.)const rawTraining = raw.training;const isPlainTrainingObject =rawTraining != null &&diff --git a/studio/frontend/src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.ts b/studio/frontend/src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.tsindex 63872dfa9be..0d377af8f9b 100644--- a/studio/frontend/src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.ts+++ b/studio/frontend/src/features/transformers-upgrade/stores/transformers-upgrade-dialog-store.ts@@ -128,10 +128,9 @@ export const useTransformersUpgradeDialogStore =get().resolve(true);return;}- // Structured failure: the swap failed but may have already unloaded the- // chat model; record that so a later cancel still rolls the caller back.- // A version mismatch also carries the superseding release, so Retry- // re-requests a version that can actually succeed.+ // Structured failure: the swap failed but may have already unloaded the chat model; record+ // that so a later cancel still rolls the caller back. A version mismatch also carries the+ // superseding release, so Retry re-requests a version that can actually succeed.const { upgrade } = get();set({phase: "error",diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.tsindex d0a6f326f24..aa10a6e268e 100644--- a/studio/frontend/src/features/video/api.ts+++ b/studio/frontend/src/features/video/api.ts@@ -218,7 +218,6 @@ export interface GalleryVideo {text_encoder_quant?: string | null;memory_mode?: string | null;offload_policy?: string | null;- // Creation time (ISO 8601 timestamp).created_at: string;// Library state, not recipe: stored beside the clip, absent on sidecars written before this existed.pinned?: boolean;diff --git a/studio/frontend/src/features/video/reference-budget.ts b/studio/frontend/src/features/video/reference-budget.tsindex 183ad2317fa..3a9f41baf83 100644--- a/studio/frontend/src/features/video/reference-budget.ts+++ b/studio/frontend/src/features/video/reference-budget.ts@@ -73,9 +73,8 @@ export function referenceFileRejection(kind: ReferenceKind,file: { type: string; size: number; name?: string },): string | null {- // Name as well as MIME, matching the accept list above and the native drop:- // the same recording chosen through the button used to be refused for the- // empty type the browser gave it.+ // Name as well as MIME, matching the accept list above and the native drop: the same recording+ // chosen through the button used to be refused for the empty type the browser gave it.const named = { type: file.type, name: file.name ?? "" };const matches = kind === "video" ? isVideoFile(named) : isAudioAttachmentFile(named);if (!matches) {diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex cb333edbb92..21d235d06f6 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -179,10 +179,9 @@ import {} from "./api";import { videoThumbnailQueue, withThumbnailRetries } from "./thumbnail-request-queue";-// Curated models come from the shared catalog, one group per model with a format second level-// (which also surfaces LTX-2.3 in Recommended). Host-dependent: a Mac gets only GGUF rows.-// The format second level also surfaces LTX-2.3 in Recommended, since its HF pipeline_tag is-// image-to-video. The load kind per artifact comes from loadSpecFor.+// Curated models come from the shared catalog, one group per model with a format second level,+// which also surfaces LTX-2.3 in Recommended since its HF pipeline_tag is image-to-video.+// Host-dependent: a Mac gets only GGUF rows. The load kind per artifact comes from loadSpecFor.function useVideoModels(host: HostClass): ModelOption[] {return useMemo(() => catalogToModelOptions(VIDEO_CATALOG, host), [host]);}@@ -320,7 +319,6 @@ function clipMeta(video: GalleryVideo): string {return `${secs} · ${video.width}×${video.height}`;}-// Bar label for an in-flight generation, plus an ETA while denoising.function genStepLabel(p: VideoGenerateProgress): string {if (p.phase === "decode") return "Decoding video and audio…";if (p.phase === "export") return "Encoding video…";@@ -485,7 +483,6 @@ function ResolvedBadge({);}-// One "what actually ran" line in the loaded-build summary below. Mirrors the images page.function BuildRow({ label, value, badge }: { label: string; value: string; badge?: ReactNode }) {return (<div className="flex items-center justify-between gap-2">@@ -564,7 +561,6 @@ function reportLoadFailure(message: string | null | undefined, fallback: string)toast.error(text || fallback);}-// A compact labeled Select row for the Advanced Options panel.function AdvancedSelect({label,hint,@@ -605,7 +601,6 @@ function AdvancedSelect({);}-// One row in the loaded-model status line.function StatusChip({ label, value }: { label: string; value: string }) {return (<span className="inline-flex items-center gap-1">@@ -645,7 +640,6 @@ function ReferenceVideoTrimStatus({);}-// The full generation recipe for a clip, with a one-click "restore to inputs".function RecipePopover({video,onRestore,@@ -779,10 +773,10 @@ type PendingH3Load = {const H3_BF16_REPO = "MiniMaxAI/MiniMax-H3";-/** Whether a pick is the H3 base pipeline, whose denoiser partition the user must choose.- * Shared by both entry points, since a chat-picker pick reaches loadOrStage without passing- * through handleModelSelect. An on-device copy counts, and a Hub-id equality test never- * recognises one, so it is matched on the final path segment. */+/** Whether a pick is the H3 base pipeline, whose denoiser partition the user must choose. Shared+ * by both entry points, since a chat-picker pick reaches loadOrStage without passing through+ * handleModelSelect. An on-device copy counts and a Hub-id equality test never recognises one, so+ * it is matched on the final path segment. */function isH3PipelinePick(repoId: string, kind: VideoLoadOptions["kind"]): boolean {if (kind !== "pipeline") return false;const id = repoId.toLowerCase();@@ -825,10 +819,9 @@ function VideoGate({ children }: { children: ReactNode }) {);}-/** Capability gate in front of the generator. The root guard never bounces /video: a chat-only- * host is both where the explanation has something to say and where video works anyway- * (Apple Silicon whose only problem is MLX), so the page answers for itself, from- * /api/system/hardware, which settles detection before replying. */+/** Capability gate in front of the generator. The root guard never bounces /video: a chat-only host+ * is both where the explanation has something to say and where video works anyway (Apple Silicon+ * whose only problem is MLX), so the page answers for itself from /api/system/hardware. */export function VideoPage({active = true,onInitialReady,@@ -983,7 +976,6 @@ function VideoGenerator({const [canReapply, setCanReapply] = useState(false);const [busy, setBusy] = useState<Busy>(null);- // Live per-step progress (phase / step / total + ETA) polled during generation.const [genStep, setGenStep] = useState<VideoGenerateProgress | null>(null);const genPollTimer = useRef<ReturnType<typeof setInterval> | null>(null);// visibilitychange handler active while a generation poll runs: background tabs clamp@@ -1460,10 +1452,10 @@ function VideoGenerator({const canPickAudioFlowShift = status?.defaults?.supports_audio_flow_shift === true;- // Reseed the Advanced selects from the LOADED build, so a declined request snaps to what- // engaged and Precision never advertises a scheme the DiT is not running. Keyed on the- // LOAD-TIME half of the record: the backend rewrites transformer_cache at GENERATION time,- // so the whole record let a step-cache toggle discard a pending edit.+ // Reseed the Advanced selects from the LOADED build, so a declined request snaps to what engaged+ // and Precision never advertises a scheme the DiT is not running. Keyed on the LOAD-TIME half of+ // the record: the backend rewrites transformer_cache at GENERATION time, so the whole record let a+ // step-cache toggle discard a pending edit.const resolvedKey = status?.loaded ? resolvedSeedKey(status.resolved) : null;useEffect(() => {const record = status?.loaded ? status.resolved : null;@@ -2044,10 +2036,9 @@ function VideoGenerator({}, [setStatusIfNewest]);// A generation can be refused because the runtime went away under the page: an idle auto-unload- // frees it server-side and the browser hears nothing. Without a re-read here Generate stays- // enabled off the stale flag and every retry 409s again, so the refusal is the news. Also- // clears the state that only means anything while one is resident (the Reapply target, a- // replacement load's tracking).+ // frees it server-side and the browser hears nothing, so without a re-read Generate stays enabled+ // off the stale flag and every retry 409s again. Also clears the state that only means anything+ // while one is resident (the Reapply target, a replacement load's tracking).const resyncAfterGenerateRefusal = useCallback(async () => {// A model picked while this read is in flight makes the answer stale rather than wrong:// /video/status reports committed state, so it says loaded: false for the load that has just@@ -2106,9 +2097,9 @@ function VideoGenerator({() =>subscribeModelEjected("video", () => {dropResidentState();- // That eject cancelled the replacement load, and its progress poll is the only thing that- // clears `busy`, which dropResidentState just stopped; leaving it set locks the page.- // Narrowed to "loading" so a generation is left alone, and held until the start settles.+ // That eject cancelled the replacement load, and its progress poll is the only thing that clears+ // `busy`, which dropResidentState just stopped; leaving it set locks the page. Narrowed to+ // "loading" so a generation is left alone, and held until the start settles.const pending = pendingStart.current;if (pending) {setBusy((prev) => (prev === "loading" ? "unloading" : prev));@@ -2213,7 +2204,6 @@ function VideoGenerator({void pollLoadProgress();}, [pollLoadProgress, cancelLoadFromToast]);- // Stops the generation poll and its visibilitychange catch-up listener.const stopGenPoll = useCallback(() => {if (genPollTimer.current) clearInterval(genPollTimer.current);genPollTimer.current = null;@@ -2577,10 +2567,9 @@ function VideoGenerator({source: ModelSelectorChangeMeta["source"] = "hub",token?: number,): Promise<boolean> => {- // Every Hub pick needs the plan, not just an undownloaded one: a cached checkpoint can still- // be missing its base repo's text encoder or VAE. Staging never sets `busy`, so plans- // resolve in response order; bumped before the non-hub return too, so a local pick- // invalidates an in-flight hub plan.+ // Every Hub pick needs the plan, not just an undownloaded one: a cached checkpoint can still be+ // missing its base repo's text encoder or VAE. Staging never sets `busy`, so plans resolve in+ // response order; bumped before the non-hub return too, so a local pick invalidates one in flight.const pick = ++pickSeq.current;// The previous pick's staged intent dies with it: a pick that stages nothing never calls// stage(), so the queue keeps the older job and its onReady loads the abandoned model.@@ -2617,10 +2606,9 @@ function VideoGenerator({// Superseded. Report started so this pick's `.then` leaves the newer label alone.if (pick !== pickSeq.current || !owns()) return true;// Same selection-time refusal the images page makes: the plan is the last point at which an- // incompatible pairing can be caught before the download it would waste. No video family- // declares one today, so this is the shared envelope's half rather than a live path.- // The check is the FLUX.2 GGUF/base size pairing, and the video planner has no diffusers base to- // pair against, so this is the shared envelope's half of the contract rather than a live path.+ // incompatible pairing can be caught before the download it would waste. The check is the FLUX.2+ // GGUF/base size pairing and the video planner has no diffusers base to pair against, so this is+ // the shared envelope's half of the contract rather than a live path.incompatible = plan.incompatible_reason ?? null;if (!incompatible && plan.entries.length > 0) {pendingStagedLoad.current = {@@ -2637,9 +2625,9 @@ function VideoGenerator({bytes: e.bytes,ggufFilename: e.gguf_filename,// The entry carrying the picked checkpoint file, so the panel can label it without guessing:- // filenames cannot tell the two apart, and repo identity is not enough when a checkpoint- // shares its repo with cached companions. The backend's answer wins, since a gated pipeline- // is staged from an ungated MIRROR; nullish coalescing, since false is still an answer.+ // filenames cannot tell the two apart, and repo identity is not enough when a checkpoint shares its+ // repo with cached companions. The backend's answer wins, since a gated pipeline is staged from an+ // ungated MIRROR; nullish coalescing, since false is still an answer.checkpoint:e.checkpoint ??(opts.filename@@ -2849,7 +2837,6 @@ function VideoGenerator({pickGuard.cancel();}, [abandonPick, pickGuard]);- // Reload the current model with the current advanced options.const handleReapply = useCallback(() => {// Status is authoritative when another client replaced the resident model; the ref remains the// fallback while this page's own load is committing.@@ -2863,10 +2850,10 @@ function VideoGenerator({}}, [handleLoad]);- // The chat picker emits (modelId, quant + filename) for a GGUF, or just (modelId) for a- // curated pipeline pick. Every pick supersedes the one before it: a staged download outlives- // its pick, so clearing only inside loadOrStage left the old job free to load the abandoned- // model. This also invalidates any plan still in flight.+ // The chat picker emits (modelId, quant + filename) for a GGUF, or just (modelId) for a curated+ // pipeline pick. Every pick supersedes the one before it: a staged download outlives its pick, so+ // clearing only inside loadOrStage left the old job free to load the abandoned model, and this+ // also invalidates any plan still in flight.const beginPick = useCallback(() => {pickSeq.current += 1;pendingStagedLoad.current = null;@@ -3051,11 +3038,11 @@ function VideoGenerator({try {setStatusIfNewest(++statusTicket.current, await unloadVideoModel());setQuant(null);- // Hold the page until any load start still in flight has run to its END, compensating unload- // and all. Without the fence an eject landing before the start registered returned success- // and cleared busy, so the next pick was refused while the older load carried on.- // That older handler, seeing the newer loadSeq, skips its compensating unload and returns without- // restarting its poll, leaving a multi-gigabyte load running with no toast and no cancel control.+ // Hold the page until any load start still in flight has run to its END, compensating unload and+ // all. Without the fence an eject landing before the start registered returned success and cleared+ // busy, so the next pick was refused while the older load carried on: that older handler, seeing+ // the newer loadSeq, skips its compensating unload and leaves a multi-gigabyte load running with+ // no toast and no cancel control.const pending = pendingStart.current;if (pending) {try {@@ -3211,7 +3198,6 @@ function VideoGenerator({void resyncAfterGenerateRefusal();return;}- // Track live progress + the terminal outcome via the shared poll loop.startGenPoll();}, [prompt,@@ -3242,7 +3228,6 @@ function VideoGenerator({resyncAfterGenerateRefusal,]);- // The Advanced (load-time) tuning controls, rendered in the right-docked panel below.const advancedControls = (<><AdvancedSelectdiff --git a/studio/frontend/src/hooks/backend-preflight-message.ts b/studio/frontend/src/hooks/backend-preflight-message.tsindex 06a7665086b..ad652475538 100644--- a/studio/frontend/src/hooks/backend-preflight-message.ts+++ b/studio/frontend/src/hooks/backend-preflight-message.ts@@ -18,10 +18,9 @@ export function preflightStaleMessage(// The backend appends the setting it could not preserve, as `reason:NAME`, so// the discriminator is the part before the colon and the name is the rest.const [kind, setting] = (reason ?? "").split(":", 2);- // Not an install problem: the home folder itself is unreachable, and updating- // needs the same folder. The roaming-profile cause is a Windows one, but this- // reason reaches every platform (`home_dir_available()` is probed ungated), so- // it is offered rather than asserted.+ // Not an install problem: the home folder itself is unreachable, and updating needs the same+ // folder. The roaming-profile cause is a Windows one, but this reason reaches every platform+ // (`home_dir_available()` is probed ungated), so it is offered rather than asserted.if (kind === WORKING_DIRECTORY_UNAVAILABLE) {const cause =typeof navigator !== "undefined" && /Win/i.test(navigator.platform ?? "")diff --git a/studio/frontend/src/hooks/gpu-vram.ts b/studio/frontend/src/hooks/gpu-vram.tsindex 796c44fa8f5..1b5603aed5d 100644--- a/studio/frontend/src/hooks/gpu-vram.ts+++ b/studio/frontend/src/hooks/gpu-vram.ts@@ -1,9 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Split out of use-system.ts so the VRAM rules can be unit tested without pulling-// the auth and React graph in behind them. Typed structurally, so SystemGpuInfo and-// GpuDevice satisfy these without importing them.+// Split out of use-system.ts so the VRAM rules can be unit tested without pulling the auth and React graph in+// behind them. Typed structurally, so SystemGpuInfo and GpuDevice satisfy these without importing them.export interface VramReportingDevice {vram_used_gb?: number;@@ -30,10 +29,8 @@ export interface VramReportingGpu {vram_used_gb_aggregate?: number | null;}-/** Sum dedicated VRAM while counting a shared host-memory pool only once.- *- * Devices arrive rounded to 2dp, so summing them reintroduces float error- * (three B200s at 179.06 give 537.1800000000001) and not every caller rounds+/** Sum dedicated VRAM while counting a shared host-memory pool only once. Devices arrive rounded to 2dp, so+ * summing them reintroduces float error (three B200s at 179.06 give 537.1800000000001) and not every caller rounds* again before printing. Round back to the precision they arrived with. */export function aggregateGpuMemoryTotalGb(devices: MemoryTotalDevice[],@@ -111,17 +108,12 @@ export interface MemoryCapacityDevice {memoryTotalGb: number;sharedMemory: boolean;sharedMemoryHostBackedGb?: number | null;- /** The backend's per-device `unified_memory`, for a ROCm APU.- *- * Separate from `sharedMemory` because the backend reports them separately and- * they do not coincide: `hardware.py` sets `shared_memory` only on Windows, so- * on Linux the very same APU arrives as `unified_memory: true,- * shared_memory: false`. Reading only `sharedMemory` there counts the APU's- * carved window as VRAM standing BESIDE system RAM, when it is a view INTO it.- *- * Both flags mean the same thing for capacity, which is why- * `sharesHostMemory` below folds them together rather than either one being- * taught about the other. */+ /** The backend's per-device `unified_memory`, for a ROCm APU. Separate from `sharedMemory` because the backend+ * reports them separately and they do not coincide: `hardware.py` sets `shared_memory` only on Windows, so on+ * Linux the very same APU arrives as `unified_memory: true, shared_memory: false`. Reading only `sharedMemory`+ * there counts the APU's carved window as VRAM standing BESIDE system RAM, when it is a view INTO it. Both+ * flags mean the same thing for capacity, which is why `sharesHostMemory` below folds them together rather than+ * either one being taught about the other. */unifiedMemory?: boolean;}@@ -187,11 +179,10 @@ export interface MemoryCapacityInput {hostDevices?: MemoryCapacityDevice[];/** Aggregate GPU budget of the whole inventory, for the unpinned case. */hostGpuTotalGb: number;- /** The same aggregate with shared-memory devices left out, for the unpinned case.- * Only the dedicated cards are memory BESIDE system RAM; an iGPU's budget is a- * capped view of that same RAM, so adding both to reach a machine-wide ceiling- * counts the shared bytes twice. Absent means "no shared device", i.e. the same- * figure as `hostGpuTotalGb`. */+ /** The same aggregate with shared-memory devices left out, for the unpinned case. Only the dedicated cards are+ * memory BESIDE system RAM; an iGPU's budget is a capped view of that same RAM, so adding both to reach a+ * machine-wide ceiling counts the shared bytes twice. Absent means "no shared device", i.e. the same figure as+ * `hostGpuTotalGb`. */hostDedicatedGpuTotalGb?: number;/** Whether ANY device on the host reports a shared pool. Only consulted when* nothing is pinned; a pin answers for itself. */@@ -268,11 +259,10 @@ export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {(input.hostDedicatedGpuTotalGb as number) >= 0? (input.hostDedicatedGpuTotalGb as number): hostGpuTotalGb;- // The budget is what the next load is ALLOWED to claim, so it is the capacity a- // verdict should be measured against: at 80% a 20 GB footprint on a 24 GB card is- // over the line the slider draws, and reading the raw total called it comfortable.- // Guarded rather than trusted: a 0 or a missing value would silently zero the- // capacity, which every caller reads as "nothing probed".+ // The budget is what the next load is ALLOWED to claim, so it is the capacity a verdict should be+ // measured against: at 80% a 20 GB footprint on a 24 GB card is over the line the slider draws,+ // and reading the raw total called it comfortable. Guarded rather than trusted: a 0 or a missing+ // value would silently zero the capacity, which every caller reads as "nothing probed".const budget =typeof input.gpuBudgetFraction === "number" &&input.gpuBudgetFraction > 0 &&@@ -311,10 +301,9 @@ export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {Number.isFinite(input.systemRamTotalGb) && input.systemRamTotalGb > 0? input.systemRamTotalGb: 0;- // Every, for the same reason the host-level flag uses every: a pin naming a- // discrete card alongside an iGPU still has dedicated VRAM beside system RAM, and- // calling that one pool hides the GPU verdict on the only figure that would catch- // a fixed placement too large for the card.+ // Every, for the same reason the host-level flag uses every: a pin naming a discrete card+ // alongside an iGPU still has dedicated VRAM beside system RAM, and calling that one pool hides+ // the GPU verdict on the only figure that would catch a fixed placement too large for the card.const sharesSystemRam = pinGoverns? pinnedTotals.shared > 0 && pinnedTotals.dedicated === 0: input.hostSharesSystemRam;@@ -325,13 +314,12 @@ export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {? input.unifiedMemory && input.unifiedPoolReportedAsGpuMemory !== false// Apple reports the one pool as the GPU budget already.? gpuCapacityGb- // A Vulkan iGPU's budget, and a ROCm APU's, are both a CAPPED view of system- // RAM, so RAM must not be added to it -- but it must not replace it either.- // The pool's real size is the RAM, and taking the capped figure as the- // machine's whole capacity called a 20 GB CPU-offloaded load impossible on a- // 91 GiB host because the iGPU was allowed 12. The larger of the two is the- // pool; on a mixed inventory that under-counts a discrete card sitting beside- // it, which is the side that refuses a load rather than admitting one that+ // A Vulkan iGPU's budget, and a ROCm APU's, are both a CAPPED view of system RAM, so RAM+ // must not be added to it -- but it must not replace it either. The pool's real size is the+ // RAM, and taking the capped figure as the machine's whole capacity called a 20 GB+ // CPU-offloaded load impossible on a 91 GiB host because the iGPU was allowed 12. The+ // larger of the two is the pool; on a mixed inventory that under-counts a discrete card+ // sitting beside it, which is the side that refuses a load rather than admitting one that// cannot run.: Math.max(gpuCapacityGb, systemRamTotalGb)// Dedicated VRAM, not the whole GPU figure: on a mixed inventory the iGPU'sdiff --git a/studio/frontend/src/hooks/server-stop-intent.ts b/studio/frontend/src/hooks/server-stop-intent.tsindex 94e770d93fa..0a7d2716812 100644--- a/studio/frontend/src/hooks/server-stop-intent.ts+++ b/studio/frontend/src/hooks/server-stop-intent.ts@@ -1,10 +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-// The "the user stopped the server on purpose" marker.-//-// sessionStorage outlives webview reloads but not the app process, so an explicit stop-// holds across Reload while a fresh launch still auto-starts.+// The "the user stopped the server on purpose" marker. sessionStorage outlives webview reloads but+// not the app process, so an explicit stop holds across Reload while a fresh launch still+// auto-starts.export const USER_STOPPED_KEY = "unsloth_server_user_stopped";// Every access is wrapped: private browsing, blocked cookies and opaque webview originsdiff --git a/studio/frontend/src/hooks/use-gpu-info.ts b/studio/frontend/src/hooks/use-gpu-info.tsindex f90c3f179b7..9889d74118f 100644--- a/studio/frontend/src/hooks/use-gpu-info.ts+++ b/studio/frontend/src/hooks/use-gpu-info.ts@@ -141,10 +141,9 @@ function toGpuInfo(),),sharedMemory: memoryTotals.shared > 0 && memoryTotals.dedicated === 0,- // Additive, and deliberately some() where sharedMemory above is "no dedicated- // pool at all": one unified part makes the aggregate total partly host RAM,- // which is already enough to stop it being a VRAM ceiling a fit verdict can- // be measured against.+ // Additive, and deliberately some() where sharedMemory above is "no dedicated pool at all": one+ // unified part makes the aggregate total partly host RAM, which is already enough to stop it+ // being a VRAM ceiling a fit verdict can be measured against.unifiedMemory: devices.some((device) => device.unified_memory === true),available: true,budgetKnown: true,@@ -174,17 +173,15 @@ function toGpuDevices(// about the CUDA / ROCm devices an image or video load can be pinned to.forDiffusion = false,): SystemGpuDevice[] {- // GGUF loads run through llama-server, so on a Vulkan build the pickable set- // is the inference inventory, not the torch view: it can see cards torch- // cannot, and its indices are the ggml ordinals `--device Vulkan<i>` pins.- // The XPU ban does not apply there, it is about torch-xpu ordinals that no- // applicator speaks; a Vulkan pick does not use them.+ // GGUF loads run through llama-server, so on a Vulkan build the pickable set is the inference+ // inventory, not the torch view: it can see cards torch cannot, and its indices are the ggml+ // ordinals `--device Vulkan<i>` pins. The XPU ban does not apply there, it is about torch-xpu+ // ordinals that no applicator speaks; a Vulkan pick does not use them.const inference = data?.inference_gpu;if (!forDiffusion && inference?.backend === "vulkan") {- // The installed inference backend is confirmed Vulkan, so even an empty- // device list (probe still cold, or transiently failed) must NOT fall- // through to the torch/CUDA inventory below: those physical IDs are- // meaningless to a Vulkan llama-server, and the backend rejects every+ // The installed inference backend is confirmed Vulkan, so even an empty device list (probe+ // still cold, or transiently failed) must NOT fall through to the torch/CUDA inventory below:+ // those physical IDs are meaningless to a Vulkan llama-server, and the backend rejects every// explicit diffusion pin outright while is_vulkan_build is true. Report no// pinnable/diffusionPinnable devices until the probe succeeds.if (!(inference.devices ?? []).length) return [];diff --git a/studio/frontend/src/hooks/use-llama-update-check.ts b/studio/frontend/src/hooks/use-llama-update-check.tsindex 7d98f503530..8707656b52a 100644--- a/studio/frontend/src/hooks/use-llama-update-check.ts+++ b/studio/frontend/src/hooks/use-llama-update-check.ts@@ -125,11 +125,10 @@ function parseStatus(value: unknown): LlamaUpdateStatus | null {};}-// The backend job persists as "success" until the next update starts (it's a-// single in-memory record, not per-tab), so a fresh mount -- a new tab, or a-// page reload of a tab that already resynced -- would otherwise replay the-// same completed job forever. Persist the handled marker outside React state-// so it survives both, and is shared across tabs in this browser.+// The backend job persists as "success" until the next update starts (it's a single in-memory+// record, not per-tab), so a fresh mount -- a new tab, or a page reload of a tab that already+// resynced -- would otherwise replay the same completed job forever. Persist the handled marker+// outside React state so it survives both, and is shared across tabs in this browser.const HANDLED_RELOAD_STORAGE_KEY = "unsloth_llama_update_reload_handled_at";function getHandledReloadAt(): string | null {@@ -205,11 +204,10 @@ export function useLlamaUpdateCheck({useEffect(() => {onReloadRequiredRef.current = onReloadRequired;}, [onReloadRequired]);- // Fires the callback once per completed job, whether this tab watched it run- // or only saw the persisted "success" after the fact (e.g. another tab- // applied it). Keyed by finished_at and seeded from localStorage so a fresh- // mount (new tab, or a page reload of a tab that already resynced) doesn't- // replay a job some tab already handled.+ // Fires the callback once per completed job, whether this tab watched it run or only saw the+ // persisted "success" after the fact (e.g. another tab applied it). Keyed by finished_at and+ // seeded from localStorage so a fresh mount (new tab, or a page reload of a tab that already+ // resynced) doesn't replay a job some tab already handled.const reloadNotifiedForRef = useRef<string | null>(getHandledReloadAt());const clearPollTimer = useCallback(() => {@@ -219,18 +217,16 @@ export function useLlamaUpdateCheck({}}, []);- // Shared by the poll path (this tab watched the job run), the surface path- // (this tab only saw the persisted success), and apply()'s stale-click path- // (the job came back embedded in a "not started" response) so none of them- // can drop or double-fire the notification.+ // Shared by the poll path (this tab watched the job run), the surface path (this tab only saw the+ // persisted success), and apply()'s stale-click path (the job came back embedded in a "not+ // started" response) so none of them can drop or double-fire the notification.const notifyReloadIfNeeded = useCallback((job: Pick<LlamaUpdateJob, "state" | "reload_required" | "finished_at">,) => {- // "error" is included for partial chained updates: the llama phase can- // land (and unload the server) before a later phase fails, and the- // backend keeps reload_required set in exactly that case. Without the- // resync the chat UI would keep pointing at the unloaded model.+ // "error" is included for partial chained updates: the llama phase can land (and unload the+ // server) before a later phase fails, and the backend keeps reload_required set in exactly+ // that case. Without the resync the chat UI would keep pointing at the unloaded model.if ((job.state === "success" || job.state === "error") &&job.reload_required &&@@ -259,10 +255,9 @@ export function useLlamaUpdateCheck({clearPollTimer();if (s.job.state === "success") {void refreshHardwareInfo();- // The update unloads the running model server-side, so the chat- // runtime still points at a model that now 400s on send. Let the- // consumer drop the selector to "select model" instead of waiting for- // a page reload. Fires here (not just from apply's onDone) so a+ // The update unloads the running model server-side, so the chat runtime still points at a+ // model that now 400s on send. Let the consumer drop the selector to "select model"+ // instead of waiting for a page reload. Fires here (not just from apply's onDone) so a// cross-tab update mirrored through this poll is covered too.notifyReloadIfNeeded(s.job);onDone?.({@@ -298,10 +293,9 @@ export function useLlamaUpdateCheck({if (!pollTimer.current) startJobPoll();return;}- // A completed job persists as "success" until the next update starts, so- // a tab that missed the running window entirely (mounted, or only checks- // hourly and misses both the running and just-finished moments) still- // needs to resync here, not just from the poll path above.+ // A completed job persists as "success" until the next update starts, so a tab that missed+ // the running window entirely (mounted, or only checks hourly and misses both the running and+ // just-finished moments) still needs to resync here, not just from the poll path above.notifyReloadIfNeeded(next.job);},[startJobPoll, notifyReloadIfNeeded],@@ -338,11 +332,10 @@ export function useLlamaUpdateCheck({};}, [enabled, surfaceIfAvailable, clearPollTimer]);- // Cross-tab nudge: a tab that only checks hourly would otherwise stay- // pointed at a server-unloaded model for up to an hour after a DIFFERENT- // open tab applies an update. The storage event only fires in other tabs- // (never the one that wrote it), so this recheck fires promptly there- // without this tab redundantly re-triggering itself.+ // Cross-tab nudge: a tab that only checks hourly would otherwise stay pointed at a+ // server-unloaded model for up to an hour after a DIFFERENT open tab applies an update. The+ // storage event only fires in other tabs (never the one that wrote it), so this recheck fires+ // promptly there without this tab redundantly re-triggering itself.useEffect(() => {if (!enabled) return;const onStorage = (event: StorageEvent) => {@@ -410,10 +403,9 @@ export function useLlamaUpdateCheck({// open Settings surface disables and follows the same install immediately.signalRunningLlamaJob(actionJob);- // Non-started jobs stay idle; an already-running update is tracked below.- // A backend switch is not: it shares this job but installs no new release,- // so following it here would toast an update that never happened. The- // shared background listener still follows the switch itself.+ // Non-started jobs stay idle; an already-running update is tracked below. A backend switch is+ // not: it shares this job but installs no new release, so following it here would toast an+ // update that never happened. The shared background listener still follows the switch itself.if (action &&action.started === false &&diff --git a/studio/frontend/src/hooks/use-model-memory.ts b/studio/frontend/src/hooks/use-model-memory.tsindex 114c3fdd825..0da16e17615 100644--- a/studio/frontend/src/hooks/use-model-memory.ts+++ b/studio/frontend/src/hooks/use-model-memory.ts@@ -4,18 +4,15 @@/*** VRAM estimate for one downloaded model, for the picker's memory bar.*- * Per row, because the rows are spread across a dozen render sites. The work is- * shared though: `/kv-cache-estimate` reads GGUF metadata off disk, so answers- * are cached by the inputs that change them and duplicate requests fold into- * one. Ten rows of the same model cost one read.+ * Per row, because the rows are spread across a dozen render sites. The work is shared though:+ * `/kv-cache-estimate` reads GGUF metadata off disk, so answers are cached by the inputs that+ * change them and duplicate requests fold into one.*/-// Deep paths, not the `@/features/chat` barrel, and that is load-bearing. The barrel-// reaches this file back: chat -> apply-inference-status-to-store -> model-picker ->-// model-selector -> pickers -> here. Importing the barrel closed that ring, and under-// dev's unbundled ESM the app died on a blank page with "Cannot access-// 'CHAT_GPU_MEMORY_MODE_KEY' before initialization". Production builds hid it, because-// the bundler hoists the declarations into one module and the ordering stops mattering.+// Deep paths, not the `@/features/chat` barrel, and that is load-bearing. The barrel reaches this+// file back: chat -> apply-inference-status-to-store -> model-picker -> model-selector -> pickers+// -> here. Importing the barrel closed that ring, and under dev's unbundled ESM the app died on a+// blank page. Production builds hid it, since the bundler hoists the declarations into one module.import { estimateKvCache } from "@/features/chat/api/chat-api";import {CHAT_GPU_MEMORY_MODE_KEY,@@ -59,14 +56,12 @@ export interface ModelMemorySource {/** Size from the listing, so the bar draws before the estimate arrives. */sizeBytes?: number | null;/**- * The concrete thing this row loads, when the listing resolved one.- *- * Selecting the row loads this, while the estimate resolved by repo id alone,- * so on a duplicate or recovered HF cache the two could pick different copies- * of the same quant and the bar would describe a model the click does not- * open. Falls back to the repo id upstream, so sending it changes nothing for- * an ordinary row.- */+ * The concrete thing this row loads, when the listing resolved one.+ *+ * Selecting the row loads this, while the estimate resolved by repo id alone, so on a duplicate+ * or recovered HF cache the two could pick different copies of the same quant. Falls back to the+ * repo id upstream, so sending it changes nothing for an ordinary row.+ */loadId?: string | null;}@@ -101,17 +96,16 @@ const CACHE = new Map<string, Estimate>();const IN_FLIGHT = new Map<string, Promise<Estimate>>();/**- * Cap on remembered answers. A session can browse a lot of models, and each- * entry is keyed by settings as well as identity, so the key space is larger- * than the model count. Oldest-first eviction; a re-fetch costs one disk read.+ * Cap on remembered answers. A session can browse a lot of models, and each entry is keyed by+ * settings as well as identity, so the key space is larger than the model count. Oldest-first+ * eviction; a re-fetch costs one disk read.*/const CACHE_LIMIT = 256;/**- * How long a failure is remembered. Failures are cached so an unsizable model- * doesn't re-request on every reopen, but the common cause is the backend being- * briefly unavailable -- without expiry those rows would stay blank for the rest- * of the session.+ * How long a failure is remembered. Failures are cached so an unsizable model does not re-request+ * on every reopen, but the common cause is the backend being briefly unavailable, and without+ * expiry those rows would stay blank for the rest of the session.*/const FAILURE_TTL_MS = 30_000;@@ -163,11 +157,10 @@ const MISS: Estimate = {/*** Re-read saved settings whenever any of them are written.*- * Two sources, because a model with no override follows the standing- * preference: the per-model configs, which announce themselves, and the- * standing GPU-memory mode and speculative type, which live in localStorage and- * so raise no same-tab event of their own. The runtime store changes in lockstep- * with those writes in-session, so it stands in as their notification.+ * Two sources, because a model with no override follows the standing preference: the per-model+ * configs, which announce themselves, and the standing GPU-memory mode and speculative type, which+ * live in localStorage and raise no same-tab event. The runtime store changes in lockstep with+ * those writes in-session, so it stands in as their notification.*/function subscribeToConfigChanges(onChange: () => void): () => void {if (typeof window === "undefined") return () => {};@@ -176,11 +169,9 @@ function subscribeToConfigChanges(onChange: () => void): () => void {onChange();};window.addEventListener(PER_MODEL_CONFIG_UPDATED_EVENT, onConfigWrite);- // The custom event above is same-tab only, by construction: the native- // storage event fires in every OTHER document sharing the origin and never in- // the one that made the write. So settings edited in a second Studio tab- // arrive here as a storage event and nowhere else, and without this a mounted- // bar kept its old fit or OOM verdict indefinitely.+ // The custom event above is same-tab only, by construction: the native storage event fires in+ // every OTHER document sharing the origin and never in the one that made the write. So settings+ // edited in a second Studio tab arrive here as a storage event and nowhere else.const onStorage = (event: Event) => {const key = (event as StorageEvent).key;// A null key means the whole store was cleared, which counts.@@ -198,11 +189,9 @@ function subscribeToConfigChanges(onChange: () => void): () => void {/*** localStorage keys whose cross-tab writes change what the bar should show.*- * A function, not a module-scope array. This module is in an import cycle- * through features/chat, so it can be evaluated while chat-runtime-store is- * still initializing; naming these keys at module scope then reads a `const`- * in its temporal dead zone and throws at import time, taking the page down.- * By call time every module has finished loading.+ * A function, not a module-scope array: this module is in an import cycle through features/chat,+ * so it can be evaluated while chat-runtime-store is still initializing, and naming these keys at+ * module scope then reads a `const` in its temporal dead zone and throws at import time.*/const watchedStorageKeys = () => [PER_MODEL_CONFIG_STORAGE_KEY,@@ -219,29 +208,23 @@ const readZeroEpoch = () => 0;let configEpoch = 0;let lastConfigSignature = "";let lastPrefSignature = "";-// Serialising every saved config is the expensive half, and only a config write-// can change it. The store ticks on every streamed token, so doing that work on-// each tick would put an O(all configs) stringify in the render path.+// Serialising every saved config is the expensive half, and only a config write can change it. The+// store ticks on every streamed token, so doing that work per tick would put an O(all configs)+// stringify in the render path.let configsDirty = true;/**- * A value that changes whenever any saved config does, so the estimate can be- * re-keyed. The settings sheet sits directly beside these rows, and without- * this a context change leaves the bar showing the old KV segment.+ * A value that changes whenever any saved config does, so the estimate can be re-keyed. The+ * settings sheet sits directly beside these rows, and without this a context change leaves the bar+ * showing the old KV segment.*/function readConfigEpoch(): number {- // The standing GPU-memory mode and speculative type matter as much as the- // saved configs: a model with no override follows them. Without them,- // switching the global mode to Manual left every mounted bar drawn against a- // budget the load would no longer use, and turning MTP on globally left the- // draft reserve missing, until the row happened to remount. Both are two- // short strings, so they are cheap to check on every read.- // The session GPU pin belongs here because budgetIsMeaningful reads it. It- // lives in the runtime store rather than in a saved config, so a preset or a- // session-only load configuration changes it with no config write: the- // whole-store subscription did fire, but this snapshot did not move, so- // useSyncExternalStore suppressed the rerender and a bar stayed drawn against- // aggregate multi-GPU VRAM after the launch had been pinned to one card.+ // The standing GPU-memory mode and speculative type matter as much as the saved configs, since a+ // model with no override follows them: without them, switching the global mode to Manual left+ // every mounted bar drawn against a budget the load would no longer use. The session GPU pin+ // belongs here too because budgetIsMeaningful reads it: it lives in the runtime store rather than+ // a saved config, so a preset changes it with no config write, and the whole-store subscription+ // fired while this snapshot did not move, so a bar stayed drawn against aggregate multi-GPU VRAM.const pin = useChatRuntimeStore.getState();// The session speculative mode belongs here for the same reason: it is read// above and never written to a config, so nothing else would move the epoch.@@ -265,14 +248,10 @@ function readConfigEpoch(): number {/*** The user's saved settings for this exact variant, if any.*- * Variant-exact only, matching `resolveInitialConfig`: the load path looks up- * (modelId, ggufVariant) and drops to defaults when there's no hit. Falling back- * to a model-level entry here would size the bar from settings the variant will- * never load with.- *- * Keys are stored normalized, which lower-cases hub repo ids, so comparing raw- * strings would miss every mixed-case repo and quietly use defaults instead of- * the context length and KV dtype the user chose.+ * Variant-exact only, matching `resolveInitialConfig`: the load path looks up (modelId,+ * ggufVariant) and drops to defaults when there is no hit, so falling back to a model-level entry+ * would size the bar from settings the variant will never load with. Keys are stored normalized,+ * which lower-cases hub repo ids, so comparing raw strings would miss every mixed-case repo.*/function configFor(source: ModelMemorySource): PerModelConfig | undefined {const wantId = normalizeModelIdentity(source.repoId);@@ -290,18 +269,13 @@ function pinnedContext(config: PerModelConfig | undefined): number | undefined {}/**- * Whether the budget we're handed still describes where this model will load.- *- * Callers pass the total across visible GPUs. Pin the model to a subset, or- * offload layers to CPU, and that total stops being the ceiling the model is- * judged against -- charting against it would call a 30 GB quant "fits" on a- * 2x24 GB host pinned to one card. Better to draw nothing than to mislead.+ * Whether the budget we are handed still describes where this model will load.*- * The "at default" tests mirror `gpuFieldsAtDefault` in per-model-config: note- * that a negative gpuLayers is the runtime's Auto value, not an override, so a- * truthiness check here would hide the bar for ordinary saved configs. GPU mode- * falls back to the standing preference, which is what the loader does when a- * model has no override of its own.+ * Callers pass the total across visible GPUs. Pin the model to a subset, or offload layers to CPU,+ * and that total stops being the ceiling: charting against it would call a 30 GB quant "fits" on a+ * 2x24 GB host pinned to one card. The "at default" tests mirror `gpuFieldsAtDefault` in+ * per-model-config: a negative gpuLayers is the runtime's Auto value, not an override, so a+ * truthiness check here would hide the bar for ordinary saved configs.*/function budgetIsMeaningful(config: PerModelConfig | undefined): boolean {const mode = config?.gpuMemoryMode ?? readPersistedGpuMemoryMode();@@ -312,19 +286,15 @@ function budgetIsMeaningful(config: PerModelConfig | undefined): boolean {const sessionPin = useChatRuntimeStore.getState().selectedGpuIds;if (sessionPin != null && sessionPin.length > 0) return false;if (!config) return true;- // Pass-through args are appended after Unsloth's own flags, so an -ngl or a- // device pin in that box is what the launch actually uses. Reading only the- // structured fields left the bar charting a CPU-offloaded run against every- // GPU on the host.+ // Pass-through args are appended after Unsloth's own flags, so an -ngl or a device pin in that box+ // is what the launch actually uses. Reading only the structured fields left the bar charting a+ // CPU-offloaded run against every GPU on the host.if (extraArgsOwnPlacement(config.llamaExtraArgs)) return false;- // Same reasoning one term over: these do not move the cache, they resize it.- // The estimate is built from the structured controls, so a --swa-full in the- // box has the launch reserve a full-context cache while the bar priced the- // compact sliding window, and the row reads as a comfortable fit.+ // Same reasoning one term over: these do not move the cache, they resize it. A --swa-full in the+ // box has the launch reserve a full-context cache while the bar priced the compact sliding window.if (extraArgsShapeKvCache(config.llamaExtraArgs)) return false;- // And these add resident files nothing here priced -- a LoRA, a control- // vector, a hand-named drafter. The total would be short by whatever they- // weigh, with no sign of it in the bar.+ // And these add resident files nothing here priced -- a LoRA, a control vector, a hand-named+ // drafter. The total would be short by whatever they weigh, with no sign of it in the bar.if (extraArgsAddResidentFiles(config.llamaExtraArgs)) return false;return (config.selectedGpuIds == null &&@@ -342,11 +312,9 @@ function budgetIsMeaningful(config: PerModelConfig | undefined): boolean {function effectiveSpeculativeType(config: PerModelConfig | undefined,): string | undefined {- // The live runtime value before the persisted one. Forced modes (mtp,- // mtp+ngram, dspark, dflash) are deliberately session-only and are never- // returned by readPersistedSpeculativeType, so a model loaded with one of them- // but not remembered was priced as auto -- and auto drops MTP on an MLA target- // while the forced load engages it and opens another full cache.+ // The live runtime value before the persisted one. Forced modes are deliberately session-only and+ // are never returned by readPersistedSpeculativeType, so a model loaded with one but not+ // remembered was priced as auto, which drops MTP on an MLA target while the forced load engages it.return (config?.speculativeType ??useChatRuntimeStore.getState().speculativeType ??@@ -428,16 +396,10 @@ export function useModelMemory(const enabled = useChatRuntimeStore((state) => state.showMemoryBar);// Read before the subscription below, because that subscription is not free:- // subscribeToConfigChanges watches the whole chat runtime store, which ticks on- // every streamed token. Every row in the list mounts this hook, so subscribing- // unconditionally meant each token woke every mounted row to re-read a snapshot- // it would not use -- including with the feature switched off entirely. Both- // branches are module-level constants, so swapping between them resubscribes- // once on toggle rather than on every render.- // `source` as well as `enabled`: an unselected picker row calls this hook with- // no source and can never draw a bar, but it still reached the subscription- // and so re-read the epoch -- localStorage included -- on every streamed- // token. A long list multiplied each token by the number of mounted rows.+ // subscribeToConfigChanges watches the whole chat runtime store, which ticks on every streamed+ // token, so subscribing unconditionally woke every mounted row per token, feature off included.+ // `source` as well as `enabled`: an unselected picker row can never draw a bar but still reached+ // the subscription. Both branches are module-level constants, so toggling resubscribes once.const watching = enabled && source != null;const epoch = useSyncExternalStore(watching ? subscribeToConfigChanges : subscribeNothing,@@ -445,21 +407,17 @@ export function useModelMemory(() => 0,);- // Whether the number the caller handed us is a dedicated VRAM pool at all.- // On a Vulkan iGPU the backend reports free shared system RAM minus a host- // reserve, so the same model flips between "fits" and "OOM likely" as the- // desktop's RAM moves; on Apple the figure is the entire machine's RAM, which- // says "fits" for almost anything Metal would refuse. Neither is a VRAM- // ceiling, so the bar declines to draw rather than warn against the wrong- // pool. Known gap: a ROCm APU reports its whole GTT pool and is not flagged- // as shared, which needs a unified-memory signal in hardware.py to fix.+ // Whether the number the caller handed us is a dedicated VRAM pool at all. On a Vulkan iGPU the+ // backend reports free shared system RAM minus a host reserve, so the same model flips between+ // "fits" and "OOM likely" as the desktop's RAM moves; on Apple the figure is the entire machine's+ // RAM. Neither is a VRAM ceiling, so the bar declines to draw. Known gap: a ROCm APU reports its+ // whole GTT pool and is not flagged as shared.const inferenceGpu = useInferenceGpuInfo();const budgetIsDedicatedVram =!inferenceGpu.sharedMemory &&- // A ROCm APU reports the GTT/system pool, which moves with host usage and is- // not an independent ceiling. The backend classifies these positively; it is- // reported as its own field rather than through shared_memory, which the- // total and free aggregates already act on.+ // A ROCm APU reports the GTT/system pool, which moves with host usage and is not an independent+ // ceiling. The backend classifies these positively; it is reported as its own field rather than+ // through shared_memory, which the total and free aggregates already act on.!inferenceGpu.unifiedMemory &&inferenceGpu.backend !== "mlx";@@ -474,10 +432,9 @@ export function useModelMemory(// Keyed on primitives rather than the object: callers build the source inline,// so a fresh identity each render would loop forever.const plan = useMemo(() => {- // A direct .gguf selection has no quant label and does not need one: the- // path names the weights outright and the route resolves such a file to- // itself. Requiring a label here suppressed the bar for exactly the custom- // and LM Studio models the direct-file support was added for.+ // A direct .gguf selection has no quant label and does not need one: the path names the weights+ // outright and the route resolves such a file to itself. Requiring a label here suppressed the+ // bar for exactly the custom and LM Studio models the direct-file support was added for.const isDirectGgufFile = (loadId ?? "").toLowerCase().endsWith(".gguf");if (!enabled || !repoId || (!quant && !isDirectGgufFile)) return null;// Empty rather than undefined past this point: a direct file legitimately@@ -518,12 +475,10 @@ export function useModelMemory(// eslint-disable-next-line react-hooks/exhaustive-deps}, [enabled, repoId, loadId, quant, sizeBytes, epoch, budgetIsDedicatedVram]);- // Gated on a real plan, not merely on the feature being on. Every row in the- // list mounts this hook, including remote and undownloaded ones that will never- // draw a bar, and loadVramBudgetSettings folds only calls that are already in- // flight together -- it holds no read-through cache. Gating on `enabled` alone- // therefore turned scrolling or filtering a long list into a repeated request- // per row that appeared.+ // Gated on a real plan, not merely on the feature being on. Every row in the list mounts this+ // hook, including remote and undownloaded ones, and loadVramBudgetSettings folds only calls+ // already in flight together, so gating on `enabled` alone turned scrolling a long list into a+ // request per row that appeared.useEffect(() => {if (!plan) return;let alive = true;@@ -574,11 +529,9 @@ export function useModelMemory(// (a DSpark sidecar runs to about 11 GB). Charting the rest would read as a// comfortable fit for a load that is nothing of the sort, so draw nothing.if (estimate?.specUnpriced) return computeModelMemory({});- // The environment can pin the launch to a subset of the cards the aggregate- // budget credits, and an automatic launch preserves that pin. budgetIsMeaningful- // can only see browser-side pins and saved config, so this is the one placement- // override it cannot reach: without it a 30 GiB model reads as fitting 2x24 GiB- // while the child is confined to one of them.+ // The environment can pin the launch to a subset of the cards the aggregate budget credits, and an+ // automatic launch preserves that pin. budgetIsMeaningful sees only browser-side pins and saved+ // config, so this is the one placement override it cannot reach.if (estimate?.inheritedDevicePin) return computeModelMemory({});const weights = estimate?.weightsBytes ?? source?.sizeBytes;return computeModelMemory({@@ -586,10 +539,9 @@ export function useModelMemory(// segment rather than as a fourth sliver the eye cannot resolve.weightsBytes:weights == null ? weights : weights + (estimate?.projectorBytes ?? 0),- // Context checkpoints are part of the cache, but llama.cpp keeps those- // snapshots in host heap: the load planner's GPU figure is- // kv_bytes - kv_checkpoint_bytes. Charged against a VRAM bar they warn OOM- // over memory that never reaches the card.+ // Context checkpoints are part of the cache, but llama.cpp keeps those snapshots in host+ // heap: the load planner's GPU figure is kv_bytes - kv_checkpoint_bytes. Charged against a+ // VRAM bar they warn OOM over memory that never reaches the card.kvBytes:estimate?.kvBytes == null? estimate?.kvBytes@@ -600,24 +552,18 @@ export function useModelMemory(gpuTotalBytes: estimate?.gpuTotalBytes,gpuFloorBytes: estimate?.gpuFloorBytes,nCtx: estimate?.nCtx,- // The dedicated-only aggregate, never the combined one. On a discrete card- // beside a Vulkan iGPU the combined total adds the iGPU's allowance, which- // is a capped view of free system RAM, so a model would be judged against- // 24 GiB of real VRAM plus whatever the desktop happened not to be using.- // `sharedMemory` cannot carry this: it is every(), so a mixed host reads- // false and the gate above lets exactly this case through.+ // The dedicated-only aggregate, never the combined one. On a discrete card beside a Vulkan iGPU+ // the combined total adds the iGPU's allowance, which is a capped view of free system RAM.+ // `sharedMemory` cannot carry this: it is every(), so a mixed host reads false and the gate above+ // lets exactly this case through.gpuGb: budgetGb,budgetFraction,- // With no pinned context the estimate is sized at the model's native- // length, but a default load sends 0 and the loader auto-reduces to the- // largest context that fits. Warning OOM for a length it would never have- // tried is the false positive this whole bar exists to avoid, so the- // verdict softens and only the weights can still fail outright.- // The route's answer when it gave one: only a context nobody pinned gets- // auto-fitted, and load_model keeps a positive inherited LLAMA_ARG_CTX_SIZE- // rather than fitting it. Reading plan.nCtx alone said "auto-fitted" for- // that launch, which suppressed the overage AND drew only the irreducible- // floor, so an inherited window over budget reported a comfortable fit.+ // With no pinned context the estimate is sized at the model's native length, but a default load+ // sends 0 and the loader auto-reduces to the largest context that fits, so warning OOM for a length+ // it would never have tried is the false positive this bar exists to avoid. The route's answer when+ // it gave one: only a context nobody pinned gets auto-fitted, and load_model keeps a positive+ // inherited LLAMA_ARG_CTX_SIZE rather than fitting it, so reading plan.nCtx alone reported a+ // comfortable fit for an inherited window over budget.contextIsAutoFitted:estimate?.contextIsPinned == null? plan.nCtx == nulldiff --git a/studio/frontend/src/hooks/use-system.ts b/studio/frontend/src/hooks/use-system.tsindex 54074d1093e..e49ba9c6392 100644--- a/studio/frontend/src/hooks/use-system.ts+++ b/studio/frontend/src/hooks/use-system.ts@@ -133,9 +133,8 @@ function scheduleVulkanRetry(): void {vulkanRetrySubscribers,)) {- // A cold subscription schedules before its first request settles. Cancel- // that pending retry as soon as discovery succeeds with a usable inventory- // or a non-Vulkan backend.+ // A cold subscription schedules before its first request settles. Cancel that pending retry as+ // soon as discovery succeeds with a usable inventory or a non-Vulkan backend.if (vulkanRetryId !== null) {window.clearTimeout(vulkanRetryId);vulkanRetryId = null;diff --git a/studio/frontend/src/hooks/use-tauri-backend.ts b/studio/frontend/src/hooks/use-tauri-backend.tsindex 2612fee9426..bc8b061d046 100644--- a/studio/frontend/src/hooks/use-tauri-backend.ts+++ b/studio/frontend/src/hooks/use-tauri-backend.ts@@ -459,18 +459,16 @@ export function useTauriBackend() {const { invoke } = await import("@tauri-apps/api/core");try {await invoke("start_install");- // Install done: start the managed backend we just installed. Don't run the- // general preflight here, it can attach to an unrelated running CLI/backend- // before launching ours. The install-complete listener does NOT call- // startServer() to avoid a double-start race.+ // Install done: start the managed backend we just installed. Don't run the general preflight+ // here, it can attach to an unrelated running CLI/backend before launching ours. The+ // install-complete listener does NOT call startServer() to avoid a double-start race.setBackendStatus("starting");elevationResumeRef.current = null;await startServer();} catch (e) {const msg = String(e);- // NEEDS_ELEVATION is not a real error: the Rust side also emits- // install-needs-elevation (sets needs-elevation status). Don't race with it- // by setting install-error here.+ // NEEDS_ELEVATION is not a real error: the Rust side also emits install-needs-elevation (sets+ // needs-elevation status). Don't race with it by setting install-error here.if (msg.includes("NEEDS_ELEVATION")) return;setBackendError(msg, "install-error");}diff --git a/studio/frontend/src/hooks/use-vram-budget-fraction.ts b/studio/frontend/src/hooks/use-vram-budget-fraction.tsindex beafd016288..5192d12a4cd 100644--- a/studio/frontend/src/hooks/use-vram-budget-fraction.ts+++ b/studio/frontend/src/hooks/use-vram-budget-fraction.ts@@ -78,10 +78,9 @@ export function useVramBudgetFraction(): number | null {useEffect(() => {let alive = true;- // Subscribe BEFORE loading. A save committed while the GET is in the air- // would otherwise be missed entirely, leaving the badge scoring against a- // fraction the user has already replaced. This is also what keeps the- // module cache honest: every writer publishes on this event.+ // Subscribe BEFORE loading. A save committed while the GET is in the air would otherwise be+ // missed entirely, leaving the badge scoring against a fraction the user has already replaced.+ // This is also what keeps the module cache honest: every writer publishes on this event.const unsubscribe = subscribeVramBudgetSettings((settings) => {cachedFraction = settings.fraction;routeAbsent = false;diff --git a/studio/frontend/src/hooks/use-web-update-check.ts b/studio/frontend/src/hooks/use-web-update-check.tsindex ead0c06189f..e027005d02b 100644--- a/studio/frontend/src/hooks/use-web-update-check.ts+++ b/studio/frontend/src/hooks/use-web-update-check.ts@@ -9,18 +9,14 @@ import { useCallback, useEffect, useState } from "react";// re-check happens naturally the next time the user reopens the app.const WEB_UPDATE_CHECK_DELAY_MS = 5000;-// End-to-end override, absent in every real browser.-//-// The banner layout suite boots a fresh page for each case it measures, and every one of-// those boots waits out this timer before the card it is there to measure exists at all.-// At 33 boots that is over two and a half minutes of a five minute step spent waiting for-// a delay whose entire purpose is to keep a network call off the critical path at launch,-// which is not a property that suite is testing.-//-// Read at mount rather than at module load, so a test can set it from an init script and-// so a bundle that is never driven by one behaves exactly as before: the global is-// undefined, and the constant above stands. Deliberately not an env var, which would bake-// the shortened delay into whatever build read it.+// End-to-end override, absent in every real browser. The banner layout suite boots a fresh page for+// each case it measures, and every one of those boots waits out this timer before the card it is+// there to measure exists at all. At 33 boots that is over two and a half minutes of a five minute+// step spent waiting for a delay whose entire purpose is to keep a network call off the critical+// path at launch, which is not a property that suite is testing. Read at mount rather than at+// module load, so a test can set it from an init script and so a bundle that is never driven by one+// behaves exactly as before: the global is undefined, and the constant above stands. Deliberately+// not an env var, which would bake the shortened delay into whatever build read it.const E2E_DELAY_GLOBAL = "__unslothE2EWebUpdateDelayMs";function overriddenDelayMs(): number | null {diff --git a/studio/frontend/src/i18n/locale-store.ts b/studio/frontend/src/i18n/locale-store.tsindex 0609a797fa9..0ebe6ea1a83 100644--- a/studio/frontend/src/i18n/locale-store.ts+++ b/studio/frontend/src/i18n/locale-store.ts@@ -230,12 +230,11 @@ function failPreference(if (revision !== preferenceRevision || pendingPreference === null) return;pendingPreference = null;pendingPreferenceShouldPersist = false;- // A rejected pick leaves the standing preference untouched, so it is still- // serving its own catalog and stays re-pickable; the flag must not move.- // A refresh of the preference already in effect is the other case: a- // `languagechange` re-resolving `auto` onto a language whose catalog fails- // leaves that preference pointing at a locale the app is not showing, which- // is exactly the state the retry path needs to see.+ // A rejected pick leaves the standing preference untouched, so it is still serving its own+ // catalog and stays re-pickable; the flag must not move. A refresh of the preference already in+ // effect is the other case: a `languagechange` re-resolving `auto` onto a language whose catalog+ // fails leaves that preference pointing at a locale the app is not showing, which is exactly the+ // state the retry path needs to see.if (preference === currentPreference && locale !== currentLocale) {currentCatalogFailed = true;}@@ -306,12 +305,11 @@ function applyPreference(const bounded = new Promise<LocaleChangeResult>((resolve) => {const timeout = globalThis.setTimeout(() => {- // Settle the way a rejection would. The load itself is left alone,- // so if it does arrive it still commits over this. Its place in the- // in-flight map is not: a load that never settles never clears its own- // entry, so leaving it there would hand every later pick of this- // language the same dead promise and time out again without ever- // asking for the catalog a second time.+ // Settle the way a rejection would. The load itself is left alone, so if it does arrive it+ // still commits over this. Its place in the in-flight map is not: a load that never settles+ // never clears its own entry, so leaving it there would hand every later pick of this+ // language the same dead promise and time out again without ever asking for the catalog a+ // second time.forgetLocaleLoad(locale, pending);if (signal?.aborted) {resolve("cancelled");@@ -355,13 +353,12 @@ function handleStorageEvent(event: StorageEvent): void {event.key === null? DEFAULT_LOCALE_PREFERENCE: normalizePreference(event.newValue);- // Adopted on failure, like hydration and for the same reason: this value is- // already the stored truth, written by the tab that made the choice, so a- // catalog that will not load here must not leave this tab holding the- // preference the user replaced. It would disagree with storage until the next- // reload, and the next personalization save would push that stale language- // back over the choice. Nothing is written back: storage is where this came- // from, and a catalog that failed is not recorded as a choice that worked.+ // Adopted on failure, like hydration and for the same reason: this value is already the stored+ // truth, written by the tab that made the choice, so a catalog that will not load here must not+ // leave this tab holding the preference the user replaced. It would disagree with storage until+ // the next reload, and the next personalization save would push that stale language back over the+ // choice. Nothing is written back: storage is where this came from, and a catalog that failed is+ // not recorded as a choice that worked.void applyPreference(nextPreference,false,@@ -471,13 +468,12 @@ export function initializeLocale({};const timeout = globalThis.setTimeout(() => {- // Same as the selection path: the load itself is left running, so a- // late catalog still commits over the fallback, but its place in the- // in-flight map goes. A load that never settles never clears its own- // entry, and the saved language is exactly the one the user reaches for- // next once English appears, so keeping it would hand that pick this- // same dead promise and spend the whole selection bound on it without- // ever asking for the catalog again.+ // Same as the selection path: the load itself is left running, so a late catalog still+ // commits over the fallback, but its place in the in-flight map goes. A load that never+ // settles never clears its own entry, and the saved language is exactly the one the user+ // reaches for next once English appears, so keeping it would hand that pick this same dead+ // promise and spend the whole selection bound on it without ever asking for the catalog+ // again.forgetLocaleLoad(locale, pending);commitFallbackLocale(preference, revision);finish();diff --git a/studio/frontend/src/i18n/relative-time.ts b/studio/frontend/src/i18n/relative-time.tsindex 261528b3cd2..a4b9f5a5c65 100644--- a/studio/frontend/src/i18n/relative-time.ts+++ b/studio/frontend/src/i18n/relative-time.ts@@ -34,11 +34,10 @@ export function formatRelativeTime(}const short = getFormatter(locale, "short");const formatted = short.format(value, unit);- // Some CLDR short patterns drop the past/future marker. Arabic months in the- // "few" plural category (3-10) render "5 months ago" as "خلال 5 أشهر" ("in- // 5 months"), which is byte-identical to the future form. Where the two- // directions are indistinguishable the long style still carries the marker,- // so use it rather than report the wrong tense.+ // Some CLDR short patterns drop the past/future marker. Arabic months in the "few" plural+ // category (3-10) render "5 months ago" as "خلال 5 أشهر" ("in 5 months"), which is byte-identical+ // to the future form. Where the two directions are indistinguishable the long style still carries+ // the marker, so use it rather than report the wrong tense.if (value !== 0 && formatted === short.format(-value, unit)) {return getFormatter(locale, "long").format(value, unit);}diff --git a/studio/frontend/src/lib/bulb-icon.tsx b/studio/frontend/src/lib/bulb-icon.tsxindex e2f50d43b0a..e4adca3e0b8 100644--- a/studio/frontend/src/lib/bulb-icon.tsx+++ b/studio/frontend/src/lib/bulb-icon.tsx@@ -3,9 +3,8 @@import type { ComponentPropsWithoutRef } from "react";-// Shared lightbulb glyph used by the composer thinking toggle and the-// reasoning "Thinking..." indicator so both stay in sync. Defaults are-// overridable via props.+// Shared lightbulb glyph used by the composer thinking toggle and the reasoning "Thinking..."+// indicator so both stay in sync. Defaults are overridable via props.export const BulbIcon = ({className,...propsdiff --git a/studio/frontend/src/lib/data-uri.ts b/studio/frontend/src/lib/data-uri.tsindex f00d86d4246..126dc4cb94a 100644--- a/studio/frontend/src/lib/data-uri.ts+++ b/studio/frontend/src/lib/data-uri.ts@@ -1,9 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Only a trailing `;base64` marks the payload as base64. A segment named-// `base64` anywhere else is an ordinary parameter, so-// `data:text/plain;base64;charset=utf-8,SGVsbG8=` stays literal text.+// Only a trailing `;base64` marks the payload as base64. A segment named `base64` anywhere else is+// an ordinary parameter, so `data:text/plain;base64;charset=utf-8,SGVsbG8=` stays literal text.const DATA_URI_BASE64_RE = /;[ \t]*base64[ \t]*$/i;const PERCENT_ESCAPE_RE = /%([0-9a-f]{2})/gi;const DEFAULT_MIME_TYPE = "text/plain;charset=US-ASCII";diff --git a/studio/frontend/src/lib/gguf-fit.ts b/studio/frontend/src/lib/gguf-fit.tsindex 9f9db042acd..0b58f9e113e 100644--- a/studio/frontend/src/lib/gguf-fit.ts+++ b/studio/frontend/src/lib/gguf-fit.ts@@ -84,18 +84,16 @@ export function classifyGgufFit(budgetFraction <= 1? budgetFraction: DEFAULT_VRAM_BUDGET_FRACTION;- // Not simply `gpuGb * fraction`. The loader's `_vram_usable_mib` charges- // `max((1 - frac) * total, floor)`, where the floor is `min(512 MiB, 3% of total)`, so the- // reserve never disappears at the top of the slider. Below the 0.97 default the percentage term- // always wins and this is identical; above it, `gpuGb * fraction` claimed capacity the backend- // does not offer, and a 20 GiB file on a full 24 GiB card at 1.0 read `fits` while `_select_gpus`- // fell back to --fit.- //+ // Not simply `gpuGb * fraction`. The loader's `_vram_usable_mib` charges `max((1 - frac) * total,+ // floor)`, where the floor is `min(512 MiB, 3% of total)`, so the reserve never disappears at the+ // top of the slider. Below the 0.97 default the percentage term always wins and this is+ // identical; above it, `gpuGb * fraction` claimed capacity the backend does not offer, and a 20+ // GiB file on a full 24 GiB card at 1.0 read `fits` while `_select_gpus` fell back to --fit.// Charged per CARD, not per host: `_select_gpus` calls `_vram_usable_mib` for every device and- // sums the results, so a k-GPU box holds back k floors. One floor for the whole box read 47.5- // GiB usable on two 24 GiB cards at 1.0 where the loader offers 47.0, so a file needing 47.2- // read `fits` against a load that fell back to --fit. Exact on matched cards, an even split on- // a mixed one, which is still far nearer than charging the floor once.+ // sums the results, so a k-GPU box holds back k floors. One floor for the whole box read 47.5 GiB+ // usable on two 24 GiB cards at 1.0 where the loader offers 47.0, so a file needing 47.2 read+ // `fits` against a load that fell back to --fit. Exact on matched cards, an even split on a mixed+ // one, which is still far nearer than charging the floor once.const cards =typeof gpuCount === "number" && Number.isFinite(gpuCount) && gpuCount >= 1? Math.floor(gpuCount)@@ -108,19 +106,17 @@ export function classifyGgufFit();const budget = gpuGb - Math.max((1 - fraction) * gpuGb, reserveFloorGb);if (required <= budget) return "fits";- // Raw card, deliberately. This band means "over your budget, still card-sized",- // which is the only thing that distinguishes it from `fits`: scoring it against- // `budget` too would make it unreachable, since `required <= budget` has already- // returned above. It is a warning tier, not a claim that the load will be- // admitted.+ // Raw card, deliberately. This band means "over your budget, still card-sized", which is the only+ // thing that distinguishes it from `fits`: scoring it against `budget` too would make it+ // unreachable, since `required <= budget` has already returned above. It is a warning tier, not a+ // claim that the load will be admitted.if (required <= gpuGb) return "marginal";- // The budget, though. Once layers spill, what the GPU can still contribute is- // what it is ALLOWED to hold, and the reserve is exactly what the model and KV- // cache may not use ("the fit reserves a slice of every card that the model and- // KV cache may not use", vram_budget_settings.py). Crediting the raw card here- // invented capacity the loader will not give: on a 24 GiB card with 16 GiB of- // RAM at the legal minimum 0.80, quants from 23 to 26 GiB were badged `partial`- // when the budget leaves them no way to load.+ // The budget, though. Once layers spill, what the GPU can still contribute is what it is ALLOWED+ // to hold, and the reserve is exactly what the model and KV cache may not use ("the fit reserves+ // a slice of every card that the model and KV cache may not use", vram_budget_settings.py).+ // Crediting the raw card here invented capacity the loader will not give: on a 24 GiB card with+ // 16 GiB of RAM at the legal minimum 0.80, quants from 23 to 26 GiB were badged `partial` when+ // the budget leaves them no way to load.const combined = budget + (systemRamGb ?? 0) * RAM_OFFLOAD_USABLE_RATIO;if (required <= combined) return "partial";return "oom";diff --git a/studio/frontend/src/lib/latex.ts b/studio/frontend/src/lib/latex.tsindex b0c55470284..adfbdd385c2 100644--- a/studio/frontend/src/lib/latex.ts+++ b/studio/frontend/src/lib/latex.ts@@ -124,14 +124,12 @@ function findInlineCodeRegions(content: string,blockRegions: Array<[number, number]>,): Array<[number, number]> {- // Every backtick inside a block region becomes a space in the mask below, so- // unless one sits outside a block region the mask cannot contain a backtick,- // `codeSpans` returns nothing and the whole rebuild is spent to learn that.- // Worth checking first because the streaming path calls this once per frame- // over a growing prefix, twice per preprocessLaTeX, so the rebuild is O(n) per- // frame and O(n^2) over a reply; and a reply carrying one fenced example and- // no inline code, where every backtick is inside the fence, is the common- // shape rather than a corner case.+ // Every backtick inside a block region becomes a space in the mask below, so unless one sits+ // outside a block region the mask cannot contain a backtick, `codeSpans` returns nothing and the+ // whole rebuild is spent to learn that. Worth checking first because the streaming path calls+ // this once per frame over a growing prefix, twice per preprocessLaTeX, so the rebuild is O(n)+ // per frame and O(n^2) over a reply; and a reply carrying one fenced example and no inline code,+ // where every backtick is inside the fence, is the common shape rather than a corner case.let spanTickOutsideBlock = false;for (let index = content.indexOf("`");diff --git a/studio/frontend/src/lib/model-lifecycle-events.ts b/studio/frontend/src/lib/model-lifecycle-events.tsindex c850031c1f9..a8c75c3318d 100644--- a/studio/frontend/src/lib/model-lifecycle-events.ts+++ b/studio/frontend/src/lib/model-lifecycle-events.ts@@ -1,17 +1,13 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// One announcement per model load or release, raised from the API call itself-// so every caller is covered without each page remembering to.-//-// Two things listen. The Images and Video pages hold their own `status` and-// re-read it on tab activation rather than on a timer, so a release from-// anywhere else leaves their controls claiming a model is still loaded. And the-// loaded models indicator polls every 5s, which is long enough that a load-// looked like it had not started: the toast said "loading" while the card said-// nothing. Both now hear the moment it happens.-//-// In lib/, not a feature, since the emitters and the listeners are both features.+// One announcement per model load or release, raised from the API call itself so every caller is+// covered without each page remembering to. Two things listen. The Images and Video pages hold+// their own `status` and re-read it on tab activation rather than on a timer, so a release from+// anywhere else leaves their controls claiming a model is still loaded. And the loaded models+// indicator polls every 5s, which is long enough that a load looked like it had not started: the+// toast said "loading" while the card said nothing. Both now hear the moment it happens. In lib/,+// not a feature, since the emitters and the listeners are both features.export const MODEL_EJECTED_EVENT = "unsloth:model-ejected";export const MODEL_LIFECYCLE_EVENT = "unsloth:model-lifecycle";@@ -141,12 +137,11 @@ export async function withBackgroundLoadNotice<T>(try {const result = await start();started = true;- // Announce a second time, now that the POST has returned. That is the- // instant the GPU arbiter has committed: acquire_for evicts whoever held- // the GPU inside this call, ahead of a download that can run for hours, so- // the first announcement was raised while the status it displaces was still- // correct. Listeners that re-read another runtime need this edge, and the- // rows this drives are keyed by runtime, so a repeat is a no-op for them.+ // Announce a second time, now that the POST has returned. That is the instant the GPU arbiter+ // has committed: acquire_for evicts whoever held the GPU inside this call, ahead of a download+ // that can run for hours, so the first announcement was raised while the status it displaces+ // was still correct. Listeners that re-read another runtime need this edge, and the rows this+ // drives are keyed by runtime, so a repeat is a no-op for them.notifyModelLifecycle({ runtime, loading: true, model });void settleWhenLoadEnds(runtime, model, readPhase, timing);return result;@@ -170,10 +165,9 @@ async function settleWhenLoadEnds(try {for (;;) {await new Promise((resolve) => setTimeout(resolve, pollMs));- // An unreadable read is not proof the load ended: a restarting backend or- // one dropped request would end the row early and hide a live load. That- // is `undefined`, kept distinct from the `null` phase precisely so the two- // are not conflated here.+ // An unreadable read is not proof the load ended: a restarting backend or one dropped request+ // would end the row early and hide a live load. That is `undefined`, kept distinct from the+ // `null` phase precisely so the two are not conflated here.const phase = await boundedRead(readPhase, readTimeoutMs);if (phase === undefined) {// Only a sustained run of unreadable polls gives up. A load that isdiff --git a/studio/frontend/src/lib/model-memory.ts b/studio/frontend/src/lib/model-memory.tsindex 11ba5fc6db0..301141179d8 100644--- a/studio/frontend/src/lib/model-memory.ts+++ b/studio/frontend/src/lib/model-memory.ts@@ -2,16 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0/**- * Splits a downloaded model's VRAM footprint into weights and what the current- * settings add on top: KV cache at the context it will load with, plus an MTP- * draft reserve when speculative decoding is on.- *- * They're kept apart because the fixes differ. Oversized weights need a smaller- * quant; a total that only overflows once context is added needs a shorter- * context or a quantized KV cache.- *- * Budget matches `gguf-fit.ts` and the backend's `_select_gpus`, so the bar and- * the fit badge on a row can't contradict each other.+ * Splits a downloaded model's VRAM footprint into weights and what the current settings add on+ * top: KV cache at the context it will load with, plus an MTP draft reserve when speculative+ * decoding is on. They are kept apart because the fixes differ: oversized weights need a smaller+ * quant, while a total that only overflows once context is added needs a shorter context or a+ * quantized KV cache. Budget matches `gguf-fit.ts` and the backend's `_select_gpus`, so the bar+ * and the fit badge on a row cannot contradict each other.*/import {@@ -30,31 +26,27 @@ export interface ModelMemoryInput {/** MTP draft reserve; null for ngram (which is free) or a model without one. */specBytes?: number | null;/**- * llama.cpp's compute buffers, from the load planner's own `compute_bytes`.- *- * Every launch reserves these, and they scale with slots and micro-batch, so a- * row near the budget could report a fit while omitting gigabytes the server- * allocates. Folded into the KV segment rather than drawn as a fourth sliver:- * it is context-linear in part and too small at default settings to resolve on- * its own, but it still has to count against the total.- */+ * llama.cpp's compute buffers, from the load planner's own `compute_bytes`.+ *+ * Every launch reserves these and they scale with slots and micro-batch, so a row near the+ * budget could report a fit while omitting gigabytes. Folded into the KV segment rather than+ * drawn as a fourth sliver: it is context-linear in part and too small to resolve on its own.+ */computeBytes?: number | null;/**- * The load planner's own GPU-resident total, which supersedes the sum of the- * segments when present.- *- * The segments are assembled here from separate fields and so can only include- * what this file knows to ask for; the planner's figure already applies the- * inherited environment, resolves companions through the loader's search roots- * and counts every buffer. Segment geometry still comes from the individual- * terms -- this decides the verdict, not the picture.- */+ * The load planner's own GPU-resident total, which supersedes the sum of the segments.+ *+ * The segments are assembled here from separate fields and can only include what this file knows+ * to ask for; the planner's figure applies the inherited environment, resolves companions through+ * the loader's search roots and counts every buffer. Segment geometry still comes from the+ * individual terms: this decides the verdict, not the picture.+ */gpuTotalBytes?: number | null;/**- * What the planner still reserves at the shortest context: drafter weights,- * flat compute buffers, recurrent rollback state. None of it shrinks when the- * context does, so it is the floor an auto-fitted row is judged against.- */+ * What the planner still reserves at the shortest context: drafter weights, flat compute buffers,+ * recurrent rollback state. None of it shrinks when the context does, so it is the floor an+ * auto-fitted row is judged against.+ */gpuFloorBytes?: number | null;/** The share of specBytes a shorter context cannot reduce (drafter weights). */specFixedBytes?: number | null;@@ -63,26 +55,25 @@ export interface ModelMemoryInput {/** Context the KV figure was measured at, for the per-token rate. */nCtx?: number | null;/**- * Fraction of that VRAM a load may claim, from /api/settings/vram-budget.- * Defaults to VRAM_HEADROOM_RATIO when unknown. This is the loader's own- * number and the user can change it, so a bar that hardcodes one warns at a- * line admission does not use.- */+ * Fraction of that VRAM a load may claim, from /api/settings/vram-budget, defaulting to+ * VRAM_HEADROOM_RATIO. This is the loader's own number and the user can change it, so a bar that+ * hardcodes one warns at a line admission does not use.+ */budgetFraction?: number | null;/**- * True when no context is pinned, so the loader will auto-fit rather than- * open the model's native length. The KV figure is then an upper bound on a- * context the load would have reduced, so it cannot justify an OOM verdict.- */+ * True when no context is pinned, so the loader will auto-fit rather than open the model's native+ * length. The KV figure is then an upper bound on a context the load would have reduced, so it+ * cannot justify an OOM verdict.+ */contextIsAutoFitted?: boolean | null;}/*** How close the total sits to the budget.*- * Studio's live meters step at 70/90 (`resources-tab.tsx`), but they show usage- * as it happens, where a sustained 70% is worth flagging. This is a reservation- * you can see coming, so it holds the accent until 80.+ * Studio's live meters step at 70/90 (`resources-tab.tsx`), but they show usage as it happens,+ * where a sustained 70% is worth flagging. This is a reservation you can see coming, so it holds+ * the accent until 80.*/export type ModelMemoryPressure = "normal" | "high" | "critical";@@ -144,25 +135,18 @@ function toGb(bytes?: number | null): number {}/**- * Bar geometry and fit status for one row.- *- * Weights are required, KV is not: a row whose estimate hasn't arrived draws- * its weights now and fills in the rest, instead of appearing late.+ * Bar geometry and fit status for one row. Weights are required, KV is not: a row whose estimate+ * has not arrived draws its weights now and fills in the rest, instead of appearing late.*/export function computeModelMemory(input: ModelMemoryInput,): ModelMemorySegments {- // A figure that is not a number cannot produce a verdict, only a confident- // looking one. `toGb` passes Infinity straight through, so an infinite- // weightsBytes reached the status ladder and came out "model-exceeds": a full- // red bar reading "Larger than VRAM" beside a weights figure of "0 GiB",- // because the formatter clamps what the verdict did not. JSON.parse turns- // 1e999 into Infinity, so a malformed response gets there without trying.- //- // `classifyMemoryFit` on the panel already answers "unknown" for exactly these- // inputs, so this was also the two surfaces disagreeing about the same bytes.- // Null and undefined are NOT covered here: those mean "has not arrived yet",- // which is an ordinary state the segments below already handle.+ // A figure that is not a number cannot produce a verdict, only a confident looking one. `toGb`+ // passes Infinity straight through, so an infinite weightsBytes reached the status ladder and came+ // out "model-exceeds": a full red bar reading "Larger than VRAM" beside a weights figure of+ // "0 GiB". JSON.parse turns 1e999 into Infinity, so a malformed response gets there without+ // trying, and `classifyMemoryFit` on the panel already answers "unknown" for these inputs. Null+ // and undefined are NOT covered: those mean "has not arrived yet", which the segments handle.if ([input.weightsBytes,@@ -182,20 +166,15 @@ export function computeModelMemory(const gpuGb = input.gpuGb ?? 0;const modelGb = toGb(input.weightsBytes);if (gpuGb <= 0 || modelGb <= 0) return EMPTY;- // The planner says this launch puts nothing on the card. A VRAM bar has- // nothing to say about it, and drawing one implies a reservation that is not- // going to happen.+ // The planner says this launch puts nothing on the card. A VRAM bar has nothing to say about it,+ // and drawing one implies a reservation that is not going to happen.if (input.gpuTotalBytes === 0) return EMPTY;- // The loader's own budget when the caller knows it, so the bar warns at the- // line admission actually draws.- //+ // The loader's own budget when the caller knows it, so the bar warns at the line admission draws.// The fallback is DEFAULT_VRAM_BUDGET_FRACTION (0.97), matching the loader's- // _CTX_FIT_VRAM_FRACTION and the Load Model panel. It used to be- // VRAM_HEADROOM_RATIO (0.90), which is not a safer guess but a measured wrong- // one: llama_cpp.py records "0.90 dropped 91-94% fits to CPU offload, #5106".- // Warning at a line admission does not draw is the same class of wrong answer- // as a false "fits", pointing the other way.+ // _CTX_FIT_VRAM_FRACTION and the Load Model panel. It used to be VRAM_HEADROOM_RATIO (0.90),+ // which is not a safer guess but a measured wrong one: llama_cpp.py records "0.90 dropped 91-94%+ // fits to CPU offload, #5106".const fraction =input.budgetFraction && input.budgetFraction > 0? input.budgetFraction@@ -206,28 +185,20 @@ export function computeModelMemory(// The planner's total when it gave one, since it accounts for terms these// segments cannot see. Falls back to the sum for a backend too old to send it.const segmentSumGb = modelGb + kvGb + specGb;- // Explicitly null-checked, because zero is an answer rather than the absence- // of one: inherited placement can make the launch entirely CPU resident, and- // `||` would have quietly swapped that for the segment sum and drawn VRAM- // pressure for a load that touches no card.+ // Explicitly null-checked, because zero is an answer rather than the absence of one: inherited+ // placement can make the launch entirely CPU resident, and `||` would have swapped that for the+ // segment sum and drawn VRAM pressure for a load that touches no card.const totalGb =input.gpuTotalBytes == null ? segmentSumGb : toGb(input.gpuTotalBytes);- // Only the weights are a hard verdict: they are what they are. The context- // term is a reservation the loader is free to shrink when nothing pinned it,- // so an unpinned row that only tips over because of KV reports "fits" rather- // than warning about a length the load would never have opened.- //- // The speculative segment is not wholly context-linear though: a separate- // drafter's own weights are resident whatever the context, and no auto-fit can- // shrink them. So the hard floor is the weights plus that fixed share -- if- // target and drafter weights together do not fit, saying "fits" because the- // context is unpinned describes a load that cannot open at any length.- // The planner's floor when it gave one: it names every fixed term, including- // the flat compute buffer and a Hybrid Mamba target's rollback state, which- // the drafter-weights figure alone misses. Both can be several GiB, and both- // survive any context reduction, so folding them into the reducible part let- // auto-fit suppress an overage nothing could fix.+ // Only the weights are a hard verdict: they are what they are. The context term is a reservation+ // the loader is free to shrink when nothing pinned it, so an unpinned row that only tips over+ // because of KV reports "fits". The speculative segment is not wholly context-linear though: a+ // separate drafter's own weights are resident whatever the context, so the hard floor is the+ // weights plus that fixed share. The planner's floor when it gave one names every fixed term,+ // including the flat compute buffer and a Hybrid Mamba target's rollback state, which the+ // drafter-weights figure alone misses; both can be several GiB and both survive any context+ // reduction, so folding them into the reducible part let auto-fit suppress an overage.const specFixedGb = toGb(input.specFixedBytes);const irreducibleGb =input.gpuFloorBytes == null@@ -240,8 +211,7 @@ export function computeModelMemory(? "context-exceeds": "fits";- // Clamp to the track, so an oversized model can't push the later segments- // out of the row.+ // Clamp to the track, so an oversized model can't push the later segments out of the row.const modelPct = Math.min(100, (modelGb / budgetGb) * 100);const kvPct = Math.min(100 - modelPct, (kvGb / budgetGb) * 100);const specPct = Math.min(100 - modelPct - kvPct, (specGb / budgetGb) * 100);@@ -252,26 +222,19 @@ export function computeModelMemory(const kvBytesPerToken =nCtx > 0 && input.kvBytes && input.kvBytes > 0 ? input.kvBytes / nCtx : 0;- // Uncapped: widths clamp to the track, but pressure still needs to tell- // "just full" from "twice over".- //- // For an unpinned row the total is priced at the model's NATIVE context while- // the loader will reduce that context to fit, so this number is an upper bound- // on a length the load would never open. Suppressing only the textual verdict- // and leaving the picture alone gave a model that loads perfectly well a full- // destructive-red bar and an over-budget readout, which says "this will not- // work" louder than the words did. The floor is what the launch cannot avoid- // reserving, so it is the honest figure to draw pressure from; when the- // planner did not give one, the fill is capped at the budget rather than- // invented, since the true fitted total is not known here.+ // Uncapped: widths clamp to the track, but pressure still needs to tell "just full" from "twice+ // over". For an unpinned row the total is priced at the model's NATIVE context while the loader+ // will reduce it to fit, so this number is an upper bound on a length the load would never open;+ // suppressing only the textual verdict gave a model that loads perfectly well a full+ // destructive-red bar. The floor is what the launch cannot avoid reserving, so it is the honest+ // figure to draw pressure from; without one the fill is capped at the budget rather than invented.const autoFitted = Boolean(input.contextIsAutoFitted);const pressureGb =autoFitted && input.gpuFloorBytes != null? // The floor alone. Auto-fit sizes the cache to whatever is left, so the- // useful signal is how much of the budget is spoken for before the- // context gets any: capping the native total at the budget instead just- // pins every such row at exactly 100%, which reads as critical for a- // load that is fine.+ // useful signal is how much of the budget is spoken for before the context gets any:+ // capping the native total at the budget instead just pins every such row at exactly 100%,+ // which reads as critical for a load that is fine.Math.min(irreducibleGb, totalGb): autoFitted? Math.min(totalGb, budgetGb)@@ -303,9 +266,8 @@ export function computeModelMemory(/*** Pass-through llama-server args that decide where the model is placed.*- * Exported for the policy tests: these are the flags whose presence means the- * VRAM total stops describing the load, so the bar has to abstain exactly as it- * does for the equivalent structured controls.+ * Exported for the policy tests: these are the flags whose presence means the VRAM total stops+ * describing the load, so the bar has to abstain exactly as it does for the structured controls.*/export const PLACEMENT_OWNING_ARGS = [// _GPU_LAYER_FLAGS and _FIT_FLAGS@@ -347,29 +309,24 @@ export const PLACEMENT_OWNING_ARGS = [];/**- * Pass-through args that change the SIZE of the KV cache rather than where it- * sits.+ * Pass-through args that change the SIZE of the KV cache rather than where it sits.*- * The bar prices the cache from the structured controls alone, so any of these- * in the box means the launch reserves something other than what was priced.- * `--swa-full` is the sharp one: on a sliding-window model it replaces the- * compact window with a full-context cache, which the loader honours at- * `_estimate_kv_cache_bytes` via `_swa_full_from_args_or_env`. Pricing the- * window and reporting a fit for a launch that allocates the full context is the- * exact false "fits" this bar exists to prevent, so it abstains instead.+ * The bar prices the cache from the structured controls alone, so any of these in the box means+ * the launch reserves something other than what was priced. `--swa-full` is the sharp one: on a+ * sliding-window model it replaces the compact window with a full-context cache, which the loader+ * honours at `_estimate_kv_cache_bytes`, so pricing the window would report the exact false "fits"+ * this bar exists to prevent.*/export const KV_SHAPING_ARGS = ["--swa-full",// Turning flash attention off changes the cache layout, not just its size:- // _estimate_kv_cache_bytes then pads variable-width V tensors to the- // model-wide maximum, which can reserve materially more than the default- // enabled layout this estimate prices.+ // _estimate_kv_cache_bytes then pads variable-width V tensors to the model-wide maximum, which+ // can reserve materially more than the default enabled layout this estimate prices."--flash-attn","-fa",- // The loader treats an extras --spec-type as authoritative over the- // structured mode, so a config saying "off" can still open an embedded NextN- // head. The request carries only the structured mode, so the draft KV and the- // target rollback state would both be missing from the total.+ // The loader treats an extras --spec-type as authoritative over the structured mode, so a config+ // saying "off" can still open an embedded NextN head. The request carries only the structured+ // mode, so the draft KV and the target rollback state would both be missing from the total."--spec-type","--spec-default",// Draft depth in llama.cpp's spellings as well as Unsloth's: a recurrent@@ -410,11 +367,9 @@ export const KV_SHAPING_ARGS = [/*** Pass-through args that make the launch hold files this estimate never sized.*- * A LoRA, a control vector, an explicit projector or a hand-named drafter are- * all resident bytes chosen in the extras box, and none of them reach the- * planner through the structured settings. Unlike the KV-shaping flags these do- * not reshape a term that was priced -- they add one that was not -- so the- * total is a floor rather than an answer and the bar abstains.+ * A LoRA, a control vector, an explicit projector or a hand-named drafter are all resident bytes+ * chosen in the extras box, and none reach the planner through the structured settings. Unlike the+ * KV-shaping flags these add a term rather than reshaping one, so the total is a floor.*/export const RESIDENT_ADDING_ARGS = [// _LOCAL_DRAFT_FLAGS and _HF_DRAFT_FLAGS in full. A hand-named drafter is@@ -456,12 +411,10 @@ export function extraArgsShapeKvCache(/*** A pass-through token reduced to the flag name the launch will parse.*- * Mirrors the backend's `_flag_name`: peel `--key=value`, and normalise- * underscores in long options, which llama.cpp accepts interchangeably with- * dashes. Without the second step `--gpu_layers` or `--ctx_size` passed every- * one of the three predicates below while still changing the real launch, so a- * single spelling defeated the whole abstention policy rather than one entry in- * one list.+ * Mirrors the backend's `_flag_name`: peel `--key=value`, and normalise underscores in long+ * options, which llama.cpp accepts interchangeably with dashes. Without the second step+ * `--gpu_layers` passed every predicate below while still changing the real launch, so a single+ * spelling defeated the whole abstention policy.*/function flagName(arg: unknown): string {const token = String(arg ?? "").trim();@@ -508,12 +461,10 @@ export interface EstimateCacheKeyParts {/*** Cache key for one estimate.*- * Every field the request carries appears here, because two rows that would ask- * the backend different questions must not share an answer. The slot count is- * the one that is easy to get wrong: an omitted count is not one slot, it is- * "whatever the server is configured for", which defaults above one. Joined with- * a separator that cannot occur in a normalized repo id or quant label, since a- * space can.+ * Every field the request carries appears here, because two rows that would ask the backend+ * different questions must not share an answer. The slot count is easy to get wrong: an omitted+ * count is not one slot, it is "whatever the server is configured for", which defaults above one.+ * Joined with a separator that cannot occur in a normalized repo id or quant label.*/export function estimateCacheKey(parts: EstimateCacheKeyParts): string {return [@@ -537,10 +488,9 @@ export function estimateCacheKey(parts: EstimateCacheKeyParts): string {/*** Whether a response says "I could not size this model".*- * The route is best-effort: it answers 200 with every field null rather than- * failing, so this arrives down the success path. Callers cache it as a failure- * so it expires, because the usual cause is a backend that is briefly away, not- * a model that can never be sized.+ * The route is best-effort: it answers 200 with every field null rather than failing, so this+ * arrives down the success path. Callers cache it as a failure so it expires, because the usual+ * cause is a backend briefly away, not a model that can never be sized.*/export function estimateIsUnsized(estimate: {kvBytes: number | null;@@ -554,23 +504,18 @@ export function estimateIsUnsized(estimate: {);}-// The unit formatting now lives in src/lib/memory/format.ts, shared with the-// Load Model panel. Re-exported here because this module is the bar's entry-// point and its call sites are unchanged.-//-// formatKvRate's labels have changed from KB/MB to KiB/MiB: the divide was-// always by 1024, so the readout was printing kibibytes labelled as kilobytes,-// the same mislabel #9570 fixed one scale up.+// The unit formatting now lives in src/lib/memory/format.ts, shared with the Load Model panel.+// Re-exported here because this module is the bar's entry point. formatKvRate's labels have+// changed from KB/MB to KiB/MiB: the divide was always by 1024, so the readout was printing+// kibibytes labelled as kilobytes.export { formatKvRate } from "./memory/format.ts";/*** Compact label for the bar's readout ("7.2 GiB").*- * @deprecated Prefer `formatGiB` from `@/lib/memory/format`, whose name says- * which unit it takes. This alias exists because there used to be a SECOND- * exported `formatMemoryGb`, in `model-config/memory-fit.ts`, which took BYTES- * rather than gigabytes -- the same name and the same `(number) => string`- * signature for two incompatible things, so importing the wrong one was off by- * 1024^3 and still typechecked.+ * @deprecated Prefer `formatGiB` from `@/lib/memory/format`, whose name says which unit it takes.+ * This alias exists because there used to be a SECOND exported `formatMemoryGb`, in+ * `model-config/memory-fit.ts`, which took BYTES rather than gigabytes: same name and signature+ * for two incompatible things, so importing the wrong one was off by 1024^3 and still typechecked.*/export { formatGiB as formatMemoryGb } from "./memory/format.ts";diff --git a/studio/frontend/src/lib/release-body-links.ts b/studio/frontend/src/lib/release-body-links.tsindex 680bb616234..e94f5d7b398 100644--- a/studio/frontend/src/lib/release-body-links.ts+++ b/studio/frontend/src/lib/release-body-links.ts@@ -391,14 +391,12 @@ function classify(lines: string[]): Classified {lines.forEach((original, index) => {const start = offset;offset += original.length + 1;- // The quote state from the line above, which is what list tracking asks- // about. Only plain text below rewrites it, so every block returning early- // leaves no quoted paragraph open behind it.+ // The quote state from the line above, which is what list tracking asks about. Only plain text+ // below rewrites it, so every block returning early leaves no quoted paragraph open behind it.const above = quote;quote = NO_QUOTE;- // A fence, comment or HTML block runs only to the end of the container it was- // written in, so a line dedented out of that item or outside that quote- // closes both.+ // A fence, comment or HTML block runs only to the end of the container it was written in, so a+ // line dedented out of that item or outside that quote closes both.const quotes = quoteDepth(original);let inBlock = openFence !== null || inRawHtml || inHtmlBlock || inComment;if (@@ -418,20 +416,18 @@ function classify(lines: string[]): Classified {endBlock();inBlock = false;}- // Read from the container the line is written in, so a fence three columns- // past a nested bullet or behind a quote marker still opens one. A block- // already open keeps only its own quote stripped, or a deeper marker in it- // would read as a closer.+ // Read from the container the line is written in, so a fence three columns past a nested bullet+ // or behind a quote marker still opens one. A block already open keeps only its own quote+ // stripped, or a deeper marker in it would read as a closer.const container = containerContent(original,lists,inBlock ? blockQuotes : quotes,);- // A comment cannot open a fence and a fence hides a comment opener, so resolve- // them in that order or a hidden delimiter opens a phantom fence. An opener is- // read past a marker on the same line too, since a fence written as an item's- // first content opens inside it. Only an opener: fenced content is literal and- // a closer carries no marker.+ // A comment cannot open a fence and a fence hides a comment opener, so resolve them in that+ // order or a hidden delimiter opens a phantom fence. An opener is read past a marker on the+ // same line too, since a fence written as an item's first content opens inside it. Only an+ // opener: fenced content is literal and a closer carries no marker.const fenceSource = inComment? null: FENCE.exec(diff --git a/studio/frontend/src/lib/release-notes-preview.ts b/studio/frontend/src/lib/release-notes-preview.tsindex 8fb8456de99..251fc1b3327 100644--- a/studio/frontend/src/lib/release-notes-preview.ts+++ b/studio/frontend/src/lib/release-notes-preview.ts@@ -26,9 +26,8 @@ const INDENTED_CODE_INDENT = 4;// At most three leading spaces: deeper is indented code, not a fence.const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/;-// An ATX heading needs a space, tab or line end after the marker, as in-// _HEADING_PATTERN. `\s` would match a non-breaking space and eat prose, and a-// bare `##` is an empty heading that still ends a bullet.+// An ATX heading needs a space, tab or line end after the marker, as in _HEADING_PATTERN. A whitespace class would+// match a non-breaking space and eat prose, and a bare `##` is an empty heading that still ends a bullet.const HEADING = /^#{1,6}(?:[ \t]|$)/;const BULLET = /^(?:[-*+]|(\d{1,9})[.)])[ \t]+(.*)$/;// At most three leading spaces, as everywhere else: deeper is indented code,@@ -259,17 +258,14 @@ interface ContentLine {}/**- * `line` with its comments removed, whether a comment block stays open, and- * whether an inline comment runs on into the line below.+ * `line` with its comments removed, whether a comment block stays open, and whether an inline comment runs on into+ * the line below.*- * Only a comment starting a line opens a block, which hides whole lines to the- * one holding `-->`. One written mid-sentence is inline HTML belonging to its- * paragraph, so its `-->` may arrive on a later line and only the text up to it- * is hidden. `closesBelow` says one does; without it the opener is ordinary text- * and hides nothing below.- *- * "Starting a line" is read inside the container, so `blockOpen` comes from the- * item's content rather than the raw line.+ * Only a comment starting a line opens a block, which hides whole lines to the one holding `-->`. One written+ * mid-sentence is inline HTML belonging to its paragraph, so its `-->` may arrive on a later line and only the+ * text up to it is hidden. `closesBelow` says one does; without it the opener is ordinary text and hides nothing+ * below. "Starting a line" is read inside the container, so `blockOpen` comes from the item's content rather than+ * the raw line.*/function stripCommentSpans(line: string,@@ -360,12 +356,10 @@ function opensHtmlBlock(line: string, afterParagraph: boolean): boolean {}/**- * The line as list tracking sees it. A comment or raw block renders nothing, but- * the line opening one is still a block at its own column, so it closes a list- * item it sits left of. Only the column survives, since the text it hides is not- * Markdown. A line inside a block already open is that block's content, so it- * keeps neither. A marker the hidden block is the content of survives with the- * column, so the item it opens is still tracked.+ * The line as list tracking sees it. A comment or raw block renders nothing, but the line opening one is still a+ * block at its own column, so it closes a list item it sits left of. Only the column survives, since the text it+ * hides is not Markdown. A line inside a block already open is that block's content, so it keeps neither. A marker+ * the hidden block is the content of survives with the column, so the item it opens is still tracked.*/function structuralLine(line: string,@@ -459,9 +453,8 @@ function visibleContent(// written at the column it happens to start in.const hidden = state.inComment || state.inRawHtml !== null;const carried = state.runOn;- // A comment is an HTML block too, so one written as a list item's first content- // opens inside that item exactly as a fence does: read past a marker on the- // same line rather than from the margin.+ // A comment is an HTML block too, so one written as a list item's first content opens inside that+ // item exactly as a fence does: read past a marker on the same line rather than from the margin.const content = itemContent(line, state.afterParagraph);const opensComment =!(state.inComment || carried) && COMMENT_BLOCK_OPEN.test(content);@@ -499,11 +492,8 @@ function visibleContent(return { text: visible, structural };}-/**- * Marker of a fence the line scanner skipped because it is indented. Only a line- * within three columns of its item's content column is one: deeper than that it- * is an indented code block, which a dedented bullet ends.- */+/** Marker of a fence the line scanner skipped because it is indented. Only a line within three columns of its+ * item's content column is one: deeper than that it is an indented code block, which a dedented bullet ends. */function opensDeepFence(line: ContentLine): string | null {if (line.indent < INDENTED_CODE_INDENT ||@@ -515,12 +505,9 @@ function opensDeepFence(line: ContentLine): string | null {return fence ? (fence[1] ?? null) : null;}-/**- * True when `line` is the first one outside the deep fence opened with `marker`- * at `column`. A fence inside a list item runs only to the end of that item, so a- * line left of the item's content column closes both, as `fence_column` does on- * the backend.- */+/** True when `line` is the first one outside the deep fence opened with `marker` at `column`. A fence inside a+ * list item runs only to the end of that item, so a line left of the item's content column closes both, as+ * `fence_column` does on the backend. */function endsDeepFence(marker: string,column: number,@@ -543,11 +530,8 @@ function closesDeepFence(marker: string, line: ContentLine): boolean {);}-/**- * Cells of a GFM table row, or null when the line holds no pipe at all. The- * optional leading and trailing pipes are delimiters, not empty cells, and a- * `\|` is literal text inside one.- */+/** Cells of a GFM table row, or null when the line holds no pipe at all. The optional leading and trailing pipes+ * are delimiters, not empty cells, and an escaped pipe is literal text inside one. */function tableCells(text: string): string[] | null {if (!text.includes("|")) {return null;@@ -589,11 +573,9 @@ function delimiterWidth(text: string): number | null {: null;}-/**- * Line indices that belong to a GFM table. A table needs a header row and a- * delimiter row of the same width, and runs to a blank line or another block. Its- * cells render as a grid, not prose, so the preview drops them like a code block.- */+/** Line indices that belong to a GFM table. A table needs a header row and a delimiter row of the same width, and+ * runs to a blank line or another block. Its cells render as a grid, not prose, so the preview drops them like a+ * code block. */function opensTable(header: ContentLine | undefined,delimiter: ContentLine | undefined,@@ -674,11 +656,8 @@ function inBlock(state: ScanState): boolean {);}-/**- * A fence, comment or HTML block inside a list item runs only to the end of that- * item, so a line dedented out of the item closes both. Lazy continuation reaches- * into none of them, so any content left of the item ends it.- */+/** A fence, comment or HTML block inside a list item runs only to the end of that item, so a line dedented out of+ * the item closes both. Lazy continuation reaches into none of them, so any content left of the item ends it. */function closeDedentedBlock(line: string, state: ScanState): void {if (state.blockColumn === 0 || !inBlock(state)) {return;@@ -774,10 +753,8 @@ function contentLines(markdown: string): ContentLine[] {return lines;}-/**- * Split a bullet at its first sentence boundary. Conservative: the next- * sentence must start like one, so "unsloth.ai in the docs" is not a break.- */+/** Split a bullet at its first sentence boundary. Conservative: the next sentence must start like one, so+ * "unsloth.ai in the docs" is not a break. */function splitLeadSentence(text: string): ReleaseNotesPreviewItem {SENTENCE_BREAK.lastIndex = 0;let match = SENTENCE_BREAK.exec(text);@@ -973,10 +950,8 @@ function collectBullets(markdown: string): {return { bullets: collector.bullets, prose: collector.prose };}-/**- * Top-level bullets of a release section, in document order. Nested bullets are- * detail and are skipped; prose is used when a release has no bullets.- */+/** Top-level bullets of a release section, in document order. Nested bullets are detail and are skipped; prose is+ * used when a release has no bullets. */export function releaseNotesPreview(markdown: string | null | undefined,limit: number = RELEASE_NOTES_PREVIEW_ITEMS,diff --git a/studio/frontend/src/lib/resolved-precision.ts b/studio/frontend/src/lib/resolved-precision.tsindex 34466402a9e..def704ce961 100644--- a/studio/frontend/src/lib/resolved-precision.ts+++ b/studio/frontend/src/lib/resolved-precision.ts@@ -6,10 +6,9 @@** The old badge rule was `source === "auto"`, so an EXPLICIT precision the backend declined* rendered no badge at all while the dropdown kept advertising the request: a Q4_K_M GGUF could- * show FP8 with transformer FP8 disabled, and a successfully generated image proved nothing about- * the precision that ran. These helpers decide from BOTH sides of the record -- what was asked for- * and what engaged -- so a fallback is impossible to miss, and they seed the Advanced selects from- * the loaded model instead of leaving them as pure local request state.+ * show FP8 with transformer FP8 disabled. These helpers decide from BOTH sides of the record, what+ * was asked for and what engaged, so a fallback is impossible to miss, and they seed the Advanced+ * selects from the loaded model instead of leaving them as pure local request state.*/// One Advanced control's engaged value + provenance. Structurally shared by the image and video@@ -70,21 +69,18 @@ export function formatResolvedValue(key: string, value: string | boolean | null* Whether the caller's request survived. True when they left the control to the backend (there was* no request to betray) or when the backend says it applied it.*- * The `status` field is authoritative rather than a `requested !== value` string comparison,- * because several controls answer in a DIFFERENT vocabulary than they are asked in: memory_mode- * takes "low_vram" and reports the offload policy "sequential", attention_backend takes "cudnn" and- * reports "_native_cudnn". Comparing those directly would flag every honored request as a- * fallback. The backend, which owns both vocabularies, classifies it once. Older backends send no- * `status` at all, so they fall back to the mismatch test, which is still right for the precision- * controls (the ones P1-2 is about) since those echo their own vocabulary.+ * The `status` field is authoritative rather than a `requested !== value` comparison, because+ * several controls answer in a DIFFERENT vocabulary than they are asked in: memory_mode takes+ * "low_vram" and reports the offload policy "sequential", attention_backend takes "cudnn" and+ * reports "_native_cudnn". The backend, which owns both vocabularies, classifies it once. Older+ * backends send no `status`, so they fall back to the mismatch test, which is still right for the+ * precision controls since those echo their own vocabulary.** Only the two statuses that MEAN a decline are read as one. `status` is deliberately typed wider- * than the backend's union so a NEWER backend's fourth value still parses, but treating anything+ * than the backend's union so a NEWER backend's fourth value still parses, and treating anything* that is not "applied" as a failure defeats that: an unknown status would paint a red- * "FP8 -> FP8" over a request that was honored, and on memory_mode (asked "low_vram", answered- * "sequential") a "LOW_VRAM -> SEQUENTIAL" that never happened. An unrecognised status is not a- * decline -- staying quiet is the safe direction, since the build that adds a status ships the- * frontend that understands it.+ * "FP8 -> FP8" over a request that was honored. An unrecognised status is not a decline, since the+ * build that adds a status ships the frontend that understands it.*/export function isResolvedHonored(resolved: ResolvedControl | undefined | null): boolean {if (!resolved) return true;@@ -128,16 +124,12 @@ export function resolvedBadge(/*** The value an Advanced select should show for the LOADED model, mapped into that select's option- * vocabulary by `toOption`. Returns null when the record says nothing useful, so the caller keeps- * whatever the user has typed.- *- * - the backend chose it -> "auto" (the badge already names what that resolved to)- * - an honored explicit request -> that request- * - a DECLINED explicit request -> the value that actually engaged- *- * The last line is the P1-2 fix on the input side: the selects were pure local request state, so a- * declined FP8 stayed selected indefinitely and the interface went on displaying a precision the- * loaded model was not running.+ * vocabulary by `toOption`. Null when the record says nothing useful, so the caller keeps whatever+ * the user has typed. The backend chose it -> "auto" (the badge already names what that resolved+ * to); an honored explicit request -> that request; a DECLINED explicit request -> the value that+ * actually engaged. The last is the fix on the input side: the selects were pure local request+ * state, so a declined FP8 stayed selected indefinitely and the interface went on displaying a+ * precision the loaded model was not running.*/export function resolvedSelectValue<T extends string>(resolved: ResolvedControl | undefined | null,@@ -155,17 +147,15 @@ export function resolvedSelectValue<T extends string>(/*** The key the pages run their Advanced-reseed effect on: the LOAD-TIME half of the resolved record.*- * NOT the whole record serialized. The backend rewrites entries of it at GENERATION time -- the- * speed_mode and attention_backend entries when the deferred compile profile engages on the 3rd- * image, the transformer_cache entry whenever the step-cache threshold flips -- so keying the- * effect on the whole blob re-ran the reseed mid-session and overwrote a Precision the user had- * picked but not yet loaded. That is the opposite of the intent: an edit made after the load is- * meant to survive until the next LOAD replaces it.+ * NOT the whole record serialized. The backend rewrites entries of it at GENERATION time (the+ * speed_mode and attention_backend entries when the deferred compile profile engages, the+ * transformer_cache entry whenever the step-cache threshold flips), so keying the effect on the+ * whole blob re-ran the reseed mid-session and overwrote a Precision the user had picked but not+ * yet loaded. An edit made after the load is meant to survive until the next LOAD replaces it.** Only the controls the reseed writes are in the key, and for attention only the REQUEST side:- * `value` is the field the generation-time rewrite touches, and the reseed's answer for an auto or- * an honored request does not read it anyway. A reload still re-fires, including a Reapply with- * new options, because that always lands a different request or engaged value on one of these.+ * `value` is the field the generation-time rewrite touches. A reload still re-fires, including a+ * Reapply with new options, because that always lands a different request or engaged value.*/export function resolvedSeedKey(resolved: Record<string, ResolvedControl> | null | undefined,@@ -184,12 +174,10 @@ export function resolvedSeedKey(}/**- * Whether a status describes the native sd.cpp engine rather than a diffusers pipeline.- *- * It reports `dtype: "gguf"` and no `engine`/`model_kind` of its own, and the two behave- * differently in ways the Loaded-build panel has to say out loud -- its attention is chosen by- * native flags, not by the PyTorch dispatcher, and its components are whatever the checkpoint- * and its companion bundle hold.+ * Whether a status describes the native sd.cpp engine rather than a diffusers pipeline. It reports+ * `dtype: "gguf"` and no `engine`/`model_kind` of its own, and the two behave differently in ways+ * the Loaded-build panel has to say out loud: its attention is chosen by native flags, not by the+ * PyTorch dispatcher, and its components are whatever the checkpoint and its companion bundle hold.*/export function isNativeEngineStatus(status: {engine?: string | null;@@ -205,16 +193,14 @@ export function isNativeEngineStatus(status: {** Shared by the image and video pages because the mistake it prevents is the same on both: the* default arm is BF16, and only a full diffusers repo actually is. A GGUF pick runs the- * checkpoint's own quantisation, so the BF16 arm has to be the LAST resort.- *- * `dtype === "gguf"` is the native sd.cpp engine, which reports no `model_kind` at all -- without- * that arm every native GGUF load, the default CPU path, was labelled BF16 in the one panel whose- * whole job is to say what actually loaded.+ * checkpoint's own quantisation, so the BF16 arm has to be the LAST resort. `dtype === "gguf"` is+ * the native sd.cpp engine, which reports no `model_kind` at all; without that arm every native+ * GGUF load, the default CPU path, was labelled BF16 in the one panel whose whole job is to say+ * what actually loaded.** A single_file load is NOT "as in checkpoint": `from_single_file` is handed the resolved- * `torch_dtype`, so an fp8 safetensors is upcast on load (the memory planner budgets the ~2x for- * exactly that). Reporting the storage precision there hid the runtime dtype, which is the one- * thing this row exists to state, so it reads the dtype like any other dense load.+ * `torch_dtype`, so an fp8 safetensors is upcast on load. Reporting the storage precision there+ * hid the runtime dtype, so it reads the dtype like any other dense load.*/export function denseTransformerBuildLabel(status: {model_kind?: string | null;@@ -225,12 +211,11 @@ export function denseTransformerBuildLabel(status: {}/**- * The dtype the pipeline actually loaded in, not the one the happy path uses.- *- * A CPU diffusers load reports float32, an older accelerator resolves to float16, and an- * fp16-incompatible family is promoted to float32 by the video loader -- and all three were- * labelled BF16 by the panel whose whole job is to say what loaded. Unknown falls back to BF16,- * which is what a diffusers load that reports nothing is.+ * The dtype the pipeline actually loaded in, not the one the happy path uses. A CPU diffusers load+ * reports float32, an older accelerator resolves to float16, and an fp16-incompatible family is+ * promoted to float32 by the video loader, and all three were labelled BF16 by the panel whose+ * whole job is to say what loaded. Unknown falls back to BF16, which is what a diffusers load that+ * reports nothing is.*/function denseDtypeLabel(dtype: string | null | undefined): string {const text = String(dtype ?? "").trim().toLowerCase();@@ -242,10 +227,9 @@ function denseDtypeLabel(dtype: string | null | undefined): string {}/**- * The Loaded-build panel's Text encoder row when no runtime text-encoder quant engaged.- *- * The native sd.cpp engine has no runtime TE quant at all, so its status always reports- * `text_encoder_quant: null` -- which is not evidence of a bf16 encoder. Its companion bundle is+ * The Loaded-build panel's Text encoder row when no runtime text-encoder quant engaged. The native+ * sd.cpp engine has no runtime TE quant at all, so its status always reports+ * `text_encoder_quant: null`, which is not evidence of a bf16 encoder: its companion bundle is* whatever the family's asset mapping names, and several are not bf16 (FLUX.1 loads* `t5xxl_fp16.safetensors`). A null on that engine means "as stored", not BF16.*/@@ -254,13 +238,11 @@ export function denseTextEncoderBuildLabel(status: { dtype?: string | null }): s}/**- * The Recipe popover's Memory row: the placement that actually ran.- *- * The two fields answer different questions and either can be absent. `memory_mode` is the- * torchao-side memory planner's pick, and the native sd.cpp engine never runs it, so its records- * carry `memory_mode: null` alongside a real `offload_policy`. Substituting "auto" there claimed- * the planner had chosen a mode on a path that has no planner -- so an absent mode reports the- * offload alone, which is all that engine knows.+ * The Recipe popover's Memory row: the placement that actually ran. The two fields answer+ * different questions and either can be absent. `memory_mode` is the torchao-side memory planner's+ * pick, and the native sd.cpp engine never runs it, so its records carry `memory_mode: null`+ * alongside a real `offload_policy`. Substituting "auto" there claimed the planner had chosen a+ * mode on a path that has no planner, so an absent mode reports the offload alone.*/export function memoryRecipeValue(memoryMode: string | null | undefined,diff --git a/studio/frontend/src/lib/sparkle-icon.ts b/studio/frontend/src/lib/sparkle-icon.tsindex 66690b1e579..4c9c42a95eb 100644--- a/studio/frontend/src/lib/sparkle-icon.ts+++ b/studio/frontend/src/lib/sparkle-icon.ts@@ -3,13 +3,11 @@import type { IconSvgElement } from "@hugeicons/react";-// Hugeicons "Sparkle" (stroke-rounded): one four-point star, not the two-star-// "Sparkles". https://hugeicons.com/icon/sparkle-//-// Local because @hugeicons/core-free-icons 4.1.1 predates it, and pulling a-// newer icon set in would move every other glyph in the app for one shape. The-// path is the published stroke-rounded outline with its fixed #141B34 stroke-// swapped for currentColor, the same as the other icons in lib/.+// Hugeicons "Sparkle" (stroke-rounded): one four-point star, not the two-star "Sparkles".+// https://hugeicons.com/icon/sparkle Local because @hugeicons/core-free-icons 4.1.1 predates it,+// and pulling a newer icon set in would move every other glyph in the app for one shape. The path+// is the published stroke-rounded outline with its fixed #141B34 stroke swapped for currentColor,+// the same as the other icons in lib/.export const SparkleIcon: IconSvgElement = [["path",diff --git a/studio/frontend/src/lib/tick-icon.ts b/studio/frontend/src/lib/tick-icon.tsindex 4971079bd21..8914323f4ad 100644--- a/studio/frontend/src/lib/tick-icon.ts+++ b/studio/frontend/src/lib/tick-icon.ts@@ -13,8 +13,7 @@ export const Tick02Icon: IconSvgElement = [stroke: "currentColor",strokeLinecap: "round",strokeLinejoin: "round",- // Fallback weight, matching the icon set; call sites with a- // strokeWidth prop override this.+ // Fallback weight, matching the icon set; call sites with a strokeWidth prop override this.strokeWidth: "1.5",key: "0",},diff --git a/studio/frontend/src/lib/transfer-stats.ts b/studio/frontend/src/lib/transfer-stats.tsindex b0e5c734493..a0288905e78 100644--- a/studio/frontend/src/lib/transfer-stats.ts+++ b/studio/frontend/src/lib/transfer-stats.ts@@ -152,9 +152,8 @@ function measurableSpan(let resumed = false;for (let i = to - 1; i > 0; i -= 1) {if (samples[i].b <= samples[i - 1].b) continue;- // A silence past the stall window is a break, not a slow burst. Reaching- // across it averages the dead time in: 20 MB/s resuming after a 30 minute- // drop published 0.64 MB/s.+ // A silence past the stall window is a break, not a slow burst. Reaching across it averages the+ // dead time in: 20 MB/s resuming after a 30 minute drop published 0.64 MB/s.if (samples[newer].t - samples[i].t > stall) {resumed = true;break;diff --git a/studio/frontend/src/lib/video-utils.ts b/studio/frontend/src/lib/video-utils.tsindex 671e29c3c76..1320b37f5c5 100644--- a/studio/frontend/src/lib/video-utils.ts+++ b/studio/frontend/src/lib/video-utils.ts@@ -144,9 +144,8 @@ export function isAudioOnly3gpBytes(raw: Uint8Array): boolean {// A track table runs to kilobytes; anything this large is not one, and reading// it would be the memory problem the box walk exists to avoid.const MAX_MOOV_BYTES = 8 * 1024 * 1024;-// A container holds a handful of these: ftyp, moov, mdat, and maybe free or-// mfra. A file that reports thousands is malformed, and walking it would be-// one slice per box.+// A container holds a handful of these: ftyp, moov, mdat, and maybe free or mfra. A file that+// reports thousands is malformed, and walking it would be one slice per box.const MAX_TOP_LEVEL_BOXES = 64;/**@@ -245,10 +244,9 @@ export async function classifiedAttachmentFile(file: File): Promise<File> {// An unreadable file is left as it came; the surface reports the read.return file;}- // Both directions, because the browser's answer comes from the same ambiguous- // extension: a platform that maps .3gp to audio/3gpp says so for a clip too,- // and the audio adapter is matched before the video one. Tracks it cannot- // read decide nothing, so the file is left as it came.+ // Both directions, because the browser's answer comes from the same ambiguous extension: a+ // platform that maps .3gp to audio/3gpp says so for a clip too, and the audio adapter is matched+ // before the video one. Tracks it cannot read decide nothing, so the file is left as it came.const corrected = tracks.video? "video/3gpp": tracks.audio