Skip to content

fix(studio): refresh token count after model load (#7450) - #7453

Merged
danielhanchen merged 119 commits into
unslothai:mainfrom
Souravrajvi0:feat/token-count-on-model-load-4af7
Aug 3, 2026
Merged

danielhanchen merged 119 commits into
unslothai:mainfrom
Souravrajvi0:feat/token-count-on-model-load-4af7

Conversation

@Souravrajvi0

@Souravrajvi0 Souravrajvi0 commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #7450

The context usage bar (X / Y tokens) only appeared after sending a message. Loading a model clears contextUsage, 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

contextUsage is only ever written from streaming completion metadata. A model load clears it (via setActiveThreadId / runtime resets) and nothing re-counted the existing thread against the new GGUF tokenizer until the user sent another message.

Fix

  1. Backend: POST /api/inference/chat/count_tokens counts 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 stale model could drag the backend back to the model that was loaded when the count started.
  2. Frontend: 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.
  3. Triggers: after a local GGUF finishes loading, when a stored thread is opened, and on a New Chat view once /api/inference/status has named the resident model.

Scope

This branch previously carried a Playwright E2E suite, a standalone token-count CLI probe, llama_cpp / tools changes and three extra test modules. All of that is out; what is left is the recount itself and the tests that pin it.

Verification

Check Result
tests/studio 1871 passed, 3 skipped, 0 failed (main is 8 failed / 1836 passed here: test_load_orchestrator used to park a bare structlog placeholder that shadowed the real package for the rest of the session, which this branch fixes)
studio/backend/tests failing + erroring node-id set identical to main (92 ids either side, pre-existing RAG / sqlite-vec / test_studio_api / test_web_rank), +5 passed for the new cases
npm run typecheck exit 0
Negative control reverting only runtime-provider.tsx reddens both #7450 cases on a value (counts 0 != 1, contextUsage None), not on a missing symbol

Compatibility

Local GGUF chats only. External providers keep the existing metadata-restore path, and post-completion usage from streaming responses is untouched.

…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@Souravrajvi0

Souravrajvi0 commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor Author

VM testing (no GGUF / no Studio UI)

Ran everything feasible in the cloud agent environment:

Frontend

  • npm run typecheck — pass
  • npm run build (tsc + vite) — pass
  • eslint on refresh-context-usage.ts — pass
  • Studio UI E2E — not possible (no GGUF model loaded, no browser session with Studio)

Backend (Python 3.13 venv, CI-equivalent deps)

  • test_chat_count_tokens_returns_input_tokens — pass
  • test_count_tokens_is_tracked_as_inference_path — pass
  • All count_tokens / chat_count tests in test_openai_auto_switch.py — 5 passed
  • Full test_openai_auto_switch.py — 179 passed
  • Message sanitization tests (drop_empty / coalesce in test_openai_tool_passthrough.py) — 8 passed
  • CI-equivalent backend suite (tests/ minus GPU/E2E ignores) — 8793 passed, 80 skipped

Souravrajvi0 and others added 4 commits July 26, 2026 04:15
)

Defer post-load recount until modelLoading clears, restore saved usage
while recount runs, walk the active parentId branch, read incognito
messages from the live thread, guard on activeThreadId, and include
local tool/RAG options in count_tokens so the bar matches chat sends.
- 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)
@Souravrajvi0

Copy link
Copy Markdown
Contributor Author

Ready for re-review — latest push addresses CI and completes UI verification.

Since last review

  • Playwright E2E for token bar on model load + model switch (both passing on VM with test-load-config)
  • CI fixes: fsevents override (install-script gate) + fastapi scan baseline refresh
  • PR description updated with full verification matrix

CI status: re-running on 1a22e4caf; prior failures were unrelated ROCm infra + npm/security gates now fixed.

Fixes #7450

Souravrajvi0 and others added 5 commits July 26, 2026 14:03
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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +150 to +156
export async function countChatInputTokens(payload: {
model: string;
messages: OpenAIChatCompletionsRequest["messages"];
enable_tools?: boolean;
enabled_tools?: string[];
mcp_enabled?: boolean;
rag_scope?: Record<string, unknown>;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +12977 to +12983
try:
count = await asyncio.to_thread(
llama_backend.count_chat_tokens,
openai_messages,
None,
openai_tools,
strict = True,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +272 to +276
const result = await countChatInputTokens({
model: capturedCheckpoint,
messages: outbound,
...toolExtras,
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

danielhanchen and others added 2 commits July 26, 2026 21:18
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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits July 26, 2026 21:38
…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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +12989 to +12993
llama_backend.count_chat_tokens,
openai_messages,
None,
openai_tools,
strict = True,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Round of five items, four fixed in 185632d1e, one declined. Head is acf2e5c6d, with current main merged in.

Fixed

Deep 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. /chat/count_tokens always refuses images, because /apply-template swaps each one for a short marker. The client was finding that out the expensive way: hashing the base64 into the branch signature, serialising it into a request body that can run to megabytes, and posting it, all synchronous on the UI thread, to be told 503. It now declines before the hash, which is why branchSignature moved below the guards.

Compare panes. The history loader recounted for every pane, but a compare pane deliberately never writes activeThreadId, so refreshContextUsage drops its total at publish. Opening two panes rebuilt two branches from storage and paid for /apply-template and /tokenize twice to display neither. Now gated on the same modelType === "base" && !pairId condition ThreadContextUsageRecount and ActiveBranchRegistrar already use.

Double recount on model load. resetLoadingUi() clears modelLoading on the line before the explicit post-load call, so the effect that watches it fires too. The generation map discarded one result but neither request. Counts are now deduped per thread while one is on the wire. Skipping the second is safe because it reads the same branch as the first, and the publish-time branch check still drops a total the branch outgrew.

Four regression tests, each with a negative control that reddens on the matching assertion:

Guard removed Reddens with
Deep Research assert 1 == 0
image decline assert 1 == 0
in-flight dedupe assert 2 == 1
compare-pane gate assert 1 == 0

Declined

Making 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

  • backend 14018 passed, 14 failed, all 14 in test_studio_api.py and test_text_io_encoding.py and all reproducing on clean main
  • tests/studio 2375 passed, 0 failures; the 3 test_chat_autoload_failure_gate.py failures I reported last round are fixed on main
  • frontend 312 passed, tsc -b clean, npm run build clean
  • the one eslint error is a restricted import from Studio: project sources backed by RAG #6205, present at the base and untouched here

CI is also running on a staging replica to keep off the org queue: danielhanchen#682.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 1bc14498c7

ℹ️ 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".

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Total Token Count disappears randomly, especailly after switching models.

3 participants