Repository navigation
fix(studio): refresh token count after model load (#7450) - #7453
danielhanchen merged 119 commits into
Conversation
…nslothai#7450) Add a chat count_tokens API and call it from the frontend when a local GGUF model finishes loading or when a thread is opened, so the context usage bar reflects the current conversation without waiting for another message.
VM testing (no GGUF / no Studio UI)Ran everything feasible in the cloud agent environment: Frontend
Backend (Python 3.13 venv, CI-equivalent deps)
|
- Add @playwright/test harness with auth injection and model-picker helpers - Cover token bar visibility on load and after unload/reload without resending - Fix isInferenceLoaded to treat empty loaded[] as unloaded (Boolean([]) bug) - Restore saved context usage before background recount in refreshContextUsage - Add data-testid hooks on context bar and model selector
- Override fsevents to 2.3.3 so @playwright/test does not introduce a new install-script dependency ([email protected]) blocked by security-audit CI - Update scan_packages_baseline for fastapi routing.py line shift in resolved studio deps (C2 polling false positive)
|
Ready for re-review — latest push addresses CI and completes UI verification. Since last review
CI status: re-running on Fixes #7450 |
Replace raw px text utilities in agents-tab with scaled text-ui tokens so test_ui_font_scale_contract passes. Stub bitsandbytes in the ROCm routing test child process so unsloth_zoo can import under the HIP torch spoof on CPU-only CI.
# Conflicts: # tests/studio/install/test_rocm_rdna_routing.py
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 732a0c80f1
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| export async function countChatInputTokens(payload: { | ||
| model: string; | ||
| messages: OpenAIChatCompletionsRequest["messages"]; | ||
| enable_tools?: boolean; | ||
| enabled_tools?: string[]; | ||
| mcp_enabled?: boolean; | ||
| rag_scope?: Record<string, unknown>; |
There was a problem hiding this comment.
Pass active reasoning settings into token recounts
For local models whose Jinja template consumes enable_thinking, reasoning_effort, or preserve_thinking, generation supplies those values through chat_template_kwargs, but this new count request cannot send any of them and the backend therefore renders /apply-template with its defaults. Switching models while using a non-default reasoning mode can consequently populate the bar with a prompt count that does not match the next completion; include the active reasoning fields and apply the same _request_reasoning_kwargs normalization during counting.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Accurate as a description, but it is a pre-existing gap in count_chat_tokens (studio/backend/core/inference/llama_cpp.py), which this PR does not touch: it has never sent chat_template_kwargs to /apply-template, so the already-shipped /api/inference/messages/count_tokens and /v1/messages/count_tokens have the same behaviour. Threading enable_thinking / reasoning_effort / preserve_thinking from the store through ChatCountTokensRequest into the shared counter changes those two endpoints too, so it belongs in its own change rather than here.
| try: | ||
| count = await asyncio.to_thread( | ||
| llama_backend.count_chat_tokens, | ||
| openai_messages, | ||
| None, | ||
| openai_tools, | ||
| strict = True, |
There was a problem hiding this comment.
Count multimodal embedding tokens in vision threads
When a stored conversation contains images and a vision GGUF is loaded or switched, this endpoint delegates to count_chat_tokens, whose successful path only renders /apply-template and tokenizes the resulting text. That path counts the template's image marker but never runs the multimodal projector used by /v1/chat/completions, so it omits the image embeddings that occupy the model's context window and can understate usage by hundreds of tokens per image; use a counting path that performs the same multimodal preprocessing as generation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same reasoning: count_chat_tokens is untouched by this PR and its /apply-template plus /tokenize path is text-only by construction (llama-server's /tokenize takes a content string and has no multimodal input), so /v1/messages/count_tokens already reports image threads this way. An image-aware count means running the projector in a new counting path, which is a feature rather than a fix to the recount this PR adds.
…othai#7453 Post-model-load recounts now follow the branch the runtime is showing, so stepping back to an earlier retry sibling and switching models no longer counts the newest stored sibling instead. The history adapter's own recount still mirrors the import head reset. The E2E unload helper sent an empty body, which UnloadRequest rejects with a 422, so no model was ever unloaded and the model-switch spec never exercised a switch. It now resolves the loaded model from /api/inference/status and asserts the unload succeeded. ensureLocalModelLoaded also stopped waiting out the 180s count_tokens response timeout on a brand-new chat, which never issues that request.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9a32cf8c81
ℹ️ 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".
| const result = await countChatInputTokens({ | ||
| model: capturedCheckpoint, | ||
| messages: outbound, | ||
| ...toolExtras, | ||
| }); |
There was a problem hiding this comment.
Include reasoning template controls in recount requests
When the active GGUF supports configurable reasoning, this recount sends only the messages and tool settings, while the real chat request renders the template with enable_thinking, reasoning_effort, and preserve_thinking. Models such as Qwen/GLM can add or remove reasoning prefixes or historical thinking based on those values, so /apply-template counts a different prompt and the refreshed context bar can be materially wrong, especially when Preserve Thinking is enabled. Forward the active reasoning controls and have chat_count_tokens pass them as the same chat_template_kwargs used by generation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The preserve_thinking argument does not hold for what this code sends. Studio serializes assistant turns through serializeAssistantReplayMessages, which consumes only text and tool-call parts, so reasoning parts are dropped and no outbound assistant turn ever carries a block or reasoning_content - I ran the real serializer on a turn with a 500-word reasoning part and the wire payload came back as plain {role: assistant, content: 'The answer is 42.'}. preserve_thinking (per llama_cpp.py's own detector comment, it 'keeps historical blocks in prior assistant turns') therefore has nothing to keep or strip here. Rendering the stock Qwen3 chat template over a 42-message conversation in that exact shape, the whole enable_thinking spread is 19 characters on a 35400-character prompt, and that template has no preserve_thinking kwarg at all. The residual gap is also pre-existing in count_chat_tokens, which this PR does not touch and which the shipped /v1/messages/count_tokens shares.
llama-server's /apply-template replaces every image_url part with a short media marker and discards the decoded bytes, so tokenizing the rendered prompt misses the whole image embedding and the context bar would claim an image-heavy conversation still fits. Refuse the recount for those payloads instead, which leaves the caller on the usage it already had, and refuse before the auto-switch so a count never moves the loaded model.
…r PR unslothai#7453 The recount has no abort signal, so a count still naming the model that was loaded when it started could reach the backend after the user picked another one and, with OpenAI auto-switch on, drag the loaded model back. Drop the auto-switch from /chat/count_tokens: model there is informational and the active model is what gets counted. Scope the saved-usage fallback to the branch being counted, so a thread with a regeneration no longer leaves a sibling branch's usage on the bar when the recount does not land. issue-tokens.py minted a plain token, but ensure_default_admin seeds the account with must_change_password and every protected route answers 403 for a token without the desktop claim, so the Playwright suite could not reach the backend at all on a fresh install.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4fcadff5c2
ℹ️ 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".
| llama_backend.count_chat_tokens, | ||
| openai_messages, | ||
| None, | ||
| openai_tools, | ||
| strict = True, |
There was a problem hiding this comment.
Count with the selected reasoning template
When a GGUF uses reasoning-sensitive chat templates, this call renders /apply-template with the backend defaults rather than the settings used by the real completion. The frontend count payload omits enable_thinking, reasoning_effort, and preserve_thinking, and this invocation has no chat_template_kwargs, while the generation paths forward those fields through _request_reasoning_kwargs. Consequently, switching models with thinking disabled or a non-default effort can populate the context bar with a token count for a different prompt.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Third pass on this one (3652855019, 3653438567), and the answer is unchanged. Measured rather than argued: rendering the stock Qwen3 chat template over a 42-message conversation in the exact shape Studio serializes gives 35400 characters, enable_thinking=True is byte-identical to the default, and enable_thinking=False differs by 19 characters - the empty think scaffold. Historical thinking cannot move it either, because serializeAssistantReplayMessages only emits text and tool-call parts, so no assistant turn on the wire carries a think block or reasoning_content for a template to keep or strip. The remaining gap lives in count_chat_tokens, which this PR does not touch and which the shipped /v1/messages/count_tokens shares, so threading the fields through it belongs in its own change.
…dow for PR unslothai#7453 Canvas appends a system instruction to the real request, and the recount already declares the matching render_html tool, so it has to count that instruction too or every Canvas conversation reads short after a model load. The instruction text and the system-message folding now live in one helper the generation path and the recount share. The stale-recount guard sampled contextUsage after the outbound payload and tool-extras builds, both of which await storage and the project/RAG lookups. A completion landing in that window was captured by the snapshot itself, so the equality check passed and the stale count overwrote its exact usage. Sample as soon as the message list is fixed instead.
|
Round of five items, four fixed in FixedDeep Research recounts. With it enabled the next send creates a server-side research run instead of posting this history, and the research reply carries no usage, so a total counted here describes a request that is never made and nothing later corrects it. The recount declines while it is on. Image branches. Compare panes. The history loader recounted for every pane, but a compare pane deliberately never writes Double recount on model load. Four regression tests, each with a negative control that reddens on the matching assertion:
DeclinedMaking count admission atomic with generation startup. Answered inline: the observation is right and the code already says so, but mutual exclusion means generation startup waiting on a lock a count holds, which is 2.7 ms for an empty chat and 22 ms for a 4700-token thread. That is the cost these guards exist to avoid. Verification
CI is also running on a staging replica to keep off the org queue: danielhanchen#682. |
The dedupe added in the previous commit turned one lost-retry bug into another. A run that starts and is stopped before it emits usage flips runActive back and fires the retry the recount effect depends on. If that retry arrives while a count is still in flight it was discarded, the in-flight count then rejected its now-stale branch, and nothing changed again, so the bar stayed blank for good. A skipped trigger is now recorded with its options and replayed once the in-flight count settles, but only if that count published nothing. That keeps the model-load case at a single count, since there the first trigger publishes and the queued one has nothing left to do, while the stopped-run case gets its retry against the branch as it stands rather than the one the first count read. The dedupe test could not tell the two apart: it awaited both calls but the replay is scheduled off the first count's finally, so a stray one landed after the assertions. It now settles first, and replaying unconditionally reddens it.
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
Collapse the multi-line explanations on the in-flight dedupe, the deferred retry, the Deep Research decline, the image decline, the compare-pane gate and the messagesContainImage predicate, keeping the reasoning each records.
Fixes #7450
The context usage bar (
X / Ytokens) only appeared after sending a message. Loading a model clearscontextUsage, so the bar sat empty until the next completion and it was unclear whether an in-progress chat still fit the newly loaded model.Cause
contextUsageis only ever written from streaming completion metadata. A model load clears it (viasetActiveThreadId/ runtime resets) and nothing re-counted the existing thread against the new GGUF tokenizer until the user sent another message.Fix
POST /api/inference/chat/count_tokenscounts prompt tokens for OpenAI-form chat messages using the loaded GGUF tokenizer, through the same sanitization the completion path runs. It never auto-switches: the caller is a background recount with no abort signal, so honouring a stalemodelcould drag the backend back to the model that was loaded when the count started.refreshContextUsage()rebuilds the branch the runtime displays from stored history, prices it through that endpoint, and publishes the result. It bails on images and audio (which the template replaces with short markers, so a count would come back short), and drops its own result if the checkpoint moved, the thread changed, or a real completion wrote usage while it was in flight./api/inference/statushas named the resident model.Scope
This branch previously carried a Playwright E2E suite, a standalone token-count CLI probe,
llama_cpp/toolschanges and three extra test modules. All of that is out; what is left is the recount itself and the tests that pin it.Verification
tests/studiomainis 8 failed / 1836 passed here:test_load_orchestratorused to park a barestructlogplaceholder that shadowed the real package for the rest of the session, which this branch fixes)studio/backend/testsmain(92 ids either side, pre-existing RAG / sqlite-vec /test_studio_api/test_web_rank), +5 passed for the new casesnpm run typecheckruntime-provider.tsxreddens both#7450cases on a value (counts 0 != 1,contextUsage None), not on a missing symbolCompatibility
Local GGUF chats only. External providers keep the existing metadata-restore path, and post-completion usage from streaming responses is untouched.