Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📊 feat: Real-Time Context Window & Token Usage Tracking (#13670)

Danny Aviladb7011d5678c
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js
index dfa8d2201b..03653333b4 100644
--- a/api/app/clients/BaseClient.js
+++ b/api/app/clients/BaseClient.js
@@ -700,7 +700,6 @@ class BaseClient {
user,
);
this.savedMessageIds.add(responseMessage.messageId);
- delete responseMessage.tokenCount;
return responseMessage;
}
diff --git a/api/server/controllers/TokenConfigController.js b/api/server/controllers/TokenConfigController.js
new file mode 100644
index 0000000000..f139effd6b
--- /dev/null
+++ b/api/server/controllers/TokenConfigController.js
@@ -0,0 +1,27 @@
+const { logger } = require('@librechat/data-schemas');
+const { resolveTokenConfigMap } = require('@librechat/api');
+const { getModelsConfig } = require('~/server/controllers/ModelController');
+const { getValueKey, getMultiplier, getCacheMultiplier } = require('~/models');
+
+/**
+ * Returns server-resolved context windows (and pricing when
+ * `interface.contextCost` is enabled) for every configured model. Resolution
+ * lives in `@librechat/api`; this controller only supplies request-scoped deps.
+ * @param {ServerRequest} req
+ * @param {ServerResponse} res
+ */
+async function tokenConfigController(req, res) {
+ try {
+ const modelsConfig = await getModelsConfig(req);
+ const tokenConfigMap = await resolveTokenConfigMap(
+ { appConfig: req.config, modelsConfig, userId: req.user.id },
+ { getValueKey, getMultiplier, getCacheMultiplier },
+ );
+ res.json(tokenConfigMap);
+ } catch (error) {
+ logger.error('[tokenConfigController]', error);
+ res.status(500).json({ error: 'Failed to resolve token config' });
+ }
+}
+
+module.exports = tokenConfigController;
diff --git a/api/server/controllers/agents/__tests__/usageEvents.integration.spec.js b/api/server/controllers/agents/__tests__/usageEvents.integration.spec.js
new file mode 100644
index 0000000000..0668d0b6c1
--- /dev/null
+++ b/api/server/controllers/agents/__tests__/usageEvents.integration.spec.js
@@ -0,0 +1,253 @@
+const { z } = require('zod');
+const { tool } = require('@langchain/core/tools');
+const { ChatGenerationChunk } = require('@langchain/core/outputs');
+const { HumanMessage, AIMessageChunk } = require('@langchain/core/messages');
+const {
+ Run,
+ Providers,
+ GraphEvents,
+ FakeChatModel,
+ createContentAggregator,
+} = require('@librechat/agents');
+const { GenerationJobManager } = require('@librechat/api');
+const { getDefaultHandlers } = require('~/server/controllers/agents/callbacks');
+
+jest.mock('nanoid', () => ({
+ nanoid: jest.fn(() => 'mock-nanoid'),
+}));
+
+jest.mock('~/server/services/Files/Citations', () => ({
+ processFileCitations: jest.fn(),
+}));
+
+jest.mock('~/server/services/Files/Code/process', () => ({
+ processCodeOutput: jest.fn(),
+ runPreviewFinalize: jest.fn(),
+}));
+
+jest.mock('~/server/services/Files/process', () => ({
+ saveBase64Image: jest.fn(),
+}));
+
+/** Real pipeline guard: published lib versions without the event skip its assertions */
+const hasContextUsageEvent = GraphEvents.ON_CONTEXT_USAGE != null;
+
+/**
+ * FakeChatModel that attaches provider-style usage_metadata on a final
+ * empty chunk (the OpenAI streaming pattern), so CHAT_MODEL_END carries
+ * aggregated usage through the real @librechat/agents pipeline.
+ */
+class UsageFakeModel extends FakeChatModel {
+ constructor(options, usagePerCall) {
+ super(options);
+ this.usagePerCall = usagePerCall;
+ this.usageCallIndex = 0;
+ }
+
+ async *_streamResponseChunks(messages, options, runManager) {
+ yield* super._streamResponseChunks(messages, options, runManager);
+ const index = Math.min(this.usageCallIndex, this.usagePerCall.length - 1);
+ this.usageCallIndex += 1;
+ yield new ChatGenerationChunk({
+ text: '',
+ message: new AIMessageChunk({ content: '', usage_metadata: this.usagePerCall[index] }),
+ });
+ }
+}
+
+const addTool = tool(async ({ a, b }) => String(a + b), {
+ name: 'add',
+ description: 'Add two numbers',
+ schema: z.object({ a: z.number(), b: z.number() }),
+});
+
+const charCounter = (msg) => {
+ const content = msg.content;
+ if (typeof content === 'string') {
+ return content.length + 3;
+ }
+ if (Array.isArray(content)) {
+ let length = 3;
+ for (const part of content) {
+ if (typeof part === 'string') {
+ length += part.length;
+ } else if (typeof part?.text === 'string') {
+ length += part.text.length;
+ }
+ }
+ return length;
+ }
+ return 3;
+};
+
+function createMockRes() {
+ const events = [];
+ return {
+ events,
+ headersSent: true,
+ writableEnded: false,
+ write(payload) {
+ for (const line of String(payload).split('\n')) {
+ if (line.startsWith('data: ')) {
+ events.push(JSON.parse(line.slice(6)));
+ }
+ }
+ return true;
+ },
+ };
+}
+
+const FIRST_CALL_USAGE = {
+ input_tokens: 100,
+ output_tokens: 20,
+ total_tokens: 120,
+};
+
+const SECOND_CALL_USAGE = {
+ input_tokens: 150,
+ output_tokens: 10,
+ total_tokens: 160,
+ input_token_details: { cache_creation: 30, cache_read: 50 },
+};
+
+const MAX_CONTEXT_TOKENS = 8000;
+
+async function runToolLoop({ res, streamId = null, collectedUsage }) {
+ const { contentParts, aggregateContent } = createContentAggregator();
+ const handlers = getDefaultHandlers({
+ res,
+ aggregateContent,
+ toolEndCallback: () => {},
+ collectedUsage,
+ streamId,
+ });
+
+ const run = await Run.create({
+ runId: 'usage-e2e-response',
+ graphConfig: {
+ type: 'standard',
+ llmConfig: {
+ provider: Providers.OPENAI,
+ model: 'gpt-4o-mini',
+ streaming: true,
+ streamUsage: false,
+ },
+ instructions: 'You are a helpful assistant.',
+ maxContextTokens: MAX_CONTEXT_TOKENS,
+ tools: [addTool],
+ },
+ returnContent: true,
+ customHandlers: handlers,
+ tokenCounter: charCounter,
+ indexTokenCountMap: {},
+ });
+
+ run.Graph.overrideModel = new UsageFakeModel(
+ {
+ responses: ['Let me calculate that.', 'The answer is 4.'],
+ toolCalls: [{ name: 'add', args: { a: 2, b: 2 }, id: 'tc_1', type: 'tool_call' }],
+ },
+ [FIRST_CALL_USAGE, SECOND_CALL_USAGE],
+ );
+
+ await run.processStream(
+ { messages: [new HumanMessage('What is 2+2?')] },
+ {
+ configurable: { thread_id: 'usage-e2e-thread', user_id: 'user-1' },
+ streamMode: 'values',
+ version: 'v2',
+ },
+ );
+
+ return { run, contentParts };
+}
+
+describe('usage events through the real agents pipeline', () => {
+ jest.setTimeout(30000);
+
+ afterAll(async () => {
+ await GenerationJobManager.destroy();
+ });
+
+ test('emits on_token_usage per model call with collectedUsage parity', async () => {
+ const res = createMockRes();
+ const collectedUsage = [];
+ const { contentParts } = await runToolLoop({ res, collectedUsage });
+
+ const usageEvents = res.events.filter((e) => e.event === 'on_token_usage');
+ expect(usageEvents).toHaveLength(2);
+
+ expect(usageEvents[0].data).toMatchObject(FIRST_CALL_USAGE);
+ expect(usageEvents[1].data).toMatchObject(SECOND_CALL_USAGE);
+ expect(usageEvents[0].data.provider).toBe(Providers.OPENAI);
+ expect(usageEvents[0].data.model).toBeTruthy();
+ expect(usageEvents[0].data.usage_type).toBeUndefined();
+
+ expect(collectedUsage).toHaveLength(2);
+ expect(collectedUsage[0]).toMatchObject(FIRST_CALL_USAGE);
+ expect(collectedUsage[1]).toMatchObject(SECOND_CALL_USAGE);
+
+ const text = contentParts
+ .filter((part) => part?.type === 'text')
+ .map((part) => part.text)
+ .join('');
+ expect(text).toContain('The answer is 4.');
+ });
+
+ test('emits a context snapshot before each model call', async () => {
+ if (!hasContextUsageEvent) {
+ console.warn('Skipping: installed @librechat/agents predates ON_CONTEXT_USAGE');
+ return;
+ }
+ const res = createMockRes();
+ const { run } = await runToolLoop({ res, collectedUsage: [] });
+ expect(run).toBeDefined();
+
+ const contextEvents = res.events.filter((e) => e.event === 'on_context_usage');
+ expect(contextEvents).toHaveLength(2);
+
+ for (const event of contextEvents) {
+ const { breakdown, contextBudget, remainingContextTokens, effectiveInstructionTokens } =
+ event.data;
+ expect(breakdown.maxContextTokens).toBe(MAX_CONTEXT_TOKENS);
+ expect(contextBudget).toBeGreaterThan(0);
+ expect(contextBudget).toBeLessThanOrEqual(MAX_CONTEXT_TOKENS);
+ expect(effectiveInstructionTokens).toBeGreaterThan(0);
+ expect(remainingContextTokens).toBeGreaterThan(0);
+ expect(remainingContextTokens).toBeLessThan(contextBudget);
+ expect(breakdown.toolTokenCounts.add).toBeGreaterThan(0);
+ }
+
+ /** Tool loop grows the context between calls */
+ expect(contextEvents[1].data.prePruneContextTokens).toBeGreaterThan(
+ contextEvents[0].data.prePruneContextTokens,
+ );
+
+ /** Snapshot precedes the call's usage event */
+ const firstContextIndex = res.events.findIndex((e) => e.event === 'on_context_usage');
+ const firstUsageIndex = res.events.findIndex((e) => e.event === 'on_token_usage');
+ expect(firstContextIndex).toBeGreaterThanOrEqual(0);
+ expect(firstContextIndex).toBeLessThan(firstUsageIndex);
+ });
+
+ test('persists usage and context snapshot for resume via GenerationJobManager', async () => {
+ const streamId = `usage-e2e-stream-${Date.now()}`;
+ await GenerationJobManager.createJob(streamId, 'user-1', 'convo-1');
+
+ const res = createMockRes();
+ await runToolLoop({ res, streamId, collectedUsage: [] });
+
+ const resumeState = await GenerationJobManager.getResumeState(streamId);
+ expect(resumeState).not.toBeNull();
+
+ expect(resumeState.collectedUsage).toHaveLength(2);
+ expect(resumeState.collectedUsage[0]).toMatchObject(FIRST_CALL_USAGE);
+ expect(resumeState.collectedUsage[1]).toMatchObject(SECOND_CALL_USAGE);
+
+ if (hasContextUsageEvent) {
+ expect(resumeState.contextUsage.breakdown.maxContextTokens).toBe(MAX_CONTEXT_TOKENS);
+ /** Latest-wins: the persisted snapshot is the second call's */
+ expect(resumeState.contextUsage.prePruneContextTokens).toBeGreaterThan(0);
+ }
+ });
+});
diff --git a/api/server/controllers/agents/__tests__/usageEvents.live.spec.js b/api/server/controllers/agents/__tests__/usageEvents.live.spec.js
new file mode 100644
index 0000000000..ff02c9325f
--- /dev/null
+++ b/api/server/controllers/agents/__tests__/usageEvents.live.spec.js
@@ -0,0 +1,161 @@
+/**
+ * Live host-layer verification: real Anthropic run through the actual
+ * getDefaultHandlers pipeline, asserting the SSE usage/context events the
+ * client consumes and their resume persistence.
+ *
+ * Run with:
+ * RUN_USAGE_LIVE_TESTS=1 ANTHROPIC_API_KEY=... npx jest usageEvents.live --runInBand
+ */
+const { HumanMessage } = require('@langchain/core/messages');
+const { Run, Providers, GraphEvents } = require('@librechat/agents');
+const { GenerationJobManager } = require('@librechat/api');
+const { getDefaultHandlers } = require('~/server/controllers/agents/callbacks');
+
+jest.mock('nanoid', () => ({
+ nanoid: jest.fn(() => 'mock-nanoid'),
+}));
+
+jest.mock('~/server/services/Files/Citations', () => ({
+ processFileCitations: jest.fn(),
+}));
+
+jest.mock('~/server/services/Files/Code/process', () => ({
+ processCodeOutput: jest.fn(),
+ runPreviewFinalize: jest.fn(),
+}));
+
+jest.mock('~/server/services/Files/process', () => ({
+ saveBase64Image: jest.fn(),
+}));
+
+const shouldRunLive =
+ process.env.RUN_USAGE_LIVE_TESTS === '1' &&
+ process.env.ANTHROPIC_API_KEY != null &&
+ process.env.ANTHROPIC_API_KEY !== '';
+
+const describeIfLive = shouldRunLive ? describe : describe.skip;
+const modelName = process.env.ANTHROPIC_USAGE_LIVE_MODEL ?? 'claude-haiku-4-5';
+const hasContextUsageEvent = GraphEvents.ON_CONTEXT_USAGE != null;
+
+const charCounter = (msg) => {
+ const content = msg.content;
+ if (typeof content === 'string') {
+ return Math.ceil(content.length / 4) + 3;
+ }
+ if (Array.isArray(content)) {
+ let length = 3;
+ for (const part of content) {
+ if (typeof part === 'string') {
+ length += Math.ceil(part.length / 4);
+ } else if (typeof part?.text === 'string') {
+ length += Math.ceil(part.text.length / 4);
+ }
+ }
+ return length;
+ }
+ return 3;
+};
+
+function createMockRes() {
+ const events = [];
+ return {
+ events,
+ headersSent: true,
+ writableEnded: false,
+ write(payload) {
+ for (const line of String(payload).split('\n')) {
+ if (line.startsWith('data: ')) {
+ events.push(JSON.parse(line.slice(6)));
+ }
+ }
+ return true;
+ },
+ };
+}
+
+describeIfLive('live usage events through the host pipeline', () => {
+ jest.setTimeout(120000);
+
+ afterAll(async () => {
+ await GenerationJobManager.destroy();
+ });
+
+ test('streams real provider usage and persists it for resume', async () => {
+ const streamId = `usage-live-${Date.now()}`;
+ await GenerationJobManager.createJob(streamId, 'user-live', 'convo-live');
+
+ /** streamId mode routes events through the job emitter — capture them
+ * as a subscribed resumable client would, not via res.write */
+ const res = createMockRes();
+ await GenerationJobManager.subscribe(streamId, (event) => {
+ res.events.push(event);
+ });
+ const collectedUsage = [];
+ const handlers = getDefaultHandlers({
+ res,
+ aggregateContent: () => {},
+ toolEndCallback: () => {},
+ collectedUsage,
+ streamId,
+ });
+
+ const run = await Run.create({
+ runId: 'usage-live-response',
+ graphConfig: {
+ type: 'standard',
+ llmConfig: {
+ provider: Providers.ANTHROPIC,
+ model: modelName,
+ apiKey: process.env.ANTHROPIC_API_KEY,
+ temperature: 0,
+ maxTokens: 64,
+ streaming: true,
+ streamUsage: true,
+ },
+ instructions: 'You are concise. Reply with one short sentence.',
+ maxContextTokens: 8000,
+ },
+ returnContent: true,
+ customHandlers: handlers,
+ tokenCounter: charCounter,
+ indexTokenCountMap: {},
+ });
+
+ await run.processStream(
+ { messages: [new HumanMessage('Say hello in five words or fewer.')] },
+ {
+ configurable: { thread_id: 'usage-live-thread', user_id: 'user-live' },
+ streamMode: 'values',
+ version: 'v2',
+ },
+ );
+
+ const usageEvents = res.events.filter((e) => e.event === 'on_token_usage');
+ expect(usageEvents).toHaveLength(1);
+ const usage = usageEvents[0].data;
+ expect(usage.input_tokens).toBeGreaterThan(0);
+ expect(usage.output_tokens).toBeGreaterThan(0);
+ expect(usage.provider).toBe(Providers.ANTHROPIC);
+ expect(usage.model).toBe(modelName);
+ expect(collectedUsage).toHaveLength(1);
+ expect(usage.input_tokens).toBe(collectedUsage[0].input_tokens);
+
+ if (hasContextUsageEvent) {
+ const contextEvents = res.events.filter((e) => e.event === 'on_context_usage');
+ expect(contextEvents).toHaveLength(1);
+ const snapshot = contextEvents[0].data;
+ expect(snapshot.breakdown.maxContextTokens).toBe(8000);
+ const estimatedUsed = snapshot.contextBudget - snapshot.remainingContextTokens;
+ expect(estimatedUsed).toBeGreaterThan(0);
+ expect(estimatedUsed / usage.input_tokens).toBeGreaterThan(0.2);
+ expect(estimatedUsed / usage.input_tokens).toBeLessThan(5);
+ }
+
+ const resumeState = await GenerationJobManager.getResumeState(streamId);
+ expect(resumeState.collectedUsage).toHaveLength(1);
+ expect(resumeState.collectedUsage[0].input_tokens).toBe(usage.input_tokens);
+ if (hasContextUsageEvent) {
+ expect(resumeState.contextUsage.breakdown.maxContextTokens).toBe(8000);
+ }
+ });
+});
diff --git a/api/server/controllers/agents/callbacks.js b/api/server/controllers/agents/callbacks.js
index 0a8f8854f7..0b543f6528 100644
--- a/api/server/controllers/agents/callbacks.js
+++ b/api/server/controllers/agents/callbacks.js
@@ -1,6 +1,12 @@
const { nanoid } = require('nanoid');
const { logger } = require('@librechat/data-schemas');
-const { Tools, StepTypes, FileContext, ErrorTypes } = require('librechat-data-provider');
+const {
+ Tools,
+ StepTypes,
+ FileContext,
+ ErrorTypes,
+ UsageEvents,
+} = require('librechat-data-provider');
const {
GraphEvents,
GraphNodeKeys,
@@ -9,6 +15,7 @@ const {
} = require('@librechat/agents');
const {
sendEvent,
+ computeUsageCostUSD,
GenerationJobManager,
writeAttachmentEvent,
createToolExecuteHandler,
@@ -41,13 +48,16 @@ class ModelEndHandler {
* Optional; when `null`, the handler is a no-op for signatures. Non-Vertex
* providers don't emit `additional_kwargs.signatures`, so capture is also
* a no-op for them even when the map is provided.
+ * @param {(data: Record<string, unknown>) => Promise<void> | void} [emitUsage] Optional
+ * callback to stream per-call token usage to the client.
*/
- constructor(collectedUsage, collectedThoughtSignatures = null) {
+ constructor(collectedUsage, collectedThoughtSignatures = null, emitUsage = null) {
if (!Array.isArray(collectedUsage)) {
throw new Error('collectedUsage must be an array');
}
this.collectedUsage = collectedUsage;
this.collectedThoughtSignatures = collectedThoughtSignatures;
+ this.emitUsage = emitUsage;
}
finalize(errorMessage) {
@@ -100,10 +110,53 @@ class ModelEndHandler {
usage.provider = agentContext.provider;
}
- const taggedUsage = markSummarizationUsage(usage, metadata);
+ let taggedUsage = markSummarizationUsage(usage, metadata);
+ /** Hidden intermediate sequential-agent calls are billed but never shown.
+ * Tag them non-primary on the COLLECTED usage too (not just the emit) so
+ * recordCollectedUsage excludes their output from the parent's tokenCount
+ * and the client folds them into cost/totals only — not the live gauge. */
+ if (
+ taggedUsage.usage_type == null &&
+ !checkIfLastAgent(metadata?.last_agent_id, metadata?.langgraph_node) &&
+ metadata?.hide_sequential_outputs === true
+ ) {
+ taggedUsage = { ...taggedUsage, usage_type: 'sequential' };
+ }
this.collectedUsage.push(taggedUsage);
+ if (this.emitUsage) {
+ /** Normalize Anthropic/Bedrock-style top-level cache fields into details */
+ const cache_creation =
+ taggedUsage.input_token_details?.cache_creation ??
+ taggedUsage.cache_creation_input_tokens;
+ const cache_read =
+ taggedUsage.input_token_details?.cache_read ?? taggedUsage.cache_read_input_tokens;
+ try {
+ await this.emitUsage({
+ input_tokens: taggedUsage.input_tokens,
+ output_tokens: taggedUsage.output_tokens,
+ total_tokens: taggedUsage.total_tokens,
+ input_token_details:
+ cache_creation != null || cache_read != null
+ ? { cache_creation, cache_read }
+ : undefined,
+ model: taggedUsage.model,
+ provider: taggedUsage.provider,
+ usage_type: taggedUsage.usage_type,
+ runId: metadata?.run_id,
+ /** Per-run sequence so identical payloads from distinct calls
+ * stay distinguishable during resume dedupe */
+ seq: this.collectedUsage.length,
+ });
+ } catch (err) {
+ /** Best-effort telemetry: a failed emit (closed SSE, Redis publish
+ * error) must not abort the handler before the thought-signature
+ * capture below, or resumed tool-call requests lose that metadata */
+ logger.warn('[ModelEndHandler] Failed to emit token usage', err);
+ }
+ }
+
/**
* `additional_kwargs.signatures` is a flat array indexed by response
* part position (text + functionCall interleaved). `tool_calls` is
@@ -220,6 +273,7 @@ function feedSubagentAggregator(aggregator, event) {
* @param {Array<UsageMetadata>} options.collectedUsage - The list of collected usage metadata.
* @param {string | null} [options.streamId] - The stream ID for resumable mode, or null for standard mode.
* @param {ToolExecuteOptions} [options.toolExecuteOptions] - Options for event-driven tool execution.
+ * @param {UsageCostDeps} [options.usageCost] - Pricing context for authoritative per-event cost.
* @returns {Record<string, t.EventHandler>} The default handlers.
* @throws {Error} If the request is not found.
*/
@@ -233,14 +287,40 @@ function getDefaultHandlers({
toolExecuteOptions = null,
summarizationOptions = null,
subagentAggregatorsByToolCallId = null,
+ usageCost = null,
}) {
if (!res || !aggregateContent) {
throw new Error(
`[getDefaultHandlers] Missing required options: res: ${!res}, aggregateContent: ${!aggregateContent}`,
);
}
+ /**
+ * Emit a token-usage event, attaching the authoritative per-event USD cost
+ * when cost display is enabled. The backend is the single source of truth
+ * for pricing (premium tiers, cache rates) — the client sums these instead
+ * of re-deriving from base rates.
+ * @param {Record<string, unknown>} data
+ */
+ const emitTokenUsage = (data) => {
+ let payload = data;
+ if (usageCost?.enabled === true && usageCost.pricing) {
+ try {
+ payload = {
+ ...data,
+ cost: computeUsageCostUSD(data, usageCost.pricing, usageCost.endpointTokenConfig),
+ };
+ } catch (err) {
+ logger.warn('[getDefaultHandlers] Failed to compute usage cost', err);
+ }
+ }
+ return emitEvent(res, streamId, { event: UsageEvents.ON_TOKEN_USAGE, data: payload });
+ };
const handlers = {
- [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(collectedUsage, collectedThoughtSignatures),
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(
+ collectedUsage,
+ collectedThoughtSignatures,
+ emitTokenUsage,
+ ),
[GraphEvents.TOOL_END]: new ToolEndHandler(toolEndCallback, logger),
[GraphEvents.ON_RUN_STEP]: {
/**
@@ -425,6 +505,27 @@ function getDefaultHandlers({
handlers[GraphEvents.ON_AGENT_LOG] = { handle: agentLogHandler };
+ /** Guarded: no-op when the installed @librechat/agents predates the event */
+ if (GraphEvents.ON_CONTEXT_USAGE) {
+ handlers[GraphEvents.ON_CONTEXT_USAGE] = {
+ /**
+ * Forward per-model-call context usage snapshots to the client,
+ * honoring the same sequential-agent visibility gate as deltas.
+ * @param {string} event - The event name.
+ * @param {StreamEventData} data - The event data.
+ * @param {GraphRunnableConfig['configurable']} [metadata] The runnable metadata.
+ */
+ handle: async (event, data, metadata) => {
+ if (
+ checkIfLastAgent(metadata?.last_agent_id, metadata?.langgraph_node) ||
+ !metadata?.hide_sequential_outputs
+ ) {
+ await emitEvent(res, streamId, { event, data });
+ }
+ },
+ };
+ }
+
return handlers;
}
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index 10c2efefab..4ba5fafde3 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -21,6 +21,8 @@ const {
applyContextToAgent,
isMemoryAgentEnabled,
recordCollectedUsage,
+ sendEvent,
+ computeUsageCostUSD,
createSubagentUsageSink,
isDeepSeekReasoningProvider,
GenerationJobManager,
@@ -52,6 +54,7 @@ const {
} = require('@librechat/agents');
const {
Constants,
+ UsageEvents,
Permissions,
VisionModes,
ContentTypes,
@@ -128,6 +131,11 @@ class AgentClient extends BaseClient {
* harvests `contentParts` onto the matching `subagent` tool_call
* so the child's full activity survives a page refresh. */
this.subagentAggregatorsByToolCallId = subagentAggregatorsByToolCallId ?? new Map();
+ /** In-flight `on_token_usage` emits from subagent child runs. The sink
+ * fires the emitter without awaiting, so chatCompletion's finally flushes
+ * these before returning — otherwise job cleanup can race the persist.
+ * @type {Promise<void>[]} */
+ this.pendingSubagentEmits = [];
/** @type {AgentClientOptions} */
this.options = Object.assign({ endpoint: options.endpoint }, clientOptions);
/** @type {string} */
@@ -875,6 +883,77 @@ class AgentClient extends BaseClient {
return this.usage;
}
+ /**
+ * Builds the subagent usage emitter for {@link createSubagentUsageSink}.
+ * Streams each billed child-run usage to the client as an `on_token_usage`
+ * event tagged `subagent` (folds into session cost/totals, not the live
+ * gauge), with the authoritative cost when `interface.contextCost` is on.
+ * Returns undefined when there's no stream to write to.
+ * @param {AppConfig} [appConfig]
+ * @returns {((usage: UsageMetadata) => void) | undefined}
+ */
+ buildSubagentUsageEmitter(appConfig) {
+ const res = this.options.res;
+ const streamId = this.options.req?._resumableStreamId || null;
+ if (!res && !streamId) {
+ return undefined;
+ }
+ const includeCost = appConfig?.interfaceConfig?.contextCost === true;
+ const endpointTokenConfig = this.options.endpointTokenConfig;
+ return (usage) => {
+ const data = {
+ input_tokens: usage.input_tokens,
+ output_tokens: usage.output_tokens,
+ total_tokens: usage.total_tokens,
+ input_token_details: this.subagentCacheDetails(usage),
+ model: usage.model,
+ provider: usage.provider,
+ usage_type: 'subagent',
+ runId: this.responseMessageId,
+ /** Unique per collected entry (post-push length) for resume dedupe */
+ seq: this.collectedUsage.length,
+ cost: includeCost
+ ? computeUsageCostUSD(
+ usage,
+ { getMultiplier: db.getMultiplier, getCacheMultiplier: db.getCacheMultiplier },
+ endpointTokenConfig,
+ )
+ : undefined,
+ };
+ /** The sink fires this without awaiting, so retain the promise and flush
+ * it in chatCompletion's finally — emitChunk persists (HSET) before
+ * publishing, and job cleanup must not race that persist or resumed
+ * clients miss billed subagent usage. */
+ const emit = (async () => {
+ try {
+ if (streamId) {
+ await GenerationJobManager.emitChunk(streamId, {
+ event: UsageEvents.ON_TOKEN_USAGE,
+ data,
+ });
+ } else {
+ sendEvent(res, { event: UsageEvents.ON_TOKEN_USAGE, data });
+ }
+ } catch (err) {
+ logger.warn('[AgentClient] Failed to emit subagent usage', err);
+ }
+ })();
+ this.pendingSubagentEmits.push(emit);
+ return emit;
+ };
+ }
+
+ /** Normalizes a subagent usage event's cache token details for emission. */
+ subagentCacheDetails(usage) {
+ const cache_creation =
+ usage.input_token_details?.cache_creation ?? usage.cache_creation_input_tokens;
+ const cache_read = usage.input_token_details?.cache_read ?? usage.cache_read_input_tokens;
+ if (cache_creation == null && cache_read == null) {
+ return undefined;
+ }
+ return { cache_creation, cache_read };
+ }
+
/**
* @param {TMessage} responseMessage
* @returns {number}
@@ -1141,8 +1220,14 @@ class AgentClient extends BaseClient {
/** Bills subagent child-run model calls — child graphs execute
* outside the streamEvents loop, so ModelEndHandler never sees
* them. Entries land in collectedUsage tagged
- * `usage_type: 'subagent'` and are spent by recordCollectedUsage. */
- subagentUsageSink: createSubagentUsageSink(this.collectedUsage),
+ * `usage_type: 'subagent'` and are spent by recordCollectedUsage.
+ * The sink also streams each as an `on_token_usage` event so the
+ * gauge's session cost/totals include billed subagent usage (the
+ * `subagent` tag keeps it out of the live context meter). */
+ subagentUsageSink: createSubagentUsageSink(
+ this.collectedUsage,
+ this.buildSubagentUsageEmitter(appConfig),
+ ),
});
if (!run) {
@@ -1259,6 +1344,14 @@ class AgentClient extends BaseClient {
this.finalizeSubagentContent();
+ /** Flush subagent usage emits the sink fired without awaiting, so their
+ * persist/publish completes before we return and the job is cleaned up
+ * (resumed clients read this persisted usage). */
+ if (this.pendingSubagentEmits.length > 0) {
+ await Promise.allSettled(this.pendingSubagentEmits);
+ this.pendingSubagentEmits = [];
+ }
+
try {
const attachments = await this.awaitMemoryWithTimeout(memoryPromise);
if (attachments && attachments.length > 0) {
diff --git a/api/server/routes/endpoints.js b/api/server/routes/endpoints.js
index e7ff1c7000..8b1fceccc4 100644
--- a/api/server/routes/endpoints.js
+++ b/api/server/routes/endpoints.js
@@ -1,9 +1,12 @@
const express = require('express');
const requireJwtAuth = require('~/server/middleware/requireJwtAuth');
+const configMiddleware = require('~/server/middleware/config/app');
const endpointController = require('~/server/controllers/EndpointController');
+const tokenConfigController = require('~/server/controllers/TokenConfigController');
const router = express.Router();
/** Auth required for role/tenant-scoped endpoint config resolution. */
router.get('/', requireJwtAuth, endpointController);
+router.get('/token-config', requireJwtAuth, configMiddleware, tokenConfigController);
module.exports = router;
diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js
index eb0655d886..7330f22916 100644
--- a/api/server/services/Endpoints/agents/initialize.js
+++ b/api/server/services/Endpoints/agents/initialize.js
@@ -242,6 +242,16 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {
*/
const subagentAggregatorsByToolCallId = new Map();
+ /** Backend prices each model call authoritatively (premium tiers, cache
+ * rates) and emits the cost on on_token_usage when contextCost is on, so
+ * the gauge sums real costs instead of re-deriving from base rates.
+ * `endpointTokenConfig` is filled in once `primaryConfig` resolves below so
+ * custom-endpoint agents price with their configured rates, not defaults. */
+ const usageCost = {
+ enabled: appConfig?.interfaceConfig?.contextCost === true,
+ pricing: { getMultiplier: db.getMultiplier, getCacheMultiplier: db.getCacheMultiplier },
+ };
+
const eventHandlers = getDefaultHandlers({
res,
toolExecuteOptions,
@@ -252,6 +262,7 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {
collectedThoughtSignatures,
streamId,
subagentAggregatorsByToolCallId,
+ usageCost,
});
if (!endpointOption.agent) {
@@ -382,6 +393,11 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {
},
);
+ /** Price emitted usage with the primary agent's resolved endpoint config so
+ * custom-endpoint agents reflect configured rates (mirrors the AgentClient
+ * spending path, which reads the same config). */
+ usageCost.endpointTokenConfig = primaryConfig.endpointTokenConfig;
+
logger.debug(
`[initializeClient] Storing tool context for ${primaryConfig.id}: ${primaryConfig.toolDefinitions?.length ?? 0} tools, registry size: ${primaryConfig.toolRegistry?.size ?? '0'}`,
);
@@ -901,6 +917,9 @@ const initializeClient = async ({ req, res, signal, endpointOption }) => {
maxContextTokens: primaryConfig.maxContextTokens,
endpoint: isEphemeralAgentId(primaryConfig.id) ? primaryConfig.endpoint : EModelEndpoint.agents,
subagentAggregatorsByToolCallId,
+ /** Resolved endpoint token/pricing config so spending and cost reflect
+ * configured rates for custom-endpoint agents instead of defaults. */
+ endpointTokenConfig: primaryConfig.endpointTokenConfig,
});
if (streamId) {
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index f8c058cae0..c1efba72fc 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -5,12 +5,6 @@ import { useRecoilState, useRecoilValue } from 'recoil';
import { Constants, isAssistantsEndpoint, isAgentsEndpoint } from 'librechat-data-provider';
import type { TConversation } from 'librechat-data-provider';
import type { ExtendedFile, FileSetter, ConvoGenerator } from '~/common';
-import {
- useChatContext,
- useChatFormContext,
- useAddedChatContext,
- useAssistantsMapContext,
-} from '~/Providers';
import {
useTextarea,
useAutoSave,
@@ -21,6 +15,12 @@ import {
useSubmitMessage,
useFocusChatEffect,
} from '~/hooks';
+import {
+ useChatContext,
+ useChatFormContext,
+ useAddedChatContext,
+ useAssistantsMapContext,
+} from '~/Providers';
import PendingManualSkillsChips from './PendingManualSkillsChips';
import { cn, getModelSpec, removeFocusRings } from '~/utils';
import { useGetStartupConfig } from '~/data-provider';
@@ -28,11 +28,12 @@ import { mainTextareaId, BadgeItem } from '~/common';
import AttachFileChat from './Files/AttachFileChat';
import FileFormChat from './Files/FileFormChat';
import TextareaHeader from './TextareaHeader';
-import SkillsCommand from './SkillsCommand';
import PromptsCommand from './PromptsCommand';
+import SkillsCommand from './SkillsCommand';
import AudioRecorder from './AudioRecorder';
import CollapseChat from './CollapseChat';
import StreamAudio from './StreamAudio';
+import TokenUsage from './TokenUsage';
import StopButton from './StopButton';
import SendButton from './SendButton';
import EditBadges from './EditBadges';
@@ -379,6 +380,7 @@ const ChatForm = memo(function ChatForm({
}
/>
<div className="mx-auto flex" />
+ <TokenUsage index={index} conversation={conversation} isSubmitting={isSubmitting} />
{SpeechToText && (
<AudioRecorder
methods={methods}
@@ -445,6 +447,7 @@ function ChatFormWrapper({ index = 0, placeholder }: { index?: number; placehold
conversation?.spec,
conversation?.useResponsesApi,
conversation?.model,
+ conversation?.maxContextTokens,
hasMessages,
],
);
diff --git a/client/src/components/Chat/Input/TokenUsage/Breakdown.tsx b/client/src/components/Chat/Input/TokenUsage/Breakdown.tsx
new file mode 100644
index 0000000000..9b01a7f6b8
--- /dev/null
+++ b/client/src/components/Chat/Input/TokenUsage/Breakdown.tsx
@@ -0,0 +1,169 @@
+import type { TokenUsageView } from '~/hooks/Chat/useTokenUsage';
+import { groupToolTokens, formatTokens, formatCost } from '~/utils';
+import { useLocalize } from '~/hooks';
+
+interface RowProps {
+ label: string;
+ value: number;
+ max?: number;
+}
+
+function Row({ label, value, max }: RowProps) {
+ const percent = max != null && max > 0 ? Math.min((value / max) * 100, 100) : null;
+ return (
+ <div className="flex items-center justify-between gap-4 text-sm">
+ <span className="text-text-secondary">{label}</span>
+ <span className="font-medium text-text-primary">
+ {formatTokens(value)}
+ {percent != null && (
+ <span className="ml-1 text-xs text-text-secondary" aria-hidden="true">
+ ({Math.round(percent)}%)
+ </span>
+ )}
+ </span>
+ </div>
+ );
+}
+
+interface BreakdownProps {
+ view: TokenUsageView;
+ showCost: boolean;
+}
+
+export default function Breakdown({ view, showCost }: BreakdownProps) {
+ const localize = useLocalize();
+ const { usedTokens, maxTokens, percent, snapshot, snapshotActive, usageTotals } = view;
+
+ const breakdown = snapshotActive ? snapshot?.breakdown : undefined;
+ const instructionTokens =
+ snapshot?.effectiveInstructionTokens ?? breakdown?.instructionTokens ?? 0;
+ const systemTokens =
+ (breakdown?.systemMessageTokens ?? 0) + (breakdown?.dynamicInstructionTokens ?? 0);
+ const messageTokens = Math.max(0, usedTokens - instructionTokens);
+ const freeTokens = maxTokens != null ? Math.max(0, maxTokens - usedTokens) : null;
+
+ const groups =
+ breakdown?.toolTokenCounts != null
+ ? groupToolTokens(breakdown.toolTokenCounts, breakdown.deferredToolNames)
+ : null;
+ const toolRows =
+ groups == null
+ ? null
+ : ([
+ [localize('com_ui_context_tools_system'), groups.system],
+ [localize('com_ui_context_tools_mcp'), groups.mcp],
+ [localize('com_ui_skills'), groups.skills],
+ [localize('com_ui_context_subagents'), groups.subagents],
+ [localize('com_ui_context_tools_system_deferred'), groups.systemDeferred],
+ [localize('com_ui_context_tools_mcp_deferred'), groups.mcpDeferred],
+ ] as const);
+
+ return (
+ <div className="w-64 space-y-3" role="region" aria-label={localize('com_ui_context_usage')}>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-text-primary">
+ {localize('com_ui_context_window')}
+ </span>
+ <span className="text-xs font-medium text-text-secondary">
+ {maxTokens != null
+ ? `${formatTokens(usedTokens)} / ${formatTokens(maxTokens)} (${Math.round(percent)}%)`
+ : formatTokens(usedTokens)}
+ </span>
+ </div>
+
+ <div
+ role="progressbar"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={maxTokens != null ? Math.round(percent) : undefined}
+ aria-label={localize('com_ui_context_usage')}
+ className="h-2 w-full overflow-hidden rounded-full bg-surface-tertiary"
+ >
+ {percent > 0 && (
+ <div
+ className="h-full rounded-full bg-text-primary transition-all duration-300"
+ style={{ width: `${Math.min(percent, 100)}%` }}
+ />
+ )}
+ </div>
+
+ <div
+ className="space-y-1.5"
+ data-testid={breakdown ? 'context-breakdown' : 'context-estimate'}
+ >
+ {breakdown ? (
+ <>
+ <Row
+ label={localize('com_ui_context_messages')}
+ value={messageTokens}
+ max={maxTokens}
+ />
+ {systemTokens > 0 && (
+ <Row label={localize('com_ui_context_system')} value={systemTokens} max={maxTokens} />
+ )}
+ {toolRows != null ? (
+ toolRows.map(
+ ([label, value]) =>
+ value > 0 && <Row key={label} label={label} value={value} max={maxTokens} />,
+ )
+ ) : (
+ <Row
+ label={localize('com_ui_context_tools')}
+ value={breakdown.toolSchemaTokens}
+ max={maxTokens}
+ />
+ )}
+ {breakdown.summaryTokens > 0 && (
+ <Row
+ label={localize('com_ui_context_summary')}
+ value={breakdown.summaryTokens}
+ max={maxTokens}
+ />
+ )}
+ {freeTokens != null && (
+ <Row label={localize('com_ui_context_free')} value={freeTokens} max={maxTokens} />
+ )}
+ </>
+ ) : (
+ <>
+ <Row label={localize('com_ui_input')} value={view.branchTotals.input} />
+ <Row
+ label={localize('com_ui_output')}
+ value={view.branchTotals.output + view.liveTokens}
+ />
+ {maxTokens == null && (
+ <p className="text-xs text-text-secondary">{localize('com_ui_context_unknown')}</p>
+ )}
+ <p className="text-xs italic text-text-secondary">{localize('com_ui_estimated')}</p>
+ </>
+ )}
+ </div>
+
+ {usageTotals.eventCount > 0 && (
+ <>
+ <div className="border-t border-border-light" role="separator" />
+ <div className="space-y-1.5" data-testid="token-usage-totals">
+ <Row label={localize('com_ui_input')} value={usageTotals.input} />
+ <Row label={localize('com_ui_output')} value={usageTotals.output} />
+ {usageTotals.cacheRead > 0 && (
+ <Row label={localize('com_ui_cache_read')} value={usageTotals.cacheRead} />
+ )}
+ {usageTotals.cacheWrite > 0 && (
+ <Row label={localize('com_ui_cache_write')} value={usageTotals.cacheWrite} />
+ )}
+ </div>
+ </>
+ )}
+
+ {showCost && view.costUSD != null && (
+ <>
+ <div className="border-t border-border-light" role="separator" />
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-text-secondary">{localize('com_ui_session_cost')}</span>
+ <span className="font-medium text-text-primary">{formatCost(view.costUSD)}</span>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/Chat/Input/TokenUsage/Gauge.tsx b/client/src/components/Chat/Input/TokenUsage/Gauge.tsx
new file mode 100644
index 0000000000..ba7e420302
--- /dev/null
+++ b/client/src/components/Chat/Input/TokenUsage/Gauge.tsx
@@ -0,0 +1,62 @@
+import { cn } from '~/utils';
+
+const SIZE = 28;
+const STROKE_WIDTH = 3.5;
+const RADIUS = (SIZE - STROKE_WIDTH) / 2;
+const CIRCUMFERENCE = 2 * Math.PI * RADIUS;
+
+interface GaugeProps {
+ /** 0–100, clamped by the caller */
+ percent: number;
+ /** Max context unknown — render an empty track only */
+ indeterminate: boolean;
+}
+
+function getStrokeClass(percent: number, indeterminate: boolean): string {
+ if (indeterminate) {
+ return 'stroke-text-secondary';
+ }
+ if (percent > 90) {
+ return 'stroke-red-500';
+ }
+ if (percent > 75) {
+ return 'stroke-yellow-500';
+ }
+ return 'stroke-text-secondary';
+}
+
+export default function Gauge({ percent, indeterminate }: GaugeProps) {
+ const offset = CIRCUMFERENCE - (percent / 100) * CIRCUMFERENCE;
+
+ return (
+ <svg
+ width={SIZE}
+ height={SIZE}
+ viewBox={`0 0 ${SIZE} ${SIZE}`}
+ className="-rotate-90"
+ aria-hidden="true"
+ focusable="false"
+ >
+ <circle
+ cx={SIZE / 2}
+ cy={SIZE / 2}
+ r={RADIUS}
+ fill="transparent"
+ strokeWidth={STROKE_WIDTH}
+ className="stroke-border-heavy"
+ strokeDasharray={indeterminate ? '2 4' : undefined}
+ />
+ <circle
+ cx={SIZE / 2}
+ cy={SIZE / 2}
+ r={RADIUS}
+ fill="transparent"
+ strokeWidth={STROKE_WIDTH}
+ strokeDasharray={CIRCUMFERENCE}
+ strokeDashoffset={indeterminate ? CIRCUMFERENCE : offset}
+ strokeLinecap="round"
+ className={cn('transition-all duration-300', getStrokeClass(percent, indeterminate))}
+ />
+ </svg>
+ );
+}
diff --git a/client/src/components/Chat/Input/TokenUsage/index.tsx b/client/src/components/Chat/Input/TokenUsage/index.tsx
new file mode 100644
index 0000000000..d4ba946d31
--- /dev/null
+++ b/client/src/components/Chat/Input/TokenUsage/index.tsx
@@ -0,0 +1,86 @@
+import { memo } from 'react';
+import { HoverCard, HoverCardTrigger, HoverCardContent, HoverCardPortal } from '@librechat/client';
+import type { TConversation } from 'librechat-data-provider';
+import useTokenUsage from '~/hooks/Chat/useTokenUsage';
+import { useGetStartupConfig } from '~/data-provider';
+import { formatTokens } from '~/utils';
+import { useLocalize } from '~/hooks';
+import Breakdown from './Breakdown';
+import Gauge from './Gauge';
+
+interface TokenUsageProps {
+ index: number;
+ conversation: TConversation | null;
+ isSubmitting: boolean;
+}
+
+function TokenUsageIndicator({
+ index,
+ conversation,
+ isSubmitting,
+ showCost,
+}: TokenUsageProps & {
+ showCost: boolean;
+}) {
+ const localize = useLocalize();
+ const view = useTokenUsage({ index, conversation, isSubmitting });
+
+ if (view.usedTokens <= 0 && view.maxTokens == null) {
+ return null;
+ }
+
+ const hasMax = view.maxTokens != null && view.maxTokens > 0;
+ const ariaLabel = hasMax
+ ? localize('com_ui_context_usage_label', {
+ 0: formatTokens(view.usedTokens),
+ 1: formatTokens(view.maxTokens ?? 0),
+ 2: String(Math.round(view.percent)),
+ })
+ : localize('com_ui_context_usage_label_unknown', { 0: formatTokens(view.usedTokens) });
+
+ return (
+ <HoverCard openDelay={150} closeDelay={100}>
+ <HoverCardTrigger asChild>
+ <button
+ type="button"
+ data-testid="token-usage"
+ className="flex size-9 items-center justify-center rounded-full p-1 transition-colors hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={ariaLabel}
+ aria-haspopup="dialog"
+ >
+ <span
+ role="meter"
+ aria-valuemin={0}
+ aria-valuemax={hasMax ? view.maxTokens : undefined}
+ aria-valuenow={view.usedTokens}
+ aria-label={localize('com_ui_context_usage')}
+ className="flex items-center justify-center"
+ >
+ <Gauge percent={view.percent} indeterminate={!hasMax} />
+ </span>
+ </button>
+ </HoverCardTrigger>
+ <HoverCardPortal>
+ <HoverCardContent side="top" align="end" className="w-auto p-3">
+ <Breakdown view={view} showCost={showCost} />
+ </HoverCardContent>
+ </HoverCardPortal>
+ </HoverCard>
+ );
+}
+
+/** Config gate kept outside the indicator so disabled deployments mount nothing */
+const TokenUsage = memo(function TokenUsage(props: TokenUsageProps) {
+ const { data: startupConfig } = useGetStartupConfig();
+ /** Wait for config before mounting: until it loads `contextUsage === false`
+ * reads as undefined, so a disabled deployment would briefly mount the
+ * indicator and fire the token-config query on first load */
+ if (startupConfig == null || startupConfig.interface?.contextUsage === false) {
+ return null;
+ }
+ return (
+ <TokenUsageIndicator {...props} showCost={startupConfig.interface?.contextCost === true} />
+ );
+});
+
+export default TokenUsage;
diff --git a/client/src/data-provider/Endpoints/queries.ts b/client/src/data-provider/Endpoints/queries.ts
index 17527c6dc1..294f81597d 100644
--- a/client/src/data-provider/Endpoints/queries.ts
+++ b/client/src/data-provider/Endpoints/queries.ts
@@ -1,6 +1,6 @@
import { useRecoilValue } from 'recoil';
-import { QueryKeys, dataService } from 'librechat-data-provider';
import { useQuery } from '@tanstack/react-query';
+import { QueryKeys, dataService } from 'librechat-data-provider';
import type { QueryObserverResult, UseQueryOptions } from '@tanstack/react-query';
import type t from 'librechat-data-provider';
import store from '~/store';
@@ -23,6 +23,24 @@ export const useGetEndpointsQuery = <TData = t.TEndpointsConfig>(
);
};
+export const useTokenConfigQuery = (
+ config?: UseQueryOptions<t.TTokenConfigMap>,
+): QueryObserverResult<t.TTokenConfigMap> => {
+ const queriesEnabled = useRecoilValue<boolean>(store.queriesEnabled);
+ return useQuery<t.TTokenConfigMap>([QueryKeys.tokenConfig], () => dataService.getTokenConfig(), {
+ staleTime: Infinity,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ /** Refetch on mount only when stale — with `staleTime: Infinity` that's
+ * exclusively after a user-key change invalidates `tokenConfig`, so a
+ * settings change made while the gauge is unmounted is picked up on
+ * return instead of serving the prior key's resolved config */
+ refetchOnMount: true,
+ ...config,
+ enabled: (config?.enabled ?? true) === true && queriesEnabled,
+ });
+};
+
/**
* Auth-aware query key so unauthenticated (login page) and authenticated
* (chat page) configs are cached independently, preventing stale
diff --git a/client/src/hooks/Chat/index.ts b/client/src/hooks/Chat/index.ts
index 11754c6c5f..9d9af790ce 100644
--- a/client/src/hooks/Chat/index.ts
+++ b/client/src/hooks/Chat/index.ts
@@ -1,4 +1,6 @@
export { default as useChatHelpers } from './useChatHelpers';
+export { default as useTokenLimits } from './useTokenLimits';
+export { default as useTokenUsage } from './useTokenUsage';
export { default as useAddedResponse } from './useAddedResponse';
export { default as useChatFunctions } from './useChatFunctions';
export { default as useGetAddedConvo } from './useGetAddedConvo';
diff --git a/client/src/hooks/Chat/useTokenLimits.ts b/client/src/hooks/Chat/useTokenLimits.ts
new file mode 100644
index 0000000000..e2454aae77
--- /dev/null
+++ b/client/src/hooks/Chat/useTokenLimits.ts
@@ -0,0 +1,66 @@
+import { useMemo } from 'react';
+import { Providers, EModelEndpoint, isAgentsEndpoint } from 'librechat-data-provider';
+import type { TConversation, TModelTokenomics } from 'librechat-data-provider';
+import { useGetStartupConfig, useTokenConfigQuery, useGetAgentByIdQuery } from '~/data-provider';
+import { getModelSpec } from '~/utils';
+
+/** Gemini tokenomics are advertised under the `google` endpoint, so a
+ * Vertex-backed agent (`provider: 'vertexai'`) must look up there. */
+function normalizeTokenConfigKey(endpoint: string): string {
+ return endpoint === Providers.VERTEXAI ? EModelEndpoint.google : endpoint;
+}
+
+export interface TokenLimits {
+ /** Statically resolved max context; live snapshots override this at run time */
+ maxContextTokens?: number;
+ rates?: TModelTokenomics;
+ endpoint?: string;
+ model?: string;
+}
+
+function toNumber(value: unknown): number | undefined {
+ const num = typeof value === 'string' ? parseFloat(value) : value;
+ return typeof num === 'number' && Number.isFinite(num) && num > 0 ? num : undefined;
+}
+
+/**
+ * Mirrors the backend resolution chain (packages/api agents/initialize.ts):
+ * explicit conversation setting → agent params → model spec preset →
+ * server-resolved token config lookup.
+ */
+export default function useTokenLimits(conversation: TConversation | null): TokenLimits {
+ const { data: startupConfig } = useGetStartupConfig();
+ const { data: tokenConfig } = useTokenConfigQuery();
+
+ const endpoint = conversation?.endpoint ?? '';
+ const agentId = isAgentsEndpoint(endpoint) ? conversation?.agent_id : null;
+ const { data: agent } = useGetAgentByIdQuery(agentId);
+
+ const spec = conversation?.spec;
+ const model = conversation?.model;
+ const maxContextSetting = conversation?.maxContextTokens;
+
+ return useMemo(() => {
+ const specPreset = getModelSpec({ specName: spec, startupConfig })?.preset;
+
+ let lookupEndpoint = endpoint;
+ let lookupModel = model ?? '';
+ if (agent) {
+ lookupEndpoint = agent.provider ?? endpoint;
+ lookupModel = agent.model ?? lookupModel;
+ } else if (specPreset) {
+ lookupEndpoint = specPreset.endpoint ?? lookupEndpoint;
+ lookupModel = lookupModel || (specPreset.model ?? '');
+ }
+ lookupEndpoint = normalizeTokenConfigKey(lookupEndpoint);
+
+ const rates = tokenConfig?.[lookupEndpoint]?.[lookupModel];
+ const maxContextTokens =
+ toNumber(maxContextSetting) ??
+ toNumber(agent?.model_parameters?.maxContextTokens) ??
+ toNumber(specPreset?.maxContextTokens) ??
+ rates?.context;
+
+ return { maxContextTokens, rates, endpoint: lookupEndpoint, model: lookupModel };
+ }, [endpoint, model, spec, maxContextSetting, agent, startupConfig, tokenConfig]);
+}
diff --git a/client/src/hooks/Chat/useTokenUsage.ts b/client/src/hooks/Chat/useTokenUsage.ts
new file mode 100644
index 0000000000..90bb4a25e2
--- /dev/null
+++ b/client/src/hooks/Chat/useTokenUsage.ts
@@ -0,0 +1,216 @@
+import { useEffect, useMemo, useRef } from 'react';
+import { useAtomValue, useSetAtom } from 'jotai';
+import { useQueryClient } from '@tanstack/react-query';
+import { Constants, QueryKeys } from 'librechat-data-provider';
+import type { TMessage, TConversation, TModelTokenomics } from 'librechat-data-provider';
+import type { ContextSnapshot, UsageTotals } from '~/store/usage';
+import type { BranchTotals } from '~/utils/tokens';
+import {
+ liveTokensFamily,
+ removeUsageAtoms,
+ usageTotalsFamily,
+ branchTotalsFamily,
+ contextSnapshotFamily,
+ snapshotsByAnchorFamily,
+} from '~/store/usage';
+import { buildIndex, sumBranch, clearIndex, findBranchSnapshotAnchor } from '~/utils';
+import { useLatestMessageId } from '~/hooks/Messages/useLatestMessage';
+import useTokenLimits from './useTokenLimits';
+
+export interface TokenUsageParams {
+ index: number;
+ conversation: TConversation | null;
+ isSubmitting: boolean;
+}
+
+export interface TokenUsageView {
+ usedTokens: number;
+ maxTokens?: number;
+ /** 0–100, clamped; 0 when max is unknown */
+ percent: number;
+ /** True when derived from per-message counts instead of a backend snapshot */
+ isEstimate: boolean;
+ snapshot: ContextSnapshot | null;
+ snapshotActive: boolean;
+ branchTotals: BranchTotals;
+ usageTotals: UsageTotals;
+ liveTokens: number;
+ rates?: TModelTokenomics;
+ /** Session cost from provider-reported usage; undefined until usage events arrive */
+ costUSD?: number;
+}
+
+/**
+ * View-model for the context usage indicator. Mount only inside the
+ * indicator so its subscriptions never re-render the chat tree.
+ */
+export default function useTokenUsage({
+ index,
+ conversation,
+ isSubmitting,
+}: TokenUsageParams): TokenUsageView {
+ const queryClient = useQueryClient();
+ const conversationKey = conversation?.conversationId ?? Constants.NEW_CONVO;
+
+ const tailId = useLatestMessageId(index);
+ const snapshot = useAtomValue(contextSnapshotFamily(conversationKey));
+ const snapshotsByAnchor = useAtomValue(snapshotsByAnchorFamily(conversationKey));
+ const usageTotals = useAtomValue(usageTotalsFamily(conversationKey));
+ const branchTotals = useAtomValue(branchTotalsFamily(conversationKey));
+ const liveTokens = useAtomValue(liveTokensFamily(conversationKey));
+ const setBranchTotals = useSetAtom(branchTotalsFamily(conversationKey));
+ const limits = useTokenLimits(conversation);
+
+ /** Authoritative session cost: the backend prices each call (premium tiers,
+ * cache rates) and emits it on the usage event; we just sum. Undefined
+ * until usage events arrive — the cost row is additionally gated on
+ * `interface.contextCost`, under which the backend actually emits cost. */
+ const costUSD = usageTotals.eventCount > 0 ? usageTotals.costUSD : undefined;
+
+ const isSubmittingRef = useRef(isSubmitting);
+ isSubmittingRef.current = isSubmitting;
+ const tailIdRef = useRef(tailId);
+ tailIdRef.current = tailId;
+ const anchorId = snapshot?.anchorMessageId ?? null;
+ const anchorIdRef = useRef(anchorId);
+ anchorIdRef.current = anchorId;
+
+ useEffect(() => {
+ /** Cache `updated` events fire on every state transition — rebuild the
+ * O(n) index only when the data snapshot reference actually changed */
+ let lastIndexed: TMessage[] | undefined;
+ const rebuild = (messages?: TMessage[]) => {
+ if (messages === lastIndexed && messages !== undefined) {
+ return;
+ }
+ lastIndexed = messages;
+ buildIndex(conversationKey, messages);
+ setBranchTotals(sumBranch(conversationKey, tailIdRef.current, anchorIdRef.current));
+ };
+
+ rebuild(queryClient.getQueryData<TMessage[]>([QueryKeys.messages, conversationKey]));
+
+ const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
+ if (isSubmittingRef.current || event.type !== 'updated') {
+ return;
+ }
+ const queryKey = event.query.queryKey;
+ if (
+ !Array.isArray(queryKey) ||
+ queryKey[0] !== QueryKeys.messages ||
+ queryKey[1] !== conversationKey
+ ) {
+ return;
+ }
+ rebuild(event.query.state.data as TMessage[] | undefined);
+ });
+ return () => {
+ unsubscribe();
+ /** Bound memory to open conversations — drop this one's token index and
+ * usage atoms on switch/unmount; both rebuild from the query cache on
+ * return. NEW_CONVO is migrated to its real id by finalizeUsage, so
+ * leave it alone to avoid racing that handoff. */
+ if (conversationKey !== Constants.NEW_CONVO) {
+ clearIndex(conversationKey);
+ removeUsageAtoms(conversationKey);
+ }
+ };
+ }, [conversationKey, queryClient, setBranchTotals]);
+
+ useEffect(() => {
+ /** The cache subscriber is muted during streaming to avoid per-chunk O(n)
+ * rebuilds, but the `created` event still moves the tail to the new
+ * response message. Without a snapshot (non-agent streams, or a lib that
+ * predates on_context_usage) sumBranch would miss that tail in the stale
+ * index and drop history + prompt. Re-index from the cache on tail change
+ * while submitting — bounded, since tailId only shifts on
+ * created/finalize/branch-switch, never per chunk. */
+ if (isSubmittingRef.current) {
+ buildIndex(
+ conversationKey,
+ queryClient.getQueryData<TMessage[]>([QueryKeys.messages, conversationKey]),
+ );
+ }
+ setBranchTotals(sumBranch(conversationKey, tailId, anchorId));
+ }, [conversationKey, tailId, anchorId, setBranchTotals, queryClient]);
+
+ return useMemo(() => {
+ /** The granular snapshot is for one specific generation. Show the live one
+ * while streaming, or when its (response-message) anchor is on the viewed
+ * branch. A null-anchor snapshot must NOT match every branch — that leaked
+ * one branch's breakdown onto its siblings. */
+ const currentActive =
+ snapshot != null &&
+ (isSubmitting || (snapshot.anchorMessageId != null && branchTotals.containsAnchor));
+
+ /** When the live snapshot belongs to another branch, recover this branch's
+ * own finalized snapshot (if it was generated this session) by walking the
+ * branch for its deepest stored anchor — keeps the granular rows on switch
+ * instead of dropping to coarse totals. */
+ let activeSnapshot: ContextSnapshot | null = currentActive ? snapshot : null;
+ if (activeSnapshot == null && !isSubmitting && snapshotsByAnchor.size > 0) {
+ const anchor = findBranchSnapshotAnchor(
+ conversationKey,
+ branchTotals.tailId,
+ snapshotsByAnchor,
+ );
+ activeSnapshot = anchor != null ? (snapshotsByAnchor.get(anchor) ?? null) : null;
+ }
+
+ if (activeSnapshot != null) {
+ const breakdown = activeSnapshot.breakdown;
+ const maxTokens = activeSnapshot.contextBudget ?? breakdown.maxContextTokens;
+ const instructionTokens =
+ activeSnapshot.effectiveInstructionTokens ?? breakdown.instructionTokens;
+ const baseUsed =
+ activeSnapshot.remainingContextTokens != null
+ ? maxTokens - activeSnapshot.remainingContextTokens
+ : instructionTokens + breakdown.messageTokens;
+ /** The snapshot is pre-invoke: in-flight output rides on `liveTokens`
+ * (0 unless streaming this branch), the last call's finalized output on
+ * `completedOutputTokens`. */
+ const usedTokens =
+ Math.max(0, baseUsed) + liveTokens + (activeSnapshot.completedOutputTokens ?? 0);
+ return {
+ usedTokens,
+ maxTokens,
+ percent: maxTokens > 0 ? Math.min((usedTokens / maxTokens) * 100, 100) : 0,
+ isEstimate: false,
+ snapshot: activeSnapshot,
+ snapshotActive: true,
+ branchTotals,
+ usageTotals,
+ liveTokens,
+ rates: limits.rates,
+ costUSD,
+ };
+ }
+
+ const usedTokens = branchTotals.input + branchTotals.output + liveTokens;
+ const maxTokens = limits.maxContextTokens;
+ return {
+ usedTokens,
+ maxTokens,
+ percent:
+ maxTokens != null && maxTokens > 0 ? Math.min((usedTokens / maxTokens) * 100, 100) : 0,
+ isEstimate: true,
+ snapshot: null,
+ snapshotActive: false,
+ branchTotals,
+ usageTotals,
+ liveTokens,
+ rates: limits.rates,
+ costUSD,
+ };
+ }, [
+ snapshot,
+ isSubmitting,
+ branchTotals,
+ usageTotals,
+ liveTokens,
+ limits,
+ costUSD,
+ snapshotsByAnchor,
+ conversationKey,
+ ]);
+}
diff --git a/client/src/hooks/SSE/index.ts b/client/src/hooks/SSE/index.ts
index 2829db76f6..5de4866d49 100644
--- a/client/src/hooks/SSE/index.ts
+++ b/client/src/hooks/SSE/index.ts
@@ -3,5 +3,6 @@ export { default as useResumableSSE } from './useResumableSSE';
export { default as useAdaptiveSSE } from './useAdaptiveSSE';
export { default as useResumeOnLoad } from './useResumeOnLoad';
export { default as useStepHandler } from './useStepHandler';
+export { default as useUsageHandler } from './useUsageHandler';
export { default as useContentHandler } from './useContentHandler';
export { default as useAttachmentHandler } from './useAttachmentHandler';
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 43ae4d2336..0fa9125e73 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -10,6 +10,7 @@ import {
ErrorTypes,
StepEvents,
apiBaseUrl,
+ UsageEvents,
createPayload,
ViolationTypes,
removeNullishValues,
@@ -29,6 +30,7 @@ import {
clearAllDrafts,
removeConvoFromAllQueries,
upsertConvoInAllQueries,
+ countTrailingOutputChars,
markStreamStartFailedMetadata,
} from '~/utils';
import {
@@ -39,6 +41,7 @@ import {
} from '~/data-provider';
import useEventHandlers, { buildCreatedInitialResponse } from './useEventHandlers';
import { useAuthContext } from '~/hooks/AuthContext';
+import useUsageHandler from './useUsageHandler';
import store from '~/store';
type ChatHelpers = Pick<
@@ -473,6 +476,16 @@ export default function useResumableSSE(
const balanceQuery = useGetUserBalance({
enabled: !!isAuthenticated && startupConfig?.balance?.enabled,
});
+ const {
+ contextHandler,
+ usageHandler,
+ tapStream,
+ tapContent,
+ finalizeUsage,
+ backfillUsage,
+ resetLive,
+ seedLive,
+ } = useUsageHandler();
/**
* Subscribe to stream via SSE library (supports custom headers)
@@ -530,6 +543,7 @@ export default function useResumableSSE(
}
try {
finalHandler(data, currentSubmission as EventSubmission);
+ finalizeUsage(data, { ...currentSubmission, userMessage });
} catch (error) {
console.error('[ResumableSSE] Error in finalHandler:', error);
setIsSubmitting(false);
@@ -589,7 +603,23 @@ export default function useResumableSSE(
return;
}
+ if (data.event === UsageEvents.ON_CONTEXT_USAGE) {
+ contextHandler(data.data, { ...currentSubmission, userMessage });
+ return;
+ }
+
+ if (data.event === UsageEvents.ON_TOKEN_USAGE) {
+ usageHandler(data.data, { ...currentSubmission, userMessage });
+ return;
+ }
+
if (data.event != null) {
+ if (
+ data.event === StepEvents.ON_MESSAGE_DELTA ||
+ data.event === StepEvents.ON_REASONING_DELTA
+ ) {
+ tapStream(data.data, { ...currentSubmission, userMessage });
+ }
if (!isResume && !createdStreamIdsRef.current.has(currentStreamId)) {
if (isOAuthStepEvent(data)) {
preCreatedStepEvents.push(data);
@@ -619,6 +649,30 @@ export default function useResumableSSE(
currentSubmission = resumeSubmission;
submissionRef.current = resumeSubmission;
userMessage = resumeSubmission.userMessage;
+ /**
+ * Totals rebuild from the persisted backfill at sync. Replayed or
+ * gap usage events already represented in the snapshot are skipped
+ * via multiset matching; events that raced past the snapshot read
+ * still fold so multi-call runs don't undercount.
+ */
+ /** Fold the run's persisted usage; events also replayed below are
+ * deduped by (runId, seq) inside the handler, so prior prompts in
+ * this conversation keep their usage and gap events still count */
+ backfillUsage(data.resumeState?.collectedUsage ?? [], resumeSubmission);
+ if (data.resumeState?.contextUsage) {
+ contextHandler(data.resumeState.contextUsage, resumeSubmission);
+ }
+ /** Output streamed before this resume is not re-delivered as deltas
+ * — estimate it from the trailing aggregated content. This is
+ * needed even with a snapshot: the snapshot is pre-invoke, so the
+ * in-flight output it precedes rides on the live estimate.
+ * countTrailingOutputChars only counts output at the very end (0
+ * when paused at a tool call), so a snapshot's budget is never
+ * double-counted. */
+ seedLive(
+ countTrailingOutputChars(data.resumeState?.aggregatedContent),
+ resumeSubmission,
+ );
if (data.resumeState?.runSteps) {
for (const runStep of data.resumeState.runSteps) {
@@ -700,7 +754,17 @@ export default function useResumableSSE(
`[ResumableSSE] Replaying ${data.resumeState.replayEvents.length} resume events`,
);
for (const replayEvent of data.resumeState.replayEvents) {
- if (replayEvent.event != null) {
+ if (replayEvent.event === UsageEvents.ON_CONTEXT_USAGE) {
+ contextHandler(replayEvent.data, resumeSubmission);
+ } else if (replayEvent.event === UsageEvents.ON_TOKEN_USAGE) {
+ usageHandler(replayEvent.data, resumeSubmission);
+ } else if (replayEvent.event != null) {
+ if (
+ replayEvent.event === StepEvents.ON_MESSAGE_DELTA ||
+ replayEvent.event === StepEvents.ON_REASONING_DELTA
+ ) {
+ tapStream(replayEvent.data, resumeSubmission);
+ }
stepHandler(replayEvent, resumeSubmission);
}
}
@@ -711,9 +775,22 @@ export default function useResumableSSE(
for (const pendingEvent of data.pendingEvents) {
if (pendingEvent.event === 'title') {
titleHandler(pendingEvent);
+ } else if (pendingEvent.event === UsageEvents.ON_CONTEXT_USAGE) {
+ contextHandler(pendingEvent.data, resumeSubmission);
+ } else if (pendingEvent.event === UsageEvents.ON_TOKEN_USAGE) {
+ usageHandler(pendingEvent.data, resumeSubmission);
} else if (pendingEvent.event != null) {
+ if (
+ pendingEvent.event === StepEvents.ON_MESSAGE_DELTA ||
+ pendingEvent.event === StepEvents.ON_REASONING_DELTA
+ ) {
+ tapStream(pendingEvent.data, resumeSubmission);
+ }
stepHandler(pendingEvent, resumeSubmission);
} else if (pendingEvent.type != null) {
+ /** Gap output streamed past the resume snapshot must reach the
+ * live estimate too, not just the message UI */
+ tapContent(pendingEvent.text, resumeSubmission);
contentHandler({ data: pendingEvent, submission: resumeSubmission });
}
}
@@ -729,6 +806,7 @@ export default function useResumableSSE(
if (text != null && index !== textIndex) {
textIndex = index;
}
+ tapContent(text, { ...currentSubmission, userMessage });
contentHandler({ data, submission: currentSubmission as EventSubmission });
return;
}
@@ -740,6 +818,9 @@ export default function useResumableSSE(
parentMessageId: data.parentMessageId,
messageId: data.messageId,
};
+ /** Legacy non-agent streams send cumulative text here — feed the
+ * live estimate like the content path above */
+ tapContent(text, { ...currentSubmission, userMessage });
messageHandler(text, { ...currentSubmission, userMessage, initialResponse });
}
} catch (error) {
@@ -767,6 +848,9 @@ export default function useResumableSSE(
console.log('[ResumableSSE] Stream 404, invalidating messages for:', convoId);
sse.close();
removeActiveJob(currentStreamId);
+ /** Terminal: drop any in-flight live estimate so the gauge doesn't
+ * keep counting stale streamed output after the stream ends */
+ resetLive({ ...currentSubmission, userMessage });
clearAllDrafts(convoId);
if (optimisticStreamIdsRef.current.has(currentStreamId)) {
clearAllDrafts(Constants.NEW_CONVO);
@@ -821,6 +905,7 @@ export default function useResumableSSE(
console.log('[ResumableSSE] Server-sent error event received:', e.data);
sse.close();
removeActiveJob(currentStreamId);
+ resetLive({ ...currentSubmission, userMessage });
if (
!createdStreamIdsRef.current.has(currentStreamId) &&
optimisticStreamIdsRef.current.has(currentStreamId)
@@ -904,6 +989,9 @@ export default function useResumableSSE(
console.error('[ResumableSSE] Max reconnect attempts reached');
sse.close();
errorHandler({ data: undefined, submission: currentSubmission as EventSubmission });
+ /** Terminal: clear the in-flight live estimate like the other
+ * stop-reconnecting paths so the gauge doesn't show stale tokens */
+ resetLive({ ...currentSubmission, userMessage });
// Optimistically remove from active jobs on max retries
removeActiveJob(currentStreamId);
if (
@@ -994,6 +1082,14 @@ export default function useResumableSSE(
balanceQuery,
removeActiveJob,
queryClient,
+ contextHandler,
+ usageHandler,
+ tapStream,
+ tapContent,
+ finalizeUsage,
+ backfillUsage,
+ resetLive,
+ seedLive,
],
);
diff --git a/client/src/hooks/SSE/useSSE.ts b/client/src/hooks/SSE/useSSE.ts
index 509b7c213e..745b268417 100644
--- a/client/src/hooks/SSE/useSSE.ts
+++ b/client/src/hooks/SSE/useSSE.ts
@@ -2,13 +2,20 @@ import { useEffect, useState } from 'react';
import { v4 } from 'uuid';
import { SSE } from 'sse.js';
import { useSetRecoilState } from 'recoil';
-import { request, createPayload, removeNullishValues } from 'librechat-data-provider';
+import {
+ request,
+ UsageEvents,
+ StepEvents,
+ createPayload,
+ removeNullishValues,
+} from 'librechat-data-provider';
import type { TMessage, TPayload, TSubmission, EventSubmission } from 'librechat-data-provider';
import type { EventHandlerParams } from './useEventHandlers';
import type { TResData } from '~/common';
import { useGetStartupConfig, useGetUserBalance } from '~/data-provider';
import { useAuthContext } from '~/hooks/AuthContext';
import useEventHandlers from './useEventHandlers';
+import useUsageHandler from './useUsageHandler';
import { clearAllDrafts } from '~/utils';
import store from '~/store';
@@ -60,6 +67,8 @@ export default function useSSE(
const balanceQuery = useGetUserBalance({
enabled: !!isAuthenticated && startupConfig?.balance?.enabled,
});
+ const { contextHandler, usageHandler, tapStream, tapContent, finalizeUsage, resetLive } =
+ useUsageHandler();
useEffect(() => {
if (submission == null || Object.keys(submission).length === 0) {
@@ -96,6 +105,7 @@ export default function useSSE(
clearAllDrafts(submission.conversation?.conversationId);
try {
finalHandler(data, submission as EventSubmission);
+ finalizeUsage(data, { ...submission, userMessage });
} catch (error) {
console.error('Error in finalHandler:', error);
setIsSubmitting(false);
@@ -116,7 +126,17 @@ export default function useSSE(
createdHandler(data, { ...submission, userMessage } as EventSubmission);
} else if (data.event === 'title') {
titleHandler(data);
+ } else if (data.event === UsageEvents.ON_CONTEXT_USAGE) {
+ contextHandler(data.data, { ...submission, userMessage });
+ } else if (data.event === UsageEvents.ON_TOKEN_USAGE) {
+ usageHandler(data.data, { ...submission, userMessage });
} else if (data.event != null) {
+ if (
+ data.event === StepEvents.ON_MESSAGE_DELTA ||
+ data.event === StepEvents.ON_REASONING_DELTA
+ ) {
+ tapStream(data.data, { ...submission, userMessage });
+ }
stepHandler(data, { ...submission, userMessage } as EventSubmission);
} else if (data.sync != null) {
const runId = v4();
@@ -129,6 +149,7 @@ export default function useSSE(
textIndex = index;
}
+ tapContent(text, { ...submission, userMessage });
contentHandler({ data, submission: submission as EventSubmission });
} else {
const text = data.text ?? data.response;
@@ -140,6 +161,9 @@ export default function useSSE(
};
if (data.message != null) {
+ /** Legacy non-agent streams (handleText) send cumulative text here,
+ * not via the content path — feed it to the live estimate too */
+ tapContent(text, { ...submission, userMessage });
messageHandler(text, { ...submission, userMessage, initialResponse });
}
}
@@ -162,6 +186,7 @@ export default function useSSE(
}
setCompleted((prev) => new Set(prev.add(streamKey)));
+ resetLive({ ...submission, userMessage });
const latestMessages = getMessages();
const conversationId = latestMessages?.[latestMessages.length - 1]?.conversationId;
try {
@@ -206,6 +231,7 @@ export default function useSSE(
console.log('error in server stream.');
(startupConfig?.balance?.enabled ?? false) && balanceQuery.refetch();
+ resetLive({ ...submission, userMessage });
let data: TResData | undefined = undefined;
try {
diff --git a/client/src/hooks/SSE/useUsageHandler.ts b/client/src/hooks/SSE/useUsageHandler.ts
new file mode 100644
index 0000000000..9ae51d6920
--- /dev/null
+++ b/client/src/hooks/SSE/useUsageHandler.ts
@@ -0,0 +1,307 @@
+import { useRef, useMemo } from 'react';
+import { getDefaultStore } from 'jotai';
+import { Constants } from 'librechat-data-provider';
+import type {
+ TMessage,
+ TConversation,
+ TTokenUsageEvent,
+ TContextUsageEvent,
+} from 'librechat-data-provider';
+import type { ContextSnapshot } from '~/store/usage';
+import {
+ markUsageFolded,
+ liveTokensFamily,
+ removeUsageAtoms,
+ calibrationFamily,
+ usageTotalsFamily,
+ branchTotalsFamily,
+ migrateUsageFolded,
+ contextSnapshotFamily,
+ snapshotsByAnchorFamily,
+} from '~/store/usage';
+import {
+ sumBranch,
+ upsertEntries,
+ migrateIndex,
+ estimateTokens,
+ normalizeUsageUnits,
+} from '~/utils';
+
+const FLUSH_INTERVAL_MS = 250;
+
+interface UsageSubmissionLike {
+ userMessage?: Pick<TMessage, 'messageId' | 'conversationId'> | null;
+ conversation?: Partial<Pick<TConversation, 'conversationId' | 'endpoint' | 'model'>> | null;
+}
+
+interface FinalDataLike {
+ requestMessage?: Partial<TMessage> | null;
+ responseMessage?: Partial<TMessage> | null;
+ conversation?: Partial<TConversation> | null;
+}
+
+export interface UsageHandlers {
+ contextHandler: (data: TContextUsageEvent, submission: UsageSubmissionLike) => void;
+ usageHandler: (data: TTokenUsageEvent, submission: UsageSubmissionLike) => void;
+ tapStream: (data: { delta?: { content?: unknown } }, submission: UsageSubmissionLike) => void;
+ /** Live estimate for the legacy content path, which streams cumulative
+ * (not incremental) text per part — sets rather than accumulates */
+ tapContent: (text: unknown, submission: UsageSubmissionLike) => void;
+ finalizeUsage: (data: FinalDataLike, submission: UsageSubmissionLike) => void;
+ resetLive: (submission: UsageSubmissionLike) => void;
+ /** Idempotently folds the resumed run's collected usage into the totals */
+ backfillUsage: (entries: TTokenUsageEvent[], submission: UsageSubmissionLike) => void;
+ /** Seeds the live estimate from already-streamed output chars on resume */
+ seedLive: (chars: number, submission: UsageSubmissionLike) => void;
+}
+
+function getConvoKey(submission: UsageSubmissionLike): string {
+ /** On a new chat's first turn the `created` event stamps the real id onto
+ * the user message while the submission's conversation is still `new`;
+ * prefer the real id so live writes land where TokenUsage is subscribed */
+ const fromUserMessage = submission.userMessage?.conversationId;
+ if (fromUserMessage != null && fromUserMessage !== Constants.NEW_CONVO) {
+ return fromUserMessage;
+ }
+ return submission.conversation?.conversationId ?? Constants.NEW_CONVO;
+}
+
+/** Cumulative text of a content-path part: a raw string or a `{ value }` part */
+function extractContentText(text: unknown): string {
+ if (typeof text === 'string') {
+ return text;
+ }
+ const value = (text as { value?: unknown })?.value;
+ return typeof value === 'string' ? value : '';
+}
+
+function countDeltaChars(content: unknown): number {
+ const parts = Array.isArray(content) ? content : [content];
+ let chars = 0;
+ for (const part of parts) {
+ if (part == null || typeof part !== 'object') {
+ continue;
+ }
+ const { text, think } = part as { text?: unknown; think?: unknown };
+ if (typeof text === 'string') {
+ chars += text.length;
+ } else if (typeof think === 'string') {
+ chars += think.length;
+ }
+ }
+ return chars;
+}
+
+/**
+ * Imperative writers for the per-conversation token usage atoms, driven by
+ * SSE events. All state lives in refs/atoms — the returned handlers are
+ * stable and never cause re-renders themselves.
+ */
+export default function useUsageHandler(): UsageHandlers {
+ /** Streamed chars since the last snapshot or model end (current call only) */
+ const streamCharsRef = useRef(0);
+ /** Provider-confirmed output tokens since the last snapshot (current run) */
+ const confirmedRef = useRef(0);
+ const lastFlushRef = useRef(0);
+
+ return useMemo<UsageHandlers>(() => {
+ const jotai = getDefaultStore();
+
+ const setLive = (convoKey: string, value: number) => {
+ jotai.set(liveTokensFamily(convoKey), value);
+ };
+
+ const contextHandler: UsageHandlers['contextHandler'] = (data, submission) => {
+ const convoKey = getConvoKey(submission);
+ jotai.set(contextSnapshotFamily(convoKey), {
+ ...data,
+ anchorMessageId: submission.userMessage?.messageId ?? null,
+ });
+ if (data.calibrationRatio != null && data.calibrationRatio > 0) {
+ jotai.set(calibrationFamily(convoKey), data.calibrationRatio);
+ }
+ streamCharsRef.current = 0;
+ confirmedRef.current = 0;
+ setLive(convoKey, 0);
+ };
+
+ /** Folds one usage event into the totals exactly once per conversation.
+ * Returns false when the event was already counted (live then replayed
+ * on resume), so callers can skip the live-estimate bump too. */
+ const foldUsage = (data: TTokenUsageEvent, submission: UsageSubmissionLike): boolean => {
+ const convoKey = getConvoKey(submission);
+ /** runId+seq is unique per model call; fall back to the payload when a
+ * source predates the sequence tag */
+ const usageKey =
+ data.runId != null && data.seq != null ? `${data.runId}:${data.seq}` : JSON.stringify(data);
+ if (!markUsageFolded(convoKey, usageKey)) {
+ return false;
+ }
+
+ /** Displayed counts use the same normalized units billing does: input is
+ * the uncached portion, output includes repaired completion tokens */
+ const units = normalizeUsageUnits(data);
+
+ const totalsAtom = usageTotalsFamily(convoKey);
+ const prev = jotai.get(totalsAtom);
+ jotai.set(totalsAtom, {
+ input: prev.input + units.input,
+ output: prev.output + units.output,
+ cacheWrite: prev.cacheWrite + units.cacheWrite,
+ cacheRead: prev.cacheRead + units.cacheRead,
+ eventCount: prev.eventCount + 1,
+ /** Authoritative per-event cost from the backend (premium tiers, cache
+ * rates); absent when contextCost is disabled — sums to 0 then */
+ costUSD: prev.costUSD + (data.cost ?? 0),
+ });
+ return true;
+ };
+
+ const usageHandler: UsageHandlers['usageHandler'] = (data, submission) => {
+ const folded = foldUsage(data, submission);
+
+ /** Only primary-call usage drives the live context estimate; tagged
+ * buckets (summarization, subagent) fold into totals/cost only. Skip
+ * the bump for an already-counted event replayed on resume. */
+ if (!folded || data.usage_type != null) {
+ return;
+ }
+ /** Use the repaired completion count (not raw output_tokens) so the
+ * snapshot gauge keeps the full response for under-reporting providers */
+ confirmedRef.current += normalizeUsageUnits(data).output;
+ streamCharsRef.current = 0;
+ setLive(getConvoKey(submission), confirmedRef.current);
+ };
+
+ const tapStream: UsageHandlers['tapStream'] = (data, submission) => {
+ const chars = countDeltaChars(data?.delta?.content);
+ if (chars <= 0) {
+ return;
+ }
+ streamCharsRef.current += chars;
+ const now = Date.now();
+ if (now - lastFlushRef.current < FLUSH_INTERVAL_MS) {
+ return;
+ }
+ lastFlushRef.current = now;
+ const convoKey = getConvoKey(submission);
+ const ratio = jotai.get(calibrationFamily(convoKey));
+ setLive(convoKey, confirmedRef.current + estimateTokens(streamCharsRef.current, ratio));
+ };
+
+ const tapContent: UsageHandlers['tapContent'] = (text, submission) => {
+ const value = extractContentText(text);
+ if (value.length === 0) {
+ return;
+ }
+ /** Cumulative per part — replace the running char count, don't add */
+ streamCharsRef.current = value.length;
+ const now = Date.now();
+ if (now - lastFlushRef.current < FLUSH_INTERVAL_MS) {
+ return;
+ }
+ lastFlushRef.current = now;
+ const convoKey = getConvoKey(submission);
+ const ratio = jotai.get(calibrationFamily(convoKey));
+ setLive(convoKey, confirmedRef.current + estimateTokens(streamCharsRef.current, ratio));
+ };
+
+ const resetLive: UsageHandlers['resetLive'] = (submission) => {
+ streamCharsRef.current = 0;
+ confirmedRef.current = 0;
+ setLive(getConvoKey(submission), 0);
+ };
+
+ const backfillUsage: UsageHandlers['backfillUsage'] = (entries, submission) => {
+ /** Fold the resumed run's persisted events idempotently — never reset
+ * the conversation totals, or a reconnect mid-stream would drop the
+ * usage of prompts already completed earlier in the session */
+ for (const entry of entries) {
+ foldUsage(entry, submission);
+ }
+ };
+
+ const seedLive: UsageHandlers['seedLive'] = (chars, submission) => {
+ if (chars <= 0) {
+ return;
+ }
+ const convoKey = getConvoKey(submission);
+ streamCharsRef.current = chars;
+ confirmedRef.current = 0;
+ setLive(convoKey, estimateTokens(chars, jotai.get(calibrationFamily(convoKey))));
+ };
+
+ const finalizeUsage: UsageHandlers['finalizeUsage'] = (data, submission) => {
+ const fromKey = getConvoKey(submission);
+ const realId = data.conversation?.conversationId ?? fromKey;
+ /** From the refs, not the atom — the throttle may not have flushed */
+ const liveAtFinalize =
+ confirmedRef.current +
+ estimateTokens(streamCharsRef.current, jotai.get(calibrationFamily(fromKey)));
+
+ upsertEntries(fromKey, [data.requestMessage, data.responseMessage]);
+
+ if (realId !== fromKey) {
+ migrateIndex(fromKey, realId);
+ migrateUsageFolded(fromKey, realId);
+ jotai.set(contextSnapshotFamily(realId), jotai.get(contextSnapshotFamily(fromKey)));
+ jotai.set(snapshotsByAnchorFamily(realId), jotai.get(snapshotsByAnchorFamily(fromKey)));
+ jotai.set(usageTotalsFamily(realId), jotai.get(usageTotalsFamily(fromKey)));
+ jotai.set(calibrationFamily(realId), jotai.get(calibrationFamily(fromKey)));
+ removeUsageAtoms(fromKey);
+ }
+
+ const responseMeta = data.responseMessage?.contextMeta;
+ if (responseMeta?.calibrationRatio != null && responseMeta.calibrationRatio > 0) {
+ jotai.set(calibrationFamily(realId), responseMeta.calibrationRatio);
+ }
+
+ const userMsgId = submission.userMessage?.messageId ?? null;
+ const responseId = data.responseMessage?.messageId ?? null;
+ const tailId = responseId ?? data.requestMessage?.messageId ?? null;
+ if (tailId) {
+ jotai.set(branchTotalsFamily(realId), sumBranch(realId, tailId, responseId ?? userMsgId));
+ }
+
+ const snapshotAtom = contextSnapshotFamily(realId);
+ const snapshot = jotai.get(snapshotAtom);
+ /** Re-anchor the snapshot from the user message — shared by both branches
+ * when a response is regenerated — to the branch-unique response message,
+ * so switching to a sibling branch falls back to that branch's own
+ * totals instead of showing this generation's snapshot. Also carry the
+ * output streamed since the pre-invoke snapshot, kept after live resets. */
+ if (snapshot != null && snapshot.anchorMessageId === userMsgId) {
+ const finalized: ContextSnapshot = {
+ ...snapshot,
+ anchorMessageId: responseId ?? snapshot.anchorMessageId,
+ ...(liveAtFinalize > 0 && { completedOutputTokens: liveAtFinalize }),
+ };
+ jotai.set(snapshotAtom, finalized);
+ /** Retain this generation's breakdown keyed by the branch-unique
+ * response id so a later run on a sibling branch (which overwrites the
+ * live snapshot) doesn't strip this branch's granular rows. */
+ if (responseId != null) {
+ const historyAtom = snapshotsByAnchorFamily(realId);
+ const next = new Map(jotai.get(historyAtom));
+ next.set(responseId, finalized);
+ jotai.set(historyAtom, next);
+ }
+ }
+
+ streamCharsRef.current = 0;
+ confirmedRef.current = 0;
+ setLive(realId, 0);
+ };
+
+ return {
+ contextHandler,
+ usageHandler,
+ tapStream,
+ tapContent,
+ finalizeUsage,
+ resetLive,
+ backfillUsage,
+ seedLive,
+ };
+ }, []);
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 7f32cd4481..3f9ea230fc 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -837,6 +837,8 @@
"com_ui_branch_error": "Failed to create branch",
"com_ui_branch_message": "Create branch from this response",
"com_ui_by_author": "by {{0}}",
+ "com_ui_cache_read": "Cache read",
+ "com_ui_cache_write": "Cache write",
"com_ui_callback_url": "Callback URL",
"com_ui_cancel": "Cancel",
"com_ui_cancelled": "Cancelled",
@@ -883,6 +885,21 @@
"com_ui_contact_admin_if_issue_persists": "Contact the Admin if the issue persists",
"com_ui_context": "Context",
"com_ui_context_filter_sort": "Filter and Sort by Context",
+ "com_ui_context_free": "Free space",
+ "com_ui_context_messages": "Messages",
+ "com_ui_context_subagents": "Subagents",
+ "com_ui_context_summary": "Summary",
+ "com_ui_context_system": "System prompt",
+ "com_ui_context_tools": "Tool schemas",
+ "com_ui_context_tools_mcp": "MCP tools",
+ "com_ui_context_tools_mcp_deferred": "MCP tools (deferred)",
+ "com_ui_context_tools_system": "System tools",
+ "com_ui_context_tools_system_deferred": "System tools (deferred)",
+ "com_ui_context_unknown": "Context size unknown",
+ "com_ui_context_usage": "Context usage",
+ "com_ui_context_usage_label": "Context window: {{0}} of {{1}} tokens used ({{2}}%)",
+ "com_ui_context_usage_label_unknown": "Context usage: {{0}} tokens used",
+ "com_ui_context_window": "Context window",
"com_ui_continue": "Continue",
"com_ui_continue_oauth": "Continue with OAuth",
"com_ui_control_bar": "Control bar",
@@ -1029,6 +1046,7 @@
"com_ui_error_try_following_prefix": "Please try one of the following",
"com_ui_error_unexpected": "Oops! Something Unexpected Occurred",
"com_ui_error_updating_preferences": "Error updating preferences",
+ "com_ui_estimated": "Estimated from message history",
"com_ui_everyone_permission_level": "Everyone's permission level",
"com_ui_examples": "Examples",
"com_ui_expand": "Expand",
@@ -1508,6 +1526,7 @@
"com_ui_select_search_model": "Search model by name",
"com_ui_select_search_provider": "Search provider by name",
"com_ui_select_search_region": "Search region by name",
+ "com_ui_session_cost": "Session cost",
"com_ui_set": "Set",
"com_ui_share": "Share",
"com_ui_share_create_message": "Your name and any messages you add after sharing stay private.",
diff --git a/client/src/store/index.ts b/client/src/store/index.ts
index 0584e9d805..7d7d9cfe61 100644
--- a/client/src/store/index.ts
+++ b/client/src/store/index.ts
@@ -1,21 +1,22 @@
import * as artifacts from './artifacts';
-import families from './families';
-import endpoints from './endpoints';
-import user from './user';
-import text from './text';
-import toast from './toast';
import submission from './submission';
+import isTemporary from './temporary';
+import endpoints from './endpoints';
+import families from './families';
+import settings from './settings';
+import prompts from './prompts';
import search from './search';
import preset from './preset';
-import prompts from './prompts';
import lang from './language';
-import settings from './settings';
+import toast from './toast';
+import user from './user';
+import text from './text';
import misc from './misc';
-import isTemporary from './temporary';
export * from './agents';
export * from './mcp';
export * from './favorites';
export * from './subagents';
+export * from './usage';
export default {
...artifacts,
diff --git a/client/src/store/usage.ts b/client/src/store/usage.ts
new file mode 100644
index 0000000000..6501648a72
--- /dev/null
+++ b/client/src/store/usage.ts
@@ -0,0 +1,113 @@
+import { atom } from 'jotai';
+import { atomFamily } from 'jotai/utils';
+import type { TContextUsageEvent } from 'librechat-data-provider';
+import type { BranchTotals } from '~/utils/tokens';
+import { EMPTY_BRANCH } from '~/utils/tokens';
+
+/** Latest backend context snapshot, anchored to the run's user message for staleness checks */
+export interface ContextSnapshot extends TContextUsageEvent {
+ anchorMessageId: string | null;
+ /** Output tokens finalized after this pre-call snapshot (the last call's response) */
+ completedOutputTokens?: number;
+}
+
+/** Cumulative provider-reported usage for the conversation's current session */
+export interface UsageTotals {
+ input: number;
+ output: number;
+ cacheWrite: number;
+ cacheRead: number;
+ eventCount: number;
+ /** Summed authoritative per-event cost from the backend (premium tiers,
+ * cache rates). Populated only when `interface.contextCost` is enabled. */
+ costUSD: number;
+}
+
+export const EMPTY_USAGE_TOTALS: UsageTotals = {
+ input: 0,
+ output: 0,
+ cacheWrite: 0,
+ cacheRead: 0,
+ eventCount: 0,
+ costUSD: 0,
+};
+
+/**
+ * Split into small per-conversation atoms so high-frequency writes (live
+ * stream estimates) re-render only the subscribers that draw them.
+ */
+export const branchTotalsFamily = atomFamily((_conversationId: string) =>
+ atom<BranchTotals>(EMPTY_BRANCH),
+);
+
+export const contextSnapshotFamily = atomFamily((_conversationId: string) =>
+ atom<ContextSnapshot | null>(null),
+);
+
+/**
+ * Finalized snapshots keyed by their (branch-unique) response message id.
+ * `contextSnapshotFamily` only holds the latest run; this retains each
+ * generation's breakdown so switching to a branch generated earlier this
+ * session keeps its granular rows instead of dropping to coarse totals.
+ * Bounded by the conversation's generation count; cleared on convo switch.
+ */
+export const snapshotsByAnchorFamily = atomFamily((_conversationId: string) =>
+ atom<Map<string, ContextSnapshot>>(new Map()),
+);
+
+export const usageTotalsFamily = atomFamily((_conversationId: string) =>
+ atom<UsageTotals>(EMPTY_USAGE_TOTALS),
+);
+
+/** Throttled in-flight output token estimate for the current model call */
+export const liveTokensFamily = atomFamily((_conversationId: string) => atom<number>(0));
+
+/** Last known provider-vs-estimate calibration ratio for the conversation */
+export const calibrationFamily = atomFamily((_conversationId: string) => atom<number>(1));
+
+/**
+ * Per-conversation set of usage-event identities already folded into the
+ * totals. Lets the live path and resume backfill fold each model call exactly
+ * once, so reconnect mid-stream preserves earlier prompts' usage instead of
+ * resetting the session totals.
+ */
+const foldedUsageKeys = new Map<string, Set<string>>();
+
+/** Records an event identity; returns false if it was already folded. */
+export function markUsageFolded(conversationId: string, key: string): boolean {
+ let seen = foldedUsageKeys.get(conversationId);
+ if (seen == null) {
+ seen = new Set<string>();
+ foldedUsageKeys.set(conversationId, seen);
+ }
+ if (seen.has(key)) {
+ return false;
+ }
+ seen.add(key);
+ return true;
+}
+
+/** Moves folded-key tracking from a temporary convo id to the persisted one. */
+export function migrateUsageFolded(fromId: string, toId: string): void {
+ const seen = foldedUsageKeys.get(fromId);
+ if (seen == null) {
+ return;
+ }
+ const target = foldedUsageKeys.get(toId) ?? new Set<string>();
+ for (const key of seen) {
+ target.add(key);
+ }
+ foldedUsageKeys.set(toId, target);
+ foldedUsageKeys.delete(fromId);
+}
+
+/** Jotai atomFamily entries are never GC'd — call on conversation switch/cleanup */
+export function removeUsageAtoms(conversationId: string): void {
+ branchTotalsFamily.remove(conversationId);
+ contextSnapshotFamily.remove(conversationId);
+ snapshotsByAnchorFamily.remove(conversationId);
+ usageTotalsFamily.remove(conversationId);
+ liveTokensFamily.remove(conversationId);
+ calibrationFamily.remove(conversationId);
+ foldedUsageKeys.delete(conversationId);
+}
diff --git a/client/src/utils/index.ts b/client/src/utils/index.ts
index 14d76e7b73..0beb890c0b 100644
--- a/client/src/utils/index.ts
+++ b/client/src/utils/index.ts
@@ -21,6 +21,7 @@ export * from './presets';
export * from './prompts';
export * from './textarea';
export * from './messages';
+export * from './tokens';
export * from './redirect';
export * from './languages';
export * from './conversation';
diff --git a/client/src/utils/tokens.spec.ts b/client/src/utils/tokens.spec.ts
new file mode 100644
index 0000000000..f25cda84ec
--- /dev/null
+++ b/client/src/utils/tokens.spec.ts
@@ -0,0 +1,273 @@
+import { Constants, Providers } from 'librechat-data-provider';
+import type { TMessage } from 'librechat-data-provider';
+import {
+ buildIndex,
+ upsertEntries,
+ migrateIndex,
+ clearIndex,
+ hasIndex,
+ sumBranch,
+ findBranchSnapshotAnchor,
+ estimateTokens,
+ normalizeUsageUnits,
+ formatCost,
+ groupToolTokens,
+ countTrailingOutputChars,
+ EMPTY_BRANCH,
+ EMPTY_TOOL_GROUPS,
+} from './tokens';
+
+const CONVO = 'convo-1';
+
+function msg(
+ messageId: string,
+ parentMessageId: string | null,
+ isCreatedByUser: boolean,
+ tokenCount?: number,
+): TMessage {
+ return {
+ messageId,
+ parentMessageId,
+ isCreatedByUser,
+ tokenCount,
+ conversationId: CONVO,
+ text: '',
+ } as TMessage;
+}
+
+describe('token index', () => {
+ afterEach(() => {
+ clearIndex(CONVO);
+ clearIndex('convo-2');
+ clearIndex(Constants.NEW_CONVO);
+ });
+
+ it('sums only the active branch via the parent chain', () => {
+ buildIndex(CONVO, [
+ msg('u1', Constants.NO_PARENT, true, 10),
+ msg('a1', 'u1', false, 20),
+ msg('u2', 'a1', true, 30),
+ msg('a2', 'u2', false, 40),
+ /** Sibling branch that must not be counted */
+ msg('a2-alt', 'u2', false, 999),
+ ]);
+
+ const totals = sumBranch(CONVO, 'a2');
+ expect(totals.input).toBe(40);
+ expect(totals.output).toBe(60);
+ expect(totals.total).toBe(4);
+ expect(totals.counted).toBe(4);
+
+ const altTotals = sumBranch(CONVO, 'a2-alt');
+ expect(altTotals.output).toBe(1019);
+ });
+
+ it('flags whether the anchor message is on the branch', () => {
+ buildIndex(CONVO, [
+ msg('u1', Constants.NO_PARENT, true, 10),
+ msg('a1', 'u1', false, 20),
+ msg('a1-alt', 'u1', false, 25),
+ ]);
+
+ expect(sumBranch(CONVO, 'a1', 'a1').containsAnchor).toBe(true);
+ expect(sumBranch(CONVO, 'a1-alt', 'a1').containsAnchor).toBe(false);
+ });
+
+ it('tracks uncounted messages and tolerates missing parents', () => {
+ buildIndex(CONVO, [msg('u2', 'missing-parent', true, undefined), msg('a2', 'u2', false, 15)]);
+
+ const totals = sumBranch(CONVO, 'a2');
+ expect(totals.total).toBe(2);
+ expect(totals.counted).toBe(1);
+ expect(totals.output).toBe(15);
+ });
+
+ it('returns EMPTY_BRANCH without an index or tail', () => {
+ expect(sumBranch('unknown', 'x')).toBe(EMPTY_BRANCH);
+ buildIndex(CONVO, []);
+ expect(sumBranch(CONVO, null)).toBe(EMPTY_BRANCH);
+ });
+
+ it('upserts incrementally and overwrites by messageId', () => {
+ buildIndex(CONVO, [msg('u1', Constants.NO_PARENT, true, 10)]);
+ upsertEntries(CONVO, [msg('a1', 'u1', false, 20), null, undefined]);
+ expect(sumBranch(CONVO, 'a1').output).toBe(20);
+
+ upsertEntries(CONVO, [msg('a1', 'u1', false, 35)]);
+ expect(sumBranch(CONVO, 'a1').output).toBe(35);
+ });
+
+ it('migrates the index to a new conversation id', () => {
+ buildIndex(Constants.NEW_CONVO, [msg('u1', Constants.NO_PARENT, true, 10)]);
+ migrateIndex(Constants.NEW_CONVO, 'convo-2');
+
+ expect(hasIndex(Constants.NEW_CONVO)).toBe(false);
+ expect(sumBranch('convo-2', 'u1').input).toBe(10);
+ });
+});
+
+describe('findBranchSnapshotAnchor', () => {
+ afterEach(() => clearIndex(CONVO));
+
+ it('returns the deepest stored anchor on the viewed branch', () => {
+ buildIndex(CONVO, [
+ msg('u1', Constants.NO_PARENT, true, 10),
+ msg('a1', 'u1', false, 20),
+ msg('u2', 'a1', true, 30),
+ msg('a2', 'u2', false, 40),
+ msg('a2-alt', 'u2', false, 50),
+ ]);
+ /** Both a1 and a2 stored; walking from a2 must return the nearer one (a2). */
+ const anchors = new Map([
+ ['a1', 1],
+ ['a2', 1],
+ ]);
+ expect(findBranchSnapshotAnchor(CONVO, 'a2', anchors)).toBe('a2');
+ /** From the sibling branch tail, the only on-branch anchor is a1. */
+ expect(findBranchSnapshotAnchor(CONVO, 'a2-alt', anchors)).toBe('a1');
+ });
+
+ it('returns null when no stored anchor sits on the branch', () => {
+ buildIndex(CONVO, [msg('u1', Constants.NO_PARENT, true, 10), msg('a1', 'u1', false, 20)]);
+ expect(findBranchSnapshotAnchor(CONVO, 'a1', new Map([['other', 1]]))).toBeNull();
+ expect(findBranchSnapshotAnchor(CONVO, 'a1', new Map())).toBeNull();
+ expect(findBranchSnapshotAnchor('unknown', 'a1', new Map([['a1', 1]]))).toBeNull();
+ });
+});
+
+describe('estimateTokens', () => {
+ it('estimates chars/4 scaled by calibration ratio', () => {
+ expect(estimateTokens(400)).toBe(100);
+ expect(estimateTokens(400, 1.1)).toBe(110);
+ expect(estimateTokens(0)).toBe(0);
+ expect(estimateTokens(100, 0)).toBe(25);
+ });
+});
+
+describe('normalizeUsageUnits', () => {
+ it('keeps cache additive for Anthropic even when cache <= input', () => {
+ /** Magnitude heuristic would wrongly treat this as inclusive and drop
+ * cache from input; the provider says additive (input is uncached-only) */
+ expect(
+ normalizeUsageUnits({
+ input_tokens: 900,
+ output_tokens: 100,
+ provider: Providers.ANTHROPIC,
+ input_token_details: { cache_read: 100 },
+ }),
+ ).toEqual({ input: 900, output: 100, cacheWrite: 0, cacheRead: 100 });
+ });
+
+ it('keeps subset semantics for OpenAI regardless of magnitude', () => {
+ expect(
+ normalizeUsageUnits({
+ input_tokens: 900,
+ output_tokens: 100,
+ provider: Providers.OPENAI,
+ input_token_details: { cache_read: 100 },
+ }),
+ ).toEqual({ input: 800, output: 100, cacheWrite: 0, cacheRead: 100 });
+ });
+
+ it('falls back to a magnitude heuristic when provider is unknown', () => {
+ /** cacheSum (12000) > input (1000) ⇒ additive */
+ expect(
+ normalizeUsageUnits({
+ input_tokens: 1000,
+ output_tokens: 500,
+ input_token_details: { cache_creation: 2000, cache_read: 10000 },
+ }),
+ ).toEqual({ input: 1000, output: 500, cacheWrite: 2000, cacheRead: 10000 });
+ });
+
+ it('repairs under-reported completion tokens (Vertex thinking)', () => {
+ /** total - input = 500 recovers the dropped thinking tokens */
+ expect(
+ normalizeUsageUnits({
+ input_tokens: 1000,
+ output_tokens: 200,
+ total_tokens: 1500,
+ provider: Providers.VERTEXAI,
+ }).output,
+ ).toBe(500);
+ });
+
+ it('does not mistake additive cache for missing completion tokens', () => {
+ /** Anthropic total includes cache; without the cache adjustment the repair
+ * would falsely inflate completion */
+ expect(
+ normalizeUsageUnits({
+ input_tokens: 1000,
+ output_tokens: 200,
+ total_tokens: 1700,
+ provider: Providers.ANTHROPIC,
+ input_token_details: { cache_creation: 300, cache_read: 200 },
+ }).output,
+ ).toBe(200);
+ });
+});
+
+describe('formatCost', () => {
+ it('formats across magnitude bands', () => {
+ expect(formatCost(0)).toBe('$0.00');
+ expect(formatCost(0.004)).toBe('<$0.01');
+ expect(formatCost(0.0523)).toBe('$0.0523');
+ expect(formatCost(1.234)).toBe('$1.23');
+ });
+});
+
+describe('groupToolTokens', () => {
+ it('classifies tools into system, mcp, skills, and subagent groups', () => {
+ const groups = groupToolTokens(
+ {
+ execute_code: 500,
+ web_search: 300,
+ skill: 200,
+ subagent: 150,
+ 'search_mcp_Google-Workspace': 400,
+ fetch_mcp_Github: 250,
+ },
+ ['fetch_mcp_Github', 'web_search'],
+ );
+
+ expect(groups).toEqual({
+ system: 500,
+ mcp: 400,
+ skills: 200,
+ subagents: 150,
+ systemDeferred: 300,
+ mcpDeferred: 250,
+ });
+ });
+
+ it('returns empty groups without counts and skips zero entries', () => {
+ expect(groupToolTokens(undefined)).toBe(EMPTY_TOOL_GROUPS);
+ expect(groupToolTokens({ execute_code: 0 })).toEqual(EMPTY_TOOL_GROUPS);
+ });
+});
+
+describe('countTrailingOutputChars', () => {
+ const text = (value: string) => ({ type: 'text', text: value });
+ const think = (value: string) => ({ type: 'think', think: value });
+ const tool = () => ({ type: 'tool_call', tool_call: { id: 'tc' } });
+
+ it('counts the trailing run of text and think parts', () => {
+ expect(countTrailingOutputChars([text('aaaa'), tool(), think('bb'), text('ccc')])).toBe(5);
+ });
+
+ it('returns 0 when the latest part is a tool call (no in-flight output)', () => {
+ /** Once a tool call is emitted, its preceding text is folded into the next
+ * snapshot's messageTokens — counting it here would double-count. */
+ expect(countTrailingOutputChars([text('aaaa'), tool(), text('ccc'), tool()])).toBe(0);
+ });
+
+ it('stops at the previous tool boundary', () => {
+ expect(countTrailingOutputChars([text('aaaa'), tool(), text('ccc')])).toBe(3);
+ });
+
+ it('handles empty and non-output content', () => {
+ expect(countTrailingOutputChars(undefined)).toBe(0);
+ expect(countTrailingOutputChars([])).toBe(0);
+ expect(countTrailingOutputChars([tool()])).toBe(0);
+ });
+});
diff --git a/client/src/utils/tokens.ts b/client/src/utils/tokens.ts
new file mode 100644
index 0000000000..9e05b122e8
--- /dev/null
+++ b/client/src/utils/tokens.ts
@@ -0,0 +1,332 @@
+import { Tools, Constants, inputTokensIncludesCache } from 'librechat-data-provider';
+import type { TMessage, TTokenUsageEvent } from 'librechat-data-provider';
+
+export interface TokenEntry {
+ tokenCount: number;
+ isCreatedByUser: boolean;
+ parentMessageId: string | null;
+}
+
+export interface BranchTotals {
+ /** Sum of user-message token counts on the active branch */
+ input: number;
+ /** Sum of assistant-message token counts on the active branch */
+ output: number;
+ /** Messages on the branch with a known tokenCount */
+ counted: number;
+ /** Total messages on the branch */
+ total: number;
+ tailId: string | null;
+ /** Whether the latest run's anchor message is on this branch */
+ containsAnchor: boolean;
+}
+
+export const EMPTY_BRANCH: BranchTotals = {
+ input: 0,
+ output: 0,
+ counted: 0,
+ total: 0,
+ tailId: null,
+ containsAnchor: false,
+};
+
+/** Module-level token index: conversationId → messageId → entry. Not render state. */
+const registry = new Map<string, Map<string, TokenEntry>>();
+
+function toEntry(message: Partial<TMessage>): TokenEntry {
+ return {
+ tokenCount: typeof message.tokenCount === 'number' ? message.tokenCount : 0,
+ isCreatedByUser: message.isCreatedByUser === true,
+ parentMessageId: message.parentMessageId ?? null,
+ };
+}
+
+/** Full O(n) rebuild — only on discrete cache replacements (load, refetch, edits) */
+export function buildIndex(conversationId: string, messages?: TMessage[] | null): void {
+ const index = new Map<string, TokenEntry>();
+ if (messages != null) {
+ for (const message of messages) {
+ if (message?.messageId) {
+ index.set(message.messageId, toEntry(message));
+ }
+ }
+ }
+ registry.set(conversationId, index);
+}
+
+/** Incremental upsert — final SSE events touch at most two entries */
+export function upsertEntries(
+ conversationId: string,
+ messages: (Partial<TMessage> | null | undefined)[],
+): void {
+ let index = registry.get(conversationId);
+ if (!index) {
+ index = new Map<string, TokenEntry>();
+ registry.set(conversationId, index);
+ }
+ for (const message of messages) {
+ if (message?.messageId) {
+ index.set(message.messageId, toEntry(message));
+ }
+ }
+}
+
+/** Re-keys the index when `new` resolves to a real conversation id */
+export function migrateIndex(fromId: string, toId: string): void {
+ if (fromId === toId) {
+ return;
+ }
+ const index = registry.get(fromId);
+ if (!index) {
+ return;
+ }
+ registry.delete(fromId);
+ registry.set(toId, index);
+}
+
+export function clearIndex(conversationId: string): void {
+ registry.delete(conversationId);
+}
+
+export function hasIndex(conversationId: string): boolean {
+ return registry.has(conversationId);
+}
+
+/** O(depth) walk from the branch tail up the parent chain */
+export function sumBranch(
+ conversationId: string,
+ tailId: string | null | undefined,
+ anchorId?: string | null,
+): BranchTotals {
+ const index = registry.get(conversationId);
+ if (!index || !tailId) {
+ return EMPTY_BRANCH;
+ }
+
+ const totals = { input: 0, output: 0, counted: 0, total: 0, containsAnchor: false };
+ let currentId: string | null = tailId;
+ let guard = index.size;
+
+ while (currentId && currentId !== Constants.NO_PARENT && guard-- > 0) {
+ const entry: TokenEntry | undefined = index.get(currentId);
+ if (!entry) {
+ break;
+ }
+ totals.total += 1;
+ if (anchorId != null && currentId === anchorId) {
+ totals.containsAnchor = true;
+ }
+ if (entry.tokenCount > 0) {
+ totals.counted += 1;
+ if (entry.isCreatedByUser) {
+ totals.input += entry.tokenCount;
+ } else {
+ totals.output += entry.tokenCount;
+ }
+ }
+ currentId = entry.parentMessageId;
+ }
+
+ return { ...totals, tailId };
+}
+
+/**
+ * Walks the branch tail up the parent chain and returns the first message id
+ * present in `anchors` — i.e. the deepest (most recent) stored snapshot anchor
+ * on the viewed branch. Used to recover a branch's granular breakdown after a
+ * later generation on a sibling branch overwrote the live snapshot.
+ */
+export function findBranchSnapshotAnchor(
+ conversationId: string,
+ tailId: string | null | undefined,
+ anchors: ReadonlyMap<string, unknown>,
+): string | null {
+ const index = registry.get(conversationId);
+ if (!index || !tailId || anchors.size === 0) {
+ return null;
+ }
+
+ let currentId: string | null = tailId;
+ let guard = index.size;
+
+ while (currentId && currentId !== Constants.NO_PARENT && guard-- > 0) {
+ if (anchors.has(currentId)) {
+ return currentId;
+ }
+ const entry: TokenEntry | undefined = index.get(currentId);
+ if (!entry) {
+ break;
+ }
+ currentId = entry.parentMessageId;
+ }
+
+ return null;
+}
+
+export interface ToolTokenGroups {
+ system: number;
+ mcp: number;
+ skills: number;
+ subagents: number;
+ systemDeferred: number;
+ mcpDeferred: number;
+}
+
+export const EMPTY_TOOL_GROUPS: ToolTokenGroups = {
+ system: 0,
+ mcp: 0,
+ skills: 0,
+ subagents: 0,
+ systemDeferred: 0,
+ mcpDeferred: 0,
+};
+
+/**
+ * Classifies per-tool schema tokens into display groups: built-in system
+ * tools, MCP tools, skills, and subagents — with deferred (on-demand) tools
+ * split out for the system/MCP groups.
+ */
+export function groupToolTokens(
+ toolTokenCounts?: Record<string, number>,
+ deferredToolNames?: string[],
+): ToolTokenGroups {
+ if (toolTokenCounts == null) {
+ return EMPTY_TOOL_GROUPS;
+ }
+ const deferred = new Set(deferredToolNames ?? []);
+ const groups = { ...EMPTY_TOOL_GROUPS };
+ for (const [name, tokens] of Object.entries(toolTokenCounts)) {
+ if (tokens <= 0) {
+ continue;
+ }
+ if (name === Tools.skill) {
+ groups.skills += tokens;
+ } else if (name === Constants.SUBAGENT) {
+ groups.subagents += tokens;
+ } else if (name.includes(Constants.mcp_delimiter)) {
+ if (deferred.has(name)) {
+ groups.mcpDeferred += tokens;
+ } else {
+ groups.mcp += tokens;
+ }
+ } else if (deferred.has(name)) {
+ groups.systemDeferred += tokens;
+ } else {
+ groups.system += tokens;
+ }
+ }
+ return groups;
+}
+
+function getOutputChars(part: unknown): number | null {
+ if (part == null || typeof part !== 'object') {
+ return null;
+ }
+ const { text, think } = part as { text?: unknown; think?: unknown };
+ if (typeof text === 'string') {
+ return text.length;
+ }
+ if (typeof think === 'string') {
+ return think.length;
+ }
+ return null;
+}
+
+/**
+ * Chars of the contiguous text/think parts at the very END of aggregated
+ * content — the output the model is actively producing on the current call,
+ * which the latest pre-invoke context snapshot does not yet account for.
+ *
+ * Crucially this does NOT skip a trailing tool-call part: once the model has
+ * emitted a tool call, that call's text is already folded into the next
+ * snapshot's `messageTokens`, so counting it would double-count against the
+ * snapshot. A tool call at the end therefore yields 0 (nothing new in flight).
+ */
+export function countTrailingOutputChars(content?: unknown[] | null): number {
+ if (!Array.isArray(content) || content.length === 0) {
+ return 0;
+ }
+ let chars = 0;
+ for (let i = content.length - 1; i >= 0; i--) {
+ const partChars = getOutputChars(content[i]);
+ if (partChars == null) {
+ break;
+ }
+ chars += partChars;
+ }
+ return chars;
+}
+
+/** Rough live estimate for streaming text, calibrated by the last known provider ratio */
+export function estimateTokens(charCount: number, calibrationRatio = 1): number {
+ if (charCount <= 0) {
+ return 0;
+ }
+ const ratio = calibrationRatio > 0 ? calibrationRatio : 1;
+ return Math.round((charCount / 4) * ratio);
+}
+
+/** Billable token quantities of one or more model calls, normalized for pricing */
+export interface CostUnits {
+ input: number;
+ output: number;
+ cacheWrite: number;
+ cacheRead: number;
+}
+
+/**
+ * Normalizes one call's usage into billable units, mirroring the backend's
+ * authoritative `splitUsage`/`resolveCompletionTokens`
+ * (packages/api/src/agents/usage.ts):
+ * - cache classification is by provider, not magnitude — Anthropic/Bedrock
+ * keep cache additive (input is uncached-only); subset providers fold
+ * cache into `input_tokens`. Falls back to a magnitude heuristic only when
+ * the provider is unknown.
+ * - completion is repaired for providers (e.g. Vertex) that under-report
+ * `output_tokens` but carry the gap in `total_tokens`.
+ * Applied per event so units stay correct when summed across calls.
+ */
+export function normalizeUsageUnits(usage: TTokenUsageEvent): CostUnits {
+ const rawInput = usage.input_tokens ?? 0;
+ const rawOutput = usage.output_tokens ?? 0;
+ const total = usage.total_tokens ?? 0;
+ const cacheWrite = usage.input_token_details?.cache_creation ?? 0;
+ const cacheRead = usage.input_token_details?.cache_read ?? 0;
+
+ const includesCache =
+ usage.provider != null
+ ? inputTokensIncludesCache(usage.provider)
+ : cacheWrite + cacheRead <= rawInput;
+
+ const cacheAdjustment = includesCache ? 0 : cacheRead + cacheWrite;
+ const output =
+ total > rawInput + rawOutput + cacheAdjustment ? total - rawInput - cacheAdjustment : rawOutput;
+
+ return {
+ input: includesCache ? Math.max(0, rawInput - cacheRead - cacheWrite) : rawInput,
+ output,
+ cacheWrite,
+ cacheRead,
+ };
+}
+
+export function formatTokens(count: number): string {
+ const formatted = new Intl.NumberFormat(undefined, {
+ notation: 'compact',
+ maximumFractionDigits: 1,
+ }).format(count);
+ return formatted.replace(/\.0(?=[A-Za-z]|$)/, '');
+}
+
+export function formatCost(usd: number): string {
+ if (usd <= 0) {
+ return '$0.00';
+ }
+ if (usd < 0.01) {
+ return '<$0.01';
+ }
+ if (usd < 1) {
+ return `$${usd.toFixed(4)}`;
+ }
+ return `$${usd.toFixed(2)}`;
+}
diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yaml
index c3e7774e06..bc96e37b4f 100644
--- a/e2e/config/librechat.e2e.yaml
+++ b/e2e/config/librechat.e2e.yaml
@@ -4,6 +4,11 @@
version: 1.3.11
cache: true
+interface:
+ # Exercises the cost row in the context usage gauge (off by default).
+ # Mock models price at the default rate, so synthetic usage yields a value.
+ contextCost: true
+
mcpServers:
e2e-memory:
type: stdio
diff --git a/e2e/config/librechat.real.yaml b/e2e/config/librechat.real.yaml
new file mode 100644
index 0000000000..7c8c3b4bd5
--- /dev/null
+++ b/e2e/config/librechat.real.yaml
@@ -0,0 +1,10 @@
+# Real-provider local e2e template. Used only by e2e/playwright.config.real.ts,
+# which requires ANTHROPIC_API_KEY in the invoking environment — the key is
+# passed through process env at runtime and never written to disk. Not wired
+# into CI; the mock workflow only runs playwright.config.mock.ts.
+version: 1.3.11
+cache: true
+
+interface:
+ # Exercise the cost row against real provider usage.
+ contextCost: true
diff --git a/e2e/playwright.config.real.ts b/e2e/playwright.config.real.ts
new file mode 100644
index 0000000000..d854155a04
--- /dev/null
+++ b/e2e/playwright.config.real.ts
@@ -0,0 +1,139 @@
+import { defineConfig, devices } from '@playwright/test';
+import fs from 'fs';
+import path from 'path';
+import { getLocalE2EEnv, getE2EBaseURL } from './setup/env';
+
+/**
+ * LOCAL-ONLY real-provider config: boots the same self-contained harness as
+ * the mock config (in-memory Mongo, seeded user, generated secrets) but runs
+ * real Anthropic calls — no fake-model hook. The API key is consumed from the
+ * invoking environment only; every other credential-like variable is blanked
+ * before the server boots, and nothing secret is written to disk.
+ *
+ * Run with:
+ * ANTHROPIC_API_KEY=... E2E_BASE_URL=http://localhost:3334 \
+ * npm run e2e:prepare && npx playwright test --config=e2e/playwright.config.real.ts
+ */
+if (!process.env.ANTHROPIC_API_KEY) {
+ throw new Error(
+ '[e2e:real] ANTHROPIC_API_KEY is required in the environment for the real-provider config.',
+ );
+}
+
+const rootPath = path.resolve(__dirname, '..');
+const serverPath = path.resolve(rootPath, 'e2e/setup/start-server.js');
+const configTemplatePath = path.resolve(rootPath, 'e2e/config/librechat.real.yaml');
+const configPath = path.resolve(rootPath, 'e2e/.generated/librechat.real.yaml');
+const reportPath = path.resolve(rootPath, 'e2e/playwright-report');
+
+const baseURL = getE2EBaseURL();
+const chromiumChannel = process.env.E2E_CHROMIUM_CHANNEL || undefined;
+
+const realModel = process.env.E2E_REAL_ANTHROPIC_MODEL ?? 'claude-haiku-4-5';
+
+const baseEnv = {
+ ...getLocalE2EEnv(),
+ CONFIG_PATH: configPath,
+ TENANT_ISOLATION_STRICT: 'false',
+ OPENAI_API_KEY: 'user_provided',
+ ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
+ /** Single deterministic model so the selector flow never drifts */
+ ANTHROPIC_MODELS: realModel,
+ OPENID_CLIENT_ID: '',
+ OPENID_ISSUER: '',
+ OPENID_AUTO_REDIRECT: 'false',
+ ALLOW_SOCIAL_LOGIN: 'false',
+ ALLOW_SOCIAL_REGISTRATION: 'false',
+ STREAM_KEEP_COMPLETED_JOBS: 'true',
+};
+
+const SECRET_KEY_PATTERN = /(API_KEY|SECRET|TOKEN|PASSWORD|CREDENTIALS|CLIENT_ID|_KEY)$/i;
+const preservedCredentialEnvKeys = new Set([
+ ...Object.keys(baseEnv),
+ 'E2E_USER_PASSWORD',
+ 'E2E_USER_B_PASSWORD',
+]);
+
+function writeRuntimeRealConfig() {
+ const template = fs.readFileSync(configTemplatePath, 'utf8');
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
+ fs.writeFileSync(configPath, template);
+}
+
+function neutralizeCredentialEnv(env: NodeJS.ProcessEnv, keep: Set<string>) {
+ for (const key of Object.keys(env)) {
+ if (!keep.has(key) && SECRET_KEY_PATTERN.test(key)) {
+ env[key] = '';
+ }
+ }
+}
+
+/** Blank any credential-like vars from a local `.env` so they never reach the test server. */
+function neutralizeDotenvSecrets(envFile: string, keep: Set<string>) {
+ if (!fs.existsSync(envFile)) {
+ return;
+ }
+ const lines = fs.readFileSync(envFile, 'utf8').split('\n');
+ for (const line of lines) {
+ const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/);
+ if (!match) {
+ continue;
+ }
+ const key = match[1];
+ if (keep.has(key)) {
+ continue;
+ }
+ if (SECRET_KEY_PATTERN.test(key)) {
+ process.env[key] = '';
+ }
+ }
+}
+
+writeRuntimeRealConfig();
+neutralizeCredentialEnv(process.env, preservedCredentialEnvKeys);
+Object.assign(process.env, baseEnv);
+neutralizeDotenvSecrets(path.resolve(rootPath, '.env'), preservedCredentialEnvKeys);
+
+export default defineConfig({
+ globalSetup: require.resolve('./setup/global-setup'),
+ globalTeardown: require.resolve('./setup/global-teardown.mock'),
+ testDir: 'specs/real/',
+ outputDir: 'specs/.test-results',
+ fullyParallel: false,
+ forbidOnly: true,
+ retries: 0,
+ workers: 1,
+ reporter: [['html', { outputFolder: reportPath, open: 'never' }], ['list']],
+ use: {
+ baseURL,
+ video: 'off',
+ trace: 'off',
+ ignoreHTTPSErrors: true,
+ headless: true,
+ storageState: path.resolve(process.cwd(), 'e2e/storageState.json'),
+ screenshot: 'only-on-failure',
+ },
+ expect: {
+ timeout: 15000,
+ },
+ projects: [
+ {
+ name: chromiumChannel ?? 'chromium',
+ use: {
+ ...devices['Desktop Chrome'],
+ ...(chromiumChannel ? { channel: chromiumChannel } : {}),
+ },
+ },
+ ],
+ webServer: [
+ {
+ command: `node ${serverPath}`,
+ cwd: rootPath,
+ url: baseURL,
+ stdout: 'pipe',
+ ignoreHTTPSErrors: true,
+ timeout: 120_000,
+ reuseExistingServer: false,
+ },
+ ],
+});
diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.js
index 9702f5282a..0e690a3679 100644
--- a/e2e/setup/fake-model.js
+++ b/e2e/setup/fake-model.js
@@ -10,6 +10,8 @@
* from the conversation and the agents' advertised tools.
*/
const { FakeChatModel } = require('@librechat/agents');
+const { ChatGenerationChunk } = require('@langchain/core/outputs');
+const { AIMessageChunk } = require('@langchain/core/messages');
const MOCK_REPLY = process.env.MOCK_LLM_REPLY || 'E2E mock reply: pong';
const CHUNK_DELAY_MS = Number(process.env.MOCK_LLM_CHUNK_DELAY_MS) || 10;
@@ -298,9 +300,41 @@ function replyResponses(text) {
return null;
}
+/**
+ * Attaches synthetic usage_metadata on a final empty chunk (the OpenAI
+ * streaming pattern) so token-usage SSE events flow end to end in mock runs.
+ */
+class UsageEmittingFakeChatModel extends FakeChatModel {
+ async *_streamResponseChunks(messages, options, runManager) {
+ let outputChars = 0;
+ for await (const chunk of super._streamResponseChunks(messages, options, runManager)) {
+ outputChars += typeof chunk.text === 'string' ? chunk.text.length : 0;
+ yield chunk;
+ }
+ const inputChars = (messages ?? []).reduce(
+ (sum, message) => sum + getContentText(message?.content).length,
+ 0,
+ );
+ const input_tokens = Math.max(1, Math.ceil(inputChars / 4));
+ const output_tokens = Math.max(1, Math.ceil(outputChars / 4));
+ yield new ChatGenerationChunk({
+ text: '',
+ message: new AIMessageChunk({
+ content: '',
+ usage_metadata: { input_tokens, output_tokens, total_tokens: input_tokens + output_tokens },
+ }),
+ });
+ }
+}
+
function overrideModel({ graph, responses, sleep, toolCalls, thrownError }) {
if (!thrownError) {
- graph.overrideTestModel(responses, sleep ?? CHUNK_DELAY_MS, toolCalls);
+ graph.overrideModel = new UsageEmittingFakeChatModel({
+ responses,
+ sleep: sleep ?? CHUNK_DELAY_MS,
+ emitCustomEvent: true,
+ toolCalls,
+ });
return;
}
diff --git a/e2e/specs/mock/usage.spec.ts b/e2e/specs/mock/usage.spec.ts
new file mode 100644
index 0000000000..ed376e4e04
--- /dev/null
+++ b/e2e/specs/mock/usage.spec.ts
@@ -0,0 +1,134 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import {
+ mockReply,
+ sendMessage,
+ messagesView,
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ isAgentsStream,
+ selectMockEndpoint,
+} from './helpers';
+
+const gauge = (page: Page) => page.getByTestId('token-usage');
+const gaugeMeter = (page: Page) => gauge(page).getByRole('meter');
+
+async function expectGaugeAboveZero(page: Page) {
+ await expect(gauge(page)).toBeVisible({ timeout: 20000 });
+ await expect(gaugeMeter(page)).toHaveAttribute('aria-valuenow', /[1-9]/, { timeout: 20000 });
+}
+
+/** Opens the gauge hover popover and returns its region locator. */
+async function openBreakdown(page: Page) {
+ await expectGaugeAboveZero(page);
+ await gauge(page).hover();
+ const popover = page.getByRole('region', { name: 'Context usage' });
+ await expect(popover).toBeVisible({ timeout: 10000 });
+ return popover;
+}
+
+/** Granularity lives only in the live `on_context_usage` snapshot; its rows
+ * render under the `context-breakdown` testid, the coarse message-history
+ * fallback under `context-estimate`. They are mutually exclusive. */
+async function expectGranular(page: Page) {
+ const popover = await openBreakdown(page);
+ await expect(popover.getByTestId('context-breakdown')).toBeVisible({ timeout: 10000 });
+ await expect(popover.getByTestId('context-estimate')).toHaveCount(0);
+ await expect(popover.getByText('Messages', { exact: true })).toBeVisible();
+ await expect(popover.getByText('Free space', { exact: true })).toBeVisible();
+}
+
+async function sendAndAwaitReply(page: Page, text: string) {
+ const response = await sendMessage(page, text);
+ expect(response.ok()).toBeTruthy();
+ await expect(mockReply(page)).toBeVisible({ timeout: 20000 });
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+}
+
+test.describe('context usage gauge', () => {
+ test('tracks usage from live SSE events and survives reload', async ({ page }) => {
+ test.setTimeout(120000);
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+
+ // REQUIRED so the message streams without a real key.
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ const response = await sendMessage(page, 'hello');
+ expect(response.ok()).toBeTruthy();
+ await expect(mockReply(page)).toBeVisible({ timeout: 20000 });
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+
+ /** Live path: the agents pipeline's context snapshot + usage events fill the gauge */
+ await expectGaugeAboveZero(page);
+
+ /** Breakdown popover: context section always; the usage section is
+ * scoped by testid since the pre-snapshot fallback renders its own
+ * Input/Output rows when the lib predates on_context_usage */
+ await gauge(page).hover();
+ const popover = page.getByRole('region', { name: 'Context usage' });
+ await expect(popover).toBeVisible({ timeout: 10000 });
+ await expect(popover.getByText('Context window')).toBeVisible();
+ const usageSection = popover.getByTestId('token-usage-totals');
+ await expect(usageSection).toBeVisible({ timeout: 10000 });
+ await expect(usageSection.getByText('Input', { exact: true })).toBeVisible();
+ await expect(usageSection.getByText('Output', { exact: true })).toBeVisible();
+
+ /** Cost row: interface.contextCost is enabled in the harness yaml, the
+ * token-config endpoint prices mock models at the default rate, and
+ * the fake model emits usage — so a $ value must render */
+ await expect(popover.getByText('Session cost')).toBeVisible();
+ await expect(popover.getByText(/\$\d|<\$0\.01/)).toBeVisible();
+ await page.keyboard.press('Escape');
+
+ /** Fallback path: after reload there is no snapshot — the gauge rebuilds
+ * from per-message tokenCount history returned by the messages query */
+ await page.reload({ timeout: 15000 });
+ await expect(mockReply(page)).toBeVisible({ timeout: 20000 });
+ await expectGaugeAboveZero(page);
+ });
+
+ test('renders the granular breakdown from the live context snapshot', async ({ page }) => {
+ test.setTimeout(120000);
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ await sendAndAwaitReply(page, 'hello');
+
+ /** The agents pipeline emits on_context_usage on each model call, so the
+ * breakdown — not the estimate fallback — drives the popover. */
+ await expectGranular(page);
+ });
+
+ test('preserves the granular breakdown after switching branches', async ({ page }) => {
+ test.setTimeout(150000);
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ await sendAndAwaitReply(page, 'hello');
+
+ /** Branch A: the just-generated branch shows its live snapshot. */
+ await expectGranular(page);
+ await page.keyboard.press('Escape');
+
+ /** Regenerate to create a sibling branch (B), which overwrites the single
+ * live snapshot and anchors it to B's response (proven selectors mirror
+ * chat.spec.ts's branch test). */
+ const assistantMessage = messagesView(page).locator('.message-render').nth(1);
+ await assistantMessage.hover();
+ const regenerateButton = assistantMessage.locator('button[title="Regenerate"]').last();
+ await expect(regenerateButton).toBeVisible();
+ const [regen] = await Promise.all([
+ page.waitForResponse(isAgentsStream, { timeout: 30000 }),
+ regenerateButton.click(),
+ ]);
+ expect(regen.ok()).toBeTruthy();
+ await expect(page.getByText('2 / 2')).toBeVisible({ timeout: 20000 });
+
+ /** Switch back to branch A. Its live snapshot was overwritten by B, so the
+ * rows can only survive via the per-anchor snapshot history map. */
+ await page.getByRole('button', { name: 'Previous sibling message' }).click();
+ await expect(page.getByText('1 / 2')).toBeVisible({ timeout: 10000 });
+
+ await expectGranular(page);
+ });
+});
diff --git a/e2e/specs/real/usage.spec.ts b/e2e/specs/real/usage.spec.ts
new file mode 100644
index 0000000000..f7cedbe1ae
--- /dev/null
+++ b/e2e/specs/real/usage.spec.ts
@@ -0,0 +1,122 @@
+import { expect, test } from '@playwright/test';
+import type { Page, TestInfo } from '@playwright/test';
+import { sendMessage, selectMockEndpoint } from '../mock/helpers';
+
+/**
+ * LOCAL-ONLY real-provider verification: drives multiple turns against real
+ * Anthropic and asserts the context gauge tracks genuine provider usage.
+ * Runs only via e2e/playwright.config.real.ts (requires ANTHROPIC_API_KEY).
+ */
+
+const REAL_MODEL = process.env.E2E_REAL_ANTHROPIC_MODEL ?? 'claude-haiku-4-5';
+
+const gauge = (page: Page) => page.getByTestId('token-usage');
+const gaugeMeter = (page: Page) => gauge(page).getByRole('meter');
+const popover = (page: Page) => page.getByRole('region', { name: 'Context usage' });
+
+async function gaugeValue(page: Page): Promise<number> {
+ const raw = await gaugeMeter(page).getAttribute('aria-valuenow');
+ const value = Number(raw);
+ expect(Number.isFinite(value)).toBe(true);
+ return value;
+}
+
+/** Parses formatTokens output ("950", "1.2K", "2M") back to a number. */
+function parseTokens(text: string): number {
+ const match = text.trim().match(/^([\d.]+)([KM])?/i);
+ if (!match) {
+ return NaN;
+ }
+ const suffix = match[2]?.toUpperCase();
+ let scale = 1;
+ if (suffix === 'M') {
+ scale = 1e6;
+ } else if (suffix === 'K') {
+ scale = 1e3;
+ }
+ return parseFloat(match[1]) * scale;
+}
+
+async function readUsageTotals(page: Page): Promise<{ input: number; output: number }> {
+ await gauge(page).hover();
+ const section = popover(page).getByTestId('token-usage-totals');
+ await expect(section).toBeVisible({ timeout: 15000 });
+ const rows = section.locator('div');
+ const input = parseTokens(
+ (await rows.filter({ hasText: 'Input' }).first().locator('span').last().innerText()) ?? '',
+ );
+ const output = parseTokens(
+ (await rows.filter({ hasText: 'Output' }).first().locator('span').last().innerText()) ?? '',
+ );
+ await page.keyboard.press('Escape');
+ return { input, output };
+}
+
+async function sendTurn(page: Page, text: string) {
+ const response = await sendMessage(page, text);
+ expect(response.ok()).toBeTruthy();
+ /** Settle: streaming over once the stop button yields back to send */
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden({
+ timeout: 90000,
+ });
+ await expect(page.getByTestId('send-button')).toBeVisible({ timeout: 30000 });
+}
+
+test.describe('context usage gauge with a real provider', () => {
+ test('grows across turns and reflects real usage', async ({ page }, testInfo: TestInfo) => {
+ test.setTimeout(300000);
+ await page.goto('/c/new', { timeout: 15000 });
+
+ await selectMockEndpoint(page, { label: 'Anthropic', model: REAL_MODEL } as never);
+
+ /** Turn 1 */
+ await sendTurn(page, 'Reply with exactly one word: alpha');
+ await expect(gauge(page)).toBeVisible({ timeout: 20000 });
+ const v1 = await gaugeValue(page);
+ expect(v1).toBeGreaterThan(0);
+ const totals1 = await readUsageTotals(page);
+ expect(totals1.input).toBeGreaterThan(0);
+ expect(totals1.output).toBeGreaterThan(0);
+ await gauge(page).hover();
+ await expect(popover(page).getByText('Messages')).toBeVisible();
+ await expect(popover(page).getByText('Free space')).toBeVisible();
+ await expect(popover(page).getByText('Session cost')).toBeVisible();
+ await expect(popover(page).getByText(/\$\d|<\$0\.01/)).toBeVisible();
+ await page.screenshot({ path: testInfo.outputPath('turn1-popover.png') });
+ await page.keyboard.press('Escape');
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+
+ /** Turn 2: context must include turn 1 — gauge and totals grow */
+ await sendTurn(page, 'Reply with exactly one word: beta');
+ const v2 = await gaugeValue(page);
+ expect(v2).toBeGreaterThan(v1);
+ const totals2 = await readUsageTotals(page);
+ expect(totals2.input).toBeGreaterThan(totals1.input);
+ expect(totals2.output).toBeGreaterThan(totals1.output);
+
+ /** Turn 3 */
+ await sendTurn(page, 'Reply with exactly one word: gamma');
+ const v3 = await gaugeValue(page);
+ expect(v3).toBeGreaterThan(v2);
+ await gauge(page).hover();
+ await expect(popover(page)).toBeVisible({ timeout: 15000 });
+ await page.screenshot({ path: testInfo.outputPath('turn3-popover.png') });
+ await page.keyboard.press('Escape');
+
+ /** Reload: gauge rebuilds from persisted per-message token counts once
+ * the messages query resolves — retry until the meter leaves zero */
+ await page.reload({ timeout: 20000 });
+ await expect(gauge(page)).toBeVisible({ timeout: 20000 });
+ await expect(gaugeMeter(page)).toHaveAttribute('aria-valuenow', /[1-9]/, { timeout: 20000 });
+ const vReload = await gaugeValue(page);
+ expect(vReload).toBeGreaterThan(0);
+ await gauge(page).hover();
+ await expect(popover(page)).toBeVisible({ timeout: 15000 });
+ await page.screenshot({ path: testInfo.outputPath('reload-popover.png') });
+
+ testInfo.annotations.push({
+ type: 'observed',
+ description: `v1=${v1} v2=${v2} v3=${v3} reload=${vReload} input1=${totals1.input} input2=${totals2.input}`,
+ });
+ });
+});
diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.ts
index 9dc39176ec..b3a3205c00 100644
--- a/packages/api/src/agents/initialize.ts
+++ b/packages/api/src/agents/initialize.ts
@@ -23,7 +23,12 @@ import type {
import type { GenericTool, LCToolRegistry, ToolMap, LCTool } from '@librechat/agents';
import type { Response as ServerResponse } from 'express';
import type { IMongoFile } from '@librechat/data-schemas';
-import type { InitializeResultBase, ServerRequest, EndpointDbMethods } from '~/types';
+import type {
+ ServerRequest,
+ EndpointDbMethods,
+ EndpointTokenConfig,
+ InitializeResultBase,
+} from '~/types';
import type { LCAvailableTools, RequestScopedMCPConnectionStore } from '../mcp/types';
import type { ResolvedManualSkill, ResolvedAlwaysApplySkill } from './skills';
import type { TFilterFilesByAgentAccess } from './resources';
@@ -311,6 +316,13 @@ export type InitializedAgent = Agent & {
* call #1 the sandbox can't see the files at all.
*/
primedCodeFiles?: import('@librechat/agents').CodeEnvFile[];
+ /**
+ * Resolved token/pricing config for this agent's endpoint (admin static
+ * `tokenConfig` and/or fetched custom-endpoint config). Surfaced from the
+ * provider `getOptions` result so the AgentClient bills, prices, and resolves
+ * context limits with the same numbers the UI shows — not default rates.
+ */
+ endpointTokenConfig?: EndpointTokenConfig;
};
export const DEFAULT_MAX_CONTEXT_TOKENS = 32000;
@@ -1230,6 +1242,7 @@ export async function initializeAgent(
? maxContextTokens
: Math.max(1024, Math.round(baseContextTokens * (1 - DEFAULT_RESERVE_RATIO))),
primedCodeFiles,
+ endpointTokenConfig: options.endpointTokenConfig,
};
return initializedAgent;
diff --git a/packages/api/src/agents/usage.spec.ts b/packages/api/src/agents/usage.spec.ts
index ab6c910270..177063b95e 100644
--- a/packages/api/src/agents/usage.spec.ts
+++ b/packages/api/src/agents/usage.spec.ts
@@ -1,7 +1,7 @@
import type { RecordUsageDeps, RecordUsageParams, SubagentUsageEvent } from './usage';
import type { UsageMetadata } from '../stream/interfaces/IJobStore';
import type { BulkWriteDeps, PricingFns } from './transactions';
-import { createSubagentUsageSink, recordCollectedUsage } from './usage';
+import { computeUsageCostUSD, createSubagentUsageSink, recordCollectedUsage } from './usage';
describe('recordCollectedUsage', () => {
let mockSpendTokens: jest.Mock;
@@ -205,6 +205,25 @@ describe('recordCollectedUsage', () => {
);
});
+ it('bills hidden sequential-agent usage but excludes it from reported totals', async () => {
+ const collectedUsage: UsageMetadata[] = [
+ { usage_type: 'message', input_tokens: 120, output_tokens: 40, model: 'gpt-4' },
+ { usage_type: 'sequential', input_tokens: 800, output_tokens: 250, model: 'gpt-4' },
+ ];
+
+ const result = await recordCollectedUsage(deps, { ...baseParams, collectedUsage });
+
+ /** Hidden intermediate output stays out of the parent's tokenCount... */
+ expect(result).toEqual({ input_tokens: 120, output_tokens: 40 });
+ /** ...but is still billed under its own context. */
+ expect(mockSpendTokens).toHaveBeenCalledTimes(2);
+ expect(mockSpendTokens).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ context: 'sequential', model: 'gpt-4' }),
+ { promptTokens: 800, completionTokens: 250 },
+ );
+ });
+
it('does not let a leading subagent entry hijack reported input_tokens', async () => {
const collectedUsage: UsageMetadata[] = [
{
@@ -1437,3 +1456,50 @@ describe('createSubagentUsageSink', () => {
expect(result).toEqual({ input_tokens: 120, output_tokens: 40 });
});
});
+
+describe('computeUsageCostUSD', () => {
+ /** Stub pricing: base prompt 3 / completion 15, cache write 3.75 / read 0.3;
+ * a premium tier above 200k input prompt tokens (8 / 40). Mirrors the
+ * shape of the real getMultiplier(inputTokenCount) premium switch. */
+ const pricing: PricingFns = {
+ getMultiplier: ({ tokenType, inputTokenCount }) => {
+ const premium = (inputTokenCount ?? 0) > 200000;
+ if (tokenType === 'completion') {
+ return premium ? 40 : 15;
+ }
+ return premium ? 8 : 3;
+ },
+ getCacheMultiplier: ({ cacheType }) => (cacheType === 'write' ? 3.75 : 0.3),
+ };
+
+ it('prices a standard call at base rates', () => {
+ const cost = computeUsageCostUSD(
+ { input_tokens: 1000, output_tokens: 500, model: 'gpt-4', provider: 'openAI' },
+ pricing,
+ );
+ expect(cost).toBeCloseTo((1000 * 3 + 500 * 15) / 1e6);
+ });
+
+ it('applies the premium tier when the call exceeds the input threshold', () => {
+ /** The exact gap finding A flagged: a long-context call bills premium */
+ const cost = computeUsageCostUSD(
+ { input_tokens: 300000, output_tokens: 1000, model: 'gpt-5.5', provider: 'openAI' },
+ pricing,
+ );
+ expect(cost).toBeCloseTo((300000 * 8 + 1000 * 40) / 1e6);
+ });
+
+ it('prices additive cache tokens (Anthropic) at cache rates', () => {
+ const cost = computeUsageCostUSD(
+ {
+ input_tokens: 1000,
+ output_tokens: 500,
+ model: 'claude-haiku-4-5',
+ provider: 'anthropic',
+ input_token_details: { cache_creation: 2000, cache_read: 10000 },
+ },
+ pricing,
+ );
+ expect(cost).toBeCloseTo((1000 * 3 + 2000 * 3.75 + 10000 * 0.3 + 500 * 15) / 1e6);
+ });
+});
diff --git a/packages/api/src/agents/usage.ts b/packages/api/src/agents/usage.ts
index bd220562a2..d6252841a7 100644
--- a/packages/api/src/agents/usage.ts
+++ b/packages/api/src/agents/usage.ts
@@ -1,5 +1,5 @@
import { logger } from '@librechat/data-schemas';
-import { Providers } from 'librechat-data-provider';
+import { inputTokensIncludesCache } from 'librechat-data-provider';
import type { TCustomConfig, TTransactionsConfig } from 'librechat-data-provider';
import type {
StructuredTokenUsage,
@@ -23,33 +23,6 @@ type SpendStructuredTokensFn = (
tokenUsage: StructuredTokenUsage,
) => Promise<unknown>;
-/**
- * Providers whose `usage_metadata.input_tokens` ALREADY INCLUDES cached tokens
- * (i.e. `input_token_details.cache_*` is a subset, not an additional charge):
- *
- * - Google / Vertex AI: `input_tokens` = `promptTokenCount` (includes `cachedContentTokenCount`)
- * - OpenAI / Azure OpenAI: `input_tokens` = `prompt_tokens` (includes `prompt_tokens_details.cached_tokens`)
- * - xAI, DeepSeek, OpenRouter, Moonshot: extend `ChatOpenAI`, same semantics
- *
- * Anthropic and Bedrock keep cache values separate from `input_tokens`, so they
- * must be added back to compute the total prompt size — that's the historical
- * additive default. Providers not listed here fall through to additive.
- */
-const SUBSET_PROVIDERS: ReadonlySet<string> = new Set([
- Providers.OPENAI,
- Providers.AZURE,
- Providers.GOOGLE,
- Providers.VERTEXAI,
- Providers.XAI,
- Providers.DEEPSEEK,
- Providers.OPENROUTER,
- Providers.MOONSHOT,
-]);
-
-function inputTokensIncludesCache(provider?: string): boolean {
- return provider != null && SUBSET_PROVIDERS.has(provider);
-}
-
/**
* Resolves `completionTokens` for billing, repairing providers whose
* `usage_metadata.output_tokens` undercounts.
@@ -143,6 +116,47 @@ export interface RecordUsageDeps {
bulkWriteOps?: BulkWriteDeps;
}
+/**
+ * Authoritative USD cost of one model call. Reuses the exact billing
+ * functions (`prepareTokenSpend`/`prepareStructuredTokenSpend` → `getMultiplier`
+ * with `inputTokenCount` for premium tiers) so the figure emitted to the
+ * client matches what is charged against balance — the client must not
+ * re-derive pricing from base rates. `tokenValue` is credits (USD × 1e6).
+ */
+export function computeUsageCostUSD(
+ usage: UsageMetadata,
+ pricing: PricingFns,
+ endpointTokenConfig?: EndpointTokenConfig,
+): number {
+ const { inputOnly, cacheCreation, cacheRead, completion } = splitUsage(usage);
+ /** user/context/conversationId only populate the transaction doc, which is
+ * discarded here — only `tokenValue` (credits) is summed */
+ const txData: TxMetadata = {
+ user: '',
+ context: 'message',
+ conversationId: '',
+ model: usage.model,
+ endpointTokenConfig,
+ };
+ const entries =
+ cacheCreation > 0 || cacheRead > 0
+ ? prepareStructuredTokenSpend(
+ txData,
+ {
+ promptTokens: { input: inputOnly, write: cacheCreation, read: cacheRead },
+ completionTokens: completion,
+ },
+ pricing,
+ )
+ : prepareTokenSpend(
+ txData,
+ { promptTokens: inputOnly, completionTokens: completion },
+ pricing,
+ );
+ const credits = entries.reduce((sum, entry) => sum + Math.abs(entry.tokenValue), 0);
+ return credits / 1e6;
+}
+
export interface RecordUsageParams {
user: string;
conversationId: string;
@@ -190,6 +204,9 @@ export async function recordCollectedUsage(
const messageUsages: UsageMetadata[] = [];
const summarizationUsages: UsageMetadata[] = [];
const subagentUsages: UsageMetadata[] = [];
+ /** Hidden sequential-agent calls: billed, but excluded from the reported
+ * output total since their output never reaches the visible message */
+ const sequentialUsages: UsageMetadata[] = [];
for (const usage of collectedUsage) {
if (usage == null) {
continue;
@@ -198,6 +215,8 @@ export async function recordCollectedUsage(
summarizationUsages.push(usage);
} else if (usage.usage_type === 'subagent') {
subagentUsages.push(usage);
+ } else if (usage.usage_type === 'sequential') {
+ sequentialUsages.push(usage);
} else {
messageUsages.push(usage);
}
@@ -310,6 +329,7 @@ export async function recordCollectedUsage(
* distort next-turn context accounting by orders of magnitude.
*/
processUsageGroup(subagentUsages, 'subagent', allDocs, { excludeFromOutputTotal: true });
+ processUsageGroup(sequentialUsages, 'sequential', allDocs, { excludeFromOutputTotal: true });
if (useBulk && allDocs.length > 0) {
try {
await bulkWriteTransactions({ user, docs: allDocs }, bulkWriteOps);
@@ -360,6 +380,7 @@ export interface SubagentUsageEvent {
*/
export function createSubagentUsageSink(
collectedUsage: UsageMetadata[],
+ onUsage?: (usage: UsageMetadata) => void,
): (event: SubagentUsageEvent) => void {
return (event) => {
if (event?.usage == null) {
@@ -373,5 +394,9 @@ export function createSubagentUsageSink(
usage.provider = event.provider;
}
collectedUsage.push(usage);
+ /** Lets the host stream the billed child usage to the client (tagged
+ * `subagent`, so it folds into session cost/totals but not the live
+ * gauge) — child runs never reach ModelEndHandler's emit path. */
+ onUsage?.(usage);
};
}
diff --git a/packages/api/src/endpoints/config/models.ts b/packages/api/src/endpoints/config/models.ts
index 6bd47d10ca..30dfa8767d 100644
--- a/packages/api/src/endpoints/config/models.ts
+++ b/packages/api/src/endpoints/config/models.ts
@@ -11,6 +11,8 @@ import type { AppConfig } from '@librechat/data-schemas';
import type { ServerRequest, GetUserKeyValuesFunction, UserKeyValues } from '~/types';
import type { FetchModelsParams } from '~/endpoints/models';
import { fetchModels as defaultFetchModels } from '~/endpoints/models';
+import { getTokenConfigKey } from '~/endpoints/custom/initialize';
+import { tokenConfigCache } from '~/cache';
import { isUserProvided } from '~/utils';
/**
@@ -96,6 +98,9 @@ export function createLoadConfigModels(deps: LoadConfigModelsDeps) {
const fetchPromisesMap: Record<string, Promise<string[]>> = {};
const uniqueKeyToEndpointsMap: Record<string, string[]> = {};
+ /** tokenKey the deduped fetch cached its token config under, so siblings
+ * sharing the fetch can be backfilled with the same config afterward */
+ const uniqueKeyToTokenKey: Record<string, string> = {};
const endpointsMap: Record<string, TEndpoint> = {};
const resolved: ResolvedEndpoint[] = [];
@@ -174,9 +179,12 @@ export function createLoadConfigModels(deps: LoadConfigModelsDeps) {
const uniqueKey = `${BASE_URL}__${API_KEY}__${headersFingerprint(endpointHeaders)}`;
if (models?.fetch && !apiKeyIsUserProvided && !baseURLIsUserProvided) {
- fetchPromisesMap[uniqueKey] =
- fetchPromisesMap[uniqueKey] ||
- fetchModels({
+ if (!fetchPromisesMap[uniqueKey]) {
+ /** User-scoped when configured headers resolve per user — the
+ * derived token config must not be cached under the shared name */
+ const tokenKey = getTokenConfigKey(endpoint, name, req.user?.id ?? '');
+ uniqueKeyToTokenKey[uniqueKey] = tokenKey;
+ fetchPromisesMap[uniqueKey] = fetchModels({
name,
apiKey: API_KEY,
baseURL: BASE_URL,
@@ -185,7 +193,9 @@ export function createLoadConfigModels(deps: LoadConfigModelsDeps) {
headers: endpointHeaders,
direct: endpoint.directEndpoint,
userIdQuery: models.userIdQuery,
+ tokenKey,
});
+ }
uniqueKeyToEndpointsMap[uniqueKey] = uniqueKeyToEndpointsMap[uniqueKey] || [];
uniqueKeyToEndpointsMap[uniqueKey].push(name);
continue;
@@ -216,6 +226,8 @@ export function createLoadConfigModels(deps: LoadConfigModelsDeps) {
direct: endpoint.directEndpoint,
userIdQuery: models.userIdQuery,
skipCache: true,
+ /** Fetched with the user's key/URL — always user-scoped */
+ tokenKey: getTokenConfigKey(endpoint, name, req.user?.id ?? ''),
});
uniqueKeyToEndpointsMap[userFetchKey] = uniqueKeyToEndpointsMap[userFetchKey] || [];
uniqueKeyToEndpointsMap[userFetchKey].push(name);
@@ -249,6 +261,23 @@ export function createLoadConfigModels(deps: LoadConfigModelsDeps) {
);
modelsConfig[name] = !modelData?.length ? defaults : modelData;
}
+
+ /** A shared fetch caches token config under one endpoint's tokenKey;
+ * copy it to the siblings so /token-config resolves each by its own
+ * name (the query is staleTime:Infinity and won't recover otherwise) */
+ const winnerTokenKey = uniqueKeyToTokenKey[currentKey];
+ if (settled.status === 'fulfilled' && winnerTokenKey != null && associatedNames.length > 1) {
+ const cache = tokenConfigCache();
+ const config = await cache.get(winnerTokenKey);
+ if (config != null) {
+ for (const name of associatedNames) {
+ const siblingKey = getTokenConfigKey(endpointsMap[name], name, req.user?.id ?? '');
+ if (siblingKey !== winnerTokenKey) {
+ await cache.set(siblingKey, config);
+ }
+ }
+ }
+ }
}
return modelsConfig;
diff --git a/packages/api/src/endpoints/custom/initialize.spec.ts b/packages/api/src/endpoints/custom/initialize.spec.ts
index cafb06ec19..c9d05a3001 100644
--- a/packages/api/src/endpoints/custom/initialize.spec.ts
+++ b/packages/api/src/endpoints/custom/initialize.spec.ts
@@ -351,4 +351,46 @@ describe('initializeCustom – token-config fetch header forwarding', () => {
}),
);
});
+
+ it('uses a static tokenConfig for billing and skips the model fetch', async () => {
+ const tokenConfig = {
+ 'gpt-4': { prompt: 1.5, completion: 4.5, context: 32000, cacheRead: 0.3, cacheWrite: 1.8 },
+ };
+ mockGetCustomEndpointConfig.mockReturnValue({
+ apiKey: 'sk-test-key',
+ baseURL: 'https://openrouter.ai/api/v1',
+ models: { fetch: true },
+ tokenConfig,
+ });
+
+ const params: BaseInitializeParams = {
+ req: {
+ user: { id: 'user-1', email: '[email protected]' },
+ body: { key: '2099-01-01' },
+ config: {},
+ } as unknown as BaseInitializeParams['req'],
+ endpoint: 'openrouter',
+ model_parameters: { model: 'gpt-4' },
+ db: {
+ getUserKeyValues: jest.fn(),
+ } as unknown as BaseInitializeParams['db'],
+ };
+
+ const result = (await initializeCustom(params)) as {
+ endpointTokenConfig?: Record<string, Record<string, number>>;
+ };
+
+ expect(fetchModels).not.toHaveBeenCalled();
+ /** Original rates pass through, plus the billing-shape cache keys so
+ * getCacheMultiplier (which reads `write`/`read`) finds them */
+ expect(result.endpointTokenConfig?.['gpt-4']).toEqual({
+ prompt: 1.5,
+ completion: 4.5,
+ context: 32000,
+ cacheRead: 0.3,
+ cacheWrite: 1.8,
+ write: 1.8,
+ read: 0.3,
+ });
+ });
});
diff --git a/packages/api/src/endpoints/custom/initialize.ts b/packages/api/src/endpoints/custom/initialize.ts
index 19d4e2c35e..0f83794920 100644
--- a/packages/api/src/endpoints/custom/initialize.ts
+++ b/packages/api/src/endpoints/custom/initialize.ts
@@ -16,6 +16,49 @@ import { tokenConfigCache } from '~/cache';
const { PROXY } = process.env;
+/**
+ * Cache key for an endpoint's fetched token config. User-scoped when the
+ * model fetch can resolve per-user: user-provided key/URL, or header
+ * templates forwarded against an admin-trusted base URL — making the
+ * response, and therefore the derived token config, user-specific.
+ */
+export function getTokenConfigKey(
+ endpointConfig: Partial<TEndpoint>,
+ endpoint: string,
+ userId: string,
+): string {
+ const hasTokenConfig = endpointConfig.tokenConfig != null;
+ const userProvidesKey = isUserProvided(extractEnvVariable(endpointConfig.apiKey ?? ''));
+ const userProvidesURL = isUserProvided(extractEnvVariable(endpointConfig.baseURL ?? ''));
+ const willForwardUserScopedHeaders = !!endpointConfig?.headers && !userProvidesURL;
+ return !hasTokenConfig && (userProvidesKey || userProvidesURL || willForwardUserScopedHeaders)
+ ? `${endpoint}:${userId}`
+ : endpoint;
+}
+
+/**
+ * Maps an admin-facing static `tokenConfig` to the billing shape: the UI uses
+ * `cacheWrite`/`cacheRead`, but `getCacheMultiplier` indexes `write`/`read`.
+ * Adds those keys (preserving the originals) so cache tokens bill at the
+ * configured rate instead of the prompt-rate fallback.
+ */
+function toBillingTokenConfig(
+ tokenConfig: Record<string, Record<string, number>>,
+): EndpointTokenConfig {
+ const result: EndpointTokenConfig = {};
+ for (const [model, rates] of Object.entries(tokenConfig)) {
+ const mapped = { ...rates } as Record<string, number>;
+ if (rates.cacheWrite != null) {
+ mapped.write = rates.cacheWrite;
+ }
+ if (rates.cacheRead != null) {
+ mapped.read = rates.cacheRead;
+ }
+ result[model] = mapped as EndpointTokenConfig[string];
+ }
+ return result;
+}
+
/**
* Builds custom options from endpoint configuration
*/
@@ -136,26 +179,23 @@ export async function initializeCustom({
const userId = req.user?.id ?? '';
const cache = tokenConfigCache();
- /** tokenConfig is an optional extended property on custom endpoints */
- const hasTokenConfig = (endpointConfig as Record<string, unknown>).tokenConfig != null;
- // When `endpointConfig.headers` will be forwarded to the model fetch (i.e.
- // base URL is admin-trusted, so the security guard below leaves them in
- // place), header templates may resolve against the current user — making
- // the response, and therefore the derived token config, user-specific.
- // User-scope the token-config cache key in that case so a cached entry
- // for one user can't be served to another.
- const willForwardUserScopedHeaders = !!endpointConfig?.headers && !userProvidesURL;
- const tokenKey =
- !hasTokenConfig && (userProvidesKey || userProvidesURL || willForwardUserScopedHeaders)
- ? `${endpoint}:${userId}`
- : endpoint;
-
- const cachedConfig =
- !hasTokenConfig &&
- FetchTokenConfig[endpoint.toLowerCase() as keyof typeof FetchTokenConfig] &&
- (await cache.get(tokenKey));
-
- endpointTokenConfig = (cachedConfig as EndpointTokenConfig) || undefined;
+ const hasTokenConfig = endpointConfig.tokenConfig != null;
+ const tokenKey = getTokenConfigKey(endpointConfig, endpoint, userId);
+
+ if (hasTokenConfig) {
+ /** A static override is authoritative — use it for the agent's billing
+ * and balance checks, not just the advertised UI token config. Mirror
+ * the admin-facing `cacheWrite`/`cacheRead` keys onto the `write`/`read`
+ * keys the billing multiplier reads. */
+ endpointTokenConfig = toBillingTokenConfig(
+ endpointConfig.tokenConfig as Record<string, Record<string, number>>,
+ );
+ } else {
+ const cachedConfig =
+ FetchTokenConfig[endpoint.toLowerCase() as keyof typeof FetchTokenConfig] &&
+ (await cache.get(tokenKey));
+ endpointTokenConfig = (cachedConfig as EndpointTokenConfig) || undefined;
+ }
if (
FetchTokenConfig[endpoint.toLowerCase() as keyof typeof FetchTokenConfig] &&
diff --git a/packages/api/src/endpoints/index.ts b/packages/api/src/endpoints/index.ts
index 208181168e..9e6e9dbac0 100644
--- a/packages/api/src/endpoints/index.ts
+++ b/packages/api/src/endpoints/index.ts
@@ -5,3 +5,5 @@ export * from './custom';
export * from './google';
export * from './models';
export * from './openai';
+export * from './pricing';
+export * from './tokenConfig';
diff --git a/packages/api/src/endpoints/pricing.spec.ts b/packages/api/src/endpoints/pricing.spec.ts
new file mode 100644
index 0000000000..388b71a509
--- /dev/null
+++ b/packages/api/src/endpoints/pricing.spec.ts
@@ -0,0 +1,119 @@
+import mongoose from 'mongoose';
+import { EModelEndpoint } from 'librechat-data-provider';
+import { createTxMethods } from '@librechat/data-schemas';
+import type { EndpointTokenConfig } from '~/types';
+import { matchModelName, findMatchingPattern } from '~/utils';
+import { buildTokenConfigMap } from './pricing';
+
+/** Adapters: TxDeps types are looser than the utils signatures (string endpoint, undefined miss) */
+const { getValueKey, getMultiplier, getCacheMultiplier } = createTxMethods(mongoose, {
+ matchModelName: (model, endpoint) => matchModelName(model, endpoint as EModelEndpoint),
+ findMatchingPattern: (model, values) =>
+ findMatchingPattern(model, values as Record<string, number>) ?? undefined,
+});
+
+const deps = { getValueKey, getMultiplier, getCacheMultiplier };
+
+describe('buildTokenConfigMap', () => {
+ it('resolves context windows without pricing by default', () => {
+ const map = buildTokenConfigMap(
+ {
+ modelsConfig: {
+ [EModelEndpoint.openAI]: ['gpt-4o'],
+ [EModelEndpoint.anthropic]: ['claude-3-5-sonnet-20241022'],
+ },
+ },
+ deps,
+ );
+
+ expect(map[EModelEndpoint.openAI]['gpt-4o'].context).toBeGreaterThan(100000);
+ expect(map[EModelEndpoint.anthropic]['claude-3-5-sonnet-20241022'].context).toBe(200000);
+ expect(map[EModelEndpoint.openAI]['gpt-4o'].prompt).toBeUndefined();
+ expect(map[EModelEndpoint.openAI]['gpt-4o'].completion).toBeUndefined();
+ });
+
+ it('includes pattern-matched pricing when enabled', () => {
+ const map = buildTokenConfigMap(
+ {
+ modelsConfig: {
+ [EModelEndpoint.anthropic]: ['claude-3-5-sonnet-20241022'],
+ },
+ includePricing: true,
+ },
+ deps,
+ );
+
+ const tokenomics = map[EModelEndpoint.anthropic]['claude-3-5-sonnet-20241022'];
+ expect(tokenomics.prompt).toBe(3);
+ expect(tokenomics.completion).toBe(15);
+ expect(tokenomics.cacheWrite).toBe(3.75);
+ expect(tokenomics.cacheRead).toBe(0.3);
+ });
+
+ it('treats unknown endpoints as custom for context lookups', () => {
+ const map = buildTokenConfigMap(
+ {
+ modelsConfig: { MyProxy: ['gpt-4o-mini'] },
+ },
+ deps,
+ );
+
+ expect(map.MyProxy['gpt-4o-mini'].context).toBeGreaterThan(0);
+ });
+
+ it('prefers endpoint token config overrides for context and rates', () => {
+ const override: EndpointTokenConfig = {
+ 'custom-model': { prompt: 1.5, completion: 4.5, context: 32000 },
+ };
+ const map = buildTokenConfigMap(
+ {
+ modelsConfig: { MyProxy: ['custom-model', 'gpt-4o-mini'] },
+ endpointTokenConfigs: { MyProxy: override },
+ includePricing: true,
+ },
+ deps,
+ );
+
+ expect(map.MyProxy['custom-model']).toEqual({
+ context: 32000,
+ prompt: 1.5,
+ completion: 4.5,
+ });
+ /** Models absent from the override fall back to static tables */
+ expect(map.MyProxy['gpt-4o-mini'].context).toBeGreaterThan(0);
+ expect(map.MyProxy['gpt-4o-mini'].prompt).toBeGreaterThan(0);
+ });
+
+ it('carries static cache rates from the override', () => {
+ const override: EndpointTokenConfig = {
+ 'cached-model': {
+ prompt: 3,
+ completion: 15,
+ context: 200000,
+ cacheRead: 0.3,
+ cacheWrite: 3.75,
+ } as EndpointTokenConfig[string],
+ };
+ const map = buildTokenConfigMap(
+ {
+ modelsConfig: { MyProxy: ['cached-model'] },
+ endpointTokenConfigs: { MyProxy: override },
+ includePricing: true,
+ },
+ deps,
+ );
+
+ expect(map.MyProxy['cached-model']).toEqual({
+ context: 200000,
+ prompt: 3,
+ completion: 15,
+ cacheRead: 0.3,
+ cacheWrite: 3.75,
+ });
+ });
+
+ it('skips endpoints with empty model lists', () => {
+ const map = buildTokenConfigMap({ modelsConfig: { [EModelEndpoint.agents]: [] } }, deps);
+ expect(map[EModelEndpoint.agents]).toBeUndefined();
+ });
+});
diff --git a/packages/api/src/endpoints/pricing.ts b/packages/api/src/endpoints/pricing.ts
new file mode 100644
index 0000000000..6bf2aa6b4a
--- /dev/null
+++ b/packages/api/src/endpoints/pricing.ts
@@ -0,0 +1,106 @@
+import { EModelEndpoint } from 'librechat-data-provider';
+import type { TModelsConfig, TTokenConfigMap, TModelTokenomics } from 'librechat-data-provider';
+import type { TxMethods } from '@librechat/data-schemas';
+import type { EndpointTokenConfig } from '~/types';
+import { getModelMaxTokens, maxTokensMap } from '~/utils';
+
+export interface TokenomicsDeps {
+ getValueKey: TxMethods['getValueKey'];
+ getMultiplier: TxMethods['getMultiplier'];
+ getCacheMultiplier: TxMethods['getCacheMultiplier'];
+}
+
+export interface TokenConfigParams {
+ /** endpoint → model list, from the resolved models config */
+ modelsConfig: TModelsConfig;
+ /** Per-endpoint overrides: fetched (e.g. OpenRouter) or yaml `tokenConfig` */
+ endpointTokenConfigs?: Record<string, EndpointTokenConfig | undefined>;
+ /** Include USD-per-1M rates; gated by `interface.contextCost` */
+ includePricing?: boolean;
+}
+
+/**
+ * Resolves context windows (and optionally pricing) for every configured
+ * model, server-side, so the client never reimplements pattern matching.
+ */
+export function buildTokenConfigMap(
+ params: TokenConfigParams,
+ deps: TokenomicsDeps,
+): TTokenConfigMap {
+ const { modelsConfig, endpointTokenConfigs, includePricing = false } = params;
+ const map: TTokenConfigMap = {};
+
+ for (const [endpoint, models] of Object.entries(modelsConfig)) {
+ if (!Array.isArray(models) || models.length === 0) {
+ continue;
+ }
+ const override = endpointTokenConfigs?.[endpoint];
+ const endpointKey = (
+ maxTokensMap[endpoint] != null ? endpoint : EModelEndpoint.custom
+ ) as EModelEndpoint;
+
+ const entry: Record<string, TModelTokenomics> = {};
+ for (const model of models) {
+ const tokenomics: TModelTokenomics = {};
+ /** getModelMaxTokens falls back to the built-in map for models absent
+ * from a partial override, so a single call covers both cases. */
+ const context = getModelMaxTokens(model, endpointKey, override);
+ if (context != null) {
+ tokenomics.context = context;
+ }
+
+ if (includePricing) {
+ const overrideRates = override?.[model];
+ if (overrideRates?.prompt != null || overrideRates?.completion != null) {
+ tokenomics.prompt = overrideRates.prompt;
+ tokenomics.completion = overrideRates.completion;
+ /** Carry admin-configured cache rates; client falls back to the
+ * prompt rate for whichever cache rate is absent */
+ if (overrideRates.cacheWrite != null) {
+ tokenomics.cacheWrite = overrideRates.cacheWrite;
+ }
+ if (overrideRates.cacheRead != null) {
+ tokenomics.cacheRead = overrideRates.cacheRead;
+ }
+ } else {
+ const valueKey = deps.getValueKey(model, endpoint);
+ tokenomics.prompt = deps.getMultiplier({
+ valueKey,
+ model,
+ endpoint,
+ tokenType: 'prompt',
+ });
+ tokenomics.completion = deps.getMultiplier({
+ valueKey,
+ model,
+ endpoint,
+ tokenType: 'completion',
+ });
+ const cacheWrite = deps.getCacheMultiplier({
+ valueKey,
+ model,
+ endpoint,
+ cacheType: 'write',
+ });
+ const cacheRead = deps.getCacheMultiplier({
+ valueKey,
+ model,
+ endpoint,
+ cacheType: 'read',
+ });
+ if (cacheWrite != null) {
+ tokenomics.cacheWrite = cacheWrite;
+ }
+ if (cacheRead != null) {
+ tokenomics.cacheRead = cacheRead;
+ }
+ }
+ }
+
+ entry[model] = tokenomics;
+ }
+ map[endpoint] = entry;
+ }
+
+ return map;
+}
diff --git a/packages/api/src/endpoints/tokenConfig.spec.ts b/packages/api/src/endpoints/tokenConfig.spec.ts
new file mode 100644
index 0000000000..a6ad3d27d4
--- /dev/null
+++ b/packages/api/src/endpoints/tokenConfig.spec.ts
@@ -0,0 +1,79 @@
+import { EModelEndpoint } from 'librechat-data-provider';
+import type { AppConfig } from '@librechat/data-schemas';
+import type { TokenomicsDeps } from './pricing';
+
+const mockCacheGet = jest.fn();
+jest.mock('~/cache', () => ({
+ tokenConfigCache: jest.fn(() => ({ get: (key: string) => mockCacheGet(key) })),
+}));
+
+import { resolveTokenConfigMap } from './tokenConfig';
+
+const deps: TokenomicsDeps = {
+ getValueKey: () => 'value-key',
+ getMultiplier: ({ tokenType }) => (tokenType === 'prompt' ? 5 : 15),
+ getCacheMultiplier: () => null,
+};
+
+function appConfigWith(custom: unknown[], contextCost = true): AppConfig {
+ return {
+ interfaceConfig: { contextCost },
+ endpoints: { [EModelEndpoint.custom]: custom },
+ } as unknown as AppConfig;
+}
+
+describe('resolveTokenConfigMap', () => {
+ beforeEach(() => mockCacheGet.mockReset().mockResolvedValue(null));
+
+ it('uses a static tokenConfig override without consulting the cache', async () => {
+ const appConfig = appConfigWith([
+ {
+ name: 'MyProxy',
+ tokenConfig: { 'custom-model': { prompt: 1.5, completion: 4.5, context: 32000 } },
+ },
+ ]);
+
+ const map = await resolveTokenConfigMap(
+ { appConfig, modelsConfig: { MyProxy: ['custom-model'] }, userId: 'user-1' },
+ deps,
+ );
+
+ expect(map.MyProxy['custom-model']).toEqual({ context: 32000, prompt: 1.5, completion: 4.5 });
+ expect(mockCacheGet).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the cached fetched config when no static override exists', async () => {
+ mockCacheGet.mockResolvedValue({ 'custom-model': { prompt: 2, completion: 6, context: 8000 } });
+ const appConfig = appConfigWith([{ name: 'MyProxy', models: { fetch: true } }]);
+
+ const map = await resolveTokenConfigMap(
+ { appConfig, modelsConfig: { MyProxy: ['custom-model'] }, userId: 'user-1' },
+ deps,
+ );
+
+ expect(mockCacheGet).toHaveBeenCalled();
+ expect(map.MyProxy['custom-model'].context).toBe(8000);
+ expect(map.MyProxy['custom-model'].prompt).toBe(2);
+ });
+
+ it('omits pricing when contextCost is disabled', async () => {
+ const appConfig = appConfigWith(
+ [
+ {
+ name: 'MyProxy',
+ tokenConfig: { 'custom-model': { prompt: 1.5, completion: 4.5, context: 32000 } },
+ },
+ ],
+ false,
+ );
+
+ const map = await resolveTokenConfigMap(
+ { appConfig, modelsConfig: { MyProxy: ['custom-model'] }, userId: 'user-1' },
+ deps,
+ );
+
+ expect(map.MyProxy['custom-model'].context).toBe(32000);
+ expect(map.MyProxy['custom-model'].prompt).toBeUndefined();
+ expect(map.MyProxy['custom-model'].completion).toBeUndefined();
+ });
+});
diff --git a/packages/api/src/endpoints/tokenConfig.ts b/packages/api/src/endpoints/tokenConfig.ts
new file mode 100644
index 0000000000..1c29220e04
--- /dev/null
+++ b/packages/api/src/endpoints/tokenConfig.ts
@@ -0,0 +1,52 @@
+import { EModelEndpoint, normalizeEndpointName } from 'librechat-data-provider';
+import type { TModelsConfig, TTokenConfigMap, TEndpoint } from 'librechat-data-provider';
+import type { AppConfig } from '@librechat/data-schemas';
+import type { EndpointTokenConfig } from '~/types';
+import { buildTokenConfigMap, type TokenomicsDeps } from '~/endpoints/pricing';
+import { getTokenConfigKey } from '~/endpoints/custom/initialize';
+import { tokenConfigCache } from '~/cache';
+
+export interface ResolveTokenConfigParams {
+ appConfig?: AppConfig;
+ /** endpoint → model list, from the resolved models config */
+ modelsConfig: TModelsConfig;
+ userId: string;
+}
+
+/**
+ * Server-side token-config resolution for the `/endpoints/token-config`
+ * route. Gathers each custom endpoint's override — a static yaml `tokenConfig`
+ * or the cached fetched config — then resolves context windows (and pricing,
+ * when `interface.contextCost` is enabled) via {@link buildTokenConfigMap}.
+ * Lives in TypeScript so the `/api` controller stays a thin wrapper.
+ */
+export async function resolveTokenConfigMap(
+ { appConfig, modelsConfig, userId }: ResolveTokenConfigParams,
+ deps: TokenomicsDeps,
+): Promise<TTokenConfigMap> {
+ const includePricing = appConfig?.interfaceConfig?.contextCost === true;
+ const customEndpoints = (appConfig?.endpoints?.[EModelEndpoint.custom] ?? []) as TEndpoint[];
+ const cache = tokenConfigCache();
+ const endpointTokenConfigs: Record<string, EndpointTokenConfig | undefined> = {};
+
+ for (const endpointConfig of customEndpoints) {
+ /** Models config and the token-config cache key by the normalized name */
+ const name = normalizeEndpointName(endpointConfig?.name);
+ if (!name) {
+ continue;
+ }
+ if (endpointConfig.tokenConfig != null) {
+ endpointTokenConfigs[name] = endpointConfig.tokenConfig as EndpointTokenConfig;
+ continue;
+ }
+ /** Model fetches and chat initialization both store under this key —
+ * user-scoped whenever the fetched config can be user-specific */
+ const tokenKey = getTokenConfigKey(endpointConfig, name, userId);
+ const cached = (await cache.get(tokenKey)) as EndpointTokenConfig | undefined;
+ if (cached) {
+ endpointTokenConfigs[name] = cached;
+ }
+ }
+
+ return buildTokenConfigMap({ modelsConfig, endpointTokenConfigs, includePricing }, deps);
+}
diff --git a/packages/api/src/stream/GenerationJobManager.ts b/packages/api/src/stream/GenerationJobManager.ts
index 238db4e6cb..9b1980a6b8 100644
--- a/packages/api/src/stream/GenerationJobManager.ts
+++ b/packages/api/src/stream/GenerationJobManager.ts
@@ -1,5 +1,5 @@
-import { Constants, parseTextParts } from 'librechat-data-provider';
import { logger, getTenantId, SYSTEM_TENANT_ID } from '@librechat/data-schemas';
+import { Constants, UsageEvents, parseTextParts } from 'librechat-data-provider';
import type { Agents, TMessageContentParts } from 'librechat-data-provider';
import type { StandardGraph } from '@librechat/agents';
import type {
@@ -177,6 +177,9 @@ class GenerationJobManagerClass {
/** Serializes replay-event read/modify/write updates per stream. */
private replayEventWriteQueues = new Map<string, Promise<void>>();
+ /** Serializes token-usage read/modify/write updates per stream. */
+ private tokenUsageWriteQueues = new Map<string, Promise<void>>();
+
private cleanupInterval: NodeJS.Timeout | null = null;
/** Whether we're using Redis stores */
@@ -649,6 +652,7 @@ class GenerationJobManagerClass {
this.jobStore.clearContentState(streamId);
this.runStepBuffers?.delete(streamId);
this.replayEventWriteQueues.delete(streamId);
+ this.tokenUsageWriteQueues.delete(streamId);
// For error jobs, DON'T delete immediately - keep around so late-connecting
// clients can receive the error. This handles the race condition where error
@@ -794,6 +798,7 @@ class GenerationJobManagerClass {
this.jobStore.clearContentState(streamId);
this.runStepBuffers?.delete(streamId);
this.replayEventWriteQueues.delete(streamId);
+ this.tokenUsageWriteQueues.delete(streamId);
// Immediate cleanup if configured (default: true)
if (this._cleanupOnComplete) {
@@ -1053,6 +1058,8 @@ class GenerationJobManagerClass {
await this.trackUserMessage(streamId, event);
await this.trackTitleEvent(streamId, event);
await this.trackReplayEvent(streamId, event);
+ await this.trackContextUsage(streamId, event);
+ await this.trackTokenUsage(streamId, event);
// For Redis mode, persist chunk for later reconstruction (fire-and-forget for resumability)
if (this._isRedis) {
@@ -1151,32 +1158,97 @@ class GenerationJobManagerClass {
}
/**
- * Persist replay-only stream events that are needed to reconstruct active
- * UI state on resume but are not represented by aggregated message content.
+ * Persist the latest context usage snapshot (one per model call) so a
+ * resuming client can restore the context gauge without waiting for the
+ * next model call.
*/
- private async trackReplayEvent(streamId: string, event: t.ServerSentEvent): Promise<void> {
- if (!isOAuthReplayEvent(event)) {
+ private async trackContextUsage(streamId: string, event: t.ServerSentEvent): Promise<void> {
+ if (!('event' in event) || event.event !== UsageEvents.ON_CONTEXT_USAGE) {
return;
}
- const previousWrite = this.replayEventWriteQueues.get(streamId) ?? Promise.resolve();
+ await this.jobStore.updateJob(streamId, {
+ contextUsage: JSON.stringify((event as { data?: unknown }).data ?? null),
+ });
+ }
+
+ /**
+ * Chains a read/modify/write job update onto the stream's queue so
+ * concurrent writers can't clobber each other's merged state.
+ */
+ private async queueJobWrite(
+ queues: Map<string, Promise<void>>,
+ streamId: string,
+ write: () => Promise<void>,
+ ): Promise<void> {
+ const previousWrite = queues.get(streamId) ?? Promise.resolve();
const nextWrite = previousWrite
.catch(() => {
- // Keep the queue moving even if a prior replay metadata write failed.
+ // Keep the queue moving even if a prior metadata write failed.
})
- .then(() => this.persistReplayEvent(streamId, event));
+ .then(write);
- this.replayEventWriteQueues.set(streamId, nextWrite);
+ queues.set(streamId, nextWrite);
try {
await nextWrite;
} finally {
- if (this.replayEventWriteQueues.get(streamId) === nextWrite) {
- this.replayEventWriteQueues.delete(streamId);
+ if (queues.get(streamId) === nextWrite) {
+ queues.delete(streamId);
}
}
}
+ /**
+ * Persist replay-only stream events that are needed to reconstruct active
+ * UI state on resume but are not represented by aggregated message content.
+ */
+ private async trackReplayEvent(streamId: string, event: t.ServerSentEvent): Promise<void> {
+ if (!isOAuthReplayEvent(event)) {
+ return;
+ }
+
+ await this.queueJobWrite(this.replayEventWriteQueues, streamId, () =>
+ this.persistReplayEvent(streamId, event),
+ );
+ }
+
+ /**
+ * Persist per-model-call token usage so resuming clients can rebuild
+ * usage totals on any replica (the live collectedUsage array only exists
+ * on the generating instance).
+ */
+ private async trackTokenUsage(streamId: string, event: t.ServerSentEvent): Promise<void> {
+ if (!('event' in event) || event.event !== UsageEvents.ON_TOKEN_USAGE) {
+ return;
+ }
+
+ await this.queueJobWrite(this.tokenUsageWriteQueues, streamId, () =>
+ this.persistTokenUsage(streamId, event as { data?: unknown }),
+ );
+ }
+
+ private async persistTokenUsage(streamId: string, event: { data?: unknown }): Promise<void> {
+ const jobData = await this.jobStore.getJob(streamId);
+ if (!jobData || event.data == null) {
+ return;
+ }
+
+ let tokenUsage: unknown[] = [];
+ if (jobData.tokenUsage) {
+ try {
+ tokenUsage = JSON.parse(jobData.tokenUsage) as unknown[];
+ } catch {
+ tokenUsage = [];
+ }
+ }
+ tokenUsage.push(event.data);
+
+ await this.jobStore.updateJob(streamId, {
+ tokenUsage: JSON.stringify(tokenUsage),
+ });
+ }
+
private async persistReplayEvent(streamId: string, event: t.ServerSentEvent): Promise<void> {
const jobData = await this.jobStore.getJob(streamId);
if (!jobData) {
@@ -1342,10 +1414,32 @@ class GenerationJobManagerClass {
}
}
+ let contextUsage: t.ResumeState['contextUsage'];
+ if (jobData.contextUsage) {
+ try {
+ contextUsage = JSON.parse(jobData.contextUsage) as t.ResumeState['contextUsage'];
+ } catch {
+ // Ignore malformed persisted context usage.
+ }
+ }
+
+ /** Persisted per model call by trackTokenUsage — unlike the live
+ * collectedUsage reference, this survives cross-replica resumes. */
+ let collectedUsage: t.ResumeState['collectedUsage'];
+ if (jobData.tokenUsage) {
+ try {
+ const parsed = JSON.parse(jobData.tokenUsage) as t.ResumeState['collectedUsage'];
+ collectedUsage = parsed && parsed.length > 0 ? parsed : undefined;
+ } catch {
+ // Ignore malformed persisted token usage.
+ }
+ }
+
logger.debug(`[GenerationJobManager] getResumeState:`, {
streamId,
runStepsLength: runSteps.length,
aggregatedContentLength: aggregatedContent.length,
+ collectedUsageLength: collectedUsage?.length ?? 0,
});
return {
@@ -1359,6 +1453,8 @@ class GenerationJobManagerClass {
model: jobData.model,
titleEvent,
replayEvents,
+ collectedUsage,
+ contextUsage,
};
}
@@ -1576,6 +1672,7 @@ class GenerationJobManagerClass {
this.syncRunningJobMetrics();
this.runStepBuffers?.clear();
this.replayEventWriteQueues.clear();
+ this.tokenUsageWriteQueues.clear();
logger.debug('[GenerationJobManager] Destroyed');
}
diff --git a/packages/api/src/stream/__tests__/usageResume.spec.ts b/packages/api/src/stream/__tests__/usageResume.spec.ts
new file mode 100644
index 0000000000..59564730f9
--- /dev/null
+++ b/packages/api/src/stream/__tests__/usageResume.spec.ts
@@ -0,0 +1,96 @@
+import { InMemoryEventTransport } from '~/stream/implementations/InMemoryEventTransport';
+import { InMemoryJobStore } from '~/stream/implementations/InMemoryJobStore';
+import { GenerationJobManagerClass } from '~/stream/GenerationJobManager';
+
+jest.spyOn(console, 'log').mockImplementation();
+
+function createInMemoryManager(): GenerationJobManagerClass {
+ const manager = new GenerationJobManagerClass();
+ manager.configure({
+ jobStore: new InMemoryJobStore({ ttlAfterComplete: 60000 }),
+ eventTransport: new InMemoryEventTransport(),
+ isRedis: false,
+ });
+ manager.initialize();
+ return manager;
+}
+
+describe('GenerationJobManager usage resume state', () => {
+ let manager: GenerationJobManagerClass | undefined;
+
+ afterEach(async () => {
+ await manager?.destroy();
+ manager = undefined;
+ });
+
+ test('accumulates persisted token usage events in resume state', async () => {
+ manager = createInMemoryManager();
+ const streamId = `usage-resume-${Date.now()}`;
+ await manager.createJob(streamId, 'user-1', streamId);
+
+ const firstUsage = {
+ input_tokens: 1200,
+ output_tokens: 300,
+ input_token_details: { cache_creation: 100, cache_read: 800 },
+ model: 'claude-3-5-sonnet',
+ provider: 'anthropic',
+ };
+ const secondUsage = {
+ input_tokens: 1600,
+ output_tokens: 120,
+ model: 'claude-3-5-sonnet',
+ provider: 'anthropic',
+ usage_type: 'summarization',
+ };
+
+ await manager.emitChunk(streamId, { event: 'on_token_usage', data: firstUsage });
+ await manager.emitChunk(streamId, { event: 'on_token_usage', data: secondUsage });
+
+ const resumeState = await manager.getResumeState(streamId);
+ expect(resumeState?.collectedUsage).toEqual([firstUsage, secondUsage]);
+ });
+
+ test('omits collected usage when none was recorded', async () => {
+ manager = createInMemoryManager();
+ const streamId = `usage-resume-empty-${Date.now()}`;
+ await manager.createJob(streamId, 'user-1', streamId);
+
+ const resumeState = await manager.getResumeState(streamId);
+ expect(resumeState?.collectedUsage).toBeUndefined();
+ expect(resumeState?.contextUsage).toBeUndefined();
+ });
+
+ test('persists the latest context usage snapshot for resume', async () => {
+ manager = createInMemoryManager();
+ const streamId = `context-resume-${Date.now()}`;
+ await manager.createJob(streamId, 'user-1', streamId);
+
+ const makeSnapshot = (messageTokens: number) => ({
+ runId: 'run-1',
+ agentId: 'agent-1',
+ breakdown: {
+ maxContextTokens: 200000,
+ instructionTokens: 1500,
+ systemMessageTokens: 1000,
+ dynamicInstructionTokens: 0,
+ toolSchemaTokens: 500,
+ summaryTokens: 0,
+ toolCount: 3,
+ messageCount: 4,
+ messageTokens,
+ availableForMessages: 188500,
+ },
+ contextBudget: 190000,
+ effectiveInstructionTokens: 1500,
+ prePruneContextTokens: messageTokens,
+ remainingContextTokens: 190000 - 1500 - messageTokens,
+ calibrationRatio: 1.05,
+ });
+
+ await manager.emitChunk(streamId, { event: 'on_context_usage', data: makeSnapshot(4000) });
+ await manager.emitChunk(streamId, { event: 'on_context_usage', data: makeSnapshot(9000) });
+
+ const resumeState = await manager.getResumeState(streamId);
+ expect(resumeState?.contextUsage).toEqual(makeSnapshot(9000));
+ });
+});
diff --git a/packages/api/src/stream/implementations/RedisJobStore.ts b/packages/api/src/stream/implementations/RedisJobStore.ts
index d49affdc28..a00eeba6b4 100644
--- a/packages/api/src/stream/implementations/RedisJobStore.ts
+++ b/packages/api/src/stream/implementations/RedisJobStore.ts
@@ -923,6 +923,8 @@ export class RedisJobStore implements IJobStore {
promptTokens: data.promptTokens ? parseInt(data.promptTokens, 10) : undefined,
titleEvent: data.titleEvent || undefined,
replayEvents: data.replayEvents || undefined,
+ contextUsage: data.contextUsage || undefined,
+ tokenUsage: data.tokenUsage || undefined,
};
}
}
diff --git a/packages/api/src/stream/interfaces/IJobStore.ts b/packages/api/src/stream/interfaces/IJobStore.ts
index e3fc042d06..32b42338f0 100644
--- a/packages/api/src/stream/interfaces/IJobStore.ts
+++ b/packages/api/src/stream/interfaces/IJobStore.ts
@@ -48,6 +48,12 @@ export interface SerializableJobData {
/** Serialized replay-only stream events for active-stream resume */
replayEvents?: string;
+ /** Serialized latest context usage snapshot for active-stream resume */
+ contextUsage?: string;
+
+ /** Serialized token usage events for active-stream resume (cross-replica safe) */
+ tokenUsage?: string;
+
/** Endpoint metadata for abort handling - avoids storing functions */
endpoint?: string;
iconURL?: string;
@@ -76,7 +82,7 @@ export interface SerializableJobData {
*/
export interface UsageMetadata {
/** Logical usage bucket for accounting/reporting. Defaults to model response usage. */
- usage_type?: 'message' | 'summarization' | 'subagent';
+ usage_type?: 'message' | 'summarization' | 'subagent' | 'sequential';
/** Total input tokens (prompt tokens) */
input_tokens?: number;
/** Total output tokens (completion tokens) */
diff --git a/packages/api/src/utils/tokens.spec.ts b/packages/api/src/utils/tokens.spec.ts
new file mode 100644
index 0000000000..0931c24815
--- /dev/null
+++ b/packages/api/src/utils/tokens.spec.ts
@@ -0,0 +1,33 @@
+import { EModelEndpoint } from 'librechat-data-provider';
+import type { EndpointTokenConfig } from '~/types';
+import { getModelMaxTokens, getModelMaxOutputTokens } from './tokens';
+
+describe('getModelMaxTokens partial-override fallback', () => {
+ const partialOverride: EndpointTokenConfig = {
+ 'custom-model': { prompt: 1, completion: 2, context: 32000, output: 4096 },
+ };
+
+ it('uses the override for a listed model', () => {
+ expect(getModelMaxTokens('custom-model', EModelEndpoint.openAI, partialOverride)).toBe(32000);
+ });
+
+ it('falls back to the built-in map for a model absent from a partial override', () => {
+ const fallback = getModelMaxTokens('gpt-4o', EModelEndpoint.openAI, partialOverride);
+ const builtin = getModelMaxTokens('gpt-4o', EModelEndpoint.openAI);
+ expect(fallback).toBe(builtin);
+ expect(fallback).toBeGreaterThan(100000);
+ });
+});
+
+describe('getModelMaxOutputTokens partial-override fallback', () => {
+ const partialOverride: EndpointTokenConfig = {
+ 'custom-model': { prompt: 1, completion: 2, context: 32000, output: 4096 },
+ };
+
+ it('falls back to the built-in map for a model absent from a partial override', () => {
+ const fallback = getModelMaxOutputTokens('gpt-4o', EModelEndpoint.openAI, partialOverride);
+ const builtin = getModelMaxOutputTokens('gpt-4o', EModelEndpoint.openAI);
+ expect(fallback).toBe(builtin);
+ expect(fallback).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/api/src/utils/tokens.ts b/packages/api/src/utils/tokens.ts
index 856b341b63..b9e248bbca 100644
--- a/packages/api/src/utils/tokens.ts
+++ b/packages/api/src/utils/tokens.ts
@@ -519,8 +519,16 @@ export function getModelMaxTokens(
endpoint: EModelEndpoint = EModelEndpoint.openAI,
endpointTokenConfig?: EndpointTokenConfig,
): number | undefined {
- const tokensMap = endpointTokenConfig ?? maxTokensMap[endpoint as keyof typeof maxTokensMap];
- return getModelTokenValue(modelName, tokensMap);
+ /** A partial override only covers the models it lists; fall back to the
+ * built-in map for unlisted models instead of dropping to the default
+ * budget (matches buildTokenConfigMap and getMultiplier). */
+ if (endpointTokenConfig != null) {
+ const overrideValue = getModelTokenValue(modelName, endpointTokenConfig);
+ if (overrideValue != null) {
+ return overrideValue;
+ }
+ }
+ return getModelTokenValue(modelName, maxTokensMap[endpoint as keyof typeof maxTokensMap]);
}
/**
@@ -536,9 +544,18 @@ export function getModelMaxOutputTokens(
endpoint: EModelEndpoint = EModelEndpoint.openAI,
endpointTokenConfig?: EndpointTokenConfig,
): number | undefined {
- const tokensMap =
- endpointTokenConfig ?? maxOutputTokensMap[endpoint as keyof typeof maxOutputTokensMap];
- return getModelTokenValue(modelName, tokensMap, 'output');
+ /** Partial override fallback — see getModelMaxTokens */
+ if (endpointTokenConfig != null) {
+ const overrideValue = getModelTokenValue(modelName, endpointTokenConfig, 'output');
+ if (overrideValue != null) {
+ return overrideValue;
+ }
+ }
+ return getModelTokenValue(
+ modelName,
+ maxOutputTokensMap[endpoint as keyof typeof maxOutputTokensMap],
+ 'output',
+ );
}
/**
diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts
index bc3107d7ca..09864bea43 100644
--- a/packages/data-provider/src/api-endpoints.ts
+++ b/packages/data-provider/src/api-endpoints.ts
@@ -148,6 +148,8 @@ export const deletePreset = () => `${BASE_URL}/api/presets/delete`;
export const aiEndpoints = () => `${BASE_URL}/api/endpoints`;
+export const tokenConfig = () => `${BASE_URL}/api/endpoints/token-config`;
+
export const models = () => `${BASE_URL}/api/models`;
export const tokenizer = () => `${BASE_URL}/api/tokenizer`;
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 6309cfc279..64bc73e291 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -846,6 +846,18 @@ export const endpointSchema = baseEndpointSchema.merge(
.optional(),
directEndpoint: z.boolean().optional(),
titleMessageRole: z.enum(['system', 'user', 'assistant']).optional(),
+ /** Static per-model token config: context window and per-million-token rates */
+ tokenConfig: z
+ .record(
+ z.object({
+ prompt: z.number(),
+ completion: z.number(),
+ context: z.number(),
+ cacheRead: z.number().optional(),
+ cacheWrite: z.number().optional(),
+ }),
+ )
+ .optional(),
}),
);
@@ -1167,6 +1179,8 @@ export const interfaceSchema = z
retainAgentFiles: z.boolean().optional(),
runCode: z.boolean().optional(),
webSearch: z.boolean().optional(),
+ contextUsage: z.boolean().optional(),
+ contextCost: z.boolean().optional(),
peoplePicker: z
.object({
users: z.boolean().optional(),
@@ -1236,6 +1250,8 @@ export const interfaceSchema = z
autoSubmitFromUrl: true,
runCode: true,
webSearch: true,
+ contextUsage: true,
+ contextCost: false,
peoplePicker: {
users: true,
groups: true,
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index 95d362ac34..e008e8c514 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -245,6 +245,10 @@ export const getAIEndpoints = (): Promise<t.TEndpointsConfig> => {
return request.get(endpoints.aiEndpoints());
};
+export const getTokenConfig = (): Promise<t.TTokenConfigMap> => {
+ return request.get(endpoints.tokenConfig());
+};
+
export const getModels = async (): Promise<t.TModelsConfig> => {
return request.get(endpoints.models());
};
diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts
index 7a66cfd80d..04a65beb51 100644
--- a/packages/data-provider/src/keys.ts
+++ b/packages/data-provider/src/keys.ts
@@ -12,6 +12,7 @@ export enum QueryKeys {
models = 'models',
balance = 'balance',
endpoints = 'endpoints',
+ tokenConfig = 'tokenConfig',
presets = 'presets',
searchResults = 'searchResults',
tokenCount = 'tokenCount',
diff --git a/packages/data-provider/src/react-query/react-query-service.ts b/packages/data-provider/src/react-query/react-query-service.ts
index b865ab3841..59430c78d1 100644
--- a/packages/data-provider/src/react-query/react-query-service.ts
+++ b/packages/data-provider/src/react-query/react-query-service.ts
@@ -4,17 +4,17 @@ import type {
UseMutationResult,
QueryObserverResult,
} from '@tanstack/react-query';
+import { MCPServerConnectionStatusResponse } from '../types/queries';
import { Constants, initialModelsConfig } from '../config';
import { defaultOrderQuery } from '../types/assistants';
-import { MCPServerConnectionStatusResponse } from '../types/queries';
+import * as permissions from '../accessPermissions';
+import { ResourceType } from '../accessPermissions';
import * as dataService from '../data-service';
import * as m from '../types/mutations';
import * as q from '../types/queries';
import { QueryKeys } from '../keys';
import * as s from '../schemas';
import * as t from '../types';
-import * as permissions from '../accessPermissions';
-import { ResourceType } from '../accessPermissions';
export { hasPermissions } from '../accessPermissions';
@@ -122,6 +122,8 @@ export const useUpdateUserKeysMutation = (): UseMutationResult<
onSuccess: (data, variables) => {
queryClient.invalidateQueries([QueryKeys.name, variables.name]);
queryClient.invalidateQueries([QueryKeys.models]);
+ /** token-config is derived from the same per-user model fetch */
+ queryClient.invalidateQueries([QueryKeys.tokenConfig]);
},
});
};
@@ -141,6 +143,7 @@ export const useRevokeUserKeyMutation = (name: string): UseMutationResult<unknow
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.name, name]);
queryClient.invalidateQueries([QueryKeys.models]);
+ queryClient.invalidateQueries([QueryKeys.tokenConfig]);
if (s.isAssistantsEndpoint(name)) {
queryClient.invalidateQueries([QueryKeys.assistants, name, defaultOrderQuery]);
queryClient.invalidateQueries([QueryKeys.assistantDocs]);
@@ -159,6 +162,7 @@ export const useRevokeAllUserKeysMutation = (): UseMutationResult<unknown> => {
return useMutation(() => dataService.revokeAllUserKeys(), {
onSuccess: () => {
queryClient.invalidateQueries([QueryKeys.name]);
+ queryClient.invalidateQueries([QueryKeys.tokenConfig]);
queryClient.invalidateQueries([
QueryKeys.assistants,
s.EModelEndpoint.assistants,
diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.ts
index 4503d2af05..e7b1186a0c 100644
--- a/packages/data-provider/src/schemas.ts
+++ b/packages/data-provider/src/schemas.ts
@@ -79,6 +79,29 @@ export const isOpenAILikeProvider = (provider?: string | null): boolean => {
return openAILikeProviders.has(provider ?? '');
};
+/**
+ * Providers whose `usage_metadata.input_tokens` ALREADY INCLUDES cached tokens
+ * (`input_token_details.cache_*` is a subset, not an additional charge):
+ * Google/Vertex (`promptTokenCount`), OpenAI/Azure (`prompt_tokens`), and the
+ * OpenAI-compatible family. Anthropic/Bedrock keep cache values separate and
+ * additive. Single source of truth shared by the backend billing path
+ * (`packages/api/src/agents/usage.ts`) and the client usage normalization.
+ */
+export const cacheSubsetProviders = new Set<string>([
+ Providers.OPENAI,
+ Providers.AZURE,
+ Providers.GOOGLE,
+ Providers.VERTEXAI,
+ Providers.XAI,
+ Providers.DEEPSEEK,
+ Providers.OPENROUTER,
+ Providers.MOONSHOT,
+]);
+
+export const inputTokensIncludesCache = (provider?: string | null): boolean => {
+ return cacheSubsetProviders.has(provider ?? '');
+};
+
export const isDocumentSupportedProvider = (provider?: string | null): boolean => {
return documentSupportedProviders.has(provider ?? '');
};
@@ -748,6 +771,8 @@ export const tMessageSchema = z.object({
feedback: feedbackSchema.optional(),
/** metadata */
metadata: z.record(z.unknown()).optional(),
+ /** Output tokens for assistant messages, calibrated prompt-side estimate for user messages */
+ tokenCount: z.number().optional(),
contextMeta: z
.object({
calibrationRatio: z
diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts
index ac069b210d..68a0bdde92 100644
--- a/packages/data-provider/src/types.ts
+++ b/packages/data-provider/src/types.ts
@@ -454,6 +454,18 @@ export type TEndpointsConfig =
export type TModelsConfig = Record<string, string[]>;
+/** Server-resolved context window and pricing for one model. Rates are USD per 1M tokens. */
+export type TModelTokenomics = {
+ context?: number;
+ prompt?: number;
+ completion?: number;
+ cacheWrite?: number;
+ cacheRead?: number;
+};
+
+/** endpoint → model → resolved tokenomics, from GET /api/endpoints/token-config */
+export type TTokenConfigMap = Record<string, Record<string, TModelTokenomics>>;
+
export type TUpdateTokenCountResponse = {
count: number;
};
diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.ts
index 0eab753bd3..0dc96fb6cc 100644
--- a/packages/data-provider/src/types/agents.ts
+++ b/packages/data-provider/src/types/agents.ts
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-namespace */
import type { FunctionToolCall, SummaryContentPart } from './assistants';
+import type { TTokenUsageEvent, TContextUsageEvent } from './runs';
import type { TAttachment, TPlugin } from 'src/schemas';
import { StepTypes, ContentTypes, ToolCallTypes } from './runs';
@@ -231,6 +232,10 @@ export namespace Agents {
data?: unknown;
[key: string]: unknown;
}>;
+ /** Cumulative provider-reported usage for the run; backfills usage totals on resume */
+ collectedUsage?: TTokenUsageEvent[];
+ /** Latest context window snapshot; restores the usage gauge on resume */
+ contextUsage?: TContextUsageEvent;
}
/**
* Represents a run step delta i.e. any changed fields on a run step during
diff --git a/packages/data-provider/src/types/runs.ts b/packages/data-provider/src/types/runs.ts
index 706c380c6f..71453a4534 100644
--- a/packages/data-provider/src/types/runs.ts
+++ b/packages/data-provider/src/types/runs.ts
@@ -40,6 +40,70 @@ export enum StepEvents {
ON_SUBAGENT_UPDATE = 'on_subagent_update',
}
+/** Token-tracking event names streamed to the client (separate from StepEvents dispatch). */
+export enum UsageEvents {
+ ON_CONTEXT_USAGE = 'on_context_usage',
+ ON_TOKEN_USAGE = 'on_token_usage',
+}
+
+/** Mirrors TokenBudgetBreakdown from @librechat/agents (data-provider cannot import it). */
+export type TTokenBudgetBreakdown = {
+ maxContextTokens: number;
+ instructionTokens: number;
+ systemMessageTokens: number;
+ dynamicInstructionTokens: number;
+ toolSchemaTokens: number;
+ summaryTokens: number;
+ toolCount: number;
+ messageCount: number;
+ messageTokens: number;
+ availableForMessages: number;
+ /** Per-tool schema token counts (post-multiplier), keyed by tool name */
+ toolTokenCounts?: Record<string, number>;
+ /** Names of counted tools that are deferred (`defer_loading`) and discovered */
+ deferredToolNames?: string[];
+};
+
+/** Per-model-call context snapshot, dispatched after pruning and before the LLM call. */
+export type TContextUsageEvent = {
+ runId?: string;
+ agentId?: string;
+ breakdown: TTokenBudgetBreakdown;
+ /** Usable budget this call: maxContextTokens minus output reserve */
+ contextBudget?: number;
+ /** Calibrated instruction overhead actually applied this call */
+ effectiveInstructionTokens?: number;
+ /** Calibrated message tokens before pruning (excluding instructions) */
+ prePruneContextTokens?: number;
+ /** Tokens still free after instructions + pruned messages */
+ remainingContextTokens?: number;
+ calibrationRatio?: number;
+};
+
+/** Provider-reported usage for a single completed model call. */
+export type TTokenUsageEvent = {
+ input_tokens?: number;
+ output_tokens?: number;
+ total_tokens?: number;
+ input_token_details?: {
+ cache_creation?: number;
+ cache_read?: number;
+ };
+ model?: string;
+ provider?: string;
+ /** Non-primary buckets fold into session cost/totals but not the live
+ * context gauge: hidden sequential-agent calls (`sequential`), summary
+ * passes (`summarization`), and isolated subagent runs (`subagent`) */
+ usage_type?: 'summarization' | 'subagent' | 'sequential';
+ runId?: string;
+ /** Per-run emission sequence; keeps identical payloads from distinct model calls unique */
+ seq?: number;
+ /** Authoritative USD cost of this call from the backend (premium tiers, cache
+ * rates); present only when `interface.contextCost` is enabled. Clients sum
+ * this rather than re-deriving cost from base rates. */
+ cost?: number;
+};
+
/** Lifecycle phase carried on subagent-progress envelopes (mirrors SDK SubagentUpdatePhase). */
export type SubagentUpdatePhase =
| 'start'
diff --git a/packages/data-schemas/src/app/interface.ts b/packages/data-schemas/src/app/interface.ts
index 5af5af5423..de74aad9c0 100644
--- a/packages/data-schemas/src/app/interface.ts
+++ b/packages/data-schemas/src/app/interface.ts
@@ -40,6 +40,8 @@ export async function loadDefaultInterface({
customWelcome: interfaceConfig?.customWelcome ?? defaults.customWelcome,
autoSubmitFromUrl: interfaceConfig?.autoSubmitFromUrl ?? defaults.autoSubmitFromUrl,
buildInfo: interfaceConfig?.buildInfo ?? defaults.buildInfo,
+ contextUsage: interfaceConfig?.contextUsage ?? defaults.contextUsage,
+ contextCost: interfaceConfig?.contextCost ?? defaults.contextCost,
// Permissions and related settings - only include if explicitly configured
bookmarks: interfaceConfig?.bookmarks,
diff --git a/packages/data-schemas/src/index.ts b/packages/data-schemas/src/index.ts
index 32fb4aa85b..9753ca6e6d 100644
--- a/packages/data-schemas/src/index.ts
+++ b/packages/data-schemas/src/index.ts
@@ -14,6 +14,7 @@ export {
cacheTokenValues,
premiumTokenValues,
defaultRate,
+ createTxMethods,
permissionBitSupersets,
partitionIssues,
validateSkillName,
diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.ts
index 6bab02a4f4..9ea9e5f1e5 100644
--- a/packages/data-schemas/src/methods/index.ts
+++ b/packages/data-schemas/src/methods/index.ts
@@ -89,7 +89,7 @@ import { createAgentMethods, type AgentMethods, type AgentDeps } from './agent';
import { createConfigMethods, type ConfigMethods } from './config';
export { RoleConflictError, DEFAULT_REFRESH_TOKEN_EXPIRY, DEFAULT_SESSION_EXPIRY };
-export { tokenValues, cacheTokenValues, premiumTokenValues, defaultRate };
+export { tokenValues, cacheTokenValues, premiumTokenValues, defaultRate, createTxMethods };
export { permissionBitSupersets };
export {
partitionIssues,
diff --git a/packages/data-schemas/src/methods/transaction.spec.ts b/packages/data-schemas/src/methods/transaction.spec.ts
index 176e7faef8..badfdaf014 100644
--- a/packages/data-schemas/src/methods/transaction.spec.ts
+++ b/packages/data-schemas/src/methods/transaction.spec.ts
@@ -1,9 +1,9 @@
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
+import type { IBalance } from '..';
import type { ITransaction } from '~/schema/transaction';
import type { TxData } from './transaction';
-import type { IBalance } from '..';
-import { createTxMethods, tokenValues, premiumTokenValues } from './tx';
+import { createTxMethods, tokenValues, premiumTokenValues, defaultRate } from './tx';
import { matchModelName, findMatchingPattern } from './test-helpers';
import { createSpendTokensMethods } from './spendTokens';
import { createTransactionMethods } from './transaction';
@@ -616,6 +616,36 @@ describe('Transactions Config Tests', () => {
});
});
+describe('Partial endpointTokenConfig fallback', () => {
+ const endpointTokenConfig = {
+ 'custom-model': { prompt: 1.5, completion: 4.5, read: 0.3 },
+ };
+
+ test('uses override rates for a listed model', () => {
+ expect(getMultiplier({ model: 'custom-model', tokenType: 'prompt', endpointTokenConfig })).toBe(
+ 1.5,
+ );
+ expect(
+ getCacheMultiplier({ model: 'custom-model', cacheType: 'read', endpointTokenConfig }),
+ ).toBe(0.3);
+ });
+
+ test('falls back to standard tables for a model absent from the override', () => {
+ const fallbackPrompt = getMultiplier({ model: 'gpt-4', tokenType: 'prompt' });
+ expect(getMultiplier({ model: 'gpt-4', tokenType: 'prompt', endpointTokenConfig })).toBe(
+ fallbackPrompt,
+ );
+ expect(getMultiplier({ model: 'gpt-4', tokenType: 'prompt', endpointTokenConfig })).not.toBe(
+ defaultRate,
+ );
+
+ const fallbackCacheRead = getCacheMultiplier({ model: 'claude-3-5-sonnet', cacheType: 'read' });
+ expect(
+ getCacheMultiplier({ model: 'claude-3-5-sonnet', cacheType: 'read', endpointTokenConfig }),
+ ).toBe(fallbackCacheRead);
+ });
+});
+
describe('calculateTokenValue Edge Cases', () => {
test('should derive multiplier from model when valueKey is not provided', async () => {
const userId = new mongoose.Types.ObjectId();
diff --git a/packages/data-schemas/src/methods/tx.ts b/packages/data-schemas/src/methods/tx.ts
index dd05312f0d..3e77007b9f 100644
--- a/packages/data-schemas/src/methods/tx.ts
+++ b/packages/data-schemas/src/methods/tx.ts
@@ -510,7 +510,13 @@ export function createTxMethods(
endpointTokenConfig?: Record<string, Record<string, number>>;
}): number {
if (endpointTokenConfig && model) {
- return endpointTokenConfig?.[model]?.[tokenType as string] ?? defaultRate;
+ const modelConfig = endpointTokenConfig[model];
+ /** A partial override only prices the models it lists; others fall
+ * through to the standard tables so billing matches the advertised
+ * token config instead of charging defaultRate */
+ if (modelConfig) {
+ return modelConfig[tokenType as string] ?? defaultRate;
+ }
}
if (valueKey && tokenType) {
@@ -555,7 +561,12 @@ export function createTxMethods(
endpointTokenConfig?: Record<string, Record<string, number>>;
}): number | null {
if (endpointTokenConfig && model) {
- return endpointTokenConfig?.[model]?.[cacheType as string] ?? null;
+ const modelConfig = endpointTokenConfig[model];
+ /** Models absent from a partial override fall through to standard
+ * cache rates rather than reporting no cache pricing */
+ if (modelConfig) {
+ return modelConfig[cacheType as string] ?? null;
+ }
}
if (valueKey && cacheType) {