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.

🐛 fix(conversation): keep the streaming fade-in on a reply that remounts mid-stream (#21622)

LiJian8cb22923e05a
diff --git a/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx b/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx
index 241765d2b40..15c099a31f7 100644
--- a/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx
+++ b/src/features/Conversation/Messages/Assistant/components/MessageContent.tsx
@@ -14,11 +14,7 @@ import { useMarkdown } from '../useMarkdown';
const MessageContent = memo<UIChatMessage>(
({ id, tools, content, chunksList, search, imageList, metadata, ...props }) => {
- const { drawer, markdownProps } = useMarkdown(
- id,
- !!tools?.length,
- !!content && content !== LOADING_FLAT,
- );
+ const { drawer, markdownProps } = useMarkdown(id, !!tools?.length, content);
// Use ConversationStore instead of ChatStore
const generating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
const isCreating = useConversationStore(messageStateSelectors.isMessageCreating(id));
diff --git a/src/features/Conversation/Messages/Assistant/useMarkdown.tsx b/src/features/Conversation/Messages/Assistant/useMarkdown.tsx
index 652576c0e3f..302d248c3e6 100644
--- a/src/features/Conversation/Messages/Assistant/useMarkdown.tsx
+++ b/src/features/Conversation/Messages/Assistant/useMarkdown.tsx
@@ -5,14 +5,14 @@ import isEqual from 'fast-deep-equal';
import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
import { useChatMarkdown } from '../useChatMarkdown';
-export const useMarkdown = (id: string, disableStreaming = false, hasContent = false) => {
+export const useMarkdown = (id: string, disableStreaming = false, content?: string) => {
const item = useConversationStore(dataSelectors.getDbMessageById(id), isEqual)!;
const isGenerating = useConversationStore(messageStateSelectors.isMessageGenerating(id));
return useChatMarkdown({
citations: item?.search?.citations,
enableStream: !disableStreaming,
- hasContent,
+ content,
id,
isGenerating,
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.streaming.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.streaming.test.tsx
new file mode 100644
index 00000000000..0063eff73a6
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.streaming.test.tsx
@@ -0,0 +1,65 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { cleanup, render } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import MessageContent from './MessageContent';
+
+let mockStoreContent = '';
+const markdownProps: { animated?: boolean; enableStream?: boolean }[] = [];
+
+vi.mock('@/features/Conversation/Markdown', () => ({
+ default: (props: { animated?: boolean; enableStream?: boolean }) => {
+ markdownProps.push(props);
+ return null;
+ },
+}));
+
+vi.mock('@/components/HtmlPreview', () => ({ HtmlPreviewDrawer: () => null }));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: any) => selector({ settings: {} }),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ userGeneralSettingsSelectors: { config: () => ({ transitionMode: 'fadeIn' }) },
+}));
+
+vi.mock('../../../store', () => ({
+ dataSelectors: {
+ getBlockContent: () => () => mockStoreContent,
+ getBlockHasTools: () => () => false,
+ getBlockMetadata: () => () => undefined,
+ getDbMessageById: () => () => ({ createdAt: 1000 }),
+ },
+ messageStateSelectors: { isAssistantGroupItemGenerating: () => () => true },
+ useConversationStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+describe('MessageContent streaming across remounts', () => {
+ afterEach(() => {
+ cleanup();
+ markdownProps.length = 0;
+ });
+
+ it('keeps fading in a reply that remounts mid-stream and keeps growing', () => {
+ // The post-tool reply first renders inside the workflow fold as a status line…
+ mockStoreContent = 'Let me summarize.';
+ render(<MessageContent id="post-tool-answer" />).unmount();
+
+ // …then grows into an answer and remounts outside the fold.
+ mockStoreContent = 'Let me summarize.\n\n## Findings';
+ render(<MessageContent id="post-tool-answer" />);
+
+ expect(markdownProps.at(-1)).toMatchObject({ animated: true, enableStream: true });
+ });
+
+ it('does not replay the fade when the reply remounts without new text', () => {
+ mockStoreContent = 'A finished reply.';
+ render(<MessageContent id="finished-answer" />).unmount();
+ render(<MessageContent id="finished-answer" />);
+
+ expect(markdownProps.at(-1)).toMatchObject({ animated: false, enableStream: false });
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx
index ce5b521b723..5a5b616112b 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx
@@ -45,7 +45,7 @@ vi.mock('../../../store', () => ({
useConversationStore: (selector: (state: unknown) => unknown) => selector({}),
}));
-type UseMarkdownArgs = [id: string, disableStreaming?: boolean, hasContent?: boolean];
+type UseMarkdownArgs = [id: string, disableStreaming?: boolean, content?: string];
const useMarkdownMock = vi.fn((..._args: UseMarkdownArgs) => ({}));
@@ -80,7 +80,7 @@ describe('MessageContent', () => {
it('disables markdown streaming when the block already has tools below the text', () => {
render(<MessageContent hasToolsOverride contentOverride="lead sentence" id="block-1" />);
- expect(useMarkdownMock).toHaveBeenCalledWith('block-1', true, true);
+ expect(useMarkdownMock).toHaveBeenCalledWith('block-1', true, 'lead sentence');
});
it('keeps markdown streaming enabled when the block has no tools and is not disabled', () => {
@@ -88,7 +88,7 @@ describe('MessageContent', () => {
<MessageContent contentOverride="lead sentence" hasToolsOverride={false} id="block-1" />,
);
- expect(useMarkdownMock).toHaveBeenCalledWith('block-1', false, true);
+ expect(useMarkdownMock).toHaveBeenCalledWith('block-1', false, 'lead sentence');
});
it('disables markdown streaming when disableStreaming is set even without tools', () => {
@@ -101,7 +101,7 @@ describe('MessageContent', () => {
/>,
);
- expect(useMarkdownMock).toHaveBeenCalledWith('block-1', true, true);
+ expect(useMarkdownMock).toHaveBeenCalledWith('block-1', true, 'lead sentence');
});
it('renders multimodal image parts instead of the raw serialized JSON', () => {
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
index 719f7cf9ab7..63b19d2cfc8 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
@@ -58,11 +58,7 @@ const MessageContent = memo<MessageContentProps>(
// Once a tool call exists below this block's text, the text is already
// finalized — skip the streaming/fade-in animation so settled content above
// a tool doesn't keep re-animating.
- const { drawer, markdownProps } = useMarkdown(
- id,
- disableStreaming || hasTools,
- !!content && content !== LOADING_FLAT,
- );
+ const { drawer, markdownProps } = useMarkdown(id, disableStreaming || hasTools, content);
if (!content && !hasTools) return <ContentLoading id={id} startTime={createdAt} />;
diff --git a/src/features/Conversation/Messages/AssistantGroup/useMarkdown.tsx b/src/features/Conversation/Messages/AssistantGroup/useMarkdown.tsx
index abf6cae8050..71c8ed63d20 100644
--- a/src/features/Conversation/Messages/AssistantGroup/useMarkdown.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/useMarkdown.tsx
@@ -1,14 +1,14 @@
import { messageStateSelectors, useConversationStore } from '../../store';
import { useChatMarkdown } from '../useChatMarkdown';
-export const useMarkdown = (id: string, disableStreaming = false, hasContent = false) => {
+export const useMarkdown = (id: string, disableStreaming = false, content?: string) => {
const isGenerating = useConversationStore(
messageStateSelectors.isAssistantGroupItemGenerating(id),
);
return useChatMarkdown({
enableStream: !disableStreaming,
- hasContent,
+ content,
id,
isGenerating,
});
diff --git a/src/features/Conversation/Messages/useChatMarkdown.test.tsx b/src/features/Conversation/Messages/useChatMarkdown.test.tsx
index 481df082ce5..297dd2da198 100644
--- a/src/features/Conversation/Messages/useChatMarkdown.test.tsx
+++ b/src/features/Conversation/Messages/useChatMarkdown.test.tsx
@@ -1,3 +1,4 @@
+import { LOADING_FLAT } from '@lobechat/const';
import { renderHook } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -73,7 +74,7 @@ describe('useChatMarkdown (assistant / grouped message pipeline)', () => {
mockTransitionMode = 'fadeIn';
const { result } = renderHook(() =>
- useChatMarkdown({ hasContent: true, id: 'fresh-1', isGenerating: true }),
+ useChatMarkdown({ content: 'Shown reply', id: 'fresh-1', isGenerating: true }),
);
expect(result.current.markdownProps.animated).toBe(true);
@@ -85,7 +86,12 @@ describe('useChatMarkdown (assistant / grouped message pipeline)', () => {
// A transient block below makes this one non-last, then disappears again.
const { result, rerender } = renderHook(
({ enableStream }) =>
- useChatMarkdown({ enableStream, hasContent: true, id: 'settle-1', isGenerating: true }),
+ useChatMarkdown({
+ content: 'Shown reply',
+ enableStream,
+ id: 'settle-1',
+ isGenerating: true,
+ }),
{ initialProps: { enableStream: false } },
);
rerender({ enableStream: true });
@@ -98,13 +104,13 @@ describe('useChatMarkdown (assistant / grouped message pipeline)', () => {
mockTransitionMode = 'fadeIn';
const first = renderHook(() =>
- useChatMarkdown({ hasContent: true, id: 'remount-1', isGenerating: true }),
+ useChatMarkdown({ content: 'Shown reply', id: 'remount-1', isGenerating: true }),
);
expect(first.result.current.markdownProps.animated).toBe(true);
first.unmount();
const second = renderHook(() =>
- useChatMarkdown({ hasContent: true, id: 'remount-1', isGenerating: true }),
+ useChatMarkdown({ content: 'Shown reply', id: 'remount-1', isGenerating: true }),
);
expect(second.result.current.markdownProps.animated).toBe(false);
@@ -114,13 +120,49 @@ describe('useChatMarkdown (assistant / grouped message pipeline)', () => {
mockTransitionMode = 'fadeIn';
renderHook(() =>
- useChatMarkdown({ hasContent: false, id: 'empty-1', isGenerating: true }),
+ useChatMarkdown({ content: LOADING_FLAT, id: 'empty-1', isGenerating: true }),
).unmount();
const { result } = renderHook(() =>
- useChatMarkdown({ hasContent: true, id: 'empty-1', isGenerating: true }),
+ useChatMarkdown({ content: 'Shown reply', id: 'empty-1', isGenerating: true }),
);
expect(result.current.markdownProps.animated).toBe(true);
});
+
+ it('keeps streaming a reply that keeps growing after it remounts', () => {
+ mockTransitionMode = 'fadeIn';
+
+ // A post-tool reply starts inside the workflow fold as a short status line,
+ // then moves out to the answer segment once it grows, which remounts it.
+ renderHook(() =>
+ useChatMarkdown({ content: 'Let me summarize.', id: 'grow-1', isGenerating: true }),
+ ).unmount();
+
+ const { result } = renderHook(() =>
+ useChatMarkdown({
+ content: 'Let me summarize.\n\n## Findings',
+ id: 'grow-1',
+ isGenerating: true,
+ }),
+ );
+
+ expect(result.current.markdownProps.animated).toBe(true);
+ expect(result.current.markdownProps.enableStream).toBe(true);
+ });
+
+ it('resumes streaming when settled text grows again', () => {
+ mockTransitionMode = 'fadeIn';
+
+ const { result, rerender } = renderHook(
+ ({ content, enableStream }) =>
+ useChatMarkdown({ content, enableStream, id: 'resume-1', isGenerating: true }),
+ { initialProps: { content: 'Shown reply', enableStream: false } },
+ );
+ rerender({ content: 'Shown reply', enableStream: true });
+ expect(result.current.markdownProps.animated).toBe(false);
+
+ rerender({ content: 'Shown reply, continued', enableStream: true });
+ expect(result.current.markdownProps.animated).toBe(true);
+ });
});
diff --git a/src/features/Conversation/Messages/useChatMarkdown.tsx b/src/features/Conversation/Messages/useChatMarkdown.tsx
index 2026988223a..df5a4b6db67 100644
--- a/src/features/Conversation/Messages/useChatMarkdown.tsx
+++ b/src/features/Conversation/Messages/useChatMarkdown.tsx
@@ -1,5 +1,6 @@
'use client';
+import { LOADING_FLAT } from '@lobechat/const';
import { type MarkdownProps } from '@lobehub/ui';
import { type ReactNode, useEffect, useMemo, useState } from 'react';
@@ -24,18 +25,19 @@ const remarkPlugins = assistantMarkdownElements
.filter(Boolean);
/**
- * Message ids whose text has already been on screen. The stream renderer fades
- * every character in from zero on mount, so a remount — the group re-partitions,
- * or a stream patch and a snapshot refresh disagree about the block's shape —
- * must not replay that fade over text the user has already read.
+ * Length of the text each message id has already shown. The stream renderer
+ * fades every character in from zero on mount, so a remount — the group
+ * re-partitions, or a stream patch and a snapshot refresh disagree about the
+ * block's shape — must not replay that fade over text the user has already
+ * read. Text that keeps growing after the remount still streams.
*/
-const shownTextIds = new Set<string>();
+const shownTextLengths = new Map<string, number>();
interface UseChatMarkdownOptions {
citations?: MarkdownProps['citations'];
+ /** The message text; a loading placeholder counts as no text. */
+ content?: string;
enableStream?: boolean;
- /** Whether the message has text to show yet; loading placeholders do not count. */
- hasContent?: boolean;
id: string;
isGenerating: boolean;
}
@@ -45,20 +47,24 @@ export const useChatMarkdown = ({
isGenerating,
citations,
enableStream: enableStreamOption = true,
- hasContent = false,
+ content,
}: UseChatMarkdownOptions): {
drawer: ReactNode;
markdownProps: Partial<MarkdownProps>;
} => {
const { transitionMode } = useUserStore(userGeneralSettingsSelectors.config);
- // Once text has settled (rendered statically, or shown by an earlier mount),
- // it never re-enters streaming: switching back remounts the stream renderer.
- const [settled, setSettled] = useState(() => shownTextIds.has(id));
- if (!settled && hasContent && !enableStreamOption) setSettled(true);
+ const textLength = content && content !== LOADING_FLAT ? content.length : 0;
+ // Text that has settled (rendered statically, or shown by an earlier mount)
+ // does not re-enter streaming until it grows: switching back remounts the
+ // stream renderer, which replays the fade over everything already shown.
+ const [settledLength, setSettledLength] = useState(() => shownTextLengths.get(id));
+ if (textLength > 0 && !enableStreamOption && settledLength !== textLength)
+ setSettledLength(textLength);
useEffect(() => {
- if (hasContent) shownTextIds.add(id);
- }, [hasContent, id]);
+ if (textLength > 0) shownTextLengths.set(id, textLength);
+ }, [id, textLength]);
+ const settled = settledLength !== undefined && textLength <= settledLength;
const enableStream = enableStreamOption && !settled;
const animated = enableStream && transitionMode === 'fadeIn' && isGenerating;