Skip to content

Studio: add /context to show what fills the context window - #13929

Merged
danielhanchen merged 18 commits into
unslothai:mainfrom
bjornts:studio-context-command
Nov 15, 2026
Merged

danielhanchen merged 18 commits into
unslothai:mainfrom
bjornts:studio-context-command

Conversation

@bjornts

@bjornts bjornts commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #13921

/context

Type /context and press Enter. A report appears on its own card under the last message. It shows how many tokens go to the system turn, the tools and the messages, how many are free, and where automatic compaction starts. "Tools (n)" expands to the tool names, and "Show prompt" shows the exact text the model receives.

The report is not a chat message. It is never saved or sent to the model, so the prompt cache is unaffected. The header ring updates to the same total. The report disappears on the next message or /compact. /context is refused while a reply is running, on an empty chat, and where the header ring's own recount declines: images, audio, video, or a compacted chat on a non-GGUF model. API models have no local tokenizer, so /context shows a toast saying there is no breakdown; the header ring already shows the provider's total against the catalogued window.

How the split works. /chat/count_tokens takes a new breakdown: true. The backend then prices the full prompt, plus the system turn with and without the tools, so the parts always add up to the total. The tool nudge counts under Tools, because it is only there for the tools. After compaction, the split is of the fitted prompt main already counts. Without breakdown, the count is unchanged.

Count fix. The GGUF count now follows the launcher's tools-on default, as the completion and the MLX count already do. Without it, the count priced a tool catalog the model never got.

Live run

unsloth/gemma-4-E2B-it-GGUF UD-Q4_K_XL, Thinking on, on an M-series Mac. MLX is covered by tests, not run live.

System Tools Messages /context Ring
Tools off 32 0 18 50 50
Tools on (6 tools) 32 1,405 230 1,667 1,667

Running /context between two turns does not change the next turn. With tools off, it was 65 prompt tokens and 36 cached both with and without /context. With tools on, it was 1,470 and 1,446.

context-tools-on-merged

Known limitation, not changed here. With tools on, the count includes the model's previous thinking, which the completion drops. Here it counted 1,667, while the next turn sent 1,470 including the new question. The header recount on main builds the same payload, so I'll look at it separately.

Tests

  • test_openai_auto_switch.py (+5): the parts add up, including the clamp case, and the nudge goes under Tools with or without a system prompt. A plain count still renders once, the shown prompt is the full one, and the launcher-default test fails on main.
  • test_llama_count_memo.py (+1): a count that asks for the prompt renders it instead of returning main's memoised count without one.
  • test_mlx_inference_backend.py (+2): the MLX split adds up, puts the nudge under Tools, and returns no prompt. A plain count keeps the nudge when a forced tool narrows the catalog to none.
  • chat-context-command.test.ts (23):
    • Only exactly /context triggers, and it never reaches the send path. An empty chat asks for a message first.
    • The request it sends, and when the ring may or may not update, including an edit or rewind mid-count.
    • The report hides on a new message, in other chats and on /compact.
    • An API model gets a toast instead of a report.
    • A prompt-settings change while counting drops the count, as the header recount does.
    • It counts nothing for images, audio, video or a compacted non-GGUF chat, and still counts a compacted GGUF chat.
  • Typecheck, ESLint, the i18n tests and the repo's Python formatter are clean.

Before / after

Same Studio build pair from this PR's merge base and head, unsloth/gemma-3-270m-it-GGUF UD-Q4_K_XL on CPU, one turn then /context. Before, /context is sent as a chat message; after, it shows the report card and nothing is sent, and the header ring reads the same 34 tokens.

/context before and after

/context shows, under the last message, how many tokens go to the system
prompt, the tools and the messages, and how much is free. Nothing is sent
to the model. count_tokens gains a breakdown option for it. API models,
which have no local tokenizer, show the last reply's total against the
model's catalogued window.

The GGUF count now includes what the completion adds after a compaction
(the note that older turns were removed, and search_conversation with
tools off) and follows the launcher tool default, so it no longer reads
low on compacted chats.

Fixes unslothai#13921
@LeoBorcherding

LeoBorcherding commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

nice feature, and keeping /context count-only (never sent, cache untouched) is the right call. tested on an M5 Mac with Qwen3.5-0.8B GGUF, base bd06376 vs head 288a5b4: plain counts match base, the breakdown always sums to the total, and the ring agrees with the report.

P1

  • tests/contrast-slider.test.ts fails on this head (passes on base): UsageBar in context-report.tsx uses fixed bg-foreground/45 and /60. The gain-aware color-mix(... var(--contrast-wash-gain, 1) ...) form fixes it.
  • conflicts with main in 6 files, so it needs a merge of main.

P2

  • countContext can write a stale count to the ring if an edit or rewind lands mid-count. Check the branch's message ids before setContextUsage, like the background recount does.
  • the API-model report shows an estimated: true text guess as real usage. Treat it as "no usage yet".

P3

  • with tools on, the tool nudge is counted under "System prompt" (33 → 532 with no system prompt set). Count it under Tools, or relabel the row.

nits: the "System prompt" row also holds template markup, and the bar stays grey while the header ring turns amber and red.

fixes for the P1 test and both P2s, with tests, are on the mirror below.

Full results, screenshots and a branch to pull from: LeoBorcherding#625

bjornts and others added 3 commits November 4, 2026 15:48
# Conflicts:
#	studio/backend/core/inference/llama_cpp.py
#	studio/backend/routes/inference.py
#	studio/backend/tests/test_openai_auto_switch.py
#	studio/frontend/src/features/chat/api/chat-adapter.ts
#	studio/frontend/src/features/chat/api/chat-api.ts
#	studio/frontend/tests/auto-compaction-settings.test.ts
…recheck branch before ring write

The usage bar's fixed bg-foreground alphas broke contrast-slider.test.ts. The API report showed a text-length estimate as provider usage. The ring write now checks the branch's message ids, since an edit or rewind mid-count passed every other guard.
… the ring

- The nudge is in the prompt only because tools are, so the breakdown's
  tool-free render leaves it out. Plain counts are unchanged.
- The "System prompt" row is now "System": it also holds the template's markup.
- The usage bar takes the header ring's severity colors.
- Drop the MLX count's checkpoint-recall reopen. It skipped gates the
  completion applies, and it is outside /context.
- The API-model hint says models report token usage, not "their size".
@LeoBorcherding LeoBorcherding self-assigned this Nov 5, 2026
@bjornts

bjornts commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful test pass and the fixes, @LeoBorcherding. main is merged in.

  • P1: cherry-picked your commit with you as author, and contrast-slider.test.ts passes. The bar fill now uses the ring's colors (see nits); the compaction mark keeps your gain-aware mix.
  • P2: both fixes and tests are yours. readBranch is now required, so no caller can skip the check.
  • P3: the nudge counts under Tools on GGUF and MLX. Plain counts are unchanged.
  • Nits: the row is now "System", and the bar turns amber and red with the ring.

The merge dropped what has since landed on main, and the breakdown now splits the fitted prompt, which clears the old known limitation. I re-ran the live table on the merged branch. I kept the GGUF count's launcher-default fix, so /context doesn't price tools the model never gets. I dropped the MLX recall change, which skipped gates the completion applies. The description is updated to match.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Pushed 2e2c868 to your branch (fast-forward from your 4863f23). It adds:

  • the report on its own card, plus a "send a message first" toast for /context on an empty chat (6a91038)
  • the context.* strings for the 11 locales main added since, so strict i18n passes

Retested at 2e2c868 on a Colab T4 and an M5 Mac, base vs head, dark and light: LeoBorcherding#625. Codex is clean on it.

LeoBorcherding and others added 5 commits November 10, 2026 17:45
…ty chat

The report was bare text under the reply, so it read as part of the assistant message. On a new chat with no messages it floated below the welcome screen, far from anything; it now asks for a message first.
cs, es-419, fa, id, nl, pl, th, tr, uk, vi and zh-TW had none of the 19
context.* keys, so i18n:check:strict failed.
# Conflicts:
#	studio/frontend/src/features/chat/external-providers.ts
main's llama-server count memo returns before /apply-template runs, so
after a header recount /context showed the system-only prefix as the
prompt, and a second /context showed none. A caller that passes
on_prompt now bypasses the memo, like admission counts do.
With audio or video the count left the media out, and a compacted chat
on a non-GGUF model was priced as if never compacted; the ring took
either number. Images are now refused before the request instead of
by the backend. A clip still in the composer is not refused.
@bjornts
bjornts force-pushed the studio-context-command branch from 2e2c868 to ac086f5 Compare November 11, 2026 04:41
@bjornts

bjornts commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

Merged main and fixed two bugs:

  • main's llama-server count memo (Studio: reuse an identical llama-server prompt count within a tool round #16756) returns before the render, so after a header recount "Show prompt" showed only the system prefix, and a second /context showed none. A count that asks for the prompt now skips the memo.
  • /context now refuses the chats the header recount refuses: images, audio, video, and a compacted chat on a non-GGUF model. Before, it wrote a count without the media, or an unfitted one, to the ring.

The one conflict was external-providers.ts, where main added externalModelTakesVideo next to externalModelContextLength. Both are kept.

@LeoBorcherding heads-up: I force-pushed to clean up the history. Your three commits keep you as author, and before the merge the tree is identical to 2e2c868, so reset to the new head before pushing again.

The backend count tests, typecheck, ESLint, strict i18n and the repo's Python formatter pass. The frontend suite's 6 failures also fail on main.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T08:22:15.037705Z f69b26d Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: ee4690f2f7

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

@danielhanchen danielhanchen self-assigned this Nov 15, 2026
# Conflicts:
#	studio/frontend/src/features/chat/chat-page.tsx
#	studio/frontend/src/features/chat/external-providers.ts
…tal), the unreachable total-only state and unused strings; trim comments
@unslothai unslothai deleted a comment from Imagineer99 Nov 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@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: 9fd640dc2c

ℹ️ 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 +40 to +41
now.params.checkpoint !== checkpoint ||
branchSignature(readBranch()) !== signature

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 Reject counts when prompt settings change in flight

If the system prompt or tool settings change while /context is awaiting its count, these checks still accept the old result: those setters advance queuedSettingsEpoch without changing the checkpoint, message signature, or contextUsage reference. Consequently, the old breakdown is displayed and its total can overwrite the header ring through recountedTokens, even though it prices different prompt settings. The existing refreshContextUsage guards against this with a captured settings epoch; apply equivalent invalidation here before returning or publishing the count.

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.

Fixed in 5084f678a: countContext now captures queuedSettingsEpoch and drops the count if it moved, as refreshContextUsage does; test added.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: f69b26d5e9

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

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 15, 2026
@danielhanchen
danielhanchen merged commit 65e6925 into unslothai:main Nov 15, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 15, 2026
)

Fixes unslothai#16716

The Skills dialog opens only from "Manage skills" in the Skills pill's
menu, and the pill is hidden while Skills is off, which is the default
until a skill is enabled. Typing `/skills` and pressing Enter now opens
the same dialog, with Skills on or off. Like `/rewind`, it is handled in
the composer before the model and queue gates, so it is never sent and
works with no model loaded. Only the bare command matches: `/skills
list`, or `/skills` with an attachment or staged audio, is sent as
usual.

It reuses `ChatSkillsDialog` and adds no new strings.

## Testing

- **`chat-skills-command.test.ts`:** only the bare `/skills` matches,
ignoring case and surrounding whitespace. It also checks that
`handleSubmit` intercepts it ahead of `shouldBlockSend` and
`interceptSend`, clears the composer and opens the dialog.
- **Live, in Studio with no model loaded, with Skills on and with Skills
off:** `/skills` opened the dialog and cleared the composer. No message
was sent and no `/chat/completions` request was made.
- Typecheck is clean. ESLint reports nothing new.

This touches the same command block in `handleSubmit` as unslothai#13929
(`/context`). I'll rebase whichever lands second.


## Before / after

`/skills` typed into a fresh chat with no model loaded, then Enter.
Before (merge base `3221ed08b`): it is sent as a prompt, a user message
appears and Studio starts loading a model. After (`0fcc25b1f`): the
Skills dialog opens, nothing is sent, and the composer stays empty after
a reload.

![/skills before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/16717/pr16717_skills-f928f1a15a1e.png)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: imagineer99 <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Studio: /context command to show what fills the context window

4 participants