The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(chat): token counter measures context, not burned budget; endpoint-wide context catalogue
purple0d19add4f8bf
diff --git a/src/api/__tests__/provider-finish-reason.test.ts b/src/api/__tests__/provider-finish-reason.test.tsindex 506ae23f..e5b84edf 100644--- a/src/api/__tests__/provider-finish-reason.test.ts+++ b/src/api/__tests__/provider-finish-reason.test.ts@@ -13,8 +13,9 @@** Run: npx vitest run src/api/__tests__/provider-finish-reason.test.ts*/-import { describe, it, expect, vi, afterEach } from 'vitest'-import { OpenAIProvider } from '../providers/openai-provider'+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'+import { OpenAIProvider, __clearContextCatalogForTests } from '../providers/openai-provider'+import { AnthropicProvider } from '../providers/anthropic-provider'import type { ProviderConfig, ChatStreamChunk } from '../providers/types'import { isThinkingCompatible } from '../../lib/model-compatibility'@@ -103,6 +104,8 @@ describe('chatStream finishReason', () => {})describe('getContextLength — server catalogue beats name heuristic', () => {+ beforeEach(() => __clearContextCatalogForTests())+it('uses context_length from /models for cloud models after listModels ran', async () => {const provider = new OpenAIProvider(makeConfig())// Name heuristic alone would say 32768 for a qwen3.x name.@@ -121,6 +124,76 @@ describe('getContextLength — server catalogue beats name heuristic', () => {// headroom against 32k and starves long chats down to the 256 floor.expect(await provider.getContextLength('Qwen/Qwen3.6-35B-A3B')).toBe(262144)})++ it('survives across provider instances (lu-cloud builds a fresh delegate per call)', async () => {+ // LuCloudProvider constructs a NEW OpenAIProvider for every call because+ // the Supabase bearer rotates. listModels runs through one delegate,+ // chatStream/applyMaxTokens through another — the catalogue must be+ // shared per endpoint, not per instance, or the fix never engages.+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({+ data: [{ id: 'Qwen/Qwen3.6-35B-A3B', object: 'model', context_length: 262144 }],+ }), { status: 200 }))+ await new OpenAIProvider(makeConfig({ apiKey: 'token-1' })).listModels()++ const second = new OpenAIProvider(makeConfig({ apiKey: 'token-2' }))+ expect(await second.getContextLength('Qwen/Qwen3.6-35B-A3B')).toBe(262144)++ // Different endpoint, same model id → must NOT inherit the value.+ const other = new OpenAIProvider(makeConfig({ baseUrl: 'https://other.test.com/v1' }))+ expect(await other.getContextLength('Qwen/Qwen3.6-35B-A3B')).toBe(32768)+ })+})++describe('stream_options include_usage — real usage on every backend', () => {+ it('sends stream_options for cloud endpoints and surfaces usage on the done chunk', async () => {+ const provider = new OpenAIProvider(makeConfig())+ const spy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(sseResponse([+ '{"choices":[{"delta":{"content":"4"}}]}',+ '{"choices":[{"delta":{},"finish_reason":"stop"}]}',+ '{"choices":[],"usage":{"prompt_tokens":85,"completion_tokens":3}}',+ '[DONE]',+ ]))++ const chunks = await collect(provider.chatStream('m', [{ role: 'user', content: '2+2' }]))+ const body = JSON.parse((spy.mock.calls[0][1] as RequestInit).body as string)+ expect(body.stream_options).toEqual({ include_usage: true })++ const done = chunks.find(c => c.done)+ expect(done?.promptEvalCount).toBe(85)+ expect(done?.evalCount).toBe(3)+ })++ it('drops stream_options on a 422 retry (endpoint rejects unknown params)', async () => {+ const provider = new OpenAIProvider(makeConfig())+ const spy = vi.spyOn(globalThis, 'fetch')+ .mockResolvedValueOnce(new Response('{"error":"unknown param"}', { status: 422 }))+ .mockResolvedValueOnce(sseResponse([+ '{"choices":[{"delta":{"content":"ok"}}]}',+ '[DONE]',+ ]))++ const chunks = await collect(provider.chatStream('m', [{ role: 'user', content: 'hi' }]))+ expect(chunks.some(c => c.content === 'ok')).toBe(true)+ const retryBody = JSON.parse((spy.mock.calls[1][1] as RequestInit).body as string)+ expect('stream_options' in retryBody).toBe(false)+ })+})++describe('anthropic stream — real usage on the done chunk', () => {+ it('surfaces message_start input_tokens + message_delta output_tokens', async () => {+ const provider = new AnthropicProvider(makeConfig({ id: 'anthropic', baseUrl: 'https://api.anthropic.com' } as never) as never)+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(sseResponse([+ '{"type":"message_start","message":{"id":"m1","usage":{"input_tokens":85,"output_tokens":1}}}',+ '{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"7"}}',+ '{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}',+ ]))++ const chunks = await collect(provider.chatStream('claude-sonnet-5', [{ role: 'user', content: '3+4' }]))+ const done = chunks.find(c => c.done)+ expect(done?.promptEvalCount).toBe(85)+ expect(done?.evalCount).toBe(3)+ expect(done?.finishReason).toBe('end_turn')+ })})describe('THINKING_COMPATIBLE — post-2025 reasoning families (Ollama)', () => {diff --git a/src/api/providers/anthropic-provider.ts b/src/api/providers/anthropic-provider.tsindex 53362cd9..6afd8c4c 100644--- a/src/api/providers/anthropic-provider.ts+++ b/src/api/providers/anthropic-provider.ts@@ -132,11 +132,22 @@ export class AnthropicProvider implements ProviderClient {// Track tool use blocks being builtconst toolUseBlocks: Map<number, { id: string; name: string; input: string }> = new Map()+ // Real token usage: message_start carries input_tokens, message_delta the+ // cumulative output_tokens. Surfaced on the done chunk exactly like the+ // OpenAI provider so the TokenCounter gets a real anchor on every backend.+ let inputTokens = 0+ let outputTokens = 0for await (const { data } of parseSSEWithEvents<AnthropicStreamEvent>(res)) {if (options?.signal?.aborted) breakswitch (data.type) {+ case 'message_start': {+ const u = data.message?.usage+ if (u?.input_tokens) inputTokens = u.input_tokens+ break+ }+case 'content_block_start': {if (data.content_block?.type === 'tool_use') {toolUseBlocks.set(data.index!, {@@ -168,19 +179,25 @@ export class AnthropicProvider implements ProviderClient {// onto the unified finishReason ('max_tokens' → 'length', the key// the chat layer uses to explain thought-only/truncated turns).const stopReason = (data.delta as any)?.stop_reason as string | undefined+ if (data.usage?.output_tokens) outputTokens = data.usage.output_tokensconst toolCalls = this.flushToolUseBlocks(toolUseBlocks)yield {content: '',toolCalls: toolCalls.length ? toolCalls : undefined,done: true,finishReason: stopReason === 'max_tokens' ? 'length' : (stopReason || 'stop'),+ promptEvalCount: inputTokens || undefined,+ evalCount: outputTokens || undefined,}return}case 'message_stop': {const toolCalls2 = this.flushToolUseBlocks(toolUseBlocks)- yield { content: '', toolCalls: toolCalls2.length ? toolCalls2 : undefined, done: true, finishReason: 'stop' }+ yield {+ content: '', toolCalls: toolCalls2.length ? toolCalls2 : undefined, done: true, finishReason: 'stop',+ promptEvalCount: inputTokens || undefined, evalCount: outputTokens || undefined,+ }return}}@@ -190,7 +207,10 @@ export class AnthropicProvider implements ProviderClient {// connection was cut mid-generation (same semantics as the OpenAI// provider's missing-[DONE] path).const toolCalls = this.flushToolUseBlocks(toolUseBlocks)- yield { content: '', toolCalls: toolCalls.length ? toolCalls : undefined, done: true, finishReason: 'disconnect' }+ yield {+ content: '', toolCalls: toolCalls.length ? toolCalls : undefined, done: true, finishReason: 'disconnect',+ promptEvalCount: inputTokens || undefined, evalCount: outputTokens || undefined,+ }}async chatWithTools(diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex e1aec159..bb01664b 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -133,21 +133,33 @@ function guessContextFromName(model: string): number {return 8192}+// Real context windows from the provider's /models catalogue (LU Cloud sends+// context_length per model). The name heuristic underestimates new cloud+// models badly (Qwen3.6-35B-A3B → 32k guess vs 262k real), which shrinks the+// applyMaxTokens headroom toward the 256 floor on long chats and truncates+// answers. Module-level and keyed by endpoint — NOT an instance field: the+// lu-cloud provider builds a FRESH OpenAIProvider delegate on every call (its+// bearer token rotates), so an instance map is always empty exactly where it+// matters. listModels fills it through one delegate; chatStream's+// applyMaxTokens and getContextLength read it through another.+const catalogContext = new Map<string, number>()++/** Test-only: reset the endpoint catalogue between test cases. */+export function __clearContextCatalogForTests(): void {+ catalogContext.clear()+}+// ── Provider Implementation ────────────────────────────────────export class OpenAIProvider implements ProviderClient {readonly id = 'openai' as const- // Real context windows from the provider's /models catalogue (LU Cloud- // sends context_length per model). The name heuristic underestimates new- // cloud models badly (Qwen3.6-35B-A3B → 32k guess vs 262k real), which- // shrinks the applyMaxTokens headroom toward the 256 floor on long chats- // and truncates answers. Filled by listModels; instances are cached in the- // registry, so the catalogue survives across requests.- private catalogContext = new Map<string, number>()-constructor(private config: ProviderConfig) {}+ private catalogKey(model: string): string {+ return `${this.baseUrl}|${model}`+ }+private get baseUrl(): string {return this.config.baseUrl.replace(/\/+$/, '')}@@ -230,9 +242,12 @@ export class OpenAIProvider implements ProviderClient {// it — we handle that with a retry below.if (options?.thinking === true) body.reasoning_effort = 'high'else if (options?.thinking === false) body.reasoning_effort = 'minimal'- // Ask LM Studio / local openai-compat servers for REAL token usage in a- // final stream chunk (choices:[] + usage:{...}). Dropped on 400 below.- if (this.useLocalProxy) body.stream_options = { include_usage: true }+ // Ask the server for REAL token usage in a final stream chunk+ // (choices:[] + usage:{...}). OpenAI, DeepInfra (LU Cloud), Groq, vLLM and+ // LM Studio all honor stream_options; an endpoint that rejects unknown+ // params 400/422s and the retry below drops it. Real usage is what keeps+ // the TokenCounter honest — a char/4 estimate can't see the system prompt.+ body.stream_options = { include_usage: true }if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)const fetcher = this.useLocalProxy ? localFetchStream : fetch@@ -475,7 +490,7 @@ export class OpenAIProvider implements ProviderClient {// catalogContext). Server value beats every heuristic — it reflects// what THIS deployment actually serves.if (m.context_length && m.context_length > 0) {- this.catalogContext.set(m.id, m.context_length)+ catalogContext.set(this.catalogKey(m.id), m.context_length)}return {id: m.id,@@ -567,7 +582,7 @@ export class OpenAIProvider implements ProviderClient {// 3. probeContextFromServer (LM Studio enhanced + generic /v1/models/<id>)// 4. Heuristik aus dem Modell-Namen// 5. Konservativer 8192er-Fallback (in guessContextFromName)- const catalog = this.catalogContext.get(model)+ const catalog = catalogContext.get(this.catalogKey(model))if (catalog && catalog > 0) return catalogif (KNOWN_CONTEXT[model]) return KNOWN_CONTEXT[model]const probed = await this.probeContextFromServer(model)diff --git a/src/components/chat/TokenCounter.tsx b/src/components/chat/TokenCounter.tsxindex 3eae9de0..21878946 100644--- a/src/components/chat/TokenCounter.tsx+++ b/src/components/chat/TokenCounter.tsx@@ -1,5 +1,5 @@import { useChatStore } from '../../stores/chatStore'-import { estimateTokens } from '../../lib/context-compaction'+import { computeContextFill } from '../../lib/token-usage'import { useActiveContextWindow } from '../../hooks/useActiveContextWindow'export function TokenCounter() {@@ -15,49 +15,27 @@ export function TokenCounter() {const conversation = conversations.find((c) => c.id === activeConversationId)const messages = conversation?.messages || []- // 100%-REAL usage: the latest assistant message's model-reported usage.- // promptTokens already includes the system prompt, tools, RAG and the full- // history, so totalTokens is the TRUE current context fill. The char/4- // estimate is only a fallback until the first real reply lands.- // The counter must not visibly "jump" between turns (David 2026-06-20: "3.5k- // springt auf 1.9k", especially after an image/video gen). The model-reported- // usage is the size of the COMPACTED prompt that turn — and that legitimately- // swings: a turn that feeds the generated image back for vision costs ~3k, the- // next turn (image trimmed by compaction, or a regenerate that reuses the prior- // args) costs ~1k. Both are "real", so showing the latest made the bar bounce.- // Use the conversation's HIGH-WATER real usage instead: it reflects the largest- // context this chat has actually reached and never dips just because one turn- // compacted harder. A live provisional estimate can still push it higher.- const reversed = [...messages].reverse()- const realMax = messages.reduce(- (mx, m) => (m.usage && !m.usage.estimated && m.usage.totalTokens > mx ? m.usage.totalTokens : mx),- 0,- )- const lastUsage = reversed.find((m) => m.usage && m.usage.totalTokens > 0)?.usage- const estimated = messages.reduce((sum, m) => {- let tokens = estimateTokens(m.content)- if (m.thinking) tokens += estimateTokens(m.thinking)- if (m.toolCallSummary) tokens += estimateTokens(m.toolCallSummary)- tokens += 4 // role overhead- return sum + tokens- }, 0)- const rawUsed = realMax > 0- ? Math.max(realMax, lastUsage?.totalTokens ?? 0)- : (lastUsage ? lastUsage.totalTokens : estimated)+ // Context fill = what the NEXT request will roughly send, anchored on the+ // newest model-reported usage (real promptTokens include system prompt ++ // tools + RAG + history) plus the visible messages after it. Reasoning+ // (`thinking`) is never resent, so it is never counted — the old+ // conversation-high-water over totalTokens pinned this counter at "16.5k"+ // forever after one looping cloud reasoner burned its whole 16,384-token+ // completion budget, while the next real prompt cost 65 tokens (David,+ // 2026-07-12). An honest dip after compaction beats a sticky wrong maximum.+ const fill = computeContextFill(messages)+ const rawUsed = fill.usedif (!activeConversationId || messages.length === 0) return null// Resolved real context window; fall back to the VRAM-safe default only while// the provider probe is still in flight (ctx not resolved yet).const maxTokens = ctx.contextWindow > 0 ? ctx.contextWindow : 16384- // Cap the numerator at the active window. The anti-jump high-water (realMax)- // is per-conversation, not per-model, so switching to a SMALLER-context model- // mid-chat would otherwise pin the bar above 100% forever (e.g. a 20k chat on- // an 8k model → "20k/8k" red). Showing "8.0k/8.0k" (full) is honest.+ // Cap the numerator at the active window: a long chat carried onto a+ // smaller-context model shows "8.0k/8.0k" (full), not "20k/8k".const usedTokens = Math.min(rawUsed, maxTokens)- // "Real" = the model reported it AND that exact number is what we're showing- // (not capped down, no larger provisional estimate on top).- const isReal = realMax > 0 && rawUsed === realMax && usedTokens === rawUsed+ // "Real" = anchored on a non-estimated model report and shown uncapped.+ const isReal = fill.real && usedTokens === rawUsedconst ratio = maxTokens > 0 ? usedTokens / maxTokens : 0const color = ratio > 0.8 ? 'text-red-400' : ratio > 0.5 ? 'text-amber-400' : 'text-gray-500'@@ -71,10 +49,8 @@ export function TokenCounter() {? 'Ollama num_ctx': 'model context'const title = isReal- ? `Context: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — real, reported by the model (includes system prompt + tools + RAG)`- : lastUsage- ? `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — includes the system prompt + tools; the exact count lands when the model replies`- : `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — estimate until the first reply`+ ? `Context: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — anchored on the model's last reported usage (includes system prompt + tools + RAG); reasoning tokens are not context and aren't counted`+ : `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}) — estimate until the model reports real usage`return (<div className={`flex items-center gap-1.5 px-2 py-1 ${color}`} title={title}>diff --git a/src/lib/__tests__/token-usage.test.ts b/src/lib/__tests__/token-usage.test.tsnew file mode 100644index 00000000..c18ef389--- /dev/null+++ b/src/lib/__tests__/token-usage.test.ts@@ -0,0 +1,85 @@+/**+ * Context-fill semantics for the TokenCounter (David, 2026-07-12): a looping+ * cloud reasoner burned its whole 16,384-token completion budget as hidden+ * thinking; the old high-water over usage.totalTokens pinned the counter at+ * "16.5k" for the rest of the conversation while the next real prompt cost+ * 65 tokens. Reasoning is never resent, so it is never context.+ *+ * Run: npx vitest run src/lib/__tests__/token-usage.test.ts+ */+import { describe, it, expect } from 'vitest'+import { computeContextFill, type FillMessage } from '../token-usage'+import { estimateTokens } from '../context-compaction'++const user = (content: string): FillMessage => ({ role: 'user', content })+const assistant = (content: string, extra: Partial<FillMessage> = {}): FillMessage =>+ ({ role: 'assistant', content, ...extra })++describe('computeContextFill', () => {+ it('estimates from visible content only when no usage exists', () => {+ const msgs = [user('hello there'), assistant('hi!')]+ const expected = estimateTokens('hello there') + 4 + estimateTokens('hi!') + 4+ expect(computeContextFill(msgs)).toEqual({ used: expected, real: false })+ })++ it('never counts thinking — with or without a usage anchor', () => {+ const noAnchor = [user('q'), assistant('', { thinking: 'x'.repeat(40000) })]+ expect(computeContextFill(noAnchor).used).toBeLessThan(50)++ const anchored = [+ user('q'),+ assistant('', {+ thinking: 'x'.repeat(40921),+ usage: { promptTokens: 85, completionTokens: 16384, totalTokens: 16469 },+ }),+ ]+ // The crashout turn: 85 real prompt tokens + an empty visible reply.+ // The old high-water showed 16,469 here.+ const fill = computeContextFill(anchored)+ expect(fill.used).toBeLessThan(150)+ expect(fill.used).toBeGreaterThanOrEqual(85)+ expect(fill.real).toBe(true)+ })++ it('anchors on the newest usage and adds visible messages after it', () => {+ const msgs = [+ user('first'),+ assistant('a1', { usage: { promptTokens: 500, completionTokens: 20, totalTokens: 520 } }),+ user('second'),+ assistant('a2', { usage: { promptTokens: 900, completionTokens: 30, totalTokens: 930 } }),+ user('third — not answered yet'),+ ]+ const tail =+ estimateTokens('a2') + 4 ++ estimateTokens('third — not answered yet') + 4+ expect(computeContextFill(msgs)).toEqual({ used: 900 + tail, real: true })+ })++ it('a provisional (estimated) anchor is used but not reported as real', () => {+ const msgs = [+ user('q'),+ assistant('a', { usage: { promptTokens: 300, completionTokens: 10, totalTokens: 310, estimated: true } }),+ ]+ const fill = computeContextFill(msgs)+ expect(fill.used).toBe(300 + estimateTokens('a') + 4)+ expect(fill.real).toBe(false)+ })++ it('counts toolCallSummary as visible context', () => {+ const withTool = computeContextFill([assistant('a', { toolCallSummary: 'used web_search("x") → 3 results' })])+ const without = computeContextFill([assistant('a')])+ expect(withTool.used).toBeGreaterThan(without.used)+ })++ it('an honest dip after compaction beats a sticky wrong maximum', () => {+ // Turn 1 fed an image (expensive prompt), turn 2 compacted it away.+ const msgs = [+ user('look at this image'),+ assistant('I see a cat', { usage: { promptTokens: 3500, completionTokens: 40, totalTokens: 3540 } }),+ user('thanks'),+ assistant('yw', { usage: { promptTokens: 1200, completionTokens: 5, totalTokens: 1205 } }),+ ]+ // Anchored on the NEWEST usage (1200), not the conversation maximum.+ expect(computeContextFill(msgs).used).toBeLessThan(1400)+ })+})diff --git a/src/lib/token-usage.ts b/src/lib/token-usage.tsnew file mode 100644index 00000000..1ea2921d--- /dev/null+++ b/src/lib/token-usage.ts@@ -0,0 +1,74 @@+/**+ * Context-fill computation for the TokenCounter.+ *+ * "Used" means: roughly what the NEXT request will send — that is the only+ * number worth alarming the user about. Two rules keep it honest:+ *+ * 1. Anchor on the newest model-reported usage when one exists. Its+ * promptTokens is 100% real and already includes the system prompt, tools,+ * RAG and the whole history up to that turn — things a char/4 estimate of+ * the visible messages can never see.+ *+ * 2. Never count reasoning as context. `thinking` is stripped from outgoing+ * requests (useChat sends role+content+images only), and completionTokens+ * on a reasoning model is mostly hidden thinking. A looping cloud reasoner+ * once burned its whole 16,384-token completion budget producing zero+ * visible output; counting that (or high-watering totalTokens across the+ * conversation, as this component used to) pinned the counter at "16.5k"+ * forever while the next real prompt cost 65 tokens (David, 2026-07-12).+ * Only the assistant's visible content joins future prompts, so only that+ * is added on top of the anchor.+ */++import { estimateTokens } from './context-compaction'++export interface FillMessage {+ role: string+ content: string+ thinking?: string+ toolCallSummary?: string+ usage?: {+ promptTokens: number+ completionTokens: number+ totalTokens: number+ estimated?: boolean+ }+}++export interface ContextFill {+ /** Estimated tokens the next request will carry. */+ used: number+ /** True when `used` is anchored on a non-estimated, model-reported usage. */+ real: boolean+}++/** Visible size of one message in a future prompt (content only, no thinking). */+function visibleTokens(m: FillMessage): number {+ let t = estimateTokens(m.content)+ if (m.toolCallSummary) t += estimateTokens(m.toolCallSummary)+ return t + 4 // role overhead+}++export function computeContextFill(messages: FillMessage[]): ContextFill {+ // Newest message carrying usage (assistant turns store it when the model+ // reports real counts; the agent path stores a provisional estimated one).+ let anchorIdx = -1+ for (let i = messages.length - 1; i >= 0; i--) {+ const u = messages[i].usage+ if (u && u.totalTokens > 0) { anchorIdx = i; break }+ }++ if (anchorIdx === -1) {+ // No usage anywhere yet — plain estimate over the visible conversation.+ return { used: messages.reduce((sum, m) => sum + visibleTokens(m), 0), real: false }+ }++ const anchor = messages[anchorIdx].usage!+ // promptTokens covers everything UP TO that turn's input; the anchored+ // message's own visible reply + every later message joins the next prompt.+ let used = anchor.promptTokens+ for (let i = anchorIdx; i < messages.length; i++) {+ used += visibleTokens(messages[i])+ }+ return { used, real: !anchor.estimated }+}