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.

💄 style(conversation): flatten the compressed context card container (#20531)

Arvin Xu91b0881dc213
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index d9b58323f98..4bc0c62ba46 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -205,8 +205,8 @@
"compressedHistory": "Compressed History",
"compression.cancel": "Uncompress",
"compression.cancelConfirm": "Are you sure you want to uncompress? This will restore the original messages.",
- "compression.history": "History",
- "compression.summary": "Summary",
+ "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.",
"confirmRemoveChatGroupItemAlert": "This Group will be deleted. Group-specific assistants will also be deleted, while external assistants will not be affected.",
"confirmRemoveGroupItemAlert": "You are about to delete this category. After deletion, its agents will be moved to the default list. Please confirm your action.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 6ac9dd73457..55184db53a4 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -205,8 +205,8 @@
"compressedHistory": "压缩历史",
"compression.cancel": "取消压缩",
"compression.cancelConfirm": "确定要取消压缩吗?这将恢复原始消息。",
- "compression.history": "历史记录",
- "compression.summary": "摘要",
+ "compression.history": "原始对话",
+ "compression.summary": "历史记录摘要",
"confirmClearCurrentMessages": "确认清空当前会话消息吗?清空后无法恢复",
"confirmRemoveChatGroupItemAlert": "确认删除该群组吗?群组专有助理将会被同样删除,外部助理不受影响",
"confirmRemoveGroupItemAlert": "确认删除该分类吗?分类内的助理会移回默认列表",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 29adce5e12c..e7726507231 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -176,8 +176,8 @@ export default {
'compression.cancel': 'Uncompress',
'compression.cancelConfirm':
'Are you sure you want to uncompress? This will restore the original messages.',
- 'compression.history': 'History',
- 'compression.summary': 'Summary',
+ '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.',
'confirmRemoveChatGroupItemAlert':
diff --git a/src/features/Conversation/Messages/CompressedGroup/index.tsx b/src/features/Conversation/Messages/CompressedGroup/index.tsx
index cd6269ab2e3..92c2b90a246 100644
--- a/src/features/Conversation/Messages/CompressedGroup/index.tsx
+++ b/src/features/Conversation/Messages/CompressedGroup/index.tsx
@@ -1,12 +1,12 @@
'use client';
-import type { CompressionGroupMetadata, UIChatMessage } from '@lobechat/types';
-import { Flexbox, Icon, Markdown, ScrollShadow } from '@lobehub/ui';
+import type { UIChatMessage } from '@lobechat/types';
+import { Flexbox, Icon, Markdown } from '@lobehub/ui';
import { ActionIcon, confirmModal, Tabs, type TabsItem } from '@lobehub/ui/base-ui';
import { createStaticStyles, cx } from 'antd-style';
import isEqual from 'fast-deep-equal';
import { ChevronDown, ChevronUp, History, Sparkles, Undo2 } from 'lucide-react';
-import { memo, useCallback, useMemo, useState } from 'react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import StreamingMarkdown from '@/components/StreamingMarkdown';
@@ -17,31 +17,11 @@ import { shinyTextStyles } from '@/styles/loading';
import { dataSelectors, useConversationStore } from '../../store';
import CompressedMessageItem from './CompressedMessageItem';
import { isCompressionSummaryGenerating, shouldShowCompressedGroupPanel } from './logic';
+import { useGroupPreferences } from './useGroupPreferences';
-const STORAGE_KEY_PREFIX = 'compressed-group-tab:';
-
-const getStoredTab = (id: string): string => {
- if (typeof window === 'undefined') return 'summary';
- return localStorage.getItem(`${STORAGE_KEY_PREFIX}${id}`) || 'summary';
-};
-
-const setStoredTab = (id: string, tab: string) => {
- if (typeof window === 'undefined') return;
- localStorage.setItem(`${STORAGE_KEY_PREFIX}${id}`, tab);
-};
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
+const styles = createStaticStyles(({ css }) => ({
container: css`
margin-block-end: 8px;
- padding-block: 8px;
- padding-inline: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 12px;
-
- background: ${cssVar.colorBgContainer};
- `,
- contentScroll: css`
- max-height: min(40vh, 400px);
`,
header: css`
.ant-tabs-nav {
@@ -60,20 +40,9 @@ export interface CompressedGroupMessageProps {
const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {
const { t } = useTranslation('chat');
- const [activeTab, setActiveTab] = useState<string>(() => getStoredTab(id));
-
- const handleTabChange = useCallback(
- (tab: string) => {
- setActiveTab(tab);
- setStoredTab(id, tab);
- },
- [id],
- );
+ const { activeTab, expanded, setActiveTab, toggleExpanded } = useGroupPreferences(id);
const message = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual);
- const toggleCompressedGroupExpanded = useConversationStore(
- (s) => s.toggleCompressedGroupExpanded,
- );
const cancelCompression = useConversationStore((s) => s.cancelCompression);
const handleCancelCompression = useCallback(() => {
@@ -86,7 +55,6 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {
const content = message?.content;
const rawCompressedMessages = (message as UIChatMessage)?.compressedMessages;
- const expanded = (message?.metadata as CompressionGroupMetadata)?.expanded ?? true;
// Filter out placeholder assistant message (content === '...' without tools)
const compressedMessages = useMemo(() => {
@@ -147,7 +115,7 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {
className={styles.header}
items={tabItems}
variant={'rounded'}
- onChange={handleTabChange}
+ onChange={setActiveTab}
/>
<Flexbox horizontal gap={4}>
<ActionIcon
@@ -159,25 +127,19 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {
<ActionIcon
icon={expanded ? ChevronUp : ChevronDown}
size={'small'}
- onClick={() => toggleCompressedGroupExpanded(id)}
+ onClick={toggleExpanded}
/>
</Flexbox>
</Flexbox>
)}
{!showPanelContent ? null : activeTab === 'summary' ? (
- <ScrollShadow className={styles.contentScroll} offset={12} size={12}>
- <Markdown style={{ overflow: 'unset' }} variant={'chat'}>
- {content}
- </Markdown>
- </ScrollShadow>
+ <Markdown variant={'chat'}>{content}</Markdown>
) : (
- <ScrollShadow className={styles.contentScroll} offset={12} size={12}>
- <Flexbox className={styles.messagesContainer} gap={4}>
- {compressedMessages?.map((msg) => (
- <CompressedMessageItem key={msg.id} message={msg} />
- ))}
- </Flexbox>
- </ScrollShadow>
+ <Flexbox className={styles.messagesContainer} gap={4}>
+ {compressedMessages?.map((msg) => (
+ <CompressedMessageItem key={msg.id} message={msg} />
+ ))}
+ </Flexbox>
)}
</Flexbox>
);
diff --git a/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.test.ts b/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.test.ts
new file mode 100644
index 00000000000..9e81f00372e
--- /dev/null
+++ b/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.test.ts
@@ -0,0 +1,94 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ compressedGroupExpandedKey,
+ compressedGroupTabKey,
+ useGroupPreferences,
+} from './useGroupPreferences';
+
+const GROUP_ID = 'ccg-test-group';
+const EXPANDED_KEY = compressedGroupExpandedKey(GROUP_ID);
+const TAB_KEY = compressedGroupTabKey(GROUP_ID);
+
+/**
+ * The values seen at RENDER time, in order — `observed[0]` is the first render.
+ * Reading `result.current` alone would not tell a synchronous read from one that
+ * hydrates in an effect, because testing-library flushes effects before returning.
+ */
+const renderPreferences = () => {
+ const observed: { activeTab: string; expanded: boolean }[] = [];
+
+ const { result, unmount } = renderHook(() => {
+ const preferences = useGroupPreferences(GROUP_ID);
+
+ observed.push({ activeTab: preferences.activeTab, expanded: preferences.expanded });
+
+ return preferences;
+ });
+
+ return { observed, result, unmount };
+};
+
+describe('useGroupPreferences', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ it('reads a stored fold on the first render, not after one', () => {
+ localStorage.setItem(EXPANDED_KEY, 'false');
+
+ const { observed } = renderPreferences();
+
+ // A deferred (effect-based) read renders `true` here and folds afterwards,
+ // which is what painted the whole summary before collapsing it.
+ expect(observed[0]).toEqual({ activeTab: 'summary', expanded: false });
+ });
+
+ it('reads the stored tab on the first render', () => {
+ localStorage.setItem(TAB_KEY, 'history');
+
+ expect(renderPreferences().observed[0].activeTab).toBe('history');
+ });
+
+ it('defaults to the summary tab and an open group when nothing is stored', () => {
+ expect(renderPreferences().observed[0]).toEqual({ activeTab: 'summary', expanded: true });
+ });
+
+ it('keeps the stored fold across an unmount and remount', () => {
+ localStorage.setItem(EXPANDED_KEY, 'false');
+
+ const first = renderPreferences();
+ expect(first.observed[0].expanded).toBe(false);
+ first.unmount();
+
+ expect(renderPreferences().observed[0].expanded).toBe(false);
+ });
+
+ it('writes the fold on toggle', () => {
+ const { result } = renderPreferences();
+ expect(result.current.expanded).toBe(true);
+
+ act(() => result.current.toggleExpanded());
+
+ expect(localStorage.getItem(EXPANDED_KEY)).toBe('false');
+ expect(result.current.expanded).toBe(false);
+
+ act(() => result.current.toggleExpanded());
+
+ expect(localStorage.getItem(EXPANDED_KEY)).toBe('true');
+ expect(result.current.expanded).toBe(true);
+ });
+
+ it('writes the tab on selection', () => {
+ const { result } = renderPreferences();
+
+ act(() => result.current.setActiveTab('history'));
+
+ expect(localStorage.getItem(TAB_KEY)).toBe('history');
+ expect(result.current.activeTab).toBe('history');
+ });
+});
diff --git a/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.ts b/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.ts
new file mode 100644
index 00000000000..dfa7e2e2b1d
--- /dev/null
+++ b/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.ts
@@ -0,0 +1,64 @@
+import { useCallback, useState } from 'react';
+
+/**
+ * Whether a group is folded open, and which of its two views is showing, are
+ * per-browser reading preferences rather than conversation data: both live in
+ * localStorage and are never written back to the message group.
+ *
+ * Both are read synchronously in the state initialiser instead of through
+ * `useLocalStorageState`. That hook renders its default first and hydrates in an
+ * effect, which is the right trade for a preference that only tweaks rendering —
+ * but the fold decides whether a potentially very long summary renders at all, so
+ * a deferred read paints the whole block and collapses it afterwards on every
+ * mount, including each virtual-list remount, dragging the transcript's scroll
+ * position around.
+ */
+export const compressedGroupTabKey = (id: string) => `compressed-group-tab:${id}`;
+
+export const compressedGroupExpandedKey = (id: string) => `compressed-group-expanded:${id}`;
+
+const readPreference = (key: string): string | null => {
+ if (typeof window === 'undefined') return null;
+
+ try {
+ return window.localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+};
+
+const writePreference = (key: string, value: string) => {
+ if (typeof window === 'undefined') return;
+
+ try {
+ window.localStorage.setItem(key, value);
+ } catch {
+ // ignore write failures (private mode, quota)
+ }
+};
+
+export const useGroupPreferences = (id: string) => {
+ const [activeTab, setActiveTabState] = useState(
+ () => readPreference(compressedGroupTabKey(id)) ?? 'summary',
+ );
+ const [expanded, setExpanded] = useState(
+ () => readPreference(compressedGroupExpandedKey(id)) !== 'false',
+ );
+
+ const setActiveTab = useCallback(
+ (tab: string) => {
+ setActiveTabState(tab);
+ writePreference(compressedGroupTabKey(id), tab);
+ },
+ [id],
+ );
+
+ const toggleExpanded = useCallback(() => {
+ const next = !expanded;
+
+ setExpanded(next);
+ writePreference(compressedGroupExpandedKey(id), String(next));
+ }, [expanded, id]);
+
+ return { activeTab, expanded, setActiveTab, toggleExpanded };
+};
diff --git a/src/features/Conversation/store/slices/message/action/state.test.ts b/src/features/Conversation/store/slices/message/action/state.test.ts
index 0e71cc758c7..d024f44375a 100644
--- a/src/features/Conversation/store/slices/message/action/state.test.ts
+++ b/src/features/Conversation/store/slices/message/action/state.test.ts
@@ -106,241 +106,4 @@ describe('MessageStateAction', () => {
});
});
});
-
- describe('toggleCompressedGroupExpanded', () => {
- it('should toggle expanded state from false to true', async () => {
- const store = createTestStore();
-
- // Setup: compressedGroup with expanded=false
- const compressedGroup: UIChatMessage = {
- id: 'group-1',
- content: 'Summary content',
- role: 'compressedGroup' as any,
- createdAt: 1000,
- updatedAt: 1000,
- metadata: { expanded: false } as any,
- };
- store.setState({ displayMessages: [compressedGroup] });
-
- // Mock API response
- const updatedMessages: UIChatMessage[] = [
- { ...compressedGroup, metadata: { expanded: true } as any },
- ];
- vi.mocked(messageService.updateMessageGroupMetadata).mockResolvedValue({
- messages: updatedMessages,
- });
-
- // Act
- await store.getState().toggleCompressedGroupExpanded('group-1');
-
- // Assert: optimistic update should have been called
- expect(messageService.updateMessageGroupMetadata).toHaveBeenCalledWith({
- context: {
- agentId: 'test-agent',
- groupId: undefined,
- threadId: null,
- topicId: 'test-topic',
- },
- expanded: true,
- messageGroupId: 'group-1',
- });
- });
-
- it('should toggle expanded state from true to false', async () => {
- const store = createTestStore();
-
- // Setup: compressedGroup with expanded=true
- const compressedGroup: UIChatMessage = {
- id: 'group-1',
- content: 'Summary content',
- role: 'compressedGroup' as any,
- createdAt: 1000,
- updatedAt: 1000,
- metadata: { expanded: true } as any,
- };
- store.setState({ displayMessages: [compressedGroup] });
-
- // Mock API response
- const updatedMessages: UIChatMessage[] = [
- { ...compressedGroup, metadata: { expanded: false } as any },
- ];
- vi.mocked(messageService.updateMessageGroupMetadata).mockResolvedValue({
- messages: updatedMessages,
- });
-
- // Act
- await store.getState().toggleCompressedGroupExpanded('group-1');
-
- // Assert
- expect(messageService.updateMessageGroupMetadata).toHaveBeenCalledWith({
- context: {
- agentId: 'test-agent',
- groupId: undefined,
- threadId: null,
- topicId: 'test-topic',
- },
- expanded: false,
- messageGroupId: 'group-1',
- });
- });
-
- it('should set specific expanded value when provided', async () => {
- const store = createTestStore();
-
- // Setup: compressedGroup with expanded=false
- const compressedGroup: UIChatMessage = {
- id: 'group-1',
- content: 'Summary content',
- role: 'compressedGroup' as any,
- createdAt: 1000,
- updatedAt: 1000,
- metadata: { expanded: false } as any,
- };
- store.setState({ displayMessages: [compressedGroup] });
-
- vi.mocked(messageService.updateMessageGroupMetadata).mockResolvedValue({
- messages: [{ ...compressedGroup, metadata: { expanded: true } as any }],
- });
-
- // Act: explicitly set to true
- await store.getState().toggleCompressedGroupExpanded('group-1', true);
-
- // Assert
- expect(messageService.updateMessageGroupMetadata).toHaveBeenCalledWith({
- context: {
- agentId: 'test-agent',
- groupId: undefined,
- threadId: null,
- topicId: 'test-topic',
- },
- expanded: true,
- messageGroupId: 'group-1',
- });
- });
-
- it('should not call API if message does not exist', async () => {
- const store = createTestStore();
-
- // Act
- await store.getState().toggleCompressedGroupExpanded('nonexistent');
-
- // Assert
- expect(messageService.updateMessageGroupMetadata).not.toHaveBeenCalled();
- });
-
- it('should not call API if message is not compressedGroup', async () => {
- const store = createTestStore();
-
- // Setup: regular user message
- const userMessage: UIChatMessage = {
- id: 'msg-1',
- content: 'Hello',
- role: 'user',
- createdAt: 1000,
- updatedAt: 1000,
- };
- store.setState({ displayMessages: [userMessage] });
-
- // Act
- await store.getState().toggleCompressedGroupExpanded('msg-1');
-
- // Assert
- expect(messageService.updateMessageGroupMetadata).not.toHaveBeenCalled();
- });
-
- it('should not call API if context is missing topicId', async () => {
- const store = createTestStore({ topicId: null });
-
- // Setup: compressedGroup
- const compressedGroup: UIChatMessage = {
- id: 'group-1',
- content: 'Summary content',
- role: 'compressedGroup' as any,
- createdAt: 1000,
- updatedAt: 1000,
- metadata: { expanded: false } as any,
- };
- // Use shallow merge (default zustand behavior)
- store.setState({ displayMessages: [compressedGroup] });
-
- // Verify context is still null
- expect(store.getState().context.topicId).toBeNull();
-
- // Act
- await store.getState().toggleCompressedGroupExpanded('group-1');
-
- // Assert: should not call API because topicId is null
- expect(messageService.updateMessageGroupMetadata).not.toHaveBeenCalled();
- });
-
- it('should default to false when metadata.expanded is undefined', async () => {
- const store = createTestStore();
-
- // Setup: compressedGroup without expanded in metadata
- const compressedGroup: UIChatMessage = {
- id: 'group-1',
- content: 'Summary content',
- role: 'compressedGroup' as any,
- createdAt: 1000,
- updatedAt: 1000,
- metadata: {} as any,
- };
- store.setState({ displayMessages: [compressedGroup] });
-
- vi.mocked(messageService.updateMessageGroupMetadata).mockResolvedValue({
- messages: [{ ...compressedGroup, metadata: { expanded: true } as any }],
- });
-
- // Act: toggle from undefined (treated as false) to true
- await store.getState().toggleCompressedGroupExpanded('group-1');
-
- // Assert: should toggle to true
- expect(messageService.updateMessageGroupMetadata).toHaveBeenCalledWith({
- context: {
- agentId: 'test-agent',
- groupId: undefined,
- threadId: null,
- topicId: 'test-topic',
- },
- expanded: true,
- messageGroupId: 'group-1',
- });
- });
-
- it('should call replaceMessages with updated data from API', async () => {
- const store = createTestStore();
-
- // Setup
- const compressedGroup: UIChatMessage = {
- id: 'group-1',
- content: 'Summary content',
- role: 'compressedGroup' as any,
- createdAt: 1000,
- updatedAt: 1000,
- metadata: { expanded: false } as any,
- };
- store.setState({ displayMessages: [compressedGroup] });
-
- const replaceMessagesSpy = vi.spyOn(store.getState(), 'replaceMessages');
-
- const updatedMessages: UIChatMessage[] = [
- { ...compressedGroup, metadata: { expanded: true } as any },
- ];
- vi.mocked(messageService.updateMessageGroupMetadata).mockResolvedValue({
- messages: updatedMessages,
- });
-
- // Act
- await store.getState().toggleCompressedGroupExpanded('group-1');
-
- // Assert
- expect(replaceMessagesSpy).toHaveBeenCalledWith(updatedMessages, {
- expectedContext: {
- agentId: 'test-agent',
- threadId: null,
- topicId: 'test-topic',
- },
- });
- });
- });
});
diff --git a/src/features/Conversation/store/slices/message/action/state.ts b/src/features/Conversation/store/slices/message/action/state.ts
index 6d72e936706..db509546d93 100644
--- a/src/features/Conversation/store/slices/message/action/state.ts
+++ b/src/features/Conversation/store/slices/message/action/state.ts
@@ -40,11 +40,6 @@ export interface MessageStateAction {
editorData?: Record<string, any> | null,
) => Promise<void>;
- /**
- * Toggle compressed group expanded state
- */
- toggleCompressedGroupExpanded: (id: string, expanded?: boolean) => Promise<void>;
-
/**
* Toggle tool inspect expanded state
*/
@@ -131,40 +126,6 @@ export const messageStateSlice: StateCreator<
}
},
- toggleCompressedGroupExpanded: async (id, expanded) => {
- const message = dataSelectors.getDisplayMessageById(id)(get());
- if (!message || message.role !== 'compressedGroup') return;
-
- const { context, internal_dispatchMessage, replaceMessages } = get();
- if (!context.agentId || !context.topicId) return;
-
- // If expanded is not provided, toggle current state
- const currentExpanded = (message.metadata as any)?.expanded ?? false;
- const nextExpanded = expanded ?? !currentExpanded;
-
- // Optimistic update
- internal_dispatchMessage({
- id,
- type: 'updateMessageGroupMetadata',
- value: { expanded: nextExpanded },
- });
-
- // Persist to server and get updated messages
- const { messages } = await messageService.updateMessageGroupMetadata({
- context: {
- agentId: context.agentId,
- groupId: context.groupId,
- threadId: context.threadId,
- topicId: context.topicId,
- },
- expanded: nextExpanded,
- messageGroupId: id,
- });
-
- // Sync with server data
- replaceMessages(messages, { expectedContext: context });
- },
-
toggleInspectExpanded: async (id, expanded) => {
const message = dataSelectors.getDbMessageById(id)(get());
if (!message) return;