🤯 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(context-engine): trim stale tool results at the payload boundary (#19777)
Arvin Xu7e319f54aa0c
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/inflightRunRegistry.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/inflightRunRegistry.test.tsindex f7789d76f9d..66bdfc109e2 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/inflightRunRegistry.test.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/inflightRunRegistry.test.ts@@ -19,7 +19,9 @@ const run = (ipcSessionId: string, extra?: Partial<HeteroInflightRun>): HeteroInagentType: 'claude-code',ipcSessionId,operationId: `op-${ipcSessionId}`,- startedAt: new Date('2026-09-21T02:00:00.000Z').toISOString(),+ // Relative to now: `claim` defaults to `Date.now()`, so a hard-coded date+ // turns stale 48h (HETERO_INFLIGHT_RUN_MAX_AGE_MS) after it was written.+ startedAt: new Date().toISOString(),topicId: 'topic-1',...extra,});diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex c8733e01064..eb08a560100 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -134,6 +134,7 @@ export const buildServerCallLlmContext = async ({discordContext: state.world?.channel?.discord,enableExpertise: selectEnableExpertise(state),enableHistoryCount: agentConfig.chatConfig?.enableHistoryCount ?? undefined,+ enableStaleToolResultTrim: agentConfig.chatConfig?.enableStaleToolResultTrim ?? undefined,evalContext: state.world?.eval,expertise: selectExpertise(state),forceFinish: state.forceFinish,diff --git a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.tsindex e01883929bd..44d92af5045 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts@@ -528,6 +528,104 @@ describe('serverMessagesEngine', () => {});});+ describe('stale tool result trimming', () => {+ const READ_CONTENT = 'x'.repeat(120_000);++ // A readFile result superseded by a later write to the same path, outside+ // the default recency window and past the default size gate, so the trim+ // fires unless the switch disables it. No createdAt → cold cache.+ const supersededReadMessages = (): UIChatMessage[] =>+ [+ {+ content: '',+ id: 'a1',+ role: 'assistant',+ tools: [+ {+ apiName: 'readFile',+ arguments: JSON.stringify({ path: '/a.ts' }),+ id: 'call-readFile',+ identifier: 'lobe-local-system',+ type: 'builtin',+ },+ ],+ },+ {+ content: READ_CONTENT,+ id: 't1',+ plugin: {+ apiName: 'readFile',+ arguments: JSON.stringify({ path: '/a.ts' }),+ identifier: 'lobe-local-system',+ },+ pluginState: { loc: [0, 200], path: '/a.ts' },+ role: 'tool',+ tool_call_id: 'call-readFile',+ },+ {+ content: '',+ id: 'a2',+ role: 'assistant',+ tools: [+ {+ apiName: 'writeFile',+ arguments: JSON.stringify({ path: '/a.ts' }),+ id: 'call-writeFile',+ identifier: 'lobe-local-system',+ type: 'builtin',+ },+ ],+ },+ {+ content: 'Successfully wrote to /a.ts',+ id: 't2',+ plugin: {+ apiName: 'writeFile',+ arguments: JSON.stringify({ path: '/a.ts' }),+ identifier: 'lobe-local-system',+ },+ pluginState: { path: '/a.ts', success: true },+ role: 'tool',+ tool_call_id: 'call-writeFile',+ },+ ...Array.from({ length: 21 }, (_, i) => ({+ content: `recent ${i}`,+ id: `pad-${i}`,+ role: 'assistant',+ })),+ ] as unknown as UIChatMessage[];++ const payloadText = (messages: any[]) =>+ messages+ .map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content)))+ .join('\n');++ it('trims stale tool results by default', async () => {+ const { messages: result } = await serverMessagesEngine({+ messages: supersededReadMessages(),+ model: 'gpt-4',+ provider: 'openai',+ });++ const payload = payloadText(result);+ expect(payload).not.toContain(READ_CONTENT);+ expect(payload).toContain('superseded by a later write');+ });++ it('forwards enableStaleToolResultTrim: false to the engine', async () => {+ const { messages: result } = await serverMessagesEngine({+ enableStaleToolResultTrim: false,+ messages: supersededReadMessages(),+ model: 'gpt-4',+ provider: 'openai',+ });++ const payload = payloadText(result);+ expect(payload).toContain(READ_CONTENT);+ expect(payload).not.toContain('superseded by a later write');+ });+ });+describe('user memory injection', () => {it('should inject user memories when provided', async () => {const messages = createBasicMessages();diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.tsindex 45d11fd69cf..b57a37d53f7 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts@@ -26,6 +26,7 @@ export const toContextSnapshot = ({enableAgentMode,enableExpertise,enableHistoryCount,+ enableStaleToolResultTrim,evalContext,expertise,forceFinish,@@ -57,6 +58,7 @@ export const toContextSnapshot = ({agent: {documents: agentDocuments,enableHistoryCount,+ enableStaleToolResultTrim,historyCount,identity: agentIdentity,inputTemplate,diff --git a/apps/server/src/modules/Mecha/ContextEngineering/types.ts b/apps/server/src/modules/Mecha/ContextEngineering/types.tsindex a8764e6412e..4717c712a45 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/types.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/types.ts@@ -13,11 +13,11 @@ import type {LobeToolManifest,OnboardingContext,PlanTodoConfig,+ ProjectInstructionFile,SkillMeta,ToolDiscoveryConfig,TopicReferenceItem,UserMemoryData,- ProjectInstructionFile,WorkspaceContext,} from '@lobechat/context-engine';import type { AgentIdentityContext, PageContentContext } from '@lobechat/prompts';@@ -133,6 +133,12 @@ export interface ServerMessagesEngineParams {/** Whether to enable history message count limit */enableHistoryCount?: boolean;+ /**+ * Whether stale tool results are replaced with short placeholders in the+ * model context. Undefined / true → trimming enabled (default).+ */+ enableStaleToolResultTrim?: boolean;+/** Force finish flag: when true, injects summary prompt for max-steps completion */forceFinish?: boolean;diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 388dce3403b..e35e62b58fe 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1000,6 +1000,8 @@"settingChat.enableHistoryCount.setlimited": "Set limited history messages","settingChat.enableHistoryCount.title": "Limit History Message Count","settingChat.enableHistoryCount.unlimited": "Unlimited history message count",+ "settingChat.enableStaleToolResultTrim.desc": "Replace outdated tool outputs (overwritten file reads, old browser snapshots, stale command output) with short placeholders in the model context to save tokens. Disable if the assistant needs full historical tool output.",+ "settingChat.enableStaleToolResultTrim.title": "Trim Stale Tool Results","settingChat.enableStreaming.desc": "Enable streaming output to display responses in real-time. When disabled, only the complete response is shown.","settingChat.enableStreaming.title": "Enable Streaming Output","settingChat.historyCount.desc": "Number of historical messages carried with each request",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 8ed5be82319..1e890e843eb 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1000,6 +1000,8 @@"settingChat.enableHistoryCount.setlimited": "使用历史消息数","settingChat.enableHistoryCount.title": "限制历史消息数","settingChat.enableHistoryCount.unlimited": "不限历史消息数",+ "settingChat.enableStaleToolResultTrim.desc": "将已被覆盖的文件读取、过期的浏览器快照与旧命令输出替换为简短占位符,以节省上下文 token。若助手需要完整的历史工具输出可关闭。",+ "settingChat.enableStaleToolResultTrim.title": "裁剪过期工具结果","settingChat.enableStreaming.desc": "启用流式输出以实时显示响应。禁用后仅显示完整响应。","settingChat.enableStreaming.title": "启用流式输出","settingChat.historyCount.desc": "每次请求携带的消息数(包括最新编写的提问。每个提问和回答都计算1)",diff --git a/packages/const/src/settings/agent.ts b/packages/const/src/settings/agent.tsindex b5c9a09f754..f6a8b3d0559 100644--- a/packages/const/src/settings/agent.ts+++ b/packages/const/src/settings/agent.ts@@ -29,6 +29,7 @@ export const DEFAULT_AGENT_CHAT_CONFIG: LobeAgentChatConfig = {enableContextCompression: true,enableFollowUpChips: false,enableHistoryCount: false,+ enableStaleToolResultTrim: true,enableStreaming: true,historyCount: 20,reasoningBudgetToken: 1024,diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex d97c48d636f..313c27030aa 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -6,6 +6,7 @@ import { ContextEngine } from '../../pipeline';import {ActivationResultTrimProcessor,AgentCouncilFlattenProcessor,+ cacheEconomicsForProvider,CompressedGroupRoleTransformProcessor,DisabledToolCallFilter,GroupMessageFlattenProcessor,@@ -18,6 +19,7 @@ import {PlaceholderMessageFilterProcessor,PlaceholderVariablesProcessor,ReactionFeedbackProcessor,+ StaleToolResultTrimProcessor,SupervisorRoleRestoreProcessor,TaskCallbackMessageProcessor,TaskMessageProcessor,@@ -160,6 +162,7 @@ export class MessagesEngine {inputTemplate,enableAgentMode,enableHistoryCount,+ enableStaleToolResultTrim,historyCount,forceFinish,historySummary,@@ -565,6 +568,18 @@ export class MessagesEngine {injectedManifests: injectedToolManifests,injectedSkills: injectedActivatedSkills,}),+ // Stale tool-result trimming — replaces the bodies of superseded tool+ // results (file reads later overwritten, stale browser snapshots, old+ // command output) with short placeholders. Rules are monotone so the+ // trimmed prefix stays byte-stable across requests and the prompt-cache+ // prefix survives; savings land at the operation boundary where the+ // cache is cold anyway. Same pipeline position constraints as+ // ActivationResultTrimProcessor above. Cache economics (TTL, read/write+ // prices) follow the active provider.+ new StaleToolResultTrimProcessor({+ economics: cacheEconomicsForProvider(provider),+ enabled: enableStaleToolResultTrim !== false,+ }),// Placeholder variables processing — MUST run AFTER all flatten / role// transform steps. AssistantGroup / Supervisor messages keep their real// content (including any `{{...}}` placeholders inside tool results)diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.staleToolResultTrim.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.staleToolResultTrim.test.tsnew file mode 100644index 00000000000..a8756a45706--- /dev/null+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.staleToolResultTrim.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from 'vitest';++import type { UIChatMessage } from '@/types/index';++import { MessagesEngine } from '../MessagesEngine';+import type { MessagesEngineParams } from '../types';++/**+ * The `enableStaleToolResultTrim` engine param gates the+ * StaleToolResultTrimProcessor: undefined / true trims (default), explicit+ * false leaves the history untouched.+ */++const READ_CONTENT = 'x'.repeat(120_000);++const assistantWithToolCall = (id: string, apiName: string, args: Record<string, unknown>) =>+ ({+ content: '',+ id,+ role: 'assistant',+ tools: [+ {+ apiName,+ arguments: JSON.stringify(args),+ id: `call-${apiName}`,+ identifier: 'lobe-local-system',+ type: 'builtin',+ },+ ],+ }) as unknown as UIChatMessage;++const toolMessage = (+ apiName: string,+ content: string,+ pluginState: Record<string, unknown>,+ args: Record<string, unknown>,+): UIChatMessage =>+ ({+ content,+ id: `tool-${apiName}`,+ plugin: {+ apiName,+ arguments: JSON.stringify(args),+ identifier: 'lobe-local-system',+ },+ pluginState,+ role: 'tool',+ tool_call_id: `call-${apiName}`,+ }) as unknown as UIChatMessage;++// A readFile result superseded by a later write to the same path, pushed out+// of the default 20-message recency window and past the default 100k minimum+// tool-char gate so the trim fires by default.+const supersededReadMessages = (): UIChatMessage[] => [+ assistantWithToolCall('a1', 'readFile', { path: '/a.ts' }),+ toolMessage('readFile', READ_CONTENT, { loc: [0, 200], path: '/a.ts' }, { path: '/a.ts' }),+ assistantWithToolCall('a2', 'writeFile', { path: '/a.ts' }),+ toolMessage(+ 'writeFile',+ 'Successfully wrote to /a.ts',+ { path: '/a.ts', success: true },+ { path: '/a.ts' },+ ),+ ...Array.from(+ { length: 21 },+ (_, i) =>+ ({ content: `recent ${i}`, id: `pad-${i}`, role: 'assistant' }) as unknown as UIChatMessage,+ ),+];++const createParams = (overrides?: Partial<MessagesEngineParams>): MessagesEngineParams => ({+ capabilities: { isCanUseFC: () => true },+ enableSystemDate: false,+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ ...overrides,+});++const payloadText = (messages: any[]) =>+ messages+ .map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content)))+ .join('\n');++describe('MessagesEngine — stale tool result trimming switch', () => {+ it('trims a superseded readFile result by default (param undefined)', async () => {+ const engine = new MessagesEngine(createParams({ messages: supersededReadMessages() }));++ const result = await engine.process();++ const payload = payloadText(result.messages);+ expect(payload).not.toContain(READ_CONTENT);+ expect(payload).toContain('superseded by a later write');+ });++ it('leaves the history untouched when enableStaleToolResultTrim is false', async () => {+ const engine = new MessagesEngine(+ createParams({ enableStaleToolResultTrim: false, messages: supersededReadMessages() }),+ );++ const result = await engine.process();++ const payload = payloadText(result.messages);+ expect(payload).toContain(READ_CONTENT);+ expect(payload).not.toContain('superseded by a later write');+ });+});diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.tsindex e5c8b165fd3..3a059abd010 100644--- a/packages/context-engine/src/engine/messages/types.ts+++ b/packages/context-engine/src/engine/messages/types.ts@@ -247,6 +247,11 @@ export interface MessagesEngineParams {enableAgentMode?: boolean;/** Whether to enable history message count limit */enableHistoryCount?: boolean;+ /**+ * Whether stale tool results are replaced with short placeholders in the+ * model context. Undefined / true → trimming enabled (default).+ */+ enableStaleToolResultTrim?: boolean;/** Whether to inject the operation expertise snapshot */enableExpertise?: boolean;/** Force finish flag: when true, injects summary prompt for max-steps completion */diff --git a/packages/context-engine/src/processors/StaleToolResultTrim.ts b/packages/context-engine/src/processors/StaleToolResultTrim.tsnew file mode 100644index 00000000000..f2387992fb0--- /dev/null+++ b/packages/context-engine/src/processors/StaleToolResultTrim.ts@@ -0,0 +1,582 @@+import debug from 'debug';++import { BaseProcessor } from '../base/BaseProcessor';+import type { Message, PipelineContext, ProcessorOptions } from '../types';++declare module '../types' {+ interface PipelineContextMetadataOverrides {+ staleToolResultTrim?: {+ byRule: Record<string, number>;+ /** Whether the turn boundary fell inside the provider cache TTL. */+ cacheWarm?: boolean;+ /** Estimated gain used by the warm break-even check (skip path only). */+ gainEstimate?: number;+ /** Measured gap between the previous turn's last activity and the trigger. */+ gapMs?: number;+ /** What the trim would have saved (skip path only). */+ potentialSavedChars?: number;+ /** Estimated rewrite cost used by the warm break-even check (skip path only). */+ rewriteCostEstimate?: number;+ savedChars: number;+ skippedReason?: 'warm-cache';+ trimmedMessages: number;+ };+ }+}++const log = debug('context-engine:processor:StaleToolResultTrimProcessor');++export interface StaleToolResultTrimConfig {+ /**+ * Cache read price relative to the plain input price.+ * Defaults to the active provider's policy from `economics`.+ */+ cacheReadPrice?: number;+ /**+ * Provider prompt-cache TTL in ms. A turn whose trigger follows the+ * previous turn's last activity within this window has a warm cache, so+ * trimming is a paid rewrite and goes through the warm break-even check.+ * Defaults to the active provider's policy from `economics`.+ */+ cacheTtlMs?: number;+ /**+ * Cache write price relative to the plain input price.+ * Defaults to the active provider's policy from `economics`.+ */+ cacheWritePrice?: number;+ /**+ * Head chars kept when an old `runCommand` / `getCommandOutput` result is+ * trimmed (the same number of tail chars is also kept).+ * @default 500+ */+ commandKeepChars?: number;+ /**+ * Head chars kept when an old web-browsing search/crawl result is trimmed.+ * @default 1000+ */+ crawlKeepChars?: number;+ /**+ * Cache economics of the active provider (TTL + read/write prices), e.g.+ * from {@link cacheEconomicsForProvider}. Individual `cache*` overrides win.+ * @default ANTHROPIC_CACHE_ECONOMICS+ */+ economics?: CacheEconomics;+ /**+ * Master switch.+ * @default true+ */+ enabled?: boolean;+ /**+ * Trailing message count that is never trimmed. The model is actively+ * working with the tail of the conversation; trimming there saves little and+ * risks evicting context it is about to use.+ * @default 20+ */+ keepRecentMessages?: number;+ /**+ * Total chars of tool results below which the trim is skipped entirely —+ * small conversations gain nothing and the gate keeps the no-op path cheap.+ * Monotone within a growing history, so it cannot flip the prefix back and+ * forth between requests.+ * @default 100_000+ */+ minTotalToolChars?: number;+ /**+ * Head chars kept when an old `readPage` result is trimmed. Unlike+ * `snapshot` (interaction state that dies with the next navigation),+ * readPage text is source material the model may quote in its final+ * answer, so the lead of the page stays available.+ * @default 1000+ */+ pageTextKeepChars?: number;+ /**+ * Warm-cache break-even: assumed number of remaining LLM steps the current+ * turn will run. The trim fires on a warm cache only when+ * `estimate × saved × readPrice > rewriteDelta × warmSafetyMargin`.+ * Conservative default; real heavy ops run 100+ steps, quick follow-ups 1-5.+ * @default 20+ */+ warmRemainingStepsEstimate?: number;+ /**+ * Multiplier on the rewrite cost in the warm break-even check, absorbing+ * estimation error.+ * @default 1.5+ */+ warmSafetyMargin?: number;+}++const LOCAL_SYSTEM = 'lobe-local-system';+const BROWSER = 'lobe-browser';+const WEB_BROWSING = 'lobe-web-browsing';++export interface CacheEconomics {+ /** Cached-read price relative to the plain input price. */+ readPrice: number;+ /** Cache entry lifetime in ms; a turn gap beyond this means the cache is cold. */+ ttlMs: number;+ /** Reprocessing price of an invalidated prefix, relative to plain input. */+ writePrice: number;+}++export const ANTHROPIC_CACHE_ECONOMICS: CacheEconomics = {+ readPrice: 0.1, // cache read = 10% of input+ ttlMs: 300_000, // 5-minute ephemeral TTL, refreshed per hit+ writePrice: 1.25, // cache write = 1.25× input+};++// Cache economics differ per provider; pricing the warmth verdict and the+// break-even gate with the wrong ones either rewrites still-warm prefixes or+// skips worthwhile trims.+const PROVIDER_CACHE_ECONOMICS: Record<string, CacheEconomics> = {+ anthropic: ANTHROPIC_CACHE_ECONOMICS,+ // Anthropic models via Bedrock share the same cache semantics.+ bedrock: ANTHROPIC_CACHE_ECONOMICS,+ deepseek: {+ // Automatic disk context cache: long-lived, hit ≈ 0.25× miss, no write+ // fee — an invalidated prefix just costs a plain input pass.+ readPrice: 0.25,+ ttlMs: 3_600_000,+ writePrice: 1,+ },+ google: {+ // Gemini implicit caching: short TTL, hit ≈ 0.25×, no explicit write fee.+ readPrice: 0.25,+ ttlMs: 300_000,+ writePrice: 1,+ },+ openai: {+ // Automatic prompt caching: short inactivity expiry, hit = 0.5×, no write fee.+ readPrice: 0.5,+ ttlMs: 300_000,+ writePrice: 1,+ },+};++/** Cache economics for a provider id; falls back to Anthropic's (most conservative TTL). */+export const cacheEconomicsForProvider = (provider?: string): CacheEconomics =>+ PROVIDER_CACHE_ECONOMICS[provider ?? ''] ?? ANTHROPIC_CACHE_ECONOMICS;++const READ_APIS = new Set(['readFile']);+const WRITE_APIS = new Set(['writeFile', 'editFile']);+const COMMAND_APIS = new Set(['runCommand', 'getCommandOutput']);+const CRAWL_APIS = new Set(['search', 'crawlSinglePage', 'crawlMultiPages']);++interface PluginInfo {+ apiName?: string;+ arguments?: unknown;+ identifier?: string;+}++const getPlugin = (message: Message): PluginInfo | undefined =>+ message.plugin as PluginInfo | undefined;++// On the wire, `plugin.arguments` is the serialized JSON string from the+// model's tool call; older rows and tests may carry the parsed object.+const parseArguments = (args: unknown): Record<string, any> | undefined => {+ if (!args) return undefined;+ if (typeof args === 'object') return args as Record<string, any>;+ if (typeof args === 'string') {+ try {+ const parsed = JSON.parse(args);+ return parsed && typeof parsed === 'object' ? parsed : undefined;+ } catch {+ return undefined;+ }+ }+ return undefined;+};++// Prefer the structured pluginState (`ReadFileState`/`WriteFileState` carry+// `path`/`loc` as real fields); fall back to parsing the tool-call arguments+// for rows written before the state fields existed.+const pathOf = (message: Message, plugin: PluginInfo | undefined): string | undefined => {+ const fromState = (message.pluginState as { path?: unknown } | undefined)?.path;+ if (typeof fromState === 'string' && fromState.length > 0) return fromState;+ const args = parseArguments(plugin?.arguments);+ const p = args?.path ?? args?.file_path;+ return typeof p === 'string' && p.length > 0 ? p : undefined;+};++const locOf = (message: Message, plugin: PluginInfo | undefined): [number, number] | undefined => {+ const fromState = (message.pluginState as { loc?: unknown } | undefined)?.loc;+ if (Array.isArray(fromState) && fromState.length === 2) {+ return [fromState[0], fromState[1]];+ }+ const loc = parseArguments(plugin?.arguments)?.loc;+ return Array.isArray(loc) && loc.length === 2 ? [loc[0], loc[1]] : undefined;+};++/**+ * The window a readFile call actually returned. An omitted `loc` defaults to+ * the first 200 lines in the service (`readLocalFile` slices `loc ?? [0, 200]`)+ * unless `fullContent` was requested — treating it as an unbounded full-file+ * read would let a later default read claim to cover ranges it never returned.+ */+const effectiveReadWindow = (+ message: Message,+ plugin: PluginInfo | undefined,+): [number, number] => {+ const explicit = locOf(message, plugin);+ if (explicit) return explicit;+ return parseArguments(plugin?.arguments)?.fullContent+ ? [Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY]+ : [0, 200];+};++/**+ * `UIChatMessage.createdAt` is an epoch-milliseconds number on the canonical+ * path; DB dumps and tests carry ISO strings. `Date.parse(number)` coerces to+ * a garbage string and yields NaN, so normalize explicitly.+ */+const toEpochMs = (value: unknown): number | undefined => {+ if (typeof value === 'number' && Number.isFinite(value)) return value;+ if (value instanceof Date) return value.getTime();+ if (typeof value === 'string') {+ const t = Date.parse(value);+ return Number.isFinite(t) ? t : undefined;+ }+ return undefined;+};++/**+ * Replaces the bodies of stale tool results with short placeholders at the+ * payload-assembly boundary.+ *+ * Motivation: within one topic, every request replays the full history, and+ * tool results dominate that history (a single readFile of a large file is+ * tens of KB). Once a result is superseded — the file was rewritten since,+ * the page snapshot is ten interactions old — replaying it buys the model+ * nothing, but every caller still pays for it on every step.+ *+ * Cache safety comes from three constraints: trim decisions only depend on+ * the presence of LATER messages, so once trimmed a message trims identically+ * on every later request and the already-trimmed prefix stays byte-stable;+ * the trim never touches messages from the in-flight turn (after the last+ * user message), because every LLM step of a running operation re-runs this+ * pipeline and rewriting the prefix mid-operation would cold the warm prompt+ * cache for every remaining step; and when the turn boundary itself has a+ * warm cache (user followed up within the provider's cache TTL), the trim is+ * a paid rewrite, so it only fires when the savings clear the warm+ * thresholds. Trimming is truly free at cold boundaries — the first turn,+ * or any gap longer than the cache TTL.+ *+ * Must run AFTER the flatten processors (assistantGroup / compressedGroup+ * hoist nested tool results into top-level `role: 'tool'` rows with+ * plugin/pluginState re-attached) and BEFORE ToolCallProcessor.+ */+export class StaleToolResultTrimProcessor extends BaseProcessor {+ readonly name = 'StaleToolResultTrimProcessor';++ private config: Required<Omit<StaleToolResultTrimConfig, 'economics' | 'enabled'>> & {+ economics: CacheEconomics;+ enabled: boolean;+ };++ constructor(config: StaleToolResultTrimConfig = {}, options: ProcessorOptions = {}) {+ super(options);+ const economics = config.economics ?? ANTHROPIC_CACHE_ECONOMICS;+ this.config = {+ cacheReadPrice: config.cacheReadPrice ?? economics.readPrice,+ cacheTtlMs: config.cacheTtlMs ?? economics.ttlMs,+ cacheWritePrice: config.cacheWritePrice ?? economics.writePrice,+ commandKeepChars: config.commandKeepChars ?? 500,+ crawlKeepChars: config.crawlKeepChars ?? 1000,+ economics,+ enabled: config.enabled ?? true,+ keepRecentMessages: config.keepRecentMessages ?? 20,+ minTotalToolChars: config.minTotalToolChars ?? 100_000,+ pageTextKeepChars: config.pageTextKeepChars ?? 1000,+ warmRemainingStepsEstimate: config.warmRemainingStepsEstimate ?? 20,+ warmSafetyMargin: config.warmSafetyMargin ?? 1.5,+ };+ }++ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {+ if (!this.config.enabled) return this.markAsExecuted(context);++ const messages = context.messages;++ // Turn boundary: the last user message starts the in-flight turn. Every+ // LLM step of a running operation re-assembles the payload and re-runs+ // this pipeline, so the trim set must be FROZEN for the whole turn —+ // anything that changes it mid-operation rewrites the prefix and colds+ // the warm prompt cache for every remaining step. Three moving parts are+ // pinned accordingly:+ //+ // 1. The recency window is derived from the turn boundary, not the+ // growing message count: the protected tail is the K messages before+ // the trigger plus the entire in-flight turn. `messages.length - K`+ // would advance as the op appends, letting old results cross the+ // cutoff mid-operation.+ // 2. The supersede index (pass 1) only covers the closed history before+ // the boundary: an in-flight write must not retroactively trim+ // pre-boundary reads mid-operation. It takes effect at the next turn+ // boundary instead.+ // 3. The minimum-size gate is measured on the closed history only:+ // counting in-flight tool output would let the gate trip mid-turn as+ // the op appends results, activating trims that were off at the+ // boundary.+ //+ // When no user message exists (tests, exotic flows), the recency window+ // alone applies.+ const lastUserIndex = messages.reduce((acc, m, i) => (m.role === 'user' ? i : acc), -1);+ const boundary =+ lastUserIndex >= 0+ ? Math.max(0, lastUserIndex + 1 - this.config.keepRecentMessages)+ : Math.max(0, messages.length - this.config.keepRecentMessages);++ let closedToolChars = 0;+ for (let i = 0; i < boundary; i++) {+ const m = messages[i];+ if (m.role === 'tool' && typeof m.content === 'string') closedToolChars += m.content.length;+ }+ if (closedToolChars < this.config.minTotalToolChars) {+ return this.markAsExecuted(context);+ }++ // Pass 1 — index events inside the closed history that invalidate earlier+ // results:+ // - writes per file path (any writeFile/editFile result row marks a write)+ // - read windows per path, to find reads fully covered by a later re-read+ // Failed results index nothing: a failed write did not supersede anything,+ // a failed read covers nothing.+ const lastWriteIndexByPath = new Map<string, number>();+ const readWindowsByPath = new Map<string, { end: number; index: number; start: number }[]>();++ for (let index = 0; index < boundary; index++) {+ const m = messages[index];+ if (m.role !== 'tool') continue;+ if (m.pluginError) continue;+ const plugin = getPlugin(m);+ if (plugin?.identifier !== LOCAL_SYSTEM) continue;++ const path = pathOf(m, plugin);+ if (!path) continue;++ if (WRITE_APIS.has(plugin.apiName ?? '')) {+ lastWriteIndexByPath.set(path, index);+ } else if (READ_APIS.has(plugin.apiName ?? '')) {+ const loc = effectiveReadWindow(m, plugin);+ const windows = readWindowsByPath.get(path) ?? [];+ windows.push({ end: loc[1], index, start: loc[0] });+ readWindowsByPath.set(path, windows);+ }+ }++ // Pass 2 — collect trim candidates (dry run first; the cache-warmth gate+ // below needs the total savings before deciding).+ const candidates: { content: string; index: number; rule: string }[] = [];+ for (let index = 0; index < boundary; index++) {+ const message = messages[index];+ if (message.role !== 'tool') continue;+ if (typeof message.content !== 'string' || message.content.length === 0) continue;+ // Error results are the most valuable debugging context — never trim.+ if (message.pluginError) continue;++ const trimmed = this.trimMessage(message, index, lastWriteIndexByPath, readWindowsByPath);+ if (trimmed === undefined || trimmed.content === message.content) continue;+ // Never admit a replacement that grows the payload — a result barely over+ // the keep threshold would come back longer once the notice is appended.+ // Image reads are exempt: the dropped attachment dwarfs any notice.+ const hasImages =+ ((message.pluginState as { images?: unknown[] } | undefined)?.images?.length ?? 0) > 0;+ if (!hasImages && trimmed.content.length >= message.content.length) continue;+ candidates.push({ content: trimmed.content, index, rule: trimmed.rule });+ }++ if (candidates.length === 0) {+ return this.markAsExecuted(context);+ }++ // Cache-warmth gate. Trimming is free only when the prompt cache is cold —+ // i.e. the gap between the previous turn's last activity and this turn's+ // trigger exceeds the provider's cache TTL (Anthropic: 5 min, refreshed+ // per hit). When the user follows up within the TTL, the untrimmed prefix+ // would still hit, so the trim must clear a break-even check against the+ // rewrite it causes:+ //+ // gain = R_est × S × readPrice (each remaining step reads S less)+ // cost = ((P − S) × writePrice − P × readPrice) × margin+ //+ // Thanks to determinism the rewrite is paid at most once per trim-set+ // change, not per follow-up — but a warm quick-question turn (1-5 steps)+ // would never recoup it, which is exactly what the check blocks. The gap,+ // the candidates, and the priced payload are all frozen at the turn+ // boundary, so the decision cannot flip mid-operation and flip the+ // prefix with it.+ const potentialSavedChars = candidates.reduce(+ (s, c) => s + (messages[c.index].content as string).length - c.content.length,+ 0,+ );+ const triggeredAt = toEpochMs(messages[lastUserIndex]?.createdAt);+ const prevActivityAt = toEpochMs(messages[lastUserIndex - 1]?.createdAt);+ const gapMs =+ triggeredAt !== undefined && prevActivityAt !== undefined+ ? triggeredAt - prevActivityAt+ : undefined;+ const cacheWarm = gapMs !== undefined && gapMs <= this.config.cacheTtlMs;++ if (cacheWarm) {+ // The cost side of the break-even must be priced from the payload frozen+ // at the turn boundary (closed history + the trigger), not the live+ // message list: candidates and savings are already frozen there, and+ // counting in-flight output would grow the estimated rewrite cost+ // step by step, flipping a trim that passed the gate back to a skip+ // mid-operation and restoring the original prefix.+ const payloadEnd = lastUserIndex >= 0 ? lastUserIndex + 1 : messages.length;+ let totalChars = 0;+ for (let i = 0; i < payloadEnd; i++) {+ const m = messages[i];+ if (typeof m.content === 'string') totalChars += m.content.length;+ }+ const gainEstimate =+ this.config.warmRemainingStepsEstimate * potentialSavedChars * this.config.cacheReadPrice;+ const rewriteCostEstimate =+ (totalChars - potentialSavedChars) * this.config.cacheWritePrice -+ totalChars * this.config.cacheReadPrice;+ const worthwhile = gainEstimate > rewriteCostEstimate * this.config.warmSafetyMargin;+ if (!worthwhile) {+ log(+ 'Skipping trim: cache warm (gap <= %dms), gain %d <= cost %d × %d',+ this.config.cacheTtlMs,+ gainEstimate,+ rewriteCostEstimate,+ this.config.warmSafetyMargin,+ );+ const skipped = this.cloneContext(context);+ skipped.metadata.staleToolResultTrim = {+ byRule: {},+ cacheWarm,+ gapMs,+ gainEstimate,+ potentialSavedChars,+ rewriteCostEstimate,+ savedChars: 0,+ skippedReason: 'warm-cache',+ trimmedMessages: 0,+ };+ return this.markAsExecuted(skipped);+ }+ }++ // Pass 3 — apply+ const clonedContext = this.cloneContext(context);+ let savedChars = 0;+ const byRule: Record<string, number> = {};+ const candidateByIndex = new Map(candidates.map((c) => [c.index, c]));++ clonedContext.messages = clonedContext.messages.map((message, index) => {+ const candidate = candidateByIndex.get(index);+ if (!candidate) return message;++ savedChars += (message.content as string).length - candidate.content.length;+ byRule[candidate.rule] = (byRule[candidate.rule] ?? 0) + 1;+ // A trimmed image read must not keep its attachments: MessageContentProcessor+ // (later in the pipeline) would still turn pluginState.images into+ // model-visible image_url parts, billing the stale image while the text+ // claims the result was trimmed.+ const pluginState = (message.pluginState as { images?: unknown } | undefined)?.images+ ? { ...(message.pluginState as Record<string, unknown>), images: undefined }+ : message.pluginState;+ return { ...message, content: candidate.content, pluginState };+ });++ const trimmedMessages = candidates.length;++ if (trimmedMessages > 0) {+ log('Trimmed %d stale tool result(s), saved %d chars', trimmedMessages, savedChars);+ }++ clonedContext.metadata.staleToolResultTrim = {+ byRule,+ cacheWarm,+ gapMs,+ savedChars,+ trimmedMessages,+ };+ return this.markAsExecuted(clonedContext);+ }++ /** Returns the replacement, or undefined when the message must stay untouched. */+ private trimMessage(+ message: Message,+ index: number,+ lastWriteIndexByPath: Map<string, number>,+ readWindowsByPath: Map<string, { end: number; index: number; start: number }[]>,+ ): { content: string; rule: string } | undefined {+ const plugin = getPlugin(message);+ const identifier = plugin?.identifier;+ const apiName = plugin?.apiName ?? '';+ const content = message.content as string;++ if (identifier === LOCAL_SYSTEM && READ_APIS.has(apiName)) {+ const path = pathOf(message, plugin);+ if (!path) return undefined;++ const writeIndex = lastWriteIndexByPath.get(path);+ if (writeIndex !== undefined && writeIndex > index) {+ return {+ content: `[readFile result trimmed: ${path} — superseded by a later write to this file. Call readFile again if you need the current content.]`,+ rule: 'readSupersededByWrite',+ };+ }++ const loc = effectiveReadWindow(message, plugin);+ const covered = (readWindowsByPath.get(path) ?? []).some(+ (w) => w.index > index && w.start <= loc[0] && w.end >= loc[1],+ );+ if (covered) {+ return {+ content: `[readFile result trimmed: ${path} (lines ${loc[0]}-${loc[1]}) — the same range was read again later. Refer to the newer read, or call readFile again if needed.]`,+ rule: 'readSupersededByRead',+ };+ }+ return undefined;+ }++ if (identifier === BROWSER && apiName === 'snapshot') {+ // Snapshots are interaction state (element refs for clicking) — they die+ // with the next navigation and are pure dead weight afterwards.+ return {+ content: `[browser snapshot result trimmed — stale page state. Take a new snapshot if you need the current page.]`,+ rule: 'staleBrowserPage',+ };+ }++ if (identifier === BROWSER && apiName === 'readPage') {+ // readPage is different: the extracted text is source material the model+ // may quote or summarize in its final answer, not interaction state.+ // Dropping it wholesale can lose the only copy of a source in a long+ // research session — keep a head excerpt like the crawl rules do, so the+ // lead (title, URL, abstract) stays quotable, and say how to re-extract.+ if (content.length <= this.config.pageTextKeepChars) return undefined;+ return {+ content: `${content.slice(0, this.config.pageTextKeepChars)}\n[... trimmed ${content.length - this.config.pageTextKeepChars} chars of an earlier readPage result. Call readPage again on the page if you need the full text.]`,+ rule: 'stalePageText',+ };+ }++ if (identifier === WEB_BROWSING && CRAWL_APIS.has(apiName)) {+ if (content.length <= this.config.crawlKeepChars) return undefined;+ return {+ content: `${content.slice(0, this.config.crawlKeepChars)}\n[... trimmed ${content.length - this.config.crawlKeepChars} chars of stale web-browsing result. Search or crawl again if you need the full content.]`,+ rule: 'staleCrawlResult',+ };+ }++ if (+ identifier === LOCAL_SYSTEM &&+ COMMAND_APIS.has(apiName) &&+ content.length > this.config.commandKeepChars * 2+ ) {+ const head = content.slice(0, this.config.commandKeepChars);+ const tail = content.slice(-this.config.commandKeepChars);+ return {+ content: `${head}\n[... trimmed ${content.length - this.config.commandKeepChars * 2} chars of old command output ...]\n${tail}`,+ rule: 'oldCommandOutput',+ };+ }++ return undefined;+ }+}diff --git a/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts b/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.tsnew file mode 100644index 00000000000..6bea2bc00ce--- /dev/null+++ b/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts@@ -0,0 +1,644 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { cacheEconomicsForProvider, StaleToolResultTrimProcessor } from '../StaleToolResultTrim';++const createContext = (messages: any[]): PipelineContext => ({+ initialState: { messages: [] },+ isAborted: false,+ messages,+ metadata: {},+});++const toolMessage = (+ identifier: string,+ apiName: string,+ content: string,+ overrides?: Record<string, unknown>,+) => ({+ content,+ id: `tool-${apiName}-${Math.random()}`,+ plugin: { apiName, identifier },+ role: 'tool',+ tool_call_id: `call-${apiName}`,+ ...overrides,+});++const readFileResult = (path: string, content: string, loc?: [number, number]) =>+ toolMessage('lobe-local-system', 'readFile', content, {+ plugin: {+ apiName: 'readFile',+ // Canonical wire shape: arguments arrive as the serialized JSON string+ // from the model's tool call, not a parsed object.+ arguments: JSON.stringify({ loc, path }),+ identifier: 'lobe-local-system',+ },+ pluginState: { loc, path },+ });++const writeFileResult = (path: string) =>+ toolMessage('lobe-local-system', 'writeFile', `Successfully wrote to ${path}`, {+ plugin: {+ apiName: 'writeFile',+ arguments: JSON.stringify({ path }),+ identifier: 'lobe-local-system',+ },+ pluginState: { path, success: true },+ });++// Tail padding that keeps the trim window away from the messages under test.+const recencyPadding = (n: number) =>+ Array.from({ length: n }, (_, i) => ({+ content: `recent ${i}`,+ id: `pad-${i}`,+ role: 'assistant',+ tool_call_id: undefined,+ }));++const createProcessor = () =>+ new StaleToolResultTrimProcessor({ keepRecentMessages: 3, minTotalToolChars: 0 });++describe('StaleToolResultTrimProcessor', () => {+ it('trims a readFile result superseded by a later write to the same path', async () => {+ const messages = [+ readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),+ writeFileResult('/a.ts'),+ ...recencyPadding(3),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[0].content).toBe(+ '[readFile result trimmed: /a.ts — superseded by a later write to this file. Call readFile again if you need the current content.]',+ );+ expect(result.messages[0].tool_call_id).toBe(messages[0].tool_call_id);+ expect(result.messages[1].content).toBe(messages[1].content);+ expect(result.metadata.staleToolResultTrim).toMatchObject({+ byRule: { readSupersededByWrite: 1 },+ cacheWarm: false,+ savedChars: 5000 - (result.messages[0].content as string).length,+ trimmedMessages: 1,+ });+ });++ it('trims a readFile result whose range was fully re-read later', async () => {+ const messages = [+ readFileResult('/a.ts', 'y'.repeat(3000), [0, 100]),+ readFileResult('/a.ts', 'z'.repeat(6000), [0, 200]),+ ...recencyPadding(3),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[0].content).toContain('the same range was read again later');+ expect(result.messages[1].content).toBe('z'.repeat(6000));+ });++ it('keeps complementary reads of the same file (partial overlap is not coverage)', async () => {+ const messages = [+ readFileResult('/a.ts', 'first chunk', [0, 200]),+ readFileResult('/a.ts', 'second chunk', [200, 400]),+ ...recencyPadding(3),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[0].content).toBe('first chunk');+ expect(result.messages[1].content).toBe('second chunk');+ expect(result.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);+ });++ it('trims stale browser snapshots outside the recency window', async () => {+ const messages = [+ toolMessage('lobe-browser', 'snapshot', '- button "写作" [ref=e1]\n'.repeat(100)),+ toolMessage('lobe-browser', 'snapshot', '- button "大纲" [ref=e2]\n'.repeat(100)),+ ...recencyPadding(3),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[0].content).toContain('stale page state');+ expect(result.messages[1].content).toContain('stale page state');+ expect(result.metadata.staleToolResultTrim?.byRule).toEqual({ staleBrowserPage: 2 });+ });++ // Codex P1: readPage text is source material for the final answer, not+ // interaction state — keep a head excerpt like the crawl rules instead of+ // dropping it wholesale.+ it('keeps a head excerpt of old readPage text instead of dropping it', async () => {+ const pageText = `Page: Example (https://example.com)\n${'article body '.repeat(500)}`;+ const messages = [toolMessage('lobe-browser', 'readPage', pageText), ...recencyPadding(3)];++ const result = await createProcessor().process(createContext(messages));++ const content = result.messages[0].content as string;+ // the lead (title, URL, start of the article) stays quotable+ expect(content.startsWith('Page: Example (https://example.com)')).toBe(true);+ expect(content).toContain('trimmed');+ expect(content).toContain('readPage again');+ expect(content.length).toBeLessThan(pageText.length);+ expect(result.metadata.staleToolResultTrim?.byRule).toEqual({ stalePageText: 1 });+ });++ it('leaves short readPage results intact', async () => {+ const messages = [+ toolMessage('lobe-browser', 'readPage', 'short page text'),+ ...recencyPadding(3),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[0].content).toBe('short page text');+ });++ it('keeps the head and tail of old command output', async () => {+ const longOutput = `HEAD-${'a'.repeat(2000)}-TAIL`;+ const messages = [+ toolMessage('lobe-local-system', 'runCommand', longOutput),+ ...recencyPadding(3),+ ];++ const result = await new StaleToolResultTrimProcessor({+ commandKeepChars: 100,+ keepRecentMessages: 3,+ minTotalToolChars: 0,+ }).process(createContext(messages));++ const content = result.messages[0].content as string;+ expect(content).toContain('HEAD-');+ expect(content).toContain('-TAIL');+ expect(content).toContain('trimmed');+ expect(content.length).toBeLessThan(longOutput.length);+ });++ it('trims old web-browsing results to a head excerpt', async () => {+ const longPage = `<crawlResults>${'p'.repeat(5000)}</crawlResults>`;+ const messages = [+ toolMessage('lobe-web-browsing', 'crawlSinglePage', longPage),+ ...recencyPadding(3),+ ];++ const result = await new StaleToolResultTrimProcessor({+ crawlKeepChars: 200,+ keepRecentMessages: 3,+ minTotalToolChars: 0,+ }).process(createContext(messages));++ const content = result.messages[0].content as string;+ expect(content.startsWith('<crawlResults>')).toBe(true);+ expect(content).toContain('trimmed');+ expect(content.length).toBeLessThan(400);+ });++ it('never trims error results', async () => {+ const messages = [+ toolMessage('lobe-browser', 'snapshot', 'e'.repeat(5000), {+ pluginError: { message: 'Script failed to execute' },+ }),+ ...recencyPadding(3),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[0].content).toBe('e'.repeat(5000));+ });++ it('never touches the recency window', async () => {+ const messages = [+ ...recencyPadding(3),+ toolMessage('lobe-browser', 'snapshot', 'recent snapshot '.repeat(100)),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[3].content).toBe('recent snapshot '.repeat(100));+ });++ it('skips small histories entirely', async () => {+ const processor = new StaleToolResultTrimProcessor({ minTotalToolChars: 1_000_000 });+ const messages = [+ readFileResult('/a.ts', 'short', [0, 10]),+ writeFileResult('/a.ts'),+ ...recencyPadding(3),+ ];++ const result = await processor.process(createContext(messages));++ expect(result.messages[0].content).toBe('short');+ expect(result.metadata.staleToolResultTrim).toBeUndefined();+ });++ it('is idempotent — trimming an already-trimmed history is byte-stable', async () => {+ const processor = createProcessor();+ const messages = [+ readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),+ writeFileResult('/a.ts'),+ toolMessage('lobe-browser', 'snapshot', 'snap '.repeat(500)),+ ...recencyPadding(3),+ ];++ const first = await processor.process(createContext(messages));+ const second = await processor.process(createContext(first.messages));++ expect(second.messages).toEqual(first.messages);+ expect(second.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);+ });++ it('does nothing when disabled', async () => {+ const processor = new StaleToolResultTrimProcessor({ enabled: false, minTotalToolChars: 0 });+ const messages = [readFileResult('/a.ts', 'x'.repeat(5000)), writeFileResult('/a.ts')];++ const result = await processor.process(createContext(messages));++ expect(result.messages[0].content).toBe('x'.repeat(5000));+ });++ // Every LLM step of a running operation re-runs the pipeline; the trim set+ // must stay frozen for the whole turn or the prefix flips mid-operation.+ it('never trims messages from the in-flight turn, and an in-flight write does not retroactively trim', async () => {+ const processor = new StaleToolResultTrimProcessor({+ keepRecentMessages: 1,+ minTotalToolChars: 0,+ });+ const messages = [+ readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),+ writeFileResult('/a.ts'),+ { content: '继续', id: 'user-1', role: 'user' },+ readFileResult('/b.ts', 'y'.repeat(5000), [0, 200]),+ writeFileResult('/b.ts'), // in-flight write — must NOT trim the read above mid-turn+ ...recencyPadding(3),+ ];++ const result = await processor.process(createContext(messages));++ // Closed history before the boundary: trimmed+ expect(result.messages[0].content).toContain('superseded by a later write');+ // In-flight: untouched even though /b.ts was likewise overwritten+ expect(result.messages[3].content).toBe('y'.repeat(5000));+ expect(result.metadata.staleToolResultTrim?.trimmedMessages).toBe(1);+ });++ // Regression (Codex P1): the recency cutoff must be derived from the turn+ // boundary, not the growing message count — otherwise results that started+ // inside the protected tail cross the cutoff as the op appends messages.+ it('freezes the recency window at the turn boundary for the whole operation', async () => {+ const processor = new StaleToolResultTrimProcessor({+ keepRecentMessages: 3,+ minTotalToolChars: 0,+ });+ const staleSnapshot = toolMessage('lobe-browser', 'snapshot', 'snap '.repeat(500));+ const messages = [+ { content: 'older turn', id: 'm0', role: 'assistant' },+ staleSnapshot, // index 1: inside the 3-message protected tail at turn start+ { content: 'tail', id: 'm2', role: 'assistant' },+ { content: 'start working', id: 'user-1', role: 'user' },+ // 50 in-flight messages appended as the operation progresses+ ...recencyPadding(50),+ ];++ const result = await processor.process(createContext(messages));++ expect(result.messages[1].content).toBe(staleSnapshot.content);+ expect(result.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);+ });++ it('parses serialized string arguments when pluginState is absent', async () => {+ const legacyRead = toolMessage('lobe-local-system', 'readFile', 'x'.repeat(5000), {+ plugin: {+ apiName: 'readFile',+ arguments: JSON.stringify({ path: '/legacy.ts' }),+ identifier: 'lobe-local-system',+ },+ });+ const legacyWrite = toolMessage(+ 'lobe-local-system',+ 'writeFile',+ 'Successfully wrote to /legacy.ts',+ {+ plugin: {+ apiName: 'writeFile',+ arguments: JSON.stringify({ path: '/legacy.ts' }),+ identifier: 'lobe-local-system',+ },+ },+ );++ const result = await createProcessor().process(+ createContext([legacyRead, legacyWrite, ...recencyPadding(3)]),+ );++ expect(result.messages[0].content).toContain('superseded by a later write');+ });++ describe('cache-warmth gate', () => {+ const T0 = Date.parse('2026-09-20T08:00:00Z');+ const MIN = 60_000;++ // Filler between the write and the trigger keeps the write result outside+ // the recency tail (keepRecentMessages=3 in createProcessor), so the stale+ // read is a trim candidate; the last two entries fix the turn-boundary+ // timestamps the warmth gate reads.+ const turnMessages = (staleChars: number, gapMs: number) => [+ readFileResult('/a.ts', 'x'.repeat(staleChars), [0, 200]),+ writeFileResult('/a.ts'),+ { content: 'filler 1', id: 'f1', role: 'assistant' },+ { content: 'filler 2', id: 'f2', role: 'assistant' },+ { content: 'filler 3', id: 'f3', role: 'assistant' },+ {+ content: 'previous turn done',+ createdAt: new Date(T0).toISOString(),+ id: 'prev',+ role: 'assistant',+ },+ {+ content: 'next task',+ createdAt: new Date(T0 + gapMs).toISOString(),+ id: 'trigger',+ role: 'user',+ },+ ...recencyPadding(3),+ ];++ it('trims when the gap exceeds the cache TTL (cold cache — trim is free)', async () => {+ const result = await createProcessor().process(+ createContext(turnMessages(5000, 10 * MIN)), // 10 min gap > 5 min TTL+ );++ expect(result.messages[0].content).toContain('superseded by a later write');+ expect(result.metadata.staleToolResultTrim).toMatchObject({+ cacheWarm: false,+ gapMs: 10 * MIN,+ trimmedMessages: 1,+ });+ });++ it('skips the trim on a warm follow-up when savings are small relative to the payload', async () => {+ // Large live payload (untrimmed) + small stale read: the rewrite of ~500k+ // chars at write price dwarfs 20 estimated steps of 5k-char savings.+ const result = await createProcessor().process(+ createContext([+ { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },+ ...turnMessages(5000, 1 * MIN),+ ]),+ );++ expect(result.messages[1].content).toBe('x'.repeat(5000));+ expect(result.metadata.staleToolResultTrim).toMatchObject({+ cacheWarm: true,+ gapMs: 60_000,+ savedChars: 0,+ skippedReason: 'warm-cache',+ trimmedMessages: 0,+ });+ // the gate's economic inputs are recorded for observability+ expect(result.metadata.staleToolResultTrim?.potentialSavedChars).toBeGreaterThan(4000);+ expect(result.metadata.staleToolResultTrim?.gainEstimate).toBeGreaterThan(0);+ expect(result.metadata.staleToolResultTrim?.rewriteCostEstimate).toBeGreaterThan(0);+ });++ it('still trims on a warm follow-up when savings clear the warm thresholds', async () => {+ const result = await createProcessor().process(+ createContext(turnMessages(400_000, 1 * MIN)), // ~400k chars saved, >99% of payload+ );++ expect(result.messages[0].content).toContain('superseded by a later write');+ expect(result.metadata.staleToolResultTrim?.trimmedMessages).toBe(1);+ });++ // Regression (Codex P1): UIChatMessage.createdAt is epoch-ms NUMBER on the+ // canonical path; Date.parse(number) yields NaN, which would silently+ // disable the warmth gate (always "cold").+ it('reads numeric epoch-ms timestamps for the warmth check', async () => {+ const messages = [+ { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },+ readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),+ writeFileResult('/a.ts'),+ { content: 'filler', id: 'f1', role: 'assistant' },+ { content: 'filler', id: 'f2', role: 'assistant' },+ { content: 'filler', id: 'f3', role: 'assistant' },+ { content: 'previous turn done', createdAt: T0, id: 'prev', role: 'assistant' },+ { content: 'next task', createdAt: T0 + MIN, id: 'trigger', role: 'user' },+ ...recencyPadding(3),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.metadata.staleToolResultTrim).toMatchObject({+ cacheWarm: true,+ gapMs: MIN,+ skippedReason: 'warm-cache',+ });+ });+ });++ describe('closed-history pinning', () => {+ // Regression (Codex P1): the warm break-even must price the rewrite from+ // the payload frozen at the turn boundary. Counting in-flight output+ // grows the cost estimate step by step and flips a passing trim back to a+ // skip mid-operation — restoring the original prefix.+ it('does not flip the warm-gate decision as in-flight output grows', async () => {+ const T0 = Date.parse('2026-09-20T08:00:00Z');+ const buildMessages = (inFlightChars: number) => [+ readFileResult('/a.ts', 'x'.repeat(200_000), [0, 200]), // big stale read → trim candidate+ writeFileResult('/a.ts'),+ { content: 'filler', id: 'f1', role: 'assistant' },+ { content: 'filler', id: 'f2', role: 'assistant' },+ { content: 'filler', id: 'f3', role: 'assistant' },+ {+ content: 'previous turn done',+ createdAt: new Date(T0).toISOString(),+ id: 'prev',+ role: 'assistant',+ },+ {+ content: 'next task',+ createdAt: new Date(T0 + 60_000).toISOString(), // warm: 1 min gap+ id: 'trigger',+ role: 'user',+ },+ // in-flight output appended as the operation progresses+ toolMessage('lobe-local-system', 'runCommand', 'y'.repeat(inFlightChars)),+ ...recencyPadding(3),+ ];++ const processor = createProcessor();+ const atTurnStart = await processor.process(createContext(buildMessages(0)));+ const midOperation = await processor.process(createContext(buildMessages(2_000_000)));++ expect(atTurnStart.metadata.staleToolResultTrim?.trimmedMessages).toBe(1);+ expect(midOperation.metadata.staleToolResultTrim?.trimmedMessages).toBe(1);+ expect(midOperation.messages[0].content).toBe(atTurnStart.messages[0].content);+ });++ // Regression (Codex P1): the size gate must be measured on the closed+ // history only — otherwise in-flight tool output trips it mid-turn and+ // activates trims that were off at the boundary, flipping the prefix.+ it('does not let in-flight tool output trip the minimum-size gate mid-turn', async () => {+ const processor = new StaleToolResultTrimProcessor({+ keepRecentMessages: 3,+ minTotalToolChars: 10_000,+ });+ const messages = [+ readFileResult('/a.ts', 'x'.repeat(3000), [0, 200]), // closed history: 3k < 10k gate+ writeFileResult('/a.ts'),+ { content: 'start', id: 'u1', role: 'user' },+ // in-flight tool output pushes total tool chars past the gate+ toolMessage('lobe-local-system', 'runCommand', 'y'.repeat(50_000)),+ ...recencyPadding(3),+ ];++ const result = await processor.process(createContext(messages));++ expect(result.messages[0].content).toBe('x'.repeat(3000));+ expect(result.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);+ });+ });++ describe('invalidation index hygiene', () => {+ // Regression (Codex P2): a FAILED write must not supersede a good read.+ it('ignores failed writes when superseding reads', async () => {+ const messages = [+ readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),+ toolMessage('lobe-local-system', 'writeFile', 'Error: disk full', {+ plugin: {+ apiName: 'writeFile',+ arguments: JSON.stringify({ path: '/a.ts' }),+ identifier: 'lobe-local-system',+ },+ pluginError: { message: 'disk full' },+ pluginState: { path: '/a.ts', success: false },+ }),+ ...recencyPadding(3),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[0].content).toBe('x'.repeat(5000));+ });++ // Regression (Codex P2): an omitted loc means the service's [0, 200]+ // default window, not a full-file read.+ it('treats an omitted loc as the default [0, 200] window', async () => {+ const messages = [+ readFileResult('/a.ts', 'x'.repeat(500), undefined),+ readFileResult('/a.ts', 'y'.repeat(500), undefined),+ ...recencyPadding(3),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[0].content).toContain('the same range was read again later');+ });++ it('a default-window re-read does not cover an explicit later range', async () => {+ const messages = [+ readFileResult('/a.ts', 'middle chunk', [300, 400]),+ readFileResult('/a.ts', 'default window', undefined),+ ...recencyPadding(3),+ ];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[0].content).toBe('middle chunk');+ });++ // Regression (Codex P2): an image read whose result is trimmed must also+ // drop pluginState.images, or MessageContentProcessor still sends the+ // stale image as image_url parts.+ it('clears image attachments when an image read result is trimmed', async () => {+ const imageRead = toolMessage('lobe-local-system', 'readFile', '[Image: design.png]', {+ plugin: {+ apiName: 'readFile',+ arguments: JSON.stringify({ path: '/design.png' }),+ identifier: 'lobe-local-system',+ },+ pluginState: {+ images: [+ { fileId: 'f1', mediaType: 'image/png', url: 'https://files.example.com/x.png' },+ ],+ path: '/design.png',+ },+ });+ const messages = [imageRead, writeFileResult('/design.png'), ...recencyPadding(3)];++ const result = await createProcessor().process(createContext(messages));++ expect(result.messages[0].content).toContain('superseded by a later write');+ expect((result.messages[0].pluginState as any).images).toBeUndefined();+ });++ // Regression (Codex P2): a result barely over the keep threshold would+ // grow once the trim notice is appended — never admit it.+ it('rejects replacements that would grow the payload', async () => {+ const messages = [+ toolMessage('lobe-web-browsing', 'crawlSinglePage', 'p'.repeat(101)),+ ...recencyPadding(3),+ ];++ const result = await new StaleToolResultTrimProcessor({+ crawlKeepChars: 100,+ keepRecentMessages: 3,+ minTotalToolChars: 0,+ }).process(createContext(messages));++ expect(result.messages[0].content).toBe('p'.repeat(101));+ expect(result.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);+ });+ });++ describe('cacheEconomicsForProvider', () => {+ it('returns provider-specific policies and falls back to Anthropic', () => {+ expect(cacheEconomicsForProvider('anthropic')).toEqual({+ readPrice: 0.1,+ ttlMs: 300_000,+ writePrice: 1.25,+ });+ expect(cacheEconomicsForProvider('deepseek').ttlMs).toBe(3_600_000);+ expect(cacheEconomicsForProvider('openai').writePrice).toBe(1);+ expect(cacheEconomicsForProvider('some-new-provider')).toEqual(+ cacheEconomicsForProvider('anthropic'),+ );+ });++ it('prices the warmth check with the active provider policy', async () => {+ // 10-minute gap: cold under Anthropic's 5-min TTL, still warm under+ // DeepSeek's hour-long disk cache.+ const T0 = Date.parse('2026-09-20T08:00:00Z');+ const messages = [+ { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },+ readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),+ writeFileResult('/a.ts'),+ { content: 'filler', id: 'f1', role: 'assistant' },+ { content: 'filler', id: 'f2', role: 'assistant' },+ { content: 'filler', id: 'f3', role: 'assistant' },+ {+ content: 'previous turn done',+ createdAt: new Date(T0).toISOString(),+ id: 'prev',+ role: 'assistant',+ },+ {+ content: 'next task',+ createdAt: new Date(T0 + 600_000).toISOString(),+ id: 'trigger',+ role: 'user',+ },+ ...recencyPadding(3),+ ];++ const anthropic = await createProcessor().process(createContext(messages));+ expect(anthropic.metadata.staleToolResultTrim?.cacheWarm).toBe(false);+ expect(anthropic.metadata.staleToolResultTrim?.trimmedMessages).toBe(1);++ const deepseek = await new StaleToolResultTrimProcessor({+ economics: cacheEconomicsForProvider('deepseek'),+ keepRecentMessages: 3,+ minTotalToolChars: 0,+ }).process(createContext(messages));+ expect(deepseek.metadata.staleToolResultTrim).toMatchObject({+ cacheWarm: true,+ skippedReason: 'warm-cache',+ });+ });+ });+});diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.tsindex 02afaa98aad..4545f6d6c42 100644--- a/packages/context-engine/src/processors/index.ts+++ b/packages/context-engine/src/processors/index.ts@@ -26,6 +26,11 @@ export {renderPlaceholderTemplate,} from './PlaceholderVariables';export { ReactionFeedbackProcessor } from './ReactionFeedback';+export {+ cacheEconomicsForProvider,+ type StaleToolResultTrimConfig,+ StaleToolResultTrimProcessor,+} from './StaleToolResultTrim';export { SupervisorRoleRestoreProcessor } from './SupervisorRoleRestore';export { TaskCallbackMessageProcessor } from './TaskCallbackMessage';export { TaskMessageProcessor } from './TaskMessage';diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 4b547ac9f2d..c24921c0c15 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1158,6 +1158,9 @@ export default {'settingChat.enableHistoryCount.setlimited': 'Set limited history messages','settingChat.enableHistoryCount.title': 'Limit History Message Count','settingChat.enableHistoryCount.unlimited': 'Unlimited history message count',+ 'settingChat.enableStaleToolResultTrim.desc':+ 'Replace outdated tool outputs (overwritten file reads, old browser snapshots, stale command output) with short placeholders in the model context to save tokens. Disable if the assistant needs full historical tool output.',+ 'settingChat.enableStaleToolResultTrim.title': 'Trim Stale Tool Results','settingChat.enableStreaming.desc':'Enable streaming output to display responses in real-time. When disabled, only the complete response is shown.','settingChat.enableStreaming.title': 'Enable Streaming Output',diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.tsindex f632bd5ad51..dbfb449a76d 100644--- a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts@@ -74,6 +74,16 @@ describe('buildMessagesEngineParams', () => {).toEqual({ enabled: true, includeFileUrl: false });});+ it('maps the agent stale-tool-result trim flag through to the engine params', () => {+ expect(buildMessagesEngineParams(baseSnapshot()).enableStaleToolResultTrim).toBeUndefined();++ const disabled = buildMessagesEngineParams({+ ...baseSnapshot(),+ agent: { ...baseSnapshot().agent, enableStaleToolResultTrim: false },+ });+ expect(disabled.enableStaleToolResultTrim).toBe(false);+ });+it('renders placeholders from the run timezone and lets host variables win', () => {const generators = buildMessagesEngineParams({...baseSnapshot(),diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.tsindex 9bbcff6491f..f49c42057d9 100644--- a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts@@ -41,6 +41,7 @@ export const buildMessagesEngineParams = (snapshot: ContextSnapshot): MessagesEnagentDocuments: agent.documents,agentIdentity: agent.identity,enableHistoryCount: agent.enableHistoryCount,+ enableStaleToolResultTrim: agent.enableStaleToolResultTrim,historyCount: agent.historyCount,inputTemplate: agent.inputTemplate,knowledge: agent.knowledge,diff --git a/packages/mecha/src/contextEngineering/types.ts b/packages/mecha/src/contextEngineering/types.tsindex c7bd95f05ef..5dd51e28760 100644--- a/packages/mecha/src/contextEngineering/types.ts+++ b/packages/mecha/src/contextEngineering/types.ts@@ -43,6 +43,8 @@ export interface ContextAgentSnapshot {/** Agent documents the agent may consult. */documents?: AgentContextDocument[];enableHistoryCount?: boolean;+ /** Undefined / true → stale tool results are trimmed (default). */+ enableStaleToolResultTrim?: boolean;historyCount?: number;/** Identity shown to the model so it introduces itself by the user-given name. */identity?: AgentIdentityContext;diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.tsindex 30d8051cc93..ce34464003f 100644--- a/packages/types/src/agent/chatConfig.ts+++ b/packages/types/src/agent/chatConfig.ts@@ -83,6 +83,13 @@ export interface LobeAgentChatConfig extends AgentMemoryChatConfig, AgentSelfIte* Custom reasoning effort level*/enableReasoningEffort?: boolean;+ /**+ * Whether stale tool results (overwritten file reads, outdated browser+ * snapshots, old command output) are replaced with short placeholders in the+ * model context to save tokens.+ * Treat undefined as `true` — trimming is the default.+ */+ enableStaleToolResultTrim?: boolean;/*** Whether to enable streaming output*/@@ -254,6 +261,7 @@ export const AgentChatConfigSchema = zenableReasoning: z.boolean().optional(),enableReasoningEffort: z.boolean().optional(),enableStreaming: z.boolean().optional(),+ enableStaleToolResultTrim: z.boolean().optional(),gpt5ReasoningEffort: z.enum(['minimal', 'low', 'medium', 'high']).optional(),gpt5_1ReasoningEffort: z.enum(['none', 'low', 'medium', 'high']).optional(),gpt5_2ProReasoningEffort: z.enum(['medium', 'high', 'xhigh']).optional(),diff --git a/src/features/ChatInput/ActionBar/Params/Controls.tsx b/src/features/ChatInput/ActionBar/Params/Controls.tsxindex 6847cffff83..a1e04049689 100644--- a/src/features/ChatInput/ActionBar/Params/Controls.tsx+++ b/src/features/ChatInput/ActionBar/Params/Controls.tsx@@ -579,6 +579,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {'enableAutoScrollOnStreaming',]);const enableStreaming = form.getFieldValue(['chatConfig', 'enableStreaming']);+ const enableStaleToolResultTrim = form.getFieldValue(['chatConfig', 'enableStaleToolResultTrim']);const enableFollowUpChips = form.getFieldValue(['chatConfig', 'enableFollowUpChips']);const globalFollowUp = useUserStore(systemAgentSelectors.followUpAction, isEqual);const globalFollowUpReady =@@ -895,6 +896,21 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {/>)}</ControlRow>+ <ControlRow+ tag="staleToolResultTrim"+ title={t('settingChat.enableStaleToolResultTrim.title')}+ tooltip={t('settingChat.enableStaleToolResultTrim.desc')}+ action={+ <Switch+ checked={enableStaleToolResultTrim !== false}+ disabled={!canCreate}+ size={'small'}+ onChange={(checked) => {+ handleFieldChange(['chatConfig', 'enableStaleToolResultTrim'], checked);+ }}+ />+ }+ /><ControlRowtag="autoScroll"title={t('settingChat.enableAutoScrollOnStreaming.title')}diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex e7511e342c3..558a02f6baa 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -242,13 +242,16 @@ export const contextEngineering = async ({: undefined;const agentMeta = agentId ? agentSelectors.getAgentMetaById(agentId)(agentStoreState) : undefined;const agentItem = agentId ? agentByIdSelectors.getAgentById(agentId)(agentStoreState) : undefined;+ // The responding agent's chat config — the transient target's own row when+ // there is one, otherwise the current agent's.+ const respondingChatConfig =+ agentConfig?.chatConfig ?? agentChatConfigSelectors.currentChatConfig(agentStoreState);const facts = await gatherContextFacts({agent: {// The current-agent chat config carries the skill activation mode the// management rule reads, even when `agentId` is a transient target.- chatConfig:- agentConfig?.chatConfig ?? agentChatConfigSelectors.currentChatConfig(agentStoreState),+ chatConfig: respondingChatConfig,description: agentMeta?.description,slug: agentItem?.slug,title: agentMeta?.title,@@ -299,6 +302,9 @@ export const contextEngineering = async ({agent: {documents: facts.agentDocuments,enableHistoryCount,+ // Pass the raw value through (explicit false preserved); the engine+ // treats undefined as enabled.+ enableStaleToolResultTrim: respondingChatConfig.enableStaleToolResultTrim,historyCount,// The agent's identity lives on the agent row (name/title), not in the// prompt text — inject it so the model can answer "who are you?" withdiff --git a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snapindex 89e76b6a624..6955b3e27c8 100644--- a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap+++ b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap@@ -147,6 +147,7 @@ exports[`settingsSelectors > defaultAgent > should merge DEFAULT_AGENT and s.set"enableContextCompression": true,"enableFollowUpChips": false,"enableHistoryCount": false,+ "enableStaleToolResultTrim": true,"enableStreaming": true,"historyCount": 20,"reasoningBudgetToken": 1024,@@ -194,6 +195,7 @@ exports[`settingsSelectors > defaultAgentConfig > should merge DEFAULT_AGENT_CON"enableContextCompression": true,"enableFollowUpChips": false,"enableHistoryCount": false,+ "enableStaleToolResultTrim": true,"enableStreaming": true,"historyCount": 20,"reasoningBudgetToken": 1024,