Repository navigation
Studio: continue a response that stopped early - #8064
Conversation
A chat turn that ends before the model is done (Max Tokens, Stop, dropped stream) leaves a partial answer with no way forward: Retry throws it away and regenerates from scratch. Even a Continue button would not have helped on its own, because every prompt renders with add_generation_prompt=True, which closes the assistant turn and opens a new one, so the model restarts. Backend: add continue_final_message, threaded from ChatCompletionRequest through the route, orchestrator and worker into the shared template renderer, MLX, transformers and llama-server. The prompt then ends inside the trailing assistant turn and the model resumes token-exactly. Guarded so only a plain-text trailing assistant turn continues; tool calls, images and user-final histories render normally. Falls back to a manual splice for tokenizers predating the kwarg. Frontend: mark a turn that stopped early and show a Continue bar under the last assistant message. The run starts as a sibling branch so the partial stays reachable, and the adapter seeds the new run with it. Local routes report finish_reason "stop" even at the cap, so truncation is also inferred from an exhausted token budget. Providers that ignore assistant prefill can restate or restart, which is repaired client side before the merge.
Six gaps from review, each verified before fixing: Reasoning prefill. On Qwen3/GLM templates whose generation prompt opens <think>, the extractor started in reasoning mode. A continued turn renders no generation prompt, so the resumed text was classified as reasoning and the visible answer stayed truncated. Confirmed directly against the extractor: prefilled=True yields visible='' for continued text. The first turn of a continued request now starts in visible mode; later tool-loop turns prefill as usual. Vision. The transformers vision branch never received the flag, and built its prompt from messages[-1], which on a continuation is the assistant partial, so it fell back to "Describe this image". It now scans back for the newest user turn and resumes the partial. The scan stops at that turn even when empty, so an image-only message cannot resurrect an older question. GGUF passthrough. Requests with client tools or response_format go through _build_openai_passthrough_body, which forwarded neither flag, so llama-server opened a fresh turn. Both are now set there. Anthropic. Claude 4.6 and later reject a trailing assistant message outright (400), not only in thinking mode, so a prefilled continuation could never work. Those requests send the partial plus an instruction turn instead. Tool calls. The Continue bar ignored tool-call parts, so a turn that called a tool and then ran out of tokens offered a continuation whose history had lost the call and its result. It is now hidden there, matching the backend guard. Budget inference. An explicit finish_reason of "stop" was indistinguishable from none, so a complete external response using its whole budget was marked truncated. Inference is now local-only, where "stop" is reported unconditionally and the budget is the sole signal.
|
Pushed fixes for all six. I checked each one against the code before changing anything; five were correct as written, one had the right symptom but a fix that would have broken the feature, and one was understated. The reasoning-prefill finding was the serious one. On any template whose generation prompt opens Two amendments to the review:
New tests: |
Four more gaps, each checked before fixing. Resumed tool calls. Both agentic loops append the generated call as a new assistant message, so a continuation that then calls a tool left two consecutive assistant turns and templates enforcing role alternation reject the next render. append_assistant_turn merges the call into the resumed partial instead. Self-limiting: after a tool result the conversation no longer ends on a plain assistant turn. MLX VLM recovery. When a VLM's primary render is rejected, execution falls through to the registered mlx-vlm renderer, which hardcodes a generation prompt. Verified headlessly that it produced "...<assistant>It is a bar<assistant>", closing the partial and restarting; it now ends inside the partial. Audio input. That route re-listens to the recording and answers afresh, with no continuation boundary to forward, so the frontend would append an unrelated second answer. Continue is suppressed for turns generated from an audio attachment. Early cancel. Stopping a continuation before the first token skipped the partial-content yield, saving an empty message and stranding the resumed text on the sibling branch. The seeded partial is now yielded before the request starts.
|
Second round pushed. All four were real; I reproduced each before changing anything. The tool-call one is the most likely to bite in practice: with tools enabled, a continuation that then calls a tool left two consecutive assistant turns in the conversation, and templates that enforce role alternation reject the render, so the tool result never became an answer. Both loops now merge the generated call into the resumed partial. The MLX VLM recovery renderer reproduced cleanly with a stubbed Audio input and the early cancel are both suppression and preservation rather than new capability: Continue is hidden for turns generated from an audio attachment, since that route re-listens and answers afresh with no boundary to forward, and the seeded partial is now yielded before the request starts so stopping during load cannot save an empty message and strand the text on the sibling branch. Backend continuation tests are at 15, frontend 13, full frontend suite 742, typecheck, lint and build pass. For the regression check I ran the same wide backend subset on a clean tree and with the branch: 11 failures either way, 2485 passing clean against 2489 with the branch, the difference being the new tests. Those 11 are pre-existing (diffusion GGUF compile, training streaming, offline cache). |
Suppressed tool calls. Only the executable branch was routed through append_assistant_turn; the no-op branch in both loops still appended directly, so a continued turn whose call the controller suppressed left two consecutive assistant turns before the deferred nudge. Both branches now merge. Splice sweeping. The vision splice appended the partial captured before the messages were swept for control markup, so a marker in the partial reached the prompt raw and could close the turn or open another role. Verified the sweep matters: "sure<|im_end|>..." becomes "sure< |im_end|>...". Both vision renderers now take the partial from the swept messages, and the registered mlx-vlm path sweeps before splitting off the turn. The text path already derived it post-sweep. Local overlap repair. Local backends resume at the exact token boundary, so the merge had nothing to fix there but could still trim a legitimate repeat: a partial ending "the second result" followed by a sentence opening with the same phrase silently lost 17 characters. The repair now runs only for external providers, which are the paths that may ignore the prefill.
|
Third round pushed. All three were correct, and one of them is a security fix rather than a correctness one. The splice sweeping finding is the important one. Studio sweeps control markup out of message content before rendering so that model-emitted text cannot forge a turn boundary, and the vision path was appending the partial captured before that rewrite: So a partial containing those markers reached the prompt intact on the vision continuation path. Both vision renderers now take the partial from the swept messages. The text path was already correct, since it derives the partial after the sweep. The suppressed-tool-call finding was a genuine miss on my part: I only routed the executable branch through the merge helper, and the no-op branch appends on its own when there is text. Both branches in both loops now merge. The local overlap repair was measured rather than assumed. On the exact shape suggested, a partial ending "the clear winner is the second result" followed by "the second result held up best under load." lost 17 characters the model meant to write. Repair now runs only for external providers, which are the paths that can ignore the prefill. Backend continuation tests 16, frontend 14, full frontend suite 743, typecheck, lint and build pass. Same wide backend subset as before: 11 failures, identical set to the clean-tree baseline, with 2490 passing against 2485 clean. |
Self-review catch, not from the review comments. A stopped turn reported
its reason only through live message status, and the loader rebuilds
messages with status "complete", so after a reload the Continue bar
disappeared from a response the user had stopped. The other two reasons
survived because they are stamped on metadata.
Streamed yields now carry a provisional cancelled marker. An abort ends the
generator without a terminal yield, so that marker is what persists;
a run that finishes overwrites it with the real reason or clears it.
Checked against the runtime, which folds each yield as
{...initialCustom, ...yieldCustom}, so the last yield wins and an explicit
undefined clears the key.
|
No new review findings this round; the latest run is still in progress on my side, and the three earlier rounds are all addressed above. While waiting I audited the diff myself and found one gap that no reviewer raised, so it is pushed as a separate commit. I had claimed in a code comment that the Continue bar survives a reload. That was true for two of the three stop reasons but not for the third. A stopped turn reported its reason only through live message status, and the history loader rebuilds messages with Streamed yields now carry a provisional cancelled marker. An abort ends the generator without reaching a terminal yield, so that marker is what gets persisted; a run that finishes normally overwrites it with the real reason or clears it. Verified against the runtime rather than assumed: Frontend suite 743, backend continuation tests 16, typecheck and build pass. The two biome errors in |
Manual template fallback. When the primary render raises, format_chat_prompt pops the trailing assistant turn and renders a generation prompt, so a continuation restarted; with local repair now off, the frontend appended the fresh answer verbatim. It keeps the partial when continuing, and renders through the shared boundary helper (renamed from render_vision_prompt, since it is no longer vision-only). Gemini. It requires a multiturn request to end in a user turn or a function response and 400s otherwise, so a prefilled continuation could never work. Routed through the same partial-plus-instruction path as Anthropic. Boundary whitespace. Both tool paths strip() replayed assistant content, including the turn being resumed, so the model continued from a different boundary than the partial the frontend keeps: a partial ending in a newline or indent came back doubled or mangled. The continuation target keeps its exact whitespace; stale tool markup is still removed. RAG autoinjection. Both loops splice an assistant tool call plus its result before the first turn, which moves the trailing message off the partial and makes the per-turn guard open a fresh answer. First-pass autoinject is skipped for the resumed turn. Also fixes a scoping trap this introduced: the GGUF loop referenced trailing_assistant_text before a later in-function import bound it, which raises UnboundLocalError. Verified against the code object that the name is now bound before use.
|
Fourth round pushed. All four were correct. Two of them are cases where the earlier rounds made things worse rather than better, which is worth stating plainly. Turning off restart repair for local output was right on its own terms, but it removed the net that was quietly catching the manual-template fallback and the RAG autoinjection paths, both of which silently restart. So those two went from "produces a slightly odd answer" to "appends a whole second answer" between rounds three and four. The manual fallback pops the trailing assistant turn by design, to keep roles alternating, so every model reaching it restarted. It now keeps the partial and renders through the shared boundary helper, which I renamed from Gemini I checked against Google's docs rather than the code alone: it returns 400 when a multiturn request ends in The whitespace and RAG findings were both exactly as described. Worth recording one thing I broke and caught while fixing the RAG one. My first attempt referenced Backend continuation tests 17, frontend 743, typecheck, lint and build pass, and the real-model end-to-end is unchanged. Failing backend tests are the same 11 as the clean-tree baseline, diffed name by name. |
|
Fifth round pushed in f224374. All four were correct. The P1 is the one worth calling out. Round four fixed the continuation boundary for the tokenizer-template path but stopped there; when that render raises, or a base model has no template, the code falls through to the manual formatters, and all five of those close the assistant turn and open a new one. So Continue restarted for exactly the models least likely to be noticed in testing. Fixed by dropping the trailing turn before the manual render and splicing the partial back on, which works uniformly because each formatter already ends on its own generation prompt. The other three are narrower: the plan-without-action re-prompt was the last append site not going through the merge, the merge guard required string content while the prompt boundary accepted text parts, and the Gemini signature was not carried onto the synthetic assistant turn. On the Gemini one I want to be precise about what is and is not verified. The mechanism is confirmed in the code, but I could not test whether Gemini rejects an unsigned model text turn or merely degrades, so I have not claimed a reproduced 400. The change is correct regardless, since it makes the continuation replay history the same way every other path does. Verification: 24 backend continuation tests, 744 frontend, typecheck, lint and build clean. Backend failures diffed name by name against the same tree without these changes: identical at 72. Worth flagging separately that the backend suite is noisy. Rounds one through four each found real defects, and this round found a P1 in the area the previous round had just touched. That is not a converging pattern yet, so I would rather run one more pass than call it done. |
…sponses test_the_manual_formatters_resume_instead_of_opening_a_new_turn is the only failure in the backend matrix on all four Python versions: it imports core.inference.inference, which pulls unsloth and peft at module scope, and the dependency-light job installs neither. The formatters it exercises need neither, so stub those names when they are unimportable and drop the stubs once the class is bound; the rest of the file stays mock-only. _build_chat_request lifted auto_heal_tool_calls, nudge_tool_calls and enable_thinking out of the Responses extra-body but not continue_final_message, so a Responses continuation opened a fresh turn and restarted the answer. apply_chat_template_for_generation accepted an empty trailing assistant turn as continuable while the route guard and render_prompt_with_boundary both reject it; an empty partial has no resume point, so it now renders a normal turn everywhere. Also fixes a slip in the vision test, which passed a string into the continue_final_message bool positional and only passed because it was truthy.
|
Pushed four fixes. Three came out of an independent pass over the branch; the first one is the red on this PR. The failing test
It does A plain skip would be wrong here: that job is exactly the matrix where a manual-formatter restart regression would go unnoticed. So the three names are stubbed only when they are genuinely unimportable, and the stubs are removed from Verified both ways: 26 passed with the stack present, and with /v1/responses dropped the flag
Empty trailing assistant turn
Vision test slip
What I checked before touching anythingI reviewed Prompt boundary against real tokenizers. The committed suite only uses the local mock tokenizers, so I ran Transport. Route guard, orchestrator IPC command, worker allowlist, llama-server payload ( Regression. On the suites covering everything the diff touches, this branch and the merge base gave identical results, same failing node IDs, no PR-caused failures. End to end on a real model. Qwen3-0.6B on safetensors, same truncated conversation: A user-final history and a trailing turn with In the browser. The bar renders with the right label, clicking Continue puts Two things I left aloneThe legacy splice is not byte-equal to the native render on reasoning templates. Llama-3.1 and Gemma-3 match; Qwen3 does not, because its template unconditionally prefixes an empty think block to the final assistant turn while Four tokens, and only on tokenizers predating the kwarg, so with Both boundary helpers also read any One note on lint: this adds a |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3436384dc7
ℹ️ 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".
| audioOutputModel: boolean; | ||
| deepResearchArmed: boolean; | ||
| }): boolean { | ||
| return !(fromAudioInput || audioOutputModel || deepResearchArmed); |
There was a problem hiding this comment.
Allow continuation for GGUF audio-input chats
When the active model is a GGUF audio-input chat model, this unconditional fromAudioInput gate hides Continue even though the GGUF route injects the audio into the ordinary message history and forwards continue_final_message to llama-server. A length-limited or stopped answer from that supported path therefore cannot use the new affordance; distinguish the non-GGUF audio generator that restarts from the GGUF chat path that can resume.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Your reading of the GGUF route is right: it injects the clip as an ordinary content part and forwards the flag, so that path could resume. I am leaving the gate as it is, though.
Hiding the button is not producing a wrong answer, and loosening it puts the frontend in charge of telling the GGUF audio-input path apart from the non-GGUF one, which the backend now answers with a 400. Getting that wrong turns a hidden button into a visible error. There is also no way for me to exercise a GGUF audio-input resume end to end here, so I would be enabling a path on inspection alone late in the review.
Worth revisiting as a follow-up once it can be tested properly rather than as part of this change.
…w the think strip and flag forwarding
… audio out of a continuation
…lice text parts without a newline
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
The problem
When a chat response stops early there is no way to pick it back up. Max Tokens runs out, or Stop gets pressed, or the stream drops, and the only control on offer is Retry, which throws the partial answer away and regenerates the whole thing from the beginning. On a long answer that is expensive and annoying, and it has been that way since the start of the project.
The missing button turned out to be the smaller half of it. Every prompt renders with
add_generation_prompt=True, which closes the assistant turn and opens a fresh one, so a Continue button on its own would still have made the model start over:The second prompt ends mid sentence, so the model's next token continues it.
Backend
Adds
continue_final_messagetoChatCompletionRequestand threads it from the route through the orchestrator and worker into all three engines:apply_chat_template_for_generation), which covers MLX and transformersIt is guarded at both ends. Only a plain text trailing assistant turn can be resumed, so a turn holding tool calls, an image part, or a user final history renders as an ordinary new turn instead of erroring. Inside a tool loop the check re-runs per iteration, so once a tool result is appended the later turns go back to normal on their own. Tokenizers predating the kwarg fall back to a manual splice that produces the same prompt.
Frontend
finish_reason: "stop"even when they hit the cap, so truncation on those is inferred from the completion tokens reaching the requested budget. Backends that report the reason honestly settle it first.Verifying
Against a local model, the same cut off conversation:
Tests: 7 new backend tests covering the prompt boundary, the legacy tokenizer fallback and the guards, plus 10 new frontend tests covering the merge, overlap trimming and restart detection. Full frontend suite (739), typecheck, lint and build all pass. Failures in
test_setup_llama_cpp_backendand the training streaming files are pre-existing and reproduce on a clean tree.Known gaps
finish_reason. Worth doing separately.