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): fold the compressed summary above its question (#21171)

Arvin Xu95c92f9bfd15
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 921b0b6cb0e..c82e09d08b0 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -212,6 +212,8 @@
"compressedHistory": "Compressed History",
"compression.cancel": "Uncompress",
"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.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.json
index 1c287853c06..bd63d45a2be 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -212,6 +212,8 @@
"compressedHistory": "压缩历史",
"compression.cancel": "取消压缩",
"compression.cancelConfirm": "确定要取消压缩吗?这将恢复原始消息。",
+ "compression.collapsed": "已压缩前 {{turns}} 轮对话 · 查看摘要",
+ "compression.collapsedUnknown": "已压缩历史对话 · 查看摘要",
"compression.history": "原始对话",
"compression.summary": "历史记录摘要",
"confirmClearCurrentMessages": "确认清空当前会话消息吗?清空后无法恢复",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 8ebad92f086..f9f6edd0f79 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -290,6 +290,8 @@ export default {
'compression.cancel': 'Uncompress',
'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.history': 'Original conversation',
'compression.summary': 'History summary',
'confirmClearCurrentMessages':
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index a838e02f912..fe3045cdf36 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -39,6 +39,7 @@ import { useInitialRevalidation } from './hooks/useInitialRevalidation';
import { useMessageRefreshError } from './hooks/useMessageRefreshError';
import { resolveMessageListFeedback } from './resolveMessageListFeedback';
import { buildChatRows } from './utils/chatRows';
+import { hoistCompressedGroups } from './utils/compressedGroupOrder';
import type { MessageDeepLink } from './utils/messageDeepLink';
import { resolveMessageDeepLink } from './utils/messageDeepLink';
import { resolveRefreshingRowId } from './utils/refreshingRow';
@@ -164,9 +165,16 @@ const ChatList = memo<ChatListProps>(
isValidating: messagesSWR.isValidating,
});
const allDisplayMessages = useConversationStore(dataSelectors.displayMessages);
+ // A compression group summarises the history before the turn that triggered
+ // it, so it belongs above that turn's question rather than between the
+ // question and its answer.
+ const orderedMessages = useMemo(
+ () => hoistCompressedGroups(allDisplayMessages),
+ [allDisplayMessages],
+ );
const displayMessages = useMemo(
- () => (filterItem ? allDisplayMessages.filter(filterItem) : allDisplayMessages),
- [allDisplayMessages, filterItem],
+ () => (filterItem ? orderedMessages.filter(filterItem) : orderedMessages),
+ [orderedMessages, filterItem],
);
const displayMessageIds = useMemo(() => displayMessages.map((m) => m.id), [displayMessages]);
// Steered follow-up turns fold into the turn they interrupted. Custom item
diff --git a/src/features/Conversation/ChatList/utils/compressedGroupOrder.test.ts b/src/features/Conversation/ChatList/utils/compressedGroupOrder.test.ts
new file mode 100644
index 00000000000..7bbf6f959b3
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/compressedGroupOrder.test.ts
@@ -0,0 +1,48 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { hoistCompressedGroups } from './compressedGroupOrder';
+
+const msg = (id: string, role: UIChatMessage['role']): UIChatMessage =>
+ ({ content: '', createdAt: 0, id, role, updatedAt: 0 }) as any;
+
+const ids = (messages: UIChatMessage[]) => messages.map((message) => message.id);
+
+describe('hoistCompressedGroups', () => {
+ it('returns the same list when the topic has no compressed group', () => {
+ const messages = [msg('u1', 'user'), msg('a1', 'assistant')];
+
+ expect(hoistCompressedGroups(messages)).toBe(messages);
+ });
+
+ it('moves the group above the user message that triggered it', () => {
+ const messages = [msg('u1', 'user'), msg('c1', 'compressedGroup'), msg('a1', 'assistantGroup')];
+
+ expect(ids(hoistCompressedGroups(messages))).toEqual(['c1', 'u1', 'a1']);
+ });
+
+ it('keeps a group that is already above the question in place', () => {
+ const messages = [msg('c1', 'compressedGroup'), msg('u1', 'user'), msg('a1', 'assistantGroup')];
+
+ expect(ids(hoistCompressedGroups(messages))).toEqual(['c1', 'u1', 'a1']);
+ });
+
+ it('lifts each group above its own turn in multi-compression topics', () => {
+ const messages = [
+ msg('c1', 'compressedGroup'),
+ msg('u1', 'user'),
+ msg('a1', 'assistantGroup'),
+ msg('u2', 'user'),
+ msg('c2', 'compressedGroup'),
+ msg('a2', 'assistantGroup'),
+ ];
+
+ expect(ids(hoistCompressedGroups(messages))).toEqual(['c1', 'u1', 'a1', 'c2', 'u2', 'a2']);
+ });
+
+ it('keeps the group at the tail when there is no user message to anchor it to', () => {
+ const messages = [msg('a1', 'assistantGroup'), msg('c1', 'compressedGroup')];
+
+ expect(ids(hoistCompressedGroups(messages))).toEqual(['a1', 'c1']);
+ });
+});
diff --git a/src/features/Conversation/ChatList/utils/compressedGroupOrder.ts b/src/features/Conversation/ChatList/utils/compressedGroupOrder.ts
new file mode 100644
index 00000000000..9745c81aed9
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/compressedGroupOrder.ts
@@ -0,0 +1,45 @@
+import type { UIChatMessage } from '@lobechat/types';
+
+const isCompressedGroup = (message: UIChatMessage) => message.role === 'compressedGroup';
+
+const findLastUserIndex = (messages: UIChatMessage[]) => {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (messages[i].role === 'user') return i;
+ }
+
+ return -1;
+};
+
+/**
+ * A compression group summarises the history *before* the turn that triggered
+ * it, but the group is created while that turn is already running, so its
+ * `createdAt` sorts it after the turn's user message. Rendered in that order the
+ * summary card splits the question from its answer and reads like a reply of
+ * its own.
+ *
+ * Place the group where its content belongs: directly above the user message
+ * that follows the compressed history, so the answer stays attached to the
+ * question. Groups that have no user message above them keep their position.
+ */
+export const hoistCompressedGroups = (messages: UIChatMessage[]): UIChatMessage[] => {
+ if (!messages.some(isCompressedGroup)) return messages;
+
+ const result: UIChatMessage[] = [];
+
+ for (const message of messages) {
+ if (!isCompressedGroup(message)) {
+ result.push(message);
+ continue;
+ }
+
+ const anchor = findLastUserIndex(result);
+
+ if (anchor === -1) {
+ result.push(message);
+ } else {
+ result.splice(anchor, 0, message);
+ }
+ }
+
+ return result;
+};
diff --git a/src/features/Conversation/Messages/CompressedGroup/index.tsx b/src/features/Conversation/Messages/CompressedGroup/index.tsx
index 7cbf4805add..7c4c5acc1f9 100644
--- a/src/features/Conversation/Messages/CompressedGroup/index.tsx
+++ b/src/features/Conversation/Messages/CompressedGroup/index.tsx
@@ -1,7 +1,7 @@
'use client';
-import type { UIChatMessage } from '@lobechat/types';
-import { createStaticStyles, cx, Flexbox, Icon, Markdown } from '@lobehub/ui';
+import type { CompressionGroupMetadata, UIChatMessage } from '@lobechat/types';
+import { createStaticStyles, cx, Divider, Flexbox, Icon, Markdown } from '@lobehub/ui';
import { ActionIcon, confirmModal, Tabs, type TabsItem } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { ChevronDown, ChevronUp, History, Sparkles, Undo2 } from 'lucide-react';
@@ -15,13 +15,43 @@ import { shinyTextStyles } from '@/styles/loading';
import { dataSelectors, useConversationStore } from '../../store';
import CompressedMessageItem from './CompressedMessageItem';
-import { isCompressionSummaryGenerating, shouldShowCompressedGroupPanel } from './logic';
+import {
+ getCompressedTurnCount,
+ isCompressionSummaryGenerating,
+ shouldShowCompressedGroupPanel,
+} from './logic';
import { useGroupPreferences } from './useGroupPreferences';
-const styles = createStaticStyles(({ css }) => ({
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ collapsedButton: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ gap: 6px;
+ align-items: center;
+
+ padding-block: 2px;
+ padding-inline: 8px;
+ border: none;
+ border-radius: 6px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextDescription};
+
+ background: none;
+
+ transition: color 0.2s ease;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ `,
container: css`
margin-block-end: 8px;
`,
+ divider: css`
+ margin: 0;
+ `,
header: css`
.ant-tabs-nav {
margin-block-end: 0;
@@ -79,6 +109,18 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {
isGeneratingSummary,
});
+ // How much history this group folded away, phrased as conversation turns.
+ const compressedTurnCount = useMemo(
+ () =>
+ getCompressedTurnCount({
+ compressedMessages,
+ originalMessageCount: (
+ (message as UIChatMessage | undefined)?.metadata as CompressionGroupMetadata | undefined
+ )?.originalMessageCount,
+ }),
+ [compressedMessages, message],
+ );
+
const tabItems: TabsItem[] = useMemo(
() => [
{
@@ -92,53 +134,64 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {
label: t('compression.history'),
},
],
- [],
+ [t],
);
+ if (isGeneratingSummary) {
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ <Flexbox horizontal>
+ <span className={cx(shinyTextStyles.shinyText)}>{t('compressedHistory')}</span>
+ </Flexbox>
+ <StreamingMarkdown>{content}</StreamingMarkdown>
+ </Flexbox>
+ );
+ }
+
return (
<Flexbox className={styles.container} gap={8}>
- {isGeneratingSummary ? (
+ {expanded ? (
<>
- <Flexbox horizontal>
- {/*<Icon icon={FolderArchive} size={14} />*/}
- <span className={cx(isGeneratingSummary ? shinyTextStyles.shinyText : '')}>
- {t('compressedHistory')}
- </span>
- </Flexbox>
- <StreamingMarkdown>{content}</StreamingMarkdown>
- </>
- ) : (
- <Flexbox horizontal align={'center'} distribution={'space-between'} width={'100%'}>
- <Tabs
- activeKey={isGeneratingSummary ? 'summary' : activeTab}
- className={styles.header}
- items={tabItems}
- variant={'rounded'}
- onChange={setActiveTab}
- />
- <Flexbox horizontal gap={4}>
- <ActionIcon
- icon={Undo2}
- size={'small'}
- title={t('compression.cancel')}
- onClick={handleCancelCompression}
- />
- <ActionIcon
- icon={expanded ? ChevronUp : ChevronDown}
- size={'small'}
- onClick={toggleExpanded}
+ <Flexbox horizontal align={'center'} distribution={'space-between'} width={'100%'}>
+ <Tabs
+ activeKey={activeTab}
+ className={styles.header}
+ items={tabItems}
+ variant={'rounded'}
+ onChange={setActiveTab}
/>
+ <Flexbox horizontal gap={4}>
+ <ActionIcon
+ icon={Undo2}
+ size={'small'}
+ title={t('compression.cancel')}
+ onClick={handleCancelCompression}
+ />
+ <ActionIcon icon={ChevronUp} size={'small'} onClick={toggleExpanded} />
+ </Flexbox>
</Flexbox>
- </Flexbox>
- )}
- {!showPanelContent ? null : activeTab === 'summary' ? (
- <Markdown variant={'chat'}>{content}</Markdown>
+ {!showPanelContent ? null : activeTab === 'summary' ? (
+ <Markdown variant={'chat'}>{content}</Markdown>
+ ) : (
+ <Flexbox className={styles.messagesContainer} gap={4}>
+ {compressedMessages?.map((msg) => (
+ <CompressedMessageItem key={msg.id} message={msg} />
+ ))}
+ </Flexbox>
+ )}
+ </>
) : (
- <Flexbox className={styles.messagesContainer} gap={4}>
- {compressedMessages?.map((msg) => (
- <CompressedMessageItem key={msg.id} message={msg} />
- ))}
- </Flexbox>
+ <Divider className={styles.divider}>
+ <button className={styles.collapsedButton} type={'button'} onClick={toggleExpanded}>
+ <Icon icon={History} size={14} />
+ <span>
+ {compressedTurnCount > 0
+ ? t('compression.collapsed', { turns: compressedTurnCount })
+ : t('compression.collapsedUnknown')}
+ </span>
+ <Icon icon={ChevronDown} size={14} />
+ </button>
+ </Divider>
)}
</Flexbox>
);
diff --git a/src/features/Conversation/Messages/CompressedGroup/logic.test.ts b/src/features/Conversation/Messages/CompressedGroup/logic.test.ts
index aba061e0dcb..6a110760550 100644
--- a/src/features/Conversation/Messages/CompressedGroup/logic.test.ts
+++ b/src/features/Conversation/Messages/CompressedGroup/logic.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { isCompressionSummaryGenerating, shouldShowCompressedGroupPanel } from './logic';
+import {
+ getCompressedTurnCount,
+ isCompressionSummaryGenerating,
+ shouldShowCompressedGroupPanel,
+} from './logic';
describe('CompressedGroup logic', () => {
it.each(['generateSummary', 'contextCompression'])(
@@ -35,3 +39,33 @@ describe('CompressedGroup logic', () => {
).toBe(false);
});
});
+
+describe('getCompressedTurnCount', () => {
+ it('counts user messages as conversation turns', () => {
+ const compressedMessages = [
+ { id: 'u1', role: 'user' },
+ { id: 'a1', role: 'assistant' },
+ { id: 'u2', role: 'user' },
+ { id: 'a2', role: 'assistantGroup' },
+ ] as any;
+
+ expect(getCompressedTurnCount({ compressedMessages })).toBe(2);
+ });
+
+ it('falls back to the message count when no user message is present', () => {
+ const compressedMessages = [
+ { id: 'a1', role: 'assistant' },
+ { id: 'a2', role: 'assistant' },
+ ] as any;
+
+ expect(getCompressedTurnCount({ compressedMessages })).toBe(2);
+ });
+
+ it('uses the server-side original message count before the detail arrives', () => {
+ expect(getCompressedTurnCount({ originalMessageCount: 3 })).toBe(3);
+ });
+
+ it('returns zero when the group carries no count at all', () => {
+ expect(getCompressedTurnCount({})).toBe(0);
+ });
+});
diff --git a/src/features/Conversation/Messages/CompressedGroup/logic.ts b/src/features/Conversation/Messages/CompressedGroup/logic.ts
index 88ff2d3df48..ff3f4b04604 100644
--- a/src/features/Conversation/Messages/CompressedGroup/logic.ts
+++ b/src/features/Conversation/Messages/CompressedGroup/logic.ts
@@ -1,3 +1,5 @@
+import type { UIChatMessage } from '@lobechat/types';
+
export const isCompressionSummaryGenerating = (operationType?: string) =>
operationType === 'generateSummary' || operationType === 'contextCompression';
@@ -8,3 +10,28 @@ export const shouldShowCompressedGroupPanel = ({
expanded: boolean;
isGeneratingSummary: boolean;
}) => expanded && !isGeneratingSummary;
+
+/**
+ * How much history a compressed group folded away, counted in conversation
+ * turns so the collapsed bar can say "the previous N turns".
+ *
+ * The nested messages are the only truthful count once they are loaded. Before
+ * that (and on a group restored from a source that carries no detail) fall back
+ * to the server-side `originalMessageCount`, which counts messages rather than
+ * turns but still gives the reader a size.
+ */
+export const getCompressedTurnCount = ({
+ compressedMessages,
+ originalMessageCount,
+}: {
+ compressedMessages?: UIChatMessage[];
+ originalMessageCount?: number;
+}) => {
+ if (compressedMessages?.length) {
+ const userTurns = compressedMessages.filter((message) => message.role === 'user').length;
+
+ return userTurns || compressedMessages.length;
+ }
+
+ return originalMessageCount ?? 0;
+};
diff --git a/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.test.ts b/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.test.ts
index 9e81f00372e..576b2ab25dc 100644
--- a/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.test.ts
+++ b/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.test.ts
@@ -39,13 +39,13 @@ describe('useGroupPreferences', () => {
});
it('reads a stored fold on the first render, not after one', () => {
- localStorage.setItem(EXPANDED_KEY, 'false');
+ localStorage.setItem(EXPANDED_KEY, 'true');
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 });
+ // A deferred (effect-based) read renders the collapsed default first and
+ // opens afterwards, which moves the transcript's scroll position.
+ expect(observed[0]).toEqual({ activeTab: 'summary', expanded: true });
});
it('reads the stored tab on the first render', () => {
@@ -54,8 +54,8 @@ describe('useGroupPreferences', () => {
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('defaults to the summary tab and a folded group when nothing is stored', () => {
+ expect(renderPreferences().observed[0]).toEqual({ activeTab: 'summary', expanded: false });
});
it('keeps the stored fold across an unmount and remount', () => {
@@ -70,17 +70,17 @@ describe('useGroupPreferences', () => {
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);
+
+ act(() => result.current.toggleExpanded());
+
+ expect(localStorage.getItem(EXPANDED_KEY)).toBe('false');
+ expect(result.current.expanded).toBe(false);
});
it('writes the tab on selection', () => {
diff --git a/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.ts b/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.ts
index dfa7e2e2b1d..e93b96fad34 100644
--- a/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.ts
+++ b/src/features/Conversation/Messages/CompressedGroup/useGroupPreferences.ts
@@ -12,6 +12,9 @@ import { useCallback, useState } from 'react';
* 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.
+ *
+ * Folded is the default: the summary is earlier history, so a collapsed bar
+ * keeps the question and its answer adjacent until the reader asks for it.
*/
export const compressedGroupTabKey = (id: string) => `compressed-group-tab:${id}`;
@@ -42,7 +45,7 @@ export const useGroupPreferences = (id: string) => {
() => readPreference(compressedGroupTabKey(id)) ?? 'summary',
);
const [expanded, setExpanded] = useState(
- () => readPreference(compressedGroupExpandedKey(id)) !== 'false',
+ () => readPreference(compressedGroupExpandedKey(id)) === 'true',
);
const setActiveTab = useCallback(