From 2b467e68d0de4736b64dbb4094fcf299e4c6a403 Mon Sep 17 00:00:00 2001 From: Innei Date: Tue, 23 Sep 2025 21:40:15 +0800 Subject: [PATCH] fix(ai-message): message streaming animation - Enhanced `AIMarkdownStreamingMessage` to use a stable reference for the `isStreaming` state, ensuring consistent rendering during updates. - Updated `MarkdownAnimateText` to handle number inputs and preserve element structure for valid React elements, improving flexibility in rendering. - Added logic in `TokenizedText` to skip rendering completely empty tokens and preserve whitespace-only tokens without additional DOM elements. These changes aim to enhance the rendering logic and user experience in the AI chat interface by providing more robust handling of various input types and improving performance during streaming. Signed-off-by: Innei --- .../message/AIMarkdownMessage.old.tsx | 504 ------------------ ...wnMessage.v2.tsx => AIMarkdownMessage.tsx} | 13 +- .../message/animated/AnimatedMarkdown.tsx | 22 +- .../message/animated/TokenizedText.tsx | 10 + 4 files changed, 27 insertions(+), 522 deletions(-) delete mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.old.tsx rename apps/desktop/layer/renderer/src/modules/ai-chat/components/message/{AIMarkdownMessage.v2.tsx => AIMarkdownMessage.tsx} (66%) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.old.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.old.tsx deleted file mode 100644 index cca345950..000000000 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.old.tsx +++ /dev/null @@ -1,504 +0,0 @@ -/** - * This AI Markdown Message use a optimize tokenization algorithm to render the streaming text. - * But tokenization put into the server response, so we can disable it. - */ -import type { LinkProps } from "@follow/components/ui/link/LinkWithTooltip.js" -import { parseMarkdown } from "@follow/components/utils/parse-markdown.js" -import { cn, isBizId } from "@follow/utils" -import { - createElement, - isValidElement, - memo, - useCallback, - useDeferredValue, - useEffect, - useMemo, - useRef, - useSyncExternalStore, -} from "react" - -import { MemoizedShikiCode } from "~/components/ui/code-highlighter" -import { MarkdownLink } from "~/components/ui/markdown/renderers/MarkdownLink" -import { usePeekModal } from "~/hooks/biz/usePeekModal" - -import { animatedPlugin } from "./animatedPlugin" -import { parseIncompleteMarkdown } from "./parse-incomplete-markdown" - -// Buffer configuration interface -interface BufferConfig { - minBufferSize: number - maxBufferSize: number // Maximum buffer size to prevent OOM - maxBufferTime: number - semanticTimeout: number - emergencyTimeout: number - // Ensure a cool-down between flushes to avoid overlapping animations - minFlushInterval: number - // Initial burst controls for faster first paint - initialMinBufferSize: number - initialMaxWait: number -} - -// Buffer endpoint patterns by priority -const BUFFER_ENDPOINTS = { - HIGH_PRIORITY: [ - /\n\n/g, // Paragraph breaks - /\n```\w*\n/g, // Code block boundaries - /\n-{2,}\n/g, // Horizontal rules - /[.!?]\s+/g, // Sentence endings with space - /\n[-*+]\s/g, // List items - /\n\d+\.\s/g, // Numbered lists - ], - MEDIUM_PRIORITY: [ - /[,:;]\s/g, // Clause boundaries - /[)\]]\s/g, // Closing brackets with space - /\n(?!\n)/g, // Single line breaks - ], - LOW_PRIORITY: [/\s/g], // Any whitespace -} as const - -// Streaming message buffer class for external state management -class StreamingMessageBuffer { - private displayedText = "" - private bufferedText = "" - private lastFlushTime = Date.now() - private flushTimeoutId: ReturnType | null = null - private subscribers = new Set<() => void>() - private config: BufferConfig - - constructor(config: BufferConfig) { - this.config = config - } - - // Subscribe to state changes - subscribe = (callback: () => void) => { - this.subscribers.add(callback) - return () => { - this.subscribers.delete(callback) - } - } - - // Get current displayed text snapshot - getSnapshot = () => { - return this.displayedText - } - - // Notify all subscribers of state change - private notify = () => { - this.subscribers.forEach((callback) => callback()) - } - - // Find last endpoint of given priority in text - private findLastEndpoint = (text: string, priority: keyof typeof BUFFER_ENDPOINTS): number => { - const patterns = BUFFER_ENDPOINTS[priority] - let lastIndex = -1 - - for (const pattern of patterns) { - const matches = [...text.matchAll(pattern)] - if (matches.length > 0) { - const lastMatch = matches.at(-1) - if (lastMatch?.index !== undefined) { - lastIndex = Math.max(lastIndex, lastMatch.index + lastMatch[0].length) - } - } - } - - return lastIndex - } - - // Determine optimal flush point in buffered text - private determineFlushPoint = (bufferedText: string): number => { - // Try high priority endpoints first - const highPriorityPoint = this.findLastEndpoint(bufferedText, "HIGH_PRIORITY") - if (highPriorityPoint > 0) return highPriorityPoint - - // Try medium priority endpoints - const mediumPriorityPoint = this.findLastEndpoint(bufferedText, "MEDIUM_PRIORITY") - if (mediumPriorityPoint > 0) return mediumPriorityPoint - - // Try low priority endpoints - const lowPriorityPoint = this.findLastEndpoint(bufferedText, "LOW_PRIORITY") - if (lowPriorityPoint > 0) return lowPriorityPoint - - // Flush entire buffer if no endpoints found - return bufferedText.length - } - - // Check if buffer should be flushed - private shouldFlushBuffer = (bufferedText: string): boolean => { - const now = Date.now() - const timeSinceLastFlush = now - this.lastFlushTime - - // Accelerate first paint: show something quickly at the very beginning - if (this.displayedText.length === 0) { - if (bufferedText.length >= this.config.initialMinBufferSize) return true - if (timeSinceLastFlush > this.config.initialMaxWait && bufferedText.length > 0) return true - } - - // Emergency timeout - always flush - if (timeSinceLastFlush > this.config.emergencyTimeout) return true - - // Buffer size limit - prevent OOM - if (bufferedText.length > this.config.maxBufferSize) return true - - // Avoid overlapping animations by enforcing a minimal interval between flushes - if (timeSinceLastFlush < this.config.minFlushInterval) return false - - // Minimum buffer size not met - if (bufferedText.length < this.config.minBufferSize) return false - - // Check for high priority endpoints (immediate flush) - if (this.findLastEndpoint(bufferedText, "HIGH_PRIORITY") > 0) return true - - // Check for medium priority endpoints with time condition - if ( - this.findLastEndpoint(bufferedText, "MEDIUM_PRIORITY") > 0 && - timeSinceLastFlush > this.config.maxBufferTime - ) { - return true - } - - // Semantic timeout for incomplete sentences - if (timeSinceLastFlush > this.config.semanticTimeout) { - return this.findLastEndpoint(bufferedText, "LOW_PRIORITY") > 0 - } - - return false - } - - // Emergency flush timer - private scheduleEmergencyFlush = () => { - if (this.flushTimeoutId) return - - this.flushTimeoutId = setTimeout(() => { - this.displayedText += this.bufferedText - this.bufferedText = "" - this.lastFlushTime = Date.now() - this.flushTimeoutId = null - this.notify() - }, this.config.emergencyTimeout) - } - - // Clear emergency flush timer - private clearEmergencyFlush = () => { - if (this.flushTimeoutId) { - clearTimeout(this.flushTimeoutId) - this.flushTimeoutId = null - } - } - - // Update text content - updateText = (newText: string, isProcessing: boolean) => { - // Safety check for undefined/null newText - if (typeof newText !== "string") { - return - } - - if (!isProcessing) { - // Immediate update when not processing - this.displayedText = newText - this.bufferedText = "" - this.lastFlushTime = Date.now() - this.clearEmergencyFlush() - this.notify() - return - } - - // Calculate delta and update buffer - const deltaText = newText.slice(this.displayedText.length + this.bufferedText.length) - if (!deltaText) return - - const newBufferedText = this.bufferedText + deltaText - - // Check if we should flush - if (this.shouldFlushBuffer(newBufferedText)) { - const flushPoint = this.determineFlushPoint(newBufferedText) - const textToFlush = newBufferedText.slice(0, flushPoint) - const remainingBuffer = newBufferedText.slice(flushPoint) - - this.displayedText += textToFlush - this.bufferedText = remainingBuffer - this.lastFlushTime = Date.now() - this.clearEmergencyFlush() - - if (remainingBuffer.length > 0) { - this.scheduleEmergencyFlush() - } - - this.notify() - } else { - this.bufferedText = newBufferedText - this.scheduleEmergencyFlush() - } - } - - // Cleanup resources - destroy = () => { - this.clearEmergencyFlush() - this.subscribers.clear() - } -} - -// Buffer configurations -const BUFFER_CONFIG = { - minBufferSize: 10, - maxBufferSize: 10000, // Prevent OOM with 10KB limit - maxBufferTime: 100, - semanticTimeout: 300, - // Keep emergency slightly larger than animation duration to prevent overlap - emergencyTimeout: 1200, - // Match animation duration in animatedPlugin (duration-1000) with a small buffer - minFlushInterval: 1000, - // Ensure very fast first paint - initialMinBufferSize: 2, - initialMaxWait: 80, -} as const - -// Hook to use streaming text buffer -const useStreamingTextBuffer = (text: string, isProcessing: boolean) => { - const bufferRef = useRef(null) - - // Initialize buffer if needed (only during processing) - if (isProcessing && !bufferRef.current) { - bufferRef.current = new StreamingMessageBuffer(BUFFER_CONFIG) - } - - // Clean up buffer when not processing - if (!isProcessing && bufferRef.current) { - bufferRef.current.destroy() - bufferRef.current = null - } - - // Update buffer when text changes (only if processing) - if (isProcessing && bufferRef.current) { - bufferRef.current.updateText(text, isProcessing) - } - - // Subscribe to buffer changes - always call the hook - const displayedText = useSyncExternalStore( - bufferRef.current?.subscribe || (() => () => {}), - bufferRef.current?.getSnapshot || (() => text), - ) - - // Cleanup on unmount to prevent memory leaks - useEffect(() => { - return () => { - bufferRef.current?.destroy() - bufferRef.current = null - } - }, []) - - // Return text directly when not processing, buffered text when processing - return isProcessing ? displayedText : text -} - -// Custom hook for throttled markdown parsing during streaming -const useThrottledMarkdownParsing = (text: string, isProcessing: boolean) => { - const lastParsedTextRef = useRef("") - const cachedResultRef = useRef(null) - const lastParseTimeRef = useRef(0) - - const parseWithCache = useCallback( - (content: string, shouldProcess: boolean) => { - const parsedContent = parseIncompleteMarkdown(content) - const now = Date.now() - - // During streaming, throttle parsing - if (shouldProcess && cachedResultRef.current) { - const timeSinceLastParse = now - lastParseTimeRef.current - if (timeSinceLastParse < 16) { - // Return cached result if within throttle window - return cachedResultRef.current - } - } - - // If content hasn't changed, return cached result - if (parsedContent === lastParsedTextRef.current && cachedResultRef.current) { - return cachedResultRef.current - } - - // Parse and cache the result - const result = baseAIMarkdownParser(parsedContent, isProcessing) - - lastParsedTextRef.current = parsedContent - cachedResultRef.current = result - lastParseTimeRef.current = now - return result - }, - [isProcessing], - ) - - return useMemo(() => { - // For non-processing state, always parse immediately - if (!isProcessing) { - return parseWithCache(text, false) - } - - // During processing, apply throttling logic - return parseWithCache(text, true) - }, [text, isProcessing, parseWithCache]) -} - -/** - * @deprecated - */ -export const AIMarkdownStreamingMessage = memo( - ({ - text, - className: classNameProp, - isProcessing, - }: { - text: string - className?: string - isProcessing?: boolean - }) => { - const className = `prose max-w-full dark:prose-invert prose-sm - prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg prose-h4:text-base prose-h5:text-base prose-h6:text-sm - prose-li:list-disc prose-li:marker:text-accent prose-hr:border-border prose-hr:mx-8` - - // Use intelligent streaming buffer for semantic text rendering - const bufferedTextRaw = useStreamingTextBuffer(text, isProcessing ?? false) - - // Use deferred value for lower priority rendering during streaming - const deferredText = useDeferredValue(bufferedTextRaw) - - // For small snippets (common at the very beginning), avoid deferring so text appears instantly - const effectiveBufferedText = bufferedTextRaw.length < 20 ? bufferedTextRaw : deferredText - - // Use our optimized parsing hook with buffered text - const parsedContent = useThrottledMarkdownParsing( - // During streaming, use non-deferred value for tiny snippets to improve first paint - isProcessing ? effectiveBufferedText : text, - isProcessing ?? false, - ) - - return
{parsedContent}
- }, - // Enhanced memo comparison for better performance - (prevProps, nextProps) => { - // If not processing, do normal comparison - if (!nextProps.isProcessing && !prevProps.isProcessing) { - return ( - prevProps.text === nextProps.text && - prevProps.className === nextProps.className && - prevProps.isProcessing === nextProps.isProcessing - ) - } - - // During processing, be more lenient with text changes to reduce re-renders - if (nextProps.isProcessing) { - // Only re-render if there's a significant change or processing state changes - return ( - prevProps.text === nextProps.text && - prevProps.className === nextProps.className && - prevProps.isProcessing === nextProps.isProcessing - ) - } - - // Default comparison - return prevProps === nextProps - }, -) - -export const AIMarkdownMessage = memo( - ({ text, className }: { text: string; className?: string }) => { - return ( -
{useMemo(() => baseAIMarkdownParser(text, false), [text])}
- ) - }, -) - -const RelatedEntryLink = (props: LinkProps) => { - const { href, children } = props - const entryId = isBizId(href) ? href : null - - const peekModal = usePeekModal() - if (!entryId) { - return - } - return ( - - ) -} - -function baseAIMarkdownParser(content: string, isProcessing: boolean) { - return parseMarkdown(content, { - rehypePlugins: isProcessing ? [animatedPlugin] : undefined, - components: { - pre: ({ children }) => { - const props = isValidElement(children) && "props" in children && children.props - - if (props) { - const { className, children } = props as any - - if (className && className.includes("language-") && typeof children === "string") { - const language = className.replace("language-", "") - const code = children - - return - } - } - - return
{children}
- }, - a: ({ node, ...props }) => { - return createElement(RelatedEntryLink, { ...props } as any) - }, - table: ({ children, ref, node, ...props }) => { - return ( -
- - {children} -
-
- ) - }, - thead: ({ children, ref, node, ...props }) => { - return ( - - {children} - - ) - }, - th: ({ children, ref, node, ...props }) => { - return ( - - {children} - - ) - }, - tbody: ({ children, ref, node, ...props }) => { - return ( - - {children} - - ) - }, - tr: ({ children, ref, node, ...props }) => { - return ( - - {children} - - ) - }, - td: ({ children, ref, node, ...props }) => { - return ( - - {children} - - ) - }, - }, - }).content -} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.v2.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx similarity index 66% rename from apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.v2.tsx rename to apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx index e39e42e74..06a1afc2c 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.v2.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx @@ -1,5 +1,5 @@ import { cn } from "@follow/utils" -import { memo } from "react" +import { memo, useRef } from "react" import { MarkdownAnimateText } from "./animated/AnimatedMarkdown" import { parseIncompleteMarkdown } from "./parse-incomplete-markdown" @@ -14,13 +14,18 @@ export const AIMarkdownStreamingMessage = memo( className?: string isStreaming?: boolean }) => { - const className = `prose max-w-full dark:prose-invert prose-sm + const className = tw`prose max-w-full dark:prose-invert prose-sm prose-h1:text-2xl prose-h2:text-xl prose-h2:mt-2 prose-h3:text-lg prose-h4:text-base prose-h5:text-base prose-h6:text-sm - prose-li:list-disc prose-li:marker:text-accent prose-hr:border-border prose-hr:mx-8` + prose-li:list-disc prose-li:marker:text-accent prose-hr:border-border prose-hr:mx-8 + ` + const stableStreamingState = useRef(isStreaming) return (
- +
) }, diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animated/AnimatedMarkdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animated/AnimatedMarkdown.tsx index 70905ac11..906416d1f 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animated/AnimatedMarkdown.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animated/AnimatedMarkdown.tsx @@ -16,7 +16,7 @@ import { MarkdownLink } from "~/components/ui/markdown/renderers" import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry" import { usePeekModal } from "~/hooks/biz/usePeekModal" -import { ANIMATION_STYLE as ANIMATION_STYLE_DEFAULT, DEFAULT_ANIMATION } from "./constants" +import { ANIMATION_STYLE as ANIMATION_STYLE_DEFAULT } from "./constants" import { TokenizedText } from "./TokenizedText" interface MarkdownAnimateTextProps { @@ -50,20 +50,14 @@ export const MarkdownAnimateText: React.FC = ({ )) } else if (typeof input === "string") { return + } else if (typeof input === "number") { + return + } else if (React.isValidElement(input)) { + // Preserve element structure and do not wrap block elements (avoid
    ...) + return React.cloneElement(input as React.ReactElement, { key: `pcc-${keyCounter++}` }) } else { - // Return non-string, non-element inputs unchanged (null, undefined, etc.) - return ( - - {input} - - ) + // Return other inputs unchanged (null, undefined, booleans, etc.) + return input } } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animated/TokenizedText.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animated/TokenizedText.tsx index 2c877597a..d7ae9ba5b 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animated/TokenizedText.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/animated/TokenizedText.tsx @@ -99,6 +99,16 @@ export const TokenizedText = ({ input }: { input: React.ReactNode }) => { return React.cloneElement(token, { key }) } + // Skip rendering completely empty tokens + if (text.length === 0) { + return null + } + + // For whitespace-only tokens, preserve spacing without adding a DOM element + if (/^\s+$/.test(text)) { + return {text} + } + return ( {text}