🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(chat-input): account context details from the real request payload (#22943)
Lobehub Coder7dcfe1d3356c
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.test.tsnew file mode 100644index 00000000000..8c91f0b1d66--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.test.ts@@ -0,0 +1,68 @@+import type { ContextBuildInput } from '@lobechat/agent-runtime';+import { countRequestPayloadTokens } from '@lobechat/context-engine';+import { describe, expect, it, vi } from 'vitest';++import type { RuntimeExecutorContext } from '../context';+import { ServerContextBuilder } from './ServerContextBuilder';++const processedMessages = [+ { content: 'You are a careful analyst.', role: 'system' },+ { content: 'read the file', role: 'user' },+ {+ content: '',+ role: 'assistant',+ tool_calls: [+ {+ function: { arguments: '{"fileId":"file_1"}', name: 'readAttachment' },+ id: 'call_1',+ type: 'function',+ },+ ],+ },+ { content: 'line of the file\n'.repeat(50), role: 'tool', tool_call_id: 'call_1' },+];+const tools = [+ {+ function: { description: 'Read an attachment', name: 'readAttachment', parameters: {} },+ type: 'function',+ },+];++vi.mock('./serverCallLlmTooling', () => ({+ resolveServerCallLlmTooling: () => ({+ resolved: {+ enabledToolIds: ['lobe-attachments'],+ manifestMap: {},+ promptManifestMap: {},+ sourceMap: {},+ tools,+ },+ }),+}));++vi.mock('./serverCallLlmContextBuilder', () => ({+ buildServerCallLlmContext: async () => ({+ processedMessages,+ shouldReplayAssistantReasoning: false,+ }),+}));++describe('ServerContextBuilder', () => {+ it('accounts the request it builds from the processed messages and sent tools', async () => {+ const builder = new ServerContextBuilder({} as RuntimeExecutorContext);++ const output = await builder.build({+ model: 'deepseek-v4-flash',+ payload: { messages: [] },+ provider: 'deepseek',+ state: {},+ } as unknown as ContextBuildInput);++ expect(output.messages).toBe(processedMessages);+ expect(output.contextAccounting).toEqual(+ countRequestPayloadTokens({ messages: processedMessages, tools }),+ );+ expect(output.contextAccounting?.bySource.toolDefinition).toBeGreaterThan(0);+ expect(output.contextAccounting?.bySource.toolCalls).toBeGreaterThan(0);+ });+});diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.tsindex ec235a84406..8896471b351 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerContextBuilder.ts@@ -3,6 +3,7 @@ import type {ContextBuildInput,ContextBuildOutput,} from '@lobechat/agent-runtime';+import { tryCountRequestPayloadTokens } from '@lobechat/context-engine';import type { RuntimeExecutorContext } from '../context';import { buildServerCallLlmContext } from './serverCallLlmContextBuilder';@@ -27,6 +28,11 @@ export class ServerContextBuilder implements ContextBuilder {});return {+ // The attempt ships these messages and `resolved.tools` as-is.+ contextAccounting: tryCountRequestPayloadTokens({+ messages: result.processedMessages,+ tools: tooling.resolved.tools,+ }),messages: result.processedMessages,modelParameters: {...result.resolvedExtendParams,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 1e6504e2ac6..39ceac9ab19 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -3030,11 +3030,18 @@"toggleWideScreen.off": "Turn off widescreen mode","toggleWideScreen.on": "Turn on widescreen mode","tokenDetails.chats": "Chat Messages",+ "tokenDetails.estimated": "Estimated",+ "tokenDetails.estimatedTooltip": "Counted with a generic tokenizer over the request body. Each model uses its own tokenizer, so the input it bills can differ.",+ "tokenDetails.fileContext": "Attachments","tokenDetails.historySummary": "History Summary",+ "tokenDetails.lastRequestInput": "Last request input (reported by model)",+ "tokenDetails.reasoning": "Reasoning","tokenDetails.rest": "Remaining","tokenDetails.supervisor": "Orchestrator",+ "tokenDetails.system": "System Prompt","tokenDetails.systemRole": "Role Settings","tokenDetails.title": "Context Details",+ "tokenDetails.toolCalls": "Tool Calls","tokenDetails.tools": "Skill Settings","tokenDetails.total": "Total Available","tokenDetails.used": "Total Used",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 0108f0f3a0b..3ec298de977 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -3030,11 +3030,18 @@"toggleWideScreen.off": "关闭宽屏模式","toggleWideScreen.on": "开启宽屏模式","tokenDetails.chats": "会话消息",+ "tokenDetails.estimated": "估算",+ "tokenDetails.estimatedTooltip": "按请求体内容用通用分词器估算。各模型的分词器不同,实际计费的输入 token 会有出入。",+ "tokenDetails.fileContext": "附件内容","tokenDetails.historySummary": "历史总结",+ "tokenDetails.lastRequestInput": "上次请求输入(模型回报)",+ "tokenDetails.reasoning": "推理过程","tokenDetails.rest": "剩余可用","tokenDetails.supervisor": "群组主持人",+ "tokenDetails.system": "系统提示","tokenDetails.systemRole": "助理档案","tokenDetails.title": "上下文明细",+ "tokenDetails.toolCalls": "工具调用","tokenDetails.tools": "技能设定","tokenDetails.total": "总可用","tokenDetails.used": "已使用",diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.tsindex b13b2434277..629b6383968 100644--- a/packages/agent-runtime/src/executors/callLlm.test.ts+++ b/packages/agent-runtime/src/executors/callLlm.test.ts@@ -353,6 +353,40 @@ describe('callLlm executor', () => {expect(transport.trace.close).toHaveBeenCalledWith(undefined);});+ it('persists the context builder request accounting on the assistant message', async () => {+ const contextAccounting = {+ bySource: {+ content: 3,+ fileContext: 0,+ reasoning: 0,+ thoughtSignature: 0,+ toolCallId: 0,+ toolCalls: 0,+ toolDefinition: 0,+ },+ estimator: 'tokenx' as const,+ messageCount: 1,+ system: 0,+ total: 3,+ };+ const transport = createCallTransport();+ const messages = createMessageTransport();+ const context: ContextBuilder = {+ build: vi.fn().mockResolvedValue({ ...contextOutput, contextAccounting }),+ };+ const host = createHost(transport.llm, messages, createStreamSink(), context);++ await callLlm(host)(instruction, createState(), {+ instructionIndex: 0,+ phase: 'user_input',+ });++ expect(messages.update).toHaveBeenCalledWith(+ 'assistant-1',+ expect.objectContaining({ metadata: expect.objectContaining({ contextAccounting }) }),+ );+ });+it('reuses an existing assistant message without creating a new one', async () => {const state = createState();const transport = createCallTransport();diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.tsindex 62565104efc..03319196bc1 100644--- a/packages/agent-runtime/src/executors/callLlm.ts+++ b/packages/agent-runtime/src/executors/callLlm.ts@@ -102,6 +102,7 @@ const executePreparedCall = async (return await finalizeCallLlmTurn({assistantMessageId: prepared.assistantMessageId,attempts: attemptsMade,+ contextAccounting: prepared.context.contextAccounting,events,host,model: prepared.model,@@ -154,6 +155,7 @@ const executePreparedCall = async (if (interrupted) {await persistInterruptedCallLlmResult({assistantMessageId: prepared.assistantMessageId,+ contextAccounting: prepared.context.contextAccounting,host,output: execution.output,});@@ -181,6 +183,7 @@ const executePreparedCall = async (if (interrupted && lastOutput) {await persistInterruptedCallLlmResult({assistantMessageId: prepared.assistantMessageId,+ contextAccounting: prepared.context.contextAccounting,host,output: lastOutput,});diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.tsindex 7a655a2f7f3..c4972e450ab 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts@@ -779,6 +779,52 @@ describe('callLlmFinalizer', () => {);});+ it('persists the request accounting on final and interrupted assistant messages', async () => {+ const contextAccounting = {+ bySource: {+ content: 120,+ fileContext: 40,+ reasoning: 10,+ thoughtSignature: 0,+ toolCallId: 4,+ toolCalls: 20,+ toolDefinition: 300,+ },+ estimator: 'tokenx' as const,+ messageCount: 4,+ system: 500,+ total: 994,+ };+ const messages = createMessageTransport();++ await finalizeCallLlmTurn({+ assistantMessageId: 'assistant-final',+ contextAccounting,+ events: [],+ host: createHost(messages),+ model: 'gpt-4',+ output: createOutput(),+ provider: 'openai',+ shouldReplayAssistantReasoning: false,+ state: AgentRuntime.createInitialState({ operationId: 'operation-1' }),+ });+ expect(messages.update).toHaveBeenLastCalledWith(+ 'assistant-final',+ expect.objectContaining({ metadata: expect.objectContaining({ contextAccounting }) }),+ );++ await persistInterruptedCallLlmResult({+ assistantMessageId: 'assistant-interrupted',+ contextAccounting,+ host: createHost(messages),+ output: createOutput({ content: 'Partial' }),+ });+ expect(messages.update).toHaveBeenLastCalledWith(+ 'assistant-interrupted',+ expect.objectContaining({ metadata: expect.objectContaining({ contextAccounting }) }),+ );+ });+it('persists partial interrupted output and skips empty interruptions', async () => {const messages = createMessageTransport();const host = createHost(messages);diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.tsindex a478d79c03f..304cf92f380 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts@@ -1,5 +1,6 @@import type {ChatToolPayload,+ MessageContextAccounting,MessageMetadata,MessageToolCall,ModelPerformance,@@ -48,6 +49,8 @@ interface FinalizeCallLlmTurnInput {assistantMessageId: string;/** Provider attempts spent on this call, including retries. */attempts?: number;+ /** Estimated accounting of the request this turn sent; persisted on the message. */+ contextAccounting?: MessageContextAccounting;events: AgentEvent[];host: AgentRuntimeHost;model: string;@@ -61,12 +64,14 @@ interface FinalizeCallLlmTurnInput {interface PersistInterruptedCallLlmResultInput {assistantMessageId: string;+ contextAccounting?: MessageContextAccounting;host: AgentRuntimeHost;output: LLMAttemptOutput;}const buildMessageMetadata = ({answerSalvagedFromReasoning,+ contextAccounting,currentStepSpeed,currentStepUsage,executionSite,@@ -76,6 +81,7 @@ const buildMessageMetadata = ({usageEstimated,}: {answerSalvagedFromReasoning?: boolean;+ contextAccounting?: MessageContextAccounting;currentStepSpeed?: ModelPerformance;currentStepUsage?: ModelUsage;executionSite?: LLMAttemptOutput['executionSite'];@@ -87,6 +93,7 @@ const buildMessageMetadata = ({const metadata: CallLlmMessageMetadata = {...(currentStepUsage && { ...currentStepUsage, usage: currentStepUsage }),...(currentStepSpeed && { ...currentStepSpeed, performance: currentStepSpeed }),+ ...(contextAccounting && { contextAccounting }),...(finishType && { finishType }),...(hasContentImages && { isMultimodal: true }),...(answerSalvagedFromReasoning && { answerSalvagedFromReasoning: true }),@@ -180,10 +187,14 @@ const buildWorkAnchor = ({const persistFinalMessage = async ({assistantMessageId,+ contextAccounting,host,output,state,-}: Pick<FinalizeCallLlmTurnInput, 'assistantMessageId' | 'host' | 'output' | 'state'>) => {+}: Pick<+ FinalizeCallLlmTurnInput,+ 'assistantMessageId' | 'contextAccounting' | 'host' | 'output' | 'state'+>) => {const finalContent = output.hasContentImages? serializePartsForStorage(output.contentParts): output.content;@@ -193,6 +204,7 @@ const persistFinalMessage = async ({const aborted = output.finishReason === 'abort';const metadata = buildMessageMetadata({answerSalvagedFromReasoning: output.answerSalvagedFromReasoning,+ contextAccounting,currentStepSpeed: output.speed,currentStepUsage: output.usage,executionSite: output.executionSite,@@ -300,6 +312,7 @@ const buildFinalState = ({export const finalizeCallLlmTurn = async ({assistantMessageId,attempts,+ contextAccounting,events,host,model,@@ -388,6 +401,7 @@ export const finalizeCallLlmTurn = async ({const finalReasoning = await persistFinalMessage({assistantMessageId,+ contextAccounting,host,output: finalizedOutput,state,@@ -458,6 +472,7 @@ export const finalizeCallLlmTurn = async ({export const persistInterruptedCallLlmResult = async ({assistantMessageId,+ contextAccounting,host,output,}: PersistInterruptedCallLlmResultInput): Promise<void> => {@@ -467,6 +482,7 @@ export const persistInterruptedCallLlmResult = async ({await host.transports.messages.update(assistantMessageId, {content: output.content,metadata: buildMessageMetadata({+ contextAccounting,currentStepSpeed: output.speed,currentStepUsage: output.usage,executionSite: output.executionSite,diff --git a/packages/agent-runtime/src/transport/context.ts b/packages/agent-runtime/src/transport/context.tsindex d452282641e..c517cee7b80 100644--- a/packages/agent-runtime/src/transport/context.ts+++ b/packages/agent-runtime/src/transport/context.ts@@ -1,4 +1,5 @@import type { ResolvedToolSet } from '@lobechat/context-engine';+import type { MessageContextAccounting } from '@lobechat/types';import type { AgentState, CallLLMPayload } from '../types';@@ -17,6 +18,12 @@ export interface ContextBuildInput {}export interface ContextBuildOutput {+ /**+ * Estimated token accounting of the final request (processed messages plus+ * the resolved `tools` array). Persisted on the assistant message as+ * `metadata.contextAccounting` for the chat input's context breakdown.+ */+ contextAccounting?: MessageContextAccounting;/** Adapter-native prepared messages; kept in-memory and out of serialized state. */messages: unknown[];/** Adapter-native model extension parameters consumed by the LLM transport. */diff --git a/packages/context-engine/src/index.ts b/packages/context-engine/src/index.tsindex 6d882ae435a..fe68f28cf57 100644--- a/packages/context-engine/src/index.ts+++ b/packages/context-engine/src/index.ts@@ -40,6 +40,14 @@ export type {PlanAttachmentPreviewsParams,} from './tokenAccounting/attachmentBudget';export { planAttachmentPreviews } from './tokenAccounting/attachmentBudget';+export type {+ CountRequestPayloadTokensParams,+ RequestPayloadMessage,+} from './tokenAccounting/requestPayload';+export {+ countRequestPayloadTokens,+ tryCountRequestPayloadTokens,+} from './tokenAccounting/requestPayload';// Processorsexport type { PlaceholderValue, PlaceholderValueMap } from './processors';export {diff --git a/packages/context-engine/src/tokenAccounting/__tests__/requestPayload.test.ts b/packages/context-engine/src/tokenAccounting/__tests__/requestPayload.test.tsnew file mode 100644index 00000000000..6fe200540d9--- /dev/null+++ b/packages/context-engine/src/tokenAccounting/__tests__/requestPayload.test.ts@@ -0,0 +1,225 @@+// cspell:ignore tokenx+import { filesPrompts } from '@lobechat/prompts';+import type { ChatFileItem } from '@lobechat/types';+import { estimateTokenCount } from 'tokenx';+import { describe, expect, it, vi } from 'vitest';++import {+ countRequestPayloadTokens,+ type RequestPayloadMessage,+ tryCountRequestPayloadTokens,+} from '../requestPayload';++const tool = {+ function: {+ description: 'Read a file from the workspace',+ name: 'lobe-local-system____readFile____builtin',+ parameters: { properties: { path: { type: 'string' } }, type: 'object' },+ },+ type: 'function',+};++const fileList = [+ {+ content: 'quarterly revenue grew 12% year over year '.repeat(20),+ fileType: 'text/plain',+ id: 'file_1',+ name: 'report.txt',+ size: 1024,+ url: 'https://example.com/report.txt',+ },+] as ChatFileItem[];++describe('countRequestPayloadTokens', () => {+ it('returns zero accounting for an empty request', () => {+ expect(countRequestPayloadTokens({ messages: [] })).toEqual({+ bySource: {+ content: 0,+ fileContext: 0,+ reasoning: 0,+ thoughtSignature: 0,+ toolCallId: 0,+ toolCalls: 0,+ toolDefinition: 0,+ },+ estimator: 'tokenx',+ messageCount: 0,+ system: 0,+ total: 0,+ });+ });++ it('separates system messages from the conversation', () => {+ const systemRole = 'You are a careful analyst. '.repeat(30);+ const result = countRequestPayloadTokens({+ messages: [+ { content: systemRole, role: 'system' },+ { content: 'hello', role: 'user' },+ ],+ });++ expect(result.system).toBe(estimateTokenCount(systemRole));+ expect(result.bySource.content).toBe(estimateTokenCount('hello'));+ expect(result.total).toBe(result.system + result.bySource.content);+ });++ it('counts the tools array as toolDefinition', () => {+ const result = countRequestPayloadTokens({+ messages: [{ content: 'hi', role: 'user' }],+ tools: [tool],+ });++ expect(result.bySource.toolDefinition).toBe(estimateTokenCount(JSON.stringify(tool)));+ });++ it('splits inlined <files_info> blocks out of user content as fileContext', () => {+ const filesContext = filesPrompts({ addUrl: true, fileList, imageList: [] });+ const result = countRequestPayloadTokens({+ messages: [+ {+ content: [{ text: `summarize this\n\n${filesContext}`, type: 'text' }],+ role: 'user',+ },+ ],+ });++ const filesInfo = filesContext.match(/<files_info>[\s\S]*<\/files_info>/)![0];+ expect(result.bySource.fileContext).toBe(estimateTokenCount(filesInfo));+ expect(result.bySource.fileContext).toBeGreaterThan(100);+ // The wrapper around the block and the user's own words stay in content.+ expect(result.bySource.content).toBe(+ estimateTokenCount(`summarize this\n\n${filesContext}`.replace(filesInfo, '')),+ );+ });++ it('splits several blocks and leaves an unclosed tag in content', () => {+ const blockA = '<files_info>alpha report</files_info>';+ const blockB = '<files_info>beta report</files_info>';+ const text = `intro ${blockA} middle ${blockB} tail <files_info> never closed`;++ const result = countRequestPayloadTokens({ messages: [{ content: text, role: 'user' }] });++ expect(result.bySource.fileContext).toBe(estimateTokenCount(blockA + blockB));+ expect(result.bySource.content).toBe(+ estimateTokenCount('intro middle tail <files_info> never closed'),+ );+ });++ // ROOT CAUSE: a lazy `<files_info>[\s\S]*?</files_info>` regex over user+ // text rescanned to the end once per unclosed opening tag (quadratic; flagged+ // by CodeQL as a polynomial regex on uncontrolled data).+ it('stays linear on user text made of unclosed <files_info> tags', () => {+ const hostile = '<files_info>'.repeat(80_000);++ const result = countRequestPayloadTokens({ messages: [{ content: hostile, role: 'user' }] });++ expect(result.bySource.fileContext).toBe(0);+ expect(result.bySource.content).toBe(estimateTokenCount(hostile));+ });++ it('counts tool calls, tool results, tool_call_id, reasoning and signatures', () => {+ const toolResult = 'line one of the file\n'.repeat(200);+ const messages: RequestPayloadMessage[] = [+ { content: 'read the file', role: 'user' },+ {+ content: '',+ reasoning: { content: 'I should read the file first.', signature: 'sig'.repeat(40) },+ role: 'assistant',+ tool_calls: [+ {+ function: { arguments: '{"path":"/tmp/a.txt"}', name: tool.function.name },+ id: 'call_1',+ thoughtSignature: 'gemini'.repeat(20),+ type: 'function',+ },+ ],+ },+ { content: toolResult, role: 'tool', tool_call_id: 'call_1' },+ ];++ const result = countRequestPayloadTokens({ messages });++ expect(result.bySource.content).toBe(+ estimateTokenCount('read the file') + estimateTokenCount(toolResult),+ );+ expect(result.bySource.toolCalls).toBe(+ estimateTokenCount('call_1') ++ estimateTokenCount(tool.function.name) ++ estimateTokenCount('{"path":"/tmp/a.txt"}') ++ estimateTokenCount('function'),+ );+ expect(result.bySource.toolCallId).toBe(estimateTokenCount('call_1'));+ expect(result.bySource.reasoning).toBe(estimateTokenCount('I should read the file first.'));+ expect(result.bySource.thoughtSignature).toBe(+ estimateTokenCount('gemini'.repeat(20)) + estimateTokenCount('sig'.repeat(40)),+ );+ });++ it('grows the conversation total when a tool result is appended', () => {+ const before: RequestPayloadMessage[] = [+ { content: 'read the file', role: 'user' },+ {+ content: '',+ role: 'assistant',+ tool_calls: [+ { function: { arguments: '{}', name: 'readFile' }, id: 'call_1', type: 'function' },+ ],+ },+ ];+ const after = [+ ...before,+ { content: 'file body '.repeat(500), role: 'tool', tool_call_id: 'call_1' },+ ];++ const a = countRequestPayloadTokens({ messages: before });+ const b = countRequestPayloadTokens({ messages: after });++ expect(b.bySource.content - a.bySource.content).toBe(+ estimateTokenCount('file body '.repeat(500)),+ );+ expect(b.messageCount).toBe(3);+ });++ it('falls back to reasoning_content and skips media parts', () => {+ const result = countRequestPayloadTokens({+ messages: [+ {+ content: [+ { text: 'what is in this image?', type: 'text' },+ {+ image_url: { url: `data:image/png;base64,${'A'.repeat(10_000)}` },+ type: 'image_url',+ },+ ],+ role: 'user',+ },+ { content: 'a cat', reasoning_content: 'looks like a cat', role: 'assistant' },+ ],+ });++ expect(result.bySource.content).toBe(+ estimateTokenCount('what is in this image?') + estimateTokenCount('a cat'),+ );+ expect(result.bySource.reasoning).toBe(estimateTokenCount('looks like a cat'));+ });+});++describe('tryCountRequestPayloadTokens', () => {+ it('returns the accounting when counting succeeds', () => {+ const params = { messages: [{ content: 'hello', role: 'user' }] };++ expect(tryCountRequestPayloadTokens(params)).toEqual(countRequestPayloadTokens(params));+ });++ it('returns undefined instead of throwing when the payload cannot be counted', () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const circular: Record<string, unknown> = {};+ circular.self = circular;++ expect(+ tryCountRequestPayloadTokens({ messages: [{ content: circular, role: 'user' }] }),+ ).toBeUndefined();+ expect(errorSpy).toHaveBeenCalled();+ errorSpy.mockRestore();+ });+});diff --git a/packages/context-engine/src/tokenAccounting/requestPayload.ts b/packages/context-engine/src/tokenAccounting/requestPayload.tsnew file mode 100644index 00000000000..ec88b1f34b9--- /dev/null+++ b/packages/context-engine/src/tokenAccounting/requestPayload.ts@@ -0,0 +1,197 @@+// cspell:ignore tokenx+import type { MessageContextAccounting, UIChatMessage } from '@lobechat/types';+import { estimateTokenCount } from 'tokenx';++import { countContextTokens } from './index';++/**+ * One message of a final chat request payload (OpenAI chat shape), as produced+ * by the context engine and sent to the model runtime. Typed structurally so+ * both `@lobechat/types` and `@lobechat/model-runtime` message types fit.+ */+export interface RequestPayloadMessage {+ content?: unknown;+ reasoning?: { content?: string; signature?: string } | string;+ reasoning_content?: string;+ role: string;+ tool_call_id?: string;+ tool_calls?: ReadonlyArray<{+ function?: { arguments?: string; name?: string };+ id?: string;+ thoughtSignature?: string;+ type?: string;+ }>;+}++export interface CountRequestPayloadTokensParams {+ /** Processed messages exactly as they are sent, system messages included. */+ messages: readonly RequestPayloadMessage[];+ /** The request's top-level `tools` array; omit when the request has none. */+ tools?: readonly unknown[];+}++/** The `<files_info>` block MessageContentProcessor appends to user content. */+const FILES_INFO_OPEN = '<files_info>';+const FILES_INFO_CLOSE = '</files_info>';++const estimate = (text: string | undefined) => (text ? estimateTokenCount(text) : 0);++/**+ * Text the provider tokenizes. Image, video and audio parts are skipped, as in+ * `countContextTokens`: providers bill them by media size, not by their+ * (often base64) URL text.+ */+const toText = (content: unknown): string => {+ if (content == null) return '';+ if (typeof content === 'string') return content;+ if (!Array.isArray(content)) return JSON.stringify(content);++ return content+ .map((part) =>+ part && typeof part === 'object' && part.type === 'text' && typeof part.text === 'string'+ ? part.text+ : '',+ )+ .filter(Boolean)+ .join('\n');+};++/**+ * Split `<files_info>…</files_info>` blocks out of user text. A linear scan,+ * not a lazy regex: user text is uncontrolled, and many unclosed opening tags+ * would make the regex rescan to the end once per tag.+ */+const splitFileContext = (text: string) => {+ let fileContext = '';+ let rest = '';+ let cursor = 0;++ while (cursor < text.length) {+ const start = text.indexOf(FILES_INFO_OPEN, cursor);+ if (start === -1) break;++ const end = text.indexOf(FILES_INFO_CLOSE, start + FILES_INFO_OPEN.length);+ // No closing tag after this opening means none after any later one either.+ if (end === -1) break;++ const blockEnd = end + FILES_INFO_CLOSE.length;+ rest += text.slice(cursor, start);+ fileContext += text.slice(start, blockEnd);+ cursor = blockEnd;+ }++ return { fileContext, rest: rest + text.slice(cursor) };+};++const toReasoning = (message: RequestPayloadMessage) => {+ if (message.reasoning) return message.reasoning;+ return message.reasoning_content ? { content: message.reasoning_content } : undefined;+};++/**+ * Map a payload message onto the `UIChatMessage` fields `countContextTokens`+ * reads, so the request is counted with the same rules as the compression+ * trigger: `tool_calls` become `tools` (id + name + arguments + type ++ * thoughtSignature), tool results stay `content` with their `tool_call_id`.+ */+const toAccountingMessage = (+ message: RequestPayloadMessage,+ content: string,+ index: number,+): UIChatMessage =>+ ({+ content,+ id: `request_payload_${index}`,+ reasoning: toReasoning(message),+ role: message.role,+ tool_call_id: message.tool_call_id,+ tools: message.tool_calls?.map((toolCall) => ({+ apiName: toolCall.function?.name,+ arguments: toolCall.function?.arguments,+ id: toolCall.id,+ thoughtSignature: toolCall.thoughtSignature,+ type: toolCall.type,+ })),+ }) as unknown as UIChatMessage;++/**+ * Estimate every token of one final chat request — the processed messages and+ * the `tools` array — by source, reusing {@link countContextTokens}.+ *+ * Unlike the compression trigger, which counts the stored conversation, this+ * counts what the context engine actually assembled: the system messages with+ * everything injected into them, history after truncation, and attachment+ * text inlined as `<files_info>` blocks (reported as `fileContext`). A+ * thinking signature replayed with a reasoning block counts with the per-call+ * `thoughtSignature`s, the other opaque signature a request echoes back.+ *+ * Counts are raw `tokenx` estimates (no drift multiplier).+ */+export const countRequestPayloadTokens = ({+ messages,+ tools = [],+}: CountRequestPayloadTokensParams): MessageContextAccounting => {+ const systemMessages: UIChatMessage[] = [];+ const conversationMessages: UIChatMessage[] = [];+ let fileContext = 0;+ let reasoningSignature = 0;++ messages.forEach((message, index) => {+ let content = toText(message.content);++ if (message.role === 'user') {+ const split = splitFileContext(content);+ content = split.rest;+ fileContext += estimate(split.fileContext);+ }++ const reasoning = toReasoning(message);+ if (reasoning && typeof reasoning === 'object') {+ reasoningSignature += estimate(reasoning.signature);+ }++ const target = message.role === 'system' ? systemMessages : conversationMessages;+ target.push(toAccountingMessage(message, content, index));+ });++ const options = { driftMultiplier: 1 };+ const system = countContextTokens({ messages: systemMessages, options }).rawTotal;+ const conversation = countContextTokens({+ messages: conversationMessages,+ options,+ tools: [...tools],+ });++ const bySource = {+ ...conversation.bySource,+ fileContext: conversation.bySource.fileContext + fileContext,+ thoughtSignature: conversation.bySource.thoughtSignature + reasoningSignature,+ };++ let total = system;+ for (const value of Object.values(bySource)) total += value;++ return {+ bySource,+ estimator: 'tokenx',+ messageCount: messages.length,+ system,+ total,+ };+};++/**+ * {@link countRequestPayloadTokens} for callers on the request path, where the+ * result is display-only: a counting failure is logged and yields `undefined`+ * instead of failing the model call.+ */+export const tryCountRequestPayloadTokens = (+ params: CountRequestPayloadTokensParams,+): MessageContextAccounting | undefined => {+ try {+ return countRequestPayloadTokens(params);+ } catch (error) {+ console.error('[context-engine] Failed to account request tokens:', error);+ return undefined;+ }+};diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex ebb7e2afdfa..bc724bfa7c6 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3474,11 +3474,19 @@ export default {'toggleWideScreen.off': 'Turn off widescreen mode','toggleWideScreen.on': 'Turn on widescreen mode','tokenDetails.chats': 'Chat Messages',+ 'tokenDetails.estimated': 'Estimated',+ 'tokenDetails.estimatedTooltip':+ 'Counted with a generic tokenizer over the request body. Each model uses its own tokenizer, so the input it bills can differ.',+ 'tokenDetails.fileContext': 'Attachments','tokenDetails.historySummary': 'History Summary',+ 'tokenDetails.lastRequestInput': 'Last request input (reported by model)',+ 'tokenDetails.reasoning': 'Reasoning','tokenDetails.rest': 'Remaining','tokenDetails.supervisor': 'Orchestrator',+ 'tokenDetails.system': 'System Prompt','tokenDetails.systemRole': 'Role Settings','tokenDetails.title': 'Context Details',+ 'tokenDetails.toolCalls': 'Tool Calls','tokenDetails.tools': 'Skill Settings','tokenDetails.total': 'Total Available','tokenDetails.used': 'Total Used',diff --git a/packages/types/src/message/common/contextAccounting.test.ts b/packages/types/src/message/common/contextAccounting.test.tsnew file mode 100644index 00000000000..5d8bceb2b5c--- /dev/null+++ b/packages/types/src/message/common/contextAccounting.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';++import { MessageContextAccountingSchema } from './contextAccounting';+import { MessageMetadataSchema } from './metadata';++const accounting = {+ bySource: {+ content: 1,+ fileContext: 2,+ reasoning: 3,+ thoughtSignature: 4,+ toolCallId: 5,+ toolCalls: 6,+ toolDefinition: 7,+ },+ estimator: 'tokenx' as const,+ messageCount: 3,+ system: 10,+ total: 38,+};++describe('MessageContextAccountingSchema', () => {+ it('keeps a recorded accounting through message metadata writes', () => {+ expect(+ MessageMetadataSchema.parse({ contextAccounting: accounting }).contextAccounting,+ ).toEqual(accounting);+ });++ it('coerces a shape from another runtime version instead of rejecting the write', () => {+ expect(+ MessageContextAccountingSchema.parse({+ bySource: { content: 1, image: 9 },+ estimator: 'o200k',+ messageCount: 1,+ system: 2,+ total: 3,+ }),+ ).toEqual({+ bySource: {+ ...accounting.bySource,+ content: 1,+ fileContext: 0,+ reasoning: 0,+ thoughtSignature: 0,+ toolCallId: 0,+ toolCalls: 0,+ toolDefinition: 0,+ },+ estimator: 'tokenx',+ messageCount: 1,+ system: 2,+ total: 3,+ });+ });+});diff --git a/packages/types/src/message/common/contextAccounting.ts b/packages/types/src/message/common/contextAccounting.tsnew file mode 100644index 00000000000..c268894eda6--- /dev/null+++ b/packages/types/src/message/common/contextAccounting.ts@@ -0,0 +1,75 @@+import { z } from 'zod';++/**+ * Token source categories of one LLM request, matching `TokenSourceType` in+ * `@lobechat/context-engine` (`countContextTokens`).+ */+export const MESSAGE_CONTEXT_TOKEN_SOURCES = [+ 'content',+ 'fileContext',+ 'toolCalls',+ 'thoughtSignature',+ 'reasoning',+ 'toolCallId',+ 'toolDefinition',+] as const;++export type MessageContextTokenSource = (typeof MESSAGE_CONTEXT_TOKEN_SOURCES)[number];++/**+ * Estimated input-token accounting of the request that produced an assistant+ * message, computed by the agent runtime from the final request payload+ * (processed messages plus the `tools` array actually sent).+ *+ * The counts come from the `tokenx` heuristic, not the provider tokenizer:+ * read them as an estimate of what the request contained, never as billing.+ */+export interface MessageContextAccounting {+ /**+ * Non-system messages and the `tools` array, split by source. Tool results+ * count under `content`; `<files_info>` attachment blocks under `fileContext`.+ */+ bySource: Record<MessageContextTokenSource, number>;+ /** Estimator behind the counts. */+ estimator: 'tokenx';+ /** Number of messages in the request, system messages included. */+ messageCount: number;+ /**+ * System messages: the agent system role plus everything the context engine+ * injects there (tool prompts, memory, history summary, …).+ */+ system: number;+ /** `system` plus every `bySource` value. */+ total: number;+}++// Lenient on purpose: client writes echo stored metadata back through this+// schema, so a value written by an older or newer runtime is coerced instead+// of failing the whole write.+const tokens = z.number().catch(0);++export const MessageContextAccountingSchema = z.object({+ bySource: z+ .object({+ content: tokens,+ fileContext: tokens,+ reasoning: tokens,+ thoughtSignature: tokens,+ toolCallId: tokens,+ toolCalls: tokens,+ toolDefinition: tokens,+ })+ .catch({+ content: 0,+ fileContext: 0,+ reasoning: 0,+ thoughtSignature: 0,+ toolCallId: 0,+ toolCalls: 0,+ toolDefinition: 0,+ }),+ estimator: z.literal('tokenx').catch('tokenx'),+ messageCount: tokens,+ system: tokens,+ total: tokens,+});diff --git a/packages/types/src/message/common/index.ts b/packages/types/src/message/common/index.tsindex 67dd7f42b48..dfc9d21a772 100644--- a/packages/types/src/message/common/index.ts+++ b/packages/types/src/message/common/index.ts@@ -1,5 +1,6 @@export * from './base';export * from './composerUserMessage';+export * from './contextAccounting';export * from './contextSelection';export * from './image';export * from './messageGroup';diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex d5022dcac3f..f42c06acdea 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -2,6 +2,8 @@ import { z } from 'zod';import { RequestTrigger } from '../../agentRuntime';import type { WorkRegistrationIntent } from '../../work';+import type { MessageContextAccounting } from './contextAccounting';+import { MessageContextAccountingSchema } from './contextAccounting';import type { ContextSelection } from './contextSelection';import { ContextSelectionSchema } from './contextSelection';import type { PageSelection } from './pageSelection';@@ -452,6 +454,9 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceScheagentDispatch: AgentDispatchMetadataSchema.optional(),agentSender: AgentSenderMetadataSchema.optional(),collapsed: z.boolean().optional(),+ // Server-computed estimate of the request behind an assistant message. Listed+ // so client-runtime writes through UpdateMessageParamsSchema keep it.+ contextAccounting: MessageContextAccountingSchema.optional(),contextSelections: z.array(ContextSelectionSchema).optional(),// Hetero-agent (Claude Code) per-message provenance. Listed here so zod does// NOT strip them from writes going through UpdateMessageParamsSchema /@@ -591,6 +596,13 @@ export interface MessageMetadata {*/collapsed?: boolean;compare?: boolean;+ /**+ * Estimated token accounting of the request that produced this assistant+ * message (system messages, `tools` array and every message part), written+ * by the agent runtime. The chat input's context breakdown reads the latest+ * one; see {@link MessageContextAccounting}.+ */+ contextAccounting?: MessageContextAccounting;/*** Generic context selections attached to user messages.* Page selections remain mirrored in `pageSelections` for compatibility.diff --git a/src/features/ChatInput/ActionBar/Token/TokenDetails.tsx b/src/features/ChatInput/ActionBar/Token/TokenDetails.tsxindex de42036f7bb..3ed7b935b2e 100644--- a/src/features/ChatInput/ActionBar/Token/TokenDetails.tsx+++ b/src/features/ChatInput/ActionBar/Token/TokenDetails.tsx@@ -1,3 +1,4 @@+import { formatUsageValue } from '@lobechat/utils';import { Center, cssVar, Flexbox, Tooltip } from '@lobehub/ui';import numeral from 'numeral';import { memo } from 'react';@@ -16,14 +17,30 @@ interface TokenDetailsProps {const TokenDetails = memo<TokenDetailsProps>(({ breakdown }) => {const { t } = useTranslation(['chat', 'components']);- const { chatsToken, historySummaryToken, maxTokens, systemRoleToken, toolsToken, totalToken } =- breakdown;+ const {+ chatsToken,+ fileContextToken,+ lastRequestInputTokens,+ maxTokens,+ reasoningToken,+ systemToken,+ toolCallsToken,+ toolsToken,+ totalToken,+ } = breakdown;const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);return (<Flexbox gap={12} style={{ minWidth: 200 }}><Flexbox horizontal align={'center'} gap={4} justify={'space-between'} width={'100%'}>- <div style={{ color: cssVar.colorTextDescription }}>{t('tokenDetails.title')}</div>+ <Flexbox horizontal align={'baseline'} gap={6}>+ <div style={{ color: cssVar.colorTextDescription }}>{t('tokenDetails.title')}</div>+ <Tooltip title={t('tokenDetails.estimatedTooltip')}>+ <div style={{ color: cssVar.colorTextQuaternary, cursor: 'help', fontSize: 12 }}>+ {t('tokenDetails.estimated')}+ </div>+ </Tooltip>+ </Flexbox><Tooltipstyles={{ root: { maxWidth: 'unset', pointerEvents: 'none' } }}title={t('ModelSelect.featureTag.tokens', {@@ -52,9 +69,9 @@ const TokenDetails = memo<TokenDetailsProps>(({ breakdown }) => {data={[{color: cssVar.magenta,- id: 'systemRole',- title: t('tokenDetails.systemRole'),- value: systemRoleToken,+ id: 'system',+ title: t('tokenDetails.system'),+ value: systemToken,},{color: cssVar.geekblue,@@ -62,18 +79,30 @@ const TokenDetails = memo<TokenDetailsProps>(({ breakdown }) => {title: t('tokenDetails.tools'),value: toolsToken,},- {- color: cssVar.orange,- id: 'historySummary',- title: t('tokenDetails.historySummary'),- value: historySummaryToken,- },{color: cssVar.gold,id: 'chats',title: t('tokenDetails.chats'),value: chatsToken,},+ {+ color: cssVar.orange,+ id: 'fileContext',+ title: t('tokenDetails.fileContext'),+ value: fileContextToken,+ },+ {+ color: cssVar.cyan,+ id: 'toolCalls',+ title: t('tokenDetails.toolCalls'),+ value: toolCallsToken,+ },+ {+ color: cssVar.purple,+ id: 'reasoning',+ title: t('tokenDetails.reasoning'),+ value: reasoningToken,+ },]}/>)}@@ -95,6 +124,16 @@ const TokenDetails = memo<TokenDetailsProps>(({ breakdown }) => {},]}/>+ {!!lastRequestInputTokens && (+ <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>+ <div style={{ color: cssVar.colorTextDescription }}>+ {t('tokenDetails.lastRequestInput')}+ </div>+ <div style={{ color: cssVar.colorTextSecondary }}>+ {formatUsageValue(lastRequestInputTokens)}+ </div>+ </Flexbox>+ )}</Flexbox>);});diff --git a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx b/src/features/ChatInput/ActionBar/Token/TokenTag.tsxindex 18396328af1..f36e99718ff 100644--- a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx+++ b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx@@ -12,24 +12,10 @@ import { useTokenBreakdown } from './useTokenBreakdown';const Token = memo(() => {const { t } = useTranslation('chat');- const { chatsToken, historySummaryToken, maxTokens, systemRoleToken, toolsToken, totalToken } =- useTokenBreakdown();+ const breakdown = useTokenBreakdown();+ const { maxTokens, totalToken } = breakdown;const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);- const content = useMemo(- () => (- <TokenDetails- breakdown={{- chatsToken,- historySummaryToken,- maxTokens,- systemRoleToken,- toolsToken,- totalToken,- }}- />- ),- [chatsToken, historySummaryToken, maxTokens, systemRoleToken, toolsToken, totalToken],- );+ const content = useMemo(() => <TokenDetails breakdown={breakdown} />, [breakdown]);// Keep the composer quiet for regular users until context pressure is real;// dev mode always shows the tag for inspection.diff --git a/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.test.ts b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.test.tsindex a5e75e51d8b..bf5d9bc1bd1 100644--- a/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.test.ts+++ b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.test.ts@@ -1,12 +1,19 @@-import { renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+// cspell:ignore tokenx+import type { UIChatMessage } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { estimateTokenCount } from 'tokenx';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { ContextWindow } from '../../store/initialState';import { useTokenBreakdown } from './useTokenBreakdown';const state = vi.hoisted(() => ({activeTopicId: undefined as string | undefined,/** `undefined`: the host publishes no topic; `null`: its conversation has none. */composerTopicId: undefined as string | null | undefined,+ contextWindow: undefined as ContextWindow | undefined,+ input: '',+ listeners: new Set<() => void>(),summaries: {} as Record<string, string>,}));@@ -31,8 +38,11 @@ vi.mock('../../store', () => ({useChatInputStore: (selector: (s: object) => unknown) =>selector({ topicId: state.composerTopicId }),useStoreApi: () => ({- getState: () => ({ contextWindowMessages: [], markdownContent: '' }),- subscribe: () => () => {},+ getState: () => ({ contextWindow: state.contextWindow, markdownContent: state.input }),+ subscribe: (listener: () => void) => {+ state.listeners.add(listener);+ return () => state.listeners.delete(listener);+ },}),}));@@ -85,16 +95,51 @@ beforeEach(() => {// The main column's topic stays globally active while another composer renders its own.state.activeTopicId = 'main-topic';state.composerTopicId = undefined;+ state.contextWindow = undefined;+ state.input = '';+ state.listeners.clear();state.summaries = { 'main-topic': 'main column summary', 'pane-topic': 'pane' };});+afterEach(() => {+ vi.useRealTimers();+});++/** Publish a composer store change and let the 300ms debounced reader pick it up. */+const publishComposer = (next: Partial<Pick<typeof state, 'contextWindow' | 'input'>>) => {+ Object.assign(state, next);+ act(() => {+ for (const listener of state.listeners) listener();+ vi.advanceTimersByTime(300);+ });+};++const recordedAccounting = {+ bySource: {+ content: 1000,+ fileContext: 300,+ reasoning: 40,+ thoughtSignature: 5,+ toolCallId: 6,+ toolCalls: 70,+ toolDefinition: 4000,+ },+ estimator: 'tokenx' as const,+ messageCount: 5,+ system: 2000,+ total: 7421,+};++const message = (m: Partial<UIChatMessage> & Pick<UIChatMessage, 'id' | 'role'>) =>+ ({ content: '', createdAt: 0, updatedAt: 0, ...m }) as UIChatMessage;+describe('useTokenBreakdown', () => {it("counts the composer's own topic summary rather than the global active topic's", () => {state.composerTopicId = 'pane-topic';const { result } = renderHook(() => useTokenBreakdown());- expect(result.current.historySummaryToken).toBe('pane'.length);+ expect(result.current.systemToken).toBe('pane'.length);});it('counts no summary when the composer conversation has no topic, even with an active topic', () => {@@ -102,13 +147,13 @@ describe('useTokenBreakdown', () => {const { result } = renderHook(() => useTokenBreakdown());- expect(result.current.historySummaryToken).toBe(0);+ expect(result.current.systemToken).toBe(0);});it('follows the global active topic when the host publishes no topic', () => {const { result } = renderHook(() => useTokenBreakdown());- expect(result.current.historySummaryToken).toBe('main column summary'.length);+ expect(result.current.systemToken).toBe('main column summary'.length);});// A document's chat panel runs on a `trigger='document'` system topic that@@ -118,12 +163,12 @@ describe('useTokenBreakdown', () => {const { rerender, result } = renderHook(() => useTokenBreakdown());- expect(result.current.historySummaryToken).toBe(0);+ expect(result.current.systemToken).toBe(0);state.summaries['doc-topic'] = 'doc summary';rerender();- expect(result.current.historySummaryToken).toBe('doc summary'.length);+ expect(result.current.systemToken).toBe('doc summary'.length);});// `/goal/:goalId` makes a sidebar-excluded supervision topic globally active@@ -134,11 +179,162 @@ describe('useTokenBreakdown', () => {const { rerender, result } = renderHook(() => useTokenBreakdown());- expect(result.current.historySummaryToken).toBe(0);+ expect(result.current.systemToken).toBe(0);state.summaries['main-topic'] = 'goal summary';rerender();- expect(result.current.historySummaryToken).toBe('goal summary'.length);+ expect(result.current.systemToken).toBe('goal summary'.length);+ });++ it('counts tool calls, tool results and attachments of the conversation, not only text', () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useTokenBreakdown());++ const userTurn = message({+ content: 'read the report',+ fileList: [+ {+ content: 'quarterly revenue grew 12% '.repeat(40),+ fileType: 'text/plain',+ id: 'file_1',+ name: 'report.txt',+ size: 1024,+ url: 'https://example.com/report.txt',+ },+ ],+ id: 'u1',+ role: 'user',+ });+ const toolCall = message({+ id: 'a1',+ role: 'assistant',+ tools: [+ {+ apiName: 'readFile',+ arguments: '{"path":"/tmp/report.txt"}',+ id: 'call_1',+ identifier: 'local-system',+ type: 'builtin',+ },+ ],+ });+ publishComposer({ contextWindow: { history: [userTurn, toolCall] } });++ const before = result.current;+ expect(before.chatsToken).toBe(estimateTokenCount('read the report'));+ expect(before.fileContextToken).toBeGreaterThan(100);+ expect(before.toolCallsToken).toBeGreaterThan(0);++ // ROOT CAUSE: the breakdown only summed string `content`, so a tool result+ // the next request carries never moved the "Chat Messages" row.+ const toolResult = 'line of the file\n'.repeat(300);+ publishComposer({+ contextWindow: {+ history: [+ userTurn,+ toolCall,+ message({ content: toolResult, id: 't1', role: 'tool', tool_call_id: 'call_1' }),+ ],+ },+ });++ expect(result.current.chatsToken - before.chatsToken).toBe(+ estimateTokenCount(toolResult) + estimateTokenCount('call_1'),+ );+ expect(result.current.totalToken).toBeGreaterThan(before.totalToken);+ });++ it('takes system and tools from the recorded request and adds what came after it', () => {+ vi.useFakeTimers();+ state.composerTopicId = 'pane-topic';+ const { result } = renderHook(() => useTokenBreakdown());++ const reply = 'Here is the summary.';+ publishComposer({+ contextWindow: {+ history: [],+ request: {+ accounting: recordedAccounting,+ inputTokens: 9000,+ messages: [+ message({+ content: reply,+ id: 'a1',+ reasoning: { content: 'thinking it over' },+ role: 'assistant',+ // Recorded provider usage must not replace the per-field estimate.+ usage: { totalInputTokens: 9000, totalOutputTokens: 999 },+ }),+ ],+ model: 'model-1',+ provider: 'provider-1',+ },+ },+ input: 'next question',+ });++ expect(result.current).toMatchObject({+ chatsToken: 1000 + 6 + estimateTokenCount(reply) + 'next question'.length,+ fileContextToken: 300,+ lastRequestInputTokens: 9000,+ reasoningToken: 40 + estimateTokenCount('thinking it over'),+ // The recorded system message already carries the pane topic's summary.+ systemToken: 2000,+ toolCallsToken: 75,+ toolsToken: 4000,+ });+ expect(result.current.totalToken).toBe(+ result.current.systemToken ++ result.current.toolsToken ++ result.current.chatsToken ++ result.current.fileContextToken ++ result.current.toolCallsToken ++ result.current.reasoningToken,+ );+ });++ it('estimates from the history window again after the composer switches model', () => {+ vi.useFakeTimers();+ state.composerTopicId = 'pane-topic';+ const { result } = renderHook(() => useTokenBreakdown());++ publishComposer({+ contextWindow: {+ history: [message({ content: 'hello there', id: 'u1', role: 'user' })],+ // Recorded for another model: its tools and system prompt no longer apply.+ request: { accounting: recordedAccounting, messages: [], model: 'other-model' },+ },+ });++ expect(result.current).toMatchObject({+ chatsToken: estimateTokenCount('hello there'),+ // The live estimate: system role (empty) + the pane topic's summary.+ systemToken: 'pane'.length,+ toolsToken: 0,+ });+ });++ it('counts the history window, not recorded messages, when a history count truncates', () => {+ vi.useFakeTimers();+ const { result } = renderHook(() => useTokenBreakdown());++ publishComposer({+ contextWindow: {+ history: [message({ content: 'latest question', id: 'u9', role: 'user' })],+ // No `messages`: the recorded request's history may drop out of the next one.+ request: { accounting: recordedAccounting, model: 'model-1', provider: 'provider-1' },+ },+ });++ expect(result.current).toMatchObject({+ chatsToken: estimateTokenCount('latest question'),+ fileContextToken: 0,+ reasoningToken: 0,+ // System and tools still come from the recorded request.+ systemToken: 2000,+ toolCallsToken: 0,+ toolsToken: 4000,+ });});});diff --git a/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.tsindex 77010fa94de..f5f33466927 100644--- a/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts+++ b/src/features/ChatInput/ActionBar/Token/useTokenBreakdown.ts@@ -1,5 +1,10 @@-import { ToolNameResolver } from '@lobechat/context-engine';+import {+ countContextTokens,+ type TokenSourceType,+ ToolNameResolver,+} from '@lobechat/context-engine';import { pluginPrompts } from '@lobechat/prompts';+import type { UIChatMessage } from '@lobechat/types';import { debounce } from 'es-toolkit/compat';import { startTransition, useEffect, useMemo, useState } from 'react';@@ -22,42 +27,109 @@ import { useAgentId } from '../../hooks/useAgentId';import { useEffectiveModel } from '../../hooks/useEffectiveModel';import { useTopicId } from '../../hooks/useTopicId';import { useStoreApi } from '../../store';+import type { ContextWindow } from '../../store/initialState';import { getToolContextRefreshKey, getToolExcludeDefaultToolIds } from './utils';const toolNameResolver = new ToolNameResolver();type ChatInputStoreApi = ReturnType<typeof useStoreApi>;+type SourceTokens = Record<TokenSourceType, number>;++const EMPTY_MESSAGES: UIChatMessage[] = [];++/**+ * `countContextTokens` replaces an assistant message's per-field estimate with+ * its recorded provider output count when one exists. Drop that count so the+ * whole breakdown stays on one estimator and the reply's tool calls and+ * reasoning keep their own sources.+ */+const withoutRecordedUsage = (message: UIChatMessage): UIChatMessage =>+ message.usage || message.metadata?.usage+ ? {+ ...message,+ metadata: message.metadata && { ...message.metadata, usage: undefined },+ usage: undefined,+ }+ : message;++const countContextWindowMessages = (messages: UIChatMessage[]): SourceTokens =>+ countContextTokens({+ messages: messages.map(withoutRecordedUsage),+ options: { driftMultiplier: 1 },+ }).bySource;interface ComposerSource {+ /** Sources of `contextWindow.history`, used when no recorded request applies. */+ history: SourceTokens;input: string;- messages: string;+ request?: ContextWindow['request'];+ /** Sources of `contextWindow.request.messages`, the part the request does not cover. */+ sinceRequest: SourceTokens;+}++interface CountCacheSlot {+ messages?: UIChatMessage[];+ tokens: SourceTokens;}-const readComposerSource = (storeApi: ChatInputStoreApi): ComposerSource => {- const state = storeApi.getState();+interface ComposerSourceCache {+ history: CountCacheSlot;+ sinceRequest: CountCacheSlot;+}++const createCountCacheSlot = (): CountCacheSlot => ({+ tokens: countContextWindowMessages(EMPTY_MESSAGES),+});++// The store notifies on every keystroke; only re-count when the messages change.+const countCached = (slot: CountCacheSlot, messages: UIChatMessage[]) => {+ if (slot.messages !== messages) {+ slot.messages = messages;+ slot.tokens = countContextWindowMessages(messages);+ }+ return slot.tokens;+};++const readComposerSource = (+ storeApi: ChatInputStoreApi,+ cache: ComposerSourceCache,+): ComposerSource => {+ const { contextWindow, markdownContent } = storeApi.getState();+return {- input: state.markdownContent || '',- messages:- state.contextWindowMessages- ?.map((message) => (typeof message.content === 'string' ? message.content : ''))- .join('') || '',+ history: countCached(cache.history, contextWindow?.history ?? EMPTY_MESSAGES),+ input: markdownContent || '',+ request: contextWindow?.request,+ sinceRequest: countCached(+ cache.sinceRequest,+ contextWindow?.request?.messages ?? EMPTY_MESSAGES,+ ),};};// A render subscription to `markdownContent` would re-render the tag on every-// keystroke at urgent priority. Read the composer imperatively behind a-// debounce instead, and publish through a transition so token counting never-// competes with typing.+// keystroke at urgent priority, and the conversation re-counts on every+// streamed chunk. Read the composer imperatively behind a debounce instead,+// and publish through a transition so token counting never competes with typing.const useComposerSource = (): ComposerSource => {const storeApi = useStoreApi();- const [source, setSource] = useState<ComposerSource>(() => readComposerSource(storeApi));+ const [cache] = useState<ComposerSourceCache>(() => ({+ history: createCountCacheSlot(),+ sinceRequest: createCountCacheSlot(),+ }));+ const [source, setSource] = useState<ComposerSource>(() => readComposerSource(storeApi, cache));useEffect(() => {const update = debounce(() => {- const next = readComposerSource(storeApi);+ const next = readComposerSource(storeApi, cache);startTransition(() => {setSource((prev) =>- prev.input === next.input && prev.messages === next.messages ? prev : next,+ prev.input === next.input &&+ prev.history === next.history &&+ prev.sinceRequest === next.sinceRequest &&+ prev.request === next.request+ ? prev+ : next,);});}, 300);@@ -67,22 +139,36 @@ const useComposerSource = (): ComposerSource => {unsubscribe();update.cancel();};- }, [storeApi]);+ }, [cache, storeApi]);return source;};+/**+ * Estimated tokens of the conversation's next request, by the parts of the+ * request body they come from. All counts use the `tokenx` estimator.+ */export interface TokenBreakdown {+ /** Message text: user and assistant content, tool results, tool call ids and the draft. */chatsToken: number;- historySummaryToken: number;+ /** Attachment text inlined as `<files_info>` blocks. */+ fileContextToken: number;+ /** Provider-reported input tokens of the latest recorded request, when known. */+ lastRequestInputTokens?: number;maxTokens: number;- systemRoleToken: number;+ /** Reasoning replayed from earlier assistant turns. */+ reasoningToken: number;+ /** System messages: the system role plus injected tool prompts, memory, history summary… */+ systemToken: number;+ /** Assistant tool call payloads and their thought signatures. */+ toolCallsToken: number;+ /** The request's `tools` array. */toolsToken: number;totalToken: number;}export const useTokenBreakdown = (): TokenBreakdown => {- const { input, messages } = useComposerSource();+ const { history, input, request: recordedRequest, sinceRequest } = useComposerSource();// The summary of this composer's own conversation (see `useTopicId`), never// the global active topic's: an embedded composer would otherwise count the// outer chat's history against its context window.@@ -95,6 +181,19 @@ export const useTokenBreakdown = (): TokenBreakdown => {const agentId = useAgentId();const { model, provider } = useEffectiveModel(agentId);+ // A request recorded for another model carried that model's tools and system+ // prompt; after a model switch, estimate the next request from scratch.+ const request =+ recordedRequest &&+ (!recordedRequest.model || recordedRequest.model === model) &&+ (!recordedRequest.provider || recordedRequest.provider === provider)+ ? recordedRequest+ : undefined;+ const hasRequest = !!request;+ // The recorded messages plus what came after describe the next request only+ // while nothing drops out of history; otherwise count the history window.+ const recordedMessages = request?.messages ? request.accounting.bySource : undefined;+ const messages = recordedMessages ? sinceRequest : history;const [activeAgentId,systemRole,@@ -150,7 +249,11 @@ export const useTokenBreakdown = (): TokenBreakdown => {const pluginIds = useAgentStore((s) => agentByIdSelectors.getAgentPluginsById(agentId)(s));const installedPlugins = useToolStore((s) => s.installedPlugins);- const toolsString = useMemo(() => {+ // The fallback for a conversation with no recorded request yet. Once the+ // runtime has recorded one, its system and tools counts are authoritative.+ const { toolsSchema, toolsSystemRole } = useMemo(() => {+ if (hasRequest) return { toolsSchema: '', toolsSystemRole: '' };+const toolsEngine = createAgentToolsEngine({ model, provider });const { tools, enabledManifests } = toolsEngine.generateToolsDetailed({@@ -159,39 +262,85 @@ export const useTokenBreakdown = (): TokenBreakdown => {provider,toolIds: pluginIds,});- const schemaNumber = tools?.map((i) => JSON.stringify(i)).join('') || '';-- const toolsSystemRole =- enabledManifests.length > 0- ? pluginPrompts({- tools: enabledManifests.map((manifest) => ({- apis: manifest.api.map((api) => ({- desc: api.description,- name: toolNameResolver.generate(manifest.identifier, api.name, manifest.type),++ return {+ toolsSchema: tools?.map((i) => JSON.stringify(i)).join('') || '',+ // Tool prompts are injected into the system message, not the tools array.+ toolsSystemRole:+ enabledManifests.length > 0+ ? pluginPrompts({+ tools: enabledManifests.map((manifest) => ({+ apis: manifest.api.map((api) => ({+ desc: api.description,+ name: toolNameResolver.generate(manifest.identifier, api.name, manifest.type),+ })),+ identifier: manifest.identifier,+ name: pluginHelpers.getPluginTitle(manifest.meta) || manifest.identifier,+ systemRole: manifest.systemRole,})),- identifier: manifest.identifier,- name: pluginHelpers.getPluginTitle(manifest.meta) || manifest.identifier,- systemRole: manifest.systemRole,- })),- })- : '';-- return toolsSystemRole + schemaNumber;+ })+ : '',+ };// installedPlugins + toolContextRefreshKey track the implicit// createAgentToolsEngine inputs read via getState() (tool manifests plus// agent/user/aiInfra config), so the engine only re-runs when they change// instead of on every render.- }, [installedPlugins, model, pluginIds, provider, skillActivateMode, toolContextRefreshKey]);-- const toolsToken = useTokenCount(canUseTool ? toolsString : '');+ }, [+ hasRequest,+ installedPlugins,+ model,+ pluginIds,+ provider,+ skillActivateMode,+ toolContextRefreshKey,+ ]);+ const toolsSchemaToken = useTokenCount(canUseTool ? toolsSchema : '');+ const toolsSystemRoleToken = useTokenCount(canUseTool ? toolsSystemRole : '');+ const systemRoleToken = useTokenCount(hasRequest ? '' : systemRole);+ const historySummaryToken = useTokenCount(hasRequest ? '' : historySummary);const inputTokenCount = useTokenCount(input);- const chatsToken = useTokenCount(messages) + inputTokenCount;- const systemRoleToken = useTokenCount(systemRole);- const historySummaryToken = useTokenCount(historySummary);+ const recorded = request?.accounting;+ const sum = (key: TokenSourceType) => (recordedMessages?.[key] ?? 0) + messages[key];++ const systemToken = recorded+ ? recorded.system+ : systemRoleToken + historySummaryToken + toolsSystemRoleToken;+ const toolsToken = recorded ? recorded.bySource.toolDefinition : toolsSchemaToken;+ const chatsToken = sum('content') + sum('toolCallId') + inputTokenCount;+ const fileContextToken = sum('fileContext');+ const toolCallsToken = sum('toolCalls') + sum('thoughtSignature');+ const reasoningToken = sum('reasoning');- const totalToken = systemRoleToken + historySummaryToken + toolsToken + chatsToken;+ const totalToken =+ systemToken + toolsToken + chatsToken + fileContextToken + toolCallsToken + reasoningToken;- return { chatsToken, historySummaryToken, maxTokens, systemRoleToken, toolsToken, totalToken };+ const lastRequestInputTokens = request?.inputTokens;++ // A stable object, so the popover content only re-renders when a count changes.+ return useMemo(+ () => ({+ chatsToken,+ fileContextToken,+ lastRequestInputTokens,+ maxTokens,+ reasoningToken,+ systemToken,+ toolCallsToken,+ toolsToken,+ totalToken,+ }),+ [+ chatsToken,+ fileContextToken,+ lastRequestInputTokens,+ maxTokens,+ reasoningToken,+ systemToken,+ toolCallsToken,+ toolsToken,+ totalToken,+ ],+ );};diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsxindex dea862863f9..6c22883205c 100644--- a/src/features/ChatInput/ChatInputProvider.tsx+++ b/src/features/ChatInput/ChatInputProvider.tsx@@ -18,7 +18,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(canRecordVoiceMessage,children,contextSelectionKey,- contextWindowMessages,+ contextWindow,draftKey,feature = DEFAULT_CHAT_INPUT_FEATURE,leftActions,@@ -48,7 +48,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(allowExpand,canRecordVoiceMessage,contextSelectionKey,- contextWindowMessages,+ contextWindow,draftKey,editor,feature,@@ -72,7 +72,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(canRecordVoiceMessage={canRecordVoiceMessage}chatInputEditorRef={chatInputEditorRef}contextSelectionKey={contextSelectionKey}- contextWindowMessages={contextWindowMessages}+ contextWindow={contextWindow}draftKey={draftKey}feature={feature}getMessages={getMessages}diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsxindex fa60ad1ebdf..6e71f231f91 100644--- a/src/features/ChatInput/StoreUpdater.tsx+++ b/src/features/ChatInput/StoreUpdater.tsx@@ -20,7 +20,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(canRecordVoiceMessage,chatInputEditorRef,contextSelectionKey,- contextWindowMessages,+ contextWindow,draftKey,feature = DEFAULT_CHAT_INPUT_FEATURE,mobile,@@ -48,7 +48,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(useStoreUpdater('canRecordVoiceMessage', canRecordVoiceMessage);useStoreUpdater('contextSelectionKey', contextSelectionKey);useStoreUpdater('uploadContextKey', uploadContextKey);- useStoreUpdater('contextWindowMessages', contextWindowMessages);+ useStoreUpdater('contextWindow', contextWindow);// Sync draftKey before paint: the draft-transition subscriber// (useChatInputDraft) swaps the editor document on this change, and doingdiff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.tsindex 77f6ddd8a46..519f49d0b95 100644--- a/src/features/ChatInput/store/initialState.ts+++ b/src/features/ChatInput/store/initialState.ts@@ -1,4 +1,9 @@-import { type OpenAIChatMessage, type VoiceMessageRecording } from '@lobechat/types';+import {+ type MessageContextAccounting,+ type OpenAIChatMessage,+ type UIChatMessage,+ type VoiceMessageRecording,+} from '@lobechat/types';import { type IEditor, type SlashOptions } from '@lobehub/editor';import { type ChatInputProps } from '@lobehub/editor/react';import { type DropdownItem } from '@lobehub/ui';@@ -36,8 +41,28 @@ export const initialSendButtonState: SendButtonProps = {export type SlashPlacement = 'top' | 'bottom';-export interface ContextWindowMessage {- content: string;+/**+ * What the conversation's next request carries before the composer draft, for+ * the context breakdown (see `getContextWindow`).+ */+export interface ContextWindow {+ /** The history window the next request includes, as the history count slices it. */+ history: UIChatMessage[];+ /** The latest request the agent runtime recorded in this conversation. */+ request?: {+ accounting: MessageContextAccounting;+ /** Provider-reported input tokens of that request, when known. */+ inputTokens?: number;+ /**+ * Messages added since: the recorded reply itself and everything after it.+ * Absent when a history count re-truncates every request; the recorded+ * messages may then drop out, so count `history` instead.+ */+ messages?: UIChatMessage[];+ /** Model and provider that request went to. */+ model?: string;+ provider?: string;+ };}export interface ChatInputFeature {@@ -67,7 +92,7 @@ export interface PublicState {allowExpand?: boolean;canRecordVoiceMessage?: boolean;contextSelectionKey?: string;- contextWindowMessages?: ContextWindowMessage[];+ contextWindow?: ContextWindow;draftKey?: string;expand?: boolean;feature?: ChatInputFeature;diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex c3c6fe7d87b..c0ca5419776 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -49,11 +49,7 @@ import { sendVoiceMessage } from './sendVoiceMessage';import { transcribeVoiceMessage } from './transcribeVoiceMessage';import { useConversationChatInputUiState } from './useConversationChatInputUiState';import { useRestoreServerQueue } from './useRestoreServerQueue';-import {- getContextWindowMessages,- getConversationSendButtonProps,- toChatInputMessages,-} from './utils';+import { getContextWindow, getConversationSendButtonProps, toChatInputMessages } from './utils';import {canSendVoiceMessage,isVoiceMessageTranscribed,@@ -232,9 +228,9 @@ const ChatInput = memo<ChatInputProps>(chatConfigByIdSelectors.getHistoryCountById(agentId || '')(s),]);const chatInputMessages = useMemo(() => toChatInputMessages(dbMessages), [dbMessages]);- const contextWindowMessages = useMemo(+ const contextWindow = useMemo(() =>- getContextWindowMessages(dbMessages, {+ getContextWindow(dbMessages, {enableHistoryCount,historyCount,}),@@ -528,7 +524,7 @@ const ChatInput = memo<ChatInputProps>(allowExpand={allowExpand}canRecordVoiceMessage={canRecordVoiceMessage}contextSelectionKey={contextKey}- contextWindowMessages={contextWindowMessages}+ contextWindow={contextWindow}draftKey={contextKey}feature={feature}getMessages={getMessages}diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.tsindex af61e25e091..f7e71567269 100644--- a/src/features/Conversation/ChatInput/utils.test.ts+++ b/src/features/Conversation/ChatInput/utils.test.ts@@ -5,7 +5,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';import {createQueueSendNowGate,- getContextWindowMessages,+ getContextWindow,getConversationChatInputUiState,getConversationSendButtonProps,getQueuedHintKey,@@ -129,33 +129,99 @@ describe('toChatInputMessages', () => {});});-describe('getContextWindowMessages', () => {+describe('getContextWindow', () => {+ const accounting = {+ bySource: {+ content: 500,+ fileContext: 0,+ reasoning: 0,+ thoughtSignature: 0,+ toolCallId: 2,+ toolCalls: 30,+ toolDefinition: 4000,+ },+ estimator: 'tokenx' as const,+ messageCount: 3,+ system: 2000,+ total: 6532,+ };+it('uses the full conversation when history count is disabled', () => {- expect(- getContextWindowMessages(tokenMessages, {- enableHistoryCount: false,- historyCount: 2,- }).map((message) => message.content),- ).toEqual(['old user', 'old assistant', 'latest tool', 'latest user']);+ const window = getContextWindow(tokenMessages, { enableHistoryCount: false, historyCount: 2 });++ expect(window.request).toBeUndefined();+ expect(window.history.map((message) => message.content)).toEqual([+ 'old user',+ 'old assistant',+ 'latest tool',+ 'latest user',+ ]);});it('slices chat messages according to history count', () => {expect(- getContextWindowMessages(tokenMessages, {+ getContextWindow(tokenMessages, {enableHistoryCount: true,historyCount: 2,- }).map((message) => message.content),+ }).history.map((message) => message.content),).toEqual(['latest tool', 'latest user']);});it('returns no historical chat messages when history count is zero', () => {expect(- getContextWindowMessages(tokenMessages, {- enableHistoryCount: true,- historyCount: 0,- }),+ getContextWindow(tokenMessages, { enableHistoryCount: true, historyCount: 0 }).history,).toEqual([]);});++ it('starts from the latest recorded request and keeps every message after it', () => {+ const messages = [+ { content: 'first', id: 'u1', role: 'user' },+ {+ content: 'older reply',+ id: 'a1',+ metadata: { contextAccounting: { ...accounting, total: 1 } },+ role: 'assistant',+ },+ { content: 'read the file', id: 'u2', role: 'user' },+ {+ content: '',+ id: 'a2',+ metadata: { contextAccounting: accounting },+ model: 'deepseek-v4-flash',+ provider: 'deepseek',+ role: 'assistant',+ usage: { totalInputTokens: 7000 },+ },+ { content: 'file body', id: 't1', role: 'tool', tool_call_id: 'call_1' },+ ] as UIChatMessage[];++ const window = getContextWindow(messages, { enableHistoryCount: false });++ expect(window.request).toMatchObject({+ accounting,+ inputTokens: 7000,+ model: 'deepseek-v4-flash',+ provider: 'deepseek',+ });+ expect(window.request?.messages?.map((message) => message.id)).toEqual(['a2', 't1']);++ // ROOT CAUSE: with a history count every request re-truncates history, so+ // messages the recorded request covered can drop out of the next one;+ // adding everything after the recorded reply on top overstated usage.+ const truncated = getContextWindow(messages, { enableHistoryCount: true, historyCount: 1 });++ expect(truncated.request).toMatchObject({ accounting, model: 'deepseek-v4-flash' });+ expect(truncated.request?.messages).toBeUndefined();+ expect(truncated.history.map((message) => message.id)).toEqual(['t1']);+ });++ it('ignores accounting on non-assistant messages', () => {+ const messages = [+ { content: 'hi', id: 'u1', metadata: { contextAccounting: accounting }, role: 'user' },+ ] as UIChatMessage[];++ expect(getContextWindow(messages, {}).request).toBeUndefined();+ });});describe('getConversationSendButtonProps', () => {diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.tsindex 0e520557754..ece31119228 100644--- a/src/features/Conversation/ChatInput/utils.ts+++ b/src/features/Conversation/ChatInput/utils.ts@@ -1,8 +1,8 @@+import { getSlicedMessages } from '@lobechat/context-engine';import type { ConversationContext, OpenAIChatMessage, UIChatMessage } from '@lobechat/types';import type { PlaceholderVariant } from '@/features/ChatInput/InputEditor/Placeholder';-import type { SendButtonProps } from '@/features/ChatInput/store/initialState';-import { chatHelpers } from '@/store/chat/helpers';+import type { ContextWindow, SendButtonProps } from '@/features/ChatInput/store/initialState';import { operationSelectors } from '@/store/chat/selectors';import {type QueuedMessage,@@ -103,13 +103,60 @@ export const toChatInputMessages = (messages: UIChatMessage[]): ChatInputMessagerole: m.role,}));-export const getContextWindowMessages = (+const getRecordedInputTokens = (message: UIChatMessage) =>+ message.usage?.totalInputTokens ??+ message.metadata?.usage?.totalInputTokens ??+ message.metadata?.totalInputTokens;++/**+ * Resolves what the conversation's next request carries before the composer draft.+ *+ * Use when:+ * - Feeding the composer's context breakdown.+ *+ * Expects:+ * - `messages` are the conversation's flat DB messages in send order.+ *+ * Returns:+ * - `history`: the window the next request includes, sliced with the context+ * engine's own group-aware history truncation.+ * - `request`, when the latest assistant message carries+ * `metadata.contextAccounting`: that request's accounting and model. Without+ * a history count it also carries the messages sent since — the reply+ * itself, its tool results and later turns — which the next request appends+ * to the recorded one. With a history count every request re-truncates, so+ * those older messages may drop out and only `history` is reliable.+ */+export const getContextWindow = (messages: UIChatMessage[],options: {enableHistoryCount?: boolean;historyCount?: number;},-) => toChatInputMessages(chatHelpers.getSlicedMessages(messages, options));+): ContextWindow => {+ const history = getSlicedMessages(messages, options) as UIChatMessage[];+ const historyTruncated = !!options.enableHistoryCount && options.historyCount !== undefined;++ for (let index = messages.length - 1; index >= 0; index--) {+ const message = messages[index];+ const accounting = message.role === 'assistant' && message.metadata?.contextAccounting;+ if (!accounting) continue;++ const inputTokens = getRecordedInputTokens(message);+ return {+ history,+ request: {+ accounting,+ ...(inputTokens ? { inputTokens } : {}),+ ...(historyTruncated ? {} : { messages: messages.slice(index) }),+ model: message.model ?? undefined,+ provider: message.provider ?? undefined,+ },+ };+ }++ return { history };+};export const getConversationSendButtonProps = (defaults: SendButtonProps,diff --git a/src/store/chat/agents/transports/ClientContextBuilder.ts b/src/store/chat/agents/transports/ClientContextBuilder.tsindex 65490166f00..8dcef6ae7fd 100644--- a/src/store/chat/agents/transports/ClientContextBuilder.ts+++ b/src/store/chat/agents/transports/ClientContextBuilder.ts@@ -4,7 +4,11 @@ import type {ContextBuildInput,ContextBuildOutput,} from '@lobechat/agent-runtime';-import { ToolResolver, type ToolsEngine } from '@lobechat/context-engine';+import {+ ToolResolver,+ type ToolsEngine,+ tryCountRequestPayloadTokens,+} from '@lobechat/context-engine';import type { MessageMetadata } from '@lobechat/types';import { TraceNameMap } from '@lobechat/types';import { dedupeBy } from '@lobechat/utils';@@ -98,6 +102,11 @@ export class ClientContextBuilder implements ContextBuilder {const { messages: preparedMessages = [], ...params } = prepared.params;return {+ // The client transport sends these messages and `params.tools` as-is.+ contextAccounting: tryCountRequestPayloadTokens({+ messages: preparedMessages,+ tools: params.tools,+ }),messages: preparedMessages,modelParameters: {options: prepared.options,