π€― 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
π fix(context-engine): send older attachments as previews instead of overflowing the context (#20563)
YuTengjingec6fc7f07688
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.tsindex 225a0c9948e..8acb76c8d3d 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.test.ts@@ -1,6 +1,7 @@// @vitest-environment nodeimport { ModelRuntime } from '@lobechat/model-runtime';import { tracer as agentRuntimeTracer } from '@lobechat/observability-otel/modules/agent-runtime';+import { RequestTrigger } from '@lobechat/types';import { describe, expect, it, vi } from 'vitest';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';@@ -37,6 +38,20 @@ describe('ServerLLMTransport.stream Β· conversation affinity', () => {'topic-2',]);});++ it('tags compression requests with the context compression trigger', async () => {+ const chat = vi.fn().mockImplementation(async () => new Response(''));+ vi.mocked(initModelRuntimeFromDB).mockImplementation(async () => new ModelRuntime({ chat }));++ const ctx = { topicId: 'topic-1', userId: 'user-1' } as RuntimeExecutorContext;+ await new ServerLLMTransport(ctx).stream({+ messages: [],+ model: 'glm-5',+ provider: 'opencodecodingplan',+ });++ expect(chat.mock.calls[0][1].metadata.trigger).toBe(RequestTrigger.ContextCompression);+ });});describe('ServerLLMTransport.createTrace Β· streaming mode', () => {diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex b86e9ca06b5..f16be516881 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -39,7 +39,7 @@ import {chatSpanName,tracer as agentRuntimeTracer,} from '@lobechat/observability-otel/modules/agent-runtime';-import { toAgentShareVisitorIds } from '@lobechat/types';+import { RequestTrigger, toAgentShareVisitorIds } from '@lobechat/types';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';@@ -360,7 +360,10 @@ export class ServerLLMTransport implements LLMTransport {handlers?.onText?.(text);},},- metadata: { topicId: this.ctx.topicId },+ // `stream()` only serves context compression. Without a trigger, RouterRuntime+ // rejects the call in development (skipping compression) and bills it as+ // trigger=null in production.+ metadata: { topicId: this.ctx.topicId, trigger: RequestTrigger.ContextCompression },user: this.ctx.userId,});diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex 99c5636a7bd..c67b619eeca 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -129,6 +129,7 @@ export const buildServerCallLlmContext = async ({const contextEngineInput = {additionalContexts: llmPayload.additionalContexts,+ attachmentPreviewFileIds: llmPayload.attachmentPreviewFileIds,agentDocuments: facts.agentDocuments,// Identity lives on the agent row, not in the prompt text β inject it so// the model introduces itself by the user-given name.diff --git a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.tsindex ade958553b7..73c708629e1 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts@@ -401,6 +401,40 @@ describe('serverMessagesEngine', () => {expect(content[0].text).toContain('url="https://app.example.com/f/file1"');});+ it('sends attachments planned for preview as previews', async () => {+ const content = 'row,value\n'.repeat(1000);+ const { messages: result } = await serverMessagesEngine({+ attachmentPreviewFileIds: ['file1'],+ messages: [+ {+ content: 'Read this',+ createdAt: Date.now(),+ fileList: [+ {+ content,+ fileType: 'text/csv',+ id: 'file1',+ name: 'data.csv',+ size: content.length,+ url: 'https://app.example.com/f/file1',+ },+ ],+ id: 'msg-1',+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ],+ model: 'gpt-4',+ provider: 'openai',+ });++ const userMessage = result.find((message) => message.role === 'user');+ const text = (userMessage?.content as any[])[0].text as string;++ expect(text).toContain('truncated="true"');+ expect(text).not.toContain(content);+ });+it('should pass active topic document initial context into MessagesEngine', async () => {const { messages: result } = await serverMessagesEngine({initialContext: {diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.tsindex b57a37d53f7..0d2e9e73863 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts@@ -19,6 +19,7 @@ export const toContextSnapshot = ({agentGroup,agentIdentity,agentManagementContext,+ attachmentPreviewFileIds,botPlatformContext,capabilities,connectorOwnershipNote,@@ -66,7 +67,7 @@ export const toContextSnapshot = ({systemRole,},// Server-side file access URLs resolve to stable file-proxy URLs in production.- fileContext: { enabled: true, includeFileUrl: true },+ fileContext: { enabled: true, includeFileUrl: true, previewFileIds: attachmentPreviewFileIds },model: {capabilities: {isCanUseAudio: capabilities?.isCanUseAudio,diff --git a/apps/server/src/modules/Mecha/ContextEngineering/types.ts b/apps/server/src/modules/Mecha/ContextEngineering/types.tsindex 4717c712a45..aa1d77462a5 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/types.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/types.ts@@ -85,6 +85,11 @@ export interface ServerMessagesEngineParams {additionalContexts?: readonly RuntimeAdditionalContextFragment[];/** Additional variable values to merge with defaults (e.g. device paths) */additionalVariables?: Record<string, string>;+ /**+ * Attachments sent as a preview plus file id because the request's attachment+ * budget is spent (planned by `shouldCompress`).+ */+ attachmentPreviewFileIds?: string[];/** Agent documents to inject into context based on load rules and positions */agentDocuments?: AgentContextDocument[];/** Immutable expertise captured when the operation started. */diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex 3b38da75196..031b7a36360 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -25,7 +25,7 @@ import {resolveDiscoveryPool,resolveInvocationToolIds,} from '@lobechat/mecha';-import { FILE_INLINE_MAX_CHARS, isOversizedFileContent } from '@lobechat/prompts';+import { FILE_PREVIEW_CHARS, isOversizedFileContent } from '@lobechat/prompts';import type {BuiltinToolResolveContext,ChatTopicBotContext,@@ -521,8 +521,11 @@ export const discoverTools = async (}/**- * Whether this turn sends any file as a truncated preview (see `previewLongFileContent`):- * an enabled agent file, or a parsed attachment of this turn or topic, over the inline limit.+ * Whether this turn can send any file as a truncated preview (see `previewLongFileContent`):+ * an enabled agent file over the inline limit, or a parsed attachment of this turn or topic+ * longer than a preview. Attachments under the inline limit are still previewed once the+ * request's attachment budget is spent (`planAttachmentPreviews`), which is only known per step,+ * so any attachment a preview would shorten enables the tool.* Enables the attachments tool in the modes whose rules include it (agent / chat). The preview* only names `readAttachment` when the final tool set carries it (see `MessagesEngine`), so* custom / exclusive tool turns and share visitors fall back to a plain preview.@@ -539,7 +542,7 @@ export const discoverTools = async (return traceDiscoveryStage('oversized_files', () =>new DocumentModel(deps.db, deps.userId, deps.workspaceId).hasFileDocumentsOverChars({fileIds: attachedFileIds,- minChars: FILE_INLINE_MAX_CHARS,+ minChars: FILE_PREVIEW_CHARS,topicId,}),);diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex e91cd46e224..bf67996d14e 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -611,6 +611,31 @@ export class GeneralChatAgent implements Agent {return Math.max(initialRatio ?? 0, DEFAULT_RECOMPRESSION_THRESHOLD_RATIO);}+ /**+ * Fit the upcoming request under the compression threshold. Runs whether or+ * not compression is enabled: the attachment preview plan keeps attachment+ * text within the room the conversation leaves even when the conversation+ * itself is never compressed.+ */+ private checkContextBudget(messages: any[], tools: any[] | undefined, state: AgentState) {+ // Mirror RuntimeExecutors.callLlm: when state.forceFinish is set, the+ // executor strips all tools via buildStepToolDelta (deactivatedToolIds: ['*']),+ // so they must not count against the compression budget either β otherwise+ // we'd burn an extra summarization pass on tool tokens that won't be sent.+ return shouldCompress(messages, {+ maxWindowToken: this.config.compressionConfig?.maxWindowToken,+ thresholdRatio: this.getCompressionThresholdRatio(messages),+ tools: state.forceFinish ? undefined : tools,+ });+ }++ private withAttachmentPreviews<T extends object>(+ payload: T,+ attachmentPreviewFileIds: string[],+ ): T {+ return attachmentPreviewFileIds.length > 0 ? { ...payload, attachmentPreviewFileIds } : payload;+ }+/*** Proceed to the next LLM call, inserting compression first when needed.*/@@ -627,34 +652,29 @@ export class GeneralChatAgent implements Agent {...this.getAllowedToolNamesPayload(),};const compressionEnabled = this.config.compressionConfig?.enabled ?? true;- // Mirror RuntimeExecutors.callLlm: when state.forceFinish is set, the- // executor strips all tools via buildStepToolDelta (deactivatedToolIds: ['*']),- // so they must not count against the compression budget either β otherwise- // we'd burn an extra summarization pass on tool tokens that won't be sent.- const compressionOptions = {- maxWindowToken: this.config.compressionConfig?.maxWindowToken,- thresholdRatio: this.getCompressionThresholdRatio(payloadWithAllowedToolNames.messages),- tools: state.forceFinish ? undefined : payloadWithAllowedToolNames.tools,- };-- if (compressionEnabled) {- const messages = payloadWithAllowedToolNames.messages;- const compressionCheck = shouldCompress(messages, compressionOptions);+ const messages = payloadWithAllowedToolNames.messages;+ const compressionCheck = this.checkContextBudget(+ messages,+ payloadWithAllowedToolNames.tools,+ state,+ );- if (compressionCheck.needsCompression) {- return {- payload: {- currentTokenCount: compressionCheck.currentTokenCount,- existingSummary: this.findExistingSummary(messages),- messages,- },- type: 'compress_context',- };- }+ if (compressionEnabled && compressionCheck.needsCompression) {+ return {+ payload: {+ currentTokenCount: compressionCheck.currentTokenCount,+ existingSummary: this.findExistingSummary(messages),+ messages,+ },+ type: 'compress_context',+ };}return {- payload: payloadWithAllowedToolNames,+ payload: this.withAttachmentPreviews(+ payloadWithAllowedToolNames,+ compressionCheck.attachmentPreviewFileIds,+ ),type: 'call_llm',};}@@ -700,28 +720,22 @@ export class GeneralChatAgent implements Agent {case 'user_input': {// Check if context compression is enabled and needed before calling LLMconst compressionEnabled = this.config.compressionConfig?.enabled ?? true; // Default to enabled- // Mirror RuntimeExecutors.callLlm: force-finish steps ship without tools,- // so they must not count against the compression budget here either.- const compressionOptions = {- maxWindowToken: this.config.compressionConfig?.maxWindowToken,- thresholdRatio: this.getCompressionThresholdRatio(state.messages),- tools: state.forceFinish ? undefined : this.getTools(state),- };-- if (compressionEnabled) {- const compressionCheck = shouldCompress(state.messages, compressionOptions);+ const compressionCheck = this.checkContextBudget(+ state.messages,+ this.getTools(state),+ state,+ );- if (compressionCheck.needsCompression) {- // Context exceeds threshold, compress ALL messages into a single summary- return {- payload: {- currentTokenCount: compressionCheck.currentTokenCount,- existingSummary: this.findExistingSummary(state.messages),- messages: state.messages,- },- type: 'compress_context',- } as AgentInstructionCompressContext;- }+ if (compressionEnabled && compressionCheck.needsCompression) {+ // Context exceeds threshold, compress ALL messages into a single summary+ return {+ payload: {+ currentTokenCount: compressionCheck.currentTokenCount,+ existingSummary: this.findExistingSummary(state.messages),+ messages: state.messages,+ },+ type: 'compress_context',+ } as AgentInstructionCompressContext;}// User input received, call LLM to generate response@@ -729,12 +743,15 @@ export class GeneralChatAgent implements Agent {const basePayload = context.payload as any;const tools = this.getTools(state, basePayload?.tools);return {- payload: {- ...basePayload,- ...this.getAllowedToolNamesPayload(),- messages: state.messages,- tools,- } as GeneralAgentCallLLMInstructionPayload,+ payload: this.withAttachmentPreviews(+ {+ ...basePayload,+ ...this.getAllowedToolNamesPayload(),+ messages: state.messages,+ tools,+ } as GeneralAgentCallLLMInstructionPayload,+ compressionCheck.attachmentPreviewFileIds,+ ),type: 'call_llm',};}@@ -1071,20 +1088,27 @@ export class GeneralChatAgent implements Agent {// Otherwise, messages have been updated with compressed content, and a// normal turn forces a fresh assistant message.const seededAssistantMessageId = state.pendingAssistantMessageId;+ const messages = compressionPayload.compressedMessages ?? state.messages;+ // The kept latest user message can still carry more attachment text than+ // the compressed context has room for.+ const { attachmentPreviewFileIds } = this.checkContextBudget(messages, tools, state);return {- payload: {- ...(seededAssistantMessageId- ? { assistantMessageId: seededAssistantMessageId }- : // Force create new assistant message after compression- { createAssistantMessage: true }),- messages: compressionPayload.compressedMessages ?? state.messages,- model: this.config.modelRuntimeConfig?.model,- parentMessageId: compressionPayload.parentMessageId,- provider: this.config.modelRuntimeConfig?.provider,- tools,- ...this.getAllowedToolNamesPayload(),- } as GeneralAgentCallLLMInstructionPayload,+ payload: this.withAttachmentPreviews(+ {+ ...(seededAssistantMessageId+ ? { assistantMessageId: seededAssistantMessageId }+ : // Force create new assistant message after compression+ { createAssistantMessage: true }),+ messages,+ model: this.config.modelRuntimeConfig?.model,+ parentMessageId: compressionPayload.parentMessageId,+ provider: this.config.modelRuntimeConfig?.provider,+ tools,+ ...this.getAllowedToolNamesPayload(),+ } as GeneralAgentCallLLMInstructionPayload,+ attachmentPreviewFileIds,+ ),type: 'call_llm',};}diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 568a412956a..7acf22ccea2 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -2488,6 +2488,75 @@ describe('GeneralChatAgent', () => {});});+ describe('attachment budget', () => {+ const paper = 'Salt gland development in Limonium bicolor. '.repeat(2000);+ const attachmentMessages = () =>+ ['old', 'mid', 'new'].map((id) => ({+ content: `summarize ${id}`,+ fileList: [+ {+ content: paper,+ fileType: 'application/pdf',+ id: `file-${id}`,+ name: `${id}.pdf`,+ size: paper.length,+ url: '',+ },+ ],+ id,+ role: 'user',+ })) as any;++ it.each([true, false])(+ 'calls the LLM with older attachments previewed (compression enabled: %s)',+ async (enabled) => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ compressionConfig: { enabled, maxWindowToken: 64_000 },+ modelRuntimeConfig: mockModelRuntimeConfig,+ operationId: 'test-session',+ });+ const state = createMockState({ messages: attachmentMessages() });++ const result = (await agent.runner(+ createMockContext('init', { model: 'gpt-4o-mini', provider: 'openai' }),+ state,+ )) as any;++ expect(result.type).toBe('call_llm');+ expect(result.payload.attachmentPreviewFileIds.sort()).toEqual(['file-mid', 'file-old']);+ },+ );++ it('plans previews for the call after compression', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ // Each paper is ~20k tokens; after compression the 0.65 recompression+ // ratio leaves ~31k raw tokens, room for one of the two new papers.+ compressionConfig: { enabled: true, maxWindowToken: 60_000 },+ modelRuntimeConfig: mockModelRuntimeConfig,+ operationId: 'test-session',+ });+ const latest = attachmentMessages()[2];+ const compressedMessages = [+ { content: 'Compressed summary', id: 'group-1', role: 'compressedGroup' },+ { ...latest, fileList: [latest.fileList[0], { ...latest.fileList[0], id: 'file-new-2' }] },+ ];++ const result = (await agent.runner(+ createMockContext('compression_result', {+ compressedMessages,+ parentMessageId: 'assistant-msg-after-compression',+ skipped: false,+ }),+ createMockState(),+ )) as any;++ expect(result.type).toBe('call_llm');+ expect(result.payload.attachmentPreviewFileIds).toEqual(['file-new-2']);+ });+ });+describe('compression_result phase', () => {it('should return call_llm with compressed messages and force a new assistant message', async () => {const agent = new GeneralChatAgent({diff --git a/packages/agent-runtime/src/types/generalAgent.ts b/packages/agent-runtime/src/types/generalAgent.tsindex 39c0eeed6fe..56cecc86f2a 100644--- a/packages/agent-runtime/src/types/generalAgent.ts+++ b/packages/agent-runtime/src/types/generalAgent.ts@@ -17,6 +17,11 @@ export interface GeneralAgentCallLLMInstructionPayload {* placeholder must be filled by this LLM turn rather than orphaned.*/assistantMessageId?: string;+ /**+ * Attachments the context engine sends as a preview plus file id, planned by+ * `shouldCompress` so attachment text fits under the compression threshold.+ */+ attachmentPreviewFileIds?: string[];/** Force create a new assistant message (e.g., after compression) */createAssistantMessage?: boolean;isFirstMessage?: boolean;diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.tsindex e9eb29889db..35bcb096262 100644--- a/packages/agent-runtime/src/types/instruction.ts+++ b/packages/agent-runtime/src/types/instruction.ts@@ -122,6 +122,11 @@ export interface Agent {export interface CallLLMPayload {additionalContexts?: readonly RuntimeAdditionalContextFragment[];allowedToolNames?: string[];+ /**+ * Attachments the context engine sends as a preview plus file id, planned by+ * `shouldCompress` so attachment text fits under the compression threshold.+ */+ attachmentPreviewFileIds?: string[];isFirstMessage?: boolean;messages: any[];model: string;diff --git a/packages/agent-runtime/src/utils/tokenCounter.test.ts b/packages/agent-runtime/src/utils/tokenCounter.test.tsindex 59aa8ee4446..7b156f80db5 100644--- a/packages/agent-runtime/src/utils/tokenCounter.test.ts+++ b/packages/agent-runtime/src/utils/tokenCounter.test.ts@@ -54,6 +54,26 @@ describe('tokenCounter', () => {});describe('shouldCompress', () => {+ // Regression: LOBE-14165. Attachments are previewed instead of triggering+ // compression, which would drop their content from older messages.+ it('previews older attachments instead of compressing for attachment text', () => {+ const paper = 'Salt gland development in Limonium bicolor. '.repeat(2000);+ const fileItem = { fileType: 'application/pdf', name: 'paper.pdf', size: paper.length };+ const messages = ['old', 'mid', 'new'].map((id) =>+ mkMsg({+ content: `summarize ${id}`,+ fileList: [{ ...fileItem, content: paper, id: `file-${id}`, url: '' }],+ id,+ role: 'user',+ }),+ );++ const result = shouldCompress(messages, { maxWindowToken: 64_000 });++ expect(result.needsCompression).toBe(false);+ expect(result.attachmentPreviewFileIds.sort()).toEqual(['file-mid', 'file-old']);+ });+it('should return needsCompression=false when under threshold', () => {const result = shouldCompress([mkMsg({ role: 'user', content: 'Hi' })]);diff --git a/packages/agent-runtime/src/utils/tokenCounter.ts b/packages/agent-runtime/src/utils/tokenCounter.tsindex c6245efe1aa..a15f4beb2fd 100644--- a/packages/agent-runtime/src/utils/tokenCounter.ts+++ b/packages/agent-runtime/src/utils/tokenCounter.ts@@ -1,4 +1,4 @@-import { countContextTokens, DEFAULT_DRIFT_MULTIPLIER } from '@lobechat/context-engine';+import { DEFAULT_DRIFT_MULTIPLIER, planAttachmentPreviews } from '@lobechat/context-engine';import type { UIChatMessage } from '@lobechat/types';/**@@ -42,6 +42,12 @@ export function getCompressionThreshold(options: TokenCountOptions = {}): number* Result of compression check*/export interface CompressionCheckResult {+ /**+ * Attachments to send as a preview plus file id so attachment text stays+ * within the room the rest of the context leaves under the threshold. Pass+ * them to the context engine with the `call_llm` payload.+ */+ attachmentPreviewFileIds: string[];/*** Best raw estimate of current input tokens (sum of message content +* tool calls + reasoning + tool_call_id + tool definitions).@@ -63,20 +69,24 @@ export interface CompressionCheckResult {** Uses {@link countContextTokens} under the hood, so the input estimate* accounts for tool calls, reasoning, and tool definitions in addition to- * `content` (see for the calibration data).+ * `content` (see for the calibration data). Attachment text is fitted into the+ * remaining room first (see {@link planAttachmentPreviews}), so attachments+ * alone never trigger compression; the estimate reflects the planned previews.*/export function shouldCompress(messages: UIChatMessage[],options: TokenCountOptions = {},): CompressionCheckResult {- const accounting = countContextTokens({+ const threshold = getCompressionThreshold(options);+ const { accounting, previewFileIds } = planAttachmentPreviews({+ driftMultiplier: options.driftMultiplier ?? DEFAULT_DRIFT_MULTIPLIER,messages,- options: { driftMultiplier: options.driftMultiplier ?? DEFAULT_DRIFT_MULTIPLIER },+ threshold,tools: options.tools,});- const threshold = getCompressionThreshold(options);return {+ attachmentPreviewFileIds: [...previewFileIds],currentTokenCount: accounting.rawTotal,needsCompression: accounting.adjustedTotal > threshold,threshold,diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.tsindex 3a059abd010..d1013b61341 100644--- a/packages/context-engine/src/engine/messages/types.ts+++ b/packages/context-engine/src/engine/messages/types.ts@@ -101,6 +101,11 @@ export interface FileContextConfig {enabled: boolean;/** Whether to include file URLs (desktop typically uses false) */includeFileUrl: boolean;+ /**+ * Attachments sent as a preview plus file id because the request's attachment+ * budget is spent (see `planAttachmentPreviews`).+ */+ previewFileIds?: string[];}/**diff --git a/packages/context-engine/src/index.ts b/packages/context-engine/src/index.tsindex aed619b2e2c..27610419f1e 100644--- a/packages/context-engine/src/index.ts+++ b/packages/context-engine/src/index.ts@@ -35,6 +35,11 @@ export {estimateSentMessageAttachmentTokenBuckets,isTextLikeUploadFile,} from './tokenAccounting';+export type {+ AttachmentPreviewPlan,+ PlanAttachmentPreviewsParams,+} from './tokenAccounting/attachmentBudget';+export { planAttachmentPreviews } from './tokenAccounting/attachmentBudget';// Processorsexport type { PlaceholderValue, PlaceholderValueMap } from './processors';export {diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.tsindex 8c04db1d195..f42495ceb23 100644--- a/packages/context-engine/src/processors/MessageContent.ts+++ b/packages/context-engine/src/processors/MessageContent.ts@@ -80,6 +80,11 @@ export interface FileContextConfig {enabled?: boolean;/** Whether to include file URLs in file context prompts */includeFileUrl?: boolean;+ /**+ * Attachments sent as a preview plus file id because the request's attachment+ * budget is spent (see `planAttachmentPreviews`).+ */+ previewFileIds?: string[];}export interface MessageContentConfig {@@ -127,11 +132,15 @@ export interface UserMessageContentPart {export class MessageContentProcessor extends BaseProcessor {readonly name = 'MessageContentProcessor';+ private readonly previewFileIds?: ReadonlySet<string>;+constructor(private config: MessageContentConfig,options: ProcessorOptions = {},) {super(options);+ const previewFileIds = config.fileContext?.previewFileIds;+ if (previewFileIds?.length) this.previewFileIds = new Set(previewFileIds);}protected async doProcess(context: PipelineContext): Promise<PipelineContext> {@@ -271,6 +280,7 @@ export class MessageContentProcessor extends BaseProcessor {fileList: message.fileList,imageList: message.imageList || [],messageId: message.id,+ previewFileIds: this.previewFileIds,videoList: message.videoList || [],});diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.tsindex 35f542e966c..73310f869ee 100644--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts@@ -627,6 +627,41 @@ describe('MessageContentProcessor', () => {);});+ it('sends files listed in previewFileIds as previews', async () => {+ const content = 'row,value\n'.repeat(1000);+ const processor = new MessageContentProcessor({+ canReadAttachment: true,+ fileContext: { enabled: true, includeFileUrl: false, previewFileIds: ['file-budget'] },+ isCanUseVision: mockIsCanUseVision,+ model: 'gpt-4',+ provider: 'openai',+ });+ const fileItem = { fileType: 'text/csv', name: 'data.csv', size: content.length };++ const result = await processor.process(+ createContext([+ {+ content: 'Compare them',+ createdAt: Date.now(),+ fileList: [+ { ...fileItem, content, id: 'file-budget' },+ { ...fileItem, content, id: 'file-inline' },+ ],+ id: 'test',+ role: 'user',+ updatedAt: Date.now(),+ },+ ]),+ );++ const text = (result.messages[0].content as any[])[0].text as string;+ expect(text).toContain('call readAttachment with fileId="file-budget"');+ expect(text).not.toContain('fileId="file-inline"');+ expect(text).toContain(+ `<file id="file-inline" name="data.csv" type="text/csv" size="${content.length}">${content}</file>`,+ );+ });+it('should omit file URLs when includeFileUrl is disabled', async () => {mockIsCanUseVision.mockReturnValue(false);diff --git a/packages/context-engine/src/tokenAccounting/__tests__/attachmentBudget.test.ts b/packages/context-engine/src/tokenAccounting/__tests__/attachmentBudget.test.tsnew file mode 100644index 00000000000..b0882796510--- /dev/null+++ b/packages/context-engine/src/tokenAccounting/__tests__/attachmentBudget.test.ts@@ -0,0 +1,97 @@+import type { ChatFileItem, UIChatMessage } from '@lobechat/types';+import { estimateTokenCount } from 'tokenx';+import { describe, expect, it } from 'vitest';++import { planAttachmentPreviews } from '../attachmentBudget';+import { DEFAULT_DRIFT_MULTIPLIER } from '../index';++const paper = (seed: string) =>+ `${seed}: salt gland development in Limonium bicolor under saline stress. `.repeat(600);++const mkFile = (id: string, content: string): ChatFileItem => ({+ content,+ fileType: 'application/pdf',+ id,+ name: `${id}.pdf`,+ size: content.length,+ url: `https://example.com/${id}.pdf`,+});++const mkUser = (id: string, files: ChatFileItem[]): UIChatMessage =>+ ({+ content: `summarize ${id}`,+ createdAt: 0,+ fileList: files,+ id,+ role: 'user',+ updatedAt: 0,+ }) as UIChatMessage;++const paperTokens = estimateTokenCount(paper('p'));+/** Room for about `papers` full papers, drift included. */+const thresholdFor = (papers: number) => Math.ceil(paperTokens * papers * DEFAULT_DRIFT_MULTIPLIER);++describe('planAttachmentPreviews', () => {+ it('previews nothing when every attachment fits', () => {+ const messages = [mkUser('m1', [mkFile('f1', paper('a'))])];++ const plan = planAttachmentPreviews({ messages, threshold: thresholdFor(3) });++ expect(plan.previewFileIds.size).toBe(0);+ });++ // Regression: LOBE-14165. Attachment text must not push the request over the+ // compression threshold, because compression drops older attachments.+ it('inlines the newest attachments and previews older ones within the threshold', () => {+ const messages = [+ mkUser('m1', [mkFile('f1', paper('a'))]),+ mkUser('m2', [mkFile('f2', paper('b'))]),+ mkUser('m3', [mkFile('f3', paper('c'))]),+ ];+ const threshold = thresholdFor(1.6);++ const plan = planAttachmentPreviews({ messages, threshold });++ expect([...plan.previewFileIds].sort()).toEqual(['f1', 'f2']);+ expect(plan.accounting.adjustedTotal).toBeLessThanOrEqual(threshold);+ });++ it('fills leftover room with an older attachment when a newer one does not fit', () => {+ const messages = [+ mkUser('m1', [mkFile('small', paper('a').slice(0, 20_000))]),+ mkUser('m2', [mkFile('big', paper('b') + paper('c'))]),+ ];+ const threshold = thresholdFor(0.8);++ const plan = planAttachmentPreviews({ messages, threshold });++ expect([...plan.previewFileIds]).toEqual(['big']);+ expect(plan.accounting.adjustedTotal).toBeLessThanOrEqual(threshold);+ });++ it('never previews attachments shorter than a preview', () => {+ const short = 'tiny note';+ const messages = [+ mkUser('m1', [mkFile('short', short)]),+ mkUser('m2', [mkFile('f2', paper('b'))]),+ ];++ const plan = planAttachmentPreviews({ messages, threshold: thresholdFor(0.2) });++ expect(plan.previewFileIds.has('short')).toBe(false);+ expect(plan.previewFileIds.has('f2')).toBe(true);+ });++ it('previews every candidate and reports the overflow when text alone exceeds the threshold', () => {+ const messages = [+ { ...mkUser('m1', [mkFile('f1', paper('a'))]), content: paper('chat').repeat(3) },+ mkUser('m2', [mkFile('f2', paper('b'))]),+ ] as UIChatMessage[];+ const threshold = thresholdFor(1);++ const plan = planAttachmentPreviews({ messages, threshold });++ expect([...plan.previewFileIds].sort()).toEqual(['f1', 'f2']);+ expect(plan.accounting.adjustedTotal).toBeGreaterThan(threshold);+ });+});diff --git a/packages/context-engine/src/tokenAccounting/__tests__/index.test.ts b/packages/context-engine/src/tokenAccounting/__tests__/index.test.tsindex c8bbeca3d0a..b7ed034b1c7 100644--- a/packages/context-engine/src/tokenAccounting/__tests__/index.test.ts+++ b/packages/context-engine/src/tokenAccounting/__tests__/index.test.ts@@ -1,4 +1,5 @@-import type { UIChatMessage } from '@lobechat/types';+import { FILE_INLINE_MAX_CHARS, filesPrompts } from '@lobechat/prompts';+import type { ChatFileItem, UIChatMessage } from '@lobechat/types';import { estimateTokenCount } from 'tokenx';import { describe, expect, it } from 'vitest';@@ -28,6 +29,7 @@ describe('countContextTokens', () => {expect(result.tools).toEqual([]);expect(result.bySource).toEqual({content: 0,+ fileContext: 0,reasoning: 0,thoughtSignature: 0,toolCallId: 0,@@ -416,6 +418,81 @@ describe('countContextTokens', () => {});});+ describe('user attachments (fileList / imageList)', () => {+ const mkFile = (id: string, content: string): ChatFileItem => ({+ content,+ fileType: 'application/pdf',+ id,+ name: `${id}.pdf`,+ size: 1000,+ url: `https://example.com/${id}.pdf`,+ });++ // Regression: LOBE-14165. Parsed attachment text is re-sent on every turn+ // but was ignored, so a topic with ~2M chars of history attachments never+ // reached the compression threshold and failed the context preflight.+ it('counts the <files_info> block shipped for history attachments', () => {+ const paper = 'Salt gland development in Limonium bicolor. '.repeat(1500);+ const fileList = [mkFile('file-a', paper), mkFile('file-b', paper)];+ const msg = mkMsg({ fileList, id: 'msg-1', role: 'user', content: 'summarize' });++ const r = countContextTokens({ messages: [msg] });++ const expected = estimateTokenCount(+ filesPrompts({ addUrl: false, fileList, messageId: 'msg-1' }),+ );+ expect(r.messages[0].bySource.fileContext).toBe(expected);+ expect(r.bySource.fileContext).toBe(expected);+ expect(r.rawTotal).toBe(estimateTokenCount('summarize') + expected);+ // Sanity: both papers are in the budget, not just the user's text.+ expect(expected).toBeGreaterThan(estimateTokenCount(paper) * 2 - 100);+ });++ it('counts an oversized attachment as its shipped preview, not the full text', () => {+ const huge = 'x '.repeat(FILE_INLINE_MAX_CHARS);+ const msg = mkMsg({ fileList: [mkFile('file-big', huge)], role: 'user' });++ const r = countContextTokens({ messages: [msg] });++ expect(r.bySource.fileContext).toBeGreaterThan(0);+ expect(r.bySource.fileContext).toBeLessThan(estimateTokenCount(huge) / 10);+ });++ it('counts image metadata in the files block', () => {+ const msg = mkMsg({+ imageList: [{ alt: 'chart.png', id: 'img-1', url: 'https://example.com/chart.png' }],+ role: 'user',+ });++ expect(countContextTokens({ messages: [msg] }).bySource.fileContext).toBeGreaterThan(0);+ });++ // Desktop sends the block without URLs, so a base64 image URL must not+ // inflate the estimate past the compression threshold.+ it('does not count attachment URLs', () => {+ const dataUrl = `data:image/png;base64,${'A'.repeat(200_000)}`;+ const withDataUrl = mkMsg({+ imageList: [{ alt: 'chart.png', id: 'img-1', url: dataUrl }],+ role: 'user',+ });+ const withShortUrl = mkMsg({+ imageList: [{ alt: 'chart.png', id: 'img-1', url: 'https://example.com/chart.png' }],+ role: 'user',+ });++ expect(countContextTokens({ messages: [withDataUrl] }).bySource.fileContext).toBe(+ countContextTokens({ messages: [withShortUrl] }).bySource.fileContext,+ );+ });++ it('adds nothing for user messages without attachments', () => {+ const r = countContextTokens({ messages: [mkMsg({ role: 'user', content: 'hi' })] });++ expect(r.bySource.fileContext).toBe(0);+ expect(r.messages[0].bySource.fileContext).toBeUndefined();+ });+ });+describe('assistantGroup children (conversation-flow flattened lists)', () => {it('counts the real assistant blocks and inline tool results', () => {const r = countContextTokens({diff --git a/packages/context-engine/src/tokenAccounting/attachmentBudget.ts b/packages/context-engine/src/tokenAccounting/attachmentBudget.tsnew file mode 100644index 00000000000..9a1ab9632cd--- /dev/null+++ b/packages/context-engine/src/tokenAccounting/attachmentBudget.ts@@ -0,0 +1,108 @@+import {+ FILE_PREVIEW_CHARS,+ isOversizedFileContent,+ previewLongFileContent,+} from '@lobechat/prompts';+import type { UIChatMessage } from '@lobechat/types';+import { estimateTokenCount } from 'tokenx';++import { countContextTokens, DEFAULT_DRIFT_MULTIPLIER } from './index';+import type { ContextTokenAccounting } from './types';++export interface PlanAttachmentPreviewsParams {+ /** Drift multiplier forwarded to {@link countContextTokens}. */+ driftMultiplier?: number;+ messages: UIChatMessage[];+ /**+ * Drift-adjusted token limit the request should stay under β the compression+ * threshold. Attachments only use the room the rest of the context leaves.+ */+ threshold: number;+ /** Tool definitions sent with the request. */+ tools?: unknown[];+}++export interface AttachmentPreviewPlan {+ /** Accounting of the request with {@link previewFileIds} sent as previews. */+ accounting: ContextTokenAccounting;+ /** Files whose text is sent as a preview the model can page through with `readAttachment`. */+ previewFileIds: Set<string>;+}++interface Candidate {+ id: string;+ /** Tokens saved by sending every occurrence of the file as a preview. */+ savings: number;+}++/**+ * Collect files whose text would be inlined in full, newest message first. A file+ * attached to several messages is inlined in each of them, so its cost adds up.+ */+const collectInlineCandidates = (messages: UIChatMessage[]): Candidate[] => {+ const candidates = new Map<string, Candidate>();++ for (let i = messages.length - 1; i >= 0; i--) {+ const msg = messages[i];+ if (msg.role !== 'user' || !msg.fileList?.length) continue;++ for (const file of msg.fileList) {+ const content = file.content || '';+ // Already a preview, or too short for a preview to save anything.+ if (content.length <= FILE_PREVIEW_CHARS) continue;+ if (isOversizedFileContent(content.length, file.originalCharCount)) continue;++ const preview = previewLongFileContent(content, { fileId: file.id, forcePreview: true });+ const savings = estimateTokenCount(content) - estimateTokenCount(preview.body);+ if (savings <= 0) continue;++ const existing = candidates.get(file.id);+ if (existing) existing.savings += savings;+ else candidates.set(file.id, { id: file.id, savings });+ }+ }++ return [...candidates.values()];+};++/**+ * Decide which attachments to send as previews so attachment text alone never+ * pushes a request over the compression threshold.+ *+ * Attachment text is re-sent on every turn, and compression only keeps a+ * summary of older messages, so letting attachments trigger compression loses+ * their content. Instead, attachments get the room the rest of the context+ * leaves under the threshold: files are inlined newest first while they fit,+ * and the rest are sent as a preview plus file id for `readAttachment`. When+ * everything fits, nothing is previewed. Compression then only fires when the+ * conversation itself (with every attachment previewed) exceeds the threshold.+ */+export const planAttachmentPreviews = ({+ driftMultiplier = DEFAULT_DRIFT_MULTIPLIER,+ messages,+ threshold,+ tools,+}: PlanAttachmentPreviewsParams): AttachmentPreviewPlan => {+ const count = (previewFileIds?: Set<string>) =>+ countContextTokens({ messages, options: { driftMultiplier, previewFileIds }, tools });++ const full = count();+ if (full.adjustedTotal <= threshold) return { accounting: full, previewFileIds: new Set() };++ const candidates = collectInlineCandidates(messages);+ if (candidates.length === 0) return { accounting: full, previewFileIds: new Set() };++ const previewFileIds = new Set(candidates.map((candidate) => candidate.id));+ const allPreviewed = count(previewFileIds);++ // Raw-token room left under the threshold with every candidate previewed.+ let room = Math.floor(threshold / driftMultiplier) - allPreviewed.rawTotal;++ for (const candidate of candidates) {+ if (candidate.savings > room) continue;+ previewFileIds.delete(candidate.id);+ room -= candidate.savings;+ }++ return { accounting: count(previewFileIds), previewFileIds };+};diff --git a/packages/context-engine/src/tokenAccounting/index.ts b/packages/context-engine/src/tokenAccounting/index.tsindex a6670719f08..99d6d2806c4 100644--- a/packages/context-engine/src/tokenAccounting/index.ts+++ b/packages/context-engine/src/tokenAccounting/index.ts@@ -1,4 +1,5 @@// cspell:ignore tokenx+import { filesPrompts } from '@lobechat/prompts';import type { AssistantContentBlock, UIChatMessage } from '@lobechat/types';import { estimateTokenCount } from 'tokenx';@@ -17,6 +18,7 @@ export const DEFAULT_DRIFT_MULTIPLIER = 1.25;const ZERO_BY_SOURCE = (): Record<TokenSourceType, number> => ({content: 0,+ fileContext: 0,reasoning: 0,thoughtSignature: 0,toolCallId: 0,@@ -39,6 +41,46 @@ const bumpSource = (bySource[key] = (bySource[key] ?? 0) + amount;};+/**+ * MessageContentProcessor appends the parsed text of every user attachment to+ * that message's content as a `<files_info>` block, on every turn the message+ * stays in history. Render the same block so the count follows the inline vs.+ * preview decision (`FILE_INLINE_MAX_CHARS`) without duplicating it. Visual+ * and audio payloads (image_url parts, etc.) are not estimated here.+ *+ * `canReadAttachment` only changes the preview notice wording, so the default+ * is close enough for budgeting. URLs are left out because Desktop ships the+ * block without them (`includeFileUrl: false`), and a local or base64 media URL+ * could otherwise push a single attachment over the compression threshold; on+ * Web this undercounts by one short URL per attachment.+ */+const countFileContext = (msg: UIChatMessage, previewFileIds?: ReadonlySet<string>): number => {+ const fileList = msg.fileList ?? [];+ const imageList = msg.imageList ?? [];+ const videoList = msg.videoList ?? [];+ const audioList = msg.audioList ?? [];++ if (+ fileList.length === 0 &&+ imageList.length === 0 &&+ videoList.length === 0 &&+ audioList.length === 0+ )+ return 0;++ return estimate(+ filesPrompts({+ addUrl: false,+ audioList,+ fileList,+ imageList,+ messageId: msg.id,+ previewFileIds,+ videoList,+ }),+ );+};+type AssistantTokenBlock =| AssistantContentBlock| Pick<UIChatMessage, 'content' | 'metadata' | 'reasoning' | 'tools' | 'usage'>;@@ -51,6 +93,7 @@ type AssistantTokenBlock =* | source | field on UIChatMessage | sent to provider as |* |--------------------|------------------------------------------------------------|----------------------------------|* | `content` | `msg.content` | `message.content` |+ * | `fileContext` | user `fileList` / `imageList` / `videoList` / `audioList` | `<files_info>` block in content |* | `toolCalls` | `msg.tools[]` (lobe internal, not OpenAI's `tool_calls`) | `message.tool_calls` |* | `thoughtSignature` | `msg.tools[N].thoughtSignature` (Gemini-specific) | echoed back per tool call |* | `reasoning` | `msg.reasoning.content` / `msg.reasoning` (string variant) | echoed back next turn (thinking) |@@ -76,7 +119,7 @@ type AssistantTokenBlock =* harness stores but doesn't ship to the provider:** `plugin`, `pluginState`, `pluginIntervention`, `pluginError`, `chunksList`,- * `editorData`, `extra`, `fileList`, `imageList`, `videoList`, `metadata`+ * `editorData`, `extra`, `metadata`* (other than `metadata.usage.totalOutputTokens` shortcut for assistant and* `metadata.instruction` for `task` messages, which ship in the template)* Also NOT counted: in-bubble `council` blocks (`AssistantContentBlock.council`)@@ -125,6 +168,7 @@ export const countContextTokens = ({options,}: CountContextTokensParams): ContextTokenAccounting => {const driftMultiplier = options?.driftMultiplier ?? DEFAULT_DRIFT_MULTIPLIER;+ const previewFileIds = options?.previewFileIds;const messageBreakdowns: MessageTokenBreakdown[] = messages.map((msg, index) => {const bySource: Partial<Record<TokenSourceType, number>> = {};@@ -275,6 +319,9 @@ export const countContextTokens = ({} else {bumpSource(bySource, 'content', estimate(msg.content));+ if (msg.role === 'user')+ bumpSource(bySource, 'fileContext', countFileContext(msg, previewFileIds));+const reasoning = msg.reasoning;if (reasoning) {const reasoningContent = typeof reasoning === 'string' ? reasoning : reasoning.content;diff --git a/packages/context-engine/src/tokenAccounting/types.ts b/packages/context-engine/src/tokenAccounting/types.tsindex d34609bdfb1..cec0c8ea084 100644--- a/packages/context-engine/src/tokenAccounting/types.ts+++ b/packages/context-engine/src/tokenAccounting/types.ts@@ -4,6 +4,9 @@ import type { UIChatMessage } from '@lobechat/types';* Source category each token belongs to.** - `content` β `msg.content` (the text body sent to provider)+ * - `fileContext` β the `<files_info>` block MessageContentProcessor appends+ * to user messages: parsed attachment text (or its preview+ * when oversized) plus image/video/audio metadata* - `toolCalls` β assistant's tool call payloads (`msg.tools[]`, equivalent* to OpenAI `tool_calls` once transformed): `id`, `apiName`,* `arguments`, `type` are sent to provider@@ -21,6 +24,7 @@ import type { UIChatMessage } from '@lobechat/types';*/export type TokenSourceType =| 'content'+ | 'fileContext'| 'toolCalls'| 'thoughtSignature'| 'reasoning'@@ -92,6 +96,11 @@ export interface CountContextTokensParams {* @default 1.25*/driftMultiplier?: number;+ /**+ * Attachments sent as a preview instead of their full text, as planned by+ * `planAttachmentPreviews`.+ */+ previewFileIds?: ReadonlySet<string>;};/*** Top-level tool definitions sent to the provider in the same request. Passdiff --git a/packages/prompts/src/prompts/files/file.ts b/packages/prompts/src/prompts/files/file.tsindex 2a942f6fd05..8d86134981d 100644--- a/packages/prompts/src/prompts/files/file.ts+++ b/packages/prompts/src/prompts/files/file.ts@@ -33,6 +33,11 @@ export interface PreviewLongFileContentOptions {canReadAttachment?: boolean;/** File id the model passes to `readAttachment` to page through the rest. */fileId: string;+ /**+ * Send a preview even when the text is under `FILE_INLINE_MAX_CHARS`: the request's attachment+ * budget had no room left for it (see `planAttachmentPreviews` in `@lobechat/context-engine`).+ */+ forcePreview?: boolean;/** Original character count when the stored text was cut at parse time. */originalChars?: number;}@@ -54,9 +59,14 @@ export const isOversizedFileContent = (contentLength: number, originalChars?: nu*/export const previewLongFileContent = (content: string,- { canReadAttachment = false, fileId, originalChars }: PreviewLongFileContentOptions,+ {+ canReadAttachment = false,+ fileId,+ forcePreview = false,+ originalChars,+ }: PreviewLongFileContentOptions,) => {- if (!isOversizedFileContent(content.length, originalChars)) {+ if (!forcePreview && !isOversizedFileContent(content.length, originalChars)) {return { attributes: '', body: content };}@@ -79,10 +89,16 @@ export const previewLongFileContent = (};};-const filePrompt = (item: ChatFileItem, addUrl: boolean, canReadAttachment: boolean) => {+const filePrompt = (+ item: ChatFileItem,+ addUrl: boolean,+ canReadAttachment: boolean,+ previewFileIds?: ReadonlySet<string>,+) => {const { attributes, body } = previewLongFileContent(item.content || '', {canReadAttachment,fileId: item.id,+ forcePreview: previewFileIds?.has(item.id),originalChars: item.originalCharCount,});return addUrl@@ -94,12 +110,13 @@ export const filePrompts = (fileList: ChatFileItem[],addUrl: boolean,canReadAttachment = false,+ previewFileIds?: ReadonlySet<string>,) => {if (fileList.length === 0) return '';const prompt = `<files><files_docstring>here are user upload files you can refer to</files_docstring>-${fileList.map((item) => filePrompt(item, addUrl, canReadAttachment)).join('\n')}+${fileList.map((item) => filePrompt(item, addUrl, canReadAttachment, previewFileIds)).join('\n')}</files>`;return prompt.trim();diff --git a/packages/prompts/src/prompts/files/index.test.ts b/packages/prompts/src/prompts/files/index.test.tsindex 0de752d432b..df612d000f2 100644--- a/packages/prompts/src/prompts/files/index.test.ts+++ b/packages/prompts/src/prompts/files/index.test.ts@@ -394,6 +394,20 @@ describe('filesPrompts', () => {expect(result).not.toContain('truncated="true"');});+ it('previews a file under the inline limit when its id is in previewFileIds', () => {+ const content = 'row,value\n'.repeat(1000);+ const result = filesPrompts({+ addUrl: false,+ canReadAttachment: true,+ fileList: [{ ...mockFile, content }],+ previewFileIds: new Set([mockFile.id]),+ });++ expect(result).toContain('truncated="true"');+ expect(result).toContain(`call readAttachment with fileId="${mockFile.id}"`);+ expect(result.length).toBeLessThan(content.length);+ });+it('replaces oversized content with a marked preview', () => {const content = `${'a'.repeat(FILE_PREVIEW_CHARS)}${'b'.repeat(FILE_INLINE_MAX_CHARS)}`;const result = filesPrompts({ addUrl: true, fileList: [{ ...mockFile, content }] });diff --git a/packages/prompts/src/prompts/files/index.ts b/packages/prompts/src/prompts/files/index.tsindex 595374e9ab1..2201c308e7d 100644--- a/packages/prompts/src/prompts/files/index.ts+++ b/packages/prompts/src/prompts/files/index.ts@@ -23,6 +23,7 @@ export const filesPrompts = ({addUrl = true,canReadAttachment = false,messageId,+ previewFileIds,}: {addUrl?: boolean;/** Whether `readAttachment` is in the request's tool set; see `PreviewLongFileContentOptions`. */@@ -31,6 +32,8 @@ export const filesPrompts = ({fileList?: ChatFileItem[];imageList?: ChatImageItem[];messageId?: string;+ /** Files sent as a preview regardless of size because the attachment budget is spent. */+ previewFileIds?: ReadonlySet<string>;videoList?: ChatVideoItem[];}) => {const hasImages = (imageList || []).length > 0;@@ -42,7 +45,7 @@ export const filesPrompts = ({const contentParts = [hasImages ? imagesPrompts(imageList!, addUrl, messageId) : '',- hasFiles ? filePrompts(fileList!, addUrl, canReadAttachment) : '',+ hasFiles ? filePrompts(fileList!, addUrl, canReadAttachment, previewFileIds) : '',hasVideos ? videosPrompts(videoList!, addUrl, messageId) : '',hasAudios ? audiosPrompts(audioList!, addUrl, messageId) : '',].filter(Boolean);diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.tsindex fe1a060f8e1..5a7c0b9a8eb 100644--- a/src/helpers/toolEngineering/index.test.ts+++ b/src/helpers/toolEngineering/index.test.ts@@ -1,3 +1,4 @@+import { AttachmentsManifest } from '@lobechat/builtin-tool-attachments';import { AuvManifest } from '@lobechat/builtin-tool-auv';import { DashboardManifest } from '@lobechat/builtin-tool-dashboard';import type * as ConstModule from '@lobechat/const';@@ -28,6 +29,11 @@ vi.mock('@/store/tool', () => ({manifest: DashboardManifest,type: 'builtin' as const,},+ {+ identifier: AttachmentsManifest.identifier,+ manifest: AttachmentsManifest,+ type: 'builtin' as const,+ },{identifier: 'search',manifest: {@@ -549,6 +555,23 @@ describe('toolEngineering', () => {expect(result.enabledToolIds).toContain('lobe-agent');});+ it.each([true, false])('enables lobe-attachments only with oversized files (%s)', (flag) => {+ const toolsEngine = createAgentToolsEngine(+ { model: 'deepseek-chat', provider: 'deepseek' },+ undefined,+ undefined,+ { hasOversizedFiles: flag },+ );++ const result = toolsEngine.generateToolsDetailed({+ model: 'deepseek-chat',+ provider: 'deepseek',+ toolIds: [],+ });++ expect(result.enabledToolIds.includes('lobe-attachments')).toBe(flag);+ });+it('should enable lobe-agent by default since it is always-on', () => {const toolsEngine = createAgentToolsEngine({model: 'deepseek-chat',diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.tsindex 126d812cf67..2c933fbe430 100644--- a/src/helpers/toolEngineering/index.ts+++ b/src/helpers/toolEngineering/index.ts@@ -145,6 +145,13 @@ export const createAgentToolsEngine = (pluginIds?: string[],/** Conversation context for context-aware builtin manifests (scope, isSubAgent). */manifestContext?: BuiltinToolResolveContext,+ options: {+ /**+ * Whether the conversation has an attachment that can be sent as a preview. Enables+ * `readAttachment` so the preview can be paged, as the server's tool discovery does.+ */+ hasOversizedFiles?: boolean;+ } = {},) => {const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);const agentState = getAgentStoreState();@@ -169,6 +176,7 @@ export const createAgentToolsEngine = (],executionTarget: chatConfigByIdSelectors.getExecutionTargetById(activeAgentId)(agentState),hasEnabledKnowledgeBases: agentSelectors.hasEnabledKnowledgeBases(agentState),+ hasOversizedFiles: options.hasOversizedFiles,// A `local` target only resolves on the desktop, where the host itself is// the machine: local tools are always reachable there.localExecutionReady: true,diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex e30a12b4c47..1f70c4697ef 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -62,6 +62,11 @@ const providersWithDeploymentName = new Set<string>([export interface GetChatCompletionPayload extends Partial<Omit<ChatStreamPayload, 'messages'>> {additionalContexts?: readonly RuntimeAdditionalContextFragment[];agentId?: string;+ /**+ * Attachments sent as a preview plus file id because the request's attachment+ * budget is spent (planned by `shouldCompress`).+ */+ attachmentPreviewFileIds?: string[];groupId?: string;messages: UIChatMessage[];/**@@ -124,6 +129,7 @@ class ChatService {agentId,groupId,additionalContexts,+ attachmentPreviewFileIds,topicId,resolvedAgentConfig,...params@@ -211,6 +217,7 @@ class ChatService {enableUserMemories,groupId,additionalContexts,+ attachmentPreviewFileIds,// History messages + the current turn; unset means no truncation.historyCount: modelParams.historyCount,// Page editor context from agent runtimediff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex 40ebdf62e9f..4bb6d723db5 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -59,6 +59,11 @@ interface ContextEngineeringContext {additionalContexts?: readonly RuntimeAdditionalContextFragment[];/** The agent ID that will respond (for group context injection) */agentId?: string;+ /**+ * Attachments sent as a preview plus file id because the request's attachment+ * budget is spent (planned by `shouldCompress`).+ */+ attachmentPreviewFileIds?: string[];/*** Identifiers the agent has explicitly disabled (`agents.plugins` tri-state).* Excluded from the client skill candidate pool entirely β not just left@@ -113,6 +118,7 @@ interface ContextEngineeringContext {// REVIEW: Maybe we can constrain identity, preference, exp to reorder or trim the context instead of passing everything inexport const contextEngineering = async ({additionalContexts,+ attachmentPreviewFileIds,messages = [],manifests,tools,@@ -320,7 +326,11 @@ export const contextEngineering = async ({systemRole,},// Desktop local/static URLs are not fetchable by remote providers or cloud tools.- fileContext: { enabled: true, includeFileUrl: !isDesktop },+ fileContext: {+ enabled: true,+ includeFileUrl: !isDesktop,+ previewFileIds: attachmentPreviewFileIds,+ },model: {capabilities: { isCanUseAudio, isCanUseFC, isCanUseVideo, isCanUseVision },displayName: getRuntimeModelDisplayName(model, provider),diff --git a/src/store/chat/agents/transports/ClientContextBuilder.ts b/src/store/chat/agents/transports/ClientContextBuilder.tsindex 2053971e1e2..65490166f00 100644--- a/src/store/chat/agents/transports/ClientContextBuilder.ts+++ b/src/store/chat/agents/transports/ClientContextBuilder.ts@@ -76,6 +76,7 @@ export class ClientContextBuilder implements ContextBuilder {{agentId: effectiveAgentId || undefined,additionalContexts: input.payload.additionalContexts,+ attachmentPreviewFileIds: input.payload.attachmentPreviewFileIds,groupId,messages,model: input.model,diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.tsindex ed0198684fd..5a4fec993d9 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts@@ -2,6 +2,7 @@ import type { AgentState } from '@lobechat/agent-runtime';import * as agentRuntime from '@lobechat/agent-runtime';import { resolveLocalSystemManifest } from '@lobechat/builtin-tool-local-system';import type * as LobeChatConst from '@lobechat/const';+import { FILE_PREVIEW_CHARS } from '@lobechat/prompts';import { type LobeChatPluginApi, type UIChatMessage } from '@lobechat/types';import { act, renderHook } from '@testing-library/react';import { type EnabledAiModel, ModelProvider } from 'model-bank';@@ -1391,6 +1392,7 @@ describe('StreamingExecutor actions', () => {expect.any(Object),undefined,expect.objectContaining({ executionEnv: 'local' }),+ { hasOversizedFiles: false },);const localSystem = state.operationToolSet?.manifestMap['lobe-local-system'];const readFile = localSystem?.api.find((api: LobeChatPluginApi) => api.name === 'readFile');@@ -1887,6 +1889,48 @@ describe('StreamingExecutor actions', () => {});});+ describe('internal_createAgentState attachment reading', () => {+ const createState = (content: string) => {+ act(() => {+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });+ });+ const { result } = renderHook(() => useChatStore());+ const userMessage = {+ content: TEST_CONTENT.USER_MESSAGE,+ fileList: [{ content, fileType: 'text/plain', id: 'file-1', name: 'paper.txt', size: 1 }],+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ } as UIChatMessage;++ return result.current.internal_createAgentState({+ agentId: TEST_IDS.SESSION_ID,+ messages: [userMessage],+ parentMessageId: userMessage.id,+ topicId: TEST_IDS.TOPIC_ID,+ });+ };++ // Regression: LOBE-14165. The attachment budget can send any attachment longer than a+ // preview as one, so the client must offer `readAttachment` to page it, like the server.+ it('enables readAttachment when an attachment is longer than a preview', () => {+ const spy = vi.spyOn(toolEngineering, 'createAgentToolsEngine');++ createState('x'.repeat(FILE_PREVIEW_CHARS + 1));++ expect(spy.mock.calls.at(-1)?.[3]).toEqual({ hasOversizedFiles: true });+ });++ it('does not enable readAttachment for short attachments', () => {+ const spy = vi.spyOn(toolEngineering, 'createAgentToolsEngine');++ createState('short note');++ expect(spy.mock.calls.at(-1)?.[3]).toEqual({ hasOversizedFiles: false });+ });+ });+describe('internal_createAgentState with disableTools', () => {it('should return empty toolManifestMap when disableTools is true', async () => {act(() => {diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 826e0849ee9..05bede6be3e 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -23,7 +23,12 @@ import {resolveSubAgentModel,} from '@lobechat/const';import { type ToolsEngine } from '@lobechat/context-engine';-import { buildTaskDetailPrompt, buildTaskListPrompt } from '@lobechat/prompts';+import {+ buildTaskDetailPrompt,+ buildTaskListPrompt,+ FILE_PREVIEW_CHARS,+ isOversizedFileContent,+} from '@lobechat/prompts';import {buildGoalOverviewContext,type ConversationContext,@@ -105,6 +110,23 @@ const getMediaAvailability = (messages: UIChatMessage[]) => ({hasVideos: messages.some((message) => message.role === 'user' && !!message.videoList?.length),});+/**+ * Whether any user attachment is long enough to be sent as a preview, either because it is+ * oversized or because the attachment budget (`planAttachmentPreviews`) previews it. Mirrors the+ * server's `readHasOversizedFiles`, which enables `readAttachment` for those previews.+ */+const hasPreviewableFiles = (messages: UIChatMessage[]) =>+ messages.some(+ (message) =>+ message.role === 'user' &&+ !!message.fileList?.some((file) => {+ const length = file.content?.length ?? 0;+ return (+ length > FILE_PREVIEW_CHARS || isOversizedFileContent(length, file.originalCharCount)+ );+ }),+ );+/*** Core streaming execution actions for AI chat*/@@ -284,6 +306,7 @@ export class StreamingExecutorActionImpl {// sub-agent runs. Desktop client runs also need the local environment so// local-system can advertise IPC-only capabilities such as direct image reads.{ executionEnv: isDesktop ? 'local' : undefined, isSubAgent, scope },+ { hasOversizedFiles: hasPreviewableFiles(messages) },);// When skillActivateMode is 'manual':// Exclude only discovery tools (activator, skill-store) so runtime-managed defaults