Repository navigation
Studio: stop a small context window ending a tool-using turn with nothing - #9768
Conversation
…hing A chat at a 4096 context died with "request (4237 tokens) exceeds the available context size (4096 tokens)" after edit_file had already written the file. Measured through the model's own template and tokenizer, the overflow was not the tool result: it was the assistant's own edit_file arguments, which the template only renders once a tool message answers the call. Five defects came out of that one thread: 1. Completed tool-call arguments were replayed verbatim forever, so a whole-file write kept costing its full size on every later turn. They are now compacted in the replayed conversation only, leaving the stored thread and what the tool received byte-identical. 2. The fit was discovered after execution, so an unservable turn had already spent its side effect. The check is hoisted above the call, and a turn that cannot be rescued is refused before it writes. 3. edit_file took one old_string/new_string pair, so building a file meant one call per hunk and the model spent whole turns chunking. It now takes a batched edits[] array, matched against the original text with overlap detection and applied all-or-nothing. 4. A tool call whose JSON was cut off mid-stream was healed by filling the first single-string argument with the raw fragment, so a truncated python call became a program that was literally its own broken JSON. Truncated calls are now told apart from merely malformed ones and are never healed. 5. A turn could spend the entire window reasoning and stop on finish_reason length with no answer and no tool call. Because a truncated thought is correctly not promoted as an answer, that rendered as an empty message. It now continues with thinking off, and says which lever to pull if that still produces nothing. Verified against the live llama-server that produced the original 400.
Asked to show a 2401-byte file inline at a 4096 window, a turn spent
eighteen tool calls getting nowhere. The log says why:
tool result: name=terminal budget_tokens=0 chars=109
Six of the last eight calls were priced at zero, so each returned only
the notice saying it had been cut. The model read that as a fresh
failure and tried again with a different line range every time.
Three changes, cheapest first:
- A result budget below a useful floor now triggers compaction and a
re-price before the call runs. Room is exactly what compaction
reclaims, and spending it here is what lets the call succeed rather
than return a notice.
- A call the window has already priced at nothing says so on the FIRST
result. The pricing is known before the tool runs, so waiting for a
repeat guard to rediscover it spends calls learning something already
computed.
- A tool that returns byte-identical results several times in a row now
tells the model the answer will not change. Keyed on the RESULT and
not the arguments, because the arguments differed on every one of the
eighteen calls; an argument-keyed guard would have watched it happen.
It never fires while results are still changing, so polling is
untouched, and it tells the model rather than aborting the run.
edit_file's description also now says a successful call means the file
on disk holds what was sent, so there is no need to read it back. That
is what started the spiral.
The result-keyed guard and the never-fire-while-changing rule follow
OpenClaw's tool-loop detection. hermes-agent's repetition guard was
measured against this turn first and would not have fired: two repeats
of a 75-char line in 9935 chars is far below its thresholds.
unparsed-arguments sentinel Two things from live threads on the previous build. 1. A turn streaming a 2401-byte file inline at a 4096 window stopped mid-token, at `ctx.arc(6, -5, 5, 0` with a <!DOCTYPE and no closing tag. The earlier fixes had already done their part: the same turn made one tool call where the build before it made eighteen. What remained is arithmetic, and the room that ran out belongs to the reply rather than the prompt, so compaction cannot help and the answer has to span two turns. The existing continuation only covered a turn that showed NOTHING. It now also resumes a truncated answer, handing the partial back with continue_final_message so the model extends it mid-token instead of restarting and apologising. Thinking stays on, because thinking was never the problem here. hermes-agent's repetition guard is ported alongside it, and this is the path it was written for: their continuation nudge once stitched a repeated fragment into a 60,698-char response. A fragment that is mostly an echo of itself is kept as-is rather than extended. It was measured against the earlier read-loop first and correctly ruled out there. 2. `__unsloth_unparsed_arguments__` was reaching both places a caller looks. The tool card showed it to the user verbatim, and the replayed assistant turn showed it to the MODEL, teaching it a key that no tool declares. Both boundaries now go through one accessor: the card shows the fragment under `raw`, and the replay sends it verbatim as the arguments string, which is what that field is in this format. test_a_turn_that_answers_is_never_continued is retargeted rather than removed. It encoded the old rule that any turn with content was left alone, which the first change deliberately reverses; what still holds, and is what it now asserts, is that an answer resumes with thinking on and extends the partial rather than being treated as a stalled thought.
The previous commit stopped `__unsloth_unparsed_arguments__` reaching the
model by replaying the truncated fragment verbatim as the call's
`arguments`, on the reasoning that the field is a string in this format
so the fragment was the honest value.
The field is a string the SERVER PARSES while rendering the chat
template, which that reasoning missed. A fragment is unparseable by
definition, that being why it is there at all, so every request carrying
one failed outright:
llama-server returned 500: Failed to parse tool call arguments as
JSON: parse error at line 1, column 7201: missing closing quote
That surfaced in the UI as "An internal error occurred", which is a
worse outcome than the cosmetic leak it was fixing.
The replay is now a short valid object naming the failure. The detail
the model needs is already in the tool result, and the fragment is not
worth resending: it is the content that overflowed the window.
Five parametrised cases pin the invariant that was missing, that
replayed arguments always parse, plus one that the replay stays small.
Checked against the broken version: all seven fail there.
The test that asserted verbatim replay is corrected rather than removed.
Its comment stated the same wrong premise, so both now record what the
assertion failed to consider.
Reading every model-facing string in this branch side by side turned up a contradiction it had shipped: the compacted-arguments placeholder ended "read the file back if you need the content", while the edit_file description says not to read back what you just wrote and both no-progress notices say reading again will not help. Three lines discouraging a re-read and one inviting it, and the re-read is the loop that cost eighteen calls in a single turn. Every one of them now says the same thing: continue from what you have, in parts if it will not fit at once, and finish the task. Each is also shorter, since they are spent out of the same window they are describing (roughly 68 -> 32 tokens for the repeated-result notice, 68 -> 47 for the starved one, 41 -> 27 for the placeholder). The larger saving is not in those. Tool schemas go into EVERY prompt and came to about 1351 tokens, a third of a 4096-token window before any conversation at all. edit_file's description was 277 of it and is now 170, with every rule kept: batch into edits, match against the original text, no overlaps, exactly one match unless replace_all, all-or-nothing, do not read back. That is about 108 tokens returned on every turn. Also fixed: thinking_exhausted_message read "spent its whole reply of the 4096-token window on reasoning", from formatting a pre-spaced fragment. Four tests asserted the exact old phrasing. The meaning survives the rewrite in each, so the assertions moved rather than the messages.
A live run spent 25 tool calls and 22387 tokens, hit the tool-iteration ceiling, and then stopped on finish_reason length inside drawBird() with the game half-written and nothing to recover it. The continuation added earlier covers the generation INSIDE the tool loop. At the iteration ceiling the loop breaks, appends the budget-exhausted nudge, and runs a separate final generation after it, which had no continuation at all. A turn that spends its whole tool budget produces its answer there, so the one path most likely to be cut off was the one path with no way back. That generation is now wrapped in the same continuation, under the same rules: the partial goes back through continue_final_message to be extended rather than responded to, thinking is left as the caller set it because thinking is not what ran out, an answer that is mostly an echo of itself is left alone, and the whole thing is capped. Four tests drive the final path directly, with max_tool_iterations = 0 so the tool loop cannot take the request first. Checked against a disabled build: the two that assert the continuation fail there, and the two that assert it stays out (clean stop, echo) still pass.
Backend: - Rebind the assistant message after run-then-compact rebuilds the conversation, so a second call in the same batch is still visible to the model when its result arrives. - Compact only the last call carrying an id. Parsers number from call_0 on every turn, so rewriting every match relabelled an earlier call with a later one's outcome. - Keep the arguments of a call that never ran. A tool reply proves an answer, not an execution, and the completed receipt claimed a write the user had declined. - Word the receipt per tool. python, terminal and MCP calls write no file, so they no longer read as already written to disk. - Build the malformed-arguments receipt from the same phrase, so a refused call is not replayed as having run. - Continue a reasoning-only length stop in the final pass, which the in-loop continuation cannot reach, and say so when it never converges. - Drop an explicit reasoning effort for a thinking-off continuation. For that style the effort wins, so the retry re-ran the failing turn. - Give continuations their own loop credits instead of charging them to the caller's tool budget. - Count the final continuation prompt before reopening the stream, and keep the partial rather than send a request that cannot be served. - Replay only the new suffix on a final continuation, and fold each attempt's usage in before the next overwrites it. - Replay the truncated answer unstripped so the continuation builds on the whitespace it was cut on. - Price the result budget against the compacted prompt when the gate ran the call because compaction will make room. - Use the conservative estimate at the admission gate so dense ASCII cannot skip the exact check. - Key the no-progress guard on the arguments too, unless the result is a notice the window itself produced. - Count repeated windows without overlap, so one long rule no longer reads as an echo. - Detect a value cut mid-literal as truncation, and a complete document with trailing junk as not. - Derive healing keys from the request's schemas as well, restoring auto-healing for single-string MCP tools. - Offer a lever the refused tool actually has. Frontend: - Tell the Max Tokens wall from the context wall using the prompt count, so a cap the prompt left no room for is not blamed.
# Conflicts: # studio/backend/core/inference/llama_cpp.py # studio/frontend/src/features/chat/api/chat-adapter.ts
#8692) * Studio: rework prompt storage into a master-detail layout Cards rendered the full prompt body with no truncation, so a few dozen saved prompts became a long scroll of uneven cards. Editing happened inline in a four-row textarea, so long prompts were edited through a peephole while the list shifted underneath. Replace the flat list with a master-detail layout: a compact rail of name plus one-line preview on the left, and a detail pane on the right that owns its height. Unsaved edits are held per entry so switching rows no longer discards them, with a dirty marker in the rail and Save/Revert in the footer. List items now auto-size to their content and reorder by dragging the grips, animated with FLIP. The drag listener lives on window rather than using setPointerCapture: reordering makes React move the row's DOM node, and detaching implicitly releases pointer capture, which ended the drag after one row. Hit-testing uses offsetTop/offsetHeight since a client rect reports the pre-animation position while FLIP is in flight. Add a Preview toggle on both tabs backed by the existing MarkdownPreview, and allow bookmarking prompt lists into the + menu next to bookmarked prompts. Rows there carry a Prompt / List pill, since selecting a prompt fills the composer while selecting a list queues and sends every prompt in it. Presentation only: no schema migration, no API change, no change to the export formats or import parser, and onUse/onRunList signatures are unchanged. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: address review feedback on prompt storage Select a newly created prompt or list only after the refresh resolves. The keep-a-row-selected effect runs against whatever list is in state, so selecting the new id while the old list was still in state made the effect bounce the selection to the first existing entry, and the new entry was never shown. Let the body shrink and stack on small viewports. The fixed 420px floor plus the header could exceed the dialog's 94dvh on a short window and clip the detail pane's actions behind overflow-hidden, and a fixed 248px rail left the detail pane unusably narrow below ~600px. The floor is now capped against the viewport, the rail narrows at sm and stacks below it, and the action rows wrap. Report when a list cannot be queued. startQueue refuses synchronously when queueing is unavailable and does not run the onAborted callback, so running a list from the project new-chat composer silently did nothing from both the Run button and the bookmarked-list menu items. * Studio: auto-scroll the prompt list while dragging A list taller than the detail pane could only be reordered within the visible region: the pointer handler hit-tested coordinates but never scrolled the overflow-y-auto ancestor, and pointerdown suppresses the browser's own drag gesture, so there was nothing to pull the list along. Holding a grip near the top or bottom edge now scrolls the pane and re-runs the hit-test each frame, so a drag can reach any row. The step ramps with depth into the edge band and is capped per frame. The step calculation lives in its own module with unit tests covering the dead zone, both directions, the ramp, the cap, and panes too short to hold two edge bands. * Studio: clear the search when selecting a newly created prompt or list Awaiting the refresh was not enough on its own. With a search active that the new entry does not match, the refreshed rail still excludes it, so the keep-a-row-selected effect bounced the selection to the first row that did match and the form closed on someone else's prompt. Clear the search alongside the selection so the new entry is eligible for the filtered rail. Applies to both create forms. * Studio: remeasure auto-grown textareas on resize, and end a drag released off-window The auto-sizing textarea only remeasured when its value changed, so any width change that rewrapped the text left the old height in place. With overflowY set to hidden that clipped the newly wrapped lines until the next keystroke. It now remeasures on window resize, and on a ResizeObserver width change for the cases where the column moves without the window doing so. The grip deliberately does not capture the pointer, so releasing the mouse outside the window delivered neither pointerup nor pointercancel and the drag stayed live, still autoscrolling and reordering. A move reporting no buttons held is now treated as the release that was missed, and window blur ends the drag for a release that happens entirely off the page. * Studio: export the visible draft, and ignore non-primary presses on grips Export passed the saved entry while the pane could be showing unsaved edits, so the downloaded file silently disagreed with what was on screen. It now exports the draft when there is one, normalised the way saving would normalise it, for both prompts and lists. A right- or middle-press on a reorder grip started a drag, and the zero-buttons recovery could not end it because buttons reads 2 or 4, so opening a context menu over a grip could reorder the list. Reordering now starts only on a primary press; touch and pen contacts report button 0 so they still drag, and isPrimary keeps a second finger from starting a competing drag. * Studio: run the visible list draft, scope drags to one pointer, keep new-entry drafts Run queued entry.items while the editor could be showing something else. Worst case, deleting every draft item left the button enabled off the stored length and silently ran the whole old list. Run now fires the visible non-blank items and disables on those. The window-level drag listeners saw every pointer on the device, so a second finger's movement reordered using its own clientY and its release ended the first finger's drag. The initiating pointerId is now recorded and the other pointers are ignored. The new-entry forms held their name and text locally, so selecting any row in the rail unmounted the form and discarded a half-written prompt or list without warning. That state now lives in the parent alongside the edit drafts, and the New button carries a dot while a draft is waiting. Starting a bookmarked list bypassed the busy gate that ordinary sends respect, overwriting the queue refs and firing another send on top of a run already in flight. It now refuses while a run or an existing queue is active and says so. * Studio: block list runs while dictating, bind drags to one pointer, shrink the body floor Ordinary sends gate on isDictating and this path did not, so selecting a bookmarked list mid-dictation set the composer text and scheduled a send that a landing transcription could overwrite first, queueing the dictated words instead of the saved prompt. isPrimary is scoped per pointer type, so on a hybrid device a primary mouse or pen press passed the guard while a touch drag was already running and took the drag over, stranding the pointer that started it. Pointer-down is now rejected outright while a drag is bound. The body floor took a flat share of the viewport, so on a phone in landscape it still added up past the dialog's 94dvh once the ~13rem of non-shrinking header and tab/search chrome was counted, and the detail actions were clipped. The floor now subtracts that chrome, and clamps at zero when the viewport is shorter than it. * Studio: let the stacked rail shrink, scope the abort reopen, narrow the delete race The stacked grid kept a hard 96px minimum on the rail row, which with the gap and padding exceeded the whole body floor on a short viewport: the detail pane collapsed to zero height and its actions overflowed into DialogContent's clipping region, undoing the floor fix. The rail row is now shrinkable and the gap and bottom padding tighten below sm. The queue abort callback reopened the storage dialog, which was right for a run started inside it but threw a modal over the destination chat when the run came from the "+" submenu. The launch source is now passed through so only a dialog-started run reopens it. Deleting awaited the request and then cleared the selection outright, so selecting another row while the delete was in flight was undone. The deleted id now goes up and the parent clears only if it still matches. * Studio: give the shrunken panes an overflow path, confirm deleting a dirty entry Shrinking the grid tracks did not shrink what was inside them. On a short viewport the rail's new button and count footer, and the detail pane's name field, metadata and action row, still overflowed their tracks and spilled into DialogContent's clipping region, so the actions stayed unusable at exactly the size the previous change targeted. Each pane now keeps the minimum its own fixed chrome needs and the body scrolls when those minimums do not fit. Delete sits beside the draft controls in this layout, where the old one was hidden while editing, so a single click destroyed the stored entry and the only copy of the unsaved draft together. Deleting a dirty prompt or list now asks first and names what is being lost. * Studio: harden the bookmarked-list run guards and the draft maps The busy guard read React state that only refreshes on the 200ms handle poll, so a list started in the window right after a send queued over the live generation. It now asks the handles directly, the way that poll does. A staged image or audio attachment was left in place, and send() picks those up, so the first prompt in the list went out with the attachment and the rest without it. Running a list while something is staged is now refused rather than clearing it, since the attachment belongs to the user. The draft maps were plain objects keyed by entry id. Ids come from storage and may be any string, so an entry called "constructor" or "toString" resolved to an inherited prototype member: the row read as permanently dirty and the inherited function's own `name` could land in the editor as the entry name and be saved from there. They are Maps now. * Studio: refuse bookmarked list runs while the image editor is open The composer is deliberately raised above the generated-image overlay, so the "+" menu stays clickable while an image edit is pending. Submitting normally rewrites the prompt into an edit instruction, sets the pending image reference and closes the overlay; startQueue appends the saved text untouched, so the first list prompt was either applied to the selected image or consumed the pending reference outright. Running a list now refuses while the overlay is open and says why. The shared composer has no overlay of its own, so this is limited to the chat thread path. * Studio: trim the prompt storage comments Several had grown to five or more lines, restating the reasoning from review rather than the fact a reader needs. Each is now at most three lines and keeps only what is not evident from the code: why there is no pointer capture, why the hit-test uses layout offsets, why the draft maps are Maps, and so on. No behaviour change. * Studio: namespace the saved-items menu keys, and make the empty drafts factories Prompts and lists live in separate tables with independent ids, and the "+" submenu renders both as siblings, so a shared id produced duplicate React keys and the wrong row could be reused or dropped on an async refresh. Keys are prefixed by kind in both composers. The empty new-entry drafts were shared module constants, so every reset handed back the same `items` array. Nothing mutates it today, but one in-place edit would corrupt it permanently; they are factories now. * Studio: address the review on prompt storage Serialize the mutations. PUT is an unconditional upsert, so a Save pressed while a DELETE was still in flight wrote the row back. Both details now refuse a second mutation while one is pending, and report a failure instead of swallowing it. Reorder by insertion slot rather than by the row under the pointer. Hit-testing the containing row oscillates across uneven heights: drop a short row onto a tall one and the tall row is still under the pointer, which sends it straight back. reorder.ts counts the passed midpoints of the other rows, which has a fixed point at every pointer height. FLIP off layout offsets. Client rects move with the scroll position, so scrolling between reorders baked the accumulated distance into every transform. Hand autoscroll outwards through the whole scroll chain. A nested scroller reports its unclipped height, so its edge could sit past the ancestor hiding it and past the viewport, where the pointer can never reach it. clipSpan intersects the pane with what clips it. Give the rail a roving tabindex and aria-current, so reaching the editor no longer means tabbing through the library. Sequence the plus-menu refreshes and drop the rows on failure, so a stale or deleted list cannot be queued from the menu. Guard the composer paths the earlier rounds missed: dictation on the chat thread's menu, and audio still being read into base64, which pendingAudio cannot see yet. Fix the lint the new component tripped: refs read during render, and setState called synchronously from an effect. * Studio: split the prompt storage PR down to the layout change Per review: land the master-detail relayout on its own. Three things that rode along with it come out, to follow separately once this is in. Bookmarked lists in the "+" menu. The pinnedListIds store, the pin control on a list, the pinned marker in the rail, and the menu entries in both composers. thread.tsx, shared-composer.tsx and plus-menu-prefs-store.ts go back to main untouched, so the guards those menu entries needed (live handles, dictation, staged attachments, the image overlay) travel with them. That also returns the storage dialog's Run button to how main queues a list. The kind pill. It exists only to tell a prompt from a list once both share the "+" submenu, so it has no reason to land before the lists do. Drag autoscroll. The module, its tests, and the scroll-chain walk in the drag loop. Reordering still works over what the pane shows; it just does not scroll to reach the rest. What stays is the layout: the rail and detail pane, per-entry drafts, the preview toggle, the auto-sizing rows and their drag/keyboard reorder, and the review fixes for that surface. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: hold prompt-storage mutation locks above the keyed detail panes The detail panes are mounted with key={entry.id}, so selecting another rail row unmounts them and the local pending lock came back false. The save is an unconditional PUT, which makes this reachable: start a Save, switch rows, switch back, Delete. If the DELETE settles first the PUT lands after it and writes the deleted row straight back. The lock now lives in the dialog, keyed by row id, and is held until the request settles. PromptListDetail had the same defect and gets the same fix. acquire and release moved to mutation-lock.ts so the transitions can be tested without a renderer, the same reason reorder.ts was split out. Five tests, mutation-checked: dropping the guard in acquire fails two of them. * Studio: decide the mutation lock from a ref, and keep edits made while saving Two review findings on the prompt-storage dialog, both real. The lock read its own outcome out of a functional updater: set started inside the setMutatingIds callback, then check it on the next line. React does not promise to run that updater during setState, so the check could see false, skip the request, and still acquire the id later during render, leaving nothing to release it and the row's Save and Delete disabled for good. That was a defect I added with the lock itself. A ref is now the authority and the decision is made synchronously; the state exists only so the buttons re-render. Separately, a save cleared the draft unconditionally on success. The editor stays usable while the request is in flight, so anything typed meanwhile is newer than what the server was sent, and clearing threw it away. Both panes now snapshot what they submit and clear only if the draft still matches, so a newer edit survives and the row stays dirty. The list editor had the same defect. samePromptDraft and sameListDraft live in mutation-lock.ts rather than the dialog because the test runner cannot import a .tsx, which is the same reason reorder.ts exists. Eight tests, all mutation-checked: neutering either comparison fails two, restoring the deferred-updater pattern fails one. * studio: end a prompt-storage drag for the pointer that started it The reorder grips deliberately skip setPointerCapture, so pointermove, pointerup and pointercancel are handled on window and see every pointer on the page. `isDragPointer` treated a null `pointerIdRef` as a match, which is the state an already-ended drag leaves behind. endDrag clears the id, but React only unsubscribes the listeners on the next commit. A window blur while the button is still held ends the drag and then matches the very next pointermove, so evaluate() reorders the list again after the drag was over. `ownsDrag` in reorder.ts now requires a live id, and it is pure so the case is testable without a renderer. * studio: capture the prompt-list FLIP baseline at the reorder The baseline was re-recorded in the layout effect keyed to [uids, items], so it only tracked commits that changed the order or the text. Row heights move without either: toggling Preview swaps every textarea for a rendered markdown block, and a resize regrows the auto-sizing textareas. The next drag then animated from offsets that described a layout no longer on screen. With rows 100px tall and a baseline left over from 40px rows, swapping the first two rows transforms the untouched third row by 120px and animates the swap over 42px instead of 102px, so the whole list visibly jumps. applyOrder now reads the offsets when the reorder is requested, which is FLIP's "first" by definition and is correct for the keyboard path too. flipShifts in reorder.ts holds the arithmetic so both cases are testable without a renderer, and the effect no longer forces a layout read on every keystroke. * studio: guard and report the prompt-storage create paths Saving from NewPromptForm or NewPromptListForm awaited savePromptEntry / savePromptList with no lock and no catch. Both defects follow from that. A second click before the first request settles mints a second newId() and stores a duplicate row, because the id is created inside the handler and the Save button is only disabled on empty content. The by-id mutation lock cannot cover this: the row has no id until the request is built. savePromptEntry throws through parseJsonOrThrow on any non-2xx, and the rejection had nowhere to go. The handler stopped before onClose, so the form stayed exactly as it was with no toast and no error, which is what a successful create with a slow refresh also looks like. The edit panes already toast; the create paths now do too. useCreateGuard decides from a ref rather than the state it schedules, for the reason mutatingRef already gives. * studio: refresh before clearing a saved prompt-storage draft The detail panes render `draft?.text ?? entry.text`, and `entry` stays the pre-save copy until listPromptEntries comes back. handleSave cleared the draft first and left the refresh unawaited, so for the length of that request the editor showed the text as it was before Save, then snapped to the saved text. Renaming showed the old name in the same way. Awaiting the refresh and clearing after it keeps the draft over the entry until the saved copy is there to replace it. It also widens the window in which samePromptDraft protects an edit made during the request, which is the point of snapshotting what was submitted. The prop is typed as returning a promise now rather than being called and dropped. * studio: refresh before clearing a deleted prompt-storage row PromptStorageDialog keeps a row selected during render: when the selected id is not in the filtered rail it falls back to the first row. handleDelete cleared the selection and then left the refresh unawaited, so that pass ran against a promptEntries that still held the deleted row, and returning from the callback released the mutation lock while the refetch was still out. Measured against a harness with a 1200ms refetch, 350ms after confirming a delete: the rail still lists 8 rows, and Delete and Use on the pane report disabled=false. Deleting the first row leaves the pane rendering that row, since the fallback picks it straight back out of the stale list. Deleting any other row moves the selection to row 1 rather than to the deleted row's neighbour. Awaiting the refresh inside the lock means the fallback runs against a list the row has already left and the controls stay held until then. Same harness, same instant: Save and Delete both report disabled=true, and the selection settles on one row, once. Both detail panes had it; both are fixed. * studio: drop the guessed height floor on the prompt-storage body The body carried min-h-[max(0px,min(420px,calc(94dvh - 13rem)))], where 13rem stands for the header, tabs and search above it. DialogContent is overflow-hidden, so whatever the dialog's own children add up to past its height is painted nowhere, and the floor only holds while that chrome really is 13rem tall. It is not on a narrow dialog. At 320x320 in Chromium the title wraps to two lines and the description to six beside Import and Export, so the chrome is about 284px while the floor still claims 92.8px for the body. DialogContent then measures clientHeight 320 against scrollHeight 377: the body's scroll port is 93px tall with only 36px of it on screen, so a row scrolled to the bottom of that port lands in 57px the dialog never paints. main has no floor and does not clip, so the mismatch arrived with the master-detail layout. min-h-0 removes the guess and makes the port honest. The floor never did any work anywhere else: at 390x844 it asks for 420px of a 628px body, at 740x360 for 130px of 152px, and at 568x320 for 93px of 134px. The grid rows already carry the 132px and 272px each pane needs and the body scrolls to them. Measured in Chromium at 320x320, 568x320, 640x360, 667x375, 740x360, 390x844, 600x800, 1024x700 and 1280x860: clipping is 0px everywhere, and scrolling Use, Save, Preview and Run into view leaves each one inside every clipping ancestor on both tabs. That last part already held before this commit; what changes is that the body no longer claims height the dialog cannot show. * studio: hold the prompt-storage create guard above the New forms useCreateGuard lived inside NewPromptForm and NewPromptListForm, which are mounted only while showNewPrompt or showNewList is true. Selecting a rail row turns that off, so a create still in flight loses the guard that was blocking a second one, and reopening New mounts a fresh guard reading false over a draft the parent still holds. Against a harness with a 1500ms PUT: Save, click a rail row, click New prompt, Save again. Before, the second Save is enabled and two ids reach the backend, so one prompt is stored twice. After, it is disabled and one id goes out. This is the same mount-boundary mistake the row mutation locks are held above the keyed detail panes to avoid. Both guards now live in PromptStorageDialog and reach the forms as props, one per kind so a prompt create and a list create stay independent. * studio: keep a new-entry draft that moved on while its create ran The New form's fields stay editable while its request is out, and Cancel is live during one too, so the draft the parent holds can differ from what was sent by the time the create lands. Both forms called the parent's onClose on success, which resets that draft outright. Against a harness with a 1500ms PUT: type "first half", Save, then finish the sentence while the request runs. Before, reopening New shows an empty form and the tail is gone, saved nowhere. Cancel mid-create, reopen New, and type a different draft: that one is wiped too when the first request lands. Both create paths now hand the submitted snapshot up, and the parent resets only when the draft still equals it, reusing the samePromptDraft and sameListDraft comparison the edit panes already settle on. onClose stays what Cancel means, an outright discard. * studio: let an oversized prompt list wait before mounting its editor Selecting the Prompt Lists tab auto-selects its first row, and the detail pane mounts SortablePromptItems for every item straight away: one controlled textarea, one grip and one ResizeObserver each. That cost grows faster than the item count. Measured in Chromium against a harness whose first list is N items, timing the tab click until the detail pane settles: N this PR main 50 146 ms 79 ms 100 246 ms 82 ms 500 2465 ms 82 ms 2000 35586 ms 70 ms main is flat because the collapsed card rendered `items.slice(0, 3)` and only mounted the editor when the user clicked Edit. The backend takes 10000 items in one list (studio/backend/routes/prompts.py), which an import can produce, so this is reachable by opening a tab. Past EDITOR_ROW_LIMIT the pane shows the first five items and an "Edit all N prompts" button instead, and mounts the editor when that is clicked. At the limit it still mounts: 100 items 246ms, 101 items 76ms and 115 nodes, 10000 items 80ms. Deferring the editor changes nothing about what is stored. Save, Run and Export all read `items`, not the mounted rows: renaming a deferred 2000-item list and saving sends all 2000 back, first and last intact. * studio: leave the view alone when a create lands after the user moved on selectCreatedPrompt cleared the search, selected the created row and hid the New form unconditionally. A create can take long enough for none of that to be where the user is any more: selecting a rail row, switching tabs or reopening New all happen while the request is out. Against a harness with a 1500ms PUT. Save, then click the fourth rail row: before, completion pulls the pane off "Explain this regex". Save, switch to Prompt Lists, type "docs" in the search there: before, completion empties that box. Both hold after. Each form now carries a mounted ref and reports it, so the parent moves the view only while the form that started the create is still the one on screen. Reopening New mounts a different form, which reports false for the old request, so a second draft is left alone too. The draft reset stays outside the guard: a draft that still matches what was sent is now a saved row wherever the user went, and keeping it would leave the + button marked unsaved for it. * studio: correct the prompt-storage selection for the visible tab only searchQuery is shared by both tabs, and the keep-a-row-selected pass ran over both collections every render. Filtering one therefore also filtered the hidden one and dropped the row it had. Select "Docs sweep" on Prompt Lists, switch to Saved Prompts, search "rewrite", switch back: before, the pane opens on "Release checklist". The query matches no list, so the hidden tab's selection is cleared while the user is nowhere near it. Gating the correction on activeTab is half of it. The per-tab reset was an effect keyed to activeTab, so the first render of the new tab still held the old query and the correction ran in it before the reset landed. Clearing in the tab handler means no render sees the mismatch, and it drops one of the file's react-hooks/set-state-in-effect errors. * studio: set the New form's mounted flag in effect setup The flag that tells the parent whether the form that started a create is still on screen was initialised at the ref and only ever cleared, in an effect cleanup. StrictMode replays an effect as setup, cleanup, setup on mount, and main.tsx wraps the app in it, so that first cleanup left the flag false for the rest of the form's life and every successful create reported an unmounted form. The visible result in a dev build: create a prompt, and it saves and refreshes, but the New form stays open with an emptied draft and the new row is never selected. Measured against the harness, before: form still open, draft "", no row selected. After: form closed, "A brand new prompt" selected. Setting it in setup restores it on the replayed mount. The guard it feeds still works: with a 1500ms PUT, selecting another row or typing a search on the other tab while the create is out still leaves both alone. * studio: latch the prompt-list editor once it is mounted editorMounted was recomputed every render from the live item count, so a list sitting exactly at EDITOR_ROW_LIMIT lost its editor the moment Add prompt took it one over: the whole editing view was replaced by the deferred summary. The draft kept the new item, but the caret and the view did not. Measured on a 100-item list, clicking Add prompt: before, the pane goes from 100 textareas to 0. After, 100 to 101. The decision is now state initialised from the count at mount. The pane is keyed by row id, so selecting another list still re-decides it, which is the part that should depend on size. * studio: hide Preview while the prompt-list editor is deferred The deferred branch renders the five-row summary and ignores `preview`, but the toggle stayed on the toolbar. Clicking it on a list above EDITOR_ROW_LIMIT left the same raw, line-clamped rows on screen and relabelled itself to Edit, so the control claimed a preview that was never rendered. Measured on a 500-item list: before, the toolbar carries a Preview button alongside "Edit all 500 prompts". After, it does not. A list under the limit is unchanged, toggle and all. * studio: namespace prompt-storage mutation locks by entry kind Prompts and prompt lists are separate tables with independent id spaces, and the backend takes arbitrary ids up to 128 characters, so an import can give one of each the same id. Both panes fed the raw id into one mutatingIds set, so saving prompt x marked list x pending and disabled its Save and Delete until that unrelated request settled. lockKey prefixes the kind, which is enough on its own: reaching a list key needs a list, since a prompt id of "list:abc" keys "prompt:list:abc". --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Maheswar Kumar <[email protected]>
) * Studio: add Chat settings to disable or ease GGUF auto-compaction Local GGUF chats always opted into truncate_oldest, then compacted at the prompt budget with a 25% extra trim (or a full checkpoint reset). Settings now let you turn that off, switch to a sliding window, and choose how much extra room a rolling compaction takes. Compaction still keys off the configured context length, not free VRAM. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: honor Chat compaction settings over process defaults Send checkpoint/error overflow fields from Studio so Chat settings override UNSLOTH_CONTEXT_POLICY and UNSLOTH_CONTEXT_OVERFLOW. Refuse checkpoint-origin sticky boundaries when a request forces rolling, and route search_conversation from the same effective policy as the fitter. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * honor zero compaction headroom * test zero-headroom rolling compaction * preserve server compaction policy by default * test server policy inheritance * mark studio-owned tool history * keep studio tool history on the fitted path * isolate studio tool history provenance * test compaction after local tool use * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * complete locale settings translations * fix sanitized catalog guard coverage * run pip cache guard on workflow changes * set utf-8 for pip cache guard reads * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * mark studio tool history in token counts * reset boundaries when context policy changes * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * mark studio tool history from replayed calls Hosted server builtins such as web_search are dropped during OpenAI serialization, so ownership must be derived from the calls that actually go on the wire. Mixed hosted-plus-local history can then keep the studio_tool_history marker and stay on the compaction path. * align prune contract test with token-count history builder The send and count paths both prune through pruneOutboundHistory into survivingMessages; the source contract still expected the old outboundMessages name on the count path. * align sticky and token-count harnesses with current compaction APIs Recall fixtures store rolling-shaped truncation records, so pin CONTEXT_POLICY to rolling when faking studio_db. Recount and prune harnesses follow the renamed token-count builder, a tighter setActiveThreadId slice, and the send-path prune call rather than the earlier count-path copy. * test(studio): follow main's chat-completions extract and VRAM/keyless moves Source-inspection contracts still pointed at openai_chat_completions after #9187 split produce_openai_chat_completions out, and at strings that #7880 and #9683 moved. Point them at the live sites and defer PEP 604 unions in the new kv-cache estimate tests. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * drop the duplicate workflow guard entry this pr added tests/studio/test_pip_cache_naming.py was already listed at line 141 of .github/workflows/workflow-trigger-lint.yml, so the Workflow guard suites step collected it twice. The trailing newline it also removed goes back. * keep the eviction bite for requests that chose no compaction setting fit_rolling_context gated the 5% floor on each eviction bite on `headroom > 0`, but keeps_boundary = False zeroes the headroom for every threadless API request and incognito chat. Those callers send no new field, so they were handed the "no extra trim" behaviour anyway: on a 201-message transcript at context_length 1100 eviction fell from 12 messages to 2. Gate it on the requested ratio instead, so only a caller that actually asked for no extra trim gives the floor up. * replay a rolling boundary where the fit cannot start an epoch _sticky_compaction_boundary rejected any boundary whose recorded policy differed from the process policy, in both directions. The rolling-to-checkpoint direction is only unsafe where fit_checkpoint_context would read the boundary as an epoch already in force and skip the reset's recall, and that needs _can_reset_epoch. Threads it refuses -- a template that cannot render tools, --disable-tools, no conversation archive -- compact through fit_rolling_context and record a rolling boundary, so on a checkpoint-default server every later turn discarded it and the boundary slid again. Measured on a stored boundary of 6: base restored 6, this branch returned 0. Each call site now computes _can_reset_epoch once and hands the same value to the boundary read and to the fit. * declare studio_tool_history on the token-count request refreshContextUsage forwards the marker, but ChatCountTokensRequest only carried it through extra = "allow", which coerces nothing. A client sending the JSON string "false" reached _only_studio_tool_history as a truthy value and moved the count onto the Unsloth tool path the completion never takes, so the context-usage bar priced a different prompt. The model's own bypass_permissions field is declared for the same reason. * restore the constraint the renamed tool-history helper documented Renaming _only_studio_memory_tool_history to _only_studio_tool_history replaced its docstring with three lines that say what the marker is and no longer say why the strict route exists: a replayed tool pair read as a client contract sends the turn to the llama-server passthrough, which runs no context fit, so the epoch, the carried-forward block and the automatic recall are gone one turn after the compaction that created them. Put that back, and match the sentence case the rest of the file and the api.ts field comments use. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * keep a rolling boundary off the checkpoint replay branch A request that may not reset still takes the checkpoint REPLAY branch in _fit_context under a checkpoint policy, so the rolling-origin boundary the previous commit restored reached fit_checkpoint_context and read as an epoch already in force. The fit returned checkpoint_started false, and _archive_and_recall reads that as "already recalled" and injected nothing. Measured at context_length 1800 with a stored boundary of 30: the reply lost the archived turns the rolling fallback would have pulled back. _sticky_compaction_state now returns the depth and whether a checkpoint reset recorded it, mixed provenance across surviving rows counting as rolling since min(boundaries) may pick either row. _fit_context takes that as sticky_is_checkpoint and enters the replay branch only for a real epoch; otherwise the count stays on the rolling fitter, which reports no checkpoint_started and still recalls. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * discard a boundary cut with more extra trim than the request asks for Phase one of fit_rolling_context re-applies the saved boundary before anything else and returns as soon as the result fits, so an already-compacted chat that moved from 25% extra room down to 10%, 5% or none replayed the deeper cut and never reached the phase that reads the new ratio. Lowering the setting did nothing at all, and the history the client had re-sent stayed dropped. The persisted truncation now carries boundary_headroom_ratio beside boundary_messages and boundary_anchor, written through one _boundary_metadata helper so the three cannot drift apart. _sticky_compaction_state refuses a rolling boundary recorded under a larger ratio than this request wants; a larger request needs no refusal, since phase two moves the boundary out by itself. Rows saved before the ratio existed carry no key and replay as they did, and a checkpoint reset ignores headroom so its depth is never refused over it. * refuse a replayed boundary on any change of extra trim, not just a cut The previous commit only refused a boundary recorded under MORE headroom than the request asked for, on the reasoning that phase two would widen a shallower one by itself. It does not: phase one re-applies the saved count and phase two runs only when the result still does not fit, so a shallower boundary that already fits is just as inert. Measured on a 121-message transcript at context_length 1600, a stored boundary of 86 gave dropped 86 under both 0.05 and 0.25, so raising the setting did nothing either. Compare for equality instead. With the 5%-origin boundary of 86 above, a request at 0.05 still replays it and a request at 0.25 recomputes to 94. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: mahiatlinux <[email protected]>
…is large Five review items, plus current main merged in. At a result budget of zero there is no body to append a notice to, so _truncate returns the zero-room stub, whose text carries neither the truncation marker nor any of the result. _is_window_notice missed it, which skipped the starved-result nudge and put the arguments back in the no-progress key: a model reading one file in different slices then repeats forever, the exact loop the guard exists to stop. A continuation was sized against the caller's whole cap. The remainder reached the payload only after the preflight and the reply-room check had both priced the turn as if it could still emit the lot, and prompt_budget shrinks as max_tokens grows, so a 100-of-1000 continuation evicted history it never needed to lose. One value is read at the top of the iteration and used for every sizing decision. Only the finish reason was reset when a final-pass continuation was accepted, so an attempt that reported no usage was charged the previous attempt's numbers a second time. The reply's total double-counted and a cap read off it could look spent while there was room. _blamed_role returned the file category whenever any call in a parallel batch was edit_file. A small edit beside an oversized python or MCP payload was diagnosed as a file that is too large, advice that cannot shrink what caused the refusal. The category comes from the largest call now. The context-length message described Max Tokens as already unlimited. That is true for one of the two cases reaching it, and false for the other: a finite cap the prompt left no room for lands there too, and telling that user their cap has no limit contradicts the number in their own Settings. It now says raising the cap cannot create room the window does not have. _edit_file_apply_all also carries an empty-pattern guard now. Not a live path, since _edit_file rejects every empty old_string before calling it, but a zero-length pattern cannot advance the span scan, and a hang is worth a guard even behind a caller that prevents it. Each fix has a regression test confirmed to fail without it. Affected backend modules 615 passed, frontend 5756 passed, tsc and ruff clean.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5ac0218050
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (settings) cachedFraction = settings.fraction; | ||
| else routeAbsent = true; |
There was a problem hiding this comment.
Retry transient VRAM-budget read failures
loadVramBudgetSettings() returns null for any non-rethrown failure, including transient network/HTTP errors and superseded reads, but this branch treats every null as proof that the route is absent. If the initial catalog read fails temporarily, routeAbsent prevents every subsequently mounted card from retrying for the rest of the session, so fit badges and variant sorting use the default fraction instead of the user's saved VRAM budget. Only cache route absence when the failure is specifically a 404.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Out of scope for this PR, and that is my fault rather than yours. use-vram-budget-fraction.ts is not a file this branch touches: a rebase I did last round replayed ten of main's commits as new SHAs, which put other people's work into the diff you were handed. I have merged main properly instead, so the diff is back to the 25 files this PR actually changes and this one is not among them. The observation may well hold against main; it is just not something this PR should carry, so I am not acting on it here.
| await onRefresh(); | ||
| onSaved(submitted); |
There was a problem hiding this comment.
Keep drafts when post-save refresh fails
When the PUT succeeds but the immediate list refresh fails, onRefresh() still resolves because refreshEntries catches and discards every error, so onSaved(submitted) clears the only draft and reveals the stale pre-save entry. The user can then unknowingly overwrite the successfully saved text by editing that old copy; the list-save and create paths make the same success assumption. Have the refresh propagate failure or update the local collection before clearing the submitted draft.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same as above: prompt-storage-dialog.tsx came from #8692 on main, not from this branch, and only appeared in the diff because of a bad rebase on my side. The diff is corrected now. Worth raising against main on its own if it holds.
| # fixed, one added) cannot slip through on set membership alone. | ||
| added = [p for p in offenders if p not in STUDIO_UNION_DEBT_FILES] | ||
| removed = [p for p in sorted(STUDIO_UNION_DEBT_FILES) if p not in offenders] | ||
| assert len(offenders) <= len(STUDIO_UNION_DEBT_FILES), ( |
There was a problem hiding this comment.
Fail the union ratchet when offender identities change
If one recorded offender is fixed while a different Studio file introduces an evaluated PEP 604 union, the offender count stays unchanged and this assertion passes even though added contains the new file. That lets a newly added module remain unimportable on the declared Python 3.9 floor, exactly the swap the preceding comment says the set-based ratchet should reject. Include not added in the assertion rather than checking only the total count.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same cause: tests/test_python39_compatibility.py is main's, from #9826, and was pulled into this diff by my rebase rather than by any change here. Corrected now. For what it is worth I agree the set-based ratchet should assert on added rather than on the count alone, but that belongs to the PR that owns the file.
Four review items, two of them P1. The final pass emitted an empty status before each continuation, copied from the in-loop re-prompt. That status is the OpenAI route's iteration boundary and clears its prev_text cursor, but this pass keeps cumulative across attempts on purpose, so the retry's first content event carries the whole prefix again and the client was sent the partial answer a second time. The informative status still goes out; only the reset is gone. The tool-execution block restored the caller's continue_final_message before the turn's assistant message was recorded, so a turn resumed mid-answer that then called a tool appended a second consecutive assistant message rather than merging into the partial. That is the role alternation append_assistant_turn exists to preserve, and strict templates reject it. The flag is captured before the reset and used for both append sites. A reply the window replaced was read as proof of a write. Under a near-zero result budget the real answer, including an Error, is swapped for a stub saying there was no room for it, and that stub carries none of the failure markers, so compacted arguments were labelled already written when the edit may have failed. Window notices are inconclusive now and get the neutral wording. The result budget and the room target still priced against the caller's whole max_tokens on a continuation iteration. With 100 of 1000 tokens left that reserves room the request will not use and can starve a read there was space for. Both use _iteration_max_tokens, as the preflight already did, and so does the compaction rescue that re-prices after it. Each fix has a regression test confirmed to fail without it. Affected backend modules 753 passed; the one failure, test_the_body_is_the_length_the_notice_claims, reproduces on a pristine main worktree and is not from this branch.
…is large Four review items. The conversation-recall budget still reserved the caller's whole max_tokens on a continuation iteration, so a search_conversation issued by a recovery turn with a fraction of its allowance left got a near-zero budget and dropped context the request had room for. Both retrieval-budget sites now use _iteration_max_tokens, matching the result budget and the preflight. A refused call under 1024 characters kept its arguments verbatim, because the refusal path inherited the general history-compaction floor. That floor exists so a receipt never costs more than what it replaces, which the size check at the end already guarantees; for a refusal the trade is always worth making, since the refusal message is about to be added to a prompt that already does not fit. The floor is skipped for refusals and the leaf threshold drops to the point where a leaf is longer than the receipt describing it. An overflow was attributed to the newest MESSAGE, but on the strict templates the assistant tool_calls block renders only once its reply is present, so the marginal cost of that reply includes arguments that were invisible until then. A turn whose bulk is a large python or MCP payload was reported as a large tool result. The paired call is consulted now, and only wins when it is the bigger half: a dominant tool result still gets the tool advice, which is what the existing cases assert and what my first attempt at this broke. Cap attribution passed customContextLength, the editable field. The store's own definition of a pending context edit is that field differing from loadedCustomContextLength, so a model still serving at 4096 while the box reads 8192 had its stop reported as user-imposed. It reads the loaded value now. Each fix has a regression test confirmed to fail without it. Affected backend modules 625 passed, frontend 5765 passed, tsc and ruff clean.
…into r9768 # Conflicts: # studio/backend/tests/test_no_progress_tool_results.py
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6b8873f82a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| _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 |
There was a problem hiding this comment.
Compact refused payloads whose bulk is spread across fields
When an oversized refused call is composed of many strings shorter than _REFUSED_LEAF_FLOOR (for example, an MCP payload with twenty 100-character fields), this branch selects 110, _shrink elides nothing, and compact_refused_tool_arguments returns the original multi-kilobyte arguments unchanged. The refusal tool message then makes strict templates render those same arguments, so the next generation can still exceed the context window and return a context error instead of the actionable refusal. For refused calls, compact the aggregate payload—or otherwise summarize the whole argument object—when no individual leaf clears the threshold.
Useful? React with 👍 / 👎.
| if role == "tool": | ||
| continue |
There was a problem hiding this comment.
Stop pairing a later parallel reply with the whole call batch
When a parallel tool-call batch already has one reply and the newest message is a later reply, this branch skips the intervening role=tool message and pairs the newest reply with the original assistant batch, then compares the sum of every call's arguments with only the newest reply. On templates where the first reply already made the assistant call block render, those arguments are part of the existing prefix rather than the newest turn's marginal cost, so a large earlier call can make an overflowing later result be diagnosed as an oversized call and produce advice to shrink the wrong payload. Stop the pairing at an intervening tool reply or measure only the costs newly introduced by the latest reply.
Useful? React with 👍 / 👎.
| max_tokens = max( | ||
| int(max_tokens or 0), _reply_floor(self._effective_context_length) | ||
| ), |
There was a problem hiding this comment.
Fit recovery evictions against the remaining output cap
When a continuation has only a small fraction of an explicit max_tokens allowance left, this fallback still fits the candidate using the caller's original cap. For example, after 900 tokens of a 1,000-token cap have already been emitted in a 4,096-token window, the retry can produce at most 100 tokens, but this reserves 1,000 and may evict roughly 744 more tokens of useful history than the 256-token reply floor requires. Both the in-loop and final-pass continuation paths call this helper after computing their remaining cap, so pass that per-attempt remainder into the fit rather than reusing max_tokens.
Useful? React with 👍 / 👎.
What this fixes
A chat at a 4096 context died with:
edit_filehad already written the file, so the side effect was spent on a turn that could never be served.Measured through the model's own template and tokenizer, against the exact llama-server that returned the 400:
The +2992 is not the tool result. It is the assistant's own
edit_filearguments, 8742 chars of HTML innew_string, which the Qwen template only renders once atoolmessage follows the call.tool_result_budgethad already squeezed the result to nothing and it made no difference.Chasing that one thread turned up nine defects, all on the same theme: at a small window a tool-using turn ends with nothing to show. They interleave in the same functions, which is why they are one branch.
The fixes
1. Completed tool-call arguments were replayed verbatim forever
Once a tool has run, its arguments no longer need replaying: the side effect landed and, for the file tools, the content is on disk. A whole-file write kept costing its full size on every later turn.
Completed calls are now compacted in the in-flight conversation to a placeholder naming the size and destination. The stored thread and what the tool received stay byte-identical, following the
strip_result_for_modelprecedent.Four triggers, in precedence order: pre-execution fit, run-then-compact (run it anyway and compact its own arguments after), reply room before every generation, and refusal last.
2. The fit was discovered after execution
The loop computed the result budget, ran the tool, then built the prompt that got rejected. The check is hoisted above
_invoke_tooland prices the prompt that would be sent, using an emptytoolmessage as a probe. Without that probe the measurement misses the arguments entirely, because the template does not render them until a result answers the call.The gate uses the window minus a small reply floor rather than
prompt_budget. An earlier revision usedprompt_budgetand refused turns at 3504, 3549 and 3740 tokens that llama-server would have served.3. edit_file took a single edit per call
Building a file meant one call per hunk, and at a small window the model spent whole turns chunking a file and ran out of turns before finishing.
edit_filenow takes a batchededits[]array. Every edit is matched against the ORIGINAL text, overlaps are rejected, and application is all-or-nothing so a partial failure cannot leave a half-written file.replace_allwas rebuilt as a single cursor pass after the previous form measured 10.4s on a large file.This follows what the neighbours converged on:
edits[]in llama.cpp,multieditin OpenCode, V4A patches in Codex.4. Truncated tool-call JSON was healed into nonsense
Healing filled a tool's single required string argument with the raw text when the JSON would not parse. For a call cut off mid-stream that turned
{"code":"html = ...into a program that was literally its own broken JSON, and the model spent the rest of the turn convinced the sandbox had mangled its file.A call that ran out of input is now told apart from one that is merely malformed: truncation fails inside a string that never closes or at the very end of the input, while text that merely opens with a brace fails earlier with input still to go. The healable-argument map is also derived from the tool schemas rather than hand-kept, which had gone stale the moment
edit_filewas added.5. A turn could spend the whole window reasoning and show nothing
Two consecutive turns ended
finish_reason: lengthhaving produced only reasoning, 2301 and 2312 tokens. Against a 4096 server that is 4096 - 2301 = 1795 and 4096 - 2312 = 1784, differing by exactly the 11 tokens the prompts differ by: both ran until the window was physically full.A truncated thought is correctly not promoted as an answer, so the turn rendered empty. It now continues with a short note of where the thought reached, and thinking off, which is the one change that stops the retry reproducing the failure. If two attempts still produce nothing it says which lever to pull.
6. A starved tool result turned into a read loop
Asked to show a 2401-byte file inline, a turn spent eighteen tool calls getting nowhere:
Six of the last eight calls were priced at zero, so each returned only the notice saying it had been cut, which reads as a fresh failure rather than a wall.
Three changes: a budget below a useful floor now triggers compaction and a re-price before the call runs; a call already priced at nothing says so on the first result rather than the third; and a tool returning byte-identical results several times tells the model the answer will not change.
The no-progress guard keys on the RESULT, not the arguments, which is the point here: the arguments differed on every one of those eighteen calls.
7. An answer the window cut in half
A turn streamed a file inline and stopped mid-token at
ctx.arc(6, -5, 5, 0, with a<!DOCTYPEand no closing tag. The room that ran out belongs to the reply, not the prompt, so compaction cannot help and the answer has to span two turns.A truncated answer now resumes, with the partial handed back through
continue_final_messageso the model extends it mid-token instead of restarting. The partial is kept if it never converges.core/inference/repetition_guard.pyguards that path: a fragment that is mostly an echo of itself is kept as-is rather than extended.8. The final generation had no continuation either
At the tool-iteration ceiling the loop breaks, appends the budget-exhausted nudge, and runs a SEPARATE final generation after it. Every recovery path above lives inside the loop, so that generation had none, and a live run lost 22387 tokens of work stopping inside
drawBird().It now uses the same continuation under the same rules.
9. The unparsed-arguments sentinel reached users and models
A tool card rendered
{"__unsloth_unparsed_arguments__":"{\"path\":\"flappy-bird.html\", .... That key is internal plumbing and was escaping at both boundaries: the card showed it to the user, and the replayed assistant turn taught the MODEL a key that no tool declares.Both now go through one accessor. The card shows the fragment under
raw; the replay sends a short valid object naming the failure, because that field is parsed as JSON by the server rendering the template and a truncated fragment fails the whole request.Token cost
Tool schemas go into every prompt and came to roughly 1351 tokens, a third of a 4096-token window before any conversation.
edit_file's description was 277 of that and is now 170, with every rule kept. About 108 tokens returned on every turn.Every model-facing message was also shortened and put on one rule: continue from what you have, in parts if it will not fit at once, and finish the task. That replaced a contradiction the branch had shipped, where the compaction placeholder told the model to read the file back while three other messages told it not to.
Verification
New:
test_tool_call_arg_compaction.py,test_tool_call_arg_healing.py,test_length_truncated_reasoning_continuation.py,test_truncated_answer_continuation.py,test_no_progress_tool_results.py,test_repetition_guard.py. Extended:test_edit_file_tool.py,test_llama_cpp_tool_loop.py.542 passed across the twelve affected backend modules on the last run, alongside 3 failures that are pre-existing on
mainand named below. 5645 passed on the frontend suite.ruff checkclean on every changed Python file,tsc --noEmitclean on the frontend.Every guard was checked against a build with it disabled, to confirm the tests fail without the fix rather than passing vacuously.
End to end against the live llama-server that produced the original 400, four parallel runs of the same prompt: three produced a complete valid game (7271, 2314 and 7886 bytes, balanced braces, closing tags). The budget rescue fired seven times, each from a dead stop:
One test in
test_llama_cpp_tool_loop.pywas rewritten rather than extended: its fake token counter billed unanswered tool-call arguments, which the real template does not do, so it would have passed against the broken behaviour.Review rounds
Four rounds of review followed the original nine fixes, and 26 further items were verified, reproduced and fixed. The ones worth a reviewer's attention:
Correctness of the continuations. The first continuation fix guarded only the final generation pass. A request with tools enabled takes the in-loop path, and within that the answer branch and the reasoning branch are separate. All four now count the candidate prompt before retrying and keep the partial when the retry would not be served, and all four spend the caller's
max_tokensacross the whole reply rather than once per attempt. Without the latter, a request capped at 100 completion tokens returned roughly 300.Compaction told the model things that were not true. Tool-call ids restart at
call_0on every turn, so a conversation-wide set of answered ids let an earlier success vouch for a later call the user had declined, which was then replayed as already written. Replies are now paired with their own call site. The receipt itself is chosen from the reply rather than the tool name, so anedit_filethat ran and errored is not described as a write and apythoncall is not told nothing was written. An elidedold_stringgets neutral wording, since onlynew_stringis on disk after a replacement.Compaction did not fire when it was needed. The floor was applied per string, so a batched refactor of fifty 800-character edits was tens of thousands of characters with nothing over the floor and nothing reclaimed. Eligibility is now aggregate. The destination path is never elided, and is repeated inside a receipt only when it is short enough to be worth it: a 513-character path across four leaves cost more than the content removed, and the size check then rejected the whole compaction.
Two unbounded loops.
editsis capped at 100 entries. A lonereplace_allno longer enumerates its matches at all, since with one entry there is nothing to overlap with andstr.replacedoes the work in linear space, where spans cost a tuple per match. Bounding it instead was the first attempt and it broke the existing 300000 and 40000 match cases, so the enumeration went instead.Smaller ones. A denied call now has its arguments compacted, because the denial is itself the
toolmessage that makes the template render the call it refused. A result is sized against a prompt carrying the current call's stand-in reply, so templates that render a call only once a reply follows do not hand the result room the arguments already occupy.in_thinkingis cleared once a truncated reasoning block is closed, which was emitting a second</think>into the visible answer. An oversizedpython,terminalor MCP call is no longer told to ask for a smaller file. On the frontend, a Max Tokens cap reached together with the context wall is treated as context-bound, since raising the cap creates no room there.Two of my own tests were retargeted rather than deleted, both because a review item showed the rule they pinned was wrong: one asserted a 1023-character string is never compacted, the other that the cap wins when it ties with the context wall. Each says in its docstring what changed and why.
Notes for review
mainand not touched here: threetest_checkpoint_compactioncases and onetest_nudge_tool_calls_wiringcase that assert on the source text ofopenai_chat_completions, which is now a delegating wrapper;test_studio_evaluated_unions_do_not_grow, which reports the same 37 offenders with and without this branch; and the Frontend CI ANSI browser smoke, which fails onmainat the same locator. Each was confirmed by running it against a pristinemainworktree rather than assumed.safetensors_agentic.pyandstudio_tool_loop.pycarry the same execute-then-discover ordering and are deliberately left alone here.max_tokensunclamped against the window. Untidy, but not this bug: clamping to the room actually remaining gives exactly the generation length already observed._edit_fileandtool_loop_controller.py. Different concern (alias healing at the tools layer rather than unparseable arguments at the coercion layer), but the two will conflict textually and whichever lands second should expect to resolve it.fits: false. Two hypotheses were tested and both are wrong (_recall_top_k(0)returns 0 so a zero recall budget injects nothing; the rescue branch needsinitial_tokens >= context_lengthand 3589 < 4096). It sits in checkpoint mode, which this branch does not touch, and wants its own reproduction.