Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop a small context window ending a tool-using turn with nothing (#9768)
Daniel Han951764ee6c59
diff --git a/studio/backend/core/inference/context_refusal.py b/studio/backend/core/inference/context_refusal.pyindex 676d8001ecf..124f1dfdbba 100644--- a/studio/backend/core/inference/context_refusal.py+++ b/studio/backend/core/inference/context_refusal.py@@ -200,6 +200,23 @@ _ROLE_ADVICE = {"A tool returned more than this context window can hold","ask for a smaller slice of the file or page",),+ # The model passed a file-sized argument to a tool. The user did not type it and+ # cannot split it, and the tool cannot be asked for less: `edit_file` with an empty+ # `old_string` is whole-file creation, so the content IS the argument. The only levers+ # are the window itself and not asking for a file this size in a window this small.+ "assistant_tool_call": (+ "Most of this prompt is the file the model passed to a tool",+ "The file the model passed to a tool does not fit on its own",+ "ask for a smaller file, or raise the Context Length before retrying",+ ),+ # The same shape with no file in it: an oversized program, command, query or MCP+ # payload. "Ask for a smaller file" names the wrong thing and cannot be acted on, so+ # this one says what is actually true of every tool.+ "assistant_tool_payload": (+ "Most of this prompt is what the model passed to a tool",+ "What the model passed to a tool does not fit on its own",+ "ask for less in one call, or raise the Context Length before retrying",+ ),# The reply resumed after it hit Max Tokens: the user cannot split or shorten it."assistant": ("Most of this prompt is the reply being continued",@@ -258,3 +275,61 @@ def describe_oversize(request_tokens: int, context_tokens: int) -> str:f"{head}{cause}, so shortening the conversation {hedge}. Increase the Context "f"Length in Model settings, or {lever}.")+++# What the user can actually shorten, per tool. Anything absent gets the neutral line:+# an MCP tool's payload is not a file and not a program, and guessing at it is worse+# than saying the one thing that is true of every tool.+_TOOL_LEVERS = {+ "edit_file": "ask for a smaller file",+ "python": "run a shorter program",+ "terminal": "run a shorter command",+ "render_html": "render a smaller page",+ "web_search": "ask a narrower question",+ "search_knowledge_base": "ask a narrower question",+ "search_conversation": "ask a narrower question",+}+++def describe_unservable_tool_call(+ tool_name: str,+ request_tokens: int,+ context_tokens: int,+ *,+ compacted_calls: int = 0,+) -> str:+ """The message for a tool call refused BEFORE it ran, because its turn cannot be served.++ `describe_oversize` reconstructs blame from a recorded diagnosis, because by the time it+ speaks the request has already been rejected and the cause has to be inferred. This one+ is said by the loop that is holding the call, so it names the tool outright instead of+ guessing at a role, and it is the only refusal on this path that can promise nothing was+ written -- which is the fact the user most needs and the 400 could never offer.++ ``compacted_calls`` is reported when history was already spent trying to make room, so+ "increase the Context Length" does not read as advice nobody tried.+ """+ # Says "leaving no room to reply" rather than only quoting the two numbers. The bar is+ # the window minus a small reply floor, so a refusal at 3,740 against 4,096 reads as a+ # contradiction unless the message accounts for the gap it is refusing over.+ head = (+ f"Not enough context left to run {tool_name}: the next request would be about "+ f"{request_tokens} tokens of a {context_tokens}-token window, leaving no room to "+ "reply. "+ )+ tried = ""+ if compacted_calls > 0:+ calls = "call" if compacted_calls == 1 else "calls"+ tried = (+ f"Arguments from {compacted_calls} earlier tool {calls} were already compacted "+ "to make room. "+ )+ # The gate runs for EVERY enabled tool, so the file wording was reaching an oversized+ # `python`, `terminal`, web or MCP call and telling the user to ask for a smaller+ # file when no file was involved -- advice that cannot make the actual program,+ # command or payload any smaller. `edit_file` keeps the line it was written for.+ lever = _TOOL_LEVERS.get(tool_name, "ask for less in one call")+ return (+ head + tried + "Nothing was written. Increase the Context Length in Model settings, "+ f"or {lever}, then try again."+ )diff --git a/studio/backend/core/inference/context_window.py b/studio/backend/core/inference/context_window.pyindex c0597635f5d..2a8b9e1bb07 100644--- a/studio/backend/core/inference/context_window.py+++ b/studio/backend/core/inference/context_window.py@@ -350,6 +350,601 @@ def tool_result_budget(return max(0, int(target * buffer) - int(prompt_tokens or 0))+def turn_is_servable(+ context_length: int,+ max_tokens: Optional[int],+ prompt_tokens: int,+ *,+ buffer: float = _TOOL_RESULT_BUDGET_BUFFER,+) -> bool:+ """Whether the next prompt fits once this tool returns, given an EMPTY result.++ `tool_result_budget` answers how much a result may add and clamps at zero, which the+ truncation reads as "cut hard" -- a number, never a refusal. So a turn whose prompt is+ already over budget before the tool has returned anything is indistinguishable from one+ with a little room left, and the loop runs the tool either way. The side effect lands,+ the result is squeezed to its notice, and the request is rejected regardless.++ Zero room is the refusal the budget could not express. Asked with the notice reserve+ charged, because a result cut to nothing still carries the notice saying so, and at+ this end of the scale that IS the whole message.+ """+ if context_length <= 1:+ return True+ return prompt_tokens + _RESULT_NOTICE_RESERVE + _reply_floor(context_length) <= context_length+++def _reply_floor(context_length: int) -> int:+ """The least reply room a turn must leave to be worth running.++ Deliberately NOT `prompt_budget`, which sets aside the whole of `max_tokens`. That is+ the right reserve for sizing a result, and much too strict for deciding whether a call+ may run at all: at a 4096 window it leaves 3072 for the prompt, so the gate refused+ turns of 3,504 and 3,740 tokens that llama-server would have served without complaint,+ and the model sat retrying smaller and smaller edits against a bar it could not see.++ llama-server admits a prompt on size alone (`n_tokens() >= n_ctx`), so that is the line+ this has to draw, minus only enough to answer in. `_RESCUE_REPLY_FLOOR_DIVISOR` already+ encodes that judgement for the compaction rescue -- small on purpose, ruling out the+ stub-answer end rather than promising a full reply.+ """+ return max(1, context_length // _RESCUE_REPLY_FLOOR_DIVISOR)+++# How much of a completed call's arguments has to be at stake before replacing them with a+# receipt is worth the edit. Below this the placeholder is a wash against what it removes,+# and the model loses sight of its own last action for nothing.+# Fields naming the call's destination rather than its payload.+_PATH_KEYS = frozenset({"path", "file_path", "filePath"})+# Longest path worth repeating inside every elided leaf's receipt.+_RECEIPT_PATH_MAX_CHARS = 120++_ARG_COMPACTION_FLOOR_CHARS = 1024+# Once the arguments AS A WHOLE are worth reclaiming, the bar each string has to clear+# drops to this. Not zero: a receipt is about 100 characters, so eliding anything shorter+# grows the call it is meant to shrink.+_ARG_COMPACTION_AGGREGATE_LEAF_FLOOR = 256+# When the total of every string reaches this, the call is worth compacting even though no+# single string does. Matches the per-leaf floor: the same amount of window either way.+_ARG_COMPACTION_TOTAL_FLOOR_CHARS = 1024+++def _largest_leaf(value: Any) -> int:+ """Longest string anywhere in the parsed arguments, at any depth."""+ if isinstance(value, str):+ return len(value)+ if isinstance(value, dict):+ return max((_largest_leaf(item) for item in value.values()), default = 0)+ if isinstance(value, list):+ return max((_largest_leaf(item) for item in value), default = 0)+ return 0+++def _total_leaves(value: Any) -> int:+ """Every string in the parsed arguments added together, at any depth."""+ if isinstance(value, str):+ return len(value)+ if isinstance(value, dict):+ return sum(_total_leaves(item) for item in value.values())+ if isinstance(value, list):+ return sum(_total_leaves(item) for item in value)+ return 0+++def _compacted_arguments(+ name: str,+ arguments: str,+ phrase: Optional[str] = None,+ reply: object = None,+) -> Optional[str]:+ """A receipt standing in for a completed call's arguments, or None to leave them.++ The arguments of a call that has ALREADY run are the one part of a tool exchange that+ is pure history: the tool received them in full, the side effect landed, and for the+ file tools the content is on disk and re-readable. Replaying them verbatim buys the+ model nothing it cannot recover, which is what makes them the right thing to spend+ when a turn spills -- unlike the result, which is the only record of what happened.++ Structured rather than dropped, and naming the path, so the model can still see which+ file it just wrote and go and read it. A bare "[omitted]" reads as a failed call and+ is answered with a retry of the same oversized write.+ """+ # Resolved here, not as a default: the constant is defined below this function, and a+ # literal default silently kept the OLD wording on this path while the executed and+ # refused paths moved to the new one -- the same receipt the model misread as tool+ # output, still being emitted by the most common caller.+ phrase = phrase or _completed_phrase_for(name, reply)+ if not isinstance(arguments, str):+ return None+ # The general floor exists so a receipt is not bigger than what it replaces, and for+ # ordinary history compaction a call under it is not worth the churn. A REFUSED call+ # is the opposite case: the refusal message itself is about to be added to a prompt+ # that already does not fit, so any reduction at all is the difference between the+ # user reading the refusal and reading llama-server's context error. The size check+ # at the end still guarantees the receipt never grows the prompt.+ refused = phrase == _REFUSED_PHRASE+ if not refused and len(arguments) < _ARG_COMPACTION_TOTAL_FLOOR_CHARS:+ return None+ try:+ parsed = json.loads(arguments)+ except Exception:+ # Unparseable arguments still cost the window, and a call that has already run+ # cannot be re-issued from them, so the size alone is an honest receipt.+ #+ # Worded from `phrase` like every other receipt. Hardcoding "after the call ran"+ # meant a REFUSED call with 1024+ characters of malformed JSON was replayed as+ # having run, next to the tool message saying nothing was written: two+ # contradictory accounts of the same call, one of which invites the model to+ # reason from a side effect that never happened.+ _unparseable = json.dumps(+ {"_unsloth_compacted": f"{len(arguments)} chars {phrase.format(where = '')}"},+ ensure_ascii = False,+ )+ # Checked here as well as at the end: without the general floor in front of it,+ # a short refused call can have a receipt longer than the arguments it replaces.+ return _unparseable if len(_unparseable) < len(arguments) else None+ if not isinstance(parsed, dict):+ return None+ path = parsed.get("path") or parsed.get("file_path") or parsed.get("filePath")+ elided = 0++ # Per-leaf or aggregate, whichever lets this call be reclaimed. A batched refactor of+ # fifty 800-character edits is forty thousand characters of window with no single+ # string over the floor, so a per-leaf test compacted NOTHING and the call sat in the+ # prompt permanently -- the pre-execution gate then had nothing to reclaim and refused+ # a turn it could have served. The floor exists so a receipt is not bigger than what+ # it replaces, and the final size check below still enforces that.+ # Chosen from the TOTAL, not the largest leaf. Keying on the largest meant one+ # 1100-character edit beside fifty 800-character ones stayed in per-leaf mode and+ # compacted only the first, leaving about 40 KB replayed -- the mixed payload is+ # exactly the shape a batched refactor produces.+ _leaf_floor = (+ # A refused call takes whatever it can get, floored only at the point where a+ # leaf is longer than the receipt describing it, so eliding cannot lose ground.+ _REFUSED_LEAF_FLOOR+ if refused+ else _ARG_COMPACTION_AGGREGATE_LEAF_FLOOR+ if _total_leaves(parsed) >= _ARG_COMPACTION_TOTAL_FLOOR_CHARS+ else _ARG_COMPACTION_FLOOR_CHARS+ )++ def _shrink(value: Any, key: str = "") -> Any:+ """Elide every large string, at whatever depth it sits.++ Depth is not optional: `edit_file` takes an `edits` ARRAY so several changes cost+ one call instead of one each, which puts the file content at+ `edits[i].new_string`. A top-level-only pass sees nothing there and quietly+ compacts nothing -- the batching and the compaction were written a day apart and+ only the tests noticed they had stopped meeting.+ """+ nonlocal elided+ # The destination is never expendable: it is the one field that says WHICH file+ # the call touched, and the receipt promises the content can be found there. A+ # deeply nested path over the aggregate floor was being elided like content,+ # leaving later turns unable to name the file they had just changed.+ if key in _PATH_KEYS:+ return value+ if isinstance(value, str) and len(value) >= _leaf_floor:+ elided += len(value)+ # Named in the receipt only when repeating it is cheaper than the field it+ # points at. Every elided leaf embeds this, so a 500-character path across+ # four leaves costs more than the content removed and the whole compaction+ # is rejected by the size check below. The `path` field is preserved+ # verbatim either way, so nothing is lost by leaving it out here.+ where = (+ f" to {path}"+ if path and key not in _PATH_KEYS and len(str(path)) <= _RECEIPT_PATH_MAX_CHARS+ else ""+ )+ # `old_string` names text the edit REMOVED. The completed phrase says the+ # content is already written and the file on disk holds it, which of the two+ # halves of a replacement is true only of `new_string`; said of the old text+ # it points the model at content the edit has just taken out.+ leaf_phrase = _COMPLETED_NEUTRAL_PHRASE if key == "old_string" else phrase+ return f"<{len(value)} chars {leaf_phrase.format(where = where)}>"+ if isinstance(value, dict):+ return {inner: _shrink(item, inner) for inner, item in value.items()}+ if isinstance(value, list):+ return [_shrink(item, key) for item in value]+ return value++ kept = {key: _shrink(value, key) for key, value in parsed.items()}+ if not elided:+ return None+ try:+ compacted = json.dumps(kept, ensure_ascii = False)+ except Exception:+ return None+ # Never grow the prompt to describe it: a call whose bulk is spread across many small+ # fields leaves nothing to elide and the receipts cost more than the fields did.+ return compacted if len(compacted) < len(arguments) else None+++# A leaf shorter than its own receipt costs room to elide, so this is the break-even+# point for the refusal wording rather than a judgement about what is worth compacting.+_REFUSED_LEAF_FLOOR = 110+_REFUSED_PHRASE = (+ "of arguments you sent, elided; this call was refused before it ran and nothing was written"+)+# Worded so the model cannot mistake it for the tool's OUTPUT. The first version read+# "<2581 chars written; re-read the file to see it>" and was quoted straight back in+# the model's reasoning as "the tool result says ... the output was omitted" -- it+# concluded the sandbox had mangled its file and abandoned a working approach. Says+# "you sent" so the owner of the text is unambiguous, and says what it is not.+# The tail once read "read the file back if you need the content", which contradicted+# every other line this PR added: `edit_file` now says not to read back what you just+# wrote, and the starved and repeated-result notices both say reading again will not help.+# Three messages discouraging a re-read and one inviting it is worse than either rule+# alone, and the re-read is the loop that cost eighteen calls in one turn.+_COMPLETED_PHRASE = "of arguments you sent, already written{where}; elided to save room. Not tool output; the file on disk holds it."+# The same receipt for a tool that writes no file. `python`, `terminal`, the search+# tools and every MCP tool are selected by size and by having been answered, exactly+# like `edit_file`, so a 2000-character `code` argument was handed a receipt saying it+# was "already written" and that "the file on disk holds it" -- a file the model can+# then set out to read, or reason from as persisted, when nothing was persisted at all.+# Neither claim about the filesystem, for every case where the reply does not settle it.+# Says only what is certainly true: these are the model's own arguments, the call ran, and+# this is not the tool's output.+_COMPLETED_NEUTRAL_PHRASE = (+ "of arguments you sent, elided to save room; the call already ran. Not tool output"+)+# Tools whose completed call really does leave the content in a file.+_FILE_WRITING_TOOLS = frozenset({"edit_file"})++# A reply that opens like this reports a call that ran and did NOT do what was asked, so+# the file wording would describe a write that never landed.+_FAILED_REPLY_MARKERS = ("error", "failed", "not found", "no such file", "traceback")++# A reply the WINDOW replaced, not one the tool wrote. Under a near-zero result budget+# `_fit_result_to_room` swaps the real answer -- including an `Error: ...` -- for a stub+# saying there was no room for it, and that stub carries none of the markers above. Read+# as proof of a write, it tells the model an edit landed when the edit may have failed,+# under exactly the tight context that makes compaction run in the first place. Absence+# of evidence, so the neutral wording applies.+_INCONCLUSIVE_REPLY_MARKERS = ("no context room left", "chars for the model;")+++def _reply_proves_a_write(name: str, content: object) -> bool:+ """Whether this reply settles that the call left its content in a file.++ The tool NAME alone is wrong in both directions, and under the tight context that+ triggers compaction the model acts on the answer. An `edit_file` that ran and returned+ "old_string not found" is not a write, and telling it the content is already on disk+ invites it to skip the retry the error was asking for. A `python` or `terminal` call+ whose code created files is not a non-write either, and telling it nothing was written+ invites it to do the same work twice.++ So the file wording is earned, not assumed: a file tool AND a reply that does not read+ as a failure. Everything else gets a receipt that claims nothing about the disk.+ """+ if name not in _FILE_WRITING_TOOLS:+ return False+ if not isinstance(content, str):+ return False+ lowered = content.lower()+ if any(marker in lowered for marker in _INCONCLUSIVE_REPLY_MARKERS):+ return False+ head = content[:200].strip().lower()+ return not any(marker in head for marker in _FAILED_REPLY_MARKERS)+++def _completed_phrase_for(name: str, reply: object = None) -> str:+ return _COMPLETED_PHRASE if _reply_proves_a_write(name, reply) else _COMPLETED_NEUTRAL_PHRASE+++def compact_executed_call_arguments(messages: list[dict], call_id: str) -> list[dict]:+ """Replace ONE just-run call's arguments with a receipt, whatever else is protected.++ `compact_completed_tool_arguments` deliberately holds the newest exchange back, which+ is right while a call is still in flight and wrong the instant it returns. Running a+ tool needs no context at all -- only the NEXT prompt does, and by then the arguments+ describe something already on disk.++ That distinction is what lets an oversized call be run instead of refused: refusing+ left the arguments in the transcript anyway, the model retried with a fresh oversized+ call, and each round added a receipt and a refusal message while reclaiming less.+ Measured over three rounds of one thread: 50%, then 34%, then 15% of the conversation+ recovered, ending in a one-character reply. Running the call and compacting it costs+ the same tokens once and leaves the file written.+ """+ # None, not the constant: the receipt is chosen per tool, so a completed `python`+ # call is not told its arguments are on disk. `edit_file` still gets the wording+ # this path was built and proven against.+ return _compact_one_call(messages, call_id, None)+++def compact_refused_tool_arguments(messages: list[dict], call_id: str) -> list[dict]:+ """Drop the arguments of one call that was declined, naming it as never sent.++ Refusing a call does not on its own make the turn servable, and on the template that+ made the refusal necessary it actively does not: an assistant turn's `tool_calls` are+ rendered only once a `tool` message answers them, and the refusal IS such a message.+ So declining costs the prompt the very arguments it was declining to afford, and the+ generation that follows is rejected with nothing written -- an accurate refusal the+ user never gets to act on.++ These arguments are the one case with no replay value whatsoever: the call did not+ run, so nothing on disk reflects them and there is nothing to re-read. Their own+ receipt has to say so, because the wording used for a completed call would tell the+ model to go and read a file that was never written.+ """+ return _compact_one_call(messages, call_id, _REFUSED_PHRASE)+++def _last_index_with_call(messages: list[dict], call_id: str) -> int:+ """Where the call this result answers actually is.++ Tool-call IDs are NOT unique across a conversation. The textual parsers number from+ `call_0` with an offset that starts at zero on every turn, and the structured+ fallback does the same when the server omits an ID, so a five-round turn holds+ several `call_0`s. Rewriting every match would relabel an earlier successful call as+ refused, or an earlier refused one as already written -- a receipt describing a+ different call's fate, which is worse than not compacting at all.++ Both callers act on the call just decided, so the last match is the right one.+ """+ for index in range(len(messages) - 1, -1, -1):+ message = messages[index]+ if message.get("role") != "assistant":+ continue+ calls = message.get("tool_calls")+ if not isinstance(calls, list):+ continue+ if any(+ isinstance(call, dict) and str(call.get("id") or "") == str(call_id) for call in calls+ ):+ return index+ return -1+++def _reply_for_call(messages: list[dict], call_id: str) -> object:+ """The last tool reply answering this id, or None when it has not been answered."""+ for message in reversed(messages):+ if message.get("role") == "tool" and str(message.get("tool_call_id") or "") == str(call_id):+ return message.get("content")+ return None+++def _compact_one_call(+ messages: list[dict],+ call_id: str,+ phrase: Optional[str] = None,+) -> list[dict]:+ """Rewrite exactly one call's arguments to a receipt worded by `phrase`.++ `None` leaves the wording to the tool, which is what a COMPLETED call wants: only+ the file tools may say the content is on disk.+ """+ if not call_id:+ return messages+ target = _last_index_with_call(messages, call_id)+ if target < 0:+ return messages+ out: list[dict] = []+ for index, message in enumerate(messages):+ calls = message.get("tool_calls")+ if index != target or not isinstance(calls, list) or not calls:+ out.append(message)+ continue+ new_calls: list[dict] = []+ changed = False+ for call in calls:+ function = call.get("function") if isinstance(call, dict) else None+ if not isinstance(function, dict) or str(call.get("id") or "") != str(call_id):+ new_calls.append(call)+ continue+ replacement = _compacted_arguments(+ str(function.get("name") or ""),+ function.get("arguments"),+ phrase,+ reply = _reply_for_call(messages, call_id),+ )+ if replacement is None:+ new_calls.append(call)+ continue+ new_calls.append({**call, "function": {**function, "arguments": replacement}})+ changed = True+ out.append({**message, "tool_calls": new_calls} if changed else message)+ return out+++# A `role=tool` reply proves an ANSWER, not an execution. The approval gate answers a+# declined call with exactly such a message, and an unreadable call is answered without+# running either. Compacting those to the completed receipt tells the model a file was+# written that the user refused, which it may then report or reason from.+_DID_NOT_RUN_MARKERS = (+ "the user declined to run this tool call",+ "could not be read",+ "nothing ran",+ "nothing was run",+ "nothing was written",+)+++def _reply_shows_execution(content: object) -> bool:+ """Whether this tool reply is the result of a call that actually ran."""+ if not isinstance(content, str):+ return True+ head = content[:200].strip().lower()+ return not any(marker in head for marker in _DID_NOT_RUN_MARKERS)+++def _executed_call_sites(messages: list[dict]) -> "dict[tuple[int, str], object]":+ """`(message index, call id)` for each call a reply shows actually ran.++ Keyed on the SITE, not the id. Generated ids restart at `call_0` on every turn, so a+ conversation-wide set of "answered" ids says an earlier successful `call_0` vouches+ for a later one. Under a tight context that is how a call the user DECLINED came to be+ replayed with the completed receipt: the reply marker correctly skipped the denial,+ and the older success had already put the id in the set. The model is then told a file+ was written that it refused, which it may report or reason from.++ Paired the way the transcript reads: a reply answers the most recent announcement of+ that id still waiting for one.+ """+ pending: dict[str, list[int]] = {}+ executed: dict[tuple[int, str], object] = {}+ for index, message in enumerate(messages):+ role = message.get("role")+ if role == "assistant":+ for call in message.get("tool_calls") or []:+ if isinstance(call, dict) and call.get("id"):+ pending.setdefault(str(call["id"]), []).append(index)+ continue+ if role != "tool":+ continue+ call_id = message.get("tool_call_id")+ if not call_id:+ continue+ sites = pending.get(str(call_id))+ if not sites:+ continue+ # NEWEST pending announcement, not the oldest. Textual parsers number from+ # `call_0` every turn, so an interrupted call that never got a result leaves a+ # stale site under the same id; pairing this reply with THAT one marks the stale+ # arguments executed and leaves the call that actually ran uncompactable.+ site = sites.pop()+ if _reply_shows_execution(message.get("content")):+ executed[(site, str(call_id))] = message.get("content")+ return executed+++def compact_completed_tool_arguments(+ messages: list[dict], *, protect_last: int = 0+) -> tuple[list[dict], int]:+ """Replace oversized arguments of already-executed calls with receipts.++ Returns the new message list and the number of calls compacted. The input is never+ mutated: this rewrites what is REPLAYED to the model, exactly as+ `strip_result_for_model` already does for results, while the stored thread and the+ arguments the tool actually received stay byte-identical.++ Only calls with a `role=tool` reply present are touched. A call still awaiting its+ result is the turn in flight, and rewriting its arguments would tell the model it+ wrote something different from what the tool is at that moment being handed.++ Oldest first, so the freshest exchange -- the one the model is mid-way through+ reasoning about -- is the last thing spent. ``protect_last`` holds that many trailing+ messages clear of the pass entirely.+ """+ answered = _executed_call_sites(messages)+ if not answered:+ return messages, 0++ limit = len(messages) - int(protect_last or 0)+ out: list[dict] = []+ compacted_calls = 0+ for index, message in enumerate(messages):+ calls = message.get("tool_calls") if index < limit else None+ if message.get("role") != "assistant" or not isinstance(calls, list) or not calls:+ out.append(message)+ continue+ new_calls: list[dict] = []+ changed = False+ for call in calls:+ function = call.get("function") if isinstance(call, dict) else None+ if not isinstance(function, dict) or (index, str(call.get("id") or "")) not in answered:+ new_calls.append(call)+ continue+ replacement = _compacted_arguments(+ str(function.get("name") or ""),+ function.get("arguments"),+ reply = answered[(index, str(call.get("id") or ""))],+ )+ if replacement is None:+ new_calls.append(call)+ continue+ new_calls.append({**call, "function": {**function, "arguments": replacement}})+ changed = True+ compacted_calls += 1+ out.append({**message, "tool_calls": new_calls} if changed else message)+ return (out, compacted_calls) if compacted_calls else (messages, 0)+++def _blamed_role(message: dict) -> str:+ """The advice key for a turn: its role, except a call the model made itself.++ An assistant turn carrying `tool_calls` is reported as `assistant_tool_call` rather+ than `assistant`, because the two have opposite levers. "The reply being continued is+ too long, start a new reply" is the right answer for a resumed generation and the+ wrong one for a turn whose bulk is an 8 KB file the model passed to `edit_file`:+ starting a new reply re-runs the same write. Kept as a role key so the split costs+ the advice table one row and `_blame_latest_turn` nothing.+ """+ role = str(message.get("role") or "")+ if role == "assistant" and message.get("tool_calls"):+ # Split again by whether a FILE is involved. The file wording reached an+ # oversized `python`, `terminal`, web or MCP call and told the user to ask for a+ # smaller file when the payload was a program, a command or a query -- naming the+ # wrong cause and offering an action that cannot shrink it.+ # From the call that accounts for the turn's SIZE, not from whichever call+ # happens to be a file tool. A parallel batch holding a small `edit_file` beside+ # an oversized `python` or MCP payload was diagnosed as a file that is too large,+ # so the advice was to ask for a smaller file -- an action that cannot shrink the+ # payload that actually caused the refusal.+ _dominant = None+ _dominant_size = -1+ for call in message.get("tool_calls") or []:+ function = call.get("function") if isinstance(call, dict) else None+ if not isinstance(function, dict):+ continue+ _size = len(str(function.get("arguments") or ""))+ if _size > _dominant_size:+ _dominant_size = _size+ _dominant = str(function.get("name") or "")+ if _dominant in _FILE_WRITING_TOOLS:+ return "assistant_tool_call"+ return "assistant_tool_payload"+ return role+++def _blamed_role_for_turn(messages: list[dict]) -> str:+ """Who to blame for the newest turn, which is not always the newest MESSAGE.++ On the strict templates an assistant `tool_calls` block renders only once a `tool`+ message answers it, so the marginal cost of that tool message is the reply PLUS the+ call's arguments, which were invisible until now. Classifying the reply alone reports+ an overflow caused by a large `python`, MCP or `edit_file` payload as a large tool+ result, and the advice -- ask for a smaller slice of the file or page -- cannot shrink+ the thing that actually overflowed.+ """+ if not messages:+ return ""+ latest = messages[-1]+ if str(latest.get("role") or "") != "tool":+ return _blamed_role(latest)+ call_id = latest.get("tool_call_id")+ for message in reversed(messages[:-1]):+ role = str(message.get("role") or "")+ if role != "assistant":+ # Only the call immediately preceding this reply is paired with it; anything+ # else between them means this reply does not belong to a call at all.+ if role == "tool":+ continue+ break+ if not message.get("tool_calls"):+ break+ if call_id and not any(+ isinstance(call, dict) and str(call.get("id") or "") == str(call_id)+ for call in message.get("tool_calls") or []+ ):+ break+ # Only when the CALL is the bigger half. A dominant tool result still gets the+ # tool advice, which is right and is what the existing cases assert: the reply is+ # the thing the user can ask for less of. Blaming the call unconditionally+ # reversed that and told them to shrink a payload that was not the problem.+ _call_chars = sum(+ len(str((call.get("function") or {}).get("arguments") or ""))+ for call in message.get("tool_calls") or []+ if isinstance(call, dict)+ )+ _reply_chars = len(str(latest.get("content") or ""))+ if _call_chars > _reply_chars:+ return _blamed_role(message)+ break+ return _blamed_role(latest)++def _latest_turn_count(messages: list[dict], count_tokens: Callable[[list[dict]], int]) -> tuple[int, bool]:@@ -482,7 +1077,7 @@ def turn_diagnosis(return {"latest_turn_tokens": latest,# Whose message it is: often a tool result the user cannot shorten.- "latest_turn_role": str(messages[-1].get("role") or ""),+ "latest_turn_role": _blamed_role_for_turn(messages),"shared_prompt_tokens": shared,# Whether the number above is a token count or a four-characters-a-token guess."latest_turn_exact": bool(exact),diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 0dbf05791ab..c51da2a7742 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -12,6 +12,7 @@ import atexitimport contextlibimport errnoimport functools+import hashlibimport jsonimport loggingimport math@@ -53,13 +54,19 @@ from core.inference.context_window import (_COMPACTION_HEADROOM_RATIO,clamp_compaction_headroom_ratio,prompt_budget,+ compact_completed_tool_arguments,+ compact_executed_call_arguments,+ compact_refused_tool_arguments,estimate_messages_tokens,+ _reply_floor,+ estimate_messages_tokens_conservative,estimate_messages_tokens_dense,evicted_messages,fit_rolling_context,messages_have_media,retrieval_budget,tool_result_budget,+ turn_is_servable,)from core.inference.stream_errors import stream_error_from_chunkfrom core.inference.llama_server_args import (@@ -406,9 +413,16 @@ from core.inference.tool_call_parser import (is_reprompt_repeat as _is_reprompt_repeat,is_reprompt_restatement as _is_reprompt_restatement,is_short_intent_without_action as _is_short_intent_without_action,+ continue_after_length_message as _continue_after_length_message,+ repeated_result_message as _repeated_result_message,+ starved_result_message as _starved_result_message,reprompt_to_act_message as _reprompt_to_act_message,+ reasoning_cap_spent_message as _reasoning_cap_spent_message,+ thinking_exhausted_message as _thinking_exhausted_message,+ unfinished_thought_progress as _unfinished_thought_progress,)from core.inference.passthrough_healing import nudge_enabled as _nudge_enabled+from core.inference.repetition_guard import is_repetition_dominatedfrom core.inference.tool_loop_controller import (ToolLoopController,append_deferred_nudges,@@ -1402,6 +1416,46 @@ _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 many times a turn may be resumed after ending inside its own reasoning. Two, because+# the first retry already runs with thinking off: if that still produces nothing visible,+# the window is too small for this model and another attempt only spends more of the user's+# time reaching the same place.+_MAX_LENGTH_CONTINUATIONS = 2+_CONTINUE_AFTER_LENGTH_STATUS = "Continuing after a long thought..."+_CONTINUE_TRUNCATED_ANSWER_STATUS = "Continuing the answer..."+# Below this, a tool result carries no content: what comes back is the notice saying it was+# cut, which costs a call and teaches the model nothing. Sized to leave a short line of real+# output rather than to guarantee a useful one; the point is to catch the collapse to zero.+_MIN_USEFUL_RESULT_TOKENS = 64+# How many times one tool may return a byte-identical result before the model is told the+# call is not going to change. Follows OpenClaw's tool-loop detection, which keys on the+# RESULT rather than the arguments and never intervenes while results are still changing:+# the arguments varied on every one of the 18 calls observed here, so an argument-keyed+# guard would have watched the whole thing happen.+_MAX_IDENTICAL_TOOL_RESULTS = 3++# Separates "no kwargs were passed" from "None was passed", which is itself a real+# reasoning-kwargs value meaning send no chat_template_kwargs at all.+_UNSET = object()+++# The tail `_fit_result_to_room` appends when a result did not fit. A result carrying it+# is the WINDOW's answer, not the tool's, so two calls with different arguments that both+# end here are not two different answers -- they are the same dead end reached twice.+_WINDOW_NOTICE_MARKER = "chars for the model;"+# The OTHER shape the same cause produces. At a budget of zero there is no room for a+# body at all, so `_truncate` returns `_zero_room_stub` instead of a truncated result+# with a notice appended, and that text carries neither the marker above nor any of the+# result. Missing it is the case this classification exists for: the nudge is skipped and+# the no-progress key falls back to including the arguments, so a model reading a file in+# different slices repeats forever, which is the loop the guard was written to stop.+_ZERO_ROOM_MARKER = "no context room left"+++def _is_window_notice(result: str) -> bool:+ return _WINDOW_NOTICE_MARKER in result or _ZERO_ROOM_MARKER in result++# 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@@ -26384,6 +26438,32 @@ class LlamaCppBackend:# re-prompt slots don't extend the budget. Mirrors the safetensors guard._tool_iters_done = 0_forced_tool_call_pending = False+ # Turns that ended INSIDE their own thought, having produced nothing to show.+ # `_finalize_reasoning_only_cumulative` deliberately refuses to promote a truncated+ # thought as the answer -- correctly, it is not one -- which left the client with an+ # empty message and the user with no reply at all. Observed on a 4096 window: the+ # model spent 2301 tokens reasoning, exactly the room the prompt left, and stopped.+ # Compaction cannot help, because there is no tool result to compact; the whole+ # window went on thinking. So carry a short note of where the thought reached into a+ # fresh turn with thinking OFF, which is the one thing that guarantees the next turn+ # produces something visible.+ _length_continuations = 0+ _effective_enable_thinking = enable_thinking+ # Dropped alongside it, because for the `reasoning_effort` style an explicit+ # effort WINS over enable_thinking: `_request_reasoning_kwargs` returns the+ # caller's "high" and never reaches the enable_thinking branch, so turning+ # thinking off would re-run the turn that just spent the window thinking.+ # Cleared rather than pinned to a level, so the existing thinking-off+ # convention for this style applies -- "low" for the models that cannot+ # actually disable reasoning.+ _effective_reasoning_effort = reasoning_effort+ # Restored once a turn gets somewhere: it is turned on to stitch ONE answer+ # back together, not for the rest of the request.+ _caller_continue_final_message = continue_final_message+ # Single-element lists so the nested execution scope can rebind them.+ _last_tool_result_key: list = [None]+ _identical_result_runs: list = [0]+ _starved_call: list = [False]# Reserve extra iterations for re-prompts so they don't consume the# caller's tool-call budget; only when tool iterations are allowed.@@ -26393,13 +26473,144 @@ class LlamaCppBackend:from core.inference.chat_template_helpers import sweep_cache as _sweep_cache_markup_cache = _sweep_cache()++ def _evict_until_it_fits(+ candidate,+ tools,+ reasoning_kw,+ continue_flag = False,+ ):+ """Drop older turns from a continuation candidate that is one eviction short.++ Only reached once the candidate has already been priced and found too large.+ The single-turn case the callers were written for genuinely has nothing to+ evict, but a multi-turn chat under `truncate_oldest` usually does, and+ refusing there ended the turn before the NEXT iteration's ordinary preflight+ could ever run -- so a recoverable continuation was abandoned.++ Deliberately the plain rolling fit with instruction pins, not the loop's full+ preflight: that one archives, recalls and moves this thread's sticky boundary,+ and none of that should happen a second time in the middle of one turn.+ Returns the evicted candidate, or None when there was nothing to evict.+ """+ if context_overflow != "truncate_oldest" or not self._effective_context_length:+ return None+ if messages_have_media(candidate):+ return None+ try:+ _fitted, _truncation = _fit_with_instruction_pins(+ list(candidate),+ context_length = self._effective_context_length,+ # The room the CONTINUATION needs, which is not the room the caller's+ # cap asks for: a small `max_tokens` makes `prompt_budget` larger than+ # the window minus the reply floor, so fitting to the caller's figure+ # would evict and still leave the candidate unservable.+ max_tokens = max(+ int(max_tokens or 0), _reply_floor(self._effective_context_length)+ ),+ count_tokens = lambda fitted: self.count_chat_tokens(+ neutralize_control_markup_in_messages(+ fitted, _markup_cache, self.markup_profile+ ),+ None,+ tools,+ strict = True,+ chat_template_kwargs = reasoning_kw,+ continue_final_message = continue_flag,+ ),+ anchor_ids = _rolling_anchor_ids,+ )+ except Exception:+ logger.debug("continuation eviction: fit failed", exc_info = True)+ return None+ if not _truncation or not _truncation.get("dropped_messages"):+ return None+ logger.info(+ "Continuation did not fit; evicted %s older message(s) to try to keep it",+ _truncation.get("dropped_messages"),+ )+ # Whether that was ENOUGH is the caller's own fit check, re-run on this: the+ # rule for what counts as servable stays in one place.+ return _fitted++ def _loop_continuation_fits(+ candidate,+ tools,+ reasoning_kw,+ continue_flag = False,+ ) -> bool:+ """Whether the retry's own prompt still fits once the partial is in it.++ The final pass has the same guard. This path did not, and it is the one a+ request with tools enabled actually takes: a `length` stop that came from+ exhausting the window makes the retry prompt window-sized, and with a single+ user turn there is no older history to evict, so llama-server rejects it or+ leaves room for a stub. A count that cannot be taken is not a refusal.+ """+ if not self._effective_context_length:+ return True+ try:+ _tokens = self.count_chat_tokens(+ neutralize_control_markup_in_messages(+ candidate, _markup_cache, self.markup_profile+ ),+ None,+ tools,+ strict = True,+ chat_template_kwargs = reasoning_kw,+ # An answer continuation goes out with `continue_final_message`, which+ # renders WITHOUT a generation prompt and with the partial as the turn+ # being extended. Counting it as an ordinary prompt prices a different+ # request from the one about to be sent.+ continue_final_message = continue_flag,+ )+ except Exception:+ logger.debug("in-loop continuation: prompt count failed", exc_info = True)+ return True+ return _tokens + _reply_floor(self._effective_context_length) <= (+ self._effective_context_length+ )++ def _loop_budget_left(spent_this_attempt: int) -> "Optional[int]":+ """What remains of a cap the CALLER set, or None when they set none.++ The in-loop payload rebuilds `max_tokens` from the caller's value on every+ iteration, so without this a request capped at 100 tokens ran two more+ 100-token generations after its own cap stopped the first.+ """+ if max_tokens is None:+ return None+ window = self._effective_context_length or 0+ if window and max_tokens >= window:+ return None+ return max(0, max_tokens - _accumulated_completion_tokens - spent_this_attempt)+# A forced function applies until the model produces it; execution or denial resolves it._forced_choice_resolved = _auto_satisfies_forced_choice- for iteration in range(max_tool_iterations + _extra):+ # A continuation re-enters this loop, so without a credit it is charged to the+ # caller's TOOL budget. At max_tool_iterations=1, three plan-without-action+ # re-prompts and two truncated reasoning turns exhaust the loop before the model+ # ever issues its call, and the tool-free final pass then cannot perform the+ # action that was asked for -- the turn fails having spent no tool iteration at+ # all. Granted as they happen rather than reserved up front, so a request that+ # never stalls keeps exactly the bound it has always had.+ # Set by a continuation to hand the NEXT iteration what is left of the caller's+ # output cap, then cleared as it is spent.+ _continuation_max_tokens: Optional[int] = None+ _continuation_credits = 0+ _MAX_CONTINUATION_CREDITS = _MAX_LENGTH_CONTINUATIONS * max(1, max_tool_iterations)+ iteration = -1+ while True:+ iteration += 1+ if iteration >= max_tool_iterations + _extra + _continuation_credits:+ breakif cancel_event is not None and cancel_event.is_set():return# Whether this turn ran a tool; a no-op-only turn stays False and doesn't consume budget._turn_executed_real_tool = False+ # Set when a reasoning retry was refused because the CALLER's allowance was+ # spent rather than the window. Per iteration: it describes this turn only.+ _reasoning_cap_spent = Falseactive_tools = tool_controller.active_tools()if not active_tools:@@ -26449,7 +26660,16 @@ class LlamaCppBackend:)_reasoning_kw = self._request_reasoning_kwargs(- enable_thinking, reasoning_effort, preserve_thinking+ _effective_enable_thinking, _effective_reasoning_effort, preserve_thinking+ )+ # What THIS request may generate, which on a continuation is the remainder of+ # the caller's cap rather than the whole of it. Read before the payload+ # consumes it below, because every sizing decision this iteration makes runs+ # first: `prompt_budget` shrinks as `max_tokens` grows, so pricing a+ # 600-token continuation as if it could still emit 1000 evicts history the+ # request never needed to lose.+ _iteration_max_tokens = (+ _continuation_max_tokens if _continuation_max_tokens is not None else max_tokens)_preflight_context_length = None_preflight_succeeded = False@@ -26480,7 +26700,7 @@ class LlamaCppBackend:conversation, truncation = _fit_with_instruction_pins(conversation,context_length = self._effective_context_length,- max_tokens = max_tokens,+ max_tokens = _iteration_max_tokens,count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(fitted, _markup_cache, self.markup_profile@@ -26532,7 +26752,8 @@ class LlamaCppBackend:# Leave room for the answer appended on the next iteration.recall_budget_tokens = _retrieval_budget(self._effective_context_length,- max_tokens,+ # As above: the cap this iteration will actually send.+ _iteration_max_tokens,truncation.get("prompt_tokens_after") or 0,reply_returns = True,),@@ -26612,6 +26833,13 @@ class LlamaCppBackend:if max_tokens is not Noneelse (self._effective_context_length or _DEFAULT_MAX_TOKENS_FLOOR))+ # A continuation is the SAME reply carried across two requests, so it spends+ # the caller's output budget once, not once per attempt. Rebuilt from the+ # caller's value above, this payload would hand a 100-token request another+ # full 100 tokens on every retry.+ if _continuation_max_tokens is not None:+ payload["max_tokens"] = _continuation_max_tokens+ _continuation_max_tokens = Noneif stop:payload["stop"] = stopif seed is not None:@@ -26637,7 +26865,7 @@ class LlamaCppBackend:conversation, truncation = _fit_with_instruction_pins(conversation,context_length = self._effective_context_length,- max_tokens = max_tokens,+ max_tokens = _iteration_max_tokens,count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(fitted, _markup_cache, self.markup_profile@@ -26748,6 +26976,57 @@ class LlamaCppBackend:_text_args_name = ""_confirm_gated_iteration = bool(confirm_tool_calls) and not bypass_permissions+ # Reclaim reply room before generating, not only before running a tool.+ #+ # The pre-execution gate compacts only when the next prompt would not FIT.+ # A prompt can fit and still leave nothing to answer in, and that is the+ # more common ending: observed on a 4096 window where every tool call was+ # servable, none was refused, the file was written -- and the turn died on+ # `finish_reason: length` with the model still thinking, because the prompt+ # had eaten the room its answer needed. Compaction is exactly the lever for+ # that and nothing was asking it to run.+ #+ # `prompt_budget` is the line here, not the window: it already encodes how+ # much of the window a reply is owed. Over it means tight, not fatal, so+ # this compacts and never refuses -- a turn that fits is always sent.+ if self._effective_context_length and conversation:+ # Same remainder the preflight used: this check decides whether to+ # compact, and pricing a continuation as if it had the whole cap+ # compacts a turn that had room.+ _reply_target = prompt_budget(+ self._effective_context_length, _iteration_max_tokens+ )+ if estimate_messages_tokens_dense(conversation) > 0.7 * _reply_target:+ try:+ _prompt_now = self.count_chat_tokens(+ neutralize_control_markup_in_messages(+ conversation, _markup_cache, self.markup_profile+ ),+ None,+ safe_tools,+ strict = True,+ chat_template_kwargs = _reasoning_kw,+ )+ except Exception:+ logger.debug("reply-room fit: prompt count failed", exc_info = True)+ _prompt_now = None+ if _prompt_now is not None and _prompt_now > _reply_target:+ _roomy, _n_roomy = compact_completed_tool_arguments(+ conversation, protect_last = 1+ )+ if _n_roomy:+ conversation[:] = _roomy+ payload["messages"] = neutralize_control_markup_in_messages(+ conversation, _markup_cache, self.markup_profile+ )+ logger.info(+ "Compacted %d completed tool call(s) for reply room: "+ "prompt was %d tokens against a %d-token budget",+ _n_roomy,+ _prompt_now,+ _reply_target,+ )+with self._open_chat_stream_with_respawn_retry(payload,cancel_event,@@ -27367,6 +27646,250 @@ class LlamaCppBackend:_stripped = content_accum.strip()if not _stripped:_stripped = reasoning_accum.strip()++ # ── Continue an answer the window cut in half ──+ # The sibling case below is a turn that showed NOTHING. This one+ # showed real work and stopped mid-sentence: observed streaming a+ # 2401-byte file inline at a 4096 window, cut at `ctx.arc(6, -5, 5,`+ # with no closing tag. Compaction cannot help, because the room that+ # ran out is the reply's, not the prompt's; the answer has to be+ # finished across two turns instead.+ #+ # `continue_final_message` is what makes that seamless: the partial+ # goes back as the assistant turn to be EXTENDED, so the model picks+ # up mid-token rather than restarting and apologising.+ _partial_answer = content_accum.strip()+ if (+ _iter_finish_reason == "length"+ and _partial_answer+ and not tool_calls_acc+ and _length_continuations < _MAX_LENGTH_CONTINUATIONS+ ):+ # Withheld BEFORE the nudge is sent, not regretted after. A model+ # echoing one fragment would otherwise have the echo stitched into+ # the answer, which is how hermes-agent got a 60,698-char reply.+ if is_repetition_dominated(_partial_answer):+ logger.info(+ "Truncated answer is repetition-dominated (%d chars); "+ "keeping it as-is rather than continuing an echo",+ len(_partial_answer),+ )+ else:+ _length_continuations += 1+ logger.info(+ "Answer cut off at %d chars; continuing %d/%d",+ len(_partial_answer),+ _length_continuations,+ _MAX_LENGTH_CONTINUATIONS,+ )+ # Candidate first, as the final pass does: a retry that+ # cannot be served, or one the caller's own cap leaves no+ # room for, must not spend the conversation or the usage.+ _cand_c = list(conversation)+ append_assistant_turn(+ _cand_c,+ # Unstripped: `strip()` would make the replayed prefix+ # differ from the text already streamed, and the next+ # delta is concatenated onto the STREAMED one. Inside a+ # code block that eats the newline and indentation the+ # continuation is about to build on.+ {"role": "assistant", "content": content_accum},+ continue_final_message = True,+ )+ _fu_c = (+ _backfill_usage_from_timings(_iter_usage, _iter_timings) or {}+ )+ # A `length` stop means the attempt produced its whole+ # allowance, which is what to charge when the server+ # reported no usage.+ _spent_c = _fu_c.get("completion_tokens", 0) or int(+ payload.get("max_tokens") or 0+ )+ _cap_left_c = _loop_budget_left(_spent_c)+ _fits_c = _cap_left_c != 0 and _loop_continuation_fits(+ _cand_c, safe_tools, _reasoning_kw, True+ )+ if _cap_left_c != 0 and not _fits_c:+ # Same as the thought continuation below: abandoning+ # here ends the turn, so the next iteration's ordinary+ # preflight never gets to drop an older exchange.+ _evicted_c = _evict_until_it_fits(+ _cand_c, safe_tools, _reasoning_kw, True+ )+ if _evicted_c is not None and _loop_continuation_fits(+ _evicted_c, safe_tools, _reasoning_kw, True+ ):+ _cand_c = _evicted_c+ _fits_c = True+ if _cap_left_c == 0 or not _fits_c:+ logger.info(+ "Not continuing the answer: %s",+ "the caller's output cap is spent"+ if _cap_left_c == 0+ else "the retry prompt would not be served",+ )+ _length_continuations -= 1+ else:+ conversation[:] = _cand_c+ continue_final_message = True+ if _cap_left_c is not None:+ _continuation_max_tokens = _cap_left_c+ _accumulated_completion_tokens += _fu_c.get(+ "completion_tokens", 0+ )+ _it_c = _iter_timings or {}+ _accumulated_predicted_ms += _it_c.get("predicted_ms", 0)+ _accumulated_predicted_n += _it_c.get("predicted_n", 0)+ if _continuation_credits < _MAX_CONTINUATION_CREDITS:+ _continuation_credits += 1+ yield {"type": "status", "text": ""}+ yield {+ "type": "status",+ "text": _CONTINUE_TRUNCATED_ANSWER_STATUS,+ }+ continue++ # ── Continue a turn that ended inside its own thought ──+ # Ahead of the re-prompt below because that one is gated on a SHORT+ # response, and a thought that filled the window is the opposite of+ # short -- the case fell through the gap and returned an empty turn.+ if (+ _iter_finish_reason == "length"+ and not content_accum.strip()+ and reasoning_accum.strip()+ and _length_continuations < _MAX_LENGTH_CONTINUATIONS+ ):+ _length_continuations += 1+ # Thinking off for the retry. Leaving it on re-runs the turn that+ # just failed, and the second failure looks identical to the first.+ _effective_enable_thinking = False+ _effective_reasoning_effort = None+ logger.info(+ "Turn ended inside its reasoning (%d chars, finish_reason "+ "length); continuing %d/%d with thinking off",+ len(reasoning_accum),+ _length_continuations,+ _MAX_LENGTH_CONTINUATIONS,+ )+ # Candidate first, exactly as the partial-answer branch above+ # does. This one mutated `conversation` directly and checked+ # neither the fit nor the caller's cap: a thought that reached+ # the context wall makes the retry prompt window-sized, and+ # with no evictable history the recovery request is the one+ # thing that must not be rejected.+ _cand_l = list(conversation)+ append_assistant_turn(+ _cand_l,+ {+ "role": "assistant",+ "content": _unfinished_thought_progress(reasoning_accum),+ },+ continue_final_message = continue_final_message,+ )+ _cand_l.append(+ {+ "role": "user",+ "content": _continue_after_length_message(),+ }+ )+ _fu_l = _backfill_usage_from_timings(_iter_usage, _iter_timings) or {}+ _spent_l = _fu_l.get("completion_tokens", 0) or int(+ payload.get("max_tokens") or 0+ )+ _cap_left_l = _loop_budget_left(_spent_l)+ # `_reasoning_kw` was computed at the top of this iteration,+ # with thinking ON. The retry goes out with it off, which is a+ # different rendered prompt on any template that reads+ # `enable_thinking`, so admitting under the old kwargs prices+ # a request nobody sends. Same fix the final pass already has.+ _off_kw_l = self._request_reasoning_kwargs(+ False, None, preserve_thinking+ )+ # Counted ONCE in the ordinary case: the eviction attempt+ # below only runs on a candidate already found too large.+ _fits_l = _cap_left_l != 0 and _loop_continuation_fits(+ _cand_l, safe_tools, _off_kw_l+ )+ if _cap_left_l != 0 and not _fits_l:+ # Possibly one eviction short. Refusing here ends the+ # turn, so the next iteration's ordinary preflight never+ # gets its chance to drop an older exchange.+ _evicted_l = _evict_until_it_fits(_cand_l, safe_tools, _off_kw_l)+ if _evicted_l is not None and _loop_continuation_fits(+ _evicted_l, safe_tools, _off_kw_l+ ):+ _cand_l = _evicted_l+ _fits_l = True+ if _cap_left_l == 0 or not _fits_l:+ logger.info(+ "Not continuing the thought: %s",+ "the caller's output cap is spent"+ if _cap_left_l == 0+ else "the retry prompt would not be served",+ )+ # Which wall it was, so the give-up below names the lever+ # the user actually has. Blaming the context window for a+ # spent Max Tokens sends them to the one setting that was+ # never the constraint, and this reaches the client as+ # ordinary content, so nothing downstream can correct it.+ _reasoning_cap_spent = _cap_left_l == 0+ _length_continuations -= 1+ _effective_enable_thinking = enable_thinking+ _effective_reasoning_effort = reasoning_effort+ else:+ conversation[:] = _cand_l+ if _cap_left_l is not None:+ _continuation_max_tokens = _cap_left_l+ _accumulated_completion_tokens += _fu_l.get("completion_tokens", 0)+ _it_l = _iter_timings or {}+ _accumulated_predicted_ms += _it_l.get("predicted_ms", 0)+ _accumulated_predicted_n += _it_l.get("predicted_n", 0)+ # Blank first so the route resets its text cursor, as the+ # re-prompt below does; else the retry reads as a hang.+ if _continuation_credits < _MAX_CONTINUATION_CREDITS:+ _continuation_credits += 1+ yield {"type": "status", "text": ""}+ yield {"type": "status", "text": _CONTINUE_AFTER_LENGTH_STATUS}+ continue++ if (+ _iter_finish_reason == "length"+ and not content_accum.strip()+ and reasoning_accum.strip()+ ):+ # Allowance spent and still nothing to show. Saying so is the+ # whole point: returning here silently is the original defect,+ # a turn that renders as an empty message with no indication+ # that anything went wrong or what the user might change.+ logger.info(+ "Reasoning exhausted the window %d times; giving up with "+ "an explanation",+ _length_continuations,+ )+ # `_reasoning_cap_spent` is only set when a continuation was+ # REFUSED. Arriving here by exhausting the retry limit leaves+ # it at its default, so the cap is re-read: the last permitted+ # attempt may be the one that finished off Max Tokens.+ _fu_g = _backfill_usage_from_timings(_iter_usage, _iter_timings) or {}+ _spent_g = _fu_g.get("completion_tokens", 0) or int(+ payload.get("max_tokens") or 0+ )+ yield {"type": "status", "text": ""}+ yield {+ "type": "content",+ "text": (+ _reasoning_cap_spent_message(max_tokens)+ if _reasoning_cap_spent or _loop_budget_left(_spent_g) == 0+ else _thinking_exhausted_message(self._effective_context_length)+ ),+ }+ _meta = _build_metadata_event(+ _iter_usage, _iter_timings, _iter_finish_reason+ )+ if _meta is not None:+ yield _meta+ return+_render_html_already_done_intent = _tool_succeeded("render_html") and re.search(@@ -27560,6 +28083,23 @@ class LlamaCppBackend:return# ── Execute tool calls ──+ # The turn got somewhere, so the earlier stall is spent history. Without+ # this reset the allowance is consumed for the whole request and a later,+ # unrelated stall gets fewer attempts than it should -- the shape of+ # NousResearch/hermes-agent#79100, where the counter survived a good+ # tool round and the give-up fired early. Thinking comes back on for the+ # same reason: it was turned off to break one stall, not for the request.+ _length_continuations = 0+ _effective_enable_thinking = enable_thinking+ _effective_reasoning_effort = reasoning_effort+ # Captured BEFORE the reset below. This turn may have been resumed with+ # `continue_final_message`, leaving the partial as the trailing assistant+ # message, and anything recorded further down has to merge into it.+ # Restoring the caller's value first made `append_assistant_turn` add a+ # SECOND consecutive assistant message, which is the role alternation that+ # helper exists to preserve and which strict templates reject.+ _merge_into_partial = continue_final_message+ continue_final_message = _caller_continue_final_message_accumulated_completion_tokens += (_backfill_usage_from_timings(_iter_usage, _iter_timings) or {}).get("completion_tokens", 0)@@ -27663,7 +28203,7 @@ class LlamaCppBackend:append_assistant_turn(conversation,assistant_msg,- continue_final_message = continue_final_message,+ continue_final_message = _merge_into_partial,)assistant_appended = Trueelse:@@ -27735,6 +28275,31 @@ class LlamaCppBackend:if decision.tool_call_id:denied_message["tool_call_id"] = decision.tool_call_idconversation.append(denied_message)+ # The denial is itself the `tool` message that makes the+ # template render the call it refused, so declining an+ # oversized write COSTS the prompt the very arguments it+ # declined to afford. The bulk compaction deliberately skips+ # denials now that replies are paired with their call, so+ # without this the user gets a context error in place of the+ # refusal they asked for.+ if decision.tool_call_id:+ conversation[:] = compact_refused_tool_arguments(+ conversation, decision.tool_call_id+ )+ # Rebuilt, not mutated, so the handle this batch is still+ # appending to is now detached. Same defect the executed+ # path had: the next call in the batch would land on the+ # stale object while its RESULT lands in `conversation`,+ # and the model receives a result for a call it cannot see.+ for _dmsg in reversed(conversation):+ if _dmsg.get("role") != "assistant":+ continue+ if any(+ (_tc or {}).get("id") == decision.tool_call_id+ for _tc in (_dmsg.get("tool_calls") or [])+ ):+ assistant_msg = _dmsg+ breakif _forced_tool_call_pending:_forced_tool_call_pending = Falsecontinue@@ -27743,6 +28308,229 @@ class LlamaCppBackend:if decision_slot is not None:abort_tool_decision(decision_slot, approval_id)+ # Can the turn this call is part of still be SERVED once it returns?+ # Everything below prices what a result may add; nothing asked whether+ # the prompt fits with no result at all. It can already not fit: the+ # model's own arguments are in `conversation` by now (appended above),+ # and a whole-file `edit_file` puts the file itself there. The budget+ # clamps to zero, the result is cut to its notice, the tool runs, and+ # llama-server rejects the next request anyway -- with the write on+ # disk. Nothing downstream recovers it: the fit protects the newest+ # turn, and ctx_shift is off for any mmproj load, so there is no+ # sliding window underneath this either.+ #+ # Two levers, both only once the turn is actually spilling. History+ # first, via the arguments of calls that already returned -- pure+ # replay, since the tool got them in full and the file is on disk --+ # and only then a refusal, which is worth saying precisely because it+ # is the one outcome on this path that leaves nothing written.+ _unservable_text: Optional[str] = None+ # Set when the gate chose to RUN an oversized call rather than+ # refuse it, on the strength of what compacting it will reclaim.+ _compact_after_execution = False+ # The exact count of the prompt that compaction WILL produce, kept so+ # the result budget below is priced against it.+ _compacted_turn_tokens: Optional[int] = None+ if self._effective_context_length:+ # This iteration's cap, like every other sizing decision in it.+ _room_target = prompt_budget(+ self._effective_context_length, _iteration_max_tokens+ )+ # Cheap gate first. The exact count is a template render plus a+ # tokenizer pass over the whole conversation, and this runs per+ # call; a thread with room to spare must not pay for it. The+ # estimate only decides whether to ASK, never whether to refuse.+ # Conservative, not the flat dense estimate. That one still+ # charges ASCII four characters a token, and base64 tokenises+ # near one, so a ~6 KB encoded `edit_file` payload prices at a+ # quarter of its real cost and slips under this threshold at a+ # 4096 window -- the exact check is skipped, the tool runs, and+ # the write lands before the next request is rejected. Erring+ # high here only costs an extra count; erring low costs the+ # whole gate.+ if estimate_messages_tokens_conservative(conversation) > 0.7 * _room_target:+ # Priced with a STAND-IN tool message for the call about to+ # run, not on the conversation as it stands. A chat template+ # renders an assistant turn's `tool_calls` only once a `tool`+ # message answers them -- until then the arguments cost the+ # prompt nothing, so counting the conversation as-is misses+ # exactly the tokens this gate exists to catch. Measured on+ # Qwen3.8-27B: the same messages price at 1,063 tokens without+ # the stand-in and 2,172 with it, and the request the loop goes+ # on to send is the second number.+ #+ # Empty content, because that is the best case: a result can be+ # cut to its notice but the call itself cannot be unsent. If+ # even this does not fit, nothing the tool returns will.+ _probe_message: dict = {+ "role": "tool",+ "name": decision.tool_name,+ "content": "",+ }+ if decision.tool_call_id:+ _probe_message["tool_call_id"] = decision.tool_call_id+ _compacted_calls = 0+ for _attempt in range(2):+ try:+ _turn_tokens = self.count_chat_tokens(+ neutralize_control_markup_in_messages(+ [*conversation, _probe_message],+ _markup_cache,+ self.markup_profile,+ ),+ None,+ safe_tools,+ strict = True,+ chat_template_kwargs = _reasoning_kw,+ )+ except Exception:+ # No count, no refusal: the old behaviour (run it and+ # let llama-server decide) beats declining a call on a+ # number that could not be taken.+ logger.debug(+ "pre-execution fit: prompt count failed",+ exc_info = True,+ )+ break+ if turn_is_servable(+ self._effective_context_length, max_tokens, _turn_tokens+ ):+ break+ if _attempt == 0:+ # Spend history, then re-price against the real+ # tokenizer rather than trusting the saving.+ _compacted, _n = compact_completed_tool_arguments(+ conversation, protect_last = 1+ )+ if _n:+ conversation[:] = _compacted+ _compacted_calls = _n+ logger.info(+ "Compacted arguments of %d completed tool call(s) "+ "to fit the context window",+ _n,+ )+ continue+ # Last resort before refusing: run it anyway, and compact+ # ITS arguments the moment it returns.+ #+ # Running a tool needs no context -- only the next prompt+ # does, and by then the arguments describe a file on disk.+ # Refusing does not avoid their cost either, because the+ # refusal is itself the `tool` message that renders them;+ # it just spends the same tokens with nothing written, and+ # the model retries with a fresh oversized call. Measured+ # over three rounds of one thread, each retry reclaimed+ # less (50%, 34%, 15%) and the turn ended in a+ # one-character reply.+ if decision.tool_call_id:+ _as_if_run = compact_executed_call_arguments(+ [*conversation, _probe_message],+ decision.tool_call_id,+ )+ try:+ _after_tokens = self.count_chat_tokens(+ neutralize_control_markup_in_messages(+ _as_if_run, _markup_cache, self.markup_profile+ ),+ None,+ safe_tools,+ strict = True,+ chat_template_kwargs = _reasoning_kw,+ )+ except Exception:+ _after_tokens = None+ if _after_tokens is not None and turn_is_servable(+ self._effective_context_length,+ max_tokens,+ _after_tokens,+ ):+ _compact_after_execution = True+ _compacted_turn_tokens = _after_tokens+ logger.info(+ "Running %s despite a %d-token turn: compacting "+ "its own arguments afterwards brings the next "+ "prompt to %d, so the file gets written",+ decision.tool_name,+ _turn_tokens,+ _after_tokens,+ )+ break+ from core.inference import context_refusal # noqa: PLC0415++ _unservable_text = context_refusal.describe_unservable_tool_call(+ decision.tool_name,+ _turn_tokens,+ self._effective_context_length,+ compacted_calls = _compacted_calls,+ )+ logger.warning(+ "Refused %s before execution: prompt would be %d tokens "+ "against a %d-token window",+ decision.tool_name,+ _turn_tokens,+ self._effective_context_length,+ )+ break++ if _unservable_text is not None:+ # Same shape as the user-denied path above, so the frontend needs+ # no new case and the model gets a tool result it can read rather+ # than a stream that stops mid-turn.+ resolved_provisional_tool_call_ids.add(decision.tool_call_id)+ yield {+ "type": "tool_end",+ "tool_name": decision.tool_name,+ "tool_call_id": decision.tool_call_id,+ "result": _unservable_text,+ "provenance": decision.provenance,+ }+ _refused_message = {+ "role": "tool",+ "name": decision.tool_name,+ "content": _unservable_text,+ }+ if decision.tool_call_id:+ _refused_message["tool_call_id"] = decision.tool_call_id+ conversation.append(_refused_message)+ # The refusal is itself the `tool` message that makes this call's+ # arguments start rendering, so declining without this leaves the+ # next generation over the window anyway: observed as an accurate+ # refusal followed four seconds later by the 400 it was issued to+ # prevent. Nothing ran, so nothing on disk reflects them.+ _before_refused_compaction = len(json.dumps(conversation, default = str))+ conversation[:] = compact_refused_tool_arguments(+ conversation, decision.tool_call_id+ )+ _after_refused_compaction = len(json.dumps(conversation, default = str))+ if _after_refused_compaction < _before_refused_compaction:+ logger.info(+ "Compacted refused %s arguments: %d -> %d chars",+ decision.tool_name,+ _before_refused_compaction,+ _after_refused_compaction,+ )+ if _forced_tool_call_pending:+ _forced_tool_call_pending = False+ # The forced choice is spent by this refusal, as it is by a user+ # denial. Left unresolved, the next iteration advertises the same+ # tool as required and the model is pushed into calling it again+ # for the same refusal, instead of being free to say what went+ # wrong or finish the turn another way.+ _forced_choice_resolved = True+ # This assistant turn was rebuilt by the compaction above, so the+ # handle the batch is appending to no longer belongs to it.+ for _rmsg in reversed(conversation):+ if _rmsg.get("role") != "assistant":+ continue+ if any(+ (_tc or {}).get("id") == decision.tool_call_id+ for _tc in (_rmsg.get("tool_calls") or [])+ ):+ assistant_msg = _rmsg+ break+ continue+_effective_timeout = None if tool_call_timeout >= 9999 else tool_call_timeout# RAG: cap paraphrased KB re-searches that slip past the dup guard.if (@@ -27754,6 +28542,11 @@ class LlamaCppBackend:# Execute in a worker thread so live stdout chunks and heartbeats# stream while the tool blocks (the SSE route turns heartbeats into# keepalives). Result is byte-identical to a direct call.+ # Filled in by `_invoke_tool` below so the result log can report+ # the budget that was actually handed over, from a scope that+ # outlives the closure.+ _last_result_budget: list = ["<not passed>"]+def _invoke_tool(_output_callback, _decision = decision):# execute_tool is injectable and may be monkey-patched with the# pre-PR signature; forward output_callback only if it's accepted.@@ -27819,10 +28612,27 @@ class LlamaCppBackend:# the tool catalogue, so the offset stays only as the# fallback for a tokenizer call that raises._exact_prompt_tokens: Optional[int] = None+ # Counted WITH a stand-in tool message for the call about+ # to run, exactly as the admission gate prices it. Qwen+ # and templates like it render an assistant tool call only+ # once a `tool` reply follows, so counting `conversation`+ # as it stands omits this call's own arguments -- and the+ # result is then handed room those arguments already+ # occupy. Empty content, because a result can be cut to+ # its notice but the call itself cannot be unsent.+ _size_probe: dict = {+ "role": "tool",+ "name": decision.tool_name,+ "content": "",+ }+ if decision.tool_call_id:+ _size_probe["tool_call_id"] = decision.tool_call_idtry:_exact_prompt_tokens = self.count_chat_tokens(neutralize_control_markup_in_messages(- conversation, _markup_cache, self.markup_profile+ [*conversation, _size_probe],+ _markup_cache,+ self.markup_profile,),None,safe_tools,@@ -27838,8 +28648,17 @@ class LlamaCppBackend:# already carries the fit's exact tokenizer count, so it# needs no correction, while the estimate that stands in# for it undercounts CJK and emoji by about half.+ # The gate decided to run this call BECAUSE compacting+ # its own arguments makes the next prompt fit, and it+ # already counted that prompt exactly. Pricing the result+ # against the uncompacted conversation instead hands a+ # large `python`, `terminal` or file call a near-zero+ # budget and throws its output away, in the one case where+ # the room is about to be there._spent = (- _exact_prompt_tokens+ _compacted_turn_tokens+ if _compact_after_execution and _compacted_turn_tokens+ else _exact_prompt_tokensif _exact_prompt_tokens is not Noneelse estimate_messages_tokens_dense(conversation)+ (@@ -27890,11 +28709,84 @@ class LlamaCppBackend:_pending_args = 2 * estimate_messages_tokens_dense(_pending_msgs)- kwargs["result_budget_tokens"] = tool_result_budget(+ _result_budget = tool_result_budget(self._effective_context_length,- max_tokens,+ # This iteration's cap, not the caller's whole+ # one. A recovery turn with 100 of 1000 tokens+ # left had the result priced as if 1000 were+ # still to come, which reserves room away and can+ # starve a read the request had space for.+ _iteration_max_tokens,_spent + _pending_args,) // (len(_pending) + 1)+ # A budget at or near zero means the call cannot deliver+ # anything: the result is cut to a notice saying it was+ # cut, which reads to the model as a fresh failure rather+ # than a wall, so it tries again. Observed at a 4096+ # window, reading a 2401-byte file back: six of the last+ # eight calls priced at zero and returned the same+ # 109-char notice, and the turn went on 18 calls.+ #+ # Room is exactly what compaction reclaims, so spend it+ # here before the call rather than after the turn is lost.+ if (+ _result_budget < _MIN_USEFUL_RESULT_TOKENS+ and self._effective_context_length+ ):+ _roomier, _n_roomier = compact_completed_tool_arguments(+ conversation, protect_last = 1+ )+ if _n_roomier:+ conversation[:] = _roomier+ try:+ # With the same stand-in reply the initial+ # sizing used. Without it, this call's own+ # arguments vanish from the count on the+ # templates that render a call only once a+ # reply follows, and the room they occupy+ # is handed to the result.+ _spent_after = self.count_chat_tokens(+ neutralize_control_markup_in_messages(+ [*conversation, _size_probe],+ _markup_cache,+ self.markup_profile,+ ),+ None,+ safe_tools,+ strict = True,+ chat_template_kwargs = _reasoning_kw,+ )+ except Exception:+ logger.debug(+ "result budget rescue: count failed",+ exc_info = True,+ )+ _spent_after = None+ if _spent_after is not None:+ _rescued = tool_result_budget(+ self._effective_context_length,+ # The same cap the first pricing used,+ # or the rescue is measured against a+ # different request from the one it is+ # rescuing.+ _iteration_max_tokens,+ _spent_after + _pending_args,+ ) // (len(_pending) + 1)+ logger.info(+ "Result budget for %s was %d; compacted "+ "%d completed call(s) and it is now %d",+ decision.tool_name,+ _result_budget,+ _n_roomier,+ _rescued,+ )+ _result_budget = max(_result_budget, _rescued)+ kwargs["result_budget_tokens"] = _result_budget+ _last_result_budget[0] = kwargs["result_budget_tokens"]+ # Known before the tool runs, so there is no reason to+ # spend calls rediscovering it: the repeat guard below+ # would reach the same conclusion three calls later.+ _starved_call[0] = _result_budget < _MIN_USEFUL_RESULT_TOKENSif accepts_kwarg(execute_tool, "conversation_budget_tokens"):if accepts_kwarg(execute_tool, "conversation_token_counter"):# The admission check estimates a result's size by@@ -27916,7 +28808,12 @@ class LlamaCppBackend:# the result cannot spend their entire shared budget.kwargs["conversation_budget_tokens"] = _retrieval_budget(self._effective_context_length,- max_tokens,+ # This iteration's cap, like the result budget+ # beside it. Reserving the caller's whole+ # allowance on a continuation that has a fraction+ # of it left returns a near-zero budget and drops+ # recall the request had room for.+ _iteration_max_tokens,_spent,reply_returns = True,)@@ -27955,6 +28852,92 @@ class LlamaCppBackend:result = f"Error: tool raised an exception: {_tool_exc}"if decision.tool_name in RAG_SEARCH_TOOLS:_kb_search_count += 1+ # What the result actually cost against what it was allowed. The pair+ # is the only way to tell a budget that was never delivered from one+ # that was delivered and ignored, and a 400 one second after a tool+ # returns cannot distinguish them on its own.+ logger.info(+ "tool result: name=%s budget_tokens=%s chars=%d",+ decision.tool_name,+ _last_result_budget[0],+ len(result) if isinstance(result, str) else -1,+ )+ # The window priced this result at nothing before the call ran, so the+ # model is told now rather than after three calls prove it.+ _result_was_starved = False+ # The budget says what the window ALLOWED, not what the tool returned.+ # A short result fits a few tokens completely -- "Created a.py", "OK",+ # the acknowledgement a mutation gives -- and telling the model that+ # nothing usable came back invites it to discard a successful write or+ # do it a second time. So the nudge waits for evidence the result was+ # actually cut: the truncation notice, or nothing at all.+ if (+ _starved_call[0]+ and isinstance(result, str)+ and (not result.strip() or _is_window_notice(result))+ ):+ _starved_call[0] = False+ _result_was_starved = True+ logger.info(+ "%s ran with a result budget below %d; telling the model the "+ "window cannot carry the result",+ decision.tool_name,+ _MIN_USEFUL_RESULT_TOKENS,+ )+ result = _starved_result_message(decision.tool_name, result)+ else:+ # Cleared either way: it describes THIS call's budget, and leaving+ # it set would hand the notice to the next call instead.+ _starved_call[0] = False++ # ── No-progress guard: the same answer, over and over ──+ # Keyed on the RESULT, not the arguments. In the turn this came from,+ # the arguments differed every time (different line ranges of one file)+ # while the answer was the same 109-char truncation notice, so an+ # argument-keyed guard would have watched all 18 calls go by. OpenClaw+ # keys on the result for the same reason and never fires while results+ # are still changing, which is what makes this safe for polling.+ if isinstance(result, str):+ # The arguments are part of the key UNLESS the result is one the+ # window itself produced. A tool that answers every distinct+ # mutation with `OK` is making progress, and the nudge below --+ # which says different arguments will not change the answer -- can+ # talk it out of the operations it has left. A starved result is+ # the opposite: it is the notice, not the tool's answer, so the+ # arguments are exactly what must NOT be part of the key. That was+ # the observed turn, where 18 calls read different line ranges of+ # one file and got the same 109-char truncation notice each time.+ _result_key = (+ decision.tool_name,+ hashlib.sha1(result.encode("utf-8", "replace")).hexdigest(),+ None+ if _result_was_starved or _is_window_notice(result)+ else hashlib.sha1(+ json.dumps(decision.arguments, sort_keys = True, default = str).encode(+ "utf-8", "replace"+ )+ ).hexdigest(),+ )+ if _result_key == _last_tool_result_key[0]:+ _identical_result_runs[0] += 1+ else:+ _last_tool_result_key[0] = _result_key+ _identical_result_runs[0] = 1+ if _identical_result_runs[0] >= _MAX_IDENTICAL_TOOL_RESULTS:+ logger.info(+ "%s returned the same result %d times; saying so instead of "+ "letting the turn spend itself repeating it",+ decision.tool_name,+ _identical_result_runs[0],+ )+ # Told, not silently stopped. The model can still finish the+ # task another way, and hard-stopping a turn that is otherwise+ # healthy would trade one dead end for a worse one.+ result = _repeated_result_message(+ decision.tool_name, _identical_result_runs[0], result+ )+ _identical_result_runs[0] = 0+ _last_tool_result_key[0] = Nonecompletion = tool_controller.record_result(decision, result)resolved_provisional_tool_call_ids.add(decision.tool_call_id)# A real execution opens the post-tool phase; carrying the pre-tool@@ -27966,6 +28949,41 @@ class LlamaCppBackend:_forced_choice_resolved = Trueyield completion.tool_end_event()conversation.append(completion.tool_message())+ if _compact_after_execution and decision.tool_call_id:+ # The promise the gate made when it let this run. Applied here+ # rather than on the next pass because the next pass may not+ # come: this turn's own generation is the request that would+ # otherwise be rejected.+ _before_len = len(json.dumps(conversation, default = str))+ conversation[:] = compact_executed_call_arguments(+ conversation, decision.tool_call_id+ )+ logger.info(+ "Compacted %s arguments after running it: %d -> %d chars",+ decision.tool_name,+ _before_len,+ len(json.dumps(conversation, default = str)),+ )+ # The compaction rebuilds the messages rather than mutating them,+ # so the local handle now points at a dict that is no longer in+ # `conversation`. One assistant turn can carry several calls, and+ # the next one in the batch appends its tool_call to this handle+ # while its RESULT goes to `conversation`: the model would receive+ # a tool result answering a call it cannot see. Rebind to the live+ # message carrying this call.+ # Backwards: generated ids restart at `call_0` every turn, so a+ # forward scan binds to the OLDEST turn carrying the id and the+ # rest of this batch is appended to history instead of to the live+ # exchange. The call being compacted is always the current one.+ for _msg in reversed(conversation):+ if _msg.get("role") != "assistant":+ continue+ if any(+ (_tc or {}).get("id") == decision.tool_call_id+ for _tc in (_msg.get("tool_calls") or [])+ ):+ assistant_msg = _msg+ breakif _forced_tool_call_pending:_forced_tool_call_pending = False@@ -28015,7 +29033,7 @@ class LlamaCppBackend:append_assistant_turn(conversation,assistant_msg,- continue_final_message = continue_final_message,+ continue_final_message = _merge_into_partial,)assistant_appended = Trueappend_deferred_nudges(conversation, deferred_noop_msgs)@@ -28316,143 +29334,525 @@ class LlamaCppBackend:_metadata_finish_reason = None_stream_done = False- try:- with self._open_chat_stream_with_respawn_retry(- stream_payload,- cancel_event,- on_respawn = _refit_final_after_respawn,- ) as (- response,- first_token_deadline,- ):- for truncation in _final_respawn_truncations:- yield {"type": "context_truncated", **truncation}- buffer = ""- for raw_chunk in self._iter_text_cancellable(- response,+ # The tool loop's continuation does not reach here: this generation runs AFTER+ # the loop breaks, so a turn that spends its whole tool budget and is then cut+ # off mid-answer had nothing to recover it. Observed live: 25 tool calls, 22387+ # tokens, stopped inside drawBird() with the game left half-written.+ _final_length_continuations = 0+ _continue_final = False+ _final_replayed_chars = 0++ def _remaining_output_budget() -> "Optional[int]":+ """What is left of a cap the CALLER set, or None when they set none.++ `finish_reason: "length"` does not say which wall was hit. A caller asking for+ at most 100 completion tokens gets it at their own cap, and continuing twice+ more returned roughly 300 -- over the limit the API promised, for latency and+ tokens nobody asked for. Only the context wall deserves a continuation, and a+ caller who set a cap gets the remainder of it rather than a fresh one.++ None means no explicit cap: `max_tokens` unset, or set to the whole window,+ which is what the backend substitutes for "Max" and is indistinguishable from+ unset. There the length stop IS the context wall, which is the case this+ continuation exists for.+ """+ if max_tokens is None:+ return None+ window = self._effective_context_length or 0+ if window and max_tokens >= window:+ return None+ # This attempt's own cost. A server that reported usage gives it exactly;+ # without one, a `length` stop still means the attempt produced the whole+ # allowance it was given, so charge that. Guessing LOW here is what lets the+ # caller's cap be overrun, which is the defect this exists to prevent.+ _this_attempt = (+ _backfill_usage_from_timings(_metadata_usage, _metadata_timings) or {}+ ).get("completion_tokens", 0) or int(stream_payload.get("max_tokens") or 0)+ return max(0, max_tokens - _accumulated_completion_tokens - _this_attempt)++ def _continuation_would_be_served(+ candidate_messages,+ continue_flag: bool,+ reasoning_kw = _UNSET,+ ) -> bool:+ """Whether the retry's own prompt still fits, now that the partial is in it.++ The first pass reached `finish_reason: length` by consuming the physical+ context, so appending everything it produced makes the next prompt roughly+ context-sized. Reopening the stream without asking gets it rejected before a+ single extra token arrives, which is worse than stopping: the user keeps the+ partial either way, and one of the two paths also shows an error.++ A count that cannot be taken is not a refusal. Failing open here restores the+ behaviour this continuation had before the check, which is the safe side.+ """+ if not self._effective_context_length:+ return True+ try:+ _tokens = self.count_chat_tokens(+ candidate_messages,+ None,+ None,+ strict = True,+ chat_template_kwargs = (+ stream_payload.get("chat_template_kwargs")+ if reasoning_kw is _UNSET+ else reasoning_kw+ ),+ continue_final_message = continue_flag,+ )+ except Exception:+ logger.debug("final continuation: prompt count failed", exc_info = True)+ return True+ # NOT `turn_is_servable`: that charges `_RESULT_NOTICE_RESERVE`, the room a+ # truncated TOOL RESULT needs for its notice, and a continuation has no tool+ # result. Borrowing it here refuses continuations that would have been served+ # and produced text, which is the working behaviour this check exists beside,+ # not instead of. llama-server admits a prompt on size alone, so that is the+ # line, minus only enough room to answer in.+ _floor = _reply_floor(self._effective_context_length)+ if _tokens + _floor <= self._effective_context_length:+ return True+ logger.info(+ "Final continuation would not be served (%d tokens of a %d-token "+ "window); keeping the partial answer instead",+ _tokens,+ self._effective_context_length,+ )+ return False++ # Where the visible answer stood when THIS attempt began. `has_content_tokens`+ # and `_last_emitted` are cumulative across continuations by design, so without a+ # per-attempt mark a continuation that emitted nothing but reasoning still looked+ # like another truncated visible answer: it replayed an empty suffix with thinking+ # left on instead of taking the reasoning-only recovery.+ _attempt_started_at = ""+ while True:+ try:+ with self._open_chat_stream_with_respawn_retry(+ stream_payload,cancel_event,- first_token_deadline = first_token_deadline,+ on_respawn = _refit_final_after_respawn,+ ) as (+ response,+ first_token_deadline,):- buffer += raw_chunk- while "\n" in buffer:- line, buffer = buffer.split("\n", 1)- line = line.strip()-- if not line:- continue- if line == "data: [DONE]":- if in_thinking:- if (- _final_reasoning_started_at is not None- and not _final_reasoning_summary_emitted- ):- _final_reasoning_summary_emitted = True- yield _reasoning_summary_event(_final_reasoning_started_at)- if has_content_tokens:- cumulative += "</think>"- _prov_entry = None- yield {- "type": "content",- "text": _strip_tool_markup(cumulative, final = True),- }- else:- cumulative = _finalize_reasoning_only_cumulative(- cumulative,- reasoning_text,- _metadata_finish_reason,- promote_reasoning_only,- )- _prov_entry = None- yield {"type": "content", "text": cumulative}- _stream_done = True- break # exit inner while- if not line.startswith("data: "):- continue-- try:- chunk_data = json.loads(line[6:])-- _report_live_llama_timings(perf_callback, chunk_data)- # Capture server timings/usage from final chunks.- _chunk_timings = chunk_data.get("timings")- if _chunk_timings:- _metadata_timings = _chunk_timings- _chunk_usage = chunk_data.get("usage")- if _chunk_usage:- _metadata_usage = _chunk_usage- # See the note on the first stream loop.- _stream_error = stream_error_from_chunk(chunk_data)- if _stream_error is not None:- raise _stream_error- choices = chunk_data.get("choices", [])- if choices:- delta = choices[0].get("delta", {})- _fr = choices[0].get("finish_reason")- if _fr:- _metadata_finish_reason = _fr-- reasoning = delta.get("reasoning_content", "")- if reasoning:- if _final_reasoning_started_at is None:- _final_reasoning_started_at = time.monotonic()- reasoning_text += reasoning- if not in_thinking:- if reasoning_provenance is not None and not cumulative:- reasoning_provenance["wrapped"] = (- reasoning_provenance.get("wrapped", 0) + 1- )- _prov_entry = {"len": 0}- reasoning_provenance.setdefault("wraps", []).append(- _prov_entry- )- cumulative += "<think>"- in_thinking = True- cumulative += reasoning- if _prov_entry is not None:- _prov_entry["len"] += len(reasoning)- yield {"type": "content", "text": cumulative}+ for truncation in _final_respawn_truncations:+ yield {"type": "context_truncated", **truncation}+ buffer = ""+ for raw_chunk in self._iter_text_cancellable(+ response,+ cancel_event,+ first_token_deadline = first_token_deadline,+ ):+ buffer += raw_chunk+ while "\n" in buffer:+ line, buffer = buffer.split("\n", 1)+ line = line.strip()- token = delta.get("content", "")- if token:+ if not line:+ continue+ if line == "data: [DONE]":+ if in_thinking:if (_final_reasoning_started_at is not Noneand not _final_reasoning_summary_emitted):_final_reasoning_summary_emitted = Trueyield _reasoning_summary_event(_final_reasoning_started_at)- has_content_tokens = True- if in_thinking:+ if has_content_tokens:cumulative += "</think>"+ _prov_entry = None+ yield {+ "type": "content",+ "text": _strip_tool_markup(cumulative, final = True),+ }+ else:+ cumulative = _finalize_reasoning_only_cumulative(+ cumulative,+ reasoning_text,+ _metadata_finish_reason,+ promote_reasoning_only,+ )+ # The block is closed now, so the flag must say+ # so. Left set, the thinking-off retry below+ # closes it a SECOND time on its first content+ # token: `<think>...</think></think>answer`, and+ # the route parses only the leading pair, so the+ # stray tag is shown to the user as answer text.in_thinking = False_prov_entry = None- cumulative += token- cleaned = (- _final_answer_stripper.strip(cumulative)- if auto_heal_tool_calls- else cumulative- )- # Emit only when cleaned text grows (monotonic).- if len(cleaned) > len(_last_emitted):- _last_emitted = cleaned- yield {"type": "content", "text": cleaned}- except json.JSONDecodeError:- logger.debug(f"Skipping malformed SSE line: {line[:100]}")- if _stream_done:- break # exit outer for- _meta = _build_metadata_event(- _metadata_usage, _metadata_timings, _metadata_finish_reason- )- if _meta is not None:- yield _meta+ yield {"type": "content", "text": cumulative}+ _stream_done = True+ break # exit inner while+ if not line.startswith("data: "):+ continue- except _LlamaStreamCancelled:- return- except httpx.ConnectError:- raise RuntimeError("Lost connection to llama-server")- except Exception as e:- if cancel_event is not None and cancel_event.is_set():+ try:+ chunk_data = json.loads(line[6:])++ _report_live_llama_timings(perf_callback, chunk_data)+ # Capture server timings/usage from final chunks.+ _chunk_timings = chunk_data.get("timings")+ if _chunk_timings:+ _metadata_timings = _chunk_timings+ _chunk_usage = chunk_data.get("usage")+ if _chunk_usage:+ _metadata_usage = _chunk_usage+ # See the note on the first stream loop.+ _stream_error = stream_error_from_chunk(chunk_data)+ if _stream_error is not None:+ raise _stream_error+ choices = chunk_data.get("choices", [])+ if choices:+ delta = choices[0].get("delta", {})+ _fr = choices[0].get("finish_reason")+ if _fr:+ _metadata_finish_reason = _fr++ reasoning = delta.get("reasoning_content", "")+ if reasoning:+ if _final_reasoning_started_at is None:+ _final_reasoning_started_at = time.monotonic()+ reasoning_text += reasoning+ if not in_thinking:+ if reasoning_provenance is not None and not cumulative:+ reasoning_provenance["wrapped"] = (+ reasoning_provenance.get("wrapped", 0) + 1+ )+ _prov_entry = {"len": 0}+ reasoning_provenance.setdefault("wraps", []).append(+ _prov_entry+ )+ cumulative += "<think>"+ in_thinking = True+ cumulative += reasoning+ if _prov_entry is not None:+ _prov_entry["len"] += len(reasoning)+ yield {"type": "content", "text": cumulative}++ token = delta.get("content", "")+ if token:+ if (+ _final_reasoning_started_at is not None+ and not _final_reasoning_summary_emitted+ ):+ _final_reasoning_summary_emitted = True+ yield _reasoning_summary_event(+ _final_reasoning_started_at+ )+ has_content_tokens = True+ if in_thinking:+ cumulative += "</think>"+ in_thinking = False+ _prov_entry = None+ cumulative += token+ cleaned = (+ _final_answer_stripper.strip(cumulative)+ if auto_heal_tool_calls+ else cumulative+ )+ # Emit only when cleaned text grows (monotonic).+ if len(cleaned) > len(_last_emitted):+ _last_emitted = cleaned+ yield {"type": "content", "text": cleaned}+ except json.JSONDecodeError:+ logger.debug(f"Skipping malformed SSE line: {line[:100]}")+ if _stream_done:+ break # exit outer for+ # Cut off mid-answer with real text on screen: resume it rather than+ # stop here. Same rule as the in-loop path -- the partial goes back to+ # be EXTENDED, thinking is left alone because it was not the problem,+ # and an answer that is mostly an echo of itself is left as it is.+ _shown_this_attempt = _last_emitted[len(_attempt_started_at) :]+ if (+ _metadata_finish_reason == "length"+ and has_content_tokens+ and _shown_this_attempt.strip()+ and _final_length_continuations < _MAX_LENGTH_CONTINUATIONS+ and not is_repetition_dominated(_last_emitted)+ ):+ from core.inference.chat_template_helpers import ( # noqa: PLC0415+ append_assistant_turn as _append_assistant_turn,+ )++ _final_length_continuations += 1+ logger.info(+ "Final answer cut off at %d chars; continuing %d/%d",+ len(_last_emitted),+ _final_length_continuations,+ _MAX_LENGTH_CONTINUATIONS,+ )+ # Built as a CANDIDATE, committed only once another stream is+ # certain to run. Mutating the payload first and folding the usage+ # in first meant a refused continuation had already spent both:+ # `_build_metadata_event` adds the same usage again, so the reply+ # reported roughly double the tokens it really cost.+ #+ # Only what is NEW since the last replay goes back. `_last_emitted`+ # is cumulative across attempts, and the helper PREPENDS the+ # trailing assistant text, so handing it the cumulative value a+ # second time yields "fragment1 + fragment1 + continuation1".+ _candidate_messages = list(stream_payload["messages"])+ _append_assistant_turn(+ _candidate_messages,+ {+ "role": "assistant",+ "content": _last_emitted[_final_replayed_chars:],+ },+ continue_final_message = True,+ )+ # The replay is text the MODEL just produced, and the first payload+ # neutralized everything it carried. Sent raw, a template delimiter+ # inside it -- printed code being the obvious case -- is read back+ # as chat structure. Neutralized before it is counted as well, so+ # the admission number describes the payload actually sent.+ _candidate_messages = neutralize_control_markup_in_messages(+ _candidate_messages, None, self.markup_profile+ )+ _next_cap = _remaining_output_budget()+ _served = _next_cap != 0 and _continuation_would_be_served(+ _candidate_messages, True+ )+ if _next_cap != 0 and not _served:+ # Same reason as the in-loop path: this is the last decision+ # of the turn, so a candidate one eviction short of servable+ # gets that eviction rather than being abandoned.+ _evicted_f = _evict_until_it_fits(+ _candidate_messages,+ None,+ stream_payload.get("chat_template_kwargs"),+ True,+ )+ if _evicted_f is not None and _continuation_would_be_served(+ _evicted_f, True+ ):+ _candidate_messages = _evicted_f+ _served = True+ if _served:+ stream_payload["messages"] = _candidate_messages+ _final_replayed_chars = len(_last_emitted)+ stream_payload["continue_final_message"] = True+ if _next_cap is not None:+ stream_payload["max_tokens"] = _next_cap+ # Folded in only now, else the reported usage counts the last+ # fragment alone.+ _fu_f = (+ _backfill_usage_from_timings(_metadata_usage, _metadata_timings)+ or {}+ )+ _accumulated_completion_tokens += _fu_f.get("completion_tokens", 0)+ _it_f = _metadata_timings or {}+ _accumulated_predicted_ms += _it_f.get("predicted_ms", 0)+ _accumulated_predicted_n += _it_f.get("predicted_n", 0)+ _stream_done = False+ _metadata_finish_reason = None+ # Per attempt, like the finish reason. This attempt's usage has+ # just been folded into the accumulator, so leaving it here lets+ # a next attempt that reports none be charged these numbers a+ # second time -- and the cap read off that total can then look+ # spent when it is not.+ _metadata_usage = None+ _metadata_timings = None+ # The next attempt starts from what is on screen now, so a+ # continuation that shows nothing new is judged on its own.+ _attempt_started_at = _last_emitted+ _continue_final = True+ # NO blank status here, unlike the in-loop re-prompt. An empty+ # status is the route's iteration boundary and resets its+ # `prev_text` cursor, but this pass keeps `cumulative` across+ # attempts by design: the retry's first content event carries+ # the whole prefix again, and diffed from a cursor that has+ # just been cleared the client is sent the partial twice.+ yield {+ "type": "status",+ "text": _CONTINUE_TRUNCATED_ANSWER_STATUS,+ }+ else:+ _meta = _build_metadata_event(+ _metadata_usage, _metadata_timings, _metadata_finish_reason+ )+ if _meta is not None:+ yield _meta+ elif (+ _metadata_finish_reason == "length"+ and not _shown_this_attempt.strip()+ and reasoning_text.strip()+ ):+ # The other half of the same failure, and the one the in-loop+ # continuation cannot reach: this pass runs AFTER the loop has+ # broken, so a turn that spends its last tool call here and then+ # thinks until the window is gone renders as an empty message.+ # `force_final_answer` from a one-shot tool lands here too.+ if _final_length_continuations < _MAX_LENGTH_CONTINUATIONS:+ from core.inference.chat_template_helpers import ( # noqa: PLC0415+ append_assistant_turn as _append_assistant_turn,+ )++ _final_length_continuations += 1+ logger.info(+ "Final pass ended inside its reasoning (%d chars); "+ "continuing %d/%d with thinking off",+ len(reasoning_text),+ _final_length_continuations,+ _MAX_LENGTH_CONTINUATIONS,+ )+ # Candidate first, committed only if it will actually run.+ # See the answer continuation above: spending the payload and+ # the usage before the decision double-counted both.+ _candidate_r = list(stream_payload["messages"])+ _append_assistant_turn(+ _candidate_r,+ {+ "role": "assistant",+ "content": _unfinished_thought_progress(reasoning_text),+ },+ continue_final_message = bool(+ stream_payload.get("continue_final_message")+ ),+ )+ _candidate_r.append(+ {"role": "user", "content": _continue_after_length_message()}+ )+ # Same reason as the answer continuation above: the progress+ # note quotes the model's own reasoning.+ _candidate_r = neutralize_control_markup_in_messages(+ _candidate_r, None, self.markup_profile+ )+ # The retry runs with thinking OFF, so it has to be ADMITTED+ # with thinking off too. Counting the candidate under the+ # original thinking-on kwargs prices a different rendered+ # prompt from the one about to be sent, which refuses a retry+ # that would have fit or admits one llama-server then rejects.+ _off_kw = self._request_reasoning_kwargs(False, None, preserve_thinking)+ _next_cap_r = _remaining_output_budget()+ _served_r = _next_cap_r != 0 and _continuation_would_be_served(+ _candidate_r, False, _off_kw+ )+ if _next_cap_r != 0 and not _served_r:+ _evicted_r = _evict_until_it_fits(_candidate_r, None, _off_kw)+ if _evicted_r is not None and _continuation_would_be_served(+ _evicted_r, False, _off_kw+ ):+ _candidate_r = _evicted_r+ _served_r = True+ if _served_r:+ stream_payload["messages"] = _candidate_r+ # The retry ends on a USER turn, so the flag from any+ # earlier answer continuation no longer describes it.+ stream_payload.pop("continue_final_message", None)+ if _next_cap_r is not None:+ stream_payload["max_tokens"] = _next_cap_r+ if _off_kw is not None:+ stream_payload["chat_template_kwargs"] = _off_kw+ else:+ stream_payload.pop("chat_template_kwargs", None)+ _fu_r = (+ _backfill_usage_from_timings(_metadata_usage, _metadata_timings)+ or {}+ )+ _accumulated_completion_tokens += _fu_r.get("completion_tokens", 0)+ _it_r = _metadata_timings or {}+ _accumulated_predicted_ms += _it_r.get("predicted_ms", 0)+ _accumulated_predicted_n += _it_r.get("predicted_n", 0)+ _stream_done = False+ _metadata_finish_reason = None+ # Per attempt, like the finish reason. This attempt's usage has+ # just been folded into the accumulator, so leaving it here lets+ # a next attempt that reports none be charged these numbers a+ # second time -- and the cap read off that total can then look+ # spent when it is not.+ _metadata_usage = None+ _metadata_timings = None+ # The next attempt starts from what is on screen now, so a+ # continuation that shows nothing new is judged on its own.+ _attempt_started_at = _last_emitted+ _continue_final = True+ # Same reason as the answer continuation above: clearing+ # the route's cursor here replays what has already been+ # streamed, reasoning included.+ yield {+ "type": "status",+ "text": _CONTINUE_AFTER_LENGTH_STATUS,+ }+ else:+ yield {"type": "status", "text": ""}+ # Content events on this stream are CUMULATIVE, so an+ # explanation sent on its own replaces whatever is on+ # screen. Once a previous attempt has shown an answer,+ # keeping it is worth more than the advice: the partial+ # already offers Continue.+ if not _last_emitted.strip():+ yield {+ "type": "content",+ # Same distinction the in-loop give-up makes. A+ # spent output cap is not the context window, and+ # this text reaches the client as ordinary+ # content, so naming the wrong lever here is the+ # last word the user gets.+ "text": (+ _reasoning_cap_spent_message(max_tokens)+ if _next_cap_r == 0+ else _thinking_exhausted_message(+ self._effective_context_length+ )+ ),+ }+ _meta = _build_metadata_event(+ _metadata_usage,+ _metadata_timings,+ _metadata_finish_reason,+ )+ if _meta is not None:+ yield _meta+ else:+ # Allowance spent and still nothing on screen. Saying so is+ # the point: an empty message gives the user nothing to act on.+ #+ # Which allowance, re-read here rather than assumed: the last+ # permitted attempt may itself have finished off an explicit+ # Max Tokens, and this branch is reached with no decision+ # about the cap ever having been made.+ _cap_left_g = _remaining_output_budget()+ yield {"type": "status", "text": ""}+ # As above: cumulative content, so this must not overwrite an+ # answer an earlier attempt already put on screen.+ if not _last_emitted.strip():+ yield {+ "type": "content",+ "text": (+ _reasoning_cap_spent_message(max_tokens)+ if _cap_left_g == 0+ else _thinking_exhausted_message(+ self._effective_context_length+ )+ ),+ }+ _meta = _build_metadata_event(+ _metadata_usage, _metadata_timings, _metadata_finish_reason+ )+ if _meta is not None:+ yield _meta+ else:+ _meta = _build_metadata_event(+ _metadata_usage, _metadata_timings, _metadata_finish_reason+ )+ if _meta is not None:+ yield _meta++ if _continue_final:+ _continue_final = False+ continue+ break++ except _LlamaStreamCancelled:return- raise+ except httpx.ConnectError:+ raise RuntimeError("Lost connection to llama-server")+ except Exception as e:+ if cancel_event is not None and cancel_event.is_set():+ return+ raise# ── Prompt token counting ──────────────────────────────────diff --git a/studio/backend/core/inference/repetition_guard.py b/studio/backend/core/inference/repetition_guard.pynew file mode 100644index 00000000000..12a9ae4ccd4--- /dev/null+++ b/studio/backend/core/inference/repetition_guard.py@@ -0,0 +1,106 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Is this truncated fragment worth continuing, or is the model just echoing itself?++Only asked on the length-continuation path. A turn cut off mid-answer is normally resumed+by handing the partial back and asking for the rest, but a model stuck in a repetition loop+can spend an entire window echoing one fragment, and continuing THAT stitches the echo into+the final answer instead of finishing it. The nudge has to be withheld before it is sent,+not regretted afterwards.++The approach and the thresholds follow NousResearch/hermes-agent's `agent/repetition_guard.py`,+written after an incident where a single turn produced a 60,698-char response delivered as+31 messages. Deliberately conservative in the same way: only LONG verbatim repeats covering+a majority of the fragment trip it, so a sentence cut mid-word, a repeated heading, or code+with similar-looking lines are all still continued.+"""++from __future__ import annotations++import math++# Below this, a fragment is too short to judge. A sentence cut mid-word can trivially+# repeat a few tokens and is legitimately continued.+MIN_FRAGMENT_LENGTH = 400++# Length of the exact-repeat window. A verbatim repeat this long is well beyond ordinary+# reuse of phrasing, citations, headings or boilerplate.+_REPEAT_WINDOW = 60++# A window repeating at least this many times is a signal even in a short fragment.+_MIN_REPEAT_COUNT = 5++# The share of the fragment repeated windows must cover before it counts as dominated.+_DOMINANCE_RATIO = 0.5++# Ceiling on distinct windows held while scanning. Every fragment a context window can+# actually produce stays well under this, so the judgement is unchanged in practice; it+# exists so the scan cannot grow with an arbitrarily long input.+_MAX_TRACKED_WINDOWS = 100_000+++def is_repetition_dominated(text: str) -> bool:+ """Whether verbatim repeats account for the majority of ``text``.++ Fails open: anything it cannot confidently judge is reported as fine to continue, so a+ false negative costs one wasted continuation while a false positive would refuse to+ finish an answer that was merely repetitive in an ordinary way.+ """+ if not isinstance(text, str):+ return False+ length = len(text)+ if length < MIN_FRAGMENT_LENGTH:+ return False+ if _line_repetition_dominated(text, length):+ return True+ # Sliding exact-repeat windows, for echoes that do not align to line boundaries.+ needed = max(_MIN_REPEAT_COUNT, math.ceil(length * _DOMINANCE_RATIO / _REPEAT_WINDOW))+ # Keyed by HASH, not by the window itself. Retaining the 60-character slices meant one+ # entry per starting offset, so an 800,000-character fragment held roughly 180 MB of+ # substrings alive purely to decide whether to send one more continuation.+ counts: dict[int, int] = {}+ # Occurrences must not overlap, or a single run of one character counts as many. A+ # 64-character rule inside a 400-character answer yields five overlapping 60-character+ # windows and tripped the threshold at 16 percent coverage, abandoning a valid answer.+ covered_to: dict[int, int] = {}+ # Where each hash was first seen, so a hash collision cannot be counted as a repeat.+ first_at: dict[int, int] = {}+ for index in range(length - _REPEAT_WINDOW + 1):+ key = hash(text[index : index + _REPEAT_WINDOW])+ if index < covered_to.get(key, 0):+ continue+ first = first_at.get(key)+ if first is None:+ # Bounded even for a fragment far larger than any window can hold. Past the+ # cap, known windows keep counting and new ones are ignored, which can only+ # fail open -- the direction this guard already errs in.+ if len(first_at) >= _MAX_TRACKED_WINDOWS:+ continue+ first_at[key] = index+ elif text[first : first + _REPEAT_WINDOW] != text[index : index + _REPEAT_WINDOW]:+ # Two different windows, one hash. Not a repeat.+ continue+ seen = counts.get(key, 0) + 1+ if seen >= needed:+ return True+ counts[key] = seen+ covered_to[key] = index + _REPEAT_WINDOW+ return False+++def _line_repetition_dominated(text: str, length: int) -> bool:+ """The common shape: one line repeated until it covers half the fragment.++ Checked first because it is cheap and allocates nothing, unlike the window pass.+ """+ counts: dict[str, int] = {}+ for line in text.splitlines():+ normalised = line.strip()+ if not normalised:+ continue+ counts[normalised] = counts.get(normalised, 0) + 1+ return any(+ seen >= _MIN_REPEAT_COUNT and seen * len(line) >= length * _DOMINANCE_RATIO+ for line, seen in counts.items()+ )diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.pyindex a00b1e1891f..45986cf72ab 100644--- a/studio/backend/core/inference/tool_call_parser.py+++ b/studio/backend/core/inference/tool_call_parser.py@@ -272,6 +272,101 @@ def reprompt_to_act_message(tool_hint: str) -> str:)+# How much of the unfinished thought is carried into the continuation. The point is to+# resume, not to replay: the whole thought is what filled the window, so putting it back+# reproduces the same ending. The tail is the part still being worked on.+_LENGTH_PROGRESS_TAIL_CHARS = 600+++def unfinished_thought_progress(reasoning: str) -> str:+ """The short note that stands in for a thought the window cut off."""+ tail = reasoning.strip()[-_LENGTH_PROGRESS_TAIL_CHARS:].lstrip()+ return f"Where I had got to:\n{tail}"+++def starved_result_message(tool_name: str, result: str) -> str:+ """Appended when the window priced this call's result at nothing before it ran.++ Said on the FIRST such call rather than after a run of identical ones: the pricing is+ known before the tool executes, so waiting for the repeat guard to notice costs several+ calls to learn something already computed.+ """+ return (+ f"{result}\n\n"+ f"[No room in the window for this result, so {tool_name} returned nothing usable. "+ "Re-reading will not help. Continue from what you have, and deliver the work in "+ "parts if it will not fit at once.]"+ )+++def repeated_result_message(tool_name: str, times: int, last_result: str) -> str:+ """Appended to a result the tool has now returned unchanged several times.++ The last result is kept rather than replaced: it may be the truncation notice that+ caused the repeats, and dropping it would leave the model with less than it had.+ """+ return (+ f"{last_result}\n\n"+ f"[{tool_name} returned exactly this {times} times; it will not change. Continue "+ "from what you have, in parts if needed, and finish the task.]"+ )+++def thinking_exhausted_message(context_length: Optional[int] = None) -> str:+ """Shown when even a thinking-off retry produced nothing visible.++ Names the lever the user actually has. Hermes surfaces the same advice+ (NousResearch/hermes-agent, `_thinking_exhausted`) and Codex's guidance for the+ identical symptom is likewise to lower reasoning effort, because no amount of+ retrying fits a thought that did not fit the first time.+ """+ # Built by substitution rather than `.format` on a pre-spaced fragment, which produced+ # "spent its whole reply of the 4096-token window on reasoning".+ window = f"{context_length}-token " if context_length else ""+ return (+ f"The model spent the whole of its {window}window on reasoning and had none "+ "left for an answer, twice in a row.\n\n"+ "To get past this:\n"+ "- Lower the reasoning effort, or turn thinking off\n"+ "- Or raise the context length, so a thought and an answer both fit\n"+ "- Or ask for a smaller piece of the task at a time"+ )+++def reasoning_cap_spent_message(max_tokens: Optional[int] = None) -> str:+ """Shown when a reasoning-only turn was stopped by the CALLER's own Max Tokens.++ A different wall from the one `thinking_exhausted_message` describes, and the levers+ are opposite: the window has room, the allowance does not, and only one attempt ran.+ Blaming the context window there sends the user to raise the one setting that was+ never the constraint, and this text reaches the client as ordinary content, so the+ frontend's cap-aware error cannot correct it afterwards.+ """+ allowance = f" of {max_tokens} tokens" if max_tokens else ""+ return (+ f"The model used its whole output allowance{allowance} on reasoning and had none "+ "left for an answer.\n\n"+ "To get past this:\n"+ "- Raise Max Tokens, so a thought and an answer both fit\n"+ "- Or lower the reasoning effort, or turn thinking off\n"+ "- Or ask for a smaller piece of the task at a time"+ )+++def continue_after_length_message() -> str:+ """The user message appended when a turn ended inside its own reasoning.++ The instruction is to ACT, not to think more carefully: the previous turn ended with+ nothing to show because thinking consumed the whole window, so asking for more+ deliberation is asking for the same ending a second time.+ """+ return (+ "You ran out of room while thinking, so nothing was produced. Stop thinking and "+ "act: call a tool or answer now. If it will not all fit, deliver the first part "+ "and continue after."+ )++# Qwen / Hermes ``<tool_call>{json}``._TC_JSON_START_RE = re.compile(r"<tool_call>\s*\{")# Qwen3.5 ``<function=name>`` and the attribute form ``<function name="name">``diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.pyindex b1a7b233ea8..5800da99880 100644--- a/studio/backend/core/inference/tool_loop_controller.py+++ b/studio/backend/core/inference/tool_loop_controller.py@@ -24,7 +24,150 @@ _CANONICAL_HEAL_ARG = {"python": "code","terminal": "command","render_html": "code",+ # Not derivable: web_search declares no REQUIRED argument, because a call carrying+ # only `url` fetches that page without searching. A bare string is still a query,+ # which is what the old catch-all default got right for this tool and only this one.+ "web_search": "query",}++# Where a bare string lands when the tool it was sent to has no argument that could hold+# it. Read by `execute_tool`, which answers with what actually went wrong instead of+# letting the tool report a missing key it was never given.+UNPARSED_ARGUMENTS_KEY = "__unsloth_unparsed_arguments__"+++# Anything that ends a JSON token. A tail free of all of them never finished arriving.+_JSON_STRUCTURAL = frozenset(',:{}[]" \t\n\r')+++def _looks_like_broken_json(raw: str) -> bool:+ """Whether this text was MEANT to be a JSON object and stopped before finishing.++ Opening with a bracket is necessary but not sufficient, and treating it as sufficient+ was wrong in both directions: `{not json at all` is a bare string a model sent for a+ single-argument tool, and healing it into that argument is the right answer, while+ `{"code":"html = ...` is a call cut off mid-stream that must not become the program.++ What separates them is WHERE the decode fails. A call that was cut off runs out of+ input -- either inside a string that never closes, or at the very end of what arrived.+ Text that merely opens with a brace fails earlier, with input still to go.+ """+ text = raw.strip()+ if not text.startswith(("{", "[")):+ return False+ try:+ json.loads(text)+ except json.JSONDecodeError as error:+ if error.msg.startswith("Unterminated string") or error.pos >= len(text):+ return True+ # A value cut mid-token reports at the token's START, not at the end of input, so+ # the two tests above miss `{"flag":tru` (Expecting value) and `{"n":1e`+ # (Expecting ',' delimiter). What they share is that everything from the failure+ # to the end is one unfinished token: no delimiter, no quote, no space.+ #+ # Excluded: a bad PROPERTY NAME. After `{` a bare word is malformed rather than+ # cut off, which is what keeps `{oops` and `{not json at all` healable.+ if error.msg.startswith("Expecting property name"):+ return False+ # Excluded for the opposite reason: a COMPLETE document with something after it.+ # `{"a": 1} trailing` decodes fully and then finds junk, so nothing was lost.+ if error.msg.startswith("Extra data"):+ return False+ remainder = text[error.pos :]+ return bool(remainder) and not any(ch in _JSON_STRUCTURAL for ch in remainder)+ return False+++def _single_string_argument(function: Mapping) -> "str | None":+ """That function's one required string argument, or None when it has anything else."""+ parameters = function.get("parameters")+ if not isinstance(parameters, Mapping):+ return None+ properties = parameters.get("properties")+ required = parameters.get("required")+ if not isinstance(properties, Mapping) or not isinstance(required, list):+ return None+ required_names = [item for item in required if isinstance(item, str)]+ if len(required_names) != 1:+ return None+ key = required_names[0]+ schema = properties.get(key)+ if not isinstance(schema, Mapping):+ return None+ kind = schema.get("type")+ if kind == "string" or (isinstance(kind, list) and "string" in kind):+ return key+ return None+++def _healable_keys_from_schemas() -> "dict[str, str]":+ """Built-in tool -> its single required string argument, for the tools that have one.++ Derived from the schemas rather than hand-listed. The map above was hand-kept, so it+ silently went stale the moment a tool was added: `edit_file` landed with three+ required arguments and no entry, and every unparseable call to it was healed into a+ "query" key that only exists on the search tools. A schema-derived answer cannot rot+ the same way -- a new tool is either single-string and healable, or it is not and says+ so.+ """+ try:+ from core.inference.tools import ALL_TOOLS # noqa: PLC0415 -- cycle at import time+ except Exception: # noqa: BLE001 -- healing must never break a chat+ return {}+ return _healable_keys_from(ALL_TOOLS)+++def _healable_keys_from(tools) -> "dict[str, str]":+ keys: dict[str, str] = {}+ for tool in tools or []:+ function = tool.get("function") if isinstance(tool, Mapping) else None+ if not isinstance(function, Mapping):+ continue+ name = str(function.get("name") or "")+ if not name:+ continue+ key = _single_string_argument(function)+ if key is not None:+ keys[name] = key+ return keys+++_HEAL_ARG_CACHE: "dict[str, str] | None" = None+++def _heal_arg_key(tool_name: str, tool_schemas = None) -> "str | None":+ """The argument a bare string should become, or None when there isn't one.++ ``tool_schemas`` is the REQUEST's tool array. MCP tools are discovered at runtime and+ so are absent from `ALL_TOOLS`; without them an MCP tool with one required string+ argument lost the auto-healing every other single-string tool has, and a bare string+ reached `execute_tool` as the unparsed sentinel instead.+ """+ global _HEAL_ARG_CACHE+ if tool_name in _CANONICAL_HEAL_ARG:+ return _CANONICAL_HEAL_ARG[tool_name]+ if _HEAL_ARG_CACHE is None:+ _HEAL_ARG_CACHE = _healable_keys_from_schemas()+ key = _HEAL_ARG_CACHE.get(tool_name)+ if key is not None or not tool_schemas:+ return key+ # Not cached: the request's tools belong to the request, and caching them by name+ # would let one chat's MCP server decide another chat's healing.+ return _healable_keys_from(tool_schemas).get(tool_name)+++def _unreadable_arguments_summary(fragment: str) -> dict[str, str]:+ """What stands in for a call whose arguments never finished arriving.++ Small and parseable on purpose. The replayed `arguments` of an assistant tool call is+ read as JSON by the server rendering the template, so anything that does not parse+ fails the whole request rather than just that call.+ """+ return {+ "error": (f"arguments were cut off after {len(fragment)} characters and could not be read")+ }++_ONE_SHOT_TOOLS = frozenset({"render_html"})NoopReason = Literal["duplicate", "disabled", "forced_mismatch", "render_html_repeat"]@@ -67,12 +210,30 @@ class ToolCallDecision:return Nonereturn self.action+ @property+ def unparsed_fragment(self) -> "str | None":+ """The raw text of a call whose JSON could not be read, if this is one.++ `UNPARSED_ARGUMENTS_KEY` is plumbing between the coercion and `execute_tool`, and+ it escaped into both places a caller looks: the tool card showed the user+ `{"__unsloth_unparsed_arguments__": ...}`, and the replayed assistant turn taught+ the model a key no tool declares. Both boundaries go through here instead.+ """+ if isinstance(self.arguments, Mapping) and UNPARSED_ARGUMENTS_KEY in self.arguments:+ return str(self.arguments.get(UNPARSED_ARGUMENTS_KEY) or "")+ return None+def tool_start_payload(self) -> dict[str, Any]:"""Build the payload fields for a real tool_start event."""+ fragment = self.unparsed_fragment+ # `raw` is the shape this module already uses for arguments it could not read into+ # a schema, so the card shows the model's own text under a name that means+ # something rather than an internal sentinel.+ arguments = {"raw": fragment} if fragment is not None else self.argumentsreturn {"tool_name": self.tool_name,"tool_call_id": self.tool_call_id,- "arguments": self.arguments,+ "arguments": arguments,"provenance": self.provenance,}@@ -82,11 +243,20 @@ class ToolCallDecision:def as_assistant_tool_call(self) -> dict[str, Any]:"""Return an OpenAI-style tool_call with normalized arguments."""+ fragment = self.unparsed_fragmenttool_call: dict[str, Any] = {"type": "function","function": {"name": self.tool_name,- "arguments": json.dumps(+ # Whatever goes here MUST parse as JSON. llama-server parses it while+ # rendering the template and answers 500 otherwise, which is what replaying+ # the fragment verbatim caused: it is unparseable by definition, that being+ # why it is here. So the replay is a short valid object that says the call+ # was cut off, and the tool result carries the detail. The fragment itself+ # is not worth resending -- it is the content that overflowed the window.+ "arguments": json.dumps(_unreadable_arguments_summary(fragment))+ if fragment is not None+ else json.dumps(self.arguments,ensure_ascii = False,sort_keys = True,@@ -180,6 +350,7 @@ def coerce_tool_arguments(*,heal: bool,tool_name: str = "",+ tool_schemas = None,) -> CoercedArguments:"""Normalize model-emitted ``function.arguments`` to a dictionary."""if isinstance(raw_args, Mapping):@@ -192,8 +363,28 @@ def coerce_tool_arguments(except (json.JSONDecodeError, ValueError):passif heal:- key = _CANONICAL_HEAL_ARG.get(tool_name, "query")- return CoercedArguments({key: raw_args}, True)+ # Healing exists for a model that sends its ONE argument as a bare string+ # instead of an object. Text that opens like JSON and fails to parse is not+ # that -- it is a broken object, usually one cut off mid-stream, and wrapping+ # it whole becomes the argument's value. Observed on `python`, which has a+ # single `code` argument and so was healable: a truncated call arrived as+ # `{"code":"html = ...`, the entire fragment was passed as the PROGRAM, and the+ # model read its own file back as `{"code":"html = ...` and spent the rest of+ # the turn convinced the sandbox had mangled it. Same defect `edit_file` had;+ # having a single string argument only hid it.+ key = (+ None+ if _looks_like_broken_json(raw_args)+ else _heal_arg_key(tool_name, tool_schemas)+ )+ if key is not None:+ return CoercedArguments({key: raw_args}, True)+ # No single argument this text could be. Inventing one used to default to+ # "query", which edit_file -- three required arguments, none of them a+ # query -- then reported as "'old_string' and 'new_string' must both be+ # strings": a type error blaming the model for a key it never sent, on a+ # call whose real problem was that its JSON never finished arriving.+ return CoercedArguments({UNPARSED_ARGUMENTS_KEY: raw_args}, False)return CoercedArguments({"raw": raw_args}, False)return CoercedArguments({}, False)@@ -502,6 +693,7 @@ class ToolLoopController:function.get("arguments", {}),heal = self._auto_heal_tool_calls,tool_name = tool_name,+ tool_schemas = self._tools,)key = canonical_tool_call_key(tool_name, coerced.arguments)mcp = mcp_display_parts(tool_name)diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 7027be2ad6a..9d9a327fc51 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -9374,55 +9374,233 @@ def _edit_file_create(return f"Created {name} ({new.count(chr(10)) + 1 if new else 0} lines)"+# Each entry costs a full `count` scan of the file plus a search pass, and the file may be+# up to 16 MiB, so the work is entries x size. Unbounded, a model-generated batch of a few+# thousand one-line edits turns a single call into gigabytes of repeated scanning and holds+# the tool worker for minutes. High enough that no honest refactor hits it, low enough that+# the worst case stays bounded.+_MAX_EDITS_PER_CALL = 100++# And a bound on the matches ONE replace_all may expand into. The entry limit above caps+# how many patterns are searched, not how many places any of them hits, so a single+# pathological entry can still swamp the worker on its own.+_MAX_MATCH_SPANS = 10_000+++def _edit_file_parse_edits(raw) -> "tuple[list[tuple[str, str, bool]], str]":+ """Validate the `edits` array into `(old, new, replace_all)` triples.++ Every string is normalized the way the file is, so a snippet copied out of `cat`+ output with plain newlines still matches a Windows-authored file.++ The surrogate check is per entry and up front, before anything is written: a+ truncated emoji escape ("\\ud83d") survives `json.loads` as a lone surrogate that+ cannot be encoded, and the UnicodeEncodeError the write raises is swallowed upstream+ into "Unknown tool: edit_file" -- the one answer that sends the model back to the+ whole-file rewrite. `old_string` needs no check, being only ever compared.+ """+ if not isinstance(raw, list) or not raw:+ return [], (+ "Error: 'edits' must be a non-empty array of {old_string, new_string} "+ "objects. Send every change to this file as separate entries in it."+ )+ if len(raw) > _MAX_EDITS_PER_CALL:+ return [], (+ f"Error: {len(raw)} edits in one call is over the limit of "+ f"{_MAX_EDITS_PER_CALL}; nothing was written. Send them in batches of "+ f"{_MAX_EDITS_PER_CALL} or fewer, applying each batch before the next."+ )+ edits: list[tuple[str, str, bool]] = []+ for index, entry in enumerate(raw, 1):+ if not isinstance(entry, dict):+ return [], f"Error: edit {index} is not an object with old_string/new_string."+ old = entry.get("old_string")+ new = entry.get("new_string")+ # Checked, not coerced: str(None) would write the literal "None" into a file.+ if not isinstance(old, str) or not isinstance(new, str):+ return [], (+ f"Error: edit {index} needs 'old_string' and 'new_string' to both be strings."+ )+ try:+ new.encode("utf-8")+ except UnicodeEncodeError:+ return [], (+ f"Error: edit {index} has unpaired surrogate characters in "+ "'new_string', usually a half-written emoji; nothing was written. "+ "Send it again as plain text."+ )+ replace_all = _edit_file_replace_all(entry.get("replace_all"))+ if replace_all is None:+ return [], f"Error: edit {index} needs 'replace_all' to be true or false."+ edits.append((old.replace("\r\n", "\n"), new.replace("\r\n", "\n"), replace_all))+ return edits, ""+++def _edit_file_apply_all(+ before: str, edits: "list[tuple[str, str, bool]]", name: str+) -> "tuple[str, int, str, str, int, str]":+ """Apply every edit against the ORIGINAL text, or none of them.++ Matched against `before` rather than against the running result, which is the rule+ llama.cpp's own `edit_file` states and the only one a model can reason about: it+ copied each `old_string` out of the file it read, so an entry that silently matched+ the output of an earlier entry would land somewhere it never saw.++ Spans are resolved for all entries first and checked for overlap, then applied right+ to left so the earlier offsets stay valid. Every failure returns before a single byte+ is written -- a partly applied batch is the one outcome worse than a refused one,+ because the model cannot tell which half landed.+ """+ spans: list[tuple[int, int, str, int]] = []+ for index, (old, new, replace_all) in enumerate(edits, 1):+ if not old:+ # Defence in depth, not a live path: `_edit_file` rejects every empty+ # `old_string` before calling this. It matters because the failure mode if+ # that guard ever moves is not a wrong answer but a HANG -- `find(old, start+ # + len(old))` cannot advance on a zero-length pattern, and the worker keeps+ # a core after its caller has timed out.+ return (+ "",+ 0,+ "",+ "",+ 0,+ (+ f"Error: edit {index} has an empty 'old_string'. Only a single edit "+ "may be empty, and only to create the file."+ ),+ )+ count = before.count(old)+ if count == 0:+ return (+ "",+ 0,+ "",+ "",+ 0,+ (+ f"Error: edit {index}'s 'old_string' was not found in {name}. It must "+ "match the file byte for byte, including indentation. Read the file and "+ "copy the text to replace out of it."+ ),+ )+ if count > 1 and not replace_all:+ return (+ "",+ 0,+ "",+ "",+ 0,+ (+ f"Error: edit {index}'s 'old_string' matches {count} places in {name}. "+ "Include surrounding lines to make it unique, or set replace_all on that "+ f"entry to change all {count}."+ ),+ )+ # One entry needs no spans at all. There is nothing to overlap with, so the whole+ # reason to enumerate matches disappears and `str.replace` does the work in linear+ # space. Enumerating cost about 16 million tuples plus a sort on a 16 MiB file of a+ # one-character pattern -- over a gigabyte for an edit the single-edit spelling had+ # always done cheaply. The batch limit does not help here: one entry is enough.+ if replace_all and len(edits) == 1:+ after = before.replace(old, new)+ first = before.find(old)+ return after, count, old, new, first, ""+ if replace_all and count > _MAX_MATCH_SPANS:+ return (+ "",+ 0,+ "",+ "",+ 0,+ (+ f"Error: edit {index}'s 'old_string' matches {count} places in {name}, "+ f"over the limit of {_MAX_MATCH_SPANS} for one entry in a batch; "+ "nothing was written. Send it as a call of its own, or use a longer "+ "'old_string'."+ ),+ )+ start = before.find(old)+ while start >= 0:+ spans.append((start, start + len(old), new, index))+ if not replace_all:+ break+ start = before.find(old, start + len(old))+ spans.sort()+ for (start, end, _, index), (next_start, _, _, next_index) in zip(spans, spans[1:]):+ if next_start < end:+ return (+ "",+ 0,+ "",+ "",+ 0,+ (+ f"Error: edits {index} and {next_index} overlap in {name}. Every "+ "old_string is matched against the file as it was before this call, so "+ "two edits cannot cover the same text. Combine them into one entry."+ ),+ )+ # One pass with a cursor, not a slice-and-concat per span. Rebuilding the whole string+ # for every replacement is quadratic, and `replace_all` over a large file is exactly+ # where that bites: a file with tens of thousands of matches took 10s where the single+ # `str.replace` it succeeded took well under one.+ parts: list[str] = []+ cursor = 0+ for start, end, new, _ in spans:+ parts.append(before[cursor:start])+ parts.append(new)+ cursor = end+ parts.append(before[cursor:])+ after = "".join(parts)+ first_start, first_end, first_new, _ = spans[0]+ return after, len(spans), before[first_start:first_end], first_new, first_start, ""++def _edit_file(arguments: dict,session_id: "str | None" = None,disable_sandbox: bool = False,) -> str:- """Replace an exact string in a file. See the notes above."""- old = arguments.get("old_string")- new = arguments.get("new_string")- # Checked, not coerced: str(None) would write the literal "None" into a file.- if not isinstance(old, str) or not isinstance(new, str):- return "Error: 'old_string' and 'new_string' must both be strings."- # A truncated emoji escape ("\ud83d") survives json.loads as a lone surrogate- # that cannot be encoded, and the UnicodeEncodeError the write raises is- # swallowed upstream into "Unknown tool: edit_file" -- the one answer that- # sends the model back to the whole-file rewrite. old_string needs no check,- # being only ever compared.- try:- new.encode("utf-8")- except UnicodeEncodeError:- return (- "Error: 'new_string' contains unpaired surrogate characters, usually "- "a half-written emoji; nothing was written. Send it again as plain text."- )+ """Replace exact strings in a file. See the notes above."""+ edits, error = _edit_file_parse_edits(arguments.get("edits"))+ if error:+ return errortarget, error = _edit_file_resolve(str(arguments.get("path") or ""), session_id, disable_sandbox)if error:return errorname = os.path.basename(target)- # Normalized for the same reason the file is, so the two can match.- old = old.replace("\r\n", "\n")- new = new.replace("\r\n", "\n")- replace_all = _edit_file_replace_all(arguments.get("replace_all"))- if replace_all is None:- return "Error: 'replace_all' must be true or false."# Decided before the no-op check below, not after: both strings empty is the# documented way to create __init__.py or .gitkeep, and read as "identical,# nothing to change" it was refused, leaving no way to write a zero-byte# file.- if not old:+ if not edits[0][0]:+ if len(edits) > 1:+ return (+ "Error: an empty 'old_string' creates the file, so it cannot be "+ f"combined with the other {len(edits) - 1} edit(s). Create the file "+ "in one call, then edit it in the next."+ )return _edit_file_create(target,- new,+ edits[0][1],name,"\n",workdir = None if disable_sandbox else _get_workdir(session_id),)- if old == new:- return "Error: 'old_string' and 'new_string' are identical; nothing to change."+ for index, (old, new, _) in enumerate(edits, 1):+ if not old:+ return (+ f"Error: edit {index} has an empty 'old_string'. Only a single edit "+ "may be empty, and only to create the file."+ )+ if old == new:+ return (+ f"Error: edit {index} has identical 'old_string' and 'new_string'; "+ "nothing to change."+ )try:st = os.stat(target)except FileNotFoundError:@@ -9449,20 +9627,9 @@ def _edit_file(before, newline, bom, error = _edit_file_decode(data, target)if error:return error- count = before.count(old)- if count == 0:- return (- f"Error: 'old_string' was not found in {name}. It must match the "- "file byte for byte, including indentation. Read the file and copy "- "the text to replace out of it."- )- if count > 1 and not replace_all:- return (- f"Error: 'old_string' matches {count} places in {name}. Include "- "surrounding lines to make it unique, or pass replace_all=true to "- f"change all {count}."- )- after = before.replace(old, new) if replace_all else before.replace(old, new, 1)+ after, total, first_old, first_new, change_at, error = _edit_file_apply_all(before, edits, name)+ if error:+ return errorerror = _edit_file_write(target,after,@@ -9476,11 +9643,11 @@ def _edit_file(# Windowed around the first replacement, rather than diffing the whole file.return _edit_file_receipt(before,- old,- new,+ first_old,+ first_new,name,- count if replace_all else 1,- change_at = max(before.find(old), 0),+ total,+ change_at = change_at,)@@ -9813,14 +9980,16 @@ EDIT_FILE_TOOL = {# The description does the steering: given the tool but no preference,# a model keeps writing heredocs because that is what it was trained on."description": (- "Change a file by replacing an exact string in it. Prefer this over "- "rewriting a file with python or a shell heredoc: it sends only the "- "lines that change, so editing a large file costs a fraction of the "- "tokens and cannot drop the parts you did not retype. Read the file "- "first and copy old_string out of it verbatim, including indentation. "- "old_string must match exactly one place unless replace_all is true; "- "if it matches none or several you get an error and nothing is "- "written. Paths are relative to the working directory."+ "Change a file by replacing exact strings. Prefer this over rewriting a "+ "file with python or a shell heredoc: it sends only what changes. Copy each "+ "old_string verbatim from the file, indentation included. Batch every change "+ "to one file into edits rather than calling repeatedly, since each call "+ "replays the whole conversation. Every old_string matches the file as it was "+ "BEFORE this call, not the result of earlier edits, and no two may overlap. "+ "Each must match exactly one place unless it sets replace_all; if any matches "+ "none or several, nothing is written. Paths are relative to the working "+ "directory. A successful call means the file holds what you sent, so do not "+ "read it back."),"parameters": {"type": "object",@@ -9829,26 +9998,40 @@ EDIT_FILE_TOOL = {"type": "string","description": "File to edit, relative to the working directory.",},- "old_string": {- "type": "string",- "description": (- "Exact text to replace, copied from the file. Pass an "- "empty string to create a new file."- ),- },- "new_string": {- "type": "string",- "description": "Text to put in its place.",- },- "replace_all": {- "type": "boolean",+ "edits": {+ "type": "array","description": (- "Replace every occurrence instead of requiring a unique "- "match. Defaults to false."+ "One or more replacements to apply together. A single "+ "entry whose old_string is empty creates a new file."),+ "items": {+ "type": "object",+ "properties": {+ "old_string": {+ "type": "string",+ "description": (+ "Exact text to replace, copied from the file. "+ "Empty creates a new file."+ ),+ },+ "new_string": {+ "type": "string",+ "description": "Text to put in its place.",+ },+ "replace_all": {+ "type": "boolean",+ "description": (+ "Replace every occurrence of this entry's "+ "old_string instead of requiring a unique "+ "match. Defaults to false."+ ),+ },+ },+ "required": ["old_string", "new_string"],+ },},},- "required": ["path", "old_string", "new_string"],+ "required": ["path", "edits"],},},}@@ -10241,6 +10424,25 @@ def execute_tool(# turn's own tool exchanges existed, which is precisely the undercount that lets the# last result overflow._REQUEST_RESULT_BUDGET.set(result_budget_tokens)+ # Arguments that never parsed, for a tool with no single argument they could be.+ # Answered here rather than by the tool, which can only report the keys it wanted and+ # would blame the model for omitting them: `edit_file` said "'old_string' and+ # 'new_string' must both be strings" about a call that sent neither because its JSON+ # was cut off mid-string. Naming the real fault is what makes the retry the right one.+ # Imported here for the same reason `strip_result_for_model` is: at module scope this+ # closes an import cycle, since the controller reads this module's own schemas.+ from .tool_loop_controller import UNPARSED_ARGUMENTS_KEY # noqa: PLC0415++ if isinstance(arguments, dict) and UNPARSED_ARGUMENTS_KEY in arguments:+ raw = str(arguments.get(UNPARSED_ARGUMENTS_KEY) or "")+ truncated = raw.lstrip().startswith(("{", "[")) and not raw.rstrip().endswith(("}", "]"))+ cause = (+ "were cut off part-way and could not be read" if truncated else "were not valid JSON"+ )+ return (+ f"Error: {name} arguments {cause}, so nothing ran. Resend as complete JSON, "+ "split across smaller calls if the content is long."+ )effective_timeout = _EXEC_TIMEOUT if timeout is _TIMEOUT_UNSET else timeoutif name == "search_knowledge_base":return _fit_result_to_room(diff --git a/studio/backend/tests/data/refactor_guard/ast_inventory.json b/studio/backend/tests/data/refactor_guard/ast_inventory.jsonindex 509f37c4a59..60c66b1e68b 100644--- a/studio/backend/tests/data/refactor_guard/ast_inventory.json+++ b/studio/backend/tests/data/refactor_guard/ast_inventory.json@@ -44,12 +44,24 @@"ParavirtualPlacement": {"kind": "class"},+ "_AMD_SMI_TOTAL_TOLERANCE": {+ "kind": "assign"+ },+ "_ANCHOR_ARGS_CHARS": {+ "kind": "assign"+ },+ "_ANCHOR_TEXT_CHARS": {+ "kind": "assign"+ },"_ANSWER_PIVOT": {"kind": "assign"},"_APPLE_UNIFIED_MEMORY_FRACTION": {"kind": "assign"},+ "_AUTO_OFFLOAD_CTX": {+ "kind": "assign"+ },"_BIG_ENDIAN_GGUF_FILENAME_RE": {"kind": "assign"},@@ -59,9 +71,18 @@"_CANONICAL_SPEC_MODES": {"kind": "assign"},+ "_CGROUP_ROOT": {+ "kind": "assign"+ },"_CHAT_LOADS_IN_FLIGHT": {"kind": "assign"},+ "_CONTINUE_AFTER_LENGTH_STATUS": {+ "kind": "assign"+ },+ "_CONTINUE_TRUNCATED_ANSWER_STATUS": {+ "kind": "assign"+ },"_CPU_DEVICE_VALUES": {"kind": "assign"},@@ -110,9 +131,24 @@"_DRAFTER_KINDS": {"kind": "assign"},+ "_DRAFT_GPU_LAYER_FLAGS": {+ "kind": "assign"+ },+ "_FAILURE_QUOTE_CHARS": {+ "kind": "assign"+ },+ "_FAILURE_SCAN_TAIL_CHARS": {+ "kind": "assign"+ },"_FINAL_ANSWER_SIGNAL": {"kind": "assign"},+ "_FIT_FLOOR_MIN_CTX": {+ "kind": "assign"+ },+ "_FIT_MIN_CTX": {+ "kind": "assign"+ },"_FORCED_PLAN_INTENT": {"kind": "assign"},@@ -131,6 +167,9 @@"_GGUF_REHEARSAL_ARGS_RE": {"kind": "assign"},+ "_GGUF_UINT_WIDTHS": {+ "kind": "assign"+ },"_GPU_DEVICE_PREFIXES": {"kind": "assign"},@@ -140,12 +179,24 @@"_GPU_OFFLOAD_OVERRIDE_FLAGS": {"kind": "assign"},+ "_HF_DRAFT_FLAGS": {+ "kind": "assign"+ },+ "_HOST_RAM_HEADROOM_MIB": {+ "kind": "assign"+ },"_IGPU_HOST_RESERVE_MIB": {"kind": "assign"},+ "_IMATRIX_TOKEN_RE": {+ "kind": "assign"+ },"_INKLING_REASONING_EFFORT": {"kind": "assign"},+ "_INSTALLER_WRAPPER_RE": {+ "kind": "assign"+ },"_LEGACY_SPEC_MODE_MAP": {"kind": "assign"},@@ -164,18 +215,45 @@"_LLAMA_ARG_TRUE_VALUES": {"kind": "assign"},+ "_LLAMA_FIT_TARGET_DEFAULT_MIB": {+ "kind": "assign"+ },"_LOADS_IN_FLIGHT": {"kind": "assign"},"_LOADS_IN_FLIGHT_LOCK": {"kind": "assign"},+ "_LOCAL_DRAFT_FLAGS": {+ "kind": "assign"+ },"_LlamaStreamCancelled": {"kind": "class"},+ "_MAX_IDENTICAL_TOOL_RESULTS": {+ "kind": "assign"+ },+ "_MAX_LENGTH_CONTINUATIONS": {+ "kind": "assign"+ },"_MAX_TOOL_CALLS_PER_TURN": {"kind": "assign"},+ "_MIN_USEFUL_RESULT_TOKENS": {+ "kind": "assign"+ },+ "_MISS": {+ "kind": "assign"+ },+ "_MMPROJ_OFFLOAD_ENV_VAR": {+ "kind": "assign"+ },+ "_MMPROJ_OFFLOAD_FLAGS": {+ "kind": "assign"+ },+ "_MMPROJ_OFFLOAD_NEG_ENV_VAR": {+ "kind": "assign"+ },"_MTP_MIN_SIZE_B": {"kind": "assign"},@@ -194,9 +272,18 @@"_PERMANENT_HUB_ERRORS": {"kind": "assign"},+ "_PROC_ROOT": {+ "kind": "assign"+ },+ "_PROC_SELF_CGROUP": {+ "kind": "assign"+ },"_PROVISIONAL_ARGS_MIN_CHARS": {"kind": "assign"},+ "_QWEN38_MODEL_RE": {+ "kind": "assign"+ },"_REASONING_EFFORT_SCALE": {"kind": "assign"},@@ -209,6 +296,9 @@"_SHARD_RE": {"kind": "assign"},+ "_SIDECAR_ADAPTER_FLAGS": {+ "kind": "assign"+ },"_SPEC_ENV_VARS": {"kind": "assign"},@@ -224,6 +314,15 @@"_SWA_PATTERN_SOURCE_RE": {"kind": "assign"},+ "_TARGET_KV_EXCLUDES_NEXTN_ARCHS": {+ "kind": "assign"+ },+ "_TARGET_ROLLBACK_SPEC_TYPES": {+ "kind": "assign"+ },+ "_TENSOR_SPLIT_FLAGS": {+ "kind": "assign"+ },"_TEXT_TOOL_GEMMA_RE": {"kind": "assign"},@@ -242,27 +341,72 @@"_UNRECOVERABLE_LOCAL_ERRNOS": {"kind": "assign"},+ "_VALID_CACHE_TYPES": {+ "kind": "assign"+ },+ "_VALID_KV_CACHE_TYPES": {+ "kind": "assign"+ },+ "_VRAM_FLOOR_RESERVE_MIB": {+ "kind": "assign"+ },"_VULKAN_DIFFUSION_GPU_IDS_ERROR": {"kind": "assign"},+ "_WINDOW_NOTICE_MARKER": {+ "kind": "assign"+ },"_accumulated_spec_types": {"kind": "def"},+ "_active_vram_fraction": {+ "kind": "def"+ },+ "_anchor_text": {+ "kind": "def"+ },"_apply_igpu_host_reserve_mib": {"kind": "def"},"_arch_aliases": {"kind": "def"},+ "_archive_and_recall": {+ "kind": "def"+ },+ "_archive_branch_transcript": {+ "kind": "def"+ },+ "_archive_content_on_branch": {+ "kind": "def"+ },+ "_archive_is_degraded": {+ "kind": "def"+ },+ "_archive_message_text": {+ "kind": "def"+ },"_args_place_tensors_on_cpu": {"kind": "def"},"_auto_mode_drops_mtp": {"kind": "def"},+ "_backend_supports_tools": {+ "kind": "def"+ },"_backfill_usage_from_timings": {"kind": "def"},+ "_branch_boundary": {+ "kind": "def"+ },+ "_branch_boundary_anchor": {+ "kind": "def"+ },+ "_branch_non_system": {+ "kind": "def"+ },"_build_ngram_mod_flags": {"kind": "def"},@@ -287,6 +431,12 @@"_cached_variant_resolution": {"kind": "def"},+ "_cached_variant_sizes": {+ "kind": "def"+ },+ "_can_reset_epoch": {+ "kind": "def"+ },"_canonicalize_spec_mode": {"kind": "def"},@@ -299,6 +449,9 @@"_companion_snapshot_sibling": {"kind": "def"},+ "_conversation_recall_reserve": {+ "kind": "def"+ },"_cpu_runtime_owner_alive": {"kind": "def"},@@ -308,6 +461,9 @@"_diffusion_manual_ngl": {"kind": "def"},+ "_draft_is_split_across_host": {+ "kind": "def"+ },"_drafter_path_kind": {"kind": "def"},@@ -323,12 +479,24 @@"_emitted_n_batch": {"kind": "def"},+ "_env_asks_for_the_native_context": {+ "kind": "def"+ },+ "_env_fixes_gpu_layers": {+ "kind": "def"+ },"_env_main_cache_type_for_budget": {"kind": "def"},+ "_env_mmproj_offload_value": {+ "kind": "def"+ },"_env_places_tensors_on_cpu": {"kind": "def"},+ "_env_sets_mmproj_offload": {+ "kind": "def"+ },"_extra_args_device": {"kind": "def"},@@ -341,6 +509,9 @@"_extra_args_draft_device_pin": {"kind": "def"},+ "_extra_args_draft_gpu_layers": {+ "kind": "def"+ },"_extra_args_draft_offloaded_to_cpu": {"kind": "def"},@@ -350,9 +521,18 @@"_extra_args_main_device": {"kind": "def"},+ "_extra_args_mmproj_offload_value": {+ "kind": "def"+ },"_extra_args_mtp_draft_path": {"kind": "def"},+ "_extra_args_mtp_draft_source": {+ "kind": "def"+ },+ "_extra_args_n_parallel": {+ "kind": "def"+ },"_extra_args_n_ubatch": {"kind": "def"},@@ -371,12 +551,21 @@"_extra_args_set_any_flag": {"kind": "def"},+ "_extra_args_set_mmproj_offload": {+ "kind": "def"+ },"_extra_args_set_spec_type": {"kind": "def"},"_extra_args_spec_draft_n_max": {"kind": "def"},+ "_extra_args_split_mode": {+ "kind": "def"+ },+ "_extra_args_tensor_split": {+ "kind": "def"+ },"_extract_model_size_b": {"kind": "def"},@@ -389,6 +578,12 @@"_finalize_reasoning_only_cumulative": {"kind": "def"},+ "_fit_context": {+ "kind": "def"+ },+ "_fit_with_instruction_pins": {+ "kind": "def"+ },"_flash_attn_enabled_from_args": {"kind": "def"},@@ -440,6 +635,9 @@"_hub_download_in_flight": {"kind": "def"},+ "_inject_recall": {+ "kind": "def"+ },"_is_big_endian_gguf_path": {"kind": "def"},@@ -461,6 +659,9 @@"_is_gemma_mtp_name": {"kind": "def"},+ "_is_installer_entrypoint": {+ "kind": "def"+ },"_is_mtp_model_name": {"kind": "def"},@@ -476,6 +677,12 @@"_is_root_dflash_drafter_path": {"kind": "def"},+ "_is_window_notice": {+ "kind": "def"+ },+ "_keeps_compaction_boundary": {+ "kind": "def"+ },"_kv_bytes_per_elem": {"kind": "def"},@@ -497,15 +704,27 @@"_load_swa_cache": {"kind": "def"},+ "_loader_path_var": {+ "kind": "def"+ },+ "_memory_tool_withheld": {+ "kind": "def"+ },"_metal_device_is_paravirtual": {"kind": "def"},"_mla_mtp_auto_enabled": {"kind": "def"},+ "_mmproj_env_is_audio_only": {+ "kind": "def"+ },"_native_linux_system_rocm_lib_dirs": {"kind": "def"},+ "_normalized_load_mode": {+ "kind": "def"+ },"_pad_kv_cells": {"kind": "def"},@@ -527,21 +746,45 @@"_period_from_layer_types": {"kind": "def"},+ "_pick_dspark": {+ "kind": "def"+ },"_pick_mmproj": {"kind": "def"},+ "_pick_mtp": {+ "kind": "def"+ },"_pipeline_parallel_disabled_by_args": {"kind": "def"},"_planned_main_cache_types": {"kind": "def"},+ "_planned_scratch_cache_type": {+ "kind": "def"+ },+ "_prefix_user_text": {+ "kind": "def"+ },+ "_prepend_loader_dir": {+ "kind": "def"+ },"_probe_dns_dead": {"kind": "def"},"_quant_label_for_endian": {"kind": "def"},+ "_recall_top_k": {+ "kind": "def"+ },+ "_records_boundary": {+ "kind": "def"+ },+ "_report_live_llama_timings": {+ "kind": "def"+ },"_resolve_llama_binary": {"kind": "def"},@@ -554,6 +797,15 @@"_resolve_swa_pattern": {"kind": "def"},+ "_resolve_variant_gguf_files": {+ "kind": "def"+ },+ "_resolved_mmproj_offload": {+ "kind": "def"+ },+ "_retrieval_budget": {+ "kind": "assign"+ },"_save_swa_cache": {"kind": "def"},@@ -566,6 +818,12 @@"_should_suppress_forced_no_tool_output": {"kind": "def"},+ "_sidecar_adapter_bytes": {+ "kind": "def"+ },+ "_sidecar_adapter_paths": {+ "kind": "def"+ },"_snapshot_dir_of": {"kind": "def"},@@ -578,9 +836,18 @@"_source_declares_option": {"kind": "def"},+ "_split_mode_confines_to_one_device": {+ "kind": "def"+ },+ "_sticky_compaction_boundary": {+ "kind": "def"+ },"_strip_flag_pairs": {"kind": "def"},+ "_subsequence_index": {+ "kind": "def"+ },"_swa_cache_path": {"kind": "def"},@@ -596,6 +863,12 @@"_sweep_abandoned_cpu_runtimes": {"kind": "def"},+ "_vram_reserve_floor_mib": {+ "kind": "def"+ },+ "_vram_usable_mib": {+ "kind": "def"+ },"_with_gguf_load_marker": {"kind": "def"},@@ -660,9 +933,15 @@"_TOOL_CALL_NAME_RE": {"kind": "assign"},+ "_TOOL_SIGNAL_OVERLAP": {+ "kind": "assign"+ },"_UNRESTRICTED_REHEARSAL_RE": {"kind": "assign"},+ "_accepts_kwarg": {+ "kind": "def"+ },"_accepts_output_callback": {"kind": "def"},@@ -684,6 +963,9 @@"_earliest_tool_signal": {"kind": "def"},+ "_first_detected_tool_name": {+ "kind": "def"+ },"_has_genuine_tool_signal": {"kind": "def"},@@ -702,6 +984,9 @@"_reprompt_intent_text": {"kind": "def"},+ "_search_images_kwargs": {+ "kind": "def"+ },"_status_for_tool": {"kind": "def"},@@ -1034,6 +1319,9 @@"_KIMI_SECTION_END": {"kind": "assign"},+ "_LENGTH_PROGRESS_TAIL_CHARS": {+ "kind": "assign"+ },"_LLAMA3_BARE_JSON_SENTINELS": {"kind": "assign"},@@ -1383,6 +1671,11 @@"kind": "def","signature": "content: str"},+ "continue_after_length_message": {+ "decorators": [],+ "kind": "def",+ "signature": ""+ },"has_tool_signal": {"decorators": [],"kind": "def",@@ -1408,11 +1701,26 @@"kind": "def","signature": "content: str, *, id_offset: int=0, allow_incomplete: bool=True, enabled_tool_names: Optional[set]=None"},+ "reasoning_cap_spent_message": {+ "decorators": [],+ "kind": "def",+ "signature": "max_tokens: Optional[int]=None"+ },+ "repeated_result_message": {+ "decorators": [],+ "kind": "def",+ "signature": "tool_name: str, times: int, last_result: str"+ },"reprompt_to_act_message": {"decorators": [],"kind": "def","signature": "tool_hint: str"},+ "starved_result_message": {+ "decorators": [],+ "kind": "def",+ "signature": "tool_name: str, result: str"+ },"strip_leading_bare_json_call": {"decorators": [],"kind": "def",@@ -1432,6 +1740,16 @@"decorators": [],"kind": "def","signature": "text: str, *, final: bool=False, enabled_tool_names: Optional[set]=None"+ },+ "thinking_exhausted_message": {+ "decorators": [],+ "kind": "def",+ "signature": "context_length: Optional[int]=None"+ },+ "unfinished_thought_progress": {+ "decorators": [],+ "kind": "def",+ "signature": "reasoning: str"}}},diff --git a/studio/backend/tests/data/refactor_guard/golden_outputs.json b/studio/backend/tests/data/refactor_guard/golden_outputs.jsonindex f3ba76bc7f9..84b9e5aa98e 100644--- a/studio/backend/tests/data/refactor_guard/golden_outputs.json+++ b/studio/backend/tests/data/refactor_guard/golden_outputs.json@@ -53,11 +53,14 @@"is_reprompt_restatement": "8bec9da2bf58bada77617c893169063c29d5ed8ef3ffe96c12c70755bfcea0be","is_short_intent_without_action": "de99e25b81def8c5ac63b03718b84c3525f49e5f31598555fb183f7637959340","parse_tool_calls_from_text": "19077dca174b78f6d41a710beb02bd3875752343c2a6b35f00ec4805cb5595f7",+ "repeated_result_message": "3edd2438690044e5084358837c50c633c7b893242cb28fb5b626febfc7b00441","reprompt_to_act_message": "53b231a1489544f480ae21ab5e3b461e0eff072564f582dae0df55938779b445",+ "starved_result_message": "b1eadfc967db807f41712d430237eec49b095ea6a1f1219972057434c9870f07","strip_leading_bare_json_call": "4dfe14fa258e30d340cfa8400eec6dde4cbbcdbaba20ac5ace312d54176c83d3","strip_llama3_leading_sentinels": "7ba3f83eee7f9c5aed00d24c8cc26e5cdd82cdca7e8aca747f02566c417eef9d","strip_segment": "6feb0ddeab2929915953a9a806766a07fba35be1e96bff66563128364daded17",- "strip_tool_markup": "fb2df4ad97d8e280dec296b615ab454b8990e1bcb3ad1caad1bfc7b4a73fd573"+ "strip_tool_markup": "fb2df4ad97d8e280dec296b615ab454b8990e1bcb3ad1caad1bfc7b4a73fd573",+ "unfinished_thought_progress": "9ea96157cabd83756b4217f82ed18a19c96c80713009269b7cf93811f872a9aa"},"core.tool_healing": {"_balanced_brace_end": "0b82a90811adc2196cb441d8bc569ab360aafa2552bb4093ab5b2777d9cf3a18",diff --git a/studio/backend/tests/data/refactor_guard/patch_targets.json b/studio/backend/tests/data/refactor_guard/patch_targets.jsonindex 12a4fd2e896..4c15042379c 100644--- a/studio/backend/tests/data/refactor_guard/patch_targets.json+++ b/studio/backend/tests/data/refactor_guard/patch_targets.json@@ -11,6 +11,9 @@"tests/test_training_cached_start.py","tests/test_training_raw_support.py"],+ "core.inference.api_monitor.uuid.uuid4": [+ "tests/test_api_monitor.py"+ ],"core.inference.chat_template_helpers.apply_chat_template_for_generation": ["tests/test_mlx_inference_backend.py","tests/test_mlx_inference_backend.py",@@ -25,6 +28,7 @@"tests/test_mlx_inference_backend.py","tests/test_mlx_inference_backend.py","tests/test_mlx_inference_backend.py",+ "tests/test_mlx_inference_backend.py","tests/test_mlx_inference_backend.py"],"core.inference.chat_template_helpers.detect_think_prefill": [@@ -164,6 +168,9 @@"tests/test_diffusion_backend.py","tests/test_sd_cpp_backend.py"],+ "core.inference.diffusion_families.cache_holds_files": [+ "tests/test_media_auto_switch.py"+ ],"core.inference.diffusion_families.detect_family_for_pick": ["tests/test_gguf_variant_dependency_key.py"],@@ -172,9 +179,11 @@"tests/test_diffusion_dit_trainer_ltx2.py"],"core.inference.diffusion_krea2.load_krea2_text_encoder": [+ "tests/test_diffusion_krea2.py","tests/test_diffusion_krea2.py"],"core.inference.diffusion_krea2.load_krea2_tokenizer": [+ "tests/test_diffusion_krea2.py","tests/test_diffusion_krea2.py"],"core.inference.diffusion_lora.loras_dir": [@@ -221,9 +230,13 @@"tests/test_gpu_selection.py"],"core.inference.llama_cpp._hub_download_blocks_gguf_load": [- "tests/test_gguf_load_cache_reuse.py"+ "tests/test_gguf_load_cache_reuse.py",+ "tests/test_mmproj_placement_policy.py"],"core.inference.llama_cpp._llama_lib_dir": [+ "tests/test_llama_cpp_placement.py",+ "tests/test_llama_cpp_placement.py",+ "tests/test_llama_cpp_placement.py","tests/test_llama_cpp_placement.py","tests/test_llama_cpp_placement.py","tests/test_llama_cpp_placement.py"@@ -273,6 +286,10 @@"core.inference.llama_cpp.httpx.get": ["tests/test_offline_gguf_cache_fallback.py"],+ "core.inference.llama_cpp.logger": [+ "tests/test_slot_reduction_context_refit.py",+ "tests/test_slot_reduction_context_refit.py"+ ],"core.inference.llama_cpp.new_approval_id": ["tests/test_llama_cpp_tool_loop.py","tests/test_llama_cpp_tool_loop.py",@@ -281,6 +298,9 @@"core.inference.llama_cpp.shutil.disk_usage": ["tests/test_gguf_load_cache_reuse.py"],+ "core.inference.llama_cpp.shutil.which": [+ "tests/test_llama_cpp_path_settings.py"+ ],"core.inference.llama_cpp.subprocess.run": ["tests/test_amd_apu_unified_memory.py","tests/test_amd_apu_unified_memory.py",@@ -290,6 +310,7 @@"tests/test_llama_cpp_mtp_detection.py","tests/test_llama_cpp_mtp_detection.py","tests/test_llama_cpp_mtp_detection.py",+ "tests/test_llama_flag_catalog.py","tests/test_metal_paravirtual_guard.py","tests/test_metal_paravirtual_guard.py","tests/test_metal_paravirtual_guard.py",@@ -362,6 +383,16 @@"core.inference.stt_sidecar.get_stt_sidecar": ["tests/test_stt_ggml_sidecar.py"],+ "core.inference.stt_transformers_worker.WhisperWorker": [+ "tests/test_stt_sidecar.py",+ "tests/test_stt_sidecar.py",+ "tests/test_stt_sidecar.py",+ "tests/test_stt_sidecar.py",+ "tests/test_stt_sidecar.py",+ "tests/test_stt_sidecar.py",+ "tests/test_stt_sidecar.py",+ "tests/test_stt_sidecar.py"+ ],"core.inference.tool_stream_exec._WORKER_JOIN_TIMEOUT_S": ["tests/test_tool_output_streaming.py","tests/test_tool_output_streaming.py"@@ -386,13 +417,36 @@"tests/test_web_fetch_extraction.py"],"core.inference.tools.build_rag_autoinject": [+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py","tests/test_llama_cpp_tool_loop.py","tests/test_llama_cpp_tool_loop.py","tests/test_safetensors_tool_loop.py","tests/test_safetensors_tool_loop.py"],"core.inference.tools.execute_tool": [+ "tests/test_anthropic_messages.py","tests/test_gguf_route_cursor_reset.py",+ "tests/test_length_truncated_reasoning_continuation.py",+ "tests/test_length_truncated_reasoning_continuation.py",+ "tests/test_length_truncated_reasoning_continuation.py",+ "tests/test_length_truncated_reasoning_continuation.py",+ "tests/test_length_truncated_reasoning_continuation.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py","tests/test_llama_cpp_tool_loop.py","tests/test_llama_cpp_tool_loop.py","tests/test_llama_cpp_tool_loop.py",@@ -460,8 +514,37 @@"tests/test_llama_cpp_tool_loop.py","tests/test_llama_cpp_tool_loop.py","tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_llama_cpp_tool_loop.py",+ "tests/test_no_progress_tool_results.py",+ "tests/test_no_progress_tool_results.py",+ "tests/test_no_progress_tool_results.py",+ "tests/test_no_progress_tool_results.py",+ "tests/test_no_progress_tool_results.py",+ "tests/test_no_progress_tool_results.py",+ "tests/test_no_progress_tool_results.py",+ "tests/test_no_progress_tool_results.py","tests/test_tool_output_streaming.py"],+ "core.inference.tools.get_enabled_mcp_tools": [+ "tests/test_external_hosted_tool_passthrough.py",+ "tests/test_external_hosted_tool_passthrough.py"+ ],"core.inference.video._detect_load_family": ["tests/test_video_prequant.py"],@@ -504,11 +587,33 @@"core.inference.video_families.detect_video_family": ["tests/test_cached_gguf_routes.py"],+ "core.rag.conversation_archive.can_archive": [+ "tests/test_checkpoint_compaction.py",+ "tests/test_checkpoint_compaction.py",+ "tests/test_checkpoint_compaction.py"+ ],+ "core.rag.conversation_archive.enabled": [+ "tests/test_checkpoint_compaction.py",+ "tests/test_checkpoint_compaction.py",+ "tests/test_checkpoint_compaction.py",+ "tests/test_checkpoint_compaction.py"+ ],+ "core.rag.conversation_archive.has_archive": [+ "tests/test_checkpoint_compaction.py",+ "tests/test_checkpoint_compaction.py"+ ],+ "core.rag.conversation_archive.reachable": [+ "tests/test_checkpoint_compaction.py"+ ],"core.rag.parsers.parse_pdf_bytes": ["tests/test_web_fetch_binary_guard.py","tests/test_web_fetch_binary_guard.py","tests/test_web_fetch_binary_guard.py"],+ "core.research_runs._peek_inference_backend": [+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py"+ ],"core.training.diffusion_checkpoint.read_checkpoint": ["tests/test_diffusion_train_perf.py"],@@ -534,7 +639,12 @@"tests/test_video_routes.py"],"core.training.get_training_backend": [- "tests/test_gpu_selection.py"+ "tests/test_gpu_selection.py",+ "tests/test_mmproj_placement_policy.py"+ ],+ "core.training.provenance.exact_resume_resource_requirements": [+ "tests/test_training_transformers_upgrade_gate.py",+ "tests/test_training_transformers_upgrade_gate.py"],"core.training.provenance.normalize_worker_provenance_event": ["tests/test_training_provenance.py"@@ -547,9 +657,12 @@"tests/test_training_history_delete.py"],"core.training.trainer.format_and_template_dataset": [+ "tests/test_audio_type_inconclusive.py","tests/test_training_preflight.py"],"core.training.trainer.load_dataset": [+ "tests/test_audio_type_inconclusive.py",+ "tests/test_training_preflight.py","tests/test_training_preflight.py","tests/test_training_preflight.py","tests/test_training_preflight.py",@@ -678,6 +791,7 @@"tests/test_cached_gguf_routes.py","tests/test_cached_gguf_routes.py","tests/test_cached_gguf_routes.py",+ "tests/test_cached_gguf_routes.py","tests/test_cached_gguf_routes.py"],"hub.utils.hf_cache_state.hf_cache_root": [@@ -706,6 +820,9 @@"hub.utils.hf_cache_state.latest_snapshot_from_cache_path": ["tests/test_models_get_model_config_case_resolution.py"],+ "hub.utils.hf_cache_state.repo_cache_dir_has_incomplete_blobs": [+ "tests/test_offline_embedding_minimal.py"+ ],"hub.utils.inventory_scan.invalidate_hf_cache_scans": ["tests/test_hf_cache_settings.py"],@@ -738,8 +855,33 @@"tests/test_picker_service.py","tests/test_picker_service.py"],+ "routes.inference._estimate_gguf_required_gb": [+ "tests/test_mmproj_placement_policy.py"+ ],+ "routes.inference._guard_diffusion_load_against_training": [+ "tests/test_diffusion_engine_load_contract.py"+ ],+ "routes.inference._remote_gguf_companion_bytes": [+ "tests/test_mmproj_placement_policy.py"+ ],+ "routes.inference._selected_gpu_ordinal": [+ "tests/test_diffusion_engine_load_contract.py"+ ],"routes.inference.get_llama_cpp_backend": [- "tests/test_consent_gate.py"+ "tests/test_consent_gate.py",+ "tests/test_tool_result_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py",+ "tests/test_web_page_cap_fits_window.py"],"routes.models._cached_repo_task": ["tests/test_cached_gguf_routes.py"@@ -748,6 +890,19 @@"tests/test_gpu_selection.py","tests/test_gpu_selection.py"],+ "routes.video._guard_video_load_against_training": [+ "tests/test_media_auto_switch.py",+ "tests/test_media_auto_switch.py"+ ],+ "routes.video._selected_gpu_ordinal": [+ "tests/test_media_auto_switch.py",+ "tests/test_media_auto_switch.py"+ ],+ "state.tool_policy.get_tool_policy": [+ "tests/test_checkpoint_compaction.py",+ "tests/test_checkpoint_compaction.py",+ "tests/test_checkpoint_compaction.py"+ ],"storage.studio_db.add_scan_folder_with_status": ["tests/test_openai_auto_switch.py"],@@ -758,6 +913,7 @@],"storage.studio_db.get_app_setting": ["tests/test_hf_cache_settings.py",+ "tests/test_llama_cpp_path_settings.py","tests/test_model_memory_settings.py","tests/test_model_memory_settings.py","tests/test_model_memory_settings.py",@@ -772,7 +928,14 @@"tests/test_personalization_settings.py","tests/test_personalization_settings.py"],+ "storage.studio_db.get_run": [+ "tests/test_training_transformers_upgrade_gate.py",+ "tests/test_training_transformers_upgrade_gate.py"+ ],"storage.studio_db.list_scan_folders": [+ "tests/test_cached_gguf_routes.py",+ "tests/test_cached_gguf_routes.py",+ "tests/test_cached_gguf_routes.py","tests/test_cached_gguf_routes.py","tests/test_cached_gguf_routes.py","tests/test_cached_gguf_routes.py",@@ -797,6 +960,7 @@],"storage.studio_db.upsert_app_settings": ["tests/test_hf_cache_settings.py",+ "tests/test_llama_cpp_path_settings.py","tests/test_model_memory_settings.py","tests/test_model_memory_settings.py","tests/test_model_memory_settings.py",@@ -813,6 +977,20 @@"tests/test_coding_agents.py","tests/test_coding_agents.py"],+ "utils.datasets.online_tokenization.attach_online_tokenization": [+ "tests/test_online_tokenization_wiring.py"+ ],+ "utils.datasets.online_tokenization.decide_online_tokenization": [+ "tests/test_online_tokenization_wiring.py"+ ],+ "utils.datasets.online_tokenization.resolve_worker_count": [+ "tests/test_online_tokenization_wiring.py"+ ],+ "utils.datasets.online_tokenization.trl_supports_skip_prepare_dataset": [+ "tests/test_online_tokenization.py",+ "tests/test_online_tokenization.py",+ "tests/test_online_tokenization_wiring.py"+ ],"utils.hardware.apple.read_gpu_power_w": ["tests/test_gpu_selection.py"],@@ -868,6 +1046,15 @@"tests/test_training_before_spawn.py","tests/test_training_before_spawn.py"],+ "utils.hardware.hardware.IS_ROCM": [+ "tests/test_memory_estimate_platforms.py",+ "tests/test_utils.py"+ ],+ "utils.hardware.hardware._context_free_cuda_memory_info": [+ "tests/test_utils.py",+ "tests/test_utils.py",+ "tests/test_utils.py"+ ],"utils.hardware.hardware._determine_attention_impl_for_gpu_estimate": ["tests/test_gpu_selection.py","tests/test_gpu_selection.py"@@ -927,6 +1114,9 @@"tests/test_gpu_selection.py","tests/test_gpu_selection.py"],+ "utils.hardware.hardware._rocm_props_total_is_carve_out": [+ "tests/test_utils.py"+ ],"utils.hardware.hardware._smi_query": ["tests/test_gpu_selection.py"],@@ -1003,6 +1193,8 @@"tests/test_utils.py","tests/test_utils.py","tests/test_utils.py",+ "tests/test_utils.py",+ "tests/test_utils.py","tests/test_utils.py"],"utils.hardware.hardware.get_gpu_memory_info": [@@ -1055,6 +1247,11 @@"utils.hardware.hardware.resolve_requested_gpu_ids": ["tests/test_gpu_selection.py"],+ "utils.hardware.hardware.trusted_mem_get_info": [+ "tests/test_utils.py",+ "tests/test_utils.py",+ "tests/test_utils.py"+ ],"utils.hardware.nvidia.get_backend_visible_gpu_info": ["tests/test_gpu_selection.py"],@@ -1074,8 +1271,13 @@"tests/test_vram_estimation.py"],"utils.hf_cache_settings.active_hf_hub_cache": [+ "tests/test_chat_load_during_training.py",+ "tests/test_chat_load_during_training.py","tests/test_diffusion_backend.py","tests/test_rag_embeddings.py",+ "tests/test_rag_embeddings.py",+ "tests/test_rag_embeddings.py",+ "tests/test_rag_embeddings.py","tests/test_sd_cpp_backend.py","tests/test_sd_cpp_backend.py","tests/test_sd_cpp_backend.py",@@ -1132,6 +1334,11 @@"tests/test_diffusion_backend.py","tests/test_diffusion_backend.py","tests/test_sd_cpp_backend.py",+ "tests/test_sd_cpp_h3_matrix.py",+ "tests/test_video_backend.py",+ "tests/test_video_backend.py",+ "tests/test_video_backend.py",+ "tests/test_video_backend.py","tests/test_video_backend.py","tests/test_video_backend.py","tests/test_video_backend.py",@@ -1168,6 +1375,8 @@"tests/test_vision_cache.py","tests/test_vision_cache.py","tests/test_vision_cache.py",+ "tests/test_vision_cache.py",+ "tests/test_vision_cache.py","tests/test_vision_cache.py"],"utils.models.model_config._is_vision_model_uncached": [@@ -1177,6 +1386,7 @@"tests/test_vision_cache.py","tests/test_vision_cache.py","tests/test_vision_cache.py",+ "tests/test_vision_cache.py","tests/test_vision_cache.py"],"utils.models.model_config._iter_gguf_files": [@@ -1215,11 +1425,18 @@"tests/test_training_cached_start.py","tests/test_training_cached_start.py","tests/test_training_cached_start.py",- "tests/test_training_cached_start.py"+ "tests/test_training_cached_start.py",+ "tests/test_training_transformers_upgrade_gate.py",+ "tests/test_training_transformers_upgrade_gate.py",+ "tests/test_training_transformers_upgrade_gate.py"],"utils.models.model_config.is_audio_input_type": ["tests/test_trained_model_scan.py"],+ "utils.models.model_config.is_embedding_model": [+ "tests/test_gguf_metadata.py",+ "tests/test_gguf_metadata.py"+ ],"utils.models.model_config.is_local_path": ["tests/test_capability_detection.py","tests/test_capability_detection.py"@@ -1233,7 +1450,8 @@"tests/test_batch_sizes_per_load.py","tests/test_batch_sizes_per_load.py","tests/test_batch_sizes_per_load.py",- "tests/test_batch_sizes_per_load.py"+ "tests/test_batch_sizes_per_load.py",+ "tests/test_mmproj_placement_policy.py"],"utils.models.model_config.load_model_config": ["tests/test_vision_cache.py",@@ -1327,7 +1545,15 @@"tests/test_stt_http_downloads.py"],"utils.process_lifetime.forget_pid": [- "tests/test_stt_mtmd_sidecar.py"+ "tests/test_stt_mtmd_sidecar.py",+ "tests/test_stt_transformers_worker.py",+ "tests/test_stt_transformers_worker.py",+ "tests/test_stt_transformers_worker.py",+ "tests/test_stt_transformers_worker.py",+ "tests/test_stt_transformers_worker.py",+ "tests/test_stt_transformers_worker.py",+ "tests/test_stt_transformers_worker.py",+ "tests/test_stt_transformers_worker.py"],"utils.security.consent._config_has_auto_map": ["tests/test_openai_auto_download.py",@@ -1357,6 +1583,10 @@"utils.security.trusted_org.is_local_path": ["tests/test_consent_gate.py"],+ "utils.transformers_version._CURRENT_EXT_TAG": [+ "tests/test_transformers_version.py",+ "tests/test_transformers_version.py"+ ],"utils.transformers_version._check_config_needs_510": ["tests/test_transformers_version.py","tests/test_transformers_version.py",@@ -1398,6 +1628,7 @@"tests/test_transformers_version.py","tests/test_transformers_version.py","tests/test_transformers_version.py",+ "tests/test_transformers_version.py","tests/test_transformers_version.py"],"utils.transformers_version._ensure_venv_t5_510_exists": [@@ -1470,7 +1701,8 @@"tests/test_training_cached_start.py","tests/test_training_cached_start.py","tests/test_training_cached_start.py",- "tests/test_training_cached_start.py"+ "tests/test_training_cached_start.py",+ "tests/test_training_provenance.py"],"utils.transformers_version.logger": ["tests/test_transformers_version.py"@@ -1478,6 +1710,7 @@"utils.transformers_version.needs_transformers_5": ["tests/test_gpu_selection.py","tests/test_gpu_selection.py",+ "tests/test_orchestrator_load_cancel_event.py","tests/test_vision_cache.py","tests/test_vision_cache.py","tests/test_vision_cache.py",@@ -1496,6 +1729,9 @@"utils.transformers_version.sidecar_swap_in_progress": ["tests/test_training_cached_start.py"],+ "utils.transformers_version.sidecar_swap_kind": [+ "tests/test_orchestrator_load_cancel_event.py"+ ],"utils.transformers_version.subprocess.run": ["tests/test_transformers_version.py","tests/test_transformers_version.py",@@ -1519,6 +1755,7 @@"tests/test_transformers_version.py","tests/test_transformers_version.py","tests/test_transformers_version.py",+ "tests/test_transformers_version.py","tests/test_transformers_version.py"],"utils.utils.hf_cache_snapshot_dir": [diff --git a/studio/backend/tests/data/refactor_guard/runtime_inventory.json b/studio/backend/tests/data/refactor_guard/runtime_inventory.jsonindex 8d3117a2d15..5023eb54285 100644--- a/studio/backend/tests/data/refactor_guard/runtime_inventory.json+++ b/studio/backend/tests/data/refactor_guard/runtime_inventory.json@@ -56,6 +56,7 @@"_KIMI_ID_RE","_KIMI_SECTION_BEGIN","_KIMI_SECTION_END",+ "_LENGTH_PROGRESS_TAIL_CHARS","_LLAMA3_BARE_JSON_SENTINELS","_LLAMA3_CALL_CHAIN_RE","_LLAMA3_HEADER_ROLES",@@ -141,6 +142,7 @@"_xml_signal_inside_leading_bare_json","_xml_signal_inside_leading_mistral","annotations",+ "continue_after_length_message","has_tool_signal","is_reprompt_repeat","is_reprompt_restatement",@@ -148,11 +150,16 @@"json","parse_tool_calls_from_text","re",+ "reasoning_cap_spent_message",+ "repeated_result_message","reprompt_to_act_message",+ "starved_result_message","strip_leading_bare_json_call","strip_llama3_leading_sentinels","strip_segment",- "strip_tool_markup"+ "strip_tool_markup",+ "thinking_exhausted_message",+ "unfinished_thought_progress"],"functions": {"_balanced_brace_end": "core.tool_healing._balanced_brace_end(content: 'str', brace_start: 'int', *, gemma_quotes: 'bool' = False) -> 'int | None'",@@ -207,16 +214,22 @@"_whole_content_is_json_value": "core.inference.tool_call_parser._whole_content_is_json_value(text: 'str') -> 'bool'","_xml_signal_inside_leading_bare_json": "core.inference.tool_call_parser._xml_signal_inside_leading_bare_json(content: 'str') -> 'bool'","_xml_signal_inside_leading_mistral": "core.inference.tool_call_parser._xml_signal_inside_leading_mistral(content: 'str') -> 'bool'",+ "continue_after_length_message": "core.inference.tool_call_parser.continue_after_length_message() -> 'str'","has_tool_signal": "core.inference.tool_call_parser.has_tool_signal(text: 'str') -> 'bool'","is_reprompt_repeat": "core.inference.tool_call_parser.is_reprompt_repeat(text: 'str', previous: 'str') -> 'bool'","is_reprompt_restatement": "core.inference.tool_call_parser.is_reprompt_restatement(text: 'str', previous: 'str') -> 'bool'","is_short_intent_without_action": "core.inference.tool_call_parser.is_short_intent_without_action(text: 'str') -> 'bool'","parse_tool_calls_from_text": "core.inference.tool_call_parser.parse_tool_calls_from_text(content: 'str', *, id_offset: 'int' = 0, allow_incomplete: 'bool' = True, enabled_tool_names: 'Optional[set]' = None) -> 'list[dict]'",+ "reasoning_cap_spent_message": "core.inference.tool_call_parser.reasoning_cap_spent_message(max_tokens: 'Optional[int]' = None) -> 'str'",+ "repeated_result_message": "core.inference.tool_call_parser.repeated_result_message(tool_name: 'str', times: 'int', last_result: 'str') -> 'str'","reprompt_to_act_message": "core.inference.tool_call_parser.reprompt_to_act_message(tool_hint: 'str') -> 'str'",+ "starved_result_message": "core.inference.tool_call_parser.starved_result_message(tool_name: 'str', result: 'str') -> 'str'","strip_leading_bare_json_call": "core.inference.tool_call_parser.strip_leading_bare_json_call(text: 'str', enabled_tool_names: 'Optional[set]' = None) -> 'str'","strip_llama3_leading_sentinels": "core.inference.tool_call_parser.strip_llama3_leading_sentinels(content: 'str') -> 'str'","strip_segment": "core.inference.tool_call_parser.strip_segment(segment: 'str', *, seg_final: 'bool', enabled_tool_names: 'Optional[set]' = None) -> 'str'",- "strip_tool_markup": "core.inference.tool_call_parser.strip_tool_markup(text: 'str', *, final: 'bool' = False, enabled_tool_names: 'Optional[set]' = None) -> 'str'"+ "strip_tool_markup": "core.inference.tool_call_parser.strip_tool_markup(text: 'str', *, final: 'bool' = False, enabled_tool_names: 'Optional[set]' = None) -> 'str'",+ "thinking_exhausted_message": "core.inference.tool_call_parser.thinking_exhausted_message(context_length: 'Optional[int]' = None) -> 'str'",+ "unfinished_thought_progress": "core.inference.tool_call_parser.unfinished_thought_progress(reasoning: 'str') -> 'str'"}},"core.tool_healing": {diff --git a/studio/backend/tests/test_edit_file_tool.py b/studio/backend/tests/test_edit_file_tool.pyindex e014ed3ac90..cc811814bcf 100644--- a/studio/backend/tests/test_edit_file_tool.py+++ b/studio/backend/tests/test_edit_file_tool.py@@ -38,6 +38,20 @@ def workdir(tmp_path, monkeypatch):def _edit(**arguments) -> str:+ """Call edit_file, accepting the single-edit spelling these tests were written in.++ The tool now takes an ``edits`` array so several changes to one file cost one call+ instead of one call each. Every case below is about one edit, and what it asserts --+ matching, uniqueness, encoding, containment, receipts -- is unchanged by the batching,+ so the shape is adapted here rather than restating 50 call sites.+ """+ if "edits" not in arguments:+ edit = {+ key: arguments.pop(key)+ for key in ("old_string", "new_string", "replace_all")+ if key in arguments+ }+ arguments["edits"] = [edit]return execute_tool("edit_file", arguments, session_id = "t")@@ -414,13 +428,21 @@ class TestThirdReviewFindings:# /dev/null stats as zero bytes, so measuring size alone sent it down# the create branch, whose rename would have swapped the character# device for a regular file.+ # Spelled as `edits`, not adapted through `_edit`: this one passes+ # `disable_sandbox`, and the batched shape is what the tool now accepts. With the+ # old top-level spelling the call is refused for a missing `edits` array, which+ # also starts with "Error:" -- so the assertion below held while the device-node+ # guard was never reached.result = execute_tool("edit_file",- {"path": "/dev/null", "old_string": "", "new_string": "x\n"},+ {"path": "/dev/null", "edits": [{"old_string": "", "new_string": "x\n"}]},session_id = "t",disable_sandbox = True,)assert result.startswith("Error:")+ # The refusal the GUARD produces, not the one a malformed call produces: pinned+ # so this cannot go green again on an argument rejection.+ assert "already exists" in resultassert stat.S_ISCHR(os.stat("/dev/null").st_mode)@pytest.mark.parametrize("path,old", [("app.py", "TODO"), ("fresh.py", "")])@@ -495,7 +517,7 @@ class TestFullAccessEscapesTheWorkdir:outside.write_text("x = 1\n")result = execute_tool("edit_file",- {"path": str(outside), "old_string": "x = 1", "new_string": "x = 2"},+ {"path": str(outside), "edits": [{"old_string": "x = 1", "new_string": "x = 2"}]},session_id = "t",disable_sandbox = True,)@@ -537,7 +559,7 @@ class TestCreationLeavesNothingBehindWhenTheWriteFails:try:result = execute_tool("edit_file",- {"path": "report.py", "old_string": "", "new_string": body},+ {"path": "report.py", "edits": [{"old_string": "", "new_string": body}]},session_id = "t",)finally:@@ -552,14 +574,14 @@ class TestCreationLeavesNothingBehindWhenTheWriteFails:try:execute_tool("edit_file",- {"path": "report.py", "old_string": "", "new_string": body},+ {"path": "report.py", "edits": [{"old_string": "", "new_string": body}]},session_id = "t",)finally:self._restore(saved)retry = execute_tool("edit_file",- {"path": "report.py", "old_string": "", "new_string": body},+ {"path": "report.py", "edits": [{"old_string": "", "new_string": body}]},session_id = "t",)assert not retry.startswith("Error:")@@ -585,13 +607,18 @@ class TestCreationLeavesNothingBehindWhenTheWriteFails:return handlemonkeypatch.setattr(os, "fdopen", failing)+ # As above: the top-level spelling is refused before the write is attempted, so+ # the simulated ENOSPC and its cleanup were never exercised.result = execute_tool("edit_file",- {"path": "notes.py", "old_string": "", "new_string": "print('hi')\n"},+ {"path": "notes.py", "edits": [{"old_string": "", "new_string": "print('hi')\n"}]},session_id = "t",)monkeypatch.undo()assert result.startswith("Error:")+ assert (+ "No space left on device" in result+ ), "the write was never attempted, so the cleanup was not exercised"assert not (workdir / "notes.py").exists()def test_a_failed_create_does_not_remove_someone_elses_file(self, workdir):@@ -600,9 +627,261 @@ class TestCreationLeavesNothingBehindWhenTheWriteFails:target.write_text("x = 1\n")result = execute_tool("edit_file",- {"path": "keep.py", "old_string": "", "new_string": "y = 2\n"},+ {"path": "keep.py", "edits": [{"old_string": "", "new_string": "y = 2\n"}]},session_id = "t",)assert result.startswith("Error:")assert "already exists" in resultassert target.read_text() == "x = 1\n"+++class TestBatchedEdits:+ """Several changes to one file in one call.++ The point is token cost, not convenience: every extra call replays the whole+ conversation and leaves an assistant turn plus a tool result in the window for good.+ llama.cpp's own edit_file takes an `edits` array for the same reason.+ """++ def _edits(self, path, edits):+ return execute_tool("edit_file", {"path": path, "edits": edits}, session_id = "t")++ def test_several_edits_land_in_one_call(self, workdir):+ target = workdir / "a.py"+ target.write_text("alpha\nbeta\ngamma\n")+ result = self._edits(+ "a.py",+ [+ {"old_string": "alpha", "new_string": "A"},+ {"old_string": "gamma", "new_string": "G"},+ ],+ )+ assert target.read_text() == "A\nbeta\nG\n"+ assert "2 replacements" in result++ def test_every_old_string_matches_the_original_not_the_running_result(self, workdir):+ """The model copied each snippet out of the file it read, so that is what they match."""+ target = workdir / "a.py"+ target.write_text("one\ntwo\n")+ self._edits(+ "a.py",+ [+ {"old_string": "one", "new_string": "two"},+ {"old_string": "two", "new_string": "three"},+ ],+ )+ # The second edit takes the ORIGINAL "two", not the one the first just wrote.+ assert target.read_text() == "two\nthree\n"++ def test_one_bad_edit_writes_none_of_them(self, workdir):+ """A half-applied batch is worse than a refused one: the model cannot tell which half."""+ target = workdir / "a.py"+ target.write_text("alpha\nbeta\n")+ result = self._edits(+ "a.py",+ [+ {"old_string": "alpha", "new_string": "A"},+ {"old_string": "nowhere", "new_string": "B"},+ ],+ )+ assert result.startswith("Error:")+ assert "edit 2" in result+ assert target.read_text() == "alpha\nbeta\n"++ def test_overlapping_edits_are_refused(self, workdir):+ target = workdir / "a.py"+ target.write_text("hello world\n")+ result = self._edits(+ "a.py",+ [+ {"old_string": "hello world", "new_string": "x"},+ {"old_string": "world", "new_string": "y"},+ ],+ )+ assert result.startswith("Error:")+ assert "overlap" in result+ assert target.read_text() == "hello world\n"++ def test_an_ambiguous_entry_names_which_one(self, workdir):+ target = workdir / "a.py"+ target.write_text("v = 1\nv = 1\nkeep\n")+ result = self._edits(+ "a.py",+ [+ {"old_string": "keep", "new_string": "kept"},+ {"old_string": "v = 1", "new_string": "v = 2"},+ ],+ )+ assert "edit 2" in result+ assert "2 places" in result+ assert target.read_text() == "v = 1\nv = 1\nkeep\n"++ def test_replace_all_is_per_entry(self, workdir):+ target = workdir / "a.py"+ target.write_text("v = 1\nv = 1\nw = 1\n")+ result = self._edits(+ "a.py",+ [+ {"old_string": "v = 1", "new_string": "v = 2", "replace_all": True},+ {"old_string": "w = 1", "new_string": "w = 2"},+ ],+ )+ assert target.read_text() == "v = 2\nv = 2\nw = 2\n"+ assert "3 replacements" in result++ def test_creation_cannot_be_batched_with_edits(self, workdir):+ """An empty old_string writes the whole file, so there is nothing to edit beside it."""+ result = self._edits(+ "new.py",+ [+ {"old_string": "", "new_string": "x = 1\n"},+ {"old_string": "x", "new_string": "y"},+ ],+ )+ assert result.startswith("Error:")+ assert not (workdir / "new.py").exists()++ def test_an_empty_edits_array_says_what_to_send(self, workdir):+ (workdir / "a.py").write_text("x = 1\n")+ result = execute_tool("edit_file", {"path": "a.py", "edits": []}, session_id = "t")+ assert result.startswith("Error:")+ assert "edits" in result++ def test_a_large_replace_all_batch_stays_linear(self, workdir):+ """Rebuilding the string per replacement is quadratic; this caught that at 10s."""+ target = workdir / "big.py"+ target.write_text("v = 1\n" * 40000)+ started = time.monotonic()+ result = self._edits(+ "big.py", [{"old_string": "v = 1", "new_string": "v = 2", "replace_all": True}]+ )+ assert not result.startswith("Error:")+ assert time.monotonic() - started < 2.0+ assert target.read_text() == "v = 2\n" * 40000+++class TestBatchSize:+ """Each entry costs a full scan of a file that may be 16 MiB, so entries x size is+ the real work. Unbounded, a model-generated batch of a few thousand one-line edits+ turns one call into gigabytes of repeated scanning and holds the worker for minutes.+ """++ def test_a_batch_over_the_limit_is_refused_before_anything_is_written(self, workdir):+ from core.inference.tools import _MAX_EDITS_PER_CALL++ target = workdir / "a.py"+ target.write_text("x = 1\n", encoding = "utf-8")+ edits = [+ {"old_string": f"line{i}", "new_string": f"L{i}"}+ for i in range(_MAX_EDITS_PER_CALL + 1)+ ]++ result = _edit(path = "a.py", edits = edits)++ assert result.startswith("Error:")+ assert "over the limit" in result+ assert "nothing was written" in result+ assert target.read_text(encoding = "utf-8") == "x = 1\n"++ def test_a_batch_at_the_limit_is_still_applied(self, workdir):+ from core.inference.tools import _MAX_EDITS_PER_CALL++ target = workdir / "a.py"+ # Zero-padded and terminated: a bare "line1" is also a prefix of "line10", which+ # the tool correctly refuses as ambiguous. That is the fixture's problem, not the+ # batching's.+ target.write_text(+ "".join(f"line{i:03d}=0\n" for i in range(_MAX_EDITS_PER_CALL)),+ encoding = "utf-8",+ )+ edits = [+ {"old_string": f"line{i:03d}=0", "new_string": f"line{i:03d}=1"}+ for i in range(_MAX_EDITS_PER_CALL)+ ]++ result = _edit(path = "a.py", edits = edits)++ assert not result.startswith("Error:")+ assert "line000=1" in target.read_text(encoding = "utf-8")++ def test_a_lone_replace_all_never_enumerates_its_matches(self, workdir):+ """A single entry has nothing to overlap with, so it needs no spans.++ Enumerating cost roughly 16 million tuples plus a sort on a 16 MiB file of a+ one-character pattern. Bounding it instead would have broken the large+ replace_all cases this tool is expected to do, so the enumeration itself goes.+ """+ from core.inference.tools import _MAX_MATCH_SPANS++ target = workdir / "a.txt"+ target.write_text("a" * (_MAX_MATCH_SPANS + 5), encoding = "utf-8")++ result = _edit(path = "a.txt", old_string = "a", new_string = "b", replace_all = True)++ assert not result.startswith("Error:")+ assert target.read_text(encoding = "utf-8") == "b" * (_MAX_MATCH_SPANS + 5)++ def test_a_batched_entry_is_bounded_because_it_still_needs_spans(self, workdir):+ """Overlap detection across entries is what the spans are for, so a batch cannot+ take the lone-entry shortcut and is bounded instead."""+ from core.inference.tools import _MAX_MATCH_SPANS++ target = workdir / "a.txt"+ original = "a" * (_MAX_MATCH_SPANS + 5) + "\nZZZ\n"+ target.write_text(original, encoding = "utf-8")++ result = _edit(+ path = "a.txt",+ edits = [+ {"old_string": "a", "new_string": "b", "replace_all": True},+ {"old_string": "ZZZ", "new_string": "YYY"},+ ],+ )++ assert result.startswith("Error:")+ assert "over the limit" in result+ assert "nothing was written" in result+ assert target.read_text(encoding = "utf-8") == original++ def test_a_replace_all_within_the_bound_still_works(self, workdir):+ target = workdir / "a.txt"+ target.write_text("a b a b a", encoding = "utf-8")++ result = _edit(path = "a.txt", old_string = "a", new_string = "c", replace_all = True)++ assert not result.startswith("Error:")+ assert target.read_text(encoding = "utf-8") == "c b c b c"+++class TestEmptyPatternSafety:+ def test_a_batched_empty_old_string_is_refused_not_scanned(self, workdir):+ """The refusal is the point, and so is the speed of it.++ A zero-length pattern cannot advance `find(old, start + len(old))`, so reaching+ the span scan with one would spin rather than answer. `_edit_file` rejects it+ first; this pins that, and `_edit_file_apply_all` carries its own guard so a+ future caller cannot reintroduce the hang.+ """+ target = workdir / "f.py"+ target.write_text("hello world\n")++ result = _edit(+ path = "f.py",+ edits = [+ {"old_string": "hello", "new_string": "hi"},+ {"old_string": "", "new_string": "x", "replace_all": True},+ ],+ )++ assert "empty 'old_string'" in result+ assert target.read_text() == "hello world\n", "a refused batch wrote anyway"++ def test_the_span_scanner_refuses_an_empty_pattern_on_its_own(self):+ """Called directly, because the tool never lets one through."""+ from core.inference.tools import _edit_file_apply_all++ _after, _total, _old, _new, _at, error = _edit_file_apply_all(+ "hello world\n", [("hello", "hi", False), ("", "x", True)], "f.py"+ )++ assert "empty 'old_string'" in errordiff --git a/studio/backend/tests/test_length_truncated_reasoning_continuation.py b/studio/backend/tests/test_length_truncated_reasoning_continuation.pynew file mode 100644index 00000000000..70f3247e523--- /dev/null+++ b/studio/backend/tests/test_length_truncated_reasoning_continuation.py@@ -0,0 +1,852 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A turn that spends the whole window thinking must not surface as an empty message.++Observed on a 4096-token window: the model generated 2301 tokens, all of them reasoning,+and stopped on `finish_reason: length` -- exactly the room the prompt left. It never+reached a tool call or an answer, and because `_finalize_reasoning_only_cumulative`+refuses to promote a truncated thought (correctly -- it is not an answer), the thread+showed nothing at all. Twice, on consecutive turns.++Compaction is not the lever: there was no tool result to compact, and the prompt was only+1795 tokens of a 3072-token budget. The window went entirely on thinking, so the fix is to+resume with thinking off rather than to reclaim prompt room that was never the problem.+"""++from __future__ import annotations++import contextlib+import copy+import json+import sys+from pathlib import Path++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference.llama_cpp import (+ _CONTINUE_AFTER_LENGTH_STATUS,+ _MAX_LENGTH_CONTINUATIONS,+ LlamaCppBackend,+)++_LONG_THOUGHT = "I should write the game. " * 200+++def _sse(delta: dict) -> str:+ return "data: " + json.dumps({"choices": [{"index": 0, "delta": delta}]}) + "\n"+++def _finish(reason: str) -> str:+ return (+ "data: "+ + json.dumps({"choices": [{"index": 0, "delta": {}, "finish_reason": reason}]})+ + "\n"+ )+++def _done() -> str:+ return "data: [DONE]\n"+++def _usage(completion_tokens: int) -> str:+ return (+ "data: "+ + json.dumps(+ {+ "choices": [{"index": 0, "delta": {}}],+ "usage": {"prompt_tokens": 100, "completion_tokens": completion_tokens},+ }+ )+ + "\n"+ )+++def _make_backend(monkeypatch, streams: list[object], payloads: list[dict]):+ backend = LlamaCppBackend.__new__(LlamaCppBackend)+ backend._process = object()+ backend._healthy = True+ backend._port = 48851+ backend._api_key = None+ backend._effective_context_length = 4096+ backend._supports_reasoning = True+ backend._reasoning_always_on = False+ backend._reasoning_style = "enable_thinking"+ backend._supports_preserve_thinking = False++ @contextlib.contextmanager+ def fake_stream_with_retry(+ _client,+ _url,+ payload,+ _cancel_event,+ headers = None,+ first_token_deadline = None,+ ):+ payloads.append(copy.deepcopy(payload))+ stream = streams.pop(0)+ yield type("FakeResponse", (), {"status_code": 200, "chunks": stream})()++ def fake_iter_text_cancellable(+ response,+ _cancel_event,+ first_token_deadline = None,+ ):+ yield from response.chunks++ monkeypatch.setattr(backend, "_stream_with_retry", fake_stream_with_retry)+ monkeypatch.setattr(backend, "_iter_text_cancellable", fake_iter_text_cancellable)+ monkeypatch.setattr(backend, "_maybe_recover_from_mtp_crash", lambda *_a, **_k: False)+ return backend+++_WEB_SEARCH_TOOL = {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web.",+ "parameters": {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ },+ },+}+++def _run(backend, **kwargs):+ kwargs.setdefault("max_tool_iterations", 3)+ return list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "Create a Flappy Bird game in HTML"}],+ tools = [_WEB_SEARCH_TOOL],+ enable_thinking = True,+ **kwargs,+ )+ )+++def _texts(events, kind: str) -> list[str]:+ return [event["text"] for event in events if event.get("type") == kind]+++def _run_no_tools(backend, **kwargs):+ """Drives the FINAL generation, the pass taken once the tool loop is done."""+ return list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "Create a Flappy Bird game in HTML"}],+ tools = [],+ max_tool_iterations = 0,+ enable_thinking = True,+ **kwargs,+ )+ )+++def _truncated_thought_then(*later: list[str]) -> list[list[str]]:+ return [+ [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()],+ *later,+ ]+++def test_a_thought_that_filled_the_window_is_continued_not_abandoned(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _truncated_thought_then([_sse({"content": "Here is the game."}), _done()]),+ payloads,+ )++ events = _run(backend)++ assert len(payloads) == 2, "the turn was abandoned instead of continued"+ assert "Here is the game." in "".join(_texts(events, "content"))+++def test_the_continuation_turns_thinking_off(monkeypatch):+ """Retrying with thinking on just re-runs the turn that failed."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _truncated_thought_then([_sse({"content": "Here is the game."}), _done()]),+ payloads,+ )++ _run(backend)++ assert payloads[0]["chat_template_kwargs"]["enable_thinking"] is True+ assert payloads[1]["chat_template_kwargs"]["enable_thinking"] is False+++def test_the_continuation_carries_progress_without_replaying_the_whole_thought(monkeypatch):+ """Putting the thought back reproduces the ending that made it necessary."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _truncated_thought_then([_sse({"content": "Here is the game."}), _done()]),+ payloads,+ )++ _run(backend)++ resumed = json.dumps(payloads[1]["messages"])+ assert "Where I had got to:" in resumed+ assert "ran out of room while thinking" in resumed+ assert len(resumed) < len(_LONG_THOUGHT), "the whole thought was replayed"+++def test_the_retry_is_announced_so_the_ui_is_not_a_hang(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _truncated_thought_then([_sse({"content": "Here is the game."}), _done()]),+ payloads,+ )++ statuses = _texts(_run(backend), "status")++ assert _CONTINUE_AFTER_LENGTH_STATUS in statuses+ index = statuses.index(_CONTINUE_AFTER_LENGTH_STATUS)+ # Blank first: the route resets its text cursor only on an empty status.+ assert index > 0 and statuses[index - 1] == ""+++def test_continuation_is_capped_so_a_small_window_cannot_loop(monkeypatch):+ """If thinking-off still produces nothing, the window is too small. Stop trying."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()]+ for _ in range(_MAX_LENGTH_CONTINUATIONS + 3)+ ],+ payloads,+ )++ _run(backend)++ assert len(payloads) == _MAX_LENGTH_CONTINUATIONS + 1+++def test_giving_up_says_so_instead_of_returning_an_empty_turn(monkeypatch):+ """Returning silently IS the original defect, so the give-up path must not repeat it.++ Mirrors the advice hermes-agent gives from `_thinking_exhausted` and Codex gives for+ the same symptom: name the lever (effort, window, task size) rather than show nothing.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()]+ for _ in range(_MAX_LENGTH_CONTINUATIONS + 2)+ ],+ payloads,+ )++ content = "".join(_texts(_run(backend), "content"))++ assert "reasoning" in content+ assert "4096-token window" in content+ assert "Lower the reasoning effort" in content+++def test_a_good_tool_round_restores_the_full_allowance(monkeypatch):+ """NousResearch/hermes-agent#79100: a surviving counter gives a later stall fewer tries.++ Stall, continue, run a tool, then stall again. The second stall is a new problem and+ is entitled to the same allowance the first one had.+ """++ payloads: list[dict] = []+ _truncated = [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()]+ _calls_a_tool = [+ _sse(+ {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_0",+ "function": {"name": "web_search", "arguments": '{"query":"x"}'},+ }+ ]+ }+ ),+ _done(),+ ]+ backend = _make_backend(+ monkeypatch,+ [_truncated, _calls_a_tool, _truncated, _truncated, _truncated],+ payloads,+ )+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: "results")++ _run(backend, max_tool_iterations = 8)++ # 1 stall + 1 continuation that called the tool + 3 more turns once the tool round+ # reset the allowance. A counter that survived would have stopped an attempt earlier.+ assert len(payloads) == 5+++def test_thinking_comes_back_on_after_a_good_tool_round(monkeypatch):+ """It was turned off to break one stall, not for the rest of the request."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()],+ [+ _sse(+ {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_0",+ "function": {+ "name": "web_search",+ "arguments": '{"query":"x"}',+ },+ }+ ]+ }+ ),+ _done(),+ ],+ [_sse({"content": "Done."}), _done()],+ ],+ payloads,+ )+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: "results")++ _run(backend, max_tool_iterations = 8)++ assert payloads[1]["chat_template_kwargs"]["enable_thinking"] is False+ assert payloads[2]["chat_template_kwargs"]["enable_thinking"] is True+++def test_a_turn_that_answers_is_handled_as_an_answer_not_a_stalled_thought(monkeypatch):+ """The trigger for THIS path is an EMPTY length stop, not any length stop.++ Retargeted rather than deleted. It used to assert that a turn producing content was+ never continued at all, which was true when the stalled-thought path was the only one.+ A truncated ANSWER is now continued too, by the sibling path in+ `test_truncated_answer_continuation.py`, and the distinction that still matters is+ which one takes it: resuming an answer must not switch thinking off, because thinking+ was never the problem, and must extend the partial rather than start a fresh turn.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [+ _sse({"reasoning_content": "Briefly."}),+ _sse({"content": "The first half of the answer"}),+ _finish("length"),+ _done(),+ ],+ [_sse({"content": " and the second half."}), _done()],+ ],+ payloads,+ )++ events = _run(backend)++ assert len(payloads) == 2+ assert payloads[1].get("continue_final_message") is True+ assert payloads[1]["chat_template_kwargs"]["enable_thinking"] is True+ assert "The first half of the answer" in "".join(_texts(events, "content"))+++def test_a_clean_reasoning_only_stop_is_left_alone(monkeypatch):+ """A thought that ENDED is promoted as the answer; only a cut-off one is resumed."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_sse({"reasoning_content": "The answer is 4."}), _finish("stop"), _done()]],+ payloads,+ )++ _run(backend)++ assert len(payloads) == 1+++def test_the_final_pass_continues_a_reasoning_only_stop(monkeypatch):+ """The in-loop continuation cannot reach this pass, which runs after the loop breaks.++ A turn that spends its last permitted tool call, or a one-shot tool that sets+ `force_final_answer`, produces its answer here. If that generation spends the window+ thinking, the user gets an empty message and no indication anything went wrong: the+ exact failure the in-loop continuation exists to prevent, on the path it does not+ cover.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()],+ [_sse({"content": "Here is the answer."}), _done()],+ ],+ payloads,+ )++ events = _run_no_tools(backend)++ assert len(payloads) == 2, "the final pass returned an empty message"+ assert payloads[1]["messages"][-1]["role"] == "user"+ assert payloads[1]["chat_template_kwargs"] == {"enable_thinking": False}+ assert "Here is the answer." in "".join(_texts(events, "content"))+++def test_the_final_pass_says_so_when_thinking_never_converges(monkeypatch):+ """Giving up silently is the original defect. The user needs something to act on."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()]+ for _ in range(_MAX_LENGTH_CONTINUATIONS + 2)+ ],+ payloads,+ )++ events = _run_no_tools(backend)++ assert len(payloads) == _MAX_LENGTH_CONTINUATIONS + 1+ assert "".join(_texts(events, "content")).strip(), "the turn ended showing nothing"+++def test_a_final_pass_that_answers_is_left_alone(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [+ _sse({"reasoning_content": _LONG_THOUGHT}),+ _sse({"content": "Done."}),+ _finish("stop"),+ _done(),+ ]+ ],+ payloads,+ )++ _run_no_tools(backend)++ assert len(payloads) == 1+++def _effort_backend(monkeypatch, streams, payloads):+ backend = _make_backend(monkeypatch, streams, payloads)+ backend._supports_reasoning = True+ backend._reasoning_style = "reasoning_effort"+ return backend+++def test_an_explicit_effort_does_not_survive_the_continuation(monkeypatch):+ """For this style an explicit effort WINS over enable_thinking.++ `_request_reasoning_kwargs` returns the caller's "high" and never reaches the+ enable_thinking branch, so turning thinking off for the retry changed nothing that+ llama-server could see and the retry re-ran the turn that had just spent the whole+ window thinking. The second failure then looked identical to the first.+ """++ payloads: list[dict] = []+ backend = _effort_backend(+ monkeypatch,+ _truncated_thought_then([_sse({"content": "Here is the game."}), _done()]),+ payloads,+ )++ _run(backend, reasoning_effort = "high")++ assert payloads[0]["chat_template_kwargs"] == {"reasoning_effort": "high"}+ # "low", not "none": this style covers models that cannot actually disable+ # reasoning, and that is the convention the non-continuation path already uses.+ assert payloads[1]["chat_template_kwargs"] == {"reasoning_effort": "low"}+++def test_the_caller_effort_comes_back_once_a_turn_gets_somewhere(monkeypatch):+ """It was dropped to break ONE stall, not for the rest of the request."""++ payloads: list[dict] = []+ backend = _effort_backend(+ monkeypatch,+ [+ [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()],+ [+ _sse(+ {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_0",+ "type": "function",+ "function": {+ "name": "web_search",+ "arguments": json.dumps({"query": "flappy bird"}),+ },+ }+ ]+ }+ ),+ _done(),+ ],+ [_sse({"content": "Here is the game."}), _done()],+ ],+ payloads,+ )++ monkeypatch.setattr(+ "core.inference.tools.execute_tool",+ lambda name, arguments, **_kwargs: "a result",+ )++ _run(backend, reasoning_effort = "high")++ assert payloads[1]["chat_template_kwargs"] == {"reasoning_effort": "low"}+ assert payloads[2]["chat_template_kwargs"] == {"reasoning_effort": "high"}+++def _tool_call_sse(index: int) -> str:+ return _sse(+ {+ "tool_calls": [+ {+ "index": 0,+ "id": f"call_{index}",+ "type": "function",+ "function": {+ "name": "web_search",+ "arguments": json.dumps({"query": f"q{index}"}),+ },+ }+ ]+ }+ )+++def test_a_request_that_never_stalls_keeps_the_bound_it_always_had(monkeypatch):+ """The credit is granted as continuations happen, not reserved up front.++ The loop bound moved from a `range(...)` to an explicit counter to make room for+ them. A request with no stall must be unaffected by that: same number of model+ calls, same tool budget, nothing extra.+ """++ streams = [[_tool_call_sse(i), _done()] for i in range(6)]+ streams.append([_sse({"content": "Done."}), _done()])+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ monkeypatch.setattr(+ "core.inference.tools.execute_tool",+ lambda name, arguments, **_kwargs: "a result",+ )++ _run(backend, max_tool_iterations = 3)++ # Three tool rounds, then the tool-free final pass. Unchanged by the conversion.+ assert len(payloads) == 4+++def test_a_stall_does_not_eat_the_tool_budget(monkeypatch):+ """The defect the credit exists for: at a small budget the retries spent it all.++ Codex's scenario, built literally. `max_tool_iterations=1` and `MAX_ACT_REPROMPTS=3`+ give the loop five slots. Three plan-without-action turns take three of them, two+ truncated reasoning turns take the other two, and the model has still not issued its+ call: control falls through to the tool-free final pass and the action the user asked+ for is never performed, though no real tool iteration was ever spent.+ """++ streams = [+ # Short, with an intent signal and no tool call: each earns a re-prompt. Distinct,+ # because a nudge that gets the same answer back stops the sequence.+ [_sse({"content": "I will search for the prices now."}), _done()],+ [_sse({"content": "I am going to look that up for you."}), _done()],+ [_sse({"content": "Let me check the current listings."}), _done()],+ [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()],+ [_sse({"reasoning_content": _LONG_THOUGHT + " more"}), _finish("length"), _done()],+ [_tool_call_sse(0), _done()],+ [_sse({"content": "Done."}), _done()],+ ]+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ calls: list[str] = []++ def _execute(name, arguments, **_kwargs):+ calls.append(name)+ return "a result"++ monkeypatch.setattr("core.inference.tools.execute_tool", _execute)++ _run(backend, max_tool_iterations = 1, nudge_tool_calls = True)++ assert calls == ["web_search"], "the stall spent the one tool iteration"+++def test_the_final_pass_blames_the_cap_when_the_cap_is_what_was_spent(monkeypatch):+ """The in-loop give-up already told these two walls apart; this pass did not.++ A caller-set Max Tokens smaller than the window leaves no remainder to continue with,+ so the final pass gives up here. Naming the CONTEXT window then sends the user to+ raise the one setting that was never the constraint, and this text reaches the client+ as ordinary content, so nothing downstream can correct it.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()]],+ payloads,+ )++ events = _run_no_tools(backend, max_tokens = 200)++ assert len(payloads) == 1, "a spent cap has nothing left to continue with"+ text = "".join(_texts(events, "content"))+ assert "output allowance of 200 tokens" in text+ assert "window on reasoning" not in text+++def test_the_final_pass_still_blames_the_window_when_no_cap_was_set(monkeypatch):+ """The other side of the same fork, so the fix above cannot swallow the window case."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()]+ for _ in range(_MAX_LENGTH_CONTINUATIONS + 2)+ ],+ payloads,+ )++ events = _run_no_tools(backend)++ text = "".join(_texts(events, "content"))+ assert "4096-token window on reasoning" in text+ assert "output allowance" not in text+++def test_the_final_pass_retry_is_admitted_under_the_kwargs_it_will_be_sent_with(monkeypatch):+ """Admission has to price the prompt that is actually about to be sent.++ The retry goes out with thinking OFF, which renders a different prompt from the+ thinking-on kwargs the turn started with. Counting the candidate under the original+ kwargs measures a prompt nobody sends: it refuses a retry that would have fit, or+ admits one llama-server then rejects.+ """++ seen: list[object] = []+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"reasoning_content": _LONG_THOUGHT}), _finish("length"), _done()],+ [_sse({"content": "Here is the answer."}), _done()],+ ],+ payloads,+ )++ real_count = backend.count_chat_tokens++ def recording_count(*args, **kwargs):+ seen.append(kwargs.get("chat_template_kwargs"))+ return real_count(*args, **kwargs)++ monkeypatch.setattr(backend, "count_chat_tokens", recording_count)++ events = _run_no_tools(backend)++ assert len(payloads) == 2, "the retry was refused"+ assert payloads[1]["chat_template_kwargs"] == {"enable_thinking": False}+ assert {+ "enable_thinking": False+ } in seen, "the retry was admitted under kwargs it is not sent with"+ assert "Here is the answer." in "".join(_texts(events, "content"))+++def test_the_in_loop_retry_is_admitted_under_the_kwargs_it_will_be_sent_with(monkeypatch):+ """The final pass got this right; the in-loop path, which is the one a request with+ tools actually takes, still admitted the retry under the previous attempt's kwargs.++ `_reasoning_kw` is computed once at the top of each iteration, with thinking on. The+ retry goes out with it off, a different rendered prompt on any template that reads+ `enable_thinking`, so the admission priced a request nobody sends.+ """++ seen: list[object] = []+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _truncated_thought_then([_sse({"content": "Done."}), _done()]),+ payloads,+ )++ real_count = backend.count_chat_tokens++ def recording_count(*args, **kwargs):+ seen.append(kwargs.get("chat_template_kwargs"))+ return real_count(*args, **kwargs)++ monkeypatch.setattr(backend, "count_chat_tokens", recording_count)++ _run(backend)++ assert len(payloads) == 2, "the retry was refused"+ assert payloads[1]["chat_template_kwargs"] == {"enable_thinking": False}+ assert {+ "enable_thinking": False+ } in seen, "the retry was admitted under kwargs it is not sent with"+++def test_the_in_loop_give_up_names_the_cap_when_the_last_attempt_spent_it(monkeypatch):+ """`_reasoning_cap_spent` is only set when a continuation is REFUSED.++ Reaching the give-up by exhausting the retry limit instead leaves it at its default,+ so a turn whose last permitted attempt finished off an explicit Max Tokens was told+ to raise the Context Length.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [+ _sse({"reasoning_content": _LONG_THOUGHT}),+ _usage(100),+ _finish("length"),+ _done(),+ ]+ for _ in range(_MAX_LENGTH_CONTINUATIONS + 2)+ ],+ payloads,+ )++ # 300 spent 100 at a time: every continuation is ADMITTED, and the cap runs out on+ # the last permitted attempt. That is the stale case -- reaching the give-up by way+ # of a refusal already sets the flag correctly.+ events = _run(backend, max_tokens = 300)++ assert len(payloads) == _MAX_LENGTH_CONTINUATIONS + 1, "a continuation was refused"+ text = "".join(_texts(events, "content"))+ assert "output allowance of 300 tokens" in text+ assert "window on reasoning" not in text+++def test_a_continuation_one_eviction_short_is_not_abandoned(monkeypatch):+ """Refusing here ends the turn, so the next iteration's preflight never runs.++ The single-turn case the check was written for really does have nothing left to+ evict. A multi-turn chat under `truncate_oldest` usually does, and abandoning it+ there throws away a recoverable answer rather than dropping one old exchange.++ The gap is `prompt_budget` against the continuation's own floor: with a small+ `max_tokens` the preflight fits the chat to 3996 of a 4096 window, while the retry+ needs 3840 or less. The fit succeeded and the continuation is still unservable.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"reasoning_content": _LONG_THOUGHT}), _usage(20), _finish("length"), _done()],+ [_sse({"content": "Done."}), _usage(10), _done()],+ ],+ payloads,+ )++ # A tokenizer this harness can actually run: llama-server is not here to render a+ # template, and the real count raises, which every fit reads as "cannot judge".+ def fake_count(messages, *_args, **_kwargs):+ return 200 + sum(len(str(m.get("content") or "")) // 4 for m in messages)++ monkeypatch.setattr(backend, "count_chat_tokens", fake_count)++ old_turns: list[dict] = []+ for index in range(30):+ old_turns.append({"role": "user", "content": f"Question {index}. " + "x" * 600})+ old_turns.append({"role": "assistant", "content": f"Answer {index}. " + "y" * 600})++ events = list(+ backend.generate_chat_completion_with_tools(+ messages = [*old_turns, {"role": "user", "content": "Create a Flappy Bird game"}],+ tools = [_WEB_SEARCH_TOOL],+ enable_thinking = True,+ max_tool_iterations = 3,+ max_tokens = 100,+ context_overflow = "truncate_oldest",+ )+ )++ assert len(payloads) == 2, "the continuation was abandoned instead of making room"+ assert "Done." in "".join(_texts(events, "content"))+++def test_a_continuation_is_sized_by_what_is_left_of_the_cap(monkeypatch):+ """`prompt_budget` shrinks as `max_tokens` grows, so the two must agree.++ The remainder was applied to the payload only AFTER the preflight had already fitted+ the chat against the caller's original cap. A continuation with 100 of 1000 tokens+ left was therefore priced as if it could still emit 1000, and under+ `truncate_oldest` that evicts history the request never needed to lose.+ """++ targets: list[int] = []+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": "Half an answer"}), _usage(900), _finish("length"), _done()],+ [_sse({"content": " and the rest."}), _usage(50), _done()],+ ],+ payloads,+ )++ import core.inference.llama_cpp as _lc # noqa: PLC0415++ real_budget = _lc.prompt_budget++ def recording_budget(context_length, max_tokens):+ targets.append(max_tokens)+ return real_budget(context_length, max_tokens)++ monkeypatch.setattr(_lc, "prompt_budget", recording_budget)++ def fake_count(messages, *_args, **_kwargs):+ return 200 + sum(len(str(m.get("content") or "")) // 4 for m in messages)++ monkeypatch.setattr(backend, "count_chat_tokens", fake_count)++ old_turns: list[dict] = []+ for index in range(8):+ old_turns.append({"role": "user", "content": f"Question {index}. " + "x" * 600})+ old_turns.append({"role": "assistant", "content": f"Answer {index}. " + "y" * 600})++ list(+ backend.generate_chat_completion_with_tools(+ messages = [*old_turns, {"role": "user", "content": "Show me the HTML inline"}],+ tools = [_WEB_SEARCH_TOOL],+ max_tool_iterations = 3,+ max_tokens = 1000,+ context_overflow = "truncate_oldest",+ )+ )++ assert len(payloads) == 2, "the answer was not continued"+ assert payloads[1]["max_tokens"] == 100, "the payload did not get the remainder"+ assert 100 in targets, f"every sizing decision still used the whole cap: {sorted(set(targets))}"diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.pyindex 0d0bbbf3af6..aae6df8da6a 100644--- a/studio/backend/tests/test_llama_cpp_tool_loop.py+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py@@ -6313,3 +6313,415 @@ def test_the_exact_recall_budget_is_recomputed_after_an_intervening_tool(monkeyp# The 12,000-character tool result is roughly 1,200 tokens of the 3,584-token budget,# and the count taken before it cannot see them.assert budgets[0] < 1400, budgets+++def _count_from_size(messages, *_args, **_kwargs):+ """Stand in for the tokenizer, priced the way a real chat template prices.++ Two behaviours the fake has to keep or the tests pass while the gate is blind:++ 1. The size FALLS when the conversation shrinks, so re-pricing after a compaction is+ distinguishable from the attempt before it.+ 2. An assistant turn's `tool_calls` cost NOTHING until a `tool` message answers them.+ Qwen3.8's template renders them only then, which is what made the first version of+ this gate useless: measured on the conversation as it stood, a 40 KB argument was+ invisible, the turn priced at 1,063 tokens against a 4,096 window, and the tool ran+ into a request that came back 400. A counter that charges for unanswered arguments+ cannot catch that regression.+ """+ answered = {+ str(message.get("tool_call_id"))+ for message in messages+ if message.get("role") == "tool" and message.get("tool_call_id")+ }+ billed = []+ for message in messages:+ calls = message.get("tool_calls")+ if message.get("role") == "assistant" and calls:+ visible = [call for call in calls if str(call.get("id")) in answered]+ billed.append({**message, "tool_calls": visible})+ else:+ billed.append(message)+ return len(json.dumps(billed, default = str)) // 4+++def test_an_unservable_tool_call_is_refused_before_it_runs(monkeypatch):+ """The write must not land on a turn llama-server is going to reject anyway.++ The model's own arguments are already in the conversation by the time the tool is+ invoked, so a whole-file `edit_file` can put the prompt over the window before the+ tool has returned anything. `tool_result_budget` clamps to zero there and the+ truncation reads that as "cut hard", so the tool used to run, the result was cut to+ its notice, and the next request was refused with the file written.+ """+ # The bulk is in the USER turn, which no receipt can replace, so running the call and+ # compacting its arguments cannot rescue this one either -- which is what makes it the+ # case that still earns a refusal.+ immovable = "please read all of this: " + "u" * 40000+ streams = [+ _structured_tool_call(+ "edit_file",+ {"path": "flappy-bird.html", "edits": [{"old_string": "", "new_string": "x" * 2000}]},+ "call_write_game",+ ),+ [_sse({"content": "Understood."}), _done()],+ ]+ backend = _make_backend(monkeypatch, streams, [])+ monkeypatch.setattr(backend, "count_chat_tokens", _count_from_size)++ executed: list[str] = []++ def fake_execute_tool(name, _arguments, **_kwargs):+ executed.append(name)+ return "wrote the file"++ monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)++ events = list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": immovable}],+ tools = [{"type": "function", "function": {"name": "edit_file"}}],+ max_tokens = 512,+ max_tool_iterations = 2,+ )+ )++ assert executed == [], "the side effect was spent on an unservable turn"+ refusals = [+ event+ for event in events+ if event.get("type") == "tool_end" and "Nothing was written" in str(event.get("result", ""))+ ]+ assert refusals, [e.get("type") for e in events]+ assert "edit_file" in refusals[0]["result"]+++def test_compacting_an_earlier_call_lets_the_next_one_run(monkeypatch):+ """The first lever, before refusing: arguments of a call that already returned.++ They are pure replay -- the tool received them in full and the file is on disk -- so+ spending them is what keeps a thread alive that would otherwise dead-end.+ """+ earlier = "<!DOCTYPE html>" + "y" * 30000+ prior_call = {+ "id": "call_earlier",+ "type": "function",+ "function": {+ "name": "edit_file",+ "arguments": json.dumps({"path": "page.html", "old_string": "", "new_string": earlier}),+ },+ }+ history = [+ {"role": "user", "content": "Write page.html"},+ {"role": "assistant", "content": "Writing.", "tool_calls": [prior_call]},+ {+ "role": "tool",+ "tool_call_id": "call_earlier",+ "name": "edit_file",+ "content": "Wrote page.html",+ },+ {"role": "user", "content": "Now fix the title"},+ ]+ streams = [+ _structured_tool_call(+ "edit_file",+ {+ "path": "page.html",+ "old_string": "<title>a</title>",+ "new_string": "<title>b</title>",+ },+ "call_fix_title",+ ),+ [_sse({"content": "Fixed."}), _done()],+ ]+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ monkeypatch.setattr(backend, "count_chat_tokens", _count_from_size)++ executed: list[str] = []++ def fake_execute_tool(name, arguments, **_kwargs):+ executed.append(name)+ # The tool still receives real arguments, never a receipt.+ assert arguments.get("new_string") == "<title>b</title>"+ return "Edited page.html"++ monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)++ events = list(+ backend.generate_chat_completion_with_tools(+ messages = history,+ tools = [{"type": "function", "function": {"name": "edit_file"}}],+ max_tokens = 512,+ max_tool_iterations = 2,+ )+ )++ assert executed == ["edit_file"], [e.get("type") for e in events]+ assert not [+ event+ for event in events+ if event.get("type") == "tool_end" and "Nothing was written" in str(event.get("result", ""))+ ]+ # The assertions above hold with no gate at all -- an ungated loop runs every tool it+ # is handed. What distinguishes the fix is the prompt SENT after the tool returned:+ # the earlier call's 30 KB argument must have become a receipt, and only there.+ assert len(payloads) >= 2, "the loop never made a second request"+ replayed = json.dumps(payloads[-1]["messages"], default = str)+ assert earlier not in replayed, "the earlier 30 KB argument was replayed verbatim"+ assert "arguments you sent" in replayed+ assert "page.html" in replayed+++def test_refusing_a_call_also_stops_it_costing_the_window(monkeypatch):+ """Observed live: an accurate refusal, then the 400 it was issued to prevent.++ The refusal is a `tool` message, and a chat template renders an assistant turn's+ `tool_calls` only once one of those answers them. So declining to run the tool is the+ very thing that makes its arguments start costing the prompt, and the generation that+ follows is rejected anyway -- with nothing written, but also nothing the user can do.+ The refused arguments are the one case with no replay value at all.+ """+ # Again the bulk is immovable: a refusal is the only outcome left, and the point here+ # is that refusing must not ALSO leave the arguments costing the window.+ immovable = "please read all of this: " + "u" * 40000+ oversized = "<!DOCTYPE html>" + "x" * 8000+ streams = [+ _structured_tool_call(+ "edit_file",+ {"path": "flappy-bird.html", "edits": [{"old_string": "", "new_string": oversized}]},+ "call_write_game",+ ),+ [_sse({"content": "I could not write that file."}), _done()],+ ]+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ monkeypatch.setattr(backend, "count_chat_tokens", _count_from_size)++ executed: list[str] = []+ monkeypatch.setattr(+ "core.inference.tools.execute_tool",+ lambda name, _arguments, **_kwargs: executed.append(name) or "wrote it",+ )++ list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": immovable}],+ tools = [{"type": "function", "function": {"name": "edit_file"}}],+ max_tokens = 512,+ max_tool_iterations = 2,+ )+ )++ assert executed == []+ assert len(payloads) >= 2, "the loop never got to a follow-up generation"+ replayed = json.dumps(payloads[-1]["messages"], default = str)+ # The prompt that follows the refusal must not carry what was refused.+ assert oversized not in replayed+ assert "refused before it ran" in replayed+ # And must not claim a file exists to go and read.+ assert "re-read the file" not in replayed+++def test_reply_room_is_reclaimed_before_generating(monkeypatch):+ """A prompt that FITS can still leave nothing to answer in.++ Observed on a 4096 window: every tool call servable, none refused, the file written,+ and the turn ended on `finish_reason: length` with the model still thinking -- the+ prompt had eaten the room its answer needed. The pre-execution gate never fired+ because nothing was ever unservable, so compaction, the exact lever for this, was+ never asked to run.+ """+ bulky = "<!DOCTYPE html>" + "z" * 30000+ prior_call = {+ "id": "call_done",+ "type": "function",+ "function": {+ "name": "edit_file",+ "arguments": json.dumps(+ {"path": "game.html", "edits": [{"old_string": "", "new_string": bulky}]}+ ),+ },+ }+ history = [+ {"role": "user", "content": "Write game.html"},+ {"role": "assistant", "content": "Writing.", "tool_calls": [prior_call]},+ {+ "role": "tool",+ "tool_call_id": "call_done",+ "name": "edit_file",+ "content": "Created game.html",+ },+ {"role": "user", "content": "Now tell me what you did"},+ ]+ payloads: list[dict] = []+ # No tool call this turn: the model just answers, so only the reply-room pass can act.+ backend = _make_backend(monkeypatch, [[_sse({"content": "Done."}), _done()]], payloads)+ monkeypatch.setattr(backend, "count_chat_tokens", _count_from_size)+ monkeypatch.setattr(+ "core.inference.tools.execute_tool",+ lambda *_a, **_k: "should not run",+ )++ list(+ backend.generate_chat_completion_with_tools(+ messages = history,+ tools = [{"type": "function", "function": {"name": "edit_file"}}],+ max_tokens = 512,+ max_tool_iterations = 1,+ )+ )++ assert payloads, "no generation request was made"+ sent = json.dumps(payloads[0]["messages"], default = str)+ assert bulky not in sent, "the finished call's 30 KB argument was still replayed"+ assert "arguments you sent" in sent+++def test_an_oversized_call_is_run_and_compacted_rather_than_refused(monkeypatch):+ """Refusing costs the same tokens as running, and leaves nothing written.++ The refusal is itself the `tool` message that makes the arguments render, so declining+ does not avoid their cost. The model then retries with a fresh oversized call and each+ round reclaims less -- 50%, then 34%, then 15% of one measured thread, ending in a+ one-character reply. Running the call needs no context at all; only the next prompt+ does, and by then the arguments describe a file on disk.+ """+ oversized = "<!DOCTYPE html>" + "x" * 24000+ streams = [+ _structured_tool_call(+ "edit_file",+ {"path": "flappy-bird.html", "edits": [{"old_string": "", "new_string": oversized}]},+ "call_write_game",+ ),+ [_sse({"content": "Wrote the game."}), _done()],+ ]+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ monkeypatch.setattr(backend, "count_chat_tokens", _count_from_size)++ executed: list[str] = []++ def fake_execute_tool(name, arguments, **_kwargs):+ executed.append(name)+ # The tool still receives the real content -- the file must actually be written.+ assert oversized in json.dumps(arguments)+ return "Created flappy-bird.html"++ monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)++ events = list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "Create a Flappy Bird game in HTML"}],+ tools = [{"type": "function", "function": {"name": "edit_file"}}],+ max_tokens = 512,+ max_tool_iterations = 2,+ )+ )++ assert executed == ["edit_file"], "the call was refused instead of run"+ assert not [+ e+ for e in events+ if e.get("type") == "tool_end" and "Nothing was written" in str(e.get("result", ""))+ ]+ assert len(payloads) >= 2, "no follow-up generation was made"+ replayed = json.dumps(payloads[-1]["messages"], default = str)+ assert oversized not in replayed, "the arguments were replayed after the call ran"+ assert "arguments you sent" in replayed+++_BIG_BODY = "<!DOCTYPE html>" + "x" * 9000+++def _two_edits_in_one_turn():+ return [+ _sse(+ {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_big",+ "type": "function",+ "function": {+ "name": "edit_file",+ "arguments": json.dumps(+ {+ "path": "game.html",+ "old_string": "",+ "new_string": _BIG_BODY,+ }+ ),+ },+ },+ {+ "index": 1,+ "id": "call_small",+ "type": "function",+ "function": {+ "name": "edit_file",+ "arguments": json.dumps(+ {+ "path": "game.html",+ "old_string": "TODO",+ "new_string": "done",+ }+ ),+ },+ },+ ]+ }+ ),+ _done(),+ ]+++def test_a_second_call_in_a_compacted_turn_is_still_visible_to_the_model(monkeypatch):+ """Compaction rebuilds the messages, which silently detaches the local handle.++ The run-then-compact rescue rewrites `conversation` in place. The loop was still+ holding the assistant message it built BEFORE that, so the next call in the same+ batch appended its `tool_call` to a dict no longer in the list while its RESULT was+ appended to the list. The model then received a `tool` message answering a call it+ could not see, which some templates reject outright and the rest render as an+ unexplained result.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [_two_edits_in_one_turn(), [_sse({"content": "Done."}), _done()]],+ payloads,+ )++ # Price the turn off the replayed JSON: the big call does not fit, the receipt does.+ def fake_count_chat_tokens(messages, *_args, **_kwargs):+ return len(json.dumps(messages, default = str)) // 2++ monkeypatch.setattr(backend, "count_chat_tokens", fake_count_chat_tokens)+ monkeypatch.setattr(+ "core.inference.tools.execute_tool",+ lambda name, arguments, **_kwargs: "Wrote game.html",+ )++ list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "Write the game"}],+ tools = [{"type": "function", "function": {"name": "edit_file"}}],+ max_tool_iterations = 4,+ )+ )++ sent = payloads[-1]["messages"]+ announced = {+ call.get("id")+ for message in sent+ if message.get("role") == "assistant"+ for call in (message.get("tool_calls") or [])+ }+ answered = {message.get("tool_call_id") for message in sent if message.get("role") == "tool"}++ assert answered, "no tool result reached the model at all"+ assert answered <= announced, f"results with no visible call: {answered - announced}"+ # And the compaction still happened: the body is not replayed.+ assert _BIG_BODY not in json.dumps(sent)diff --git a/studio/backend/tests/test_no_progress_tool_results.py b/studio/backend/tests/test_no_progress_tool_results.pynew file mode 100644index 00000000000..d82d3d79e4c--- /dev/null+++ b/studio/backend/tests/test_no_progress_tool_results.py@@ -0,0 +1,536 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A tool that keeps returning the same answer must not be allowed to eat the turn.++Observed at a 4096 window, asked to show a 2401-byte file inline. `tool_result_budget`+collapsed to zero, so every read returned only the notice saying it had been cut:++ tool result: name=terminal budget_tokens=0 chars=109 (six of the last eight)++The model read that as a fresh failure and tried again, varying the line range each time,+for eighteen calls. Two things were missing. The budget was never rescued, though room is+exactly what compaction reclaims; and nothing noticed that the answer had stopped changing.++The guard is keyed on the RESULT, not the arguments, which is the whole point here: the+arguments differed on every one of those calls. OpenClaw's tool-loop detection keys on the+result for the same reason, and stays quiet while results are still changing so that+legitimate polling is untouched.+"""++from __future__ import annotations++import contextlib+import copy+import json+import sys+from pathlib import Path++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++import core.inference.llama_cpp as llama_cpp_module+from core.inference.llama_cpp import _MAX_IDENTICAL_TOOL_RESULTS, LlamaCppBackend++_TRUNCATION_NOTICE = "(truncated to 0 chars for the model; showing lines 1-11 of 63.)"+++def _finish(reason: str) -> str:+ return (+ "data: "+ + json.dumps({"choices": [{"index": 0, "delta": {}, "finish_reason": reason}]})+ + "\n"+ )+++def _usage(completion_tokens: int) -> str:+ return (+ "data: "+ + json.dumps(+ {+ "choices": [{"index": 0, "delta": {}}],+ "usage": {"prompt_tokens": 100, "completion_tokens": completion_tokens},+ }+ )+ + "\n"+ )+++def _sse(delta: dict) -> str:+ return "data: " + json.dumps({"choices": [{"index": 0, "delta": delta}]}) + "\n"+++def _done() -> str:+ return "data: [DONE]\n"+++def _call(query: str, index: int = 0) -> str:+ return _sse(+ {+ "tool_calls": [+ {+ "index": 0,+ "id": f"call_{index}",+ "function": {+ "name": "web_search",+ "arguments": json.dumps({"query": query}),+ },+ }+ ]+ }+ )+++_WEB_SEARCH_TOOL = {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web.",+ "parameters": {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ },+ },+}+++def _make_backend(monkeypatch, streams: list[object], payloads: list[dict]):+ backend = LlamaCppBackend.__new__(LlamaCppBackend)+ backend._process = object()+ backend._healthy = True+ backend._port = 48853+ backend._api_key = None+ backend._effective_context_length = 4096+ backend._supports_reasoning = False+ backend._reasoning_always_on = False+ backend._reasoning_style = "enable_thinking"+ backend._supports_preserve_thinking = False++ @contextlib.contextmanager+ def fake_stream_with_retry(+ _client,+ _url,+ payload,+ _cancel_event,+ headers = None,+ first_token_deadline = None,+ ):+ payloads.append(copy.deepcopy(payload))+ yield type("FakeResponse", (), {"status_code": 200, "chunks": streams.pop(0)})()++ def fake_iter_text_cancellable(+ response,+ _cancel_event,+ first_token_deadline = None,+ ):+ yield from response.chunks++ monkeypatch.setattr(backend, "_stream_with_retry", fake_stream_with_retry)+ monkeypatch.setattr(backend, "_iter_text_cancellable", fake_iter_text_cancellable)+ monkeypatch.setattr(backend, "_maybe_recover_from_mtp_crash", lambda *_a, **_k: False)+ return backend+++def _run(backend, **kwargs):+ kwargs.setdefault("max_tool_iterations", 12)+ return list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "Show me the HTML inline"}],+ tools = [_WEB_SEARCH_TOOL],+ **kwargs,+ )+ )+++def _tool_results(events: list[dict]) -> list[str]:+ return [e.get("result", "") for e in events if e.get("type") == "tool_end"]+++def test_a_tool_repeating_one_answer_is_told_so(monkeypatch):+ """The arguments vary every time, so only the RESULT can reveal the dead end."""++ streams = [[_call(f"attempt {i}", i), _done()] for i in range(_MAX_IDENTICAL_TOOL_RESULTS)]+ streams.append([_sse({"content": "I will work from what I have."}), _done()])+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: _TRUNCATION_NOTICE)++ results = _tool_results(_run(backend))++ assert any("it will not change" in r for r in results)+ # The notice that caused the repeats is kept: replacing it would leave the model+ # holding less than it already had.+ assert any(_TRUNCATION_NOTICE in r for r in results)+++def test_the_run_is_not_stopped_only_the_model_is_told(monkeypatch):+ """Hard-stopping a turn that is otherwise healthy trades one dead end for a worse one."""++ streams = [[_call(f"attempt {i}", i), _done()] for i in range(_MAX_IDENTICAL_TOOL_RESULTS)]+ streams.append([_sse({"content": "Working from what I have."}), _done()])+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: _TRUNCATION_NOTICE)++ events = _run(backend)++ texts = "".join(e["text"] for e in events if e.get("type") == "content")+ assert "Working from what I have." in texts+++def test_changing_results_are_never_interrupted(monkeypatch):+ """Polling is the case a result-keyed guard has to leave alone."""++ streams = [[_call(f"attempt {i}", i), _done()] for i in range(_MAX_IDENTICAL_TOOL_RESULTS + 2)]+ streams.append([_sse({"content": "Done."}), _done()])+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ _seq = iter(range(100))+ monkeypatch.setattr(+ "core.inference.tools.execute_tool",+ lambda *_a, **_k: f"still running, tick {next(_seq)}",+ )++ results = _tool_results(_run(backend))++ assert results, "no tool ran"+ assert not any("it will not change" in r for r in results)+++def _thread_with_a_big_completed_call(body_chars: int = 9000) -> list[dict]:+ """A finished edit_file whose arguments are still being replayed in full."""++ body = "<div>x</div>" * (body_chars // 12)+ return [+ {"role": "user", "content": "Create a Flappy Bird game in HTML"},+ {+ "role": "assistant",+ "content": "Writing the file.",+ "tool_calls": [+ {+ "id": "c1",+ "type": "function",+ "function": {+ "name": "edit_file",+ "arguments": json.dumps(+ {+ "path": "flappy-bird.html",+ "edits": [{"old_string": "", "new_string": body}],+ }+ ),+ },+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "c1",+ "name": "edit_file",+ "content": f"Wrote {len(body)} chars to flappy-bird.html",+ },+ {"role": "user", "content": "Show me the HTML inline"},+ ]+++def test_a_tool_is_not_priced_at_zero_behind_a_finished_call(monkeypatch):+ """A call priced at zero can only ever return the notice saying it returned nothing.++ Scope, stated because the name could promise more: this pins the PRICING, not the+ compaction rescue that backs it up. The rescue re-counts the prompt with the real+ tokenizer, and this harness has no llama-server to render a template, so the rescue+ bails out here by design. It is covered by the live run at a 4096 window, where the+ log line `Result budget for X was 0; compacted N completed call(s) and it is now M`+ is the evidence.+ """++ received: list[object] = []++ def _record(*_args, **kwargs):+ received.append(kwargs.get("result_budget_tokens"))+ return "the file contents"++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_call("read it"), _done()], [_sse({"content": "Here it is."}), _done()]],+ payloads,+ )+ monkeypatch.setattr("core.inference.tools.execute_tool", _record)++ list(+ backend.generate_chat_completion_with_tools(+ messages = _thread_with_a_big_completed_call(),+ tools = [_WEB_SEARCH_TOOL],+ max_tool_iterations = 4,+ )+ )++ assert received, "the tool never ran"+ budget = received[0]+ if budget is not None:+ assert (+ budget > 0+ ), "the call was priced at zero, so it could only ever return a truncation notice"+++def test_a_repeat_that_stops_repeating_resets(monkeypatch):+ """Two identical answers either side of a different one are not a dead end."""++ streams = [[_call(f"attempt {i}", i), _done()] for i in range(4)]+ streams.append([_sse({"content": "Done."}), _done()])+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ _answers = iter(["same", "same", "different", "same"])+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: next(_answers))++ results = _tool_results(_run(backend))++ assert not any("it will not change" in r for r in results)+++def test_distinct_calls_answered_with_the_same_acknowledgement_are_left_alone(monkeypatch):+ """A generic `OK` is not a dead end, and the nudge would talk the model out of the+ work it has left.++ Some tools answer every distinct mutation with the same short string. Keyed on the+ result alone, three successful writes to three different records read as one answer+ repeated, and the model is then told that different arguments will not change it.+ The window's OWN notices keep the result-only key, which is the case this guard was+ built for and is covered above.+ """++ streams = [[_call(f"record-{i}", i), _done()] for i in range(_MAX_IDENTICAL_TOOL_RESULTS + 1)]+ streams.append([_sse({"content": "All three updated."}), _done()])+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: "OK")++ results = _tool_results(_run(backend))++ assert results, "no tool ran"+ assert not any("it will not change" in r for r in results)+++def _starve_the_budget(monkeypatch):+ """Force every result budget under _MIN_USEFUL_RESULT_TOKENS, as a tight window does."""+ import core.inference.llama_cpp as _lc # noqa: PLC0415+ monkeypatch.setattr(_lc, "tool_result_budget", lambda *_a, **_k: 0)+++def test_a_short_result_that_fit_is_not_called_starved(monkeypatch):+ """The budget says what the window ALLOWED, not what the tool returned.++ "Created a.py" fits a few tokens completely. Telling the model it got nothing usable+ and to continue without it invites it to discard a successful write, or do it twice.+ """+ _starve_the_budget(monkeypatch)+ streams = [[_call("make the file", 0), _done()], [_sse({"content": "Done."}), _done()]]+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: "Created a.py")++ results = _tool_results(_run(backend))++ assert any("Created a.py" in r for r in results)+ assert not any("nothing usable" in r or "without it" in r for r in results)+++def test_a_result_the_window_actually_cut_is_still_called_starved(monkeypatch):+ """The case the nudge exists for must survive the new evidence requirement."""+ _starve_the_budget(monkeypatch)+ streams = [[_call("read the file", 0), _done()], [_sse({"content": "Done."}), _done()]]+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: _TRUNCATION_NOTICE)++ results = _tool_results(_run(backend))++ assert any(_TRUNCATION_NOTICE in r for r in results)+ assert any(r != _TRUNCATION_NOTICE for r in results), "the nudge was not added"+++def test_the_budget_rescue_recounts_with_the_stand_in_reply_too(monkeypatch):+ """Both counts have to price the SAME prompt, or the rescue gives away real room.++ The initial sizing appends an empty `tool` stand-in because Qwen-style templates render+ an assistant tool call only once a reply follows it. The rescue re-count after+ compaction did not, so on those templates this call's own arguments dropped out of the+ total and the room they occupy was handed to the result -- the exact overcount the+ stand-in exists to prevent, reintroduced on the path that was meant to fix it.+ """++ counted: list[list] = []++ def fake_count(messages, *_args, **_kwargs):+ counted.append(list(messages))+ # Under the prompt budget, so the pre-execution fit leaves the calls alone and+ # there is still something for the rescue to compact, but close enough to it that+ # the result prices under _MIN_USEFUL_RESULT_TOKENS, which is what triggers it.+ return 3050++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_call("read it"), _done()], [_sse({"content": "Here it is."}), _done()]],+ payloads,+ )+ monkeypatch.setattr(backend, "count_chat_tokens", fake_count)+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: "contents")++ rescued: list[int] = []+ real_compact = llama_cpp_module.compact_completed_tool_arguments++ def spy_compact(messages, *args, **kwargs):+ fitted, n = real_compact(messages, *args, **kwargs)+ if kwargs.get("protect_last") and n:+ rescued.append(n)+ return fitted, n++ monkeypatch.setattr(llama_cpp_module, "compact_completed_tool_arguments", spy_compact)++ # Two finished calls, because the rescue protects the newest one: with a single+ # completed call there is nothing left for it to compact and it never re-counts.+ _thread = _thread_with_a_big_completed_call()+ _older = copy.deepcopy(_thread[1:3])+ _older[0]["tool_calls"][0]["id"] = "c0"+ _older[1]["tool_call_id"] = "c0"++ list(+ backend.generate_chat_completion_with_tools(+ messages = [_thread[0], *_older, *_thread[1:]],+ tools = [_WEB_SEARCH_TOOL],+ max_tool_iterations = 4,+ )+ )++ assert rescued, "the rescue never ran, so this asserts nothing"+ ends_on_the_call = [+ messages+ for messages in counted+ if messages and messages[-1].get("role") == "assistant" and messages[-1].get("tool_calls")+ ]+ assert (+ not ends_on_the_call+ ), "a prompt was priced with the pending call's own arguments rendered away"+++def test_the_zero_room_stub_counts_as_a_window_notice(monkeypatch):+ """At a budget of zero there is no truncated body to append a notice to.++ `_truncate` returns `_zero_room_stub` instead, whose text carries neither the+ truncation marker nor any of the result. Missing it is exactly the case this+ classification exists for: the nudge is skipped and the no-progress key falls back to+ including the arguments, so a model reading one file in different slices gets the+ same empty stub forever without ever being told why.+ """+ from core.inference.tools import _zero_room_stub++ stub = _zero_room_stub(2401, None, True)+ assert "chars for the model;" not in stub, "fixture no longer exercises the gap"++ _starve_the_budget(monkeypatch)+ streams = [[_call("read the file", 0), _done()], [_sse({"content": "Done."}), _done()]]+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, streams, payloads)+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: stub)++ results = _tool_results(_run(backend))++ assert any(stub in r for r in results)+ assert any(r != stub for r in results), "the starved-result nudge was not added"+++def test_a_resumed_turn_prices_its_tool_result_by_what_is_left(monkeypatch):+ """The payload used the continuation's remainder; this budget still used the whole cap.++ With 100 of 1000 tokens left, the result was priced as if 1000 were still to come, so+ `tool_result_budget` reserved room the request was never going to use and could hand+ the call a zero budget -- a starvation notice for a read there was space for.+ """++ caps: list[object] = []+ import core.inference.llama_cpp as _lc # noqa: PLC0415++ real_budget = _lc.tool_result_budget++ def recording_budget(context_length, max_tokens, spent):+ caps.append(max_tokens)+ return real_budget(context_length, max_tokens, spent)++ monkeypatch.setattr(_lc, "tool_result_budget", recording_budget)++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": "Half an answer"}), _usage(900), _finish("length"), _done()],+ [_call("read it", 0), _done()],+ [_sse({"content": "Done."}), _done()],+ ],+ payloads,+ )+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: "contents")++ list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "Show me the file"}],+ tools = [_WEB_SEARCH_TOOL],+ max_tool_iterations = 3,+ max_tokens = 1000,+ )+ )++ assert caps, "the result was never priced"+ assert 1000 not in caps, f"a resumed turn priced its result against the whole cap: {caps}"+++def test_a_resumed_turn_sizes_its_recall_by_what_is_left(monkeypatch):+ """`retrieval_budget` reserves the output allowance before handing back recall room.++ Reserving the caller's whole cap on a continuation that has a fraction of it left+ returns a near-zero budget, so `search_conversation` drops context the request had+ ample room for.+ """++ caps: list[object] = []+ import core.inference.llama_cpp as _lc # noqa: PLC0415++ real_budget = _lc._retrieval_budget++ def recording_budget(context_length, max_tokens, spent, **kwargs):+ caps.append(max_tokens)+ return real_budget(context_length, max_tokens, spent, **kwargs)++ monkeypatch.setattr(_lc, "_retrieval_budget", recording_budget)++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": "Half an answer"}), _usage(900), _finish("length"), _done()],+ [_call("read it", 0), _done()],+ [_sse({"content": "Done."}), _done()],+ ],+ payloads,+ )++ def _accepts_everything(*_a, **_k):+ return "contents"++ _accepts_everything.__signature__ = None+ monkeypatch.setattr("core.inference.tools.execute_tool", _accepts_everything)++ list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "Show me the file"}],+ tools = [_WEB_SEARCH_TOOL],+ max_tool_iterations = 3,+ max_tokens = 1000,+ )+ )++ assert 1000 not in caps, (+ f"a resumed turn sized its recall against the whole cap: {caps}"+ )diff --git a/studio/backend/tests/test_repetition_guard.py b/studio/backend/tests/test_repetition_guard.pynew file mode 100644index 00000000000..1a91edc13b7--- /dev/null+++ b/studio/backend/tests/test_repetition_guard.py@@ -0,0 +1,165 @@+# 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 may and may not be continued when a turn is cut off mid-answer.++The guard's job is narrow: refuse to extend a fragment that is mostly an echo of itself,+because continuing one stitches the echo into the final answer. Everything else, including+text that merely looks repetitive, must still be continued -- a false positive abandons a+real answer halfway, which is worse than the wasted call a false negative costs.++Thresholds follow NousResearch/hermes-agent's `agent/repetition_guard.py`.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference.repetition_guard import MIN_FRAGMENT_LENGTH, is_repetition_dominated+++def test_one_line_echoed_until_it_owns_the_fragment():+ assert is_repetition_dominated("I will now show the file to the user.\n" * 40)+++def test_an_echo_that_ignores_line_boundaries():+ """The sliding-window pass exists for repeats that do not align to newlines."""+ assert is_repetition_dominated("the same sixty characters over and over again, yes " * 30)+++ "text",+ [+ # Real code: similar shapes, different content.+ "".join(f" ctx.lineTo({i * 3}, {i * 7 % 31});\n" for i in range(80)),+ # Prose cut mid-word. Written out rather than multiplied: a repeated sentence is+ # exactly what the guard is for, so building this case with `* 6` would have+ # asserted the opposite of what it claims.+ "The bird falls under gravity and the pipes scroll leftward. Each pipe carries a "+ "gap whose centre drifts as the score climbs, so the difficulty ramps without any "+ "explicit level system. Collision is checked against the bird's bounding circle "+ "rather than its sprite, which keeps near-misses forgiving and reads as fair to a "+ "player. The ground scrolls at the same rate as the pipes to sell the parallax, "+ "while the clouds behind move at a third of it. Scores persist for the session "+ "only, because a best-score that survives a reload invites cheating and the game "+ "is not worth defending that hard. The last thing to wire up is the collision "+ "check, which has to run befo",+ # A heading repeated a few times is ordinary structure, not an echo.+ ("## Features\n\nSomething genuinely different each time here, at length.\n" * 4),+ ],+)+def test_ordinary_text_is_still_continued(text):+ assert is_repetition_dominated(text) is False++[email protected]("text", ["", "short", "a" * (MIN_FRAGMENT_LENGTH - 1)])+def test_short_fragments_are_never_judged(text):+ """A sentence cut mid-word can trivially repeat tokens and deserves its continuation."""+ assert is_repetition_dominated(text) is False++[email protected]("value", [None, 42, b"bytes", ["a"]])+def test_it_fails_open_on_anything_it_cannot_read(value):+ assert is_repetition_dominated(value) is False+++def test_a_long_run_of_one_character_is_not_mistaken_for_content():+ assert is_repetition_dominated("x" * 5000)+++_A_RULE = "-" * 80+++def test_a_horizontal_rule_does_not_condemn_the_answer_around_it():+ """Occurrences have to be counted without overlap, or one run counts as many.++ An 80-character rule contains 21 identical 60-character windows, which alone clears+ `_MIN_REPEAT_COUNT`. The answer it divides is real work, and abandoning it mid-stream+ over one line of markdown is the failure this guard exists to avoid causing.+ """+ text = (+ "Here is the plan for the game loop, written out before any code so the shape is "+ "clear.\n" + _A_RULE + "\nThe bird accelerates downward each frame and the pipes "+ "scroll leftward at a constant rate. Collision runs against a bounding circle, "+ "which keeps near-misses forgiving. Score increments as the bird passes a pipe's "+ "trailing edge, and the difficulty ramps by narrowing the gap rather than by "+ "raising the speed, so the controls stay learnable throughout the run.\n"+ )++ assert len(text) > MIN_FRAGMENT_LENGTH+ assert is_repetition_dominated(text) is False+++def test_a_genuine_echo_of_the_same_window_is_still_caught():+ """The non-overlap rule must not cost the guard the case it was ported for."""+ text = "Let me check the file once more to be sure of its contents.\n" * 40++ assert is_repetition_dominated(text) is True+++def test_the_scan_does_not_grow_with_the_length_of_the_fragment():+ """The scan kept one 60-character slice per starting offset.++ An 800,000-character fragment therefore held roughly 180 MB of substrings alive, on a+ path whose only job is to decide whether to send one more continuation. What is+ asserted is the SHAPE, not a byte count: doubling the fragment must not double the+ cost. Before the bound it did, exactly.+ """+ import tracemalloc++ from core.inference import repetition_guard++ def peak_for(lines: int) -> int:+ text = "".join(f"unique line number {index:07d} of prose\n" for index in range(lines))+ tracemalloc.start()+ try:+ assert repetition_guard.is_repetition_dominated(text) is False+ return tracemalloc.get_traced_memory()[1]+ finally:+ tracemalloc.stop()++ small = peak_for(20_000)+ large = peak_for(40_000)++ assert large < small * 1.3, f"twice the fragment cost {large} bytes against {small}"+++def test_the_window_cap_cannot_turn_a_clean_fragment_into_a_refusal():+ """Past the cap new windows are ignored, which can only fail OPEN. Proven, not assumed."""+ from core.inference import repetition_guard++ text = "".join(f"unique line number {index:07d} of prose\n" for index in range(20_000))++ assert repetition_guard.is_repetition_dominated(text) is False+ assert repetition_guard._MAX_TRACKED_WINDOWS < len(text)+++def test_two_different_windows_sharing_a_hash_are_not_counted_as_a_repeat():+ """Counting by hash is only safe if a collision cannot stand in for a repeat."""+ from core.inference import repetition_guard++ collide = {}+ real_hash = hash++ def everything_collides(value):+ collide[value] = True+ return 1234++ original = repetition_guard.hash if hasattr(repetition_guard, "hash") else None+ repetition_guard.hash = everything_collides+ try:+ text = "".join(f"unique line number {index:07d} of prose\n" for index in range(200))+ assert repetition_guard.is_repetition_dominated(text) is False+ finally:+ if original is None:+ del repetition_guard.hash+ else:+ repetition_guard.hash = original+ assert real_hash("x") == real_hash("x")diff --git a/studio/backend/tests/test_tool_call_arg_compaction.py b/studio/backend/tests/test_tool_call_arg_compaction.pynew file mode 100644index 00000000000..b94c151e31c--- /dev/null+++ b/studio/backend/tests/test_tool_call_arg_compaction.py@@ -0,0 +1,948 @@+# 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 turn that spills is the model's own tool-call arguments, not the tool's result.++`tool_result_budget` sizes what a tool RETURNS. Nothing sized what the model SENT: a+whole-file `edit_file` puts the file itself in the assistant turn, the fit protects that+turn as the newest, and `ctx_shift` is off for any mmproj load, so the request is refused+with the write already on disk. These cover the two levers that answer it -- compacting+the arguments of calls that already returned, and refusing before spending a side effect+when that is not enough.+"""++import json++import pytest++from core.inference.context_refusal import describe_unservable_tool_call+from core.inference.context_window import (+ _ARG_COMPACTION_FLOOR_CHARS,+ _blamed_role,+ compact_completed_tool_arguments,+ compact_executed_call_arguments,+ compact_refused_tool_arguments,+ turn_is_servable,+)+++def _call(+ call_id = "c1",+ name = "edit_file",+ **arguments,+):+ return {+ "id": call_id,+ "type": "function",+ "function": {"name": name, "arguments": json.dumps(arguments)},+ }+++def _thread(+ body,+ *,+ answered = True,+ call_id = "c1",+):+ messages = [+ {"role": "user", "content": "Create a Flappy Bird game in HTML"},+ {+ "role": "assistant",+ "content": "Writing the file.",+ "tool_calls": [_call(call_id, path = "flappy-bird.html", old_string = "", new_string = body)],+ },+ ]+ if answered:+ messages.append(+ {+ "role": "tool",+ "tool_call_id": call_id,+ "name": "edit_file",+ "content": f"Wrote {len(body)} chars to flappy-bird.html",+ }+ )+ return messages+++def _replayed_arguments(messages):+ return messages[1]["tool_calls"][0]["function"]["arguments"]+++def test_an_executed_call_gives_up_its_arguments():+ body = "<!DOCTYPE html>" + "x" * 8000+ messages = _thread(body)+ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1+ replayed = json.loads(_replayed_arguments(fitted))+ assert str(len(body)) in replayed["new_string"]+ # The path survives: a model that cannot see which file it just wrote answers the+ # receipt by writing it again.+ assert replayed["path"] == "flappy-bird.html"+ assert "flappy-bird.html" in replayed["new_string"]+ assert len(_replayed_arguments(fitted)) < len(_replayed_arguments(messages))+++def test_what_the_tool_received_is_never_rewritten():+ """Only the replay changes, exactly as `strip_result_for_model` only changes the replay."""+ body = "x" * 8000+ messages = _thread(body)+ before = _replayed_arguments(messages)++ fitted, _ = compact_completed_tool_arguments(messages)++ assert _replayed_arguments(messages) == before+ assert body in before+ assert fitted is not messages+++def test_a_call_still_awaiting_its_result_is_left_alone():+ """Rewriting the in-flight call would describe a write different from the one running."""+ messages = _thread("x" * 8000, answered = False)++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 0+ assert fitted is messages+++def test_protect_last_holds_the_freshest_exchange_clear():+ messages = _thread("x" * 8000)++ _, compacted = compact_completed_tool_arguments(messages, protect_last = 2)++ assert compacted == 0+++def test_small_arguments_are_not_worth_a_receipt():+ """Retargeted: the floor is on the arguments as a WHOLE, not on each string.++ This passed a single 1023-character body, one below the per-leaf floor, and asserted+ nothing was compacted. That per-leaf rule was the defect: a batched refactor of fifty+ 800-character edits is forty thousand characters of window with no single string over+ the floor, so nothing was reclaimed and the call sat in the prompt permanently. What+ the floor is really for -- not spending a ~100-character receipt to save less -- is a+ statement about the total, which is what this now pins.+ """+ messages = _thread("x" * 200)++ _, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 0+++def test_a_batch_of_small_edits_is_compacted_on_its_total():+ """No single string clears the per-leaf floor; together they are most of the window."""+ edits = [+ {+ "old_string": f"def old_{i}():\n" + " pass\n" * 60,+ "new_string": f"def new_{i}():\n" + " return 1\n" * 60,+ }+ for i in range(20)+ ]+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("c1", "edit_file", path = "a.py", edits = edits)],+ },+ {"role": "tool", "tool_call_id": "c1", "name": "edit_file", "content": "Applied 20 edits"},+ ]++ def _args(msgs):+ return msgs[0]["tool_calls"][0]["function"]["arguments"]++ before = len(_args(messages))+ assert all(+ len(value) < _ARG_COMPACTION_FLOOR_CHARS for edit in edits for value in edit.values()+ ), "fixture must keep every leaf under the per-leaf floor"++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1+ assert len(_args(fitted)) < before // 2+++def test_one_large_edit_beside_many_small_ones_still_compacts_all_of_them():+ """The mode was chosen from the LARGEST leaf, so a mixed batch stayed in per-leaf mode.++ One 1100-character edit beside fifty 800-character ones cleared the per-leaf floor on+ the strength of the single big leaf, compacted only that leaf, and replayed the other+ forty-odd kilobytes verbatim. A batched refactor produces exactly this shape.+ """+ edits = [{"old_string": "X" * 1100, "new_string": "Y" * 1100}]+ edits += [+ {"old_string": f"a{i:03d}" + "m" * 795, "new_string": f"b{i:03d}" + "n" * 795}+ for i in range(50)+ ]+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("c1", "edit_file", path = "a.py", edits = edits)],+ },+ {"role": "tool", "tool_call_id": "c1", "name": "edit_file", "content": "Applied 51 edits"},+ ]++ def _args(msgs):+ return msgs[0]["tool_calls"][0]["function"]["arguments"]++ before = len(_args(messages))+ assert before > 80_000, "fixture must be the size the replay actually costs"++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1+ # Per-leaf mode leaves the fifty small edits whole, which is over half the payload.+ assert len(_args(fitted)) < before // 4+++def test_a_thread_with_no_tool_calls_is_returned_untouched():+ messages = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}]++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 0+ assert fitted is messages+++def test_unparseable_arguments_still_report_their_size():+ """A call that already ran cannot be re-issued from its arguments, so size is honest."""+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "c1",+ "type": "function",+ "function": {"name": "edit_file", "arguments": "{not json" + "x" * 8000},+ }+ ],+ },+ {"role": "tool", "tool_call_id": "c1", "name": "edit_file", "content": "ok"},+ ]++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1+ assert "8009" in fitted[0]["tool_calls"][0]["function"]["arguments"]+++def test_arguments_spread_thin_are_left_rather_than_grown():+ """Receipts for many small fields cost more than the fields did."""+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("c1", **{f"k{i}": "v" for i in range(200)})],+ },+ {"role": "tool", "tool_call_id": "c1", "name": "edit_file", "content": "ok"},+ ]++ _, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 0+++ "prompt_tokens, servable",+ [(0, True), (2000, True), (4096, False), (9000, False)],+)+def test_zero_room_is_the_refusal_the_budget_could_not_express(prompt_tokens, servable):+ """`tool_result_budget` clamps at zero, which truncation reads as a number, not a stop."""+ assert (+ turn_is_servable(4096, 512, prompt_tokens) is servable+ ), f"{prompt_tokens} tokens against a 4096 window"+++def test_a_tool_call_turn_is_blamed_apart_from_a_resumed_reply():+ """ "Start a new reply" re-runs the same oversized write, so the two need different advice."""+ assert _blamed_role({"role": "assistant", "content": "half a repl"}) == "assistant"+ assert _blamed_role({"role": "assistant", "tool_calls": [_call()]}) == "assistant_tool_call"+ assert _blamed_role({"role": "tool", "content": "out"}) == "tool"+++def test_the_pre_execution_refusal_promises_nothing_was_written():+ """The fact the 400 could never offer, and the reason for refusing before executing."""+ message = describe_unservable_tool_call("edit_file", 4237, 4096)++ assert "edit_file" in message+ assert "4237" in message and "4096" in message+ assert "Nothing was written" in message+++def test_the_refusal_says_when_history_was_already_spent():+ """Otherwise "increase the Context Length" reads as advice nobody tried."""+ assert "compacted" in describe_unservable_tool_call("edit_file", 4237, 4096, compacted_calls = 2)+ assert "compacted" not in describe_unservable_tool_call("edit_file", 4237, 4096)+++def test_content_nested_in_the_edits_array_is_still_elided():+ """edit_file batches through `edits[]`, so the file content is never top level.++ Written a day apart, the batching and this compaction stopped meeting: a top-level+ pass walked `path` and `edits`, found no long string, and compacted nothing at all.+ """+ body = "<!DOCTYPE html>" + "y" * 8000+ messages = [+ {+ "role": "assistant",+ "content": "Writing.",+ "tool_calls": [+ {+ "id": "c1",+ "type": "function",+ "function": {+ "name": "edit_file",+ "arguments": json.dumps(+ {+ "path": "flappy-bird.html",+ "edits": [{"old_string": "", "new_string": body}],+ }+ ),+ },+ }+ ],+ },+ {"role": "tool", "tool_call_id": "c1", "name": "edit_file", "content": "Created it"},+ ]++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1+ replayed = json.loads(fitted[0]["tool_calls"][0]["function"]["arguments"])+ assert body not in json.dumps(fitted)+ assert replayed["path"] == "flappy-bird.html"+ assert str(len(body)) in replayed["edits"][0]["new_string"]+++def test_a_refused_call_is_not_described_as_written():+ """Nothing ran, so telling the model to re-read the file would send it after nothing."""+ body = "y" * 8000+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "c1",+ "type": "function",+ "function": {+ "name": "edit_file",+ "arguments": json.dumps(+ {"path": "a.html", "edits": [{"old_string": "", "new_string": body}]}+ ),+ },+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "c1",+ "name": "edit_file",+ "content": "Not enough context",+ },+ ]++ fitted = compact_refused_tool_arguments(messages, "c1")++ replayed = json.dumps(fitted)+ assert body not in replayed+ assert "refused before it ran" in replayed+ assert "re-read the file" not in replayed+++def test_compacting_a_refusal_leaves_other_calls_alone():+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ _call("keep", "edit_file", path = "a.py", note = "z" * 8000),+ _call("drop", "edit_file", path = "b.py", note = "q" * 8000),+ ],+ },+ {"role": "tool", "tool_call_id": "drop", "name": "edit_file", "content": "refused"},+ ]++ fitted = compact_refused_tool_arguments(messages, "drop")++ calls = fitted[0]["tool_calls"]+ assert "z" * 8000 in calls[0]["function"]["arguments"]+ assert "q" * 8000 not in calls[1]["function"]["arguments"]+++ "prompt_tokens, servable",+ [+ # Observed live at a 4096 window: the gate refused these while llama-server, which+ # admits on size alone, would have served them. The model answered by retrying+ # ever smaller edits against a bar it could not see.+ (3504, True),+ (3549, True),+ (3712, True),+ # Genuinely too big: no room left to answer in.+ (3740, False),+ (4119, False),+ ],+)+def test_the_gate_refuses_only_what_the_server_would_reject(prompt_tokens, servable):+ """`prompt_budget` sets aside all of max_tokens -- right for sizing a result, far too+ strict for deciding whether a call may run at all."""+ assert turn_is_servable(4096, 512, prompt_tokens) is servable+++def test_the_refusal_does_not_read_as_a_contradiction():+ """ "3740 tokens against a 4096-token window" invites the obvious objection."""+ message = describe_unservable_tool_call("edit_file", 3740, 4096)++ assert "no room to reply" in message+++def test_a_receipt_cannot_be_mistaken_for_the_tools_output():+ """The first wording was quoted back by the model as "the tool result says ...".++ It then decided the sandbox had mangled its file and abandoned a working approach. The+ receipt has to name whose text it replaced, and say what it is not.+ """+ body = "y" * 8000+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "c1",+ "type": "function",+ "function": {+ "name": "edit_file",+ "arguments": json.dumps(+ {"path": "a.html", "edits": [{"old_string": "", "new_string": body}]}+ ),+ },+ }+ ],+ },+ {"role": "tool", "tool_call_id": "c1", "name": "edit_file", "content": "Created a.html"},+ ]++ replayed = json.dumps(compact_executed_call_arguments(messages, "c1"))++ assert "arguments you sent" in replayed+ assert "Not tool output" in replayed+ # The tool's real result is the one record of what happened and is never touched.+ assert "Created a.html" in replayed+++ "reply",+ [+ # The approval gate's own wording, verbatim.+ "The user declined to run this tool call.",+ # The unreadable-arguments guard: the call never reached the tool.+ "Error: edit_file arguments were cut off after 82 characters and could not be "+ "read, so nothing ran. Resend as complete JSON.",+ "Error: edit_file arguments are not valid JSON, so nothing ran.",+ ],+)+def test_a_call_that_never_ran_keeps_its_arguments(reply):+ """A `role=tool` reply proves an ANSWER, not an execution.++ The completed receipt says the content is "already written" and tells the model to+ re-read the file. Handing that to a call the user DECLINED, or one whose arguments+ could not be read, states a write that never happened. The model then reports the+ file as done, or reads a path that does not exist and disbelieves the tool.+ """+ messages = _thread("x" * 8000)+ messages[-1]["content"] = reply++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 0+ assert fitted is messages+ assert "already written" not in json.dumps(fitted)+++def test_an_ordinary_result_is_still_compacted_beside_one_that_did_not_run():+ """The guard must cost only the calls that never ran, not disable compaction."""+ body = "x" * 8000+ messages = _thread(body)+ messages.append(+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("c2", "edit_file", path = "b.py", new_string = "y" * 8000)],+ }+ )+ messages.append(+ {+ "role": "tool",+ "tool_call_id": "c2",+ "name": "edit_file",+ "content": "The user declined to run this tool call.",+ }+ )++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1+ assert body not in json.dumps(fitted[1])+ assert "y" * 8000 in json.dumps(fitted[3])+++def _reused_id_thread():+ """Two turns, both numbering from `call_0`, which is what the parsers really emit."""+ return [+ {"role": "user", "content": "Write the file"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("call_0", "edit_file", path = "first.html", new_string = "a" * 4000)],+ },+ {+ "role": "tool",+ "tool_call_id": "call_0",+ "name": "edit_file",+ "content": "Wrote first.html",+ },+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("call_0", "edit_file", path = "second.html", new_string = "b" * 4000)],+ },+ ]+++def test_compaction_does_not_reach_back_to_an_older_call_of_the_same_id():+ """Tool-call IDs are not unique across a conversation.++ The textual parsers number from `call_0` with an offset that starts at zero on every+ turn, and the structured fallback does the same when the server omits an ID, so a+ multi-round turn holds several `call_0`s. Rewriting every match hands an earlier+ call a receipt describing a LATER call's fate.+ """+ messages = _reused_id_thread()+ messages.append(+ {+ "role": "tool",+ "tool_call_id": "call_0",+ "name": "edit_file",+ "content": "Wrote second.html",+ }+ )++ fitted = compact_executed_call_arguments(messages, "call_0")++ assert "b" * 4000 not in json.dumps(fitted[3]), "the current call was not compacted"+ assert "a" * 4000 in json.dumps(fitted[1]), "an earlier call of the same id was rewritten"+++def test_a_refusal_does_not_relabel_an_earlier_success_as_refused():+ """The worse direction: a receipt that states a write which DID happen never did."""+ messages = _reused_id_thread()+ messages.append(+ {+ "role": "tool",+ "tool_call_id": "call_0",+ "name": "edit_file",+ "content": "Not enough context",+ }+ )++ fitted = compact_refused_tool_arguments(messages, "call_0")++ assert "refused before it ran" in json.dumps(fitted[3])+ assert "refused before it ran" not in json.dumps(fitted[1])+ assert "a" * 4000 in json.dumps(fitted[1])++[email protected]("tool_name", ["python", "terminal", "web_search", "mcp__server__tool"])+def test_a_tool_that_writes_no_file_is_not_told_its_arguments_are_on_disk(tool_name):+ """Selection is by size and by having been answered, which is every tool, not just+ the file ones. A 4000-character `code` argument was handed the `edit_file` receipt,+ telling the model the content was already written and that the file on disk holds+ it, so it could go looking for a file nothing had created."""+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("c1", tool_name, code = "print(1)\n" * 500)],+ },+ {"role": "tool", "tool_call_id": "c1", "name": tool_name, "content": "1"},+ ]++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1, "the arguments still have to be spent; only the wording changes"+ replayed = json.dumps(fitted)+ assert "on disk" not in replayed.replace("nothing was written to disk", "")+ assert "already written" not in replayed+ assert "the call already ran" in replayed+++def test_the_file_receipt_is_unchanged_for_edit_file():+ """The wording this path was proven against live must not move."""+ messages = _thread("<!DOCTYPE html>" + "x" * 8000)++ fitted, _ = compact_completed_tool_arguments(messages)++ replayed = _replayed_arguments(fitted)+ assert "already written to flappy-bird.html" in replayed+ assert "the file on disk holds it" in replayed+++def test_a_refused_call_with_malformed_arguments_is_not_replayed_as_having_run():+ """The parse-error fallback had the wording hardcoded, so it contradicted the reply.++ The `tool` message beside it says nothing was written; the receipt said the call ran.+ Two accounts of one call, and the one the model can act on is the wrong one.+ """+ broken = '{"path":"a.html","new_string":"' + "z" * 4000 # never closes+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "c1",+ "type": "function",+ "function": {"name": "edit_file", "arguments": broken},+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "c1",+ "name": "edit_file",+ "content": "Not enough context",+ },+ ]++ fitted = compact_refused_tool_arguments(messages, "c1")++ replayed = json.dumps(fitted)+ assert "z" * 4000 not in replayed+ assert "refused before it ran" in replayed+ assert "after the call ran" not in replayed+++ "tool_name, lever",+ [+ ("edit_file", "ask for a smaller file"),+ ("python", "run a shorter program"),+ ("terminal", "run a shorter command"),+ # Not a file, not a program, and not guessable: the neutral line.+ ("mcp__server__tool", "ask for less in one call"),+ ],+)+def test_the_refusal_offers_a_lever_the_tool_actually_has(tool_name, lever):+ """The gate runs for every enabled tool, so "ask for a smaller file" was reaching+ calls with no file in them, where it is advice the user cannot act on."""+ message = describe_unservable_tool_call(tool_name, 4119, 4096)++ assert lever in message+ if tool_name != "edit_file":+ assert "smaller file" not in message+++def test_an_earlier_success_does_not_vouch_for_a_later_declined_call():+ """Ids restart at call_0 every turn, so "answered" cannot be a conversation-wide set.++ The reply marker correctly skips the denial, but the older success had already put+ call_0 in the set, and the declined call was replayed as already written. The model+ is then told a file exists that it refused to create.+ """+ messages = _reused_id_thread()+ messages.append(+ {+ "role": "tool",+ "tool_call_id": "call_0",+ "name": "edit_file",+ "content": "The user declined to run this tool call.",+ }+ )++ fitted, compacted = compact_completed_tool_arguments(messages)++ # The first call really did run, so it is still spent.+ assert compacted == 1+ assert "a" * 4000 not in json.dumps(fitted[1])+ # The declined one keeps its arguments and is never called written.+ assert "b" * 4000 in json.dumps(fitted[3])+ assert "already written to second.html" not in json.dumps(fitted)+++def test_an_edit_that_ran_and_failed_is_not_called_written():+ """The tool NAME does not settle disk state. A call that ran and changed nothing is+ not a write, and saying the content is already there invites the model to skip the+ retry the error was asking for."""+ body = "x" * 8000+ messages = _thread(body)+ messages[-1]["content"] = "Error: old_string not found in flappy-bird.html"++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1, "the arguments are still spent; only the wording changes"+ replayed = json.dumps(fitted)+ assert body not in replayed+ assert "already written" not in replayed+ assert "the file on disk holds it" not in replayed+ assert "the call already ran" in replayed+++def test_a_successful_edit_still_earns_the_file_wording():+ messages = _thread("<!DOCTYPE html>" + "x" * 8000)++ fitted, _ = compact_completed_tool_arguments(messages)++ assert "already written to flappy-bird.html" in _replayed_arguments(fitted)++[email protected]("tool_name", ["python", "terminal"])+def test_a_non_file_tool_is_not_told_it_wrote_nothing(tool_name):+ """The other direction of the same guess: this code may well have created files."""+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("c1", tool_name, code = "open('out.txt','w')\n" * 400)],+ },+ {"role": "tool", "tool_call_id": "c1", "name": tool_name, "content": "done"},+ ]++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1+ replayed = json.dumps(fitted)+ assert "nothing was written" not in replayed+ assert "already written" not in replayed+ assert "the call already ran" in replayed+++def test_the_destination_path_survives_aggregate_compaction():+ """The receipt promises the content is on disk, so the field naming WHICH file is+ the one thing that can never be spent. Once the aggregate floor lowers the per-leaf+ bar to 256, a long nested path was elided like content."""+ long_path = "src/" + "very_long_directory_name/" * 20 + "module.py"+ assert len(long_path) > 256+ edits = [+ {"old_string": "a" * 300, "new_string": "b" * 300},+ {"old_string": "c" * 300, "new_string": "d" * 300},+ ]+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("c1", "edit_file", path = long_path, edits = edits)],+ },+ {"role": "tool", "tool_call_id": "c1", "name": "edit_file", "content": "Applied 2 edits"},+ ]++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1+ replayed = fitted[0]["tool_calls"][0]["function"]["arguments"]+ assert long_path in replayed, "the model can no longer name the file it just changed"+ assert "a" * 300 not in replayed+++ "tool_name, expect_file_wording",+ [("edit_file", True), ("python", False), ("terminal", False), ("mcp__s__t", False)],+)+def test_the_refusal_blames_a_file_only_when_a_file_is_involved(tool_name, expect_file_wording):+ """`_blamed_role` sent every oversized tool call to the file advice, so a program or+ an MCP payload was answered with "ask for a smaller file"."""+ from core.inference.context_window import _blamed_role # noqa: PLC0415++ message = {"role": "assistant", "tool_calls": [_call("c1", tool_name, code = "x")]}++ role = _blamed_role(message)++ assert role == ("assistant_tool_call" if expect_file_wording else "assistant_tool_payload")+++def test_a_reply_pairs_with_the_newest_pending_call_of_a_reused_id():+ """An interrupted call leaves a stale site under an id the next turn reuses.++ Pairing the reply with the OLDEST pending site marks the abandoned call's arguments+ executed while the call that actually ran keeps its arguments replayed in full: both+ halves wrong, and the expensive half is the one that stays.+ """+ body_a = "a" * 4000+ body_b = "b" * 4000+ messages = [+ {"role": "user", "content": "Write the file"},+ {+ "role": "assistant",+ "content": "",+ # Announced, then the turn was interrupted: no `tool` reply ever followed.+ "tool_calls": [_call("call_0", "edit_file", path = "first.html", new_string = body_a)],+ },+ {"role": "user", "content": "Try again"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("call_0", "edit_file", path = "second.html", new_string = body_b)],+ },+ {+ "role": "tool",+ "tool_call_id": "call_0",+ "name": "edit_file",+ "content": "Wrote second.html",+ },+ ]++ fitted, compacted = compact_completed_tool_arguments(messages)++ assert compacted == 1+ assert body_b not in json.dumps(fitted[3]), "the call that actually ran was not compacted"+ assert body_a in json.dumps(fitted[1]), "an unanswered call was called executed"+++def test_a_mixed_batch_is_blamed_on_the_call_that_made_it_large():+ """Any `edit_file` in a parallel batch won the file wording, whatever its size.++ A small edit beside an oversized `python` payload was therefore diagnosed as a file+ that is too large, and the advice -- ask for a smaller file -- cannot shrink the+ payload that actually caused the refusal.+ """+ from core.inference.context_window import _blamed_role # noqa: PLC0415++ message = {+ "role": "assistant",+ "tool_calls": [+ _call("c1", "edit_file", path = "a.py", edits = [{"old_string": "a", "new_string": "b"}]),+ _call("c2", "python", code = "x" * 40000),+ ],+ }++ assert _blamed_role(message) == "assistant_tool_payload"+++def test_a_batch_whose_bulk_is_the_file_edit_still_gets_the_file_wording():+ """The other side of the same choice, so the fix cannot swallow the file case."""+ from core.inference.context_window import _blamed_role # noqa: PLC0415++ message = {+ "role": "assistant",+ "tool_calls": [+ _call("c1", "edit_file", path = "a.py", new_string = "x" * 40000),+ _call("c2", "python", code = "print(1)"),+ ],+ }++ assert _blamed_role(message) == "assistant_tool_call"+++def test_a_reply_the_window_replaced_does_not_prove_a_write():+ """`_fit_result_to_room` can swap the real answer for a stub saying there was no room.++ The stub carries none of the failure markers, so a FAILED edit was labelled "already+ written" -- under exactly the tight context that makes compaction run. Absence of+ evidence is not evidence, so the neutral wording applies.+ """+ from core.inference.context_window import _completed_phrase_for # noqa: PLC0415+ from core.inference.tools import _zero_room_stub # noqa: PLC0415++ stub = _zero_room_stub(2401, None, True)+ written = _completed_phrase_for("edit_file", "Wrote 2401 chars to a.html")+ omitted = _completed_phrase_for("edit_file", stub)++ assert "written" in written, "the fixture no longer describes a real write"+ assert omitted != written, "a reply the window ate was read as proof of a write"+ assert "written" not in omitted+++def test_a_truncated_reply_is_inconclusive_too():+ """The other shape of the same cause: a body cut down with a notice appended."""+ from core.inference.context_window import _completed_phrase_for # noqa: PLC0415++ cut = "Wrote 2401 ch\n\n... (truncated to 13 chars for the model; 2401 chars total)"++ assert "written" not in _completed_phrase_for("edit_file", cut)+++def test_a_refused_call_is_compacted_below_the_general_floor():+ """The floor is there so a receipt never costs more than what it replaces.++ A refused call is the case where that trade is always worth making: the refusal+ message is about to be added to a prompt that already does not fit, so any reduction+ is the difference between the user reading the refusal and reading llama-server's+ context error instead.+ """+ from core.inference.context_window import ( # noqa: PLC0415+ _ARG_COMPACTION_TOTAL_FLOOR_CHARS,+ compact_refused_tool_arguments,+ )++ body = "x" * 400+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("c1", "python", code = body)],+ },+ ]+ before = messages[0]["tool_calls"][0]["function"]["arguments"]+ assert len(before) < _ARG_COMPACTION_TOTAL_FLOOR_CHARS, "fixture must sit under the floor"++ fitted = compact_refused_tool_arguments(messages, "c1")+ after = fitted[0]["tool_calls"][0]["function"]["arguments"]++ assert len(after) < len(before), "a refused call under the floor was left whole"+ assert body not in after+++def test_a_receipt_that_would_grow_the_prompt_is_still_refused():+ """The floor's real job, kept: eliding must never cost more than it saves."""+ from core.inference.context_window import compact_refused_tool_arguments # noqa: PLC0415++ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("c1", "python", code = "print(1)")],+ },+ ]+ before = messages[0]["tool_calls"][0]["function"]["arguments"]++ fitted = compact_refused_tool_arguments(messages, "c1")++ assert fitted[0]["tool_calls"][0]["function"]["arguments"] == before+++def test_an_overflowing_tool_turn_is_blamed_on_the_call_not_the_reply():+ """Strict templates render the assistant call only once its reply is present.++ The marginal cost of that reply is therefore the reply PLUS the arguments, and+ blaming the reply alone tells the user to ask for a smaller slice of a file when what+ overflowed was the payload they cannot shrink that way.+ """+ from core.inference.context_window import _blamed_role_for_turn # noqa: PLC0415++ messages = [+ {"role": "user", "content": "run it"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [_call("c1", "python", code = "x" * 40000)],+ },+ {"role": "tool", "tool_call_id": "c1", "name": "python", "content": "ok"},+ ]++ assert _blamed_role_for_turn(messages) == "assistant_tool_payload"+++def test_a_tool_reply_with_no_call_behind_it_is_still_blamed_on_itself():+ """The fallback has to survive: a reply whose call is gone is the reply's own weight."""+ from core.inference.context_window import _blamed_role_for_turn # noqa: PLC0415++ messages = [+ {"role": "user", "content": "run it"},+ {"role": "tool", "tool_call_id": "c1", "name": "python", "content": "x" * 40000},+ ]++ assert _blamed_role_for_turn(messages) == "tool"diff --git a/studio/backend/tests/test_tool_call_arg_healing.py b/studio/backend/tests/test_tool_call_arg_healing.pynew file mode 100644index 00000000000..623ca6144a3--- /dev/null+++ b/studio/backend/tests/test_tool_call_arg_healing.py@@ -0,0 +1,360 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Healing must not invent an argument the tool does not have.++`_CANONICAL_HEAL_ARG` was hand-kept and defaulted to "query" for anything absent, so it+went stale the moment a tool was added: `edit_file` landed with three required arguments+and no entry, and a call whose JSON was cut off mid-string was healed into `{"query": ...}`+and reported back as "'old_string' and 'new_string' must both be strings" -- a type error+blaming the model for a key it never sent.+"""++import json+import sys+from pathlib import Path++import pytest++_BACKEND_ROOT = Path(__file__).resolve().parents[1]+if str(_BACKEND_ROOT) not in sys.path:+ sys.path.insert(0, str(_BACKEND_ROOT))++from core.inference.tool_loop_controller import (+ _looks_like_broken_json,+ UNPARSED_ARGUMENTS_KEY,+ _heal_arg_key,+ coerce_tool_arguments,+)+from core.inference.tools import execute_tool++_TRUNCATED = '{"path":"flappy-bird.html","old_string":"","new_string":"<!DOCTYPE html>'+++ "tool_name, key",+ [+ ("python", "code"),+ ("terminal", "command"),+ ("render_html", "code"),+ # No REQUIRED argument at all -- a url-only call fetches without searching -- so+ # this one cannot be derived and is named explicitly.+ ("web_search", "query"),+ # Derived from the schema rather than hand-listed.+ ("search_knowledge_base", "query"),+ ("search_conversation", "query"),+ ],+)+def test_a_single_string_tool_still_heals(tool_name, key):+ coerced = coerce_tool_arguments("some text", heal = True, tool_name = tool_name)+ assert coerced.healed is True+ assert coerced.arguments == {key: "some text"}++[email protected]("tool_name", ["edit_file", "mcp__server__tool", ""])+def test_a_tool_with_no_single_string_argument_is_not_healed(tool_name):+ coerced = coerce_tool_arguments(_TRUNCATED, heal = True, tool_name = tool_name)+ assert _heal_arg_key(tool_name) is None+ assert coerced.healed is False+ assert coerced.arguments == {UNPARSED_ARGUMENTS_KEY: _TRUNCATED}+++def test_valid_json_is_never_healed():+ coerced = coerce_tool_arguments(+ '{"path":"a.py","edits":[{"old_string":"a","new_string":"b"}]}',+ heal = True,+ tool_name = "edit_file",+ )+ assert coerced.healed is False+ assert coerced.arguments["path"] == "a.py"+++def test_the_model_is_told_the_arguments_were_cut_off():+ """Naming the real fault is what makes the retry the right one."""+ coerced = coerce_tool_arguments(_TRUNCATED, heal = True, tool_name = "edit_file")++ result = execute_tool("edit_file", coerced.arguments, session_id = "t")++ assert result.startswith("Error:")+ assert "edit_file" in result+ assert "cut off" in result+ assert "nothing ran" in result+ # The old answer, which blamed the model for keys it never sent.+ assert "must both be strings" not in result+++def test_unparseable_but_complete_arguments_are_not_called_truncated():+ coerced = coerce_tool_arguments("not json at all", heal = True, tool_name = "edit_file")++ result = execute_tool("edit_file", coerced.arguments, session_id = "t")++ assert "not valid JSON" in result+ assert "cut off" not in result+++def test_a_healable_tool_still_reaches_the_tool_not_the_guard():+ """The guard must catch only the calls that could not be read, not every healed one.++ Retargeted: this once passed `_TRUNCATED` and asserted python healed it into `code`.+ That WAS the defect -- broken JSON became the program -- so the case is now covered by+ `test_broken_json_is_not_healed_even_for_a_single_string_tool`, and what belongs here+ is the bare string healing actually exists for.+ """+ coerced = coerce_tool_arguments("print('hi')", heal = True, tool_name = "python")++ assert UNPARSED_ARGUMENTS_KEY not in coerced.arguments+ assert coerced.arguments == {"code": "print('hi')"}+++_TRUNCATED_PYTHON = "{\"code\":\"html = open('game.html','w')\\nhtml.write('<!DOCTYPE"+++def test_broken_json_is_not_healed_even_for_a_single_string_tool():+ """`python` has one `code` argument, which hid this defect rather than avoiding it.++ A truncated call arrived as `{"code":"html = ...`, healing wrapped the whole fragment+ as the PROGRAM, and the model then read its own file back as `{"code":"html = ...` and+ spent the rest of the turn convinced the sandbox had mangled its content.+ """+ coerced = coerce_tool_arguments(_TRUNCATED_PYTHON, heal = True, tool_name = "python")++ assert coerced.healed is False+ assert coerced.arguments == {UNPARSED_ARGUMENTS_KEY: _TRUNCATED_PYTHON}+ assert "code" not in coerced.arguments+++ "raw",+ [+ # Fails at char 1, with the rest of the text still to go: not a cut-off call.+ "{not json at all",+ "{oops",+ # Complete JSON with something after it -- broken, but nothing was lost. The+ # generalisation below keys on "the tail is one unfinished token", and `trailing`+ # is exactly that shape, so "Extra data" has to be excluded by name.+ '{"a": 1} trailing',+ '{"a": 1} tail',+ "[1,2] rest",+ ],+)+def test_text_that_merely_opens_with_a_brace_still_heals(raw):+ """Guarding on the opening bracket alone refused calls that were never truncated.++ `test_non_json_arguments_still_reach_the_tool_as_a_dict` covers the contract from the+ other side: a single-required-argument tool is handed the raw text rather than a blob.+ """+ assert _looks_like_broken_json(raw) is False++ coerced = coerce_tool_arguments(raw, heal = True, tool_name = "web_search")++ assert coerced.healed is True+ assert coerced.arguments == {"query": raw}+++ "raw",+ [+ _TRUNCATED, # stops inside new_string+ _TRUNCATED_PYTHON, # stops inside code+ '{"a": 1,', # stops after a comma+ '{"a": ', # stops before a value+ '[{"a":1},', # stops inside an array+ # Cut inside a bare LITERAL rather than a string. These report at the token's+ # start, not at the end of input, so an end-of-input test alone misses them and+ # the fragment gets healed into an argument.+ '{"flag":tru', # Expecting value+ '{"a":nul',+ '{"n":1e', # Expecting ',' delimiter+ '{"n":12.',+ ],+)+def test_a_call_that_ran_out_of_input_is_never_healed(raw):+ assert _looks_like_broken_json(raw) is True++ coerced = coerce_tool_arguments(raw, heal = True, tool_name = "web_search")++ assert coerced.healed is False+ assert coerced.arguments == {UNPARSED_ARGUMENTS_KEY: raw}+++def _decision_for(raw: str):+ from core.inference.tool_loop_controller import ToolCallDecision+ coerced = coerce_tool_arguments(raw, heal = True, tool_name = "edit_file")+ return ToolCallDecision(+ action = "execute",+ tool_name = "edit_file",+ arguments = coerced.arguments,+ tool_call_id = "call_0",+ )+++def test_the_sentinel_never_reaches_the_tool_card():+ """It is plumbing between the coercion and execute_tool, and it escaped into the UI.++ Reported from a live thread as a tool card reading+ `{"__unsloth_unparsed_arguments__":"{\\"path\\":\\"flappy-bird.html\\", ...`+ """+ payload = _decision_for(_TRUNCATED).tool_start_payload()++ assert UNPARSED_ARGUMENTS_KEY not in json.dumps(payload)+ # The model's own text is still shown: the user needs to see what was cut off.+ assert payload["arguments"] == {"raw": _TRUNCATED}+++ "raw",+ [+ _TRUNCATED,+ _TRUNCATED_PYTHON,+ "not json at all",+ '{"a": 1,',+ '{"unterminated": "' + "x" * 4000,+ ],+)+def test_replayed_arguments_always_parse_as_json(raw):+ """The invariant that matters more than any of the wording below.++ llama-server parses this field while rendering the template, so a value that does not+ parse fails the WHOLE request, not just the one call. Replaying the fragment verbatim+ looked like the honest thing to do and produced a live 500:++ Failed to parse tool call arguments as JSON: [json.exception.parse_error.101]+ parse error at line 1, column 7201: missing closing quote++ A fragment is unparseable by definition, that being why it is here at all.+ """+ tool_call = _decision_for(raw).as_assistant_tool_call()++ parsed = json.loads(tool_call["function"]["arguments"])+ assert isinstance(parsed, dict)+++def test_a_replayed_unreadable_call_stays_small():+ """The fragment is the content that overflowed the window; resending it is backwards."""+ tool_call = _decision_for(+ '{"path":"x","edits":[{"new_string":"' + "y" * 8000+ ).as_assistant_tool_call()++ assert len(tool_call["function"]["arguments"]) < 200+++def test_the_sentinel_never_reaches_the_model():+ """Replaying it taught the model a key that no tool declares."""+ tool_call = _decision_for(_TRUNCATED).as_assistant_tool_call()++ assert UNPARSED_ARGUMENTS_KEY not in json.dumps(tool_call)+ # This asserted the fragment was replayed verbatim, on the reasoning that `arguments`+ # is a string in this format so the fragment was the honest value. It is a string the+ # server PARSES, which the assertion did not consider, and the result was a live 500.+ # The detail the model needs is in the tool result; the replay only has to be readable.+ assert "cut off" in tool_call["function"]["arguments"]+++def test_a_readable_call_is_unaffected_at_both_boundaries():+ from core.inference.tool_loop_controller import ToolCallDecision++ decision = ToolCallDecision(+ action = "execute",+ tool_name = "edit_file",+ arguments = {"path": "a.py", "edits": []},+ tool_call_id = "call_0",+ )++ assert decision.unparsed_fragment is None+ assert decision.tool_start_payload()["arguments"] == {"path": "a.py", "edits": []}+ assert json.loads(decision.as_assistant_tool_call()["function"]["arguments"]) == {+ "path": "a.py",+ "edits": [],+ }+++def test_a_genuine_bare_string_still_heals():+ """The case healing exists for: one argument sent as a string instead of an object."""+ coerced = coerce_tool_arguments("print(1 + 1)", heal = True, tool_name = "python")++ assert coerced.healed is True+ assert coerced.arguments == {"code": "print(1 + 1)"}+++def test_the_model_is_told_python_arguments_were_cut_off():+ coerced = coerce_tool_arguments(_TRUNCATED_PYTHON, heal = True, tool_name = "python")++ result = execute_tool("python", coerced.arguments, session_id = "t")++ assert "could not be read" in result+ assert "cut off" in result+ assert "nothing ran" in result+++_MCP_TOOL = {+ "type": "function",+ "function": {+ "name": "mcp__notes__search",+ "parameters": {+ "type": "object",+ "properties": {"phrase": {"type": "string"}},+ "required": ["phrase"],+ },+ },+}+++def test_an_mcp_tool_with_one_string_argument_is_healed_from_the_request_schemas():+ """MCP tools are discovered at runtime, so `ALL_TOOLS` cannot know them.++ Deriving the key from the static catalogue alone silently withdrew healing from+ every MCP tool: a bare string reached `execute_tool` as the unparsed sentinel and+ was answered as a call that could not be read, though nothing was wrong with it.+ """+ coerced = coerce_tool_arguments(+ "quarterly report",+ heal = True,+ tool_name = "mcp__notes__search",+ tool_schemas = [_MCP_TOOL],+ )++ assert coerced.healed is True+ assert coerced.arguments == {"phrase": "quarterly report"}+++def test_the_request_schemas_are_not_cached_across_chats():+ """One chat's MCP server must not decide another chat's healing."""+ coerce_tool_arguments(+ "quarterly report",+ heal = True,+ tool_name = "mcp__notes__search",+ tool_schemas = [_MCP_TOOL],+ )++ coerced = coerce_tool_arguments("quarterly report", heal = True, tool_name = "mcp__notes__search")++ assert coerced.healed is False+++def test_a_truncated_mcp_call_is_still_not_healed():+ """Knowing the key must not resurrect the defect the guard was added for."""+ coerced = coerce_tool_arguments(+ _TRUNCATED,+ heal = True,+ tool_name = "mcp__notes__search",+ tool_schemas = [_MCP_TOOL],+ )++ assert coerced.healed is False+ assert coerced.arguments == {UNPARSED_ARGUMENTS_KEY: _TRUNCATED}+++def test_the_controller_hands_its_own_tools_to_the_healer():+ from core.inference.tool_loop_controller import ToolLoopController # noqa: PLC0415++ controller = ToolLoopController(tools = [_MCP_TOOL])++ decision = controller.prepare_call(+ {+ "id": "call_0",+ "type": "function",+ "function": {"name": "mcp__notes__search", "arguments": "quarterly report"},+ }+ )++ assert decision.arguments == {"phrase": "quarterly report"}diff --git a/studio/backend/tests/test_truncated_answer_continuation.py b/studio/backend/tests/test_truncated_answer_continuation.pynew file mode 100644index 00000000000..e3d295b0170--- /dev/null+++ b/studio/backend/tests/test_truncated_answer_continuation.py@@ -0,0 +1,868 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An answer the window cut in half must be finished, not left mid-sentence.++Sibling of `test_length_truncated_reasoning_continuation.py`, which covers a turn that+showed NOTHING. This is the turn that showed real work and stopped mid-token: observed+streaming a 2401-byte file inline at a 4096 window, cut at `ctx.arc(6, -5, 5,` with a+`<!DOCTYPE` and no closing tag.++Compaction is the wrong lever twice over here. The room that ran out belongs to the reply,+not the prompt, and the earlier fixes had already done their job: the same turn made one+tool call where an earlier build made eighteen. What is left is arithmetic, so the answer+has to span two turns.++`continue_final_message` is what makes that seamless. The partial goes back as the assistant+turn to be EXTENDED rather than as history to be responded to, so the model resumes instead+of restarting and apologising.+"""++from __future__ import annotations++import contextlib+import copy+import json+import sys+from pathlib import Path++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference.llama_cpp import (+ _CONTINUE_TRUNCATED_ANSWER_STATUS,+ _MAX_LENGTH_CONTINUATIONS,+ LlamaCppBackend,+)++_HALF_AN_ANSWER = (+ "<!DOCTYPE html>\n<html>\n<body>\n<canvas id='c'></canvas>\n<script>\n"+ # Varied on purpose. Forty VERBATIM copies of one line is repetition-dominated by the+ # guard's line rule, which is correct of the guard and wrong of a fixture standing in+ # for streamed code: the first draft of this file tripped its own echo test.+ + "".join(+ f" ctx.lineTo({i * 3}, {i * 7 % 31});\n ctx.stroke(); // segment {i}\n" for i in range(40)+ )+ + " ctx.arc(6, -5, 5, 0"+)+++def _sse(delta: dict) -> str:+ return "data: " + json.dumps({"choices": [{"index": 0, "delta": delta}]}) + "\n"+++def _finish(reason: str) -> str:+ return (+ "data: "+ + json.dumps({"choices": [{"index": 0, "delta": {}, "finish_reason": reason}]})+ + "\n"+ )+++def _done() -> str:+ return "data: [DONE]\n"+++_WEB_SEARCH_TOOL = {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web.",+ "parameters": {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ },+ },+}+++def _make_backend(monkeypatch, streams: list[object], payloads: list[dict]):+ backend = LlamaCppBackend.__new__(LlamaCppBackend)+ backend._process = object()+ backend._healthy = True+ backend._port = 48857+ backend._api_key = None+ backend._effective_context_length = 4096+ backend._supports_reasoning = False+ backend._reasoning_always_on = False+ backend._reasoning_style = "enable_thinking"+ backend._supports_preserve_thinking = False++ @contextlib.contextmanager+ def fake_stream_with_retry(+ _client,+ _url,+ payload,+ _cancel_event,+ headers = None,+ first_token_deadline = None,+ ):+ payloads.append(copy.deepcopy(payload))+ yield type("FakeResponse", (), {"status_code": 200, "chunks": streams.pop(0)})()++ def fake_iter_text_cancellable(+ response,+ _cancel_event,+ first_token_deadline = None,+ ):+ yield from response.chunks++ monkeypatch.setattr(backend, "_stream_with_retry", fake_stream_with_retry)+ monkeypatch.setattr(backend, "_iter_text_cancellable", fake_iter_text_cancellable)+ monkeypatch.setattr(backend, "_maybe_recover_from_mtp_crash", lambda *_a, **_k: False)+ return backend+++def _run(backend, **kwargs):+ kwargs.setdefault("max_tool_iterations", 4)+ return list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "Show me the HTML inline"}],+ tools = [_WEB_SEARCH_TOOL],+ **kwargs,+ )+ )+++def _texts(events, kind: str) -> list[str]:+ return [event["text"] for event in events if event.get("type") == kind]+++def _cut_off_then(*later: list[str]) -> list[list[str]]:+ return [+ [_sse({"content": _HALF_AN_ANSWER}), _finish("length"), _done()],+ *later,+ ]+++def test_an_answer_cut_in_half_is_finished(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": ", 0, 6.28);\n</script>\n</html>"}), _done()]),+ payloads,+ )++ events = _run(backend)++ assert len(payloads) == 2, "the answer was left mid-sentence"+ assert "</html>" in "".join(_texts(events, "content"))+++def test_the_partial_goes_back_to_be_extended_not_responded_to(monkeypatch):+ """Without this the model restarts the answer instead of resuming it."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": " done"}), _done()]),+ payloads,+ )++ _run(backend)++ assert payloads[1].get("continue_final_message") is True+ assert payloads[1]["messages"][-1]["role"] == "assistant"+ assert payloads[1]["messages"][-1]["content"].endswith("ctx.arc(6, -5, 5, 0")+++def test_the_continuation_is_announced(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": " done"}), _done()]),+ payloads,+ )++ statuses = _texts(_run(backend), "status")++ assert _CONTINUE_TRUNCATED_ANSWER_STATUS in statuses+ index = statuses.index(_CONTINUE_TRUNCATED_ANSWER_STATUS)+ assert index > 0 and statuses[index - 1] == ""+++def test_an_echo_is_kept_as_is_rather_than_continued(monkeypatch):+ """Continuing a repetition loop stitches the echo into the answer.++ This is the incident behind hermes-agent's repetition guard: one turn produced a+ 60,698-char response because the continuation nudge kept extending a repeated fragment.+ """++ echo = "The user wants to see the HTML inline, so I will show the file now.\n" * 40+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_sse({"content": echo}), _finish("length"), _done()]],+ payloads,+ )++ _run(backend)++ assert len(payloads) == 1, "an echo was continued instead of being left alone"+++def test_continuation_is_capped(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _finish("length"), _done()]+ for _ in range(_MAX_LENGTH_CONTINUATIONS + 3)+ ],+ payloads,+ )++ _run(backend)++ assert len(payloads) == _MAX_LENGTH_CONTINUATIONS + 1+++def test_a_clean_stop_is_never_continued(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_sse({"content": _HALF_AN_ANSWER}), _finish("stop"), _done()]],+ payloads,+ )++ _run(backend)++ assert len(payloads) == 1+++def test_the_partial_is_kept_when_it_never_converges(monkeypatch):+ """Giving up must not throw away the work already streamed to the user."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _finish("length"), _done()]+ for _ in range(_MAX_LENGTH_CONTINUATIONS + 3)+ ],+ payloads,+ )++ content = "".join(_texts(_run(backend), "content"))++ assert "<!DOCTYPE html>" in content+++def _run_no_tools(backend, **kwargs):+ """Drives the FINAL generation, the path taken once the tool loop is done."""+ return list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "Show me the HTML inline"}],+ tools = [],+ max_tool_iterations = 0,+ **kwargs,+ )+ )+++def test_the_final_answer_is_continued_too(monkeypatch):+ """The in-loop continuation never reaches this path, which runs after the loop breaks.++ Observed live: 25 tool calls, 22387 tokens, `incomplete: length`, stopped inside+ drawBird() with the game half-written and nothing to recover it. A turn that spends+ its whole tool budget produces its answer here, not in the loop.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": ", 0, 6.28);\n</script>\n</html>"}), _done()]),+ payloads,+ )++ events = _run_no_tools(backend)++ assert len(payloads) == 2, "the final answer was left mid-sentence"+ assert payloads[1].get("continue_final_message") is True+ assert "</html>" in "".join(_texts(events, "content"))+++def test_the_final_continuation_is_capped(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _finish("length"), _done()]+ for _ in range(_MAX_LENGTH_CONTINUATIONS + 3)+ ],+ payloads,+ )++ _run_no_tools(backend)++ assert len(payloads) == _MAX_LENGTH_CONTINUATIONS + 1+++def test_a_final_echo_is_not_continued(monkeypatch):+ echo = "I will show the file now, here it is in full for you to read.\n" * 40+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_sse({"content": echo}), _finish("length"), _done()]],+ payloads,+ )++ _run_no_tools(backend)++ assert len(payloads) == 1+++def test_a_clean_final_stop_is_never_continued(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_sse({"content": _HALF_AN_ANSWER}), _finish("stop"), _done()]],+ payloads,+ )++ _run_no_tools(backend)++ assert len(payloads) == 1+++_SECOND_HALF = (+ ", 0, Math.PI * 2);\n ctx.fill();\n"+ + "".join(+ f" pipes[{i}].x -= speed * {i % 5 + 1};\n if (pipes[{i}].x < -60) recycle({i});\n"+ for i in range(40)+ )+ + " requestAnimationFrame(fr"+)+++def _usage(completion_tokens: int) -> str:+ return (+ "data: "+ + json.dumps(+ {+ "choices": [{"index": 0, "delta": {}}],+ "usage": {"prompt_tokens": 100, "completion_tokens": completion_tokens},+ }+ )+ + "\n"+ )+++def _metadata(events) -> dict:+ return [event for event in events if event.get("type") == "metadata"][-1]+++def test_the_final_continuation_replays_each_fragment_once(monkeypatch):+ """`_append_assistant_turn` PREPENDS onto the trailing assistant text.++ So handing it the cumulative answer on the second continuation writes the first+ fragment in twice, and the model resumes from a prompt whose own output is doubled.+ Only what is new since the last replay may be sent.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _finish("length"), _done()],+ [_sse({"content": _SECOND_HALF}), _finish("length"), _done()],+ [_sse({"content": "ame);\n</script>\n</html>"}), _done()],+ ],+ payloads,+ )++ events = _run_no_tools(backend)++ assert len(payloads) == 3+ replayed = payloads[2]["messages"][-1]["content"]+ assert replayed == _HALF_AN_ANSWER + _SECOND_HALF+ assert replayed.count("<!DOCTYPE html>") == 1+ # And the user is shown each fragment once as well. Content events are CUMULATIVE+ # here, not deltas, so the last one is the whole answer.+ shown = _texts(events, "content")[-1]+ assert shown.count("<!DOCTYPE html>") == 1+ assert shown.endswith("</html>")+++def test_usage_is_kept_across_final_continuations(monkeypatch):+ """Each attempt's usage is overwritten by the next, so it has to be folded in first.++ Left unfolded, a three-attempt answer reports the tokens of its last fragment alone+ and the tokens-per-second readout beside it is computed from the same short window.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _usage(700), _finish("length"), _done()],+ [_sse({"content": _SECOND_HALF}), _usage(500), _finish("length"), _done()],+ [_sse({"content": "ame);\n</script>\n</html>"}), _usage(30), _done()],+ ],+ payloads,+ )++ usage = _metadata(_run_no_tools(backend))["usage"]++ assert usage["completion_tokens"] == 700 + 500 + 30+++def test_the_replayed_prefix_keeps_the_whitespace_it_was_cut_on(monkeypatch):+ """Stripping the replay makes it differ from what was already streamed.++ The next delta is concatenated onto the STREAMED text, not onto the replay, so a+ stripped replay silently drops the newline and indentation the continuation is+ about to build on. Inside a code block that is the difference between a line+ starting where it should and starting flush against the previous one.+ """++ cut_on_whitespace = _HALF_AN_ANSWER + "\n "+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": cut_on_whitespace}), _finish("length"), _done()],+ [_sse({"content": "ctx.fill();\n</script>\n</html>"}), _done()],+ ],+ payloads,+ )++ _run(backend)++ assert payloads[1]["messages"][-1]["content"] == cut_on_whitespace+++def test_a_continuation_that_would_be_rejected_is_not_sent(monkeypatch):+ """The first pass hit `length` by consuming the physical context.++ Appending everything it produced makes the retry's prompt roughly context-sized, so+ reopening the stream gets it rejected before a single extra token arrives. The user+ keeps the partial either way; only one of the two paths also shows an error.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": " never sent"}), _done()]),+ payloads,+ )+ monkeypatch.setattr(backend, "count_chat_tokens", lambda *_args, **_kwargs: 4096)++ events = _run_no_tools(backend)++ assert len(payloads) == 1+ # And the work already streamed is still the answer.+ assert "<!DOCTYPE html>" in "".join(_texts(events, "content"))+++def test_a_count_that_cannot_be_taken_is_not_a_refusal(monkeypatch):+ """Failing open restores what this path did before the check, which is the safe side."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": ", 0, 6.28);\n</script>\n</html>"}), _done()]),+ payloads,+ )++ def _no_count(*_args, **_kwargs):+ raise RuntimeError("llama-server is not loaded")++ monkeypatch.setattr(backend, "count_chat_tokens", _no_count)++ events = _run_no_tools(backend)++ assert len(payloads) == 2+ assert "</html>" in "".join(_texts(events, "content"))+++def test_a_continuation_with_room_to_answer_in_is_still_sent(monkeypatch):+ """The gate must refuse only what llama-server would refuse.++ Its first form borrowed `turn_is_servable`, which charges the reserve a truncated+ TOOL RESULT needs for its notice. A continuation has no tool result, so that bar+ refused prompts that would have been served and gone on to produce text -- breaking+ the very continuation it was added to protect. 3800 of a 4096 window leaves 296, and+ the reply floor is 256.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": ", 0, 6.28);\n</script>\n</html>"}), _done()]),+ payloads,+ )+ monkeypatch.setattr(backend, "count_chat_tokens", lambda *_args, **_kwargs: 3800)++ events = _run_no_tools(backend)++ assert len(payloads) == 2, "a continuation with room to answer in was refused"+ assert "</html>" in "".join(_texts(events, "content"))+++def test_a_caller_set_max_tokens_is_not_exceeded(monkeypatch):+ """`finish_reason: length` does not say WHICH wall was hit.++ A caller asking for at most 100 completion tokens gets the stop at their own cap, and+ continuing twice more returned roughly 300 against a limit the API promised. Only the+ context wall deserves a continuation.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": " never sent"}), _done()]),+ payloads,+ )++ _run_no_tools(backend, max_tokens = 100)++ assert len(payloads) == 1, "the caller's output cap was overrun"+++def test_a_caller_cap_with_room_left_continues_within_it(monkeypatch):+ """Not a blanket refusal: the retry gets the REMAINDER of the caller's budget."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _usage(400), _finish("length"), _done()],+ [_sse({"content": ", 0, 6.28);\n</script>\n</html>"}), _usage(20), _done()],+ ],+ payloads,+ )++ events = _run_no_tools(backend, max_tokens = 1000)++ assert len(payloads) == 2+ assert payloads[1]["max_tokens"] == 600, "the retry got a fresh cap, not the remainder"+ assert "</html>" in "".join(_texts(events, "content"))+++def test_max_tokens_equal_to_the_window_is_the_context_wall(monkeypatch):+ """That is what the backend substitutes for "Max", so it is not a caller cap."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": ", 0, 6.28);\n</script>\n</html>"}), _done()]),+ payloads,+ )++ _run_no_tools(backend, max_tokens = 4096)++ assert len(payloads) == 2+++def test_a_refused_continuation_does_not_double_count_its_usage(monkeypatch):+ """The fold ran before the decision, and the reject path reported the same tokens+ again through _build_metadata_event."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [[_sse({"content": _HALF_AN_ANSWER}), _usage(700), _finish("length"), _done()]],+ payloads,+ )+ monkeypatch.setattr(backend, "count_chat_tokens", lambda *_a, **_k: 4096)++ usage = _metadata(_run_no_tools(backend))["usage"]++ assert len(payloads) == 1+ assert usage["completion_tokens"] == 700, "the refused attempt was counted twice"+++def test_the_in_loop_continuation_respects_the_caller_cap(monkeypatch):+ """With tools enabled a plain length stop takes the IN-LOOP path, not the final one.++ The in-loop payload rebuilds max_tokens from the caller's value on every iteration,+ so the guard added to the final pass did not reach here: a request capped at 100+ tokens still ran two more 100-token generations.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": " never sent"}), _done()]),+ payloads,+ )++ _run(backend, max_tokens = 100)++ assert len(payloads) == 1, "the caller's output cap was overrun in the loop"+++def test_the_in_loop_continuation_spends_the_remainder(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _usage(400), _finish("length"), _done()],+ [_sse({"content": ", 0, 6.28);\n</script>\n</html>"}), _usage(20), _done()],+ ],+ payloads,+ )++ _run(backend, max_tokens = 1000)++ assert len(payloads) == 2+ assert payloads[1]["max_tokens"] == 600, "the retry got a fresh cap, not the remainder"+++def test_an_in_loop_continuation_that_would_be_rejected_is_not_sent(monkeypatch):+ """Same guard the final pass has. With one user turn there is no history to evict."""++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": " never sent"}), _done()]),+ payloads,+ )+ monkeypatch.setattr(backend, "count_chat_tokens", lambda *_a, **_k: 4096)++ events = _run(backend)++ assert len(payloads) == 1+ assert "<!DOCTYPE html>" in "".join(_texts(events, "content")), "the partial was lost"+++def test_an_in_loop_continuation_with_room_is_still_sent(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": ", 0, 6.28);\n</script>\n</html>"}), _done()]),+ payloads,+ )+ monkeypatch.setattr(backend, "count_chat_tokens", lambda *_a, **_k: 3800)++ events = _run(backend)++ assert len(payloads) == 2+ assert "</html>" in "".join(_texts(events, "content"))+++def test_replayed_output_is_neutralized_before_it_is_sent(monkeypatch):+ """The replay is text the MODEL produced, and the first payload neutralized+ everything it carried. Sent raw, a template delimiter inside it -- printed code+ being the obvious case -- is read back as chat structure."""++ with_delimiter = _HALF_AN_ANSWER + "\nprint('<|im_end|>')\n"+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": with_delimiter}), _finish("length"), _done()],+ [_sse({"content": "done"}), _done()],+ ],+ payloads,+ )++ _run_no_tools(backend)++ assert len(payloads) == 2+ assert "<|im_end|>" not in json.dumps(payloads[1]["messages"])+++def test_a_continuation_that_stalls_in_reasoning_is_not_read_as_more_answer(monkeypatch):+ """`has_content_tokens` and `_last_emitted` are cumulative across attempts by design.++ Judging the NEXT attempt by them classified a continuation that produced nothing but+ reasoning as another truncated visible answer: it replayed an empty suffix with+ thinking still on, which is the same failing turn a third time, instead of taking the+ reasoning-off recovery. Judged on what this attempt put on screen now.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _finish("length"), _done()],+ [+ _sse({"reasoning_content": "Let me reconsider the whole approach. " * 60}),+ _finish("length"),+ _done(),+ ],+ [_sse({"content": "and here is the rest."}), _done()],+ ],+ payloads,+ )++ events = _run_no_tools(backend)++ assert len(payloads) == 3, "the stalled continuation was not recovered"+ # The recovery ends on a USER turn asking for the answer, which is what tells it+ # apart from the answer continuation: that one replays the partial and extends it.+ assert payloads[2]["messages"][-1]["role"] == "user"+ assert "continue_final_message" not in payloads[2]+++def test_an_answer_already_on_screen_is_not_replaced_by_the_explanation(monkeypatch):+ """Content events on this stream are cumulative, so a lone explanation overwrites.++ Reaching the give-up with visible text is only possible now that a stalled+ continuation takes the reasoning-only path, and losing a written answer to a message+ about why there is no answer would be a worse outcome than the one being fixed.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _finish("length"), _done()],+ [+ _sse({"reasoning_content": "Let me reconsider the whole approach. " * 60}),+ _finish("length"),+ _done(),+ ],+ [+ _sse({"reasoning_content": "Still thinking about it. " * 60}),+ _finish("length"),+ _done(),+ ],+ [+ _sse({"reasoning_content": "And again. " * 60}),+ _finish("length"),+ _done(),+ ],+ ],+ payloads,+ )++ events = _run_no_tools(backend)+ texts = [event["text"] for event in events if event.get("type") == "content"]++ assert texts, "the turn ended showing nothing"+ assert _HALF_AN_ANSWER[:40] in texts[-1], "the written answer was overwritten"+++def test_the_in_loop_answer_continuation_is_priced_as_a_continuation(monkeypatch):+ """The request goes out with `continue_final_message`; the admission counted without.++ That renders a different prompt -- no generation prompt, the partial as the turn being+ extended -- so the check can refuse a continuation llama-server would have served, or+ admit one it then rejects.+ """++ seen: list[object] = []+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": _SECOND_HALF}), _done()]),+ payloads,+ )++ real_count = backend.count_chat_tokens++ def recording_count(*args, **kwargs):+ seen.append(kwargs.get("continue_final_message"))+ return real_count(*args, **kwargs)++ monkeypatch.setattr(backend, "count_chat_tokens", recording_count)++ _run(backend)++ assert len(payloads) == 2, "the continuation was refused"+ assert payloads[1].get("continue_final_message") is True+ assert True in seen, "the continuation was admitted as an ordinary prompt"+++def test_an_attempt_that_reports_no_usage_is_not_charged_the_previous_one(monkeypatch):+ """Only the finish reason was reset when a continuation was accepted.++ `_metadata_usage` and `_metadata_timings` survived, so an attempt that reported+ nothing was charged the previous attempt's numbers a second time: the reply's own+ total double-counts, and a cap read off that total can look spent while there is+ still room.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _usage(700), _finish("length"), _done()],+ # No usage chunk at all, which llama-server omits on some builds.+ [_sse({"content": _SECOND_HALF}), _done()],+ ],+ payloads,+ )++ usage = _metadata(_run_no_tools(backend))["usage"]++ assert (+ usage["completion_tokens"] == 700+ ), f"the first attempt's 700 tokens were counted twice: {usage['completion_tokens']}"+++def test_a_final_continuation_does_not_reset_the_route_cursor(monkeypatch):+ """An empty status is the OpenAI route's iteration boundary: it clears `prev_text`.++ This pass keeps `cumulative` across attempts on purpose, so the retry's first content+ event carries the whole prefix again. Diffed from a cursor the empty status has just+ reset, the client is sent the entire partial answer a second time.+ """++ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _cut_off_then([_sse({"content": _SECOND_HALF}), _done()]),+ payloads,+ )++ events = _run_no_tools(backend)++ assert len(payloads) == 2, "the answer was not continued"+ # Only what happens AFTER text is on screen matters: a blank status before the+ # first content event resets a cursor that is already empty.+ kinds = [(e.get("type"), e.get("text")) for e in events]+ first_content = next(i for i, (kind, _) in enumerate(kinds) if kind == "content")+ after = [text for kind, text in kinds[first_content:] if kind == "status"]+ assert after, "the retry was not announced at all"+ assert "" not in after, f"an iteration-boundary reset was emitted mid-answer: {after}"+++def test_a_resumed_turn_that_calls_a_tool_stays_one_assistant_message(monkeypatch):+ """`append_assistant_turn` merges into a resumed partial; the reset defeated it.++ The caller's `continue_final_message` was restored at the top of the tool-execution+ block, before the call was recorded, so a turn resumed mid-answer that then called a+ tool appended a SECOND consecutive assistant message. Strict templates reject that.+ """++ seen: list[list] = []+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ [_sse({"content": _HALF_AN_ANSWER}), _finish("length"), _done()],+ [+ _sse(+ {+ "content": '<tool_call>{"name": "web_search", "arguments": {"query": "x"}}</tool_call>'+ }+ ),+ _done(),+ ],+ [_sse({"content": "Done."}), _done()],+ ],+ payloads,+ )+ monkeypatch.setattr("core.inference.tools.execute_tool", lambda *_a, **_k: "a result")++ list(+ backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "Show me the HTML inline"}],+ tools = [_WEB_SEARCH_TOOL],+ max_tool_iterations = 3,+ )+ )++ assert len(payloads) >= 3, "the tool round never happened"+ messages = payloads[-1]["messages"]+ roles = [m.get("role") for m in messages]+ for first, second in zip(roles, roles[1:]):+ assert not (+ first == "assistant" and second == "assistant"+ ), f"two assistant turns in a row: {roles}"diff --git a/studio/backend/tests/tools/refactor_guard.py b/studio/backend/tests/tools/refactor_guard.pyindex 73b54f7d256..c4a72e47248 100644--- a/studio/backend/tests/tools/refactor_guard.py+++ b/studio/backend/tests/tools/refactor_guard.py@@ -290,6 +290,13 @@ _ARG_FIXTURES = {"first": lambda text: _parser_first_sentinel(text),"found": lambda text: max(_parser_first_sentinel(text), 0),"out": lambda text: [],+ # The model-facing notices added for a small window: each takes the tool name first+ # (which gets the corpus text) and then the result it is appended to.+ "result": lambda text: text,+ "last_result": lambda text: text,+ # A run length, not text. Above _MAX_IDENTICAL_TOOL_RESULTS so the message renders+ # the plural branch it will really be seen in.+ "times": lambda text: 3,"previous": lambda text: text,"markers": lambda text: _tool_healing_build_markers(text),"patterns": lambda text: _tool_healing_all_pats(),diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex d50edff75bf..dd6d6281605 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -6192,10 +6192,38 @@ export function createOpenAIStreamAdapter();}};+ // The window is passed so a length-stop can tell a Max Tokens the user chose+ // from the backend's stand-in for "Max" (the whole context length). The two+ // need opposite advice, and "Increase Max Tokens" cannot be acted on when it+ // is already unlimited.const stream =generationDecision === "durable"? durableStream()- : streamChatCompletions(requestPayload, runSignal);+ : streamChatCompletions(+ requestPayload,+ runSignal,+ // Only when the request targets the LOCAL model. ggufContextLength+ // stays populated for a resident GGUF even while an external model is+ // selected, so an external request with a 16K cap was being measured+ // against an unrelated 4096-token local window and reported as having+ // unlimited Max Tokens and no context left.+ // `maxSeqLength` last, and coerced from 0: a local safetensors or+ // MLX request on this path has neither GGUF field set, and reading+ // that as "no window" makes every context-length stop look like a+ // user-set Max Tokens one -- advice to raise a value already at the+ // model's maximum. Same order the RAG `context_length` above uses.+ // `loadedCustomContextLength`, not `customContextLength`: the+ // latter is the EDITABLE field, and the store's own definition of a+ // pending edit is the two differing. A model still serving at 4096+ // while the field reads 8192 would make its 4096 stop look+ // user-imposed, and the toast would advise raising Max Tokens+ // instead of reloading at the larger context.+ isExternalRequest+ ? null+ : (runtime.loadedCustomContextLength ??+ runtime.ggufContextLength ??+ (params.maxSeqLength || null)),+ );// Per run, not per module: two turns must not share a cycle.const canPublish = createStreamPublishGate();@@ -7477,10 +7505,15 @@ export function createOpenAIStreamAdapter(const msg = err instanceof Error ? err.message : String(err);if (err instanceof GenerationLengthError) {toast.error("Response ran out of tokens", {+ // The error already chose between the Max Tokens and Context Length+ // remedies from the cap and the prompt size. Repeating the Max Tokens+ // advice here overrode that choice in the one place the user reads,+ // sending them to a setting that is already at its maximum.description:+ msg ||"The model used the full Max Tokens budget while thinking " +- "and did not produce a final answer. Increase Max Tokens in " +- "chat Settings or turn off thinking, then retry.",+ "and did not produce a final answer. Increase Max Tokens in " ++ "chat Settings or turn off thinking, then retry.",duration: 8000,});} else if (err instanceof ChatGenerationTerminalError) {diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 8ffdaa73a4d..2cf06463607 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -48,6 +48,7 @@ import {runBoundedVariantsRequest,} from "./gguf-variants-request";import { assertCompletedPaddedBody } from "./padded-response";+import { maxTokensIsTheLimit } from "./generation-length.ts";export const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";// Bumped alongside that event so other tabs, which never receive it, can drop caches@@ -111,10 +112,31 @@ export class StreamInterruptedError extends Error {* content, so the chat UI can explain a completed stream holding only a thinking panel.*/export class GenerationLengthError extends Error {- constructor() {+ /**+ * @param maxTokensWasSet whether the user actually configured a Max Tokens value.+ *+ * With Max Tokens left on "Max" the backend already requests the WHOLE context length+ * (`payload["max_tokens"] = self._effective_context_length`), so generation stops at the+ * context wall rather than at any setting, and "Increase Max Tokens" is advice that+ * cannot be followed: it is at its maximum and raising it changes nothing. Observed on a+ * 4096-token window where the prompt left roughly a thousand tokens to answer in, which+ * medium thinking spent before writing anything.+ *+ * The false branch is NOT only that case. A finite cap the prompt left no room for+ * lands here too (cap 2048, prompt 3000, window 4096), and the context-length remedy+ * is right there as well -- which is why the wording says raising the cap cannot+ * create room, rather than describing the cap itself as having no limit. That+ * description would contradict the finite value the user can see in Settings.+ */+ constructor(maxTokensWasSet = true) {super(- "The model reached the Max Tokens limit before producing a final answer. " +- "Increase Max Tokens or disable thinking, then retry.",+ maxTokensWasSet+ ? "The model reached the Max Tokens limit before producing a final answer. " ++ "Increase Max Tokens or disable thinking, then retry."+ : "The model ran out of room to answer: thinking used what the context window " ++ "had left after the prompt, before any answer was written. Raising Max " ++ "Tokens cannot create room the window does not have -- increase the " ++ "Context Length in Model settings, or disable thinking, then retry.",);this.name = "GenerationLengthError";}@@ -1489,6 +1511,12 @@ function classifyStructuredDeltaContent(content: unknown): {export async function* streamChatCompletions(payload: OpenAIChatCompletionsRequest,signal: AbortSignal,+ /**+ * The window this request is served by, when the caller knows it. Used only to tell a+ * user-chosen Max Tokens apart from the backend's stand-in for "Max", which is the whole+ * context length -- the two need opposite advice when generation stops on length.+ */+ loadedContextLength?: number | null,): AsyncGenerator<OpenAIChatChunk> {const response = await authFetch("/v1/chat/completions", {method: "POST",@@ -1515,6 +1543,10 @@ export async function* streamChatCompletions(let terminalFinishReason: string | null = null;let sawAssistantContent = false;let sawReasoningContent = false;+ // Reported by the server on the final chunk. Needed to tell the two walls apart: a+ // finite Max Tokens below the context length does not mean Max Tokens is what stopped+ // the generation.+ let promptTokens: number | null = null;const throwIfReasoningOnlyLength = () => {if (@@ -1522,7 +1554,16 @@ export async function* streamChatCompletions(sawReasoningContent &&!sawAssistantContent) {- throw new GenerationLengthError();+ // The backend substitutes the full context length when the user left Max Tokens on+ // "Max", so a payload value equal to it is indistinguishable from unset here -- and+ // both mean the same thing to the user: the setting is not the lever.+ throw new GenerationLengthError(+ maxTokensIsTheLimit({+ cap: payload.max_tokens ?? null,+ contextLength: loadedContextLength ?? null,+ promptTokens,+ }),+ );}};@@ -1610,6 +1651,10 @@ export async function* streamChatCompletions(separatorIndex = buffer.search(/\r?\n\r?\n/);continue;}+ const parsedUsage = (parsed as { usage?: { prompt_tokens?: number } }).usage;+ if (typeof parsedUsage?.prompt_tokens === "number") {+ promptTokens = parsedUsage.prompt_tokens;+ }// finish_reason is a valid terminal signal for providers that close without a [DONE] sentinel.const parsedChoices = (parsed as {diff --git a/studio/frontend/src/features/chat/api/generation-length.ts b/studio/frontend/src/features/chat/api/generation-length.tsnew file mode 100644index 00000000000..1c54da7dba5--- /dev/null+++ b/studio/frontend/src/features/chat/api/generation-length.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * Whether Max Tokens, rather than the context window, is what stopped this generation.+ *+ * Two different walls produce the same `finish_reason: "length"`, and only one of them has+ * a setting the user can raise. Comparing the cap to the whole window answers the first+ * question and not the second: with a 4096-token window, a 3000-token prompt and Max+ * Tokens 2048, generation stops after roughly 1096 tokens -- well short of the cap -- and+ * "increase Max Tokens" is then advice that cannot create any room at all.+ *+ * With Max Tokens on "Max" the backend sends the whole context length, so a cap equal to+ * it is indistinguishable from unset here, and both mean the same thing to the user.+ *+ * `promptTokens` is the server's own count from the final usage chunk. Absent, the cap+ * alone decides, which is what this did before the prompt was available.+ */+export function maxTokensIsTheLimit({+ cap,+ contextLength,+ promptTokens,+}: {+ cap: number | null;+ contextLength: number | null;+ promptTokens: number | null;+}): boolean {+ const window = contextLength ?? Number.POSITIVE_INFINITY;+ if (cap === null || cap >= window) {+ return false;+ }+ if (promptTokens === null) {+ return true;+ }+ // Strictly below, not at. At equality the cap and the physical context wall are hit+ // in the same token, so raising Max Tokens creates no room and the advice to do so is+ // the one thing that cannot help. The context length is the lever there.+ return promptTokens + cap < window;+}diff --git a/studio/frontend/tests/generation-length-cap-attribution.test.ts b/studio/frontend/tests/generation-length-cap-attribution.test.tsnew file mode 100644index 00000000000..46ff9352803--- /dev/null+++ b/studio/frontend/tests/generation-length-cap-attribution.test.ts@@ -0,0 +1,122 @@+// 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 { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";++import { maxTokensIsTheLimit } from "../src/features/chat/api/generation-length.ts";++// Hoisted: biome's useTopLevelRegex flags a literal recompiled per call.+const LOCAL_WINDOW_ARGUMENT =+ /isExternalRequest\s*\n\s*\? null\s*\n\s*: \(runtime\.loadedCustomContextLength \?\?\s*\n\s*runtime\.ggufContextLength \?\?\s*\n\s*\(params\.maxSeqLength \|\| null\)\)/;+// The EDITABLE field must not be what a stop is judged against: the store defines a+// pending context edit as exactly `customContextLength !== loadedCustomContextLength`.+const PENDING_FIELD = /: \(runtime\.customContextLength \?\?/;++test("a cap the prompt left no room for is not the limit that was hit", () => {+ // 4096 window, 3000-token prompt, Max Tokens 2048: generation stops at roughly 1096,+ // well short of the cap. Blaming Max Tokens sends the user to raise a setting that+ // cannot create any room.+ assert.equal(+ maxTokensIsTheLimit({ cap: 2048, contextLength: 4096, promptTokens: 3000 }),+ false,+ );+});++test("a cap the prompt left room for is the limit that was hit", () => {+ assert.equal(+ maxTokensIsTheLimit({ cap: 512, contextLength: 4096, promptTokens: 3000 }),+ true,+ );+});++test("hitting the cap and the context wall together is context-bound", () => {+ // Retargeted. This asserted the cap wins at equality, which is exactly backwards: when+ // promptTokens + cap equals the window, both limits are reached in the same token, so+ // raising Max Tokens creates no room at all and the Context Length remedy is the only+ // one that can work.+ assert.equal(+ maxTokensIsTheLimit({ cap: 1096, contextLength: 4096, promptTokens: 3000 }),+ false,+ );+ // One token of headroom and the cap really is what stopped it.+ assert.equal(+ maxTokensIsTheLimit({ cap: 1095, contextLength: 4096, promptTokens: 3000 }),+ true,+ );+});++test("Max Tokens on Max is never the limit", () => {+ // The backend substitutes the whole context length, so a cap equal to it is+ // indistinguishable from unset, and raising it is impossible either way.+ assert.equal(+ maxTokensIsTheLimit({ cap: 4096, contextLength: 4096, promptTokens: 10 }),+ false,+ );+ assert.equal(+ maxTokensIsTheLimit({ cap: null, contextLength: 4096, promptTokens: 10 }),+ false,+ );+});++test("without a prompt count the cap alone decides", () => {+ // What this did before the server's count was read: the safe fallback, not a refusal.+ assert.equal(+ maxTokensIsTheLimit({ cap: 2048, contextLength: 4096, promptTokens: null }),+ true,+ );+});++test("an unknown context length cannot make a cap the limit", () => {+ assert.equal(+ maxTokensIsTheLimit({ cap: 2048, contextLength: null, promptTokens: null }),+ true,+ );+ assert.equal(+ maxTokensIsTheLimit({ cap: null, contextLength: null, promptTokens: null }),+ false,+ );+});++test("a local model with no GGUF window still reports one", () => {+ // A safetensors or MLX request on the legacy stream path has neither+ // customContextLength nor ggufContextLength, while params.maxSeqLength IS its+ // effective window and is also where the default Max Tokens comes from. Passing+ // null there makes the window infinite below, so every context-length stop is+ // reported as a Max Tokens stop and the user is told to raise a setting that is+ // already at the model's maximum.+ assert.equal(+ maxTokensIsTheLimit({ cap: 2048, contextLength: null, promptTokens: 3000 }),+ true,+ );+ assert.equal(+ maxTokensIsTheLimit({ cap: 2048, contextLength: 4096, promptTokens: 3000 }),+ false,+ );++ const adapter = readFileSync(+ fileURLToPath(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ ),+ "utf8",+ );+ assert.match(adapter, LOCAL_WINDOW_ARGUMENT);+});++test("a pending Context Length edit does not decide what stopped the generation", () => {+ // Typing 8192 into the field while the model still serves at 4096 would make the+ // 4096 stop look user-imposed, and the advice would be to raise Max Tokens rather+ // than to reload at the larger context.+ const adapter = readFileSync(+ fileURLToPath(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ ),+ "utf8",+ );++ assert.match(adapter, LOCAL_WINDOW_ARGUMENT);+ assert.doesNotMatch(adapter, PENDING_FIELD);+});diff --git a/studio/frontend/tests/generation-length-toast-advice.test.ts b/studio/frontend/tests/generation-length-toast-advice.test.tsnew file mode 100644index 00000000000..4aae523a638--- /dev/null+++ b/studio/frontend/tests/generation-length-toast-advice.test.ts@@ -0,0 +1,58 @@+// 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";++// Asserted against the source like the other chat-adapter tests: importing the+// module would drag in the stores and the toast layer for one catch block.+const source = readFileSync(+ fileURLToPath(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ ),+ "utf8",+);++// Hoisted: biome's useTopLevelRegex flags a literal recompiled per call.+const TOAST_BRANCH =+ /err instanceof GenerationLengthError\) \{[\s\S]*?\n {10}\} else if/;+const FROM_THE_ERROR = /description:\s*\n?\s*msg \|\|/;+const THE_ERROR_CLASS = /class GenerationLengthError/;+const CAP_REMEDY = /Increase Max Tokens or disable thinking/;+// Retargeted. The old wording claimed Max Tokens was "already unlimited", which is+// only true for one of the two cases that reach this branch: a finite cap the prompt+// left no room for lands here too, and telling that user their cap is unlimited+// contradicts the number in their own Settings.+const WINDOW_REMEDY = /cannot create room the window does not have/;+const NO_UNLIMITED_CLAIM = /already unlimited/;+const WINDOW_SETTING = /Length in Model settings/;++test("the toast repeats the advice the error chose, not the Max Tokens advice", () => {+ // GenerationLengthError already decides between the Max Tokens and the Context+ // Length remedy, from the cap and the prompt size. The toast hardcoded the Max+ // Tokens wording, which overrode that decision in the one place the user reads:+ // on a prompt that left no room, it sent them to raise a setting already at its+ // maximum, while the message body two lines away said the opposite.+ const branch = TOAST_BRANCH.exec(source);+ assert.ok(branch, "the GenerationLengthError toast branch moved");+ assert.match(branch[0], FROM_THE_ERROR);+});++test("the two remedies really are different text, so passing it through matters", () => {+ // Read rather than imported, as tests/padded-response.test.ts reads it: importing+ // chat-api pulls in the asset graph for two string literals.+ const chatApi = readFileSync(+ fileURLToPath(+ new URL("../src/features/chat/api/chat-api.ts", import.meta.url),+ ),+ "utf8",+ );++ assert.match(chatApi, THE_ERROR_CLASS);+ assert.match(chatApi, CAP_REMEDY);+ assert.match(chatApi, WINDOW_REMEDY);+ assert.match(chatApi, WINDOW_SETTING);+ assert.doesNotMatch(chatApi, NO_UNLIMITED_CLAIM);+});