Skip to content

🤯 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.

:bug: fix context compression threshold config (#14439)

Rylan Cai282b20c45407
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
index 6402943cf6b..651a0ccb27e 100644
--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
@@ -365,12 +365,14 @@ export class GeneralChatAgent implements Agent {
*/
private toLLMCall(payload: GeneralAgentCallLLMInstructionPayload): AgentInstruction {
const compressionEnabled = this.config.compressionConfig?.enabled ?? true;
+ const compressionOptions = {
+ maxWindowToken: this.config.compressionConfig?.maxWindowToken,
+ thresholdRatio: this.config.compressionConfig?.thresholdRatio,
+ };
if (compressionEnabled) {
const messages = payload.messages;
- const compressionCheck = shouldCompress(messages, {
- maxWindowToken: this.config.compressionConfig?.maxWindowToken,
- });
+ const compressionCheck = shouldCompress(messages, compressionOptions);
if (compressionCheck.needsCompression) {
return {
@@ -433,11 +435,13 @@ export class GeneralChatAgent implements Agent {
case 'user_input': {
// Check if context compression is enabled and needed before calling LLM
const compressionEnabled = this.config.compressionConfig?.enabled ?? true; // Default to enabled
+ const compressionOptions = {
+ maxWindowToken: this.config.compressionConfig?.maxWindowToken,
+ thresholdRatio: this.config.compressionConfig?.thresholdRatio,
+ };
if (compressionEnabled) {
- const compressionCheck = shouldCompress(state.messages, {
- maxWindowToken: this.config.compressionConfig?.maxWindowToken,
- });
+ const compressionCheck = shouldCompress(state.messages, compressionOptions);
if (compressionCheck.needsCompression) {
// Context exceeds threshold, compress ALL messages into a single summary
diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
index e1fe3d2297c..518e4c1e060 100644
--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
@@ -122,6 +122,34 @@ describe('GeneralChatAgent', () => {
},
});
});
+
+ it('should trigger compression using thresholdRatio from compressionConfig', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ compressionConfig: {
+ enabled: true,
+ maxWindowToken: 200_000,
+ thresholdRatio: 0.5,
+ },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState({
+ messages: [
+ {
+ content: '',
+ metadata: { usage: { totalOutputTokens: 100_001 } },
+ role: 'assistant',
+ },
+ ] as any,
+ });
+ const context = createMockContext('init', { model: 'gpt-4o-mini', provider: 'openai' });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual(expectCompressionInstruction(state.messages));
+ });
});
describe('llm_result phase', () => {
diff --git a/packages/agent-runtime/src/types/generalAgent.ts b/packages/agent-runtime/src/types/generalAgent.ts
index fbab265dbf4..75f11dff319 100644
--- a/packages/agent-runtime/src/types/generalAgent.ts
+++ b/packages/agent-runtime/src/types/generalAgent.ts
@@ -81,6 +81,8 @@ export interface GeneralAgentConfig {
enabled?: boolean;
/** Model's max context window token count (default: 128k) */
maxWindowToken?: number;
+ /** Threshold ratio for triggering compression (default: 0.5) */
+ thresholdRatio?: number;
};
/**
* Dynamic intervention audits registry (per-tool)
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.test.ts b/src/server/services/agentRuntime/AgentRuntimeService.test.ts
index cf2f66313bf..90bd32a7468 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.test.ts
@@ -1,6 +1,7 @@
/**
* @vitest-environment node
*/
+import { getModelPropertyWithFallback } from '@lobechat/model-runtime';
import type * as ModelBankModule from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -12,6 +13,10 @@ import {
type StartExecutionParams,
} from './types';
+vi.mock('@lobechat/model-runtime', () => ({
+ getModelPropertyWithFallback: vi.fn(),
+}));
+
// Mock trusted client to avoid server-side env access
vi.mock('@/libs/trusted-client', () => ({
generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
@@ -395,6 +400,71 @@ describe('AgentRuntimeService', () => {
mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);
});
+ it('should pass resolved contextWindowTokens into compressionConfig', async () => {
+ vi.mocked(getModelPropertyWithFallback).mockResolvedValueOnce(200_000);
+
+ let capturedConfig: any;
+ const serviceWithFactory = new AgentRuntimeService(mockDb, mockUserId, {
+ agentFactory: (config) => {
+ capturedConfig = config;
+ return { runner: vi.fn() } as any;
+ },
+ });
+
+ await (serviceWithFactory as any).createAgentRuntime({
+ metadata: {
+ agentConfig: { chatConfig: { enableContextCompression: true } },
+ modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },
+ },
+ operationId: 'test-operation-1',
+ stepIndex: 1,
+ });
+
+ expect(getModelPropertyWithFallback).toHaveBeenCalledWith(
+ 'gpt-4o-mini',
+ 'contextWindowTokens',
+ 'openai',
+ );
+ expect(capturedConfig).toEqual(
+ expect.objectContaining({
+ compressionConfig: expect.objectContaining({
+ enabled: true,
+ maxWindowToken: 200_000,
+ }),
+ }),
+ );
+ });
+
+ it('should fall back to undefined maxWindowToken when model lookup misses', async () => {
+ vi.mocked(getModelPropertyWithFallback).mockResolvedValueOnce(undefined);
+
+ let capturedConfig: any;
+ const serviceWithFactory = new AgentRuntimeService(mockDb, mockUserId, {
+ agentFactory: (config) => {
+ capturedConfig = config;
+ return { runner: vi.fn() } as any;
+ },
+ });
+
+ await (serviceWithFactory as any).createAgentRuntime({
+ metadata: {
+ agentConfig: { chatConfig: { enableContextCompression: true } },
+ modelRuntimeConfig: { model: 'unknown-model', provider: 'openai' },
+ },
+ operationId: 'test-operation-1',
+ stepIndex: 1,
+ });
+
+ expect(capturedConfig).toEqual(
+ expect.objectContaining({
+ compressionConfig: expect.objectContaining({
+ enabled: true,
+ maxWindowToken: undefined,
+ }),
+ }),
+ );
+ });
+
it('should execute step successfully', async () => {
const mockStepResult = {
newState: { ...mockState, stepCount: 2, status: 'running' },
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index c34f1293f07..ee5df77c701 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -7,6 +7,7 @@ import type {
import { AgentRuntime, findInMessages, GeneralChatAgent } from '@lobechat/agent-runtime';
import type { ISnapshotStore } from '@lobechat/agent-tracing';
import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';
+import { getModelPropertyWithFallback } from '@lobechat/model-runtime';
import { AgentRuntimeErrorType, ChatErrorType, type ChatMessageError } from '@lobechat/types';
import debug from 'debug';
import urlJoin from 'url-join';
@@ -1523,11 +1524,21 @@ export class AgentRuntimeService {
operationId: string;
stepIndex: number;
}) {
+ const contextWindowTokens =
+ metadata?.modelRuntimeConfig?.model && metadata?.modelRuntimeConfig?.provider
+ ? await getModelPropertyWithFallback<number | undefined>(
+ metadata.modelRuntimeConfig.model,
+ 'contextWindowTokens',
+ metadata.modelRuntimeConfig.provider,
+ )
+ : undefined;
+
// Create Agent instance — use custom factory if provided, otherwise default to GeneralChatAgent
const generalConfig = {
agentConfig: metadata?.agentConfig,
compressionConfig: {
enabled: metadata?.agentConfig?.chatConfig?.enableContextCompression ?? true,
+ maxWindowToken: contextWindowTokens ?? undefined,
},
dynamicInterventionAudits,
modelRuntimeConfig: metadata?.modelRuntimeConfig,
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
index 6ceb9b051fa..723d6cc549b 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
@@ -1,3 +1,4 @@
+import * as agentRuntime from '@lobechat/agent-runtime';
import { type UIChatMessage } from '@lobechat/types';
import { act, renderHook } from '@testing-library/react';
import { type EnabledAiModel, ModelProvider } from 'model-bank';
@@ -226,6 +227,110 @@ describe('StreamingExecutor actions', () => {
streamSpy.mockRestore();
});
+ it('should pass model contextWindowTokens into compressionConfig when creating the agent', async () => {
+ act(() => {
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
+ });
+
+ useAiInfraStore.setState({
+ enabledAiModels: [
+ {
+ abilities: { functionCall: true },
+ contextWindowTokens: 200_000,
+ id: 'gpt-4o-mini',
+ providerId: 'openai',
+ type: 'chat',
+ } as EnabledAiModel,
+ ],
+ });
+
+ const agentSpy = vi.spyOn(agentRuntime, 'GeneralChatAgent');
+ const { result } = renderHook(() => useChatStore());
+ const userMessage = {
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: TEST_CONTENT.USER_MESSAGE,
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+
+ const streamSpy = vi
+ .spyOn(chatService, 'createAssistantMessageStream')
+ .mockImplementation(async ({ onFinish }) => {
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
+ });
+
+ await act(async () => {
+ await result.current.executeClientAgent({
+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ parentMessageType: 'user',
+ });
+ });
+
+ expect(agentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ compressionConfig: expect.objectContaining({
+ enabled: true,
+ maxWindowToken: 200_000,
+ }),
+ }),
+ );
+
+ streamSpy.mockRestore();
+ });
+
+ it('should fall back to undefined maxWindowToken for unknown models', async () => {
+ act(() => {
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
+ });
+
+ const agentSpy = vi.spyOn(agentRuntime, 'GeneralChatAgent');
+
+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
+ agentConfig: createMockAgentConfig({ model: 'unknown-model', provider: 'openai' }),
+ chatConfig: createMockChatConfig(),
+ isBuiltinAgent: false,
+ plugins: [],
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const userMessage = {
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: TEST_CONTENT.USER_MESSAGE,
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+
+ const streamSpy = vi
+ .spyOn(chatService, 'createAssistantMessageStream')
+ .mockImplementation(async ({ onFinish }) => {
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
+ });
+
+ await act(async () => {
+ await result.current.executeClientAgent({
+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ parentMessageType: 'user',
+ });
+ });
+
+ expect(agentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ compressionConfig: expect.objectContaining({
+ enabled: true,
+ maxWindowToken: undefined,
+ }),
+ }),
+ );
+
+ streamSpy.mockRestore();
+ });
+
it('should resolve aborted tools when cancelled after LLM returns tool calls', async () => {
act(() => {
useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 31982d412e5..2963366718b 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -29,6 +29,8 @@ import { localFileService } from '@/services/electron/localFileService';
import { messageService } from '@/services/message';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
+import { aiModelSelectors } from '@/store/aiInfra/selectors';
+import { getAiInfraStoreState } from '@/store/aiInfra/store';
import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actions/agentSignalBridge';
import { type ChatStore, useChatStore } from '@/store/chat/store';
@@ -534,10 +536,16 @@ export class StreamingExecutorActionImpl {
// ===========================================
log('[executeClientAgent] Creating agent runtime with config', modelRuntimeConfig);
+ const contextWindowTokens = aiModelSelectors.modelContextWindowTokens(
+ model,
+ provider!,
+ )(getAiInfraStoreState());
+
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 1000 },
compressionConfig: {
enabled: agentConfigData.chatConfig?.enableContextCompression ?? true, // Default to enabled
+ maxWindowToken: contextWindowTokens ?? undefined,
},
dynamicInterventionAudits,
operationId: `${messageKey}/${params.parentMessageId}`,