Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

show the local model's context window before the first token count (#8882)

Maheswar Kumar6e5360ca91ff
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 5ae071297d5..43fbad522ab 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -19608,6 +19608,16 @@ async def chat_count_tokens(
enabled_tool_names = _count_history_gate,
).strip()
+ # Nothing survived the resolution above, so the template would render its generation marker
+ # alone and the total would describe a conversation nobody has started (#8882). Decided here
+ # because only this side knows whether `--enable-tools` put schemas in an otherwise bare prompt,
+ # and the passthrough's own catalog renders with no message to carry it.
+ if not openai_messages and not openai_tools:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens for an empty prompt.",
+ )
+
# llama-server falls back to the load-time --chat-template-kwargs per key a request omits,
# so omitting these prices the template in whatever mode the model was LOADED in.
_template_kwargs = llama_backend._request_reasoning_kwargs(
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 88afd3cc0fd..b4be650d566 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -4206,6 +4206,67 @@ def test_chat_count_tokens_still_counts_without_audio(monkeypatch):
assert counted != {}, "the tokenizer must be reached"
+def test_chat_count_tokens_refuses_an_empty_prompt(monkeypatch):
+ """#8882: an empty conversation renders the generation marker alone.
+
+ unsloth/Phi-4-mini-instruct-GGUF Q4_K_M renders "<|assistant|>" for an empty message list, one
+ token, and the header reported it as usage on a chat nobody had started.
+ """
+ switched, counted = _count_tokens_backend(monkeypatch, count = 1)
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inference_route.chat_count_tokens(_count_request([]), "tester"))
+ assert excinfo.value.status_code == 503
+ assert "empty" in str(excinfo.value.detail).lower()
+ assert counted == {}, "the tokenizer must not be reached"
+ assert switched == []
+
+
+def test_chat_count_tokens_counts_an_empty_chat_carrying_a_system_prompt(monkeypatch):
+ # The system prompt is in every request the chat will send, so it occupies the window already.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 7)
+ body = _counted_body(_count_request([{"role": "system", "content": "You are helpful."}]))
+ assert body["input_tokens"] == 7
+ assert [message.get("role") for message in counted.get("messages") or []] == ["system"]
+
+
+def test_chat_count_tokens_counts_an_empty_chat_the_cli_policy_fills(monkeypatch):
+ """`--enable-tools` outranks the request's own `enable_tools: false`.
+
+ The client cannot see that policy, so the emptiness verdict belongs here: the schemas and the
+ action nudge it injects are real occupancy, and refusing them would blank a bar that has a
+ number to show.
+ """
+ import state.tool_policy as _tp
+
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 850, supports_tools = True)
+
+ async def _select(payload, *, tools_on, mcp_allowed):
+ return [{"type": "function", "function": {"name": "web_search"}}]
+
+ monkeypatch.setattr(inference_route, "_select_request_tools", _select)
+ monkeypatch.setattr(_tp, "get_tool_policy", lambda: True)
+
+ body = _counted_body(_count_request([], enable_tools = False))
+ assert body["input_tokens"] == 850
+ nudged = any(
+ message.get("role") == "system" and "web_search" in str(message.get("content", ""))
+ for message in counted.get("messages") or []
+ )
+ assert nudged is True
+
+
+def test_chat_count_tokens_counts_a_passthrough_catalog_without_messages(monkeypatch):
+ # The passthrough forwards the caller's own schemas, and /apply-template renders them with no
+ # message to carry them, so the prompt is not empty even though `messages` is.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 640, supports_tools = True)
+ catalog = [{"type": "function", "function": {"name": "lookup_order"}}]
+ body = _counted_body(_count_request([], tools = catalog))
+ assert body["input_tokens"] == 640
+ assert [(tool.get("function") or {}).get("name") for tool in counted.get("tools") or []] == [
+ "lookup_order"
+ ]
+
+
# Shapes the recount sends for a thread with documents in scope. Only a PENDING turn is answered
# from these exact messages, and the tool loop opens it by splicing in what RAG retrieves.
_PENDING_USER_TURN = [{"role": "user", "content": "what does the contract say"}]
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index b2716753464..86f098d7baf 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -78,6 +78,7 @@ import {
import { GuidedTour, useGuidedTourController } from "@/features/tour";
import { isTauri } from "@/lib/api-base";
import { chatModelLoaded } from "./lib/chat-model-loaded";
+import { hasKnownContextWindow } from "./lib/context-window-known";
import { isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
@@ -2169,6 +2170,12 @@ export function ChatPage({
() => isExternalModelId(inferenceParams.checkpoint),
[inferenceParams.checkpoint],
);
+ const contextWindowKnown = hasKnownContextWindow({
+ ggufContextLength,
+ modelLoading,
+ isExternalModel,
+ residentCheckpoint,
+ });
const {
checkpoint: runtimeCheckpoint,
isGguf: runtimeModelIsGguf,
@@ -3562,15 +3569,15 @@ export function ChatPage({
) : null}
</div>
<div className="pointer-events-auto ml-auto flex items-center gap-1">
- {view.mode === "single" && contextUsage ? (
+ {view.mode === "single" && (contextUsage || contextWindowKnown) ? (
<ContextUsageBar
- used={contextUsage.totalTokens}
+ used={contextUsage?.totalTokens ?? null}
// null on external providers; the bar handles that.
total={ggufContextLength}
- cached={contextUsage.cachedTokens}
- cacheWrites={contextUsage.cacheWriteTokens}
- promptTokens={contextUsage.promptTokens}
- completionTokens={contextUsage.completionTokens}
+ cached={contextUsage?.cachedTokens}
+ cacheWrites={contextUsage?.cacheWriteTokens}
+ promptTokens={contextUsage?.promptTokens}
+ completionTokens={contextUsage?.completionTokens}
className="h-[var(--studio-chat-control-height,34px)]"
/>
) : null}
diff --git a/studio/frontend/src/features/chat/components/context-usage-bar.tsx b/studio/frontend/src/features/chat/components/context-usage-bar.tsx
index 9c80ce6b117..830eaacb738 100644
--- a/studio/frontend/src/features/chat/components/context-usage-bar.tsx
+++ b/studio/frontend/src/features/chat/components/context-usage-bar.tsx
@@ -7,15 +7,11 @@ import {
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import type { FC } from "react";
-
-const formatTokenCount = (n: number): string => {
- if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
- return String(n);
-};
-
-const formatTokenCountFull = (n: number): string => {
- return n.toLocaleString();
-};
+import {
+ type ContextUsageBarInput,
+ deriveContextUsageBar,
+ formatTokenCountFull,
+} from "../lib/context-usage-bar-state";
function getSeverityColor(percent: number): {
bar: string;
@@ -26,17 +22,9 @@ function getSeverityColor(percent: number): {
return { bar: "bg-control-accent", text: "text-control-accent" };
}
-export const ContextUsageBar: FC<{
- used: number;
- // null on external providers (unknown window); bar hides the ratio.
- total?: number | null;
- cached?: number;
- // Anthropic-only (billed at the write premium).
- cacheWrites?: number;
- promptTokens?: number;
- completionTokens?: number;
- className?: string;
-}> = ({
+export const ContextUsageBar: FC<
+ ContextUsageBarInput & { className?: string }
+> = ({
used,
total,
cached,
@@ -45,19 +33,17 @@ export const ContextUsageBar: FC<{
completionTokens,
className,
}) => {
- const hasKnownLimit = typeof total === "number" && total > 0;
- const hasUsageDetails =
- promptTokens !== undefined ||
- completionTokens !== undefined ||
- (cached !== undefined && cached > 0) ||
- (cacheWrites !== undefined && cacheWrites > 0);
-
- // Nothing to show: no limit and no per-turn counters.
- if (!hasKnownLimit && used <= 0 && !hasUsageDetails) return null;
+ const state = deriveContextUsageBar({
+ used,
+ total,
+ cached,
+ cacheWrites,
+ promptTokens,
+ completionTokens,
+ });
+ if (!state) return null;
- const percent = hasKnownLimit
- ? Math.min((used / (total as number)) * 100, 100)
- : null;
+ const { percent } = state;
const severity = getSeverityColor(percent ?? 0);
return (
@@ -65,22 +51,14 @@ export const ContextUsageBar: FC<{
<TooltipTrigger asChild>
<button
type="button"
- aria-label={
- hasKnownLimit
- ? `Context usage: ${formatTokenCount(used)} of ${formatTokenCount(total as number)} tokens`
- : `Token usage: ${formatTokenCount(used)} tokens`
- }
+ aria-label={state.label}
className={cn(
"flex items-center gap-2 rounded-[10px] px-2.5 py-1 font-mono text-chat-icon-fg text-ui-13 tabular-nums transition-colors hover:bg-chat-icon-bg-hover hover:text-chat-icon-fg-hover",
className,
)}
>
- <span>
- {hasKnownLimit
- ? `${formatTokenCount(used)} / ${formatTokenCount(total as number)}`
- : `${formatTokenCount(used)} tokens`}
- </span>
- {hasKnownLimit && percent !== null ? (
+ <span>{state.face}</span>
+ {percent !== null ? (
<div className="h-1.5 w-16 rounded-full bg-black/10 dark:bg-white/15 overflow-hidden">
<div
className={cn("h-full rounded-full transition-all", severity.bar)}
@@ -97,7 +75,7 @@ export const ContextUsageBar: FC<{
className="[&_span>svg]:hidden!"
>
<div className="grid min-w-44 gap-1.5 text-xs">
- {hasKnownLimit && percent !== null ? (
+ {percent !== null ? (
<div className="flex items-center justify-between gap-4">
<span className="text-muted-foreground">Context usage</span>
<span className={cn("font-mono tabular-nums font-medium", severity.text)}>
@@ -137,18 +115,14 @@ export const ContextUsageBar: FC<{
</span>
</div>
)}
- <div className="my-0.5 border-t border-border/40" />
+ {percent !== null || state.hasUsageDetails ? (
+ <div className="my-0.5 border-t border-border/40" />
+ ) : null}
<div className="flex items-center justify-between gap-4">
- <span className="text-muted-foreground">
- {hasKnownLimit ? "Total" : "Total tokens"}
- </span>
- <span className="font-mono tabular-nums">
- {hasKnownLimit
- ? `${formatTokenCountFull(used)} / ${formatTokenCountFull(total as number)}`
- : formatTokenCountFull(used)}
- </span>
+ <span className="text-muted-foreground">{state.totalRowName}</span>
+ <span className="font-mono tabular-nums">{state.totalRowValue}</span>
</div>
- {hasKnownLimit && percent !== null && percent > 85 ? (
+ {percent !== null && percent > 85 ? (
<div className="mt-1 max-w-64 text-ui-11 leading-snug text-muted-foreground/90">
Close to the context limit. Generation will stop at 100%.
Increase <span className="font-medium">Context Length</span> in
diff --git a/studio/frontend/src/features/chat/lib/context-usage-bar-state.ts b/studio/frontend/src/features/chat/lib/context-usage-bar-state.ts
new file mode 100644
index 00000000000..eba518e7592
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/context-usage-bar-state.ts
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// its own plain module so the node suite can drive it: the component is JSX the runner cannot import
+
+export const formatTokenCount = (n: number): string => {
+ if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
+ return String(n);
+};
+
+export const formatTokenCountFull = (n: number): string => {
+ return n.toLocaleString();
+};
+
+export type ContextUsageBarInput = {
+ // null when nothing has been counted yet
+ used?: number | null;
+ // null on external providers, whose context window is unknown
+ total?: number | null;
+ cached?: number;
+ // anthropic-only (billed at the write premium)
+ cacheWrites?: number;
+ promptTokens?: number;
+ completionTokens?: number;
+};
+
+export type ContextUsageBarState = {
+ face: string;
+ label: string;
+ totalRowName: string;
+ totalRowValue: string;
+ // null whenever no ratio can be stated, which also withholds the fill and the 85% warning
+ percent: number | null;
+ // whether any per-turn row renders, so the tooltip rule never floats above nothing
+ hasUsageDetails: boolean;
+};
+
+// a counted zero and an uncounted chat differ: an unmeasured prompt must not read as 0% of the window
+export function deriveContextUsageBar({
+ used,
+ total,
+ cached,
+ cacheWrites,
+ promptTokens,
+ completionTokens,
+}: ContextUsageBarInput): ContextUsageBarState | null {
+ const limit = typeof total === "number" && total > 0 ? total : null;
+ const usedTokens =
+ typeof used === "number" && Number.isFinite(used) ? used : null;
+ const hasUsageDetails =
+ promptTokens !== undefined ||
+ completionTokens !== undefined ||
+ (cached !== undefined && cached > 0) ||
+ (cacheWrites !== undefined && cacheWrites > 0);
+
+ if (limit === null) {
+ // nothing to show: no window to name, and no counted usage to report against one
+ if (usedTokens === null) return null;
+ if (usedTokens <= 0 && !hasUsageDetails) return null;
+ return {
+ face: `${formatTokenCount(usedTokens)} tokens`,
+ label: `Token usage: ${formatTokenCount(usedTokens)} tokens`,
+ totalRowName: "Total tokens",
+ totalRowValue: formatTokenCountFull(usedTokens),
+ percent: null,
+ hasUsageDetails,
+ };
+ }
+
+ if (usedTokens === null) {
+ return {
+ face: `— / ${formatTokenCount(limit)}`,
+ label: `Context window: ${formatTokenCount(limit)} tokens, usage not counted yet`,
+ totalRowName: "Context window",
+ totalRowValue: formatTokenCountFull(limit),
+ percent: null,
+ hasUsageDetails,
+ };
+ }
+
+ return {
+ face: `${formatTokenCount(usedTokens)} / ${formatTokenCount(limit)}`,
+ label: `Context usage: ${formatTokenCount(usedTokens)} of ${formatTokenCount(limit)} tokens`,
+ totalRowName: "Total",
+ totalRowValue: `${formatTokenCountFull(usedTokens)} / ${formatTokenCountFull(limit)}`,
+ percent: Math.min((usedTokens / limit) * 100, 100),
+ hasUsageDetails,
+ };
+}
diff --git a/studio/frontend/src/features/chat/lib/context-window-known.ts b/studio/frontend/src/features/chat/lib/context-window-known.ts
new file mode 100644
index 00000000000..28360cb674f
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/context-window-known.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// its own plain module so the node suite can drive it: chat-page.tsx pulls in the whole chat runtime
+
+export type KnownContextWindowInput = {
+ // the resident GGUF's n_ctx; null for external providers and non-GGUF models
+ ggufContextLength: number | null;
+ // a load in flight still carries the outgoing model's window
+ modelLoading: boolean;
+ isExternalModel: boolean;
+ // what /api/inference/status holds; undefined before the first read
+ residentCheckpoint: string | null | undefined;
+};
+
+// the recount that fills the bar stands down for images, audio, Deep Research and a busy backend
+export function hasKnownContextWindow({
+ ggufContextLength,
+ modelLoading,
+ isExternalModel,
+ residentCheckpoint,
+}: KnownContextWindowInput): boolean {
+ if (modelLoading || isExternalModel) return false;
+ if (ggufContextLength == null || ggufContextLength <= 0) return false;
+ // matches chatModelLoaded: undefined is "status not read yet", not "evicted"
+ return residentCheckpoint !== null;
+}
diff --git a/studio/frontend/tests/context-window-visible.test.ts b/studio/frontend/tests/context-window-visible.test.ts
new file mode 100644
index 00000000000..fd6795d4532
--- /dev/null
+++ b/studio/frontend/tests/context-window-visible.test.ts
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// #8867: the bar rendered only once a token count existed, so a local model's context window was
+// invisible until a reply came back. An earlier version of this file pinned source text only, and
+// a build that fell back to 0 instead of null still passed every assertion.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import { deriveContextUsageBar } from "../src/features/chat/lib/context-usage-bar-state.ts";
+import { hasKnownContextWindow } from "../src/features/chat/lib/context-window-known.ts";
+
+const RESIDENT = "unsloth/Qwen3.6-35B-A3B-MTP-GGUF";
+
+const base = {
+ ggufContextLength: 32768,
+ modelLoading: false,
+ isExternalModel: false,
+ residentCheckpoint: RESIDENT as string | null | undefined,
+};
+
+test("a resident GGUF's window is known before the first turn", () => {
+ assert.equal(hasKnownContextWindow(base), true);
+});
+
+// the window belongs to the outgoing model until the load response lands
+test("a load in flight has no window to name", () => {
+ assert.equal(hasKnownContextWindow({ ...base, modelLoading: true }), false);
+});
+
+// selecting an API model nulls ggufContextLength, so a stale length must be refused on its own
+test("an API model shows no window even with a stale length in the store", () => {
+ assert.equal(hasKnownContextWindow({ ...base, isExternalModel: true }), false);
+});
+
+test("a non-GGUF local model has no window either", () => {
+ assert.equal(
+ hasKnownContextWindow({ ...base, ggufContextLength: null }),
+ false,
+ );
+});
+
+test("a model evicted for an image load has no window", () => {
+ assert.equal(
+ hasKnownContextWindow({ ...base, residentCheckpoint: null }),
+ false,
+ );
+});
+
+// same rule as chatModelLoaded: the first /status read has not landed yet
+test("residency not yet read still names the window", () => {
+ assert.equal(
+ hasKnownContextWindow({ ...base, residentCheckpoint: undefined }),
+ true,
+ );
+});
+
+// the reported case: a GGUF is resident, its window is known, nothing has been counted
+test("an uncounted chat names the window and claims no usage", () => {
+ const state = deriveContextUsageBar({ used: null, total: 32768 });
+ assert.ok(state);
+ assert.equal(state.face, "— / 32.8k");
+ assert.equal(state.totalRowName, "Context window");
+ assert.equal(state.totalRowValue, "32,768");
+ // null, not 0: an unmeasured prompt must not read as 0% of the window
+ assert.equal(state.percent, null);
+ assert.match(state.label, /usage not counted yet/);
+});
+
+// the mutation the old source-regex tests could not see
+test("a counted zero is not the same as an uncounted chat", () => {
+ const state = deriveContextUsageBar({ used: 0, total: 32768 });
+ assert.ok(state);
+ assert.equal(state.face, "0 / 32.8k");
+ assert.equal(state.percent, 0);
+ assert.equal(state.totalRowName, "Total");
+});
+
+test("a counted chat states the ratio", () => {
+ const state = deriveContextUsageBar({
+ used: 4096,
+ total: 32768,
+ promptTokens: 4096,
+ completionTokens: 0,
+ });
+ assert.ok(state);
+ assert.equal(state.face, "4.1k / 32.8k");
+ assert.equal(state.percent, 12.5);
+ assert.equal(state.totalRowValue, "4,096 / 32,768");
+ assert.equal(state.hasUsageDetails, true);
+});
+
+// a prompt already over the window pins at 100 rather than overflowing the fill
+test("usage past the window clamps to 100 percent", () => {
+ assert.equal(deriveContextUsageBar({ used: 40000, total: 32768 })?.percent, 100);
+});
+
+// external providers: usage is known, the window is not
+test("an unknown window shows a bare token count and no ratio", () => {
+ const state = deriveContextUsageBar({ used: 4096, total: null });
+ assert.ok(state);
+ assert.equal(state.face, "4.1k tokens");
+ assert.equal(state.percent, null);
+ assert.equal(state.totalRowName, "Total tokens");
+});
+
+test("no window and no count renders nothing", () => {
+ assert.equal(deriveContextUsageBar({ used: null, total: null }), null);
+ assert.equal(deriveContextUsageBar({ used: 0, total: null }), null);
+});
+
+// the divider would otherwise float above an empty region
+test("an uncounted chat reports no per-turn rows", () => {
+ assert.equal(
+ deriveContextUsageBar({ used: null, total: 32768 })?.hasUsageDetails,
+ false,
+ );
+});
+
+test("the header renders the bar on the window alone, with usage optional", () => {
+ const page = readFileSync(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ page,
+ /view\.mode === "single" && \(contextUsage \|\| contextWindowKnown\)/,
+ );
+ assert.match(page, /used=\{contextUsage\?\.totalTokens \?\? null\}/);
+});
+