Skip to content

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.

fix(ui): the meter counts the tool catalog it is sending

Davidd2810671db8d
diff --git a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts b/src/api/mcp/__tests__/tool-catalog-tokens.test.ts
index 9e7fc1e6..24b7358f 100644
--- a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts
+++ b/src/api/mcp/__tests__/tool-catalog-tokens.test.ts
@@ -31,6 +31,7 @@ import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { toolRegistry, DEFAULT_PERMISSIONS } from '../index'
import { gateCreateTools } from '../../../lib/tool-selection'
+import { estimateTokens } from '../../../lib/context-compaction'
/** Mirrors CODEX_CATEGORIES in useCodex.ts (same reason as the sibling tests). */
const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web', 'image', 'video', 'workflow']
@@ -108,6 +109,17 @@ describe('the coding step carries a catalog the diet actually shrank', () => {
expect(fullWire().length).toBeLessThanOrEqual(FULL_CHAR_CEILING)
})
+ it('the catalog the meter now adds is the bigger half of a first step', () => {
+ // The token counter adds estimateTokens(JSON.stringify(tools)) on top of
+ // the message estimate (useCodex/useAgentChat reportTools). A fresh coding
+ // step's messages are ~732 tokens on this scale, so leaving the catalog out
+ // showed under a third of the request. Same estimator the meter uses, so
+ // this is the correction itself, not a proxy for it.
+ const catalog = estimateTokens(codingWire())
+ expect(catalog).toBeGreaterThan(1500)
+ expect(catalog).toBeLessThanOrEqual(CODING_CHAR_CEILING / 4 + 1)
+ })
+
it('the mobile catalog went on the same diet, or it drifts from here', () => {
// The relay re-declares AGENT_TOOLS inline. tool-description-parity pins
// them word for word; this one names the cut phrases directly, so a revert
diff --git a/src/components/chat/TokenCounter.tsx b/src/components/chat/TokenCounter.tsx
index 4b54aa99..d41f8968 100644
--- a/src/components/chat/TokenCounter.tsx
+++ b/src/components/chat/TokenCounter.tsx
@@ -27,9 +27,15 @@ export function TokenCounter() {
// 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.
+ // Messages PLUS the tool catalog: both are the request, both are billed, and
+ // the catalog is the bigger half of what a fresh coding step costs. Leaving
+ // it out made the meter read about 1.700 tokens low on every step of a
+ // coding run, worst exactly where it is otherwise near zero.
const fill = computeContextFill(
messages,
- sent ? { tokens: sent.tokens, atMessageCount: sent.atMessageCount } : undefined,
+ sent
+ ? { tokens: sent.tokens + sent.toolsTokens, atMessageCount: sent.atMessageCount }
+ : undefined,
)
const rawUsed = fill.used
@@ -68,7 +74,7 @@ export function TokenCounter() {
? `. Capped: a step sends at most ${maxTokens.toLocaleString()} of this model's ${ctx.contextWindow.toLocaleString()} tokens (Settings, send window), and tool results older than the newest step go out shortened`
: ''
const title = fill.source === 'built'
- ? `Last request: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens, the size of the payload actually built for the last step, decay and compaction included${capNote}`
+ ? `Last request: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens, the size of the payload actually built for the last step, tool catalog, decay and compaction included${capNote}`
: isReal
? `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${capNote}`
: `Estimated: ${usedTokens.toLocaleString()} / ${maxTokens.toLocaleString()} tokens (${source}), estimate until the model reports real usage${capNote}`
diff --git a/src/hooks/__tests__/decay-wiring.test.ts b/src/hooks/__tests__/decay-wiring.test.ts
index bd8876d2..30f9a2b7 100644
--- a/src/hooks/__tests__/decay-wiring.test.ts
+++ b/src/hooks/__tests__/decay-wiring.test.ts
@@ -55,6 +55,15 @@ describe.each([
expect(source).toMatch(/tokens: built\.promptTokens/)
})
+ it('reports the tool catalog too, or the meter reads low by all of it', () => {
+ // The catalog is its own field on the wire, so the message estimate above
+ // cannot see it. It is picked after the build, which is why it arrives as
+ // a second call instead of riding in the report.
+ expect(source).toMatch(
+ /reportTools\(convId, estimateTokens\(JSON\.stringify\(tools\)\)\)/,
+ )
+ })
+
it('leaves a decay row in the tool audit so support can see it', () => {
expect(source).toMatch(/toolName: 'context_decay'/)
expect(source).toMatch(/savedChars: built\.savedChars/)
@@ -106,3 +115,20 @@ describe('the builder runs before the model call, every step', () => {
expect(buildAt).toBeLessThan(nativeAt)
})
})
+
+describe('the prompt-transport path does not count its catalog twice', () => {
+ it('useCodex zeroes the catalog where the tools become a message', () => {
+ // buildHermesToolPrompt writes the catalog INTO messages[0], on the working
+ // array as well, so from the next step on the message estimate carries it.
+ const promptAt = codex.indexOf('const hermesSystem = buildHermesToolPrompt(')
+ const zeroAt = codex.indexOf('reportTools(convId, 0)')
+ expect(promptAt).toBeGreaterThan(-1)
+ expect(zeroAt).toBeGreaterThan(promptAt)
+ })
+
+ it('useAgentChat builds its hermes prompt into the system message up front', () => {
+ // Same reason, different shape: there it is already in the first system
+ // message, so that loop never reports a catalog at all.
+ expect(agent).toMatch(/buildHermesToolPrompt\(hermesToolDefs\)/)
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 815838bf..f4185cc3 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -883,6 +883,12 @@ export function useAgentChat() {
type: 'function' as const,
function: { name: t.name, description: t.description, parameters: t.inputSchema },
}))
+ // Same reason as the coding loop: the catalog rides as its own field
+ // on the wire, so the message estimate the builder reported never saw
+ // it and the meter read low by the whole catalog.
+ if (convId) {
+ useSendSizeStore.getState().reportTools(convId, estimateTokens(JSON.stringify(tools)))
+ }
let turn!: { content: string; toolCalls: ToolCall[]; thinking?: string; promptEvalCount?: number; evalCount?: number }
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 3fde7faf..373f760e 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -1149,6 +1149,13 @@ export function useCodex() {
type: 'function' as const,
function: { name: t.name, description: t.description, parameters: t.inputSchema },
}))
+ // The catalog is part of what this step weighs and part of what the
+ // provider bills for it, and it is chosen here, after the request was
+ // built. Without this the meter showed the messages alone: 732 tokens
+ // on the first coding step against 2.400 on the wire.
+ if (convId) {
+ useSendSizeStore.getState().reportTools(convId, estimateTokens(JSON.stringify(tools)))
+ }
void diagLog('iter-start', {
iter: i,
activeModel, modelToUse, strategy, providerId,
@@ -1355,6 +1362,10 @@ export function useCodex() {
},
)
const hermesSystem = buildHermesToolPrompt(hermesTools) + `\n\n${systemPrompt}`
+ // Prompt transport: the catalog IS a message here, so the message
+ // estimate of the next step already carries it. Counting it a second
+ // time as a catalog would be this fix undoing itself.
+ if (convId) useSendSizeStore.getState().reportTools(convId, 0)
// Both arrays: the working one so the NEXT step's budget still
// counts the hermes tool prompt, the send one because that is what
// actually goes out.
diff --git a/src/lib/__tests__/send-window.test.ts b/src/lib/__tests__/send-window.test.ts
index eb0f8e80..b99d7780 100644
--- a/src/lib/__tests__/send-window.test.ts
+++ b/src/lib/__tests__/send-window.test.ts
@@ -8,7 +8,7 @@
* budget itself, and the denominator the user sees.
*/
-import { describe, it, expect } from 'vitest'
+import { describe, it, expect, beforeEach } from 'vitest'
import { readFileSync } from 'fs'
import { resolve } from 'path'
import {
@@ -18,6 +18,7 @@ import {
} from '../send-window'
import { computeContextFill } from '../token-usage'
import { DEFAULT_SETTINGS } from '../constants'
+import { useSendSizeStore } from '../../stores/sendSizeStore'
describe('A2: the paid-provider send cap', () => {
it('gives a 262k cloud model a 64k budget, not 209k', () => {
@@ -137,3 +138,60 @@ describe('A2: the counter divides by the send window', () => {
expect(src).toMatch(/older than the newest step go out shortened/)
})
})
+
+describe('A2 meter honesty: the tool catalog is part of the request', () => {
+ const step = {
+ tokens: 732,
+ window: 64000,
+ atMessageCount: 2,
+ trimmedResults: 0,
+ savedChars: 0,
+ }
+
+ beforeEach(() => {
+ useSendSizeStore.setState({ byConv: {} })
+ })
+
+ it('the builder reports the messages, the router reports the catalog', () => {
+ const store = useSendSizeStore.getState()
+ store.report('c1', step)
+ expect(useSendSizeStore.getState().get('c1')!.toolsTokens).toBe(0)
+ store.reportTools('c1', 1856)
+ const entry = useSendSizeStore.getState().get('c1')!
+ expect(entry.tokens).toBe(732)
+ expect(entry.toolsTokens).toBe(1856)
+ })
+
+ it('the next step keeps the catalog while its own router is still running', () => {
+ const store = useSendSizeStore.getState()
+ store.report('c1', step)
+ store.reportTools('c1', 1856)
+ store.report('c1', { ...step, tokens: 9000, atMessageCount: 6 })
+ // A reset to zero here would dip the meter by the whole catalog once per
+ // step, for as long as the embedding router takes.
+ expect(useSendSizeStore.getState().get('c1')!.toolsTokens).toBe(1856)
+ })
+
+ it('a catalog for a conversation that never built anything is dropped', () => {
+ useSendSizeStore.getState().reportTools('ghost', 1856)
+ expect(useSendSizeStore.getState().get('ghost')).toBeUndefined()
+ })
+
+ it('the counter adds the catalog to its numerator', () => {
+ const src = readFileSync(
+ resolve(__dirname, '..', '..', 'components', 'chat', 'TokenCounter.tsx'),
+ 'utf8',
+ )
+ expect(src).toMatch(/tokens: sent\.tokens \+ sent\.toolsTokens/)
+ })
+
+ it('the numerator really moves by the catalog, it is not a cosmetic field', () => {
+ const msgs = [
+ { role: 'user', content: 'refactor the parser' },
+ { role: 'assistant', content: '' },
+ ]
+ const withoutCatalog = computeContextFill(msgs, { tokens: 732, atMessageCount: 2 })
+ const withCatalog = computeContextFill(msgs, { tokens: 732 + 1856, atMessageCount: 2 })
+ expect(withCatalog.used - withoutCatalog.used).toBe(1856)
+ })
+})
diff --git a/src/stores/sendSizeStore.ts b/src/stores/sendSizeStore.ts
index 85653611..8cf9b35b 100644
--- a/src/stores/sendSizeStore.ts
+++ b/src/stores/sendSizeStore.ts
@@ -15,8 +15,19 @@ import { create } from 'zustand'
* worth carrying across a restart.
*/
export interface SendSizeReport {
- /** Estimated tokens of the request as it went out. */
+ /** Estimated tokens of the MESSAGES of the request as they went out. */
tokens: number
+ /**
+ * Estimated tokens of the serialized tool catalog that rode with them.
+ *
+ * The catalog is not a message, it is its own field on the wire, so the
+ * message estimate never saw it and the meter read about 1.700 tokens low on
+ * every coding step (the honest Ollama estimate and the model's own reported
+ * usage both include it, and the built anchor was overwriting both with the
+ * incomplete number). Zero on the prompt-transport path, where the catalog
+ * lives inside the system message and the message estimate already has it.
+ */
+ toolsTokens: number
/** The effective send window it was built against. */
window: number
/** Messages in the conversation when the request was built. */
@@ -27,17 +38,42 @@ export interface SendSizeReport {
savedChars: number
}
+/**
+ * What the builder can report on its own. The catalog is chosen further down
+ * the step, so it arrives separately through reportTools.
+ */
+export type BuiltSizeReport = Omit<SendSizeReport, 'toolsTokens'>
+
interface SendSizeState {
byConv: Record<string, SendSizeReport>
- report: (convId: string, size: SendSizeReport) => void
+ report: (convId: string, size: BuiltSizeReport) => void
+ /** The catalog this step is sending, once the router has picked it. */
+ reportTools: (convId: string, toolsTokens: number) => void
get: (convId: string) => SendSizeReport | undefined
clear: (convId: string) => void
}
export const useSendSizeStore = create<SendSizeState>((set, get) => ({
byConv: {},
+ // The catalog of the step before carries over instead of being reset to zero
+ // here. The router runs between the two calls and may await an embedding, so
+ // resetting would make the meter dip by the whole catalog for as long as that
+ // takes, once per step.
report: (convId, size) =>
- set((state) => ({ byConv: { ...state.byConv, [convId]: size } })),
+ set((state) => ({
+ byConv: {
+ ...state.byConv,
+ [convId]: { toolsTokens: state.byConv[convId]?.toolsTokens ?? 0, ...size },
+ },
+ })),
+ reportTools: (convId, toolsTokens) =>
+ set((state) => {
+ const prior = state.byConv[convId]
+ // Nothing to attach it to: the build threw and the meter is back on the
+ // model's own usage, which counts the catalog itself.
+ if (!prior) return state
+ return { byConv: { ...state.byConv, [convId]: { ...prior, toolsTokens } } }
+ }),
get: (convId) => get().byConv[convId],
clear: (convId) =>
set((state) => {