🤯 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): keep history when the compaction summary fails (#21590)
YuTengjing2d7ca948aae9
diff --git a/.agents/skills/source-layout/SKILL.md b/.agents/skills/source-layout/SKILL.mdindex bfabd72e395..8653d5824be 100644--- a/.agents/skills/source-layout/SKILL.md+++ b/.agents/skills/source-layout/SKILL.md@@ -39,7 +39,7 @@ One rule for every app and package:Source and test files stay at or below 1200 lines. Generated code (`*.gen.ts`, `generated/` directories) and the `locales/default/` tables are exempt:- A new file over 1200 lines, or an existing file that crosses 1200 lines in this change, is split in the same change. `bun run check`, the pre-commit hook, and the PR's File Size Gate job fail on both.-- A file already over 1200 lines must not grow, including for a bug fix: the change may only keep or reduce its line count. Before adding code, extract the cohesive part the change touches. Put a new test in a scenario test file under the limit (§2), splitting the old test file first when the test belongs to one of its scenarios. Because hundreds of legacy files are over the limit, these checks report their growth as an advisory (a warning annotation in CI) instead of failing; it is still a required fix.+- A file already over 1200 lines must not grow, including for a bug fix: the change may only keep or reduce its line count. Before adding code, extract the cohesive part the change touches into a sibling inside the file's own directory (`Foo.ts` becomes `Foo/index.ts`, §4), not into a neighboring file or another slice. Put a new test in a scenario test file under the limit (§2), splitting the old test file first when the test belongs to one of its scenarios. Because hundreds of legacy files are over the limit, these checks report their growth as an advisory (a warning annotation in CI) instead of failing; it is still a required fix.The limit says when to split, not where. Split on a real boundary (state, reuse, render update, sub-domain, pipeline stage), as `react` requires; never cut a file at an arbitrary line count. When a heavy feature is mounted by several hosts, use `compose-atoms` instead.@@ -47,12 +47,12 @@ The limit says when to split, not where. Split on a real boundary (state, reuse,A split keeps the public import path: `Foo.tsx` becomes `Foo/index.tsx`, so `import Foo from './Foo'` keeps working and callers do not change. Commit the move (`mkdir -p Foo && git mv Foo.tsx Foo/index.tsx`) alone before extracting, so reviewers can read the extraction diff separately and Git keeps the rename while those commits stay intact (a squash merge folds them together). `split-large-file` has the full procedure.-| Kind | `index` keeps | Siblings | Precedent |-| --------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- |-| React component | Public API, shared top-level state, composition | Child components (PascalCase), `useXxx.ts` for state transitions and side effects, pure logic modules with their own tests | `Conversation/Messages/GoalTaskCard/` |-| Server service | The class and its orchestration methods | Stage functions taking an explicit `deps` object (`pipeline/<stage>.ts`), sub-domain folders | `services/aiAgent/`, `services/comfyui/` |-| tRPC router | The merged router | One sub-router per sub-domain (`market/agent.ts` exports `agentRouter`) | `routers/lambda/market/` |-| Zustand store | — | Follow `zustand` | `src/store/page` |+| Kind | `index` keeps | Siblings | Precedent |+| --------------- | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |+| React component | Public API, shared top-level state, composition | Child components (PascalCase), `useXxx.ts` for state transitions and side effects, pure logic modules with their own tests | `Conversation/Messages/GoalTaskCard/` |+| Server service | The class and its orchestration methods | Stage functions taking an explicit `deps` object (`pipeline/<stage>.ts`), sub-domain folders | `services/aiAgent/`, `services/comfyui/` |+| tRPC router | The merged router | One sub-router per sub-domain (`market/agent.ts` exports `agentRouter`) | `routers/lambda/market/` |+| Zustand store | The action class and its public method signatures | Logic modules exporting a function that takes one params object plus `get`; the class method delegates to it | `agentRun/actions/entries/conversationLifecycle/` |- Prefer flat siblings. Add a sub-folder for a sub-area with several files of its own (`ChatInput/ControlBar/`).- Kind folders (`components/`, `hooks/`, `utils/`) follow who uses the code:diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 4708bd843b2..4f81405d8f3 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -220,6 +220,9 @@"compression.cancelConfirm": "Are you sure you want to uncompress? This will restore the original messages.","compression.collapsed": "Compressed {{turns}} earlier turns · View summary","compression.collapsedUnknown": "Compressed earlier history · View summary",+ "compression.emptySummary": "The model returned an empty summary",+ "compression.failed": "Context compression failed, original messages kept",+ "compression.failedReason": "Summary generation failed: {{reason}}","compression.history": "Original conversation","compression.summary": "History summary","confirmClearCurrentMessages": "You are about to clear the current conversation messages. Once cleared, they cannot be retrieved. Please confirm your action.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 4e2494c27cb..61a28064bd9 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -220,6 +220,9 @@"compression.cancelConfirm": "确定要取消压缩吗?这将恢复原始消息。","compression.collapsed": "已压缩前 {{turns}} 轮对话 · 查看摘要","compression.collapsedUnknown": "已压缩历史对话 · 查看摘要",+ "compression.emptySummary": "模型没有返回摘要内容",+ "compression.failed": "压缩上下文失败,原始消息已保留",+ "compression.failedReason": "生成摘要失败:{{reason}}","compression.history": "原始对话","compression.summary": "历史记录摘要","confirmClearCurrentMessages": "确认清空当前会话消息吗?清空后无法恢复",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex f5bae73f199..84903ce34fc 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -342,6 +342,9 @@ export default {'Are you sure you want to uncompress? This will restore the original messages.','compression.collapsed': 'Compressed {{turns}} earlier turns · View summary','compression.collapsedUnknown': 'Compressed earlier history · View summary',+ 'compression.emptySummary': 'The model returned an empty summary',+ 'compression.failed': 'Context compression failed, original messages kept',+ 'compression.failedReason': 'Summary generation failed: {{reason}}','compression.history': 'Original conversation','compression.summary': 'History summary','confirmClearCurrentMessages':diff --git a/src/features/Conversation/Error/ExceededContextWindowError.tsx b/src/features/Conversation/Error/ExceededContextWindowError.tsxindex c36f34d7fbd..4242a9e6e70 100644--- a/src/features/Conversation/Error/ExceededContextWindowError.tsx+++ b/src/features/Conversation/Error/ExceededContextWindowError.tsx@@ -51,10 +51,20 @@ const ExceededContextWindowError = memo<ExceededContextWindowErrorProps>(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 }),- );+ // Leave the failed turn out of the summary so it can be regenerated afterwards. A failed+ // compaction keeps the original history, so retrying would hit the same error again.+ // The failure toast's Retry reruns this whole flow, not only the compaction: once a bare+ // compaction succeeds, compacting again from this card finds nothing to summarize and+ // would skip the regeneration.+ const compactAndRetry = (): Promise<void> =>+ retryParentMessage(() =>+ useChatStore.getState().executeCompression(context, '', {+ beforeMessageId: parentId,+ onRetry: () => void compactAndRetry(),+ }),+ );++ await compactAndRetry();}, [canCompact, context, parentId, retryParentMessage]);return (diff --git a/src/features/Conversation/Error/useRetryParentMessage.test.ts b/src/features/Conversation/Error/useRetryParentMessage.test.tsindex df6836f55f3..d51768bab34 100644--- a/src/features/Conversation/Error/useRetryParentMessage.test.ts+++ b/src/features/Conversation/Error/useRetryParentMessage.test.ts@@ -57,6 +57,17 @@ describe('useRetryParentMessage', () => {expect(calls).toEqual(['before', 'regenerate']);});+ it('should skip regenerating when the pre-retry action reports failure', async () => {+ const { result } = renderHook(() => useRetryParentMessage('assistant-message'));++ await act(async () => {+ await result.current.retryParentMessage(async () => false);+ });++ expect(storeMock.regenerateUserMessage).not.toHaveBeenCalled();+ expect(result.current.loading).toBe(false);+ });+it('should skip retry when the message has no parent', async () => {storeMock.displayMessages = [{ id: 'assistant-message' }];const { result } = renderHook(() => useRetryParentMessage('assistant-message'));diff --git a/src/features/Conversation/Error/useRetryParentMessage.ts b/src/features/Conversation/Error/useRetryParentMessage.tsindex 71cd03c8b24..a1c4d352479 100644--- a/src/features/Conversation/Error/useRetryParentMessage.ts+++ b/src/features/Conversation/Error/useRetryParentMessage.ts@@ -2,7 +2,8 @@ import { useCallback, useState } from 'react';import { useConversationStore } from '@/features/Conversation/store';-type BeforeRetry = () => Promise<void> | void;+/** Runs before the retry; resolving to `false` skips the retry. */+type BeforeRetry = () => Promise<boolean | void> | boolean | void;/*** @param id - Error message id; its parent user message is the retry target.@@ -24,7 +25,7 @@ export const useRetryParentMessage = (id: string, parentIdOverride?: string) =>setLoading(true);try {- await beforeRetry?.();+ if ((await beforeRetry?.()) === false) return;await regenerateUserMessage(parentId);} finally {setLoading(false);diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/compression.test.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/compression.test.tsnew file mode 100644index 00000000000..17a05aa2bf3--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/compression.test.ts@@ -0,0 +1,179 @@+import { toast } from '@lobehub/ui';+import { act } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { chatService } from '@/services/chat';+import { messageService } from '@/services/message';+import { agentSelectors } from '@/store/agent/selectors';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import { useChatStore } from '../../../../../store';++vi.mock('@/services/resourcePermission', () => ({+ resourcePermissionService: { getGeneralAccess: vi.fn() },+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },+ },+}));++const agentId = 'agent-1';+const topicId = 'topic-1';+const context = { agentId, threadId: null, topicId };+const key = messageMapKey({ agentId, topicId });+const originalMessages = [+ { content: 'question', id: 'user-1', role: 'user', topicId },+ { content: 'answer', id: 'assistant-1', role: 'assistant', topicId },+] as any[];++const closeToast = vi.fn();++const getMessageIds = () => (useChatStore.getState().dbMessagesMap[key] ?? []).map((m) => m.id);++beforeEach(() => {+ vi.spyOn(agentSelectors, 'getAgentConfigById').mockImplementation(+ () => () => ({ model: 'gpt-4o-mini', provider: 'openai' }) as any,+ );++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [key]: originalMessages },+ messagesMap: { [key]: originalMessages },+ });+ });++ vi.spyOn(messageService, 'createCompressionGroup').mockResolvedValue({+ messageGroupId: 'group-1',+ messages: [{ content: '', id: 'group-1', role: 'compressedGroup' } as any],+ messagesToSummarize: originalMessages,+ });+ vi.spyOn(messageService, 'cancelCompression').mockResolvedValue({+ messages: originalMessages,+ });+ vi.spyOn(toast, 'error').mockImplementation(() => ({ close: closeToast }) as any);+});++afterEach(() => {+ vi.restoreAllMocks();+ closeToast.mockReset();+});++describe('executeCompression', () => {+ it('keeps the original messages when the summary request fails', async () => {+ const finalizeSpy = vi.spyOn(messageService, 'finalizeCompression');+ vi.spyOn(chatService, 'fetchPresetTaskResult').mockImplementation(async ({ onError }) => {+ onError?.(new Error('Request blocked by chat security'), undefined);+ });++ let succeeded: boolean | undefined;+ await act(async () => {+ succeeded = await useChatStore.getState().executeCompression(context, '');+ });++ expect(succeeded).toBe(false);+ expect(finalizeSpy).not.toHaveBeenCalled();+ expect(messageService.cancelCompression).toHaveBeenCalledWith({+ agentId,+ groupId: undefined,+ messageGroupId: 'group-1',+ threadId: null,+ topicId,+ });+ expect(getMessageIds()).toEqual(['user-1', 'assistant-1']);+ expect(toast.error).toHaveBeenCalledWith(+ expect.objectContaining({+ description: expect.stringContaining('Request blocked by chat security'),+ duration: 0,+ }),+ );+ });++ it('reruns the compaction from the failure toast', async () => {+ const fetchSpy = vi+ .spyOn(chatService, 'fetchPresetTaskResult')+ .mockImplementation(async ({ onError }) => {+ onError?.(new Error('timeout'), undefined);+ });++ await act(async () => {+ await useChatStore.getState().executeCompression(context, '');+ });++ const [{ actions }] = vi.mocked(toast.error).mock.calls[0] as [any];+ await act(async () => {+ actions[0].onClick();+ });++ await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalledTimes(2));+ expect(messageService.createCompressionGroup).toHaveBeenCalledTimes(2);+ expect(closeToast).toHaveBeenCalledTimes(1);+ });++ it('runs the caller retry flow from the failure toast when provided', async () => {+ const onRetry = vi.fn();+ vi.spyOn(chatService, 'fetchPresetTaskResult').mockImplementation(async ({ onError }) => {+ onError?.(new Error('timeout'), undefined);+ });++ await act(async () => {+ await useChatStore.getState().executeCompression(context, '', { onRetry });+ });++ const [{ actions }] = vi.mocked(toast.error).mock.calls[0] as [any];+ actions[0].onClick();++ expect(onRetry).toHaveBeenCalledTimes(1);+ expect(closeToast).toHaveBeenCalledTimes(1);+ expect(messageService.createCompressionGroup).toHaveBeenCalledTimes(1);+ });++ it('does not finalize an empty summary', async () => {+ const finalizeSpy = vi.spyOn(messageService, 'finalizeCompression');+ vi.spyOn(chatService, 'fetchPresetTaskResult').mockImplementation(+ async ({ onMessageHandle }) => {+ onMessageHandle?.({ text: ' ', type: 'text' });+ },+ );++ let succeeded: boolean | undefined;+ await act(async () => {+ succeeded = await useChatStore.getState().executeCompression(context, '');+ });++ expect(succeeded).toBe(false);+ expect(finalizeSpy).not.toHaveBeenCalled();+ expect(messageService.cancelCompression).toHaveBeenCalledTimes(1);+ expect(getMessageIds()).toEqual(['user-1', 'assistant-1']);+ });++ it('finalizes the group with the generated summary', async () => {+ const finalized = [{ content: 'summary', id: 'group-1', role: 'compressedGroup' } as any];+ const finalizeSpy = vi+ .spyOn(messageService, 'finalizeCompression')+ .mockResolvedValue({ messages: finalized });+ vi.spyOn(chatService, 'fetchPresetTaskResult').mockImplementation(+ async ({ onMessageHandle }) => {+ onMessageHandle?.({ text: 'summary', type: 'text' });+ },+ );++ let succeeded: boolean | undefined;+ await act(async () => {+ succeeded = await useChatStore.getState().executeCompression(context, '');+ });++ expect(succeeded).toBe(true);+ expect(finalizeSpy).toHaveBeenCalledWith({+ agentId,+ content: 'summary',+ messageGroupId: 'group-1',+ topicId,+ });+ expect(messageService.cancelCompression).not.toHaveBeenCalled();+ expect(getMessageIds()).toEqual(['group-1']);+ });+});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/compression.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/compression.tsnew file mode 100644index 00000000000..296eeeb7905--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/compression.ts@@ -0,0 +1,196 @@+import { chainCompressContext } from '@lobechat/prompts';+import { RequestTrigger } from '@lobechat/types';+import { nanoid } from '@lobechat/utils';+import { toast } from '@lobehub/ui';+import { t } from 'i18next';++import { chatService } from '@/services/chat';+import { messageService } from '@/services/message';+import { getAgentStoreState } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { dbMessageSelectors } from '@/store/chat/selectors';+import { type ChatStore } from '@/store/chat/store';+import {+ createPendingCompressedGroup,+ getCompressionCandidateMessageIds,+} from '@/store/chat/utils/compression';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++const isAbortError = (error: unknown, abortController?: AbortController) =>+ !!abortController?.signal.aborted ||+ (error instanceof Error &&+ (error.name === 'AbortError' ||+ error.message.includes('aborted') ||+ error.message.includes('cancelled')));++export interface ContextCompressionOptions {+ /** Keep this message and everything after it out of the summary. */+ beforeMessageId?: string;+ /**+ * Retry action offered in the failure toast. Defaults to running the same compaction again;+ * callers that chain work after compaction (e.g. compact-and-retry) pass their full flow.+ */+ onRetry?: () => void;+}++const createAbortError = () =>+ Object.assign(new Error('Compression cancelled'), { name: 'AbortError' });++export interface ContextCompressionParams extends ContextCompressionOptions {+ context: Record<string, any>;+ parentOperationId: string;+}++/**+ * Compress the conversation history into a summary group (`/compact` and the compact-and-retry+ * error card). Reuses the same service methods as the agent runtime's compress_context executor.+ *+ * @returns Whether the history was replaced by a summary. A failed or empty summary rolls the+ * compression group back so the original messages stay intact.+ */+export const executeContextCompression = async (+ params: ContextCompressionParams,+ get: () => ChatStore,+): Promise<boolean> => {+ const { context, parentOperationId, ...options } = params;+ const { agentId, topicId } = context;+ if (!topicId) return false;++ const contextKey = messageMapKey(context as any);+ const dbMessages = dbMessageSelectors.getDbMessagesByKey(contextKey)(get()) || [];+ const messageIds = getCompressionCandidateMessageIds(dbMessages, options);+ if (messageIds.length === 0) return false;++ const tempId = 'tmp_compress_' + nanoid();+ const { abortController, operationId } = get().startOperation({+ context: { ...context, messageId: tempId },+ parentOperationId,+ type: 'contextCompression',+ });++ // Immediate UI feedback: render a pending compressed group from the first frame+ get().internal_createClientMessage(+ tempId,+ createPendingCompressedGroup({+ agentId,+ groupId: context.groupId,+ id: tempId,+ threadId: context.threadId,+ topicId,+ }) as any,+ { operationId },+ );++ let messageGroupId: string | undefined;++ try {+ // 1. Create compression group on server+ const result = await messageService.createCompressionGroup({+ agentId,+ messageIds,+ topicId,+ });+ const { messages: serverMessages, messagesToSummarize } = result;+ messageGroupId = result.messageGroupId;+ const groupId = messageGroupId;++ // Replace local pending group with server compression group+ get().replaceMessages(serverMessages, { context: context as any });+ get().associateMessageWithOperation(messageGroupId, operationId);++ // 2. Generate summary via LLM+ const { model, provider } = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());+ const compressionPayload = chainCompressContext(messagesToSummarize);+ let summaryContent = '';+ let summaryError: Error | undefined;++ // fetchPresetTaskResult reports request failures (e.g. a chat-security 403 or a provider+ // timeout) through onError instead of rejecting, so capture them explicitly.+ await chatService.fetchPresetTaskResult({+ abortController,+ onError: (error) => {+ summaryError = error;+ },+ onMessageHandle: (chunk) => {+ if (chunk.type === 'text') {+ summaryContent += chunk.text || '';+ get().internal_dispatchMessage(+ { id: groupId, type: 'updateMessage', value: { content: summaryContent } },+ { operationId },+ );+ }+ },+ params: { ...compressionPayload, model, provider },+ trigger: RequestTrigger.ContextCompression,+ });++ if (abortController.signal.aborted) throw createAbortError();+ if (summaryError) throw summaryError;+ // Finalizing an empty summary would fold the history into a blank group and lose it.+ if (!summaryContent.trim()) throw new Error(t('compression.emptySummary', { ns: 'chat' }));++ // 3. Finalize compression+ const finalResult = await messageService.finalizeCompression({+ agentId,+ content: summaryContent,+ messageGroupId: groupId,+ topicId,+ });++ if (finalResult.messages) {+ get().replaceMessages(finalResult.messages, { context: context as any });+ }++ get().completeOperation(operationId);+ return true;+ } catch (error) {+ if (isAbortError(error, abortController)) {+ get().internal_dispatchMessage({ type: 'deleteMessages', ids: [tempId] }, { operationId });+ return false;+ }++ console.error('[/compact] Compression failed:', error);+ get().internal_dispatchMessage({ type: 'deleteMessages', ids: [tempId] }, { operationId });++ // Roll the server group back so the original messages are restored instead of being+ // hidden behind an unfinished summary.+ if (messageGroupId) {+ try {+ const rollback = await messageService.cancelCompression({+ agentId,+ groupId: context.groupId,+ messageGroupId,+ threadId: context.threadId,+ topicId,+ });+ get().replaceMessages(rollback.messages, { context: context as any });+ } catch (rollbackError) {+ console.error('[/compact] Failed to rollback compression:', rollbackError);+ }+ }++ const reason = error instanceof Error ? error.message : String(error);+ get().failOperation(operationId, { message: reason, type: 'compression_failed' });+ // Keep the toast until dismissed: the conversation looks unchanged after the rollback, so a+ // toast that fades on its own leaves no trace that compaction was attempted.+ const retry =+ options.onRetry ?? (() => void get().executeCompression(context, parentOperationId, options));+ const failureToast = toast.error({+ actions: [+ {+ label: t('retry', { ns: 'common' }),+ // A failed retry raises its own toast, so close this one instead of stacking them+ onClick: () => {+ failureToast.close();+ retry();+ },+ variant: 'text',+ },+ ],+ description: t('compression.failedReason', { ns: 'chat', reason }),+ duration: 0,+ title: t('compression.failed', { ns: 'chat' }),+ });+ return false;+ }+};diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.tssimilarity index 95%rename from src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsrename to src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.tsindex 4cef2701e78..7a30e8abad1 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts@@ -7,7 +7,6 @@ import {collectHeteroAttachedFiles,isRemoteHeterogeneousType,} from '@lobechat/heterogeneous-agents';-import { chainCompressContext } from '@lobechat/prompts';import type {ChatAudioItem,ChatImageItem,@@ -22,7 +21,6 @@ import {applyTopicModelToHeterogeneousProvider,getWorkingDirEffectivePath,getWorkingDirSourcePath,- RequestTrigger,resolveAgentAgencyConfig,toComposerUserMessage,} from '@lobechat/types';@@ -53,7 +51,6 @@ import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';import { agentService } from '@/services/agent';import { aiAgentService, MAX_CLIENT_OPERATION_SNAPSHOT } from '@/services/aiAgent';import { aiChatService } from '@/services/aiChat';-import { chatService } from '@/services/chat';import { resolveSelectedSkillsWithContent } from '@/services/chat/mecha/skillPreload';import { resolveSelectedToolsWithContent } from '@/services/chat/mecha/toolPreload';import { messageService } from '@/services/message';@@ -106,11 +103,7 @@ import {mergeAgentRuntimeInitialContexts,resolveActiveTopicDocumentInitialContext,} from '@/store/chat/utils/activeTopicDocumentContext';-import {- createPendingCompressedGroup,- getCompressionCandidateMessageIds,- hasRunningCompressionOperation,-} from '@/store/chat/utils/compression';+import { hasRunningCompressionOperation } from '@/store/chat/utils/compression';import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { snapshotAgentModel, snapshotAgentReasoning } from '@/store/chat/utils/snapshotAgentModel';@@ -128,8 +121,8 @@ import { useUserMemoryStore } from '@/store/userMemory';import { markdownToTxt } from '@/utils/markdownToTxt';import { aggregateSubagentMetrics } from '@/utils/subagentMetrics';-import { materializeLocalSystemToolSnapshots } from '../transports/client/localSystemToolSnapshots';-import type { CommandSendOverrides } from './commandBus';+import { materializeLocalSystemToolSnapshots } from '../../transports/client/localSystemToolSnapshots';+import type { CommandSendOverrides } from '../commandBus';import {hasNonActionContent,injectReferTopicNode,@@ -140,10 +133,11 @@ import {parseSelectedToolsFromEditorData,parseSingleAgentMentionDirectRoute,processCommands,-} from './commandBus';-import { mergePartialPersistedMessages, resolveSendResponseMessages } from './persistedMessages';-import { resolveExistingTopicForRun } from './resolveExistingTopic';-import { resolveProjectDirectoryRun } from './resolveProjectDirectoryRun';+} from '../commandBus';+import { mergePartialPersistedMessages, resolveSendResponseMessages } from '../persistedMessages';+import { resolveExistingTopicForRun } from '../resolveExistingTopic';+import { resolveProjectDirectoryRun } from '../resolveProjectDirectoryRun';+import { type ContextCompressionOptions, executeContextCompression } from './compression';/*** Extended params for sendMessage with context@@ -210,16 +204,6 @@ type Setter = StoreSetter<ChatStore>;export const conversationLifecycle = (set: Setter, get: () => ChatStore, _api?: unknown) =>new ConversationLifecycleActionImpl(set, get, _api);-const isAbortError = (error: unknown, abortController?: AbortController) =>- !!abortController?.signal.aborted ||- (error instanceof Error &&- (error.name === 'AbortError' ||- error.message.includes('aborted') ||- error.message.includes('cancelled')));--const createAbortError = () =>- Object.assign(new Error('Compression cancelled'), { name: 'AbortError' });-const throwIfSendAborted = (signal?: AbortSignal) => {if (!signal?.aborted) return;@@ -1690,7 +1674,7 @@ export class ConversationLifecycleActionImpl {try {const { executeHeterogeneousAgent } =- await import('../transports/hetero/heterogeneousAgentExecutor');+ await import('../../transports/hetero/heterogeneousAgentExecutor');// Extract imageList from the persisted user message (chatUploadFileList// may already be cleared by this point, so we read from DB instead)const userMsg = heteroData.messages.find((m: any) => m.id === heteroData.userMessageId);@@ -2380,109 +2364,15 @@ export class ConversationLifecycleActionImpl {/*** Execute context compression for /compact command.- * Reuses the same service methods as the agent runtime's compress_context executor.+ *+ * @returns Whether the history was replaced by a summary.*/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, options);- if (messageIds.length === 0) return;-- const tempId = 'tmp_compress_' + nanoid();- const { abortController, operationId } = this.#get().startOperation({- context: { ...context, messageId: tempId },- parentOperationId,- type: 'contextCompression',- });-- // Immediate UI feedback: render a pending compressed group from the first frame- this.#get().internal_createClientMessage(- tempId,- createPendingCompressedGroup({- agentId,- groupId: context.groupId,- id: tempId,- threadId: context.threadId,- topicId,- }) as any,- { operationId },- );-- try {- // 1. Create compression group on server- const result = await messageService.createCompressionGroup({- agentId,- messageIds,- topicId,- });- const { messageGroupId, messages: serverMessages, messagesToSummarize } = result;-- // Replace local pending group with server compression group- this.#get().replaceMessages(serverMessages, { context: context as any });- this.#get().associateMessageWithOperation(messageGroupId, operationId);-- // 2. Generate summary via LLM- const { model, provider } = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());- const compressionPayload = chainCompressContext(messagesToSummarize);- let summaryContent = '';-- await chatService.fetchPresetTaskResult({- abortController,- onMessageHandle: (chunk) => {- if (chunk.type === 'text') {- summaryContent += chunk.text || '';- this.#get().internal_dispatchMessage(- { id: messageGroupId, type: 'updateMessage', value: { content: summaryContent } },- { operationId },- );- }- },- params: { ...compressionPayload, model, provider },- trigger: RequestTrigger.ContextCompression,- });-- if (abortController.signal.aborted) throw createAbortError();-- // 3. Finalize compression- const finalResult = await messageService.finalizeCompression({- agentId,- content: summaryContent,- messageGroupId,- topicId,- });-- if (finalResult.messages) {- this.#get().replaceMessages(finalResult.messages, { context: context as any });- }-- this.#get().completeOperation(operationId);- } catch (error) {- if (isAbortError(error, abortController)) {- this.#get().internal_dispatchMessage(- { type: 'deleteMessages', ids: [tempId] },- { operationId },- );- return;- }-- console.error('[/compact] Compression failed:', error);- this.#get().internal_dispatchMessage(- { type: 'deleteMessages', ids: [tempId] },- { operationId },- );- this.#get().failOperation(operationId, {- message: error instanceof Error ? error.message : String(error),- type: 'compression_failed',- });- }- };+ options?: ContextCompressionOptions,+ ): Promise<boolean> =>+ executeContextCompression({ ...options, context, parentOperationId }, this.#get);}export type ConversationLifecycleAction = Pick<