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
feat: correct context window + 100%-real token usage (Ollama + LM Studio)
purpleef8fc1db5a11
diff --git a/src/api/ollama.ts b/src/api/ollama.tsindex ccd3dec7..b7d23136 100644--- a/src/api/ollama.ts+++ b/src/api/ollama.ts@@ -51,6 +51,18 @@ export async function getModelContext(name: string): Promise<number> {}}+// Cached model-context lookup so the chat hooks can forward a correct num_ctx+// to Ollama on EVERY send without an /api/show round-trip each time. A model's+// trained context length doesn't change at runtime; cache lives for the session.+const _ctxCache = new Map<string, number>()+export async function getModelContextCached(name: string): Promise<number> {+ const hit = _ctxCache.get(name)+ if (hit !== undefined) return hit+ const v = await getModelContext(name)+ _ctxCache.set(name, v)+ return v+}+export async function chatStream(model: string,messages: { role: string; content: string }[],diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.tsindex 1bcbe798..19086b19 100644--- a/src/api/providers/ollama-provider.ts+++ b/src/api/providers/ollama-provider.ts@@ -103,6 +103,10 @@ export class OllamaProvider implements ProviderClient {// 2026-05-27: "LU caps VRAM ~5 GB regardless of context window UI// setting" — the UI setting was never wired here. Setting num_ctx// higher than the loaded model's max is harmless (Ollama clamps).+ // num_ctx comes from the caller (hook): the user override OR the model's+ // real context length (capped for VRAM safety). 0/undefined → Ollama keeps+ // its own default; the hook always passes a real value so a chat never+ // silently sits at Ollama's 2048 default.if (options?.contextWindow && options.contextWindow > 0) {ollamaOptions.num_ctx = options.contextWindow}@@ -152,6 +156,7 @@ export class OllamaProvider implements ProviderClient {// client-side TTFT, which WebView2 release-mode buffers into// uselessness for fast small models.evalCount: chunk.eval_count,+ promptEvalCount: chunk.prompt_eval_count,evalDurationMs: chunk.eval_duration !== undefined ? chunk.eval_duration / 1_000_000 : undefined,}}@@ -184,6 +189,10 @@ export class OllamaProvider implements ProviderClient {if (options?.topK !== undefined) ollamaOptions.top_k = options.topKif (options?.maxTokens) ollamaOptions.num_predict = options.maxTokens// Bug AA v2.5.0 — see chatStream() for the why.+ // num_ctx comes from the caller (hook): the user override OR the model's+ // real context length (capped for VRAM safety). 0/undefined → Ollama keeps+ // its own default; the hook always passes a real value so a chat never+ // silently sits at Ollama's 2048 default.if (options?.contextWindow && options.contextWindow > 0) {ollamaOptions.num_ctx = options.contextWindow}diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 151d0754..a7e674c9 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -179,6 +179,9 @@ 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 (isLocalUrl(this.baseUrl)) body.stream_options = { include_usage: true }const fetcher = isLocalUrl(this.baseUrl) ? localFetchStream : fetchlet res = await fetcher(`${this.baseUrl}/chat/completions`, {@@ -189,8 +192,9 @@ export class OpenAIProvider implements ProviderClient {} as any)// Retry without reasoning_effort if the model/endpoint rejects it.- if (!res.ok && res.status === 400 && 'reasoning_effort' in body) {+ if (!res.ok && res.status === 400 && ('reasoning_effort' in body || 'stream_options' in body)) {delete body.reasoning_effort+ delete body.stream_optionsres = await fetcher(`${this.baseUrl}/chat/completions`, {method: 'POST',headers: this.headers,@@ -205,12 +209,22 @@ export class OpenAIProvider implements ProviderClient {// Accumulate tool call arguments across chunks (OpenAI streams them in pieces)const toolCallAccum: Map<number, { id: string; name: string; args: string }> = new Map()+ let promptTokens = 0+ let completionTokens = 0+ const doneChunk = (): ChatStreamChunk => {+ const toolCalls = this.flushToolCalls(toolCallAccum)+ return {+ content: '',+ toolCalls: toolCalls.length ? toolCalls : undefined,+ done: true,+ promptEvalCount: promptTokens || undefined,+ evalCount: completionTokens || undefined,+ }+ }for await (const event of parseSSEStream(res)) {if (event.data === '[DONE]') {- // Flush accumulated tool calls- const toolCalls = this.flushToolCalls(toolCallAccum)- yield { content: '', toolCalls: toolCalls.length ? toolCalls : undefined, done: true }+ yield doneChunk()return}@@ -221,6 +235,14 @@ export class OpenAIProvider implements ProviderClient {continue}+ // Real token usage — the include_usage final chunk carries `usage` with+ // an empty choices[], so capture it BEFORE the choice guard below.+ const u = (chunk as { usage?: { prompt_tokens?: number; completion_tokens?: number } }).usage+ if (u) {+ promptTokens = u.prompt_tokens || promptTokens+ completionTokens = u.completion_tokens || completionTokens+ }+const choice = chunk.choices?.[0]if (!choice) continue@@ -246,16 +268,15 @@ export class OpenAIProvider implements ProviderClient {yield { content, done: false }}- if (choice.finish_reason === 'tool_calls' || choice.finish_reason === 'stop') {- const toolCalls = this.flushToolCalls(toolCallAccum)- yield { content: '', toolCalls: toolCalls.length ? toolCalls : undefined, done: true }- return- }+ // NB: we intentionally do NOT early-return on finish_reason. With+ // stream_options.include_usage the server sends the usage chunk AFTER+ // the finish_reason chunk — returning early would discard it. The [DONE]+ // sentinel (or the end-of-stream fallback below) emits the single done+ // chunk, which now carries the captured usage.}- // If stream ended without explicit done- const toolCalls = this.flushToolCalls(toolCallAccum)- yield { content: '', toolCalls: toolCalls.length ? toolCalls : undefined, done: true }+ // Stream ended without an explicit [DONE] sentinel.+ yield doneChunk()}async chatWithTools(@@ -290,8 +311,9 @@ export class OpenAIProvider implements ProviderClient {signal: options?.signal,} as any)- if (!res.ok && res.status === 400 && 'reasoning_effort' in body) {+ if (!res.ok && res.status === 400 && ('reasoning_effort' in body || 'stream_options' in body)) {delete body.reasoning_effort+ delete body.stream_optionsres = await fetcher(`${this.baseUrl}/chat/completions`, {method: 'POST',headers: this.headers,diff --git a/src/api/providers/types.ts b/src/api/providers/types.tsindex 4aab4bc3..4b29389c 100644--- a/src/api/providers/types.ts+++ b/src/api/providers/types.ts@@ -121,6 +121,7 @@ export interface ChatStreamChunk {// available, because WebView2 release-mode often buffers the response and// makes client-side TTFT measurement meaningless for fast models.evalCount?: number // tokens generated by the model+ promptEvalCount?: number // tokens in the prompt = real consumed context (system+tools+history+input)evalDurationMs?: number // generation time in ms (excludes prompt eval + load)}diff --git a/src/components/chat/TokenCounter.tsx b/src/components/chat/TokenCounter.tsxindex a9b0f97f..9f534c27 100644--- a/src/components/chat/TokenCounter.tsx+++ b/src/components/chat/TokenCounter.tsx@@ -3,6 +3,7 @@ import { useChatStore } from '../../stores/chatStore'import { useModelStore } from '../../stores/modelStore'import { useSettingsStore } from '../../stores/settingsStore'import { estimateTokens, getModelMaxTokens } from '../../lib/context-compaction'+import { effectiveContextWindow } from '../../lib/context-window'export function TokenCounter() {const activeConversationId = useChatStore((s) => s.activeConversationId)@@ -14,20 +15,28 @@ export function TokenCounter() {// (e.g. 8.2k) even after the user moved the slider to 16384. Subscribing// to the settings store fixes the staleness — `useSettingsStore` re-renders// any consumer on every settings update.- const settingsMaxTokens = useSettingsStore((s) => s.settings.maxTokens)+ // Context-window override (num_ctx), NOT maxTokens (that's the output limit+ // num_predict — using it as the denominator was a long-standing mismatch).+ const contextOverride = useSettingsStore((s) => s.settings.contextWindowOverride)const [modelMaxTokens, setModelMaxTokens] = useState<number>(4096)const conversation = conversations.find((c) => c.id === activeConversationId)const messages = conversation?.messages || []- // Estimate used tokens from all messages- const usedTokens = messages.reduce((sum, m) => {+ // 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.+ const lastUsage = [...messages].reverse().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 overheadreturn sum + tokens}, 0)+ const usedTokens = lastUsage ? lastUsage.totalTokens : estimated+ const isReal = !!lastUsage// Fetch max tokens when model changes — only the model-side default is// cached here; the user override is read live from the settings store.@@ -38,9 +47,10 @@ export function TokenCounter() {if (!activeConversationId || messages.length === 0) return null- // Effective ceiling: user-set maxTokens wins if non-zero (the slider's "0"- // default means "use whatever the model reports").- const maxTokens = settingsMaxTokens > 0 ? settingsMaxTokens : modelMaxTokens+ // Denominator = the context window we actually send to the model (num_ctx):+ // the override if set, else the model's real context capped for VRAM safety.+ // Same formula the Ollama provider uses, so display and reality can't drift.+ const maxTokens = effectiveContextWindow(modelMaxTokens, contextOverride)const ratio = maxTokens > 0 ? usedTokens / maxTokens : 0const color = ratio > 0.8 ? 'text-red-400' : ratio > 0.5 ? 'text-amber-400' : 'text-gray-500'@@ -48,10 +58,9 @@ export function TokenCounter() {const formatK = (n: number) => n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n)- const isOverride = settingsMaxTokens > 0 && settingsMaxTokens !== modelMaxTokens- const title = isOverride- ? `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (Settings override — model default is ${modelMaxTokens.toLocaleString()})`- : `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens`+ const title = isReal+ ? `Context: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (num_ctx) — real, reported by the model (includes system prompt + tools + RAG)`+ : `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (num_ctx) — estimate until the first reply`return (<div className={`flex items-center gap-1.5 px-2 py-1 ${color}`} title={title}>diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 205007ae..9ce05fee 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -25,6 +25,8 @@ import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, strimport { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, canonicalToolName } from '../lib/loose-tool-parse'import { buildVisionFeedback } from '../api/vision-feedback'import { compactMessages, getModelMaxTokens } from '../lib/context-compaction'+import { getModelContextCached } from '../api/ollama'+import { effectiveContextWindow } from '../lib/context-window'import { useMemoryStore } from '../stores/memoryStore'import { getProviderForModel, getProviderIdFromModel } from '../api/providers'import { buildExtractionPrompt, parseExtractionResponse } from '../lib/memory-extraction'@@ -516,25 +518,31 @@ export function useAgentChat() {: settings.thinkingEnabled === true): undefined+ // num_ctx (David: "muss immer stimmen"): the override, else the model's+ // REAL context (capped for VRAM), floored at 8192 so feeding a generated+ // image back for vision feedback never overflows a 4096-default model.+ let agentCtx: number = settings.contextWindowOverride || 8192+ if (providerId === 'ollama' && !settings.contextWindowOverride) {+ try {+ agentCtx = Math.max(effectiveContextWindow(await getModelContextCached(modelId), 0), 8192)+ } catch { /* keep the 8192 floor on failure */ }+ }const chatOptions = {temperature: settings.temperature,topP: settings.topP,topK: settings.topK,maxTokens: settings.maxTokens || undefined,- // Bug AA v2.5.0 — Kj103x. Same num_ctx override flow as useChat.- // David 2026-06-04: default the AGENT context to 8192 (not the model's- // 4096 default) so feeding a generated image back for vision feedback- // doesn't overflow ("request 5667 > available 4096" → HTTP 400 →- // "Agent error: Connection failed" after gemma's image). 8192 is within- // both installed models' real limits.- contextWindow: settings.contextWindowOverride || 8192,+ contextWindow: agentCtx,thinking: thinkOpt as unknown as boolean,signal: abort.signal,}// Context compaction — keep the trim target in sync with the 8192 num_ctx// above so a generated image fed back for vision isn't trimmed right out.- const maxCtx = Math.max(await getModelMaxTokens(activeModel), settings.contextWindowOverride || 8192)+ // Keep the compaction budget == the actual num_ctx we send, so we never+ // trim to the model's full context (e.g. 128k) while Ollama only has the+ // capped num_ctx allocated — that mismatch caused prompt overflow.+ const maxCtx = agentCtxagentMessages = compactMessages(agentMessages as OllamaChatMessage[],Math.floor(maxCtx * 0.8)diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex bf59fba9..34adbd22 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -9,6 +9,8 @@ import { useMemoryStore } from "../stores/memoryStore"import { retrieveContext } from "../api/rag"import { speakStreaming, isSpeechSynthesisSupported, getVoicesAsync } from "../api/voice"import { getModelMaxTokens } from "../lib/context-compaction"+import { getModelContextCached } from "../api/ollama"+import { effectiveContextWindow } from "../lib/context-window"import { useAgentChat } from "./useAgentChat"import { useMemory } from "./useMemory"import { useAgentModeStore } from "../stores/agentModeStore"@@ -191,15 +193,24 @@ export function useChat() {? undefined: settings.thinkingEnabled === true): undefined+ // num_ctx must always be a real value (David: "kontext window muss immer+ // stimmen"). For Ollama, default to the model's REAL context length+ // (capped for VRAM safety) when there's no explicit override — otherwise+ // Ollama silently runs at 2048 and truncates real chats/RAG. Cloud and+ // LM-Studio ignore contextWindow (load-time config there).+ let effectiveCtx: number | undefined = settings.contextWindowOverride || undefined+ if (providerId === 'ollama') {+ try {+ effectiveCtx = effectiveContextWindow(await getModelContextCached(modelId), settings.contextWindowOverride)+ } catch { /* keep override-or-undefined on failure */ }+ }const chatOpts = {temperature: settings.temperature,topP: settings.topP,topK: settings.topK,maxTokens: settings.maxTokens || undefined,- // Bug AA v2.5.0 — Kj103x. 0 in settings means "let provider decide";- // any positive value gets forwarded as Ollama `num_ctx`. Other- // providers ignore the field.- contextWindow: settings.contextWindowOverride || undefined,+ // num_ctx: real model context (capped) for Ollama, else override-or-none.+ contextWindow: effectiveCtx,thinking: useThinking,signal: abort.signal,}@@ -312,6 +323,20 @@ export function useChat() {.getState().updateMessageThinking(convId!, assistantMessage.id, thinkingRef.current)}+ // Real token usage from the model's final chunk — promptEvalCount is+ // the FULL consumed context (system+tools+RAG+history+input), so the+ // TokenCounter can show 100%-real usage instead of a char/4 estimate.+ if (chunk.promptEvalCount || chunk.evalCount) {+ const promptTokens = chunk.promptEvalCount || 0+ const completionTokens = chunk.evalCount || 0+ useChatStore+ .getState()+ .updateMessageUsage(convId!, assistantMessage.id, {+ promptTokens,+ completionTokens,+ totalTokens: promptTokens + completionTokens,+ })+ }}}} catch (err) {diff --git a/src/lib/context-window.ts b/src/lib/context-window.tsnew file mode 100644index 00000000..98b0588a--- /dev/null+++ b/src/lib/context-window.ts@@ -0,0 +1,31 @@+/**+ * Effective context-window resolution — single source of truth so the value we+ * SEND to the model (Ollama `num_ctx`) and the value we DISPLAY (TokenCounter+ * denominator) can never disagree (David 2026-06-05: "muss immer stimmen").+ *+ * Leaf module — imports NOTHING from api/* so it can be used by both the+ * provider layer and the UI without an import cycle.+ *+ * Why a cap and not the model's full trained context:+ * - Ollama allocates the KV cache for `num_ctx` at load time. A model may+ * advertise a 128k–256k context, but allocating that much KV cache OOMs+ * consumer GPUs instantly. Ollama's own default (2048) is the opposite+ * failure: it silently truncates every real chat.+ * - 16384 is the balance: 8× Ollama's default (no silent truncation for+ * normal chats/RAG), yet a modest KV footprint that fits a 12 GB card.+ * - Power users who know their VRAM set `contextWindowOverride` in Settings;+ * that wins and can go all the way to the model's real maximum.+ */+export const DEFAULT_CONTEXT_CAP = 16384++/**+ * @param modelMax the model's real/trained context length (0/undefined = unknown)+ * @param override user's explicit contextWindowOverride (0 = no override)+ * @returns the context window to actually use — never exceeds the model's real+ * max (when known), never silently sits at Ollama's 2048 default.+ */+export function effectiveContextWindow(modelMax: number | undefined, override?: number): number {+ if (override && override > 0) return override+ const max = modelMax && modelMax > 0 ? modelMax : DEFAULT_CONTEXT_CAP+ return Math.min(max, DEFAULT_CONTEXT_CAP)+}diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex 139e7fbc..bae67326 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -42,6 +42,7 @@ interface ChatState {insertMessageBefore: (conversationId: string, beforeId: string, message: Message) => voidupdateMessageContent: (conversationId: string, messageId: string, content: string) => voidupdateMessageThinking: (conversationId: string, messageId: string, thinking: string) => void+ updateMessageUsage: (conversationId: string, messageId: string, usage: { promptTokens: number; completionTokens: number; totalTokens: number }) => voidupdateMessageAgentBlocks: (conversationId: string, messageId: string, blocks: AgentBlock[]) => voiddeleteMessagesAfter: (conversationId: string, messageId: string) => voidgetActiveConversation: () => Conversation | undefined@@ -168,6 +169,19 @@ export const useChatStore = create<ChatState>()(),})),+ updateMessageUsage: (conversationId, messageId, usage) =>+ set((state) => ({+ conversations: state.conversations.map((c) =>+ c.id === conversationId+ ? {+ ...c,+ messages: c.messages.map((m) => (m.id === messageId ? { ...m, usage } : m)),+ updatedAt: Date.now(),+ }+ : c+ ),+ })),+updateMessageAgentBlocks: (conversationId, messageId, agentBlocks) =>set((state) => ({conversations: state.conversations.map((c) =>diff --git a/src/types/chat.ts b/src/types/chat.tsindex 94964a70..8235e6ee 100644--- a/src/types/chat.ts+++ b/src/types/chat.ts@@ -24,6 +24,11 @@ export interface Message {// Hidden messages are included in the API payload but not rendered.hidden?: booleantool_calls?: { function: { name: string; arguments: Record<string, unknown> } }[]+ // Real token usage reported by the model (Ollama prompt_eval_count/eval_count,+ // OpenAI/LM-Studio usage.*). promptTokens = the FULL consumed context for that+ // turn (system prompt + tools + RAG + history + input), so it powers a+ // 100%-real context readout instead of a char/4 estimate.+ usage?: { promptTokens: number; completionTokens: number; totalTokens: number }}export interface Conversation {