🤯 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(chat): offer context compaction for oversized requests (#21504)
YuTengjing8410ffb68742
diff --git a/locales/en-US/error.json b/locales/en-US/error.jsonindex 1cf7e365edb..ce45042493a 100644--- a/locales/en-US/error.json+++ b/locales/en-US/error.json@@ -34,6 +34,8 @@"otherScope.title": "This is in another space","pluginSettings.desc": "Complete the following configuration to start using this skill","pluginSettings.title": "{{name}} Skill Settings",+ "requestBodyTooLarge.desc": "This request is too large for the model provider, often because the conversation contains many large images or files. Compact the context to summarize the history into text and try again. If the large files are in the message you just sent, edit it to remove some of them first.",+ "requestBodyTooLarge.title": "Request Too Large","response.400": "Sorry, the server does not understand your request. Please make sure your request parameters are correct.","response.401": "Sorry, the server has rejected your request, possibly due to insufficient permissions or invalid authentication.","response.403": "Sorry, the server has rejected your request. You do not have permission to access this content.",diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.jsonindex 1569e2ba95a..b85cc09137a 100644--- a/locales/zh-CN/error.json+++ b/locales/zh-CN/error.json@@ -34,6 +34,8 @@"otherScope.title": "该内容在另一个空间","pluginSettings.desc": "请完成以下配置,即可启用该技能","pluginSettings.title": "{{name}} 技能配置",+ "requestBodyTooLarge.desc": "这次请求超过了模型提供商允许的大小,通常是对话里的大图或文件太多。压缩上下文会把历史总结成文字,然后重新发送。如果大文件就在刚发的消息里,请先编辑消息删掉一部分。",+ "requestBodyTooLarge.title": "请求内容过大","response.400": "请求参数有误,请检查后重试","response.401": "未通过身份验证或权限不足,请登录或更新凭证后重试","response.403": "你没有访问权限",diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.tsindex 785890cbd10..ce42d5c0965 100644--- a/packages/locales/src/default/error.ts+++ b/packages/locales/src/default/error.ts@@ -110,6 +110,10 @@ export default {'The conversation has exceeded the context window limit. You can compact the context to compress history and continue chatting.','exceededContext.title': 'Context Window Exceeded',+ 'requestBodyTooLarge.desc':+ 'This request is too large for the model provider, often because the conversation contains many large images or files. Compact the context to summarize the history into text and try again. If the large files are in the message you just sent, edit it to remove some of them first.',+ 'requestBodyTooLarge.title': 'Request Too Large',+'unknownError.copyTraceId': 'Trace ID Copied','unknownError.copyTraceIdTooltip': 'Click to copy','unknownError.desc': 'An unexpected error occurred. You can retry or report on',diff --git a/src/features/Conversation/Error/ExceededContextWindowError.tsx b/src/features/Conversation/Error/ExceededContextWindowError.tsxindex 9205ced8d60..c36f34d7fbd 100644--- a/src/features/Conversation/Error/ExceededContextWindowError.tsx+++ b/src/features/Conversation/Error/ExceededContextWindowError.tsx@@ -3,47 +3,78 @@ import { Minimize2 } from 'lucide-react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';-import { usePermission } from '@/hooks/usePermission';import { useChatStore } from '@/store/chat';import { useConversationStore } from '../store';import BaseErrorForm from './BaseErrorForm';import { useRetryParentMessage } from './useRetryParentMessage';+/**+ * Copy for the failure that compaction recovers from. Both an over-long history and an+ * oversized request body (e.g. many large images inlined by the provider) shrink once the+ * history is summarized into text, so they share the compact-and-retry action.+ */+const COPY = {+ exceededContext: {+ desc: 'exceededContext.desc',+ title: 'exceededContext.title',+ },+ requestBodyTooLarge: {+ desc: 'requestBodyTooLarge.desc',+ title: 'requestBodyTooLarge.title',+ },+} as const;+interface ExceededContextWindowErrorProps {+ /**+ * Whether the user may write to this conversation. Supplied by the error renderer so the+ * card shares its retry gate (workspace permission plus `use` access to the agent or group);+ * the compression route rejects anyone else.+ */+ canCompact: boolean;id: string;+ /** Parent user message of an assistant group, whose `id` is a nested content block. */+ parentId?: string;+ reason?: keyof typeof COPY;}-const ExceededContextWindowError = memo<ExceededContextWindowErrorProps>(({ id }) => {- const { t } = useTranslation('error');- const { allowed: canCreate } = usePermission('create_content');-- const context = useConversationStore((s) => s.context);- const { disabled, loading, retryParentMessage } = useRetryParentMessage(id);-- const handleCompact = useCallback(async () => {- if (!canCreate || !context.topicId) return;-- await retryParentMessage(() => useChatStore.getState().executeCompression(context, ''));- }, [canCreate, context, retryParentMessage]);-- return (- <BaseErrorForm- avatar={<Icon icon={Minimize2} size={24} />}- desc={t('exceededContext.desc')}- title={t('exceededContext.title')}- action={- <Button- disabled={!canCreate || !context.topicId || disabled}- loading={loading}- type={'primary'}- onClick={handleCompact}- >- {t('exceededContext.compact')}- </Button>- }- />- );-});+const ExceededContextWindowError = memo<ExceededContextWindowErrorProps>(+ ({ canCompact, id, parentId: groupParentId, reason = 'exceededContext' }) => {+ const { t } = useTranslation('error');++ const context = useConversationStore((s) => s.context);+ const { disabled, loading, parentId, retryParentMessage } = useRetryParentMessage(+ id,+ groupParentId,+ );++ const handleCompact = useCallback(async () => {+ if (!canCompact || !context.topicId) return;++ // Leave the failed turn out of the summary so it can be regenerated afterwards.+ await retryParentMessage(() =>+ useChatStore.getState().executeCompression(context, '', { beforeMessageId: parentId }),+ );+ }, [canCompact, context, parentId, retryParentMessage]);++ return (+ <BaseErrorForm+ avatar={<Icon icon={Minimize2} size={24} />}+ desc={t(COPY[reason].desc)}+ title={t(COPY[reason].title)}+ action={+ <Button+ disabled={!canCompact || !context.topicId || disabled}+ loading={loading}+ type={'primary'}+ onClick={handleCompact}+ >+ {t('exceededContext.compact')}+ </Button>+ }+ />+ );+ },+);export default ExceededContextWindowError;diff --git a/src/features/Conversation/Error/dedicatedErrorCards.ts b/src/features/Conversation/Error/dedicatedErrorCards.tsindex 7ad26854d29..e4e61bffa8f 100644--- a/src/features/Conversation/Error/dedicatedErrorCards.ts+++ b/src/features/Conversation/Error/dedicatedErrorCards.ts@@ -19,6 +19,7 @@ export const DEDICATED_ERROR_CARD_TYPES = [AgentRuntimeErrorType.OllamaServiceUnavailable,AgentRuntimeErrorType.OllamaBizError,AgentRuntimeErrorType.ExceededContextWindow,+ AgentRuntimeErrorType.RequestBodyTooLarge,AgentRuntimeErrorType.NoOpenAIAPIKey,] as const;diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxindex 5b026ece912..e1b35aac4a5 100644--- a/src/features/Conversation/Error/index.test.tsx+++ b/src/features/Conversation/Error/index.test.tsx@@ -35,6 +35,7 @@ const createTopicForwardModalMock = vi.hoisted(() => vi.fn());const commitWorkingDirectoryMock = vi.hoisted(() => vi.fn());// Stands in for whatever card a downstream build installs into the business slot.const businessSlot = vi.hoisted(() => ({ render: false }));+const resourceAccessMock = vi.hoisted(() => ({ canUseResource: true }));const missingTranslationKeys = vi.hoisted(() => new Set<string>());const businessErrorContentMock = vi.hoisted(() =>vi.fn(() => ({@@ -148,6 +149,10 @@ vi.mock('@/features/Conversation/MessageForward/TopicForwardModal', () => ({createTopicForwardModal: createTopicForwardModalMock,}));+vi.mock('@/features/Conversation/hooks/useConversationResourceAccess', () => ({+ useConversationResourceAccess: () => resourceAccessMock,+}));+vi.mock('@/hooks/useProviderName', () => ({useProviderName: () => 'Mock Provider',}));@@ -217,6 +222,7 @@ describe('ErrorMessageExtra', () => {detectHeterogeneousAgentCommandMock.mockResolvedValue({ available: true });missingTranslationKeys.clear();businessSlot.render = false;+ resourceAccessMock.canUseResource = true;serverConfigMock.enableBusinessFeatures = false;shareContextMock.topicShareId = '';transcriptSourceMock.value = 'chat';@@ -517,6 +523,64 @@ describe('ErrorMessageExtra', () => {expect(screen.getByText('dynamic')).toBeInTheDocument();});+ it('offers context compaction for an oversized request body', () => {+ render(+ <ErrorMessageExtra+ error={{ message: 'response.RequestBodyTooLarge' }}+ data={{+ error: { type: AgentRuntimeErrorType.RequestBodyTooLarge } as any,+ id: 'msg-request-too-large',+ }}+ />,+ );++ expect(screen.getByText('dynamic')).toBeInTheDocument();+ expect(dynamicComponentPropsMock).toHaveBeenCalledWith({+ canCompact: true,+ id: 'msg-request-too-large',+ reason: 'requestBodyTooLarge',+ });+ });++ it('withholds context compaction from members who can only view the conversation', () => {+ resourceAccessMock.canUseResource = false;++ render(+ <ErrorMessageExtra+ error={{ message: 'response.RequestBodyTooLarge' }}+ data={{+ error: { type: AgentRuntimeErrorType.RequestBodyTooLarge } as any,+ id: 'msg-request-too-large',+ }}+ />,+ );++ expect(dynamicComponentPropsMock).toHaveBeenCalledWith(+ expect.objectContaining({ canCompact: false, reason: 'requestBodyTooLarge' }),+ );+ });++ it('lets context compaction retry the group parent when the error is a nested block', () => {+ render(+ <ErrorMessageExtra+ error={{ message: 'response.RequestBodyTooLarge' }}+ retryScopeId="group-parent"+ data={{+ error: { type: AgentRuntimeErrorType.RequestBodyTooLarge } as any,+ id: 'group-child-block',+ }}+ onRegenerate={vi.fn()}+ />,+ );++ expect(dynamicComponentPropsMock).toHaveBeenCalledWith({+ canCompact: true,+ id: 'group-child-block',+ parentId: 'group-parent',+ reason: 'requestBodyTooLarge',+ });+ });+it('renders the auth guide when the refreshed error is missing type but still carries session code', () => {render(<ErrorMessageExtradiff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 94af2618c9a..817e5f1686c 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -233,6 +233,7 @@ const getErrorAlertConfig = (case AgentRuntimeErrorType.ModelNotFound:case AgentRuntimeErrorType.QuotaLimitReached:case AgentRuntimeErrorType.ExceededContextWindow:+ case AgentRuntimeErrorType.RequestBodyTooLarge:case AgentRuntimeErrorType.LocationNotSupportError: {return {type: 'secondary',@@ -588,7 +589,24 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(}case AgentRuntimeErrorType.ExceededContextWindow: {- return <ExceededContextWindowError id={data.id} />;+ return (+ <ExceededContextWindowError+ canCompact={canCreate}+ id={data.id}+ parentId={retryScopeId}+ />+ );+ }++ case AgentRuntimeErrorType.RequestBodyTooLarge: {+ return (+ <ExceededContextWindowError+ canCompact={canCreate}+ id={data.id}+ parentId={retryScopeId}+ reason={'requestBodyTooLarge'}+ />+ );}case AgentRuntimeErrorType.NoOpenAIAPIKey: {diff --git a/src/features/Conversation/Error/useRetryParentMessage.test.ts b/src/features/Conversation/Error/useRetryParentMessage.test.tsindex 570cb06d1dc..df6836f55f3 100644--- a/src/features/Conversation/Error/useRetryParentMessage.test.ts+++ b/src/features/Conversation/Error/useRetryParentMessage.test.ts@@ -68,4 +68,17 @@ describe('useRetryParentMessage', () => {expect(result.current.disabled).toBe(true);expect(storeMock.regenerateUserMessage).not.toHaveBeenCalled();});++ it('should retry the supplied parent when the id is a nested group block', async () => {+ storeMock.displayMessages = [];+ const { result } = renderHook(() => useRetryParentMessage('group-child-block', 'group-parent'));++ await act(async () => {+ await result.current.retryParentMessage();+ });++ expect(result.current.disabled).toBe(false);+ expect(result.current.parentId).toBe('group-parent');+ expect(storeMock.regenerateUserMessage).toHaveBeenCalledWith('group-parent');+ });});diff --git a/src/features/Conversation/Error/useRetryParentMessage.ts b/src/features/Conversation/Error/useRetryParentMessage.tsindex dcf219c6b12..71cd03c8b24 100644--- a/src/features/Conversation/Error/useRetryParentMessage.ts+++ b/src/features/Conversation/Error/useRetryParentMessage.ts@@ -4,13 +4,19 @@ import { useConversationStore } from '@/features/Conversation/store';type BeforeRetry = () => Promise<void> | void;-export const useRetryParentMessage = (id: string) => {+/**+ * @param id - Error message id; its parent user message is the retry target.+ * @param parentIdOverride - Retry target supplied by an assistant group, whose `id` is a nested+ * content block rather than a top-level display message.+ */+export const useRetryParentMessage = (id: string, parentIdOverride?: string) => {const [loading, setLoading] = useState(false);const regenerateUserMessage = useConversationStore((s) => s.regenerateUserMessage);- const parentId = useConversationStore(+ const ownParentId = useConversationStore((s) => s.displayMessages.find((m) => m.id === id)?.parentId,);+ const parentId = parentIdOverride ?? ownParentId;const retryParentMessage = useCallback(async (beforeRetry?: BeforeRetry) => {@@ -30,6 +36,7 @@ export const useRetryParentMessage = (id: string) => {return {disabled: !parentId,loading,+ parentId,retryParentMessage,};};diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex f06b64957f3..4cef2701e78 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -2385,14 +2385,14 @@ export class ConversationLifecycleActionImpl {executeCompression = async (context: Record<string, any>,parentOperationId: string,+ options?: { beforeMessageId?: string },): Promise<void> => {const { agentId, topicId } = context;if (!topicId) return;const contextKey = messageMapKey(context as any);const dbMessages = dbMessageSelectors.getDbMessagesByKey(contextKey)(this.#get()) || [];- const messageIds = getCompressionCandidateMessageIds(dbMessages);-+ const messageIds = getCompressionCandidateMessageIds(dbMessages, options);if (messageIds.length === 0) return;const tempId = 'tmp_compress_' + nanoid();diff --git a/src/store/chat/utils/compression.test.ts b/src/store/chat/utils/compression.test.tsindex 4f8aa9cd264..f1ff3342a5e 100644--- a/src/store/chat/utils/compression.test.ts+++ b/src/store/chat/utils/compression.test.ts@@ -25,6 +25,26 @@ describe('compression utils', () => {).toEqual(['user-1', 'tool-1']);});+ it('should keep the given message and later ones out of compression candidates', () => {+ const messages = [+ { id: 'user-1', role: 'user' },+ { id: 'assistant-1', role: 'assistant' },+ { id: 'user-2', role: 'user' },+ { id: 'assistant-2', role: 'assistant' },+ ] as any[];++ expect(getCompressionCandidateMessageIds(messages, { beforeMessageId: 'user-2' })).toEqual([+ 'user-1',+ 'assistant-1',+ ]);+ expect(getCompressionCandidateMessageIds(messages, { beforeMessageId: 'missing' })).toEqual([+ 'user-1',+ 'assistant-1',+ 'user-2',+ 'assistant-2',+ ]);+ });+it('should detect running compression operations in the same conversation context', () => {const operations: Operation[] = [{diff --git a/src/store/chat/utils/compression.ts b/src/store/chat/utils/compression.tsindex eded0739a97..0d2021b6b44 100644--- a/src/store/chat/utils/compression.ts+++ b/src/store/chat/utils/compression.ts@@ -9,11 +9,24 @@ import { type Operation } from '../slices/operation/types';export const isCompressionOperationType = (type?: string) =>type === 'contextCompression' || type === 'generateSummary';-export const getCompressionCandidateMessageIds = (messages: UIChatMessage[]) =>- messages+/**+ * @param options.beforeMessageId Keep this message and everything after it out of the+ * summary, e.g. the user turn a recovery card regenerates after compacting. Compressing it+ * would hide it from the conversation, leaving nothing to regenerate.+ */+export const getCompressionCandidateMessageIds = (+ messages: UIChatMessage[],+ options?: { beforeMessageId?: string },+) => {+ const keepFrom = options?.beforeMessageId+ ? messages.findIndex((message) => message.id === options.beforeMessageId)+ : -1;++ return (keepFrom === -1 ? messages : messages.slice(0, keepFrom)).filter((message) => message.role !== 'compressedGroup').map((message) => message.id).filter(Boolean);+};export const createPendingCompressedGroup = ({agentId,