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
Add an extra llama-server arguments box to the model settings (#8702)
Daniel Han2098b7cd4344
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 51a7c9e327a..bb4e24fba38 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -61,6 +61,7 @@ from core.inference.llama_server_args import (memory_state_satisfies_settings,fit_is_effectively_on,resolve_effective_memory_state,+ scrub_denied_env,scrub_memory_env,parse_cache_override,parse_cache_override_per_axis,@@ -484,6 +485,15 @@ _DEFAULT_STREAM_STALL_TIMEOUT_S = 120.0 # 2 min# loop). Structured delta.tool_calls are grammar-bounded by llama-server; text# parsed from content is not, so one runaway turn could fan out unbounded._MAX_TOOL_CALLS_PER_TURN = 8+# How far back the classifier looks for llama.cpp's argument-parsing error. It+# prints one and exits, so it is always at the end; generous enough to survive a+# usage hint printed after it, small enough that a 10 MB unterminated line (which+# _drain_stdout keeps whole) stays cheap to scan.+_FAILURE_SCAN_TAIL_CHARS = 64 * 1024+# How much of a quoted fragment from the child's own output an error message carries.+# Long enough for any real flag or reason, short enough that a wrapper printing+# megabytes cannot make the API error unreadable.+_FAILURE_QUOTE_CHARS = 200# Obligation phrasing INTENT_SIGNAL leaves alone ("I need to call ..."), paired with# an action verb. Sentence-anchored: mid-sentence the same words are prose that names# a tool ("The API I should invoke is foo() because ..."), and suppressing that loses@@ -4932,6 +4942,8 @@ class LlamaCppBackend:"supports_no_mmproj_offload": False,"supports_load_mode": False,"spec_draft_ngl_flag": None,+ "flags": {},+ "help_probe_ok": False,}try:binary_stat = Path(bin_path).stat()@@ -4976,6 +4988,23 @@ class LlamaCppBackend:saw_spec_type = Falseprobe_ok = Falsehelp_text = ""+ # Every flag this build documents, with its help text. Pre-initialised for+ # the same reason as the booleans above: a failed probe must fall back to+ # "nothing known", not raise.+ blocks: dict[str, str] = {}+ # Same reason, and the reason it lives out here rather than beside the parse+ # loop: a probe that times out leaves the loop unrun, and the catalogue below+ # is still built. Reading an unset local there turned a slow binary into an+ # UnboundLocalError instead of "nothing known about this build".+ takes_value: dict[str, bool] = {}++ def _is_real(flag: str) -> bool:+ """True if the flag exists AND is not a removal stub."""+ desc = blocks.get(flag)+ if desc is None:+ return False+ return "argument has been removed" not in desc+try:probe_env = cls._llama_server_env_for_binary(bin_path)# Capability detection describes the binary, independently of the@@ -5005,9 +5034,10 @@ class LlamaCppBackend:# Split into per-flag blocks (each --flag line + its indented# continuation), so the "argument has been removed" description# sits with its flag.- blocks: dict[str, str] = {}current_flags: list[str] = []current_desc: list[str] = []+ # Flag -> whether its declaration shows a value placeholder.+ current_takes_value = Falsefor line in help_text.splitlines():stripped = line.strip()if stripped.startswith("-") and not line.startswith(" "):@@ -5016,8 +5046,32 @@ class LlamaCppBackend:desc = " ".join(current_desc)for f in current_flags:blocks[f] = desc+ takes_value[f] = current_takes_valuecurrent_flags = []current_desc = [stripped]+ # Whether the flag takes a value at all, which is what tells+ # "--verbose foo" (a typo llama-server refuses) from "--numa+ # distribute". A placeholder follows its flag by a SINGLE space+ # ("--threads N"); the description sits in an aligned column two+ # or more spaces away. Only the yes/no is taken from this: how+ # many values, and of what shape, is not worth guessing at from+ # help text that wraps.+ current_takes_value = False+ _previous_end = None+ for _match in re.finditer(r"\S+", stripped):+ _token = _match.group()+ _flag_shaped = _token.startswith("-") and re.match(+ r"-{1,2}[A-Za-z][A-Za-z0-9_-]*,?$", _token+ )+ if _flag_shaped:+ _previous_end = _match.end()+ continue+ # The first token that is not an alias: a placeholder when it+ # is one space away, the description when it is further.+ current_takes_value = (+ _previous_end is not None and _match.start() - _previous_end == 1+ )+ break# Extract long-form flag tokens from the DECLARATION# prefix only (comma-separated aliases). Stop at the# first non-flag token so flag references inside@@ -5025,8 +5079,14 @@ class LlamaCppBackend:for tok in re.split(r"[,\s]+", stripped):if tok.startswith("--") and re.match(r"--[A-Za-z][A-Za-z0-9_-]*$", tok):current_flags.append(tok)+ elif tok.startswith("-") and re.match(r"-[A-Za-z][A-Za-z0-9_-]*$", tok):+ # A short alias (-fa, -t, -ngl). Kept, not just skipped:+ # the catalogue is what the editor checks a typed flag+ # against, and -t is as valid as --threads, so dropping+ # it warned that a correct flag was unknown.+ current_flags.append(tok)elif tok.startswith("-") and len(tok) > 1:- # short alias like -fa; keep scanning aliases.+ # A value placeholder like -1; keep scanning aliases.continueelse:# First non-flag token marks end of decl.@@ -5037,13 +5097,7 @@ class LlamaCppBackend:desc = " ".join(current_desc)for f in current_flags:blocks[f] = desc-- def _is_real(flag: str) -> bool:- """True if the flag exists AND is not a removal stub."""- desc = blocks.get(flag)- if desc is None:- return False- return "argument has been removed" not in desc+ takes_value[f] = current_takes_value# MTP token from the full --spec-type help block (decl + indented# continuation). First-line-only probing missed builds putting the@@ -5191,6 +5245,24 @@ class LlamaCppBackend:"supports_no_mmproj_offload": supports_no_mmproj_offload,"supports_load_mode": supports_load_mode,"spec_draft_ngl_flag": spec_draft_ngl_flag,+ # The whole parsed catalogue, not just the booleans above. The UI+ # validates pass-through args against THIS build rather than a list+ # bundled with Unsloth, since a custom or newer llama.cpp is exactly+ # the case where a bundled list would be wrong. Removal stubs are+ # excluded: a build that still lists --draft-max only to say the+ # argument has been removed would otherwise read as supporting it,+ # and the editor would stay quiet about a flag the load then refuses.+ "flags": {flag: desc for flag, desc in blocks.items() if _is_real(flag)},+ # The flags that take no value, so the editor can tell "--verbose foo"+ # (a typo llama-server refuses) from "--numa distribute".+ "switch_flags": sorted(+ flag for flag, takes in takes_value.items() if not takes and _is_real(flag)+ ),+ # Whether --help actually succeeded. A run that exits nonzero after+ # printing part of its help still leaves a non-empty catalogue, and a+ # caller that equated "parsed something" with "read the whole thing"+ # would call every flag past the failure point unknown.+ "help_probe_ok": bool(probe_ok),}with cls._capability_cache_lock:published = cls._capability_cache.get(cache_key)@@ -10777,6 +10849,7 @@ class LlamaCppBackend:binary: Optional[str] = None,log_path: "Optional[Path | str]" = None,secrets: Sequence[Optional[str]] = (),+ extra_args: Optional[Sequence[str]] = None,) -> str:"""Classify, then redact, whatever the classification quoted.@@ -10800,6 +10873,7 @@ class LlamaCppBackend:binary,log_path,secrets,+ extra_args,),secrets,)@@ -10813,6 +10887,7 @@ class LlamaCppBackend:binary: Optional[str] = None,log_path: "Optional[Path | str]" = None,secrets: Sequence[Optional[str]] = (),+ extra_args: Optional[Sequence[str]] = None,) -> str:"""Explain *why* llama-server failed to start, from its output.@@ -10895,6 +10970,85 @@ class LlamaCppBackend:f"{LlamaCppBackend._runtime_remedy(binary)}.")+ # Argument parsing runs before the model is touched, so a rejected flag is+ # never about the GGUF or memory. llama.cpp prints two shapes, and the+ # difference matters to the reader: an unknown flag is a typo or a flag+ # this build does not have, while a rejected VALUE is the right flag used+ # wrongly. Both are otherwise diagnosed as an invalid GGUF or an OOM.+ # Bounded, unlike the branches above, which have to see a dyld line whose+ # library name can itself be the pathological part. llama.cpp prints an+ # argument error and exits, so it is always at the end of the capture.+ scan_tail = (output or "")[-_FAILURE_SCAN_TAIL_CHARS:]++ def _short(value: str) -> str:+ """A quoted fragment of the child's output, kept to a readable length.++ The capture is a run of non-whitespace, and nothing stops a wrapper on+ LLAMA_SERVER_PATH from printing 64 KiB of it, so this is the bound that+ keeps an API error the size of an error rather than the size of the+ capture. _STARTUP_TAIL_CHARS bounds the surrounding diagnostics; this+ bounds the one piece interpolated straight from the child.+ """+ value = value.strip()+ return (+ value+ if len(value) <= _FAILURE_QUOTE_CHARS+ else (value[:_FAILURE_QUOTE_CHARS] + "...")+ )++ unknown_arg = re.search(r"error:\s*invalid argument:\s*(\S+)", scan_tail, re.IGNORECASE)+ if unknown_arg:+ # Both owners in one sentence, because nothing reaching here says which+ # one it was: Unsloth emits its own flags conditionally on the capability+ # probe, and a binary swapped underneath a cached probe rejects one of+ # those just as readily as it rejects a typo from the box. Sending every+ # reader to the extra arguments would point most of them at a box they+ # never opened.+ return (+ f"llama-server does not recognise the argument "+ f"'{_short(unknown_arg.group(1))}'. Check it in this model's extra "+ f"arguments, or reinstall llama.cpp if you did not set it."+ )++ bad_arg_value = re.search(+ r'error while handling argument "([^"]+)":\s*([^\r\n]*)',+ scan_tail,+ re.IGNORECASE,+ )+ if bad_arg_value:+ _arg = _short(bad_arg_value.group(1))+ _why = _short(bad_arg_value.group(2) or "")+ # "stoi" is what llama.cpp surfaces when std::stoi throws on a value+ # that is not a number; nobody outside the C++ standard library reads+ # that as an error message.+ if _why.lower() in {"stoi", "stof", "stod", "stoul", "stoll"}:+ _why = "the value is not a number"+ _tail = f": {_why}" if _why else ""+ # Whose flag it is decides the advice. Studio emits its own options+ # conditionally on the capability probe, so a build that reads+ # "--flash-attn on" differently rejects a value the box never held, and+ # sending that reader to edit their extra arguments points them at a+ # setting they cannot use to fix it. Named here only when the extras+ # really do carry the flag; an alias spelling falls back to the neutral+ # wording rather than guessing.+ _owned_by_user = False+ if extra_args:+ from core.inference.llama_server_args import _flag_name+ _failed_flag = _flag_name(_arg)+ _owned_by_user = _failed_flag is not None and any(+ _flag_name(str(token)) == _failed_flag for token in extra_args+ )+ if _owned_by_user:+ return (+ f"llama-server rejected the value for '{_arg}'{_tail}. Fix it in "+ f"the extra arguments for this model."+ )+ return (+ f"llama-server rejected the value for '{_arg}'{_tail}. Check it in "+ f"this model's extra arguments, or reinstall llama.cpp if you did "+ f"not set it."+ )+# Tensor parallelism (--split-mode tensor) is arch-gated in llama.cpp;# unsupported architectures abort the load with this marker. Point the# user at the toggle instead of a generic invalid-GGUF/OOM message.@@ -15464,6 +15618,15 @@ class LlamaCppBackend:"Model Memory owns placement; dropped inherited %s",", ".join(_mem_scrubbed),)+ # Same reasoning one level up: a flag validate_extra_args refuses has+ # an env twin llama.cpp reads before argv, so denying the token alone+ # would leave the capability reachable and unrecorded.+ _denied_scrubbed = scrub_denied_env(env)+ if _denied_scrubbed:+ logger.info(+ "dropped inherited %s: managed by Unsloth Studio",+ ", ".join(_denied_scrubbed),+ )# Record what the child will ACTUALLY run with (env defaults plus# last-wins argv), not just what Unsloth emitted, so the reload# hint also catches a user-supplied --mlock / --no-mmap.@@ -16046,6 +16209,7 @@ class LlamaCppBackend:binary,self._llama_log_path,(self._api_key,),+ self._extra_args,)self._cleanup_failed_cpu_fallback()self._vram_fraction_pending = None@@ -16638,6 +16802,7 @@ class LlamaCppBackend:binary,self._llama_log_path,(self._api_key,),+ self._extra_args,)_raise_terminal_load_failure(self._mmproj_retry_failure_message(@@ -16674,6 +16839,7 @@ class LlamaCppBackend:binary,self._llama_log_path,(self._api_key,),+ self._extra_args,))diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex a87d104cb6d..cd00b711b72 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -14,6 +14,7 @@ Ref: https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.mdfrom __future__ import annotationsimport os+import sysfrom typing import Iterable, Mapping, Optional# Valid llama-server --parallel range, shared with LoadRequest.n_parallel.@@ -67,9 +68,9 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (# llama.cpp binaries match.frozenset({"--webui", "--no-webui"}),frozenset({"--ui", "--no-ui"}),- frozenset({"--ui-config"}),- frozenset({"--ui-config-file"}),- frozenset({"--ui-mcp-proxy", "--no-ui-mcp-proxy"}),+ frozenset({"--ui-config", "--webui-config"}),+ frozenset({"--ui-config-file", "--webui-config-file"}),+ frozenset({"--ui-mcp-proxy", "--webui-mcp-proxy", "--no-ui-mcp-proxy", "--no-webui-mcp-proxy"}),frozenset({"--models-dir"}),frozenset({"--models-preset"}),frozenset({"--models-max"}),@@ -83,12 +84,95 @@ _DENYLIST_GROUPS: tuple[frozenset[str], ...] = (# llama-server's own built-in tools flag would silently stack on top of# Unsloth's --enable-tools / --disable-tools policy resolver.frozenset({"--tools"}),- # Slot-state dir: Studio owns it for KV persistence across idle unload.+ # --agent is --tools by another name: upstream documents it as "enable CORS+ # proxy and ALL built-in tools", and that set includes exec_shell_command.+ # Denying --tools while allowing this left the same capability one alias away.+ frozenset({"-ag", "--agent", "-no-ag", "--no-agent"}),+ # Where those tools run: docker:/podman: spins up a container, ssh:<target>+ # runs them on another host entirely.+ frozenset({"--tools-runtime"}),+ # MCP servers are tools from a config file or an inline JSON blob; upstream+ # says "do not enable in untrusted environments" for both.+ frozenset({"--mcp-servers-config"}),+ frozenset({"--mcp-servers-json"}),+ # CORS: Unsloth terminates browser access at its own origin, so widening the+ # child's would hand a page past the boundary the proxy exists to hold.+ frozenset({"--cors-origins"}),+ frozenset({"--cors-headers"}),+ frozenset({"--cors-methods"}),+ frozenset({"--cors-credentials", "--no-cors-credentials"}),+ # Serves local files over the child's HTTP surface.+ frozenset({"--media-path"}),+ # Startup output is how _classify_llama_start_failure tells a bad GGUF from an+ # OOM from a rejected flag; redirecting or silencing it makes every failure+ # the same opaque one.+ frozenset({"--log-file"}),+ frozenset({"--log-disable"}),+ # Slot-state dir: Studio owns it for KV persistence across idle unload. Endpoint+ # exposure (--slots, --props) is deliberately NOT denied alongside it: Unsloth+ # reads GET /props and never /slots, so either is the user's own call.frozenset({"--slot-save-path"}),+ # These print and exit instead of serving, so the load would "succeed" with no+ # server behind it and only time out later.+ frozenset({"-h", "--help", "--usage"}),+ frozenset({"--version"}),+ frozenset({"--list-devices"}),+ frozenset({"-cl", "--cache-list"}),+ frozenset({"--completion-bash"}),)_DENYLIST: frozenset[str] = frozenset().union(*_DENYLIST_GROUPS)+# Flags that take TWO values rather than one. Scanned out of `llama-server --help`:+# every other option is `--flag VALUE` or a switch, and this list exists so the+# positional check below does not refuse a legitimate second value.+_TWO_VALUE_FLAGS: frozenset[str] = frozenset({"--control-vector-layer-range"})++# Flags that take a second value on SOME builds. Today's llama.cpp writes the scale+# into the value ("--lora-scaled FNAME:SCALE"), and older ones took it as a separate+# token ("--lora-scaled FNAME SCALE"); both spellings are already handled in+# _sidecar_weight_files. So the second token is allowed but never required: demanding+# it would refuse the current syntax, and refusing it broke a list that loaded before+# the positional check existed.+_OPTIONAL_SECOND_VALUE_FLAGS: frozenset[str] = frozenset(+ {"--lora-scaled", "--control-vector-scaled"}+)++# Shape bounds. Not a security boundary -- the denylist is -- but a pasted file or a+# runaway generator should fail here, naming the limit, rather than at execve or in+# llama-server's own parser. Generous enough that a grammar or a JSON schema fits.+MAX_EXTRA_ARG_TOKENS = 256+MAX_EXTRA_ARGS_BYTES = 32 * 1024+# Windows passes CreateProcess ONE string for the whole command line, capped at 32767+# characters, and the model path, Unsloth's own flags and the quoting subprocess adds+# all come out of the same budget. So the extras get a smaller share there: accepting+# the full 32 KiB would pass every check here and then fail inside Popen, after the+# load had already begun switching models.+MAX_EXTRA_ARGS_BYTES_WINDOWS = 24 * 1024+++# CreateProcess takes the whole command line as ONE string, capped here. The rest of+# the command (the binary, the model path, Unsloth's own flags) has to fit too, so the+# extras are checked against the limit minus this reserve.+WINDOWS_COMMAND_LIMIT = 32767+WINDOWS_COMMAND_RESERVE = 8192+++def windows_command_length(args: list) -> int:+ """Characters ``subprocess`` would put on a Windows command line for ``args``.++ list2cmdline is the exact serializer Popen uses there, and it is not a sum of+ lengths: a value needing quotes has its backslashes doubled, so an escape-heavy+ grammar can nearly double. Measuring it is the only honest check.+ """+ import subprocess+ return len(subprocess.list2cmdline([str(a) for a in args]))+++def max_extra_args_bytes() -> int:+ """The size cap for this platform."""+ return MAX_EXTRA_ARGS_BYTES_WINDOWS if sys.platform == "win32" else MAX_EXTRA_ARGS_BYTES+def _flag_name(token: str) -> Optional[str]:"""Flag name for ``token``, or None if it isn't a flag.@@ -115,6 +199,35 @@ def _flag_name(token: str) -> Optional[str]:return name+def _value_is_attached(token: str, flag: str) -> bool:+ """Whether this token carries its own value, rather than expecting the next one.++ Not "the name changed": _flag_name also folds llama.cpp's underscore spelling+ (--ctx_size is --ctx-size to it, and the binary takes both), so comparing the+ normalised name against the raw token read "--ctx_size 4096" as attached and then+ refused the 4096 as a bare value. Only "=" and an attached short like -np8 are+ values in the same token.+ """+ raw = token.strip()+ if "=" in raw:+ return True+ return raw.replace("_", "-") != flag+++def _is_spawnable(token: str) -> bool:+ """Whether execve could carry this token at all (no unpaired surrogates)."""+ try:+ token.encode("utf-8")+ except UnicodeEncodeError:+ return False+ return True+++def _has_control_characters(token: str) -> bool:+ """A NUL, or any C0 control other than tab and newline."""+ return any(ch == "\x00" or (ord(ch) < 32 and ch not in "\t\n") for ch in token)++def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:"""Validate user-supplied llama-server args. Returns a flat list ready toextend the llama-server command; raises ``ValueError`` naming the@@ -122,15 +235,122 @@ def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:if not args:return []out: list[str] = []+ total_bytes = 0+ # How many following tokens the flag just seen may still claim as values. A+ # switch claims none, so the next bare token has no owner.+ pending_values = 0+ # Values still owed to a two-value flag, tracked apart because it is the one+ # arity this module knows for certain.+ pending_two_value = 0+ two_value_flag = ""for raw in args:token = str(raw)+ if len(out) >= MAX_EXTRA_ARG_TOKENS:+ raise ValueError(+ f"too many extra llama-server args (limit {MAX_EXTRA_ARG_TOKENS} tokens)"+ )+ # A grammar or JSON schema is a legitimately long single token, so the cap+ # is on the whole list rather than per token.+ # Strictly, unlike the sizing below: JSON and the browser can both carry an+ # unpaired surrogate, which survives every check here and then makes+ # subprocess.Popen raise while it encodes argv, long after the load has begun+ # switching models. Refused at the boundary, where it is still a 400.+ try:+ encoded = token.encode("utf-8")+ except UnicodeEncodeError as error:+ raise ValueError(+ "extra llama-server args cannot contain unpaired surrogate characters"+ ) from error+ total_bytes += len(encoded)+ limit = max_extra_args_bytes()+ if total_bytes > limit:+ raise ValueError(f"extra llama-server args are too large (limit {limit} bytes)")+ # execve rejects a NUL outright; the rest would reach the child's parser as+ # invisible characters and be blamed on the flag they are attached to.+ if _has_control_characters(token):+ raise ValueError("extra llama-server args cannot contain control characters")flag = _flag_name(token)if flag is not None and flag in _DENYLIST:raise ValueError(f"llama-server flag '{flag}' is managed by Unsloth Studio "f"and cannot be passed as an extra arg")+ if flag is None:+ # A token belonging to no flag. Today's llama-server answers "invalid+ # argument" and refuses to start, which is a failed load rather than a+ # 400, and a build that did accept a positional would read it as the+ # model path: that is the one thing the -m / --model denial exists to+ # prevent, and it would sidestep the native-path lease as well.+ if pending_values <= 0:+ raise ValueError(+ "extra llama-server args cannot contain a bare value "+ f"('{token[:64]}'); every value must follow its flag"+ )+ pending_values -= 1+ if pending_two_value > 0:+ pending_two_value -= 1+ elif token != token.strip():+ # _flag_name strips before it looks anything up, so a quoted "--top-k "+ # passed the denylist and the arity walk as --top-k and then went to the+ # child with the space still on it. llama.cpp looks the whole token up,+ # so it answers "error: invalid argument: --top-k" (measured on b10342),+ # naming a flag that looks correct in the log. Only flag-shaped tokens:+ # a VALUE may legitimately end in whitespace, a chat template or a+ # grammar being the obvious ones.+ raise ValueError(+ f"llama-server does not accept the spaces around '{token[:64]}': "+ f"write it as '{flag}'"+ )+ elif "=" in token:+ # llama.cpp looks the WHOLE token up in its option map, folding only the+ # underscore spelling, so "--top-k=20" is not "--top-k" with a value: it+ # is an argument it has never heard of. Measured on b10342 and b10360,+ # where --top-k=20, --ctx-size=4096 and --flash-attn=on each exit with+ # "error: invalid argument". Accepting the GNU spelling here meant the+ # switch tore down the resident model and the child then refused to+ # start, so it is refused while it is still a 400 with somewhere to go.+ # Splitting it here would be a guess: for a switch the value is not one,+ # and this module cannot know an ordinary flag's arity.+ value = token.partition("=")[2]+ raise ValueError(+ f"llama-server does not read an attached value: write '{flag}' and "+ f"'{value[:32]}' as two separate arguments, not '{token[:64]}'"+ )+ else:+ # Its own value when attached, otherwise the tokens that follow.+ attached = _value_is_attached(token, flag)+ if pending_two_value > 0:+ raise ValueError(f"llama-server flag '{two_value_flag}' takes two values")+ # An attached value is ONE of the two, not the whole option:+ # "--control-vector-layer-range=1" still owes its END, and+ # llama-server exits on the incomplete option.+ if flag in _TWO_VALUE_FLAGS:+ pending_values = 1 if attached else 2+ pending_two_value = pending_values+ elif flag in _OPTIONAL_SECOND_VALUE_FLAGS:+ # Allowed, not owed: pending_two_value stays 0, so nothing here+ # insists on the second token.+ pending_values = 1 if attached else 2+ pending_two_value = 0+ else:+ pending_values = 0 if attached else 1+ pending_two_value = 0+ two_value_flag = flagout.append(token)+ if pending_two_value > 0:+ # Only this shape is checkable: an ordinary flag's arity is unknown here, so+ # a list ending in one is left to llama-server. START without END is a launch+ # that fails on the command line rather than a request that fails here.+ raise ValueError(f"llama-server flag '{two_value_flag}' takes two values")+ if sys.platform == "win32":+ # After the per-token walk, because this is a property of the whole list.+ serialized = windows_command_length(out)+ budget = WINDOWS_COMMAND_LIMIT - WINDOWS_COMMAND_RESERVE+ if serialized > budget:+ raise ValueError(+ "extra llama-server args are too long for a Windows command line "+ f"({serialized} characters after quoting, limit {budget})"+ )parse_ctx_override(out)parse_cache_override(out)parse_split_mode_override(out)@@ -138,6 +358,145 @@ def validate_extra_args(args: Optional[Iterable[str]]) -> list[str]:return out+def drop_managed_flags(args: Optional[Iterable[str]]) -> tuple[list[str], list[str]]:+ """Split stored args into what still loads and the flag names removed.++ For the paths that CARRY OVER an existing value rather than receive a new one.+ The denylist grows (``--agent`` and the MCP flags were added once a text box+ made them one paste away), so an override saved by an older build can hold a+ name that is refused today. Refusing there punishes a user for a decision made+ later: the load, or the save of an unrelated setting, fails naming a flag they+ may not remember writing. Dropping is the same judgement applied quietly.++ A flag takes its value with it, or ``--log-file /var/log/x`` would leave a bare+ ``/var/log/x`` behind, which llama.cpp reads as a positional model path. The+ bounds and the control-character rule are enforced by re-validating what is+ left, so the result is always something ``validate_extra_args`` accepts.+ """+ tokens = [str(raw) for raw in (args or [])]++ def _takes_next(+ index: int,+ token: str,+ flag: str,+ source: list = None,+ ) -> bool:+ """True when the token's value is the NEXT token rather than its own.++ ``source`` defaults to the input list; the trimming loop passes the list it+ is shortening, where "the next token" means the one just removed.+ """+ if _value_is_attached(token, flag):+ return False+ seq = tokens if source is None else source+ if source is not None:+ # Called on the last surviving token, whose value was the token just shed.+ return True+ following = seq[index + 1] if index + 1 < len(seq) else None+ return following is not None and _flag_name(following) is None++ kept: list[str] = []+ dropped: list[str] = []+ skip_next = False+ for index, token in enumerate(tokens):+ if skip_next:+ skip_next = False+ continue+ flag = _flag_name(token)+ if flag is not None and flag in _DENYLIST:+ dropped.append(flag)+ skip_next = _takes_next(index, token, flag)+ continue+ # A control character never reached the child as anything but noise, and a+ # NUL never reached it at all (execve refuses). A poisoned VALUE takes its+ # flag with it for the same reason a denied flag takes its value: a flag+ # left expecting one would eat the next token and change what that means.+ if _has_control_characters(token) or not _is_spawnable(token):+ # A placeholder either way: this list is joined into a warning log, and+ # the unusable characters are in the token itself, so echoing its name+ # would rewrite whatever is reading that log just as echoing its value+ # would.+ dropped.append("<flag>" if flag is not None else "<value>")+ if flag is not None:+ # Its value goes too, exactly as a denied flag's does: an orphan left+ # behind is a bare positional, which llama-server reads as the model+ # path.+ skip_next = _takes_next(index, token, flag)+ elif kept:+ owner = _flag_name(kept[-1])+ if owner is not None:+ dropped.append(owner)+ kept.pop()+ continue+ if flag is not None and "=" in token:+ # An attached value llama-server refuses outright, whatever the flag. Dropped+ # here with the denied names rather than left to the trimming loop below:+ # that loop sheds the TAIL, so one legacy "--top-k=20" in the middle would+ # cost every flag written after it. Nothing to skip, the value is in the+ # token. After the control-character check, so a poisoned name is still+ # logged as a placeholder rather than echoed.+ dropped.append(flag)+ continue+ if flag is not None and token != token.strip():+ # Refused for the same reason, and its value goes with it: the padding is+ # part of the token llama.cpp looks up, so the flag never arrives and the+ # value it was written for would be left as a bare positional.+ dropped.append(flag)+ skip_next = _takes_next(index, token, flag)+ continue+ if (+ flag is not None+ and _takes_next(index, token, flag)+ and (_has_control_characters(tokens[index + 1]) or not _is_spawnable(tokens[index + 1]))+ ):+ # Recorded, not just skipped: the value is about to be dropped for its+ # control characters, and a flag that vanished without a word in the log+ # is the harder half of that to explain afterwards.+ dropped.append(flag)+ continue+ kept.append(token)++ while kept:+ try:+ return validate_extra_args(kept), dropped+ except ValueError:+ # Only the bounds can still fail here, and they are about length, so the+ # tail is the right thing to shed. A flag whose value has just gone with+ # it goes too: `['--grammar', <33 KiB>]` trimmed to `['--grammar']` is+ # syntactically valid to this validator, which knows the arity of only a+ # few flags, and llama-server then refuses the launch over a flag with+ # no value.+ # Names, not values: this list goes into a log line, and the token that+ # broke the bound is by definition enormous.+ dropped.append(_flag_name(kept[-1]) or "<value>")+ kept = kept[:-1]+ last_flag = _flag_name(kept[-1]) if kept else None+ if last_flag is not None and _takes_next(len(kept) - 1, kept[-1], last_flag, kept):+ dropped.append(last_flag)+ kept = kept[:-1]+ # A two-value flag loses the whole option rather than half of it: one+ # value left behind is a command llama-server refuses at startup, which+ # is the failure this trimming exists to avoid.+ while len(kept) >= 2:+ owner = _flag_name(kept[-2])+ if (+ owner in _TWO_VALUE_FLAGS+ and _flag_name(kept[-1]) is None+ and "=" not in kept[-2]+ ):+ dropped.append(owner)+ kept = kept[:-2]+ continue+ break+ return [], dropped+++def sorted_managed_flags() -> list[str]:+ """Every denied flag, sorted, for a UI that wants to explain a rejection before+ the request is made. The validator stays the authority; this is only a mirror."""+ return sorted(_DENYLIST)++def is_managed_flag(flag: str) -> bool:"""True if ``flag`` is Unsloth-managed. Normalises via ``_flag_name`` so`-np8` / `--parallel=8` classify like the canonical tokens."""@@ -396,6 +755,33 @@ def parse_gpu_layers_override(args: Optional[Iterable[str]]) -> Optional[int]:return value+def check_batch_floor(args: Optional[Iterable[str]], n_parallel: int) -> None:+ """Raise when a pass-through --batch-size would abort llama-server.++ The launcher raises the value it emits itself to ``max(slots, 2)``, with the+ measurements recorded beside that code: ``-b 1`` aborts at any slot count, and a+ batch below ``--parallel`` aborts too. Extras are appended AFTER that flag and win+ the last-wins parse, so a small value here is not a smaller batch, it is a server+ that dies during startup, and by then the previous model has been unloaded.++ Only the shapes that are certainly wrong: an unreadable value is left to+ llama-server, which names it better than a guess here would.+ """+ raw_value = _last_flag_value(args, _BATCH_FLAGS)+ if raw_value is None:+ return+ try:+ value = int(raw_value)+ except ValueError:+ return+ floor = max(2, int(n_parallel or 1))+ if value < floor:+ raise ValueError(+ f"llama-server aborts on --batch-size {value}: it needs at least {floor} "+ f"for the {max(1, int(n_parallel or 1))} parallel slot(s) this load serves"+ )++def fit_is_enabled_in(args: Optional[Iterable[str]]) -> bool:"""Whether the last ``--fit`` in extras turns the fitter ON.@@ -802,6 +1188,115 @@ def _env_var_locks_or_reserves(name: str, value: str) -> bool:return False+# The LLAMA_ARG_* twins of flags the denylist refuses. llama.cpp reads these before+# argv, so a name refused in extra args is still reachable through the environment+# Unsloth's own process inherits. Anyone who can set that environment can already do+# worse, so this is not the boundary -- it just stops a denied flag arriving by the+# back door and leaving no trace in the recorded command.+DENIED_ENV_VARS: tuple[str, ...] = (+ "LLAMA_ARG_TOOLS",+ "LLAMA_ARG_TOOLS_RUNTIME",+ "LLAMA_ARG_AGENT",+ "LLAMA_ARG_MCP_SERVERS_CONFIG",+ "LLAMA_ARG_MCP_SERVERS_JSON",+ "LLAMA_ARG_CORS_ORIGINS",+ "LLAMA_ARG_CORS_HEADERS",+ "LLAMA_ARG_CORS_METHODS",+ "LLAMA_ARG_CORS_CREDENTIALS",+ "LLAMA_ARG_MEDIA_PATH",+ # The twins of --log-file and --log-disable. Studio classifies a failed start by+ # reading llama-server's own output, so an inherited redirect leaves every+ # failure looking like the same opaque one; and unlike the flags, Studio emits+ # nothing later that would override these. LLAMA_ARG_LOG_DISABLE has no twin in+ # today's builds, and is listed so it cannot arrive as one.+ "LLAMA_ARG_LOG_FILE",+ "LLAMA_ARG_LOG_DISABLE",+ # --api-prefix moves every endpoint, including the /health Studio waits on, so an+ # inherited one turns every load into a timeout.+ "LLAMA_ARG_API_PREFIX",+ # --api-key and its file. Studio terminates auth itself and sends the child no+ # Authorization header, so an inherited key makes the healthy child refuse every+ # request. The bundled build reads LLAMA_API_KEY for the flag and+ # LLAMA_ARG_API_KEY_FILE for the file; the third spelling is listed because the+ # name has moved between releases and none of them is ours to honour.+ "LLAMA_API_KEY",+ "LLAMA_ARG_API_KEY",+ "LLAMA_ARG_API_KEY_FILE",+ # The twins of --ssl-key-file and --ssl-cert-file. Given both, llama-server+ # listens on https, while Studio probes /health and proxies over http against+ # the port it launched: the child comes up healthy and every load times out.+ # Measured on b10360, where an inherited pair turns "listening on+ # http://127.0.0.1:PORT" into "listening on https://...".+ "LLAMA_ARG_SSL_KEY_FILE",+ "LLAMA_ARG_SSL_CERT_FILE",+ # The rest of the twins its --help documents for a denied flag, enumerated from+ # the bundled b10342 help rather than picked one at a time: every "(env: NAME)"+ # whose option this module refuses. Studio emits most of these itself and argv+ # wins over the environment, so removing them changes nothing in the ordinary+ # case; they are here for the paths where it does not, and so a flag denied in+ # the box is not reachable through the environment instead. The mapping below+ # records which flag each one belongs to, since the name does not always say+ # (LLAMA_ARG_STATIC_PATH is --path).+ "LLAMA_ARG_MODEL",+ "LLAMA_ARG_MODEL_URL",+ "LLAMA_ARG_DOCKER_REPO",+ "LLAMA_ARG_HF_REPO",+ "LLAMA_ARG_HF_FILE",+ "LLAMA_ARG_ALIAS",+ "LLAMA_ARG_HOST",+ "LLAMA_ARG_PORT",+ "LLAMA_ARG_REUSE_PORT",+ "LLAMA_ARG_N_PARALLEL",+ "LLAMA_ARG_POOLING",+ "LLAMA_ARG_EMBEDDINGS",+ "LLAMA_ARG_RERANKING",+ # The web UI and its MCP proxy, which upstream marks as not for untrusted+ # environments, and the directory the child serves files from.+ "LLAMA_ARG_UI",+ "LLAMA_ARG_UI_CONFIG",+ "LLAMA_ARG_UI_CONFIG_FILE",+ "LLAMA_ARG_UI_MCP_PROXY",+ "LLAMA_ARG_STATIC_PATH",+ # Deliberately absent: LLAMA_ARG_MMPROJ and LLAMA_ARG_MMPROJ_URL. --mmproj is+ # refused in the box because Unsloth resolves the projector itself, but the+ # environment twin is an INPUT here: _launch_has_mmproj reads both to know the+ # launch has a projector at all, which is what keeps the vision and audio state+ # of a model loaded through an inherited one. Only the paravirtual CPU recovery+ # drops them, where an unpinned projector is the corrupt path it is undoing.+ # The pooling twins are absent for the opposite reason: load_model already pops+ # LLAMA_ARG_POOLING / _RERANKING / _EMBEDDINGS itself, next to where it decides+ # what the GGUF header says.+ # The multi-model server mode: a child holding its own model directory, preset+ # and autoload policy is not the single model Studio launched and accounts for.+ "LLAMA_ARG_MODELS_DIR",+ "LLAMA_ARG_MODELS_PRESET",+ "LLAMA_ARG_MODELS_MAX",+ "LLAMA_ARG_MODELS_AUTOLOAD",+)++# Which flag each twin belongs to, for the drift test. Derived by name for most of+# them, but not all: LLAMA_ARG_STATIC_PATH is --path, LLAMA_API_KEY is --api-key, and+# a rename upstream would otherwise leave a variable here guarding nothing.+DENIED_ENV_TWIN_FLAGS: dict[str, str] = {+ "LLAMA_ARG_STATIC_PATH": "--path",+ "LLAMA_API_KEY": "--api-key",+ "LLAMA_ARG_API_KEY": "--api-key",+ "LLAMA_ARG_N_PARALLEL": "--parallel",+ "LLAMA_ARG_EMBEDDINGS": "--embeddings",+ "LLAMA_ARG_RERANKING": "--reranking",+ "LLAMA_ARG_UI_CONFIG_FILE": "--ui-config-file",+ "LLAMA_ARG_MODELS_AUTOLOAD": "--models-autoload",+}+++def scrub_denied_env(env: dict) -> list[str]:+ """Drop inherited ``LLAMA_ARG_*`` twins of denied flags. Returns the names removed."""+ removed = [name for name in DENIED_ENV_VARS if name in env]+ for name in removed:+ env.pop(name, None)+ return removed++def scrub_memory_env(env: dict) -> list[str]:"""Drop inherited memory placement the settings override.diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 30976eff181..1c5bf67c323 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -334,6 +334,15 @@ class ValidateModelRequest(BaseModel):None, description = "Frontend-visible signed native path grant")hf_token: Optional[str] = Field(None, description = "HuggingFace token for gated models")+ llama_extra_args: Optional[List[str]] = Field(+ None,+ description = (+ "Pass-through llama-server args the follow-up /load will send. Sized with, "+ "not validated here: a --ctx-size or cache override changes the memory this "+ "preflight estimates, so omitting it would approve a different command from "+ "the one that runs."+ ),+ )gguf_variant: Optional[str] = Field(None, description = "GGUF quantization variant (e.g. 'Q4_K_M')")@@ -857,6 +866,17 @@ class _InferenceRuntimeFields(BaseModel):"when the load left it at the llama.cpp default (or to extra args / env)."),)+ requested_llama_extra_args: Optional[List[str]] = Field(+ None,+ description = (+ "Pass-through llama-server arguments the running load was INVOKED "+ "with, or None for a non-GGUF load and for a load that passed none. "+ "Published so a client that attached to an already-running server "+ "(a fresh tab, or another browser) knows what it is running: without "+ "it, a rollback after a failed switch restores the previous model "+ "without the arguments it had."+ ),+ )class LoadResponse(_InferenceRuntimeFields):@@ -910,6 +930,71 @@ class LoadProgressResponse(BaseModel):fraction: float = Field(0.0, description = "bytes_loaded / bytes_total, clamped to 0..1.")+class LlamaFlagCatalogResponse(BaseModel):+ """Every llama-server flag THIS build documents, for validating pass-through args.++ Read from the installed binary's ``--help`` rather than a list bundled with+ Unsloth: a custom or newer llama.cpp is exactly the case where a bundled list+ would reject a flag that works, or accept one that does not exist.+ """++ flags: dict[str, str] = Field(+ default_factory = dict,+ description = "Flag name -> its help text, e.g. {'--top-k': 'top-k sampling ...'}",+ )+ managed: list[str] = Field(+ default_factory = list,+ description = "Flags Unsloth Studio owns; validate_extra_args rejects these outright",+ )+ switch_flags: list[str] = Field(+ default_factory = list,+ description = (+ "Flags this build documents as taking no value, so an editor can tell "+ "'--verbose foo' (which llama-server refuses) from '--numa distribute'"+ ),+ )+ max_bytes: int = Field(+ 0,+ description = (+ "Size limit validate_extra_args applies on THIS host; smaller on Windows, "+ "where the whole command line shares one 32767-character budget"+ ),+ )+ windows_command_budget: int = Field(+ 0,+ description = (+ "Characters the quoted command may take on Windows, or 0 elsewhere. An "+ "editor mirrors it because the quoting can double a backslash-heavy value."+ ),+ )+ default_parallel_slots: int = Field(+ 1,+ description = (+ "Serving slots a load gets when it names none, the server-wide "+ "--parallel. An editor needs it to judge a pass-through --batch-size: "+ "llama-server aborts on a batch below the slots it serves, and with the "+ "Slots field blank this is the number the launch will use."+ ),+ )+ parallel_slots_clamped: bool = Field(+ False,+ description = (+ "True when this build serves ONE slot however many are asked for, because "+ "it has no --kv-unified and load_model falls back. The default above is "+ "already effective, but an EXPLICIT Slots value is not: without this an "+ "editor sizes its batch floor from a count the launch will not use, and "+ "refuses a --batch-size the backend accepts."+ ),+ )+ probe_ok: bool = Field(+ False,+ description = (+ "False when --help could not be read. `flags` is then empty and callers "+ "must not report a flag as unknown, only as unverified."+ ),+ )++class InferenceStatusResponse(_InferenceRuntimeFields):"""Current inference backend status"""diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 919a87a9448..47f62190aec 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -1275,6 +1275,7 @@ try:)from core.inference.llama_server_args import (_effective_tensor_parallel,+ drop_managed_flags,extra_args_disable_mmproj,parse_gpu_layers_override,parse_split_mode_override,@@ -1328,6 +1329,7 @@ except ImportError:)from core.inference.llama_server_args import (_effective_tensor_parallel,+ drop_managed_flags,extra_args_disable_mmproj,parse_gpu_layers_override,parse_split_mode_override,@@ -2192,6 +2194,7 @@ from models.inference import (LoadProgressResponse,UnloadResponse,InferenceStatusResponse,+ LlamaFlagCatalogResponse,ChatCompletionRequest,ChatCountTokensRequest,ChatCompletionChunk,@@ -4391,6 +4394,27 @@ def _llama_runtime_fields(llama_backend: LlamaCppBackend) -> dict:parallel_slots = (None if llama_backend.is_diffusion else llama_backend.effective_parallel_slots),+ # What the load was INVOKED with, not the rewritten launch list: that is the+ # list a client would have to resend to reproduce this server, and the one+ # the rollback path needs. Empty reports as None, so "passed none" and+ # "never set" read alike to a client that only ever resends a non-empty list.+ # getattr, unlike the rest of this block: the drift check below is what turns+ # a backend missing a runtime field into one clear error naming all of them,+ # and reading the attribute here would pre-empt it with a bare AttributeError.+ # An explicit [] is NOT None here. A rollback resends this field only when it+ # has one, and omitting it is what makes /load inherit, so a model that was+ # running with no extras would come back carrying the arguments of the load+ # that just failed. None stays for "nothing was ever set", which is the only+ # case where inheriting is the right answer.+ requested_llama_extra_args = (+ None+ if llama_backend.is_diffusion+ else (+ None+ if getattr(llama_backend, "requested_extra_args", None) is None+ else list(llama_backend.requested_extra_args)+ )+ ),)unresolved = (set(_InferenceRuntimeFields.model_fields) - fields.keys() - {"requires_trust_remote_code"}@@ -5687,23 +5711,15 @@ async def _maybe_auto_switch_model(# cached repo has no path entry and resolves on the second try; an# early build keyed a loose .gguf by its filename label, so# "<path>:LABEL" is read too, after the bare path used today.- file_variant = None- if not variant and target_id.lower().endswith(".gguf"):- from hub.utils.gguf import extract_quant_label- file_variant = extract_quant_label(os.path.basename(target_id))- override = {}- for override_key in (- f"{target_id}:{variant}" if variant else None,- f"{override_id}:{variant}" if variant else None,- target_id,- f"{target_id}:{file_variant}" if file_variant else None,- override_id,- ):- if not override_key:- continue- override = get_model_override(override_key)- if override:- break+ from utils.openai_auto_switch_settings import (+ resolve_override_for_load,+ )++ # The candidate order above, kept in one place so the panel+ # showing a user what a load will apply reads the same row.+ _override_key, override = resolve_override_for_load(+ target_id, override_id, variant+ )load_kwargs = {"model_path": target_id, "gguf_variant": variant}load_kwargs.update(model_override_load_kwargs(@@ -6660,6 +6676,121 @@ def _gguf_layer_count(config: ModelConfig) -> Optional[int]:return None+def _local_gguf_main_path(config: ModelConfig) -> Optional[str]:+ """The main GGUF on this disk for a config, or None while it is not downloaded.++ The header answers questions the load would otherwise only answer by failing+ (diffusion, embedding), but only once the file is here: a repo that has not been+ fetched yet has nothing to read, and the callers all fall back to what they did+ before rather than reaching for the network on a request path.+ """+ main = getattr(config, "gguf_file", None)+ if main and Path(main).is_file():+ return str(main)+ repo = getattr(config, "gguf_hf_repo", None)+ variant = getattr(config, "gguf_variant", None)+ if repo and variant:+ from hub.utils.gguf import resolve_local_gguf_path+ main = resolve_local_gguf_path(repo, variant)+ if main and Path(main).is_file():+ return str(main)+ return None+++def _is_embedding_gguf(config: ModelConfig) -> bool:+ """Whether this GGUF's pooling type makes llama-server launch with --embedding.++ False whenever the header cannot be read, which keeps every caller doing what it+ did before the check existed: this only ever relaxes a refusal, and relaxing one+ on a guess is how a load reaches the abort the refusal exists to prevent.+ """+ try:+ main = _local_gguf_main_path(config)+ if not main:+ return False+ probe = LlamaCppBackend()+ probe._read_gguf_metadata(main)+ return bool(probe.is_embedding_gguf)+ except Exception as exc:+ logger.debug("Could not identify embedding GGUF for the batch floor: %s", exc)+ return False+++def _embedding_clamped_slots(+ config: ModelConfig,+ slots: int,+ *,+ extra_args: Optional[list[str]],+ n_batch: Optional[int],+ n_ubatch: Optional[int],+ n_ctx: Optional[int],+) -> int:+ """Slots an embedding GGUF really serves, after the micro-batch clamp on load.++ --embedding makes llama-server cap the batch at the micro-batch, and it aborts+ when that is below the slot count, so load_model reduces the slots to it before+ launching. The batch floor has to be judged against the reduced count or this+ refuses a command the launcher would run: four slots with "-ub 2" and a+ pass-through "--batch-size 2" launches at two slots, where two is the floor.++ Only ever returns a count at or below the one asked for, and returns that one+ unchanged for anything but a positively classified embedding GGUF.+ """+ if slots <= 1:+ return max(1, slots)+ if not _is_embedding_gguf(config):+ return slots+ from core.inference.llama_cpp import _emitted_n_batch, _extra_args_n_ubatch++ effective_ubatch = _extra_args_n_ubatch(+ extra_args,+ n_ctx = n_ctx if n_ctx and n_ctx > 0 else None,+ n_batch = _emitted_n_batch(n_batch, slots),+ n_ubatch = n_ubatch,+ )+ if effective_ubatch is None or effective_ubatch >= slots:+ return slots+ # max(): a degenerate "-b 0" resolves to 0, and --parallel 0 is rejected at arg+ # parse, which is the same floor load_model applies.+ return max(1, effective_ubatch) # allow-slot-clamp: mirrors the load_model clamp+++async def _batch_floor_survives_embedding_clamp(+ config: ModelConfig,+ extra_args: Optional[list[str]],+ requested_slots: int,+ request,+ *,+ diffusion_kind: Optional[bool] = None,+) -> bool:+ """Whether a batch the floor just refused is legal once the clamps are applied.++ Both routes check the floor against the slots the launch serves, and for an+ embedding GGUF that is smaller again than the kv-unified count: llama-server+ caps the batch at the micro-batch under --embedding and aborts when that is+ below the slots, so load_model reduces them first. Asked only after a refusal,+ so the header read is paid on the way to a 400 rather than on every load.+ """+ from core.inference.llama_server_args import check_batch_floor++ # Off the event loop: the classification reads the GGUF header from disk, and+ # both routes reach this from an async handler serving download progress polls.+ slots = await asyncio.to_thread(+ _embedding_clamped_slots,+ config,+ _effective_parallel_slots(requested_slots, diffusion_kind = diffusion_kind),+ extra_args = extra_args,+ n_batch = getattr(request, "n_batch", None),+ n_ubatch = getattr(request, "n_ubatch", None),+ n_ctx = getattr(request, "max_seq_length", None),+ )+ try:+ check_batch_floor(extra_args, slots)+ except ValueError:+ return False+ return True++def _classify_diffusion_gguf(config: ModelConfig) -> Optional[bool]:"""Classify a GGUF as diffusion, normal, or unknown before loading."""identity = " ".join(@@ -6669,16 +6800,10 @@ def _classify_diffusion_gguf(config: ModelConfig) -> Optional[bool]:name_says_diffusion = "diffusiongemma" in _re.sub(r"[^a-z0-9]+", "", identity)try:- main = getattr(config, "gguf_file", None)- if not (main and Path(main).is_file()):- repo = getattr(config, "gguf_hf_repo", None)- variant = getattr(config, "gguf_variant", None)- if repo and variant:- from hub.utils.gguf import resolve_local_gguf_path- main = resolve_local_gguf_path(repo, variant)- if main and Path(main).is_file():+ main = _local_gguf_main_path(config)+ if main:probe = LlamaCppBackend()- probe._read_gguf_metadata(str(main))+ probe._read_gguf_metadata(main)if probe.is_diffusion:return Trueif getattr(probe, "_architecture", None):@@ -6867,6 +6992,12 @@ class _LoadPlacement(NamedTuple):diffusion_kind: Optional[bool]+class _NoParallelRequest:+ """A stand-in for a load that named no slot count, for reading the default."""++ n_parallel = None++def _resolve_parallel_slots(request, fastapi_request: Optional[Request]) -> int:if request.n_parallel is not None:return request.n_parallel@@ -6874,6 +7005,30 @@ def _resolve_parallel_slots(request, fastapi_request: Optional[Request]) -> int:return getattr(state, "llama_parallel_slots", 1)+def _effective_parallel_slots(n_parallel: int, *, diffusion_kind: Optional[bool] = None) -> int:+ """Slots the launch will actually serve, after the clamps load_model applies.++ A build without --kv-unified splits the context window per slot, so load_model+ falls back to one; the diffusion runner receives no --parallel at all. Anything+ sized or refused against the asked-for count instead of this one is judging a+ command that will not launch: the batch floor in particular would refuse+ "--batch-size 2" against a four-slot default on a build that serves one.+ """+ if n_parallel <= 1:+ return max(1, n_parallel)+ if diffusion_kind is True:+ return 1 # allow-slot-clamp: diffusion never receives --parallel+ try:+ caps = LlamaCppBackend.probe_server_capabilities()+ if caps.get("found") and not caps.get("supports_kv_unified"):+ return 1 # allow-slot-clamp: mirrors the load_model clamp+ except Exception as exc:+ # Unreadable capabilities are not a reason to refuse anything: keep the ask,+ # which is what every other caller of the probe here does.+ logger.warning("Could not probe llama-server slots: %s", exc)+ return n_parallel++async def _prepare_load_placement(config: ModelConfig,request: LoadRequest | ValidateModelRequest,@@ -7312,16 +7467,15 @@ def _resolve_inherited_extra_args(strip_batch = "n_batch" in fields_set,strip_ubatch = "n_ubatch" in fields_set,)- try:- extra_llama_args = validate_extra_args(stripped)- except ValueError:- # Shouldn't happen on already-validated args; degrade to- # no-extras rather than 400 if managed flags changed.+ # Inherited, not sent: a flag denylisted since it was stored loses only+ # itself. The previous behaviour dropped the whole list, so one name added+ # to the denylist silently took every other flag with it.+ extra_llama_args, _dropped = drop_managed_flags(stripped)+ if _dropped:logger.warning(- "Stored llama_extra_args failed revalidation; loading without them: %s",- stripped,+ "Stored llama_extra_args are no longer allowed; dropped %s",+ ", ".join(_dropped),)- extra_llama_args = []else:if extra_llama_args:logger.info(@@ -8152,6 +8306,47 @@ async def _load_model_impl(# Invalid GPU IDs must fail before the training coexistence guard.placement = await _prepare_load_placement(config, request, extra_llama_args)+ if placement.diffusion_kind is True and extra_llama_args:+ # The visual runner builds its own command and appends none of these, so+ # keeping them would record a load as running arguments the process never+ # received, and the panel would then show and remember them. This is the+ # authoritative classification: the caller only had staged metadata, which+ # can be inconclusive for a GGUF it has not finished downloading.+ logger.info(+ "Dropping %d extra llama-server arg(s) for %s: the diffusion runner takes none.",+ len(extra_llama_args),+ model_log_label,+ )+ extra_llama_args = []+ if config.is_gguf and extra_llama_args:+ # After the slot count is known, because the floor depends on it. The+ # editor draws the same line, but a CLI or API caller never sees it, and+ # this is the one class of pass-through value that takes the server down+ # during startup rather than being ignored: a 400 here beats a load that+ # has already unloaded the previous model.+ from core.inference.llama_server_args import check_batch_floor+ try:+ check_batch_floor(+ extra_llama_args,+ # The count that will launch, not the one asked for: a build+ # without --kv-unified serves one slot however many were+ # requested, and refusing a batch of 2 against it is a 400 on a+ # command that would have run.+ _effective_parallel_slots(_n_parallel, diffusion_kind = placement.diffusion_kind),+ )+ except ValueError as exc:+ # An embedding GGUF comes down further still: --embedding caps the+ # batch at the micro-batch, so load_model reduces the slots to it+ # before launching. Read only now, because it costs a header read+ # and it can only ever turn a refusal into an acceptance.+ if not await _batch_floor_survives_embedding_clamp(+ config,+ extra_llama_args,+ _n_parallel,+ request,+ diffusion_kind = placement.diffusion_kind,+ ):+ raise HTTPException(status_code = 400, detail = str(exc)) from excgguf_intent: Optional[GgufLoadIntent] = None_tensor_intent_overall = Falseif config.is_gguf:@@ -8871,13 +9066,101 @@ async def validate_model(detail = f"Invalid model identifier: {model_log_label}",)+ # The caller's own list when it sent one, or the resolver hands back this+ # fourth argument unchanged and a --ctx-size the load is about to use would+ # be missing from the estimate that approves it.effective_extra_args = _resolve_inherited_extra_args(- request, config, model_identifier, None- )+ request, config, model_identifier, getattr(request, "llama_extra_args", None)+ )++ # The caller's list is judged BEFORE anything rewrites it, exactly as /load+ # judges the explicit list it was sent. Translating first let a list /load+ # refuses pass here: "--gpu-layers=20" was parsed into the first-class field+ # and stripped, so validate_extra_args never saw the attached spelling+ # llama.cpp has no such flag for, and the switch was approved for a load that+ # answers 400. A malformed value ("-ngl bad") raised out of the parser here+ # too, which is a 500 where the same list is a 400 on the load.+ if config.is_gguf and effective_extra_args:+ from core.inference.llama_server_args import validate_extra_args+ try:+ validate_extra_args(effective_extra_args)+ except ValueError as exc:+ raise HTTPException(status_code = 400, detail = str(exc)) from exc++ # Manual mode owns the offload flags, and /load translates an explicit -ngl+ # into the first-class field before it strips them. Doing that there and not+ # here made the two disagree about what will actually run: a diffusion GGUF+ # asked with gpu_layers 0 and "-ngl 20" was approved as a zero-layer load that+ # cannot compete with training for VRAM, and then launched twenty layers on+ # the GPU; the opposite pairing refused a load that only ever runs on the CPU.+ # Same translation, same strip, so the guard below judges the same command.+ # After the validation above, so nothing here parses a token the load refuses.+ if getattr(request, "gpu_memory_mode", None) == "manual" and effective_extra_args:+ from core.inference.llama_server_args import (+ parse_gpu_layers_override,+ strip_shadowing_flags,+ )++ _validate_ngl_override = parse_gpu_layers_override(effective_extra_args)+ if _validate_ngl_override is not None:+ request = request.model_copy(update = {"gpu_layers": _validate_ngl_override})+ effective_extra_args = strip_shadowing_flags(+ effective_extra_args,+ strip_context = False,+ strip_cache = False,+ strip_spec = False,+ strip_template = False,+ strip_split_mode = False,+ strip_tensor_split = _should_strip_tensor_split(request),+ strip_offload = True,+ )# Apply the same placement policy as /load before the frontend unloads# the current model.placement = await _prepare_load_placement(config, request, effective_extra_args)+ if placement.diffusion_kind is True and effective_extra_args:+ # Same drop as /load, and for the same reason: the diffusion runner appends+ # none of these, so an estimate that reads a --ctx-size out of them approves+ # a load against a command that will never carry it. The classification here+ # is the authoritative one, so this can only be decided after placement.+ logger.info(+ "Ignoring %d extra llama-server arg(s) for %s: the diffusion runner takes none.",+ len(effective_extra_args),+ model_log_label,+ )+ effective_extra_args = []+ if config.is_gguf and effective_extra_args:+ # The same two checks /load runs, here because the picker treats a+ # successful validate as permission to unload the model it is replacing.+ # Without them a remembered list that this build no longer accepts (a+ # flag denied since it was saved, a batch below the slot floor) passed+ # the preflight, the running model went away, and /load then answered+ # 400: a failed switch and a rollback instead of a refusal with nothing+ # disturbed.+ # Only the floor here: the list itself was judged above, before the manual+ # translation could rewrite it, and re-validating the STRIPPED list would+ # answer for a command neither route sends.+ from core.inference.llama_server_args import check_batch_floor+ _requested_slots = _resolve_parallel_slots(request, fastapi_request)+ try:+ check_batch_floor(+ effective_extra_args,+ _effective_parallel_slots(+ _requested_slots,+ diffusion_kind = placement.diffusion_kind,+ ),+ )+ except ValueError as exc:+ # The same embedding clamp /load allows for, or this preflight+ # refuses a command the load it gates would have launched.+ if not await _batch_floor_survives_embedding_clamp(+ config,+ effective_extra_args,+ _requested_slots,+ request,+ diffusion_kind = placement.diffusion_kind,+ ):+ raise HTTPException(status_code = 400, detail = str(exc)) from exceffective_load_in_4bit = _effective_load_in_4bit(config, request.load_in_4bit)# Both checks cover the [adapter, base] set (matching the scan route and workers):@@ -10038,6 +10321,124 @@ def _probe_llama_cpp_status(llama_backend) -> tuple[bool, dict]:return supports_mtp, freshness+def _parallel_slots_are_clamped() -> bool:+ """Whether this build serves one slot whatever is asked for.++ The published default is already effective, but an explicit Slots value is chosen+ in the editor and never passes through here, so the editor cannot apply the clamp+ without being told it exists: Slots 4 with "--batch-size 2" was refused there while+ the backend, which clamps to one, accepts exactly that command. Asked of the same+ helper the load uses, with a count above one, so the two can never drift.+ """+ return _effective_parallel_slots(2) == 1+++async def _effective_default_slots(fastapi_request) -> tuple[int, bool]:+ """The default slot count a load would really serve, without blocking the loop.++ _effective_parallel_slots asks the binary whether it supports --kv-unified, and on+ a cold cache that is `llama-server --help` with a ten second timeout. Called inline+ it stalled every other request on the first open of the panel after an update, and+ on the managed-only answer too, which is the one path that exists to avoid waiting+ for a probe. The settings read stays here: it is a row in SQLite, and a single slot+ needs no probe to know it cannot be clamped below one.+ """+ requested = _resolve_parallel_slots(_NoParallelRequest(), fastapi_request)+ if requested <= 1:+ # One slot cannot be clamped below one, but whether this build clamps is still+ # the editor's question: it sizes an EXPLICIT Slots value the user may raise+ # without ever re-reading this route.+ return requested, await asyncio.to_thread(_parallel_slots_are_clamped)+ effective = await asyncio.to_thread(_effective_parallel_slots, requested)+ return effective, effective == 1++[email protected]("/llama-flags", response_model = LlamaFlagCatalogResponse)+async def get_llama_flags(+ fastapi_request: Request = None,+ managed_only: bool = False,+ current_subject: str = Depends(get_current_subject),+):+ """Flags the installed llama-server accepts, for the extra-arguments editor.++ Cheap to call: ``probe_server_capabilities`` caches on the binary's revision, so+ only the first call after an install or an update runs the 10s ``--help`` probe.+ A failed probe answers ``probe_ok = false`` with no flags rather than erroring, so+ the editor degrades to "cannot verify" instead of blocking every argument.++ ``managed_only`` skips the probe entirely. The denylist is Unsloth's own and needs+ no binary to read, while the caller that needs it most is the panel sanitizing a+ stored list before it becomes an explicit request: making that wait on a cold+ ``--help`` would leave a legacy flag in the request for as long as the probe runs.+ """+ from core.inference.llama_server_args import (+ WINDOWS_COMMAND_LIMIT,+ WINDOWS_COMMAND_RESERVE,+ max_extra_args_bytes,+ sorted_managed_flags,+ )++ _default_slots, _slots_clamped = await _effective_default_slots(fastapi_request)+ # What this host refuses on size, so an editor draws the same line rather than+ # letting a 25 KiB grammar through to a 400.+ limits = {+ "max_bytes": max_extra_args_bytes(),+ "windows_command_budget": (+ WINDOWS_COMMAND_LIMIT - WINDOWS_COMMAND_RESERVE if sys.platform == "win32" else 0+ ),+ # The slot count a load gets when it names none, read the same way the loader+ # reads it. An editor cannot see this number, and llama-server aborts on a+ # batch below the slots it serves, so without it a pass-through -b 2 looks+ # fine here and takes down a launch that runs four slots.+ # The effective count, after the clamps the launch applies: a build without+ # --kv-unified serves one slot however many are configured, and an editor+ # sizing its batch floor from the raw default would refuse a batch that runs.+ "default_parallel_slots": _default_slots,+ "parallel_slots_clamped": _slots_clamped,+ }++ if managed_only:+ return LlamaFlagCatalogResponse(+ flags = {},+ managed = sorted_managed_flags(),+ # No probe was attempted, so nothing here can say a flag is a typo.+ probe_ok = False,+ **limits,+ )+ try:+ backend = get_llama_cpp_backend()+ # Off the event loop: on a cold cache this runs `llama-server --help` with a+ # 10s timeout, and the startup probes were moved to a thread for exactly that+ # reason (test_startup_llama_probe_non_blocking). Awaiting it inline would+ # stall every other request on the first open of the panel after an update.+ capabilities = await asyncio.to_thread(type(backend).probe_server_capabilities)+ flags = capabilities.get("flags") or {}+ switch_flags = list(capabilities.get("switch_flags") or ())+ # Three ways to be unverifiable, and the editor treats them alike: no binary+ # (found=False), a --help that did not parse (empty catalogue), and a --help+ # that exited nonzero after printing part of itself. The last one is why the+ # probe's own result is read rather than inferred from a non-empty map: a+ # partial catalogue would otherwise be published as the whole truth, and+ # every flag past the failure point called a typo.+ probe_ok = (+ bool(capabilities.get("found"))+ and bool(flags)+ and bool(capabilities.get("help_probe_ok", True))+ )+ except Exception as exc: # noqa: BLE001 -- an unverifiable flag is not a failed request+ logger.debug(f"llama-server flag catalogue unavailable: {exc}")+ flags = {}+ switch_flags = []+ probe_ok = False+ return LlamaFlagCatalogResponse(+ flags = {str(k): str(v) for k, v in flags.items()},+ managed = sorted_managed_flags(),+ switch_flags = [str(flag) for flag in switch_flags],+ probe_ok = probe_ok,+ **limits,+ )++@router.get("/status", response_model = InferenceStatusResponse)async def get_status(current_subject: str = Depends(get_current_subject)):"""diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex e7cf1c65958..a06de770fd2 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -739,6 +739,12 @@ class ModelOverridePayload(BaseModel):class ModelOverridesResponse(BaseModel):overrides: dict[str, dict]+ # Filled only when the caller named a model: the entry ITS load would apply,+ # resolved here rather than in the browser. The folding rules are Python's+ # (casefold is not toLowerCase, and an ambiguous fold matches nothing on+ # purpose), so a client mirroring them can only approximate.+ resolved: Optional[dict] = None+ resolved_key: Optional[str] = Nonedef _upload_limit_response(limit_mb: int) -> UploadLimitResponse:@@ -1072,9 +1078,26 @@ def update_openai_auto_switch(@router.get("/openai-auto-switch/overrides", response_model = ModelOverridesResponse)def get_openai_auto_switch_overrides(+ model_id: Optional[str] = None,+ alias_id: Optional[str] = None,+ gguf_variant: Optional[str] = None,current_subject: str = Depends(get_current_subject),) -> ModelOverridesResponse:- return ModelOverridesResponse(overrides = get_model_overrides())+ """Every stored override, and optionally the one a named model's load would use.++ The resolution is the loader's own (``resolve_override_for_load``), so what a+ panel shows and what a load applies cannot disagree.+ """+ resolved_key: Optional[str] = None+ resolved: Optional[dict] = None+ if model_id:+ from utils.openai_auto_switch_settings import resolve_override_for_load+ resolved_key, resolved = resolve_override_for_load(model_id, alias_id, gguf_variant)+ return ModelOverridesResponse(+ overrides = get_model_overrides(),+ resolved = resolved,+ resolved_key = resolved_key,+ )def _bare_model_id(model_id: str) -> Optional[str]:@@ -1086,6 +1109,35 @@ def _bare_model_id(model_id: str) -> Optional[str]:return split[0] if split is not None else None+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.+ """+ from utils.openai_auto_switch_settings import get_model_override++ for candidate in (+ _bare_model_id(model_id),+ _legacy_standalone_gguf_key(model_id),+ ):+ if (+ candidate+ and candidate != target_id+ and get_model_override(candidate).get("llama_extra_args")+ ):+ return True+ return False++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.@@ -1194,7 +1246,7 @@ def _serialized_override_write(func):def update_openai_auto_switch_override(payload: ModelOverridePayload, current_subject: str = Depends(get_current_subject)) -> ModelOverridesResponse:- from core.inference.llama_server_args import validate_extra_args+ from core.inference.llama_server_args import drop_managed_flags, validate_extra_argsfrom utils.openai_auto_switch_settings import get_model_overridetry:@@ -1241,7 +1293,22 @@ def update_openai_auto_switch_override(if requested_extra_args is not None:break# Not validated on an explicit remove: a 400 would only leave the override in place.- extra_args = [] if payload.remove is True else validate_extra_args(requested_extra_args)+ if payload.remove is True:+ extra_args = []+ elif payload.llama_extra_args is None:+ # Carried over, not sent: the caller is saving some other field and this+ # value predates the request. A flag denylisted since it was written is+ # dropped rather than refused, or an unrelated save fails naming a flag+ # the user may not remember writing (and cannot fix from this payload).+ extra_args, dropped_flags = drop_managed_flags(requested_extra_args)+ if dropped_flags:+ logger.warning(+ "model_override.dropped_managed_flags model_id=%s flags=%s",+ payload.model_id,+ ", ".join(dropped_flags),+ )+ else:+ extra_args = validate_extra_args(requested_extra_args)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:@@ -1292,9 +1359,19 @@ 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 is touched.+ keep_empty = (+ payload.llama_extra_args == []+ and not payload.fill_absent_fields+ and _fallback_supplies_extra_args(payload.model_id, target_id)+ )set_model_override(target_id,llama_extra_args = extra_args,+ keep_empty_extra_args = keep_empty,max_seq_length = payload.max_seq_length,custom_context_length = payload.custom_context_length,kv_cache_dtype = payload.kv_cache_dtype,diff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.pyindex 193aaea66eb..bce7e496d67 100644--- a/studio/backend/tests/test_gguf_load_cache_reuse.py+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py@@ -834,6 +834,9 @@ class TestLoadHubDownloadExclusion:"mlx_kv_quant_reason","mlx_kv_quant_note","chat_template_override_reason",+ # Read from requested_extra_args, which is what the load was invoked+ # with rather than the rewritten launch list.+ "requested_llama_extra_args",}unresolved = sorted(namediff --git a/studio/backend/tests/test_inference_status_loaded_gguf.py b/studio/backend/tests/test_inference_status_loaded_gguf.pyindex e1064348fe2..5d3d58456d8 100644--- a/studio/backend/tests/test_inference_status_loaded_gguf.py+++ b/studio/backend/tests/test_inference_status_loaded_gguf.py@@ -169,3 +169,36 @@ def test_an_auto_applied_chat_template_is_not_reported_as_the_users(status_routebackend = _StatusBackend("org/A-GGUF")backend.chat_template_override = "bundled-template"assert status_route(backend).chat_template_override is None+++def test_status_publishes_the_running_pass_through_arguments(status_route):+ # A tab opened while a model is already running never saw the load, so the only+ # place it can learn what the server was invoked with is here. Without it, a+ # rollback after a failed switch restores the previous model without them, and+ # the omitted field cannot inherit either: the failed target is left resident,+ # and the route refuses to carry arguments across models.+ backend = _StatusBackend("org/A-GGUF")+ backend.requested_extra_args = ["--numa", "distribute"]+ status = status_route(backend)+ assert status.requested_llama_extra_args == ["--numa", "distribute"]+++def test_an_explicit_empty_list_is_not_a_missing_one(status_route):+ # A rollback resends this field only when it has one, and omitting it is what+ # makes /load inherit. A model that was running with no extras must come back+ # with none, not with the arguments of the load that just failed.+ backend = _StatusBackend("org/A-GGUF")+ backend.requested_extra_args = []+ assert status_route(backend).requested_llama_extra_args == []+ # None is the one case where nothing was ever set, and inheriting is right.+ backend.requested_extra_args = None+ assert status_route(backend).requested_llama_extra_args is None+++def test_the_diffusion_runner_reports_none(status_route):+ # It appends none of them, so publishing a list would describe a command that+ # does not exist.+ backend = _StatusBackend("org/A-GGUF")+ backend.is_diffusion = True+ backend.requested_extra_args = ["--numa", "distribute"]+ assert status_route(backend).requested_llama_extra_args is Nonediff --git a/studio/backend/tests/test_llama_cpp_start_failure_classification.py b/studio/backend/tests/test_llama_cpp_start_failure_classification.pyindex 625ea642e52..11cbfb4f0cc 100644--- a/studio/backend/tests/test_llama_cpp_start_failure_classification.py+++ b/studio/backend/tests/test_llama_cpp_start_failure_classification.py@@ -148,9 +148,7 @@ class TestUnsupportedNonDiffusionArchitecture:class TestOllamaAndFallback:- _OLLAMA_GGUF = (- f"/home/u/.ollama{__import__('os').sep}ollama_links" f"{__import__('os').sep}m.gguf"- )+ _OLLAMA_GGUF = f"/home/u/.ollama{__import__('os').sep}ollama_links{__import__('os').sep}m.gguf"def test_ollama_compat_message_still_works(self):out = "llama_model_load: error loading model: key not found"@@ -284,8 +282,7 @@ class TestMissingSharedLibrary:# write_exec_wrapper's entrypoint: /bin/sh reports a missing exec# target as "not found" and exits 127.out = (- "/home/t/.unsloth/llama.cpp/llama-server: 2: exec: "- "./build/bin/llama-server: not found"+ "/home/t/.unsloth/llama.cpp/llama-server: 2: exec: ./build/bin/llama-server: not found")msg = _classify(out, "/models/x.gguf", "local/x", 127)assert "package manager" not in msg@@ -821,13 +818,34 @@ class TestDiagnosticsDoNotLeak:def test_a_huge_unterminated_line_is_cheap(self):# _drain_stdout keeps an unterminated line whole; the tail must be# sliced before it is filtered character by character.+ #+ # Proven by BEHAVIOUR rather than by a stopwatch. The bound is observable: an+ # argument error further back than the tail cannot be reported unless+ # something read it. A wall-clock budget tests the same property by proxy and+ # measures the runner instead, which is why this exact assertion goes red on+ # the Windows runner for main as well as for a branch. The stopwatch stays+ # only as a catastrophic guard, loose enough that no runner can trip it.import time- out = "x" * 10_000_000 + "\nggml_metal_init: error"+ buried = "error: invalid argument: --nope\n" + "x" * 10_000_000 + "\nggml_metal_init: error"start = time.perf_counter()- msg = _classify(out, "/models/x.gguf", "local/x", 1)- assert time.perf_counter() - start < 0.2+ msg = _classify(buried, "/models/x.gguf", "local/x", 1)+ elapsed = time.perf_counter() - start++ # 10 MB back, so out of the scanned tail: reporting it would mean the whole+ # capture was walked.+ assert "--nope" not in msg+ # And what IS in the tail still surfaces.assert "ggml_metal_init: error" in msg+ assert elapsed < 5, f"{elapsed:.1f}s to classify one 10 MB line"++ def test_an_argument_error_inside_the_tail_is_still_reported(self):+ # The other half of the bound: near the end is where llama-server actually+ # prints it, immediately before exiting.+ out = "x" * 10_000_000 + "\nerror: invalid argument: --nope"+ msg = _classify(out, "/models/x.gguf", "local/x", 1)++ assert "--nope" in msgclass TestDyldInstallNames:@@ -1255,6 +1273,10 @@ class TestAnEncodedSecretIsStillRedacted:"A=1," * 25000,'TOKEN="' + "y" * 100000,],+ # Named, because pytest puts the whole parameter in the node id and then in+ # PYTEST_CURRENT_TEST. Windows caps an environment variable at 32767+ # characters, so a 100 KB id errors the test in setup on that OS alone.+ ids = ["escaped-quotes", "long-value", "many-pairs", "unterminated-quote"],)def test_the_name_pass_stays_linear(self, blob):"""No nested quantifier: a crafted line must not be able to stall it."""@@ -1477,6 +1499,9 @@ class TestTheRedactionHolesCodexFound:@pytest.mark.parametrize("blob",['TOKEN="' + "y" * 100000, "a.b.c.d=" * 12000, "A=1," * 25000],+ # Same reason as above: the parameter is the node id, and the node id+ # becomes an environment variable.+ ids = ["unterminated-quote", "dotted-names", "many-pairs"],)def test_the_widened_pattern_stays_linear(self, blob):import time@@ -1484,3 +1509,163 @@ class TestTheRedactionHolesCodexFound:start = time.monotonic()LlamaCppBackend._scrub_secret_values(blob, ())assert time.monotonic() - start < 2.0+++class TestRejectedArguments:+ """Argument parsing runs before the model is touched, so these are never a+ bad GGUF or an OOM. The strings are what the bundled llama-server actually+ prints, captured from it directly rather than written from memory."""++ def test_an_unknown_flag_is_named(self):+ msg = _classify("error: invalid argument: --tempp", "/models/x.gguf", "local/x", 1)+ assert "--tempp" in msg+ assert "extra arguments" in msg+ # The generic diagnosis must not survive: the file and the memory are fine.+ assert "memory" not in msg.lower()++ def test_a_flag_unsloth_set_itself_is_covered_by_the_same_message(self):+ # Nothing reaching the classifier says whose flag it was, and Unsloth emits+ # its own conditionally on the capability probe, so a binary swapped under a+ # cached probe lands here too. The message has to serve that reader as well+ # as the one who mistyped something in the box.+ msg = _classify("error: invalid argument: --flash-attn", "/models/x.gguf", "local/x", 1)+ assert "--flash-attn" in msg+ assert "reinstall llama.cpp" in msg++ def test_a_rejected_value_is_told_apart_from_an_unknown_flag(self):+ # Different fix for the reader: the flag is right, the value is not.+ msg = _classify(+ 'error while handling argument "--numa": invalid value',+ "/models/x.gguf",+ "local/x",+ 1,+ )+ assert "--numa" in msg+ assert "invalid value" in msg+ assert "does not recognise" not in msg++ def test_a_missing_value_keeps_llama_cpps_own_reason(self):+ msg = _classify(+ 'error while handling argument "--top-k": expected value for argument',+ "/models/x.gguf",+ "local/x",+ 1,+ )+ assert "--top-k" in msg+ assert "expected value" in msg++ def test_a_std_stoi_failure_is_translated(self):+ # llama.cpp surfaces the C++ standard library's exception name verbatim.+ # "stoi" is not an error message anyone outside libstdc++ can act on.+ msg = _classify(+ 'error while handling argument "--top-k": stoi', "/models/x.gguf", "local/x", 1+ )+ assert "not a number" in msg+ assert "stoi" not in msg++ def test_a_value_error_on_a_flag_the_user_did_not_set_stays_neutral(self):+ # Studio emits its own options conditionally on the capability probe, so a+ # build that reads "--flash-attn on" differently rejects a value the box+ # never held. Sending that reader to edit their extra arguments points them+ # at a setting they cannot use to fix it.+ msg = _classify(+ 'error while handling argument "--flash-attn": invalid value',+ "/models/x.gguf",+ "local/x",+ 1,+ )+ assert "--flash-attn" in msg+ assert "reinstall llama.cpp" in msg++ def test_a_value_error_on_a_flag_the_user_did_set_names_the_box(self):+ # Ownership established: the extras really do carry the flag, so the box is+ # where the fix is.+ msg = LlamaCppBackend._classify_llama_start_failure(+ 'error while handling argument "--numa": invalid value',+ "/models/x.gguf",+ "local/x",+ 1,+ None,+ None,+ (),+ ["--numa", "wherever"],+ )+ assert "--numa" in msg+ assert "Fix it in the extra arguments" in msg+ assert "reinstall" not in msg++ def test_an_alias_spelling_falls_back_to_the_neutral_wording(self):+ # -fa and --flash-attn are the same option to llama.cpp but not to this+ # comparison, and a wrong "you set this" is worse than a neutral one.+ msg = LlamaCppBackend._classify_llama_start_failure(+ 'error while handling argument "--flash-attn": invalid value',+ "/models/x.gguf",+ "local/x",+ 1,+ None,+ None,+ (),+ ["-fa", "on"],+ )+ assert "reinstall llama.cpp" in msg++ def test_an_ordinary_failure_is_untouched(self):+ # The two new branches sit ahead of the generic diagnosis, so this pins+ # that they do not swallow it.+ msg = _classify(_OOM_OUT, "/models/big.gguf", "local/big", 1)+ assert "enough memory" in msg.lower()+ assert "argument" not in msg.lower()++ def test_the_argument_scan_reads_only_the_tail(self):+ # The bound exists because _drain_stdout keeps an unterminated line whole,+ # and scanning a 10 MB one twice puts the classifier past any sane budget.+ # Asserted by BEHAVIOUR rather than by the clock: a wall-clock budget on a+ # shared CI runner measures the runner, and a Windows one failed this at+ # 204ms against 200 while the bound it was meant to prove was in place.+ from core.inference.llama_cpp import _FAILURE_SCAN_TAIL_CHARS++ # Inside the tail: found, and the whole capture is enormous either way.+ within = "x" * 10_000_000 + "\nerror: invalid argument: --tempp"+ assert "--tempp" in _classify(within, "/models/x.gguf", "local/x", 1)+ # Before it: not found, which is only possible if the scan stopped short of+ # the head. Reported as an ordinary failure instead.+ buried = "error: invalid argument: --tempp\n" + "x" * (_FAILURE_SCAN_TAIL_CHARS * 2)+ assert "--tempp" not in _classify(buried, "/models/x.gguf", "local/x", 1)++ def test_a_model_load_error_mentioning_arguments_is_not_misread(self):+ # "invalid argument" as an errno string (EINVAL) is not llama.cpp's+ # argument parser, and the anchored "error: invalid argument:" prefix is+ # what keeps them apart.+ out = "llama_model_load: error loading model: invalid argument (22)"+ msg = _classify(out, "/models/x.gguf", "local/x", 1)+ assert "does not recognise" not in msg+++class TestArgumentErrorsAreQuotedShort:+ """What a failed start copies out of the child's own output."""++ def test_a_pathological_argument_is_truncated(self):+ # A wrapper on LLAMA_SERVER_PATH can print anything, and the capture is a run+ # of non-whitespace, so without a bound the API error becomes 64 KiB of it.+ out = "error: invalid argument: " + "x" * 50_000+ msg = _classify(out, "/models/x.gguf", "local/x", 1)++ assert len(msg) < 1_000, len(msg)+ assert "..." in msg+ # Still says what happened, and still names the beginning of the argument.+ assert "does not recognise the argument" in msg+ assert "xxxx" in msg++ def test_a_pathological_reason_is_truncated(self):+ out = 'error while handling argument "--top-k": ' + "y" * 50_000+ msg = _classify(out, "/models/x.gguf", "local/x", 1)++ assert len(msg) < 1_000, len(msg)+ assert "--top-k" in msg++ def test_an_ordinary_argument_error_is_untouched(self):+ out = "error: invalid argument: --tempp"+ msg = _classify(out, "/models/x.gguf", "local/x", 1)++ assert "--tempp" in msg+ assert "..." not in msgdiff --git a/studio/backend/tests/test_llama_extra_args_compatibility.py b/studio/backend/tests/test_llama_extra_args_compatibility.pynew file mode 100644index 00000000000..a0d13b89d37--- /dev/null+++ b/studio/backend/tests/test_llama_extra_args_compatibility.py@@ -0,0 +1,529 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What happens to an install that predates this denylist.++Widening ``_DENYLIST_GROUPS`` is the one change here that can act on data already on+disk: an override saved before a flag was denied still holds it. Every path that+reads such an entry is pinned here, because the failure mode is a user who never+typed the flag being unable to load or to save.++The rule the suite encodes: an argument the CALLER just sent is refused loudly (400,+naming the flag), and an argument merely CARRIED OVER from storage is dropped+quietly. The first is a mistake being made now; the second is history.+"""++from __future__ import annotations++import importlib.util+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+_LSA_PATH = _BACKEND / "core" / "inference" / "llama_server_args.py"+_spec = importlib.util.spec_from_file_location("_lsa_compat_test", _LSA_PATH)+_lsa = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_lsa)++# Saved by a build where each of these was still allowed. Not hypothetical: the+# first three appear verbatim in llama-server command lines people copy.+LEGACY_STORED = [+ ["--log-file", "/var/log/llama.log"],+ ["--slot-save-path", "/tmp/slots"],+ ["--media-path", "/srv/media"],+ ["--cors-origins", "*"],+ ["--agent"],+ ["--mcp-servers-json", "{}"],+]++[email protected]("stored", LEGACY_STORED)+def test_a_stored_flag_denied_after_the_fact_is_dropped_not_kept(stored):+ # The validator itself still refuses: it is the boundary, and it has no idea+ # whether its caller is a request or a stored row.+ with pytest.raises(ValueError, match = "managed by Unsloth Studio"):+ _lsa.validate_extra_args(stored)++[email protected]("stored", LEGACY_STORED)+def test_the_drop_helper_keeps_everything_else(stored):+ # What the carry-over paths use instead of a refusal. The user's other flags+ # are not collateral: only the denied names go.+ kept, dropped = _lsa.drop_managed_flags([*stored, "--numa", "distribute"])++ assert kept == ["--numa", "distribute"]+ assert dropped == [_lsa._flag_name(stored[0])]+ # And what survives is loadable, or the drop would have moved the failure+ # rather than removed it.+ assert _lsa.validate_extra_args(kept) == kept+++def test_dropping_takes_the_flags_value_with_it():+ # Leaving "/var/log/llama.log" behind would hand llama.cpp a bare positional,+ # which it reads as the model path.+ kept, dropped = _lsa.drop_managed_flags(+ ["--top-k", "20", "--log-file", "/var/log/llama.log", "--seed", "1"]+ )++ assert kept == ["--top-k", "20", "--seed", "1"]+ assert dropped == ["--log-file"]+++def test_an_attached_value_form_is_dropped_whole():+ # The denied one for its name, the other because llama-server refuses the+ # attached spelling itself. Both self-contained, so neither takes a following+ # token with it.+ kept, dropped = _lsa.drop_managed_flags(["--log-file=/x", "--top-k=20", "--numa", "distribute"])++ assert kept == ["--numa", "distribute"]+ assert dropped == ["--log-file", "--top-k"]+++def test_an_attached_value_in_the_middle_does_not_take_the_rest_with_it():+ # The trimming loop sheds the TAIL, so a stored "--top-k=20" left for it would+ # cost every flag written after it. Dropped in the walk instead, beside the+ # denied names.+ kept, _dropped = _lsa.drop_managed_flags(+ ["--top-k=20", "--numa", "distribute", "--grammar", "root ::= [0-9]"]+ )+ assert kept == ["--numa", "distribute", "--grammar", "root ::= [0-9]"]+++def test_nothing_to_drop_returns_the_list_unchanged():+ args = ["--numa", "distribute", "--top-k", "20"]+ kept, dropped = _lsa.drop_managed_flags(args)++ assert kept == args+ assert dropped == []+++def test_an_empty_or_missing_list_is_handled():+ assert _lsa.drop_managed_flags(None) == ([], [])+ assert _lsa.drop_managed_flags([]) == ([], [])+++def test_a_bound_breaking_stored_list_is_also_dropped_to_something_loadable():+ # The bounds are new too, so a stored list can be over them. A drop that+ # returned an unloadable list would leave the load failing anyway.+ kept, dropped = _lsa.drop_managed_flags(["--verbose"] * (_lsa.MAX_EXTRA_ARG_TOKENS + 10))++ assert _lsa.validate_extra_args(kept) == kept+ assert len(dropped) > 0+++def test_a_poisoned_value_is_never_echoed_into_the_dropped_list():+ # Every caller joins this list into a warning log. A stored value carrying ANSI+ # escapes would then rewrite whatever is reading that log, and the value itself+ # is not the operator's business either: the flag name is what identifies it.+ kept, dropped = _lsa.drop_managed_flags(["--grammar", "\x1b[2Jroot ::= [0-9]", "--top-k", "20"])++ assert kept == ["--top-k", "20"]+ assert dropped == ["--grammar", "<value>"]+ assert not any("\x1b" in name for name in dropped)+++def test_a_control_character_in_a_stored_value_is_dropped_too():+ kept, _ = _lsa.drop_managed_flags(["--chat-template", "a\x00b", "--top-k", "20"])++ assert _lsa.validate_extra_args(kept) == kept+ assert "--top-k" in kept+++# --- the paths that actually carry a stored value over --------------------------+# The helper is only half of it: the two call sites reach it through module globals+# populated by an import list, so a wiring mistake is invisible until a load runs.+++def test_the_inherited_load_path_drops_only_the_denied_flag(monkeypatch):+ import routes.inference as inference_route++ assert hasattr(inference_route, "drop_managed_flags"), (+ "the resolver reads this from module globals; an unlisted import NameErrors "+ "only when a model with stored flags is loaded"+ )++ class _Backend:+ extra_args = ["--log-file", "/var/log/llama.log", "--numa", "distribute"]+ # Same model and variant, or the resolver refuses the pickup before it ever+ # reaches the drop and the test proves nothing.+ extra_args_source = ("local/x", "")++ class _Config:+ is_gguf = True+ gguf_variant = ""++ class _Request:+ llama_extra_args = None+ gguf_variant = ""+ gpu_memory_mode = "auto"+ model_fields_set: set = set()++ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Backend())+ resolved = inference_route._resolve_inherited_extra_args(_Request(), _Config(), "local/x", None)++ # --numa surviving is the point: the previous behaviour returned [] on any+ # refusal, so one name added to the denylist took every other flag with it.+ assert resolved == ["--numa", "distribute"]+++def test_the_override_save_carries_over_without_refusing(monkeypatch):+ # A user changing Context Length on a model whose stored flags predate the+ # denylist must not get a 400 about a flag they are not editing.+ import routes.settings as settings_route++ saved: dict = {}+ stored = {"llama_extra_args": ["--slot-save-path", "/tmp/slots", "--numa", "distribute"]}+ monkeypatch.setattr(+ settings_route, "get_model_override", lambda _id: dict(stored), raising = False+ )+ import utils.openai_auto_switch_settings as oas++ monkeypatch.setattr(oas, "get_model_override", lambda _id: dict(stored))+ monkeypatch.setattr(+ oas,+ "set_model_override",+ lambda model_id, **kwargs: saved.update({model_id: kwargs}),+ )+ monkeypatch.setattr(settings_route, "set_model_override", oas.set_model_override, raising = False)+ monkeypatch.setattr(+ settings_route, "resolve_model_override_keys", lambda _id: ["local/x"], raising = False+ )+ monkeypatch.setattr(settings_route, "cached_repo_alias_keys", lambda _id: [], raising = False)++ payload = settings_route.ModelOverridePayload(model_id = "local/x", max_seq_length = 4096)+ response = settings_route.update_openai_auto_switch_override(payload, current_subject = "t")++ assert response is not None+ written = saved.get("local/x", {})+ kept = written.get("llama_extra_args")+ if kept is not None:+ assert "--slot-save-path" not in kept+ assert "--numa" in kept+++def test_the_auto_switch_path_sanitizes_a_legacy_override(monkeypatch):+ # The third carry-over path, and the one with no user in front of it: an OpenAI+ # auto-switch or an idle reload builds a LoadRequest from the stored override.+ # An explicit list is refused with a 400, so a flag denied after it was saved+ # would break that model's automatic loads until someone rewrote the entry.+ from utils.openai_auto_switch_settings import model_override_load_kwargs++ kwargs = model_override_load_kwargs(+ {"llama_extra_args": ["--agent", "--numa", "distribute"], "n_parallel": 4},+ is_gguf = True,+ )++ assert kwargs["llama_extra_args"] == ["--numa", "distribute"]+ assert kwargs["n_parallel"] == 4+++def test_the_auto_switch_path_leaves_a_clean_override_alone():+ from utils.openai_auto_switch_settings import model_override_load_kwargs+ kwargs = model_override_load_kwargs(+ {"llama_extra_args": ["--numa", "distribute"]}, is_gguf = True+ )++ assert kwargs["llama_extra_args"] == ["--numa", "distribute"]+++def test_trimming_to_the_bounds_never_leaves_a_flag_without_its_value():+ # validate_extra_args knows the arity of only a few flags, so a dangling+ # --grammar passes it and llama-server refuses the launch instead.+ kept, dropped = _lsa.drop_managed_flags(["--top-k", "20", "--grammar", "a" * 40_000])++ assert kept == ["--top-k", "20"]+ assert "--grammar" in dropped+ # And a log line does not carry the 40 KB value that broke the bound.+ assert all(len(name) < 100 for name in dropped)+++def test_a_token_that_cannot_be_spawned_is_refused_at_the_boundary():+ # An unpaired surrogate survives JSON and the browser, passes every other check+ # here, and then makes subprocess.Popen raise while it encodes argv, after the+ # load has already begun switching models. A 400 is the honest answer.+ with pytest.raises(ValueError, match = "surrogate"):+ _lsa.validate_extra_args(["--chat-template", "\ud800"])+++def test_a_stored_surrogate_is_dropped_like_any_other_unusable_value():+ kept, dropped = _lsa.drop_managed_flags(["--grammar", "\ud800", "--top-k", "20"])++ assert kept == ["--top-k", "20"]+ assert _lsa.validate_extra_args(kept) == kept+ assert "--grammar" in dropped+++def test_validate_sizes_itself_with_the_arguments_the_caller_sent():+ # /validate estimates the memory that approves the follow-up /load, and a+ # --ctx-size in the extras changes that estimate. The resolver hands back its+ # fourth argument unchanged for an explicit list, so passing None there meant the+ # preflight approved a different command from the one that runs.+ import inspect++ import routes.inference as inference_route++ source = inspect.getsource(inference_route)+ assert (+ "_resolve_inherited_extra_args(\n request, config, model_identifier, None\n )"+ not in source+ )+ assert 'model_identifier, getattr(request, "llama_extra_args", None)' in source++ class _Request:+ llama_extra_args = ["--ctx-size", "8192"]++ class _Config:+ is_gguf = True+ gguf_variant = ""++ # The helper's own contract: an explicit list is returned as given.+ assert inference_route._resolve_inherited_extra_args(+ _Request(), _Config(), "local/x", _Request.llama_extra_args+ ) == ["--ctx-size", "8192"]+++def test_a_poisoned_flag_takes_its_value_with_it():+ # The control characters are in the FLAG here. Dropping only that token leaves+ # "root ::= ..." as a bare positional, which validate_extra_args accepts and+ # llama-server reads as the model path.+ kept, dropped = _lsa.drop_managed_flags(["--grammar\x1b[2J", "root ::= [0-9]", "--top-k", "20"])++ assert kept == ["--top-k", "20"]+ assert _lsa.validate_extra_args(kept) == kept+ # And the name is not echoed into the log line either: the escape is IN it.+ assert dropped == ["<flag>"]+ assert all("\x1b" not in name for name in dropped)+++def test_a_poisoned_flag_with_an_attached_value_drops_alone():+ kept, dropped = _lsa.drop_managed_flags(["--grammar\x1b=root", "--top-k", "20"])++ assert kept == ["--top-k", "20"]+ # The control character is judged first: its name is never echoed into a log,+ # and the attached-value rule would have named it.+ assert dropped == ["<flag>"]+++def test_a_bare_value_with_no_flag_is_refused():+ # llama-server answers "invalid argument" and refuses to start, so this is a+ # failed load rather than a 400; and a build that DID take a positional would+ # read it as the model path, which is what denying -m / --model exists to stop.+ for bad in (+ ["/private/models/other.gguf"],+ ["--top-k", "20", "/models/other.gguf"],+ ):+ with pytest.raises(ValueError, match = "bare value"):+ _lsa.validate_extra_args(bad)+ # The attached spelling is refused before anything can be said about what+ # follows it, since llama-server never reads it as a flag at all.+ with pytest.raises(ValueError, match = "two separate arguments"):+ _lsa.validate_extra_args(["--top-k=20", "stray"])+++def test_a_value_that_belongs_to_a_flag_is_still_fine():+ assert _lsa.validate_extra_args(["--numa", "distribute"])+ assert _lsa.validate_extra_args(["--grammar", "root ::= [0-9]"])+ # The one flag in llama-server's help that takes two values.+ assert _lsa.validate_extra_args(["--control-vector-layer-range", "1", "10"])+++def test_the_underscore_spelling_keeps_its_detached_value():+ # llama.cpp takes both spellings (measured on b10360: `llama-server --ctx_size+ # 4096 --help` prints its help), and _flag_name folds one onto the other. Deciding+ # attachment from that fold read "--ctx_size 4096" as a flag carrying its own+ # value and then refused the 4096 as a bare token, which is a list the CLI has+ # passed through for as long as the field has existed.+ for good in (+ ["--ctx_size", "4096"],+ ["--n_gpu_layers", "5"],+ ["--rope_scaling", "yarn"],+ ["--top-k", "20", "--ctx_size", "4096"],+ ):+ assert _lsa.validate_extra_args(good) == good+ # The value is still consumed exactly once: a second bare token has no owner.+ with pytest.raises(ValueError, match = "bare value"):+ _lsa.validate_extra_args(["--ctx_size", "4096", "stray"])+ # The underscore spelling folds, the attached one does not exist for llama.cpp+ # whichever way it is spelled.+ with pytest.raises(ValueError, match = "two separate arguments"):+ _lsa.validate_extra_args(["--ctx_size=4096"])+++def test_a_batch_below_the_floor_is_refused_before_the_launch():+ # llama-server aborts on a batch of 1 at any slot count, and on a batch below the+ # slots it serves (measured, and recorded beside the launcher that raises its own+ # --batch-size for it). Extras are appended after that flag and win, so this is a+ # server that dies during startup, by which time the previous model is unloaded.+ for args, slots in (+ (["-b", "1"], 1),+ (["--batch-size", "0"], 1),+ (["--batch-size=1"], 1),+ (["-b", "2"], 4),+ (["--top-k", "20", "-b", "3"], 4),+ ):+ with pytest.raises(ValueError, match = "aborts on --batch-size"):+ _lsa.check_batch_floor(args, slots)+ # At or above the floor, and anything this side cannot read, is left alone:+ # llama-server names an unreadable value better than a guess here would.+ for args, slots in (+ (["-b", "2"], 1),+ (["-b", "4"], 4),+ (["-b", "8"], 4),+ (["-b", "abc"], 4),+ (["--top-k", "20"], 4),+ ([], 4),+ ):+ assert _lsa.check_batch_floor(args, slots) is None+++def test_a_scaled_sidecar_may_take_its_scale_separately():+ # Today's llama.cpp writes it into the value ("--lora-scaled FNAME:SCALE"), older+ # builds took it as its own token, and _sidecar_weight_files reads both. Allowed+ # and never required: demanding the second token would refuse the current syntax,+ # and refusing it broke a list that loaded before the positional check existed.+ for good in (+ ["--lora-scaled", "/a.gguf", "0.5"],+ ["--lora-scaled", "/a.gguf:0.5"],+ ["--lora-scaled", "/a.gguf"],+ ["--control-vector-scaled", "/v.gguf", "0.8"],+ ["--control-vector-scaled", "/v.gguf:0.8", "--top-k", "20"],+ ["--lora-scaled", "/a.gguf", "0.5", "--top-k", "20"],+ ):+ assert _lsa.validate_extra_args(good) == good+ # A third bare token still belongs to nothing.+ with pytest.raises(ValueError, match = "bare value"):+ _lsa.validate_extra_args(["--lora-scaled", "/a.gguf", "0.5", "stray"])+++def test_a_two_value_flag_is_kept_whole():+ # Half of this option is not a smaller version of it: llama-server refuses+ # "--control-vector-layer-range 1" on the command line, so a list that carries it+ # is a load that fails at spawn rather than a request that fails at the boundary.+ for bad in (+ ["--control-vector-layer-range"],+ ["--control-vector-layer-range", "1"],+ ["--control-vector-layer-range", "1", "--numa", "distribute"],+ ["--top-k", "20", "--control-vector-layer-range", "1"],+ ):+ with pytest.raises(ValueError, match = "takes two values"):+ _lsa.validate_extra_args(bad)+++def test_the_attached_form_of_a_two_value_flag_is_refused_like_any_other():+ # It used to be read as START owing an END, which was a guess about a spelling+ # llama.cpp does not have: the whole token is looked up in its option map, so+ # "--control-vector-layer-range=1" is an argument it has never heard of.+ for bad in (+ ["--control-vector-layer-range=1"],+ ["--control-vector-layer-range=1", "10"],+ ["--control-vector-layer-range=1", "--numa", "distribute"],+ ):+ with pytest.raises(ValueError, match = "two separate arguments"):+ _lsa.validate_extra_args(bad)+ # Detached, it is the one option here whose arity is known for certain.+ assert _lsa.validate_extra_args(["--control-vector-layer-range", "1", "10"])+ with pytest.raises(ValueError, match = "takes two values"):+ _lsa.validate_extra_args(["--control-vector-layer-range", "1"])+++def test_trimming_sheds_a_two_value_flag_whole():+ # A list stored by an older build can exceed today's bound, and the trim walks in+ # from the tail. Shedding END alone leaves START looking like an ordinary value,+ # which nothing downstream would object to and llama-server would then reject.+ kept, dropped = _lsa.drop_managed_flags(+ ["--top-k", "20", "--control-vector-layer-range", "1", "10", "--grammar", "x" * 40000]+ )+ assert kept == ["--top-k", "20", "--control-vector-layer-range", "1", "10"]+ kept, dropped = _lsa.drop_managed_flags(+ ["--top-k", "20", "--control-vector-layer-range", "1", "x" * 40000]+ )+ assert kept == ["--top-k", "20"]+ assert "--control-vector-layer-range" in dropped+ # And whatever survives is a list the validator would take.+ assert _lsa.validate_extra_args(kept) == kept+++def test_the_windows_check_measures_what_popen_would_write(monkeypatch):+ # list2cmdline is not a sum of lengths: backslashes before a quote double, so an+ # escape-heavy grammar can pass a byte cap and still blow CreateProcess's 32767+ # character limit once quoted, inside Popen, after the switch has begun.+ monkeypatch.setattr(_lsa.sys, "platform", "win32", raising = False)+ value = ("\\" * 10 + '"') * 2000+ assert len(value) < _lsa.MAX_EXTRA_ARGS_BYTES_WINDOWS++ with pytest.raises(ValueError, match = "Windows command line"):+ _lsa.validate_extra_args(["--grammar", value])++ # Same list, other platforms: no such limit, so no refusal.+ monkeypatch.setattr(_lsa.sys, "platform", "linux", raising = False)+ assert _lsa.validate_extra_args(["--grammar", value])+++def test_the_loader_and_the_panel_resolve_the_same_row(monkeypatch):+ # The panel used to mirror these rules in the browser, where casefold is only+ # approximated by toLowerCase and an ambiguous fold is easy to get wrong. Both+ # sides now go through this, so what a panel shows and what a load applies cannot+ # disagree.+ import utils.openai_auto_switch_settings as oas++ stored = {+ "/models/Foo.gguf:Q4_K_M": {"llama_extra_args": ["--numa", "distribute"]},+ "unsloth/model-gguf": {"llama_extra_args": ["--top-k", "20"]},+ }+ monkeypatch.setattr(oas, "get_model_overrides", lambda: dict(stored))++ # The load path before the advertised alias, and variant-qualified first. The+ # path keeps its case (POSIX), while the quant folds, which is the rule a browser+ # mirroring this kept getting subtly wrong.+ key, override = oas.resolve_override_for_load(+ "/models/Foo.gguf", "unsloth/model-gguf", "q4_k_m"+ )+ assert override["llama_extra_args"] == ["--numa", "distribute"]+ assert key == "/models/Foo.gguf:Q4_K_M"++ # With no such row, the alias answers.+ key, override = oas.resolve_override_for_load("/models/other.gguf", "unsloth/model-gguf", None)+ assert override["llama_extra_args"] == ["--top-k", "20"]+++def test_the_candidate_order_is_the_loaders_own():+ from utils.openai_auto_switch_settings import override_lookup_candidates++ assert override_lookup_candidates("local/x", "alias/x", "Q4") == [+ "local/x:Q4",+ "alias/x:Q4",+ "local/x",+ "alias/x",+ ]+ # A loose .gguf also answers to the filename-label key an early build wrote.+ candidates = override_lookup_candidates("/models/gemma-3-270m-it-Q4_K_M.gguf")+ assert candidates[0] == "/models/gemma-3-270m-it-Q4_K_M.gguf"+ assert any(key.endswith(":Q4_K_M") for key in candidates), candidates+++def test_a_flag_padded_with_spaces_is_refused():+ # _flag_name strips before it looks anything up, so a quoted "--top-k " passed the+ # denylist and the arity walk as --top-k and then went to the child with the space+ # still on it. llama.cpp looks the WHOLE token up: measured on b10342, it answers+ # "error: invalid argument: --top-k", naming a flag that reads as correct.+ for bad in (["--top-k ", "20"], [" --top-k", "20"], ["--verbose "]):+ with pytest.raises(ValueError, match = "spaces around"):+ _lsa.validate_extra_args(bad)+ # A VALUE may legitimately carry whitespace: a grammar or a chat template does,+ # and quoting one into a single token is what the box is for.+ assert _lsa.validate_extra_args(["--grammar", "root ::= [0-9] "]) == [+ "--grammar",+ "root ::= [0-9] ",+ ]+++def test_a_padded_flag_is_carried_over_by_dropping_it_with_its_value():+ # Dropped in the walk, like the denied names and the attached spelling: left to+ # the trimming loop it would shed the whole tail after it. Its value goes too,+ # since the flag never arrives and an orphan is a bare positional.+ kept, dropped = _lsa.drop_managed_flags(["--top-k ", "20", "--numa", "distribute"])+ assert kept == ["--numa", "distribute"]+ assert dropped == ["--top-k"]+ kept, _dropped = _lsa.drop_managed_flags(["--verbose ", "--numa", "distribute"])+ assert kept == ["--numa", "distribute"]diff --git a/studio/backend/tests/test_llama_extra_args_end_to_end.py b/studio/backend/tests/test_llama_extra_args_end_to_end.pynew file mode 100644index 00000000000..36c7c195add--- /dev/null+++ b/studio/backend/tests/test_llama_extra_args_end_to_end.py@@ -0,0 +1,130 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What the child process actually receives when the editor sends extra args.++The unit tests either side of this one pin the validator and the row's copy. This+one pins the thing both exist to produce: the argv llama-server is launched with.+It reuses the placement suite's harness, which runs the real ``load_model`` and+captures the command at the Popen boundary instead of spawning anything.++The bar the whole feature is measured against is the first test here: with nothing+in the box, the command must be byte-identical to the one Unsloth emitted before.+"""++from __future__ import annotations++import pytest++# The harness (module stubs, a fake GGUF, a fake GPU probe, the captured Popen)+# already exists; importing it keeps one copy of that setup. By path, because the+# tests directory is not a package and rootdir-relative imports do not resolve.+import importlib.util as _importlib_util+from pathlib import Path as _Path++_PLACEMENT_PATH = _Path(__file__).resolve().parent / "test_llama_cpp_placement.py"+_spec = _importlib_util.spec_from_file_location("_placement_harness", _PLACEMENT_PATH)+_placement = _importlib_util.module_from_spec(_spec)+_spec.loader.exec_module(_placement)+_backend = _placement._backend+_launch = _placement._launch+++def _cmd(tmp_path, **load_kwargs):+ backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 20_000, 24_000)])+ return _launch(backend, gguf, **load_kwargs)["cmd"]+++def _stable(cmd: list[str]) -> list[str]:+ """The command with the two values that differ per launch masked.++ The port is picked from whatever is free and the GGUF lives under a per-test+ tmp dir, so a literal comparison could never hold. Everything else is the+ part this feature must not move.+ """+ masked = list(cmd)+ for index, token in enumerate(masked):+ if index and masked[index - 1] == "--port":+ masked[index] = "<port>"+ elif index and masked[index - 1] in {"-m", "--model"}:+ masked[index] = "<model>"+ return masked+++def test_no_extra_args_leaves_the_command_unchanged(tmp_path):+ # The acceptance bar: someone who never opens the box must see exactly what+ # they saw before. None (inherit) and [] (explicitly none) both mean that here.+ baseline = _stable(_cmd(tmp_path))+ assert _stable(_cmd(tmp_path, extra_args = None)) == baseline+ assert _stable(_cmd(tmp_path, extra_args = [])) == baseline+ # And the masking is not hiding the whole command.+ assert "--flash-attn" in baseline and "<port>" in baseline+++def test_an_extra_arg_reaches_the_child(tmp_path):+ cmd = _cmd(tmp_path, extra_args = ["--top-k", "20"])++ assert "--top-k" in cmd+ assert cmd[cmd.index("--top-k") + 1] == "20"+++def test_extra_args_come_after_unsloths_own(tmp_path):+ # This is what makes the row's "passed after the settings above" true, and it+ # is llama.cpp's last-wins parsing that turns position into precedence.+ cmd = _cmd(tmp_path, extra_args = ["--top-k", "20"])+ managed = [i for i, token in enumerate(cmd) if token in {"--model", "-m", "--port"}]++ assert managed, "expected Unsloth's own flags in the command"+ assert cmd.index("--top-k") > max(managed)+++def test_a_shadowing_value_wins_by_arriving_last(tmp_path):+ # --ctx-size is Context Length's flag. The backend deliberately allows the+ # shadow and reconciles its own sizing, so the user's value has to be the one+ # llama.cpp reads: last.+ cmd = _cmd(tmp_path, extra_args = ["--ctx-size", "4096"])+ positions = [i for i, token in enumerate(cmd) if token in {"--ctx-size", "-c"}]++ assert positions, "expected a context flag in the command"+ assert cmd[max(positions) + 1] == "4096"+++def test_a_multi_token_value_stays_one_argv_entry(tmp_path):+ # The tokeniser's whole purpose: a template with spaces must not become two+ # arguments, which is what would happen if the string were split by the shell+ # or by the backend.+ template = "{% for m in messages %}{{ m.content }}{% endfor %}"+ cmd = _cmd(tmp_path, extra_args = ["--chat-template", template])++ assert cmd[cmd.index("--chat-template") + 1] == template+++ "denied",+ [+ ["--agent"],+ ["--tools-runtime", "docker:x"],+ ["--mcp-servers-json", "{}"],+ ["--parallel", "8"],+ ["--api-key", "secret"],+ ],+)+def test_a_denied_flag_never_reaches_the_child(tmp_path, denied):+ # The load has to refuse rather than launch and hope: llama-server would+ # happily honour any of these.+ with pytest.raises(ValueError, match = "managed by Unsloth Studio"):+ from core.inference.llama_server_args import validate_extra_args+ validate_extra_args(denied)+++def test_the_denied_env_twin_does_not_survive_the_launch(tmp_path, monkeypatch):+ # Denying the token is only half of it: llama.cpp reads LLAMA_ARG_* before argv,+ # so an inherited value would reach the child with nothing in the command to+ # show for it.+ monkeypatch.setenv("LLAMA_ARG_AGENT", "1")+ monkeypatch.setenv("LLAMA_ARG_TOOLS", "all")+ backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 20_000, 24_000)])+ env = _launch(backend, gguf)["env"]++ assert "LLAMA_ARG_AGENT" not in env+ assert "LLAMA_ARG_TOOLS" not in envdiff --git a/studio/backend/tests/test_llama_extra_args_platforms.py b/studio/backend/tests/test_llama_extra_args_platforms.pynew file mode 100644index 00000000000..4ffd074dbff--- /dev/null+++ b/studio/backend/tests/test_llama_extra_args_platforms.py@@ -0,0 +1,247 @@+# 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 extra-arguments pass-through across every platform and accelerator.++Studio emits a different command on each of these: CUDA, ROCm and Vulkan take+different offload flags, Metal takes none of them, and Windows spells the binary+and the paths differently. The claim this suite has to defend is the same on all of+them, and it is a claim about what does NOT change:++ with the box empty, the command is byte-identical to the one Unsloth emitted+ before this feature existed.++The matrix is the Cartesian product of the platforms Studio ships on and the+accelerators it detects, driven through the real ``load_model`` with the command+captured at the Popen boundary.+"""++from __future__ import annotations++import importlib.util+from pathlib import Path++import pytest++# The placement harness (module stubs, a fake GGUF, a fake GPU probe, the captured+# Popen) already exists; by path, because the tests dir is not a package.+_PLACEMENT_PATH = Path(__file__).resolve().parent / "test_llama_cpp_placement.py"+_spec = importlib.util.spec_from_file_location("_placement_harness_platforms", _PLACEMENT_PATH)+_placement = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_placement)+_backend = _placement._backend+_launch = _placement._launch++# (label, sys.platform, os.name, a WSL-shaped release string or None)+PLATFORMS = [+ ("linux", "linux", "posix", None),+ ("wsl2", "linux", "posix", "5.15.153.1-microsoft-standard-WSL2"),+ ("windows", "win32", "nt", None),+ ("macos", "darwin", "posix", None),+]++# (label, vulkan, memory) -- memory [] is the CPU-only / no-device answer the probe+# gives when there is nothing to place on.+ACCELERATORS = [+ ("nvidia-single", False, [(0, 20_000, 24_000)]),+ ("nvidia-multi", False, [(0, 20_000, 24_000), (1, 20_000, 24_000)]),+ ("amd-vulkan", True, [(0, 12_000, 16_000)]),+ ("cpu-only", False, []),+]++MATRIX = [pytest.param(p, a, id = f"{p[0]}-{a[0]}") for p in PLATFORMS for a in ACCELERATORS]+++def _apply_platform(monkeypatch, platform) -> None:+ """Move the seams the launch path actually branches on.++ Only ``sys.platform`` and the WSL markers: patching ``os.name`` as well swaps+ pathlib's flavour mid-run, so the harness's own tmp GGUF stops resolving and+ every assertion below becomes a lie about a file that was never opened. The+ authoritative Windows and macOS signal is the per-OS CI matrix on real runners;+ this is the branch coverage that can be had on one host.+ """+ _label, sys_platform, _os_name, wsl_release = platform+ import platform as _platform+ import sys as _sys++ monkeypatch.setattr(_sys, "platform", sys_platform, raising = False)+ if wsl_release:+ monkeypatch.setattr(_platform, "release", lambda: wsl_release, raising = False)+ monkeypatch.setenv("WSL_DISTRO_NAME", "Ubuntu")+ else:+ monkeypatch.delenv("WSL_DISTRO_NAME", raising = False)+++def _stable(cmd: list[str]) -> list[str]:+ """The command with the two per-launch values masked (port, model path)."""+ masked = list(cmd)+ for index, token in enumerate(masked):+ if index and masked[index - 1] == "--port":+ masked[index] = "<port>"+ elif index and masked[index - 1] in {"-m", "--model"}:+ masked[index] = "<model>"+ return masked++[email protected]("platform,accelerator", MATRIX)+def test_an_empty_box_changes_nothing_anywhere(tmp_path, monkeypatch, platform, accelerator):+ # The acceptance bar, on every combination. None (inherit) and [] (explicitly+ # none) are both "the user did not put anything in the box".+ _apply_platform(monkeypatch, platform)+ _label, vulkan, memory = accelerator++ backend, gguf = _backend(tmp_path, vulkan = vulkan, memory = memory)+ baseline = _stable(_launch(backend, gguf)["cmd"])++ backend, gguf = _backend(tmp_path, vulkan = vulkan, memory = memory)+ assert _stable(_launch(backend, gguf, extra_args = None)["cmd"]) == baseline++ backend, gguf = _backend(tmp_path, vulkan = vulkan, memory = memory)+ assert _stable(_launch(backend, gguf, extra_args = [])["cmd"]) == baseline++[email protected]("platform,accelerator", MATRIX)+def test_an_extra_arg_lands_last_and_changes_nothing_before_it(+ tmp_path, monkeypatch, platform, accelerator+):+ # Appended, never interleaved: llama.cpp's last-wins parsing is the whole+ # mechanism, and a flag that landed early would lose to Unsloth's own.+ _apply_platform(monkeypatch, platform)+ _label, vulkan, memory = accelerator++ backend, gguf = _backend(tmp_path, vulkan = vulkan, memory = memory)+ baseline = _stable(_launch(backend, gguf)["cmd"])++ backend, gguf = _backend(tmp_path, vulkan = vulkan, memory = memory)+ with_extra = _stable(_launch(backend, gguf, extra_args = ["--top-k", "20"])["cmd"])++ assert with_extra == [*baseline, "--top-k", "20"]++[email protected]("platform,accelerator", MATRIX)+def test_placement_is_not_moved_by_an_unrelated_extra_arg(+ tmp_path, monkeypatch, platform, accelerator+):+ # A flag Unsloth's estimator knows nothing about must not disturb the flags it+ # computed: the offload decision belongs to the placement code on every one of+ # these accelerators, and --seed has no business changing it.+ _apply_platform(monkeypatch, platform)+ _label, vulkan, memory = accelerator+ placement_flags = {+ "-ngl",+ "--n-gpu-layers",+ "--gpu-layers",+ "--fit",+ "-sm",+ "--split-mode",+ "--tensor-split",+ "-ncmoe",+ "--n-cpu-moe",+ }++ backend, gguf = _backend(tmp_path, vulkan = vulkan, memory = memory)+ baseline = _launch(backend, gguf)["cmd"]++ backend, gguf = _backend(tmp_path, vulkan = vulkan, memory = memory)+ with_extra = _launch(backend, gguf, extra_args = ["--seed", "42"])["cmd"]++ def _placement(cmd):+ out = []+ for index, token in enumerate(cmd):+ if token in placement_flags:+ out.append((token, cmd[index + 1] if index + 1 < len(cmd) else None))+ return out++ assert _placement(with_extra) == _placement(baseline)++[email protected]("platform,accelerator", MATRIX)+def test_a_denied_flag_is_refused_identically_everywhere(+ tmp_path, monkeypatch, platform, accelerator+):+ # The denylist is a property of Unsloth, not of the host: a flag refused on+ # Linux must not be reachable by running the same build on Windows.+ from core.inference.llama_server_args import validate_extra_args+ _apply_platform(monkeypatch, platform)+ for denied in (["--agent"], ["--mcp-servers-json", "{}"], ["--log-file", "x"]):+ with pytest.raises(ValueError, match = "managed by Unsloth Studio"):+ validate_extra_args(denied)++[email protected]("platform", PLATFORMS, ids = [p[0] for p in PLATFORMS])+def test_a_windows_shaped_value_survives_as_one_token(tmp_path, monkeypatch, platform):+ # Backslashes and a drive letter are ordinary characters to the backend: the+ # split happens in the browser, and the API takes one argv token per entry.+ _apply_platform(monkeypatch, platform)+ windows_path = r"C:\\Users\\me\\models\\template.jinja"++ backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 20_000, 24_000)])+ cmd = _launch(backend, gguf, extra_args = ["--chat-template-file", windows_path])["cmd"]++ assert cmd[cmd.index("--chat-template-file") + 1] == windows_path++[email protected]("platform", PLATFORMS, ids = [p[0] for p in PLATFORMS])+def test_the_denied_env_twins_are_scrubbed_on_every_platform(tmp_path, monkeypatch, platform):+ # llama.cpp reads LLAMA_ARG_* before argv on all of them, so denying the token+ # without the variable would leave the capability reachable wherever Studio runs.+ _apply_platform(monkeypatch, platform)+ monkeypatch.setenv("LLAMA_ARG_AGENT", "1")+ monkeypatch.setenv("LLAMA_ARG_TOOLS", "all")+ # The logging twin matters most of all: Studio classifies a failed start by+ # reading llama-server's output, and nothing it emits later overrides this.+ monkeypatch.setenv("LLAMA_ARG_LOG_FILE", "/tmp/llama.log")+ # --api-prefix moves /health, which every load waits on, and an inherited API key+ # makes the healthy child refuse requests Studio sends without one.+ monkeypatch.setenv("LLAMA_ARG_API_PREFIX", "/llama")+ monkeypatch.setenv("LLAMA_API_KEY", "sk-someone-elses")+ monkeypatch.setenv("LLAMA_ARG_API_KEY_FILE", "/etc/llama.keys")+ # Given both TLS twins llama-server listens on https, while Studio probes /health+ # and proxies over http: the child is healthy and every load times out.+ monkeypatch.setenv("LLAMA_ARG_SSL_KEY_FILE", "/etc/llama/key.pem")+ monkeypatch.setenv("LLAMA_ARG_SSL_CERT_FILE", "/etc/llama/cert.pem")+ monkeypatch.setenv("LLAMA_ARG_NO_WARMUP", "1")++ backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 20_000, 24_000)])+ env = _launch(backend, gguf)["env"]++ assert "LLAMA_ARG_AGENT" not in env+ assert "LLAMA_ARG_TOOLS" not in env+ assert "LLAMA_ARG_LOG_FILE" not in env+ assert "LLAMA_ARG_API_PREFIX" not in env+ assert "LLAMA_API_KEY" not in env+ assert "LLAMA_ARG_API_KEY_FILE" not in env+ assert "LLAMA_ARG_SSL_KEY_FILE" not in env+ assert "LLAMA_ARG_SSL_CERT_FILE" not in env+ # Not a general purge: a variable that is not a denied flag's twin, and that+ # no other reconciliation claims, is the user's own configuration and stays.+ assert env.get("LLAMA_ARG_NO_WARMUP") == "1"++[email protected]("platform", PLATFORMS, ids = [p[0] for p in PLATFORMS])+def test_the_size_cap_leaves_room_for_the_rest_of_a_windows_command(monkeypatch, platform):+ # CreateProcess takes ONE string for the whole command line, capped at 32767+ # characters, and the model path, Unsloth's own flags and subprocess's quoting+ # come out of the same budget. A grammar that passed here and then failed inside+ # Popen would do so after the load had begun switching models.+ import sys as _sys++ from core.inference import llama_server_args as lsa++ _label, sys_platform, _os_name, _wsl = platform+ monkeypatch.setattr(_sys, "platform", sys_platform, raising = False)+ monkeypatch.setattr(lsa.sys, "platform", sys_platform, raising = False)++ limit = lsa.max_extra_args_bytes()+ if sys_platform == "win32":+ assert limit == lsa.MAX_EXTRA_ARGS_BYTES_WINDOWS+ assert limit < 32767 - 4096, "no room left for the command Unsloth builds"+ else:+ assert limit == lsa.MAX_EXTRA_ARGS_BYTES++ # And the validator refuses at that cap, naming it.+ with pytest.raises(ValueError, match = str(limit)):+ lsa.validate_extra_args(["--grammar", "x" * (limit + 1)])+ # Just under it is accepted on every platform.+ assert lsa.validate_extra_args(["--grammar", "x" * (limit - 32)])diff --git a/studio/backend/tests/test_llama_flag_catalog.py b/studio/backend/tests/test_llama_flag_catalog.pynew file mode 100644index 00000000000..72631742a30--- /dev/null+++ b/studio/backend/tests/test_llama_flag_catalog.py@@ -0,0 +1,364 @@+# 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 flag catalogue the extra-arguments editor validates against.++The catalogue comes from the INSTALLED binary's ``--help``, not a list shipped with+Unsloth, because a custom or newer llama.cpp is exactly the case where a bundled list+would reject a flag that works. These tests pin the two things the editor depends on:+that a failed probe is reported as unverifiable rather than as "no such flag", and+that the managed list it explains rejections with cannot drift from the validator.+"""++from __future__ import annotations++import asyncio+import importlib.util+from pathlib import Path++import pytest++_LSA_PATH = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_server_args.py"+_spec = importlib.util.spec_from_file_location("_lsa_catalog_test", _LSA_PATH)+_lsa = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_lsa)+++def _call(+ monkeypatch,+ capabilities,+ *,+ raises = False,+):+ """Run the route with a stubbed probe, returning the response model."""+ import routes.inference as inference_route++ class _Backend:+ @staticmethod+ def probe_server_capabilities():+ if raises:+ raise RuntimeError("no binary")+ return capabilities++ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Backend())+ return asyncio.run(inference_route.get_llama_flags(current_subject = "test"))+++def test_a_parsed_catalogue_is_returned(monkeypatch):+ caps = {"found": True, "flags": {"--top-k": "top-k sampling", "--numa": "NUMA policy"}}+ result = _call(monkeypatch, caps)++ assert result.probe_ok is True+ assert result.flags["--top-k"] == "top-k sampling"+ assert "--numa" in result.flags+++def test_a_failed_probe_is_unverifiable_not_empty_of_flags(monkeypatch):+ # The distinction the editor turns into copy: probe_ok False means "cannot+ # check", and every argument has to be let through. Reporting no flags as if+ # the binary supported none would mark every correct flag as a typo.+ result = _call(monkeypatch, {}, raises = True)++ assert result.probe_ok is False+ assert result.flags == {}+ # Still worth answering: the managed list needs no binary, so a rejection can+ # still be explained before the request is made.+ assert "--parallel" in result.managed+++def test_a_missing_binary_is_also_unverifiable(monkeypatch):+ # found=False is the no-binary answer, which is not the same as a binary whose+ # help would not parse, but the editor can do nothing different about it.+ result = _call(monkeypatch, {"found": False, "flags": {}})++ assert result.probe_ok is False+++def test_a_help_run_that_failed_partway_is_unverifiable(monkeypatch):+ # The catalogue is non-empty, which is exactly the trap: --help exited nonzero+ # after printing some of itself, so everything below the failure point is+ # missing and would be reported as "not in this build".+ result = _call(+ monkeypatch,+ {"found": True, "flags": {"--top-k": "x"}, "help_probe_ok": False},+ )++ assert result.probe_ok is False+++def test_an_older_probe_without_the_field_is_still_trusted(monkeypatch):+ # The key is new; a capability dict that predates it (or a stub in another test)+ # must not read as a failed probe.+ result = _call(monkeypatch, {"found": True, "flags": {"--top-k": "x"}})++ assert result.probe_ok is True+++def test_a_binary_whose_help_did_not_parse_is_unverifiable(monkeypatch):+ # A binary that ran but produced nothing parseable must not read as verified,+ # or every flag becomes unknown.+ result = _call(monkeypatch, {"found": True, "flags": {}})++ assert result.probe_ok is False+++def test_the_managed_list_cannot_drift_from_the_validator(monkeypatch):+ # The editor explains a rejection using this list, and the load is refused by+ # validate_extra_args. If they disagree, the UI accepts an argument the load+ # then refuses, or warns about one that would have worked.+ result = _call(monkeypatch, {"found": True, "flags": {"--top-k": "x"}})++ for flag in result.managed:+ assert _lsa.is_managed_flag(flag), flag+ for flag in ("--parallel", "--model", "--api-key", "--agent", "--host"):+ assert flag in result.managed++[email protected]("value", [123, None])+def test_help_text_is_coerced_to_a_string(monkeypatch, value):+ # The probe's dict is typed as object, and a non-string description would fail+ # response validation at request time rather than here.+ result = _call(monkeypatch, {"found": True, "flags": {"--top-k": value}})++ assert isinstance(result.flags["--top-k"], str)+++# --- what the probe publishes ---------------------------------------------------+# The route only forwards; these pin the map it forwards, driven through the real+# --help parser rather than a stub of it.+++def _probe_with_help(+ monkeypatch,+ tmp_path,+ help_text: str,+ returncode: int = 0,+):+ """Run the real capability probe over a canned --help."""+ import types++ from core.inference.llama_cpp import LlamaCppBackend++ binary = tmp_path / "llama-server"+ binary.write_text("#!/bin/sh\n")+ binary.chmod(0o755)++ def _run(_cmd, **kwargs):+ return types.SimpleNamespace(stdout = help_text, stderr = "", returncode = returncode)++ monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", _run)+ # Keyed on (path, mtime, size), so a fresh file per test is a fresh probe.+ return LlamaCppBackend.probe_server_capabilities(str(binary))+++_HELP_WITH_A_REMOVAL_STUB = """\+--top-k N top-k sampling (default: 40)+--draft, --draft-n, --draft-max N the argument has been removed. use --spec-draft-n-max+--numa TYPE attempt optimizations that help on some NUMA systems+"""+++def test_a_removed_flag_is_not_published_as_supported(monkeypatch, tmp_path):+ # llama.cpp keeps the old names in --help only to say they are gone. Publishing+ # them would make the editor stay quiet about a flag the load then refuses,+ # which is the one thing the catalogue exists to prevent.+ caps = _probe_with_help(monkeypatch, tmp_path, _HELP_WITH_A_REMOVAL_STUB)++ assert "--top-k" in caps["flags"]+ assert "--numa" in caps["flags"]+ for removed in ("--draft", "--draft-n", "--draft-max"):+ assert removed not in caps["flags"], removed+++def test_short_aliases_are_published_too(monkeypatch, tmp_path):+ # -t is as valid as --threads, and the catalogue is what the editor checks a+ # typed flag against, so publishing only long names warned that a correct flag+ # was not in this build.+ caps = _probe_with_help(+ monkeypatch,+ tmp_path,+ "-t, --threads N number of threads (default: -1)\n"+ "-fa, --flash-attn on|off|auto set Flash Attention use\n",+ )++ assert "--threads" in caps["flags"]+ assert "-t" in caps["flags"]+ assert caps["flags"]["-t"] == caps["flags"]["--threads"]+ assert "-fa" in caps["flags"]+ # A value placeholder is not a flag.+ assert "-1" not in caps["flags"]+ assert "N" not in caps["flags"]+++def test_a_help_that_exited_nonzero_says_so(monkeypatch, tmp_path):+ # Partial output parses fine, so nothing else in the dict would reveal that the+ # rest of the catalogue is missing.+ caps = _probe_with_help(monkeypatch, tmp_path, _HELP_WITH_A_REMOVAL_STUB, returncode = 1)++ assert caps["help_probe_ok"] is False+++def test_a_clean_help_run_says_so(monkeypatch, tmp_path):+ caps = _probe_with_help(monkeypatch, tmp_path, _HELP_WITH_A_REMOVAL_STUB)++ assert caps["help_probe_ok"] is True+++def test_the_denylist_can_be_read_without_probing(monkeypatch):+ # The panel sanitizes a stored list with this before turning it into an explicit+ # request, and a cold --help takes up to ten seconds. Waiting for the probe would+ # leave a flag denied since that list was saved sitting in the request.+ import asyncio++ import routes.inference as inference_route++ probed = False++ class _Backend:+ @staticmethod+ def probe_server_capabilities():+ nonlocal probed+ probed = True+ return {"found": True, "flags": {"--top-k": "x"}}++ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Backend())+ result = asyncio.run(inference_route.get_llama_flags(managed_only = True, current_subject = "test"))++ assert probed is False+ assert "--agent" in result.managed+ assert result.flags == {}+ # Nothing was checked against a binary, so nothing may be called a typo.+ assert result.probe_ok is False+++def test_the_published_slot_default_is_the_effective_one(monkeypatch):+ # A build without --kv-unified serves one slot however many are configured, and+ # load_model clamps to that before launch. An editor sizing its batch floor from+ # the raw default would refuse "--batch-size 2" against a command that runs it.+ import routes.inference as inference_route++ monkeypatch.setattr(+ inference_route.LlamaCppBackend,+ "probe_server_capabilities",+ staticmethod(lambda *a, **k: {"found": True, "supports_kv_unified": False}),+ )+ assert inference_route._effective_parallel_slots(4) == 1+ # With the flag the ask stands, and one slot is already the floor.+ monkeypatch.setattr(+ inference_route.LlamaCppBackend,+ "probe_server_capabilities",+ staticmethod(lambda *a, **k: {"found": True, "supports_kv_unified": True}),+ )+ assert inference_route._effective_parallel_slots(4) == 4+ assert inference_route._effective_parallel_slots(1) == 1+ # The diffusion runner receives no --parallel at all.+ assert inference_route._effective_parallel_slots(4, diffusion_kind = True) == 1+++def test_an_unreadable_probe_keeps_the_asked_for_slot_count(monkeypatch):+ # Refusing to answer is not a reason to clamp: every other caller of the probe+ # here keeps the ask when it cannot be read.+ import routes.inference as inference_route++ def _boom(*_a, **_k):+ raise RuntimeError("no binary")++ monkeypatch.setattr(+ inference_route.LlamaCppBackend,+ "probe_server_capabilities",+ staticmethod(_boom),+ )+ assert inference_route._effective_parallel_slots(4) == 4+++def test_the_slot_probe_never_runs_on_the_event_loop(monkeypatch):+ # The clamp asks the binary whether it supports --kv-unified, and on a cold cache+ # that is `llama-server --help` with a ten second timeout. Computed inline it+ # stalled every other request on the first open of the panel after an update, and+ # the managed-only answer too, which exists precisely to avoid waiting for a probe.+ import asyncio+ import threading++ import routes.inference as inference_route++ loop_thread = None+ probe_thread = None++ def _probe(*_a, **_k):+ nonlocal probe_thread+ probe_thread = threading.current_thread()+ return {"found": True, "supports_kv_unified": True}++ monkeypatch.setattr(+ inference_route.LlamaCppBackend,+ "probe_server_capabilities",+ staticmethod(_probe),+ )+ monkeypatch.setattr(inference_route, "_resolve_parallel_slots", lambda *a, **k: 4)++ async def _run():+ nonlocal loop_thread+ loop_thread = threading.current_thread()+ return await inference_route._effective_default_slots(None)++ assert asyncio.run(_run()) == (4, False)+ assert probe_thread is not None, "the clamp did not consult the binary at all"+ assert probe_thread is not loop_thread, "the --help probe ran on the event loop"+++def test_a_single_slot_default_still_reports_the_clamp(monkeypatch):+ # One slot cannot be clamped below one, so the default needs no probe. Whether+ # this build clamps is a different question and still has to be answered: the+ # editor sizes an EXPLICIT Slots value the user may raise without re-reading+ # this route, and off the loop like the rest of it.+ import asyncio+ import threading++ import routes.inference as inference_route++ loop_thread = None+ probe_thread = None++ def _probe(*_a, **_k):+ nonlocal probe_thread+ probe_thread = threading.current_thread()+ return {"found": True, "supports_kv_unified": False}++ monkeypatch.setattr(+ inference_route.LlamaCppBackend,+ "probe_server_capabilities",+ staticmethod(_probe),+ )+ monkeypatch.setattr(inference_route, "_resolve_parallel_slots", lambda *a, **k: 1)++ async def _run():+ nonlocal loop_thread+ loop_thread = threading.current_thread()+ return await inference_route._effective_default_slots(None)++ assert asyncio.run(_run()) == (1, True)+ assert probe_thread is not loop_thread, "the --help probe ran on the event loop"+++def test_the_clamp_is_read_from_the_same_helper_the_load_uses(monkeypatch):+ import routes.inference as inference_route++ monkeypatch.setattr(+ inference_route.LlamaCppBackend,+ "probe_server_capabilities",+ staticmethod(lambda *a, **k: {"found": True, "supports_kv_unified": True}),+ )+ assert inference_route._parallel_slots_are_clamped() is False+ monkeypatch.setattr(+ inference_route.LlamaCppBackend,+ "probe_server_capabilities",+ staticmethod(lambda *a, **k: {"found": True, "supports_kv_unified": False}),+ )+ assert inference_route._parallel_slots_are_clamped() is True+ # An unreadable probe keeps the ask here too, so nothing is refused over it.+ monkeypatch.setattr(+ inference_route.LlamaCppBackend,+ "probe_server_capabilities",+ staticmethod(lambda *a, **k: (_ for _ in ()).throw(RuntimeError("no binary"))),+ )+ assert inference_route._parallel_slots_are_clamped() is Falsediff --git a/studio/backend/tests/test_llama_server_args.py b/studio/backend/tests/test_llama_server_args.pyindex 5768749d087..5261141a50d 100644--- a/studio/backend/tests/test_llama_server_args.py+++ b/studio/backend/tests/test_llama_server_args.py@@ -111,8 +111,23 @@ def test_empty_list_returns_empty_list():assert validate_extra_args([]) == []-def test_value_with_equals_form_passes_through():- assert validate_extra_args(["--top-k=20"]) == ["--top-k=20"]+def test_the_attached_value_form_is_refused():+ # llama.cpp looks the whole token up in its option map and folds only the+ # underscore spelling, so "--top-k=20" is an argument it has never heard of.+ # Measured on b10342 and b10360: "error: invalid argument: --top-k=20", and the+ # same for --ctx-size=4096 and --flash-attn=on. Accepting it here meant the+ # switch tore down the resident model and the child then refused to start.+ with pytest.raises(ValueError, match = "two separate arguments"):+ validate_extra_args(["--top-k=20"])+ # The detached spelling is what it takes, and the underscore one still folds.+ assert validate_extra_args(["--top-k", "20"]) == ["--top-k", "20"]+ assert validate_extra_args(["--ctx_size", "4096"]) == ["--ctx_size", "4096"]+ # A managed name is still named as managed: that message says which control+ # owns it, which is the more useful of the two.+ with pytest.raises(ValueError, match = "managed by Unsloth Studio"):+ validate_extra_args(["--parallel=8"])+ # An "=" inside a VALUE is untouched: it is the value's own syntax.+ assert validate_extra_args(["--override-kv", "a=int:2"]) == ["--override-kv", "a=int:2"]def test_managed_long_flag_underscore_alias_is_rejected():@@ -120,9 +135,16 @@ def test_managed_long_flag_underscore_alias_is_rejected():validate_extra_args(["--slot_save_path", "/tmp/slots"])-def test_non_flag_token_passes_through():- # Bare positionals are passed through; llama-server can reject them.- assert validate_extra_args(["foo"]) == ["foo"]+def test_a_bare_positional_is_rejected():+ # This used to pass through on the grounds that llama-server can reject it, and+ # it does: "error: invalid argument: foo", so the launch fails instead of the+ # request. Refused here now that a textbox can produce one, because a build that+ # DID accept a positional would read it as the model path, which is exactly what+ # denying -m / --model prevents.+ with pytest.raises(ValueError, match = "bare value"):+ validate_extra_args(["foo"])+ # A value that follows its flag is untouched.+ assert validate_extra_args(["--numa", "distribute"]) == ["--numa", "distribute"]# ── Denylist (rejected) ──────────────────────────────────────────────@@ -193,8 +215,43 @@ def test_non_flag_token_passes_through():"--pooling",# llama-server's own --tools clashes with Unsloth's tool policy."--tools",+ # --agent is --tools by another name ("enable CORS proxy and ALL built-in+ # tools", which includes exec_shell_command), and --tools-runtime says where+ # those tools run -- a container, or another host over ssh.+ "-ag",+ "--agent",+ "-no-ag",+ "--no-agent",+ "--tools-runtime",+ # MCP servers are the same capability from a file or an inline blob.+ "--mcp-servers-config",+ "--mcp-servers-json",+ # Unsloth terminates browser access at its own origin.+ "--cors-origins",+ "--cors-headers",+ "--cors-methods",+ "--cors-credentials",+ "--no-cors-credentials",+ "--media-path",+ # Startup output is how a bad GGUF is told from an OOM from a rejected flag.+ "--log-file",+ "--log-disable",# Slot-state dir: Studio owns it for KV persistence across idle unload."--slot-save-path",+ # These print and exit instead of serving.+ "-h",+ "--help",+ "--usage",+ "--version",+ "--list-devices",+ "-cl",+ "--cache-list",+ "--completion-bash",+ # Aliases of already-denied UI flags; upstream ships both spellings.+ "--webui-config",+ "--webui-config-file",+ "--webui-mcp-proxy",+ "--no-webui-mcp-proxy",],)def test_denylist_rejects_all_aliases(denied):@@ -241,8 +298,11 @@ def test_slot_save_path_is_managed_in_all_forms():validate_extra_args(args)assert is_managed_flag("--slot-save-path") is Trueassert is_managed_flag("--slot-save-path=/tmp/x") is True- # --slots (read-only diagnostics endpoint) stays a user choice.+ # Endpoint exposure stays a user choice: Unsloth reads GET /props and never+ # /slots, so neither flag can strand it.assert is_managed_flag("--slots") is False+ assert is_managed_flag("--no-slots") is False+ assert is_managed_flag("--props") is False@pytest.mark.parametrize(@@ -639,8 +699,6 @@ def test_strip_shadowing_flags_defaults_strip_everything():["--split-mode", "none"],["--split-mode", "layer"],["-sm", "tensor"],- ["--split-mode=row"],- ["-sm=tensor"],],)def test_split_mode_passes_through(args):@@ -648,6 +706,15 @@ def test_split_mode_passes_through(args):assert validate_extra_args(args) == args[email protected]("args", [["--split-mode=row"], ["-sm=tensor"]])+def test_the_attached_split_mode_spelling_is_refused(args):+ # The parsers below still read the attached form, since they also run over+ # Unsloth's own emitted flags; the boundary is where the user's spelling of it+ # is turned back, while the message can still reach them.+ with pytest.raises(ValueError, match = "two separate arguments"):+ validate_extra_args(args)++def test_split_mode_is_not_managed():assert is_managed_flag("--split-mode") is Falseassert is_managed_flag("-sm") is False@@ -971,3 +1038,152 @@ def test_strip_shadowing_flags_keeps_model_draft_without_spec():strip_template = False,)assert out == ["--model-draft", "/custom/mtp.gguf"]+++# --- shape bounds -----------------------------------------------------------+# Not the security boundary (the denylist is), just a floor under what reaches+# execve, so a pasted file fails here naming the limit instead of in the child.+++def test_token_count_is_capped():+ with pytest.raises(ValueError, match = "too many"):+ validate_extra_args(["--verbose"] * (_lsa.MAX_EXTRA_ARG_TOKENS + 1))+ # The cap itself still passes, so the limit is inclusive as stated.+ assert len(validate_extra_args(["--verbose"] * _lsa.MAX_EXTRA_ARG_TOKENS)) == (+ _lsa.MAX_EXTRA_ARG_TOKENS+ )+++def test_total_size_is_capped():+ with pytest.raises(ValueError, match = "too large"):+ validate_extra_args(["--grammar", "x" * (_lsa.MAX_EXTRA_ARGS_BYTES + 1)])+++def test_a_long_single_token_is_allowed_under_the_total():+ # A grammar or JSON schema is legitimately one long token, so the cap is on the+ # list rather than per token.+ schema = "x" * (_lsa.MAX_EXTRA_ARGS_BYTES // 2)+ assert validate_extra_args(["--grammar", schema]) == ["--grammar", schema]+++def test_the_size_cap_counts_bytes_not_characters():+ # Astral-plane characters are 4 bytes each; a character-counted cap would let+ # through four times the argv this claims to bound.+ big = "\U0001f600" * (_lsa.MAX_EXTRA_ARGS_BYTES // 4)+ with pytest.raises(ValueError, match = "too large"):+ validate_extra_args(["--grammar", big])++[email protected]("token", ["a\x00b", "a\x07b", "\x1b[31m"])+def test_control_characters_are_rejected(token):+ with pytest.raises(ValueError, match = "control characters"):+ validate_extra_args([token])++[email protected]("token", ["line\nbreak", "tab\there"])+def test_tab_and_newline_survive(token):+ # A chat template or grammar passed inline carries both. As its flag's value,+ # which is where such a string actually arrives: a bare one is refused now.+ assert validate_extra_args(["--grammar", token]) == ["--grammar", token]+++# --- environment twins ------------------------------------------------------+++def test_denied_env_twins_are_scrubbed():+ env = {+ "LLAMA_ARG_AGENT": "1",+ "LLAMA_ARG_TOOLS": "all",+ "LLAMA_ARG_MCP_SERVERS_JSON": "{}",+ "PATH": "/usr/bin",+ }+ removed = _lsa.scrub_denied_env(env)+ assert set(removed) == {"LLAMA_ARG_AGENT", "LLAMA_ARG_TOOLS", "LLAMA_ARG_MCP_SERVERS_JSON"}+ # Only the twins go.+ assert env == {"PATH": "/usr/bin"}+++def test_scrubbing_is_a_no_op_without_the_twins():+ env = {"PATH": "/usr/bin", "LLAMA_ARG_MLOCK": "1"}+ assert _lsa.scrub_denied_env(env) == []+ assert env == {"PATH": "/usr/bin", "LLAMA_ARG_MLOCK": "1"}+++def test_every_denied_env_var_names_a_denied_flag():+ # The twins are only worth scrubbing while the flag itself is refused; this+ # catches a group being dropped from the denylist and leaving a live back door.+ #+ # Both prefixes, because llama.cpp uses both: --api-key reads LLAMA_API_KEY while+ # --api-key-file reads LLAMA_ARG_API_KEY_FILE, and which one a flag gets has+ # changed between releases.+ for name in _lsa.DENIED_ENV_VARS:+ stem = name.removeprefix("LLAMA_ARG_").removeprefix("LLAMA_")+ flag = _lsa.DENIED_ENV_TWIN_FLAGS.get(name) or "--" + stem.lower().replace("_", "-")+ assert is_managed_flag(flag), f"{name} has no denied flag ({flag})"+++def test_every_denied_flag_with_a_twin_in_the_help_is_scrubbed():+ # The list was enumerated from the bundled b10342 --help rather than guessed:+ # every "(env: NAME)" whose option this module refuses. Recorded here as the+ # pairs that mattered, so a name dropped from the denylist, or a twin dropped+ # from the scrub, is a red test rather than a back door found later.+ #+ # llama.cpp applies the environment BEFORE argv, so the ones Studio always emits+ # are overridden anyway; the rest are the reason this exists.+ for env_var, flag in (+ ("LLAMA_ARG_UI_MCP_PROXY", "--ui-mcp-proxy"),+ ("LLAMA_ARG_UI", "--ui"),+ ("LLAMA_ARG_STATIC_PATH", "--path"),+ ("LLAMA_ARG_MODELS_DIR", "--models-dir"),+ ("LLAMA_ARG_MODELS_AUTOLOAD", "--models-autoload"),+ ("LLAMA_ARG_EMBEDDINGS", "--embeddings"),+ ("LLAMA_ARG_RERANKING", "--reranking"),+ ("LLAMA_ARG_MODEL", "--model"),+ ("LLAMA_ARG_HF_REPO", "--hf-repo"),+ ("LLAMA_ARG_HOST", "--host"),+ ("LLAMA_ARG_PORT", "--port"),+ ("LLAMA_ARG_N_PARALLEL", "--parallel"),+ ("LLAMA_ARG_SSL_KEY_FILE", "--ssl-key-file"),+ ("LLAMA_ARG_SSL_CERT_FILE", "--ssl-cert-file"),+ ):+ assert is_managed_flag(flag), flag+ assert env_var in _lsa.DENIED_ENV_VARS, env_var+ env = {name: "1" for name in _lsa.DENIED_ENV_VARS}+ env["PATH"] = "/usr/bin"+ # The projector twins are an INPUT here, not a back door: _launch_has_mmproj reads+ # both to know the launch has a projector at all, which is what keeps the vision+ # and audio state of a model loaded through an inherited one. Scrubbing them+ # globally cleared that state (test_gpu_init_crash_message caught it), and only+ # the paravirtual CPU recovery drops them, where an unpinned projector is the+ # corrupt path it is undoing.+ for kept in ("LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL"):+ assert kept not in _lsa.DENIED_ENV_VARS, kept+ # HF_TOKEN is deliberately not here: it is the standard Hugging Face credential+ # Studio's own downloads use, not a llama-server behaviour switch, and the child+ # is always given a local -m path rather than a repo to fetch.+ assert "HF_TOKEN" not in _lsa.DENIED_ENV_VARS+ _lsa.scrub_denied_env(env)+ assert env == {"PATH": "/usr/bin"}+++def test_the_projector_env_twins_survive_the_scrub():+ # --mmproj is refused in the box because Unsloth resolves the projector itself,+ # but the environment twin is an INPUT: _launch_has_mmproj reads both names to+ # know the launch has a projector at all, which is what keeps the vision and+ # audio state of a model loaded through an inherited one. Scrubbing them made+ # every such load report itself as text-only.+ env = {+ "LLAMA_ARG_MMPROJ": "/models/mmproj-F16.gguf",+ "LLAMA_ARG_MMPROJ_URL": "https://example.invalid/mmproj-F16.gguf",+ "LLAMA_ARG_AGENT": "1",+ }+ removed = _lsa.scrub_denied_env(env)+ assert removed == ["LLAMA_ARG_AGENT"]+ assert env == {+ "LLAMA_ARG_MMPROJ": "/models/mmproj-F16.gguf",+ "LLAMA_ARG_MMPROJ_URL": "https://example.invalid/mmproj-F16.gguf",+ }+ # Only the paravirtual CPU recovery drops them, where an unpinned projector is+ # the corrupt path it is undoing, and it does that itself.+ assert "LLAMA_ARG_MMPROJ" not in _lsa.DENIED_ENV_VARS+ assert "LLAMA_ARG_MMPROJ_URL" not in _lsa.DENIED_ENV_VARSdiff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex c46eb17250c..84c591c054b 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -7753,3 +7753,168 @@ def test_the_resident_shortcut_refuses_an_explicit_quant_mismatch(monkeypatch):monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: backend)assert inference_route._loaded_identity_satisfies("unsloth/Muse-GGUF:Q8_0") is Falseassert inference_route._loaded_identity_satisfies("unsloth/Muse-GGUF:Q4_K_M") is True+++def test_clearing_the_box_for_a_quant_survives_the_next_load(override_store):+ # The carry-over copies a legacy bare entry's flags onto the first per-quant save,+ # and leaves the bare entry standing. Clearing the box then writes an empty list,+ # an entry with nothing usable left is not stored, and the next load falls through+ # to the bare key: the box comes up empty and the server still runs them.+ settings.set_model_override("unsloth/B-GGUF", llama_extra_args = ["--numa", "distribute"])+ carried = _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 4096)+ assert carried.overrides["unsloth/B-GGUF:Q4_K_M"]["llama_extra_args"] == [+ "--numa",+ "distribute",+ ]++ cleared = _put("unsloth/B-GGUF:Q4_K_M", llama_extra_args = [], remove = False)+ # The row survives the all-default save, saying explicitly that this quant has+ # none, which is what stops the lookup before it reaches the bare key.+ assert cleared.overrides["unsloth/B-GGUF:Q4_K_M"] == {"llama_extra_args": []}+ _key, resolved = settings.resolve_override_for_load("unsloth/B-GGUF", variant = "Q4_K_M")+ assert not resolved.get("llama_extra_args")+++def test_the_clear_leaves_the_legacy_row_for_the_quants_still_reading_it(override_store):+ # The bare row is the fallback for every quant that has none of its own, so+ # clearing Q4's box must not take Q6's flags with it. Only the row the user+ # edited changes.+ settings.set_model_override(+ "unsloth/B-GGUF",+ llama_extra_args = ["--numa", "distribute"],+ max_seq_length = 4096,+ )+ _put("unsloth/B-GGUF:Q4_K_M", llama_extra_args = [], remove = False)+ bare = settings.get_model_override("unsloth/B-GGUF")+ assert bare["llama_extra_args"] == ["--numa", "distribute"]+ assert bare["max_seq_length"] == 4096+ _key, sibling = settings.resolve_override_for_load("unsloth/B-GGUF", variant = "Q6_K")+ assert sibling["llama_extra_args"] == ["--numa", "distribute"]+++def test_the_clear_holds_when_another_quant_has_a_row_of_its_own(override_store):+ # The first fix stripped the bare row and was gated on no sibling row existing,+ # which is the wrong question: a sibling with a row of its own never reads the+ # bare one, so the gate only stopped the clear from working at all.+ settings.set_model_override("unsloth/B-GGUF", llama_extra_args = ["--numa", "distribute"])+ settings.set_model_override("unsloth/B-GGUF:Q8_0", max_seq_length = 4096)+ _put("unsloth/B-GGUF:Q4_K_M", llama_extra_args = [], remove = False)+ _key, resolved = settings.resolve_override_for_load("unsloth/B-GGUF", variant = "Q4_K_M")+ assert not resolved.get("llama_extra_args")+ assert settings.get_model_override("unsloth/B-GGUF")["llama_extra_args"] == [+ "--numa",+ "distribute",+ ]+++def test_a_clear_with_no_fallback_behind_it_stores_nothing(override_store):+ # Nothing would answer for this model anyway, so the row goes as it always has:+ # the tombstone exists to stop a fallback, not to leave a row per cleared box.+ settings.set_model_override("unsloth/B-GGUF:Q4_K_M", llama_extra_args = ["--numa", "distribute"])+ cleared = _put("unsloth/B-GGUF:Q4_K_M", llama_extra_args = [], remove = False)+ assert "unsloth/B-GGUF:Q4_K_M" not in cleared.overrides+++def test_an_explicit_forget_still_removes_the_row(override_store):+ # remove = True is the other operation, and it must not leave a tombstone behind+ # for the picker to read as a saved setting.+ settings.set_model_override("unsloth/B-GGUF", llama_extra_args = ["--numa", "distribute"])+ settings.set_model_override("unsloth/B-GGUF:Q4_K_M", llama_extra_args = ["--top-k", "20"])+ forgotten = _put("unsloth/B-GGUF:Q4_K_M", llama_extra_args = [], remove = True)+ assert "unsloth/B-GGUF:Q4_K_M" not in forgotten.overrides+++def test_a_save_that_did_not_touch_the_box_leaves_the_fallback(override_store):+ # Omitting the field is how every save that never opened the editor behaves, and+ # it means "keep them", not "clear them".+ settings.set_model_override("unsloth/B-GGUF", llama_extra_args = ["--numa", "distribute"])+ _put("unsloth/B-GGUF:Q4_K_M", max_seq_length = 4096)+ assert settings.get_model_override("unsloth/B-GGUF")["llama_extra_args"] == [+ "--numa",+ "distribute",+ ]+++def test_a_fill_pass_never_clears_a_fallback(override_store):+ # The migration writes only what is missing, and mirrors both spellings of a model;+ # clearing from it would delete flags it is supposed to be preserving.+ settings.set_model_override("unsloth/B-GGUF", llama_extra_args = ["--numa", "distribute"])+ _put(+ "unsloth/B-GGUF:Q4_K_M",+ llama_extra_args = [],+ remove = False,+ fill_absent_fields = True,+ )+ assert settings.get_model_override("unsloth/B-GGUF")["llama_extra_args"] == [+ "--numa",+ "distribute",+ ]+++def test_clearing_one_quant_stops_the_legacy_repo_row_from_answering(monkeypatch):+ # 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 an all-default save for the+ # quant, which stores nothing, falls straight back through to a row no page can+ # show, and the flags the user just cleared come back on the next load. The+ # cleared box is kept as an explicit empty list instead: a row that resolves, and+ # supplies no arguments.+ _mock_override_store(monkeypatch)+ settings.set_model_override("unsloth/B-GGUF", llama_extra_args = ["--top-k", "40"])+ _put("unsloth/B-GGUF:Q4_K_M", llama_extra_args = [])++ assert settings.get_model_override("unsloth/B-GGUF:Q4_K_M") == {"llama_extra_args": []}+ key, override = settings.resolve_override_for_load(+ "unsloth/B-GGUF", None, "Q4_K_M"+ )+ assert key == "unsloth/B-GGUF:Q4_K_M"+ assert override.get("llama_extra_args") == []+ # And the bare row is untouched, because it is still the fallback for every other+ # quant of this repo that has no row of its own.+ assert settings.get_model_override("unsloth/B-GGUF")["llama_extra_args"] == [+ "--top-k",+ "40",+ ]+ other_key, other = settings.resolve_override_for_load("unsloth/B-GGUF", None, "Q8_0")+ assert other_key == "unsloth/B-GGUF"+ assert other["llama_extra_args"] == ["--top-k", "40"]+++def test_an_empty_save_with_nothing_to_suppress_still_stores_nothing(monkeypatch):+ # The tombstone exists only to stop a fallback. With no row behind this one,+ # "no launch flags" and "nothing stored" are the same thing, and writing an empty+ # row would leave an entry the settings page then lists as configured.+ _mock_override_store(monkeypatch)+ _put("unsloth/B-GGUF:Q4_K_M", llama_extra_args = [])+ assert settings.get_model_override("unsloth/B-GGUF:Q4_K_M") == {}+ assert settings.get_model_overrides() == {}+++def test_a_fill_never_writes_the_tombstone(monkeypatch):+ # fill_absent_fields only adds what is missing, so an empty list in a fill is the+ # absence of a request, not a clear: writing a row for it would suppress the+ # fallback the user never asked to be rid of.+ _mock_override_store(monkeypatch)+ settings.set_model_override("unsloth/B-GGUF", llama_extra_args = ["--top-k", "40"])+ _put("unsloth/B-GGUF:Q4_K_M", llama_extra_args = [], fill_absent_fields = True)+ assert "llama_extra_args" not in settings.get_model_override("unsloth/B-GGUF:Q4_K_M")+ key, override = settings.resolve_override_for_load("unsloth/B-GGUF", None, "Q4_K_M")+ assert override.get("llama_extra_args") == ["--top-k", "40"]+++def test_normalize_keeps_an_explicit_empty_list_only_when_asked(monkeypatch):+ # The two spellings of the same payload, kept apart by one flag: everywhere else+ # an empty list is a field nobody set, and only the save that means "cleared"+ # asks for it to be stored.+ assert settings.normalize_model_override({"llama_extra_args": []}) == {}+ assert settings.normalize_model_override(+ {"llama_extra_args": []}, keep_empty_extra_args = True+ ) == {"llama_extra_args": []}+ # And the flag only decides what an EMPTY list means. A list with tokens in it is+ # stored either way: this module deliberately does not judge them (the route runs+ # validate_extra_args before it gets here), so the flag must not become a second,+ # quieter filter.+ for keep in (False, True):+ assert settings.normalize_model_override(+ {"llama_extra_args": ["--top-k", "40"]}, keep_empty_extra_args = keep+ ) == {"llama_extra_args": ["--top-k", "40"]}diff --git a/studio/backend/tests/test_validate_diffusion_extra_args.py b/studio/backend/tests/test_validate_diffusion_extra_args.pynew file mode 100644index 00000000000..3bf37fcac31--- /dev/null+++ b/studio/backend/tests/test_validate_diffusion_extra_args.py@@ -0,0 +1,435 @@+# 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/inference/validate must ignore pass-through arguments for a diffusion GGUF.++/load already drops them: the visual runner builds its own command and appends none of+them. /validate is the call that approves the load, and it reads a --ctx-size out of the+same list to size the estimate, so leaving them in place approves a load against a+command that will never carry them. The caller cannot decide this itself either, since+its staged metadata is inconclusive for a GGUF it has not finished downloading, which is+why the drop belongs after the authoritative classification rather than before it.+"""++import asyncio+import importlib.util+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++from models.inference import ValidateModelRequest+++_BACKEND_ROOT = Path(__file__).resolve().parent.parent+++def _load_route_module(name: str):+ spec = importlib.util.spec_from_file_location(name, _BACKEND_ROOT / "routes/inference.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++async def _noop_gpu_ids(_config, gpu_ids, **_kwargs):+ return gpu_ids, False+++class TestValidateDropsDiffusionExtraArgs(unittest.TestCase):+ def _validate(self, route, *, diffusion_kind):+ seen: list = []++ def _capture(*_args, **kwargs):+ seen.append(kwargs.get("llama_extra_args"))++ request = ValidateModelRequest(+ model_path = "someone/diffusion-gguf",+ llama_extra_args = ["--ctx-size", "8192"],+ )+ config = SimpleNamespace(+ identifier = "someone/diffusion-gguf",+ display_name = "diffusion-gguf",+ is_gguf = True,+ is_lora = False,+ is_vision = False,+ gguf_file = None,+ )+ with (+ patch.object(+ route,+ "_resolve_model_identifier_for_request",+ return_value = ("someone/diffusion-gguf", "someone/diffusion-gguf", False),+ ),+ patch.object(route.ModelConfig, "from_identifier", return_value = config),+ patch.object(+ route,+ "_resolve_inherited_extra_args",+ return_value = ["--ctx-size", "8192"],+ ),+ patch.object(route, "_classify_diffusion_gguf", return_value = diffusion_kind),+ patch.object(route, "_resolve_gguf_gpu_ids_for_request", new = _noop_gpu_ids),+ patch.object(route, "_effective_load_in_4bit", return_value = True),+ patch.object(route, "_guard_chat_load_against_training", new = _capture),+ ):+ asyncio.run(route.validate_model(request, current_subject = "test-user"))+ return seen++ def test_a_diffusion_gguf_is_estimated_without_them(self):+ route = _load_route_module("inf_route_diffusion_extra_args_1")+ self.assertEqual(self._validate(route, diffusion_kind = True), [[]])++ def test_an_ordinary_gguf_still_estimates_with_them(self):+ # The drop is narrow on purpose: this is the path the editor exists for, and+ # a --ctx-size here has to reach the estimate that approves the load.+ route = _load_route_module("inf_route_diffusion_extra_args_2")+ self.assertEqual(+ self._validate(route, diffusion_kind = False),+ [["--ctx-size", "8192"]],+ )++ def test_an_inconclusive_gguf_keeps_them(self):+ # None is "nothing to read yet", not "diffusion". Dropping on it would strip a+ # working override from an ordinary model whose header has not arrived.+ route = _load_route_module("inf_route_diffusion_extra_args_3")+ self.assertEqual(+ self._validate(route, diffusion_kind = None),+ [["--ctx-size", "8192"]],+ )+++class TestValidateJudgesTheListBeforeRewritingIt(unittest.TestCase):+ """The manual translation reads -ngl out of the extras and strips it, so it has to+ run AFTER the list has been validated: otherwise a spelling /load refuses is+ parsed and removed before validation sees it, and the switch is approved for a+ load that answers 400."""++ def _validate(+ self,+ route,+ *,+ extra_args,+ manual = True,+ ):+ request = ValidateModelRequest(+ model_path = "someone/gguf",+ llama_extra_args = extra_args,+ **({"gpu_memory_mode": "manual", "gpu_layers": 0} if manual else {}),+ )+ config = SimpleNamespace(+ identifier = "someone/gguf",+ display_name = "gguf",+ is_gguf = True,+ is_lora = False,+ is_vision = False,+ gguf_file = None,+ )+ with (+ patch.object(+ route,+ "_resolve_model_identifier_for_request",+ return_value = ("someone/gguf", "someone/gguf", False),+ ),+ patch.object(route.ModelConfig, "from_identifier", return_value = config),+ patch.object(route, "_resolve_inherited_extra_args", return_value = list(extra_args)),+ patch.object(route, "_classify_diffusion_gguf", return_value = False),+ patch.object(route, "_resolve_gguf_gpu_ids_for_request", new = _noop_gpu_ids),+ patch.object(route, "_effective_load_in_4bit", return_value = True),+ patch.object(route, "_guard_chat_load_against_training", new = lambda *a, **k: None),+ ):+ return asyncio.run(route.validate_model(request, current_subject = "test-user"))++ def test_an_attached_offload_spelling_is_refused_not_translated(self):+ # llama.cpp looks the whole token up in its option map, so "--gpu-layers=20"+ # is an argument it has never heard of; /load refuses the list. Translating+ # first read the 20, stripped the token, and approved the switch.+ from fastapi import HTTPException++ route = _load_route_module("inf_route_validate_order_1")+ with self.assertRaises(HTTPException) as caught:+ self._validate(route, extra_args = ["--gpu-layers=20"])+ self.assertEqual(caught.exception.status_code, 400)+ self.assertIn("two separate arguments", str(caught.exception.detail))++ def test_a_malformed_layer_count_is_a_refusal_not_a_crash(self):+ # parse_gpu_layers_override raises on a non-integer, and it used to run+ # before the try that turns a bad list into a 400, so this was a 500.+ from fastapi import HTTPException++ route = _load_route_module("inf_route_validate_order_2")+ with self.assertRaises(HTTPException) as caught:+ self._validate(route, extra_args = ["-ngl", "bad"])+ self.assertEqual(caught.exception.status_code, 400)++ def test_a_well_formed_list_still_passes(self):+ route = _load_route_module("inf_route_validate_order_3")+ response = self._validate(route, extra_args = ["-ngl", "20"])+ self.assertTrue(getattr(response, "valid", True))+++class TestValidateTranslatesManualNgl(unittest.TestCase):+ """Manual GPU memory owns the offload flags, and /load turns an explicit -ngl into+ the first-class field before stripping them. /validate has to do the same, or the+ call that APPROVES the switch is judging a different command than the one that runs:+ gpu_layers 0 with "-ngl 20" was approved as a load that places nothing on any device+ and cannot compete with training for VRAM, and then launched twenty layers on it."""++ def _validate(+ self,+ route,+ *,+ gpu_layers,+ extra_args,+ diffusion_kind = True,+ ):+ seen: list = []++ def _capture(_config, request, **kwargs):+ seen.append((request.gpu_layers, kwargs.get("llama_extra_args")))++ request = ValidateModelRequest(+ model_path = "someone/diffusion-gguf",+ llama_extra_args = extra_args,+ gpu_memory_mode = "manual",+ gpu_layers = gpu_layers,+ )+ config = SimpleNamespace(+ identifier = "someone/diffusion-gguf",+ display_name = "diffusion-gguf",+ is_gguf = True,+ is_lora = False,+ is_vision = False,+ gguf_file = None,+ )+ with (+ patch.object(+ route,+ "_resolve_model_identifier_for_request",+ return_value = ("someone/diffusion-gguf", "someone/diffusion-gguf", False),+ ),+ patch.object(route.ModelConfig, "from_identifier", return_value = config),+ patch.object(route, "_resolve_inherited_extra_args", return_value = list(extra_args)),+ patch.object(route, "_classify_diffusion_gguf", return_value = diffusion_kind),+ patch.object(route, "_resolve_gguf_gpu_ids_for_request", new = _noop_gpu_ids),+ patch.object(route, "_effective_load_in_4bit", return_value = True),+ patch.object(route, "_guard_chat_load_against_training", new = _capture),+ ):+ asyncio.run(route.validate_model(request, current_subject = "test-user"))+ return seen++ def test_an_explicit_layer_count_reaches_the_guard(self):+ route = _load_route_module("inf_route_manual_ngl_1")+ seen = self._validate(route, gpu_layers = 0, extra_args = ["-ngl", "20"])+ # The layer count the load will really run, and the raw flag stripped out of+ # the list exactly as /load strips it once it owns the field.+ self.assertEqual(seen, [(20, [])])++ def test_a_zero_layer_override_is_read_the_same_way(self):+ # The inverse pairing: asked for 20, overridden to 0. Judged as the CPU-only+ # load it is, rather than refused for VRAM it never takes.+ route = _load_route_module("inf_route_manual_ngl_2")+ seen = self._validate(route, gpu_layers = 20, extra_args = ["-ngl", "0"])+ self.assertEqual(seen, [(0, [])])++ def test_auto_mode_leaves_the_flag_alone(self):+ # Only manual mode owns these. In Auto the flag is a pass-through the loader+ # honours, so translating it here would invent a first-class value /load never set.+ route = _load_route_module("inf_route_manual_ngl_3")+ seen: list = []++ def _capture(_config, request, **kwargs):+ seen.append((request.gpu_layers, kwargs.get("llama_extra_args")))++ request = ValidateModelRequest(+ model_path = "someone/gguf",+ llama_extra_args = ["-ngl", "20"],+ )+ config = SimpleNamespace(+ identifier = "someone/gguf",+ display_name = "gguf",+ is_gguf = True,+ is_lora = False,+ is_vision = False,+ gguf_file = None,+ )+ with (+ patch.object(+ route,+ "_resolve_model_identifier_for_request",+ return_value = ("someone/gguf", "someone/gguf", False),+ ),+ patch.object(route.ModelConfig, "from_identifier", return_value = config),+ patch.object(route, "_resolve_inherited_extra_args", return_value = ["-ngl", "20"]),+ patch.object(route, "_classify_diffusion_gguf", return_value = False),+ patch.object(route, "_resolve_gguf_gpu_ids_for_request", new = _noop_gpu_ids),+ patch.object(route, "_effective_load_in_4bit", return_value = True),+ patch.object(route, "_guard_chat_load_against_training", new = _capture),+ ):+ asyncio.run(route.validate_model(request, current_subject = "test-user"))+ self.assertEqual(seen, [(request.gpu_layers, ["-ngl", "20"])])+++if __name__ == "__main__":+ unittest.main()+++class TestValidateRefusesWhatLoadWouldRefuse(unittest.TestCase):+ """The picker unloads the running model once /validate approves the switch, so a+ list /load would answer 400 on has to be refused here instead: a refusal leaves+ the current model alone, a failed switch does not."""++ def _validate(+ self,+ route,+ *,+ extra_args,+ n_parallel = None,+ diffusion_kind = False,+ ):+ request = ValidateModelRequest(+ model_path = "someone/gguf",+ llama_extra_args = extra_args,+ n_parallel = n_parallel,+ )+ config = SimpleNamespace(+ identifier = "someone/gguf",+ display_name = "gguf",+ is_gguf = True,+ is_lora = False,+ is_vision = False,+ gguf_file = None,+ )+ with (+ patch.object(+ route,+ "_resolve_model_identifier_for_request",+ return_value = ("someone/gguf", "someone/gguf", False),+ ),+ patch.object(route.ModelConfig, "from_identifier", return_value = config),+ patch.object(route, "_resolve_inherited_extra_args", return_value = extra_args),+ patch.object(route, "_classify_diffusion_gguf", return_value = diffusion_kind),+ patch.object(route, "_resolve_gguf_gpu_ids_for_request", new = _noop_gpu_ids),+ patch.object(route, "_effective_load_in_4bit", return_value = True),+ patch.object(route, "_effective_parallel_slots", side_effect = lambda n, **_: n),+ patch.object(route, "_guard_chat_load_against_training", new = lambda *a, **k: None),+ ):+ return asyncio.run(route.validate_model(request, current_subject = "test-user"))++ def test_a_denied_flag_is_refused_before_the_switch(self):+ route = _load_route_module("inf_route_validate_denies_1")+ with self.assertRaises(Exception) as caught:+ self._validate(route, extra_args = ["--agent"])+ self.assertEqual(getattr(caught.exception, "status_code", None), 400)+ self.assertIn("managed by Unsloth Studio", str(caught.exception.detail))++ def test_a_batch_below_the_slot_floor_is_refused_before_the_switch(self):+ route = _load_route_module("inf_route_validate_denies_2")+ with self.assertRaises(Exception) as caught:+ self._validate(route, extra_args = ["-b", "2"], n_parallel = 4)+ self.assertEqual(getattr(caught.exception, "status_code", None), 400)+ self.assertIn("aborts on --batch-size", str(caught.exception.detail))++ def test_a_list_the_load_would_accept_still_passes(self):+ route = _load_route_module("inf_route_validate_denies_3")+ resp = self._validate(route, extra_args = ["--numa", "distribute"], n_parallel = 4)+ self.assertTrue(resp.is_gguf)+++class TestEmbeddingSlotClampInTheBatchFloor(unittest.TestCase):+ """--embedding caps the batch at the micro-batch and llama-server aborts when that+ is below the slot count, so load_model reduces the slots to it before launching.+ A floor sized from the pre-clamp count refuses a command the launcher would run."""++ def _clamped(+ self,+ route,+ *,+ is_embedding,+ extra_args,+ slots = 4,+ **kwargs,+ ):+ config = SimpleNamespace(identifier = "someone/embed-gguf", gguf_file = None)+ with patch.object(route, "_is_embedding_gguf", return_value = is_embedding):+ return route._embedding_clamped_slots(+ config,+ slots,+ extra_args = extra_args,+ n_batch = kwargs.get("n_batch"),+ n_ubatch = kwargs.get("n_ubatch"),+ n_ctx = kwargs.get("n_ctx"),+ )++ def test_the_slots_follow_the_micro_batch_down(self):+ route = _load_route_module("inf_route_embed_clamp_1")+ self.assertEqual(+ self._clamped(route, is_embedding = True, extra_args = ["-b", "2", "-ub", "2"]),+ 2,+ )++ def test_a_chat_gguf_keeps_the_slots_it_asked_for(self):+ route = _load_route_module("inf_route_embed_clamp_2")+ self.assertEqual(+ self._clamped(route, is_embedding = False, extra_args = ["-b", "2", "-ub", "2"]),+ 4,+ )++ def test_defaults_clamp_nothing(self):+ # Nothing overrides the batch, so the launch runs llama.cpp's own 2048 and the+ # micro-batch is nowhere near the slot count.+ route = _load_route_module("inf_route_embed_clamp_3")+ self.assertEqual(+ self._clamped(route, is_embedding = True, extra_args = ["--numa", "distribute"]),+ 4,+ )++ def test_the_clamp_floors_at_one_slot(self):+ # "-b 0" resolves to a zero micro-batch, and --parallel 0 is rejected at arg+ # parse, which is the floor load_model applies too.+ route = _load_route_module("inf_route_embed_clamp_4")+ self.assertEqual(+ self._clamped(route, is_embedding = True, extra_args = ["-b", "0", "-ub", "0"]),+ 1,+ )++ def test_an_unreadable_header_leaves_the_refusal_alone(self):+ # _is_embedding_gguf answers False for a GGUF that is not on this disk yet, so+ # nothing is relaxed on a guess.+ route = _load_route_module("inf_route_embed_clamp_5")+ config = SimpleNamespace(identifier = "someone/gguf", gguf_file = None, gguf_hf_repo = None)+ self.assertFalse(route._is_embedding_gguf(config))+++class TestValidateAllowsTheEmbeddingClampedBatch(TestValidateRefusesWhatLoadWouldRefuse):+ """The preflight has to allow exactly what the load allows, or the picker refuses a+ switch the load it gates would have completed."""++ def test_an_embedding_gguf_may_batch_at_its_micro_batch(self):+ route = _load_route_module("inf_route_validate_embed_1")+ with patch.object(route, "_is_embedding_gguf", return_value = True):+ resp = self._validate(+ route,+ extra_args = ["-b", "2", "-ub", "2"],+ n_parallel = 4,+ )+ self.assertTrue(resp.is_gguf)++ def test_a_chat_gguf_is_still_refused(self):+ route = _load_route_module("inf_route_validate_embed_2")+ with (+ patch.object(route, "_is_embedding_gguf", return_value = False),+ self.assertRaises(Exception) as caught,+ ):+ self._validate(route, extra_args = ["-b", "2", "-ub", "2"], n_parallel = 4)+ self.assertEqual(getattr(caught.exception, "status_code", None), 400)+ self.assertIn("aborts on --batch-size", str(caught.exception.detail))++ def test_an_embedding_gguf_below_its_own_floor_is_still_refused(self):+ # The clamp floors at one slot, and llama-server aborts on a batch of 1 at any+ # slot count, so this is not a refusal the clamp may lift.+ route = _load_route_module("inf_route_validate_embed_3")+ with (+ patch.object(route, "_is_embedding_gguf", return_value = True),+ self.assertRaises(Exception) as caught,+ ):+ self._validate(route, extra_args = ["-b", "1", "-ub", "1"], n_parallel = 4)+ self.assertEqual(getattr(caught.exception, "status_code", None), 400)diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.pyindex 72db44dacdf..fb942060b02 100644--- a/studio/backend/utils/openai_auto_switch_settings.py+++ b/studio/backend/utils/openai_auto_switch_settings.py@@ -445,7 +445,9 @@ def _bounded_int(value: Any, *, minimum: int, maximum: int) -> Optional[int]:return parsed-def normalize_model_override(payload: dict[str, Any]) -> dict[str, Any]:+def normalize_model_override(+ payload: dict[str, Any], *, keep_empty_extra_args: bool = False+) -> dict[str, Any]:"""Validate one per-model launch config, dropping anything unusable.Silently drops rather than raising: an override is a convenience mirror of the@@ -453,12 +455,21 @@ def normalize_model_override(payload: dict[str, Any]) -> dict[str, Any]:from another host) must not block persisting the rest or fail the API load thatreads it. ``validate_extra_args`` is the caller's job -- it lives in thellama_server_args allow-list module, which this one must not import.++ ``keep_empty_extra_args`` keeps an explicit empty list, which is the difference+ between "this model has no launch flags" and "nothing is stored for this model".+ They are the same thing everywhere except under a fallback: a quant whose row is+ gone reads the bare repository row instead, so a cleared box would come back+ holding whatever that legacy row carries. Off by default, since a row saying only+ that is worth storing in exactly one case."""entry: dict[str, Any] = {}extra_args = payload.get("llama_extra_args")if isinstance(extra_args, (list, tuple)) and extra_args:entry["llama_extra_args"] = [str(arg) for arg in extra_args]+ elif keep_empty_extra_args and isinstance(extra_args, (list, tuple)):+ entry["llama_extra_args"] = []# 0 / negative means "unset"; the loader reads absence as the app default.for key in ("max_seq_length", "custom_context_length"):@@ -577,6 +588,23 @@ def model_override_load_kwargs(override: dict[str, Any], *, is_gguf: bool) -> dimax_seq_length = resolve_fit_max_seq_length(override, is_gguf = is_gguf)if max_seq_length is not None:kwargs["max_seq_length"] = max_seq_length+ stored_extra_args = override.get("llama_extra_args")+ if stored_extra_args:+ # Sanitized here because this is where stored data becomes a request: the+ # load treats an explicit list as the caller's own and refuses a managed+ # flag with a 400, so an override written before a name was denylisted would+ # break every auto-switch and idle reload of that model until someone+ # rewrote it by hand. The inheritance and settings-save paths do the same.+ from core.inference.llama_server_args import drop_managed_flags++ kept, dropped = drop_managed_flags(stored_extra_args)+ if dropped:+ from loggers import get_logger+ get_logger(__name__).warning(+ "model_override.dropped_managed_flags flags=%s", ", ".join(dropped)+ )+ override = {**override, "llama_extra_args": kept}+for source, target in (("llama_extra_args", "llama_extra_args"),("kv_cache_dtype", "cache_type_kv"),@@ -785,6 +813,57 @@ def _folded_override_matches(model_id: str, overrides: dict) -> list[str]:]+def override_lookup_candidates(+ load_id: str,+ alias_id: Optional[str] = None,+ variant: Optional[str] = None,+) -> list[str]:+ """The keys a load tries, in order, when looking for its stored override.++ Variant-qualified before bare, and the LOAD PATH before the advertised alias: the+ settings UI keys a local row by the path it loads from, while the alias is a+ derived id, so reading the alias first lets an older entry shadow a fresh save.+ An early build keyed a loose ``.gguf`` by its filename label, which is why the+ ``<path>:LABEL`` spelling is tried too.++ Shared so the auto-switch loader and anything showing the user what a load will+ apply cannot drift apart.+ """+ file_variant = None+ if not variant and load_id.lower().endswith(".gguf"):+ from hub.utils.gguf import extract_quant_label+ file_variant = extract_quant_label(os.path.basename(load_id))+ ordered = [+ f"{load_id}:{variant}" if variant else None,+ f"{alias_id}:{variant}" if alias_id and variant else None,+ load_id,+ f"{load_id}:{file_variant}" if file_variant else None,+ alias_id,+ ]+ seen: list[str] = []+ for key in ordered:+ if key and key not in seen:+ seen.append(key)+ return seen+++def resolve_override_for_load(+ load_id: str,+ alias_id: Optional[str] = None,+ variant: Optional[str] = None,+) -> tuple[Optional[str], dict]:+ """``(key, override)`` the load would apply, or ``(None, {})``.++ Resolution belongs here rather than in a client: the folding rules are Python's+ (casefold is not toLowerCase), and an ambiguous fold deliberately matches nothing.+ """+ for key in override_lookup_candidates(load_id, alias_id, variant):+ override = get_model_override(key)+ if override:+ return resolve_model_override_key(key) or key, override+ return None, {}++def resolve_model_override_key(model_id: str) -> Optional[str]:"""The stored key an override lookup for ``model_id`` would actually hit.@@ -873,6 +952,7 @@ def set_model_override(max_seq_length: Optional[int] = None,*,fill_absent_fields: bool = False,+ keep_empty_extra_args: bool = False,**config: Any,) -> dict:"""Upsert one model's launch config; a config with no usable fields removes it.@@ -891,7 +971,8 @@ def set_model_override(**config,"llama_extra_args": llama_extra_args,"max_seq_length": max_seq_length,- }+ },+ keep_empty_extra_args = keep_empty_extra_args,)from storage.studio_db import upsert_app_setting_map_entrydiff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 6f0dc4690b4..bc4c8729c93 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -19,6 +19,9 @@ import {import { isHiddenModelId } from "@/features/hub/lib/hidden-models";import { resolveInitialConfig } from "@/features/model-picker";import { isMlxId } from "@/features/model-picker/components/model-selector/recommended-fit";+import { loadManagedLlamaFlags } from "@/features/model-picker/api/llama-flags";+import { fetchLoadExtraArgs } from "@/features/model-picker/api/model-overrides";+import { sanitizeStoredExtraArgs } from "@/features/model-picker/model-config/llama-extra-args";import { usePlatformStore } from "@/config/env";import { projectHasSources } from "@/features/rag/api/rag-api";import {@@ -2732,6 +2735,58 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{})).isDiffusion;}+ // The stored override can live only on the server (written through the API, or+ // from another browser), and this config comes from local storage. Nothing is+ // resident at startup, so /load's omission path has nothing to inherit from, and+ // the model would come up without the arguments that were saved for it.+ //+ // Sanitized like every other hydration: this becomes an EXPLICIT list, which+ // /load validates strictly rather than putting through the carry-over paths that+ // drop a newly denied flag quietly.+ let resolvedExtraArgs = config.llamaExtraArgs;+ if (candidate.kind === "gguf" && !isDiffusion) {+ try {+ const managed = await loadManagedLlamaFlags();+ const clean = (tokens: readonly string[]) =>+ sanitizeStoredExtraArgs(tokens, managed?.managed ?? new Set<string>(), {+ maxBytes: managed?.maxBytes,+ windowsCommandBudget: managed?.windowsCommandBudget,+ });+ if (resolvedExtraArgs === undefined) {+ const stored = await fetchLoadExtraArgs(+ modelPath,+ // The advertised repository id as well as the path this load resolves+ // to: cached inventory can hand back a different loadId, and the row+ // was written under whichever of the two the user was looking at.+ candidate.id,+ candidate.ggufVariant ?? null,+ );+ if (stored.tokens.length > 0) {+ const cleaned = clean(stored.tokens);+ if (cleaned.length > 0) {+ resolvedExtraArgs = cleaned;+ }+ } else if (stored.explicit) {+ // A row carrying an EMPTY list is a cleared box, not an absent one, and+ // the difference decides what /load does: omitting the field lets it+ // carry the resident model's arguments over, which is what was cleared.+ resolvedExtraArgs = [];+ }+ } else if (resolvedExtraArgs !== null && resolvedExtraArgs.length > 0) {+ // The local copy gets the same treatment as the fetched one. It was+ // written by whatever build was running then, so a flag added to the+ // managed set since would be sent explicitly and answered with a 400,+ // and the remembered model would not come up at all.+ const cleaned = clean(resolvedExtraArgs);+ if (cleaned.length !== resolvedExtraArgs.length) {+ resolvedExtraArgs = cleaned.length > 0 ? cleaned : [];+ }+ }+ } catch {+ // An overrides outage must not stop a startup load: without this the model+ // comes up as it did before the feature existed.+ }+ }const effectiveTensorParallel = isDiffusion? false: config.tensorParallel;@@ -2784,6 +2839,11 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{// omitted when blank: a null counts as set and strips inherited -b / -ub...(config.nBatch != null ? { n_batch: config.nBatch } : {}),...(config.nUbatch != null ? { n_ubatch: config.nUbatch } : {}),+ // Checked with the same arguments the load below sends, or a list+ // the backend refuses would pass this gate and fail the launch.+ ...(resolvedExtraArgs !== undefined+ ? { llama_extra_args: resolvedExtraArgs ?? [] }+ : {}),}: {}),}))@@ -2829,6 +2889,14 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{n_parallel: config.nParallel ?? null,...(config.nBatch != null ? { n_batch: config.nBatch } : {}),...(config.nUbatch != null ? { n_ubatch: config.nUbatch } : {}),+ // Remembered pass-through arguments, for the same reason as the rest of+ // this block: nothing is resident at startup, so the omission path has+ // nothing to inherit them from and the model would come up without the+ // flags the user asked to be remembered. Undefined means this config+ // predates the field; a cleared list is an explicit none.+ ...(resolvedExtraArgs !== undefined+ ? { llama_extra_args: resolvedExtraArgs ?? [] }+ : {}),}: {}),}).catch((error: unknown) => {@@ -2932,6 +3000,15 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{loadedNBatch: committedNBatch,nUbatch: committedNUbatch,loadedNUbatch: committedNUbatch,+ // What this launch is running, for a later rollback. The status applier+ // cannot seed it: the model-loading lease is held for the whole of this+ // load, which is exactly the guard that stops a mid-switch poll writing+ // here. Without it an immediate switch snapshots the previous model's+ // list, and a failed switch restores this one with the wrong arguments.+ loadedLlamaExtraArgs:+ loadResp.requested_llama_extra_args !== undefined+ ? (loadResp.requested_llama_extra_args ?? [])+ : (resolvedExtraArgs ?? null),tensorParallel: loadResp.tensor_parallel ?? false,loadedTensorParallel: loadResp.tensor_parallel ?? false,...loadedGpuMemoryFields(loadResp),@@ -2968,6 +3045,9 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{loadedNBatch: null,nUbatch: null,loadedNUbatch: null,+ // Same reason, and the baseline has to be cleared rather than left: a+ // rollback to THIS model must not resend a GGUF's arguments.+ loadedLlamaExtraArgs: null,tensorParallel: loadResp.tensor_parallel ?? false,loadedTensorParallel: loadResp.tensor_parallel ?? false,// Non-GGUF response: clears any stale GPU baseline a prior manual-GPUdiff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex bfe6a89aeb2..768d6091eea 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -299,6 +299,12 @@ export async function validateModel(gpu_layers: payload.gpu_layers,// Slots scale the KV estimate; keep validate sized like the load.n_parallel: payload.n_parallel,+ // A --ctx-size or cache override in here changes the estimate, so a preflight+ // that dropped them would approve a different command from the one that runs.+ ...(payload.llama_extra_args !== undefined+ ? // biome-ignore lint/style/useNamingConvention: API schema+ { llama_extra_args: payload.llama_extra_args }+ : {}),// batch sizes scale the same estimate; omitted when blank so they never read as set...(payload.n_batch != null ? { n_batch: payload.n_batch } : {}),...(payload.n_ubatch != null ? { n_ubatch: payload.n_ubatch } : {}),diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 18bd9af89a7..76a3ba2997d 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -3238,13 +3238,16 @@ export function ChatPage({const previousConfig = currentRuntimePerModelConfig({includeMaxSeqLength: true,});- const hasAppliedConfig = applyModelLoadConfigToRuntime(- rememberedConfigFor(selection),- );+ const remembered = rememberedConfigFor(selection);+ const hasAppliedConfig = applyModelLoadConfigToRuntime(remembered);await selectModelRef.current({...selection,...(hasAppliedConfig ? { keepSpeculative: true } : {}),previousConfig,+ // As on the Hub launch: the runtime mirror carries no launch flags, and+ // the handoff arrives from training with another model resident (or+ // none), so there is nothing for /load to inherit them from.+ ...(remembered ? { config: remembered } : {}),});};if (targetLora) {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 ce5a95d9bf8..024828f95f8 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@@ -74,6 +74,7 @@ import {normalizeMaxSeqLength,type PerModelConfig,} from "@/features/model-picker";+import { invalidateLlamaFlagCatalog } from "@/features/model-picker/api/llama-flags";import type {ChatLoraSummary,ChatModelSummary,@@ -422,6 +423,9 @@ async function syncInferenceStatusToStore(options?: {* the refresh below leaves it intact.*/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.+ invalidateLlamaFlagCatalog();if (!isExternalModelId(useChatRuntimeStore.getState().params.checkpoint)) {useChatRuntimeStore.getState().clearCheckpoint();}@@ -988,6 +992,11 @@ export function useChatModelRuntime() {pendingLoadConfig?.specDraftNMax ?? stateBeforeUnload.specDraftNMax;let loadNParallel =pendingLoadConfig?.nParallel ?? stateBeforeUnload.nParallel;+ // No store fallback and no reset with the rest below: undefined means+ // "this config never read them", and the route preserves the stored+ // flags when the field is omitted. Falling back to another model's+ // value, or to null, would clear flags the user set elsewhere.+ const loadLlamaExtraArgs = pendingLoadConfig?.llamaExtraArgs;let loadNBatch =pendingLoadConfig?.nBatch ?? stateBeforeUnload.nBatch;let loadNUbatch =@@ -1075,6 +1084,14 @@ export function useChatModelRuntime() {...(validateNUbatch != null? { n_ubatch: validateNUbatch }: {}),+ // The same list the load below sends. A --ctx-size or cache+ // override in here changes the memory this preflight estimates,+ // so omitting it approves a different command: during training+ // that means approving the switch, unloading the resident model,+ // and having /load refuse the target with the real arguments.+ ...(!targetIsDiffusion && loadLlamaExtraArgs !== undefined+ ? { llama_extra_args: loadLlamaExtraArgs ?? [] }+ : {}),}: {}),});@@ -1272,6 +1289,14 @@ export function useChatModelRuntime() {spec_draft_n_max: loadSpecDraftNMax,// GGUF-only: slots mean nothing for a transformers load.n_parallel: isGguf ? loadNParallel : null,+ // Sent only once known, and [] is the explicit "launch with none":+ // the flags are llama-server's, so a transformers load never carries+ // them, and neither does a diffusion GGUF: that one is GGUF-shaped but+ // runs through the visual runner, which builds its command without+ // these, so sending them would record arguments the process never got.+ ...(isGguf && !targetIsDiffusion && loadLlamaExtraArgs !== undefined+ ? { llama_extra_args: loadLlamaExtraArgs ?? [] }+ : {}),// omitted when blank: a null counts as set and strips inherited -b / -ub...(isGguf && loadNBatch != null ? { n_batch: loadNBatch } : {}),...(isGguf && loadNUbatch != null@@ -1446,6 +1471,30 @@ export function useChatModelRuntime() {loadedNParallel: committedSlots,nBatch: committedNBatch,loadedNBatch: committedNBatch,+ // 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 as null: the+ // rollback sends this field only when it has one, and omitting it is+ // what makes /load inherit, so a model that was launched with no+ // extras would come back carrying the arguments of the load that just+ // failed. null stays for "we were never told".+ //+ // The server's own echo first, since it is the only account of what+ // the launch actually carried: a reload that omits the field but sets+ // max_seq_length has its inherited --ctx-size stripped before launch,+ // and the status refresh that would notice runs while modelLoading is+ // still true and reseeds nothing. Without this the next rollback+ // resent a flag the successful reload had removed.+ loadedLlamaExtraArgs:+ loadResponse.requested_llama_extra_args !== undefined+ ? (loadResponse.requested_llama_extra_args ?? [])+ : loadLlamaExtraArgs !== undefined+ ? (loadLlamaExtraArgs ?? [])+ : resetsPerModelSettings+ ? null+ : (stateBeforeUnload.loadedLlamaExtraArgs ?? null),nUbatch: committedNUbatch,loadedNUbatch: committedNUbatch,customContextLength: keepCustomCtx,@@ -1570,6 +1619,13 @@ export function useChatModelRuntime() {...(stateBeforeUnload.loadedNUbatch != null? { n_ubatch: stateBeforeUnload.loadedNUbatch }: {}),+ // Explicit, unlike the batch pair above: the failed switch left the+ // TARGET resident, so an omitted field here inherits across models,+ // which the route refuses, and the previous model would come back+ // without the arguments it was running.+ ...(stateBeforeUnload.loadedLlamaExtraArgs != null+ ? { llama_extra_args: stateBeforeUnload.loadedLlamaExtraArgs }+ : {}),// Restore the previous model in the split mode it was running,// not the default layer split.tensor_parallel: stateBeforeUnload.loadedTensorParallel ?? false,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 a311c30f444..575f470126b 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@@ -456,6 +456,25 @@ export function applyActiveModelStatusToStore(rememberedNParallel === status.requested_parallel_slots && {nParallel: rememberedNParallel,}),+ // What the running server was actually invoked with. Without this a tab opened+ // while a model was already loaded knows nothing about its pass-through+ // arguments (the switch path is where they were recorded), and a rollback after+ // a failed switch restores that model without them: the failed target is left+ // resident, so an omitted field cannot inherit across models either.+ //+ // Adopted from every settled status, not only a first read or a model change:+ // another tab or an API client can reload the SAME model and variant with+ // different arguments, or with none, and a baseline pinned at the first read+ // would resend the old list from the rollback path and resurrect arguments that+ // are not running. seedLoadParams is the guard that matters here, and it is the+ // same one the rest of this block uses: while a load is in flight performLoad+ // owns these values, so a poll that answers mid-switch cannot overwrite them.+ // A backend that does not publish the field changes nothing.+ ...(status.requested_llama_extra_args !== undefined &&+ (status.is_gguf ?? true) &&+ seedLoadParams && {+ loadedLlamaExtraArgs: status.requested_llama_extra_args ?? null,+ }),// one rule per batch pair, see resolveBatchSizeSeed...("loaded" in nBatchSeed && { loadedNBatch: nBatchSeed.loaded ?? null }),...("value" in nBatchSeed && { nBatch: nBatchSeed.value ?? null }),diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 86fb1322234..201041a5b3b 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -95,6 +95,9 @@ import {resolveInitialConfig,type PerModelConfig,} from "@/features/model-picker";+import { loadManagedLlamaFlags } from "@/features/model-picker/api/llama-flags";+import { fetchLoadExtraArgs } from "@/features/model-picker/api/model-overrides";+import { sanitizeStoredExtraArgs } from "@/features/model-picker/model-config/llama-extra-args";import {confirmTransformersUpgradeIfNeeded,useTransformersUpgradeDialogStore,@@ -1265,6 +1268,62 @@ export function SharedComposer({resolvedIsDiffusion = staged.isDiffusion;diffusionUnknown = staged.diffusionUnknown;}+ // Pass-through arguments can live only in the server's override map (set+ // through the API, or from another browser), and this config comes from+ // local storage. /load's omission path inherits them from a RESIDENT+ // instance of the same model, which a compare pane starting cold or+ // switching away from the other model does not have, so without this the+ // experiment runs a different command from the one that was saved.+ if (+ targetIsGguf &&+ // Not for the diffusion runner, which appends none of them.+ resolvedIsDiffusion !== true+ ) {+ try {+ // Sanitised for the same reason the panel sanitises what it hydrates:+ // either list becomes an EXPLICIT /load argument, which is 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, whether the list came from the server or from this+ // browser's own storage.+ const managed = await loadManagedLlamaFlags();+ const clean = (tokens: readonly string[]) =>+ sanitizeStoredExtraArgs(+ tokens,+ managed?.managed ?? new Set<string>(),+ {+ maxBytes: managed?.maxBytes,+ windowsCommandBudget: managed?.windowsCommandBudget,+ },+ );+ const local = ownConfig.llamaExtraArgs;+ if (local === undefined) {+ const resolvedArgs = await fetchLoadExtraArgs(+ sel.id,+ sel.id,+ sel.ggufVariant ?? null,+ );+ const cleaned = clean(resolvedArgs.tokens);+ if (cleaned.length > 0) {+ ownConfig.llamaExtraArgs = cleaned;+ } else if (resolvedArgs.explicit) {+ // An explicit empty row is a cleared box, and this pane has to send+ // it as one: left undefined the field is omitted and /load carries+ // the resident model's arguments into the comparison, so the panes+ // would not be running the command they are compared on.+ ownConfig.llamaExtraArgs = [];+ }+ } else if (local !== null && local.length > 0) {+ const cleaned = clean(local);+ if (cleaned.length !== local.length) {+ ownConfig.llamaExtraArgs = cleaned.length > 0 ? cleaned : [];+ }+ }+ } catch {+ // The load still works; a real overrides outage surfaces there.+ }+ }// Mirror single-view resolveLoadMaxSeqLength: 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.@@ -1369,6 +1428,12 @@ export function SharedComposer({gpu_layers: effectiveGpuLayers,// Slots scale the KV estimate; keep validate sized like the load.n_parallel: ownConfig.nParallel ?? null,+ // Only when this panel has read the stored value: omitted, the load+ // inherits it, which is what keeps CLI-set flags working.+ ...(ownConfig.llamaExtraArgs !== undefined+ ? // biome-ignore lint/style/useNamingConvention: API schema+ { llama_extra_args: ownConfig.llamaExtraArgs ?? [] }+ : {}),// omitted when blank: a null counts as set and strips inherited -b / -ub...(ownConfig.nBatch != null? { n_batch: ownConfig.nBatch }@@ -1451,6 +1516,12 @@ export function SharedComposer({tensor_split: compareLoadKnobs.splitRatio ?? undefined,gpu_ids: effectiveSelectedGpuIds ?? undefined,n_parallel: ownConfig.nParallel ?? null,+ // Only when this panel has read the stored value: omitted, the load+ // inherits it, which is what keeps CLI-set flags working.+ ...(ownConfig.llamaExtraArgs !== undefined+ ? // biome-ignore lint/style/useNamingConvention: API schema+ { llama_extra_args: ownConfig.llamaExtraArgs ?? [] }+ : {}),...(ownConfig.nBatch != null? { n_batch: ownConfig.nBatch }: {}),@@ -1519,6 +1590,13 @@ export function SharedComposer({loadedNBatch: committedNBatch,nUbatch: committedNUbatch,loadedNUbatch: committedNUbatch,+ // What this pane's launch is running, for a later rollback: the status+ // applier is held off for the whole load, so nothing else records it, and+ // a switch straight after would snapshot the other model's list.+ loadedLlamaExtraArgs:+ resp.requested_llama_extra_args !== undefined+ ? (resp.requested_llama_extra_args ?? [])+ : (ownConfig.llamaExtraArgs ?? null),tensorParallel: resp.tensor_parallel ?? false,loadedTensorParallel: resp.tensor_parallel ?? false,defaultChatTemplate: resp.chat_template ?? null,diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 339a0abb340..0639cf24ccb 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -1360,6 +1360,15 @@ type ChatRuntimeStore = {nBatch: number | null;/** batch size the last successful load sent (null = default) */loadedNBatch: number | null;+ /**+ * Pass-through llama-server arguments the resident model is running, as far as+ * this client knows (null = none, or never told). Kept so a rollback after a+ * failed switch can put the previous model back with them: by then the target+ * load has already replaced the backend's inheritance source, so omitting the+ * field on that rollback reads as a cross-model pickup and restores the model+ * without the arguments it was running.+ */+ 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) */@@ -2065,6 +2074,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({loadedNParallel: null,nBatch: null,loadedNBatch: null,+ loadedLlamaExtraArgs: null,nUbatch: null,loadedNUbatch: null,tensorParallel: false,@@ -2557,6 +2567,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({loadedNParallel: null,nBatch: null,loadedNBatch: null,+ loadedLlamaExtraArgs: null,nUbatch: null,loadedNUbatch: null,tensorParallel: false,diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex e9682709910..2e8816d0767 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -83,6 +83,14 @@ export interface LoadModelRequest {n_batch?: number | null;/** prompt micro-batch size (--ubatch-size), 1..65536; omit/null = llama.cpp default 512, capped at the batch size */n_ubatch?: number | null;+ /**+ * Pass-through llama-server args, one argv token per entry, appended after+ * Unsloth's own flags so llama.cpp's last-wins parser takes these. Flags Unsloth+ * manages are refused with a 4xx naming the flag. Omit/null inherits the stored+ * per-model value; [] launches with none. GGUF only.+ */+ // biome-ignore lint/style/useNamingConvention: API schema+ llama_extra_args?: string[] | null;/*** Split the model across GPUs by tensor (--split-mode tensor) instead* of by layer for GGUF models. Multi-GPU only; no effect on a single GPU.@@ -258,6 +266,8 @@ export interface LoadModelResponse {requested_n_batch?: number | null;/** micro-batch size (--ubatch-size) the load was invoked with; null = default */requested_n_ubatch?: number | null;+ /** Pass-through llama-server arguments the running load was invoked with. */+ requested_llama_extra_args?: string[] | null;}export interface UnloadModelRequest {@@ -345,6 +355,8 @@ export interface InferenceStatusResponse {requested_n_batch?: number | null;/** micro-batch size (--ubatch-size) the active load was invoked with; null = default */requested_n_ubatch?: number | null;+ /** Pass-through llama-server arguments the running load was invoked with. */+ requested_llama_extra_args?: string[] | null;n_layers?: number | null;/** Model's MoE expert-layer count (the n_cpu_moe ceiling); 0 if not MoE. */n_moe_layers?: number;diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsxindex 68c5b3d69c3..287bfc738b6 100644--- a/studio/frontend/src/features/hub/hub-page.tsx+++ b/studio/frontend/src/features/hub/hub-page.tsx@@ -1335,6 +1335,11 @@ export function ModelsPage() {keepSpeculative: hasAppliedConfig,throwOnError: true,previousConfig,+ // The runtime store is not enough: applyPerModelConfigToRuntime has no field+ // for the launch flags, and /load only inherits them from the SAME resident+ // model, so a cold launch or a switch from another model ran without the+ // arguments this model was remembered with.+ ...(rememberedConfig ? { config: rememberedConfig } : {}),}).then(() => {// Read fresh: the load is async, so the checkpoint may have changed.@@ -1483,6 +1488,11 @@ export function ModelsPage() {isLora: target.meta.isLora,keepSpeculative: true,forceReload: true,+ // The submitted config, not only its echo in the runtime store: the store+ // does not carry llamaExtraArgs, so without this the load omits the field+ // and the route keeps the resident server's old list. Applying an edit, or+ // clearing the box, would then do nothing on this page.+ config,previousConfig,}).catch(() => undefined);},diff --git a/studio/frontend/src/features/model-picker/api/llama-flags.ts b/studio/frontend/src/features/model-picker/api/llama-flags.tsnew file mode 100644index 00000000000..8a1378dd9b1--- /dev/null+++ b/studio/frontend/src/features/model-picker/api/llama-flags.ts@@ -0,0 +1,248 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";++/** What the installed llama-server accepts, for checking pass-through args. */+export type LlamaFlagCatalog = {+ /** Flag name -> its help text. Empty when the probe failed. */+ flags: Record<string, string>;+ /** Flags Unsloth manages; the load refuses these outright. */+ managed: ReadonlySet<string>;+ /** Flags this build documents as taking no value ("--verbose", "--jinja"). */+ switches: ReadonlySet<string>;+ /** Size limit this host applies, which is smaller on Windows. */+ maxBytes: number;+ /**+ * Characters the quoted command may take on Windows, or 0 elsewhere. Mirrored+ * because the quoting can double a backslash-heavy value, so bytes alone do not+ * say whether the launch will fit.+ */+ windowsCommandBudget: number;+ /**+ * Slots a load gets when it names none, the server-wide --parallel. Needed to+ * judge a pass-through --batch-size: llama-server aborts on a batch below the+ * slots it serves, and with the Slots field blank this is what the launch uses.+ */+ defaultParallelSlots: number;+ /**+ * True when this build serves ONE slot however many are asked for (no+ * --kv-unified, so load_model falls back). defaultParallelSlots is already+ * effective, but an EXPLICIT Slots value chosen in this panel is not, and sizing+ * the batch floor from it refuses a --batch-size the backend accepts.+ */+ parallelSlotsClamped: boolean;+ /**+ * False when `--help` could not be read. Nothing may then be reported as a typo:+ * an unverifiable flag is not a wrong one.+ */+ probeOk: boolean;+};++type ApiLlamaFlagCatalog = {+ flags?: Record<string, string>;+ managed?: string[];+ // biome-ignore lint/style/useNamingConvention: API schema+ switch_flags?: string[];+ // biome-ignore lint/style/useNamingConvention: API schema+ max_bytes?: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ windows_command_budget?: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ default_parallel_slots?: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ parallel_slots_clamped?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ probe_ok?: boolean;+};++// Describes the binary, so it is worth caching: several rows can mount at once and+// none of them should pay a separate probe. Not for the whole session though. A+// llama.cpp update and a backend switch (CUDA to Vulkan, say) both replace the+// binary in place while the tab stays open, and the flag list moves with it, so a+// session-long cache would keep reporting a newly added flag as unknown. A minute+// is short enough that nobody meets that, and long enough that a panel being opened+// and closed does not re-ask. The backend keys its own cache on the binary's+// revision, so a repeat read is a dict lookup and not another --help.+const CATALOG_TTL_MS = 60_000;+let inFlightCatalog: Promise<LlamaFlagCatalog | null> | null = null;+let cachedCatalog: LlamaFlagCatalog | null = null;+let cachedAt = 0;+// Bumped by every invalidation. A read that started before the binary changed is+// describing the old one, so it must neither be cached nor handed to a caller that+// asked after the change: without this the stale promise is reused by the next call+// and writes the previous backend's flags back for the whole TTL.+let catalogGeneration = 0;++/** What a caller gets without paying for the --help probe. */+export type LlamaManagedFlags = {+ managed: ReadonlySet<string>;+ maxBytes: number;+ windowsCommandBudget: number;+ defaultParallelSlots: number;+ /**+ * True when this build serves ONE slot however many are asked for (no+ * --kv-unified, so load_model falls back). defaultParallelSlots is already+ * effective, but an EXPLICIT Slots value chosen in this panel is not, and sizing+ * the batch floor from it refuses a --batch-size the backend accepts.+ */+ parallelSlotsClamped: boolean;+};++let inFlightManaged: Promise<LlamaManagedFlags | null> | null = null;+let cachedManaged: LlamaManagedFlags | null = null;++const catalogListeners = new Set<() => void>();++/**+ * Told when the catalogue is invalidated, for a consumer holding one in state.+ *+ * Clearing the module cache is not enough for a row that already read it: updating+ * llama.cpp from the banner replaces the binary while the panel stays mounted, and+ * the row would go on judging arity against the old build's help until the section+ * is closed and reopened.+ */+export function subscribeLlamaFlagCatalog(listener: () => void): () => void {+ catalogListeners.add(listener);+ return () => {+ catalogListeners.delete(listener);+ };+}++/** Drop the cache, for a caller that knows the binary just changed. */+export function invalidateLlamaFlagCatalog(): void {+ cachedCatalog = null;+ cachedAt = 0;+ catalogGeneration += 1;+ // Dropped as well as cleared: a request already on the wire answers for the+ // binary that has just been replaced.+ inFlightCatalog = null;+ // The managed answer too. Its denylist is Unsloth's own and no binary changes it,+ // but it carries defaultParallelSlots beside it, and that is the EFFECTIVE count:+ // a build without --kv-unified serves one slot however many are configured. A tab+ // that had already fetched it went on sizing the hidden hydration check's batch+ // floor from the previous backend, letting "--batch-size 2" through on a build+ // that now serves four slots, or refusing it after a clamp to one.+ cachedManaged = null;+ inFlightManaged = null;+ for (const listener of catalogListeners) {+ listener();+ }+}++/**+ * Just the flags Unsloth refuses, without the `--help` probe behind the catalogue.+ *+ * The panel sanitizes a stored list with this before turning it into an explicit+ * request, and that must not wait on a cold probe (up to ten seconds), or a flag+ * denied since the list was saved stays in the request for as long as it runs.+ * Cached for the session: unlike the flag map, it describes this build of Studio.+ */+export function loadManagedLlamaFlags(): Promise<LlamaManagedFlags | null> {+ if (cachedManaged) {+ return Promise.resolve(cachedManaged);+ }+ if (cachedCatalog) {+ return Promise.resolve(cachedCatalog);+ }+ // Read before the request goes out, and checked before its answer is published,+ // exactly as the full catalogue does. The denylist in this answer is Unsloth's own+ // and no binary changes it, but defaultParallelSlots beside it is the EFFECTIVE+ // count, which depends on the probed binary: a request already on the wire when+ // llama.cpp is replaced would otherwise repopulate the cache the invalidation had+ // just cleared, and keep the old build's slot floor for the rest of the session.+ const generation = catalogGeneration;+ inFlightManaged ??= (async () => {+ try {+ const res = await authFetch(+ "/api/inference/llama-flags?managed_only=true",+ );+ if (!res.ok) {+ return null;+ }+ const body = (await res.json()) as ApiLlamaFlagCatalog;+ // An older backend answers the route without the parameter and returns its+ // full catalogue, which carries the same list.+ const managed: LlamaManagedFlags = {+ managed: new Set(body.managed ?? []),+ maxBytes: body.max_bytes ?? 0,+ windowsCommandBudget: body.windows_command_budget ?? 0,+ // 0 on a backend that predates the field, which reads as "not known" and+ // leaves the editor's own hard floor of 2 in charge.+ defaultParallelSlots: body.default_parallel_slots ?? 0,+ // Absent on a backend that predates the field, and false is the safe read:+ // the floor then follows the asked-for count, exactly as it did before.+ parallelSlotsClamped: Boolean(body.parallel_slots_clamped),+ };+ if (generation !== catalogGeneration) {+ // The binary changed while this was in flight: answer "cannot verify"+ // rather than the old build's limits, and cache nothing.+ return null;+ }+ cachedManaged = managed;+ return cachedManaged;+ } catch {+ return null;+ } finally {+ // Only if it is still ours: an invalidation may have cleared it already, and+ // a later call may have started its own.+ if (generation === catalogGeneration) {+ inFlightManaged = null;+ }+ }+ })();+ return inFlightManaged;+}++/**+ * Read the flag catalogue, or null when this backend has no such route.+ *+ * Null and `probeOk: false` mean the same thing to the caller (cannot verify), but+ * they are kept apart so an older backend is not reported as a broken llama.cpp.+ */+export function loadLlamaFlagCatalog(): Promise<LlamaFlagCatalog | null> {+ if (cachedCatalog && Date.now() - cachedAt < CATALOG_TTL_MS) {+ return Promise.resolve(cachedCatalog);+ }+ const generation = catalogGeneration;+ inFlightCatalog ??= (async () => {+ try {+ const res = await authFetch("/api/inference/llama-flags");+ if (!res.ok) {+ return null;+ }+ const body = (await res.json()) as ApiLlamaFlagCatalog;+ const catalog: LlamaFlagCatalog = {+ flags: body.flags ?? {},+ managed: new Set(body.managed ?? []),+ switches: new Set(body.switch_flags ?? []),+ // An older backend sends neither, and 0 reads as "no limit of my own",+ // leaving the editor's own default in charge.+ maxBytes: body.max_bytes ?? 0,+ windowsCommandBudget: body.windows_command_budget ?? 0,+ // 0 on a backend that predates the field, which reads as "not known" and+ // leaves the editor's own hard floor of 2 in charge.+ defaultParallelSlots: body.default_parallel_slots ?? 0,+ parallelSlotsClamped: Boolean(body.parallel_slots_clamped),+ probeOk: Boolean(body.probe_ok),+ };+ if (generation !== catalogGeneration) {+ // The binary changed while this was in flight: answer the caller with+ // "cannot verify" rather than the old build's flags, and cache nothing.+ return null;+ }+ cachedCatalog = catalog;+ cachedAt = Date.now();+ return catalog;+ } catch {+ return null;+ } finally {+ // Only if it is still ours: an invalidation may have cleared it already, and+ // a later call may have started its own.+ if (generation === catalogGeneration) {+ inFlightCatalog = null;+ }+ }+ })();+ return inFlightCatalog;+}diff --git a/studio/frontend/src/features/model-picker/api/model-overrides.ts b/studio/frontend/src/features/model-picker/api/model-overrides.tsindex 18a5fa58b23..f717791831a 100644--- a/studio/frontend/src/features/model-picker/api/model-overrides.ts+++ b/studio/frontend/src/features/model-picker/api/model-overrides.ts@@ -10,6 +10,7 @@ import { readFastApiError } from "@/lib/format-fastapi-error";import {normalizeGgufVariantIdentity,normalizeModelIdentity,+ splitQuantSuffix,} from "../model-config/model-identity";import type { PerModelConfig } from "../model-config/per-model-config";@@ -65,6 +66,130 @@ export function modelOverrideKey(return ggufVariant ? `${modelId}:${ggufVariant}` : modelId;}+/**+ * The stored pass-through args for a model, under any key the backend would resolve.+ *+ * The overrides route folds identities before it reads a row: a repo id and a quant+ * differing only in case resolve to the same entry, and it falls back from+ * `repo:QUANT` to the bare repo. A literal lookup on the two keys this panel happens+ * to use would show an empty box for a model that will launch with arguments, and+ * the first edit would then replace a list nobody saw. Keys are tried most specific+ * first, then folded, mirroring that order.+ */+/**+ * A path that names one file whatever the casing, folded for comparison, or null+ * when the path is case-sensitive.+ *+ * The rules are _fold_case_insensitive_path's, and they have to be, because the+ * server applies an override this resolver has to find: a Windows drive path, a UNC+ * share and a WSL drive mount all fold, the separator is interchangeable, and+ * trailing separators are trimmed down to the root. A POSIX path is not folded, or+ * "/models/Foo.gguf" would collect the arguments stored for "/models/foo.gguf".+ */+const WINDOWS_DRIVE_PATH = /^[a-zA-Z]:[\\/]/;+const WSL_DRIVE_PATH = /^\/mnt\/[a-zA-Z](\/|$)/;++function foldCaseInsensitivePath(key: string): string | null {+ const slashed = key.replace(/\\/g, "/");+ let minimum: number;+ if (WINDOWS_DRIVE_PATH.test(key)) {+ minimum = 3;+ } else if (slashed.startsWith("//")) {+ minimum = 2;+ } else if (WSL_DRIVE_PATH.test(slashed)) {+ minimum = 6;+ } else {+ return null;+ }+ let trimmed = slashed;+ while (trimmed.length > minimum && trimmed.endsWith("/")) {+ trimmed = trimmed.slice(0, -1);+ }+ return trimmed.toLowerCase();+}++function foldOverrideKey(key: string): string {+ // A path that folds does so whole, separators and casing together.+ const path = foldCaseInsensitivePath(key);+ if (path !== null) {+ 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". This is the check+ // the backend's split_quant_suffix makes.+ const split = splitQuantSuffix(key);+ const id = split ? split[0] : key;+ const quant = split ? `:${split[1].toLowerCase()}` : "";+ // A POSIX path keeps its case; only the quant folds, because the browser+ // lowercases that before storing. A repo id folds whole.+ return id.startsWith("/") ? `${id}${quant}` : `${id.toLowerCase()}${quant}`;+}++/**+ * The stored arguments, with "the row carried an empty list" kept apart from "no+ * row carried the field at all".+ *+ * The distinction is what the settings page's tombstone is for: clearing the box+ * for one quant saves an explicit [], and that is what stops the server's lookup+ * before it reaches a legacy bare-repository row that still holds arguments.+ * Collapsing the two left the panel with llamaExtraArgs undefined, its next Load+ * omitted the field, and /load carried the resident model's arguments over: the+ * very ones that had just been cleared.+ */+export type ResolvedExtraArgs = {+ tokens: string[];+ explicit: boolean;+};++/** The field as one entry stores it, empty list and absent field kept apart. */+function resolvedFrom(entry: ApiModelOverride): ResolvedExtraArgs {+ const tokens = entry.llama_extra_args;+ return { tokens: tokens ?? [], explicit: Array.isArray(tokens) };+}++export function resolveStoredExtraArgs(+ overrides: ApiModelOverrides,+ keys: readonly string[],+): ResolvedExtraArgs {+ // Whole ENTRIES, in the order the backend tries them, stopping at the first one+ // that exists. The auto-switch loader breaks on the first non-empty override and+ // reads its fields from there, so falling through to a bare repo id because the+ // variant row happens to carry no arguments would launch the picker with flags an+ // API load would not use.+ // An entry with no fields is skipped rather than stopping the search, because+ // that is what `if override: break` does on the server.+ const present = (value: ApiModelOverride | undefined | null) =>+ value && Object.keys(value).length > 0 ? value : null;+ const folded = new Map<string, ApiModelOverride | null>();+ for (const [key, value] of Object.entries(overrides)) {+ if (!present(value)) {+ continue;+ }+ const foldedKey = foldOverrideKey(key);+ // Ambiguous folds resolve to nothing, as resolve_model_override_key does:+ // duplicate case variants left by an upgrade must not have one of them picked+ // at enumeration order, which is another model's settings half the time.+ folded.set(foldedKey, folded.has(foldedKey) ? null : value);+ }+ for (const key of keys) {+ const exact = present(overrides[key]);+ if (exact) {+ return resolvedFrom(exact);+ }+ // Folding, by the same rule the backend resolves with: a POSIX path is+ // case-sensitive, so lowercasing one whole would hand /models/foo.gguf the+ // arguments stored for /models/Foo.gguf and then send them explicitly on Load.+ // Windows, UNC and WSL paths do fold, and so does the quant suffix the browser+ // lowercases before storing.+ const match = folded.get(foldOverrideKey(key));+ if (match) {+ return resolvedFrom(match);+ }+ }+ return { tokens: [], explicit: false };+}+export async function fetchModelOverrides(): Promise<ApiModelOverrides> {const res = await authFetch(OVERRIDES_URL);if (!res.ok) {@@ -76,6 +201,64 @@ export async function fetchModelOverrides(): Promise<ApiModelOverrides> {return body.overrides ?? {};}+/**+ * The pass-through arguments the LOAD of this model would apply.+ *+ * Asked of the server rather than worked out here, because the resolution is+ * Python's: casefold is not toLowerCase (Straße and STRASSE are one path to the+ * loader and two to a browser), and an ambiguous fold deliberately matches nothing.+ * A client mirroring those rules can only approximate them, and the approximation+ * shows up as a cold load launching without arguments an API load applies.+ *+ * Falls back to resolving locally against the whole map when the backend predates+ * the parameter, which is the same answer in every case but the exotic ones.+ */+export async function fetchLoadExtraArgs(+ loadId: string,+ aliasId: string,+ ggufVariant?: string | null,+ fallbackKeys: readonly string[] = [],+): Promise<ResolvedExtraArgs> {+ const query = new URLSearchParams({ model_id: loadId, alias_id: aliasId });+ if (ggufVariant) {+ query.set("gguf_variant", ggufVariant);+ }+ const res = await authFetch(`${OVERRIDES_URL}?${query.toString()}`);+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, "Failed to load saved model settings"),+ );+ }+ const body = (await res.json()) as {+ overrides?: ApiModelOverrides;+ resolved?: ApiModelOverride | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ resolved_key?: string | null;+ };+ if (body.resolved !== undefined) {+ // An explicit empty list is a cleared box, not an absence, and the caller has+ // to send it as one: omitting the field lets /load carry the resident model's+ // arguments over, which is exactly what was cleared.+ return resolvedFrom(body.resolved ?? {});+ }+ // A backend that predates the resolved field answers with the whole map, and the+ // caller has to say which keys to look under. Derived here when it did not: the+ // panel passes its own richer list (it knows the alias the settings page used),+ // while the auto-load and compare callers have only these two identities, and+ // defaulting to none made them read an empty map and launch without the stored+ // arguments against an older server.+ const derived =+ fallbackKeys.length > 0+ ? fallbackKeys+ : [+ modelOverrideKey(loadId, ggufVariant),+ modelOverrideKey(aliasId, ggufVariant),+ loadId,+ aliasId,+ ].filter((key, index, all) => all.indexOf(key) === index);+ return resolveStoredExtraArgs(body.overrides ?? {}, derived);+}+/*** Translate the UI's per-model config into the backend's schema. Only fields the user set are* sent: an absent field reads as "app default", so nulls would pin defaults and stop the model@@ -124,6 +307,13 @@ export function toApiOverride(config: PerModelConfig | null): ApiModelOverride {if (config.chatTemplateOverride?.trim()) {payload.chat_template_override = config.chatTemplateOverride;}+ // The one field where absent does NOT mean "app default": the route preserves+ // llama_extra_args it is not sent, which is what kept CLI-set flags alive while+ // this panel had no control for them. So `undefined` (never read) stays omitted,+ // and a cleared box has to say so with an explicit empty list.+ if (config.llamaExtraArgs !== undefined) {+ payload.llama_extra_args = config.llamaExtraArgs ?? [];+ }// Only "manual" is a real override; "auto" is the follow-the-global default.if (config.gpuMemoryMode === "manual") {payload.gpu_memory_mode = "manual";@@ -217,8 +407,9 @@ async function sendModelOverride(// Say which operation this is: an all-default save carries no fields, shape-identical// to a forget, and guessing wrong wipes flags the UI cannot show or restore.remove: config === null && !options?.keepLaunchFlags,- // Flags have no UI control, so the backend preserves them when omitted; a forget- // means all of it, so that path sends an explicit [].+ // The backend preserves the flags when omitted, which is what a save that+ // never opened the box relies on; a forget means all of it, so that path+ // sends an explicit []....(config === null && !options?.keepLaunchFlags? // biome-ignore lint/style/useNamingConvention: API schema{ llama_extra_args: [] }diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsxindex 7edd433ff47..6f48558b43e 100644--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx@@ -56,12 +56,35 @@ import {useState,useSyncExternalStore,} from "react";-import { syncModelOverride } from "../api/model-overrides";+import {+ type ModelMemorySettings,+ loadModelMemorySettings,+ subscribeModelMemorySettings,+} from "@/features/settings/api/model-memory";+import {+ type LlamaFlagCatalog,+ loadLlamaFlagCatalog,+ loadManagedLlamaFlags,+ subscribeLlamaFlagCatalog,+} from "../api/llama-flags";+import {+ fetchLoadExtraArgs,+ modelOverrideKey,+ syncModelOverride,+} from "../api/model-overrides";+import {+ diagnoseExtraArgs,+ extraArgsAreLoadable,+ formatExtraArgs,+ parseExtraArgs,+ sanitizeStoredExtraArgs,+} from "../model-config/llama-extra-args";import {useDefaultChatTemplate,useModelMaxPositionEmbeddings,} from "../hooks/use-model-defaults";import { perModelConfigsEqual } from "../model-config/apply-per-model-config";+import { ggufQuantLabel } from "../model-config/model-identity";import {CONTEXT_LENGTH_MIN,DEFAULT_MAX_SEQ_LENGTH,@@ -125,6 +148,30 @@ const SPECULATIVE_TYPE_LABELS: Record<off: "Off",};+/**+ * The batch size llama-server will not go below for this load.+ *+ * Two is its own hard floor (it aborts on a batch of 1 at any slot count), and above+ * that the floor follows the slots the launch SERVES. That is not always the number+ * chosen here: a build without --kv-unified serves one slot however many are asked+ * for, and load_model clamps to it, so sizing the floor from an explicit Slots value+ * refused "--batch-size 2" against a command the backend accepts. With the field+ * blank the server-wide default applies, which the catalogue already publishes+ * effective. A backend that publishes neither leaves the hard floor in charge.+ */+function effectiveBatchFloor(+ requestedSlots: number | null | undefined,+ limits:+ | { defaultParallelSlots?: number; parallelSlotsClamped?: boolean }+ | null+ | undefined,+): number {+ if (limits?.parallelSlotsClamped) {+ return 2;+ }+ return Math.max(2, requestedSlots ?? limits?.defaultParallelSlots ?? 2);+}+function hasNonDefaultAdvanced(config: PerModelConfig): boolean {return (config.kvCacheDtype != null ||@@ -135,6 +182,9 @@ function hasNonDefaultAdvanced(config: PerModelConfig): boolean {config.nUbatch != null ||config.tensorParallel ||config.chatTemplateOverride != null ||+ // Hidden flags can change what the model does, so a panel that opens collapsed+ // over them says "defaults" about a load that is anything but.+ (config.llamaExtraArgs != null && config.llamaExtraArgs.length > 0) ||(config.gpuMemoryMode ?? "auto") !== "auto" ||(config.gpuLayers != null && config.gpuLayers >= 0) ||(config.nCpuMoe ?? 0) > 0 ||@@ -157,6 +207,7 @@ function withoutUnsupportedDiffusionSettings(!config.tensorParallel &&config.nBatch == null &&config.nUbatch == null &&+ (config.llamaExtraArgs == null || config.llamaExtraArgs.length === 0) &&!hasUnsupportedGpuPick) {return config;@@ -170,6 +221,10 @@ function withoutUnsupportedDiffusionSettings(// the diffusion runner ignores the llama-server batch flagsnBatch: null,nUbatch: null,+ // The diffusion shim never appends llama-server flags to its command, but the+ // load records them as though it had, so a box filled before classification+ // flipped would leave the model running without what it says.+ llamaExtraArgs: null,...(hasUnsupportedGpuPick? {selectedGpuIds: undefined,@@ -864,6 +919,7 @@ function GgufAdvancedSettings({gpuDevices,gpuLayersInputRef,moeLayersInputRef,+ onExtraArgsLoadableChange,}: {config: PerModelConfig;update: (patch: Partial<PerModelConfig>) => void;@@ -876,6 +932,8 @@ function GgufAdvancedSettings({gpuDevices: SystemGpuDevice[];gpuLayersInputRef?: Ref<NumericValueInputHandle>;moeLayersInputRef?: Ref<NumericValueInputHandle>;+ /** Which stored entries the extra-arguments row reads, most specific first. */+ onExtraArgsLoadableChange: (loadable: boolean) => void;}) {const batchAdviceId = useId();const ubatchAdviceId = useId();@@ -1170,10 +1228,202 @@ function GgufAdvancedSettings({/><ChatTemplateSetting config={config} onEditTemplate={onEditTemplate} />++ {/* Last, because it is the escape hatch for everything the rows above do not+ cover, and because llama.cpp's last-wins parsing means these really are+ appended after them. GGUF only: the flags are llama-server's. */}+ {!isDiffusion && (+ <ExtraArgsRow+ config={config}+ update={update}+ onLoadableChange={onExtraArgsLoadableChange}+ />+ )}</>);}+/**+ * Pass-through llama-server arguments for this model.+ *+ * llama-server documents 283 flags and Unsloth already emits or manages about 115+ * of them, so the long tail is a text box rather than 168 more controls. The+ * boundary is `validate_extra_args` on the backend, which refuses the flags Unsloth+ * owns; this row is the same judgement shown early, plus a check against the flags+ * THIS build documents, which a list shipped with Unsloth could not do.+ */+function ExtraArgsRow({+ config,+ update,+ onLoadableChange,+}: {+ config: PerModelConfig;+ update: (patch: Partial<PerModelConfig>) => void;+ onLoadableChange: (loadable: boolean) => void;+}) {+ const [catalog, setCatalog] = useState<LlamaFlagCatalog | null>(null);+ // What is typed, which is not what is stored: the stored value is argv tokens, so+ // the text only exists here. Seeded from the config, then owned by the box, or+ // every re-render would re-quote what the user is halfway through typing.+ const [text, setText] = useState(() =>+ formatExtraArgs(config.llamaExtraArgs),+ );+ const adviceId = useId();+ // What the box last put INTO the config, so an external change can be told apart+ // from the echo of the user's own typing. Reset and the parent's hydration both+ // replace llamaExtraArgs while this row is mounted, and a box that kept its old+ // text would then disagree with what Load sends. Re-seeding on every config+ // change instead would re-quote a half-typed line on each keystroke.+ const selfWritten = useRef(formatExtraArgs(config.llamaExtraArgs));+ const external = formatExtraArgs(config.llamaExtraArgs);+ useEffect(() => {+ if (external === selfWritten.current) {+ return;+ }+ selfWritten.current = external;+ setText(external);+ }, [external]);++ // Re-read on invalidation, not only on mount: updating llama.cpp from the banner+ // replaces the binary while this panel stays open, and a row holding the old+ // build's catalogue would go on judging arity, and calling flags unknown, against+ // help text that no longer describes the server it is about to launch.+ const [catalogEpoch, setCatalogEpoch] = useState(0);+ useEffect(+ () => subscribeLlamaFlagCatalog(() => setCatalogEpoch((epoch) => epoch + 1)),+ [],+ );+ useEffect(() => {+ let cancelled = false;+ loadLlamaFlagCatalog().then((loaded) => {+ if (!cancelled) {+ // Null is "cannot verify": adopted as well, or the row would keep checking+ // against the previous binary after an update it cannot read.+ setCatalog(loaded);+ }+ });+ return () => {+ cancelled = true;+ };+ }, [catalogEpoch]);++ // Model Memory removes some of these before the launch: apply_model_memory_policy+ // emits its own load mode and strips the rest, so an --mlock typed here would be+ // shown, saved, and never passed. Read once and then kept in sync, like the section+ // in Settings that owns it. A failed read leaves the row quiet rather than claiming+ // a removal it cannot confirm.+ const [modelMemory, setModelMemory] = useState<ModelMemorySettings | null>(+ null,+ );+ useEffect(() => {+ let cancelled = false;+ loadModelMemorySettings()+ .then((loaded) => {+ if (!cancelled) {+ setModelMemory(loaded);+ }+ })+ .catch(() => {});+ const unsubscribe = subscribeModelMemorySettings(setModelMemory);+ return () => {+ cancelled = true;+ unsubscribe();+ };+ }, []);++ const diagnostics = diagnoseExtraArgs(text, catalog, {+ gpuSelectionActive: config.selectedGpuIds != null,+ manualGpuMemory: config.gpuMemoryMode === "manual",+ // The same floor the batch control shows, for the same reason: with Slots blank+ // the count is the server default this page cannot see, so only the hard 2 holds.+ // A build that clamps serves one slot whatever is chosen here, so an explicit+ // Slots value must not raise the floor above a batch the backend would accept.+ batchFloor: effectiveBatchFloor(config.nParallel, catalog),+ keepResident: modelMemory?.keepResident ?? false,+ noRamReserve: modelMemory?.noRamReserve ?? false,+ });+ const tokenCount = parseExtraArgs(text).tokens.length;++ // The panel owns the Load button, and an error here is one validate_extra_args+ // would refuse. Reported up rather than only painted red, so the load is not+ // started just to come back as a failure.+ const loadable = extraArgsAreLoadable(diagnostics);+ useEffect(() => {+ onLoadableChange(loadable);+ // Deliberately no cleanup. Collapsing Advanced settings unmounts this row while+ // the tokens stay in the config and still go out with the load, so withdrawing+ // the objection there would re-enable a button for a request the backend+ // refuses. The panel clears it when the model changes instead.+ }, [loadable, onLoadableChange]);++ const commit = (next: string) => {+ setText(next);+ const { tokens } = parseExtraArgs(next);+ // Recorded before the update, so the config change this causes reads as the+ // box's own and does not bounce back through the effect above.+ selfWritten.current = formatExtraArgs(tokens.length > 0 ? tokens : null);+ // null, not [], so the panel's own "no flags" reads the same as the stored one;+ // toApiOverride turns it into the explicit [] that clears the server's copy.+ update({ llamaExtraArgs: tokens.length > 0 ? tokens : null });+ };++ return (+ <div className="space-y-2">+ <div className="flex min-w-0 items-center gap-1.5">+ <span className={LABEL_CLASS}>Extra Arguments</span>+ <InfoHint>+ <div className="flex flex-col gap-1.5">+ <div>+ Passed straight to llama-server for this model, after the settings+ above, so anything set in both is taken from here.+ </div>+ <div>+ Quote a value containing spaces or backslashes, including a+ Windows path. Nothing runs a shell, so $HOME, ; and | are ordinary+ characters. Flags Unsloth owns, like the model, the port and the+ API key, are refused.+ </div>+ </div>+ </InfoHint>+ </div>+ <div className="panel-text-surface h-20 w-full overflow-hidden corner-squircle">+ <textarea+ value={text}+ onChange={(event) => commit(event.target.value)}+ spellCheck={false}+ placeholder="--rope-scaling yarn --yarn-orig-ctx 32768"+ aria-label="Extra llama-server arguments"+ aria-describedby={diagnostics.length > 0 ? adviceId : undefined}+ className="block size-full resize-none bg-transparent px-3.5 py-2.5 text-left font-mono text-ui-12 leading-relaxed text-nav-fg outline-none placeholder:text-muted-foreground"+ />+ </div>+ {(tokenCount > 0 || diagnostics.length > 0) && (+ <div id={adviceId} className="space-y-1">+ {tokenCount > 0 && (+ <p className="text-ui-11 text-muted-foreground">+ {tokenCount === 1 ? "1 argument" : `${tokenCount} arguments`}+ </p>+ )}+ {diagnostics.map((diagnostic) => (+ <p+ key={diagnostic.message}+ className={+ diagnostic.level === "error"+ ? "text-ui-11 text-red-500"+ : diagnostic.level === "warning"+ ? "text-ui-11 text-amber-500"+ : "text-ui-11 text-muted-foreground"+ }+ >+ {diagnostic.message}+ </p>+ ))}+ </div>+ )}+ </div>+ );+}+interface ModelConfigPageProps {target: ModelPickTarget;onBack?: () => void;@@ -1247,10 +1497,35 @@ export function ModelConfigPage({const [configState, setConfig] = useState<PerModelConfig>(() =>reconcileConfigGpuSelection(initial.config, isDiffusion, gpuDevices),);+ // The live config, for the async reads below: an effect that closed over it would+ // hold whatever it was when the request started.+ const configRef = useRef(configState);+ configRef.current = configState;const [remember, setRemember] = useState(() => initial.remembered);const [savedRemember, setSavedRemember] = useState(() => initial.remembered);const [speculativeFallback] = useState(readPersistedSpeculativeType);const [templateOpen, setTemplateOpen] = useState(false);+ // Raised by the extra-arguments row when what is typed is something+ // validate_extra_args would refuse, so the load is not started to fail. Held by+ // the panel rather than the row because the row unmounts whenever Advanced+ // settings are collapsed, while its tokens stay in the config.+ const [extraArgsLoadable, setExtraArgsLoadable] = useState(true);+ // True until the stored-arguments read below settles. A load started before it+ // lands sends no llama_extra_args, and /load cannot inherit them from a process+ // that is not running, so a fast click would launch a cold model without the+ // arguments that were about to appear on screen.+ const [extraArgsHydrating, setExtraArgsHydrating] = useState(+ () => target.isGguf && !isDiffusion,+ );+ // The row does not withdraw its own objection when it unmounts, or collapsing+ // Advanced settings would re-enable Load for arguments the backend refuses. A+ // different model is the one thing that really does retire it.+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on the model, not on the setter+ useEffect(() => {+ setExtraArgsLoadable(true);+ setExtraArgsHydrating(target.isGguf && !isDiffusion);+ }, [configId, target.ggufVariant, target.isGguf, isDiffusion]);+// Compare against what the backend was asked for, not what it applied: staging a// new value must retire a verdict that answered a different request.const chatTemplateOutcome =@@ -1279,7 +1554,9 @@ export function ModelConfigPage({);// Until the switch is used anywhere, a model carrying non-default advanced values opens the// section itself. Frozen at mount so editing a field back to its default cannot close it.- const [autoOpenAdvanced] = useState(() => hasNonDefaultAdvanced(configState));+ const [autoOpenAdvanced, setAutoOpenAdvanced] = useState(() =>+ hasNonDefaultAdvanced(configState),+ );// Frozen like the rest of the auto-open decision, so editing the width does not// reopen the section the user just closed.const [initialMlxKvBits] = useState(() => configState.mlxKvBits ?? null);@@ -1383,6 +1660,280 @@ export function ModelConfigPage({stagedDims,);const resolvedIsDiffusion = classifiedIsDiffusion === true;++ // The one field on this page whose stored value the local config may never have+ // seen. Everything else here is written by this panel, but llama_extra_args can be+ // set through the overrides API with no UI involved, which is exactly why that+ // route preserves it when omitted. Showing an empty box for a model that has flags+ // would read as "none", and the first edit would then submit a list that silently+ // dropped them. Fetched, not guessed.+ //+ // The row judges what is typed while it is mounted, and deliberately leaves its+ // verdict standing when Advanced settings collapse, because the tokens still go+ // out with the load. But a verdict reached before the catalogue arrived was+ // reached without knowing which flags this build documents, and collapsing the+ // section freezes it: a bare --threads typed during a cold probe would keep Load+ // enabled and fail at llama-server startup. So while the row is unmounted, the+ // panel re-judges what the config holds once the catalogue lands.+ // The row holds its own subscription, but it is unmounted whenever this check is+ // the one running, so the panel needs its own: an in-app llama.cpp update with+ // Advanced collapsed would otherwise leave a verdict reached against the previous+ // binary standing, and Load live for a flag the new one has removed.+ const [hiddenCatalogEpoch, setHiddenCatalogEpoch] = useState(0);+ useEffect(+ () =>+ subscribeLlamaFlagCatalog(() =>+ setHiddenCatalogEpoch((epoch) => epoch + 1),+ ),+ [],+ );+ // biome-ignore lint/correctness/useExhaustiveDependencies: the arguments, the section and the binary are the inputs+ useEffect(() => {+ if (showAdvanced || !target.isGguf || resolvedIsDiffusion) {+ return;+ }+ const args = configState.llamaExtraArgs;+ if (args == null || args.length === 0) {+ // The row leaves its objection standing when it unmounts, because the tokens+ // it objected to still go out with the load. Once there are none, there is+ // nothing left to object to: Reset with Advanced collapsed used to leave Load+ // disabled over arguments the request no longer carries.+ setExtraArgsLoadable(true);+ return;+ }+ let cancelled = false;+ loadLlamaFlagCatalog().then((catalog) => {+ if (cancelled || !catalog) {+ // Null is "cannot verify": leaving the standing verdict alone is the same+ // benefit of the doubt the row gives an unprobed build.+ return;+ }+ const loadable = extraArgsAreLoadable(+ diagnoseExtraArgs(formatExtraArgs(args), catalog, {+ gpuSelectionActive: configState.selectedGpuIds != null,+ manualGpuMemory: configState.gpuMemoryMode === "manual",+ // The server-wide default when the Slots field is blank: that is the+ // count the launch will serve, and llama-server aborts on a batch below+ // it. Clamped builds serve one whatever is chosen.+ batchFloor: effectiveBatchFloor(configState.nParallel, catalog),+ }),+ );+ // Only ever tightens. This judges the TOKENS, and formatExtraArgs quotes them+ // back into a balanced string, so an unclosed quote the row objected to reads+ // as fine here; raising the verdict would re-enable Load over the unfinished+ // value the user is still typing. A list that is genuinely clean keeps+ // whatever verdict already stands, which is true unless the row set it.+ if (!loadable) {+ setExtraArgsLoadable(false);+ }+ });+ return () => {+ cancelled = true;+ };+ }, [+ showAdvanced,+ configState.llamaExtraArgs,+ configState.selectedGpuIds,+ configState.gpuMemoryMode,+ configState.nParallel,+ target.isGguf,+ resolvedIsDiffusion,+ hiddenCatalogEpoch,+ ]);++ // Here rather than in the row that displays it: that row is inside Advanced+ // settings, which is not rendered while the section is collapsed, so a panel+ // opened closed would never fetch and a cold load would launch without the stored+ // arguments. The row seeds its textarea from the config either way.+ const extraArgsHydrated = useRef<string | null>(null);+ // biome-ignore lint/correctness/useExhaustiveDependencies: the model is the identity+ useEffect(() => {+ if (!target.isGguf || resolvedIsDiffusion) {+ // Nothing else even has this field: the row is GGUF-only and so is the load+ // payload, so a Transformers or MLX model must not wait on either request.+ // A diffusion GGUF is GGUF-shaped but runs through the diffusion shim, which+ // appends no llama-server flags and whose config strips them, so it must not+ // wait either.+ setExtraArgsHydrating(false);+ return;+ }+ // The order the auto-switch loader tries, and for the same reason: the settings+ // UI keys a local row by the path it loads from, while configId is a derived+ // alias, so reading the alias first lets an older entry stay the one API loads+ // apply while the panel shows none of it. A loose .gguf was keyed by its+ // filename label in an early build, which is the fourth candidate here.+ const loadId = target.id;+ const fileVariant =+ !target.ggufVariant && loadId.toLowerCase().endsWith(".gguf")+ ? ggufQuantLabel(loadId.replace(/\\/g, "/").split("/").pop() ?? loadId)+ : null;+ const keys = [+ modelOverrideKey(loadId, target.ggufVariant),+ modelOverrideKey(configId, target.ggufVariant),+ loadId,+ ...(fileVariant ? [`${loadId}:${fileVariant}`] : []),+ configId,+ ].filter((key, index, all) => all.indexOf(key) === index);+ // Joined because an array literal is a new value on every render.+ const identity = keys.join("\u0000");+ if (extraArgsHydrated.current === identity) {+ setExtraArgsHydrating(false);+ return;+ }+ let cancelled = false;+ // What the config held BEFORE the request went out. Anything else at the end of+ // it was typed by the user while it was in flight, and sanitizing that would+ // rewrite live input: typing --agent during the window cleared the box instead+ // of showing the error, and a long paste could be trimmed behind the cursor.+ const localAtStart = configRef.current.llamaExtraArgs;+ // The denylist, not the catalogue: sanitizing a stored list needs only the flags+ // Unsloth refuses, and that route answers without running `llama-server --help`.+ // Waiting on the probe instead would hold Load shut for as long as a cold --help+ // takes, and releasing on a deadline would leave a legacy flag in an explicit+ // request that /load then refuses.+ // A last-resort release, so a request that never settles cannot disable Load for+ // good: past this a load behaves as it did before the feature.+ const release = setTimeout(() => setExtraArgsHydrating(false), 15000);+ Promise.all([+ // Resolved by the backend, which owns the rules: the local resolver stays as+ // the fallback for a backend that predates the parameter.+ fetchLoadExtraArgs(loadId, configId, target.ggufVariant, keys),+ loadManagedLlamaFlags(),+ ])+ .then(([resolvedArgs, managed]) => {+ // Marked here rather than before the request: StrictMode replays the effect+ // (setup, cleanup, setup), so a key marked up front would leave the first+ // fetch cancelled and the second setup returning early, and the box would+ // never fill in development.+ if (cancelled) {+ return;+ }+ extraArgsHydrated.current = identity;+ // Through the resolver, not a literal lookup: the backend folds identities+ // and reads whole entries in its own order before it reads a field.+ //+ // Sanitised before it becomes a request: hydrating turns a stored list into+ // an EXPLICIT one, which /load validates strictly instead of putting it+ // through the carry-over paths that drop a newly denied flag quietly.+ // Without this, an install upgraded across a denylist change stops loading a+ // model that worked the day before.+ const stored = sanitizeStoredExtraArgs(+ resolvedArgs.tokens,+ managed?.managed ?? new Set<string>(),+ // The host's bounds, not the constants: a Windows server takes 24 KiB and+ // holds a quoted-command budget as well, so trimming to 32 KiB here sends a+ // list /load answers 400 on.+ {+ maxBytes: managed?.maxBytes,+ windowsCommandBudget: managed?.windowsCommandBudget,+ },+ );+ // A list this build refuses can equally have come from local storage, saved+ // by a build that still allowed it. The server copy is sanitised above; this+ // is the same treatment for the one already in hand, which nothing else+ // would catch while Advanced stays collapsed.+ const local = configRef.current.llamaExtraArgs;+ if (local != null && local.length > 0 && local === localAtStart) {+ const cleaned = sanitizeStoredExtraArgs(+ local,+ managed?.managed ?? new Set<string>(),+ {+ maxBytes: managed?.maxBytes,+ windowsCommandBudget: managed?.windowsCommandBudget,+ },+ );+ if (cleaned.length !== local.length) {+ setConfig((current) =>+ current.llamaExtraArgs === local+ ? { ...current, llamaExtraArgs: cleaned.length > 0 ? cleaned : null }+ : current,+ );+ }+ }+ if (stored.length === 0) {+ // An EXPLICIT empty row is a decision, not an absence: the settings page+ // writes one when the box is cleared for a quant whose bare-repository+ // row still carries arguments, and it is what stops the server's lookup+ // there. Left undefined the panel omits the field on Load, and /load+ // carries the resident model's arguments over: the very ones just+ // cleared. Only when nothing was typed here in the meantime.+ const local = configRef.current.llamaExtraArgs;+ if (resolvedArgs.explicit && local === undefined) {+ setExtraArgsLoadable(true);+ setConfig((current) =>+ current.llamaExtraArgs === undefined+ ? { ...current, llamaExtraArgs: [] }+ : current,+ );+ }+ return;+ }+ // Judged here as well as in the row: with Advanced collapsed the row never+ // mounts, so nothing would object to a stored list this build refuses (an+ // override written through the API is only structurally validated), and+ // Load would be live for a request that comes back 400. The managed set is+ // enough for that: the value checks do not need the binary's catalogue.+ const hydratedIsLoadable = extraArgsAreLoadable(+ diagnoseExtraArgs(formatExtraArgs(stored), {+ flags: {},+ managed: managed?.managed ?? new Set<string>(),+ // Read without the probe, so nothing here knows which flags are+ // switches, and nothing may be called a typo either.+ switches: new Set<string>(),+ maxBytes: managed?.maxBytes ?? 0,+ windowsCommandBudget: managed?.windowsCommandBudget ?? 0,+ defaultParallelSlots: managed?.defaultParallelSlots ?? 0,+ // Carried from the managed-only read, which knows it: a build that+ // serves one slot however many are asked for floors the batch at 2,+ // and hydration must judge a stored list the same way the row does.+ parallelSlotsClamped: managed?.parallelSlotsClamped ?? false,+ probeOk: false,+ },+ {+ // The slot floor is already known here, and the backend refuses a batch+ // below it deterministically. Left out, this released Load on a stored+ // "--batch-size 2" against a four-slot server, and a click in the window+ // before the full catalogue check lands reaches that 400.+ batchFloor: effectiveBatchFloor(configRef.current.nParallel, managed),+ }),+ );+ // Read from a ref rather than inside the updater below: an updater must stay+ // free of side effects (StrictMode calls it twice), and this decides one.+ if (configRef.current.llamaExtraArgs !== undefined) {+ // Typed into while this was in flight. The row is judging that text and its+ // verdict is the live one, so this answer about the stored list must not+ // overwrite either of them: doing so re-enabled Load for invalid input.+ return;+ }+ setExtraArgsLoadable(hydratedIsLoadable);+ setConfig((current) =>+ // Guarded again, because the ref is only as fresh as the last render.+ current.llamaExtraArgs === undefined+ ? { ...current, llamaExtraArgs: stored }+ : current,+ );+ // The frozen snapshot above was taken before this answer arrived, so without+ // this a model whose arguments live only on the server opens looking like+ // every default. An explicit preference still wins: this only feeds the+ // fallback.+ setAutoOpenAdvanced(true);+ })+ .catch(() => {+ // Nothing to say: the panel is still usable, and the load would report a+ // real problem with the overrides service far more clearly than this could.+ })+ .finally(() => {+ // Including the failure: an overrides service that is down must not leave+ // Load disabled for good.+ if (!cancelled) {+ setExtraArgsHydrating(false);+ }+ });+ return () => {+ cancelled = true;+ clearTimeout(release);+ };+ }, [configId, target.id, target.ggufVariant, target.isGguf, resolvedIsDiffusion]);const config = reconcileConfigGpuSelection(configState,resolvedIsDiffusion,@@ -1479,6 +2030,16 @@ export function ModelConfigPage({const loadableConfig = resolvedIsDiffusion? withoutUnsupportedDiffusionSettings(config, gpuIndexKind): config;+ // A model classified as diffusion after the box was typed into keeps the row's+ // objection while the arguments themselves are stripped from what loads, and the+ // row does not withdraw it when it unmounts. Retired here, or Load stays disabled+ // over arguments the request no longer carries.+ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on the classification, not on the setter+ useEffect(() => {+ if (resolvedIsDiffusion) {+ setExtraArgsLoadable(true);+ }+ }, [resolvedIsDiffusion]);const pinFixedLayerContext =target.isGguf &&loadableConfig.gpuMemoryMode === "manual" &&@@ -1779,6 +2340,7 @@ export function ModelConfigPage({gpuDevices={gpuDevices}gpuLayersInputRef={gpuLayersInputRef}moeLayersInputRef={moeLayersInputRef}+ onExtraArgsLoadableChange={setExtraArgsLoadable}/>)}@@ -1852,7 +2414,15 @@ export function ModelConfigPage({size="sm"className="h-8"disabled={atDefault}- onClick={() => setConfig({ ...DEFAULT_PER_MODEL_CONFIG })}+ onClick={() =>+ setConfig({+ // null, not the default's absent: absent omits the field, and the+ // load then INHERITS the running process's arguments, so a reload+ // after Reset kept the very flags the empty box says are gone.+ ...DEFAULT_PER_MODEL_CONFIG,+ llamaExtraArgs: null,+ })+ }>Reset</Button>@@ -1863,6 +2433,8 @@ export function ModelConfigPage({disabled={stagedMetadataPending ||budgetSettling ||+ !extraArgsLoadable ||+ extraArgsHydrating ||(isActiveModel &&atBaseline &&!rememberChanged &&diff --git a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.tsindex f527b014e8d..4290841f3e3 100644--- a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts+++ b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts@@ -142,10 +142,20 @@ export function perModelConfigsEqual(Boolean(a.tensorParallel) === Boolean(b.tensorParallel) &&cleanTemplate(a.chatTemplateOverride) ===cleanTemplate(b.chatTemplateOverride) &&+ extraArgsSignature(a.llamaExtraArgs) === extraArgsSignature(b.llamaExtraArgs) &&gpuFieldsEqual(a, b));}+/**+ * Compare on the launched command, so "not loaded" and "cleared" are equal here.+ * They differ only in what a SAVE does, and treating them as different would make+ * the row read as an unsaved change the moment it finished reading the server.+ */+function extraArgsSignature(value: string[] | null | undefined): string {+ return (value ?? []).join("\u0000");+}+function gpuFieldsEqual(a: PerModelConfig, b: PerModelConfig): boolean {return gpuFieldsSignature(a) === gpuFieldsSignature(b);}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.tsnew file mode 100644index 00000000000..45007b0616a--- /dev/null+++ b/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts@@ -0,0 +1,1138 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * Turning what the user types into the argv tokens the API takes.+ *+ * `LoadRequest.llama_extra_args` is a list with one argv token per entry, which is+ * what the CLI already sends and what the overrides table already stores. The+ * single string only ever lives in the control, so the split happens here.+ *+ * Deliberately not a shell: there is no `sh -c` anywhere on this path (the child is+ * spawned from a list), so expanding `$HOME`, globbing, or honouring `;` and `|`+ * would invent meanings the backend does not implement. Quotes and backslashes are+ * handled because a chat template or a grammar genuinely needs a space inside one+ * token; everything else is a literal character.+ */++// Hoisted: these run per token, and biome flags a literal in a hot path.+const NEEDS_QUOTING = /[\s"'\\]/;+const DOUBLE_QUOTE_ESCAPES = /(["\\$`])/g;+const DIGIT = /[0-9]/;+const UNDERSCORE = /_/g;+// biome-ignore lint/suspicious/noControlCharactersInRegex: mirroring the backend's own check+// The same rule as CONTROL_IN_ARGV below, and as the backend's own check.+const CONTROL_CHARACTERS = /[\u0000-\u0008\u000b-\u001f]/;+const INTEGER = /^-?[0-9]+$/;+/**+ * A NUL, or any other C0 control except tab and newline.+ *+ * The two exceptions are the backend's, from _has_control_characters, and they are+ * not an oversight there: a grammar, a JSON schema or a chat template is routinely+ * multi-line, and quoting one into a single argv token is exactly what the box is+ * for. Refusing those here would disable Load over a value the launch accepts.+ */+// biome-ignore lint/suspicious/noControlCharactersInRegex: that is exactly what this finds+const CONTROL_IN_ARGV = /[\u0000-\u0008\u000B-\u001F]/;++/**+ * Whether this token is something execve could not carry.+ *+ * The surrogate half is checked by walking the string rather than with a character+ * class, because a class matches BOTH units of a well-formed pair: an emoji in a+ * chat template or a grammar is a pair, Python encodes it without complaint, and+ * treating it as unusable would quietly drop a valid argument. Only an UNPAIRED+ * surrogate is refused, which is the one Popen raises on while encoding argv.+ */+function isUnusableInArgv(token: string): boolean {+ if (CONTROL_IN_ARGV.test(token)) {+ return true;+ }+ for (let index = 0; index < token.length; index += 1) {+ const unit = token.charCodeAt(index);+ if (unit >= 0xd800 && unit <= 0xdbff) {+ const next = token.charCodeAt(index + 1);+ if (Number.isNaN(next) || next < 0xdc00 || next > 0xdfff) {+ return true;+ }+ index += 1;+ } else if (unit >= 0xdc00 && unit <= 0xdfff) {+ return true;+ }+ }+ return false;+}+// Hoisted for the same reason as the patterns above: this runs on every keystroke.+const TEXT_ENCODER = new TextEncoder();++/** Longest input the editor will parse, mirroring MAX_EXTRA_ARGS_BYTES in llama_server_args.py. */+export const EXTRA_ARGS_MAX_BYTES = 32 * 1024;+/** Mirrors MAX_EXTRA_ARG_TOKENS in llama_server_args.py. */+export const EXTRA_ARGS_MAX_TOKENS = 256;++/** The one option in llama-server's help that takes two values. */+const TWO_VALUE_FLAGS = new Set(["--control-vector-layer-range"]);++/**+ * Options that take a second value on SOME builds.+ *+ * Today's llama.cpp writes the scale into the value ("--lora-scaled FNAME:SCALE"),+ * older ones took it as a separate token ("--lora-scaled FNAME SCALE"), and+ * _sidecar_weight_files already reads both. So the second token is allowed but never+ * required: demanding it would refuse the current syntax, and refusing it broke a+ * list that loaded before the positional check existed.+ */+const OPTIONAL_SECOND_VALUE_FLAGS = new Set([+ "--lora-scaled",+ "--control-vector-scaled",+]);++export type ExtraArgsParse = {+ tokens: string[];+ /** Set when a quote is left open, so the row can say so instead of silently dropping it. */+ unterminatedQuote: '"' | "'" | null;+ /**+ * Indices of tokens the user QUOTED, which argv cannot record.+ *+ * `--chat-template '- hello'` is one option and its value, but the quotes are gone+ * by the time it is a token list, and "- hello" is flag-shaped, so the row called+ * the option's value missing and disabled Load over a list the backend accepts and+ * llama.cpp reads correctly (it takes the next argv element whatever it starts+ * with). Only the editor can tell the two apart, and only while the text is still+ * text, so the marks are recorded here and used by the diagnostics.+ */+ quotedIndices: ReadonlySet<number>;+};++/**+ * A stored list with the flags this build refuses removed, values and all.+ *+ * The panel hydrates from the stored override and then sends what it holds as an+ * explicit list, which /load validates strictly rather than putting through the+ * carry-over paths that drop such a flag quietly. An install upgraded across a+ * denylist change would therefore fail to load a model that worked the day before.+ * Mirrors drop_managed_flags: a flag takes its value with it, or llama-server reads+ * the orphan as a positional model path.+ */+/**+ * What ``subprocess.list2cmdline`` would put on a Windows command line for these.+ *+ * A port of CPython's rule, because that is the exact serializer Popen uses there+ * and it is not a sum of lengths: an argument needing quotes has each backslash run+ * before a quote doubled, so an escape-heavy grammar can grow by half again.+ */+export function windowsCommandLength(tokens: readonly string[]): number {+ const result: string[] = [];+ for (const token of tokens) {+ if (result.length > 0) {+ result.push(" ");+ }+ // Quoted only for whitespace or emptiness, as CPython does: a token that merely+ // contains a quote is not quoted, though its backslashes still double.+ const needQuote = token.includes(" ") || token.includes("\t") || token === "";+ if (needQuote) {+ result.push('"');+ }+ let backslashes = 0;+ for (const character of token) {+ if (character === "\\") {+ backslashes += 1;+ continue;+ }+ if (character === '"') {+ result.push("\\".repeat(backslashes * 2));+ backslashes = 0;+ result.push('\\"');+ continue;+ }+ if (backslashes > 0) {+ result.push("\\".repeat(backslashes));+ backslashes = 0;+ }+ result.push(character);+ }+ if (backslashes > 0) {+ result.push("\\".repeat(backslashes));+ // And once more inside the quotes, or the run would escape the closing one.+ if (needQuote) {+ result.push("\\".repeat(backslashes));+ }+ }+ if (needQuote) {+ result.push('"');+ }+ }+ return result.join("").length;+}++/**+ * Whether this token carries its own value instead of expecting the next one.+ *+ * Not "the name changed": extraArgFlagName also folds llama.cpp's underscore+ * spelling, and the binary takes both, so comparing the folded name against the raw+ * token read "--ctx_size 4096" as attached and then called the 4096 a bare value.+ * Only "=" and an attached short like -np8 are values in the same token. Mirrors+ * _value_is_attached in llama_server_args.py.+ */+function valueIsAttached(token: string, flag: string): boolean {+ const raw = token.trim();+ if (raw.includes("=")) {+ return true;+ }+ return raw.replace(UNDERSCORE, "-") !== flag;+}++/** Whether this token's value is the NEXT token rather than part of itself. */+function takesNextToken(+ token: string,+ flag: string,+ next: string | undefined,+): boolean {+ if (valueIsAttached(token, flag)) {+ return false;+ }+ return next !== undefined && extraArgFlagName(next) === null;+}++/**+ * A stored list reduced to what THIS build would accept.+ *+ * Mirrors drop_managed_flags: denied flags go, tokens carrying control characters or+ * unpaired surrogates go, anything past the size bounds goes, and a flag never+ * outlives the value that went with it (an orphaned value is a bare positional,+ * which llama-server reads as the model path).+ *+ * The panel needs this because hydrating turns a stored list into an EXPLICIT+ * request, which /load validates strictly instead of putting it through the very+ * carry-over paths that exist to drop such a token quietly. Without it, an install+ * upgraded across any of those rules stops loading a model that worked yesterday.+ */+export function sanitizeStoredExtraArgs(+ tokens: readonly string[],+ managed: ReadonlySet<string>,+ limits?: { maxBytes?: number; windowsCommandBudget?: number },+): string[] {+ const kept: string[] = [];+ let skipNext = false;+ for (const [index, token] of tokens.entries()) {+ if (skipNext) {+ skipNext = false;+ continue;+ }+ const flag = extraArgFlagName(token);+ const next = tokens[index + 1];+ if (flag !== null && managed.has(flag)) {+ skipNext = takesNextToken(token, flag, next);+ continue;+ }+ if (isUnusableInArgv(token)) {+ if (flag !== null) {+ skipNext = takesNextToken(token, flag, next);+ } else if (+ kept.length > 0 &&+ extraArgFlagName(kept[kept.length - 1]) !== null+ ) {+ // The flag this value belonged to.+ kept.pop();+ }+ continue;+ }+ if (+ flag !== null &&+ takesNextToken(token, flag, next) &&+ next !== undefined &&+ isUnusableInArgv(next)+ ) {+ // Its value is about to be dropped, so the flag goes with it.+ continue;+ }+ kept.push(token);+ }+ // Then the shapes validate_extra_args refuses outright, whatever their size: a+ // token belonging to no flag, and a two-value option left half-written. The backend+ // sheds both because its own trimming re-validates after every cut; this mirror+ // trims by size alone, so it has to know the same rules.+ let bounded = dropUnvalidatableTokens(dropUnusableValues(kept));+ // Then the bounds, shed from the tail, never leaving a flag without its value.+ //+ // The host's own limits when the caller has them: a Windows install takes 24 KiB,+ // not 32, and holds a quoted-command budget besides. Trimming to the wider constant+ // and sending the result is a 400 on the load the hydration was meant to enable,+ // which is the failure this sanitising exists to avoid.+ const maxBytes = limits?.maxBytes || EXTRA_ARGS_MAX_BYTES;+ const commandBudget = limits?.windowsCommandBudget ?? 0;+ const overBounds = (): boolean =>+ bounded.length > EXTRA_ARGS_MAX_TOKENS ||+ TEXT_ENCODER.encode(bounded.join("")).length > maxBytes ||+ (commandBudget > 0 && windowsCommandLength(bounded) > commandBudget);+ while (bounded.length > 0 && overBounds()) {+ bounded.pop();+ const last = bounded[bounded.length - 1];+ const lastFlag = last === undefined ? null : extraArgFlagName(last);+ // Any flag whose value has just gone, not only one spelled exactly as it+ // normalizes: extraArgFlagName folds llama.cpp's underscores, so comparing the+ // normalized name against the raw token left "--grammar_file" standing after its+ // value was trimmed. The backend cannot infer an ordinary flag's arity, so the+ // orphan reaches llama-server and the load fails after the teardown.+ if (last !== undefined && lastFlag !== null && !valueIsAttached(last, lastFlag)) {+ bounded.pop();+ }+ // Re-applied after every cut, exactly as the backend re-validates after its own:+ // shedding one value of a two-value option leaves the other looking ordinary,+ // whether the first was written attached or not.+ bounded = dropUnvalidatableTokens(dropUnusableValues(bounded));+ }+ return bounded;+}++/**+ * A list with the flags whose VALUE the backend's own parsers refuse removed.+ *+ * The same list of flags the row reports on, and the same rules: parse_ctx_override+ * and its siblings raise on a missing or unreadable value, which is a 400 rather than+ * a note. drop_managed_flags repairs these too, by shedding its tail until the whole+ * list validates, which costs whatever followed them; removing just the option and+ * its value keeps the rest of a legacy list working.+ */+function dropUnusableValues(tokens: readonly string[]): string[] {+ const out: string[] = [];+ let skipNext = false;+ for (const [index, token] of tokens.entries()) {+ if (skipNext) {+ skipNext = false;+ continue;+ }+ const flag = extraArgFlagName(token);+ if (+ flag === null ||+ !(INTEGER_VALUE_FLAGS.has(flag) || VALUE_REQUIRED_FLAGS.has(flag))+ ) {+ out.push(token);+ continue;+ }+ const attached = valueIsAttached(token, flag);+ const next = tokens[index + 1];+ const value = attached ? token.split("=")[1] : next;+ const missing =+ value === undefined ||+ value === "" ||+ (!attached && extraArgFlagName(value) !== null);+ const minimum = INTEGER_VALUE_MINIMUM[flag];+ const unusable =+ missing ||+ (INTEGER_VALUE_FLAGS.has(flag) &&+ (!INTEGER.test(value.trim()) ||+ (minimum !== undefined && Number(value.trim()) < minimum)));+ if (!unusable) {+ out.push(token);+ continue;+ }+ // The value goes with the flag, or it is left as a bare token, which is the+ // one thing llama-server would read as a model path.+ skipNext = !attached && !missing;+ }+ return out;+}++/**+ * A list reduced to what validate_extra_args would accept on shape alone.+ *+ * Two rules, both of which the backend enforces by re-validating after each cut it+ * makes: a bare token belonging to no flag is refused outright (llama-server reads a+ * positional as the model path, which is what the -m denial exists to prevent), and a+ * two-value option needs both of its values. Everything else is left alone, because+ * this side does not know the arity of an ordinary flag either.+ */+function dropUnvalidatableTokens(tokens: readonly string[]): string[] {+ const out: string[] = [];+ let pending = 0;+ let twoValuePending = 0;+ // Values still owed to a flag that was itself dropped, so they go rather than+ // being kept as tokens belonging to nothing.+ let droppedOwes = 0;+ // Where the incomplete two-value option starts, so the whole of it can go.+ let ownerAt = -1;+ for (const token of tokens) {+ const flag = extraArgFlagName(token);+ if (droppedOwes > 0 && flag === null) {+ droppedOwes -= 1;+ continue;+ }+ droppedOwes = 0;+ if (flag === null) {+ if (pending <= 0) {+ // Ownerless. Dropped rather than kept, which is what drop_managed_flags+ // does with the same token.+ continue;+ }+ pending -= 1;+ if (twoValuePending > 0) {+ twoValuePending -= 1;+ if (twoValuePending === 0) {+ ownerAt = -1;+ }+ }+ out.push(token);+ continue;+ }+ if (twoValuePending > 0 && ownerAt >= 0) {+ // A new flag arrived while the option still owed a value: the whole option+ // goes, along with the value it did get.+ out.length = ownerAt;+ }+ if (token.includes("=")) {+ // llama.cpp looks the whole token up in its option map, so "--top-k=20" is an+ // argument it has never heard of and validate_extra_args refuses it. A stored+ // list holding one would 400 the load this hydration exists to enable; the+ // value is inside the token, so nothing follows it out.+ pending = 0;+ twoValuePending = 0;+ ownerAt = -1;+ continue;+ }+ if (token !== token.trim()) {+ // Refused for the same reason: the padding is part of the token llama.cpp+ // looks up, so a quoted "--top-k " never arrives as a flag. Its value goes+ // with it, or the orphan is left behind as a bare positional.+ droppedOwes = valueIsAttached(token, flag) ? 0 : 1;+ pending = 0;+ twoValuePending = 0;+ ownerAt = -1;+ continue;+ }+ const attached = valueIsAttached(token, flag);+ if (TWO_VALUE_FLAGS.has(flag)) {+ // An attached value is one of the two, so the option still owes its END.+ pending = attached ? 1 : 2;+ twoValuePending = pending;+ ownerAt = out.length;+ } else if (OPTIONAL_SECOND_VALUE_FLAGS.has(flag)) {+ // Allowed, not owed, so nothing here removes the option for want of it.+ pending = attached ? 1 : 2;+ twoValuePending = 0;+ ownerAt = -1;+ } else {+ pending = attached ? 0 : 1;+ twoValuePending = 0;+ ownerAt = -1;+ }+ out.push(token);+ }+ if (twoValuePending > 0 && ownerAt >= 0) {+ out.length = ownerAt;+ }+ return out;+}++/** The denylist half of the sanitizer, for a caller that only has that to apply. */+export function dropManagedExtraArgs(+ tokens: readonly string[],+ managed: ReadonlySet<string>,+): string[] {+ const kept: string[] = [];+ let skipNext = false;+ for (const [index, token] of tokens.entries()) {+ if (skipNext) {+ skipNext = false;+ continue;+ }+ const flag = extraArgFlagName(token);+ if (flag === null || !managed.has(flag)) {+ kept.push(token);+ continue;+ }+ skipNext = takesNextToken(token, flag, tokens[index + 1]);+ }+ return kept;+}++/**+ * Split a command-line fragment into argv tokens.+ *+ * Newlines are separators like spaces, so a multi-line box reads as one command and+ * a user can put each flag on its own line.+ */+export function parseExtraArgs(input: string): ExtraArgsParse {+ const tokens: string[] = [];+ 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;++ for (let i = 0; i < input.length; i += 1) {+ const ch = input[i];++ if (+ quote === null &&+ (ch === " " || ch === "\t" || ch === "\n" || ch === "\r")+ ) {+ if (started) {+ if (currentQuoted) {+ quotedIndices.add(tokens.length);+ }+ tokens.push(current);+ current = "";+ started = false;+ currentQuoted = false;+ }+ continue;+ }++ // A backslash escapes the next character, but only where a shell would: inside+ // single quotes it is literal, which is what makes '\d' usable in a grammar.+ if (ch === "\\" && quote !== "'" && i + 1 < input.length) {+ const next = input[i + 1];+ // Inside double quotes only these are escapes; elsewhere the backslash stands.+ if (quote === '"' && !['"', "\\", "$", "`", "\n"].includes(next)) {+ current += ch;+ started = true;+ continue;+ }+ // A backslash-newline is a line continuation, so pasting a wrapped command+ // works. It contributes nothing, so `started` is left as it was: setting it+ // would make the indentation on the next line close an empty token, and a+ // wrapped command indented under its first line (the usual shape) would send+ // an empty positional argument that llama-server reads as a model path.+ if (next === "\n") {+ i += 1;+ continue;+ }+ current += next;+ started = true;+ i += 1;+ continue;+ }++ if (quote === null && (ch === '"' || ch === "'")) {+ quote = ch;+ // An empty quoted string is still a token: --grammar '' means something.+ started = true;+ currentQuoted = true;+ continue;+ }++ if (quote !== null && ch === quote) {+ quote = null;+ continue;+ }++ current += ch;+ started = true;+ }++ if (started) {+ if (currentQuoted) {+ quotedIndices.add(tokens.length);+ }+ tokens.push(current);+ }+ return { tokens, unterminatedQuote: quote, quotedIndices };+}++/**+ * Render tokens back into one editable line.+ *+ * Round-tripping matters: the stored value is a token list, so this is what the box+ * shows when the panel reopens. Quote only what has to be quoted, or every reopen+ * would add another layer of escaping to the user's own text.+ */+export function formatExtraArgs(+ tokens: readonly string[] | null | undefined,+): string {+ if (tokens === null || tokens === undefined || tokens.length === 0) {+ return "";+ }+ return tokens+ .map((token) => {+ if (token === "") {+ return "''";+ }+ if (!NEEDS_QUOTING.test(token)) {+ return token;+ }+ // Single quotes unless the token contains one, since they escape nothing and+ // leave a grammar or a template readable.+ if (!token.includes("'")) {+ return `'${token}'`;+ }+ return `"${token.replace(DOUBLE_QUOTE_ESCAPES, "\\$1")}"`;+ })+ .join(" ");+}++/** The flag name a token carries, or null when it is a value. Mirrors `_flag_name`. */+export function extraArgFlagName(token: string): string | null {+ const trimmed = token.trim();+ if (!trimmed.startsWith("-") || trimmed === "-" || trimmed === "--") {+ return null;+ }+ // A negative number is a value, not a flag: shorts always start with a letter.+ if (trimmed.length >= 2 && (DIGIT.test(trimmed[1]) || trimmed[1] === ".")) {+ return null;+ }+ let name = trimmed.split("=", 1)[0];+ if (name.startsWith("--")) {+ name = name.replace(UNDERSCORE, "-");+ }+ // Attached `-np8` normalises to `-np`, or a denied flag slips through glued to+ // its value. Mirrors the same branch in _flag_name.+ if (name.length > 3 && name.startsWith("-np")) {+ const suffix = name.slice(3);+ if (+ DIGIT.test(suffix[0]) ||+ (suffix.length > 1 && "-+".includes(suffix[0]) && DIGIT.test(suffix[1]))+ ) {+ return "-np";+ }+ }+ return name;+}++/** Every flag token in a parsed list, in order, deduplicated. */+export function extraArgFlags(tokens: readonly string[]): string[] {+ const seen = new Set<string>();+ for (const token of tokens) {+ const flag = extraArgFlagName(token);+ if (flag !== null) {+ seen.add(flag);+ }+ }+ return [...seen];+}++// --- diagnostics ------------------------------------------------------------+// Kept in this file rather than beside it: the node test harness resolves value+// imports at runtime with no bundler, so a tested helper importing a sibling by+// extensionless path cannot load. Every other tested module here is self-contained+// for the same reason.++import type { LlamaFlagCatalog } from "../api/llama-flags";++/**+ * What to tell the user about what they typed, before the load tries it.+ *+ * Three levels, and the difference is the whole point of the row: an `error` is+ * refused by the backend so the load cannot start, a `warning` is allowed through+ * because we may simply be unable to verify it, and a `note` is correct usage worth+ * stating out loud.+ */+export type ExtraArgsDiagnostic = {+ level: "error" | "warning" | "note";+ message: string;+};++/**+ * Controls in this panel that emit the same flag. Not a denial: the backend appends+ * extras last and reconciles the ones that move its own sizing (`parse_ctx_override`+ * and friends exist for exactly that), and the CLI has always allowed it. The user+ * just deserves to be told which one wins.+ */+const CONTROL_OWNED_FLAGS: Record<string, string> = {+ "--ctx-size": "Context Length",+ "-c": "Context Length",+ "--batch-size": "Batch Size",+ "-b": "Batch Size",+ "--ubatch-size": "Micro-batch Size",+ "-ub": "Micro-batch Size",+ "--cache-type-k": "KV Cache Dtype",+ "-ctk": "KV Cache Dtype",+ "--cache-type-v": "KV Cache Dtype",+ "-ctv": "KV Cache Dtype",+ "--gpu-layers": "GPU Layers",+ "--n-gpu-layers": "GPU Layers",+ "-ngl": "GPU Layers",+ "--n-cpu-moe": "MoE Layers on CPU",+ "-ncmoe": "MoE Layers on CPU",+ "--split-mode": "Tensor Parallelism",+ "-sm": "Tensor Parallelism",+ "--spec-type": "Speculative Decoding",+ "--spec-draft-n-max": "Draft Tokens",+ "--chat-template": "Chat Template",+ "--chat-template-file": "Chat Template",+};++/**+ * Flags the launch REMOVES when the GPU picker owns placement. Not a shadow the user+ * wins: `_strip_device_extra_args` deletes these from the command whenever gpu_ids is+ * set, so telling the reader theirs is taken from here would be false.+ */+const GPU_SELECTION_STRIPPED_FLAGS: Record<string, string> = {+ "--device": "GPU selection",+ "-dev": "GPU selection",+ "--main-gpu": "GPU selection",+ "-mg": "GPU selection",+};++/**+ * Flags Manual GPU memory REMOVES without translating, unlike the layer count.+ *+ * `/load` calls strip_shadowing_flags(strip_offload=True) whenever gpu_memory_mode+ * is manual. An -ngl in the extras survives that, because the route reads it with+ * parse_gpu_layers_override and writes it into the first-class field first; nothing+ * does the same for the MoE count or the fitter, so those are dropped and the+ * controls' own values are what runs. Telling the reader theirs wins would be false.+ */+const MANUAL_OFFLOAD_STRIPPED_FLAGS: Record<string, string> = {+ "--n-cpu-moe": "MoE Layers on CPU",+ "-ncmoe": "MoE Layers on CPU",+ "--cpu-moe": "MoE Layers on CPU",+ "-cmoe": "MoE Layers on CPU",+ "--fit": "GPU Memory",+ "-fit": "GPU Memory",+};++/**+ * Flags Model Memory removes, per setting.+ *+ * apply_model_memory_policy runs before the extras reach the command line. "Keep model+ * in GPU memory" emits its own load mode and strips every other load-mode-bearing flag,+ * because a trailing one resets the whole mode and would drop the lock; "Don't reserve+ * system RAM" drops the flags that would hold a full host copy. Either way the argument+ * never reaches llama-server, so reporting that it wins would be false.+ */+const KEEP_RESIDENT_STRIPPED_FLAGS: Record<string, string> = {+ "--mlock": "Keep model in GPU memory",+ "-mlock": "Keep model in GPU memory",+ "--load-mode": "Keep model in GPU memory",+ "-lm": "Keep model in GPU memory",+ "--no-mmap": "Keep model in GPU memory",+ "-no-mmap": "Keep model in GPU memory",+ "--mmap": "Keep model in GPU memory",+ "--direct-io": "Keep model in GPU memory",+ "-dio": "Keep model in GPU memory",+ "--no-direct-io": "Keep model in GPU memory",+ "-ndio": "Keep model in GPU memory",+};++/** The subset no-reserve vetoes: mmap and dio hold no full host copy, so they stay. */+const NO_RAM_RESERVE_STRIPPED_FLAGS: Record<string, string> = {+ "--mlock": "Don't reserve system RAM",+ "-mlock": "Don't reserve system RAM",+ "--no-mmap": "Don't reserve system RAM",+ "-no-mmap": "Don't reserve system RAM",+ "--no-direct-io": "Don't reserve system RAM",+ "-ndio": "Don't reserve system RAM",+};++/**+ * Smallest value the backend's own parser accepts, per flag.+ *+ * parse_ctx_override refuses a negative context; parse_gpu_layers_override accepts+ * -1 (all layers) and nothing below it. The rest are checked for being integers+ * only, because that is all those parsers claim.+ */+const INTEGER_VALUE_MINIMUM: Record<string, number> = {+ "--ctx-size": 0,+ "-c": 0,+ "--gpu-layers": -1,+ "--n-gpu-layers": -1,+ "-ngl": -1,+};+++/** Values the backend parses as integers, and refuses the load over. */+/**+ * Flags whose value the backend reads with _last_flag_value, which raises when it is+ * missing or empty. Not integers, so only presence is checked here.+ */+const VALUE_REQUIRED_FLAGS = new Set([+ "--cache-type-k",+ "-ctk",+ "--cache-type-v",+ "-ctv",+ "--split-mode",+ "-sm",+]);++/** The pass-through spellings of the batch size the floor above applies to. */+const BATCH_SIZE_FLAGS = new Set(["--batch-size", "-b"]);++const INTEGER_VALUE_FLAGS = new Set([+ "--ctx-size",+ "-c",+ "--gpu-layers",+ "--n-gpu-layers",+ "-ngl",+ "--n-cpu-moe",+ "-ncmoe",+ "--parallel",+ "--batch-size",+ "-b",+ "--ubatch-size",+ "-ub",+]);++/** Sampling belongs to the conversation, not the launch. */+const REQUEST_SCOPED_FLAGS = new Set([+ "--temp",+ "--temperature",+ "--top-p",+ "--top-k",+ "--min-p",+ "--repeat-penalty",+ "--presence-penalty",+ "--frequency-penalty",+ "-n",+ "--predict",+ "--n-predict",+]);++/** The load settings that decide which flags survive to the command line. */+export type ExtraArgsContext = {+ /** The GPU picker owns placement, which removes the device flags. */+ gpuSelectionActive?: boolean;+ /** GPU Memory is Manual, which removes the offload flags its controls own. */+ manualGpuMemory?: boolean;+ /** Smallest --batch-size this launch can run, max(slots, 2). */+ batchFloor?: number;+ /** Model Memory keeps the weights resident, which owns the load mode. */+ keepResident?: boolean;+ /** Model Memory reserves no system RAM, which vetoes the reserving flags. */+ noRamReserve?: boolean;+};++export function diagnoseExtraArgs(+ input: string,+ catalog: LlamaFlagCatalog | null,+ /**+ * What this load's own settings do to the arguments, so the row can say which of+ * them the launch will remove. An object rather than a run of booleans: every+ * setting that owns a flag group adds one, and a positional list of five would be+ * read wrong at the call site long before it stopped compiling.+ */+ context: ExtraArgsContext = {},+): ExtraArgsDiagnostic[] {+ const gpuSelectionActive = context.gpuSelectionActive ?? false;+ const manualGpuMemory = context.manualGpuMemory ?? false;+ const batchFloor = Math.max(2, context.batchFloor ?? 2);+ const keepResident = context.keepResident ?? false;+ const noRamReserve = context.noRamReserve ?? false;+ const out: ExtraArgsDiagnostic[] = [];+ const { tokens, unterminatedQuote, quotedIndices } = parseExtraArgs(input);+ // Tokens the walk below consumed as somebody's value. A quoted token in value+ // POSITION is a value whatever it starts with: llama.cpp takes the next argv+ // element for a value-taking option without looking at it, and the backend+ // forwards the list verbatim, so "--chat-template '- hello'" works. Position+ // matters as much as the quotes: a user who quotes out of habit ("--top-k" 20)+ // still wrote a flag, and reading that as a value would refuse a list that runs.+ const valueIndices = new Set<number>();++ if (unterminatedQuote) {+ out.push({+ level: "error",+ message: `Unclosed ${unterminatedQuote === '"' ? "double" : "single"} quote.`,+ });+ }+ if (tokens.length > EXTRA_ARGS_MAX_TOKENS) {+ out.push({+ level: "error",+ message: `Too many arguments: ${tokens.length}, limit ${EXTRA_ARGS_MAX_TOKENS}.`,+ });+ }+ // The other half of the backend's bounds. A grammar or a JSON schema is one long+ // token, so a payload can sit well inside the token cap and still be refused on+ // size; without this the Load button starts a request that cannot succeed.+ // The host's own limit when it has told us one: it is smaller on Windows, where+ // the whole command line shares a single 32767-character budget.+ const maxBytes = catalog?.maxBytes || EXTRA_ARGS_MAX_BYTES;+ const bytes = TEXT_ENCODER.encode(tokens.join("")).length;+ if (bytes > maxBytes) {+ out.push({+ level: "error",+ message: `Arguments are too large: ${bytes} bytes, limit ${maxBytes}.`,+ });+ }+ // And on Windows, what the quoting makes of them: a backslash run before a quote+ // doubles, so bytes alone do not say whether the launch fits.+ if (catalog?.windowsCommandBudget) {+ const quoted = windowsCommandLength(tokens);+ if (quoted > catalog.windowsCommandBudget) {+ out.push({+ level: "error",+ message: `Arguments are too long for a Windows command line: ${quoted} characters after quoting, limit ${catalog.windowsCommandBudget}.`,+ });+ }+ }++ // The backend refuses any token carrying one, and a command copied out of+ // coloured terminal output is the usual way one arrives.+ if (tokens.some((token) => CONTROL_CHARACTERS.test(token))) {+ out.push({+ level: "error",+ message: "Arguments cannot contain control characters.",+ });+ } else if (tokens.some((token) => isUnusableInArgv(token))) {+ // What is left once control characters are ruled out: half a surrogate pair,+ // which pasting a truncated string can produce. The load refuses it because+ // Popen raises while encoding argv rather than starting llama-server. An emoji+ // is a whole pair and stays perfectly fine.+ out.push({+ level: "error",+ message: "Arguments contain an incomplete character.",+ });+ }++ // A token belonging to no flag. llama-server answers "invalid argument" and+ // refuses to start, and validate_extra_args refuses it outright, so saying so here+ // is the difference between a red line under the box and a failed load. Two-value+ // flags are allowed for, as they are on the backend.+ 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, either because the next token is another flag+ // or because the text ended. Reported only when the arity is known: the catalogue+ // read this build's own help and lists it as value-taking, or it is the two-value+ // flag whose arity needs no probe. An unverified flag keeps the benefit of the+ // doubt, as it does above. llama-server exits during startup on these, which is a+ // failed load rather than a red line under the box.+ const owedValues: string[] = [];+ const noteOwed = (owner: string | null, pending: number) => {+ if (owner === null || pending <= 0) {+ return;+ }+ if (+ TWO_VALUE_FLAGS.has(owner) ||+ (catalog?.probeOk === true &&+ owner in catalog.flags &&+ !catalog.switches.has(owner))+ ) {+ owedValues.push(owner);+ }+ };+ for (const [index, token] of tokens.entries()) {+ const quotedValue = pendingValues > 0 && quotedIndices.has(index);+ const flag = quotedValue ? null : extraArgFlagName(token);+ if (flag === null) {+ if (pendingValues <= 0) {+ out.push({+ level: "error",+ message: `"${token}" belongs to no flag. Every value has to follow its flag.`,+ });+ break;+ }+ valueIndices.add(index);+ pendingValues -= 1;+ if (pendingValues <= 0) {+ pendingOwner = null;+ }+ continue;+ }+ // Before the obligation is replaced: "--numa --verbose" leaves --numa without+ // the value it needs, and only this point in the walk still knows that.+ noteOwed(pendingOwner, pendingValues);+ const attached = valueIsAttached(token, flag);+ pendingValues = TWO_VALUE_FLAGS.has(flag)+ ? // An attached value is ONE of the two, so the option still owes its END.+ attached+ ? 1+ : 2+ : OPTIONAL_SECOND_VALUE_FLAGS.has(flag)+ ? // Allowed, not owed: the second token is taken if it is there.+ attached+ ? 1+ : 2+ : attached+ ? 0+ : // A flag THIS build documents as taking no value claims none, so the+ // next bare token has no owner. Only when the catalogue actually knows+ // the flag: an unverified one keeps the benefit of the doubt.+ catalog?.switches.has(flag)+ ? 0+ : 1;+ // Never reported as owing a value: only the flags whose arity is certain are.+ pendingOwner =+ pendingValues > 0 && !OPTIONAL_SECOND_VALUE_FLAGS.has(flag) ? flag : null;+ }+ noteOwed(pendingOwner, pendingValues);++ const seen = new Set<string>();+ const unknown: string[] = [];+ const shadowed: string[] = [];+ const stripped: string[] = [];+ const manualStripped: string[] = [];+ const memoryStripped: [string, string][] = [];+ const reportedValues = new Set<string>();+ for (const [index, token] of tokens.entries()) {+ // Judged the same way the walk above judged it, or a quoted value that begins+ // with a hyphen would be reported here as a flag this build has never heard of.+ const flag = valueIndices.has(index) ? null : extraArgFlagName(token);+ if (flag === null) {+ continue;+ }+ // Before the de-duplication below, because llama.cpp reads the LAST occurrence:+ // in `-ngl 20 -ngl many` it is the second one the backend parses and refuses, so+ // checking only the first would leave Load enabled for a request that 400s.+ if (INTEGER_VALUE_FLAGS.has(flag) || VALUE_REQUIRED_FLAGS.has(flag)) {+ const attached = valueIsAttached(token, flag);+ const value = attached ? token.split("=")[1] : tokens[index + 1];+ // A flag whose value is the next token has none when that token is itself a+ // flag: `--ctx-size --numa` reads --numa as the value in a shell and as a+ // missing one here, which is what the backend's parser says too.+ const missing =+ value === undefined ||+ value === "" ||+ (!attached &&+ !valueIndices.has(index + 1) &&+ extraArgFlagName(value) !== null);+ const minimum = INTEGER_VALUE_MINIMUM[flag];+ const numeric = INTEGER_VALUE_FLAGS.has(flag);+ let message: string | null = null;+ if (missing) {+ message = numeric+ ? `${flag} needs a number after it.`+ : `${flag} needs a value after it.`;+ } else if (!numeric) {+ message = null;+ } else if (!INTEGER.test(value.trim())) {+ message = `${flag} takes a number, and "${value}" is not one.`;+ } else if (minimum !== undefined && Number(value.trim()) < minimum) {+ message =+ minimum === 0+ ? `${flag} cannot be negative.`+ : `${flag} takes ${minimum} or more.`;+ } else if (+ BATCH_SIZE_FLAGS.has(flag) &&+ Number(value.trim()) < Math.max(2, batchFloor)+ ) {+ // Not raised the way the first-class control is: this flag is appended after+ // the launcher's own --batch-size and wins it, so the load starts and+ // llama-server aborts on the assertion instead.+ const floor = Math.max(2, batchFloor);+ message =+ floor > 2+ ? `${flag} takes ${floor} or more here: llama-server aborts on a batch below the ${floor} parallel slot(s) it serves.`+ : `${flag} takes 2 or more: llama-server aborts on a batch of 1.`;+ }+ if (message !== null && !reportedValues.has(message)) {+ reportedValues.add(message);+ out.push({ level: "error", message });+ }+ }+ if (seen.has(flag)) {+ continue;+ }+ seen.add(flag);++ if (token !== token.trim()) {+ // The padding is part of the token llama.cpp looks up, so a quoted "--top-k "+ // never arrives as a flag: it answers "error: invalid argument: --top-k",+ // naming a flag that looks perfectly correct in the log. Reported whether or+ // not a control owns the flag, since the name is not the problem.+ out.push({+ level: "error",+ message: `Remove the spaces around "${token}". llama-server reads them as part of the flag.`,+ });+ } else if (token.includes("=") && !catalog?.managed.has(flag)) {+ // Measured on b10342 and b10360: "--top-k=20", "--ctx-size=4096" and+ // "--flash-attn=on" each exit with "error: invalid argument". A managed flag+ // is left to the message below, which names the control that owns it.+ out.push({+ level: "error",+ message: `llama-server does not read "${flag}=value". Write ${flag} and its value as two arguments.`,+ });+ }++ if (catalog?.managed.has(flag)) {+ const control = CONTROL_OWNED_FLAGS[flag];+ out.push({+ level: "error",+ message: control+ ? `${flag} is set by ${control} above and cannot be passed here.`+ : `${flag} is managed by Unsloth Studio and cannot be passed here.`,+ });+ continue;+ }+ if (gpuSelectionActive && GPU_SELECTION_STRIPPED_FLAGS[flag]) {+ stripped.push(flag);+ continue;+ }+ if (manualGpuMemory && MANUAL_OFFLOAD_STRIPPED_FLAGS[flag]) {+ manualStripped.push(flag);+ continue;+ }+ // No-reserve first: with both settings on it is the one that runs, and its own+ // veto is what removes the flag.+ if (noRamReserve && NO_RAM_RESERVE_STRIPPED_FLAGS[flag]) {+ memoryStripped.push([flag, NO_RAM_RESERVE_STRIPPED_FLAGS[flag]]);+ continue;+ }+ if (keepResident && !noRamReserve && KEEP_RESIDENT_STRIPPED_FLAGS[flag]) {+ memoryStripped.push([flag, KEEP_RESIDENT_STRIPPED_FLAGS[flag]]);+ continue;+ }+ const control = CONTROL_OWNED_FLAGS[flag];+ if (control) {+ shadowed.push(`${flag} (${control})`);+ continue;+ }+ if (REQUEST_SCOPED_FLAGS.has(flag)) {+ out.push({+ level: "note",+ message: `${flag} only sets a default here. Sampling for a conversation lives in its chat settings.`,+ });+ continue;+ }+ // Only when the catalogue was actually read: a build we could not probe must+ // not have every one of its flags called a typo.+ if (catalog?.probeOk && !(flag in catalog.flags)) {+ unknown.push(flag);+ }+ }++ if (stripped.length > 0) {+ out.push({+ level: "warning",+ message: `${stripped.join(", ")} will be removed: the GPU selection above owns placement. Set GPU Memory to Default to pass it yourself.`,+ });+ }+ for (const owner of owedValues) {+ const message = TWO_VALUE_FLAGS.has(owner)+ ? `${owner} needs two values, a start and an end layer.`+ : INTEGER_VALUE_FLAGS.has(owner)+ ? `${owner} needs a number after it.`+ : `${owner} needs a value after it.`;+ if (!reportedValues.has(message)) {+ reportedValues.add(message);+ out.push({ level: "error", message });+ }+ }++ if (memoryStripped.length > 0) {+ const setting = memoryStripped[0][1];+ out.push({+ level: "warning",+ message: `${memoryStripped.map(([flag]) => flag).join(", ")} will be removed: ${setting} in Settings owns how the weights are held.`,+ });+ }+ if (manualStripped.length > 0) {+ out.push({+ level: "warning",+ message: `${manualStripped.join(", ")} will be removed: GPU Memory is Manual, and its controls own offload. Set GPU Memory to Default to pass it yourself.`,+ });+ }+ if (shadowed.length > 0) {+ out.push({+ level: "note",+ message: `Passed after the controls above, so ${shadowed.join(", ")} wins.`,+ });+ }+ if (unknown.length > 0) {+ out.push({+ level: "warning",+ message:+ unknown.length === 1+ ? `${unknown[0]} is not in this llama-server's --help. It will still be passed.`+ : `${unknown.join(", ")} are not in this llama-server's --help. They will still be passed.`,+ });+ }+ return out;+}++/** True when nothing here would stop the load. */+export function extraArgsAreLoadable(+ diagnostics: readonly ExtraArgsDiagnostic[],+): boolean {+ return !diagnostics.some((d) => d.level === "error");+}diff --git a/studio/frontend/src/features/model-picker/model-config/model-identity.ts b/studio/frontend/src/features/model-picker/model-config/model-identity.tsindex cf28569096c..d07eb72dff2 100644--- a/studio/frontend/src/features/model-picker/model-config/model-identity.ts+++ b/studio/frontend/src/features/model-picker/model-config/model-identity.ts@@ -104,7 +104,7 @@ function ggufStem(filename: string): string {/*** Mirrors extract_quant_label in gguf.py, for a bare filename. The parent-directory pass* cannot fire on a basename, so this is the stem's quant token or the stem itself. */-function ggufQuantLabel(filename: string): string {+export function ggufQuantLabel(filename: string): string {const stem = ggufStem(filename);let fallback: RegExpExecArray | null = null;for (const match of stem.matchAll(QUANT_TOKEN)) {diff --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 57e51b2324c..e2f9ba353ae 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@@ -25,6 +25,18 @@ export interface PerModelConfig {nUbatch: number | null;tensorParallel: boolean;chatTemplateOverride: string | null;+ /**+ * Pass-through llama-server args, one argv token per entry, appended after+ * Unsloth's own flags.+ *+ * Three states, and the difference is load-bearing. `undefined` means this copy+ * never read the stored value, so a save must leave the server's alone: the+ * overrides route preserves the field when it is omitted, which is what kept+ * CLI-set flags alive while the panel had no control for them. `null` means the+ * user cleared the box, which has to be sent as an explicit `[]` or the clear is+ * silently dropped. A non-empty list is what to launch with.+ */+ llamaExtraArgs?: string[] | null;// GPU Memory controls (per-model, GGUF-only), optional so older blobs still parse. null/absent// selectedGpuIds means automatic. --tensor-split is not remembered: it is bound to the GPU set.gpuMemoryMode?: "auto" | "manual";@@ -150,8 +162,10 @@ export {const STORAGE_KEY = "unsloth_model_configs";const LEGACY_STORAGE_KEY = "unsloth_load_settings";const LEGACY_MIGRATION_FLAG = "unsloth_model_configs_migrated";-// v2 added nBatch / nUbatch; a v1 client's normalizer would rewrite them away-const STORAGE_SCHEMA_VERSION = 2;+// v2 added nBatch / nUbatch and v3 llamaExtraArgs; a client from before either+// would normalize the field it does not know straight back out of the record.+const STORAGE_SCHEMA_VERSION = 3;+const PRE_EXTRA_ARGS_SCHEMA_VERSION = 2;const PRE_BATCH_SCHEMA_VERSION = 1;const MAX_ENTRIES = 500;const MAX_PER_MODEL_CONFIG_STORAGE_BYTES = 1024 * 1024;@@ -176,6 +190,7 @@ const STORED_CONFIG_FIELDS = new Set(["nUbatch","tensorParallel","chatTemplateOverride",+ "llamaExtraArgs","gpuMemoryMode","gpuLayers","nCpuMoe",@@ -183,6 +198,24 @@ 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 wiping case is the one worth being careful about, since the flags it 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;+ }+ if (!Array.isArray(value)) {+ return undefined;+ }+ const tokens = value.filter((entry): entry is string => typeof entry === "string");+ return tokens.length > 0 ? tokens : null;+}+function normalizeGpuFields(partial: RawConfig): {gpuMemoryMode?: "auto" | "manual";gpuLayers?: number;@@ -483,6 +516,10 @@ function legacyEntryToConfig(raw: Record<string, unknown>): PerModelConfig {tensorParallel:typeof raw.tensorParallel === "boolean" ? raw.tensorParallel : false,chatTemplateOverride: null,+ // Absent, not null: a legacy blob predates the editor, and the server may well+ // hold flags set from the CLI. Reading that as "cleared" would wipe them on the+ // first save from this panel.+ llamaExtraArgs: undefined,// Carry legacy GPU Memory knobs; normalizeGpuFields drops anything malformed.gpuMemoryMode:raw.gpuMemoryMode === "auto" || raw.gpuMemoryMode === "manual"@@ -679,6 +716,7 @@ function normalizeV1(partial: RawConfig): PerModelConfig {isChatTemplateWithinLimit(partial.chatTemplateOverride)? partial.chatTemplateOverride: null,+ llamaExtraArgs: normalizeLlamaExtraArgs(partial.llamaExtraArgs),...normalizeGpuFields(partial),};}@@ -705,11 +743,15 @@ function normalize(raw: unknown): PerModelConfig {function toStoredConfig(config: PerModelConfig): StoredPerModelConfig {const normalized = normalize(config);- // records without the v2-only batch fields keep v1 so older clients can still rewrite them+ // Stamped with the OLDEST version that still understands every field present, so+ // a record an older client can safely rewrite is not needlessly locked away from+ // it. Only a record carrying a newer field is put out of that client's reach.const version =- normalized.nBatch != null || normalized.nUbatch != null+ normalized.llamaExtraArgs != null && normalized.llamaExtraArgs.length > 0? STORAGE_SCHEMA_VERSION- : PRE_BATCH_SCHEMA_VERSION;+ : normalized.nBatch != null || normalized.nUbatch != null+ ? PRE_EXTRA_ARGS_SCHEMA_VERSION+ : PRE_BATCH_SCHEMA_VERSION;return {version,...normalized,@@ -828,6 +870,9 @@ export function isDefaultConfig(config: PerModelConfig): boolean {Boolean(config.tensorParallel) ===Boolean(DEFAULT_PER_MODEL_CONFIG.tensorParallel) &&(config.chatTemplateOverride ?? null) === null &&+ // Or a config whose only change is Extra Arguments reads as default, and+ // savePerModelConfig deletes the entry it was asked to remember.+ (config.llamaExtraArgs == null || config.llamaExtraArgs.length === 0) &&gpuFieldsAtDefault(config));}diff --git a/studio/frontend/src/features/settings/hooks/use-llama-backend-switch.ts b/studio/frontend/src/features/settings/hooks/use-llama-backend-switch.tsindex 16a63446297..6ec4cf209de 100644--- a/studio/frontend/src/features/settings/hooks/use-llama-backend-switch.ts+++ b/studio/frontend/src/features/settings/hooks/use-llama-backend-switch.ts@@ -1,6 +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+import { invalidateLlamaFlagCatalog } from "@/features/model-picker/api/llama-flags";import { useT } from "@/i18n";import {signalLlamaJobStarted,@@ -77,6 +78,11 @@ export function useLlamaBackendSwitch() {setApplying(false);// The install marker is authoritative after completion.setSelected(next.backendRequest);+ // Here rather than where the switch is requested: that call only STARTS the+ // install, so the binary whose --help the flag catalogue describes is still+ // the old one, and a panel opened during the job would cache it again. Before+ // the owned-job check, so a tab that merely watched the switch drops it too.+ invalidateLlamaFlagCatalog();if (!outcome) {return;}diff --git a/studio/frontend/tests/credential-persistence.test.ts b/studio/frontend/tests/credential-persistence.test.tsindex 9fd839cd524..94512cd2e3e 100644--- a/studio/frontend/tests/credential-persistence.test.ts+++ b/studio/frontend/tests/credential-persistence.test.ts@@ -437,6 +437,26 @@ test("HF store hydrates from the API without recreating plaintext storage", asyn});+/**+ * Wait for the store's write to finish, on a deadline rather than a tick budget.+ *+ * A fixed number of setImmediate turns is a bet on how many the runtime needs, and a+ * two-core runner running the suite in parallel loses that bet: the write is a real+ * promise chain, so under load it settles a few turns later and the assertion below+ * reads a store that is still persisting.+ */+async function settled(+ hfStore: { useHfTokenStore: { getState: () => { isPersisting: boolean } } },+): Promise<void> {+ const deadline = Date.now() + 5000;+ while (hfStore.useHfTokenStore.getState().isPersisting) {+ if (Date.now() > deadline) {+ throw new Error("the HF token write never settled");+ }+ await new Promise((resolve) => setTimeout(resolve, 1));+ }+}+test("HF hydration does not overwrite an in-flight user edit", async () => {const { store } = installLocalStorageFake();store.set("unsloth_auth_token", "session-token");@@ -476,10 +496,7 @@ test("HF hydration does not overwrite an in-flight user edit", async () => {headers: { "Content-Type": "application/json" },}),);- for (let attempt = 0; attempt < 10; attempt += 1) {- if (!hfStore.useHfTokenStore.getState().isPersisting) break;- await new Promise((resolve) => setImmediate(resolve));- }+ await settled(hfStore);assert.equal(hfStore.getHfToken(), "hf_user_edit");assert.equal(hfStore.useHfTokenStore.getState().isPersisting, false);} finally {@@ -561,10 +578,7 @@ test("a delayed HF write response reconciles a newer cross-tab commit", async ()status: 200,headers: { "Content-Type": "application/json" },}));- for (let attempt = 0; attempt < 10; attempt += 1) {- if (!hfStore.useHfTokenStore.getState().isPersisting) break;- await new Promise((resolve) => setImmediate(resolve));- }+ await settled(hfStore);assert.equal(reads, 2);assert.equal(hfStore.getHfToken(), "hf_new_tab");@@ -641,10 +655,7 @@ test("a superseded successful HF write advances the rollback baseline", async ()resolveSecond(new Response(JSON.stringify({ detail: "failed" }), {status: 500, headers: { "Content-Type": "application/json" },}));- for (let attempt = 0; attempt < 10; attempt += 1) {- if (!hfStore.useHfTokenStore.getState().isPersisting) break;- await new Promise((resolve) => setImmediate(resolve));- }+ await settled(hfStore);assert.equal(hfStore.getHfToken(), "hf_first");assert.match(hfStore.useHfTokenStore.getState().persistenceError ?? "", /failed/);} finally {diff --git a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts b/studio/frontend/tests/llama-extra-args-diagnostics.test.tsnew file mode 100644index 00000000000..937b009f12e--- /dev/null+++ b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts@@ -0,0 +1,1397 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { test } from "node:test";+import { fileURLToPath } from "node:url";+import type { LlamaFlagCatalog } from "../src/features/model-picker/api/llama-flags.ts";+import {+ diagnoseExtraArgs,+ dropManagedExtraArgs,+ extraArgsAreLoadable,+ parseExtraArgs,+ sanitizeStoredExtraArgs,+} from "../src/features/model-picker/model-config/llama-extra-args.ts";++// The row is the backend's judgement shown early. Where these disagree, the panel+// accepts an argument the load then refuses, or warns about one that works.++const CATALOG: LlamaFlagCatalog = {+ flags: {+ "--top-k": "top-k sampling",+ "--numa": "NUMA policy",+ "--ctx-size": "context size",+ "--rope-scaling": "RoPE scaling",+ "--device": "device list",+ "-ngl": "layers to offload",+ "--batch-size": "logical batch size",+ },+ // The names the backend actually returns, aliases included: --n-parallel is in+ // its denylist, and leaving it out here would test a catalogue that cannot exist.+ managed: new Set([+ "--parallel",+ "--n-parallel",+ "-np",+ "--model",+ "--api-key",+ "--agent",+ "--ctx-size",+ ]),+ // What this build says takes no value, so "--verbose foo" reads as the typo+ // llama-server calls it.+ switches: new Set(["--verbose"]),+ maxBytes: 32 * 1024,+ windowsCommandBudget: 0,+ defaultParallelSlots: 0,+ probeOk: true,+};++const levels = (input: string, catalog: LlamaFlagCatalog | null = CATALOG) =>+ diagnoseExtraArgs(input, catalog).map((d) => d.level);++const messages = (input: string, catalog: LlamaFlagCatalog | null = CATALOG) =>+ diagnoseExtraArgs(input, catalog)+ .map((d) => d.message)+ .join(" | ");++test("a well-formed argument the binary knows says nothing", () => {+ assert.deepEqual(diagnoseExtraArgs("--numa distribute", CATALOG), []);+ assert.deepEqual(diagnoseExtraArgs("", CATALOG), []);+});++test("a managed flag is an error that names the control that owns it", () => {+ const text = messages("--parallel 8");+ assert.match(text, /--parallel/);+ assert.equal(levels("--parallel 8")[0], "error");+ assert.equal(+ extraArgsAreLoadable(diagnoseExtraArgs("--parallel 8", CATALOG)),+ false,+ );+});++test("a managed flag with no control says who owns it instead", () => {+ // --api-key is not a row in this panel, so pointing at one would be a lie.+ const text = messages("--api-key secret");+ assert.match(text, /managed by Unsloth Studio/);+ assert.doesNotMatch(text, /above/);+});++test("an attached or equals form is caught the same way", () => {+ // The backend normalises these before checking, so the row has to as well.+ assert.equal(levels("-np8")[0], "error");+ assert.equal(levels("--parallel=8")[0], "error");+ assert.equal(levels("--n_parallel 8")[0], "error");+});++test("a flag a control also sets is a note, not a refusal", () => {+ // Deliberate: the backend appends extras last and reconciles the ones that move+ // its own sizing, and the CLI has always allowed this. Say who wins, do not block.+ const diagnostics = diagnoseExtraArgs("--batch-size 512", CATALOG);+ assert.deepEqual(+ diagnostics.map((d) => d.level),+ ["note"],+ );+ assert.match(diagnostics[0].message, /Batch Size/);+ assert.equal(extraArgsAreLoadable(diagnostics), true);+});++test("a flag missing from this build warns but still loads", () => {+ const diagnostics = diagnoseExtraArgs("--tempp 0.7", CATALOG);+ assert.deepEqual(+ diagnostics.map((d) => d.level),+ ["warning"],+ );+ assert.match(diagnostics[0].message, /--tempp/);+ assert.match(diagnostics[0].message, /still be passed/);+ assert.equal(extraArgsAreLoadable(diagnostics), true);+});++test("nothing is called unknown when the probe failed", () => {+ // The failure mode this exists to prevent: an unverifiable build would mark every+ // correct flag as a typo, which is worse than saying nothing.+ const unverified: LlamaFlagCatalog = {+ flags: {},+ managed: CATALOG.managed,+ // Nothing was read from the binary, so nothing is known to be a switch either.+ switches: new Set<string>(),+ maxBytes: 32 * 1024,+ windowsCommandBudget: 0,+ defaultParallelSlots: 0,+ probeOk: false,+ };+ assert.deepEqual(+ diagnoseExtraArgs("--tempp 0.7 --numa distribute", unverified),+ [],+ );+ // A managed flag is still refused: that judgement needs no binary.+ assert.equal(levels("--parallel 8", unverified)[0], "error");+});++test("an older backend with no catalogue still refuses nothing and warns nothing", () => {+ assert.deepEqual(diagnoseExtraArgs("--tempp 0.7", null), []);+});++test("sampling flags are noted as launch defaults", () => {+ // They work, but the chat settings send sampling per request, so a value set here+ // is not what a conversation will use.+ const text = messages("--top-k 20");+ assert.match(text, /chat settings/);+ assert.equal(levels("--top-k 20")[0], "note");+});++test("an unclosed quote is an error", () => {+ const diagnostics = diagnoseExtraArgs('--chat-template "a b', CATALOG);+ assert.equal(diagnostics[0].level, "error");+ assert.match(diagnostics[0].message, /Unclosed double quote/);+ assert.equal(extraArgsAreLoadable(diagnostics), false);+});++test("too many arguments is an error at the backend's own limit", () => {+ const diagnostics = diagnoseExtraArgs("--verbose ".repeat(257), CATALOG);+ assert.equal(diagnostics[0].level, "error");+ assert.match(diagnostics[0].message, /limit 256/);+});++test("a payload over the byte limit is an error, even within the token cap", () => {+ // One long token is the realistic shape: a grammar or a JSON schema. The backend+ // refuses this on size, so the row has to say so rather than let the load start.+ const huge = `--grammar ${"a".repeat(40_000)}`;+ const diagnostics = diagnoseExtraArgs(huge, CATALOG);++ assert.equal(diagnostics[0].level, "error");+ assert.match(diagnostics[0].message, /limit 32768/);+ assert.equal(extraArgsAreLoadable(diagnostics), false);+ // Multi-byte characters count as their UTF-8 length, which is what the backend+ // measures; counting characters would let a CJK grammar through.+ const multibyte = `--grammar ${"\u65e5".repeat(11_000)}`;+ assert.equal(+ extraArgsAreLoadable(diagnoseExtraArgs(multibyte, CATALOG)),+ false,+ );+ // And an ordinary line is nowhere near it.+ assert.deepEqual(diagnoseExtraArgs("--numa distribute", CATALOG), []);+});++test("each flag is reported once however often it appears", () => {+ assert.equal(+ diagnoseExtraArgs("--tempp 1 --tempp 2 --tempp 3", CATALOG).length,+ 1,+ );+});++test("several unknown flags share one line", () => {+ const diagnostics = diagnoseExtraArgs("--aaa 1 --bbb 2", CATALOG);+ assert.equal(diagnostics.length, 1);+ assert.match(diagnostics[0].message, /--aaa, --bbb/);+});++test("values are never mistaken for flags", () => {+ // "-1" and "0.7" are values; treating them as flags would warn about every+ // negative number the user types.+ assert.deepEqual(+ diagnoseExtraArgs("--numa distribute --top-k -1", CATALOG).map(+ (d) => d.level,+ ),+ ["note"],+ );+});++test("a device flag is called removed, not winning, when GPUs are picked", () => {+ // The launch strips these whenever gpu_ids is set (_strip_device_extra_args), so+ // the ordinary "passed last, yours wins" note would be a lie for them.+ const withPick = diagnoseExtraArgs("--device CUDA0", CATALOG, { gpuSelectionActive: true });+ assert.equal(withPick[0].level, "warning");+ assert.match(withPick[0].message, /--device will be removed/);+ assert.match(withPick[0].message, /GPU selection/);+ // With no GPU picked the flag is the user's own and nothing is stripped.+ assert.deepEqual(diagnoseExtraArgs("--device CUDA0", CATALOG, {}), []);+});++test("a flag that takes a number rejects a value that is not one", () => {+ // parse_ctx_override and parse_gpu_layers_override raise before the load starts,+ // so the row has to say so rather than enable a request that cannot succeed.+ // -ngl rather than --ctx-size: this build's catalogue has --ctx-size on the+ // managed list, and that refusal would fire first and prove nothing.+ const bad = diagnoseExtraArgs("-ngl many", CATALOG);+ assert.equal(bad[0].level, "error");+ assert.match(bad[0].message, /takes a number/);+ assert.equal(extraArgsAreLoadable(bad), false);+ assert.equal(+ extraArgsAreLoadable(diagnoseExtraArgs("--batch-size=abc", CATALOG)),+ false,+ );+ // A real value is fine, negative included: -1 means every layer.+ assert.equal(+ extraArgsAreLoadable(diagnoseExtraArgs("-ngl -1", CATALOG)),+ true,+ );+ assert.equal(+ extraArgsAreLoadable(diagnoseExtraArgs("--batch-size 512", CATALOG)),+ true,+ );+});++test("a control character is an error, as it is at the backend", () => {+ // The usual way one arrives is a command copied out of coloured terminal output.+ const diagnostics = diagnoseExtraArgs("--grammar a\u001b[0mb", CATALOG);+ assert.equal(diagnostics[0].level, "error");+ assert.match(diagnostics[0].message, /control characters/);+ assert.equal(extraArgsAreLoadable(diagnostics), false);+ // Tab and newline are separators here, not control characters to refuse.+ assert.equal(+ extraArgsAreLoadable(diagnoseExtraArgs("--top-k\t20", CATALOG)),+ true,+ );+});++// --- the panel wiring, asserted on source ------------------------------------+test("a repeated numeric flag is checked at every occurrence", () => {+ // llama.cpp reads the last one, and so does the backend's parse_gpu_layers_override,+ // so a check that stopped at the first occurrence left Load enabled for a request+ // that comes back 400.+ const out = diagnoseExtraArgs("-ngl 20 -ngl many", CATALOG);+ assert.ok(+ out.some(+ (d) => d.level === "error" && d.message.includes('"many" is not one'),+ ),+ JSON.stringify(out),+ );+});++test("the same bad value is reported once, not once per copy", () => {+ const out = diagnoseExtraArgs("-ngl many -ngl many", CATALOG);+ assert.equal(+ out.filter((d) => d.message.includes('"many" is not one')).length,+ 1,+ );+});++test("a numeric flag with nothing after it is an error", () => {+ // parse_ctx_override raises on a missing value rather than reading the next flag+ // as one, so leaving Load enabled here only moves the failure to the backend.+ for (const input of ["--ctx-size", "--ctx-size=", "--ctx-size --numa"]) {+ const out = diagnoseExtraArgs(input, CATALOG);+ assert.ok(+ out.some((d) => d.level === "error" && d.message.includes("needs a number")),+ `${input}: ${JSON.stringify(out)}`,+ );+ }+});++test("a numeric flag outside its range is an error", () => {+ // The two ranges the backend's parsers actually enforce: a context cannot be+ // negative, and -1 is the lowest meaningful layer count (all of them).+ assert.ok(+ diagnoseExtraArgs("--ctx-size -1", CATALOG).some(+ (d) => d.level === "error" && d.message.includes("cannot be negative"),+ ),+ );+ assert.ok(+ diagnoseExtraArgs("-ngl -2", CATALOG).some(+ (d) => d.level === "error" && d.message.includes("-1 or more"),+ ),+ );+ // And -1 itself is fine, or the editor would refuse the ordinary way of asking+ // for every layer.+ assert.ok(+ !diagnoseExtraArgs("-ngl -1", CATALOG).some((d) => d.level === "error"),+ );+});++test("a stored flag this build refuses is dropped with its value", () => {+ // Hydration turns a stored list into an explicit request, which /load validates+ // strictly instead of dropping the flag the way the carry-over paths do. Leaving+ // the value behind would hand llama.cpp a bare positional it reads as a model.+ const managed = new Set(["--log-file", "--agent"]);+ assert.deepEqual(+ dropManagedExtraArgs(+ ["--log-file", "/var/log/llama.log", "--numa", "distribute"],+ managed,+ ),+ ["--numa", "distribute"],+ );+ assert.deepEqual(+ dropManagedExtraArgs(["--agent", "--numa", "distribute"], managed),+ ["--numa", "distribute"],+ );+ assert.deepEqual(+ dropManagedExtraArgs(["--log-file=/x", "--top-k=20"], managed),+ ["--top-k=20"],+ );+ // Nothing to drop is the list unchanged, and an empty denylist changes nothing.+ const clean = ["--numa", "distribute"];+ assert.deepEqual(dropManagedExtraArgs(clean, managed), clean);+ assert.deepEqual(dropManagedExtraArgs(clean, new Set<string>()), clean);+});++test("a value-taking flag with nothing after it is an error too", () => {+ // _last_flag_value raises for these groups from inside validate_extra_args, so a+ // shadowing note on its own left Load enabled for a request that 400s.+ for (const input of ["--cache-type-k=", "--top-k 20 -sm", "--split-mode="]) {+ const out = diagnoseExtraArgs(input, CATALOG);+ assert.ok(+ out.some((d) => d.level === "error" && d.message.includes("needs a value")),+ `${input}: ${JSON.stringify(out)}`,+ );+ }+ // A value that is there says nothing about presence.+ assert.ok(+ !diagnoseExtraArgs("--cache-type-k q8_0", CATALOG).some(+ (d) => d.level === "error",+ ),+ );+});++test("the stored sanitizer removes everything this build would refuse", () => {+ // Not only denied flags: the bounds, control characters and unpaired surrogates+ // are all new refusals that a list saved by the previous release can trip, and+ // hydration turns that list into an explicit request. Each of these mirrors a+ // case pinned against drop_managed_flags in the backend suite.+ const managed = new Set(["--log-file"]);+ const control = `${String.fromCharCode(0x1b)}[2Jx`;+ const surrogate = String.fromCharCode(0xd800);++ assert.deepEqual(+ sanitizeStoredExtraArgs(+ ["--log-file", "/var/log/llama.log", "--numa", "distribute"],+ managed,+ ),+ ["--numa", "distribute"],+ );+ // A poisoned value takes its flag with it, or the flag is left expecting one and+ // eats the next token instead.+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--chat-template", control, "--top-k", "20"], managed),+ ["--top-k", "20"],+ );+ assert.deepEqual(+ sanitizeStoredExtraArgs(+ ["--chat-template", surrogate, "--top-k", "20"],+ managed,+ ),+ ["--top-k", "20"],+ );+ // And a poisoned flag takes its value, or the value is left as a bare positional+ // that llama-server reads as a model path.+ assert.deepEqual(+ sanitizeStoredExtraArgs([`--grammar${control}`, "root", "--top-k", "20"], managed),+ ["--top-k", "20"],+ );+ // The bounds, shed from the tail exactly as the backend sheds them.+ assert.equal(+ sanitizeStoredExtraArgs(new Array(300).fill("--verbose"), managed).length,+ 256,+ );+ // A clean list is untouched.+ const clean = ["--numa", "distribute"];+ assert.deepEqual(sanitizeStoredExtraArgs(clean, managed), clean);+});++test("the sanitizer trims to the HOST's bounds, not the constants", () => {+ // A Windows server takes 24 KiB, not 32, and holds a quoted-command budget on top+ // of it. Trimming to the wider constant leaves a list /load answers 400 on, which+ // is the one outcome hydrating a stored override is supposed to prevent.+ const managed = new Set<string>();+ const stored = ["--grammar", "x".repeat(30000), "--top-k", "20"];+ assert.deepEqual(sanitizeStoredExtraArgs(stored, managed), stored);+ assert.deepEqual(+ sanitizeStoredExtraArgs(stored, managed, { maxBytes: 24 * 1024 }),+ [],+ );+ // The quoted length, not the byte count: a token needing quotes doubles the+ // backslash runs before its quotes, so this passes the byte bound and fails the+ // command-line one.+ const quoted = ["--grammar", `${"\\".repeat(10)}" `.repeat(400)];+ assert.deepEqual(sanitizeStoredExtraArgs(quoted, managed), quoted);+ assert.deepEqual(+ sanitizeStoredExtraArgs(quoted, managed, {+ maxBytes: 24 * 1024,+ windowsCommandBudget: 8192,+ }),+ [],+ );+ // Zero means "not known", not "nothing fits": an older server answers the+ // catalogue without either field.+ assert.deepEqual(+ sanitizeStoredExtraArgs(stored, managed, {+ maxBytes: 0,+ windowsCommandBudget: 0,+ }),+ stored,+ );+});++test("a two-value flag is shed whole when the bounds bite", () => {+ // Mirrors drop_managed_flags: dropping END alone leaves START looking like an+ // ordinary value, and llama-server refuses the option outright.+ const managed = new Set<string>();+ assert.deepEqual(+ sanitizeStoredExtraArgs(+ ["--top-k", "20", "--control-vector-layer-range", "1", "x".repeat(40000)],+ managed,+ ),+ ["--top-k", "20"],+ );+ // Intact, it survives.+ const whole = ["--control-vector-layer-range", "1", "10"];+ assert.deepEqual(sanitizeStoredExtraArgs(whole, managed), whole);+});++test("a whole surrogate pair is a character, not a fault", () => {+ // The class-based check matched both units of every emoji, so a chat template or+ // grammar carrying one was dropped on hydration even though Python encodes it+ // without complaint. Only half a pair is refused.+ const emoji = String.fromCodePoint(0x1f600);+ const lone = String.fromCharCode(0xd800);+ const managed = new Set<string>();++ assert.deepEqual(+ sanitizeStoredExtraArgs(["--chat-template", `hi ${emoji}`, "--top-k", "20"], managed),+ ["--chat-template", `hi ${emoji}`, "--top-k", "20"],+ );+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--chat-template", lone, "--top-k", "20"], managed),+ ["--top-k", "20"],+ );+ // And the editor says the same about what is typed.+ assert.ok(+ !diagnoseExtraArgs(`--chat-template ${emoji}`, CATALOG).some(+ (d) => d.level === "error",+ ),+ );+ assert.ok(+ diagnoseExtraArgs(`--chat-template ${lone}`, CATALOG).some(+ (d) => d.level === "error" && d.message.includes("incomplete character"),+ ),+ );+});++test("a multi-line quoted value is not a control-character fault", () => {+ // _has_control_characters allows tab and newline on purpose: a grammar, a JSON+ // schema or a chat template is routinely multi-line, and quoting one into a+ // single argv token is what the box is for.+ const grammar = "--grammar 'root ::= [0-9]+\n | \"x\"'";+ assert.ok(+ !diagnoseExtraArgs(grammar, CATALOG).some((d) => d.level === "error"),+ JSON.stringify(diagnoseExtraArgs(grammar, CATALOG)),+ );+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--grammar", "a\nb\tc", "--top-k", "20"], new Set<string>()),+ ["--grammar", "a\nb\tc", "--top-k", "20"],+ );+ // An escape sequence is still refused.+ assert.ok(+ diagnoseExtraArgs(`--grammar ${String.fromCharCode(0x1b)}x`, CATALOG).some(+ (d) => d.level === "error",+ ),+ );+});++test("a value with no flag in front of it is an error", () => {+ // validate_extra_args refuses it, and llama-server answers "invalid argument"+ // and refuses to start, so without this the box looks fine and the load 400s.+ const out = diagnoseExtraArgs("--top-k 20 /models/other.gguf", CATALOG);+ assert.ok(+ out.some((d) => d.level === "error" && d.message.includes("belongs to no flag")),+ JSON.stringify(out),+ );+ // The two-value option is not one of those.+ assert.ok(+ !diagnoseExtraArgs("--control-vector-layer-range 1 10", CATALOG).some(+ (d) => d.level === "error",+ ),+ );+ // Nor is an ordinary value.+ assert.ok(+ !diagnoseExtraArgs("--numa distribute", CATALOG).some(+ (d) => d.level === "error",+ ),+ );+});++test("a value after a switch is the typo llama-server calls it", () => {+ // -v, --verbose, --log-verbose is declared with no value in this build's help, and+ // "--verbose foo" exits with "error: invalid argument: foo".+ const out = diagnoseExtraArgs("--verbose foo", CATALOG);+ assert.ok(+ out.some((d) => d.level === "error" && d.message.includes("belongs to no flag")),+ JSON.stringify(out),+ );+ // A flag that does take one is untouched, and an unverified build says nothing:+ // only what the catalogue actually declares is acted on.+ assert.ok(+ !diagnoseExtraArgs("--numa distribute", CATALOG).some(+ (d) => d.level === "error",+ ),+ );+});++test("the size limits are the host's, not this file's", () => {+ // Windows caps extras lower, because the whole command line shares one 32767+ // character budget, and the editor has to draw the same line the load does.+ const windows: LlamaFlagCatalog = {+ ...CATALOG,+ maxBytes: 24 * 1024,+ windowsCommandBudget: 24575,+ };+ const big = `--grammar ${"x".repeat(25 * 1024)}`;+ assert.ok(+ diagnoseExtraArgs(big, windows).some(+ (d) => d.level === "error" && d.message.includes("24576"),+ ),+ );+ // The same input is fine where the host allows 32 KiB.+ assert.ok(!diagnoseExtraArgs(big, CATALOG).some((d) => d.level === "error"));+});++test("what the quoting makes of an argument counts on Windows", () => {+ // list2cmdline doubles a backslash run before a quote, so bytes alone do not say+ // whether the launch fits. Same rule as the backend's own check.+ const windows: LlamaFlagCatalog = {+ ...CATALOG,+ maxBytes: 24 * 1024,+ windowsCommandBudget: 24575,+ };+ const escaped = `${"\\".repeat(10)}"`.repeat(2000);+ assert.ok(escaped.length < 24 * 1024);+ assert.ok(+ diagnoseExtraArgs(`--grammar ${JSON.stringify(escaped)}`, windows).some(+ (d) => d.level === "error" && d.message.includes("after quoting"),+ ),+ );+});++// The harness has no DOM renderer, so the row's contract is pinned the way the+// sibling model-config tests do it.++const pageSource = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/model-picker/components/model-config-page.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+);++test("the row stores argv tokens, not the typed string", () => {+ const row = pageSource.slice(pageSource.indexOf("function ExtraArgsRow("));+ const body = row.slice(0, row.indexOf("\n}\n")).replace(/\s+/g, " ");+ // The wire format is one token per entry; storing the raw string would make the+ // backend split it, which it does not do.+ assert.match(+ body,+ /update\(\{ llamaExtraArgs: tokens\.length > 0 \? tokens : null \}\)/,+ );+ // Cleared reads as null here and becomes an explicit [] at the API boundary.+ assert.match(body, /const \{ tokens \} = parseExtraArgs\(next\)/);+});++test("the box is filled from the stored flags, not left looking empty", () => {+ const panel = pageSource.slice(+ pageSource.indexOf("export function ModelConfigPage("),+ );+ const body = panel.replace(/\s+/g, " ");+ // The overrides API can set these with no UI involved, and this panel's config+ // comes from local storage, so the only way the box can show what is actually+ // set is to ask. An empty box would read as "no flags" and the first edit would+ // submit a list that dropped them.+ // Resolved by the backend, whose folding rules are the ones the load applies.+ assert.match(body, /fetchLoadExtraArgs\(loadId, configId, target\.ggufVariant, keys\)/);+ // Through the resolver, not a literal lookup: the backend folds identities and+ // falls back from repo:QUANT to the bare repo before it reads a row.+ // The candidate keys still travel, as the fallback for a backend that predates+ // the resolving parameter.+ assert.match(body, /modelOverrideKey\(loadId, target\.ggufVariant\)/);+ // And through the denylist first: hydrating makes the stored list an explicit+ // request, which /load validates strictly rather than dropping a newly denied+ // flag the way the carry-over paths do.+ assert.match(body, /sanitizeStoredExtraArgs\( resolvedArgs\.tokens,/);+ // Into the config, not only the textarea. The load sends what the config holds,+ // and the route's omission path inherits from a resident process rather than+ // from this stored override, so a box that filled without the config would show+ // flags the launch did not use.+ assert.match(body, /llamaExtraArgs: stored/);+ // And the key is marked only once a response is in hand, or StrictMode's replayed+ // effect cancels the first fetch and skips the second.+ const marked = body.indexOf("extraArgsHydrated.current = identity");+ assert.ok(+ marked > body.indexOf("if (cancelled) { return; }"),+ "mark after the response",+ );+});++test("hydration is not gated behind the advanced disclosure", () => {+ // The row that displays these lives inside GgufAdvancedSettings, which is only+ // rendered while the section is open. A panel opened with it collapsed would+ // never fetch, and a cold load would then launch without the stored arguments,+ // so the fetch belongs in the parent that always mounts.+ const row = pageSource.slice(pageSource.indexOf("function ExtraArgsRow("));+ const rowBody = row.slice(0, row.indexOf("\n}\n"));+ assert.doesNotMatch(rowBody, /fetchLoadExtraArgs/);+ const advanced = pageSource.slice(+ pageSource.indexOf("function GgufAdvancedSettings("),+ pageSource.indexOf("export function ModelConfigPage("),+ );+ assert.doesNotMatch(advanced, /fetchLoadExtraArgs/);+});++test("the row does not withdraw its objection when it unmounts", () => {+ const row = pageSource.slice(pageSource.indexOf("function ExtraArgsRow("));+ const body = row.slice(0, row.indexOf("\n}\n")).replace(/\s+/g, " ");+ // Collapsing Advanced settings unmounts the row while its tokens stay in the+ // config and still go out with the load, so a cleanup that reset the flag would+ // re-enable Load for a request the backend refuses.+ const effect = body.slice(body.indexOf("onLoadableChange(loadable)"));+ assert.doesNotMatch(+ effect.slice(0, effect.indexOf("const commit")),+ /return \(\) => onLoadableChange/,+ );+ // The panel retires it on a model change instead.+ assert.match(+ pageSource.replace(/\s+/g, " "),+ /setExtraArgsLoadable\(true\); setExtraArgsHydrating\(target\.isGguf && !isDiffusion\); \}, \[configId, target\.ggufVariant, target\.isGguf, isDiffusion\]\)/,+ );+});++test("a config that never read the stored value is not sent as a clear", () => {+ const overrides = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/model-picker/api/model-overrides.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ ).replace(/\s+/g, " ");+ // The route preserves llama_extra_args when omitted, which is what kept CLI-set+ // flags alive while this panel had no control. Sending [] for a config that never+ // loaded them would wipe them on the first save.+ assert.match(+ overrides,+ /if \(config\.llamaExtraArgs !== undefined\) \{ payload\.llama_extra_args = config\.llamaExtraArgs \?\? \[\]; \}/,+ );+});++test("the load sends the flags only once they are known", () => {+ const composer = readFileSync(+ fileURLToPath(+ new URL("../src/features/chat/shared-composer.tsx", import.meta.url),+ ),+ "utf8",+ ).replace(/\s+/g, " ");+ assert.match(+ composer,+ /ownConfig\.llamaExtraArgs !== undefined \? .* \{ llama_extra_args: ownConfig\.llamaExtraArgs \?\? \[\] \} : \{\}/,+ );+});++test("the panel's own Load goes through the runtime, which sends them too", () => {+ // Found by loading a model from the panel and reading the emitted command: the+ // flags were in the config and absent from the argv, because this hook is the+ // path the Load button takes and it built the payload field by field.+ const runtime = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/chat/hooks/use-chat-model-runtime.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ ).replace(/\s+/g, " ");+ assert.match(+ runtime,+ /const loadLlamaExtraArgs = pendingLoadConfig\?\.llamaExtraArgs/,+ );+ assert.match(+ runtime,+ /isGguf && !targetIsDiffusion && loadLlamaExtraArgs !== undefined \? \{ llama_extra_args: loadLlamaExtraArgs \?\? \[\] \} : \{\}/,+ );+});++test("the box follows a config change it did not make", () => {+ const row = pageSource.slice(pageSource.indexOf("function ExtraArgsRow("));+ const body = row.slice(0, row.indexOf("\n}\n")).replace(/\s+/g, " ");+ // Reset and the parent's hydration both replace llamaExtraArgs while this row is+ // mounted. Without this the textarea keeps its old text and disagrees with what+ // Load sends; with a plain re-seed on every change it re-quotes a half-typed line.+ assert.match(body, /if \(external === selfWritten\.current\) \{ return; \}/);+ assert.match(body, /selfWritten\.current = formatExtraArgs\(/);+});++test("load waits for the stored arguments to be read", () => {+ const panel = pageSource.slice(+ pageSource.indexOf("export function ModelConfigPage("),+ );+ const body = panel.replace(/\s+/g, " ");+ // A click that beats the fetch would launch a cold model without them, and /load+ // cannot inherit from a process that is not running.+ assert.match(body, /extraArgsHydrating \|\|/);+ // But never for good: a failed or hanging overrides read releases the gate.+ assert.match(body, /\.finally\(\(\) => \{ .*setExtraArgsHydrating\(false\)/);+ assert.match(body, /setTimeout\(\(\) => setExtraArgsHydrating\(false\), \d+\)/);+ // And the short deadline is on the CATALOGUE, not on the gate: the first read of+ // it runs --help on a cold binary, and releasing Load on that timer would let a+ // click through while the stored arguments were already in hand.+ // And it waits on the DENYLIST, which needs no binary, rather than on the+ // catalogue behind a cold --help.+ assert.match(body, /loadManagedLlamaFlags\(\)/);+ assert.doesNotMatch(body, /loadLlamaFlagCatalog\(\)[^;]*Promise\.all/);+});++test("a model with no such field does not wait for one", () => {+ const panel = pageSource.slice(+ pageSource.indexOf("export function ModelConfigPage("),+ );+ const body = panel.replace(/\s+/g, " ");+ // The row and the load payload are both GGUF-only, so a Transformers or MLX model+ // must not have Load held shut while two requests it will never use settle.+ // A diffusion GGUF is GGUF-shaped but runs through the diffusion shim, which+ // appends no llama-server flags, so it must not wait either.+ assert.match(+ body,+ /if \(!target\.isGguf \|\| resolvedIsDiffusion\) \{ .*setExtraArgsHydrating\(false\); return; \}/,+ );+ assert.match(body, /useState\( \(\) => target\.isGguf && !isDiffusion, \)/);+});++test("a diffusion classification retires the argument objection", () => {+ const panel = pageSource.slice(+ pageSource.indexOf("export function ModelConfigPage("),+ );+ const body = panel.replace(/\s+/g, " ");+ // withoutUnsupportedDiffusionSettings strips the arguments from what loads while+ // the row keeps its objection (it deliberately has no cleanup), so Load would+ // stay disabled over arguments the request no longer carries.+ assert.match(+ body,+ /if \(resolvedIsDiffusion\) \{ setExtraArgsLoadable\(true\); \}/,+ );+});++test("hydration asks under the keys the load path uses", () => {+ const panel = pageSource.slice(+ pageSource.indexOf("export function ModelConfigPage("),+ );+ const body = panel.replace(/\s+/g, " ");+ // A cached GGUF outside the active HF cache loads by its snapshot path while+ // configId is the repo id, and the auto-switch loader reads the path-qualified+ // key first, so an override left there is the one API loads apply.+ assert.match(body, /modelOverrideKey\(loadId, target\.ggufVariant\), modelOverrideKey\(configId, target\.ggufVariant\), loadId,/);+ // Including the filename-label key an early build wrote for a loose .gguf.+ assert.match(body, /fileVariant \? \[`\$\{loadId\}:\$\{fileVariant\}`\] : \[\]/);+});++test("a rollback restores the previous model with its arguments", () => {+ const runtime = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/chat/hooks/use-chat-model-runtime.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ ).replace(/\s+/g, " ");+ // By the time this runs the TARGET is resident, so an omitted field inherits+ // across models, which the route refuses, and the previous model would come back+ // without the arguments it had been running.+ assert.match(+ runtime,+ /stateBeforeUnload\.loadedLlamaExtraArgs != null \? \{ llama_extra_args: stateBeforeUnload\.loadedLlamaExtraArgs \}/,+ );+ // And the snapshot is kept on every successful load, not only an explicit one,+ // taken from the server's own echo first: a reload that omits the field but sets+ // max_seq_length has its inherited --ctx-size stripped before launch, and the+ // status refresh that would notice runs while the load is still in flight.+ assert.match(+ runtime,+ /loadedLlamaExtraArgs: loadResponse\.requested_llama_extra_args !== undefined/,+ );+ assert.match(runtime, /: loadLlamaExtraArgs !== undefined/);+});++test("a hydrated list is judged even when the row cannot be", () => {+ const panel = pageSource.slice(+ pageSource.indexOf("export function ModelConfigPage("),+ );+ const body = panel.replace(/\s+/g, " ");+ // With Advanced collapsed the row never mounts, so nothing objects to a stored+ // list this build refuses (the overrides route only validates its shape), and+ // Load would be live for a request that comes back 400.+ assert.match(body, /const hydratedIsLoadable = extraArgsAreLoadable\( diagnoseExtraArgs\(formatExtraArgs\(stored\)/);+ // But not over an edit made while the request was out: the row is judging that+ // text, and replacing its verdict re-enabled Load for invalid input.+ assert.match(+ body,+ /if \(configRef\.current\.llamaExtraArgs !== undefined\) \{ .*return; \} setExtraArgsLoadable\(hydratedIsLoadable\)/,+ );+});++test("the runtime preflight is sized with the arguments the load sends", () => {+ const runtime = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/chat/hooks/use-chat-model-runtime.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ ).replace(/\s+/g, " ");+ // A --ctx-size or cache override changes the memory /validate estimates. During+ // training an approval it did not size for means unloading the resident model and+ // having /load refuse the target, which is a rollback the user never asked for.+ const validateCall = runtime.slice(+ runtime.indexOf("await validateModel({"),+ runtime.indexOf("// Upgrade consent runs before"),+ );+ assert.match(+ validateCall,+ /loadLlamaExtraArgs !== undefined \? \{ llama_extra_args: loadLlamaExtraArgs \?\? \[\] \}/,+ );+});++test("a catalogue read from the previous binary is discarded", () => {+ const flagsApi = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/model-picker/api/llama-flags.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ ).replace(/\s+/g, " ");+ // A switch that completes mid-request must not have the old build's flags written+ // back, and the next caller must not be handed that same promise.+ assert.match(flagsApi, /catalogGeneration \+= 1;/);+ assert.match(flagsApi, /inFlightCatalog = null;/);+ assert.match(+ flagsApi,+ /if \(generation !== catalogGeneration\) \{ .*return null; \}/,+ );+});++test("a catalogued flag left without its value is refused", () => {+ // The catalogue is the only place a flag's arity is known: the backend validator+ // cannot ask the binary, so a text ending in "--rope-scaling" used to leave Load+ // enabled and llama-server then exited during startup, which is a failed load+ // instead of a red line under the box.+ assert.ok(levels("--rope-scaling").includes("error"));+ assert.ok(levels("--top-k 20 --numa").includes("error"));+ assert.deepEqual(+ diagnoseExtraArgs("--numa", CATALOG).map((d) => d.message),+ ["--numa needs a value after it."],+ );+ // Given its value, it is fine, and so is a switch on its own.+ assert.deepEqual(diagnoseExtraArgs("--numa distribute", CATALOG), []);+ // A switch on its own owes nothing (this fixture's help lists it as a switch+ // without describing it, hence the unrelated unknown-flag warning).+ assert.ok(!levels("--verbose").includes("error"));+ // The attached spelling is refused instead: llama.cpp looks the whole token up in+ // its option map, so "--numa=distribute" is an argument it has never heard of+ // (measured on b10342 and b10360, "error: invalid argument").+ assert.deepEqual(+ diagnoseExtraArgs("--numa=distribute", CATALOG).map((d) => d.message),+ ['llama-server does not read "--numa=value". Write --numa and its value as two arguments.'],+ );+});++test("an unverified flag keeps the benefit of the doubt at the end", () => {+ // A build this Studio could not probe, or a flag newer than the help it read:+ // calling either a missing value would disable Load over a launch that works.+ const unverified: LlamaFlagCatalog = {+ flags: {},+ managed: new Set<string>(),+ switches: new Set<string>(),+ maxBytes: 0,+ windowsCommandBudget: 0,+ defaultParallelSlots: 0,+ probeOk: false,+ };+ assert.deepEqual(diagnoseExtraArgs("--rope-scaling", unverified), []);+ assert.deepEqual(diagnoseExtraArgs("--rope-scaling", null), []);+ // Catalogued build, flag it has never heard of: warned about as unknown, not+ // refused for a value it may not even take.+ assert.deepEqual(levels("--tempp"), ["warning"]);+ assert.ok(!levels("--tempp").includes("error"));+});++test("a two-value flag left short is refused whatever the catalogue says", () => {+ // Its arity is known without a probe, and it is the one the backend validator+ // checks itself, so the two ends agree.+ const unverified: LlamaFlagCatalog = {+ flags: {},+ managed: new Set<string>(),+ switches: new Set<string>(),+ maxBytes: 0,+ windowsCommandBudget: 0,+ defaultParallelSlots: 0,+ probeOk: false,+ };+ assert.equal(levels("--control-vector-layer-range 1", unverified)[0], "error");+ assert.equal(levels("--control-vector-layer-range", unverified)[0], "error");+ assert.deepEqual(+ diagnoseExtraArgs("--control-vector-layer-range 1 10", unverified),+ [],+ );+ // The attached spelling is refused as such, rather than read as one of the two:+ // llama.cpp has no such spelling to be half of.+ // The attached spelling is refused as such, rather than read as one of the two:+ // llama.cpp has no such spelling for this to be half of, whether an END follows+ // it or not.+ for (const text of [+ "--control-vector-layer-range=1",+ "--control-vector-layer-range=1 10",+ ]) {+ assert.ok(+ diagnoseExtraArgs(text, unverified).some(+ (d) => d.level === "error" && d.message.includes("does not read"),+ ),+ text,+ );+ }+});++test("Manual GPU memory reports the offload flags it removes", () => {+ // /load calls strip_shadowing_flags(strip_offload=True) in Manual mode. The layer+ // count survives that, because the route translates it into the first-class field+ // first; nothing does the same for the MoE count or the fitter, so saying they win+ // was false and the model quietly ran the control's value instead.+ const manual = (input: string) =>+ diagnoseExtraArgs(input, CATALOG, { manualGpuMemory: true }).map((d) => d.message);+ assert.ok(+ manual("--n-cpu-moe 10")[0].includes("will be removed"),+ manual("--n-cpu-moe 10")[0],+ );+ assert.ok(manual("-ncmoe 10")[0].includes("-ncmoe will be removed"));+ assert.ok(manual("--fit on")[0].includes("will be removed"));+ // Nothing is refused: the load still runs, just without them.+ assert.ok(!manual("--n-cpu-moe 10").includes("error"));+ assert.equal(+ diagnoseExtraArgs("--n-cpu-moe 10", CATALOG, { manualGpuMemory: true }).every(+ (d) => d.level !== "error",+ ),+ true,+ );+ // In Default mode they are passed, and the note about who wins is the true one.+ assert.ok(+ diagnoseExtraArgs("--n-cpu-moe 10", CATALOG, {})+ .map((d) => d.message)+ .join(" ")+ .includes("wins"),+ );+ // The layer count is translated, not dropped, so it still reads as winning.+ assert.ok(+ diagnoseExtraArgs("-ngl 20", CATALOG, { manualGpuMemory: true })+ .map((d) => d.message)+ .join(" ")+ .includes("wins"),+ );+});++test("a pass-through batch below the floor is refused", () => {+ // The loader raises the --batch-size it emits itself (max(slots, 2), measured+ // upstream: b1 aborts at any slot count, b4/p8 aborts, b8/p8 loads), but a+ // pass-through -b is appended after it and wins, so the load starts and+ // llama-server aborts on GGML_ASSERT instead.+ const at = (input: string, batchFloor: number) =>+ diagnoseExtraArgs(input, CATALOG, { batchFloor });+ assert.ok(at("-b 1", 2).some((d) => d.level === "error"));+ assert.ok(at("--batch-size 0", 2).some((d) => d.level === "error"));+ assert.ok(at("--batch-size 4", 8).some((d) => d.level === "error"));+ assert.match(+ at("--batch-size 4", 8).filter((d) => d.level === "error")[0].message,+ /8 parallel slot/,+ );+ // At or above the floor it passes (the note about shadowing the control stays),+ // and the micro-batch is not policed here.+ const errors = (input: string, batchFloor: number) =>+ at(input, batchFloor).filter((d) => d.level === "error");+ assert.deepEqual(errors("--batch-size 8", 8), []);+ assert.deepEqual(errors("-b 2", 2), []);+ assert.deepEqual(errors("-ub 1", 2), []);+ // A blank slot count leaves only the hard floor of 2, the same limit the batch+ // control itself asserts.+ assert.deepEqual(errors("-b 2", 1), []);+});++test("Model Memory reports the flags its settings remove", () => {+ // apply_model_memory_policy runs before the extras reach the command line, so an+ // --mlock typed here was shown, saved, and never passed.+ const keep = (input: string) =>+ diagnoseExtraArgs(input, CATALOG, { keepResident: true }).map(+ (d) => d.message,+ );+ const noReserve = (input: string) =>+ diagnoseExtraArgs(input, CATALOG, { noRamReserve: true }).map(+ (d) => d.message,+ );+ assert.match(keep("--mlock")[0], /will be removed/);+ assert.match(keep("--load-mode mmap")[0], /Keep model in GPU memory/);+ assert.match(noReserve("--no-mmap")[0], /Don't reserve system RAM/);+ // No-reserve leaves the loaders that hold no full host copy alone.+ assert.equal(+ noReserve("--direct-io").some((message) => /will be removed/.test(message)),+ false,+ );+ // With both on, no-reserve is the one that runs, and it names itself.+ assert.match(+ diagnoseExtraArgs("--mlock", CATALOG, {+ keepResident: true,+ noRamReserve: true,+ })[0].message,+ /Don't reserve system RAM/,+ );+ // With neither, nothing is stripped and a hand-typed flag still applies.+ assert.equal(+ diagnoseExtraArgs("--mlock", CATALOG, {}).some((d) =>+ /will be removed/.test(d.message),+ ),+ false,+ );+});++test("llama.cpp's underscore spelling is not read as an attached value", () => {+ // _flag_name folds --ctx_size to --ctx-size, and the binary takes both (measured+ // on b10360: `llama-server --ctx_size 4096 --help` prints its help). Deciding+ // attachment by comparing the folded name against the raw token called the 4096 a+ // bare value and disabled Load for a spelling that works.+ assert.deepEqual(+ diagnoseExtraArgs("--numa distribute", CATALOG).filter(+ (d) => d.level === "error",+ ),+ [],+ );+ assert.deepEqual(+ diagnoseExtraArgs("--rope_scaling yarn", CATALOG).filter(+ (d) => d.level === "error",+ ),+ [],+ );+ // Still attached when it really is: an "=" form, or a short with its value glued+ // on. --n_parallel folds onto the managed --n-parallel and stays refused.+ assert.ok(+ diagnoseExtraArgs("--rope_scaling yarn --numa", CATALOG).some(+ (d) => d.level === "error",+ ),+ );+ assert.ok(+ diagnoseExtraArgs("--n_parallel 8", CATALOG).some(+ (d) => d.level === "error",+ ),+ );+});++test("a flag that interrupts another's value is refused", () => {+ // "--numa --verbose" leaves --numa without the value this build's help says it+ // takes, and llama-server exits during startup. The end-of-input check could not+ // see it: the obligation was overwritten by the next flag first.+ const messages = (input: string) =>+ diagnoseExtraArgs(input, CATALOG)+ .filter((d) => d.level === "error")+ .map((d) => d.message);+ assert.deepEqual(messages("--numa --verbose"), [+ "--numa needs a value after it.",+ ]);+ assert.deepEqual(messages("--numa --numa distribute"), [+ "--numa needs a value after it.",+ ]);+ // A switch owes nothing, and an unverified flag keeps the benefit of the doubt.+ assert.deepEqual(messages("--verbose --numa distribute"), []);+ assert.deepEqual(messages("--tempp --numa distribute"), []);+});++test("the batch floor follows the server-wide slot default", () => {+ // With Slots blank the launch serves the server-wide --parallel (4 in run.py),+ // so -b 2 aborts even though it clears the hard floor of 2. The catalogue+ // publishes that number because the browser cannot see it.+ const withDefault = { ...CATALOG, defaultParallelSlots: 4 };+ assert.ok(+ diagnoseExtraArgs("-b 2", withDefault, { batchFloor: 4 }).some(+ (d) => d.level === "error",+ ),+ );+ assert.deepEqual(+ diagnoseExtraArgs("-b 4", withDefault, { batchFloor: 4 }).filter(+ (d) => d.level === "error",+ ),+ [],+ );+});++test("the sanitizer drops what the validator refuses on shape", () => {+ // The upgrade case this exists for: a list saved by an older build, hydrated into+ // an EXPLICIT request that /load validates strictly. drop_managed_flags repairs+ // these on the server by re-validating after every cut it makes; this mirror trims+ // by size alone, so it has to know the same rules.+ const managed = new Set<string>();+ // A token belonging to no flag: llama-server would read it as the model path.+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--top-k", "20", "stray"], managed),+ ["--top-k", "20"],+ );+ assert.deepEqual(+ sanitizeStoredExtraArgs(["stray", "--top-k", "20"], managed),+ ["--top-k", "20"],+ );+ // A two-value option left half-written, in both spellings.+ assert.deepEqual(+ sanitizeStoredExtraArgs(+ ["--top-k", "20", "--control-vector-layer-range", "1"],+ managed,+ ),+ ["--top-k", "20"],+ );+ assert.deepEqual(+ sanitizeStoredExtraArgs(+ ["--top-k", "20", "--control-vector-layer-range=1", "x".repeat(40000)],+ managed,+ ),+ ["--top-k", "20"],+ );+ // The attached spelling goes whether it is whole or not: the backend refuses it+ // outright, so hydrating one into an explicit request would 400 the load. Only+ // that token, the way drop_managed_flags sheds it, so the rest still loads.+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--control-vector-layer-range=1", "10"], managed),+ [],+ );+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--top-k=20", "--numa", "distribute"], managed),+ ["--numa", "distribute"],+ );+ // A value the backend's own parser refuses takes its flag with it, and only it:+ // the server sheds its whole tail instead, which costs whatever followed.+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--ctx-size", "abc", "--top-k", "20"], managed),+ ["--top-k", "20"],+ );+ assert.deepEqual(sanitizeStoredExtraArgs(["--cache-type-k"], managed), []);+ // Valid values are untouched, including the ones whose minimum is negative.+ for (const list of [+ ["--ctx-size", "0"],+ ["-ngl", "-1"],+ ["--cache-type-k", "q8_0"],+ ["--numa", "distribute"],+ ["--ctx_size", "4096"],+ ]) {+ assert.deepEqual(sanitizeStoredExtraArgs(list, managed), list);+ }+});++test("a scaled sidecar may take its scale as a second token", () => {+ // Today's llama.cpp writes it into the value ("--lora-scaled FNAME:SCALE") and+ // older builds took it separately ("--lora-scaled FNAME SCALE"); the launcher+ // reads both in _sidecar_weight_files. So the second token is allowed and never+ // required: demanding it would refuse the current syntax, and refusing it broke a+ // list that loaded before the positional check existed.+ const scaled: LlamaFlagCatalog = {+ ...CATALOG,+ flags: {+ ...CATALOG.flags,+ "--lora-scaled": "path with scaling",+ "--control-vector-scaled": "control vector with scaling",+ },+ };+ const errors = (input: string) =>+ diagnoseExtraArgs(input, scaled).filter((d) => d.level === "error");+ assert.deepEqual(errors("--lora-scaled /a.gguf 0.5"), []);+ assert.deepEqual(errors("--lora-scaled /a.gguf:0.5"), []);+ assert.deepEqual(errors("--control-vector-scaled /v.gguf 0.8 --top-k 20"), []);+ assert.deepEqual(errors("--lora-scaled /a.gguf"), []);+ // A third bare token still has no owner.+ assert.equal(errors("--lora-scaled /a.gguf 0.5 stray").length, 1);+ // And the sanitizer keeps the pair rather than reading the scale as ownerless.+ const managed = new Set<string>();+ for (const list of [+ ["--lora-scaled", "/a.gguf", "0.5"],+ ["--lora-scaled", "/a.gguf:0.5"],+ ["--control-vector-scaled", "/v.gguf", "0.8", "--top-k", "20"],+ ]) {+ assert.deepEqual(sanitizeStoredExtraArgs(list, managed), list);+ }+});++test("a trimmed value never leaves its flag behind, whatever the spelling", () => {+ // The bounds are shed from the tail, and the flag whose value has just gone must+ // go with it: an orphan is a flag llama-server then rejects for want of a value,+ // after the switch has already unloaded the resident model. The check used to+ // compare the NORMALIZED name against the raw token, so llama.cpp's underscore+ // spelling never matched and "--grammar_file" was left standing.+ const managed = new Set<string>();+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--numa", "distribute", "--grammar_file", "x".repeat(40000)], managed),+ ["--numa", "distribute"],+ );+ // The hyphenated one behaved already, and still does.+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--numa", "distribute", "--grammar-file", "x".repeat(40000)], managed),+ ["--numa", "distribute"],+ );+ // A bare value at the tail takes nothing with it: it belongs to no flag, and the+ // token before it is a value of its own.+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--numa", "distribute", "x".repeat(40000)], managed),+ ["--numa", "distribute"],+ );+});++test("the attached spelling is refused wherever it is judged", () => {+ // llama.cpp looks the whole token up in its option map and folds only underscores,+ // so "--top-k=20" is an argument it has never heard of: measured on b10342 and+ // b10360 as "error: invalid argument: --top-k=20". Accepting it left Load enabled+ // for a switch that unloads the running model and then fails to start the next.+ const managed = new Set<string>();+ // Not --ctx-size: a control owns it, and that message names the control instead.+ for (const text of ["--top-k=20", "--rope-scaling=yarn", "--flash-attn=on"]) {+ assert.ok(+ diagnoseExtraArgs(text, CATALOG).some(+ (d) => d.level === "error" && d.message.includes("does not read"),+ ),+ text,+ );+ }+ // A managed flag keeps the message that names the control owning it.+ assert.ok(+ diagnoseExtraArgs("--parallel=8", CATALOG).every(+ (d) => !d.message.includes("does not read"),+ ),+ );+ // And an "=" inside a VALUE is the value's own syntax, not an attached one. This+ // fixture's help does not list --override-kv, hence the unrelated warning.+ assert.ok(+ diagnoseExtraArgs("--override-kv a=int:2", CATALOG).every(+ (d) => d.level !== "error",+ ),+ );+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--override-kv", "a=int:2"], managed),+ ["--override-kv", "a=int:2"],+ );+});++test("the managed answer is invalidated with the catalogue", () => {+ const flagsApi = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/model-picker/api/llama-flags.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ ).replace(/\s+/g, " ");+ // Its denylist is Unsloth's own, but it carries defaultParallelSlots beside it and+ // that is the EFFECTIVE count: a build without --kv-unified serves one slot however+ // many are configured. Updating llama.cpp from the banner left a tab that had+ // already fetched it sizing the hidden hydration check's batch floor from the+ // previous backend, so "--batch-size 2" passed on a build now serving four slots.+ assert.match(flagsApi, /cachedManaged = null; inFlightManaged = null;/);+ // The dynamic limits are what make it stale, so they have to be in that answer.+ assert.match(flagsApi, /defaultParallelSlots: number;/);+});++test("a flag quoted with stray spaces is refused, not silently sent", () => {+ // parseExtraArgs keeps what was quoted, so "'--top-k ' 20" is the token+ // "--top-k " with the space still on it. Every check here trims before it looks+ // the name up, so it read as the supported --top-k and Load stayed enabled, while+ // llama.cpp looks the WHOLE token up and answers "error: invalid argument:+ // --top-k" (measured on b10342), naming a flag that looks correct in the log.+ assert.ok(+ diagnoseExtraArgs("'--top-k ' 20", CATALOG).some(+ (d) => d.level === "error" && d.message.includes("Remove the spaces"),+ ),+ );+ // A VALUE may legitimately end in whitespace: a grammar or a chat template does.+ assert.ok(+ diagnoseExtraArgs("--grammar 'root ::= [0-9] '", CATALOG).every(+ (d) => d.level !== "error",+ ),+ );+ // And the stored sanitizer sheds it with its value, rather than hydrating a list+ // that would 400 or start a launch that fails.+ const managed = new Set<string>();+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--top-k ", "20", "--numa", "distribute"], managed),+ ["--numa", "distribute"],+ );+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--verbose ", "--numa", "distribute"], managed),+ ["--numa", "distribute"],+ );+ assert.deepEqual(+ sanitizeStoredExtraArgs(["--grammar", "root ::= x "], managed),+ ["--grammar", "root ::= x "],+ );+});++test("a quoted value that begins with a hyphen is a value, not a flag", () => {+ // parseExtraArgs takes the quotes off, and "- hello" is flag-shaped, so the row+ // called --chat-template's value missing and disabled Load over a list the backend+ // accepts and llama.cpp reads correctly: it takes the next argv element for a+ // value-taking option without looking at what it starts with.+ // A control owns --chat-template, so the note about who wins stays; what must not+ // be here is an error saying the value is missing.+ for (const text of ["--chat-template '- hello'", '--chat-template "- hello"']) {+ assert.ok(+ diagnoseExtraArgs(text, CATALOG).every((d) => d.level !== "error"),+ text,+ );+ }+ // The quoted token is not reported as an unknown flag either.+ assert.ok(+ diagnoseExtraArgs("--grammar '-x'", CATALOG).every(+ (d) => !d.message.includes("-x"),+ ),+ );+ // Position matters as much as the quotes: quoting a FLAG out of habit still reads+ // as a flag, or a list that runs would be refused.+ assert.ok(+ diagnoseExtraArgs('"--top-k" 20', CATALOG).every((d) => d.level !== "error"),+ );+ assert.ok(+ diagnoseExtraArgs("'--numa'", CATALOG).some(+ (d) => d.level === "error" && d.message.includes("needs a value"),+ ),+ );+ // With no option in front of it there is nothing for it to be the value OF, so it+ // is judged as written: flag-shaped, unknown to this build, warned about and still+ // passed. The same answer the backend gives, which reads it as a flag too.+ const orphan = diagnoseExtraArgs("'- hello'", CATALOG);+ assert.ok(orphan.every((d) => d.level !== "error"));+ assert.ok(orphan.some((d) => d.level === "warning"));+ // The tokeniser records which tokens were quoted; the token list itself is+ // unchanged, since argv has no room for that distinction.+ const parsed = parseExtraArgs("--chat-template '- hello'");+ assert.deepEqual(parsed.tokens, ["--chat-template", "- hello"]);+ assert.deepEqual([...parsed.quotedIndices], [1]);+});++test("a managed answer from the previous binary is never published", () => {+ const flagsApi = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/model-picker/api/llama-flags.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ ).replace(/\s+/g, " ");+ // Clearing the cache is not enough on its own: a managed request already on the+ // wire when llama.cpp is replaced would resolve afterwards and put the old+ // build's defaultParallelSlots back, where it would stay for the session. The+ // full catalogue has read its generation before the request and checked it+ // before publishing since the start; this path now does the same, including the+ // finally, which used to clear a newer request's in-flight promise.+ assert.match(+ flagsApi,+ /const generation = catalogGeneration; inFlightManaged \?\?=/,+ );+ assert.match(+ flagsApi,+ /if \(generation !== catalogGeneration\) \{ .*return null; \} cachedManaged = managed;/,+ );+ assert.match(+ flagsApi,+ /if \(generation === catalogGeneration\) \{ inFlightManaged = null; \}/,+ );+});diff --git a/studio/frontend/tests/llama-extra-args-override-lookup.test.ts b/studio/frontend/tests/llama-extra-args-override-lookup.test.tsnew file mode 100644index 00000000000..b9b716142b9--- /dev/null+++ b/studio/frontend/tests/llama-extra-args-override-lookup.test.ts@@ -0,0 +1,211 @@+// 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 stored row the picker reads its pass-through arguments from.+//+// This has to agree with the server, because the two act on the same data from+// different ends: the panel hydrates from a row and then sends what it found as an+// EXPLICIT list, while an API auto-switch resolves the row itself. Where they+// disagree, a model launches with one set of flags from the picker and another from+// the API, which is the kind of difference nobody thinks to look for.+//+// The rules mirrored here are resolve_model_override_key and _folded_override_matches+// in utils/openai_auto_switch_settings.py.++import assert from "node:assert/strict";+import test from "node:test";++import { registerStoreStubResolver } from "./helpers/kit.ts";++registerStoreStubResolver();++const { resolveStoredExtraArgs } = await import(+ "../src/features/model-picker/api/model-overrides.ts"+);++const ARGS = ["--numa", "distribute"];++test("an exact key wins", () => {+ assert.deepEqual(+ resolveStoredExtraArgs(+ { "unsloth/Model-GGUF:q4_k_m": { llama_extra_args: ARGS } },+ ["unsloth/Model-GGUF:q4_k_m"],+ ),+ { tokens: ARGS, explicit: true },+ );+});++test("a repo id and its quant fold by case", () => {+ // The browser lowercases the quant before storing, so a row written with the+ // upstream spelling still has to be found.+ assert.deepEqual(+ resolveStoredExtraArgs(+ { "unsloth/Model-GGUF:Q4_K_M": { llama_extra_args: ARGS } },+ ["unsloth/model-gguf:q4_k_m"],+ ),+ { tokens: ARGS, explicit: true },+ );+});++test("a POSIX path stays case-sensitive", () => {+ // /models/Foo.gguf and /models/foo.gguf are two real files, and folding them+ // would replay one model's arguments on the other.+ assert.deepEqual(+ resolveStoredExtraArgs({ "/models/Foo.gguf": { llama_extra_args: ARGS } }, [+ "/models/foo.gguf",+ ]),+ { tokens: [], explicit: false },+ );+});++test("a colon inside a POSIX filename is not a quant", () => {+ assert.deepEqual(+ resolveStoredExtraArgs(+ { "/models/foo:bar.gguf": { llama_extra_args: ARGS } },+ ["/models/foo:Bar.gguf"],+ ),+ { tokens: [], explicit: false },+ );+});++test("a Windows path folds", () => {+ assert.deepEqual(+ resolveStoredExtraArgs(+ { "C:\\Models\\Foo.gguf": { llama_extra_args: ARGS } },+ ["c:\\models\\foo.gguf"],+ ),+ { tokens: ARGS, explicit: true },+ );+});++test("a separator and a trailing slash do not make a different key", () => {+ // _fold_case_insensitive_path replaces backslashes, then trims trailing+ // separators down to the root, so all of these name one file to the server.+ for (const key of [+ "C:\\Models\\Foo.gguf",+ "c:/models/foo.gguf",+ "C:/Models/Foo.gguf/",+ ]) {+ assert.deepEqual(+ resolveStoredExtraArgs({ [key]: { llama_extra_args: ARGS } }, [+ "c:\\models\\foo.gguf",+ ]),+ { tokens: ARGS, explicit: true },+ key,+ );+ }+});++test("a UNC share folds however it is spelled", () => {+ // Written with forward slashes it still starts "//", which is the shape the+ // server tests; reading it as an ordinary POSIX path made it case-sensitive.+ assert.deepEqual(+ resolveStoredExtraArgs(+ { "\\\\Server\\Share\\Foo.gguf": { llama_extra_args: ARGS } },+ ["//server/share/foo.gguf"],+ ),+ { tokens: ARGS, explicit: true },+ );+});++test("a WSL drive mount folds like the Windows volume it is", () => {+ // _fold_case_insensitive_path treats /mnt/<letter> as a Windows path, because it+ // is one seen through Linux. Leaving it under the POSIX rule stranded an override+ // the server does apply, and a cold picker load then omitted the arguments.+ assert.deepEqual(+ resolveStoredExtraArgs(+ { "/mnt/c/models/foo.gguf": { llama_extra_args: ARGS } },+ ["/mnt/C/Models/Foo.gguf"],+ ),+ { tokens: ARGS, explicit: true },+ );+ // Not every /mnt path: /mnt/storage is an ordinary POSIX mount point.+ assert.deepEqual(+ resolveStoredExtraArgs(+ { "/mnt/storage/models/foo.gguf": { llama_extra_args: ARGS } },+ ["/mnt/storage/models/Foo.gguf"],+ ),+ { tokens: [], explicit: false },+ );+});++test("two keys that fold together resolve to nothing", () => {+ // resolve_model_override_key returns None here on purpose: picking one of them at+ // enumeration order applies another model's settings half the time.+ assert.deepEqual(+ resolveStoredExtraArgs(+ {+ "unsloth/Model-GGUF": { llama_extra_args: ARGS },+ "unsloth/model-gguf": { llama_extra_args: ["--top-k", "20"] },+ },+ ["unsloth/MODEL-gguf"],+ ),+ { tokens: [], explicit: false },+ );+});++test("the first entry that exists is the one read, fields and all", () => {+ // The auto-switch loader breaks on the first non-empty override and reads its+ // fields from there. Falling through to the bare repo because the variant row+ // happens to carry no arguments would launch the picker with flags an API load+ // would not use.+ assert.deepEqual(+ resolveStoredExtraArgs(+ {+ "unsloth/model-gguf:q4_k_m": { max_seq_length: 4096 },+ "unsloth/model-gguf": { llama_extra_args: ARGS },+ },+ ["unsloth/model-gguf:q4_k_m", "unsloth/model-gguf"],+ ),+ { tokens: [], explicit: false },+ );+});++test("an empty entry is skipped rather than stopping the search", () => {+ // `if override: break` on the server: a row with no fields is not a match.+ assert.deepEqual(+ resolveStoredExtraArgs(+ {+ "unsloth/model-gguf:q4_k_m": {},+ "unsloth/model-gguf": { llama_extra_args: ARGS },+ },+ ["unsloth/model-gguf:q4_k_m", "unsloth/model-gguf"],+ ),+ { tokens: ARGS, explicit: true },+ );+});++test("no row at all is no arguments, not an error", () => {+ assert.deepEqual(resolveStoredExtraArgs({}, ["unsloth/model-gguf"]), {+ tokens: [],+ explicit: false,+ });+});++test("a row that carries an empty list is explicit, not absent", () => {+ // The tombstone the settings page writes when the box is cleared for a quant+ // whose bare-repository row still holds arguments. Read as "nothing stored" the+ // panel omits the field on Load, and /load carries the resident model's+ // arguments over: the flags the user had just cleared come back.+ assert.deepEqual(+ resolveStoredExtraArgs(+ {+ "unsloth/model-gguf:q4_k_m": { llama_extra_args: [] },+ "unsloth/model-gguf": { llama_extra_args: ARGS },+ },+ ["unsloth/model-gguf:q4_k_m", "unsloth/model-gguf"],+ ),+ { tokens: [], explicit: true },+ );+});++test("a matched row with other fields but no arguments is not explicit", () => {+ // It stopped the search, as the server's `if override: break` does, but it said+ // nothing about arguments, so there is no clear to honour.+ assert.deepEqual(+ resolveStoredExtraArgs({ "unsloth/model-gguf": { max_seq_length: 4096 } }, [+ "unsloth/model-gguf",+ ]),+ { tokens: [], explicit: false },+ );+});diff --git a/studio/frontend/tests/llama-extra-args-panel-hydration.test.ts b/studio/frontend/tests/llama-extra-args-panel-hydration.test.tsnew file mode 100644index 00000000000..243ec46a60a--- /dev/null+++ b/studio/frontend/tests/llama-extra-args-panel-hydration.test.ts@@ -0,0 +1,216 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Two rules the panel has to keep while it hydrates the stored arguments, both about+// what happens in the window between the request going out and its answer arriving.+// Source-level, because both live inside effects of a component this suite has no+// renderer for; the behaviour they guard was found by review, not by a red test.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import path from "node:path";+import { test } from "node:test";+import { fileURLToPath } from "node:url";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const PANEL = readFileSync(+ path.join(+ HERE,+ "..",+ "src/features/model-picker/components/model-config-page.tsx",+ ),+ "utf8",+);++test("a list typed while hydration was in flight is not sanitized", () => {+ // The local list is sanitized because it can be legacy stored data this build now+ // refuses. But if the user typed during the window, that value is live input:+ // rewriting it cleared the box on "--agent" instead of showing the error, and could+ // trim a long paste behind the cursor. The snapshot tells the two apart.+ assert.match(PANEL, /const localAtStart = configRef\.current\.llamaExtraArgs;/);+ assert.match(PANEL, /local !== null && local\.length > 0 && local === localAtStart|local != null && local\.length > 0 && local === localAtStart/);+});++test("a collapsed section is re-judged once the catalogue lands", () => {+ // The row keeps its verdict when Advanced settings collapse, because the tokens+ // still go out with the load. A verdict reached before the probe answered did not+ // know which flags this build documents, and collapsing froze it: a bare --threads+ // kept Load enabled and failed at llama-server startup instead.+ assert.match(PANEL, /if \(showAdvanced \|\| !target\.isGguf \|\| resolvedIsDiffusion\) \{/);+ assert.match(PANEL, /loadLlamaFlagCatalog\(\)\.then\(\(catalog\) => \{/);+});++const ADAPTER = readFileSync(+ path.join(HERE, "..", "src/features/chat/api/chat-adapter.ts"),+ "utf8",+);++test("a background auto-load hydrates a server-only override", () => {+ // resolveInitialConfig reads local storage, so an override written through the API+ // or from another browser leaves the field undefined. Nothing is resident at+ // startup, so /load has nothing to inherit from and the model came up without the+ // arguments saved for it.+ assert.match(ADAPTER, /let resolvedExtraArgs = config\.llamaExtraArgs;/);+ assert.match(ADAPTER, /const stored = await fetchLoadExtraArgs\(/);+ // Sanitized, because this becomes an explicit list that /load validates strictly.+ assert.match(ADAPTER, /sanitizeStoredExtraArgs\(tokens, managed\?\.managed/);+ // The local copy too: it was written by whatever build was running then, so a+ // flag added to the managed set since would be sent explicitly and 400.+ assert.match(ADAPTER, /const cleaned = clean\(resolvedExtraArgs\);/);+ // Resolved under the advertised repository id as well as the load path: cached+ // inventory can hand back a different loadId, and the row was written under+ // whichever of the two was on screen.+ assert.match(ADAPTER, /candidate\.id,\n\s*candidate\.ggufVariant \?\? null,/);+ // And both the preflight and the load send what was resolved, not the raw config.+ assert.equal(+ ADAPTER.match(/llama_extra_args: resolvedExtraArgs \?\? \[\]/g)?.length,+ 2,+ );+ // A diffusion GGUF takes none of them, so it is not fetched for either.+ assert.match(ADAPTER, /candidate\.kind === "gguf" &&\s*\n?\s*!isDiffusion/);+});++const HUB = readFileSync(+ path.join(HERE, "..", "src/features/hub/hub-page.tsx"),+ "utf8",+);++test("applying from the Hub settings page carries the arguments into the load", () => {+ // applyPerModelConfigToRuntime does not store llamaExtraArgs, so a selection made+ // without the config left the field undefined: the load omitted it, the route kept+ // the resident server's old list, and an edit or a clear did nothing.+ assert.match(HUB, /forceReload: true,\n(\s*\/\/.*\n)*\s*config,/);+});++test("a collapsed section stops objecting once nothing is left to object to", () => {+ // Reset with Advanced collapsed clears the list, and the row is not mounted to+ // withdraw the verdict it left standing, so Load stayed disabled.+ assert.match(PANEL, /setExtraArgsLoadable\(true\);\n\s*return;/);+});++const COMPOSER = readFileSync(+ path.join(HERE, "..", "src/features/chat/shared-composer.tsx"),+ "utf8",+);++test("a compare pane sanitizes the local list as well as the fetched one", () => {+ // A config saved by an older build can still name a flag that is managed now, and+ // the pane sends whichever list it holds as an explicit /load argument, so the+ // comparison came back 400 instead of running.+ assert.match(COMPOSER, /const local = ownConfig\.llamaExtraArgs;/);+ assert.match(COMPOSER, /const cleaned = clean\(local\);/);+});++test("the hidden revalidation can only tighten the verdict", () => {+ // It judges the TOKENS, and formatExtraArgs quotes them back into a balanced+ // string, so an unclosed quote the row objected to reads as fine here. Raising the+ // verdict would re-enable Load over the value the user is still typing.+ assert.match(PANEL, /if \(!loadable\) \{\n\s*setExtraArgsLoadable\(false\);/);+});++test("a mounted row re-reads the catalogue when the binary changes", () => {+ // Updating llama.cpp from the banner replaces the binary while the panel stays+ // open; the row would otherwise judge arity against the old build's help.+ assert.match(PANEL, /subscribeLlamaFlagCatalog\(\(\) => setCatalogEpoch/);+ assert.match(PANEL, /\}, \[catalogEpoch\]\);/);+});++test("the hidden validation re-runs when the binary changes", () => {+ // The row's own subscription cannot help here: it is unmounted whenever this+ // check is the one running, so an in-app llama.cpp update with Advanced collapsed+ // left a verdict reached against the previous binary standing.+ assert.match(PANEL, /subscribeLlamaFlagCatalog\(\(\) =>\s*\n?\s*setHiddenCatalogEpoch/);+ assert.match(PANEL, /hiddenCatalogEpoch,\n\s*\]\);/);+});++const OVERRIDES = readFileSync(+ path.join(HERE, "..", "src/features/model-picker/api/model-overrides.ts"),+ "utf8",+);++test("the legacy overrides fallback searches the caller's own identities", () => {+ // A backend that predates the resolved field answers with the whole map, and the+ // caller has to say which keys to look under. The auto-load and compare callers+ // pass none, so the default of [] searched nothing and they launched without the+ // stored arguments against an older server.+ assert.match(OVERRIDES, /fallbackKeys\.length > 0\s*\n?\s*\? fallbackKeys/);+ assert.match(OVERRIDES, /modelOverrideKey\(loadId, ggufVariant\)/);+ assert.match(OVERRIDES, /modelOverrideKey\(aliasId, ggufVariant\)/);+});++test("the hidden hydration check knows the slot floor", () => {+ // The floor is already fetched here, and the backend refuses a batch below it+ // deterministically, so releasing Load without it opens a window where a click+ // reaches that 400.+ assert.match(+ PANEL,+ /batchFloor: effectiveBatchFloor\(configRef\.current\.nParallel, managed\)/,+ );+});++test("a build that serves one slot does not raise the floor", () => {+ // The published default is already effective, but an EXPLICIT Slots value is not:+ // a build without --kv-unified serves one slot however many are asked for, so+ // Slots 4 with "--batch-size 2" was refused here while the backend, which clamps+ // to one, accepts exactly that command. One helper at all three call sites, so the+ // row and the two hidden checks cannot drift apart.+ assert.match(PANEL, /if \(limits\?\.parallelSlotsClamped\) \{\n\s*return 2;/);+ assert.equal(+ PANEL.match(/effectiveBatchFloor\(/g)?.length,+ 4,+ "one definition and three call sites",+ );+});++const ADAPTER_AUTOLOAD = ADAPTER;++test("an auto-load records what it launched with", () => {+ // The model-loading lease is held for the whole of this load, which is the guard+ // that stops the status applier writing the baseline, so nothing else records it:+ // an immediate switch would snapshot the previous model's list, and a failed+ // switch would then restore this one with the wrong arguments.+ assert.match(+ ADAPTER_AUTOLOAD,+ /loadedLlamaExtraArgs:\s*\n?\s*loadResp\.requested_llama_extra_args !== undefined/,+ );+ // And a non-GGUF load clears it rather than leaving a GGUF's list standing.+ assert.match(ADAPTER_AUTOLOAD, /loadedLlamaExtraArgs: null,/);+});++test("a compare pane records what it launched with", () => {+ assert.match(+ COMPOSER,+ /loadedLlamaExtraArgs:\s*\n?\s*resp\.requested_llama_extra_args !== undefined/,+ );+});++test("a stored empty list hydrates as a clear, not as nothing stored", () => {+ // The settings page writes an explicit [] when the box is cleared for a quant+ // whose bare-repository row still carries arguments: it is the tombstone that+ // stops the server's lookup there. Read as an absence, all three hydrating+ // callers left llamaExtraArgs undefined, omitted the field on /load, and the+ // route carried the resident model's arguments over, the ones just cleared.+ assert.match(OVERRIDES, /explicit: Array\.isArray\(tokens\)/);+ assert.match(OVERRIDES, /return \{ tokens: \[\], explicit: false \};/);+ assert.match(PANEL, /resolvedArgs\.explicit && local === undefined/);+ assert.match(ADAPTER, /\} else if \(stored\.explicit\) \{/);+ assert.match(COMPOSER, /\} else if \(resolvedArgs\.explicit\) \{/);+});++const CHAT_PAGE = readFileSync(+ path.join(HERE, "..", "src/features/chat/chat-page.tsx"),+ "utf8",+);++test("a launch that only applies the remembered config still carries its arguments", () => {+ // applyPerModelConfigToRuntime has no field for the launch flags, and /load only+ // inherits them from the SAME resident model, so a cold launch or a switch from+ // another model ran without the arguments this model was remembered with. Both+ // paths that load through the runtime alone now pass the config itself.+ assert.match(HUB, /\.\.\.\(rememberedConfig \? \{ config: rememberedConfig \} : \{\}\),/);+ assert.match(CHAT_PAGE, /const remembered = rememberedConfigFor\(selection\);/);+ assert.match(CHAT_PAGE, /\.\.\.\(remembered \? \{ config: remembered \} : \{\}\),/);+ // Nothing is invented when there is no remembered config: the field stays absent,+ // which is what lets /load keep a resident model's own flags.+ assert.doesNotMatch(HUB, /config: rememberedConfig \?\? null/);+});diff --git a/studio/frontend/tests/llama-extra-args-status-hydration.test.ts b/studio/frontend/tests/llama-extra-args-status-hydration.test.tsnew file mode 100644index 00000000000..a3b0c13b8e6--- /dev/null+++ b/studio/frontend/tests/llama-extra-args-status-hydration.test.ts@@ -0,0 +1,75 @@+// 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 a tab learns what the RUNNING server was invoked with.+//+// The switch path records it, so a tab that performed the load knows. A tab opened or+// refreshed while a model was already loaded does not, and its baseline stays null.+// That baseline is what a failed switch resends: the failed target is left resident,+// so an omitted llama_extra_args cannot inherit across models (the route refuses to),+// and the previous model comes back without the arguments it was running.+//+// The fix is that /api/inference/status publishes requested_llama_extra_args and the+// applier seeds the baseline from it. Checked at the source, like the chat-template+// seed test next door: the applier is one large object literal with no seam to call.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import path from "node:path";+import { test } from "node:test";+import { fileURLToPath } from "node:url";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const read = (relative: string) =>+ readFileSync(path.join(HERE, "..", relative), "utf8");++const APPLIER = read("src/features/chat/lib/apply-inference-status-to-store.ts");+const RUNTIME = read("src/features/chat/hooks/use-chat-model-runtime.ts");+const API_TYPES = read("src/features/chat/types/api.ts");++test("the status type carries the running arguments", () => {+ assert.match(API_TYPES, /requested_llama_extra_args\?: string\[\] \| null;/);+});++test("the applier seeds the loaded baseline from the status echo", () => {+ assert.match(+ APPLIER,+ /loadedLlamaExtraArgs: status\.requested_llama_extra_args \?\? null/,+ );+});++test("an older backend that omits the field changes nothing", () => {+ // undefined is "this server does not publish it", which must leave a baseline this+ // tab recorded first-hand alone rather than clearing it to null.+ assert.match(APPLIER, /status\.requested_llama_extra_args !== undefined/);+});++test("the baseline follows a same-model reload from elsewhere", () => {+ // Another tab or an API client can reload the same model and variant with other+ // arguments, or with none: a baseline pinned at the first read would resend the+ // old list from the rollback path and resurrect arguments that are not running.+ // The in-flight guard stays, since performLoad owns these values mid-switch.+ assert.match(+ APPLIER,+ /requested_llama_extra_args !== undefined &&\s*\n\s*\(status\.is_gguf \?\? true\) &&\s*\n\s*seedLoadParams/,+ );+});++test("the rollback still resends that baseline explicitly", () => {+ assert.match(+ RUNTIME,+ /stateBeforeUnload\.loadedLlamaExtraArgs != null\s*\n?\s*\? \{ llama_extra_args: stateBeforeUnload\.loadedLlamaExtraArgs \}/,+ );+});++test("an explicit empty list is kept apart from an unknown one", () => {+ // The rollback sends this field only when it has one, and omitting it is what+ // makes /load inherit: a model launched with no extras would otherwise come back+ // carrying the arguments of the load that just failed. null stays for "never told".+ assert.match(RUNTIME, /loadLlamaExtraArgs !== undefined\s*\n?\s*\? \(loadLlamaExtraArgs \?\? \[\]\)/);+ // The status echo goes in as it arrives, so a server running none reads as [].+ assert.match(+ APPLIER,+ /loadedLlamaExtraArgs: status\.requested_llama_extra_args \?\? null/,+ );+});diff --git a/studio/frontend/tests/llama-extra-args.test.ts b/studio/frontend/tests/llama-extra-args.test.tsnew file mode 100644index 00000000000..2dfa4eaf7af--- /dev/null+++ b/studio/frontend/tests/llama-extra-args.test.ts@@ -0,0 +1,238 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { test } from "node:test";+import {+ EXTRA_ARGS_MAX_TOKENS,+ extraArgFlagName,+ extraArgFlags,+ formatExtraArgs,+ parseExtraArgs,+} from "../src/features/model-picker/model-config/llama-extra-args.ts";++// The wire format is one argv token per entry, so this split decides what the child+// process actually receives. A token boundary in the wrong place turns one flag's+// value into another flag.++test("a plain command splits on whitespace", () => {+ assert.deepEqual(parseExtraArgs("--top-k 20 --seed 42").tokens, [+ "--top-k",+ "20",+ "--seed",+ "42",+ ]);+});++test("runs of whitespace collapse and the edges are ignored", () => {+ assert.deepEqual(parseExtraArgs(" --top-k 20 ").tokens, [+ "--top-k",+ "20",+ ]);+ assert.deepEqual(parseExtraArgs("").tokens, []);+ assert.deepEqual(parseExtraArgs(" ").tokens, []);+});++test("newlines separate, so one flag per line reads as one command", () => {+ assert.deepEqual(+ parseExtraArgs("--top-k 20\n--seed 42\r\n--numa distribute").tokens,+ ["--top-k", "20", "--seed", "42", "--numa", "distribute"],+ );+});++test("a quoted value keeps its spaces in one token", () => {+ // The reason quoting exists here at all: a chat template or a grammar is one+ // argv entry containing spaces.+ assert.deepEqual(parseExtraArgs(`--chat-template "a b c"`).tokens, [+ "--chat-template",+ "a b c",+ ]);+ assert.deepEqual(parseExtraArgs(`--chat-template 'a b c'`).tokens, [+ "--chat-template",+ "a b c",+ ]);+});++test("quotes can open mid-token and more than once", () => {+ assert.deepEqual(parseExtraArgs(`--opt=a" "b`).tokens, ["--opt=a b"]);+ assert.deepEqual(parseExtraArgs(`'a'"b"c`).tokens, ["abc"]);+});++test("an empty quoted string is still a token", () => {+ // --grammar '' is a real thing to pass; dropping it would silently change the+ // command rather than fail.+ assert.deepEqual(parseExtraArgs(`--grammar ''`).tokens, ["--grammar", ""]);+});++test("an unterminated quote is reported, not swallowed", () => {+ const parsed = parseExtraArgs(`--chat-template "a b`);+ assert.equal(parsed.unterminatedQuote, '"');+ // The tokens so far are still returned, so the row can show what it did read.+ assert.deepEqual(parsed.tokens, ["--chat-template", "a b"]);+ assert.equal(parseExtraArgs("--top-k 20").unterminatedQuote, null);+});++test("a backslash escapes the next character outside quotes", () => {+ assert.deepEqual(parseExtraArgs("--path a\\ b").tokens, ["--path", "a b"]);+ assert.deepEqual(parseExtraArgs('--x \\"quoted\\"').tokens, [+ "--x",+ '"quoted"',+ ]);+});++test("single quotes take everything literally", () => {+ // What makes a regex-bearing grammar survive: inside single quotes a backslash+ // is a backslash, as in a shell.+ assert.deepEqual(parseExtraArgs(`--grammar 'root ::= [\\d]+'`).tokens, [+ "--grammar",+ "root ::= [\\d]+",+ ]);+});++test("double quotes escape only what a shell escapes", () => {+ assert.deepEqual(parseExtraArgs(`"a\\"b"`).tokens, ['a"b']);+ // A backslash before an ordinary character stays, so a Windows path survives.+ assert.deepEqual(parseExtraArgs(`"C:\\Users\\model"`).tokens, [+ "C:\\Users\\model",+ ]);+});++test("a trailing backslash-newline continues the line", () => {+ // POSIX 2.2.1: an unquoted backslash before a newline is a line continuation and+ // both characters go. This is the one place the split deliberately differs from+ // Python's shlex, which is a lexer with no continuation rule and leaves a literal+ // newline inside the token. The box is multi-line and people paste wrapped+ // commands into it, so the shell reading is the one that matches the intent.+ assert.deepEqual(parseExtraArgs("--top-k \\\n20").tokens, ["--top-k", "20"]);+ // Inside single quotes it is literal, as in a shell.+ assert.deepEqual(parseExtraArgs("--x 'a\\\nb'").tokens, ["--x", "a\\\nb"]);+ // The shape a wrapped command actually has when it is pasted: every line after+ // the first is indented. The continuation contributes nothing, so that indentation+ // is ordinary whitespace between tokens. Treating it as the start of one produced+ // an empty token, which llama-server reads as a positional model path.+ assert.deepEqual(parseExtraArgs("--foo value \\\n --bar other").tokens, [+ "--foo",+ "value",+ "--bar",+ "other",+ ]);+ // And it still joins what it is between: no space either side means one token.+ assert.deepEqual(parseExtraArgs("--x=a\\\nb").tokens, ["--x=ab"]);+});++test("a trailing lone backslash is kept, not treated as an error", () => {+ // The other deliberate difference from shlex, which raises here. A text field is+ // half-typed most of the time, so refusing the whole box mid-keystroke is worse+ // than carrying the character.+ assert.deepEqual(parseExtraArgs("--x \\").tokens, ["--x", "\\"]);+ assert.equal(parseExtraArgs("--x \\").unterminatedQuote, null);+});++test("an unquoted Windows path loses its separators, as in a shell", () => {+ // Not a bug to fix in the splitter: an unquoted backslash escapes the next+ // character in every POSIX shell, and changing that would break every escape the+ // hint tells people to use. It IS a trap on Windows, which is why the row's hint+ // names backslashes and not just spaces.+ assert.deepEqual(+ parseExtraArgs("--chat-template-file C:\\a\\b.jinja").tokens,+ ["--chat-template-file", "C:ab.jinja"],+ );+ // Quoted, it survives whole, and that is what the hint asks for.+ assert.deepEqual(+ parseExtraArgs('--chat-template-file "C:\\a\\b.jinja"').tokens,+ ["--chat-template-file", "C:\\a\\b.jinja"],+ );+ assert.deepEqual(+ parseExtraArgs("--chat-template-file 'C:\\a\\b.jinja'").tokens,+ ["--chat-template-file", "C:\\a\\b.jinja"],+ );+});++test("shell metacharacters are literal, because nothing here runs a shell", () => {+ // The child is spawned from a list, so pretending otherwise would invent a+ // meaning the backend does not implement.+ assert.deepEqual(parseExtraArgs("--x a;b|c>d").tokens, ["--x", "a;b|c>d"]);+ assert.deepEqual(parseExtraArgs("--x $HOME").tokens, ["--x", "$HOME"]);+ assert.deepEqual(parseExtraArgs("--x *.gguf").tokens, ["--x", "*.gguf"]);+});++// --- round-tripping ---------------------------------------------------------+// The stored value is a token list, so the box is re-rendered from tokens every+// time the panel reopens. Anything that does not round-trip accumulates escaping.++const ROUND_TRIP: string[][] = [+ ["--top-k", "20"],+ ["--chat-template", "a b c"],+ ["--grammar", "root ::= [\\d]+"],+ ["--x", ""],+ ["--x", "it's"],+ ["--x", 'say "hi"'],+ ["--x", "both'and\""],+ ["--x", "C:\\Users\\model"],+ ["--x", "a;b|c"],+ ["--x", "$HOME"],+ ["--x", "tab\there"],+];++for (const tokens of ROUND_TRIP) {+ test(`round-trips ${JSON.stringify(tokens)}`, () => {+ assert.deepEqual(parseExtraArgs(formatExtraArgs(tokens)).tokens, tokens);+ });+}++test("formatting leaves ordinary tokens unquoted", () => {+ // Or the box would fill with quotes the user never typed.+ assert.equal(formatExtraArgs(["--top-k", "20"]), "--top-k 20");+ assert.equal(formatExtraArgs([]), "");+ assert.equal(formatExtraArgs(null), "");+ assert.equal(formatExtraArgs(undefined), "");+});++// --- flag names -------------------------------------------------------------+// Mirrors _flag_name in llama_server_args.py. Where these disagree, the UI accepts+// an argument the load then refuses, or warns about one that would have worked.++test("a flag name is peeled from its value", () => {+ assert.equal(extraArgFlagName("--top-k"), "--top-k");+ assert.equal(extraArgFlagName("--top-k=20"), "--top-k");+ assert.equal(extraArgFlagName("-fa"), "-fa");+});++test("long-option underscores normalise like llama.cpp", () => {+ assert.equal(extraArgFlagName("--top_k"), "--top-k");+ assert.equal(extraArgFlagName("--n_parallel=4"), "--n-parallel");+});++test("a value is not a flag", () => {+ assert.equal(extraArgFlagName("20"), null);+ assert.equal(extraArgFlagName("-1"), null);+ assert.equal(extraArgFlagName("-0.5"), null);+ assert.equal(extraArgFlagName("-"), null);+ assert.equal(extraArgFlagName("--"), null);+});++test("an attached -np value still names -np", () => {+ // Otherwise a denied flag slips through glued to its value.+ assert.equal(extraArgFlagName("-np8"), "-np");+ assert.equal(extraArgFlagName("-np-1"), "-np");+ assert.equal(extraArgFlagName("-np"), "-np");+});++test("whitespace padding does not hide a flag", () => {+ assert.equal(extraArgFlagName(" --parallel"), "--parallel");+ assert.equal(extraArgFlagName("\t-np "), "-np");+});++test("flags are collected in order without duplicates", () => {+ assert.deepEqual(+ extraArgFlags(["--top-k", "20", "--seed", "42", "--top-k", "30"]),+ ["--top-k", "--seed"],+ );+ assert.deepEqual(extraArgFlags(["20", "42"]), []);+});++test("the token cap mirrors the backend", () => {+ // The backend refuses past this, so the editor has to warn at the same number+ // rather than let the load fail.+ assert.equal(EXTRA_ARGS_MAX_TOKENS, 256);+});diff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.pyindex b2314d8451c..bf37451783f 100644--- a/tests/studio/test_chat_autoload_failure_gate.py+++ b/tests/studio/test_chat_autoload_failure_gate.py@@ -70,6 +70,30 @@ export type Scenario = {download: (request: any) => string;};+// The stored-arguments hydration the auto-load runs before it calls /load. Neutral+// here on purpose: these scenarios are about the failure gate, not about which flags+// a model launches with, and a stub that invented some would change the /load payload+// every scenario asserts on. fetchLoadExtraArgs answers "nothing stored", which is+// what a fresh install has, and the sanitizer is identity so a scenario that does set+// llamaExtraArgs still sends exactly what it set.+export async function loadManagedLlamaFlags(): Promise<any> {+ return null;+}+export async function fetchLoadExtraArgs(+ _loadId: string,+ _aliasId?: string | null,+ _variant?: string | null,+): Promise<{ tokens: string[]; explicit: boolean }> {+ return { tokens: [], explicit: false };+}+export function sanitizeStoredExtraArgs(+ tokens: readonly string[],+ _managed: ReadonlySet<string>,+ _limits?: any,+): string[] {+ return [...tokens];+}+export const EVENTS: any[] = [];let SCENARIO: Scenario;export function setScenario(scenario: Scenario) {